Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
829fc44cbc | ||
|
|
6b4049c9f5 | ||
|
|
934ba16c72 | ||
|
|
9f1dc44673 | ||
|
|
24258e215f | ||
|
|
793eec6e51 | ||
|
|
6785750729 | ||
|
|
72fa043f47 | ||
|
|
cc7397787b | ||
|
|
cef476aca3 | ||
|
|
f50444594f | ||
|
|
275d337032 | ||
|
|
b314470281 | ||
|
|
eb3add5b89 | ||
|
|
c126d5a24a | ||
|
|
1a3e79502d | ||
|
|
fcc6a7974e | ||
|
|
f4ed542b00 | ||
|
|
d06be5ca32 | ||
|
|
8d48a08b13 | ||
|
|
f6ee43bf55 | ||
|
|
268f99051a | ||
|
|
60a09e7def | ||
|
|
bf1dc2e33e | ||
|
|
f34714ea07 | ||
|
|
c2cfba1129 | ||
|
|
cea8bfee98 | ||
|
|
2f8107d5ca | ||
|
|
a67a142139 | ||
|
|
48416af5bc | ||
|
|
cca80ac2e8 | ||
|
|
52d267683b | ||
|
|
0b00682fac | ||
|
|
d1b8bff5ce | ||
|
|
ae8f0d42ef | ||
|
|
39b61a0340 | ||
|
|
06334ca3f9 | ||
|
|
f9e97b561f | ||
|
|
d7f6f502a8 | ||
|
|
54e36ff8b7 | ||
|
|
a1c69c5b28 | ||
|
|
bf68866dca | ||
|
|
87d52938b5 | ||
|
|
90a4189db4 | ||
|
|
013fcd0919 | ||
|
|
00209ebe87 | ||
|
|
96e54e963f | ||
|
|
2f05ed81b1 | ||
|
|
822f8b63d4 | ||
|
|
e0ec9b87e6 | ||
|
|
27bad9f1fa | ||
|
|
403ace1cef | ||
|
|
761a1271a4 | ||
|
|
c5a8942976 | ||
|
|
fb0424b729 | ||
|
|
52b8b6dcca | ||
|
|
d7178250ae | ||
|
|
9b282177e0 | ||
|
|
59273c9544 | ||
|
|
86e706dff7 | ||
|
|
ad5caf88a6 | ||
|
|
a7efb9bb00 | ||
|
|
34f47a4bd0 | ||
|
|
d60fcad18f | ||
|
|
8124c5af54 | ||
|
|
bfc8d4b1b7 | ||
|
|
0b8e9ae7f1 | ||
|
|
662a5ee336 | ||
|
|
8cbbdb20b5 | ||
|
|
cadbc6d1ca | ||
|
|
64128645c2 | ||
|
|
8155cc915a | ||
|
|
150dde5a7d | ||
|
|
a65f558d35 | ||
|
|
0dff130682 | ||
|
|
2d1d4ed632 | ||
|
|
67c5447ebc | ||
|
|
db6e8d321e | ||
|
|
cbeab6afd2 | ||
|
|
ed698fced1 | ||
|
|
081ee4a8ba | ||
|
|
5de07fac0e | ||
|
|
03335f49c1 | ||
|
|
d0d759d216 | ||
|
|
67ead19dd9 | ||
|
|
f7c646163b | ||
|
|
8d05f99526 | ||
|
|
625ead95b3 | ||
|
|
0acc922d9a | ||
|
|
595956cc75 | ||
|
|
929784667b | ||
|
|
d4e254b349 | ||
|
|
89c5f8e2ad | ||
|
|
2ffe924a44 | ||
|
|
c9f677f35b | ||
|
|
d60f024e74 | ||
|
|
1fa3acdbe9 |
No files matched your search
@@ -66,6 +66,14 @@ packages the moment it merged; formatting and lint drifted the same way, and onl
|
||||
the repository gate saw it. Both failures are paid for inside the lane when the
|
||||
gate runs the build and the linter, and at merge when it does not.
|
||||
|
||||
Gate the **candidate** before `main` moves. Check the merge candidate out
|
||||
detached — or gate the lane branch — and advance the ref only on a green result:
|
||||
gating after a fast-forward lands the failure on the branch of record and leaves
|
||||
only fix-forward or reset as exits. The lane brief must name the linter as well,
|
||||
`golangci-lint run ./<package>/...` beside the scoped tests, because a scoped
|
||||
test run cannot see a complexity or style limit and `task check` is where that
|
||||
failure otherwise surfaces — once it is already merged.
|
||||
|
||||
A copy of the script under `.pi/control-plane-run/` is that run's disposable
|
||||
state and may lag the skill's version. The skill's copy is the one to trust.
|
||||
|
||||
@@ -126,6 +134,36 @@ ln -sfn /work/apps/archie-core/.pi/agents /work/apps/cp-<lane>/.pi/agents
|
||||
`.pi/` is gitignored, so the worktree stays clean and the symlink cannot reach a
|
||||
commit. This costs an hour to rediscover.
|
||||
|
||||
## Peer sessions over intercom
|
||||
|
||||
A fleet here can also run as **sibling sessions** coordinated over `intercom` —
|
||||
a peer per lane — rather than pi-subagents children under one orchestrator.
|
||||
These facts are peer-specific, and each has cost a real run.
|
||||
|
||||
- **Name the channel in the brief.** A peer's knowledge of how to report lives in
|
||||
its context, not its configuration. Write "report to <peer> over intercom" as
|
||||
an instruction; a convention that is only assumed evaporates.
|
||||
- **A compaction erases conventions, not just facts.** A peer that compacts
|
||||
mid-task keeps its task state and loses its transport: it reverts to
|
||||
addressing its operator, and the coordinator reads that as idleness or death.
|
||||
**Peer silence is not evidence of either** — ask for a one-line ack over the
|
||||
channel before concluding anything. Re-priming restores the channel; the
|
||||
transport itself survives compaction intact.
|
||||
- **Match the task's shape to the session's window, not its strength.** A sweep
|
||||
over hundreds of items needs the largest window available; a bounded hard
|
||||
artifact (a PRD, a conformance review, a design decision) belongs in a smaller,
|
||||
reasoning-strong session. A wide task in a small window stalls the task — too
|
||||
wide is not the same as too hard, and it is the coordinator's assignment error,
|
||||
not the peer's failure.
|
||||
- **Checkpoint at ~70%, never compact mid-task.** A terse ledger sent to the
|
||||
coordinator before the window fills survives; one reconstructed afterwards
|
||||
loses exactly the identifiers — bead IDs, exact counts — that made it worth
|
||||
having. Instruct every long-running peer to report and stop there.
|
||||
- **One writer per resource.** Exactly one session writes the tracker. Two
|
||||
writers produce double-closes, contradictory verdicts, and counts nobody can
|
||||
reconcile. When a sweep changes hands, the successor re-derives them rather
|
||||
than inheriting the predecessor's ledger as fact.
|
||||
|
||||
## Traps worth carrying
|
||||
|
||||
- **`touch` does not invalidate a Task source.** Task hashes file _content_, so a
|
||||
@@ -143,11 +181,41 @@ build` still reports the binary up to date, shipping the old value. Tracked as
|
||||
reaches, or changes a wire type, passes its own gate and fails
|
||||
`task check` on a missing `tools/go.sum` entry or a stale schema. Such a
|
||||
lane runs `go -C tools mod tidy` and `task docs:generate` and commits both.
|
||||
Adding or editing a page under `docs/` — a PRD included — changes
|
||||
`docs/data/generated/dev-docs.json`, which gains or loses a page: regenerate it
|
||||
and commit it in the same commit, or `docs:artifact:check` fails. That failure
|
||||
lands on `main`, not in the lane, if the ref moves first.
|
||||
- **Untracked files in the shared checkout are other sessions'.** prdlint
|
||||
scratch (`docs/prds/rules.jsonl`), editor state, and gate-written artifacts
|
||||
appear and vanish under a lane. Never chase, add, stage or commit them: a
|
||||
merge train's scope is its own lanes' files, and nothing else.
|
||||
|
||||
## codegraph answers symbol questions cheaply
|
||||
|
||||
The maintainer's `codegraph` MCP server indexes this repository. Prefer it to
|
||||
grep or whole-file reading for "who calls X", "is this dead", "what does this
|
||||
change touch": it enumerates call sites that a grep only summarises, and labels
|
||||
each caller's confidence so interface fan-out is not mistaken for direct calls.
|
||||
|
||||
- **`pr_impact <base> <head>`** lists changed symbols with per-symbol caller and
|
||||
test counts. Read `interface_dispatch` and the inferred tests alongside
|
||||
`test_count`: a method reached through an interface reports a low direct test
|
||||
count while many indirect tests reach it, and the compact line alone invites
|
||||
the wrong conclusion.
|
||||
- **It is a derived cache.** `scip-go` and tree-sitter rebuild it, and a query
|
||||
indexes the revisions it names, so a cold query is slow and losing the index
|
||||
costs a rebuild rather than data. `list_repositories` reports the indexed
|
||||
revision — compare it with the tree before trusting a default-revision answer.
|
||||
- **Stagger heavy queries.** Concurrent sessions share one instance, and
|
||||
**name-based** `symbol_context` is what locks: it returns `database is locked`
|
||||
or times out, while the same symbol **by id** returns immediately. Query
|
||||
serially and retry rather than assuming a hang.
|
||||
- **Report problems one line at a time** in
|
||||
`/work/apps/codegraph/data/feedback.jsonl` — one JSON object per line, keys
|
||||
`date`, `repo`, `task`, `tools`, `helped`, `missed`, `wrong`, `slow`. A raw
|
||||
newline inside a string makes the line invalid and breaks every reader; a
|
||||
multi-line entry corrupted that file once. Validate, append, never rewrite.
|
||||
|
||||
## Tracker conventions
|
||||
|
||||
`bd` is the only tracker; no markdown TODO lists, no local trackers.
|
||||
|
||||
@@ -5,6 +5,96 @@ release's per-component sections are labelled beneath its heading.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.45.0] - 2026-09-30
|
||||
|
||||
### archied
|
||||
|
||||
- fix(eda): reject a result map missing a field or needing a conversion
|
||||
- feat(eda): per-org workflow enable/disable gating bindings
|
||||
- feat(telegram): carry inbound media through the chat turn
|
||||
- fix(prsource): use a CodeQL-recognised containment guard when extracting archives
|
||||
- feat(store): key control-plane resources by (org, kind)
|
||||
- fix(store): refuse resource keys the audit key cannot disambiguate
|
||||
- fix(daemon): resume the task branch before container acquisition
|
||||
- feat(webui): show attachment metadata in the session transcript
|
||||
- feat(webui): name a workflow's declared inputs on the work-request form
|
||||
- feat(controlplane): carry the caller org from the request principal
|
||||
- fix(webui): the workflow handlers act in the caller's org
|
||||
- feat(kitrun): render the OAuth credential file with sentinels
|
||||
- feat(store): record accepted package authority against the pin
|
||||
- fix(workflow): the own-PR flow no longer parks on the operator-approval gate
|
||||
- feat(gateway): a TTL-bounded dedup gate for redelivered platform messages
|
||||
- feat(egress): capture the OAuth scope set and carry it to the harness secret
|
||||
- feat(kitrun): render the OAuth scopes and omit an uncaptured primary key
|
||||
- feat(store): project installed package contributions into org resources
|
||||
- feat(gateway): coalesce rapid-fire text events into one turn
|
||||
- fix(config): expand plugin, module and skills dirs like every other operator path
|
||||
- fix(webui): drop the config schema's editability advert
|
||||
- feat(webui): events counts, YAML reading, log rows and dashboard filters
|
||||
|
||||
### archie-agent
|
||||
|
||||
- feat(eda): per-org workflow enable/disable gating bindings
|
||||
- feat(telegram): carry inbound media through the chat turn
|
||||
- fix(prsource): use a CodeQL-recognised containment guard when extracting archives
|
||||
- feat(store): key control-plane resources by (org, kind)
|
||||
- feat(controlplane): carry the caller org from the request principal
|
||||
- feat(kitrun): render the OAuth credential file with sentinels
|
||||
- feat(store): record accepted package authority against the pin
|
||||
- fix(workflow): the own-PR flow no longer parks on the operator-approval gate
|
||||
- feat(egress): capture the OAuth scope set and carry it to the harness secret
|
||||
- feat(kitrun): render the OAuth scopes and omit an uncaptured primary key
|
||||
- feat(store): project installed package contributions into org resources
|
||||
|
||||
## [1.44.1] - 2026-09-29
|
||||
|
||||
### archied
|
||||
|
||||
Two fixes to tasks that could not get past their workflow definition.
|
||||
|
||||
- **Approving a task no longer parks it again.** A task requeued under a
|
||||
different workflow kept the previous run's definition pinned, so the worker
|
||||
refused to compile the dispatch — it named `feasibility` while the row named
|
||||
`implement` — and the task parked immediately, identically on every further
|
||||
approval, which left `decline` as the only working operator action.
|
||||
The daemon now re-pins whenever the pinned definition's id disagrees with the
|
||||
task's workflow. A pin that is present, digest-valid and id-consistent is
|
||||
still a strict no-op, so an operator's own definition override survives a
|
||||
dispatch unchanged.
|
||||
- **A shipped workflow definition now reaches an existing install.** A stored
|
||||
seed was consulted only for a resource the store did not already hold, so a
|
||||
document that changed in the build never reached a database an earlier
|
||||
release had seeded. For workflow definitions that is a total outage rather
|
||||
than a stale setting: the collection validates as one document, so a stored
|
||||
step type this build no longer has failed every task's pin, whatever workflow
|
||||
the task named — and the documented recovery, removing the resource and
|
||||
restarting, wrote nothing either, because the store answered the seed's known
|
||||
request ID from a history that outlives the resource. A seed now refreshes a
|
||||
kind it wrote the newest revision of and re-creates a resource that is gone,
|
||||
while an operator's own replacement is never undone.
|
||||
|
||||
### archie-agent
|
||||
|
||||
The runtime image is rebuilt with this release and links the shared workflow
|
||||
package carrying the definition-id helper above. Hosts that run agent
|
||||
containers need `docker compose pull agent` after updating to pick it up.
|
||||
|
||||
## [1.44.0] - 2026-09-29
|
||||
|
||||
### archied
|
||||
|
||||
Archie can now review pull requests.
|
||||
|
||||
- **Reviews on request and by watch.** Ask in chat or on the dashboard work form, add a repository to the watch list, or just let archie review its own PRs before it opens them. Review intensity follows a depth dial (quick/standard/deep) classified from the size of the change, and every finished review passes a verification layer — coverage-gap and cross-finding consistency checks — before it is produced.
|
||||
- **No forge credential reaches the review sandbox.** The daemon prefetches the pull request's data and rebuilds its source snapshot over the forge's HTTP API, so the agent container works from an isolated copy with no read access to the repository's credentials.
|
||||
- **Reviews stop at the operator gate before posting.** `review.precision_gate` / `approve_before_post` decide whether a finished review posts itself or parks for operator approval. With this release the parked state is a stop sign, not a checkpoint: the approve/reject/re-review responses behind the gate are not wired yet, and the gate's settings are not yet editable in the dashboard (configure them in `config.toml`). A parked review sits until that follow-up lands.
|
||||
- The adversarial self-review pass archie previously ran before opening its own PRs is superseded by this pipeline and has been removed.
|
||||
- Hardened harness input handling: harness identifiers are bounded to integer types.
|
||||
|
||||
### archie-agent
|
||||
|
||||
The runtime image is rebuilt with this release; it links the shared pr-review workflow packages behind the reviews above. Hosts that run agent containers need `docker compose pull agent` after updating to pick it up.
|
||||
|
||||
## [1.43.0] - 2026-09-28
|
||||
|
||||
### archied
|
||||
|
||||
@@ -341,10 +341,12 @@ StateStoreGrantIssuer` (`staterpc.GrantIssuer`) registers a fresh
|
||||
separate fresh-context reviewer pass on every change as a matter of course.
|
||||
Red-green TDD plus `task check` is the gate; a manual adversarial pass is
|
||||
opt-in per request — ask before running one. This is the rule for a human or
|
||||
agent _contributor_. Separately, archied runs the same adversarial review
|
||||
automatically on the PRs it opens (gated per repo by `repo.review_enabled`)
|
||||
— see `docs/architecture/adversarial-review.md`. The two paths are distinct:
|
||||
you run one when asked; archied runs one before it opens a PR.
|
||||
agent _contributor_. Separately, archied runs its own PR review pipeline
|
||||
(`docs/prds/pr-review-agent.md`) before it opens a PR of its own — see that
|
||||
PRD's Triggers section ("archie's own PRs"). It supersedes the older
|
||||
single-reviewer stage `docs/architecture/adversarial-review.md` described
|
||||
(`repo.review_enabled` no longer exists). The two paths are distinct: you
|
||||
run a manual pass when asked; archied runs its own before it opens a PR.
|
||||
6. **Linter Guard:**
|
||||
|
||||
- When using `errorlint` fixes, ensure boolean predicates (e.g.
|
||||
|
||||
+1
-1
@@ -154,7 +154,7 @@ tasks:
|
||||
- bash tools/webhook-send.sh {{.CLI_ARGS}}
|
||||
|
||||
bench:prreview:
|
||||
desc: Score PR review findings on the Martian benchmark (-- -findings DIR; --help for flags)
|
||||
desc: Review or rescore the Martian benchmark (-- -review-model PROVIDER/MODEL -classification-model PROVIDER/MODEL; --help for flags)
|
||||
cmds:
|
||||
- go run ./cmd/archie-prbench {{.CLI_ARGS}}
|
||||
|
||||
|
||||
@@ -20,13 +20,20 @@ func main() { os.Exit(run()) }
|
||||
func run() int {
|
||||
var opts prbench.Options
|
||||
var problems string
|
||||
flag.StringVar(&opts.Config, "config", configuration.DefaultConfigPath(), "configuration file whose providers serve the judge model")
|
||||
flag.StringVar(&opts.Fixtures, "findings", "", "directory of <problem id>.json findings to score")
|
||||
flag.StringVar(&opts.Config, "config", configuration.DefaultConfigPath(), "configuration file whose providers serve the reviewer and judge")
|
||||
flag.StringVar(&opts.Fixtures, "findings", "", "directory of <problem id>.json findings to rescore; omit to review live")
|
||||
flag.StringVar(&opts.ReviewModel, "review-model", "", "provider/model for the review role in live runs")
|
||||
flag.StringVar(&opts.ClassifyModel, "classification-model", "", "provider/model for the classification role in live runs")
|
||||
flag.StringVar(&opts.JudgeModel, "judge-model", "anthropic/claude-sonnet-4.6", "provider/model of the independent judge")
|
||||
flag.StringVar(&opts.Out, "out", "prbench-out", "directory for per-problem results and summary.json")
|
||||
flag.StringVar(&opts.Out, "out", "bin/prbench-results", "directory for per-problem results and summary.json")
|
||||
flag.StringVar(&opts.Resume, "resume", "", "reuse complete results from a previous run with the same models")
|
||||
flag.StringVar(&problems, "problems", "", "comma-separated problem ids (default: all)")
|
||||
flag.IntVar(&opts.Concurrency, "concurrency", 4, "problems judged at once")
|
||||
flag.Parse()
|
||||
opts.GitHubToken = os.Getenv("GH_TOKEN")
|
||||
if opts.GitHubToken == "" {
|
||||
opts.GitHubToken = os.Getenv("GITHUB_TOKEN")
|
||||
}
|
||||
if problems != "" {
|
||||
opts.Problems = strings.Split(problems, ",")
|
||||
}
|
||||
|
||||
@@ -338,6 +338,7 @@ func TestStateStoreRealProcessSmoke(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("real-process smoke test builds and execs the binary; skip under -short")
|
||||
}
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
bin := buildBinary(t, dir)
|
||||
cfg := writeConfigWithServiceListen(t, dir)
|
||||
@@ -355,7 +356,7 @@ func TestStateStoreRealProcessSmoke(t *testing.T) {
|
||||
// Combined task/event/capture view: a task, an event on that task, and an
|
||||
// unrelated capture written through one consumer, read back across all
|
||||
// three surfaces in a single pass (the dashboard/observability read path).
|
||||
task, err := cl.EnqueueChatTask(ctx, "acme", "widget", "verify state store", "body", "implement", "")
|
||||
task, err := cl.EnqueueChatTask(ctx, "acme", "widget", "verify state store", "body", "implement", "", nil)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("EnqueueChatTask = %+v, %v", task, err)
|
||||
}
|
||||
@@ -453,6 +454,7 @@ func TestStateStoreRealProcessDeadline(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("real-process smoke test builds and execs the binary; skip under -short")
|
||||
}
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
bin := buildBinary(t, dir)
|
||||
cfg := writeMinimalConfig(t, dir)
|
||||
@@ -479,13 +481,14 @@ func TestStateStoreRealProcessRestartRecovery(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("real-process smoke test builds and execs the binary; skip under -short")
|
||||
}
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
bin := buildBinary(t, dir)
|
||||
cfg := writeMinimalConfig(t, dir)
|
||||
|
||||
first := startStateStoreProcess(t, bin, cfg)
|
||||
s1 := dial(t, first.addr)
|
||||
task, err := s1.EnqueueChatTask(t.Context(), "acme", "widget", "survive restart", "body", "implement", "")
|
||||
task, err := s1.EnqueueChatTask(t.Context(), "acme", "widget", "survive restart", "body", "implement", "", nil)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("first EnqueueChatTask = %+v, %v", task, err)
|
||||
}
|
||||
@@ -525,6 +528,7 @@ func TestStateStoreRealProcessTokenProtectedCaptureStream(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("real-process smoke test builds and execs the binary; skip under -short")
|
||||
}
|
||||
t.Parallel()
|
||||
const token = "operator-secret-token"
|
||||
dir := t.TempDir()
|
||||
bin := buildBinary(t, dir)
|
||||
@@ -572,6 +576,7 @@ func TestStateStoreRealProcessRemoteSurfaces(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("real-process smoke test builds and execs the binary; skip under -short")
|
||||
}
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
bin := buildBinary(t, dir)
|
||||
cfg := writeMinimalConfig(t, dir)
|
||||
|
||||
@@ -52,7 +52,7 @@ func recoveryFixture(t *testing.T) (string, *pgstore.TaskDB) {
|
||||
// seedTask writes one task so the database holds more than its settings.
|
||||
func seedTask(t *testing.T, st *pgstore.TaskDB, title string) {
|
||||
t.Helper()
|
||||
if _, err := st.EnqueueChatTask(t.Context(), "acme", "widget", title, "body", "implement", ""); err != nil {
|
||||
if _, err := st.EnqueueChatTask(t.Context(), "acme", "widget", title, "body", "implement", "", nil); err != nil {
|
||||
t.Fatalf("seed task %q: %v", title, err)
|
||||
}
|
||||
}
|
||||
@@ -259,7 +259,7 @@ func TestRecoveryRollbackReplaysTheRevisionThroughReplace(t *testing.T) {
|
||||
if !strings.Contains(stdout, controlplane.ModelRoleAssignmentsKind) {
|
||||
t.Errorf("rollback must name the resource it replayed; stdout = %q", stdout)
|
||||
}
|
||||
resource, err := st.Resource(t.Context(), controlplane.ModelRoleAssignmentsKind)
|
||||
resource, err := st.Resource(t.Context(), storecontract.DefaultOrgID, controlplane.ModelRoleAssignmentsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -269,7 +269,7 @@ func TestRecoveryRollbackReplaysTheRevisionThroughReplace(t *testing.T) {
|
||||
if resource.Version != 3 {
|
||||
t.Errorf("resource version = %d, want a new revision (3) rather than a rewrite of the old one", resource.Version)
|
||||
}
|
||||
history, err := st.ResourceHistory(t.Context(), controlplane.ModelRoleAssignmentsKind, 0)
|
||||
history, err := st.ResourceHistory(t.Context(), storecontract.DefaultOrgID, controlplane.ModelRoleAssignmentsKind, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -293,7 +293,7 @@ func TestRecoveryRollbackRestoresANamedRevision(t *testing.T) {
|
||||
if code != 0 {
|
||||
t.Fatalf("rollback exited %d: %s", code, stderr)
|
||||
}
|
||||
resource, err := st.Resource(t.Context(), controlplane.ModelRoleAssignmentsKind)
|
||||
resource, err := st.Resource(t.Context(), storecontract.DefaultOrgID, controlplane.ModelRoleAssignmentsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -463,7 +463,7 @@ func storedResourceCount(t *testing.T, stdout string) int {
|
||||
// a silent no-op.
|
||||
func seedResource(t *testing.T, st *pgstore.TaskDB, kind, value, label string) {
|
||||
t.Helper()
|
||||
current, err := st.Resource(t.Context(), kind)
|
||||
current, err := st.Resource(t.Context(), storecontract.DefaultOrgID, kind)
|
||||
expected := int64(0)
|
||||
if err == nil {
|
||||
expected = current.Version
|
||||
@@ -477,7 +477,8 @@ func seedResource(t *testing.T, st *pgstore.TaskDB, kind, value, label string) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
Kind: kind, Value: encoded, Actor: label, Source: "test",
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: kind, Value: encoded, Actor: label, Source: "test",
|
||||
RequestID: fmt.Sprintf("%s-%d", label, expected+1), ExpectedVersion: expected,
|
||||
}); err != nil {
|
||||
t.Fatalf("seed resource %s: %v", kind, err)
|
||||
|
||||
@@ -496,9 +496,6 @@ target = "127.0.0.1:9090" # REQUIRED. The State Store gRPC address arch
|
||||
# # [containers].max_concurrency globally.
|
||||
# # persistent_storage = true # reuse a per-repo Docker volume and Git object cache until volume_ttl
|
||||
# # max_retries = 5 # per-repo override of the global max_retries above
|
||||
# # review_enabled = true # run a fresh adversarial reviewer (no path to the implementer's
|
||||
# # context) after gates pass and before the PR opens. Default false --
|
||||
# # an uncalibrated reviewer that cries wolf is worse than no review.
|
||||
|
||||
# ── Tools ───────────────────────────────────────────────────────────────────
|
||||
# Limits on what a tool may return. These bound how much of the context window
|
||||
|
||||
@@ -1,6 +1,29 @@
|
||||
# Adversarial self-review
|
||||
|
||||
Archie runs a fresh adversarial review of the diff before it opens a pull
|
||||
> **Removed, not shipped (2026-09-28, `d73e0748`). This page records a system
|
||||
> that no longer exists in the tree.**
|
||||
>
|
||||
> `d73e0748` ("remove the superseded adversarial-self-review system") deleted the
|
||||
> stage and its contract: `workflow.Reviewer`, `ReviewRequest`, `ReviewReport`
|
||||
> and `StageReview` are gone from `internal/domain/workflow`, so everything under
|
||||
> "Contract" below describes types that cannot be found.
|
||||
>
|
||||
> The authority is `docs/prds/pr-review-agent.md`, which says so itself: it
|
||||
> "supersedes the reviewer executor and blocking rule in
|
||||
> `docs/architecture/adversarial-review.md`". archied now runs its PR review
|
||||
> pipeline before it opens a pull request; there is no separate adversarial
|
||||
> self-review pass and no `repo.review_enabled` setting.
|
||||
>
|
||||
> The page is kept rather than deleted because PRDs link to it
|
||||
> (`docs/prds/adversarial-self-review.md`, `docs/prds/inline-review.md`,
|
||||
> `docs/prds/pr-review-agent.md`). Read it as history.
|
||||
>
|
||||
> One section is stale in a second, older way: "Operator-triggered review" below
|
||||
> describes the synchronous `review_pr` (fetch the head, snapshot it, run the
|
||||
> reviewer, return findings), which `archie-core-afbk.14` replaced with a queued
|
||||
> pr-review task.
|
||||
|
||||
Archie ran a fresh adversarial review of the diff before it opened a pull
|
||||
request, so a PR arrives with a findings record rather than an unreviewed
|
||||
claim. The reviewer provably cannot see the implementer's context: it reviews a
|
||||
`.git`-free snapshot of the committed tree, not the worktree, the commit
|
||||
|
||||
@@ -312,6 +312,11 @@
|
||||
"additionalProperties": false,
|
||||
"description": "MediaAttachment describes a file attached to a message.",
|
||||
"properties": {
|
||||
"data": {
|
||||
"contentEncoding": "base64",
|
||||
"description": "Data carries the attachment bytes in-process. An inbound path sets\nit after downloading the file; outbound senders never set it and\nread Path or URL instead. It never crosses a wire or persistence\nboundary -- it is a turn-scoped value, not a stored one.",
|
||||
"type": "string"
|
||||
},
|
||||
"duration": {
|
||||
"description": "Duration is the play time in seconds for audio and video.",
|
||||
"type": "integer"
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"url": "/dev/architecture/adversarial-review/",
|
||||
"title": "Adversarial self-review",
|
||||
"section": "Architecture",
|
||||
"body": "# Adversarial self-review\n\nArchie runs a fresh adversarial review of the diff before it opens a pull\nrequest, so a PR arrives with a findings record rather than an unreviewed\nclaim. The reviewer provably cannot see the implementer's context: it reviews a\n`.git`-free snapshot of the committed tree, not the worktree, the commit\nhistory, or the implementer's transcript.\n\nPromoted from `docs/prds/adversarial-self-review.md` (the design decision;\n`archie-core-h019`). Describes the stage as shipped.\n\n## Contract (`internal/domain/workflow`)\n\nThe workflow domain owns the contract and the blocking decision; it never names\nthe executor.\n\n- `Reviewer.Review(ctx, ReviewRequest) ReviewReport` — the interface the\n workflow stage consumes.\n- `ReviewRequest` is the reviewer's entire input: `SnapshotDir` (a `.git`-free\n export of the reviewed commit), `Diff` (base...head), `IssueText` (the\n originating issue title/body), and `MaxSteps`.\n- `ReviewFinding` / `ReviewReport` are the structured result. The load-bearing\n rule is `Blocking() == (Verdict == confirmed \u0026\u0026 Level == error)`: only a\n confirmed error-level finding blocks; a plausible finding never blocks\n however severe it claims to be.\n\n`ReviewReport` distinguishes `not_run`, `skipped`, and `completed` (zero\nfindings) structurally, so \"ran and found nothing\" is not the same as \"never\nran\" — collapsing them would make an outage indistinguishable from a clean\nreview.\n\n## Execution (`internal/app/agentworker`)\n\nThe executor is an ai-sdk `agent.Subagent`: a nested synchronous generation in\nthe same worker process, with its own model, system prompt, toolset and step\nbudget.\n\n- **Conversation isolation is structural.** `Subagent.Run` sends only a prompt\n string, never the implementer's message history.\n- **Workspace isolation is the `.git`-free snapshot.** The reviewer's toolset is\n read-only (`read`, `grep`, `find`) and rooted at `SnapshotDir` — never the\n worker's own toolset, which carries the `worktreerpc` publication grant.\n- **Findings return through a typed capture tool** (`record_finding`), validated\n on the way in, so the reviewer reports through the contract rather than free\n text the caller regexes.\n- **Fail-closed.** A reviewer that errors, truncates, or reaches no conclusion\n yields `ReviewStatusNotRun`, which the stage treats as a park — never a silent\n \"PR opened unreviewed\".\n\n## Lifecycle effect\n\n`StageReview` runs in the implement workflow after the deterministic gates and\nbefore `StageOpenPR`, gated by `repo.review_enabled` (opt-in, default off). A\nsurviving blocking finding — or a review that failed to run — parks the task\n(`StatusParked`, not `waiting_human`) with the findings rendered into the park\nreason; `StageOpenPR` never runs. Warn/plausible findings and the zero-finding\ncase leave the outcome unset, so the PR opens with a findings section rendered\nonto its body. `StagePostReviewComments` then runs after `StageOpenPR` and posts\nthe **line-anchored** findings as inline review comments, carrying a one-click\nsuggestion on a confirmed finding the reviewer could state a fix for. That stage\nis best-effort — a comment that fails to post is logged, never a park — because\nthe body section already lists every finding, and it is the record a whole-file\nfinding (no line to anchor to) only ever appears in.\n\n## Model and budget\n\nThe reviewer model is `models.reviewer`, falling back to `models.builder`.\nEffort is the per-stage `MaxSteps` budget, mapped onto `Subagent.MaxSteps`\n(default 10).\n\n## Operator-triggered review\n\nThe same reviewer runs against an _existing_ PR via the channel-neutral\n`review_pr` chat command: fetch the PR's head, snapshot it, run the isolated\nreviewer, and return the structured findings. Authorisation is identity-scoped\nto the operator's configured repositories; duplicate or concurrent reviews of\nthe same PR are deduplicated.\n"
|
||||
"body": "# Adversarial self-review\n\n\u003e **Removed, not shipped (2026-09-28, `d73e0748`). This page records a system\n\u003e that no longer exists in the tree.**\n\u003e\n\u003e `d73e0748` (\"remove the superseded adversarial-self-review system\") deleted the\n\u003e stage and its contract: `workflow.Reviewer`, `ReviewRequest`, `ReviewReport`\n\u003e and `StageReview` are gone from `internal/domain/workflow`, so everything under\n\u003e \"Contract\" below describes types that cannot be found.\n\u003e\n\u003e The authority is `docs/prds/pr-review-agent.md`, which says so itself: it\n\u003e \"supersedes the reviewer executor and blocking rule in\n\u003e `docs/architecture/adversarial-review.md`\". archied now runs its PR review\n\u003e pipeline before it opens a pull request; there is no separate adversarial\n\u003e self-review pass and no `repo.review_enabled` setting.\n\u003e\n\u003e The page is kept rather than deleted because PRDs link to it\n\u003e (`docs/prds/adversarial-self-review.md`, `docs/prds/inline-review.md`,\n\u003e `docs/prds/pr-review-agent.md`). Read it as history.\n\u003e\n\u003e One section is stale in a second, older way: \"Operator-triggered review\" below\n\u003e describes the synchronous `review_pr` (fetch the head, snapshot it, run the\n\u003e reviewer, return findings), which `archie-core-afbk.14` replaced with a queued\n\u003e pr-review task.\n\nArchie ran a fresh adversarial review of the diff before it opened a pull\nrequest, so a PR arrives with a findings record rather than an unreviewed\nclaim. The reviewer provably cannot see the implementer's context: it reviews a\n`.git`-free snapshot of the committed tree, not the worktree, the commit\nhistory, or the implementer's transcript.\n\nPromoted from `docs/prds/adversarial-self-review.md` (the design decision;\n`archie-core-h019`). Describes the stage as shipped.\n\n## Contract (`internal/domain/workflow`)\n\nThe workflow domain owns the contract and the blocking decision; it never names\nthe executor.\n\n- `Reviewer.Review(ctx, ReviewRequest) ReviewReport` — the interface the\n workflow stage consumes.\n- `ReviewRequest` is the reviewer's entire input: `SnapshotDir` (a `.git`-free\n export of the reviewed commit), `Diff` (base...head), `IssueText` (the\n originating issue title/body), and `MaxSteps`.\n- `ReviewFinding` / `ReviewReport` are the structured result. The load-bearing\n rule is `Blocking() == (Verdict == confirmed \u0026\u0026 Level == error)`: only a\n confirmed error-level finding blocks; a plausible finding never blocks\n however severe it claims to be.\n\n`ReviewReport` distinguishes `not_run`, `skipped`, and `completed` (zero\nfindings) structurally, so \"ran and found nothing\" is not the same as \"never\nran\" — collapsing them would make an outage indistinguishable from a clean\nreview.\n\n## Execution (`internal/app/agentworker`)\n\nThe executor is an ai-sdk `agent.Subagent`: a nested synchronous generation in\nthe same worker process, with its own model, system prompt, toolset and step\nbudget.\n\n- **Conversation isolation is structural.** `Subagent.Run` sends only a prompt\n string, never the implementer's message history.\n- **Workspace isolation is the `.git`-free snapshot.** The reviewer's toolset is\n read-only (`read`, `grep`, `find`) and rooted at `SnapshotDir` — never the\n worker's own toolset, which carries the `worktreerpc` publication grant.\n- **Findings return through a typed capture tool** (`record_finding`), validated\n on the way in, so the reviewer reports through the contract rather than free\n text the caller regexes.\n- **Fail-closed.** A reviewer that errors, truncates, or reaches no conclusion\n yields `ReviewStatusNotRun`, which the stage treats as a park — never a silent\n \"PR opened unreviewed\".\n\n## Lifecycle effect\n\n`StageReview` runs in the implement workflow after the deterministic gates and\nbefore `StageOpenPR`, gated by `repo.review_enabled` (opt-in, default off). A\nsurviving blocking finding — or a review that failed to run — parks the task\n(`StatusParked`, not `waiting_human`) with the findings rendered into the park\nreason; `StageOpenPR` never runs. Warn/plausible findings and the zero-finding\ncase leave the outcome unset, so the PR opens with a findings section rendered\nonto its body. `StagePostReviewComments` then runs after `StageOpenPR` and posts\nthe **line-anchored** findings as inline review comments, carrying a one-click\nsuggestion on a confirmed finding the reviewer could state a fix for. That stage\nis best-effort — a comment that fails to post is logged, never a park — because\nthe body section already lists every finding, and it is the record a whole-file\nfinding (no line to anchor to) only ever appears in.\n\n## Model and budget\n\nThe reviewer model is `models.reviewer`, falling back to `models.builder`.\nEffort is the per-stage `MaxSteps` budget, mapped onto `Subagent.MaxSteps`\n(default 10).\n\n## OperatorLine truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/architecture/agent-system/",
|
||||
@@ -106,7 +106,7 @@
|
||||
"url": "/dev/development/",
|
||||
"title": "Development guides",
|
||||
"section": "Development",
|
||||
"body": "# Development guides\n\nChecklists for changing Archie, one page per area. Each names every place a\nchange must reach, so a feature that works in one layer does not silently stop\nat the next. A change that spans areas starts on the page for the area it\nbegins in, which points to the others. The pages point at the documents that\nown the design (`docs/architecture/`, the PRDs, `CLAUDE.md`) rather than\nrestating them.\n\n| Area | Covers |\n| ---------------------------------------------- | -------------------------------------------------------------------------------- |\n| [Frontend UI](/dev/development/frontend-ui/) | Anything under `ui/`, and the dashboard's API routes |\n| [Agent](/dev/development/agent/) | The agent container, its image, profiles, tools and workspace |\n| [Workflows](/dev/development/workflows/) | Workflow definitions and step types |\n| [Daemon](/dev/development/daemon/) | Task statuses, fields and the brief; sources, event types, mappings and bindings |\n| [State Store](/dev/development/state-store/) | Stored fields, tables, RPCs and errors |\n| [Control plane and settings](/dev/development/control-plane/) | Settings in `config.toml` or the dashboard |\n| [Processes and wiring](/dev/development/wiring/) | Where code goes, processes, plugin engines, channels, NATS subjects |\n| [Merging work](/dev/development/merging-work/) | Merging a lane or a branch |\n\n## Every change\n\n- Write the failing test first for anything with logic, branching or a\n contract, and check it fails on an assertion, not a compile error.\n- Test through the path production uses. A test that sets a value directly on\n the consumer proves nothing about the layers that normally deliver it.\n- Run `task check` and let its exit status decide the commit:\n `task check \u0026\u0026 git commit ...`. `task test` passes `-short`, which skips the\n process and Postgres tests, so run `go test -count=1 ./cmd/... ./internal/...`\n too when a change crosses a process or the database.\n- Regenerate, never hand-edit, generated output: `task proto:generate`,\n `go -C tools tool sqlc generate -f $PWD/internal/infrastructure/postgres/sqlc.yaml`,\n `task ui`, `task docs:artifact`. `task proto:check` compares against the git\n index, so stage regenerated contracts before running it.\n- Stage by path, or read `git status` before `git add -A`. Tests that start\n embedded NATS or write logs must use `t.TempDir()`; anything they leave in the\n tree gets committed. `task check` also adds linter-tool lines to `go.sum`\n (bead 1e37); restore `go.sum` before committing unless you changed a\n dependency.\n- A change to `docs/prds/`, `docs/architecture/` **or `docs/development/`**\n carries the regenerated `docs/data/generated/dev-docs.json`: run\n `task docs:artifact` (not `task docs:check`, which checks contracts only).\n PRD edits also follow `docs/prds/RULES.md` and pass `task docs:prds`.\n"
|
||||
"body": "# Development guides\n\nChecklists for changing Archie, one page per area. Each names every place a\nchange must reach, so a feature that works in one layer does not silently stop\nat the next. A change that spans areas starts on the page for the area it\nbegins in, which points to the others. The pages point at the documents that\nown the design (`docs/architecture/`, the PRDs, `CLAUDE.md`) rather than\nrestating them.\n\n| Area | Covers |\n| ---------------------------------------------- | -------------------------------------------------------------------------------- |\n| [Frontend UI](/dev/development/frontend-ui/) | Anything under `ui/`, and the dashboard's API routes |\n| [Agent](/dev/development/agent/) | The agent container, its image, profiles, tools and workspace |\n| [Workflows](/dev/development/workflows/) | Workflow definitions and step types |\n| [Daemon](/dev/development/daemon/) | Task statuses, fields and the brief; sources, event types, mappings and bindings |\n| [State Store](/dev/development/state-store/) | Stored fields, tables, RPCs and errors |\n| [Control plane and settings](/dev/development/control-plane/) | Settings in `config.toml` or the dashboard |\n| [Processes and wiring](/dev/development/wiring/) | Where code goes, processes, plugin engines, channels, NATS subjects |\n| [Merging work](/dev/development/merging-work/) | Merging a lane or a branch |\n\n## Every change\n\n- Write the failing test first for anything with logic, branching or a\n contract, and check it fails on an assertion, not a compile error.\n- Test through the path production uses. A test that sets a value directly on\n the consumer proves nothing about the layers that normally deliver it.\n- Run `task check` and let its exit status decide the commit:\n `task check \u0026\u0026 git commit ...`. `task test` passes `-short`, which skips the\n process and Postgres tests, so run `go test -count=1 ./cmd/... ./internal/...`\n too when a change crosses a process or the database.\n- Regenerate, never hand-edit, generated output: `task proto:generate`,\n `go -C tools tool sqlc generate -f $PWD/internal/infrastructure/postgres/sqlc.yaml`,\n `task ui`, `task docs:artifact`. `task proto:check` compares against the git\n index, so stage regenerated contracts before running it.\n- Stage by path, or read `git status` before `git add -A`. Tests that start\n embedded NATS or write logs must use `t.TempDir()`; anything they leave in the\n tree gets committed. `task check` writes no module file on a consistent tree,\n root or `tools/` (verified at HEAD with `GOFLAGS` unset and with `-mod=mod`):\n a stale `go.mod` or `go.sum` fails it, with `missing go.sum entry` or\n `updates to go.mod needed`, rather than being repaired. Only a global\n `GOFLAGS=-mod=mod` in `go env` re-enables that repair, which is why the\n `go -C tools` steps pass `-mod=readonly`; if `go.sum` goes dirty, run\n `go mod tidy` and commit the result on its own.\n- A change to `docs/prds/`, `docs/architecture/` **or `docs/development/`**\n carries the regenerated `docs/data/generated/dev-docs.json`: run\n `task docs:artifact` (not `task docs:check`, which checks contracts only).\n PRD edits also follow `docs/prds/RULES.md` and pass `task docs:prds`.\n"
|
||||
},
|
||||
{
|
||||
"url": "/dev/development/agent/",
|
||||
@@ -118,19 +118,19 @@
|
||||
"url": "/dev/development/control-plane/",
|
||||
"title": "Control plane and settings",
|
||||
"section": "Development",
|
||||
"body": "# Control plane and settings\n\nAuthority: `docs/architecture/configuration.md`. The wiring matrix, the\ndecoded-but-unwired ledger and the three shapes an unwired field takes are in\n`.agents/skills/archie-config-and-flags`.\n\nA field that parses is not a field that works. Before adding one, name the code\nthat reads it and the path the value takes to get there.\n\n## Decide what kind of setting it is\n\n- **Bootstrap-only** (read once at process start: `database_url`, `state_dir`,\n `work_dir`). It stays in the file, is checked by `validateBootstrap` in\n `internal/infrastructure/configuration/validate.go`, and the runtime overlay\n refuses changes to it.\n- **Database-owned** (repository policies, scheduling, tools, plugins,\n channels, containers). The file only seeds it. Once the State Store holds the\n control-plane resource, the stored document is layered over the file\n (`controlplane.Client.RuntimeConfig`) and the file key stops mattering. It is\n checked by `validateDatabaseOwned` and by the resource's validator.\n- **Worker-carried.** A value the agent container needs travels in\n `config.TaskConfig` (`Config.ForTask`) or on `taskrun.Request`. Never pass it\n as an environment variable the daemon did not already define, and never carry\n a secret this way.\n\n## Adding a database-owned field\n\n1. Add it to the wire-shape type the resource's `Document` names — a dedicated\n struct in `internal/app/controlplane/` with explicit snake_case json tags\n (`channel_settings.go`, `tool_settings.go`, `container_settings.go` are the\n precedents), never the internal config struct itself. A struct fed straight\n into the document falls back to Go field names (`Window`, `MaxRequests`),\n and a bare `time.Duration` marshals as nanoseconds — both render unusable\n in the Web UI. The resource's JSON schema and the dashboard's Advanced\n settings editor are generated from that type, so no UI work is needed for\n the editor itself.\n2. Map to and from the internal config type at the resource boundary (`Seed`,\n the layering in `runtime_config.go`, and the validator all use the same\n mapping). Durations in the document are a string-marshalling type\n (`config.Duration` or a document-local one), never a bare `time.Duration`.\n3. A document stored before the shape existed carries Go-cased keys. Read them\n with `controlplanerpc.DecodeRenamingLegacyKeys` (an `UnmarshalJSON` on the\n wire type) while keeping `DisallowUnknownFields` — dropping unknown keys\n would decode a misspelling as \"unset\" — and register a `Normalize` on the\n `Definition` that re-encodes the document, so a legacy document converges\n the next time it is written. A map or a nested struct needs its layering\n checked: a stored map replaces the file's, not merges into it, and a field\n the stored document omits keeps the file's value. Add a case to\n `internal/app/controlplane/runtime_config_test.go` for both.\n4. Validate it in one function both sides call, and add a case to\n `TestResourceValidatorsRejectWhatEffectiveValidationRejects` in\n `validators_agree_test.go`, so the file and the resource cannot disagree.\n5. Decide whether it reloads: it does only if every consumer re-reads it from\n `config.Holder`. The allowlist is `internal/app/archied/reload.go`; anything\n not on it requires a restart.\n6. If the settings page shows it as a plain field, add it to\n `internal/webui/config_schema.go` and the view in `api_config.go`.\n7. A generic catalog resource (`replace` command, not domain-managed, no\n query service) is watched **once per archie-ui process** by `webui.RunLive`,\n then published to every browser through `/api/stream`. Do not add an\n EventSource per resource to a settings store or a gRPC Watch per HTTP client.\n The control-plane server polls `Resource` every 250ms per upstream Watch;\n verify watch count is independent of client count and that late clients get\n the hub's current value (`internal/webui/live_hub_test.go`, real server over\n bufconn). Reopens resume after the last delivered version and charge failed\n attempts; accepting a gRPC stream does not establish its health.\n\n## Every new field\n\n- Test through the layering: build the effective config the way boot does,\n not by setting the field on the consumer.\n- Add a commented example to `config.example.toml`. Touch `deployments/*.toml`\n only when a profile there needs a value different from the default.\n- Update the wiring matrix in `.agents/skills/archie-config-and-flags`.\n- Secrets are `SecretRef`s resolved through the secret registry. Never inspect\n a resolved value, even in a test.\n- Reject a configuration that sets a field with no consumer rather than\n accepting and ignoring it (per-identity `forge.intake` is the precedent).\n"
|
||||
"body": "# Control plane and settings\n\nAuthority: `docs/architecture/configuration.md`. The wiring matrix, the\ndecoded-but-unwired ledger and the three shapes an unwired field takes are in\n`.agents/skills/archie-config-and-flags`.\n\nA field that parses is not a field that works. Before adding one, name the code\nthat reads it and the path the value takes to get there.\n\n## Decide what kind of setting it is\n\n- **Bootstrap-only** (read once at process start: `database_url`, `state_dir`,\n `work_dir`). It stays in the file, is checked by `validateBootstrap` in\n `internal/infrastructure/configuration/validate.go`, and the runtime overlay\n refuses changes to it.\n- **Database-owned** (repository policies, scheduling, tools, plugins,\n channels, containers). The file only seeds it. Once the State Store holds the\n control-plane resource, the stored document is layered over the file\n (`controlplane.Client.RuntimeConfig`) and the file key stops mattering. It is\n checked by `validateDatabaseOwned` and by the resource's validator. A stored\n value is refreshed from the file only when the store has no value for the kind\n at all; a kind that ships a document of its own (workflow definitions,\n personas) is refreshed whenever the seed itself wrote the stored copy, since\n that copy is a previous release's document rather than an operator's\n (`controlplane.Server.seedKind`).\n- **Worker-carried.** A value the agent container needs travels in\n `config.TaskConfig` (`Config.ForTask`) or on `taskrun.Request`. Never pass it\n as an environment variable the daemon did not already define, and never carry\n a secret this way.\n\n## Adding a database-owned field\n\n1. Add it to the wire-shape type the resource's `Document` names — a dedicated\n struct in `internal/app/controlplane/` with explicit snake_case json tags\n (`channel_settings.go`, `tool_settings.go`, `container_settings.go` are the\n precedents), never the internal config struct itself. A struct fed straight\n into the document falls back to Go field names (`Window`, `MaxRequests`),\n and a bare `time.Duration` marshals as nanoseconds — both render unusable\n in the Web UI. The resource's JSON schema and the dashboard's Advanced\n settings editor are generated from that type, so no UI work is needed for\n the editor itself.\n2. Map to and from the internal config type at the resource boundary (`Seed`,\n the layering in `runtime_config.go`, and the validator all use the same\n mapping). Durations in the document are a string-marshalling type\n (`config.Duration` or a document-local one), never a bare `time.Duration`.\n3. A document stored before the shape existed carries Go-cased keys. Read them\n with `controlplanerpc.DecodeRenamingLegacyKeys` (an `UnmarshalJSON` on the\n wire type) while keeping `DisallowUnknownFields` — dropping unknown keys\n would decode a misspelling as \"unset\" — and register a `Normalize` on the\n `Definition` that re-encodes the document, so a legacy document converges\n the next time it is written. A map or a nested struct needs its layering\n checked: a stored map replaces the file's, not merges into it, and a field\n the stored document omits keeps the file's value. Add a case to\n `internal/app/controlplane/runtime_config_test.go` for both.\n4. Validate it in one function both sides call, and add a case to\n `TestResourceValidatorsRejectWhatEffectiveValidationRejects` in\n `validators_agree_test.go`, so the file and the resource cannot disagree.\n5. Decide whether it reloads: it does only if every consumer re-reads it from\n `config.Holder`. The allowlist is `internal/app/archied/reload.go`; anything\n not on it requires a restart.\n6. If the settings page shows it as a plain field, add it to\n `internal/webui/config_schema.go` and the view in `api_config.go`.\n7. A generic catalog resource (`replace` command, not domain-managed, no\n query service) is watched **once per archie-ui process** by `webui.RunLive`,\n then published to every browser through `/api/stream`. Do not add an\n EventSource per resource to a settings store or a gRPC Watch per HTTP client.\n The control-plane server polls `Resource` every 250ms per upstream Watch;\n verify watch count is independent of client count and that late clients get\n the hub's current value (`internal/webui/live_hub_test.go`, real server over\n bufconn). Reopens resume after the last delivered version and charge failed\n attempts; accepting a gRPC stream does not establish its health.\n\n## Every new field\n\n- Test through the layering: build the effective config the way boot does,\n not by setting the field on the consumer.\n- Add a commented example to `config.example.toml`. Touch `deployments/*.toml`\n only when a profile there needs a value different from the default.\n- Update the wiring matrix in `.agents/skills/archie-config-and-flags`.\n- Secrets are `SecretRef`s resolved throLine truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/development/daemon/",
|
||||
"title": "Daemon",
|
||||
"section": "Development",
|
||||
"body": "# Daemon\n\nThe daemon claims and runs tasks, and turns captured events into tasks through\nbindings. This page covers both.\n\n## Task lifecycle\n\nAuthority: `docs/architecture/agent-system.md`. The status vocabulary lives in\n`internal/taskstate`, which imports no internal package.\n\n### Adding a status\n\n1. Add the constant to `internal/taskstate/taskstate.go` and place it in\n `Terminal`, `Actions` and `Statuses`. Its value is stored, so renaming it\n later is a migration.\n2. Alias it in `internal/domain/workflow/task/task.go` and\n `internal/domain/workflow/task_aliases.go`.\n3. Add it to the default catalogue in `ui/src/lib/task-meta.ts`. The server\n catalogue replaces the defaults when it loads, but the defaults render first.\n4. Find every hand-written status list in SQL:\n `grep -rn \"'merged'\" internal/infrastructure/postgres/queries`.\n `ClearTerminalTasks` must match `taskstate.Terminal`, which\n `TestClearTerminalTasksMatchesTaskstate` enforces. The stats queries count\n outcomes by name; decide whether the new status counts.\n5. Extend the table in `taskstate_test.go`.\n\n### Adding a task field\n\nFollow [State Store](/dev/development/state-store/) for the\ncolumn and the wire. Then decide who writes it: `UpdateTask` writes a fixed\ncolumn set, so a field set at enqueue needs its own statement (as\n`StampTaskBinding` does for binding provenance and inputs).\n\n### Changing what the agent receives\n\n- The task brief is `container.TaskPayload`, written to\n `\u003cworkspace\u003e/.git/task.json` by `WriteTaskJSON`. Never write it to the\n workspace root: the commit stage stages everything there.\n- The run request is `taskrun.Request`. `Validate` rejects a request that\n cannot run; a new requirement goes there.\n- Parking always carries a class (`taskstate.ParkTransient`,\n `ParkNeedsHuman`, `ParkTerminal`) chosen by the code that parks. Pick the one\n that says what an operator must do.\n- A task with no repository (`Task.HasRepository`) runs in a scratch workspace\n with no worktree grant. Code that assumes an owner and repo must check first.\n\n## Event automation\n\nAuthority: `docs/prds/event-automation.md` (the model: source, event type,\nmapping, binding, workflow, profile) and `docs/architecture/bindings.md`\n(threat model).\n\n### Where each check lives\n\nA binding is checked twice, and a new rule usually belongs in both places:\n\n- **On save**, in `checkedBinding` (`internal/webui/api_binding.go`), so the\n operator sees the problem while editing. It calls the domain checks\n `binding.Validate`, `binding.CompileFilter` and `Binding.CheckWorkflow`.\n- **At dispatch**, in `dispatchOneBinding` and `resolveBindingTarget`\n (`internal/daemon`), because the workflow or mapping may have changed since\n the save. A refusal is recorded with `recordDispatchFailure` and starts no\n task.\n\nPut the rule itself in `internal/domain/binding` or\n`internal/domain/workflow/task` and call it from both, rather than writing it\ntwice.\n\n### Adding a binding field\n\n1. Domain type and `Validate` in `internal/domain/binding`.\n2. Column, queries, store mapping, wire field, `newColumns`\n ([State Store](/dev/development/state-store/)).\n3. The request type and `checkedBinding` in `api_binding.go`.\n4. The draft, payload and editor in `ui/src/bindings/`\n ([Frontend UI](/dev/development/frontend-ui/)).\n5. Its effect at dispatch, with a case in\n `internal/daemon/dispatch_inputs_test.go` or `dispatch_bindings_test.go`.\n\n### Rules that must hold\n\n- Signing belongs to the source. Intake verifies the HMAC against the source's\n secret before the payload is parsed.\n- An event must be identified as an event type before anything dispatches it,\n and a binding applies only to its mapping's event type. Dispatch test\n fixtures therefore create an event type before inserting captures.\n- The dispatch ledger is claimed before the task is enqueued (at most once).\n- Anything an event supplies that selects what the agent acts on, such as a\n repository, must be checked against configuration. An event never widens\n what an agent can reach.\n"
|
||||
"body": "# Daemon\n\nThe daemon claims and runs tasks, and turns captured events into tasks through\nbindings. This page covers both.\n\n## Task lifecycle\n\nAuthority: `docs/architecture/agent-system.md`. The status vocabulary lives in\n`internal/taskstate`, which imports no internal package.\n\n### Adding a status\n\n1. Add the constant to `internal/taskstate/taskstate.go` and place it in\n `Terminal`, `Actions` and `Statuses`. Its value is stored, so renaming it\n later is a migration.\n2. Alias it in `internal/domain/workflow/task/task.go` and\n `internal/domain/workflow/task_aliases.go`.\n3. Add it to the default catalogue in `ui/src/lib/task-meta.ts`. The server\n catalogue replaces the defaults when it loads, but the defaults render first.\n4. Find every hand-written status list in SQL:\n `grep -rn \"'merged'\" internal/infrastructure/postgres/queries`.\n `ClearTerminalTasks` must match `taskstate.Terminal`, which\n `TestClearTerminalTasksMatchesTaskstate` enforces. The stats queries count\n outcomes by name; decide whether the new status counts.\n5. Extend the table in `taskstate_test.go`.\n\n### Adding a task field\n\nFollow [State Store](/dev/development/state-store/) for the\ncolumn and the wire. Then decide who writes it: `UpdateTask` writes a fixed\ncolumn set, so a field set at enqueue belongs in the insert that creates the\nrow (as `InsertChatTask` does for inputs), or in its own statement when only\nsome producers set it (as `StampTaskBinding` does for binding provenance).\n\n### Changing what the agent receives\n\n- The task brief is `container.TaskPayload`, written to\n `\u003cworkspace\u003e/.git/task.json` by `WriteTaskJSON`. Never write it to the\n workspace root: the commit stage stages everything there.\n- The run request is `taskrun.Request`. `Validate` rejects a request that\n cannot run; a new requirement goes there.\n- Parking always carries a class (`taskstate.ParkTransient`,\n `ParkNeedsHuman`, `ParkTerminal`) chosen by the code that parks. Pick the one\n that says what an operator must do.\n- A task with no repository (`Task.HasRepository`) runs in a scratch workspace\n with no worktree grant. Code that assumes an owner and repo must check first.\n\n## Event automation\n\nAuthority: `docs/prds/event-automation.md` (the model: source, event type,\nmapping, binding, workflow, profile) and `docs/architecture/bindings.md`\n(threat model).\n\n### Where each check lives\n\nA binding is checked twice, and a new rule usually belongs in both places:\n\n- **On save**, in `checkedBinding` (`internal/webui/api_binding.go`), so the\n operator sees the problem while editing. It calls the domain checks\n `binding.Validate`, `binding.CompileFilter` and `Binding.CheckWorkflow`.\n- **At dispatch**, in `dispatchOneBinding` and `resolveBindingTarget`\n (`internal/daemon`), because the workflow or mapping may have changed since\n the save. A refusal is recorded with `recordDispatchFailure` and starts no\n task.\n\nPut the rule itself in `internal/domain/binding` or\n`internal/domain/workflow/task` and call it from both, rather than writing it\ntwice.\n\n### Adding a binding field\n\n1. Domain type and `Validate` in `internal/domain/binding`.\n2. Column, queries, store mapping, wire field, `newColumns`\n ([State Store](/dev/development/state-store/)).\n3. The request type and `checkedBinding` in `api_binding.go`.\n4. The draft, payload and editor in `ui/src/bindings/`\n ([Frontend UI](/dev/development/frontend-ui/)).\n5. Its effect at dispatch, with a case in\n `internal/daemon/dispatch_inputs_test.go` or `dispatch_bindings_test.go`.\n\n### Rules that must hold\n\n- Signing belongs to the source. Intake verifies the HMAC against the source's\n secret before the payload is parsed.\n- An event must be identified as an event type before anything dispatches it,\n and a binding applies only to its mapping's event type. Dispatch test\n fixtures therefore create an event type before inserting captures.\n- The dispatch ledger is claimed before the task is enqueued (at most once).\n- Anything an event supplies that selects what the agent acts on, such as a\n repository, must be checked against configuration. An event never widens\n what an agent can reach.\n"
|
||||
},
|
||||
{
|
||||
"url": "/dev/development/frontend-ui/",
|
||||
"title": "Frontend UI",
|
||||
"section": "Development",
|
||||
"body": "# Frontend UI\n\nAuthority: `.agents/skills/archie-web-ui` (stack facts, design-system rules,\ntone and accessibility). This page covers what a change must reach, not how it\nshould look.\n\n## Adding or changing a feature\n\n1. The feature lives in `ui/src/\u003cfeature\u003e/`. Move a helper to `ui/src/base/`\n only when a second feature needs it.\n2. Keep wire shapes, draft state and payload building in a plain `.ts` module\n beside the components (`ui/src/bindings/binding-draft.ts` is the pattern),\n and test it in `ui/test/*.test.ts`. Components stay thin.\n3. Every mutation goes through `api.*` in `ui/src/lib/api`, which sends the\n CSRF and Content-Type headers the server's mutation guard requires. A bare\n `fetch` is refused.\n4. A value the server also describes (task statuses, actions, workflow inputs)\n comes from the server. Keep a local default only so the first render works,\n and keep it in step (`ui/src/lib/task-meta.ts`).\n5. Run `task ui`, `task test:ui` and `cd ui \u0026\u0026 npm run typecheck`. Commit the\n regenerated `ui/dist/`; the Go binaries embed it. A fresh git worktree has\n no ignored `ui/node_modules`: run `cd ui \u0026\u0026 npm ci` before these commands.\n6. **One long-lived browser connection:** `ui/src/lib/api.ts` has the only\n `new EventSource`, owned by `stores/live-updates.ts`. Feature stores consume\n topics with `live.subscribe(topic, callback)`; do not open a page-owned SSE\n stream. Logs alone opt in while mounted, replacing that same EventSource\n with `?topics=logs\u0026since=\u003clast cursor\u003e`; a browser's `Last-Event-ID` only\n survives its own automatic reconnect, not a newly constructed EventSource.\n Task and log topics resume by cursor; control-plane, identity and apply-status\n topics replay the latest snapshot. Test a fetch and same-origin navigation\n after visiting Settings and Logs: the UI process serves HTTP/1.1 and six\n persistent streams can starve every later browser request.\n\n## Adding an API route\n\n1. The handler goes in the `internal/webui/api_\u003cconcern\u003e.go` file for its\n concern. Check the request fully on the server; the UI's checks are only a\n convenience.\n2. A mutation calls `authorizeTaskMutation` first.\n3. A route whose store is not configured answers 503, and\n `internal/app/archieui/degraded_routes_test.go` pins what each route\n returns without its contract. Add the route there.\n4. The dashboard runs in its own process (`archie-ui`) and must not link the\n daemon or the workflow engine (`cmd/archie-ui/architecture_test.go`). Reach\n stored data through `storecontract` interfaces wired in\n `internal/app/archieui/compose.go`.\n5. Settings that live in a control-plane resource need no new route: the\n Advanced settings page edits every resource from its generated schema.\n6. For a new live topic, add one process-wide producer to `internal/webui`'s\n `RunLive` and fan it through the `/api/stream` hub; `internal/app/archieui/run.go`\n starts the producers with the process context. Never create an upstream\n watch or poller in an HTTP handler. A slow client must reconnect for cursor\n and snapshot repair rather than silently lose an update. Prove the producer\n with several browser clients against the real peer, not just a scripted\n stream; `live_hub_test.go` is the example.\n"
|
||||
"body": "# Frontend UI\n\nAuthority: `.agents/skills/archie-web-ui` (stack facts, design-system rules,\ntone and accessibility). This page covers what a change must reach, not how it\nshould look.\n\n## Adding or changing a feature\n\n1. The feature lives in `ui/src/\u003cfeature\u003e/`. Move a helper to `ui/src/base/`\n only when a second feature needs it.\n2. Keep wire shapes, draft state and payload building in a plain `.ts` module\n beside the components (`ui/src/bindings/binding-draft.ts` is the pattern),\n and test it in `ui/test/*.test.ts`. Components stay thin.\n3. Every mutation goes through `api.*` in `ui/src/lib/api`, which sends the\n CSRF and Content-Type headers the server's mutation guard requires. A bare\n `fetch` is refused.\n4. A value the server also describes (task statuses, actions, workflow inputs)\n comes from the server. Keep a local default only so the first render works,\n and keep it in step (`ui/src/lib/task-meta.ts`).\n5. Run `task ui`, `task test:ui` and `cd ui \u0026\u0026 npm run typecheck`. Commit the\n regenerated `ui/dist/`; the Go binaries embed it. A fresh git worktree has\n no ignored `ui/node_modules`: run `cd ui \u0026\u0026 npm ci` before these commands.\n6. **One long-lived browser connection:** `ui/src/lib/api.ts` has the only\n `new EventSource`, owned by `stores/live-updates.ts`. Feature stores consume\n topics with `live.subscribe(topic, callback)`; do not open a page-owned SSE\n stream. Logs alone opt in while mounted, replacing that same EventSource\n with `?topics=logs\u0026since=\u003clast cursor\u003e`; a browser's `Last-Event-ID` only\n survives its own automatic reconnect, not a newly constructed EventSource.\n Task and log topics resume by cursor; control-plane, identity and apply-status\n topics replay the latest snapshot. Test a fetch and same-origin navigation\n after visiting Settings and Logs: the UI process serves HTTP/1.1 and six\n persistent streams can starve every later browser request.\n\n## Testing the dashboard\n\nAuthority: the runner itself is `ui/package.json`'s `test` script: `node --test\n--experimental-strip-types test/*.test.ts` over `ui/test/*.test.ts`. It runs\npure TypeScript modules with `node`'s type stripping — no SFC loader, no DOM,\nno second dependency beyond what the app already carries. That is the standard,\nand a decision record for when it is deliberately not enough:\n\n- **Test archie's logic in a module; leave SFC wiring alone.** Wire shapes,\n draft state, copy conditions, filters and payload building live in plain\n `.ts` files beside the components and are tested in `ui/test/`. Components\n stay thin, so there is normally nothing in an SFC that is archie logic.\n- **Installed primitives are upstream-tested, not re-tested here.**\n `reka-ui` (2.10.5 here) maintains colocated tests per component in its own\n repo (Vitest/jsdom + axe: Switch, TagsInput, NumberField, Select, the\n arrow-navigation composables). The npm package ships none of those files, so\n this coverage is inherited through the version bound, not the tarball —\n `grep -l test node_modules/reka-ui` finds nothing. Duplicating them as local\n mount tests would test a dependency.\n- **A `.vue` import cannot run under the module runner.** `node --test` fails\n such a module with `ERR_UNKNOWN_FILE_EXTENSION: .vue` and the runner has no\n built-in loader for SFCs. A file under `ui/test/` that imports a `.vue` is\n therefore a broken test, not a weak one.\n- **If a DOM mount harness is ever needed** (a page-level accessibility\n contract, cross-component interaction, focus behaviour): `happy-dom` +\n `@vue/test-utils` + `vitest` scoped to a separate DOM test glob, keeping the\n module runner for everything else. Measured on the ui tree (vitest 5.0.2,\n happy-dom 20.14.5, @vue/test-utils 2.5.1): they add 24 top-level\n `node_modules` entries and 27 MB on a 296 MB install, a working 2-test mount\n suite (role=radiogroup vs role=switch, aria-label, click activation against\n the real SFCs) runs in 1.2 s on top of the current 0.5 s module suite, and\n `vue-tsc` (7.4 s) dominates `task test:ui` either way. The single-runner\n alternative (absorbing the existing suite into vitest) was measured\n infeasible as-is: all 29 existing files import `node:test`, which vitest\n cannot collect (\"No test suite found in file\" for every one), so it would be\n a rewrite of the whole suite, and its runtime was not measured. Nothing in\n `ui/dist` or CI changes either way; happy-dom is pure JS, no browser binary.\n- **What the module standard does not verify:** whether a call site passes an\n `aria-label` or which `v-if` branch shows. Those live in SFC templates and\n are only visible with a mount. If a page's accessible-name wiring is the\n risk, say so in the page's task and reach for the harness decision above\n rather than quietly growing mount tests. Never suppress a lint rule or a\n test to keep Line truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/development/merging-work/",
|
||||
@@ -154,7 +154,7 @@
|
||||
"url": "/dev/development/workflows/",
|
||||
"title": "Workflows",
|
||||
"section": "Development",
|
||||
"body": "# Workflows\n\nAuthority: `docs/architecture/agent-system.md` for the lifecycle,\n`docs/prds/event-automation.md` for inputs, repository modes and profiles.\n\nWorkflow definitions are YAML stored as a control-plane resource. The State\nStore validates them and the agent compiles them, each against the step\nvocabulary it registers, so both must see the same step types.\n\n## Adding a step type\n\n1. Write the factory in `internal/domain/workflow` as a `StepType`. It decodes\n and validates its settings and returns an error for anything it cannot\n honour. The factory runs when a definition is saved and again when it is\n compiled, so a bad definition is refused on save.\n2. Register it through a provider in\n `internal/infrastructure/workflowsteps/workflowsteps.go`. That one list is\n what every process registers, which is how the validating and executing\n sides agree.\n3. An agent-driven step builds on `AgentStage`; do not start a second path to\n the agent runner.\n4. A step that needs no repository goes in `repoFreeStepTypes` in\n `definition.go`, or workflows declaring `repository: none` or `optional`\n cannot use it. A step that needs one may assume `tc.Dir` holds a worktree\n only when the workflow's repository is `required`.\n5. A step that ends the workflow sets `tc.Outcome`. A workflow that runs out of\n steps without an outcome is parked as a definition bug.\n6. Add a parse test (settings accepted and refused) and a run test with fake\n `Trees` and agent runner.\n\n## Changing the definition format\n\n- The fields a caller needs without the engine (inputs, repository, profile)\n live in `task.WorkflowInterface`, because the dashboard process must not\n import the workflow engine (`cmd/archie-ui/architecture_test.go`). Anything a\n binding or the dashboard checks goes there.\n- The YAML decoder rejects unknown keys. Existing stored definitions must keep\n parsing, so a new key is optional with a default that preserves today's\n behaviour.\n- Examples in `examples/workflows/` are parsed against the registered\n vocabulary by `TestExampleWorkflowsParse`. Add one for a new capability.\n"
|
||||
"body": "# Workflows\n\nAuthority: `docs/architecture/agent-system.md` for the lifecycle,\n`docs/prds/event-automation.md` for inputs, repository modes and profiles.\n\nWorkflow definitions are YAML stored as a control-plane resource. The State\nStore validates them and the agent compiles them, each against the step\nvocabulary it registers, so both must see the same step types.\n\n## Adding a step type\n\n1. Write the factory in `internal/domain/workflow` as a `StepType`. It decodes\n and validates its settings and returns an error for anything it cannot\n honour. The factory runs when a definition is saved and again when it is\n compiled, so a bad definition is refused on save.\n2. Register it through a provider in\n `internal/infrastructure/workflowsteps/workflowsteps.go`. That one list is\n what every process registers, which is how the validating and executing\n sides agree.\n3. An agent-driven step builds on `AgentStage`; do not start a second path to\n the agent runner.\n4. A step that needs no repository goes in `repoFreeStepTypes` in\n `definition.go`, or workflows declaring `repository: none` or `optional`\n cannot use it. A step that needs one may assume `tc.Dir` holds a worktree\n only when the workflow's repository is `required`.\n5. A step that ends the workflow sets `tc.Outcome`. A workflow that runs out of\n steps without an outcome is parked as a definition bug.\n6. Add a parse test (settings accepted and refused) and a run test with fake\n `Trees` and agent runner.\n\n## Changing the definition format\n\n- The fields a caller needs without the engine (inputs, repository, profile)\n live in `task.WorkflowInterface`, because the dashboard process must not\n import the workflow engine (`cmd/archie-ui/architecture_test.go`). Anything a\n binding or the dashboard checks goes there.\n- The YAML decoder rejects unknown keys. Existing stored definitions must keep\n parsing, so a new key is optional with a default that preserves today's\n behaviour.\n- Examples in `examples/workflows/` are parsed against the registered\n vocabulary by `TestExampleWorkflowsParse`. Add one for a new capability.\n\n## Enabling and disabling\n\nThe `workflow-enablement` control-plane resource lists, per org, the workflows\nthat org has disabled; anything unlisted is enabled. Its readers are the\ndaemon's binding dispatch (a disabled workflow's binding is skipped like an\nunarmed one), the dashboard's binding save (refused) and binding list\n(`workflow_disabled`), and work requests. A new reader of \"may this org run\nthis workflow\" goes through `task.WorkflowEnablement.Enabled`, never a second\nlist. The dashboard acts in the default org until access resolves a caller's\nown.\n\n## Starting a workflow from chat\n\n`task_spawn` accepts `workflow` and an `inputs` object. The gateway forwards\ninputs through the task creation contract; it does not interpret individual\nworkflows. The daemon checks inputs against the pinned `WorkflowInterface`\nbefore acquiring a container and parks invalid requests with the reason.\n"
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/01-project-management/",
|
||||
@@ -376,7 +376,7 @@
|
||||
"url": "/dev/prds/multi-action-playbooks/",
|
||||
"title": "Multi-action playbooks and typed action results",
|
||||
"section": "PRDs",
|
||||
"body": "# Multi-action playbooks and typed action results\n\n**Status:** Approved\n**Date:** 2026-09-22\n**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`\n**Beads issue:** `archie-core-nx30` (unblocks `archie-core-t2db.27` and `archie-core-t2db.31`)\n\n## Why this exists\n\n`eda-playbook-engine.md`'s hard boundary rejects any playbook that is not\nexactly one `workflow` action, so the parent document's data-flow, Module and\nChannel/Forge decisions have no loadable shape to attach to. The boundary's own\nstated condition is now met: both execution-time gaps are resolved\n(`eda-playbook-engine.md`, \"Execution-time gaps\"; the `playbook_dispatches`\nledger). This document designs the relaxation.\n\n## A playbook is one of two shapes\n\n- A **workflow playbook** is exactly one `workflow` action. Unchanged: it names\n a workflow definition and is routed by the daemon's definition pin.\n- An **action playbook** is one or more `module` actions in order. Each action\n has an optional `id`, a `kind` naming a registered Module kind, `args`, and an\n optional `when`.\n\nOne playbook does not mix the two shapes.\n\n```yaml\ntrigger: { kind: bug }\nactions:\n - id: build\n position: module\n kind: log\n args: { message: '\"build started\"' }\n - id: done\n position: module\n kind: log\n args: { message: '\"done: \" + string(actions.build.result.written)' }\n when: actions.build.result.written == true\n```\n\nThe first Module kind is the side-effect-free `log` kind\n(`module-position.md`, \"Recommended first slice\"). A Module kind with an\nexternal side effect, and the Channel and Forge positions, are out of scope.\n\n## A result type is the kind's generated Result struct\n\nEach Module kind owns a hand-written `Args` and `Result` struct\n(`internal/domain/eda/module/log` is the worked example); `ModuleRegistry.Invoke`\nreturns the result as a flat `map[string]any`. `ModuleRegistry.DecodeResult`\n(`internal/domain/eda/module`) is the single site that converts that map into\nthe kind's `Result` struct before a later expression reads it, so the value the\nchecker validates and the value the run reads have one definition.\n\n`actions.\u003cid\u003e` is typed by the kind of the action that declares `\u003cid\u003e`:\n`{ result: \u003cKindResult\u003e }`. `event` stays `dyn` (J4,\n`playbook-expression-syntax.md`).\n\n## Reject-at-load, preserved\n\nRelaxing the boundary must not make a bad reference resolvable. The load fails,\nnaming the playbook and the offending action, for:\n\n- an `id` missing where a later action references it, duplicated, or outside\n its shape's grammar: a workflow action id keeps the shared\n stable-identifier grammar (J1, already enforced), while a module action id\n must be a lowercase CEL field name writable as `actions.\u003cid\u003e` (so a CEL\n keyword such as `in`, `true`, `false`, or `null` is rejected at load);\n- an `actions.\u003cid\u003e` read of an id no earlier action declares;\n- an `actions` read that is not statically resolvable to an id (any map index,\n literal or dynamic, `in`, a comprehension): the typed `actions` root is an\n object type, so only field selection `actions.\u003cid\u003e` resolves and the\n `actions[\"id\"]` spelling is not accepted;\n- a `result` field the referenced kind's `Result` does not define;\n- a reference to an earlier action that produces no result;\n- an unknown `position`, an unknown `kind`, or a `module` action with no `kind`;\n- a field belonging to the other shape (`kind` on a `workflow` action, or\n `workflow` on a `module` action);\n- an arg KEY the kind's `Args` schema does not define;\n- an arg value whose checked CEL type cannot fill its `Args` field (`'123'`\n for a string field). A `dyn` value, such as an `event` read, passes: its\n type is known only per event, and the module decode refuses a bad one at\n run.\n\nDeclaring the kind's `Result` schema to CEL at load makes a result-field typo a\nload failure rather than a dispatch failure. Matching arg keys against the\nkind's `Args` schema makes an arg-key typo or a wrongly typed value a load\nfailure.\n\n## The environment is per playbook\n\nResult typing depends on the ids a playbook declares and the kind each id runs,\nso the CEL environment is built from one playbook's action list rather than once\nper `Store`, and `expr.NewEnv` takes that list: each declared id becomes a field\nof the `actions` object typed by its kind's `Result`.\n\n## Running an action playbook is out of scope\n\nThis document makes an action playbook load and its references type-check.\nRunning one is designed in `docs/prds/action-playbook-run.md`.\n\n## Decisions\n\n**D1 — dispatch before `t2db.31`.** Superseded by\n`docs/prds/action-playbook-run.md`. Was: an action playbook loads and\nvalidates but is not routed; the definition-pin dispatch reports no match for it,\nand the daemon logs a visible warning naming it.\n\n**D2 — mixing positions.*Line truncated
|
||||
"body": "# Multi-action playbooks and typed action results\n\n**Status:** Approved\n**Date:** 2026-09-22\n**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`\n**Beads issue:** `archie-core-nx30` (unblocks `archie-core-t2db.27` and `archie-core-t2db.31`)\n\n## Why this exists\n\n`eda-playbook-engine.md`'s hard boundary rejects any playbook that is not\nexactly one `workflow` action, so the parent document's data-flow, Module and\nChannel/Forge decisions have no loadable shape to attach to. The boundary's own\nstated condition is now met: both execution-time gaps are resolved\n(`eda-playbook-engine.md`, \"Execution-time gaps\"; the `playbook_dispatches`\nledger). This document designs the relaxation.\n\n## A playbook is one of two shapes\n\n- A **workflow playbook** is exactly one `workflow` action. Unchanged: it names\n a workflow definition and is routed by the daemon's definition pin.\n- An **action playbook** is one or more `module` actions in order. Each action\n has an optional `id`, a `kind` naming a registered Module kind, `args`, and an\n optional `when`.\n\nOne playbook does not mix the two shapes.\n\n```yaml\ntrigger: { kind: bug }\nactions:\n - id: build\n position: module\n kind: log\n args: { message: '\"build started\"' }\n - id: done\n position: module\n kind: log\n args: { message: '\"done: \" + string(actions.build.result.written)' }\n when: actions.build.result.written == true\n```\n\nThe first Module kind is the side-effect-free `log` kind\n(`module-position.md`, \"Recommended first slice\"). A Module kind with an\nexternal side effect, and the Channel and Forge positions, are out of scope.\n\n## A result type is the kind's generated Result struct\n\nEach Module kind owns a hand-written `Args` and `Result` struct\n(`internal/domain/eda/module/log` is the worked example); `ModuleRegistry.Invoke`\nreturns the result as a flat `map[string]any`. `ModuleRegistry.DecodeResult`\n(`internal/domain/eda/module`) is the single site that converts that map into\nthe kind's `Result` struct before a later expression reads it, so the value the\nchecker validates and the value the run reads have one definition.\n\n`actions.\u003cid\u003e` is typed by the kind of the action that declares `\u003cid\u003e`:\n`{ result: \u003cKindResult\u003e }`. `event` stays `dyn` (J4,\n`playbook-expression-syntax.md`).\n\n## Reject-at-load, preserved\n\nRelaxing the boundary must not make a bad reference resolvable. The load fails,\nnaming the playbook and the offending action, for:\n\n- an `id` missing where a later action references it, duplicated, or outside\n its shape's grammar: a workflow action id keeps the shared\n stable-identifier grammar (J1, already enforced), while a module action id\n must be a lowercase CEL field name writable as `actions.\u003cid\u003e` (so a CEL\n keyword such as `in`, `true`, `false`, or `null` is rejected at load);\n- an `actions.\u003cid\u003e` read of an id no earlier action declares;\n- an `actions` read that is not statically resolvable to an id (any map index,\n literal or dynamic, `in`, a comprehension): the typed `actions` root is an\n object type, so only field selection `actions.\u003cid\u003e` resolves and the\n `actions[\"id\"]` spelling is not accepted;\n- a `result` field the referenced kind's `Result` does not define;\n- a reference to an earlier action that produces no result;\n- an unknown `position`, an unknown `kind`, or a `module` action with no `kind`;\n- a field belonging to the other shape (`kind` on a `workflow` action, or\n `workflow` on a `module` action);\n- an arg KEY the kind's `Args` schema does not define;\n- an arg value whose checked CEL type cannot fill its `Args` field (`'123'`\n for a string field). A `dyn` value, such as an `event` read, passes: its\n type is known only per event, and the module decode refuses a bad one at\n run.\n\nDeclaring the kind's `Result` schema to CEL at load makes a result-field typo a\nload failure rather than a dispatch failure. Matching arg keys against the\nkind's `Args` schema makes an arg-key typo or a wrongly typed value a load\nfailure.\n\n## The environment is per playbook\n\nResult typing depends on the ids a playbook declares and the kind each id runs,\nso the CEL environment is built from one playbook's action list rather than once\nper `Store`, and `expr.NewEnv` takes that list: each declared id becomes a field\nof the `actions` object typed by its kind's `Result`.\n\n## Running an action playbook is out of scope\n\nThis document makes an action playbook load and its references type-check.\nRunning one is designed in `docs/prds/action-playbook-run.md`.\n\n## Decisions\n\n**D1 — dispatch before `t2db.31`.** Superseded by\n`docs/prds/action-playbook-run.md`. Was: an action playbook loads and\nvalidates but is not routed; the definition-pin dispatch reports no match for it,\nand the daemon logs a visible warning naming it.\n\n**D2 — mixing positions.*Line truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/news-and-releases/",
|
||||
@@ -406,13 +406,25 @@
|
||||
"url": "/dev/prds/playbook-expression-syntax/",
|
||||
"title": "Playbook data-flow and condition syntax",
|
||||
"section": "PRDs",
|
||||
"body": "# Playbook data-flow and condition syntax\n\n**Status:** Approved\n**Date:** 2026-09-03\n**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`\n**Beads issue:** `archie-core-t2db.14` (expression environment).\nUnbuilt decisions: `archie-core-t2db.25` (J1 action ids),\n`archie-core-t2db.26` (J2 args as CEL),\n`archie-core-t2db.27` (Result schemas declared to CEL).\n\n**Decision:** CEL via `cel.dev/cel-go` (v0.32.0), pinned. One expression\nmechanism covers both an action's `when` condition and its `args` values.\n\n## The requirement, stated directly\n\nA playbook action is gated and parametrised by runtime data: (a) a condition\ndeciding whether the action runs; (b) a later action's `args` values referencing\nan earlier action's `Result` and the triggering event's fields. Both are **CEL\nexpressions**, evaluated against one evaluation context. There is no separate\ninterpolation syntax: CEL reads nested maps and fields natively, so `args`\nvalues that need data are written as CEL, and only plain literal args remain\nplain YAML scalars.\n\nBoth halves are read-only: expressions may read context values and compute a\nresult from them, never mutate, never call host functions, never perform I/O.\nCEL enforces this structurally (no side effects, linear evaluation when macros\nare bounded, cost-limited).\n\n```yaml\nactions:\n - id: build\n position: module\n kind: log\n args:\n message: '\"build finished\"' # literal\n when: 'event.label == \"bugfix\"' # gate on event field\n - position: module\n kind: log\n args:\n message: '\"done: \" + string(actions.build.result.written)'\n when: \"actions.build.result.written == true\"\n```\n\n## Trust boundary of the expression\n\nA playbook YAML is **operator-installed, in-process, daemon-privileged** -- the\nsame tier as `ModuleDir`/`PluginDir`/`SecretEngineDir` (module-position.md's\ntrust-boundary section): loaded from a configured directory at startup, never\nfrom a webhook body or task worktree. The schema-by-example flow uses live\nevents to _design against_; the saved playbook is operator-authored file content\nin an operator-configured location.\n\nTwo consequences:\n\n1. The expression string is **trusted**. Operator-authored config, not attacker\n input; no sandboxing against a hostile expression string is required. If a\n future playbook source is less trusted (auto-generated bindings from\n unauthenticated captures), that is the playbook-file trust tier moving -- the\n loader's acceptance check is the right place, not the evaluator.\n2. The **data the expression reads is NOT trusted** (decoded webhook body, prior\n results through the same pipeline). Robustness against hostile data is\n required: no panic on wrong-typed/missing fields, no unbounded cost on\n deep/cyclic maps, bounded evaluation time. CEL provides this structurally\n (cost limits, linear non-Turing-complete evaluation, error values instead of\n panics -- verified in the vetting record below).\n\n## The gate precedent is deliberately NOT copied\n\n`internal/gate/gateeval` evaluates arbitrary interpreted Go (`.archie/gate.go`)\nas the repo's conditional-logic precedent. That is the wrong precedent for\nplaybook conditions because this document's premise is: **YAML is pure\norchestration data; Yaegi is where imperative logic lives** (Problem section;\nmodule-position.md's \"no generic hook\" section). Yaegi snippets in YAML would\nmove imperative logic into the data layer -- the inversion this design exists to\nprevent -- and make playbooks un-lintable.\n\nThe line: conditions are **declarative predicates over runtime data, not\nprograms**. CEL is non-Turing-complete and side-effect-free, so it cannot become\na program; a condition that needs real logic gets a Module kind (Yaegi),\nreferenced by the action, not a stronger expression body.\n\n## Plugin-engine-rule interaction\n\nThe plugin engine rule forbids a generic `Module` interface with an `any`\npayload; it exists to keep static implementation contracts typed. Evaluating CEL\nagainst runtime `map[string]any` is **not the same problem**: the rule concerns\n_implementation contracts_ (static operations a capability family exposes), not\n_runtime data values_ (legitimately dynamic -- an event payload's shape is\nunknown until it arrives). The Module contract stays fully typed (generated\n`Args`/`Result` schemas); CEL is a read-only data reader under the playbook\nengine family, not a new capability contract. Stated once.\n\n## Minimum viable evaluation context (what expressions see)\n\nOne flat context, namespaced from the playbook run, built at dispatch time:\n\n| Name | Type | Source Line truncated
|
||||
"body": "# Playbook data-flow and condition syntax\n\n**Status:** Approved\n**Date:** 2026-09-03\n**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`\n**Beads issue:** `archie-core-t2db.14` (expression environment).\n\n**Decision:** CEL via `cel.dev/cel-go` (v0.32.0), pinned. One expression\nmechanism covers both an action's `when` condition and its `args` values.\n\n## The requirement, stated directly\n\nA playbook action is gated and parametrised by runtime data: (a) a condition\ndeciding whether the action runs; (b) a later action's `args` values referencing\nan earlier action's `Result` and the triggering event's fields. Both are **CEL\nexpressions**, evaluated against one evaluation context. There is no separate\ninterpolation syntax: CEL reads nested maps and fields natively, so `args`\nvalues that need data are written as CEL, and only plain literal args remain\nplain YAML scalars.\n\nBoth halves are read-only: expressions may read context values and compute a\nresult from them, never mutate, never call host functions, never perform I/O.\nCEL enforces this structurally (no side effects, linear evaluation when macros\nare bounded, cost-limited).\n\n```yaml\nactions:\n - id: build\n position: module\n kind: log\n args:\n message: '\"build finished\"' # literal\n when: 'event.label == \"bugfix\"' # gate on event field\n - position: module\n kind: log\n args:\n message: '\"done: \" + string(actions.build.result.written)'\n when: \"actions.build.result.written == true\"\n```\n\n## Trust boundary of the expression\n\nA playbook YAML is **operator-installed, in-process, daemon-privileged** -- the\nsame tier as `ModuleDir`/`PluginDir`/`SecretEngineDir` (module-position.md's\ntrust-boundary section): loaded from a configured directory at startup, never\nfrom a webhook body or task worktree. The schema-by-example flow uses live\nevents to _design against_; the saved playbook is operator-authored file content\nin an operator-configured location.\n\nTwo consequences:\n\n1. The expression string is **trusted**. Operator-authored config, not attacker\n input; no sandboxing against a hostile expression string is required. If a\n future playbook source is less trusted (auto-generated bindings from\n unauthenticated captures), that is the playbook-file trust tier moving -- the\n loader's acceptance check is the right place, not the evaluator.\n2. The **data the expression reads is NOT trusted** (decoded webhook body, prior\n results through the same pipeline). Robustness against hostile data is\n required: no panic on wrong-typed/missing fields, no unbounded cost on\n deep/cyclic maps, bounded evaluation time. CEL provides this structurally\n (cost limits, linear non-Turing-complete evaluation, error values instead of\n panics -- verified in the vetting record below).\n\n## The gate precedent is deliberately NOT copied\n\n`internal/gate/gateeval` evaluates arbitrary interpreted Go (`.archie/gate.go`)\nas the repo's conditional-logic precedent. That is the wrong precedent for\nplaybook conditions because this document's premise is: **YAML is pure\norchestration data; Yaegi is where imperative logic lives** (Problem section;\nmodule-position.md's \"no generic hook\" section). Yaegi snippets in YAML would\nmove imperative logic into the data layer -- the inversion this design exists to\nprevent -- and make playbooks un-lintable.\n\nThe line: conditions are **declarative predicates over runtime data, not\nprograms**. CEL is non-Turing-complete and side-effect-free, so it cannot become\na program; a condition that needs real logic gets a Module kind (Yaegi),\nreferenced by the action, not a stronger expression body.\n\n## Plugin-engine-rule interaction\n\nThe plugin engine rule forbids a generic `Module` interface with an `any`\npayload; it exists to keep static implementation contracts typed. Evaluating CEL\nagainst runtime `map[string]any` is **not the same problem**: the rule concerns\n_implementation contracts_ (static operations a capability family exposes), not\n_runtime data values_ (legitimately dynamic -- an event payload's shape is\nunknown until it arrives). The Module contract stays fully typed (generated\n`Args`/`Result` schemas); CEL is a read-only data reader under the playbook\nengine family, not a new capability contract. Stated once.\n\n## Minimum viable evaluation context (what expressions see)\n\nOne flat context, namespaced from the playbook run, built at dispatch time:\n\n| Name | Type | Source |\n| --------- | ------------------------ | ---------------------------------------------------------------------------------Line truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/plugin-settings-live/",
|
||||
"title": "Plugin settings reconcile live",
|
||||
"section": "PRDs",
|
||||
"body": "# Plugin settings reconcile live\n\n**Status:** Draft\n**Tracking:** GitHub [#1154](https://github.com/samcharles93/archie-core/issues/1154), epic [#998](https://github.com/samcharles93/archie-core/issues/998)\n**Authority:** `docs/prds/runtime-control-plane.md` decides each feature owns how\nits changes take effect; `docs/architecture/plugins-and-extensions.md` owns the\nplugin engine rule; `docs/prds/control-plane-apply-status.md` owns where apply\nreports go.\n\n## Outcome\n\nAn operator drops a plugin, module or secret-engine file into the configured\ndirectory while archied runs, and the daemon loads it without a restart. An\nedit to an installed file replaces what is running. Deleting an installed file\nnever stops running code; apply status says so. A stored change to\n`plugin-settings` applies live for additions instead of requiring a restart.\n\n## Triggers\n\n`plugin-settings` joins the kinds archied watches (`PluginSettingsKind` moves\nto the live list in `internal/app/archied/control_plane.go`). After the daemon\nlayers a new version it reconciles the three directories the document names.\nA second trigger needs no document change: a poller reconciles on an interval,\nso a file dropped into a directory loads on its own. The poll interval is the\napply-status restamp constant; no filesystem-watch dependency is added. The\npoller reads the current document's directories from the running config each\ntick, so a changed `plugin_dir`, `module_dir` or `secret_engine_dir` retargets\nreconciliation without a restart.\n\n## Rules\n\n- Adding and changing load; removing never unloads. Yaegi interpreters are not\n reclaimed while a caller still exists and there is no unload path; the\n running set can only grow.\n- Each file is loaded through a fresh interpreter (the boot pattern). A changed\n file therefore loads cleanly, and replacement switches consumers to the new\n interpretation; files are content-hashed so only new and changed files load.\n- A file that fails to load is skipped and reported; already-running code keeps\n running. This is the degrade-and-skip convention `plugin.LoadDir` and\n `Registry.LoadDir` already apply at boot. Boot keeps its reject-at-load rule\n for the module directory; a broken file at runtime skips without aborting.\n- A directory that does not exist reconciles to an empty set.\n\n## The three registries\n\n- **Secret engines** (`internal/secret`). Reconciliation re-runs\n `Registry.LoadDir` against the live directory. `Register` replaces by name,\n so an edited engine takes effect for the next resolution. A deleted engine\n stays registered: existing references keep resolving through it until\n restart, and the record says so. Engines are stateless resolvers, so a swap\n needs no lifecycle step.\n- **Modules** (`internal/domain/eda/module`): reconciliation re-runs\n `ModuleRegistry.Register` for the kind's file. The invoker maps\n last-write-wins, and playbook dispatch resolves through the registry at\n invoke time, so the swap reaches a running playbook store unchanged. A file\n deleted for a kind leaves the old invoker in place, running; reported.\n- **Plugins** (`internal/plugin`): `Host` grows running-state operations beside\n `Register`, `Start` and `Stop`. One adds a single module while the host is\n running: it is inserted in dependency order, started alone, and on failure\n rolled back alone, leaving every previously started module running. The\n other replaces a module whose manifest id matches: stop it, start the new\n one, and restart the old one when the new start fails. Replacing a module\n that another depends on is refused, not swapped. These operations obey the\n plugin engine rule: the host still invokes start and stop itself, isolates\n the failure to the one module, and keeps a rollback. A deleted file makes no\n host call: the module runs on and is reported.\n\n## `skills_dir`\n\n`skills_dir` is not part of this change. The daemon refuses a candidate\n`plugin-settings` document whose `skills_dir` differs from the value it is\nrunning, reporting that the field applies on restart, until a skill\nreconciliation exists to carry it. The refusal is the existing rejected-edit\napply-status shape: the store keeps the version, the document is not applied,\nlast-known-good keeps running.\n\n## Apply status\n\nOne record: `archied` on `plugin-settings`. The reconciliation outcome is\nreported against the version the process is running. The record's error field\ncarries the outstanding reconciliation problem: a deleted file still running, a\nfile that failed to load, or the directory failing to read. A reconciliation\nwith nothing outstanding clears the error. The version stays the version the\nprocess is running; an add that succeeded is live even while a removal is\noutstanding, and the error says so rather than showing the kind as\nrestart-required. archie-gateway keeps boot-time loading; its record simply\nstays on the vLine truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/pr-review-agent/",
|
||||
"title": "PR review agent",
|
||||
"section": "PRDs",
|
||||
"body": "# PR review agent\n\n**Status:** Approved\n**Authority:** `docs/architecture/agent-system.md`; supersedes the reviewer\nexecutor and blocking rule in `docs/architecture/adversarial-review.md`, and\nthe designs in `docs/prds/operator-pr-review.md` and\n`docs/prds/review-calibration.md`.\n**Compounds with:** `docs/prds/execution-tree-state-machine.md` (every agent\ncall is a StepExecution), `docs/prds/external-agent-harness.md` (any agent\nstep may run on a harness), `docs/prds/inline-review.md` (posting),\n`docs/prds/pr-review-remediation.md` (consumes the findings).\n\n## Decision\n\nArchie ships a pull request reviewer as its first end-to-end product. It\nreviews any pull request on a watched repository, a PR an operator names, and\narchie's own PRs before they open.\n\nThe reviewer is a fixed pipeline, not a single agent. The review strategy is\ngenerated per PR: three lens agents propose review dimensions from the PR's\ncontent, one reviewer definition runs once per dimension, and later agents\nverify, challenge and combine the findings. Everything that can be computed\nis code: diff parsing, clustering, blast radius, evidence extraction,\nscoring, deduplication, line mapping and the review event.\n\nThe pipeline is **recall-first**. It posts every evidenced finding above the\nconfidence threshold, up to the comment cap. A precision gate exists as an\noperator dial and is off by default.\n\nAcceptance is measured, not asserted: see Verification.\n\n## Pipeline\n\nEach numbered phase is a stage of the `pr-review` workflow. Each agent call is\nan `agent` StepExecution; fan-out phases record one child per call.\n\n1. **Intake.** Code reads the PR metadata and diff statistics: type,\n complexity, languages, areas touched, risk signals. Depth comes from lines\n changed: under 100 is `quick` (at most 3 dimensions), under 500 is\n `standard` (6), otherwise `deep` (12). An operator may set depth\n explicitly.\n2. **Anatomy.** Code parses the diff into files and hunks, clusters related\n files, and computes the blast radius: unchanged files that import or are\n imported by changed files. One agent writes the PR narrative, risk\n surfaces, changes that do not fit the narrative, and gaps between the\n description and the diff.\n3. **Dimension selection.** Three lens agents run in parallel over the intake,\n anatomy and diff, each able to read the repository:\n - **behaviour:** where the old and new code diverge for any input; API\n contracts, concurrency and state, security, error handling, data flow;\n - **mechanics:** whether the code runs at the language and framework\n level; types, signatures and every caller, decorators and middleware,\n framework contracts, imports;\n - **fit:** patterns, complexity, abstraction, test adequacy, documentation\n that no longer matches, dependencies, migration completeness.\n\n Each lens returns review dimensions: a name, a reviewer prompt written for\n this PR, target files, context files and a priority. Code merges them,\n drops duplicates and keeps the highest-priority dimensions up to the\n depth's cap.\n4. **Review.** One reviewer definition runs once per dimension, in parallel,\n at most 8 at a time. Each reads its target and context files and may\n follow references. Each finding carries file, line range, severity\n (`critical`, `important`, `suggestion`, `nitpick`), title, body, an\n optional suggested fix, quoted evidence, confidence and tags.\n5. **Verification layer**, over the review findings:\n - code extracts an evidence package per finding: the code at the cited\n lines and snippets from its callers;\n - an evidence verifier checks high-priority findings against their\n packages;\n - an adversary confirms or challenges each finding, looks for issues every\n reviewer missed, and is more sceptical when intake scores the PR as\n likely machine-written;\n - a compound agent looks, within each cluster of confirmed findings, for\n defects that only exist in combination.\n6. **Coverage and consistency**, in parallel:\n - a coverage gate checks every cluster and high-exposure blast-radius file\n was reviewed, and runs gap reviewers for what was not, at most 2 rounds;\n - consistency verification lists every cross-location obligation the\n changed code creates (what must be true elsewhere for this line to be\n correct), then verifies each by reading both ends. A broken obligation\n becomes a finding.\n7. **Synthesis**, code only:\n - score = severity weight (1.0, 0.7, 0.3, 0.1) × confidence × multipliers:\n compound 1.5, adversary-confirmed 1.3, adversary-challenged 0.5, likely\n machine-written PR 1.2, blast radius over 10 files 1.2;\n - drop findings under the severity's confidence floor: critical 0.2,\n important 0.3, suggestion 0.4, nitpick 0.4;\n - merge exact duplicates (file, overlapping lines, category) in code, and\n nearLine truncated
|
||||
"body": "# PR review agent\n\n**Status:** Approved\n**Authority:** `docs/architecture/agent-system.md`; supersedes the reviewer\nexecutor and blocking rule in `docs/architecture/adversarial-review.md`, and\nthe designs in `docs/prds/operator-pr-review.md` and\n`docs/prds/review-calibration.md`.\n**Compounds with:** `docs/prds/execution-tree-state-machine.md` (every agent\ncall is a StepExecution), `docs/prds/external-agent-harness.md` (any agent\nstep may run on a harness), `docs/prds/inline-review.md` (posting),\n`docs/prds/pr-review-remediation.md` (consumes the findings).\n\n## Decision\n\nArchie ships a pull request reviewer as its first end-to-end product. It\nreviews any pull request on a watched repository, a PR an operator names, and\narchie's own PRs before they open.\n\nThe reviewer is a fixed pipeline, not a single agent. The review strategy is\ngenerated per PR: three lens agents propose review dimensions from the PR's\ncontent, one reviewer definition runs once per dimension, and later agents\nverify, challenge and combine the findings. Everything that can be computed\nis code: diff parsing, clustering, blast radius, evidence extraction,\nscoring, deduplication, line mapping and the review event.\n\nThe pipeline is **recall-first**. It posts every evidenced finding above the\nconfidence threshold, up to the comment cap. A precision gate exists as an\noperator dial and is off by default.\n\nAcceptance is measured, not asserted: see Verification.\n\n## Pipeline\n\nEach numbered phase is a stage of the `pr-review` workflow. Each agent call is\nan `agent` StepExecution; fan-out phases record one child per call.\n\n1. **Intake.** Code reads the PR metadata and diff statistics: type,\n complexity, languages, areas touched, risk signals. Depth comes from lines\n changed: under 100 is `quick` (at most 3 dimensions), under 500 is\n `standard` (6), otherwise `deep` (12). An operator may set depth\n explicitly.\n2. **Anatomy.** Code parses the diff into files and hunks, clusters related\n files, and computes the blast radius: unchanged files that import or are\n imported by changed files. One agent writes the PR narrative, risk\n surfaces, changes that do not fit the narrative, and gaps between the\n description and the diff.\n3. **Dimension selection.** Three lens agents run in parallel over the intake\n (including its machine-written score), anatomy and diff, each able to read\n the repository. A PR that intake scores as likely machine-written adds a\n hallucination-check dimension: claims, citations and behaviour the diff\n does not actually implement.\n - **behaviour:** where the old and new code diverge for any input; API\n contracts, concurrency and state, security, error handling, data flow;\n - **mechanics:** whether the code runs at the language and framework\n level; types, signatures and every caller, decorators and middleware,\n framework contracts, imports;\n - **fit:** patterns, complexity, abstraction, test adequacy, documentation\n that no longer matches, dependencies, migration completeness.\n\n Each lens returns review dimensions: a name, a reviewer prompt written for\n this PR, target files, context files and a priority. Code merges them,\n drops duplicates and keeps the highest-priority dimensions up to the\n depth's cap.\n4. **Review.** One reviewer definition runs once per dimension, in parallel,\n at most 8 at a time. Each reads its target and context files and may\n follow references. Each finding carries file, line range, severity\n (`critical`, `important`, `suggestion`, `nitpick`), title, body, an\n optional suggested fix, quoted evidence, confidence and tags. A reviewer\n that exhausts its turn cap or deadline before its terminal tool call\n records a distinct StepExecution status from a reviewer that completed\n and found nothing; synthesis and the posted review treat the two\n differently (the former is unreviewed, the latter is reviewed-clean).\n5. **Verification layer**, over the review findings:\n - code extracts an evidence package per finding: the code at the cited\n lines and snippets from its callers;\n - an evidence verifier checks high-priority findings against their\n packages;\n - an adversary confirms or challenges each finding, looks for issues every\n reviewer missed, and is more sceptical when intake scores the PR as\n likely machine-written;\n - a compound agent looks, within each cluster of confirmed findings, for\n defects that only exist in combination.\n6. **Coverage and consistency**, in parallel:\n - a coverage gate checks every cluster and high-exposure blast-radius file\n was reviewed, and runs gap reviewers for what was not, at most 2 rounds;\n - consistency verification lists every cross-location obligation the\n changed code creates (what must be true elsewhere for this line to be\n correct), then verifies each by reading both endLine truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/pr-review-operator-response/",
|
||||
"title": "PR review: the operator's answer to the approval gate",
|
||||
"section": "PRDs",
|
||||
"body": "# PR review: the operator's answer to the approval gate\n\n**Status:** Draft\n**Authority:** `docs/prds/pr-review-agent.md` (\"Operator approval\") for the gate, and `docs/prds/state-store-contract.md` (rev. 2e) for every task field that crosses the State Store.\n**Compounds with:** `docs/prds/execution-tree-state-machine.md` (a run cannot resume partway through its stage list).\n\n## Decision 1 — where the operator answers\n\nThe dashboard's `POST /api/tasks/{id}/action` (`internal/webui/api_tasks.go`, `handleTaskAction`) is the authoritative surface: the only one that resolves the actor from a credential and can carry a payload. Chat is a shortcut, not a second authority — `/approve` (`internal/gateway/gateway.go`, `Router.handleApprove`) answers the post decision with every offered finding selected, and gains no instruction or selection syntax.\n\n`taskstate.Action` gains `rereview`, and `taskstate.Actions` returns `approve`, `reject` and `rereview` for `WaitingHuman`. `approve` posts the review, `reject` discards it through the existing terminal decline, `rereview` reruns the review phases with instructions. The action body carries `instructions`, required by `rereview`, and `findings`, the finding keys `approve` posts; an absent selection means all of them.\n\nThe path is `handleTaskAction` → `applyOperatorTaskAction` → `Chat.Contract.ApplyOperatorTaskAction` → the daemon's `LocalChatAdapter` → `taskactions.Client` (NATS `archie.gateway.task-action`) → `taskactions.Service.Apply` → one guarded store write that records the decision and requeues. Chat's `/approve` path (`StoreTaskController.Approve` → `chatTaskControllerAdapter.ApproveChatTask`) must reach that same write through the same function, so the two surfaces cannot record different decisions for one operator intent.\n\nA requeue resumes the workflow the waiting state names, never a name the handler hardcodes. `taskactions.Service.apply` and `chatTaskControllerAdapter.ApproveChatTask` requeue every approval under `implement`, which is the feasibility handoff: an approval whose wait recorded `pr-review` would run the implement workflow. Feasibility must keep that handoff by naming `implement` on the task before it enters the wait, which is the invariant the handler needs — the workflow a task carries is the workflow it runs next. `Requeue` treats an empty workflow as \"keep the task's\".\n\n### The review the operator answers\n\nThe gate writes the review it is holding onto the task before it ends the run: one JSON column, `review_gate`, a sibling of `review_payload`, holding the scored findings, the head SHA, the pull request's identity and the workflow the wait resumes. The run's existing `Store.Update` persists it. The same column carries the answer back: the response path's guarded write fills in the outcome, the selection and the instructions, and clears the offer for a re-review.\n\nThe operator reads the offer through the existing task read — `taskView.Task` on `GET /api/tasks` and `GET /api/tasks/{id}/debug` — so no new read endpoint is needed.\n\nThis record is load-bearing because the run that computed the findings ends at the gate and the engine cannot resume it partway. Without it, \"post the selected findings\" cannot mean the findings the operator saw: the resumed run recomputes them with agent calls. An `approve` resume therefore posts the recorded review filtered by the selection, and the review the resumed phases recompute never reaches the output.\n\n## Decision 2 — the cap\n\nThe cap is a column: `rereview_rounds` on `tasks`, `bigint NOT NULL DEFAULT 0`, read by the response path and incremented in the same guarded write that requeues a re-review. A re-review at the cap is refused with the conflict sentinel the dashboard answers 409 with, and nothing is requeued. Two is a constant in the domain, not a config knob: the PRD fixes it.\n\n`Task.Attempt` cannot carry the count, because it counts every requeue. The two alternatives are worse.\n\n- The execution tree measures passes through the gate, not operator requests. A crash recovery (`RecoverStale`) or an operator retry re-runs the pipeline to the gate and would consume the cap; and a stage has no step read (`task.Store` carries none), so this route needs a new interface method anyway.\n- `Task.Notes` is the agent memory ledger, not scratch. `AgentStage.buildRequest` passes it into every generic agent request, `agentexec` renders it as a prompt section, and `persistAppendedNotes` appends to it. A counter parsed out of a field agents write to is the encoded-state defect this repository rejects, and instructions parked there would reach every unrelated workflow's agents.\n\n`RemediationRounds` is the precedent: one writer, one reader, one meaning, kept separate from `RetryCount` so unrelated retries cannot draw a budget down.\n\nThe write crosses the State Store. A goose migration adds the column; `internal/infrastructure/postgres/queriesLine truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/pr-review-remediation/",
|
||||
@@ -444,11 +456,17 @@
|
||||
"section": "PRDs",
|
||||
"body": "# Review calibration -- decision\n\n**Status:** Draft\n**Beads issue:** `archie-core-h019.5` (parent `archie-core-h019`)\n\n\u003e Superseded by `docs/prds/pr-review-agent.md`.\n\nDecides the half of calibration `docs/prds/adversarial-self-review.md` left\nopen: \"the adversarial-confirmation mechanism that keeps a finding from\nsurfacing on a single reviewer's say-so.\"\n\n## The problem, precisely\n\nThe shipped contract (`internal/domain/workflow/review_findings.go`, h019.2)\nalready makes only a **confirmed** error-level finding block\n(`Blocking() == Verdict == confirmed \u0026\u0026 Level == error`), and a zero-finding\nreview is already distinguishable from one that never ran (`ReviewStatus`).\nWhat is missing is the other half: a reviewer can report _nothing_\nand say only \"I found nothing\" in free text. The operator cannot tell \"I\nchecked the five things that matter and they are clean\" from \"I did not look.\"\nThat is the failure the epic names -- a findings surface that consumes attention\nwithout earning trust.\n\n## Decisions\n\n### 1. \"Checked and cleared\" becomes structured, not prose\n\n`ReviewReport` gains `Checked []ReviewCheck`:\n\n```go\ntype ReviewCheck struct {\n Property string // what was verified clean, e.g. \"nil-safety of Foo callers\"\n Evidence string // how it was verified, e.g. \"read all 4 callers; each nil-checks\"\n}\n```\n\n`Evidence` is required, for the same reason `ReviewFinding.FailureScenario` is:\na check without evidence is an assertion, and the whole point is to separate a\nverified property from an unexamined one. A zero-finding review is credible\nonly when it lists what it checked.\n\n### 2. Report checks through a typed tool, like findings\n\nThe reviewer calls a new capture tool `record_checked` (mirroring\n`record_finding`) once per property it verified clean. The same environmental\nargument as findings applies: the reviewer cannot end its turn having silently\nskipped the checklist. `ReviewReport.Summary` stays as the human overview.\n\n### 3. Style nits are out of contract\n\nA finding must describe wrong behaviour or a crash. Style, formatting, naming,\nand preference nits are explicitly out of contract -- they are the padding that\ntrains the operator to skim. Stated in the reviewer prompt and in the\n`ReviewFinding` type's own documentation. Not machine-enforced: deciding \"is\nthis a style nit\" from free text is unreliable, and a wrong rejection is worse\nthan a tolerated one. The category enum already has no style bucket; the rule\ncloses the gap that would otherwise let one hide under `other`.\n\n### 4. Surfacing\n\nThe PR-body findings section lists the cleared properties alongside findings,\nso \"ran and found nothing\" arrives with its evidence. (Park reasons keep\nrendering only blocking findings -- what a human needs to act on, not the full\nchecklist.)\n\n## What this does not decide\n\n- Adding a second, independent reviewer pass. The verdict distinction plus the\n recorded checks is the confirmation mechanism; a second model pass is a\n separate, heavier decision and nothing in `h019.5` requires it.\n- How many findings can survive before `MaxSteps` is exhausted (a budget\n question, already satisfied by the per-stage budget).\n\n## Packages this touches\n\n- `internal/domain/workflow` -- `ReviewCheck`, `ReviewReport.Checked`, validation.\n- `internal/app/agentworker` -- `record_checked` tool, prompt rules.\n- `internal/domain/workflow/review.go` -- render cleared properties on the PR body.\n"
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/review-settings-resource/",
|
||||
"title": "Review settings resource",
|
||||
"section": "PRDs",
|
||||
"body": "# Review settings resource\n\n**Status:** Draft\n**Beads issue:** `archie-core-0ry6`\n**Authority:** `docs/prds/runtime-control-plane.md` for the resource model,\n`docs/architecture/configuration.md` for ownership, and\n`docs/prds/pr-review-agent.md` for what the two dials do.\n\n## Decision\n\n`review.precision_gate` and `review.approve_before_post` are one control-plane\nresource, `review-settings`. The file's `[review]` section seeds it, the stored\ndocument outranks the file from then on, and the dashboard writes it through the\nsame settings machinery as every other resource.\n\nThe resource is deployment-wide, like every definition the State Store seeds\n(`storecontract.DefaultOrgID`): not per-repository, per-identity, or per-run.\n\n## Why its own kind\n\nThe two dials are pr-review policy — what a review may post, and whether a human\ndecides — not a limit on a task run. The document that carries task limits\nbelongs to that feature. `runtime-control-plane.md` splits settings by feature\nand refuses documents unrelated features share; `configuration.md` puts a typed\nruntime setting with the domain whose behaviour it describes. One document per\nfeature is the rule, not one document per settings page.\n\nA new kind also has no legacy documents. Its first value is the seed derived\nfrom the file, so \"the store outranks the file\" begins from an explicit copy of\nboth fields rather than from a document that predates them.\n\n## Document\n\nNew file `internal/app/controlplane/review_settings.go`:\n\n```go\nconst ReviewSettingsKind = \"review-settings\"\n\ntype reviewSettings struct {\n PrecisionGate bool `json:\"precision_gate\"`\n ApproveBeforePost bool `json:\"approve_before_post\"`\n}\n```\n\nIts `Definition` sets `ApplyMode: \"live\"`, `Document: reviewSettings{}`, and a\n`Seed` returning `reviewSettings{cfg.Review.PrecisionGate, cfg.Review.ApproveBeforePost}`,\nand a `Validate` wrapping `validateAs`: both fields are free booleans with no cross-field\nrule, so the validator is a named place to put one rather than an inline no-op\n(`validatePluginSettings` is the precedent). No `Normalize`, because the kind\nhas no second wire shape to converge.\n\n## Seeding\n\n`ImportConfig`/`seededValues` write the seed for a kind the store does not hold,\nso a deployment that never edited the dials runs the values in `[review]`. Once\na document is stored, the file key stops mattering, which is the rule for every\ndatabase-owned setting.\n\n## Apply\n\n`runtimeConfigFrom` in `internal/app/controlplane/runtime_config.go` layers the\nstored document over the file's `Review`, assigning `out.Review.PrecisionGate`\nand `out.Review.ApproveBeforePost` field by field. Field-by-field, not\n`out.Review = ...`: a field added to `config.Review` later keeps the file's value\nuntil the document carries it.\n\n`ReviewSettingsKind` joins `runtimeResourceKinds` in\n`internal/app/archied/control_plane.go`, so a new stored version re-runs the\nlayering and republishes through `config.Holder`. Live rather than\nrestart-required, because every consumer re-reads it: `Review` is on\n`reloadableFields` in `internal/app/archied/reload.go`, and the value reaches a\nrun through `Daemon.configFor` → `Config.ForTask` → `TaskConfig.ToConfig` →\n`TaskContext.Cfg`, which `stagePRPrecisionGate` and `stagePROperatorApproval`\nread. The next task run uses the new value; a run in flight keeps the value it\nstarted with.\n\n## Projection and page\n\n`BuildConfigView` gains a plain `Review` field carrying both values out of\n`cfg.Review`, the way `BudgetsView` carries the layered budgets, so the published\nconfig snapshot tells any reader what is in force. The Review page renders the\ntwo toggles from the control-plane store's draft for `review-settings` — the\nshape `SystemTasksPage.vue` uses for `workflow-execution-settings` — and shows\nthe projected value beside them; a Settings route plus a `PAGE_RESOURCES` entry\n(`ui/src/stores/control-plane.ts`) bind the page to the kind.\n\nNothing else re-advertises them. `configFieldDescriptors` and `ConfigView.Schema`\ngain no `review.*` row: the config catalog's generic renderer was deleted, so a\ndescriptor row adds a field nothing can edit, which is the shape `becb0b5e`\nremoved.\n\n## What the test proves\n\n`internal/app/controlplane/runtime_config_test.go` adds the round trip that\nbuilds the effective config the way boot does: seed the kind from a file config\nwith both dials set one way, store a document with both flipped, layer it\nthrough `runtimeConfigFrom`, and assert the effective `cfg.Review` equals the\nstored document. A second case covers the absent kind, where the file's values\nstay in effect. The assertion is on `cfg.Review` — the value `TaskContext.Cfg`\ncarries into the two stages — not on a struct the test set directly.\n`TestRuntimeResourceKindsApplyLive` gains `review-settings` as live. The\nvalidator needs no `validators_agree_test.goLine truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/runtime-control-plane/",
|
||||
"title": "Runtime control plane",
|
||||
"section": "PRDs",
|
||||
"body": "# Runtime control plane\n\n**Status:** Approved \n**Date:** 2026-09-20 \n**Tracking:** `archie-core-j28m`, `archie-core-1786637498420-327-bacadaae`\n\n## Outcome\n\nArchie can be managed from the Web UI or a messaging channel. Both use the same\nAPI.\n\n## Model\n\nEach feature owns its settings and commands. The database stores them. There is\nno global configuration document.\n\nThis includes:\n\n- workflows;\n- identities and bindings;\n- providers and models;\n- repository policies;\n- channels and schedules;\n- capture mappings and bindings;\n- tool settings;\n- prompts and personas;\n- plugin settings.\n\nPlugin code remains installed code. Only its settings are stored in the\ndatabase.\n\nEach feature defines its data, validation, permissions, editor fields, and how\nchanges take effect. Each feature also defines its allowed actions. For example,\nidentities can be created, suspended, and retired.\n\nRepository and identity settings remain separate. They are not stored as large\nrecords that unrelated features must share.\n\nThe State Store process hosts the control-plane API on its existing gRPC server.\nNo new process is added. Feature code validates changes. Storage code only\nwrites versions and audit records.\n\nEvery write records who made it, where it came from, a request ID, and the\nversion being edited. The API layer sets the actor; the request body cannot.\nThe server validates the change, then writes it with its audit record. It rejects\nedits to an old version.\n\n## API\n\nThe API has four operations:\n\n1. **Catalogue** tells clients what can be viewed or changed and how to edit it.\n2. **Query** reads data and versions without exposing secrets.\n3. **Command** asks the owning feature to make a change.\n4. **Watch** streams changes and errors to clients.\n\nComplex features can use custom screens. They still use the same commands.\n\nA dashboard session or channel sender must map to an Archie identity before it\ncan run a command. Messaging syntax maps to the same commands as the Web UI.\n\n`archie-ui` receives only an API client. It does not receive a database handle,\ndaemon pointer, global configuration object, or secret value.\n\nThe database stores the requested settings. Each process reports the version it\nis using or why it failed. The UI shows both.\n\nSome changes require a restart. The UI shows them as pending. When a live change\nreplaces a running component, Archie starts and checks the new one before\nswitching. If the check fails, the old one keeps running.\n\n## Bootstrap, migration, and recovery\n\nBootstrap contains only the database path, listen addresses, credentials, TLS,\nand encryption-key references. State Store and control-plane RPCs use the same\nendpoint.\n\nWhen upgraded, existing instances are migrated to the database. Existing\ndatabase values are not overwritten. After migration, settings in TOML are\nignored and cannot block State Store startup.\n\nThe Web UI remains available when `archied` or Gateway is down. It shows failed\nchanges and can correct or roll them back.\n\nOffline commands can back up, restore, validate, and roll back the database.\nRecovery does not require `archied` or the Web UI. The database stores secret\nreferences, not secret values.\n\n## Workflows\n\nUsers create and edit workflows in the Web UI. Workflows are stored as versioned\nYAML. Built-in workflows can be overridden and restored.\n\nA workflow is a list of steps. Each step has a known type and its own settings.\nPlugins can add step types. Each run keeps the workflow version it started with.\n\nYaegi, `.archie/stages/*.go`, and `.archie/gate.go` will be removed. Their useful\nbehaviour must first be available as normal workflow steps.\n\n## First implementation\n\nThe first implementation makes task limits editable: maximum model steps,\nmaximum runtime, and maximum consecutive gate failures.\n\nIt includes:\n\n- validated task-limit fields;\n- version history and audit records;\n- the four API operations;\n- authenticated Web UI and messaging access;\n- live updates and apply status;\n- a Pinia-backed editor in the Web UI;\n- a messaging command using the same API;\n- migration of existing `[budgets]` values;\n- an end-to-end restart test.\n\nRunning tasks keep the limits they started with. New tasks use the latest applied\nversion. This replaces the old settings overlay instead of extending it.\n\n## Not included in the first implementation\n\n- Moving bootstrap or secret values into normal settings.\n- A generic JSON editor.\n- Rebuilding every settings screen at once.\n- Changing the limits of a running task.\n"
|
||||
"body": "# Runtime control plane\n\n**Status:** Approved \n**Date:** 2026-09-20 \n**Tracking:** `archie-core-j28m`, `archie-core-1786637498420-327-bacadaae`\n\n## Outcome\n\nArchie can be managed from the Web UI or a messaging channel. Both use the same\nAPI.\n\n## Model\n\nEach feature owns its settings and commands. The database stores them. There is\nno global configuration document.\n\nThis includes:\n\n- workflows;\n- identities and bindings;\n- providers and models;\n- repository policies;\n- channels and schedules;\n- capture mappings and bindings;\n- tool settings;\n- prompts and personas;\n- plugin settings.\n\nPlugin code remains installed code. Only its settings are stored in the\ndatabase.\n\nEach feature defines its data, validation, permissions, editor fields, and how\nchanges take effect. Each feature also defines its allowed actions. For example,\nidentities can be created, suspended, and retired.\n\nRepository and identity settings remain separate. They are not stored as large\nrecords that unrelated features must share.\n\nThe State Store process hosts the control-plane API on its existing gRPC server.\nNo new process is added. Feature code validates changes. Storage code only\nwrites versions and audit records.\n\nEvery write records who made it, where it came from, a request ID, and the\nversion being edited. The API layer sets the actor; the request body cannot.\nThe server validates the change, then writes it with its audit record. It rejects\nedits to an old version.\n\nThe request ID is the write's idempotency key, and it is scoped per org and\nper kind, never global. The key is `(org_id, kind, request_id)` — the unique\nindex `idx_resource_history_org_kind_request` (migration `0021_resources_per_org.sql`)\n— so replaying a request ID is the same org's prior write of the same kind, and\na request ID reused across orgs or across kinds is a separate write. This is the\nsame scoping as the task idempotency key `org/identity/owner/repo/number`\n(`docs/prds/orgs-and-access.md`).\n\n## API\n\nThe API has four operations:\n\n1. **Catalogue** tells clients what can be viewed or changed and how to edit it.\n2. **Query** reads data and versions without exposing secrets.\n3. **Command** asks the owning feature to make a change.\n4. **Watch** streams changes and errors to clients.\n\nComplex features can use custom screens. They still use the same commands.\n\nA dashboard session or channel sender must map to an Archie identity before it\ncan run a command. Messaging syntax maps to the same commands as the Web UI.\n\n`archie-ui` receives only an API client. It does not receive a database handle,\ndaemon pointer, global configuration object, or secret value.\n\nThe database stores the requested settings. Each process reports the version it\nis using or why it failed. The UI shows both.\n\nSome changes require a restart. The UI shows them as pending. When a live change\nreplaces a running component, Archie starts and checks the new one before\nswitching. If the check fails, the old one keeps running.\n\n## Bootstrap, migration, and recovery\n\nBootstrap contains only the database path, listen addresses, credentials, TLS,\nand encryption-key references. State Store and control-plane RPCs use the same\nendpoint.\n\nWhen upgraded, existing instances are migrated to the database. Existing\ndatabase values are not overwritten, with one exception: a resource whose\ndocument the build ships is refreshed when the seed itself wrote the stored\ncopy, because that copy is a previous release's document rather than an\noperator's. After migration, settings in TOML are ignored and cannot block\nState Store startup.\n\nThe Web UI remains available when `archied` or Gateway is down. It shows failed\nchanges and can correct or roll them back.\n\nOffline commands can back up, restore, validate, and roll back the database.\nRecovery does not require `archied` or the Web UI. The database stores secret\nreferences, not secret values.\n\n## Workflows\n\nUsers create and edit workflows in the Web UI. Workflows are stored as versioned\nYAML. Built-in workflows can be overridden and restored.\n\nA workflow is a list of steps. Each step has a known type and its own settings.\nPlugins can add step types. Each run keeps the workflow version it started with.\n\nYaegi, `.archie/stages/*.go`, and `.archie/gate.go` will be removed. Their useful\nbehaviour must first be available as normal workflow steps.\n\n## First implementation\n\nThe first implementation makes task limits editable: maximum model steps,\nmaximum runtime, and maximum consecutive gate failures.\n\nIt includes:\n\n- validated task-limit fields;\n- version history and audit records;\n- the four API operations;\n- authenticated Web UI and messaging access;\n- live updates and apply status;\n- a Pinia-backed editor in the Web UI;\n- a messaging command using the same API;\n- migration of existing `[budgets]` values;\n- an end-to-end restart test.\n\nRuLine truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/self-update-transaction/",
|
||||
@@ -480,6 +498,12 @@
|
||||
"section": "PRDs",
|
||||
"body": "# Skill curator (reference implementation) -- decision\n\n**Status:** Approved\n**Date:** 2026-09-02\n**Beads issue:** `archie-core-1786637499206`\n**Parent epic:** `archie-core-1786637500725` (curator engine)\n\n## Decision\n\nThe skill curator's v1 scope is **mechanical validation and safe\nnormalisation only** -- it never rewrites skill prose, never deletes a\nskill, and never calls the model. Each pass:\n\n1. Lists every skill under one configured root.\n2. Reads each `SKILL.md` and attempts to parse its frontmatter\n (`internal/skill.Parse`).\n3. Records an `Action` for any structural problem: a parse failure, or a\n missing `name`/`description` in the frontmatter that parsed.\n4. Normalises trivial whitespace (trailing whitespace per line, exactly\n one trailing newline) and writes back **only** when normalisation\n actually changes the bytes, recording an `Action` for that write.\n\nNothing here needs judgement. \"Review, prune, and improve\" -- the epic's\nframing -- is real for v1 but deliberately narrow: review is structural\nvalidation, improve is whitespace normalisation, and prune is _reporting_\na problem, never removing a skill. `Manifest.Skills = true` still marks\nthis curator agentic (existing `agentic()` rule), so it receives model\naccess from the registrar -- unused but nothing about the contract\nor the runtime needs to change to let a later version reason about\ncontent quality using it.\n\n## Why this scope, not more\n\nAn autonomous process that rewrites or deletes a user's skill content\nis a real risk with no undo path (no draft/approval flow for\ncurator writes exists yet, unlike the workflow engine's PR-based review).\nThe epic's own stated purpose for this issue is proving the curator\ncontract holds for a second, structurally different consumer than the\nsession-memory curator (files-as-skills vs. observations-as-memory), not\nsolving \"what makes a skill good.\" Mechanical validation is real,\nuseful, safe to run unattended, and fully exercises\nList/Read/Write -- every method `curator.SkillStore` declares except\n`Delete`, which this curator's Pass never has a safe reason to call in\nv1 (kept implemented on the store adapter regardless, since the\ninterface requires it and a future consumer may).\n\n## Why `internal/skill` isn't `curator.SkillStore` directly\n\n`internal/skill.Discover` parses every `SKILL.md` under a root and\nreturns an error for the **whole** call if any one of them fails to\nparse -- the read side was built for \"load the catalogue to start the\ndaemon,\" where one bad skill failing the whole boot is arguably correct,\nnot for \"review each skill and report what's wrong with it\nindividually.\" A per-skill parse failure must become one `Action`, not\nabort the pass before any skill is reviewed. So\n`internal/infrastructure/skillcurator` gets its own thin store adapter\nthat lists raw directory names and reads/writes raw `SKILL.md` bytes\nper name; the skill curator itself calls `internal/skill.Parse` on each\none, isolated per skill.\n\n## Root scope\n\nOne root only, resolved the same way `loadWorkflows` already resolves\n`skillsBase` (`cfg.SkillsDir`, falling back to `cfg.WorkDir`) -- not\nevery root `skill.CatalogRoots`/`DefaultRoots` would read for a model\n(which layers a shared dir over the per-profile one). Write and Delete\nneed one unambiguous target; a curator that could write into a shared,\nmulti-tenant skills directory is a bigger decision than this issue\ncovers. The model still sees the full multi-root catalogue through the\nexisting read path -- this curator only maintains the local one.\n\n## Shape\n\n### `internal/infrastructure/skillcurator/store.go`\n\n```go\n// Store implements curator.SkillStore over one root directory's\n// .agents/skills/*/SKILL.md files, tolerating a per-skill parse failure\n// as the curator's problem to report rather than this store's problem\n// to abort on.\ntype Store struct { root string }\n\nfunc NewStore(root string) *Store\n\nfunc (s *Store) List(ctx context.Context) ([]curator.SkillRef, error)\nfunc (s *Store) Read(ctx context.Context, name string) (curator.Skill, error)\nfunc (s *Store) Write(ctx context.Context, sk curator.Skill) error\nfunc (s *Store) Delete(ctx context.Context, name string) error\n```\n\n`Read` best-effort parses frontmatter for `Skill.Description` (empty on\nparse failure -- not this method's job to report that; `Pass` does, via\nits own `skill.Parse` call on `Skill.Content`). `Write` rejects a name\nthat does not already exist as a directory (this store curates existing\nskills; creating a new one is out of scope). `Delete` removes the whole\nskill directory, matching \"delete a skill,\" not just `SKILL.md`.\n\n### `internal/infrastructure/skillcurator/skillcurator.go`\n\n```go\n// Curator implements domain/curator.CuratorEngine. See\n// docs/prds/skill-curator.md for what a pass does and why.\ntype Curator struct { /* unexported: registrar view, interval *Line truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/soul/",
|
||||
"title": "SOUL: an agent's user-authored personality",
|
||||
"section": "PRDs",
|
||||
"body": "# SOUL: an agent's user-authored personality\n\n**Status:** Draft\n**Authority:** `docs/architecture/identity.md`, “Three-layer identity model”;\n`docs/prds/orgs-and-access.md` for identity and org ownership.\n\n## Decision\n\nSOUL supplies an agent's name, register and warmth. It belongs to the agent's\nimmutable `IdentityID`, not its session, model, installation or container\nprofile. Rename preserves it; changing a profile does not change who acts.\nSOUL never changes attribution, credentials, grants or identity lifecycle.\n`config.AgentProfile` remains an execution environment, not another identity.\n\nUse the existing three layers: invariants, user-authored SOUL, and curator-derived\nrepresentation. Curators may propose SOUL changes but never apply them.\n\n## Files and ownership\n\nThe config directory is `${XDG_CONFIG_HOME:-~/.config}/archie`, or the directory\nof an explicitly selected config file. The default/root agent uses `SOUL.md`\ndirectly there; additional agents use `agents/\u003cidentity-id\u003e/SOUL.md`. The root is\nthe identity selected by application composition, never the initiating user or\na session's personality selection. No file creates or selects an identity.\n\nThe common case keeps a human-friendly filename; additional agents get separate\nasset directories, following `.agents/skills/\u003cname\u003e/SKILL.md` without confusing\nthese directories with `[containers.profiles.\u003cname\u003e]`. Reject display-name or\nslug directories: rename and same-name agents across orgs would require another\nname-resolution rule. Immutable IDs avoid both problems without an org directory.\n\nWhen a file-owned agent's file is absent, create the shipped default with\nexclusive creation. Never overwrite an existing file, including an empty one.\nA creation failure still permits the turn using the embedded shipped default.\nShip that document independently of `agent.ShippedPersonas`, so deleting personas\ncannot delete the fallback.\n\nResolve once at the start of every new generation:\n\n1. A stored SOUL entry for the acting identity is authoritative.\n2. Without an entry, read that identity's file again.\n3. An absent, empty, unreadable or invalid selected source uses the shipped default.\n\nThe first explicit dashboard/API save takes ownership permanently. Thereafter\nfile edits are ignored: emit one ownership notice and show the owning stored\nversion in the dashboard. Restoring the shipped default writes a stored value;\nit does not remove ownership. Refuse writes that remove an owned entry.\n\nThis ownership boundary is the design's one stateful rule. Files seed the\neditable value, not an automatic durable import. Reject seed-once import because\nit breaks next-message file editing; reject file-always-wins because it makes\ndashboard saves ineffective. Neither a restart nor an upgrade overwrites an\nowned value, following the precedence of `controlplane.AgentProfileKind` without\ncopying its startup import timing.\n\n## Prompt and failure contract\n\nKeep `archie.md.tpl`'s XML-escaped\n`\u003csoul purpose=\"identity_and_style\" trust=\"data\"\u003e` block before\n`\u003cinstruction_precedence\u003e`. SOUL is style reference data; the invariant sections,\ntool inventory and runtime metadata remain authoritative and uneditable.\nPreserve `TestBuildSystemPromptSoulCannotOverrideInvariants`.\n\nAccept UTF-8 plain Markdown with at most 8 KiB in its XML-escaped body. This bounds\npersonality to a small prompt contribution; count the complete rendered prompt\nin the turn's context budget and never truncate invariant sections. Bound file\nreads before decoding; reject oversize input rather than truncating instructions.\nFile and stored writes use the same validator; an invalid save leaves the stored\nversion unchanged. The shipped default must pass that validator.\n\nRead and creation errors never fail a turn. Log once per identity/source failure\nepisode, retry on the next turn, and allow a new warning after recovery. If the\nstore cannot establish whether an owned entry exists, use the shipped default,\nnot a potentially shadowed file. Do not log SOUL text. Each turn keeps its resolved\nsnapshot; edits affect the next generation without restart or SIGHUP.\n\n## Cross-layer delivery\n\n- `internal/domain/agent` owns SOUL content validation and the identity-keyed read\n contract; `internal/domain/identity` remains the actor/lifecycle authority.\n- The configuration infrastructure resolves the config directory and handles\n file discovery, exclusive default creation and bounded per-turn reads.\n Application composition resolves the acting `IdentityID` through the existing\n identity repository/bindings and supplies it to the gateway.\n- Register `SoulKind` (`agent-souls`) in the control plane with a live descriptor\n and an org-scoped document mapping identity IDs to `{text}`. Persist it through\n the State Store's existing resource/history contracts, not a new table,\nLine truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/state-store-contract/",
|
||||
"title": "State Store — contract boundary \u0026 transport (ratification)",
|
||||
@@ -534,11 +558,23 @@
|
||||
"section": "PRDs",
|
||||
"body": "# Webhook intake security -- decision\n\n**Status:** Approved\n**Date:** 2026-08-22\n**Beads issue:** `archie-core-t2db.5`, blocks `archie-core-t2db.4`\n\n## Why this is decided ahead of the code it constrains\n\n`archie-core-t2db` (no-code playbooks) and `archie-core-7d5u` (typed event\nsources) both land a public intake surface whose eventual output is an agent\nwith tool access and a repo. Neither capture (`t2db.1`) nor the intake family\n(`7d5u.3`) has shipped yet, so this decision exists to be a contract the two\nepics build against, not a retrofit once the surface exists. A webhook URL\nthat can start an agent is remote code execution with extra steps if any of\nthe five points below is missing on day one.\n\n## 1. Per-source authentication\n\nReuse the per-route HMAC-SHA256 scheme already in\n`internal/channels/webhook/webhook.go` (`validateHMAC`), unchanged: a source\nregisters with a shared secret; the signature is checked against the raw\nbody. Do not invent a second scheme for intake.\n\n**Capture and triggering split at the signature, not at a separate flag.** An\nevent with a missing or invalid signature is still captured (visible in the\ninspector, marked unauthenticated) so an operator can diagnose a\nmisconfigured sender -- but an unauthenticated event can never be matched\nagainst a binding. Authentication is what promotes an event from \"something\narrived\" to \"something that can run a workflow.\"\n\n## 2. Human approval before a binding arms\n\nA binding has three states: `draft -\u003e pending_approval -\u003e armed`. Only\n`armed` bindings are evaluated against incoming events. Creating or editing a\nbinding's matcher, mapping, or target workflow always sets it to\n`pending_approval`, including edits to an already-armed binding -- an edit is\nnot silently re-armed, or the approval gate is decorative. Approval requires\nan authenticated dashboard session; there is no unattended approval path.\n\nModel: `internal/channels/telegram`'s dangerous-command approval flow\n(`dangerousAction` / `pendingApproval` in `dangerous.go` / `approval.go`) is\nthe existing precedent for \"a human decision gates code from running\" in this\ncodebase -- follow its shape rather than designing a new approval primitive.\n\n## 3. Rate and volume limits, per source\n\nA token-bucket limiter keyed by source ID, not global -- one noisy or hostile\nsender must not exhaust another source's capture budget. Precedent for\nper-key volume capping: `internal/pairing/store.go`'s `MaxPendingPerPlatform`.\n\nOn limit exceeded, the request is rejected (HTTP 429), not silently dropped.\nA silently dropped event is indistinguishable from a sender that never fired\n-- the same invisible-failure shape the update-verification work\n(`archie-core-522`) exists to prevent. The rejection itself is observable in\nthe inspector as a distinct outcome from \"not received.\"\n\n## 4. Blast radius bounded by code, not by prompt wording\n\nA playbook-triggered task runs through exactly the same enforcement as every\nother task: the `[[repos.gate]]` quality gate, `diff_cap_lines`, the\nsandboxed per-task container (`internal/container`), worktree isolation, and\n\"the model never runs git.\" No new relaxation is introduced for\nplaybook-triggered work, and none is needed -- the existing constraints are\nthe control.\n\nMapped payload fields are treated as ordinary user-controlled text inside an\nagent prompt, exactly like an inbound chat message never as trusted\ninstructions. \"The agent should ignore instructions in the payload\" is not a\ncontrol and must not appear as one anywhere in this feature -- per the\nenvironmental-enforcement principle (`docs/architecture/agent-system.md`,\n\"Existing invariants to preserve\"), the boundary is the gate and the sandbox,\nnot a sentence in the system prompt.\n\n## 5. Retention and redaction of captured payloads\n\n**Retention:** captured events (bound or not) are purged after 7 days,\nconfigurable per deployment. Unbound events exist to be mapped against; nothing\njustifies keeping them indefinitely once that window has passed, and an\nunbounded capture store is the same disk-exhaustion risk item 3 addresses at\nthe request-rate level.\n\n**Redaction:** before a captured payload is persisted, apply the same\nkey-name heuristic `internal/gateway/stream.go`'s `sensitiveParameterKey`\nalready uses for tool-call parameters (matches `token`, `secret`, `password`,\n`passwd`, `api_key`, `apikey`, `authorization`, `credential`, `cookie`,\n`private_key` against normalised JSON keys) and replace matching values with\nthe same `[redacted]` marker. This is best-effort, not a guarantee -- a\nsender that names a secret field something the heuristic misses will still\nhave it captured. Document that limitation where captured payloads are\ndisplayed, rather than implying the redaction is complete.\n\n**Visibility:** captured payloads, redacted or not, are visible only to an\nauthenticated dashboarLine truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/workflow-call-outputs/",
|
||||
"title": "Declared outputs of a workflow run",
|
||||
"section": "PRDs",
|
||||
"body": "# Declared outputs of a workflow run\n\n**Status:** Draft\n**Date:** 2026-09-30\n**Bead:** `archie-core-t2db.43`\n**Authority:** `docs/prds/event-automation.md` for what a declared output is,\n`docs/prds/workflow-calls.md` for the call and its grants,\n`docs/prds/state-store-contract.md` for the State Store contract the wire\nchange must satisfy.\n**Supersedes:** `docs/prds/workflow-calls.md`, \"Waiting on the callee\": the\ncallee's transition detail is the human summary, not the stand-in for\nstructured outputs.\n\nA workflow declares named, typed outputs. A run writes each one once. A\n`wait: true` caller receives them, and may publish one as its own.\n\n## Where outputs are declared\n\n`outputs:` on the workflow definition, beside `inputs:`, decoded into\n`task.WorkflowInterface.Outputs map[string]OutputSpec` where\n`OutputSpec{Type, Required}`:\n\n```yaml\nid: firewall-contain\noutputs:\n contained: { type: bool, required: true }\n summary: { type: string }\n```\n\nNames and types are the input grammar: the same identifier shape, the same\ntype set, and the same check in `WorkflowInterface.Validate`, which both\n`ParseDefinition` and `ParseWorkflowInterface` call.\n\n**Forced by:** `ParseDefinition` decodes with `KnownFields(true)`, so a key no\ndecoded struct declares is refused — the declaration must live on\n`WorkflowInterface` for an author to write it at all, and that is where\n`docs/development/workflows.md` puts every field a process without the engine\nmust read. The type set is the shared value vocabulary: `TypeAccepts` and\n`ValueType` already check a mapped parameter and an input with it. `required`\ndefaults to false, and the generated YAML for a builtin that declares no\noutputs is unchanged, because a definition's digest pins a run.\n\n**Rejected:** outputs per step, or per call step, because a workflow returns a\nresult as itself rather than as one of its stages. Also `task.Definition`\ngaining outputs: no reader needs them — a binding offers inputs, and a call's\noutputs assignment is checked against the callee's YAML in the same\ncollection — and a declared field with no reader parses and does nothing.\n\n## How a run writes one\n\nEach declared output is offered to the run's agent stages as a capture tool\nnamed after the output, whose arguments are `{\"value\": ...}`; the accepted\ncall's `value` member is the output's value. The engine holds the accepted\nvalues on the task context and writes them into its own task row in the\n`Store.Update` call the run already makes. A deterministic stage may set the\nsame values in Go, and the run's finish check validates them identically.\n\n**Forced by:** a run's only structured results are capture calls\n(`agentexec.CaptureTool`, `Result.Captures`), and the workflow interface\nalready declares when a stage needs them (`task.WorkflowNeeds.Captures`).\nDeriving the tools from the declaration means an output cannot be written\nunder a name nobody declared, and it keeps one route to structured agent\noutput rather than adding a second beside the capture path. The row write is\nthe run's existing write: the task row is where a run's own state lives, and\nthe container already holds `Update` on its own row.\n\nThe tool is offered with `MaxCalls: 1`, and a stage is not offered an output\nthe run has written, so a run writes each output once: a repeat within a stage\nis answered with the tool's rejection and the agent carries on, and a later\nstage cannot overwrite a value. A stage's own capture tool may not share a\nname with a declared output, because the value would otherwise be ambiguous.\n\n**Rejected:** a `workflow.output` step type, because assigning the run's\nresult from a step needs a grammar for \"the previous stage's result\" that does\nnot exist, and a step that reaches the agent would be the second path\n`docs/development/workflows.md` forbids. Also a write RPC of its own: the\ncontainer's `Update` already reaches its own row, and a second write verb for\none column is a second thing to keep in step.\n\n## How a caller receives one\n\nOn a successful `wait: true` call the caller's stage holds the callee's\noutputs as a `map[string]any`. A call step's `outputs:` setting publishes one\nas one of the caller's own outputs:\n\n```yaml\nsteps:\n - type: workflow.call\n workflow: firewall-contain\n wait: true\n inputs: { src_ip: inputs.src_ip }\n outputs: { contained: outputs.contained }\n```\n\nThe key names the callee's declared name; the value names one of the caller's\nown with the prefix the call's `inputs:` already uses. A published value joins\nthe caller's output set for its run, so a caller returns its callee's result to\nits own caller, and a run may publish a callee's output and write its own\nothers.\n\nLifetime is the attempt. The run starts with an empty output set, every later\nstage of that attempt sees the values, and the finish write replaces the row's\nset wholesale — so nothing an attemLine truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/workflow-calls/",
|
||||
"title": "Workflows calling workflows",
|
||||
"section": "PRDs",
|
||||
"body": "# Workflows calling workflows\n\n**Status:** Draft\n**Date:** 2026-09-26\n**Bead:** `archie-core-t2db.41`\n**Extends:** `docs/prds/event-automation.md` (workflow/binding/profile model), `docs/prds/state-store-contract.md` (two new RPCs), `docs/prds/execution-tree-state-machine.md` (call kind)\n\n## The call, end to end\n\n```\ncaller run (in agent container)\n workflow.call step ──StartCall──▶ State Store EnqueueCallTask(caller, workflow, inputs)\n │ callee task row: org/identity/owner/repo\n │ derived from the caller row server-side\n ▼\n callee task (queued, org of the caller)\n │ daemon claims, pins the callee's OWN\n │ definition → its OWN agent profile\n ▼\n callee run (its own container, own tree)\n wait: true ──poll──▶ State Store WorkflowCallStatus(caller, callee)\n wait: false ──continue\n```\n\nA `workflow.call` step starts the callee as a first-class task and, with\n`wait: true`, waits for its terminal state. The callee is never run \"inside\"\nthe caller: it gets its own task row, its own pinned definition, its own\nprofile, its own container, and its own outcome on its own run\n(`execution-tree-state-machine.md`).\n\n## Save-time checks (the collection is the authority)\n\nAll semantic checks run in `workflow.ValidateDefinitionCollection`, the gate\nevery save and load of the `workflow-definitions` resource passes through.\nA single-definition parse cannot see callees, so it validates shape only.\n\n- **Callee exists.** A call to a workflow outside the collection is refused.\n- **Inputs checked.** A call value is a literal or a reference\n (`inputs.\u003cname\u003e`) to the calling workflow's declared input. References must\n name a declared input; the resolved type must satisfy the callee's declared\n type; unknown callee inputs are refused; a required callee input must be\n assigned.\n- **Self-calls refused.** The call graph over the collection is walked from\n every workflow; a workflow that reaches itself, directly or through other\n workflows, is refused with the cycle path. (Cycles can otherwise deadlock:\n `wait: true` callers hold their containers.)\n- **Repository.** `workflow.call` needs no repository, so it is legal in a\n `repository: none` workflow: the callee inherits the caller's task record\n (owner/repo/identity/org), and the callee's own `repository` mode decides\n whether its run clones.\n- **Org enablement** (bead `archie-core-t2db.42`): the single\n instance-wide collection the current model serves is what \"enabled for\n the caller's org\" resolves against — an undefined callee parks. The\n callee's org is derived from the caller's row, so a callee is never\n visible outside its caller's org. The per-org enable/disable catalogue\n lands with `archie-core-t2db.42` and becomes the one source of this\n predicate.\n\n## Runtime\n\n**Depth limit.** `workflow.MaxCallDepth` (5). The calling stage refuses a call\nthat would exceed it; the store re-checks on insert (callee depth = caller\ndepth + 1), so no path can enqueue past the limit.\n\n**Starting the callee.** The caller runs inside a container whose task-scoped\nState Store grant authorizes only `Update`/`Transition`/`InsertEvent` on its\nown task — it can neither enqueue a task nor read another one. One new\ncontract RPC starts the callee:\n\n- `EnqueueCallTask(caller_task_id, workflow, inputs_json) → task`\n — the store reads the caller row, refuses a caller that is not `running`,\n refuses past the depth limit, and inserts the callee row deriving org,\n workspace, identity, owner, repo and a fresh synthetic issue number from\n the caller (the same org COALESCE `EnqueueIssue`/`InsertChatTask` use). The\n callee row carries `call_parent_task_id` and `call_depth`.\n\n**Waiting on the callee.** One new read RPC returns a call's callee:\n\n- `WorkflowCallStatus(caller_task_id, call_task_id) → (status, detail)` — the\n handler verifies `call_parent_task_id` matches, so a caller reads only its\n own callees, and returns the callee's status plus its latest transition\n detail (the callee's summary — the wait:true \"outputs\" until a structured\n outputs model lands).\n\nBoth RPCs are admitted to task-scoped grants on `caller_task_id == granted\ntask ID` (`authorizesTaskScopedCall` gains two request-shape cases). This is\nthe one sanctioned widening of a task grant: the callee is the caller's child,\nand starting it is the mechanism by which one event becomes several runs. The\nwidenings stay request-shape checks; the parent-child authorization is a\nhandler-side row check, so the interceptor never reads the database.\n\n**Schema.** `tasks` gains Line truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/workflow-step-vocabulary/",
|
||||
"title": "Workflow step vocabulary: what a step type is and how binaries agree on it",
|
||||
"section": "PRDs",
|
||||
"body": "# Workflow step vocabulary: what a step type is and how binaries agree on it\n\n**Status:** Draft\n**Date:** 2026-09-29\n**Beads:** `archie-core-m7oc` (agreement between separately deployed binaries), `archie-core-ze7y` (the deleted `.archie/stages/*.go` equivalent)\n**Extends:** `docs/architecture/plugins-and-extensions.md` (plugin engine rule), `docs/prds/event-automation.md` (the workflow model step types serve)\n\n**Authority:** `docs/architecture/plugins-and-extensions.md` — the workflow step vocabulary is a Workflow capability family, and its extension point follows the plugin engine rule.\n\n## Decision\n\nA workflow step type is a named Go factory: the word a YAML workflow writes in\na step's `type` field, plus the factory that builds its stage. The name is a\nstable identifier; the identity also declares what plugin family claims it,\nso a contribution that shadows a shipped stage is refused instead of\noverriding it.\n\nThe Workflow domain owns the typed family contract — `StepTypeProvider` for a\ncontribution and `Manager` as the owning registry. A provider contributes a\nwhole set of step types under its own stable-identifier name; the manager\nvalidates the entire contribution before applying any of it (named provider,\nwell-formed step-type names, non-nil factories, no step type claimed twice,\nno claim on a name another provider holds) and applies it atomically. The\ngeneric `plugin.Plugin` contract stays metadata-only.\n\nThe vocabulary is a compiled-in, closed set. `internal/infrastructure/workflowsteps`\nis the one place a step type is bundled into any binary that resolves one: the\nshipped workflow stages, the repository-hook replacements (`workflow.diff-rules`)\nand the repository-free event steps each arrive as one provider, and adding a\nstep type means adding a provider to that set. Interpreted plugin sources\ncannot contribute step types: the Yaegi plugin host satisfies only the\nmetadata contract, and no bridge to `StepFactory` exists.\n\nEvery binary that resolves a step type builds its manager from that same\nprovider set at its composition root, before its first resolution, and\ninjects the manager everywhere it resolves definitions. Agreement is per\nbuild: the State Store, the daemon's workflow-definitions client and the agent\nworker built from the same source register identical vocabularies by\nconstruction; binaries built from different sources can disagree, and only a\nmatching deploy fixes that.\n\nAn unknown step type is refused twice, and never degraded. The validator\n`ParseDefinition` refuses a definition naming an unregistered type at save\ntime, on the validating side the composition root built (the State Store's\nworkflow-definitions resource validates there before anything is stored). The\ncompiler refuses the same definition at run, so a binary handed a definition\nwritten against a vocabulary it does not have fails that run loudly instead of\nsilently skipping steps. Both checks live in the Workflow domain against the\ninjected manager, which is why no binary can opt out of the check by\nsubstituting its own registry.\n\n## Relationship between the questions\n\n`archie-core-ze7y` is the same question seen from the deleted\nrepository-authored stages: those `.archie/stages/*.go` files held arbitrary\nstages, and their gate half landed as `workflow.diff-rules` settings rather\nthan interpreted Go. Their stage half has no replacement and does not get one\nthat approximates it: no interpreted-Go stage type is built, and no command\nstep type is created by this decision to stand in for them. The refusal of\n`.archie/stages/*.go` stays until the maintainer's trust decision\n(`archie-core-ndm8`) says otherwise.\n\nIf that decision ever allows a command step type, it arrives as a provider in\nthe compiled-in set under the rules above — a new contributor of exactly one\nstep type at a named provider. It is not a plugin contribution mechanism, and\nit does not change any answer in this document.\n\n## Rejected alternatives\n\n- **A vocabulary version or hash on the wire.** The executing side already\n refuses an unknown step type at its first compile, which is the mismatch\n detector, and it fails closed. A wire field would only narrow the\n deploy-skew window that a matching deploy closes, at the cost of a new\n contract field.\n- **A Yaegi-plugin-to-`StepFactory` bridge.** It would run repository-supplied\n interpreted code inside the daemon's process with daemon privileges. The\n trust boundary invariant requires repository-authored code to run in the\n task container, not in an interpreter embeddable into any binary.\n- **A package-level process-global registrar.** Global mutable registry state\n is unreadable at the composition root, collides with itself when one\n process builds the vocabulary twice, and is what made the first attempt at\n this question worse instead of better.\n- **Degrading on an unknown step type.** A run that skipsLine truncated
|
||||
}
|
||||
],
|
||||
"nav": [
|
||||
@@ -821,10 +857,18 @@
|
||||
"title": "Playbook data-flow and condition syntax",
|
||||
"url": "/dev/prds/playbook-expression-syntax/"
|
||||
},
|
||||
{
|
||||
"title": "Plugin settings reconcile live",
|
||||
"url": "/dev/prds/plugin-settings-live/"
|
||||
},
|
||||
{
|
||||
"title": "PR review agent",
|
||||
"url": "/dev/prds/pr-review-agent/"
|
||||
},
|
||||
{
|
||||
"title": "PR review: the operator's answer to the approval gate",
|
||||
"url": "/dev/prds/pr-review-operator-response/"
|
||||
},
|
||||
{
|
||||
"title": "PR review comment remediation -- decision",
|
||||
"url": "/dev/prds/pr-review-remediation/"
|
||||
@@ -845,6 +889,10 @@
|
||||
"title": "Review calibration -- decision",
|
||||
"url": "/dev/prds/review-calibration/"
|
||||
},
|
||||
{
|
||||
"title": "Review settings resource",
|
||||
"url": "/dev/prds/review-settings-resource/"
|
||||
},
|
||||
{
|
||||
"title": "Runtime control plane",
|
||||
"url": "/dev/prds/runtime-control-plane/"
|
||||
@@ -869,6 +917,10 @@
|
||||
"title": "Skill curator (reference implementation) -- decision",
|
||||
"url": "/dev/prds/skill-curator/"
|
||||
},
|
||||
{
|
||||
"title": "SOUL: an agent's user-authored personality",
|
||||
"url": "/dev/prds/soul/"
|
||||
},
|
||||
{
|
||||
"title": "State Store — contract boundary \u0026 transport (ratification)",
|
||||
"url": "/dev/prds/state-store-contract/"
|
||||
@@ -905,9 +957,17 @@
|
||||
"title": "Webhook intake security -- decision",
|
||||
"url": "/dev/prds/webhook-intake-security/"
|
||||
},
|
||||
{
|
||||
"title": "Declared outputs of a workflow run",
|
||||
"url": "/dev/prds/workflow-call-outputs/"
|
||||
},
|
||||
{
|
||||
"title": "Workflows calling workflows",
|
||||
"url": "/dev/prds/workflow-calls/"
|
||||
},
|
||||
{
|
||||
"title": "Workflow step vocabulary: what a step type is and how binaries agree on it",
|
||||
"url": "/dev/prds/workflow-step-vocabulary/"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -11,6 +11,12 @@
|
||||
"title": "Building your first playbook binding",
|
||||
"section": "Guides",
|
||||
"body": "# Building your first playbook binding\n\nThis walks through the whole no-code path the event-capture epic promises:\npoint an external app's webhook at archie, see the real payload it sends,\nmap the fields you care about, bind them to a workflow, and watch the next\nmatching event turn into a task -- no code, no redeploy, no restart. See\n`docs/architecture/bindings.md` for the model and threat model behind each\nstep below.\n\n## 1. Send a test event\n\nPoint whatever external app you want archie to react to at:\n\n```\nPOST http://\u003cyour-archied-host\u003e:8484/webhooks/capture/\u003csource\u003e\n```\n\n`\u003csource\u003e` is a name you choose for this sender (e.g. `sentry`, `github-ci`,\n`stripe`) -- it's just a URL path segment, not a preset list. Send one real\nevent however is easiest for a first test, e.g.:\n\n```bash\ncurl -X POST http://localhost:8484/webhooks/capture/sentry \\\n -H \"Content-Type: application/json\" \\\n -d '{\"issue\": {\"title\": \"NullPointerException in checkout\"}, \"level\": \"error\"}'\n```\n\nThis event isn't signed yet, so it's captured but marked **unauthenticated**\n-- visible for you to design against, but incapable of triggering anything\n(`docs/architecture/bindings.md`'s threat-model section explains why: an\nunauthenticated event can never match a binding, no matter how it looks).\n\n## 2. Inspect the captured payload\n\nOpen the dashboard's **Event inspector** (`/captures`). Your test event\nappears there with its real body -- this is schema-by-example: you're\nlooking at an actual payload from the actual sender, not guessing at a\nschema in advance.\n\n## 3. Map the fields you care about\n\nOpen **Field mappings** (`/mappings`) → **New mapping**. Pick your captured\nevent from the dropdown, then click through its payload tree on the right --\nevery key and value is clickable. Clicking a value binds it as a field\n(name, JSON path, and an inferred type you can change). Add whichever fields\nyour workflow needs (e.g. the issue title), mark the ones that must be\npresent as **Required**, hit **Preview** to confirm they resolve correctly\nagainst the real payload, then **Save**.\n\n## 4. Create the binding\n\nOpen **Playbook bindings** (`/bindings`) → **New binding**:\n\n- **Name** -- anything descriptive.\n- **Source** -- the same `\u003csource\u003e` segment from step 1 (e.g. `sentry`).\n- **Field mapping** -- the one you just saved.\n- **Workflow** -- which registered workflow should run on a match.\n- **Repo pin** (optional) -- leave both blank to use the single configured\n repo; set owner/repo explicitly if you run a multi-repo deployment.\n- **Shared secret** -- a real secret (16+ bytes), never `test1234`. The\n sender signs every request body with this via HMAC-SHA256 so archie can\n tell a genuine event from anyone who finds the URL.\n\nSave. The binding starts in **draft** -- nothing fires yet.\n\n## 5. Approve it\n\nA **draft** or freshly-**edited** binding needs an explicit human approval\nbefore it can ever match a live event -- this is deliberate, not a missing\nstep: an operator authoring a binding is a considered act, an event arriving\nis not, and nothing should self-arm (`docs/architecture/bindings.md`'s\nthreat-model section, point 2). Click **Approve**. Status becomes **armed**.\n\n## 6. Fire it for real\n\nSend the same kind of event again, this time **signed** with the binding's\nsecret:\n\n```bash\nBODY='{\"issue\": {\"title\": \"NullPointerException in checkout\"}, \"level\": \"error\"}'\nSECRET=\"the-secret-you-set-in-step-4\"\nSIG=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hmac \"$SECRET\" | sed 's/^.* //')\n\ncurl -X POST http://localhost:8484/webhooks/capture/sentry \\\n -H \"Content-Type: application/json\" \\\n -H \"X-Hub-Signature-256: sha256=$SIG\" \\\n -d \"$BODY\"\n```\n\nThis event is captured as **authenticated**, matched against your armed\nbinding, and dispatched into a new task through the exact same\ngate/worktree/sandbox pipeline every other task goes through -- see\n`docs/architecture/messaging-and-work-intake.md`'s \"Intake provenance\". Check\nthe **Tasks** page; a new task should appear, its body built from the fields\nyour mapping resolved.\n\n## Editing a live binding\n\nAny edit to an armed binding -- even a typo fix -- drops it back to\n**pending_approval** automatically. This can't be bypassed by editing; it\nhas to be re-approved. When editing, leave the **Shared secret** field blank\nto keep the existing secret; only fill it in if you're deliberately\nrotating it.\n"
|
||||
},
|
||||
{
|
||||
"url": "/docs/guides/pr-review-benchmark/",
|
||||
"title": "PR review benchmark",
|
||||
"section": "Guides",
|
||||
"body": "# PR review benchmark\n\nRun `scripts/pr-review-benchmark.sh` with `PRBENCH_REVIEW_MODEL` and\n`PRBENCH_CLASSIFICATION_MODEL` set to configured `provider/model` references.\nThe judge defaults to `anthropic/claude-sonnet-4.6`; set\n`PRBENCH_JUDGE_MODEL` to another configured model when needed. The script uses\n`~/.config/archie/config.toml` for providers and `GH_TOKEN` or `GITHUB_TOKEN`\nfor read access to the benchmark pull requests. It posts no forge review.\n\nThe default run reviews the 38 runnable Martian pull requests once each at\n`deep`, judges the comments against 102 golden comments, and writes\n`bin/prbench-results/run.json`, `summary.json`, and one JSON result per pull\nrequest. That output directory is ignored by git. A completed full run fails\nwhen any problem fails or golden micro-recall is below 0.70. Golden-only\nprecision is reported alongside recall. Set `PRBENCH_OUT` to keep separate\nruns; `-problems ID` limits a smoke run to one pull request. Completed results\nare saved as each PR finishes. Pass `-resume DIR` to reuse completed results\nfrom a run with the same models; each reused problem must match the current\nbenchmark entry, and failed problems are rerun.\nA smoke run alone is not the acceptance run.\n\nThe benchmark passes only each problem's ID and pull request URL to the\nreviewer. The judge receives the golden comments after the review has ended.\nThe runner uses the production decision phases through the merge gate,\nincluding scoring and the 25-comment cap, then stops before polish and forge\nposting. A reviewer that fails to finish makes that problem fail. The results\nrecord budget-skipped phases and the selected models. Model substitutions do\nnot satisfy the PRD's named-model criterion even if recall clears the threshold.\n"
|
||||
}
|
||||
],
|
||||
"nav": [
|
||||
@@ -24,6 +30,10 @@
|
||||
{
|
||||
"title": "Building your first playbook binding",
|
||||
"url": "/docs/guides/first-playbook/"
|
||||
},
|
||||
{
|
||||
"title": "PR review benchmark",
|
||||
"url": "/docs/guides/pr-review-benchmark/"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -17,7 +17,12 @@ that reads it and the path the value takes to get there.
|
||||
channels, containers). The file only seeds it. Once the State Store holds the
|
||||
control-plane resource, the stored document is layered over the file
|
||||
(`controlplane.Client.RuntimeConfig`) and the file key stops mattering. It is
|
||||
checked by `validateDatabaseOwned` and by the resource's validator.
|
||||
checked by `validateDatabaseOwned` and by the resource's validator. A stored
|
||||
value is refreshed from the file only when the store has no value for the kind
|
||||
at all; a kind that ships a document of its own (workflow definitions,
|
||||
personas) is refreshed whenever the seed itself wrote the stored copy, since
|
||||
that copy is a previous release's document rather than an operator's
|
||||
(`controlplane.Server.seedKind`).
|
||||
- **Worker-carried.** A value the agent container needs travels in
|
||||
`config.TaskConfig` (`Config.ForTask`) or on `taskrun.Request`. Never pass it
|
||||
as an environment variable the daemon did not already define, and never carry
|
||||
|
||||
@@ -28,8 +28,9 @@ Authority: `docs/architecture/agent-system.md`. The status vocabulary lives in
|
||||
|
||||
Follow [State Store](state-store.md) for the
|
||||
column and the wire. Then decide who writes it: `UpdateTask` writes a fixed
|
||||
column set, so a field set at enqueue needs its own statement (as
|
||||
`StampTaskBinding` does for binding provenance and inputs).
|
||||
column set, so a field set at enqueue belongs in the insert that creates the
|
||||
row (as `InsertChatTask` does for inputs), or in its own statement when only
|
||||
some producers set it (as `StampTaskBinding` does for binding provenance).
|
||||
|
||||
### Changing what the agent receives
|
||||
|
||||
|
||||
@@ -31,6 +31,50 @@ should look.
|
||||
after visiting Settings and Logs: the UI process serves HTTP/1.1 and six
|
||||
persistent streams can starve every later browser request.
|
||||
|
||||
## Testing the dashboard
|
||||
|
||||
Authority: the runner itself is `ui/package.json`'s `test` script: `node --test
|
||||
--experimental-strip-types test/*.test.ts` over `ui/test/*.test.ts`. It runs
|
||||
pure TypeScript modules with `node`'s type stripping — no SFC loader, no DOM,
|
||||
no second dependency beyond what the app already carries. That is the standard,
|
||||
and a decision record for when it is deliberately not enough:
|
||||
|
||||
- **Test archie's logic in a module; leave SFC wiring alone.** Wire shapes,
|
||||
draft state, copy conditions, filters and payload building live in plain
|
||||
`.ts` files beside the components and are tested in `ui/test/`. Components
|
||||
stay thin, so there is normally nothing in an SFC that is archie logic.
|
||||
- **Installed primitives are upstream-tested, not re-tested here.**
|
||||
`reka-ui` (2.10.5 here) maintains colocated tests per component in its own
|
||||
repo (Vitest/jsdom + axe: Switch, TagsInput, NumberField, Select, the
|
||||
arrow-navigation composables). The npm package ships none of those files, so
|
||||
this coverage is inherited through the version bound, not the tarball —
|
||||
`grep -l test node_modules/reka-ui` finds nothing. Duplicating them as local
|
||||
mount tests would test a dependency.
|
||||
- **A `.vue` import cannot run under the module runner.** `node --test` fails
|
||||
such a module with `ERR_UNKNOWN_FILE_EXTENSION: .vue` and the runner has no
|
||||
built-in loader for SFCs. A file under `ui/test/` that imports a `.vue` is
|
||||
therefore a broken test, not a weak one.
|
||||
- **If a DOM mount harness is ever needed** (a page-level accessibility
|
||||
contract, cross-component interaction, focus behaviour): `happy-dom` +
|
||||
`@vue/test-utils` + `vitest` scoped to a separate DOM test glob, keeping the
|
||||
module runner for everything else. Measured on the ui tree (vitest 5.0.2,
|
||||
happy-dom 20.14.5, @vue/test-utils 2.5.1): they add 24 top-level
|
||||
`node_modules` entries and 27 MB on a 296 MB install, a working 2-test mount
|
||||
suite (role=radiogroup vs role=switch, aria-label, click activation against
|
||||
the real SFCs) runs in 1.2 s on top of the current 0.5 s module suite, and
|
||||
`vue-tsc` (7.4 s) dominates `task test:ui` either way. The single-runner
|
||||
alternative (absorbing the existing suite into vitest) was measured
|
||||
infeasible as-is: all 29 existing files import `node:test`, which vitest
|
||||
cannot collect ("No test suite found in file" for every one), so it would be
|
||||
a rewrite of the whole suite, and its runtime was not measured. Nothing in
|
||||
`ui/dist` or CI changes either way; happy-dom is pure JS, no browser binary.
|
||||
- **What the module standard does not verify:** whether a call site passes an
|
||||
`aria-label` or which `v-if` branch shows. Those live in SFC templates and
|
||||
are only visible with a mount. If a page's accessible-name wiring is the
|
||||
risk, say so in the page's task and reach for the harness decision above
|
||||
rather than quietly growing mount tests. Never suppress a lint rule or a
|
||||
test to keep SFC behaviour out of the gate.
|
||||
|
||||
## Adding an API route
|
||||
|
||||
1. The handler goes in the `internal/webui/api_<concern>.go` file for its
|
||||
|
||||
@@ -34,9 +34,13 @@ restating them.
|
||||
index, so stage regenerated contracts before running it.
|
||||
- Stage by path, or read `git status` before `git add -A`. Tests that start
|
||||
embedded NATS or write logs must use `t.TempDir()`; anything they leave in the
|
||||
tree gets committed. `task check` also adds linter-tool lines to `go.sum`
|
||||
(bead 1e37); restore `go.sum` before committing unless you changed a
|
||||
dependency.
|
||||
tree gets committed. `task check` writes no module file on a consistent tree,
|
||||
root or `tools/` (verified at HEAD with `GOFLAGS` unset and with `-mod=mod`):
|
||||
a stale `go.mod` or `go.sum` fails it, with `missing go.sum entry` or
|
||||
`updates to go.mod needed`, rather than being repaired. Only a global
|
||||
`GOFLAGS=-mod=mod` in `go env` re-enables that repair, which is why the
|
||||
`go -C tools` steps pass `-mod=readonly`; if `go.sum` goes dirty, run
|
||||
`go mod tidy` and commit the result on its own.
|
||||
- A change to `docs/prds/`, `docs/architecture/` **or `docs/development/`**
|
||||
carries the regenerated `docs/data/generated/dev-docs.json`: run
|
||||
`task docs:artifact` (not `task docs:check`, which checks contracts only).
|
||||
|
||||
@@ -39,3 +39,21 @@ vocabulary it registers, so both must see the same step types.
|
||||
behaviour.
|
||||
- Examples in `examples/workflows/` are parsed against the registered
|
||||
vocabulary by `TestExampleWorkflowsParse`. Add one for a new capability.
|
||||
|
||||
## Enabling and disabling
|
||||
|
||||
The `workflow-enablement` control-plane resource lists, per org, the workflows
|
||||
that org has disabled; anything unlisted is enabled. Its readers are the
|
||||
daemon's binding dispatch (a disabled workflow's binding is skipped like an
|
||||
unarmed one), the dashboard's binding save (refused) and binding list
|
||||
(`workflow_disabled`), and work requests. A new reader of "may this org run
|
||||
this workflow" goes through `task.WorkflowEnablement.Enabled`, never a second
|
||||
list. The dashboard acts in the default org until access resolves a caller's
|
||||
own.
|
||||
|
||||
## Starting a workflow from chat
|
||||
|
||||
`task_spawn` accepts `workflow` and an `inputs` object. The gateway forwards
|
||||
inputs through the task creation contract; it does not interpret individual
|
||||
workflows. The daemon checks inputs against the pinned `WorkflowInterface`
|
||||
before acquiring a container and parks invalid requests with the reason.
|
||||
@@ -0,0 +1,28 @@
|
||||
# PR review benchmark
|
||||
|
||||
Run `scripts/pr-review-benchmark.sh` with `PRBENCH_REVIEW_MODEL` and
|
||||
`PRBENCH_CLASSIFICATION_MODEL` set to configured `provider/model` references.
|
||||
The judge defaults to `anthropic/claude-sonnet-4.6`; set
|
||||
`PRBENCH_JUDGE_MODEL` to another configured model when needed. The script uses
|
||||
`~/.config/archie/config.toml` for providers and `GH_TOKEN` or `GITHUB_TOKEN`
|
||||
for read access to the benchmark pull requests. It posts no forge review.
|
||||
|
||||
The default run reviews the 38 runnable Martian pull requests once each at
|
||||
`deep`, judges the comments against 102 golden comments, and writes
|
||||
`bin/prbench-results/run.json`, `summary.json`, and one JSON result per pull
|
||||
request. That output directory is ignored by git. A completed full run fails
|
||||
when any problem fails or golden micro-recall is below 0.70. Golden-only
|
||||
precision is reported alongside recall. Set `PRBENCH_OUT` to keep separate
|
||||
runs; `-problems ID` limits a smoke run to one pull request. Completed results
|
||||
are saved as each PR finishes. Pass `-resume DIR` to reuse completed results
|
||||
from a run with the same models; each reused problem must match the current
|
||||
benchmark entry, and failed problems are rerun.
|
||||
A smoke run alone is not the acceptance run.
|
||||
|
||||
The benchmark passes only each problem's ID and pull request URL to the
|
||||
reviewer. The judge receives the golden comments after the review has ended.
|
||||
The runner uses the production decision phases through the merge gate,
|
||||
including scoring and the 25-comment cap, then stops before polish and forge
|
||||
posting. A reviewer that fails to finish makes that problem fail. The results
|
||||
record budget-skipped phases and the selected models. Model substitutions do
|
||||
not satisfy the PRD's named-model criterion even if recall clears the threshold.
|
||||
@@ -57,6 +57,9 @@
|
||||
"/news/archie/1.41.2/": "/news/1.41.2/",
|
||||
"/news/archie/1.42.0/": "/news/1.42.0/",
|
||||
"/news/archie/1.43.0/": "/news/1.43.0/",
|
||||
"/news/archie/1.44.0/": "/news/1.44.0/",
|
||||
"/news/archie/1.44.1/": "/news/1.44.1/",
|
||||
"/news/archie/1.45.0/": "/news/1.45.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/",
|
||||
@@ -131,6 +134,9 @@
|
||||
"/news/archied/1.41.2/": "/news/1.41.2/",
|
||||
"/news/archied/1.42.0/": "/news/1.42.0/",
|
||||
"/news/archied/1.43.0/": "/news/1.43.0/",
|
||||
"/news/archied/1.44.0/": "/news/1.44.0/",
|
||||
"/news/archied/1.44.1/": "/news/1.44.1/",
|
||||
"/news/archied/1.45.0/": "/news/1.45.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/",
|
||||
|
||||
@@ -1,4 +1,19 @@
|
||||
[
|
||||
{
|
||||
"version": "1.45.0",
|
||||
"date": "2026-09-30",
|
||||
"body": "### archied\n\n- fix(eda): reject a result map missing a field or needing a conversion\n- feat(eda): per-org workflow enable/disable gating bindings\n- feat(telegram): carry inbound media through the chat turn\n- fix(prsource): use a CodeQL-recognised containment guard when extracting archives\n- feat(store): key control-plane resources by (org, kind)\n- fix(store): refuse resource keys the audit key cannot disambiguate\n- fix(daemon): resume the task branch before container acquisition\n- feat(webui): show attachment metadata in the session transcript\n- feat(webui): name a workflow's declared inputs on the work-request form\n- feat(controlplane): carry the caller org from the request principal\n- fix(webui): the workflow handlers act in the caller's org\n- feat(kitrun): render the OAuth credential file with sentinels\n- feat(store): record accepted package authority against the pin\n- fix(workflow): the own-PR flow no longer parks on the operator-approval gate\n- feat(gateway): a TTL-bounded dedup gate for redelivered platform messages\n- feat(egress): capture the OAuth scope set and carry it to the harness secret\n- feat(kitrun): render the OAuth scopes and omit an uncaptured primary key\n- feat(store): project installed package contributions into org resources\n- feat(gateway): coalesce rapid-fire text events into one turn\n- fix(config): expand plugin, module and skills dirs like every other operator path\n- fix(webui): drop the config schema's editability advert\n- feat(webui): events counts, YAML reading, log rows and dashboard filters\n\n### archie-agent\n\n- feat(eda): per-org workflow enable/disable gating bindings\n- feat(telegram): carry inbound media through the chat turn\n- fix(prsource): use a CodeQL-recognised containment guard when extracting archives\n- feat(store): key control-plane resources by (org, kind)\n- feat(controlplane): carry the caller org from the request principal\n- feat(kitrun): render the OAuth credential file with sentinels\n- feat(store): record accepted package authority against the pin\n- fix(workflow): the own-PR flow no longer parks on the operator-approval gate\n- feat(egress): capture the OAuth scope set and carry it to the harness secret\n- feat(kitrun): render the OAuth scopes and omit an uncaptured primary key\n- feat(store): project installed package contributions into org resources"
|
||||
},
|
||||
{
|
||||
"version": "1.44.1",
|
||||
"date": "2026-09-29",
|
||||
"body": "### archied\n\nTwo fixes to tasks that could not get past their workflow definition.\n\n- **Approving a task no longer parks it again.** A task requeued under a\n different workflow kept the previous run's definition pinned, so the worker\n refused to compile the dispatch — it named `feasibility` while the row named\n `implement` — and the task parked immediately, identically on every further\n approval, which left `decline` as the only working operator action.\n The daemon now re-pins whenever the pinned definition's id disagrees with the\n task's workflow. A pin that is present, digest-valid and id-consistent is\n still a strict no-op, so an operator's own definition override survives a\n dispatch unchanged.\n- **A shipped workflow definition now reaches an existing install.** A stored\n seed was consulted only for a resource the store did not already hold, so a\n document that changed in the build never reached a database an earlier\n release had seeded. For workflow definitions that is a total outage rather\n than a stale setting: the collection validates as one document, so a stored\n step type this build no longer has failed every task's pin, whatever workflow\n the task named — and the documented recovery, removing the resource and\n restarting, wrote nothing either, because the store answered the seed's known\n request ID from a history that outlives the resource. A seed now refreshes a\n kind it wrote the newest revision of and re-creates a resource that is gone,\n while an operator's own replacement is never undone.\n\n### archie-agent\n\nThe runtime image is rebuilt with this release and links the shared workflow\npackage carrying the definition-id helper above. Hosts that run agent\ncontainers need `docker compose pull agent` after updating to pick it up."
|
||||
},
|
||||
{
|
||||
"version": "1.44.0",
|
||||
"date": "2026-09-29",
|
||||
"body": "### archied\n\nArchie can now review pull requests.\n\n- **Reviews on request and by watch.** Ask in chat or on the dashboard work form, add a repository to the watch list, or just let archie review its own PRs before it opens them. Review intensity follows a depth dial (quick/standard/deep) classified from the size of the change, and every finished review passes a verification layer — coverage-gap and cross-finding consistency checks — before it is produced.\n- **No forge credential reaches the review sandbox.** The daemon prefetches the pull request's data and rebuilds its source snapshot over the forge's HTTP API, so the agent container works from an isolated copy with no read access to the repository's credentials.\n- **Reviews stop at the operator gate before posting.** `review.precision_gate` / `approve_before_post` decide whether a finished review posts itself or parks for operator approval. With this release the parked state is a stop sign, not a checkpoint: the approve/reject/re-review responses behind the gate are not wired yet, and the gate's settings are not yet editable in the dashboard (configure them in `config.toml`). A parked review sits until that follow-up lands.\n- The adversarial self-review pass archie previously ran before opening its own PRs is superseded by this pipeline and has been removed.\n- Hardened harness input handling: harness identifiers are bounded to integer types.\n\n### archie-agent\n\nThe runtime image is rebuilt with this release; it links the shared pr-review workflow packages behind the reviews above. Hosts that run agent containers need `docker compose pull agent` after updating to pick it up."
|
||||
},
|
||||
{
|
||||
"version": "1.43.0",
|
||||
"date": "2026-09-28",
|
||||
|
||||
@@ -118,7 +118,12 @@ typed values are checked at load; `dyn` values are checked by the module decode.
|
||||
|
||||
**D5 — where the result map becomes the `Result` struct.** Settled:
|
||||
`ModuleRegistry` stays schema-agnostic. `ModuleRegistry.DecodeResult`
|
||||
(`internal/domain/eda/module`) is the conversion site.
|
||||
(`internal/domain/eda/module`) is the conversion site. It accepts a value only
|
||||
when it already carries the field's declared type, and a map only when it
|
||||
carries every declared field. A conversion changes the value's representation --
|
||||
a number for a string field is the named case -- and an absent field reads as the
|
||||
zero value, so each is reported rather than becoming a quietly wrong value in a
|
||||
later expression.
|
||||
|
||||
## Verification
|
||||
|
||||
@@ -128,5 +133,8 @@ typed values are checked at load; `dyn` values are checked by the module decode.
|
||||
dynamically indexed `actions` read fails.
|
||||
- An arg KEY the kind's `Args` schema does not define fails the load, and so
|
||||
does `message: '123'` for the `log` kind. `message: event.title` loads.
|
||||
- A result map missing a declared field, and one whose value is not already the
|
||||
field's type, are both reported by the decode; a value that would only be
|
||||
convertible (a number for a string field) is not accepted.
|
||||
- The one-action `workflow` playbook shape, its dispatch, and its existing
|
||||
load-time checks are unchanged.
|
||||
@@ -4,9 +4,6 @@
|
||||
**Date:** 2026-09-03
|
||||
**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`
|
||||
**Beads issue:** `archie-core-t2db.14` (expression environment).
|
||||
Unbuilt decisions: `archie-core-t2db.25` (J1 action ids),
|
||||
`archie-core-t2db.26` (J2 args as CEL),
|
||||
`archie-core-t2db.27` (Result schemas declared to CEL).
|
||||
|
||||
**Decision:** CEL via `cel.dev/cel-go` (v0.32.0), pinned. One expression
|
||||
mechanism covers both an action's `when` condition and its `args` values.
|
||||
@@ -222,6 +219,14 @@ cost of CEL is measured and bounded.
|
||||
applied to every expression; the linter and daemon use the same value so they
|
||||
agree. Alternative considered: exact number is a constant to tune at first
|
||||
use.
|
||||
- **J6 -- `args` failure semantics.** An `args` value that cannot be evaluated
|
||||
aborts its playbook run: the action and every later action in that playbook do
|
||||
not run, because data has no false value to fall back on and an action run
|
||||
without its arguments is a silent one. Other playbooks matching the same event
|
||||
still run, and the task is unaffected: a playbook run never changes routing.
|
||||
The daemon log reports the failure, naming the task, the playbook and the
|
||||
action; no task event is written. Alternative considered: mirroring J3,
|
||||
rejected because a predicate has a meaningful false and data does not.
|
||||
|
||||
## Interaction with the execution-time gaps
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
# Plugin settings reconcile live
|
||||
|
||||
**Status:** Draft
|
||||
**Tracking:** GitHub [#1154](https://github.com/samcharles93/archie-core/issues/1154), epic [#998](https://github.com/samcharles93/archie-core/issues/998)
|
||||
**Authority:** `docs/prds/runtime-control-plane.md` decides each feature owns how
|
||||
its changes take effect; `docs/architecture/plugins-and-extensions.md` owns the
|
||||
plugin engine rule; `docs/prds/control-plane-apply-status.md` owns where apply
|
||||
reports go.
|
||||
|
||||
## Outcome
|
||||
|
||||
An operator drops a plugin, module or secret-engine file into the configured
|
||||
directory while archied runs, and the daemon loads it without a restart. An
|
||||
edit to an installed file replaces what is running. Deleting an installed file
|
||||
never stops running code; apply status says so. A stored change to
|
||||
`plugin-settings` applies live for additions instead of requiring a restart.
|
||||
|
||||
## Triggers
|
||||
|
||||
`plugin-settings` joins the kinds archied watches (`PluginSettingsKind` moves
|
||||
to the live list in `internal/app/archied/control_plane.go`). After the daemon
|
||||
layers a new version it reconciles the three directories the document names.
|
||||
A second trigger needs no document change: a poller reconciles on an interval,
|
||||
so a file dropped into a directory loads on its own. The poll interval is the
|
||||
apply-status restamp constant; no filesystem-watch dependency is added. The
|
||||
poller reads the current document's directories from the running config each
|
||||
tick, so a changed `plugin_dir`, `module_dir` or `secret_engine_dir` retargets
|
||||
reconciliation without a restart.
|
||||
|
||||
## Rules
|
||||
|
||||
- Adding and changing load; removing never unloads. Yaegi interpreters are not
|
||||
reclaimed while a caller still exists and there is no unload path; the
|
||||
running set can only grow.
|
||||
- Each file is loaded through a fresh interpreter (the boot pattern). A changed
|
||||
file therefore loads cleanly, and replacement switches consumers to the new
|
||||
interpretation; files are content-hashed so only new and changed files load.
|
||||
- A file that fails to load is skipped and reported; already-running code keeps
|
||||
running. This is the degrade-and-skip convention `plugin.LoadDir` and
|
||||
`Registry.LoadDir` already apply at boot. Boot keeps its reject-at-load rule
|
||||
for the module directory; a broken file at runtime skips without aborting.
|
||||
- A directory that does not exist reconciles to an empty set.
|
||||
|
||||
## The three registries
|
||||
|
||||
- **Secret engines** (`internal/secret`). Reconciliation re-runs
|
||||
`Registry.LoadDir` against the live directory. `Register` replaces by name,
|
||||
so an edited engine takes effect for the next resolution. A deleted engine
|
||||
stays registered: existing references keep resolving through it until
|
||||
restart, and the record says so. Engines are stateless resolvers, so a swap
|
||||
needs no lifecycle step.
|
||||
- **Modules** (`internal/domain/eda/module`): reconciliation re-runs
|
||||
`ModuleRegistry.Register` for the kind's file. The invoker maps
|
||||
last-write-wins, and playbook dispatch resolves through the registry at
|
||||
invoke time, so the swap reaches a running playbook store unchanged. A file
|
||||
deleted for a kind leaves the old invoker in place, running; reported.
|
||||
- **Plugins** (`internal/plugin`): `Host` grows running-state operations beside
|
||||
`Register`, `Start` and `Stop`. One adds a single module while the host is
|
||||
running: it is inserted in dependency order, started alone, and on failure
|
||||
rolled back alone, leaving every previously started module running. The
|
||||
other replaces a module whose manifest id matches: stop it, start the new
|
||||
one, and restart the old one when the new start fails. Replacing a module
|
||||
that another depends on is refused, not swapped. These operations obey the
|
||||
plugin engine rule: the host still invokes start and stop itself, isolates
|
||||
the failure to the one module, and keeps a rollback. A deleted file makes no
|
||||
host call: the module runs on and is reported.
|
||||
|
||||
## `skills_dir`
|
||||
|
||||
`skills_dir` is not part of this change. The daemon refuses a candidate
|
||||
`plugin-settings` document whose `skills_dir` differs from the value it is
|
||||
running, reporting that the field applies on restart, until a skill
|
||||
reconciliation exists to carry it. The refusal is the existing rejected-edit
|
||||
apply-status shape: the store keeps the version, the document is not applied,
|
||||
last-known-good keeps running.
|
||||
|
||||
## Apply status
|
||||
|
||||
One record: `archied` on `plugin-settings`. The reconciliation outcome is
|
||||
reported against the version the process is running. The record's error field
|
||||
carries the outstanding reconciliation problem: a deleted file still running, a
|
||||
file that failed to load, or the directory failing to read. A reconciliation
|
||||
with nothing outstanding clears the error. The version stays the version the
|
||||
process is running; an add that succeeded is live even while a removal is
|
||||
outstanding, and the error says so rather than showing the kind as
|
||||
restart-required. archie-gateway keeps boot-time loading; its record simply
|
||||
stays on the version it last applied until it restarts, which the per-process
|
||||
apply-status page already reads correctly.
|
||||
@@ -44,8 +44,11 @@ an `agent` StepExecution; fan-out phases record one child per call.
|
||||
imported by changed files. One agent writes the PR narrative, risk
|
||||
surfaces, changes that do not fit the narrative, and gaps between the
|
||||
description and the diff.
|
||||
3. **Dimension selection.** Three lens agents run in parallel over the intake,
|
||||
anatomy and diff, each able to read the repository:
|
||||
3. **Dimension selection.** Three lens agents run in parallel over the intake
|
||||
(including its machine-written score), anatomy and diff, each able to read
|
||||
the repository. A PR that intake scores as likely machine-written adds a
|
||||
hallucination-check dimension: claims, citations and behaviour the diff
|
||||
does not actually implement.
|
||||
- **behaviour:** where the old and new code diverge for any input; API
|
||||
contracts, concurrency and state, security, error handling, data flow;
|
||||
- **mechanics:** whether the code runs at the language and framework
|
||||
@@ -62,7 +65,11 @@ an `agent` StepExecution; fan-out phases record one child per call.
|
||||
at most 8 at a time. Each reads its target and context files and may
|
||||
follow references. Each finding carries file, line range, severity
|
||||
(`critical`, `important`, `suggestion`, `nitpick`), title, body, an
|
||||
optional suggested fix, quoted evidence, confidence and tags.
|
||||
optional suggested fix, quoted evidence, confidence and tags. A reviewer
|
||||
that exhausts its turn cap or deadline before its terminal tool call
|
||||
records a distinct StepExecution status from a reviewer that completed
|
||||
and found nothing; synthesis and the posted review treat the two
|
||||
differently (the former is unreviewed, the latter is reviewed-clean).
|
||||
5. **Verification layer**, over the review findings:
|
||||
- code extracts an evidence package per finding: the code at the cited
|
||||
lines and snippets from its callers;
|
||||
@@ -94,8 +101,9 @@ an `agent` StepExecution; fan-out phases record one child per call.
|
||||
8. **Merge gate.** One classification call per finding decides blocking or
|
||||
advisory: blocking only for broken builds, security, data loss, contract
|
||||
breaks and regressions. A failed call means advisory.
|
||||
9. **Output.** One call per comment tightens its wording, keeping the
|
||||
original on failure. The review is posted as one forge review with inline
|
||||
9. **Output.** One call per comment tightens its wording, running in a
|
||||
bounded pool at most 8 at a time (matching phase 4), keeping the original
|
||||
on failure. The review is posted as one forge review with inline
|
||||
comments. Any blocking finding requests changes; otherwise the review is a
|
||||
comment. Archie never posts an approval.
|
||||
|
||||
@@ -113,7 +121,11 @@ With `review.approve_before_post = true`, synthesis ends in
|
||||
`waiting_human`. The operator chooses which findings to post, rejects the
|
||||
review, or asks for a re-review with instructions. A re-review reruns phases
|
||||
3 to 8 with the instructions added to the lens and reviewer prompts, at most
|
||||
2 times. A review with no findings posts nothing and does not wait.
|
||||
2 times. A review with no findings posts nothing and does not wait. The gate
|
||||
belongs to the standalone `pr-review` workflow only; archie's own-PR stage list
|
||||
drops it, because a park there would end an implement run before its PR
|
||||
exists (`docs/prds/pr-review-operator-response.md`,
|
||||
"The gate is not reachable from archie's own PRs").
|
||||
|
||||
## Isolation
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# PR review: the operator's answer to the approval gate
|
||||
|
||||
**Status:** Draft
|
||||
**Authority:** `docs/prds/pr-review-agent.md` ("Operator approval") for the gate, and `docs/prds/state-store-contract.md` (rev. 2e) for every task field that crosses the State Store.
|
||||
**Compounds with:** `docs/prds/execution-tree-state-machine.md` (a run cannot resume partway through its stage list).
|
||||
|
||||
## Decision 1 — where the operator answers
|
||||
|
||||
The dashboard's `POST /api/tasks/{id}/action` (`internal/webui/api_tasks.go`, `handleTaskAction`) is the authoritative surface: the only one that resolves the actor from a credential and can carry a payload. Chat is a shortcut, not a second authority — `/approve` (`internal/gateway/gateway.go`, `Router.handleApprove`) answers the post decision with every offered finding selected, and gains no instruction or selection syntax.
|
||||
|
||||
`taskstate.Action` gains `rereview`, and `taskstate.Actions` returns `approve`, `reject` and `rereview` for `WaitingHuman`. `approve` posts the review, `reject` discards it through the existing terminal decline, `rereview` reruns the review phases with instructions. The action body carries `instructions`, required by `rereview`, and `findings`, the finding keys `approve` posts; an absent selection means all of them.
|
||||
|
||||
The path is `handleTaskAction` → `applyOperatorTaskAction` → `Chat.Contract.ApplyOperatorTaskAction` → the daemon's `LocalChatAdapter` → `taskactions.Client` (NATS `archie.gateway.task-action`) → `taskactions.Service.Apply` → one guarded store write that records the decision and requeues. Chat's `/approve` path (`StoreTaskController.Approve` → `chatTaskControllerAdapter.ApproveChatTask`) must reach that same write through the same function, so the two surfaces cannot record different decisions for one operator intent.
|
||||
|
||||
A requeue resumes the workflow the waiting state names, never a name the handler hardcodes. `taskactions.Service.apply` and `chatTaskControllerAdapter.ApproveChatTask` requeue every approval under `implement`, which is the feasibility handoff: an approval whose wait recorded `pr-review` would run the implement workflow. Feasibility must keep that handoff by naming `implement` on the task before it enters the wait, which is the invariant the handler needs — the workflow a task carries is the workflow it runs next. `Requeue` treats an empty workflow as "keep the task's".
|
||||
|
||||
### The review the operator answers
|
||||
|
||||
The gate writes the review it is holding onto the task before it ends the run: one JSON column, `review_gate`, a sibling of `review_payload`, holding the scored findings, the head SHA, the pull request's identity and the workflow the wait resumes. The run's existing `Store.Update` persists it. The same column carries the answer back: the response path's guarded write fills in the outcome, the selection and the instructions, and clears the offer for a re-review.
|
||||
|
||||
The operator reads the offer through the existing task read — `taskView.Task` on `GET /api/tasks` and `GET /api/tasks/{id}/debug` — so no new read endpoint is needed.
|
||||
|
||||
This record is load-bearing because the run that computed the findings ends at the gate and the engine cannot resume it partway. Without it, "post the selected findings" cannot mean the findings the operator saw: the resumed run recomputes them with agent calls. An `approve` resume therefore posts the recorded review filtered by the selection, and the review the resumed phases recompute never reaches the output.
|
||||
|
||||
## Decision 2 — the cap
|
||||
|
||||
The cap is a column: `rereview_rounds` on `tasks`, `bigint NOT NULL DEFAULT 0`, read by the response path and incremented in the same guarded write that requeues a re-review. A re-review at the cap is refused with the conflict sentinel the dashboard answers 409 with, and nothing is requeued. Two is a constant in the domain, not a config knob: the PRD fixes it.
|
||||
|
||||
`Task.Attempt` cannot carry the count, because it counts every requeue. The two alternatives are worse.
|
||||
|
||||
- The execution tree measures passes through the gate, not operator requests. A crash recovery (`RecoverStale`) or an operator retry re-runs the pipeline to the gate and would consume the cap; and a stage has no step read (`task.Store` carries none), so this route needs a new interface method anyway.
|
||||
- `Task.Notes` is the agent memory ledger, not scratch. `AgentStage.buildRequest` passes it into every generic agent request, `agentexec` renders it as a prompt section, and `persistAppendedNotes` appends to it. A counter parsed out of a field agents write to is the encoded-state defect this repository rejects, and instructions parked there would reach every unrelated workflow's agents.
|
||||
|
||||
`RemediationRounds` is the precedent: one writer, one reader, one meaning, kept separate from `RetryCount` so unrelated retries cannot draw a budget down.
|
||||
|
||||
The write crosses the State Store. A goose migration adds the column; `internal/infrastructure/postgres/queries/tasks.sql` and its sqlc output carry it; `internal/infrastructure/postgres/store.go` maps it; `proto/state/v1/state.proto` carries it as a new `Task` field with its regenerated contracts and `staterpc/values.go` mapping both ways; `internal/domain/workflow/task/task.go` declares it; `internal/infrastructure/taskactions/store.go` adds it to the `taskactions.Task` projection the response path reads. The write itself is a guarded requeue method beside `RetryTask`, which increments a counter, and `BeginRemediation`, which records a payload in the same transaction: one transition-table guard, one increment and one requeue in one write. It must join every column-listing query, which `docs/development/state-store.md` names.
|
||||
|
||||
Tests that prove it: the guarded write increments for a re-review and for no other requeue; a re-review at the cap is refused and leaves the task waiting; and the field survives the wire, which `TestTaskProtoCarriesEveryDomainField` asserts for every field of the domain task.
|
||||
|
||||
## Decision 3 — how the instructions reach the stages
|
||||
|
||||
The recorded instructions enter the pipeline at phase 3 and phase 4 only, which is what the PRD asks for: a labelled operator-instructions block appended to `runLens`'s mission in `stagePRLenses` and to `runReviewer`'s mission.
|
||||
|
||||
They cannot ride `AgentStage.buildRequest`. Every pr-review stage builds its `agentexec.Request` in `runPRReviewAgentRecorded`, which sets no `Request.Notes`, so nothing the generic path threads reaches these calls. The pipeline restores the instructions from the task record at the same point it restores the review, and the two mission builders read them there.
|
||||
|
||||
## The gate is not reachable from archie's own PRs
|
||||
|
||||
`StagePRReviewAndOpenPR` splices `prReviewDecisionStages()`, the list `PRReview()` uses, so the gate is reachable from the implement workflow too. It must not be. The change is one entry moving: `stagePROperatorApproval()` leaves the shared list for `PRReview()`'s own stage list, immediately before the merge gate, and the own-PR splice keeps taking the shared list unchanged. This is a prerequisite for the response channel and a change of its own.
|
||||
|
||||
Three reasons, the second deciding it alone.
|
||||
|
||||
- The gate's question is which findings to post, and on archie's own PRs there is no pull request to post to at the point the splice reaches the gate. That trigger's human decision point is its park on an unchallenged blocking finding.
|
||||
- Approving a wait inside the implement workflow re-enters that workflow at its first stage against a worktree that already carries the change. A builder that then reports no changes sets `BuildNoChanges`, `StageCommitPush` calls `closeNoChangesIssue`, and the issue is closed with no pull request ever opened. Nothing the gate decides is worth a route to silently closing an issue.
|
||||
- Short-circuiting instead would put a conditional no-op in every stage whose work a wait had completed, which changes the resume semantics of the whole pipeline rather than this gate.
|
||||
|
||||
## What a full restart gives, and what it costs
|
||||
|
||||
A requeue re-runs the workflow's stage list from its first stage; the engine has no partway resume. That satisfies the PRD's "reruns phases 3 to 8" for free, and it is acceptable for the standalone pipeline precisely because that pipeline has no stage that writes and then closes. The costs:
|
||||
|
||||
- Phases 1 and 2 recompute. Both are code except two agent calls — the machine-written score and the anatomy narrative — so those re-run, and a changed score can change whether the hallucination-check dimension is added.
|
||||
- The pull request's snapshot is checked out again.
|
||||
- The run's cost and wall-clock budgets are per attempt, so a re-review starts with a fresh allowance, which the cap bounds.
|
||||
|
||||
## Verification
|
||||
|
||||
- A gate wait on the standalone `pr-review` workflow answered `approve` posts exactly the findings the operator selected, and no finding the resumed phases produced.
|
||||
- A re-review at the cap is refused, the task stays waiting, and the count survives a store round trip.
|
||||
- A re-review's instructions reach the lens and reviewer missions; a first run's do not.
|
||||
- The gate is unreachable from the implement workflow's stage list.
|
||||
@@ -0,0 +1,123 @@
|
||||
# Review settings resource
|
||||
|
||||
**Status:** Draft
|
||||
**Beads issue:** `archie-core-0ry6`
|
||||
**Authority:** `docs/prds/runtime-control-plane.md` for the resource model,
|
||||
`docs/architecture/configuration.md` for ownership, and
|
||||
`docs/prds/pr-review-agent.md` for what the two dials do.
|
||||
|
||||
## Decision
|
||||
|
||||
`review.precision_gate` and `review.approve_before_post` are one control-plane
|
||||
resource, `review-settings`. The file's `[review]` section seeds it, the stored
|
||||
document outranks the file from then on, and the dashboard writes it through the
|
||||
same settings machinery as every other resource.
|
||||
|
||||
The resource is deployment-wide, like every definition the State Store seeds
|
||||
(`storecontract.DefaultOrgID`): not per-repository, per-identity, or per-run.
|
||||
|
||||
## Why its own kind
|
||||
|
||||
The two dials are pr-review policy — what a review may post, and whether a human
|
||||
decides — not a limit on a task run. The document that carries task limits
|
||||
belongs to that feature. `runtime-control-plane.md` splits settings by feature
|
||||
and refuses documents unrelated features share; `configuration.md` puts a typed
|
||||
runtime setting with the domain whose behaviour it describes. One document per
|
||||
feature is the rule, not one document per settings page.
|
||||
|
||||
A new kind also has no legacy documents. Its first value is the seed derived
|
||||
from the file, so "the store outranks the file" begins from an explicit copy of
|
||||
both fields rather than from a document that predates them.
|
||||
|
||||
## Document
|
||||
|
||||
New file `internal/app/controlplane/review_settings.go`:
|
||||
|
||||
```go
|
||||
const ReviewSettingsKind = "review-settings"
|
||||
|
||||
type reviewSettings struct {
|
||||
PrecisionGate bool `json:"precision_gate"`
|
||||
ApproveBeforePost bool `json:"approve_before_post"`
|
||||
}
|
||||
```
|
||||
|
||||
Its `Definition` sets `ApplyMode: "live"`, `Document: reviewSettings{}`, and a
|
||||
`Seed` returning `reviewSettings{cfg.Review.PrecisionGate, cfg.Review.ApproveBeforePost}`,
|
||||
and a `Validate` wrapping `validateAs`: both fields are free booleans with no cross-field
|
||||
rule, so the validator is a named place to put one rather than an inline no-op
|
||||
(`validatePluginSettings` is the precedent). No `Normalize`, because the kind
|
||||
has no second wire shape to converge.
|
||||
|
||||
## Seeding
|
||||
|
||||
`ImportConfig`/`seededValues` write the seed for a kind the store does not hold,
|
||||
so a deployment that never edited the dials runs the values in `[review]`. Once
|
||||
a document is stored, the file key stops mattering, which is the rule for every
|
||||
database-owned setting.
|
||||
|
||||
## Apply
|
||||
|
||||
`runtimeConfigFrom` in `internal/app/controlplane/runtime_config.go` layers the
|
||||
stored document over the file's `Review`, assigning `out.Review.PrecisionGate`
|
||||
and `out.Review.ApproveBeforePost` field by field. Field-by-field, not
|
||||
`out.Review = ...`: a field added to `config.Review` later keeps the file's value
|
||||
until the document carries it.
|
||||
|
||||
`ReviewSettingsKind` joins `runtimeResourceKinds` in
|
||||
`internal/app/archied/control_plane.go`, so a new stored version re-runs the
|
||||
layering and republishes through `config.Holder`. Live rather than
|
||||
restart-required, because every consumer re-reads it: `Review` is on
|
||||
`reloadableFields` in `internal/app/archied/reload.go`, and the value reaches a
|
||||
run through `Daemon.configFor` → `Config.ForTask` → `TaskConfig.ToConfig` →
|
||||
`TaskContext.Cfg`, which `stagePRPrecisionGate` and `stagePROperatorApproval`
|
||||
read. The next task run uses the new value; a run in flight keeps the value it
|
||||
started with.
|
||||
|
||||
## Projection and page
|
||||
|
||||
`BuildConfigView` gains a plain `Review` field carrying both values out of
|
||||
`cfg.Review`, the way `BudgetsView` carries the layered budgets, so the published
|
||||
config snapshot tells any reader what is in force. The Review page renders the
|
||||
two toggles from the control-plane store's draft for `review-settings` — the
|
||||
shape `SystemTasksPage.vue` uses for `workflow-execution-settings` — and shows
|
||||
the projected value beside them; a Settings route plus a `PAGE_RESOURCES` entry
|
||||
(`ui/src/stores/control-plane.ts`) bind the page to the kind.
|
||||
|
||||
Nothing else re-advertises them. `configFieldDescriptors` and `ConfigView.Schema`
|
||||
gain no `review.*` row: the config catalog's generic renderer was deleted, so a
|
||||
descriptor row adds a field nothing can edit, which is the shape `becb0b5e`
|
||||
removed.
|
||||
|
||||
## What the test proves
|
||||
|
||||
`internal/app/controlplane/runtime_config_test.go` adds the round trip that
|
||||
builds the effective config the way boot does: seed the kind from a file config
|
||||
with both dials set one way, store a document with both flipped, layer it
|
||||
through `runtimeConfigFrom`, and assert the effective `cfg.Review` equals the
|
||||
stored document. A second case covers the absent kind, where the file's values
|
||||
stay in effect. The assertion is on `cfg.Review` — the value `TaskContext.Cfg`
|
||||
carries into the two stages — not on a struct the test set directly.
|
||||
`TestRuntimeResourceKindsApplyLive` gains `review-settings` as live. The
|
||||
validator needs no `validators_agree_test.go` case: it wraps `validateAs` with
|
||||
no rule, because no combination of the two booleans is invalid, and a case that
|
||||
cannot fail is a test the project then carries for nothing.
|
||||
|
||||
## Rejected: extending workflow-execution-settings
|
||||
|
||||
That resource is `workflow.ExecutionSettings`, "the limits captured when a
|
||||
workflow execution starts". Putting review policy in it makes the review feature
|
||||
a field of the limits document, gives a boolean edit a ride on a document whose
|
||||
candidate is validated and swapped as one unit with the budgets, and forces
|
||||
absence-aware pointer fields onto booleans so a document stored before the fields
|
||||
existed does not turn a file's `precision_gate = true` into `false`. It buys one
|
||||
less kind at the cost of the ownership rule the model is built on.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Per-repository, per-identity, or per-workflow review settings. A scope key is
|
||||
a later decision with its own resource shape.
|
||||
- Any other review knob. A field joins the document only with a consumer, the
|
||||
rule every config field carries.
|
||||
- The reviewer pipeline's behaviour. This document places the settings; it does
|
||||
not change what they do.
|
||||
@@ -45,6 +45,14 @@ version being edited. The API layer sets the actor; the request body cannot.
|
||||
The server validates the change, then writes it with its audit record. It rejects
|
||||
edits to an old version.
|
||||
|
||||
The request ID is the write's idempotency key, and it is scoped per org and
|
||||
per kind, never global. The key is `(org_id, kind, request_id)` — the unique
|
||||
index `idx_resource_history_org_kind_request` (migration `0021_resources_per_org.sql`)
|
||||
— so replaying a request ID is the same org's prior write of the same kind, and
|
||||
a request ID reused across orgs or across kinds is a separate write. This is the
|
||||
same scoping as the task idempotency key `org/identity/owner/repo/number`
|
||||
(`docs/prds/orgs-and-access.md`).
|
||||
|
||||
## API
|
||||
|
||||
The API has four operations:
|
||||
@@ -76,8 +84,11 @@ and encryption-key references. State Store and control-plane RPCs use the same
|
||||
endpoint.
|
||||
|
||||
When upgraded, existing instances are migrated to the database. Existing
|
||||
database values are not overwritten. After migration, settings in TOML are
|
||||
ignored and cannot block State Store startup.
|
||||
database values are not overwritten, with one exception: a resource whose
|
||||
document the build ships is refreshed when the seed itself wrote the stored
|
||||
copy, because that copy is a previous release's document rather than an
|
||||
operator's. After migration, settings in TOML are ignored and cannot block
|
||||
State Store startup.
|
||||
|
||||
The Web UI remains available when `archied` or Gateway is down. It shows failed
|
||||
changes and can correct or roll them back.
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
# SOUL: an agent's user-authored personality
|
||||
|
||||
**Status:** Draft
|
||||
**Authority:** `docs/architecture/identity.md`, “Three-layer identity model”;
|
||||
`docs/prds/orgs-and-access.md` for identity and org ownership.
|
||||
|
||||
## Decision
|
||||
|
||||
SOUL supplies an agent's name, register and warmth. It belongs to the agent's
|
||||
immutable `IdentityID`, not its session, model, installation or container
|
||||
profile. Rename preserves it; changing a profile does not change who acts.
|
||||
SOUL never changes attribution, credentials, grants or identity lifecycle.
|
||||
`config.AgentProfile` remains an execution environment, not another identity.
|
||||
|
||||
Use the existing three layers: invariants, user-authored SOUL, and curator-derived
|
||||
representation. Curators may propose SOUL changes but never apply them.
|
||||
|
||||
## Files and ownership
|
||||
|
||||
The config directory is `${XDG_CONFIG_HOME:-~/.config}/archie`, or the directory
|
||||
of an explicitly selected config file. The default/root agent uses `SOUL.md`
|
||||
directly there; additional agents use `agents/<identity-id>/SOUL.md`. The root is
|
||||
the identity selected by application composition, never the initiating user or
|
||||
a session's personality selection. No file creates or selects an identity.
|
||||
|
||||
The common case keeps a human-friendly filename; additional agents get separate
|
||||
asset directories, following `.agents/skills/<name>/SKILL.md` without confusing
|
||||
these directories with `[containers.profiles.<name>]`. Reject display-name or
|
||||
slug directories: rename and same-name agents across orgs would require another
|
||||
name-resolution rule. Immutable IDs avoid both problems without an org directory.
|
||||
|
||||
When a file-owned agent's file is absent, create the shipped default with
|
||||
exclusive creation. Never overwrite an existing file, including an empty one.
|
||||
A creation failure still permits the turn using the embedded shipped default.
|
||||
Ship that document independently of `agent.ShippedPersonas`, so deleting personas
|
||||
cannot delete the fallback.
|
||||
|
||||
Resolve once at the start of every new generation:
|
||||
|
||||
1. A stored SOUL entry for the acting identity is authoritative.
|
||||
2. Without an entry, read that identity's file again.
|
||||
3. An absent, empty, unreadable or invalid selected source uses the shipped default.
|
||||
|
||||
The first explicit dashboard/API save takes ownership permanently. Thereafter
|
||||
file edits are ignored: emit one ownership notice and show the owning stored
|
||||
version in the dashboard. Restoring the shipped default writes a stored value;
|
||||
it does not remove ownership. Refuse writes that remove an owned entry.
|
||||
|
||||
This ownership boundary is the design's one stateful rule. Files seed the
|
||||
editable value, not an automatic durable import. Reject seed-once import because
|
||||
it breaks next-message file editing; reject file-always-wins because it makes
|
||||
dashboard saves ineffective. Neither a restart nor an upgrade overwrites an
|
||||
owned value, following the precedence of `controlplane.AgentProfileKind` without
|
||||
copying its startup import timing.
|
||||
|
||||
## Prompt and failure contract
|
||||
|
||||
Keep `archie.md.tpl`'s XML-escaped
|
||||
`<soul purpose="identity_and_style" trust="data">` block before
|
||||
`<instruction_precedence>`. SOUL is style reference data; the invariant sections,
|
||||
tool inventory and runtime metadata remain authoritative and uneditable.
|
||||
Preserve `TestBuildSystemPromptSoulCannotOverrideInvariants`.
|
||||
|
||||
Accept UTF-8 plain Markdown with at most 8 KiB in its XML-escaped body. This bounds
|
||||
personality to a small prompt contribution; count the complete rendered prompt
|
||||
in the turn's context budget and never truncate invariant sections. Bound file
|
||||
reads before decoding; reject oversize input rather than truncating instructions.
|
||||
File and stored writes use the same validator; an invalid save leaves the stored
|
||||
version unchanged. The shipped default must pass that validator.
|
||||
|
||||
Read and creation errors never fail a turn. Log once per identity/source failure
|
||||
episode, retry on the next turn, and allow a new warning after recovery. If the
|
||||
store cannot establish whether an owned entry exists, use the shipped default,
|
||||
not a potentially shadowed file. Do not log SOUL text. Each turn keeps its resolved
|
||||
snapshot; edits affect the next generation without restart or SIGHUP.
|
||||
|
||||
## Cross-layer delivery
|
||||
|
||||
- `internal/domain/agent` owns SOUL content validation and the identity-keyed read
|
||||
contract; `internal/domain/identity` remains the actor/lifecycle authority.
|
||||
- The configuration infrastructure resolves the config directory and handles
|
||||
file discovery, exclusive default creation and bounded per-turn reads.
|
||||
Application composition resolves the acting `IdentityID` through the existing
|
||||
identity repository/bindings and supplies it to the gateway.
|
||||
- Register `SoulKind` (`agent-souls`) in the control plane with a live descriptor
|
||||
and an org-scoped document mapping identity IDs to `{text}`. Persist it through
|
||||
the State Store's existing resource/history contracts, not a new table,
|
||||
process or SOUL RPC. An empty map owns no identity; saves preserve other entries
|
||||
and use expected-version checks. Validate that each key is an agent identity
|
||||
in the resource's org; begin with the default org without inventing org setup.
|
||||
Every save records the authenticated editor's identity, source, request ID and
|
||||
timestamp; file installation records the system identity, not a fictitious user.
|
||||
- Replace `TurnRunnerConfig.Personas` / `PersonaPromptSource` with the per-identity
|
||||
source in `prepareTurn`; name the `SystemPromptConfig` input SOUL. Both normal
|
||||
and streaming turns use this assembly path. Do not add personality to the
|
||||
worker environment, `AgentProfile` or workflow-stage prompts.
|
||||
- On an agent identity's dashboard page, expose its effective SOUL, file/default
|
||||
or stored source, shadowed file path, owning version, and Markdown editing.
|
||||
Save to the control plane, never the host file; show validation/version
|
||||
conflicts and offer restoring shipped content or a history revision as a save.
|
||||
Read effective file/default content and ownership metadata through a gateway
|
||||
query using the turn resolver; the separate UI process never reads the
|
||||
gateway host's files. Apply identity-management access rules and the existing
|
||||
shared live-update hub.
|
||||
- Update `docs/development/agent.md` and `control-plane.md` with this reach and
|
||||
precedence, `frontend-ui.md` with the gateway query, and the config wiring
|
||||
guidance with a copyable file example.
|
||||
|
||||
## Persona removal gate
|
||||
|
||||
SOUL supersedes `PersonaRegistry` and the persona-reconciliation proposal;
|
||||
identity-per-action supersedes personas as an identity mechanism.
|
||||
`PersonaRegistry.GetActive` composes the baseline with one of five styles from
|
||||
`agent.ShippedPersonas`; SOUL replaces the baseline, not that style catalogue.
|
||||
Per-session switching disappears: remove `/personality`, Telegram personality
|
||||
callbacks, the dashboard persona page, and chat wire fields `personas`,
|
||||
`active_personas` and `personas_available` without reusing their field numbers.
|
||||
Do not merge session selections into SOUL or retain a separate style axis.
|
||||
Custom persona text must remain available to copy before deleting its stored
|
||||
resource; no migration guesses one agent's SOUL from several sessions.
|
||||
|
||||
Remove persona loading, selectors and commands only after every chat composition
|
||||
supplies the identity-aware SOUL source, the fallback renders without personas,
|
||||
and the dashboard can edit it. SOUL delivery does not wait for org creation or a
|
||||
new container-profile model.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- Two agents use distinct files and stored entries; renaming one or sharing a
|
||||
container profile does not change or mix their SOULs.
|
||||
- Before ownership, a file edit changes the next normal or streaming prompt;
|
||||
creating defaults never clobbers an existing file.
|
||||
- After a save, conflicting file edits and restarts cannot override the stored
|
||||
value; the ignored file and owning version are visible. Updating one agent
|
||||
preserves the other; stale saves fail and history restores are audited saves.
|
||||
- Missing, empty, unreadable, malformed and oversize selected inputs render the
|
||||
shipped default. Repeated read failures log once, recover on a later turn,
|
||||
and never abort generation.
|
||||
- Hostile markup stays escaped before singular, unchanged invariant blocks;
|
||||
prompt budgeting includes SOUL and cannot drop the rules.
|
||||
- Dashboard edits reach the next generation without restart; persona removal
|
||||
leaves every channel with a nonempty identity slot and preserved custom text.
|
||||
@@ -0,0 +1,213 @@
|
||||
# Declared outputs of a workflow run
|
||||
|
||||
**Status:** Draft
|
||||
**Date:** 2026-09-30
|
||||
**Bead:** `archie-core-t2db.43`
|
||||
**Authority:** `docs/prds/event-automation.md` for what a declared output is,
|
||||
`docs/prds/workflow-calls.md` for the call and its grants,
|
||||
`docs/prds/state-store-contract.md` for the State Store contract the wire
|
||||
change must satisfy.
|
||||
**Supersedes:** `docs/prds/workflow-calls.md`, "Waiting on the callee": the
|
||||
callee's transition detail is the human summary, not the stand-in for
|
||||
structured outputs.
|
||||
|
||||
A workflow declares named, typed outputs. A run writes each one once. A
|
||||
`wait: true` caller receives them, and may publish one as its own.
|
||||
|
||||
## Where outputs are declared
|
||||
|
||||
`outputs:` on the workflow definition, beside `inputs:`, decoded into
|
||||
`task.WorkflowInterface.Outputs map[string]OutputSpec` where
|
||||
`OutputSpec{Type, Required}`:
|
||||
|
||||
```yaml
|
||||
id: firewall-contain
|
||||
outputs:
|
||||
contained: { type: bool, required: true }
|
||||
summary: { type: string }
|
||||
```
|
||||
|
||||
Names and types are the input grammar: the same identifier shape, the same
|
||||
type set, and the same check in `WorkflowInterface.Validate`, which both
|
||||
`ParseDefinition` and `ParseWorkflowInterface` call.
|
||||
|
||||
**Forced by:** `ParseDefinition` decodes with `KnownFields(true)`, so a key no
|
||||
decoded struct declares is refused — the declaration must live on
|
||||
`WorkflowInterface` for an author to write it at all, and that is where
|
||||
`docs/development/workflows.md` puts every field a process without the engine
|
||||
must read. The type set is the shared value vocabulary: `TypeAccepts` and
|
||||
`ValueType` already check a mapped parameter and an input with it. `required`
|
||||
defaults to false, and the generated YAML for a builtin that declares no
|
||||
outputs is unchanged, because a definition's digest pins a run.
|
||||
|
||||
**Rejected:** outputs per step, or per call step, because a workflow returns a
|
||||
result as itself rather than as one of its stages. Also `task.Definition`
|
||||
gaining outputs: no reader needs them — a binding offers inputs, and a call's
|
||||
outputs assignment is checked against the callee's YAML in the same
|
||||
collection — and a declared field with no reader parses and does nothing.
|
||||
|
||||
## How a run writes one
|
||||
|
||||
Each declared output is offered to the run's agent stages as a capture tool
|
||||
named after the output, whose arguments are `{"value": ...}`; the accepted
|
||||
call's `value` member is the output's value. The engine holds the accepted
|
||||
values on the task context and writes them into its own task row in the
|
||||
`Store.Update` call the run already makes. A deterministic stage may set the
|
||||
same values in Go, and the run's finish check validates them identically.
|
||||
|
||||
**Forced by:** a run's only structured results are capture calls
|
||||
(`agentexec.CaptureTool`, `Result.Captures`), and the workflow interface
|
||||
already declares when a stage needs them (`task.WorkflowNeeds.Captures`).
|
||||
Deriving the tools from the declaration means an output cannot be written
|
||||
under a name nobody declared, and it keeps one route to structured agent
|
||||
output rather than adding a second beside the capture path. The row write is
|
||||
the run's existing write: the task row is where a run's own state lives, and
|
||||
the container already holds `Update` on its own row.
|
||||
|
||||
The tool is offered with `MaxCalls: 1`, and a stage is not offered an output
|
||||
the run has written, so a run writes each output once: a repeat within a stage
|
||||
is answered with the tool's rejection and the agent carries on, and a later
|
||||
stage cannot overwrite a value. A stage's own capture tool may not share a
|
||||
name with a declared output, because the value would otherwise be ambiguous.
|
||||
|
||||
**Rejected:** a `workflow.output` step type, because assigning the run's
|
||||
result from a step needs a grammar for "the previous stage's result" that does
|
||||
not exist, and a step that reaches the agent would be the second path
|
||||
`docs/development/workflows.md` forbids. Also a write RPC of its own: the
|
||||
container's `Update` already reaches its own row, and a second write verb for
|
||||
one column is a second thing to keep in step.
|
||||
|
||||
## How a caller receives one
|
||||
|
||||
On a successful `wait: true` call the caller's stage holds the callee's
|
||||
outputs as a `map[string]any`. A call step's `outputs:` setting publishes one
|
||||
as one of the caller's own outputs:
|
||||
|
||||
```yaml
|
||||
steps:
|
||||
- type: workflow.call
|
||||
workflow: firewall-contain
|
||||
wait: true
|
||||
inputs: { src_ip: inputs.src_ip }
|
||||
outputs: { contained: outputs.contained }
|
||||
```
|
||||
|
||||
The key names the callee's declared name; the value names one of the caller's
|
||||
own with the prefix the call's `inputs:` already uses. A published value joins
|
||||
the caller's output set for its run, so a caller returns its callee's result to
|
||||
its own caller, and a run may publish a callee's output and write its own
|
||||
others.
|
||||
|
||||
Lifetime is the attempt. The run starts with an empty output set, every later
|
||||
stage of that attempt sees the values, and the finish write replaces the row's
|
||||
set wholesale — so nothing an attempt wrote survives into the next, and a run
|
||||
that writes nothing stores nothing. Values reach a caller only from a
|
||||
successful terminal state: the caller assigns them after `callSucceeded`, so a
|
||||
parked or failed callee delivers nothing whatever its row holds. A call step
|
||||
with `wait: false` and an `outputs:` block is refused when the definition is
|
||||
saved, because nothing has finished when the caller moves on.
|
||||
|
||||
**Forced by:** caller and callee are separate runs in separate containers, so
|
||||
the caller's own row is the only durable place to hold a received value. The
|
||||
prefix rule is not a new grammar: in `inputs.<name>` the prefixed side is the
|
||||
caller's own value and the map key is the callee's, and `outputs.<name>` reads
|
||||
the same way in the other direction.
|
||||
|
||||
**Rejected:** an implicit same-name copy from callee to caller, because the
|
||||
caller's contract would then depend on a callee it does not name, and swapping
|
||||
the callee would silently change what the caller returns. Also letting a later
|
||||
stage read a callee's output in its mission text: that needs a stage-result
|
||||
reference namespace this model does not define.
|
||||
|
||||
## Failure rules
|
||||
|
||||
- **Undeclared value.** The agent path cannot produce one — the tool exists
|
||||
only for a declared output. A Go stage that sets an undeclared key parks the
|
||||
run before its outcome transition, and a stage capture tool sharing a
|
||||
declared output's name is refused when the run starts.
|
||||
- **Declared but never written.** With `required: true` the run parks naming
|
||||
the output and reaches no successful terminal state, so no caller observes a
|
||||
success missing a promised value. Without it the key is absent from the
|
||||
object rather than null, and a written `null` counts as not written, as
|
||||
`CheckInputs` treats a null input. A published output the callee never wrote
|
||||
leaves the caller's output absent, which the caller's own `required` then
|
||||
judges.
|
||||
- **Save time.** `WorkflowInterface.Validate` refuses an unknown type and a
|
||||
malformed name. A call step's `outputs:` assignment is checked by a
|
||||
`checkCallOutputs` beside `checkCallInputs`: the key must be declared by the
|
||||
callee, the reference must name an output the caller declares, and the
|
||||
callee's declared type must satisfy the caller's.
|
||||
- **Run time.** A captured value is re-validated against the declared type
|
||||
when the run reads it back, for the reason `readCaptures` re-checks every
|
||||
record: the captures file is writable by the harness user. A published
|
||||
callee value is re-checked against the caller's declared type before it
|
||||
enters the caller's set; a mismatch parks the caller naming the output.
|
||||
|
||||
**Rejected:** typing at save time only, because a captured value has no
|
||||
save-time form; and at run time only, because a definition error would surface
|
||||
as a failed run instead of a refused save.
|
||||
|
||||
## Storage and wire
|
||||
|
||||
- `tasks.outputs`, text, `NOT NULL DEFAULT ''`, written by the run's own row
|
||||
write — the shape `tasks.inputs` already has, with `EncodeOutputs` and
|
||||
`DecodeOutputs` beside `EncodeInputs`/`DecodeInputs`.
|
||||
- The `Task` message carries it as `outputs_json`, because the container's
|
||||
`Update` sends the whole row and a column the message cannot carry is a
|
||||
column that write drops.
|
||||
- `WorkflowCallStatusResponse` carries it as `outputs_json` beside `status`
|
||||
and `detail`, read from the callee's row by the handler that already
|
||||
verifies `call_parent_task_id`; `detail` keeps carrying the transition
|
||||
detail. The Go facade stays the two methods of `task.Caller`; no interface
|
||||
method is added.
|
||||
|
||||
**Forced by the grant:** a caller authenticates as its own task and may reach
|
||||
`WorkflowCallStatus` on its own task ID, `Update`/`Transition`/`InsertEvent`
|
||||
on its own row, and the step-execution pair on its own execution. It can read
|
||||
neither the callee's row nor the callee's steps. `WorkflowCallStatus` is
|
||||
therefore the only channel that exists, and it is already the sanctioned
|
||||
cross-run read — this model fills the placeholder it carries. The values live
|
||||
on the callee's row rather than on the caller's call step because the callee
|
||||
writes them and the caller only receives them.
|
||||
|
||||
The write order is part of the contract: a run persists its outputs before its
|
||||
outcome transition, so the status a caller sees when its wait ends already
|
||||
carries them. A set whose encoded form passes the bound the store applies to a
|
||||
structured payload (`clip`, as `ReviewPayload` is stored) is refused rather
|
||||
than clipped, because clipped JSON does not parse.
|
||||
|
||||
No sentinel moves: a missing required output is an engine park reason, and a
|
||||
caller asking about a task that is not its callee still gets `ErrCallNotYours`,
|
||||
so nothing new crosses `mapError`/`unmapError` and no canonical message string
|
||||
changes.
|
||||
|
||||
**Rejected:**
|
||||
- A new read RPC (`WorkflowCallOutputs`) — a second poll of a row the caller
|
||||
already polls, whose answer could disagree with the status beside it, and a
|
||||
second grant-widening row for the same parent-child check.
|
||||
- The step-execution record — `ListSteps` is granted by `read` on a run, so a
|
||||
caller cannot read the callee's steps at all, and making them readable would
|
||||
hand it the callee's whole step history, which the parent-child check exists
|
||||
to prevent. A step's `detail` is text clipped like every other detail.
|
||||
- The caller's call step as the store — the value originates in another
|
||||
process and must outlive the container that produced it.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- A run started by a binding: it has no caller, and its outputs live on its
|
||||
own row only.
|
||||
- A stage reference to a previous stage's captured value.
|
||||
- Assigning outputs in a caller cancelled while it waits.
|
||||
|
||||
## Verification
|
||||
|
||||
- A definition whose output type is not in the vocabulary, and a call
|
||||
publishing an output neither side declares, are refused when saved.
|
||||
- A `wait: true` caller receives a value its callee wrote, returns it as its
|
||||
own output, and the caller's row carries it.
|
||||
- A run whose required output is never written parks, and its caller's stage
|
||||
fails naming the output.
|
||||
- A call step publishing an output over `wait: false` is refused when saved.
|
||||
- A retried attempt that writes no outputs leaves an empty set on the row.
|
||||
- An example under `examples/workflows/` carries an `outputs:` block and a
|
||||
call that publishes one, which `TestExampleWorkflowsParse` covers.
|
||||
@@ -0,0 +1,85 @@
|
||||
# Workflow step vocabulary: what a step type is and how binaries agree on it
|
||||
|
||||
**Status:** Draft
|
||||
**Date:** 2026-09-29
|
||||
**Beads:** `archie-core-m7oc` (agreement between separately deployed binaries), `archie-core-ze7y` (the deleted `.archie/stages/*.go` equivalent)
|
||||
**Extends:** `docs/architecture/plugins-and-extensions.md` (plugin engine rule), `docs/prds/event-automation.md` (the workflow model step types serve)
|
||||
|
||||
**Authority:** `docs/architecture/plugins-and-extensions.md` — the workflow step vocabulary is a Workflow capability family, and its extension point follows the plugin engine rule.
|
||||
|
||||
## Decision
|
||||
|
||||
A workflow step type is a named Go factory: the word a YAML workflow writes in
|
||||
a step's `type` field, plus the factory that builds its stage. The name is a
|
||||
stable identifier; the identity also declares what plugin family claims it,
|
||||
so a contribution that shadows a shipped stage is refused instead of
|
||||
overriding it.
|
||||
|
||||
The Workflow domain owns the typed family contract — `StepTypeProvider` for a
|
||||
contribution and `Manager` as the owning registry. A provider contributes a
|
||||
whole set of step types under its own stable-identifier name; the manager
|
||||
validates the entire contribution before applying any of it (named provider,
|
||||
well-formed step-type names, non-nil factories, no step type claimed twice,
|
||||
no claim on a name another provider holds) and applies it atomically. The
|
||||
generic `plugin.Plugin` contract stays metadata-only.
|
||||
|
||||
The vocabulary is a compiled-in, closed set. `internal/infrastructure/workflowsteps`
|
||||
is the one place a step type is bundled into any binary that resolves one: the
|
||||
shipped workflow stages, the repository-hook replacements (`workflow.diff-rules`)
|
||||
and the repository-free event steps each arrive as one provider, and adding a
|
||||
step type means adding a provider to that set. Interpreted plugin sources
|
||||
cannot contribute step types: the Yaegi plugin host satisfies only the
|
||||
metadata contract, and no bridge to `StepFactory` exists.
|
||||
|
||||
Every binary that resolves a step type builds its manager from that same
|
||||
provider set at its composition root, before its first resolution, and
|
||||
injects the manager everywhere it resolves definitions. Agreement is per
|
||||
build: the State Store, the daemon's workflow-definitions client and the agent
|
||||
worker built from the same source register identical vocabularies by
|
||||
construction; binaries built from different sources can disagree, and only a
|
||||
matching deploy fixes that.
|
||||
|
||||
An unknown step type is refused twice, and never degraded. The validator
|
||||
`ParseDefinition` refuses a definition naming an unregistered type at save
|
||||
time, on the validating side the composition root built (the State Store's
|
||||
workflow-definitions resource validates there before anything is stored). The
|
||||
compiler refuses the same definition at run, so a binary handed a definition
|
||||
written against a vocabulary it does not have fails that run loudly instead of
|
||||
silently skipping steps. Both checks live in the Workflow domain against the
|
||||
injected manager, which is why no binary can opt out of the check by
|
||||
substituting its own registry.
|
||||
|
||||
## Relationship between the questions
|
||||
|
||||
`archie-core-ze7y` is the same question seen from the deleted
|
||||
repository-authored stages: those `.archie/stages/*.go` files held arbitrary
|
||||
stages, and their gate half landed as `workflow.diff-rules` settings rather
|
||||
than interpreted Go. Their stage half has no replacement and does not get one
|
||||
that approximates it: no interpreted-Go stage type is built, and no command
|
||||
step type is created by this decision to stand in for them. The refusal of
|
||||
`.archie/stages/*.go` stays until the maintainer's trust decision
|
||||
(`archie-core-ndm8`) says otherwise.
|
||||
|
||||
If that decision ever allows a command step type, it arrives as a provider in
|
||||
the compiled-in set under the rules above — a new contributor of exactly one
|
||||
step type at a named provider. It is not a plugin contribution mechanism, and
|
||||
it does not change any answer in this document.
|
||||
|
||||
## Rejected alternatives
|
||||
|
||||
- **A vocabulary version or hash on the wire.** The executing side already
|
||||
refuses an unknown step type at its first compile, which is the mismatch
|
||||
detector, and it fails closed. A wire field would only narrow the
|
||||
deploy-skew window that a matching deploy closes, at the cost of a new
|
||||
contract field.
|
||||
- **A Yaegi-plugin-to-`StepFactory` bridge.** It would run repository-supplied
|
||||
interpreted code inside the daemon's process with daemon privileges. The
|
||||
trust boundary invariant requires repository-authored code to run in the
|
||||
task container, not in an interpreter embeddable into any binary.
|
||||
- **A package-level process-global registrar.** Global mutable registry state
|
||||
is unreadable at the composition root, collides with itself when one
|
||||
process builds the vocabulary twice, and is what made the first attempt at
|
||||
this question worse instead of better.
|
||||
- **Degrading on an unknown step type.** A run that skips steps it cannot
|
||||
compile would finish green while silently dropping the behaviour the
|
||||
definition asked for; refusal at save and at run is the only honest option.
|
||||
@@ -41,10 +41,11 @@ func runAsHarnessUser(cmd *exec.Cmd, name string) error {
|
||||
}
|
||||
|
||||
// harnessCredential resolves a user name or "uid[:gid]" to a credential.
|
||||
// Root is refused whichever way it is named.
|
||||
// Root is refused whichever way it is named. IDs are bounded to 31 bits so
|
||||
// they convert to int for os.Chown on every platform.
|
||||
func harnessCredential(name string) (*syscall.Credential, error) {
|
||||
uidText, gidText, hasGid := strings.Cut(name, ":")
|
||||
uid, uidErr := strconv.ParseUint(uidText, 10, 32)
|
||||
uid, uidErr := strconv.ParseUint(uidText, 10, 31)
|
||||
var cred syscall.Credential
|
||||
if uidErr == nil {
|
||||
cred.Uid, cred.Gid = uint32(uid), uint32(uid)
|
||||
@@ -53,18 +54,18 @@ func harnessCredential(name string) (*syscall.Credential, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("harness user %q: %w", uidText, err)
|
||||
}
|
||||
id, err := strconv.ParseUint(u.Uid, 10, 32)
|
||||
id, err := strconv.ParseUint(u.Uid, 10, 31)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("harness user %q has non-numeric uid %q", uidText, u.Uid)
|
||||
}
|
||||
group, err := strconv.ParseUint(u.Gid, 10, 32)
|
||||
group, err := strconv.ParseUint(u.Gid, 10, 31)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("harness user %q has non-numeric gid %q", uidText, u.Gid)
|
||||
}
|
||||
cred.Uid, cred.Gid = uint32(id), uint32(group)
|
||||
}
|
||||
if hasGid {
|
||||
gid, err := strconv.ParseUint(gidText, 10, 32)
|
||||
gid, err := strconv.ParseUint(gidText, 10, 31)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("harness group %q is not numeric", gidText)
|
||||
}
|
||||
|
||||
@@ -388,6 +388,8 @@ func TestHarnessUser(t *testing.T) {
|
||||
{"0", 0, 0, true},
|
||||
{"root", 0, 0, true},
|
||||
{"not-a-user-anywhere", 0, 0, true},
|
||||
{"2147483648", 0, 0, true},
|
||||
{"1000:2147483648", 0, 0, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
cred, err := harnessCredential(tt.user)
|
||||
|
||||
@@ -1,272 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/agent"
|
||||
"github.com/samcharles93/ai-sdk/core"
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
"github.com/samcharles93/ai-sdk/toolkit"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
)
|
||||
|
||||
// newReviewerFor builds the workflow.Reviewer for one task run, or nil
|
||||
// when the repo has not opted into review (Repo.ReviewEnabled == false)
|
||||
// or no providers are configured. Model resolution mirrors AgentStage's
|
||||
// own role->"builder" fallback (agent.go): Models["reviewer"], falling
|
||||
// back to Models["builder"].
|
||||
func newReviewerFor(req taskrun.Request) workflow.Reviewer {
|
||||
if !req.Repo.ReviewEnabled {
|
||||
return nil
|
||||
}
|
||||
return NewOperatorReviewer(req.Cfg.Models, req.Providers)
|
||||
}
|
||||
|
||||
// NewOperatorReviewer builds the workflow.Reviewer for an operator-triggered
|
||||
// review, resolved from daemon-level models and providers rather than a task
|
||||
// run. It shares newReviewerFor's role->"builder" model fallback but drops
|
||||
// the Repo.ReviewEnabled gate: the operator asked for the review explicitly,
|
||||
// so "not opted in" is not a reason to refuse. It returns nil when no model
|
||||
// resolves (no reviewer/builder model configured) or no provider runtime
|
||||
// builds, so the caller can report a clear "review not configured" result.
|
||||
func NewOperatorReviewer(models map[string]string, providers map[string]agentexec.Provider) workflow.Reviewer {
|
||||
modelRef := ReviewerModel(models)
|
||||
if modelRef == "" {
|
||||
return nil
|
||||
}
|
||||
rt := agentexec.NewRuntime(providers)
|
||||
if rt == nil {
|
||||
return nil
|
||||
}
|
||||
return newSubagentReviewer(rt, modelRef)
|
||||
}
|
||||
|
||||
// ReviewerModel resolves the reviewer role's model with the builder fallback.
|
||||
// It is the single source of truth for the role->"builder" rule, shared by
|
||||
// the workflow stage (via NewOperatorReviewer/newReviewerFor) and the
|
||||
// operator-triggered review's result reporting so the reported model and the
|
||||
// model actually run cannot diverge.
|
||||
func ReviewerModel(models map[string]string) string {
|
||||
if models["reviewer"] != "" {
|
||||
return models["reviewer"]
|
||||
}
|
||||
return models["builder"]
|
||||
}
|
||||
|
||||
// defaultReviewMaxSteps bounds the reviewer's tool loop when neither
|
||||
// ReviewRequest.MaxSteps nor the repo's configured budget set one.
|
||||
const defaultReviewMaxSteps = 10
|
||||
|
||||
// subagentReviewer implements workflow.Reviewer using ai-sdk's
|
||||
// agent.Subagent: a nested, synchronous generation in this same worker
|
||||
// process, with its own model, system prompt, toolset, and step budget.
|
||||
//
|
||||
// Isolation is two-fold. Conversation isolation is structural: Subagent.Run
|
||||
// only ever sends a prompt string, never the implementer's message
|
||||
// history. Workspace isolation is built by the caller (StageReview via
|
||||
// workflow.Trees.Snapshot): reviewerToolSet is rooted at that snapshot
|
||||
// directory and holds only read-only tools -- never the worker's own
|
||||
// toolset, which carries the worktreerpc publication grant a reviewer must
|
||||
// not be able to reach.
|
||||
type subagentReviewer struct {
|
||||
runtime *runtime.Runtime
|
||||
modelRef string
|
||||
}
|
||||
|
||||
// newSubagentReviewer constructs a Reviewer that runs on modelRef, resolved
|
||||
// through rt (the same provider runtime the worker's own agent runner
|
||||
// uses). rt must be non-nil.
|
||||
func newSubagentReviewer(rt *runtime.Runtime, modelRef string) *subagentReviewer {
|
||||
return &subagentReviewer{runtime: rt, modelRef: modelRef}
|
||||
}
|
||||
|
||||
var _ workflow.Reviewer = (*subagentReviewer)(nil)
|
||||
|
||||
// Review runs one adversarial review. It never returns a Go error: every
|
||||
// failure mode (unresolvable model, a Subagent.Run error, a truncated
|
||||
// run) folds into the returned ReviewReport, per
|
||||
// docs/prds/adversarial-self-review.md section 4's fail-closed contract.
|
||||
func (s *subagentReviewer) Review(ctx context.Context, req workflow.ReviewRequest) workflow.ReviewReport {
|
||||
if s.runtime == nil {
|
||||
return workflow.NewNotRunReviewReport("no provider runtime configured for the reviewer")
|
||||
}
|
||||
provider, model, err := s.runtime.ChatProvider(ctx, s.modelRef)
|
||||
if err != nil {
|
||||
return workflow.NewNotRunReviewReport(fmt.Sprintf("resolve reviewer model %q: %v", s.modelRef, err))
|
||||
}
|
||||
|
||||
var findings []workflow.ReviewFinding
|
||||
var checks []workflow.ReviewCheck
|
||||
tools := reviewerToolSet(req.SnapshotDir, &findings, &checks)
|
||||
|
||||
maxSteps := req.MaxSteps
|
||||
if maxSteps <= 0 {
|
||||
maxSteps = defaultReviewMaxSteps
|
||||
}
|
||||
|
||||
sub := agent.Subagent{
|
||||
Provider: provider,
|
||||
Model: model,
|
||||
System: reviewerSystemPrompt,
|
||||
Tools: tools,
|
||||
MaxSteps: maxSteps,
|
||||
}
|
||||
|
||||
summary, runErr := sub.Run(ctx, reviewerPrompt(req))
|
||||
if runErr != nil {
|
||||
// A truncated or errored run still yields whatever the reviewer
|
||||
// captured before it ran out of budget -- those findings are real
|
||||
// and must not be discarded just because the run's own
|
||||
// conclusion never arrived (docs/prds/adversarial-self-review.md
|
||||
// section 1, "findings return through a closure"). Zero captured
|
||||
// findings on error means the reviewer never got anywhere, which
|
||||
// fail-closed treats as not having run at all.
|
||||
if len(findings) == 0 {
|
||||
return workflow.NewNotRunReviewReport(runErr.Error())
|
||||
}
|
||||
return completedReview(findings, checks, "")
|
||||
}
|
||||
return completedReview(findings, checks, summary)
|
||||
}
|
||||
|
||||
// completedReview builds a completed report carrying the captured findings
|
||||
// and the properties the reviewer verified clean.
|
||||
func completedReview(findings []workflow.ReviewFinding, checks []workflow.ReviewCheck, summary string) workflow.ReviewReport {
|
||||
report := workflow.NewCompletedReviewReport(findings, summary)
|
||||
report.Checked = checks
|
||||
return report
|
||||
}
|
||||
|
||||
// reviewerSystemPrompt instructs the reviewer per CLAUDE.md's own
|
||||
// adversarial-review discipline: assume every line is wrong until proven
|
||||
// correct, work the checklist, report only what a fresh reader can verify
|
||||
// from what it was given.
|
||||
const reviewerSystemPrompt = `You are a fresh adversarial code reviewer. You did not write this change and have no access to how or why it was written -- only what is given to you below.
|
||||
|
||||
Assume every line is wrong until you have verified it is correct. Read whole files with your read tool, not just diff hunks, before concluding a call site or interface is satisfied. Use grep/find to check for other call sites a change affects.
|
||||
|
||||
Check for: dead code, unchecked errors, hardcoded values that should be parameters, interface-satisfaction defects, nil-pointer risk, goroutine leaks, races and unsynchronized shared state.
|
||||
|
||||
For every defect you find, call record_finding with: the file and line, a one-sentence defect statement, a concrete failure scenario (specific inputs or state that produce the wrong output or a crash -- not a hypothetical), a verdict, a level, and a category.
|
||||
|
||||
A finding must describe wrong behaviour or a crash. Style, formatting, naming, and preference nits are out of contract -- do not report them; they are exactly the padding that teaches an operator to skim past a findings list.
|
||||
|
||||
As you clear each checklist property, call record_checked with the property and how you verified it (which files or call sites you read). Record every property you actually checked and found correct, even when you also found defects; a review that reports no findings must still record what it checked, because "I checked and it is fine" and "I did not look" must not read the same.
|
||||
|
||||
Verdict is "confirmed" only when you have traced the actual failure -- read the code paths involved and can state exactly how it goes wrong. Verdict is "plausible" for a real worry you have not fully traced. Only a "confirmed" finding at level "error" blocks the pull request; do not inflate a plausible worry to confirmed/error to make it count -- an unjustified block is worse than a missed one, because it teaches the operator to stop trusting your reports.
|
||||
|
||||
Level is "error" for a defect that blocks; "warn" for something worth knowing but not blocking.
|
||||
|
||||
When a confirmed defect's fix is mechanical, and only then, pass suggestion: the exact text that should replace the anchored line, so the author can apply it in one click. It replaces that line exactly, so include the whole line (indentation included) and nothing else, and never guess -- a wrong one-click fix is worse than none. Do not pass a suggestion for a plausible finding, or for a fix you cannot state as a single line.
|
||||
|
||||
When you have finished checking, reply with a short summary of what you checked and what you found (or that you found nothing). If you find nothing, say so plainly -- reporting zero findings on properties you actually checked is a valid and expected outcome, not a failure to find something.`
|
||||
|
||||
// reviewerPrompt renders the reviewer's mission: the diff and issue text.
|
||||
// The snapshot itself is not embedded here -- it reaches the reviewer only
|
||||
// through its read-only toolset, rooted at SnapshotDir, never as prompt
|
||||
// text the reviewer could mistake for something it already checked.
|
||||
func reviewerPrompt(req workflow.ReviewRequest) string {
|
||||
var b strings.Builder
|
||||
b.WriteString("Review the following change. The full file tree at the reviewed commit is available through your tools; ")
|
||||
b.WriteString("start by reading the files the diff touches, not just the diff itself.\n\n")
|
||||
b.WriteString("<issue>\n")
|
||||
b.WriteString(req.IssueText)
|
||||
b.WriteString("\n</issue>\n\n<diff>\n")
|
||||
b.WriteString(req.Diff)
|
||||
b.WriteString("\n</diff>\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// reviewerToolSet builds the reviewer's read-only toolset, rooted at
|
||||
// snapshotDir, plus the structured capture tools that append directly to
|
||||
// findings and checks. This is a distinct toolset built fresh for each
|
||||
// review -- never the worker's own registry, which holds write/edit/shell
|
||||
// tools and the worktreerpc publication grant.
|
||||
func reviewerToolSet(snapshotDir string, findings *[]workflow.ReviewFinding, checks *[]workflow.ReviewCheck) core.ToolSet {
|
||||
reg := toolkit.NewRegistry()
|
||||
readOnly := []toolkit.Tool{
|
||||
toolkit.NewReadTool(snapshotDir, toolkit.NewReadTracker()),
|
||||
toolkit.NewGrepTool(snapshotDir),
|
||||
toolkit.NewFindTool(snapshotDir),
|
||||
}
|
||||
for _, tool := range readOnly {
|
||||
_ = reg.Register(tool) // names are fixed and distinct; Register cannot fail here
|
||||
}
|
||||
set := reg.CoreToolSet(toolkit.NonInteractiveBridge{})
|
||||
set["record_finding"] = recordFindingTool(findings)
|
||||
set["record_checked"] = recordCheckedTool(checks)
|
||||
return set
|
||||
}
|
||||
|
||||
// checkInput is the reviewer-facing shape of workflow.ReviewCheck.
|
||||
type checkInput struct {
|
||||
Property string `json:"property" jsonschema:"description=The property or code path you verified clean, e.g. 'nil-safety of Foo callers'."`
|
||||
Evidence string `json:"evidence" jsonschema:"description=How you verified it, e.g. 'read all 4 callers; each nil-checks before use'."`
|
||||
}
|
||||
|
||||
// recordCheckedTool builds the typed capture tool the reviewer calls once per
|
||||
// property it verified clean. Without it a zero-finding review reads the same
|
||||
// as a review that never looked; with it, "ran and found nothing" arrives
|
||||
// backed by what was actually checked.
|
||||
func recordCheckedTool(checks *[]workflow.ReviewCheck) *core.Tool {
|
||||
return core.NewTypedTool(
|
||||
"record_checked",
|
||||
"Record one property or code path you verified clean. Call this once per property you actually checked and found correct -- a review that reports no findings must still record what it checked.",
|
||||
func(_ context.Context, in checkInput) (string, error) {
|
||||
check := workflow.ReviewCheck{Property: in.Property, Evidence: in.Evidence}
|
||||
if err := check.Validate(); err != nil {
|
||||
return "record_checked rejected: " + err.Error(), nil //nolint:nilerr // rejection feedback lets the model retry with a valid check
|
||||
}
|
||||
*checks = append(*checks, check)
|
||||
return "check recorded", nil
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// findingInput is the reviewer-facing shape of workflow.ReviewFinding: the
|
||||
// model reports plain strings for Verdict/Level/Category, validated and
|
||||
// converted before being appended.
|
||||
type findingInput struct {
|
||||
File string `json:"file" jsonschema:"description=Repo-relative file path where the defect is located."`
|
||||
Line int `json:"line" jsonschema:"description=Line number where the defect is located."`
|
||||
Defect string `json:"defect" jsonschema:"description=One-sentence statement of the defect."`
|
||||
FailureScenario string `json:"failure_scenario" jsonschema:"description=Concrete inputs or state that produce the wrong output or a crash -- not a hypothetical."`
|
||||
Suggestion string `json:"suggestion,omitempty" jsonschema:"description=Optional. The exact replacement for the anchored line, when the fix is mechanical and you are certain of it -- it is offered as a one-click apply, so an approximate or partial line is worse than none. Only a confirmed finding may carry one; omit it for a plausible finding. Single line only."`
|
||||
Verdict string `json:"verdict" jsonschema:"description=Only 'confirmed' may block. Use 'plausible' for a real worry you have not fully traced.,enum=confirmed|plausible"`
|
||||
Level string `json:"level" jsonschema:"description=error blocks when confirmed; warn is advisory only.,enum=error|warn"`
|
||||
Category string `json:"category" jsonschema:"enum=dead-code|unchecked-error|hardcoded-value|interface-satisfaction|nil-risk|goroutine-leak|race|other"`
|
||||
}
|
||||
|
||||
// recordFindingTool builds the typed capture tool the reviewer must call
|
||||
// to report a defect. Rejecting an invalid finding with a plain-text
|
||||
// message (rather than a Go error) lets the model see what was wrong and
|
||||
// retry, the same environmental-enforcement pattern the rest of the
|
||||
// agent-loop tool contract uses.
|
||||
func recordFindingTool(findings *[]workflow.ReviewFinding) *core.Tool {
|
||||
return core.NewTypedTool(
|
||||
"record_finding",
|
||||
"Report one defect found during review. Call this once per defect; do not summarize multiple defects into one call.",
|
||||
func(_ context.Context, in findingInput) (string, error) {
|
||||
finding := workflow.ReviewFinding{
|
||||
File: in.File,
|
||||
Line: in.Line,
|
||||
Defect: in.Defect,
|
||||
FailureScenario: in.FailureScenario,
|
||||
Suggestion: in.Suggestion,
|
||||
Verdict: workflow.ReviewVerdict(in.Verdict),
|
||||
Level: workflow.ReviewLevel(in.Level),
|
||||
Category: workflow.ReviewCategory(in.Category),
|
||||
}
|
||||
if err := finding.Validate(); err != nil {
|
||||
return "record_finding rejected: " + err.Error(), nil //nolint:nilerr // rejection feedback lets the model retry with a valid finding
|
||||
}
|
||||
*findings = append(*findings, finding)
|
||||
return "finding recorded", nil
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
package agentworker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/agent"
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
// TestReviewerToolSetIsReadOnlyAndHasNoMutationPath asserts, as a
|
||||
// construction fact rather than a prompt claim, that the reviewer's
|
||||
// toolset carries no tool capable of writing, editing, or running a
|
||||
// shell command -- the class of tool that could reach the worktreerpc
|
||||
// publication grant or otherwise mutate anything. Read/grep/find plus the
|
||||
// findings-capture tool are the entire surface.
|
||||
func TestReviewerToolSetIsReadOnlyAndHasNoMutationPath(t *testing.T) {
|
||||
var findings []workflow.ReviewFinding
|
||||
var checks []workflow.ReviewCheck
|
||||
set := reviewerToolSet(t.TempDir(), &findings, &checks)
|
||||
|
||||
names := make([]string, 0, len(set))
|
||||
for name := range set {
|
||||
names = append(names, name)
|
||||
}
|
||||
slices.Sort(names)
|
||||
|
||||
want := []string{"find", "grep", "read", "record_checked", "record_finding"}
|
||||
slices.Sort(want)
|
||||
if !slices.Equal(names, want) {
|
||||
t.Fatalf("reviewer toolset = %v, want exactly %v (no write/edit/shell)", names, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReviewerToolSetIsRootedAtTheGivenSnapshot asserts the read tool
|
||||
// cannot read outside the snapshot directory it was constructed with --
|
||||
// it has no path back to the implementer's actual worktree.
|
||||
func TestReviewerToolSetIsRootedAtTheGivenSnapshot(t *testing.T) {
|
||||
snapshot := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(snapshot, "in-snapshot.txt"), []byte("ok\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outside := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(outside, "secret.txt"), []byte("nope\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var findings []workflow.ReviewFinding
|
||||
var checks []workflow.ReviewCheck
|
||||
set := reviewerToolSet(snapshot, &findings, &checks)
|
||||
readTool := set["read"]
|
||||
if readTool == nil {
|
||||
t.Fatal("reviewer toolset has no read tool")
|
||||
}
|
||||
|
||||
out, err := readTool.Execute(t.Context(), `{"path":"in-snapshot.txt"}`)
|
||||
if err != nil {
|
||||
t.Fatalf("read in-snapshot file: %v", err)
|
||||
}
|
||||
if !containsSubstr(out, "ok") {
|
||||
t.Errorf("read in-snapshot file = %q, want it to contain the file's content", out)
|
||||
}
|
||||
|
||||
// Tool failures are encoded in-band in the returned content, not as a
|
||||
// Go error (toolkit.Registry.CoreToolSet's own contract) -- an escape
|
||||
// attempt must reject there, not succeed.
|
||||
escapeOut, err := readTool.Execute(t.Context(), `{"path":"`+filepath.Join(outside, "secret.txt")+`"}`)
|
||||
if err != nil {
|
||||
t.Fatalf("read outside-snapshot path: %v", err)
|
||||
}
|
||||
if containsSubstr(escapeOut, "nope") {
|
||||
t.Errorf("read tool returned content from outside the snapshot: %q", escapeOut)
|
||||
}
|
||||
if !containsSubstr(escapeOut, "escapes") {
|
||||
t.Errorf("read tool output = %q, want a path-confinement rejection", escapeOut)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordFindingToolAppendsToCapturedSlice asserts the capture-tool
|
||||
// contract: findings are recorded via the closure over the findings
|
||||
// slice, not returned from Subagent.Run's text.
|
||||
func TestRecordFindingToolAppendsToCapturedSlice(t *testing.T) {
|
||||
var findings []workflow.ReviewFinding
|
||||
tool := recordFindingTool(&findings)
|
||||
|
||||
input := `{"file":"main.go","line":10,"defect":"nil deref","failure_scenario":"calling Foo(nil) panics","verdict":"confirmed","level":"error","category":"nil-risk"}`
|
||||
if _, err := tool.Execute(t.Context(), input); err != nil {
|
||||
t.Fatalf("record_finding: %v", err)
|
||||
}
|
||||
if len(findings) != 1 {
|
||||
t.Fatalf("captured %d findings, want 1", len(findings))
|
||||
}
|
||||
if !findings[0].Blocking() {
|
||||
t.Error("captured finding is not blocking, want confirmed+error to block")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordFindingToolRejectsInvalidVerdictWithoutError asserts an
|
||||
// invalid finding is rejected in-band (so the model can retry) rather
|
||||
// than surfacing as a hard tool error, and is not captured.
|
||||
func TestRecordFindingToolRejectsInvalidVerdictWithoutError(t *testing.T) {
|
||||
var findings []workflow.ReviewFinding
|
||||
tool := recordFindingTool(&findings)
|
||||
|
||||
input := `{"file":"main.go","line":1,"defect":"x","failure_scenario":"y","verdict":"maybe","level":"error","category":"other"}`
|
||||
out, err := tool.Execute(t.Context(), input)
|
||||
if err != nil {
|
||||
t.Fatalf("record_finding returned a Go error for invalid input: %v", err)
|
||||
}
|
||||
if !containsSubstr(out, "rejected") {
|
||||
t.Errorf("record_finding output = %q, want a rejection message", out)
|
||||
}
|
||||
if len(findings) != 0 {
|
||||
t.Errorf("captured %d findings, want 0 for an invalid finding", len(findings))
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordCheckedToolAppendsToCapturedSlice asserts the calibration capture
|
||||
// contract: a cleared property is recorded through the closure, so a
|
||||
// zero-finding review can report what it actually checked.
|
||||
func TestRecordCheckedToolAppendsToCapturedSlice(t *testing.T) {
|
||||
var checks []workflow.ReviewCheck
|
||||
tool := recordCheckedTool(&checks)
|
||||
|
||||
input := `{"property":"nil-safety of Foo callers","evidence":"read all 4 callers; each nil-checks"}`
|
||||
if _, err := tool.Execute(t.Context(), input); err != nil {
|
||||
t.Fatalf("record_checked: %v", err)
|
||||
}
|
||||
if len(checks) != 1 || checks[0].Property != "nil-safety of Foo callers" {
|
||||
t.Fatalf("captured checks = %+v, want one check for the recorded property", checks)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordCheckedToolRejectsMissingEvidence asserts a check without evidence
|
||||
// is rejected in-band and not captured, so "verified clean" cannot be recorded
|
||||
// as a bare assertion.
|
||||
func TestRecordCheckedToolRejectsMissingEvidence(t *testing.T) {
|
||||
var checks []workflow.ReviewCheck
|
||||
tool := recordCheckedTool(&checks)
|
||||
|
||||
out, err := tool.Execute(t.Context(), `{"property":"looks fine","evidence":""}`)
|
||||
if err != nil {
|
||||
t.Fatalf("record_checked returned a Go error for invalid input: %v", err)
|
||||
}
|
||||
if !containsSubstr(out, "rejected") {
|
||||
t.Errorf("record_checked output = %q, want a rejection message", out)
|
||||
}
|
||||
if len(checks) != 0 {
|
||||
t.Errorf("captured %d checks, want 0 for a check with no evidence", len(checks))
|
||||
}
|
||||
}
|
||||
|
||||
// TestCompletedReviewCarriesChecks asserts the report the reviewer returns
|
||||
// carries the captured checks, not just the findings.
|
||||
func TestCompletedReviewCarriesChecks(t *testing.T) {
|
||||
checks := []workflow.ReviewCheck{{Property: "p", Evidence: "e"}}
|
||||
report := completedReview(nil, checks, "summary")
|
||||
if !report.Ran() {
|
||||
t.Fatal("completedReview report did not run")
|
||||
}
|
||||
if len(report.Checked) != 1 || report.Checked[0].Property != "p" {
|
||||
t.Fatalf("report.Checked = %+v, want the captured check", report.Checked)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReviewSubagentConstructionNeverSendsConversationHistory asserts, at
|
||||
// the exact agent.Subagent construction Review performs, that only a
|
||||
// prompt string reaches the model. This exercises the same Subagent{}
|
||||
// shape subagentReviewer.Review builds (provider, model, system prompt,
|
||||
// reviewerToolSet, MaxSteps) directly against a fake chat.Provider, so it
|
||||
// proves the construction fact without needing a full *runtime.Runtime:
|
||||
// Subagent.Run populates GenerateOptions.Prompt and never Messages, so
|
||||
// there is no code path for the implementer's transcript to travel
|
||||
// through.
|
||||
func TestReviewSubagentConstructionNeverSendsConversationHistory(t *testing.T) {
|
||||
captured := &capturingChatProvider{}
|
||||
var findings []workflow.ReviewFinding
|
||||
var checks []workflow.ReviewCheck
|
||||
req := workflow.ReviewRequest{
|
||||
SnapshotDir: t.TempDir(),
|
||||
Diff: "diff --git a/x.go b/x.go\n",
|
||||
IssueText: "some issue text",
|
||||
}
|
||||
|
||||
sub := agent.Subagent{
|
||||
Provider: captured,
|
||||
Model: "fake-model",
|
||||
System: reviewerSystemPrompt,
|
||||
Tools: reviewerToolSet(req.SnapshotDir, &findings, &checks),
|
||||
MaxSteps: defaultReviewMaxSteps,
|
||||
}
|
||||
prompt := reviewerPrompt(req)
|
||||
if _, err := sub.Run(t.Context(), prompt); err != nil {
|
||||
t.Fatalf("Subagent.Run() error = %v", err)
|
||||
}
|
||||
|
||||
if captured.lastRequest == nil {
|
||||
t.Fatal("chat provider was never called")
|
||||
}
|
||||
// The only non-system message the model ever sees is the one
|
||||
// Subagent.Run derives from the prompt string -- there is no code
|
||||
// path here for a second, implementer-authored message to arrive
|
||||
// alongside it.
|
||||
var userMessages int
|
||||
for _, m := range captured.lastRequest.Messages {
|
||||
if m.Role == chat.RoleUser {
|
||||
userMessages++
|
||||
if m.Content != prompt {
|
||||
t.Errorf("user message content = %q, want the review prompt %q", m.Content, prompt)
|
||||
}
|
||||
}
|
||||
}
|
||||
if userMessages != 1 {
|
||||
t.Errorf("chat.Request carried %d user messages, want exactly 1 (the review prompt, no implementer history)", userMessages)
|
||||
}
|
||||
}
|
||||
|
||||
func containsSubstr(s, substr string) bool {
|
||||
return len(substr) == 0 ||
|
||||
(len(s) >= len(substr) && func() bool {
|
||||
for i := 0; i+len(substr) <= len(s); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}())
|
||||
}
|
||||
|
||||
// capturingChatProvider is a minimal chat.Provider fake that records the
|
||||
// last chat.Request it received and returns a fixed, valid completion.
|
||||
type capturingChatProvider struct {
|
||||
lastRequest *chat.Request
|
||||
}
|
||||
|
||||
func (c *capturingChatProvider) Name() string { return "fake" }
|
||||
|
||||
func (c *capturingChatProvider) Chat(_ context.Context, req chat.Request) (chat.Response, error) {
|
||||
r := req
|
||||
c.lastRequest = &r
|
||||
return chat.Response{Content: "no findings", FinishReason: "stop"}, nil
|
||||
}
|
||||
|
||||
func (c *capturingChatProvider) ChatStream(_ context.Context, req chat.Request) (chat.Stream, error) {
|
||||
return nil, errors.New("not implemented")
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/prsource"
|
||||
"github.com/samcharles93/archie-core/internal/installtype"
|
||||
"github.com/samcharles93/archie-core/internal/storage"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
@@ -217,12 +218,11 @@ func applyToolLimits(agent agentexec.Runner, policy config.ToolPolicy, allow []s
|
||||
runner.AllowTools = allow
|
||||
}
|
||||
|
||||
// stageRunners builds the runner every agent stage uses, and the reviewer.
|
||||
func stageRunners(req taskrun.Request, mcpSet *mcpProviderSet, newRunner runnerFactory, log *slog.Logger) (agentexec.Runner, workflow.Reviewer, error) {
|
||||
// stageRunners builds the runner every agent stage uses.
|
||||
func stageRunners(req taskrun.Request, mcpSet *mcpProviderSet, newRunner runnerFactory, log *slog.Logger) (agentexec.Runner, error) {
|
||||
if req.Harness != nil {
|
||||
// The built-in loop has no route to a model from a Kit container, so
|
||||
// the review stage parks rather than running on it.
|
||||
return agentexec.HarnessStages{Runner: agentexec.NewHarnessRunner(nil), Spec: *req.Harness}, nil, nil
|
||||
// The built-in loop has no route to a model from a Kit container.
|
||||
return agentexec.HarnessStages{Runner: agentexec.NewHarnessRunner(nil), Spec: *req.Harness}, nil
|
||||
}
|
||||
var agent agentexec.Runner
|
||||
if mcpSet != nil && mcpSet.registry != nil {
|
||||
@@ -231,10 +231,10 @@ func stageRunners(req taskrun.Request, mcpSet *mcpProviderSet, newRunner runnerF
|
||||
agent = newRunner(req.Providers, log)
|
||||
}
|
||||
if agent == nil {
|
||||
return nil, nil, fmt.Errorf("no agent runner configured for task %d", req.Task.ID)
|
||||
return nil, fmt.Errorf("no agent runner configured for task %d", req.Task.ID)
|
||||
}
|
||||
applyToolLimits(agent, req.Cfg.ToolPolicy, req.Tools)
|
||||
return agent, newReviewerFor(req), nil
|
||||
return agent, nil
|
||||
}
|
||||
|
||||
// routeTask remains available for routing-only callers. Production execution
|
||||
@@ -286,7 +286,7 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen
|
||||
log.Warn("mcp providers had errors, continuing with available tools", "err", mcpErr)
|
||||
}
|
||||
|
||||
agent, reviewer, err := stageRunners(req, mcpSet, newRunner, log)
|
||||
agent, err := stageRunners(req, mcpSet, newRunner, log)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -310,18 +310,27 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen
|
||||
}
|
||||
|
||||
tc := &workflow.TaskContext{
|
||||
Task: req.Task,
|
||||
Repo: req.Repo,
|
||||
Cfg: req.Cfg.ToConfig(),
|
||||
Forge: dependencies.forge,
|
||||
Store: dependencies.store,
|
||||
Calls: dependencies.calls,
|
||||
Trees: trees,
|
||||
Agent: agent,
|
||||
Reviewer: reviewer,
|
||||
Bus: bus,
|
||||
Log: log,
|
||||
Task: req.Task,
|
||||
Repo: req.Repo,
|
||||
Cfg: req.Cfg.ToConfig(),
|
||||
Forge: dependencies.forge,
|
||||
Store: dependencies.store,
|
||||
Calls: dependencies.calls,
|
||||
Trees: trees,
|
||||
Agent: agent,
|
||||
Bus: bus,
|
||||
Log: log,
|
||||
}
|
||||
// pr-review reads an external pull request's data from workDir, which the
|
||||
// daemon already populated before this task started (daemon's
|
||||
// prefetchPRReview, writing under workDir/.archie-pr-review -- the same
|
||||
// host directory Docker bind-mounts at storage.WorktreeMountDir) -- never
|
||||
// over the network, and never with a forge credential in this process.
|
||||
// See docs/development/agent.md, "Giving the agent something new".
|
||||
if req.Task.Workflow == "pr-review" {
|
||||
tc.PRSource = prsource.NewFromMount(filepath.Join(workDir, prsource.PrefetchDirName))
|
||||
}
|
||||
|
||||
if req.Repo.PersistentStorage {
|
||||
memory, readErr := readProjectMemory(storage.MemoryPath)
|
||||
if readErr != nil {
|
||||
|
||||
@@ -60,7 +60,7 @@ func TestExecuteTaskRequestStartsWorkflowCallCallee(t *testing.T) {
|
||||
const callerYAML = "id: caller\nrepository: none\ninputs:\n src_ip: {type: string}\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n inputs: {src_ip: \"inputs.src_ip\"}\n wait: false\n - type: agent.run\n settings:\n mission: report\n"
|
||||
// A real caller row, claimed and running, so the store's enqueue reads
|
||||
// the same row shape production does.
|
||||
task, err := st.EnqueueChatTask(ctx, "", "", "workflow.call integration", "", "caller", "")
|
||||
task, err := st.EnqueueChatTask(ctx, "", "", "workflow.call integration", "", "caller", "", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("seed caller task: %v", err)
|
||||
}
|
||||
|
||||
@@ -238,15 +238,11 @@ type boot struct {
|
||||
// unrelated call.
|
||||
embeddings domainembedding.Client
|
||||
|
||||
toolReg *tools.Registry
|
||||
chatModels *chatModelManager
|
||||
personas *gateway.PersonaRegistry
|
||||
chatTasks gateway.TaskCreator
|
||||
chatController *gateway.StoreTaskController
|
||||
// chatPRReviewer is the operator-triggered PR review capability, built
|
||||
// once and shared by every channel so a review in flight on one channel
|
||||
// is deduplicated against the same request on another (single-flight).
|
||||
chatPRReviewer gateway.ChatPRReviewer
|
||||
toolReg *tools.Registry
|
||||
chatModels *chatModelManager
|
||||
personas *gateway.PersonaRegistry
|
||||
chatTasks gateway.TaskCreator
|
||||
chatController *gateway.StoreTaskController
|
||||
defaultChatIdentity string
|
||||
updateService *releaseupdate.Service
|
||||
|
||||
@@ -930,10 +926,10 @@ func (b *boot) loadPlugins() error {
|
||||
|
||||
// buildWorktreeManager composes the process-wide worktree manager from the
|
||||
// resolved primary forge credential and the loaded config. Both process roots
|
||||
// own one: the daemon works tasks in it, and the Gateway materialises a pull
|
||||
// request head in it when an operator asks for a review (boot.prReviewer
|
||||
// refuses to build a reviewer without one, so a Gateway that skips this step
|
||||
// advertises no review_pr). It reads only, so it has nothing to report.
|
||||
// own one: the daemon works tasks in it, and the Gateway used it to
|
||||
// materialise a pull request head for the now-removed synchronous
|
||||
// operator-review path (archie-core-afbk.7). It reads only, so it has
|
||||
// nothing to report.
|
||||
//
|
||||
// Identity managers are not built here: buildTreesAndIdentities builds one per
|
||||
// identity, each in its own WorkDir, because the Gateway must not own daemon
|
||||
@@ -1412,6 +1408,7 @@ func (b *boot) buildDaemon() {
|
||||
KindWorkflows: b.kindWorkflows,
|
||||
LabelWorkflows: b.labelWorkflows,
|
||||
WorkflowDefinitions: b.workflowDefinitions,
|
||||
WorkflowEnablement: b.controlPlane,
|
||||
Playbooks: b.playbooks,
|
||||
}
|
||||
if identities, ok := b.stateStore.(identity.Repository); ok {
|
||||
|
||||
@@ -41,7 +41,6 @@ type chatSetup struct {
|
||||
ChatTaskLister gateway.ChatTaskLister
|
||||
ChatTaskLogs gateway.ChatTaskLogReader
|
||||
ChatTaskActor gateway.ChatTaskActor
|
||||
ChatPRReviewer gateway.ChatPRReviewer
|
||||
DefaultChatIdentity string
|
||||
// Bus carries primary-input events (archie-core-035): a completed
|
||||
// chat turn is published here so input-driven curators can wake. Nil
|
||||
@@ -182,7 +181,6 @@ func newChatTurnRunner(
|
||||
TaskLogs: s.ChatTaskLogs,
|
||||
TaskActor: s.ChatTaskActor,
|
||||
TaskIdentity: s.DefaultChatIdentity,
|
||||
PRReviewer: s.ChatPRReviewer,
|
||||
Bus: s.Bus,
|
||||
BotUser: cfg.BotUser,
|
||||
Channel: channel,
|
||||
|
||||
@@ -100,6 +100,80 @@ func (m *preparedChatTurnModel) ToolSummaries() []gateway.ToolSummary {
|
||||
return append([]gateway.ToolSummary(nil), m.toolInfo...)
|
||||
}
|
||||
|
||||
// buildTurnMessages maps the gateway's compressed history onto ai-sdk chat
|
||||
// messages. The turn's inbound media is not part of stored history, so it
|
||||
// is merged here into the final user message as content parts: the model
|
||||
// sees the caption text plus each attachment's bytes (or URL), exactly for
|
||||
// the turn it arrived in.
|
||||
func buildTurnMessages(request gateway.TurnModelRequest) []chat.Message {
|
||||
messages := make([]chat.Message, len(request.Messages))
|
||||
for i, message := range request.Messages {
|
||||
role := chat.RoleUser
|
||||
switch message.Role {
|
||||
case "assistant":
|
||||
role = chat.RoleAssistant
|
||||
case "system":
|
||||
role = chat.RoleSystem
|
||||
}
|
||||
messages[i] = chat.Message{Role: role, Content: message.Content}
|
||||
}
|
||||
parts := mediaParts(request.Media)
|
||||
if len(parts) == 0 {
|
||||
return messages
|
||||
}
|
||||
last := len(messages) - 1
|
||||
// The media belongs to the inbound message, which is always the final
|
||||
// user entry; if the view ever ends differently, content stays intact
|
||||
// over silently attaching parts to an unrelated message.
|
||||
if last < 0 || messages[last].Role != chat.RoleUser {
|
||||
return messages
|
||||
}
|
||||
userMessages := messages[last]
|
||||
userMessages.Parts = append(chat.Parts{chat.TextPart{Text: userMessages.Content}}, parts...)
|
||||
userMessages.Content = ""
|
||||
messages[last] = userMessages
|
||||
return messages
|
||||
}
|
||||
|
||||
// mediaParts converts inbound media attachments into ai-sdk content
|
||||
// parts: images get ImagePart, everything else FilePart. An attachment
|
||||
// carrying neither bytes nor a URL names nothing consumable and is
|
||||
// dropped -- the turn's text still reaches the model.
|
||||
func mediaParts(media []gateway.MediaAttachment) []chat.Part {
|
||||
if len(media) == 0 {
|
||||
return nil
|
||||
}
|
||||
parts := make([]chat.Part, 0, len(media))
|
||||
for _, att := range media {
|
||||
if att.Type == "image" {
|
||||
switch {
|
||||
case len(att.Data) > 0 && att.MIMEType != "":
|
||||
parts = append(parts, chat.ImagePart{Data: att.Data, MediaType: att.MIMEType})
|
||||
case att.URL != "":
|
||||
parts = append(parts, chat.ImagePart{URL: att.URL})
|
||||
}
|
||||
continue
|
||||
}
|
||||
part := chat.FilePart{Name: att.FileName, MediaType: att.MIMEType}
|
||||
if len(att.Data) > 0 {
|
||||
part.Data = att.Data
|
||||
} else {
|
||||
part.URL = att.URL
|
||||
}
|
||||
if len(part.Data) == 0 && part.URL == "" {
|
||||
continue
|
||||
}
|
||||
if part.MediaType == "" {
|
||||
part.MediaType = "application/octet-stream"
|
||||
}
|
||||
parts = append(parts, part)
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return nil
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
func (m *preparedChatTurnModel) ToolSchemaTokens() int {
|
||||
return m.toolTokens
|
||||
}
|
||||
@@ -110,17 +184,7 @@ func (m *preparedChatTurnModel) Generate(
|
||||
stream gateway.TurnStream,
|
||||
) (string, error) {
|
||||
options := m.options
|
||||
options.Messages = make([]chat.Message, len(request.Messages))
|
||||
for i, message := range request.Messages {
|
||||
role := chat.RoleUser
|
||||
switch message.Role {
|
||||
case "assistant":
|
||||
role = chat.RoleAssistant
|
||||
case "system":
|
||||
role = chat.RoleSystem
|
||||
}
|
||||
options.Messages[i] = chat.Message{Role: role, Content: message.Content}
|
||||
}
|
||||
options.Messages = buildTurnMessages(request)
|
||||
// This is one provider response's output allowance, not a turn-
|
||||
// continuation budget. Tool loops remain free to continue.
|
||||
options.MaxTokens = request.MaxOutputTokens
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
// TestBuildTurnMessagesAttachesMediaPartsToTheFinalUserMessage: inbound
|
||||
// media only reaches the model when the turn's request is turned into
|
||||
// message parts; the attachment belongs on the message the user just sent.
|
||||
func TestBuildTurnMessagesAttachesMediaPartsToTheFinalUserMessage(t *testing.T) {
|
||||
request := gateway.TurnModelRequest{
|
||||
Messages: []gateway.CompressedMessage{
|
||||
{Role: "system", Content: "sys"},
|
||||
{Role: "user", Content: "what is this?"},
|
||||
},
|
||||
Media: []gateway.MediaAttachment{
|
||||
{Type: "image", MIMEType: "image/png", Data: []byte("png-bytes")},
|
||||
{Type: "image", URL: "https://example.invalid/pic.jpg"},
|
||||
{Type: "document", MIMEType: "application/pdf", FileName: "report.pdf", Data: []byte("pdf-bytes")},
|
||||
},
|
||||
}
|
||||
|
||||
messages := buildTurnMessages(request)
|
||||
if len(messages) != 2 {
|
||||
t.Fatalf("messages = %d, want 2", len(messages))
|
||||
}
|
||||
if messages[0].Content != "sys" || len(messages[0].Parts) != 0 {
|
||||
t.Errorf("system message = %#v, want plain content and no parts", messages[0])
|
||||
}
|
||||
if messages[1].Content != "" {
|
||||
t.Errorf("user content = %q, want it moved into a text part", messages[1].Content)
|
||||
}
|
||||
parts := messages[1].Parts
|
||||
if len(parts) != 4 {
|
||||
t.Fatalf("user parts = %d, want text plus three media parts: %#v", len(parts), parts)
|
||||
}
|
||||
if text, ok := parts[0].(chat.TextPart); !ok || text.Text != "what is this?" {
|
||||
t.Errorf("part 0 = %#v, want the caption text", parts[0])
|
||||
}
|
||||
image, ok := parts[1].(chat.ImagePart)
|
||||
if !ok || string(image.Data) != "png-bytes" || image.MediaType != "image/png" {
|
||||
t.Errorf("part 1 = %#v, want an image part carrying the png bytes", parts[1])
|
||||
}
|
||||
linked, ok := parts[2].(chat.ImagePart)
|
||||
if !ok || linked.URL != "https://example.invalid/pic.jpg" {
|
||||
t.Errorf("part 2 = %#v, want an image part pointing at the URL", parts[2])
|
||||
}
|
||||
file, ok := parts[3].(chat.FilePart)
|
||||
if !ok {
|
||||
t.Fatalf("part 3 = %#v, want a file part", parts[3])
|
||||
}
|
||||
if string(file.Data) != "pdf-bytes" || file.MediaType != "application/pdf" || file.Name != "report.pdf" {
|
||||
t.Errorf("file part = %#v, want the pdf bytes with type and name", file)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildTurnMessagesSkipsUndeliverableMedia: an attachment carrying
|
||||
// neither bytes nor a URL names nothing the model can consume, so it must
|
||||
// be dropped rather than sent as an empty part.
|
||||
func TestBuildTurnMessagesSkipsUndeliverableMedia(t *testing.T) {
|
||||
request := gateway.TurnModelRequest{
|
||||
Messages: []gateway.CompressedMessage{
|
||||
{Role: "user", Content: "look"},
|
||||
},
|
||||
Media: []gateway.MediaAttachment{
|
||||
{Type: "video"},
|
||||
{Type: "image", MIMEType: "image/png", Data: []byte("png")},
|
||||
},
|
||||
}
|
||||
messages := buildTurnMessages(request)
|
||||
fileSeen := false
|
||||
for _, p := range messages[0].Parts {
|
||||
if _, ok := p.(chat.FilePart); ok {
|
||||
fileSeen = true
|
||||
}
|
||||
}
|
||||
if fileSeen {
|
||||
t.Errorf("parts = %#v, want the empty attachment dropped", messages[0].Parts)
|
||||
}
|
||||
if len(messages[0].Parts) != 2 {
|
||||
t.Fatalf("user parts = %d, want text plus the one deliverable image", len(messages[0].Parts))
|
||||
}
|
||||
if text, ok := messages[0].Parts[0].(chat.TextPart); !ok || text.Text != "look" {
|
||||
t.Errorf("part 0 = %#v, want the text part", messages[0].Parts[0])
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildTurnMessagesWithoutMediaKeepsPlainContent is the regression
|
||||
// guard for the overwhelmingly common case: text-only turns stay exactly as
|
||||
// they were, with Content and no parts.
|
||||
func TestBuildTurnMessagesWithoutMediaKeepsPlainContent(t *testing.T) {
|
||||
request := gateway.TurnModelRequest{
|
||||
Messages: []gateway.CompressedMessage{
|
||||
{Role: "system", Content: "sys"},
|
||||
{Role: "user", Content: "plain"},
|
||||
{Role: "assistant", Content: "reply"},
|
||||
},
|
||||
}
|
||||
messages := buildTurnMessages(request)
|
||||
for i, want := range []struct {
|
||||
role chat.Role
|
||||
content string
|
||||
}{
|
||||
{chat.RoleSystem, "sys"},
|
||||
{chat.RoleUser, "plain"},
|
||||
{chat.RoleAssistant, "reply"},
|
||||
} {
|
||||
if messages[i].Content != want.content || messages[i].Parts != nil {
|
||||
t.Errorf("message %d = %#v, want content %q and no parts", i, messages[i], want.content)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,29 +32,3 @@ func TestStartGatewayRuntimeSetsUpMemoryBeforeGatewayChat(t *testing.T) {
|
||||
t.Fatal("startGatewayRuntime wires setupGatewayChat before setupMemoryEngine; the turn runner would capture a nil memory engine")
|
||||
}
|
||||
}
|
||||
|
||||
// TestStartGatewayRuntimeBuildsWorktreeManagerBeforeGatewayChat pins the
|
||||
// Gateway's own worktree-manager ordering. The Gateway owns PR review, so
|
||||
// startGatewayRuntime must compose the process-wide worktree manager before
|
||||
// setupGatewayChat resolves boot.prReviewer: prReviewer returns nil without a
|
||||
// manager, and a nil reviewer omits review_pr from every channel's tool set
|
||||
// (internal/gateway/review_tools.go). The Gateway deliberately does not call
|
||||
// buildTreesAndIdentities -- that also registers daemon identity runners it
|
||||
// must not own -- so nothing at runtime connects the manager to this
|
||||
// composition phase except the call this asserts on.
|
||||
func TestStartGatewayRuntimeBuildsWorktreeManagerBeforeGatewayChat(t *testing.T) {
|
||||
fileset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fileset, "gateway.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run := methodBody(t, file, "startGatewayRuntime")
|
||||
trees := methodCallPosition(run, "buildWorktreeManager")
|
||||
chat := methodCallPosition(run, "setupGatewayChat")
|
||||
if trees == token.NoPos || chat == token.NoPos {
|
||||
t.Fatalf("startGatewayRuntime call positions: buildWorktreeManager=%v setupGatewayChat=%v, want both present", trees, chat)
|
||||
}
|
||||
if chat < trees {
|
||||
t.Fatal("startGatewayRuntime wires setupGatewayChat before buildWorktreeManager; the Gateway would resolve a nil reviewer and never advertise review_pr")
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ func (s *outageStore) down(stall time.Duration) {
|
||||
s.failing, s.stall = true, stall
|
||||
}
|
||||
|
||||
func (s *outageStore) Resource(ctx context.Context, kind string) (storecontract.Resource, error) {
|
||||
func (s *outageStore) Resource(ctx context.Context, orgID, kind string) (storecontract.Resource, error) {
|
||||
s.mu.Lock()
|
||||
failing, stall := s.failing, s.stall
|
||||
s.mu.Unlock()
|
||||
@@ -55,7 +55,7 @@ func (s *outageStore) Resource(ctx context.Context, kind string) (storecontract.
|
||||
time.Sleep(stall)
|
||||
return storecontract.Resource{}, errors.New("state store unreachable")
|
||||
}
|
||||
return s.TaskDB.Resource(ctx, kind)
|
||||
return s.TaskDB.Resource(ctx, orgID, kind)
|
||||
}
|
||||
|
||||
// TestWatchRetryGrowsWhileTheStateStoreIsDown is the outage this reconnect
|
||||
|
||||
@@ -156,13 +156,14 @@ func (b *boot) startGatewayRuntime(ctx context.Context, actor gateway.ChatTaskAc
|
||||
b.addCleanup(b.bus.Close)
|
||||
b.capabilityHost = plugin.NewHost()
|
||||
b.startRateLimiter(ctx, b.cfg.Chat.RateLimit)
|
||||
// The Gateway owns PR review (docs/prds/operator-pr-review.md §4), so it
|
||||
// composes the process-wide worktree manager before setupGatewayChat
|
||||
// resolves boot.prReviewer: prReviewer returns nil without a manager, and
|
||||
// a nil reviewer omits review_pr from every channel's tool set. The
|
||||
// manager is the only part of the daemon's tree composition the Gateway
|
||||
// takes -- it must not own identity runners, so it does not call
|
||||
// buildTreesAndIdentities.
|
||||
// The Gateway composes the process-wide worktree manager before
|
||||
// setupGatewayChat; nothing in this process reads it today (the old
|
||||
// synchronous operator-review path that did was removed with the
|
||||
// adversarial self-review system, archie-core-afbk.7 -- see that bead's
|
||||
// continuation for the operator trigger's replacement). Kept for the
|
||||
// manager's other consumers; it is the only part of the daemon's tree
|
||||
// composition the Gateway takes -- it must not own identity runners, so
|
||||
// it does not call buildTreesAndIdentities.
|
||||
b.buildWorktreeManager()
|
||||
// setupMemoryEngine must run before setupGatewayChat: setupGatewayChat
|
||||
// constructs the turn runner, which captures b.memEngines at
|
||||
|
||||
@@ -126,9 +126,9 @@ func (b *boot) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskActor
|
||||
setup := chatSetup{
|
||||
Cfg: config.NewHolder(cfg), LLM: b.chatLLM, ChatModels: b.chatModels, ToolReg: b.toolReg,
|
||||
Personas: b.personas, ChatTasks: b.chatTasks,
|
||||
ChatTaskLister: chatTaskListerAdapter{tasks: b.stateStore.Tasks},
|
||||
ChatTaskLogs: chatTaskLogReaderAdapter{tasks: b.stateStore.TaskByID, taskLogs: b.taskLogs},
|
||||
ChatTaskActor: actor, ChatPRReviewer: b.prReviewer(),
|
||||
ChatTaskLister: chatTaskListerAdapter{tasks: b.stateStore.Tasks},
|
||||
ChatTaskLogs: chatTaskLogReaderAdapter{tasks: b.stateStore.TaskByID, taskLogs: b.taskLogs},
|
||||
ChatTaskActor: actor,
|
||||
DefaultChatIdentity: b.defaultChatIdentity,
|
||||
Bus: b.bus, Log: b.log,
|
||||
MemoryEngine: b.memoryStore(),
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/sdnotify"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
@@ -116,7 +117,7 @@ func TestGatewayServingAnnouncesReady(t *testing.T) {
|
||||
serveCh := make(chan error, 1)
|
||||
go func() { serveCh <- b.serveGatewayListener(ctx, ln, true, stubGatewayContract{}, nil) }()
|
||||
|
||||
if !listener.waitForState(t, 5*time.Second, readyState) {
|
||||
if !listener.waitForState(t, 5*time.Second, sdnotify.ReadyState) {
|
||||
t.Fatal("no READY=1 datagram within 5s of the Gateway serving")
|
||||
}
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ func (b *boot) setupKitLauncher(ctx context.Context) {
|
||||
b.kitLauncher = &kitrun.Launcher{
|
||||
Pool: pool, Fetch: fetcher, Proxy: proxy, Networks: networks,
|
||||
AgentBinary: agentBinary, CAFile: egress.CACertPath(caDir),
|
||||
Config: b.cfgHolder, Secrets: b.secrets, Grants: grants,
|
||||
Config: b.cfgHolder, Secrets: b.secrets, Grants: grants, OAuth: oauthStore,
|
||||
}
|
||||
log.Info("kit harness runs enabled", "proxy", ln.Addr().String())
|
||||
}
|
||||
|
||||
@@ -539,14 +539,16 @@ type chatTaskWriterAdapter struct {
|
||||
enqueue func(
|
||||
ctx context.Context,
|
||||
owner, repo, title, body, workflow, identity string,
|
||||
inputs map[string]any,
|
||||
) (*workflow.Task, error)
|
||||
}
|
||||
|
||||
func (a chatTaskWriterAdapter) EnqueueChatTask(
|
||||
ctx context.Context,
|
||||
owner, repo, title, body, workflow, identity string,
|
||||
inputs map[string]any,
|
||||
) (int64, error) {
|
||||
task, err := a.enqueue(ctx, owner, repo, title, body, workflow, identity)
|
||||
task, err := a.enqueue(ctx, owner, repo, title, body, workflow, identity, inputs)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@@ -567,7 +567,7 @@ func TestManualRequeueTaskRejectsOtherStatuses(t *testing.T) {
|
||||
func TestChatTaskListerAdapterReadsSQLiteIdentity(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
want, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "identity task", "", "tdd", "reviewer")
|
||||
want, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "identity task", "", "tdd", "reviewer", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -610,13 +610,14 @@ func TestChatTaskWriterAdapter(t *testing.T) {
|
||||
enqueue: func(
|
||||
context.Context,
|
||||
string, string, string, string, string, string,
|
||||
map[string]any,
|
||||
) (*workflow.Task, error) {
|
||||
return tt.result, tt.err
|
||||
},
|
||||
}
|
||||
id, err := adapter.EnqueueChatTask(
|
||||
context.Background(),
|
||||
"owner", "repo", "title", "body", "workflow", "identity",
|
||||
"owner", "repo", "title", "body", "workflow", "identity", nil,
|
||||
)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("EnqueueChatTask() error = %v, wantErr %t", err, tt.wantErr)
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"context"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storepkg"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
)
|
||||
|
||||
// contributedLayer ships one workflow definition file's portable YAML.
|
||||
func contributedLayer(t *testing.T, path, yaml string) []byte {
|
||||
t.Helper()
|
||||
var raw bytes.Buffer
|
||||
writer := tar.NewWriter(&raw)
|
||||
if err := writer.WriteHeader(&tar.Header{Typeflag: tar.TypeReg, Name: path, Size: int64(len(yaml))}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := writer.Write([]byte(yaml)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return raw.Bytes()
|
||||
}
|
||||
|
||||
func packageDescriptor() storepkg.Descriptor {
|
||||
return storepkg.Descriptor{
|
||||
APIVersion: storepkg.APIVersion, DisplayName: "Review pack", Version: "1",
|
||||
Contributes: storepkg.Contributions{Workflows: []string{"workflows/review.yaml"}},
|
||||
Files: []storepkg.File{{Path: "workflows/review.yaml", Mode: 0o644}},
|
||||
}
|
||||
}
|
||||
|
||||
// TestPackageContributionsLiveRoundTrip drives the State Store's own
|
||||
// composition — the projections stateStoreDeps wires, the install and remove
|
||||
// RPCs the dashboard calls, and the workflow-definitions resource the daemon
|
||||
// reads per dispatch — over one real gRPC connection: installing a package
|
||||
// makes its workflow a usable org resource, and removing it stops being
|
||||
// usable, both without restarting anything.
|
||||
func TestPackageContributionsLiveRoundTrip(t *testing.T) {
|
||||
db := pgstore.Open(t)
|
||||
projections, err := newPackageProjections(db.Pool)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const yaml = "id: review\nsteps:\n - type: bootstrap.apply\n"
|
||||
service := storepkg.Service{
|
||||
Registry: packageLayerRegistry{descriptor: packageDescriptor(), layer: contributedLayer(t, "workflows/review.yaml", yaml)},
|
||||
Store: postgres.NewInstalledPackages(db.Pool),
|
||||
Projections: projections,
|
||||
}
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
server := grpc.NewServer()
|
||||
staterpc.RegisterServer(server, staterpc.Deps{Packages: service})
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
|
||||
conn, err := grpc.NewClient("passthrough:///state",
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
client := staterpc.NewClient(conn)
|
||||
const digest = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
|
||||
if _, err := client.InstallPackage(t.Context(), "org-a", "review", "localhost:5000/review", digest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The contribution is usable: the org resource the daemon's
|
||||
// WorkflowDefinitions client reads carries it now, no restart involved.
|
||||
resource, err := postgres.NewResources(db.Pool).Resource(t.Context(), "org-a", controlplane.WorkflowDefinitionsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
collection, err := workflow.DecodeDefinitionCollection(resource.Value, workflow.BuiltinStepRegistry())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := collection.DefinitionByID("review"); !ok {
|
||||
t.Fatal("installed package's workflow is not an org workflow after install")
|
||||
}
|
||||
if err := client.RemoveInstalled(t.Context(), "org-a", "review"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resource, err = postgres.NewResources(db.Pool).Resource(t.Context(), "org-a", controlplane.WorkflowDefinitionsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
collection, err = workflow.DecodeDefinitionCollection(resource.Value, workflow.BuiltinStepRegistry())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := collection.DefinitionByID("review"); ok {
|
||||
t.Fatal("removed package's workflow still dispatches: the org resource kept it")
|
||||
}
|
||||
if entries, err := postgres.NewPackageContributions(db.Pool).Entries(t.Context(), "org-a", "review"); err != nil || len(entries) != 0 {
|
||||
t.Fatalf("contributions ledger after removal = %#v, %v", entries, err)
|
||||
}
|
||||
}
|
||||
|
||||
type packageLayerRegistry struct {
|
||||
descriptor storepkg.Descriptor
|
||||
layer []byte
|
||||
}
|
||||
|
||||
func (r packageLayerRegistry) Fetch(context.Context, string, string) (storepkg.Descriptor, []byte, error) {
|
||||
return r.descriptor, r.layer, nil
|
||||
}
|
||||
|
||||
// TestStateStoreDepsWiresPackageProjections pins the wiring the live round
|
||||
// trip drives: stateStoreDeps builds projections on the State Store's pool and
|
||||
// carries them into the packages service it composes.
|
||||
func TestStateStoreDepsWiresPackageProjections(t *testing.T) {
|
||||
file := "state_store.go"
|
||||
fset := token.NewFileSet()
|
||||
parsed, err := parser.ParseFile(fset, file, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var calls []string
|
||||
ast.Inspect(parsed, func(node ast.Node) bool {
|
||||
if call, ok := node.(*ast.CallExpr); ok {
|
||||
if fn, ok := call.Fun.(*ast.Ident); ok {
|
||||
calls = append(calls, fn.Name)
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
found := false
|
||||
for _, call := range calls {
|
||||
if call == "newPackageProjections" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("stateStoreDeps (%s body) wires no package projections", file)
|
||||
}
|
||||
}
|
||||
@@ -1,364 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/app/agentworker"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/artifactsync"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
// prReviewer implements gateway.ChatPRReviewer for the daemon. It fetches
|
||||
// an existing PR's metadata, materialises its head in a fresh clone, and runs
|
||||
// the same adversarial reviewer the workflow stage uses, all synchronously in
|
||||
// the requesting turn. Authorization is identity-scoped (the task_spawn
|
||||
// repository allow-list) and one review per PR runs at a time.
|
||||
type prReviewer struct {
|
||||
forge forge.PullRequestReader // nil = forge cannot read PRs
|
||||
trees *worktree.Manager
|
||||
models map[string]string
|
||||
providers map[string]agentexec.Provider
|
||||
maxSteps int
|
||||
// artifacts publishes the completed review to the collaborative editor.
|
||||
// nil = publishing is disabled (no [artifacts] base_url configured).
|
||||
artifacts artifactsync.Sender
|
||||
// currentMaxSteps lets the composition root apply live control-plane
|
||||
// versions to reviews that have not started yet. Tests and direct
|
||||
// constructions retain maxSteps as the fallback.
|
||||
currentMaxSteps func() int
|
||||
// allowed maps a chat identity to the "owner/name" repos it may review.
|
||||
// A nil identity is an authenticated dashboard operator, who may review
|
||||
// any configured repository.
|
||||
allowed map[string]map[string]bool
|
||||
log *slog.Logger
|
||||
|
||||
mu sync.Mutex
|
||||
inflight map[string]struct{}
|
||||
}
|
||||
|
||||
var _ gateway.ChatPRReviewer = (*prReviewer)(nil)
|
||||
|
||||
// ReviewPR fetches the PR, runs the isolated reviewer against its head, and
|
||||
// returns the structured findings. It never half-reviews: a missing forge
|
||||
// capability, an unresolvable head/base, or an absent reviewer model returns
|
||||
// an error rather than a fabricated result.
|
||||
func (r *prReviewer) ReviewPR(ctx context.Context, identity *string, repo string, number int) (gateway.PRReviewResult, error) {
|
||||
owner, name, err := splitOwnerRepo(repo)
|
||||
if err != nil {
|
||||
return gateway.PRReviewResult{}, err
|
||||
}
|
||||
if err := r.authorize(identity, owner, name); err != nil {
|
||||
return gateway.PRReviewResult{}, err
|
||||
}
|
||||
|
||||
key := owner + "/" + name + "#" + strconv.Itoa(number)
|
||||
if !r.begin(key) {
|
||||
return gateway.PRReviewResult{}, fmt.Errorf("review already in progress for %s", key)
|
||||
}
|
||||
defer r.end(key)
|
||||
|
||||
if r.forge == nil {
|
||||
return gateway.PRReviewResult{}, fmt.Errorf("forge does not support pull request review")
|
||||
}
|
||||
pr, err := r.forge.GetPullRequest(ctx, owner, name, number)
|
||||
if err != nil {
|
||||
return gateway.PRReviewResult{}, err
|
||||
}
|
||||
|
||||
model := agentworker.ReviewerModel(r.models)
|
||||
if model == "" {
|
||||
return gateway.PRReviewResult{}, fmt.Errorf("reviewer model is not configured (set models.reviewer, or models.builder as a fallback)")
|
||||
}
|
||||
reviewer := agentworker.NewOperatorReviewer(r.models, r.providers)
|
||||
if reviewer == nil {
|
||||
return gateway.PRReviewResult{}, fmt.Errorf("no provider runtime configured for the reviewer model %q", model)
|
||||
}
|
||||
if r.trees == nil {
|
||||
return gateway.PRReviewResult{}, fmt.Errorf("worktree manager is not configured")
|
||||
}
|
||||
|
||||
dir, cleanup, err := r.trees.CheckoutPR(ctx, owner, name, pr.HeadRef, pr.BaseRef)
|
||||
if err != nil {
|
||||
return gateway.PRReviewResult{}, err
|
||||
}
|
||||
defer cleanup()
|
||||
|
||||
diff, err := r.trees.Diff(ctx, dir, pr.BaseRef)
|
||||
if err != nil {
|
||||
return gateway.PRReviewResult{}, fmt.Errorf("compute PR diff: %w", err)
|
||||
}
|
||||
|
||||
snapshotDir, err := os.MkdirTemp("", "pr-review-snapshot-*")
|
||||
if err != nil {
|
||||
return gateway.PRReviewResult{}, fmt.Errorf("create review snapshot directory: %w", err)
|
||||
}
|
||||
defer os.RemoveAll(snapshotDir)
|
||||
if err := r.trees.Snapshot(ctx, dir, snapshotDir); err != nil {
|
||||
return gateway.PRReviewResult{}, fmt.Errorf("snapshot PR head: %w", err)
|
||||
}
|
||||
|
||||
maxSteps := r.maxSteps
|
||||
if r.currentMaxSteps != nil {
|
||||
maxSteps = r.currentMaxSteps()
|
||||
}
|
||||
report := reviewer.Review(ctx, workflow.ReviewRequest{
|
||||
SnapshotDir: snapshotDir,
|
||||
Diff: diff,
|
||||
IssueText: prIssueText(pr),
|
||||
MaxSteps: maxSteps,
|
||||
})
|
||||
r.logReview(key, model, report)
|
||||
|
||||
result := mapReviewResult(repo, number, model, report)
|
||||
return r.attachArtifact(ctx, result, identity, owner, name, number, report), nil
|
||||
}
|
||||
|
||||
// authorize enforces the identity-scoped repository allow-list. A nil
|
||||
// identity (dashboard operator) may review any configured repository.
|
||||
func (r *prReviewer) authorize(identity *string, owner, repo string) error {
|
||||
full := owner + "/" + repo
|
||||
if identity == nil {
|
||||
for _, set := range r.allowed {
|
||||
if set[full] {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("repository %q is not configured", full)
|
||||
}
|
||||
set, ok := r.allowed[*identity]
|
||||
if !ok {
|
||||
return fmt.Errorf("identity %q is not configured for PR review", *identity)
|
||||
}
|
||||
if !set[full] {
|
||||
return fmt.Errorf("repository %q is not configured for this identity", full)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *prReviewer) begin(key string) bool {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.inflight == nil {
|
||||
r.inflight = make(map[string]struct{})
|
||||
}
|
||||
if _, ok := r.inflight[key]; ok {
|
||||
return false
|
||||
}
|
||||
r.inflight[key] = struct{}{}
|
||||
return true
|
||||
}
|
||||
|
||||
func (r *prReviewer) end(key string) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
delete(r.inflight, key)
|
||||
}
|
||||
|
||||
func (r *prReviewer) logReview(key, model string, report workflow.ReviewReport) {
|
||||
if r.log == nil {
|
||||
return
|
||||
}
|
||||
blocking := 0
|
||||
for _, f := range report.Findings {
|
||||
if f.Blocking() {
|
||||
blocking++
|
||||
}
|
||||
}
|
||||
r.log.Info("operator PR review complete",
|
||||
"pr", key, "model", model, "status", string(report.Status),
|
||||
"findings", len(report.Findings), "blocking", blocking)
|
||||
}
|
||||
|
||||
// attachArtifact publishes the report when the sender is configured and
|
||||
// records the editor deep link on the result. Publishing never fails the
|
||||
// review: a failure degrades to an empty URL.
|
||||
func (r *prReviewer) attachArtifact(ctx context.Context, result gateway.PRReviewResult, identity *string, owner, name string, number int, report workflow.ReviewReport) gateway.PRReviewResult {
|
||||
result.ArtifactURL = r.publishArtifact(ctx, reviewActor(identity), owner, name, number, report)
|
||||
return result
|
||||
}
|
||||
|
||||
// reviewActor resolves the attribution: the requesting chat identity when one
|
||||
// exists, else the daemon's operator-reviewer actor.
|
||||
func reviewActor(identity *string) string {
|
||||
if identity != nil && *identity != "" {
|
||||
return *identity
|
||||
}
|
||||
return "system:pr-reviewer"
|
||||
}
|
||||
|
||||
// publishArtifact renders the report and hands it to the collaborative
|
||||
// editor when artifact publishing is configured. It returns the editor deep
|
||||
// link, or "" when publishing is disabled or failed: a publish failure is a
|
||||
// logged degradation, never an error that fails the producing review.
|
||||
func (r *prReviewer) publishArtifact(ctx context.Context, actor, owner, name string, number int, report workflow.ReviewReport) string {
|
||||
if r.artifacts == nil {
|
||||
return ""
|
||||
}
|
||||
title := fmt.Sprintf("Review of %s/%s#%d", owner, name, number)
|
||||
artifact := artifactsync.Artifact{
|
||||
Title: title,
|
||||
Source: report.RenderMarkdown(title),
|
||||
Meta: artifactsync.Meta{
|
||||
Format: "markdown",
|
||||
Category: "pr-review",
|
||||
Visibility: "account-only",
|
||||
Egress: "none",
|
||||
Actor: actor,
|
||||
Origin: "pr-review",
|
||||
RequestID: "artifact:pr-review:" + owner + "/" + name + "#" + strconv.Itoa(number),
|
||||
Version: "r1",
|
||||
SentAt: time.Now().UTC(),
|
||||
Task: &artifactsync.Task{Owner: owner, Repo: name, Number: number},
|
||||
},
|
||||
}
|
||||
url, err := r.artifacts.Publish(ctx, artifact)
|
||||
if err != nil {
|
||||
if r.log != nil {
|
||||
r.log.Warn("artifact publish failed; the review result is unaffected",
|
||||
"artifact", artifact.RequestID(), "err", err)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if r.log != nil {
|
||||
r.log.Info("artifact published", "artifact", artifact.RequestID(), "url", url)
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
// splitOwnerRepo splits "owner/name" with the same validation the gateway's
|
||||
// task_spawn allow-list uses.
|
||||
func splitOwnerRepo(s string) (owner, repo string, err error) {
|
||||
owner, repo, ok := strings.Cut(s, "/")
|
||||
if !ok || owner == "" || repo == "" {
|
||||
return "", "", fmt.Errorf("repository %q must be owner/name", s)
|
||||
}
|
||||
return owner, repo, nil
|
||||
}
|
||||
|
||||
// prIssueText renders the PR title/body as the review's issue text.
|
||||
func prIssueText(pr forge.PullRequest) string {
|
||||
if pr.Body == "" {
|
||||
return pr.Title
|
||||
}
|
||||
return pr.Title + "\n\n" + pr.Body
|
||||
}
|
||||
|
||||
// mapReviewResult adapts a workflow.ReviewReport into the gateway's
|
||||
// channel-neutral result shape.
|
||||
func mapReviewResult(repo string, number int, model string, report workflow.ReviewReport) gateway.PRReviewResult {
|
||||
out := gateway.PRReviewResult{
|
||||
Repo: repo,
|
||||
Number: number,
|
||||
Model: model,
|
||||
Status: string(report.Status),
|
||||
Summary: report.Summary,
|
||||
Reason: report.SkipReason,
|
||||
Findings: make([]gateway.PRReviewFinding, 0, len(report.Findings)),
|
||||
}
|
||||
for _, f := range report.Findings {
|
||||
out.Findings = append(out.Findings, gateway.PRReviewFinding{
|
||||
File: f.File,
|
||||
Line: f.Line,
|
||||
Defect: f.Defect,
|
||||
FailureScenario: f.FailureScenario,
|
||||
Verdict: string(f.Verdict),
|
||||
Level: string(f.Level),
|
||||
Category: string(f.Category),
|
||||
Blocking: f.Blocking(),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// buildReviewAllowlist derives the identity-scoped review allow-list from the
|
||||
// same profiles task_spawn uses, so a chat identity and the review command
|
||||
// agree on which repositories the identity may touch.
|
||||
func buildReviewAllowlist(cfg config.Config) map[string]map[string]bool {
|
||||
profiles, _ := chatTaskProfiles(cfg)
|
||||
out := make(map[string]map[string]bool, len(profiles))
|
||||
for _, p := range profiles {
|
||||
set := make(map[string]bool, len(p.Repos))
|
||||
for _, repo := range p.Repos {
|
||||
set[repo] = true
|
||||
}
|
||||
out[p.Identity] = set
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// prReviewer assembles the operator-triggered review capability, or nil when
|
||||
// the forge cannot read PRs (the noop forge, or a forge with no PR read
|
||||
// support). A review tool that can never run must not be advertised, matching
|
||||
// the TaskTools nil-backend rule.
|
||||
//
|
||||
// The instance is built once and memoized on the boot struct so every channel
|
||||
// shares one in-flight set: a review of the same PR requested concurrently
|
||||
// from the Web UI and Telegram deduplicates instead of running twice.
|
||||
func (b *boot) prReviewer() gateway.ChatPRReviewer {
|
||||
if b.chatPRReviewer != nil {
|
||||
return b.chatPRReviewer
|
||||
}
|
||||
if b.trees == nil {
|
||||
return nil
|
||||
}
|
||||
forgeReader, _ := b.forgeClient.(forge.PullRequestReader)
|
||||
if forgeReader == nil {
|
||||
return nil
|
||||
}
|
||||
maxSteps := b.cfg.Budgets.MaxSteps
|
||||
if b.cfgHolder != nil {
|
||||
maxSteps = b.cfgHolder.Get().Budgets.MaxSteps
|
||||
}
|
||||
review := &prReviewer{
|
||||
forge: forgeReader,
|
||||
trees: b.trees,
|
||||
models: b.cfg.Models,
|
||||
providers: executionProviders(b.cfg),
|
||||
maxSteps: maxSteps,
|
||||
artifacts: b.artifactSender(),
|
||||
allowed: buildReviewAllowlist(b.cfg),
|
||||
log: b.log,
|
||||
}
|
||||
if b.cfgHolder != nil {
|
||||
review.currentMaxSteps = func() int { return b.cfgHolder.Get().Budgets.MaxSteps }
|
||||
}
|
||||
b.chatPRReviewer = review
|
||||
return b.chatPRReviewer
|
||||
}
|
||||
|
||||
// artifactSender builds the collaborative-editor sender when the [artifacts]
|
||||
// section configures one. An empty base_url disables publishing entirely; a
|
||||
// base_url with an unresolvable token is a missing credential, which disables
|
||||
// the capability with a loud warning rather than stopping the daemon
|
||||
// (docs/architecture/configuration.md, "A missing credential disables a
|
||||
// capability").
|
||||
func (b *boot) artifactSender() artifactsync.Sender {
|
||||
cfg := b.cfg.Artifacts
|
||||
if cfg.BaseURL == "" {
|
||||
return nil
|
||||
}
|
||||
token, err := b.secrets.Resolve(cfg.Token)
|
||||
if err != nil {
|
||||
b.log.Warn("artifact publishing disabled: the service credential could not be resolved",
|
||||
"base_url", cfg.BaseURL, "token_engine", cfg.Token.Engine, "err", err)
|
||||
return nil
|
||||
}
|
||||
if token == "" {
|
||||
b.log.Warn("artifact publishing disabled: the service token resolved empty",
|
||||
"base_url", cfg.BaseURL, "token_engine", cfg.Token.Engine)
|
||||
return nil
|
||||
}
|
||||
return artifactsync.NewClient(cfg.BaseURL, token)
|
||||
}
|
||||
@@ -1,317 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/artifactsync"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
func TestSplitOwnerRepo(t *testing.T) {
|
||||
tests := []struct {
|
||||
in string
|
||||
owner string
|
||||
repo string
|
||||
wantErr bool
|
||||
}{
|
||||
{"acme/widget", "acme", "widget", false},
|
||||
{"acme/widget/service", "acme", "widget/service", false},
|
||||
{"acme", "", "", true},
|
||||
{"/widget", "", "", true},
|
||||
{"acme/", "", "", true},
|
||||
{"", "", "", true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
owner, repo, err := splitOwnerRepo(tt.in)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Errorf("splitOwnerRepo(%q) error = nil, want error", tt.in)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("splitOwnerRepo(%q) error = %v", tt.in, err)
|
||||
continue
|
||||
}
|
||||
if owner != tt.owner || repo != tt.repo {
|
||||
t.Errorf("splitOwnerRepo(%q) = (%q, %q), want (%q, %q)", tt.in, owner, repo, tt.owner, tt.repo)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPRIssueText(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
pr forge.PullRequest
|
||||
want string
|
||||
}{
|
||||
{"title only", forge.PullRequest{Title: "Fix login"}, "Fix login"},
|
||||
{"title and body", forge.PullRequest{Title: "Fix login", Body: "The form 500s."}, "Fix login\n\nThe form 500s."},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := prIssueText(tt.pr); got != tt.want {
|
||||
t.Errorf("prIssueText = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapReviewResult(t *testing.T) {
|
||||
report := workflow.ReviewReport{
|
||||
Status: workflow.ReviewStatusCompleted,
|
||||
Summary: "checked and cleared",
|
||||
Findings: []workflow.ReviewFinding{
|
||||
{File: "a.go", Line: 3, Defect: "nil deref", FailureScenario: "x", Verdict: workflow.ReviewVerdictConfirmed, Level: workflow.ReviewLevelError, Category: workflow.ReviewCategoryNilRisk},
|
||||
{File: "b.go", Line: 0, Defect: "style", FailureScenario: "y", Verdict: workflow.ReviewVerdictPlausible, Level: workflow.ReviewLevelWarn, Category: workflow.ReviewCategoryOther},
|
||||
},
|
||||
}
|
||||
got := mapReviewResult("acme/widget", 7, "openai/gpt-5", report)
|
||||
|
||||
if got.Repo != "acme/widget" || got.Number != 7 || got.Model != "openai/gpt-5" || got.Status != "completed" || got.Summary != "checked and cleared" {
|
||||
t.Fatalf("result meta = %+v", got)
|
||||
}
|
||||
if len(got.Findings) != 2 {
|
||||
t.Fatalf("findings = %d, want 2", len(got.Findings))
|
||||
}
|
||||
if !got.Findings[0].Blocking {
|
||||
t.Error("confirmed error finding should be blocking")
|
||||
}
|
||||
if got.Findings[1].Blocking {
|
||||
t.Error("plausible warn finding must not be blocking")
|
||||
}
|
||||
if got.Findings[0].Line != 3 {
|
||||
t.Errorf("line = %d, want 3", got.Findings[0].Line)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapReviewResultNotRunPreservesReason(t *testing.T) {
|
||||
report := workflow.NewNotRunReviewReport("no reviewer model configured")
|
||||
got := mapReviewResult("acme/widget", 7, "", report)
|
||||
if got.Status != "not_run" || got.Reason != "no reviewer model configured" {
|
||||
t.Fatalf("not_run result = %+v, want status not_run and reason preserved", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrReviewerAuthorize(t *testing.T) {
|
||||
r := &prReviewer{allowed: map[string]map[string]bool{
|
||||
"": {"acme/widget": true, "acme/core": true},
|
||||
"archie": {"acme/widget": true},
|
||||
}}
|
||||
archie := "archie"
|
||||
other := "other"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
identity *string
|
||||
owner string
|
||||
repo string
|
||||
wantErr bool
|
||||
}{
|
||||
{"identity own repo", &archie, "acme", "widget", false},
|
||||
{"identity foreign repo", &archie, "acme", "core", true},
|
||||
{"unknown identity", &other, "acme", "widget", true},
|
||||
{"operator any configured", nil, "acme", "core", false},
|
||||
{"operator unconfigured repo", nil, "acme", "other", true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := r.authorize(tt.identity, tt.owner, tt.repo)
|
||||
if tt.wantErr && err == nil {
|
||||
t.Errorf("authorize(%v, %s/%s) error = nil, want error", tt.identity, tt.owner, tt.repo)
|
||||
}
|
||||
if !tt.wantErr && err != nil {
|
||||
t.Errorf("authorize(%v, %s/%s) error = %v, want nil", tt.identity, tt.owner, tt.repo, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrReviewerSingleflight(t *testing.T) {
|
||||
r := &prReviewer{}
|
||||
key := "acme/widget#7"
|
||||
if !r.begin(key) {
|
||||
t.Fatal("first begin = false, want true")
|
||||
}
|
||||
if r.begin(key) {
|
||||
t.Fatal("concurrent begin = true, want false (deterministic single-flight)")
|
||||
}
|
||||
r.end(key)
|
||||
if !r.begin(key) {
|
||||
t.Fatal("begin after end = false, want true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildReviewAllowlist(t *testing.T) {
|
||||
cfg := config.Config{
|
||||
Identities: []config.IdentityConfig{
|
||||
{Name: "archie", Repos: []config.Repo{{Owner: "acme", Name: "widget"}}},
|
||||
},
|
||||
}
|
||||
allowed := buildReviewAllowlist(cfg)
|
||||
|
||||
if !allowed["archie"]["acme/widget"] {
|
||||
t.Errorf("allowlist missing acme/widget for identity archie: %+v", allowed)
|
||||
}
|
||||
if allowed["archie"]["acme/core"] {
|
||||
t.Errorf("allowlist leaked acme/core to identity archie: %+v", allowed)
|
||||
}
|
||||
if _, ok := allowed["nobody"]; ok {
|
||||
t.Errorf("allowlist contains unknown identity nobody: %+v", allowed)
|
||||
}
|
||||
}
|
||||
|
||||
// reviewCapableForge satisfies both forge.Forge (via embedding) and
|
||||
// forge.PullRequestReader, so boot.prReviewer can be exercised in isolation.
|
||||
type reviewCapableForge struct {
|
||||
forge.Forge
|
||||
}
|
||||
|
||||
func (reviewCapableForge) GetPullRequest(context.Context, string, string, int) (forge.PullRequest, error) {
|
||||
return forge.PullRequest{}, nil
|
||||
}
|
||||
|
||||
// TestPrReviewerIsMemoized pins the cross-channel single-flight fix: every
|
||||
// gateway must share one prReviewer so a review of the same PR requested from
|
||||
// two channels at once deduplicates instead of running twice. The boot must
|
||||
// own a worktree manager: a reviewer without one can never run and must not be
|
||||
// produced (see TestPrReviewerNilWithoutTrees).
|
||||
func TestPrReviewerIsMemoized(t *testing.T) {
|
||||
b := &boot{
|
||||
forgeClient: reviewCapableForge{Forge: forge.NewNoop(slog.New(slog.DiscardHandler))},
|
||||
trees: &worktree.Manager{},
|
||||
}
|
||||
|
||||
first := b.prReviewer()
|
||||
if first == nil {
|
||||
t.Fatal("prReviewer() = nil, want a reviewer")
|
||||
}
|
||||
if second := b.prReviewer(); first != second {
|
||||
t.Fatal("prReviewer() returned distinct instances; channels would not share the in-flight set")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrReviewerNilWithoutTrees pins the producer-side invariant: a PR-capable
|
||||
// forge without a worktree manager must yield no reviewer. The standalone
|
||||
// Gateway never builds trees, and the daemon used to capture b.trees before it
|
||||
// was assigned, so both advertised a review_pr tool that always failed.
|
||||
func TestPrReviewerNilWithoutTrees(t *testing.T) {
|
||||
b := &boot{forgeClient: reviewCapableForge{Forge: forge.NewNoop(slog.New(slog.DiscardHandler))}}
|
||||
|
||||
if got := b.prReviewer(); got != nil {
|
||||
t.Fatalf("prReviewer() with no worktree manager = %T, want nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReviewPRToolRegisteredOnlyWithWorkingReviewer composes the real boot
|
||||
// wiring (boot.prReviewer -> gateway.ReviewTools) and asserts review_pr is
|
||||
// advertised only when the reviewer can actually run.
|
||||
func TestReviewPRToolRegisteredOnlyWithWorkingReviewer(t *testing.T) {
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
b := &boot{
|
||||
forgeClient: reviewCapableForge{Forge: forge.NewNoop(logger)},
|
||||
log: logger,
|
||||
}
|
||||
|
||||
if hasReviewPRTool(gateway.ReviewTools(b.prReviewer(), "archie")) {
|
||||
t.Fatal("review_pr advertised with no worktree manager: a tool that cannot run must not be offered")
|
||||
}
|
||||
|
||||
b.trees = &worktree.Manager{}
|
||||
if !hasReviewPRTool(gateway.ReviewTools(b.prReviewer(), "archie")) {
|
||||
t.Fatal("review_pr not advertised with a worktree manager")
|
||||
}
|
||||
}
|
||||
|
||||
// hasReviewPRTool reports whether review_pr is offered. Presence is asserted by
|
||||
// name rather than by entry count: the contract is that this one capability is
|
||||
// offered only when it can run, so adding a sibling review tool must not turn
|
||||
// this red.
|
||||
func hasReviewPRTool(entries []tools.ToolEntry) bool {
|
||||
for _, e := range entries {
|
||||
if e.Name == "review_pr" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type fakeArtifactSender struct {
|
||||
calls int
|
||||
url string
|
||||
err error
|
||||
last artifactsync.Artifact
|
||||
}
|
||||
|
||||
func (f *fakeArtifactSender) Publish(_ context.Context, a artifactsync.Artifact) (string, error) {
|
||||
f.calls++
|
||||
f.last = a
|
||||
if f.err != nil {
|
||||
return "", f.err
|
||||
}
|
||||
return f.url, nil
|
||||
}
|
||||
|
||||
func TestPrReviewerPublishesTheCompletedReview(t *testing.T) {
|
||||
fake := &fakeArtifactSender{url: "https://offloaded.dev/collab?document=a_1"}
|
||||
r := &prReviewer{artifacts: fake, log: slog.New(slog.DiscardHandler)}
|
||||
report := workflow.NewCompletedReviewReport([]workflow.ReviewFinding{{
|
||||
File: "handler.go", Line: 42, Defect: "nil deref",
|
||||
FailureScenario: "empty payload crashes", Verdict: workflow.ReviewVerdictConfirmed,
|
||||
Level: workflow.ReviewLevelError,
|
||||
}}, "one finding")
|
||||
report.Checked = []workflow.ReviewCheck{{Property: "p", Evidence: "e"}}
|
||||
|
||||
url := r.publishArtifact(context.Background(), "system:pr-reviewer", "acme", "widget", 7, report)
|
||||
if url != fake.url {
|
||||
t.Fatalf("publishArtifact = %q, want the sender's url %q", url, fake.url)
|
||||
}
|
||||
if fake.calls != 1 {
|
||||
t.Fatalf("Publish called %d times, want 1", fake.calls)
|
||||
}
|
||||
got := fake.last
|
||||
if got.Meta.Format != "markdown" || got.Meta.Category != "pr-review" {
|
||||
t.Fatalf("format/category = %s/%s, want markdown/pr-review", got.Meta.Format, got.Meta.Category)
|
||||
}
|
||||
if got.Meta.Actor != "system:pr-reviewer" || got.Meta.Origin != "pr-review" {
|
||||
t.Fatalf("attribution = %s/%s", got.Meta.Actor, got.Meta.Origin)
|
||||
}
|
||||
if got.Meta.Visibility != "account-only" || got.Meta.Egress != "none" {
|
||||
t.Fatalf("visibility/egress = %s/%s", got.Meta.Visibility, got.Meta.Egress)
|
||||
}
|
||||
if got.Title != "Review of acme/widget#7" {
|
||||
t.Fatalf("title = %q", got.Title)
|
||||
}
|
||||
if got.Meta.RequestID != "artifact:pr-review:acme/widget#7" {
|
||||
t.Fatalf("requestId = %q, want the deterministic artifact key", got.Meta.RequestID)
|
||||
}
|
||||
if got.Meta.Task == nil || got.Meta.Task.Owner != "acme" || got.Meta.Task.Number != 7 {
|
||||
t.Fatalf("task coordinates = %+v", got.Meta.Task)
|
||||
}
|
||||
if !strings.Contains(got.Source, "## Findings") {
|
||||
t.Fatalf("source is not the rendered report:\n%s", got.Source)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrReviewerPublishDegradesOnSenderFailure(t *testing.T) {
|
||||
r := &prReviewer{artifacts: &fakeArtifactSender{err: errors.New("503 exhausted")}, log: slog.New(slog.DiscardHandler)}
|
||||
if url := r.publishArtifact(context.Background(), "system:pr-reviewer", "acme", "widget", 7, workflow.NewCompletedReviewReport(nil, "s")); url != "" {
|
||||
t.Fatalf("url = %q, want empty on a failed publish", url)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrReviewerPublishIsANoOpWithoutASender(t *testing.T) {
|
||||
r := &prReviewer{}
|
||||
if url := r.publishArtifact(context.Background(), "system:pr-reviewer", "acme", "widget", 7, workflow.NewCompletedReviewReport(nil, "s")); url != "" {
|
||||
t.Fatalf("url = %q, want empty when the sender is disabled", url)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
@@ -51,7 +52,7 @@ func TestStateStoreBootSeedsProviderSourceReference(t *testing.T) {
|
||||
go func() { errCh <- RunStateStore(ctx, StateStoreOptions{Config: path, Listen: "127.0.0.1:0"}) }()
|
||||
deadline := time.After(10 * time.Second)
|
||||
for {
|
||||
resource, err := store.Resource(t.Context(), controlplane.ProviderSettingsKind)
|
||||
resource, err := store.Resource(t.Context(), storecontract.DefaultOrgID, controlplane.ProviderSettingsKind)
|
||||
if err == nil {
|
||||
if strings.Contains(string(resource.Value), "ARCHIE_PROVIDER_") || !strings.Contains(string(resource.Value), ref.Key) {
|
||||
t.Fatalf("stored provider settings = %s, want source reference and no derived env name", resource.Value)
|
||||
|
||||
@@ -117,6 +117,7 @@ var reloadableFields = map[string]bool{
|
||||
"Models": true,
|
||||
"ModelLimits": true,
|
||||
"Notify": true,
|
||||
"Review": true,
|
||||
// BotUser/BotEmail used to be poll-path only; ForTask now carries both
|
||||
// into the task snapshot as well, because the sandboxed worker builds
|
||||
// its own worktree.Manager and signs its own commits (agentworker
|
||||
|
||||
@@ -1,22 +1,18 @@
|
||||
// sd_notify.go implements systemd's sd_notify(3) protocol for archied: one
|
||||
// READY=1 when the run loop starts serving, and a WATCHDOG=1 heartbeat while
|
||||
// the run loop is demonstrably still making progress.
|
||||
// sd_notify.go wires the daemon into internal/sdnotify's implementation of
|
||||
// systemd's sd_notify(3) protocol: one READY=1 when the run loop starts
|
||||
// serving, and a WATCHDOG=1 heartbeat while the run loop is demonstrably still
|
||||
// making progress.
|
||||
//
|
||||
// The protocol is three environment variables and one datagram per state, so
|
||||
// this file speaks it directly instead of taking a module dependency: the whole
|
||||
// client is net.DialUnix plus a Write. Nothing here is fatal -- a process with
|
||||
// no NOTIFY_SOCKET (a plain terminal, Docker, a user unit without WatchdogSec)
|
||||
// sends nothing and serves exactly as before, and a socket that cannot be
|
||||
// written to is logged and ignored.
|
||||
// The protocol client and the heartbeat sampler live in internal/sdnotify
|
||||
// because archie-messaging, a separate process that cannot import this
|
||||
// package, is the next process that must be able to announce itself
|
||||
// (archie-core-g5g8). What stays here is what is the daemon's own: which
|
||||
// marker counts as progress (daemon.LastPollAt) and how long the loop may go
|
||||
// without beginning a poll pass.
|
||||
//
|
||||
// The heartbeat is deliberately not a bare ticker. A ticker fires whether or
|
||||
// not the loop it stands for is alive, so it would keep systemd satisfied while
|
||||
// the event loop was wedged -- the exact failure the watchdog exists to catch.
|
||||
// The sampler instead reads the daemon's own progress marker
|
||||
// (daemon.LastPollAt, stamped by the poll loop at the start of every pass) and
|
||||
// withholds the heartbeat once that marker is older than the loop's own poll
|
||||
// cadence. While passes keep beginning, beats flow at half of WatchdogSec; a
|
||||
// loop blocked inside a pass stops being reported as alive.
|
||||
// Nothing here is fatal -- a process with no NOTIFY_SOCKET (a plain terminal,
|
||||
// Docker, a user unit without WatchdogSec) sends nothing and serves exactly as
|
||||
// before, and a socket that cannot be written to is logged and ignored.
|
||||
//
|
||||
// Consuming the states is the unit's business: READY=1 needs Type=notify, and
|
||||
// the heartbeat needs WatchdogSec.
|
||||
@@ -25,75 +21,12 @@ package archied
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/sdnotify"
|
||||
)
|
||||
|
||||
const (
|
||||
// notifySocketEnv names the socket a manager passes to a Type=notify unit.
|
||||
notifySocketEnv = "NOTIFY_SOCKET"
|
||||
// watchdogUsecEnv carries WatchdogSec in microseconds.
|
||||
watchdogUsecEnv = "WATCHDOG_USEC"
|
||||
// watchdogPIDEnv names the process whose beats the watchdog counts.
|
||||
watchdogPIDEnv = "WATCHDOG_PID"
|
||||
|
||||
// readyState and watchdogState are the two sd_notify states archied sends.
|
||||
readyState = "READY=1"
|
||||
watchdogState = "WATCHDOG=1"
|
||||
|
||||
// watchdogHeartbeatDivisor is sd_notify(3)'s recommendation: beat at half
|
||||
// of WatchdogSec, so one missed beat is tolerated and two are not.
|
||||
watchdogHeartbeatDivisor = 2
|
||||
)
|
||||
|
||||
// notifier writes sd_notify states to the socket named in the environment. A
|
||||
// notifier with no address -- the normal case away from systemd -- sends
|
||||
// nothing and says nothing.
|
||||
type notifier struct {
|
||||
addr string
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// newNotifier resolves the notify socket. The address is read from the
|
||||
// environment systemd sets for the process, so systemd replaces the previous
|
||||
// unit's socket with the new one across a restart.
|
||||
func newNotifier(getenv func(string) string, log *slog.Logger) notifier {
|
||||
return notifier{addr: getenv(notifySocketEnv), log: log}
|
||||
}
|
||||
|
||||
// send delivers one state line. A failure is logged, never returned: a
|
||||
// notification is an observation about the daemon, and no observation is worth
|
||||
// refusing to serve over.
|
||||
func (n notifier) send(state string) {
|
||||
if n.addr == "" {
|
||||
return
|
||||
}
|
||||
if err := sendNotify(n.addr, state); err != nil {
|
||||
n.log.Warn("systemd notify failed", "state", state, "socket", n.addr, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// sendNotify writes one state datagram to a unixgram socket. sd_notify(3) is
|
||||
// one datagram per state, so each send dials afresh: a manager restart recreates
|
||||
// its socket, and a connection cached across one would fail every send after it.
|
||||
// A leading '@' names the Linux abstract namespace, which user managers use;
|
||||
// net.UnixAddr takes that syntax verbatim.
|
||||
func sendNotify(addr, state string) error {
|
||||
conn, err := net.DialUnix("unixgram", nil, &net.UnixAddr{Name: addr, Net: "unixgram"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = conn.Close() }()
|
||||
if _, err := conn.Write([]byte(state)); err != nil {
|
||||
return fmt.Errorf("write %q: %w", state, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// announceReady tells systemd the daemon has finished starting. It is called at
|
||||
// the moment a process declares itself serving: the daemon's run loop (next to
|
||||
// healthSurface.markServing), and the serve steps of archie-gateway and
|
||||
@@ -101,42 +34,35 @@ func sendNotify(addr, state string) error {
|
||||
// own and would otherwise hang a Type=notify unit until TimeoutStartSec while
|
||||
// perfectly healthy.
|
||||
func (b *boot) announceReady() {
|
||||
notifyReady(b.log)
|
||||
}
|
||||
|
||||
// notifyReady is announceReady without the boot: the Gateway's serving tail
|
||||
// runs on a boot it owns, but a free helper keeps the announcement one call
|
||||
// rather than a second notion of "started" on each surface.
|
||||
func notifyReady(log *slog.Logger) {
|
||||
newNotifier(os.Getenv, log).send(readyState)
|
||||
sdnotify.Ready(b.log)
|
||||
}
|
||||
|
||||
// startWatchdog arms the heartbeat sampler for the daemon's run loop. It does
|
||||
// nothing unless a manager named a notify socket and asked for a watchdog
|
||||
// (WATCHDOG_USEC), so every deployment without systemd is unaffected.
|
||||
func (b *boot) startWatchdog(ctx context.Context) {
|
||||
n := newNotifier(os.Getenv, b.log)
|
||||
if n.addr == "" {
|
||||
n := sdnotify.New(os.Getenv, b.log)
|
||||
if !n.Enabled() {
|
||||
return
|
||||
}
|
||||
interval, ok := watchdogHeartbeat(os.Getenv, os.Getpid(), b.log)
|
||||
interval, ok := sdnotify.Heartbeat(os.Getenv, os.Getpid(), b.log)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
sampler := loopWatchdog{
|
||||
interval: interval,
|
||||
cadence: b.loopCadence,
|
||||
progress: b.d.LastPollAt,
|
||||
beat: func() { n.send(watchdogState) },
|
||||
log: b.log,
|
||||
sampler := sdnotify.Watchdog{
|
||||
Interval: interval,
|
||||
Cadence: b.loopCadence,
|
||||
Progress: b.d.LastPollAt,
|
||||
Beat: func() { n.Send(sdnotify.WatchdogState) },
|
||||
Log: b.log,
|
||||
}
|
||||
b.log.Info("systemd watchdog armed",
|
||||
"heartbeat", interval.String(),
|
||||
"loop_cadence", b.loopCadence().String())
|
||||
|
||||
go func() {
|
||||
if err := sampler.run(ctx); err != nil && !errors.Is(err, context.Canceled) {
|
||||
if err := sampler.Run(ctx); err != nil && !errors.Is(err, context.Canceled) {
|
||||
b.log.Error("systemd watchdog stopped", "err", err)
|
||||
}
|
||||
}()
|
||||
@@ -161,86 +87,3 @@ func (b *boot) loopCadence() time.Duration {
|
||||
}
|
||||
return cadence
|
||||
}
|
||||
|
||||
// watchdogHeartbeat reads systemd's watchdog contract and returns the heartbeat
|
||||
// cadence, which is half of WatchdogSec. ok is false when systemd asked for no
|
||||
// watchdog, and also when it asked for one from a different process:
|
||||
// WATCHDOG_PID names the process whose beats count, so a unit watching another
|
||||
// process must not have this one beating on its behalf.
|
||||
func watchdogHeartbeat(getenv func(string) string, pid int, log *slog.Logger) (time.Duration, bool) {
|
||||
raw := getenv(watchdogUsecEnv)
|
||||
if raw == "" {
|
||||
return 0, false
|
||||
}
|
||||
if rawPID := getenv(watchdogPIDEnv); rawPID != "" {
|
||||
wantPID, err := strconv.Atoi(rawPID)
|
||||
if err != nil || wantPID != pid {
|
||||
log.Warn("systemd watchdog disabled: WATCHDOG_PID is not this process",
|
||||
"watchdog_pid", rawPID, "pid", pid, "err", err)
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
watchdog, err := time.ParseDuration(raw + "us")
|
||||
if err != nil || watchdog <= 0 {
|
||||
log.Warn("systemd watchdog disabled: WATCHDOG_USEC unreadable", "value", raw, "err", err)
|
||||
return 0, false
|
||||
}
|
||||
return watchdog / watchdogHeartbeatDivisor, true
|
||||
}
|
||||
|
||||
// loopWatchdog samples the run loop's progress marker and emits the watchdog
|
||||
// heartbeat only while that marker is fresh. Sampling is periodic; the beat is
|
||||
// not, because it is licensed by the marker rather than by the clock.
|
||||
type loopWatchdog struct {
|
||||
// interval is the sampling cadence: half of systemd's WatchdogSec.
|
||||
interval time.Duration
|
||||
// cadence reports how long the loop may go between poll passes.
|
||||
cadence func() time.Duration
|
||||
// progress reports the start of the loop's most recent poll pass, or the
|
||||
// zero time when no pass has begun yet.
|
||||
progress func() time.Time
|
||||
// beat emits one WATCHDOG=1.
|
||||
beat func()
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// run samples until ctx ends. It returns ctx.Err() on shutdown, which is the
|
||||
// only way out: this sampler never gives up on its own, because a sampler that
|
||||
// stopped would leave systemd watching a process nothing reports for.
|
||||
func (w loopWatchdog) run(ctx context.Context) error {
|
||||
armedAt := time.Now()
|
||||
stalled := false
|
||||
ticker := time.NewTicker(w.interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ticker.C:
|
||||
}
|
||||
|
||||
last := w.progress()
|
||||
if last.IsZero() {
|
||||
// No pass has begun at all. Measure staleness from arming, so a
|
||||
// loop that never starts polling is caught like one that stopped.
|
||||
last = armedAt
|
||||
}
|
||||
cadence := w.cadence()
|
||||
switch age := time.Since(last); {
|
||||
case age > cadence:
|
||||
if !stalled {
|
||||
w.log.Warn("systemd watchdog: run loop has not begun a poll pass within its interval; withholding the heartbeat until it does",
|
||||
"stale_for", age.String(), "loop_cadence", cadence.String())
|
||||
stalled = true
|
||||
}
|
||||
default:
|
||||
if stalled {
|
||||
w.log.Info("systemd watchdog: run loop resumed; heartbeats resumed",
|
||||
"last_pass_age", age.String())
|
||||
stalled = false
|
||||
}
|
||||
w.beat()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,8 +18,16 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
"github.com/samcharles93/archie-core/internal/sdnotify"
|
||||
)
|
||||
|
||||
// The protocol-level properties of the notify client -- the '@' address form,
|
||||
// the disabled and unusable socket contract, and the half-of-WatchdogSec
|
||||
// heartbeat -- are pinned in internal/sdnotify, where the client now lives.
|
||||
// These tests pin what is the daemon's: that its three serving entry points
|
||||
// announce, that the sampler samples daemon.LastPollAt, and that the whole
|
||||
// path stays silent and harmless without a NOTIFY_SOCKET.
|
||||
|
||||
// notifyRecorder captures every record at every level. The other recording
|
||||
// handler in this package keeps warnings only; these tests need "this path
|
||||
// logged nothing at all" as positive evidence that a disabled notifier stayed
|
||||
@@ -49,6 +57,7 @@ func (h *notifyRecorder) all() []slog.Record {
|
||||
return append([]slog.Record(nil), h.records...)
|
||||
}
|
||||
|
||||
// at returns the captured records at one level.
|
||||
func (h *notifyRecorder) at(level slog.Level) []slog.Record {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
@@ -83,7 +92,7 @@ func listenNotify(t *testing.T, addr string) *notifyListener {
|
||||
t.Fatalf("listen for notify datagrams at %q: %v", addr, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
t.Setenv(notifySocketEnv, addr)
|
||||
t.Setenv(sdnotify.NotifySocketEnv, addr)
|
||||
return ¬ifyListener{conn: conn}
|
||||
}
|
||||
|
||||
@@ -174,93 +183,12 @@ func pollPasses(ctx context.Context, d *daemon.Daemon, on *atomic.Bool, every ti
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotifyReachesAbstractSocket pins the '@' address form. systemd is not
|
||||
// restricted to filesystem paths, and a client that stripped the prefix would
|
||||
// connect to a file that does not exist instead of the abstract namespace.
|
||||
func TestNotifyReachesAbstractSocket(t *testing.T) {
|
||||
listener := listenNotify(t, fmt.Sprintf("@archie-notify-test-%d", os.Getpid()))
|
||||
|
||||
(&boot{log: slog.New(slog.DiscardHandler)}).announceReady()
|
||||
|
||||
if states := listener.states(t, 300*time.Millisecond); !slices.Contains(states, readyState) {
|
||||
t.Errorf("states received = %v, want %q among them", states, readyState)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotifierDisabledIsSilentAndUnusableSocketWarns pins the two ends of the
|
||||
// delivery contract: no socket means nothing is attempted and nothing is said,
|
||||
// while a socket that cannot be written to is reported once and then ignored.
|
||||
// Neither may ever be fatal.
|
||||
func TestNotifierDisabledIsSilentAndUnusableSocketWarns(t *testing.T) {
|
||||
rec := ¬ifyRecorder{}
|
||||
log := slog.New(rec)
|
||||
|
||||
newNotifier(func(string) string { return "" }, log).send(readyState)
|
||||
if got := rec.all(); len(got) != 0 {
|
||||
t.Errorf("a notifier with no socket logged %d records, want none: %v", len(got), got)
|
||||
}
|
||||
|
||||
missing := filepath.Join(t.TempDir(), "absent", "n.sock")
|
||||
newNotifier(func(string) string { return missing }, log).send(readyState)
|
||||
warns := rec.at(slog.LevelWarn)
|
||||
if len(warns) != 1 {
|
||||
t.Fatalf("sends to an unusable socket logged %d warnings, want exactly 1", len(warns))
|
||||
}
|
||||
if errs := rec.at(slog.LevelError); len(errs) != 0 {
|
||||
t.Errorf("sends to an unusable socket logged %d errors, want none", len(errs))
|
||||
}
|
||||
}
|
||||
|
||||
// TestWatchdogHeartbeatInterval pins the interval convention: systemd passes
|
||||
// WatchdogSec as WATCHDOG_USEC and sd_notify(3) heartbeats at half of it, and
|
||||
// WATCHDOG_PID names the process whose beats count.
|
||||
func TestWatchdogHeartbeatInterval(t *testing.T) {
|
||||
const self = 42
|
||||
tests := []struct {
|
||||
name string
|
||||
usec string
|
||||
pidEnv string
|
||||
want time.Duration
|
||||
wantOK bool
|
||||
}{
|
||||
{name: "no watchdog requested", wantOK: false},
|
||||
{name: "half of a 30s watchdog", usec: "30000000", want: 15 * time.Second, wantOK: true},
|
||||
{name: "sub-second watchdog", usec: "20000", want: 10 * time.Millisecond, wantOK: true},
|
||||
{name: "unparseable", usec: "soon", wantOK: false},
|
||||
{name: "zero", usec: "0", wantOK: false},
|
||||
{name: "negative", usec: "-1", wantOK: false},
|
||||
{name: "watchdog pid is this process", usec: "20000", pidEnv: "42", want: 10 * time.Millisecond, wantOK: true},
|
||||
{name: "watchdog pid is another process", usec: "20000", pidEnv: "7", wantOK: false},
|
||||
{name: "watchdog pid is unreadable", usec: "20000", pidEnv: "seven", wantOK: false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
getenv := func(key string) string {
|
||||
switch key {
|
||||
case watchdogUsecEnv:
|
||||
return tt.usec
|
||||
case watchdogPIDEnv:
|
||||
return tt.pidEnv
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
got, ok := watchdogHeartbeat(getenv, self, slog.New(slog.DiscardHandler))
|
||||
if ok != tt.wantOK || got != tt.want {
|
||||
t.Errorf("watchdogHeartbeat(usec=%q, pid=%q) = %v, %v; want %v, %v",
|
||||
tt.usec, tt.pidEnv, got, ok, tt.want, tt.wantOK)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotifyReadyAndWatchdogHeartbeat is the run-loop path end to end: a real
|
||||
// NOTIFY_SOCKET, the daemon's own boot path announcing READY, and the run
|
||||
// loop's own progress marker producing WATCHDOG heartbeats.
|
||||
func TestNotifyReadyAndWatchdogHeartbeat(t *testing.T) {
|
||||
listener := newNotifyListener(t)
|
||||
t.Setenv(watchdogUsecEnv, "20000") // 20ms watchdog: heartbeat every 10ms
|
||||
t.Setenv(sdnotify.WatchdogUsecEnv, "20000") // 20ms watchdog: heartbeat every 10ms
|
||||
|
||||
b, d := newNotifyTestBoot(t, 50*time.Millisecond)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
@@ -274,11 +202,11 @@ func TestNotifyReadyAndWatchdogHeartbeat(t *testing.T) {
|
||||
b.startWatchdog(ctx)
|
||||
|
||||
states := listener.states(t, 300*time.Millisecond)
|
||||
if !slices.Contains(states, readyState) {
|
||||
t.Errorf("states received = %v, want %q among them", states, readyState)
|
||||
if !slices.Contains(states, sdnotify.ReadyState) {
|
||||
t.Errorf("states received = %v, want %q among them", states, sdnotify.ReadyState)
|
||||
}
|
||||
if countState(states, watchdogState) == 0 {
|
||||
t.Errorf("states received = %v, want at least one %q among them", states, watchdogState)
|
||||
if countState(states, sdnotify.WatchdogState) == 0 {
|
||||
t.Errorf("states received = %v, want at least one %q among them", states, sdnotify.WatchdogState)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -288,7 +216,7 @@ func TestNotifyReadyAndWatchdogHeartbeat(t *testing.T) {
|
||||
// kept alive by an independent ticker.
|
||||
func TestWatchdogWithholdsHeartbeatWhenRunLoopStalls(t *testing.T) {
|
||||
listener := newNotifyListener(t)
|
||||
t.Setenv(watchdogUsecEnv, "20000") // 20ms watchdog: heartbeat every 10ms
|
||||
t.Setenv(sdnotify.WatchdogUsecEnv, "20000") // 20ms watchdog: heartbeat every 10ms
|
||||
|
||||
const cadence = 50 * time.Millisecond
|
||||
b, d := newNotifyTestBoot(t, cadence)
|
||||
@@ -300,7 +228,7 @@ func TestWatchdogWithholdsHeartbeatWhenRunLoopStalls(t *testing.T) {
|
||||
go pollPasses(ctx, d, &polling, 5*time.Millisecond)
|
||||
|
||||
b.startWatchdog(ctx)
|
||||
if beats := countState(listener.states(t, 200*time.Millisecond), watchdogState); beats == 0 {
|
||||
if beats := countState(listener.states(t, 200*time.Millisecond), sdnotify.WatchdogState); beats == 0 {
|
||||
t.Fatal("no WATCHDOG=1 within 200ms while the run loop was polling")
|
||||
}
|
||||
|
||||
@@ -323,12 +251,12 @@ func TestWatchdogWithholdsHeartbeatWhenRunLoopStalls(t *testing.T) {
|
||||
// terminal, and a systemd unit with no WatchdogSec all take this path, and none
|
||||
// of them may see a datagram, a warning, or a failed start.
|
||||
func TestNotifyUnsetIsNoOp(t *testing.T) {
|
||||
t.Setenv(watchdogUsecEnv, "20000")
|
||||
t.Setenv(sdnotify.WatchdogUsecEnv, "20000")
|
||||
// t.Setenv cannot unset a variable: register the restoration first, then
|
||||
// remove it for real so "unset" means unset.
|
||||
t.Setenv(notifySocketEnv, "")
|
||||
if err := os.Unsetenv(notifySocketEnv); err != nil {
|
||||
t.Fatalf("unset %s: %v", notifySocketEnv, err)
|
||||
t.Setenv(sdnotify.NotifySocketEnv, "")
|
||||
if err := os.Unsetenv(sdnotify.NotifySocketEnv); err != nil {
|
||||
t.Fatalf("unset %s: %v", sdnotify.NotifySocketEnv, err)
|
||||
}
|
||||
|
||||
rec := ¬ifyRecorder{}
|
||||
@@ -349,8 +277,8 @@ func TestNotifyUnsetIsNoOp(t *testing.T) {
|
||||
// would be a regression on every deployment that has no systemd at all.
|
||||
func TestNotifySocketFailureIsNotFatal(t *testing.T) {
|
||||
missing := filepath.Join(t.TempDir(), "absent", "n.sock")
|
||||
t.Setenv(notifySocketEnv, missing)
|
||||
t.Setenv(watchdogUsecEnv, "20000")
|
||||
t.Setenv(sdnotify.NotifySocketEnv, missing)
|
||||
t.Setenv(sdnotify.WatchdogUsecEnv, "20000")
|
||||
|
||||
rec := ¬ifyRecorder{}
|
||||
b, d := newNotifyTestBoot(t, 50*time.Millisecond)
|
||||
@@ -405,7 +333,7 @@ func TestStateStoreBootAnnouncesReady(t *testing.T) {
|
||||
errCh := make(chan error, 1)
|
||||
go func() { errCh <- RunStateStore(ctx, StateStoreOptions{Config: path, Listen: "127.0.0.1:0"}) }()
|
||||
|
||||
if !listener.waitForState(t, 15*time.Second, readyState) {
|
||||
if !listener.waitForState(t, 15*time.Second, sdnotify.ReadyState) {
|
||||
select {
|
||||
case bootErr := <-errCh:
|
||||
t.Fatalf("RunStateStore exited before announcing ready: %v", bootErr)
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
@@ -289,10 +290,20 @@ func (b *boot) openStateStore(ctx context.Context) error {
|
||||
func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps {
|
||||
deps := staterpc.Deps{Tasks: b.st, Log: b.log, Grants: grants}
|
||||
if b.pg != nil {
|
||||
deps.Packages = storepkg.Service{
|
||||
packages := storepkg.Service{
|
||||
Registry: registry.LocalRegistry{},
|
||||
Store: postgres.NewInstalledPackages(b.pg),
|
||||
}
|
||||
// A projection failure degrades the org resources a package would have
|
||||
// contributed to, the way a group above degrades: the State Store boots
|
||||
// and reports, rather than refusing to serve the task tables.
|
||||
projections, err := newPackageProjections(b.pg)
|
||||
if err != nil {
|
||||
b.log.Error("build package projections", "err", err)
|
||||
} else {
|
||||
packages.Projections = projections
|
||||
}
|
||||
deps.Packages = packages
|
||||
}
|
||||
if identities, ok := b.st.(identity.Repository); ok {
|
||||
deps.Identities = identities
|
||||
@@ -494,3 +505,22 @@ func stateStoreServerOpts(listen, token string, grants *staterpc.TaskGrants) (op
|
||||
grpc.ChainStreamInterceptor(grants.StreamInterceptor(token)),
|
||||
}, false, nil
|
||||
}
|
||||
|
||||
// newPackageProjections builds the family projectors an installed package's
|
||||
// contributions apply through: workflows become org workflow definitions, the
|
||||
// one resource kind the runtime reads live today. The step vocabulary
|
||||
// (stepVocabulary) is the same one this process's control plane validates
|
||||
// dashboard edits with, so a definition the projector admits is compilable
|
||||
// where it dispatches (openStateStoreControlPlane for the pairing).
|
||||
func newPackageProjections(pool *pgxpool.Pool) (map[string]storepkg.FamilyProjector, error) {
|
||||
steps, err := stepVocabulary()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("register workflow step vocabulary: %w", err)
|
||||
}
|
||||
workflows, err := controlplane.NewWorkflowPackageProjector(
|
||||
postgres.NewResources(pool), postgres.NewPackageContributions(pool), steps)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build workflow package projector: %w", err)
|
||||
}
|
||||
return map[string]storepkg.FamilyProjector{storepkg.FamilyWorkflows: workflows}, nil
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
||||
)
|
||||
|
||||
// The audit identity every offline rollback records. A rollback is one more
|
||||
@@ -135,7 +136,7 @@ func replayRevision(ctx context.Context, resources controlplane.ResourceStore, o
|
||||
if !server.Owns(options.Kind) {
|
||||
return "", fmt.Errorf("unknown resource kind %q", options.Kind)
|
||||
}
|
||||
current, err := resources.Resource(ctx, options.Kind)
|
||||
current, err := resources.Resource(ctx, storecontract.DefaultOrgID, options.Kind)
|
||||
if errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
return "", fmt.Errorf("%s has no stored value to roll back", options.Kind)
|
||||
}
|
||||
@@ -146,7 +147,7 @@ func replayRevision(ctx context.Context, resources controlplane.ResourceStore, o
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
replaced, err := server.Command(ctx, &pb.CommandRequest{
|
||||
replaced, err := server.Command(ctx, controlplanerpc.CommandRequest(ctx, &pb.CommandRequest{
|
||||
Kind: options.Kind,
|
||||
Command: "replace",
|
||||
ValueJson: revision.Value,
|
||||
@@ -154,7 +155,7 @@ func replayRevision(ctx context.Context, resources controlplane.ResourceStore, o
|
||||
Actor: OfflineRollbackActor,
|
||||
Source: OfflineRollbackSource,
|
||||
RequestId: fmt.Sprintf("recovery-rollback-%s-%d", options.Kind, time.Now().UTC().UnixNano()),
|
||||
})
|
||||
}))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("replay %s at revision %d: %w", options.Kind, revision.Version, err)
|
||||
}
|
||||
@@ -165,7 +166,7 @@ func replayRevision(ctx context.Context, resources controlplane.ResourceStore, o
|
||||
// revisionToReplay picks the value to put back: the revision the operator
|
||||
// named, or the newest one older than the value the resource carries now.
|
||||
func revisionToReplay(ctx context.Context, st controlplane.ResourceStore, kind string, current, requested int64) (storecontract.Resource, error) {
|
||||
history, err := st.ResourceHistory(ctx, kind, 0)
|
||||
history, err := st.ResourceHistory(ctx, storecontract.DefaultOrgID, kind, 0)
|
||||
if err != nil {
|
||||
return storecontract.Resource{}, fmt.Errorf("read %s history: %w", kind, err)
|
||||
}
|
||||
|
||||
@@ -54,11 +54,12 @@ func putResource(t *testing.T, pool *pgxpool.Pool, kind, value, label string) {
|
||||
t.Helper()
|
||||
resources := postgres.NewResources(pool)
|
||||
expected := int64(0)
|
||||
if current, err := resources.Resource(t.Context(), kind); err == nil {
|
||||
if current, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, kind); err == nil {
|
||||
expected = current.Version
|
||||
}
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
Kind: kind, Value: []byte(value), Actor: label, Source: "test",
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: kind, Value: []byte(value), Actor: label, Source: "test",
|
||||
RequestID: fmt.Sprintf("%s-%d", label, expected+1), ExpectedVersion: expected,
|
||||
}); err != nil {
|
||||
t.Fatalf("put %s: %v", kind, err)
|
||||
@@ -125,7 +126,7 @@ func TestPostgresRecoveryBackupAndRestore(t *testing.T) {
|
||||
if !strings.Contains(summary, "after the snapshot") {
|
||||
t.Errorf("restore must say writes after the snapshot are lost; summary = %q", summary)
|
||||
}
|
||||
current, err := postgres.NewResources(pool).Resource(t.Context(), controlplane.ModelRoleAssignmentsKind)
|
||||
current, err := postgres.NewResources(pool).Resource(t.Context(), storecontract.DefaultOrgID, controlplane.ModelRoleAssignmentsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -188,7 +189,7 @@ func TestPostgresRecoveryRollback(t *testing.T) {
|
||||
if _, err := RunStateStoreRecovery(t.Context(), options); err != nil {
|
||||
t.Fatalf("rollback: %v", err)
|
||||
}
|
||||
current, err := postgres.NewResources(pool).Resource(t.Context(), kind)
|
||||
current, err := postgres.NewResources(pool).Resource(t.Context(), storecontract.DefaultOrgID, kind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -175,7 +175,7 @@ func TestStateStoreDataSurvivesRestart(t *testing.T) {
|
||||
if err := first.openStateStore(t.Context()); err != nil {
|
||||
t.Fatalf("first openStateStore: %v", err)
|
||||
}
|
||||
task, err := first.st.EnqueueChatTask(t.Context(), "acme", "widget", "restart check", "body", "implement", "")
|
||||
task, err := first.st.EnqueueChatTask(t.Context(), "acme", "widget", "restart check", "body", "implement", "", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("EnqueueChatTask: %v", err)
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ func TestChatTaskActorAdapterCrossIdentityRefused(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "parked job", "", "", "identity-owner")
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "parked job", "", "", "identity-owner", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -146,7 +146,7 @@ func TestChatTaskActorAdapterRefusesDisallowedStateAction(t *testing.T) {
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "test task", "", "", "archie")
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "test task", "", "", "archie", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -251,7 +251,7 @@ func TestChatTaskActorAdapterAppliesActionsToStore(t *testing.T) {
|
||||
|
||||
adapter := newChatTaskActorForTest(t, st, config.Config{MaxRetries: 3})
|
||||
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "actionable task", "", "", "archie")
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "actionable task", "", "", "archie", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ func TestDashboardAndChatAgreeOnTerminalStates(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "decide on me", "", "", "reviewer")
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "decide on me", "", "", "reviewer", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -6,55 +6,9 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// TestGatewayWorktreeManagerAdvertisesReviewPR composes the Gateway's own
|
||||
// tree step with the reviewer and the review tool: whatever
|
||||
// buildWorktreeManager produces must be enough for boot.prReviewer to yield a
|
||||
// reviewer and for ReviewTools to advertise review_pr. The call-order
|
||||
// assertion in composition_order_test.go proves the Gateway makes this step;
|
||||
// this proves the step is sufficient, so a manager built without the forge
|
||||
// credential or the configured work dir cannot pass as wired.
|
||||
func TestGatewayWorktreeManagerAdvertisesReviewPR(t *testing.T) {
|
||||
const token = "gateway-forge-token"
|
||||
cfg := config.Config{
|
||||
WorkDir: t.TempDir(),
|
||||
BotUser: "archie-bot",
|
||||
BotEmail: "bot@example.test",
|
||||
Forge: config.Forge{Host: "https://forge.example.test"},
|
||||
}
|
||||
b := &boot{
|
||||
cfg: cfg,
|
||||
cfgHolder: config.NewHolder(cfg),
|
||||
token: token,
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
forgeClient: reviewCapableForge{Forge: forge.NewNoop(slog.New(slog.DiscardHandler))},
|
||||
}
|
||||
|
||||
b.buildWorktreeManager()
|
||||
|
||||
if b.trees.WorkDir != cfg.WorkDir {
|
||||
t.Errorf("worktree manager WorkDir = %q, want the configured %q", b.trees.WorkDir, cfg.WorkDir)
|
||||
}
|
||||
if b.trees.BaseURL != cfg.Forge.Host {
|
||||
t.Errorf("worktree manager BaseURL = %q, want the configured forge host %q", b.trees.BaseURL, cfg.Forge.Host)
|
||||
}
|
||||
if b.trees.Token != token {
|
||||
t.Errorf("worktree manager Token = %q, want the resolved forge token %q", b.trees.Token, token)
|
||||
}
|
||||
|
||||
reviewer := b.prReviewer()
|
||||
if reviewer == nil {
|
||||
t.Fatal("prReviewer() = nil after the Gateway's worktree-manager step; review_pr would never be advertised")
|
||||
}
|
||||
if !hasReviewPRTool(gateway.ReviewTools(reviewer, "archie")) {
|
||||
t.Fatal("review_pr not advertised after the Gateway's worktree-manager step")
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildTreesAndIdentitiesBuildsRootManagerAndIdentityRunners pins the
|
||||
// daemon's tree composition, which the shared buildWorktreeManager must not
|
||||
// change: the daemon still owns the process-wide manager *and* one runner per
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/sdnotify"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
@@ -199,6 +200,18 @@ func (s *Service) Start(ctx context.Context) error {
|
||||
})
|
||||
}
|
||||
|
||||
// Every configured channel has been handed its lifetime and the service
|
||||
// blocks here serving them. systemd's READY=1 asserts the same fact this
|
||||
// line has just established, so the announcement goes out here rather than
|
||||
// from a second notion of "started" (the convention archie-core-1174 set
|
||||
// for the daemon, the Gateway and the State Store; archie-core-g5g8 is this
|
||||
// process joining them). Not earlier: a channel whose configuration is
|
||||
// invalid fails composition, above, and READY must not precede it. Not
|
||||
// later: a unit whose TimeoutStartSec expires first would restart a healthy
|
||||
// process. Nothing is consumed until the unit says Type=notify, so this is
|
||||
// inert on today's install.
|
||||
sdnotify.Ready(s.log)
|
||||
|
||||
<-ctx.Done()
|
||||
|
||||
for _, ch := range s.channels {
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/sdnotify"
|
||||
)
|
||||
|
||||
// notifyListener is a stand-in for systemd's NOTIFY_SOCKET: a unixgram socket
|
||||
// that collects the state lines the service sends. It is bound to the real
|
||||
// NOTIFY_SOCKET for the duration of the test.
|
||||
type notifyListener struct {
|
||||
conn *net.UnixConn
|
||||
}
|
||||
|
||||
// listenNotify binds a notify socket in the test's temp dir and points
|
||||
// NOTIFY_SOCKET at it. A unix socket path is capped near 108 bytes, so the
|
||||
// short file name is what keeps the path inside t.TempDir() under that.
|
||||
func listenNotify(t *testing.T) *notifyListener {
|
||||
t.Helper()
|
||||
addr := filepath.Join(t.TempDir(), "n.sock")
|
||||
conn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{Name: addr, Net: "unixgram"})
|
||||
if err != nil {
|
||||
t.Fatalf("listen for notify datagrams at %q: %v", addr, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
t.Setenv(sdnotify.NotifySocketEnv, addr)
|
||||
return ¬ifyListener{conn: conn}
|
||||
}
|
||||
|
||||
// waitForState reads datagrams until one carries want or the window closes.
|
||||
func (l *notifyListener) waitForState(t *testing.T, window time.Duration, want string) bool {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(window)
|
||||
buf := make([]byte, 1024)
|
||||
for time.Now().Before(deadline) {
|
||||
if err := l.conn.SetReadDeadline(time.Now().Add(50 * time.Millisecond)); err != nil {
|
||||
t.Fatalf("set notify read deadline: %v", err)
|
||||
}
|
||||
n, _, err := l.conn.ReadFromUnix(buf)
|
||||
if err != nil {
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) && netErr.Timeout() {
|
||||
continue
|
||||
}
|
||||
t.Fatalf("read notify datagram: %v", err)
|
||||
}
|
||||
if string(buf[:n]) == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// TestServiceAnnouncesReadyWhenServing: archie-messaging run as a Type=notify
|
||||
// unit must send READY=1 at the moment it declares itself serving, or systemd
|
||||
// kills a healthy process once TimeoutStartSec expires. It could not before:
|
||||
// the client lived in internal/app/archied, which this process cannot import
|
||||
// (archie-core-g5g8). The announcement is judged against the same evidence the
|
||||
// other serve paths use -- the process itself says it is serving -- and not
|
||||
// against a second notion of started invented here.
|
||||
func TestServiceAnnouncesReadyWhenServing(t *testing.T) {
|
||||
listener := listenNotify(t)
|
||||
|
||||
srv, err := compose(t.Context(), deps{
|
||||
Config: ResolvedConfig{Options: Options{ShutdownTimeout: 2 * time.Second}},
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Chat: &dummyChatContract{},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
started := make(chan error, 1)
|
||||
go func() { started <- srv.Start(ctx) }()
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
srv.Stop()
|
||||
select {
|
||||
case err := <-started:
|
||||
if err != nil {
|
||||
t.Errorf("srv.Start returned %v, want a clean stop", err)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Error("srv.Start did not return after Stop, so a channel leaked its goroutine")
|
||||
}
|
||||
})
|
||||
|
||||
if !listener.waitForState(t, 5*time.Second, sdnotify.ReadyState) {
|
||||
t.Fatal("no READY=1 datagram within 5s of the Messaging Service serving")
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
||||
)
|
||||
|
||||
type messagingControlPlane struct{ client pb.ControlPlaneServiceClient }
|
||||
@@ -46,7 +47,7 @@ func (c messagingControlPlane) Catalog(ctx context.Context) ([]messaging.Setting
|
||||
}
|
||||
|
||||
func (c messagingControlPlane) Query(ctx context.Context, kind string) (messaging.SettingResource, error) {
|
||||
response, err := c.client.Query(ctx, &pb.QueryRequest{Kind: kind})
|
||||
response, err := c.client.Query(ctx, controlplanerpc.QueryRequest(ctx, kind))
|
||||
if err != nil {
|
||||
return messaging.SettingResource{}, settingsRPCError(err)
|
||||
}
|
||||
@@ -62,7 +63,7 @@ func (c messagingControlPlane) Command(ctx context.Context, command messaging.Se
|
||||
if err != nil {
|
||||
return messaging.SettingResource{}, errors.Join(messaging.ErrSettingsValidation, err)
|
||||
}
|
||||
response, err := c.client.Command(ctx, &pb.CommandRequest{Kind: command.Kind, Command: "replace", ValueJson: value, ExpectedVersion: command.ExpectedVersion, RequestId: command.RequestID, Actor: command.Actor, Source: command.Source})
|
||||
response, err := c.client.Command(ctx, controlplanerpc.CommandRequest(ctx, &pb.CommandRequest{Kind: command.Kind, Command: "replace", ValueJson: value, ExpectedVersion: command.ExpectedVersion, RequestId: command.RequestID, Actor: command.Actor, Source: command.Source}))
|
||||
if err != nil {
|
||||
return messaging.SettingResource{}, settingsRPCError(err)
|
||||
}
|
||||
|
||||
@@ -87,6 +87,11 @@ func TestRoutesWithoutAContractDegradeExplicitly(t *testing.T) {
|
||||
name: "workflow registry", method: http.MethodGet, path: "/api/workflows",
|
||||
want: http.StatusOK, emptyJSON: `"definitions":null`,
|
||||
},
|
||||
{
|
||||
name: "workflow enabled toggle", method: http.MethodPut, path: "/api/workflows/implement/enabled",
|
||||
body: `{"enabled":false}`,
|
||||
want: http.StatusServiceUnavailable,
|
||||
},
|
||||
{
|
||||
name: "dashboard work request", method: http.MethodPost, path: "/api/work-requests",
|
||||
body: `{"repository":"acme/widget","workflow":"implement","title":"do it"}`,
|
||||
@@ -171,7 +176,7 @@ func composeUIProcess(t *testing.T) (*webui.Server, int64) {
|
||||
}
|
||||
t.Cleanup(closeClient)
|
||||
|
||||
task, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "a task", "body", "implement", "")
|
||||
task, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "a task", "body", "implement", "", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("seed task: %v", err)
|
||||
}
|
||||
|
||||
@@ -103,7 +103,7 @@ func serveGRPC(t *testing.T, register func(grpc.ServiceRegistrar)) (target strin
|
||||
func TestUIServesDashboardAgainstRemoteContracts(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
defer st.Close()
|
||||
if _, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "remote summary", "body", "implement", ""); err != nil {
|
||||
if _, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "remote summary", "body", "implement", "", nil); err != nil {
|
||||
t.Fatalf("seed task: %v", err)
|
||||
}
|
||||
// Claimed (not just enqueued): StartStep guards on the execution's own
|
||||
|
||||
@@ -156,7 +156,7 @@ func composeUIProcessWithLog(t *testing.T) (*webui.Server, int64, int) {
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
task, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "a task", "body", "implement", "")
|
||||
task, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "a task", "body", "implement", "", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("seed task: %v", err)
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ func (c *Client) Catalog(ctx context.Context) ([]*pb.ResourceDescriptor, error)
|
||||
}
|
||||
|
||||
func (c *WorkflowDefinitionsClient) WorkflowDefinitions(ctx context.Context) (workflow.WorkflowDefinitionCollection, int64, error) {
|
||||
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: WorkflowDefinitionsKind})
|
||||
response, err := c.rpc.Query(ctx, controlplanerpc.QueryRequest(ctx, WorkflowDefinitionsKind))
|
||||
if err != nil {
|
||||
return workflow.WorkflowDefinitionCollection{}, 0, controlplanerpc.ClientError(err)
|
||||
}
|
||||
@@ -90,7 +90,7 @@ func (c *WorkflowDefinitionsClient) ReplaceWorkflowDefinitions(ctx context.Conte
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
response, err := c.rpc.Command(ctx, &pb.CommandRequest{Kind: WorkflowDefinitionsKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID})
|
||||
response, err := c.rpc.Command(ctx, controlplanerpc.CommandRequest(ctx, &pb.CommandRequest{Kind: WorkflowDefinitionsKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID}))
|
||||
if err != nil {
|
||||
return 0, controlplanerpc.ClientError(err)
|
||||
}
|
||||
@@ -98,7 +98,7 @@ func (c *WorkflowDefinitionsClient) ReplaceWorkflowDefinitions(ctx context.Conte
|
||||
}
|
||||
|
||||
func (c *Client) WorkflowExecutionSettings(ctx context.Context) (workflow.ExecutionSettings, int64, error) {
|
||||
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: WorkflowExecutionSettingsKind})
|
||||
response, err := c.rpc.Query(ctx, controlplanerpc.QueryRequest(ctx, WorkflowExecutionSettingsKind))
|
||||
if err != nil {
|
||||
return workflow.ExecutionSettings{}, 0, controlplanerpc.ClientError(err)
|
||||
}
|
||||
@@ -114,7 +114,7 @@ func (c *Client) ReplaceWorkflowExecutionSettings(ctx context.Context, settings
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
response, err := c.rpc.Command(ctx, &pb.CommandRequest{Kind: WorkflowExecutionSettingsKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID})
|
||||
response, err := c.rpc.Command(ctx, controlplanerpc.CommandRequest(ctx, &pb.CommandRequest{Kind: WorkflowExecutionSettingsKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID}))
|
||||
if err != nil {
|
||||
return 0, controlplanerpc.ClientError(err)
|
||||
}
|
||||
@@ -122,7 +122,7 @@ func (c *Client) ReplaceWorkflowExecutionSettings(ctx context.Context, settings
|
||||
}
|
||||
|
||||
func (c *Client) WatchWorkflowExecutionSettings(ctx context.Context, afterVersion int64) (<-chan AppliedSettings, error) {
|
||||
stream, err := c.rpc.Watch(ctx, &pb.WatchRequest{Kind: WorkflowExecutionSettingsKind, AfterVersion: afterVersion})
|
||||
stream, err := c.rpc.Watch(ctx, controlplanerpc.WatchRequest(ctx, WorkflowExecutionSettingsKind, afterVersion))
|
||||
if err != nil {
|
||||
return nil, controlplanerpc.ClientError(err)
|
||||
}
|
||||
@@ -152,7 +152,7 @@ type AppliedResource struct {
|
||||
// refused to decode -- the store answered with that version, and resuming
|
||||
// before it would re-offer it on every reconnect.
|
||||
func (c *Client) WatchResource(ctx context.Context, kind string, afterVersion int64) (<-chan AppliedResource, error) {
|
||||
stream, err := c.rpc.Watch(ctx, &pb.WatchRequest{Kind: kind, AfterVersion: afterVersion})
|
||||
stream, err := c.rpc.Watch(ctx, controlplanerpc.WatchRequest(ctx, kind, afterVersion))
|
||||
if err != nil {
|
||||
return nil, controlplanerpc.ClientError(err)
|
||||
}
|
||||
@@ -168,7 +168,7 @@ type AppliedSettings struct {
|
||||
}
|
||||
|
||||
func (c *Client) Personas(ctx context.Context) (agent.PersonaCollection, int64, error) {
|
||||
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: PersonasKind})
|
||||
response, err := c.rpc.Query(ctx, controlplanerpc.QueryRequest(ctx, PersonasKind))
|
||||
if err != nil {
|
||||
return agent.PersonaCollection{}, 0, controlplanerpc.ClientError(err)
|
||||
}
|
||||
@@ -183,7 +183,7 @@ type AppliedPersonas struct {
|
||||
}
|
||||
|
||||
func (c *Client) WatchPersonas(ctx context.Context, afterVersion int64) (<-chan AppliedPersonas, error) {
|
||||
stream, err := c.rpc.Watch(ctx, &pb.WatchRequest{Kind: PersonasKind, AfterVersion: afterVersion})
|
||||
stream, err := c.rpc.Watch(ctx, controlplanerpc.WatchRequest(ctx, PersonasKind, afterVersion))
|
||||
if err != nil {
|
||||
return nil, controlplanerpc.ClientError(err)
|
||||
}
|
||||
@@ -241,7 +241,7 @@ func sendUpdate[T any](ctx context.Context, out chan<- T, update T) bool {
|
||||
}
|
||||
|
||||
func (c *Client) Schedules(ctx context.Context) ([]scheduling.JobSpec, int64, error) {
|
||||
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: SchedulesKind})
|
||||
response, err := c.rpc.Query(ctx, controlplanerpc.QueryRequest(ctx, SchedulesKind))
|
||||
if err != nil {
|
||||
return nil, 0, controlplanerpc.ClientError(err)
|
||||
}
|
||||
@@ -257,7 +257,7 @@ func (c *Client) ReplaceSchedules(ctx context.Context, jobs []scheduling.JobSpec
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
response, err := c.rpc.Command(ctx, &pb.CommandRequest{Kind: SchedulesKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID})
|
||||
response, err := c.rpc.Command(ctx, controlplanerpc.CommandRequest(ctx, &pb.CommandRequest{Kind: SchedulesKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID}))
|
||||
if err != nil {
|
||||
return 0, controlplanerpc.ClientError(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package controlplane
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
// orgRecordingClient is the rpc end that records the org of every request it
|
||||
// is handed, so a test can read back what the client put on the wire.
|
||||
type orgRecordingClient struct {
|
||||
queryOrg string
|
||||
commandOrg string
|
||||
watchOrg string
|
||||
}
|
||||
|
||||
func (*orgRecordingClient) Catalog(context.Context, *pb.CatalogRequest, ...grpc.CallOption) (*pb.CatalogResponse, error) {
|
||||
panic("Catalog is not part of the org-stamping path")
|
||||
}
|
||||
|
||||
func (c *orgRecordingClient) Query(_ context.Context, in *pb.QueryRequest, _ ...grpc.CallOption) (*pb.QueryResponse, error) {
|
||||
c.queryOrg = in.GetOrgId()
|
||||
return &pb.QueryResponse{Resource: &pb.Resource{Kind: in.GetKind()}}, nil
|
||||
}
|
||||
|
||||
func (*orgRecordingClient) History(context.Context, *pb.HistoryRequest, ...grpc.CallOption) (*pb.HistoryResponse, error) {
|
||||
panic("History is not part of the org-stamping path")
|
||||
}
|
||||
|
||||
func (*orgRecordingClient) Audit(context.Context, *pb.AuditRequest, ...grpc.CallOption) (*pb.AuditResponse, error) {
|
||||
return &pb.AuditResponse{}, nil
|
||||
}
|
||||
|
||||
func (c *orgRecordingClient) Command(_ context.Context, in *pb.CommandRequest, _ ...grpc.CallOption) (*pb.CommandResponse, error) {
|
||||
c.commandOrg = in.GetOrgId()
|
||||
return &pb.CommandResponse{Resource: &pb.Resource{Version: 1}}, nil
|
||||
}
|
||||
|
||||
func (c *orgRecordingClient) Watch(_ context.Context, in *pb.WatchRequest, _ ...grpc.CallOption) (grpc.ServerStreamingClient[pb.WatchResponse], error) {
|
||||
c.watchOrg = in.GetOrgId()
|
||||
return eofWatchStream{}, nil
|
||||
}
|
||||
|
||||
// eofWatchStream is the client end of a stream that ends before it carries
|
||||
// anything: the watch under test only builds the request.
|
||||
type eofWatchStream struct{ grpc.ClientStream }
|
||||
|
||||
func (eofWatchStream) Recv() (*pb.WatchResponse, error) { return nil, io.EOF }
|
||||
|
||||
func TestClientStampsCallerOrgOnEveryRequestShape(t *testing.T) {
|
||||
// The table holds the org, not a context: a stored context.Context field is
|
||||
// what containedctx rejects, and each case only needs to say what the caller
|
||||
// put on its context.
|
||||
tests := []struct {
|
||||
name string
|
||||
orgID string
|
||||
want string
|
||||
}{
|
||||
{name: "no org on the context is the default org", want: string(org.DefaultOrgID)},
|
||||
{name: "org on the context travels on the wire", orgID: "acme", want: "acme"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
if tt.orgID != "" {
|
||||
ctx = org.WithOrg(ctx, org.OrgID(tt.orgID))
|
||||
}
|
||||
rpc := &orgRecordingClient{}
|
||||
client := NewRPCClient(rpc)
|
||||
|
||||
if _, _, err := client.Query(ctx, ChannelSettingsKind, func([]byte) error { return nil }); err != nil {
|
||||
t.Fatalf("Query: %v", err)
|
||||
}
|
||||
if _, err := client.ReplaceSchedules(ctx, nil, 0, "actor", "source", "request"); err != nil {
|
||||
t.Fatalf("ReplaceSchedules: %v", err)
|
||||
}
|
||||
if _, err := client.WatchResource(ctx, WorkflowExecutionSettingsKind, 0); err != nil {
|
||||
t.Fatalf("WatchResource: %v", err)
|
||||
}
|
||||
|
||||
if rpc.queryOrg != tt.want || rpc.commandOrg != tt.want || rpc.watchOrg != tt.want {
|
||||
t.Fatalf("wire orgs = query %q command %q watch %q, want %q each",
|
||||
rpc.queryOrg, rpc.commandOrg, rpc.watchOrg, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -31,8 +31,8 @@ var (
|
||||
// root asserts the State Store against it, so this is the single definition of
|
||||
// what a control-plane backing store must offer.
|
||||
type ResourceStore interface {
|
||||
Resource(context.Context, string) (storecontract.Resource, error)
|
||||
ResourceHistory(context.Context, string, int) ([]storecontract.Resource, error)
|
||||
Resource(ctx context.Context, orgID, kind string) (storecontract.Resource, error)
|
||||
ResourceHistory(ctx context.Context, orgID, kind string, limit int) ([]storecontract.Resource, error)
|
||||
Audit(ctx context.Context, table string, keys []string, limit int) ([]storecontract.AuditEntry, error)
|
||||
PutResource(context.Context, storecontract.ResourceWrite) (storecontract.Resource, error)
|
||||
}
|
||||
@@ -78,7 +78,7 @@ func (s *Server) Query(ctx context.Context, request *pb.QueryRequest) (*pb.Query
|
||||
if _, ok := s.definitions[request.GetKind()]; !ok {
|
||||
return nil, status.Error(codes.NotFound, "resource not found")
|
||||
}
|
||||
resource, err := s.store.Resource(ctx, request.Kind)
|
||||
resource, err := s.store.Resource(ctx, requestOrg(request.GetOrgId()), request.Kind)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
@@ -96,7 +96,7 @@ func (s *Server) History(ctx context.Context, request *pb.HistoryRequest) (*pb.H
|
||||
if limit <= 0 || limit > defaultHistoryLimit {
|
||||
limit = defaultHistoryLimit
|
||||
}
|
||||
revisions, err := s.store.ResourceHistory(ctx, request.Kind, limit)
|
||||
revisions, err := s.store.ResourceHistory(ctx, requestOrg(request.GetOrgId()), request.Kind, limit)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
@@ -149,7 +149,7 @@ func (s *Server) Command(ctx context.Context, request *pb.CommandRequest) (*pb.C
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
resource, err := s.store.PutResource(ctx, storecontract.ResourceWrite{Kind: request.Kind, Value: value, Actor: request.Actor, Source: request.Source, RequestID: request.RequestId, ExpectedVersion: request.ExpectedVersion, At: time.Now().UTC()})
|
||||
resource, err := s.store.PutResource(ctx, storecontract.ResourceWrite{OrgID: requestOrg(request.GetOrgId()), Kind: request.Kind, Value: value, Actor: request.Actor, Source: request.Source, RequestID: request.RequestId, ExpectedVersion: request.ExpectedVersion, At: time.Now().UTC()})
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
@@ -164,7 +164,7 @@ func (s *Server) Watch(request *pb.WatchRequest, stream pb.ControlPlaneService_W
|
||||
ticker := time.NewTicker(250 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
resource, err := s.store.Resource(stream.Context(), request.Kind)
|
||||
resource, err := s.store.Resource(stream.Context(), requestOrg(request.GetOrgId()), request.Kind)
|
||||
if err == nil && resource.Version > version {
|
||||
if err := stream.Send(&pb.WatchResponse{Resource: resourceProto(resource)}); err != nil {
|
||||
return err
|
||||
@@ -182,7 +182,16 @@ func (s *Server) Watch(request *pb.WatchRequest, stream pb.ControlPlaneService_W
|
||||
}
|
||||
|
||||
func resourceProto(resource storecontract.Resource) *pb.Resource {
|
||||
return &pb.Resource{Kind: resource.Kind, Version: resource.Version, ValueJson: resource.Value, UpdatedAt: timestamp(resource.At)}
|
||||
return &pb.Resource{OrgId: resource.OrgID, Kind: resource.Kind, Version: resource.Version, ValueJson: resource.Value, UpdatedAt: timestamp(resource.At)}
|
||||
}
|
||||
|
||||
// requestOrg is the org a request acts in. Until the caller's org is derived
|
||||
// server-side (access), a request that names none acts in the default org.
|
||||
func requestOrg(orgID string) string {
|
||||
if orgID == "" {
|
||||
return storecontract.DefaultOrgID
|
||||
}
|
||||
return orgID
|
||||
}
|
||||
|
||||
func timestamp(value time.Time) *timestamppb.Timestamp {
|
||||
|
||||
@@ -79,7 +79,7 @@ func TestImportConfigSeedsWorkflowDefinitionsWithoutOverwritingOverride(t *testi
|
||||
if _, _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resource, err := resources.Resource(t.Context(), WorkflowDefinitionsKind)
|
||||
resource, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, WorkflowDefinitionsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -95,13 +95,13 @@ func TestImportConfigSeedsWorkflowDefinitionsWithoutOverwritingOverride(t *testi
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{Kind: WorkflowDefinitionsKind, Value: value, ExpectedVersion: resource.Version, Actor: "test", Source: "test", RequestID: "override"}); err != nil {
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{OrgID: storecontract.DefaultOrgID, Kind: WorkflowDefinitionsKind, Value: value, ExpectedVersion: resource.Version, Actor: "test", Source: "test", RequestID: "override"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := resources.Resource(t.Context(), WorkflowDefinitionsKind)
|
||||
got, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, WorkflowDefinitionsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -119,7 +119,7 @@ func TestImportConfigSeedsPersonasWithoutOverwritingEdits(t *testing.T) {
|
||||
if _, _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resource, err := resources.Resource(t.Context(), PersonasKind)
|
||||
resource, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, PersonasKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -132,13 +132,13 @@ func TestImportConfigSeedsPersonasWithoutOverwritingEdits(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{Kind: PersonasKind, Value: value, ExpectedVersion: resource.Version, Actor: "test", Source: "test", RequestID: "persona-edit"}); err != nil {
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{OrgID: storecontract.DefaultOrgID, Kind: PersonasKind, Value: value, ExpectedVersion: resource.Version, Actor: "test", Source: "test", RequestID: "persona-edit"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := resources.Resource(t.Context(), PersonasKind)
|
||||
got, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, PersonasKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -161,7 +161,7 @@ func TestImportWorkflowExecutionSettingsDoesNotOverwriteExistingValue(t *testing
|
||||
if _, err := server.ImportWorkflowExecutionSettings(t.Context(), workflow.ExecutionSettings{MaxModelToolSteps: 99, MaxRuntime: time.Hour, MaxConsecutiveGateFailures: 9}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resource, err := resources.Resource(t.Context(), WorkflowExecutionSettingsKind)
|
||||
resource, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, WorkflowExecutionSettingsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -186,7 +186,7 @@ func TestRegistryRoutesAndValidatesDefinitions(t *testing.T) {
|
||||
if _, _, err := server.ImportConfig(t.Context(), config.Config{Containers: config.ContainerConfig{Image: "archie-agent:test", PullPolicy: "missing"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := resources.Resource(t.Context(), ContainerRuntimePoliciesKind); err != nil {
|
||||
if _, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, ContainerRuntimePoliciesKind); err != nil {
|
||||
t.Fatalf("container runtime policies were not seeded: %v", err)
|
||||
}
|
||||
|
||||
@@ -220,7 +220,7 @@ func TestProviderSeedKeepsReferencesAndNeverResolvedSecrets(t *testing.T) {
|
||||
if _, _, err := server.ImportConfig(context.Background(), cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resource, err := resources.Resource(t.Context(), ProviderSettingsKind)
|
||||
resource, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, ProviderSettingsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -308,12 +308,38 @@ func TestImportConfigSkipsASeedItCannotValidate(t *testing.T) {
|
||||
if len(skipped) != 1 || skipped[0].Kind != RepositoryPoliciesKind || skipped[0].Err == nil {
|
||||
t.Fatalf("skipped = %+v, want the repository policies and the reason", skipped)
|
||||
}
|
||||
if _, err := resources.Resource(t.Context(), RepositoryPoliciesKind); !errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
if _, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, RepositoryPoliciesKind); !errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
t.Errorf("repository policies Resource = %v, want ErrResourceNotFound: an invalid seed must not be stored", err)
|
||||
}
|
||||
// Kinds that are fine are still seeded: one skipped kind does not abandon
|
||||
// the rest of the migration.
|
||||
if _, err := resources.Resource(t.Context(), WorkflowDefinitionsKind); err != nil {
|
||||
if _, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, WorkflowDefinitionsKind); err != nil {
|
||||
t.Errorf("workflow definitions: %v, want them seeded alongside the skipped kind", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A request names the org whose copy of a kind it acts on; one naming none acts
|
||||
// in the default org, so a write for one org is invisible to the others.
|
||||
func TestControlPlaneRequestsActInTheirOrg(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
server := testServer(t, resources)
|
||||
written, err := server.Command(t.Context(), &pb.CommandRequest{
|
||||
Kind: WorkflowEnablementKind, Command: "replace", ValueJson: []byte(`{"orgs":{}}`),
|
||||
Actor: "test", Source: "test", RequestId: "acme-write", OrgId: "acme",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if written.Resource.OrgId != "acme" || written.Resource.Version != 1 {
|
||||
t.Fatalf("written = %+v, want acme at version 1", written.Resource)
|
||||
}
|
||||
if _, err := server.Query(t.Context(), &pb.QueryRequest{Kind: WorkflowEnablementKind, OrgId: "acme"}); err != nil {
|
||||
t.Fatalf("acme Query: %v", err)
|
||||
}
|
||||
if _, err := server.Query(t.Context(), &pb.QueryRequest{Kind: WorkflowEnablementKind}); status.Code(err) != codes.NotFound {
|
||||
t.Fatalf("default-org Query = %v, want NotFound: acme's write leaked into the default org", err)
|
||||
}
|
||||
}
|
||||
@@ -285,7 +285,7 @@ func TestWatchServesOnlyVersionsAfterTheRequestedOne(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := resources.PutResource(ctx, storecontract.ResourceWrite{Kind: WorkflowExecutionSettingsKind, Value: value, ExpectedVersion: version, Actor: "test", Source: "test", RequestID: "watch-next"}); err != nil {
|
||||
if _, err := resources.PutResource(ctx, storecontract.ResourceWrite{OrgID: storecontract.DefaultOrgID, Kind: WorkflowExecutionSettingsKind, Value: value, ExpectedVersion: version, Actor: "test", Source: "test", RequestID: "watch-next"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
// Schemas are not declared here: each Definition names its document type, and
|
||||
// Definition.Descriptor derives the JSON Schema from it (internal/app/controlplane/schema.go).
|
||||
func builtinDefinitions(steps workflow.StepRegistry) []Definition {
|
||||
definitions := []Definition{workflowDefinition(), workflowDefinitionsDefinition(steps), personaDefinition(), scheduleDefinition(), agentProfileDefinition(), credentialBindingsDefinition()}
|
||||
definitions := []Definition{workflowDefinition(), workflowDefinitionsDefinition(steps), workflowEnablementDefinition(), personaDefinition(), scheduleDefinition(), agentProfileDefinition(), credentialBindingsDefinition()}
|
||||
definitions = append(definitions, modelDefinitions()...)
|
||||
definitions = append(definitions, operationalDefinitions()...)
|
||||
return definitions
|
||||
|
||||
@@ -45,7 +45,7 @@ func TestImportConfigRefusesAResolvedProviderSnapshot(t *testing.T) {
|
||||
if !reported {
|
||||
t.Errorf("skipped = %+v, want provider-settings reported", skipped)
|
||||
}
|
||||
if _, err := resources.Resource(t.Context(), ProviderSettingsKind); err == nil {
|
||||
if _, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, ProviderSettingsKind); err == nil {
|
||||
t.Fatal("provider-settings was stored from a resolved snapshot")
|
||||
} else if !strings.Contains(err.Error(), "not found") {
|
||||
t.Fatalf("Resource = %v, want %v", err, storecontract.ErrResourceNotFound)
|
||||
|
||||
@@ -53,12 +53,33 @@ func operationalDefinitions() []Definition {
|
||||
}
|
||||
}
|
||||
|
||||
// validatePluginSettings accepts every value: the four directories are free-form
|
||||
// operator paths with no cross-field rule and no rule the configuration package
|
||||
// applies either (configuration.Validate has no say over them), so there is
|
||||
// nothing yet for this validator to enforce. It stays a real function rather than
|
||||
// an inline no-op so the place to add a rule is obvious when one exists -- e.g.
|
||||
// "a path that is absolute" or "a skills dir under the plugin dir".
|
||||
// validatePluginSettings accepts every value, deliberately. The four directories
|
||||
// are free-form operator paths, and that is the decision recorded for
|
||||
// archie-core #1143 rather than a validator nobody has written yet.
|
||||
//
|
||||
// Two candidate rules were considered and are refused:
|
||||
//
|
||||
// - That the directory must exist. Every consumer reads a missing directory as
|
||||
// an empty one by design: plugin.LoadDir and secret.Registry.LoadDir return
|
||||
// no entries and no error on os.IsNotExist, loadModules skips a kind whose
|
||||
// file is absent, and playbook.Load returns an empty store. The no-error half
|
||||
// is pinned by internal/secret's TestLoadDirNonexistent. An existence rule
|
||||
// would turn each of those deliberate no-ops into a refused startup.
|
||||
// - That the path must be absolute, or that skills_dir must sit under
|
||||
// plugin_dir. No directory setting in this repository is validated for shape
|
||||
// (work_dir, state_dir, chat.workspace, the routing and playbook paths and an
|
||||
// MCP server's work_dir are all free-form), so a rule for these four alone
|
||||
// would be arbitrary. It would also fail closed in the wrong place: a stored
|
||||
// document is layered over the file and the boot path validates the result,
|
||||
// so a rule added here refuses to start a daemon whose only problem is a
|
||||
// value the store already holds.
|
||||
//
|
||||
// A "~/..." value is not the missing rule either: it is a path-expansion
|
||||
// concern, handled where the file is read (configuration.applyGeneralDefaults),
|
||||
// not a reason to refuse the document.
|
||||
//
|
||||
// It stays a real function rather than an inline no-op so that a rule, if one is
|
||||
// ever settled, has one obvious home.
|
||||
func validatePluginSettings(input []byte) error {
|
||||
return validateAs(input, func(pluginSettings) error { return nil })
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ package controlplane
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -73,14 +75,47 @@ type SeedSkip struct {
|
||||
Err error
|
||||
}
|
||||
|
||||
// ImportConfig seeds every control-plane resource that has no stored value yet
|
||||
// from the file config, and reports the version of every kind it left alone.
|
||||
// The audit identity every seed writes under. It is a constant rather than a
|
||||
// literal at each call site because a later boot reads it back: it is how a
|
||||
// stored value is told apart from one an operator replaced (seedWroteNewest),
|
||||
// and a writer whose identity its own reader cannot name cannot make that
|
||||
// distinction at all.
|
||||
const (
|
||||
seedActor = "system:migration"
|
||||
seedSource = "legacy-config"
|
||||
)
|
||||
|
||||
// ImportConfig brings every control-plane resource up to date with the value
|
||||
// this build seeds for it, and reports the version each kind is left at.
|
||||
//
|
||||
// A seed the resource's own validator refuses is SKIPPED and returned in skipped,
|
||||
// not fatal. Nothing is written for that kind, so it stays ABSENT and the file
|
||||
// document's value stays the one in effect (Client.RuntimeConfig leaves an absent
|
||||
// kind alone), with the fix still in the file. The seed is retried on the next
|
||||
// start of this process, so correcting config.toml re-seeds it.
|
||||
// For a kind the store does not hold, that is the seed itself. For a kind it
|
||||
// does hold, the stored value wins and the seed writes nothing -- with one
|
||||
// exception, because the two ways a kind gets its content are not symmetric:
|
||||
//
|
||||
// - A kind derived from the file config is seeded once and then owned by the
|
||||
// store. Editing config.toml does not reach a database that holds a value
|
||||
// for it, which is the whole point of the file being only a seed.
|
||||
// - A kind whose document the build ships (the ones that set Definition.Defaults,
|
||||
// the same set the catalog offers as "restore shipped") is not derived from
|
||||
// operator input at all, so a stored copy is a copy of an older build's
|
||||
// document and nothing else. A value like that is brought up to date, or a
|
||||
// State Store upgraded under a running deployment keeps serving the previous
|
||||
// release's document forever. For workflow-definitions that is not a stale
|
||||
// setting but an outage: the collection validates as one document, so a
|
||||
// stored step type this build no longer has fails every task's pin, whatever
|
||||
// workflow the task names.
|
||||
//
|
||||
// A refreshed kind keeps its history: the value it replaced stays a revision in
|
||||
// resource_history. What is replaced is only the seed's own work -- a
|
||||
// definition set an operator replaced is theirs and is left alone, on the boot
|
||||
// that finds it and on every boot after.
|
||||
//
|
||||
// A seed the resource's own validator refuses is SKIPPED and returned in
|
||||
// skipped, not fatal. Nothing is written for that kind, so it stays ABSENT and
|
||||
// the file document's value stays the one in effect (Client.RuntimeConfig
|
||||
// leaves an absent kind alone), with the fix still in the file. The seed is
|
||||
// retried on the next start of this process, so correcting config.toml re-seeds
|
||||
// it.
|
||||
// docs/prds/runtime-control-plane.md, "Bootstrap, migration, and recovery":
|
||||
// after migration, settings in TOML are ignored and cannot block State Store
|
||||
// startup -- and this import runs on the State Store's startup path. Fail closed
|
||||
@@ -91,35 +126,130 @@ func (s *Server) ImportConfig(ctx context.Context, cfg config.Config) (map[strin
|
||||
versions := make(map[string]int64, len(s.ordered))
|
||||
var skipped []SeedSkip
|
||||
for _, definition := range s.ordered {
|
||||
resource, err := s.store.Resource(ctx, definition.Kind)
|
||||
if err == nil {
|
||||
versions[definition.Kind] = resource.Version
|
||||
continue
|
||||
}
|
||||
if !errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
version, err := s.seedKind(ctx, definition, cfg)
|
||||
var refusal *seedRefusal
|
||||
switch {
|
||||
case errors.As(err, &refusal):
|
||||
skipped = append(skipped, SeedSkip{Kind: definition.Kind, Err: refusal.err})
|
||||
case err != nil:
|
||||
return nil, nil, err
|
||||
default:
|
||||
versions[definition.Kind] = version
|
||||
}
|
||||
value, err := definition.seededValue(cfg)
|
||||
if err != nil {
|
||||
// Skipped and reported, not fatal: nothing is written, so the kind
|
||||
// stays absent and the file document's value is the one in effect,
|
||||
// while the process that would RUN the value still fails closed on
|
||||
// it (boot.runtimeConfig validates the effective document).
|
||||
// seededValue wraps a seed's encode and validation failures together,
|
||||
// which is why both take this path: the alternative is a second seed
|
||||
// implementation here to tell them apart.
|
||||
skipped = append(skipped, SeedSkip{Kind: definition.Kind, Err: err})
|
||||
continue
|
||||
}
|
||||
resource, err = s.store.PutResource(ctx, storecontract.ResourceWrite{Kind: definition.Kind, Value: value, Actor: "system:migration", Source: "legacy-config", RequestID: "import:" + definition.Kind, ExpectedVersion: 0, At: time.Now().UTC()})
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("seed %s: %w", definition.Kind, err)
|
||||
}
|
||||
versions[definition.Kind] = resource.Version
|
||||
}
|
||||
return versions, skipped, nil
|
||||
}
|
||||
|
||||
// seedRefusal is the seed's own validation refusing the value this build
|
||||
// derived. It is an error because it is one -- there is nothing to write -- and a
|
||||
// distinct type because ImportConfig answers it by reporting the kind rather
|
||||
// than failing the boot (see ImportConfig on why a bad seed is not fatal).
|
||||
type seedRefusal struct{ err error }
|
||||
|
||||
func (r *seedRefusal) Error() string { return r.err.Error() }
|
||||
|
||||
func (r *seedRefusal) Unwrap() error { return r.err }
|
||||
|
||||
// seedKind seeds one kind if the store holds nothing for it, refreshes a
|
||||
// shipped document the seed itself wrote, and otherwise leaves the stored value
|
||||
// alone, returning the version the kind is left at. A *seedRefusal means the
|
||||
// value this build derived is not one the resource's validator accepts, and
|
||||
// nothing was written.
|
||||
func (s *Server) seedKind(ctx context.Context, definition Definition, cfg config.Config) (int64, error) {
|
||||
stored, storedErr := s.store.Resource(ctx, storecontract.DefaultOrgID, definition.Kind)
|
||||
absent := errors.Is(storedErr, storecontract.ErrResourceNotFound)
|
||||
if storedErr != nil && !absent {
|
||||
return 0, storedErr
|
||||
}
|
||||
value, err := definition.seededValue(cfg)
|
||||
if err != nil {
|
||||
// Skipped and reported, not fatal: nothing is written, so the kind
|
||||
// stays absent and the file document's value is the one in effect,
|
||||
// while the process that would RUN the value still fails closed on
|
||||
// it (boot.runtimeConfig validates the effective document).
|
||||
// seededValue wraps a seed's encode and validation failures together,
|
||||
// which is why both take this path: the alternative is a second seed
|
||||
// implementation here to tell them apart.
|
||||
return 0, &seedRefusal{err: err}
|
||||
}
|
||||
if !absent && bytes.Equal(stored.Value, value) {
|
||||
// The store already holds what this build seeds. Comparing the values
|
||||
// rather than re-writing them is what keeps a boot from adding a
|
||||
// revision for a document that did not change.
|
||||
return stored.Version, nil
|
||||
}
|
||||
if !absent {
|
||||
refresh, err := s.shippedValueIsStale(ctx, definition)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !refresh {
|
||||
return stored.Version, nil
|
||||
}
|
||||
}
|
||||
write := storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID, Kind: definition.Kind, Value: value,
|
||||
Actor: seedActor, Source: seedSource,
|
||||
RequestID: seedRequestID(definition.Kind, value),
|
||||
ExpectedVersion: expectedVersion(stored, absent), At: time.Now().UTC(),
|
||||
}
|
||||
resource, err := s.store.PutResource(ctx, write)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("seed %s: %w", definition.Kind, err)
|
||||
}
|
||||
return resource.Version, nil
|
||||
}
|
||||
|
||||
// expectedVersion is the optimistic-concurrency guard a seed writes under: the
|
||||
// revision it is replacing, or nothing at all for a kind that has none.
|
||||
func expectedVersion(stored storecontract.Resource, absent bool) int64 {
|
||||
if absent {
|
||||
return 0
|
||||
}
|
||||
return stored.Version
|
||||
}
|
||||
|
||||
// shippedValueIsStale reports whether a stored value is the build's to replace:
|
||||
// the kind ships a document of its own (Defaults is set exactly for those, and
|
||||
// a file-derived seed never overwrites a stored value) and the revision the
|
||||
// seed itself wrote is the newest one. A newer revision carrying any other
|
||||
// identity is an operator's replacement, and an operator's replacement is not
|
||||
// the seed's to undo.
|
||||
func (s *Server) shippedValueIsStale(ctx context.Context, definition Definition) (bool, error) {
|
||||
if definition.Defaults == nil {
|
||||
return false, nil
|
||||
}
|
||||
return s.seedWroteNewest(ctx, definition.Kind)
|
||||
}
|
||||
|
||||
// seedWroteNewest reports whether the newest revision of kind was written by a
|
||||
// seed. It reads the ledger rather than the current row because the ledger is
|
||||
// what records who wrote a value, and the row does not.
|
||||
func (s *Server) seedWroteNewest(ctx context.Context, kind string) (bool, error) {
|
||||
history, err := s.store.ResourceHistory(ctx, storecontract.DefaultOrgID, kind, 1)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("read %s history: %w", kind, err)
|
||||
}
|
||||
if len(history) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
return history[0].Actor == seedActor && history[0].Source == seedSource, nil
|
||||
}
|
||||
|
||||
// seedRequestID is the idempotency key a seed writes under. It is derived from
|
||||
// the value rather than from the kind alone, because the key is spent the
|
||||
// moment it is in the ledger (resource_history's UNIQUE (kind, request_id), and
|
||||
// PutResource answers a known key from that ledger): a key derived from the
|
||||
// kind makes every later value a replay of the first one ever written, which is
|
||||
// how a document that changed in the build never reached a database the seed
|
||||
// had already written. Deriving it from the value keeps the write idempotent --
|
||||
// the same document twice is still one revision -- without making the second
|
||||
// document impossible.
|
||||
func seedRequestID(kind string, value []byte) string {
|
||||
sum := sha256.Sum256(value)
|
||||
return "import:" + kind + ":" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// seededValue is the value the State Store writes for a kind it does not hold
|
||||
// yet: the definition's seed derived from cfg, run through the same Decode a
|
||||
// write applies. ImportConfig stores it; the offline config layering reads it
|
||||
@@ -175,7 +305,7 @@ func (s *Server) ValidateStored(ctx context.Context) (int, error) {
|
||||
checked := 0
|
||||
var failures []error
|
||||
for _, definition := range s.ordered {
|
||||
resource, err := s.store.Resource(ctx, definition.Kind)
|
||||
resource, err := s.store.Resource(ctx, storecontract.DefaultOrgID, definition.Kind)
|
||||
if errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
package controlplane
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// retiredStepType names a step type no registry declares. A stored collection
|
||||
// carrying one is what a database seeded by an earlier release holds once a
|
||||
// built-in workflow's step vocabulary changes under it.
|
||||
const retiredStepType = "legacy.retired-step"
|
||||
|
||||
// staleWorkflowDefinitions is a stored workflow-definitions value this build
|
||||
// refuses. ValidateDefinitionCollection validates the collection as one
|
||||
// document, which is what makes one stale entry fail every task's pin, whatever
|
||||
// workflow that task names.
|
||||
//
|
||||
// It is encoded directly rather than through encodeWorkflowDefinitions, because
|
||||
// that runs the validator a write applies: the point of the fixture is the
|
||||
// document an earlier release wrote, which this build's write path would refuse
|
||||
// (the validator cannot bless the value whose rejection is the bug reported).
|
||||
func staleWorkflowDefinitions(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
value, err := json.Marshal(workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{
|
||||
{ID: "legacy", YAML: "id: legacy\nsteps:\n - type: " + retiredStepType + "\n"},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("encode the stale definitions: %v", err)
|
||||
}
|
||||
if _, err := workflow.DecodeDefinitionCollection(value, testSteps(t).Registry()); err == nil {
|
||||
t.Fatal("the stored value under test decodes; it is not the stale state this test is about")
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// writeSeeded writes value as the revision an earlier release's seed left
|
||||
// behind: the seed's own audit identity, and the seed's own request ID for that
|
||||
// value. The producer supplies both -- the value is the only thing substituted
|
||||
// -- so a test does not restate a key or an identity it would then be pinning.
|
||||
func writeSeeded(t *testing.T, resources *pgstore.TaskDB, kind string, value []byte) storecontract.Resource {
|
||||
t.Helper()
|
||||
if current, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, kind); err == nil {
|
||||
t.Fatalf("%s already holds version %d; a seeded fixture writes the first revision", kind, current.Version)
|
||||
} else if !errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
t.Fatalf("read %s: %v", kind, err)
|
||||
}
|
||||
seeded, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: kind, Value: value, ExpectedVersion: 0,
|
||||
Actor: seedActor, Source: seedSource, RequestID: seedRequestID(kind, value),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("write the seeded %s revision: %v", kind, err)
|
||||
}
|
||||
return seeded
|
||||
}
|
||||
|
||||
// replaceAsOperator replaces a kind the way the dashboard does: a write carrying
|
||||
// the operator's attribution, which is what marks the value as theirs.
|
||||
func replaceAsOperator(t *testing.T, resources *pgstore.TaskDB, kind string, value []byte, expected int64) storecontract.Resource {
|
||||
t.Helper()
|
||||
replaced, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: kind, Value: value, ExpectedVersion: expected,
|
||||
Actor: "operator", Source: "archie-ui", RequestID: "operator-replace-" + kind,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("replace %s: %v", kind, err)
|
||||
}
|
||||
return replaced
|
||||
}
|
||||
|
||||
// TestImportConfigRefreshesAStaleShippedValue is defect 1 of #1233. A seed was
|
||||
// consulted only for a kind the store did not hold, so a document that changed
|
||||
// in the build never reached a database an earlier release seeded -- and for
|
||||
// workflow-definitions that is not a stale setting but an outage, because the
|
||||
// collection validates as one document and a step type this build no longer has
|
||||
// fails every task's pin.
|
||||
func TestImportConfigRefreshesAStaleShippedValue(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
server := testServer(t, resources)
|
||||
// The state under test is "the seed's own document, one release old" -- the
|
||||
// state the issue reports -- rather than "a value somebody else wrote",
|
||||
// which is the distinction the refresh turns on.
|
||||
seeded := writeSeeded(t, resources, WorkflowDefinitionsKind, staleWorkflowDefinitions(t))
|
||||
|
||||
versions, _, err := server.ImportConfig(t.Context(), config.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("ImportConfig: %v", err)
|
||||
}
|
||||
refreshed, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, WorkflowDefinitionsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if refreshed.Version <= seeded.Version {
|
||||
t.Fatalf("%s is still at version %d: the stale seed value was not replaced", WorkflowDefinitionsKind, refreshed.Version)
|
||||
}
|
||||
definitions, err := workflow.DecodeDefinitionCollection(refreshed.Value, testSteps(t).Registry())
|
||||
if err != nil {
|
||||
t.Fatalf("the stored workflow definitions still do not decode, so no task can pin: %v", err)
|
||||
}
|
||||
if len(definitions.Definitions) != len(workflow.ShippedDefinitions().Definitions) {
|
||||
t.Fatalf("stored definitions = %d, want the shipped %d", len(definitions.Definitions), len(workflow.ShippedDefinitions().Definitions))
|
||||
}
|
||||
if versions[WorkflowDefinitionsKind] != refreshed.Version {
|
||||
t.Fatalf("the import reported version %d, want the version the store holds, %d", versions[WorkflowDefinitionsKind], refreshed.Version)
|
||||
}
|
||||
// A refresh is a write like any other: what it replaced stays a revision, so
|
||||
// the value the previous release shipped is still readable.
|
||||
history, err := resources.ResourceHistory(t.Context(), storecontract.DefaultOrgID, WorkflowDefinitionsKind, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(history) != 2 || !bytes.Equal(history[1].Value, staleWorkflowDefinitions(t)) {
|
||||
t.Fatalf("history = %+v, want the replaced value kept as a revision", history)
|
||||
}
|
||||
}
|
||||
|
||||
// TestImportConfigLeavesASeededValueAloneOnceItMatches pins the other half of the
|
||||
// refresh: a boot that finds the value it would write writes nothing. A seed that
|
||||
// re-wrote its own document on every start would add a revision per boot, and the
|
||||
// revision an operator reads as "what I am running" would move for no reason.
|
||||
func TestImportConfigLeavesASeededValueAloneOnceItMatches(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
server := testServer(t, resources)
|
||||
for attempt := 1; attempt <= 2; attempt++ {
|
||||
if _, _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
|
||||
t.Fatalf("ImportConfig %d: %v", attempt, err)
|
||||
}
|
||||
stored, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, WorkflowDefinitionsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored.Version != 1 {
|
||||
t.Fatalf("after %d seed(s) %s is at version %d, want the one revision", attempt, WorkflowDefinitionsKind, stored.Version)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestImportConfigKeepsAStoredValueThatIsNotTheSeeds pins the half the refresh
|
||||
// must not break. The seed writes a value it produced itself; a value it did not
|
||||
// produce is somebody's, and two kinds of somebody are covered here:
|
||||
//
|
||||
// - an operator's replacement, which the seed must leave alone on the boot
|
||||
// that finds it and on every boot after -- a refresh that consulted the
|
||||
// store's copy rather than the ledger would take the value back the moment
|
||||
// it had written it once;
|
||||
// - a kind derived from the file config, where the file is only a seed by
|
||||
// design, so a changed config.toml does not reach a database that holds a
|
||||
// value for it.
|
||||
func TestImportConfigKeepsAStoredValueThatIsNotTheSeeds(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
kind string
|
||||
// settle leaves the store holding the value the imports must not touch,
|
||||
// and returns that value.
|
||||
settle func(t *testing.T, resources *pgstore.TaskDB) []byte
|
||||
// cfg is the file config the imports run with. For the file-derived
|
||||
// case it names a different value from the one that was seeded.
|
||||
cfg func() config.Config
|
||||
// verify checks the stored value after the imports, given the value
|
||||
// settle left behind.
|
||||
verify func(t *testing.T, got, want []byte)
|
||||
}{
|
||||
{
|
||||
name: "an operator's replacement, whose shipped document also moved on",
|
||||
kind: WorkflowDefinitionsKind,
|
||||
cfg: func() config.Config { return config.Config{} },
|
||||
settle: func(t *testing.T, resources *pgstore.TaskDB) []byte {
|
||||
t.Helper()
|
||||
// The seed wrote a document this build refuses, and the operator
|
||||
// then replaced it. The stored value is therefore neither the
|
||||
// seed's nor the one this build ships, which is exactly the
|
||||
// state a refresh keyed on authorship has to leave alone.
|
||||
seeded := writeSeeded(t, resources, WorkflowDefinitionsKind, staleWorkflowDefinitions(t))
|
||||
value, err := encodeWorkflowDefinitions(workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{
|
||||
{ID: "operator-only", YAML: "id: operator-only\nsteps:\n - type: bootstrap.apply\n"},
|
||||
}}, testSteps(t).Registry())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return replaceAsOperator(t, resources, WorkflowDefinitionsKind, value, seeded.Version).Value
|
||||
},
|
||||
verify: func(t *testing.T, got, want []byte) {
|
||||
t.Helper()
|
||||
definitions, err := workflow.DecodeDefinitionCollection(got, testSteps(t).Registry())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, want) || len(definitions.Definitions) != 1 || definitions.Definitions[0].ID != "operator-only" {
|
||||
t.Fatalf("stored value = %s, want the operator's replacement kept", got)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a value derived from the file config, whose config.toml changed",
|
||||
kind: RepositoryPoliciesKind,
|
||||
cfg: func() config.Config {
|
||||
cfg := validConfigForValidation()
|
||||
cfg.Repos = []config.Repo{{Owner: "acme", Name: "widget"}}
|
||||
return cfg
|
||||
},
|
||||
settle: func(t *testing.T, resources *pgstore.TaskDB) []byte {
|
||||
t.Helper()
|
||||
resolved := validConfigForValidation()
|
||||
resolved.Repos = []config.Repo{{Owner: "acme", Name: "app"}}
|
||||
if _, _, err := testServer(t, resources).ImportConfig(t.Context(), resolved); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, RepositoryPoliciesKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return stored.Value
|
||||
},
|
||||
verify: func(t *testing.T, got, want []byte) {
|
||||
t.Helper()
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("stored repository policies = %s, want the seeded %s: the file is a seed, not the owner", got, want)
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
server := testServer(t, resources)
|
||||
want := tt.settle(t, resources)
|
||||
before, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, tt.kind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for attempt := 1; attempt <= 2; attempt++ {
|
||||
versions, _, err := server.ImportConfig(t.Context(), tt.cfg())
|
||||
if err != nil {
|
||||
t.Fatalf("ImportConfig %d: %v", attempt, err)
|
||||
}
|
||||
after, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, tt.kind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after.Version != before.Version {
|
||||
t.Fatalf("import %d moved %s from version %d to %d: the stored value is not the seed's to replace",
|
||||
attempt, tt.kind, before.Version, after.Version)
|
||||
}
|
||||
if versions[tt.kind] != before.Version {
|
||||
t.Fatalf("import %d reported version %d for %s, want the stored %d", attempt, versions[tt.kind], tt.kind, before.Version)
|
||||
}
|
||||
tt.verify(t, after.Value, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestImportConfigRecreatesAKindAnOperatorRemoved is defect 2 of #1233: the
|
||||
// documented recovery -- remove the resource, restart -- wrote nothing. The seed's
|
||||
// request ID is in resource_history, that ledger outlives the row it describes,
|
||||
// and a write whose request ID is already in the ledger is answered as a replay,
|
||||
// so the seed reported a version for a kind that was not there and left it absent.
|
||||
func TestImportConfigRecreatesAKindAnOperatorRemoved(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
resources := pgstore.Open(t)
|
||||
defer resources.Close()
|
||||
server := testServer(t, resources)
|
||||
if _, _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seeded, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, WorkflowDefinitionsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
history, err := resources.ResourceHistory(t.Context(), storecontract.DefaultOrgID, WorkflowDefinitionsKind, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(history) != 1 {
|
||||
t.Fatalf("seed revisions = %d, want the one the removal leaves behind", len(history))
|
||||
}
|
||||
|
||||
if _, err := resources.Pool.Exec(t.Context(), `DELETE FROM resources WHERE kind = $1`, WorkflowDefinitionsKind); err != nil {
|
||||
t.Fatalf("remove the resource: %v", err)
|
||||
}
|
||||
if _, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, WorkflowDefinitionsKind); !errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
t.Fatalf("resource after the removal = %v, want ErrResourceNotFound", err)
|
||||
}
|
||||
|
||||
if _, _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
|
||||
t.Fatalf("ImportConfig after the removal: %v", err)
|
||||
}
|
||||
restored, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, WorkflowDefinitionsKind)
|
||||
if err != nil {
|
||||
t.Fatalf("the removed %s was not re-seeded: %v", WorkflowDefinitionsKind, err)
|
||||
}
|
||||
if restored.Version != seeded.Version || !bytes.Equal(restored.Value, seeded.Value) {
|
||||
t.Fatalf("re-seeded %s = version %d, want the seed back at version %d", WorkflowDefinitionsKind, restored.Version, seeded.Version)
|
||||
}
|
||||
if _, err := workflow.DecodeDefinitionCollection(restored.Value, testSteps(t).Registry()); err != nil {
|
||||
t.Fatalf("the re-seeded workflow definitions do not decode: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,7 @@ type storeReader struct {
|
||||
}
|
||||
|
||||
func (r storeReader) Query(ctx context.Context, kind string, decode func([]byte) error) (int64, bool, error) {
|
||||
resource, err := r.resources.Resource(ctx, kind)
|
||||
resource, err := r.resources.Resource(ctx, storecontract.DefaultOrgID, kind)
|
||||
if errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
seed, ok := r.seeds[kind]
|
||||
if !ok {
|
||||
|
||||
@@ -34,6 +34,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/agentworker"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
|
||||
@@ -267,7 +268,7 @@ func admitThroughStateStore(t *testing.T, steps *workflow.Manager, stepType stri
|
||||
t.Fatalf("build control plane server: %v", err)
|
||||
}
|
||||
|
||||
if resource, resourceErr := resources.Resource(t.Context(), WorkflowDefinitionsKind); resourceErr == nil {
|
||||
if resource, resourceErr := resources.Resource(t.Context(), storecontract.DefaultOrgID, WorkflowDefinitionsKind); resourceErr == nil {
|
||||
before = resource.Version
|
||||
}
|
||||
value, err := json.Marshal(probeCollection(stepType))
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package controlplane
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
||||
)
|
||||
|
||||
const WorkflowEnablementKind = "workflow-enablement"
|
||||
|
||||
func workflowEnablementDefinition() Definition {
|
||||
return Definition{
|
||||
Kind: WorkflowEnablementKind,
|
||||
Title: "Workflow enablement",
|
||||
Document: task.WorkflowEnablement{},
|
||||
ApplyMode: "live",
|
||||
Seed: func(config.Config) any { return task.WorkflowEnablement{Orgs: map[org.OrgID]task.OrgWorkflows{}} },
|
||||
Validate: func(input []byte) error {
|
||||
return validateAs(input, func(enablement task.WorkflowEnablement) error { return enablement.Validate() })
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// WorkflowEnablement returns which workflows each org has disabled.
|
||||
func (c *Client) WorkflowEnablement(ctx context.Context) (task.WorkflowEnablement, error) {
|
||||
response, err := c.rpc.Query(ctx, controlplanerpc.QueryRequest(ctx, WorkflowEnablementKind))
|
||||
if err != nil {
|
||||
return task.WorkflowEnablement{}, controlplanerpc.ClientError(err)
|
||||
}
|
||||
var enablement task.WorkflowEnablement
|
||||
err = json.Unmarshal(response.Resource.ValueJson, &enablement)
|
||||
return enablement, err
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package controlplane
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storepkg"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
// projectionActor is the audit identity every package projection carries: the
|
||||
// write is made by the installed package, never by a request body.
|
||||
const projectionActor = "archie-state-store"
|
||||
|
||||
// projectWriteAttempts bounds one apply or withdrawal: each attempt re-reads
|
||||
// the org's document and re-merges, so a document the operator edited during
|
||||
// the projection is folded in, and only a persistently moving document
|
||||
// refuses the projection.
|
||||
const projectWriteAttempts = 3
|
||||
|
||||
// WorkflowProjector carries an installed package's workflow contributions
|
||||
// into the org's workflow-definitions resource, the same document an operator
|
||||
// edits on the dashboard (docs/prds/store.md, "Packages"). The readers the
|
||||
// daemon holds read that resource per dispatch, so a projected workflow is
|
||||
// usable at the next dispatch and a withdrawn one stops dispatching, without
|
||||
// restarting processes.
|
||||
//
|
||||
// Apply merges: a contributed id that belongs to an operator or to another
|
||||
// package is refused (storepkg.ErrContributionCollision), never silently
|
||||
// replaced.
|
||||
type WorkflowProjector struct {
|
||||
store ResourceStore
|
||||
ledger storepkg.ProjectionLedger
|
||||
steps workflow.StepRegistry
|
||||
}
|
||||
|
||||
var _ storepkg.FamilyProjector = (*WorkflowProjector)(nil)
|
||||
|
||||
// NewWorkflowPackageProjector builds the projector for storepkg.FamilyWorkflows
|
||||
// on the workflow step vocabulary the composition root registered: the
|
||||
// vocabulary the projected definitions are compiled and validated against,
|
||||
// the same one the control plane validates dashboard edits with.
|
||||
func NewWorkflowPackageProjector(resources ResourceStore, ledger storepkg.ProjectionLedger, manager *workflow.Manager) (*WorkflowProjector, error) {
|
||||
steps, err := stepRegistry(manager)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resources == nil || ledger == nil {
|
||||
return nil, errors.New("control plane: workflow projection needs a resource store and a contributions ledger")
|
||||
}
|
||||
return &WorkflowProjector{store: resources, ledger: ledger, steps: steps}, nil
|
||||
}
|
||||
|
||||
func (p *WorkflowProjector) Apply(ctx context.Context, orgID, name, digest string, contents map[string][]byte) error {
|
||||
entries := make([]workflow.WorkflowDefinitionEntry, 0, len(contents))
|
||||
recorded := make([]storepkg.ProjectionEntry, 0, len(contents))
|
||||
for contentName, content := range contents {
|
||||
id, err := workflow.DefinitionID(string(content))
|
||||
if err != nil {
|
||||
return fmt.Errorf("contributed workflow %q: %w", contentName, err)
|
||||
}
|
||||
entries = append(entries, workflow.WorkflowDefinitionEntry{ID: id, YAML: string(content)})
|
||||
recorded = append(recorded, storepkg.ProjectionEntry{Family: storepkg.FamilyWorkflows, EntryID: id})
|
||||
}
|
||||
// One apply, one request: a retried PutResource reuses the same request ID
|
||||
// and answers once, while a later install of the same package writes a
|
||||
// revision of its own.
|
||||
source := "package:" + name + "@" + digest
|
||||
if err := p.write(ctx, orgID, source, "package-project:"+digest, func(collection workflow.WorkflowDefinitionCollection) (workflow.WorkflowDefinitionCollection, error) {
|
||||
return mergeContribution(collection, entries, name)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.ledger.Record(ctx, orgID, name, recorded); err != nil {
|
||||
return fmt.Errorf("record contributions of %q: %w", name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *WorkflowProjector) Withdraw(ctx context.Context, orgID, name, digest string) error {
|
||||
entries, err := p.ledger.Entries(ctx, orgID, name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("entries of package %q: %w", name, err)
|
||||
}
|
||||
withdrawn := make(map[string]struct{}, len(entries))
|
||||
for _, entry := range entries {
|
||||
if entry.Family == storepkg.FamilyWorkflows {
|
||||
withdrawn[entry.EntryID] = struct{}{}
|
||||
}
|
||||
}
|
||||
if len(withdrawn) == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := p.write(ctx, orgID, "package-withdraw:"+name+"@"+digest, "package-withdraw:"+digest,
|
||||
func(collection workflow.WorkflowDefinitionCollection) (workflow.WorkflowDefinitionCollection, error) {
|
||||
merged := make([]workflow.WorkflowDefinitionEntry, 0, len(collection.Definitions))
|
||||
for _, item := range collection.Definitions {
|
||||
if _, gone := withdrawn[item.ID]; gone {
|
||||
continue
|
||||
}
|
||||
merged = append(merged, item)
|
||||
}
|
||||
return workflow.WorkflowDefinitionCollection{Definitions: merged}, nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.ledger.Forget(ctx, orgID, name, storepkg.FamilyWorkflows)
|
||||
}
|
||||
|
||||
// write merges an org's stored workflow-definitions document and puts it
|
||||
// back, bounded by projectWriteAttempts: each attempt re-reads and re-merges,
|
||||
// so a document the operator edited during the projection is folded in, and
|
||||
// the write carries the ledger's replay identity of one episode.
|
||||
func (p *WorkflowProjector) write(ctx context.Context, orgID, source, requestPrefix string, merge func(workflow.WorkflowDefinitionCollection) (workflow.WorkflowDefinitionCollection, error)) error {
|
||||
requestID := requestPrefix + ":" + strconv.FormatInt(time.Now().UTC().UnixNano(), 36)
|
||||
for attempt := 0; ; attempt++ {
|
||||
collection, version := p.collection(ctx, orgID)
|
||||
merged, err := merge(collection)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value, err := encodeWorkflowDefinitions(merged, p.steps)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := p.store.PutResource(ctx, storecontract.ResourceWrite{
|
||||
OrgID: orgID, Kind: WorkflowDefinitionsKind, Value: value, ExpectedVersion: version,
|
||||
Actor: projectionActor, Source: source, RequestID: requestID,
|
||||
}); errors.Is(err, storecontract.ErrResourceVersionConflict) && attempt < projectWriteAttempts-1 {
|
||||
continue
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// collection reads an org's workflow-definitions document. An org that never
|
||||
// received one starts from the shipped definitions, the state a first write
|
||||
// seeds, so projection leaves the org with one answer either way.
|
||||
func (p *WorkflowProjector) collection(ctx context.Context, orgID string) (workflow.WorkflowDefinitionCollection, int64) {
|
||||
resource, err := p.store.Resource(ctx, orgID, WorkflowDefinitionsKind)
|
||||
if errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
return workflow.ShippedDefinitions(), 0
|
||||
}
|
||||
if err != nil {
|
||||
return workflow.WorkflowDefinitionCollection{}, 0
|
||||
}
|
||||
collection, err := workflow.DecodeDefinitionCollection(resource.Value, p.steps)
|
||||
if err != nil {
|
||||
return workflow.WorkflowDefinitionCollection{}, 0
|
||||
}
|
||||
return collection, resource.Version
|
||||
}
|
||||
|
||||
// mergeContribution merges a package's contributed entries into an org's
|
||||
// collection. An operator's entry with the same workflow id is a refusal, not
|
||||
// a silent replacement; the package's own entries reach here only after its
|
||||
// ledger rows were cleared, so colliding is always foreign work.
|
||||
func mergeContribution(base workflow.WorkflowDefinitionCollection, contributed []workflow.WorkflowDefinitionEntry, name string) (workflow.WorkflowDefinitionCollection, error) {
|
||||
replacing := make(map[string]struct{}, len(contributed))
|
||||
for _, entry := range contributed {
|
||||
replacing[entry.ID] = struct{}{}
|
||||
}
|
||||
merged := make([]workflow.WorkflowDefinitionEntry, 0, len(base.Definitions)+len(contributed))
|
||||
for _, entry := range base.Definitions {
|
||||
if _, incoming := replacing[entry.ID]; incoming {
|
||||
return workflow.WorkflowDefinitionCollection{}, fmt.Errorf("package %q: %w: workflow %q", name, storepkg.ErrContributionCollision, entry.ID)
|
||||
}
|
||||
merged = append(merged, entry)
|
||||
}
|
||||
merged = append(merged, contributed...)
|
||||
return workflow.WorkflowDefinitionCollection{Definitions: merged}, nil
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package controlplane
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storepkg"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
const testDigest = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
|
||||
// testPackageProjector builds the workflow package projector against a real
|
||||
// migrated database and the production step vocabulary. The projector's
|
||||
// ledger rows describe installed packages, so a fixture installs one.
|
||||
func testPackageProjector(ctx context.Context, t *testing.T, orgID, pkgName, digest string) (*WorkflowProjector, ResourceStore, storepkg.ProjectionLedger) {
|
||||
t.Helper()
|
||||
db := pgstore.Open(t)
|
||||
installed := storepkg.Installed{
|
||||
OrgID: orgID, Name: pkgName, Reference: "localhost:5000/" + pkgName,
|
||||
Digest: digest, Descriptor: testPackageDescriptor(), Layer: []byte("layer"), UpdatePolicy: "manual",
|
||||
}
|
||||
if err := postgres.NewInstalledPackages(db.Pool).Install(ctx, installed); err != nil {
|
||||
t.Fatalf("install package record: %v", err)
|
||||
}
|
||||
resources := postgres.NewResources(db.Pool)
|
||||
ledger := postgres.NewPackageContributions(db.Pool)
|
||||
projector, err := NewWorkflowPackageProjector(resources, ledger, testSteps(t))
|
||||
if err != nil {
|
||||
t.Fatalf("build workflow projector: %v", err)
|
||||
}
|
||||
return projector, resources, ledger
|
||||
}
|
||||
|
||||
// testPackageDescriptor is the valid descriptor backing the ledger fixture.
|
||||
func testPackageDescriptor() storepkg.Descriptor {
|
||||
return storepkg.Descriptor{
|
||||
APIVersion: storepkg.APIVersion, DisplayName: "Review pack", Version: "1",
|
||||
Contributes: storepkg.Contributions{Workflows: []string{"workflows/review.yaml"}},
|
||||
}
|
||||
}
|
||||
|
||||
// contributedWorkflow builds a contributed workflow the shipped vocabulary
|
||||
// compiles, with a fresh id no shipped or operator workflow claims.
|
||||
func contributedWorkflow(name string) workflow.WorkflowDefinitionEntry {
|
||||
return workflow.WorkflowDefinitionEntry{ID: name, YAML: "id: " + name + "\nsteps:\n - type: bootstrap.apply\n"}
|
||||
}
|
||||
|
||||
// storedCollection returns an org's workflow-definitions document the way its
|
||||
// readers see it: shipped definitions stand in for an absent row.
|
||||
func storedCollection(ctx context.Context, t *testing.T, resources ResourceStore, orgID string) (workflow.WorkflowDefinitionCollection, int64) {
|
||||
t.Helper()
|
||||
resource, err := resources.Resource(ctx, orgID, WorkflowDefinitionsKind)
|
||||
if errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
return workflow.ShippedDefinitions(), 0
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
collection, err := workflow.DecodeDefinitionCollection(resource.Value, workflow.BuiltinStepRegistry())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return collection, resource.Version
|
||||
}
|
||||
|
||||
// operatorEdit installs a workflow the operator owns, exactly a dashboard
|
||||
// replacement does.
|
||||
func operatorEdit(ctx context.Context, t *testing.T, resources ResourceStore, orgID string, entry workflow.WorkflowDefinitionEntry) {
|
||||
t.Helper()
|
||||
collection, version := storedCollection(ctx, t, resources, orgID)
|
||||
collection.Definitions = append(collection.Definitions, entry)
|
||||
value, err := encodeWorkflowDefinitions(collection, testSteps(t).Registry())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := resources.PutResource(ctx, storecontract.ResourceWrite{
|
||||
OrgID: orgID, Kind: WorkflowDefinitionsKind, Value: value, ExpectedVersion: version,
|
||||
Actor: "operator", Source: "dashboard", RequestID: "operator-edit",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func resourceVersionOf(ctx context.Context, t *testing.T, resources ResourceStore, orgID string) int64 {
|
||||
t.Helper()
|
||||
_, version := storedCollection(ctx, t, resources, orgID)
|
||||
return version
|
||||
}
|
||||
|
||||
func TestWorkflowProjectorApplyAndWithdraw(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
const pkgName = "review"
|
||||
const contributedID = "review"
|
||||
contributedYAML := contributedWorkflow(contributedID).YAML
|
||||
|
||||
// applied builds a projector that has projected one contributed workflow.
|
||||
applied := func(t *testing.T) (*WorkflowProjector, ResourceStore, storepkg.ProjectionLedger) {
|
||||
t.Helper()
|
||||
projector, resources, ledger := testPackageProjector(ctx, t, "org-a", pkgName, testDigest)
|
||||
if err := projector.Apply(ctx, "org-a", pkgName, testDigest, map[string][]byte{
|
||||
"workflows/review.yaml": []byte(contributedYAML),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return projector, resources, ledger
|
||||
}
|
||||
|
||||
t.Run("apply makes the contributed workflow an org workflow without a restart", func(t *testing.T) {
|
||||
_, resources, ledger := applied(t)
|
||||
collection, _ := storedCollection(ctx, t, resources, "org-a")
|
||||
if _, ok := collection.DefinitionByID(contributedID); !ok {
|
||||
t.Fatal("org workflow-definitions does not carry the contributed workflow")
|
||||
}
|
||||
entries, err := ledger.Entries(ctx, "org-a", pkgName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 1 || entries[0] != (storepkg.ProjectionEntry{Family: storepkg.FamilyWorkflows, EntryID: contributedID}) {
|
||||
t.Fatalf("ledger = %#v", entries)
|
||||
}
|
||||
})
|
||||
t.Run("withdraw takes exactly the package's entries back out", func(t *testing.T) {
|
||||
projector, resources, _ := testPackageProjector(ctx, t, "org-a", pkgName, testDigest)
|
||||
other := contributedWorkflow("review-operator")
|
||||
if err := projector.Apply(ctx, "org-a", pkgName, testDigest, map[string][]byte{
|
||||
"workflows/review.yaml": []byte(contributedYAML),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
operatorEdit(ctx, t, resources, "org-a", other)
|
||||
if err := projector.Withdraw(ctx, "org-a", pkgName, testDigest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
collection, _ := storedCollection(ctx, t, resources, "org-a")
|
||||
if _, ok := collection.DefinitionByID(contributedID); ok {
|
||||
t.Fatal("the package's contributed workflow survives withdrawal")
|
||||
}
|
||||
if _, ok := collection.DefinitionByID(other.ID); !ok {
|
||||
t.Fatal("operator workflow was withdrawn by a package remove")
|
||||
}
|
||||
})
|
||||
t.Run("a contributed id colliding with an operator workflow is refused", func(t *testing.T) {
|
||||
projector, resources, _ := testPackageProjector(ctx, t, "org-a", pkgName, testDigest)
|
||||
operatorEdit(ctx, t, resources, "org-a", contributedWorkflow(contributedID))
|
||||
before := resourceVersionOf(ctx, t, resources, "org-a")
|
||||
if err := projector.Apply(ctx, "org-a", pkgName, testDigest, map[string][]byte{
|
||||
"workflows/review.yaml": []byte(contributedYAML),
|
||||
}); !errors.Is(err, storepkg.ErrContributionCollision) {
|
||||
t.Fatalf("colliding contribution error = %v", err)
|
||||
}
|
||||
if after := resourceVersionOf(ctx, t, resources, "org-a"); after != before {
|
||||
t.Fatal("refused contribution wrote the resource anyway")
|
||||
}
|
||||
})
|
||||
t.Run("an invalid contributed workflow is refused without a write", func(t *testing.T) {
|
||||
projector, resources, _ := testPackageProjector(ctx, t, "org-a", pkgName, testDigest)
|
||||
before := resourceVersionOf(ctx, t, resources, "org-a")
|
||||
if err := projector.Apply(ctx, "org-a", pkgName, testDigest, map[string][]byte{
|
||||
"workflows/broken.yaml": []byte("id: broken\nsteps:\n - type: not-a-step\n"),
|
||||
}); err == nil {
|
||||
t.Fatal("invalid workflow definition projected")
|
||||
}
|
||||
if after := resourceVersionOf(ctx, t, resources, "org-a"); after != before {
|
||||
t.Fatal("refused projection wrote the resource anyway")
|
||||
}
|
||||
})
|
||||
t.Run("withdraw of a package that never applied is a no-op", func(t *testing.T) {
|
||||
projector, _, _ := testPackageProjector(ctx, t, "org-x", pkgName, testDigest)
|
||||
if err := projector.Withdraw(ctx, "org-x", pkgName, testDigest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -28,9 +28,12 @@ type executionSettingsDocument struct {
|
||||
}
|
||||
|
||||
// ImportWorkflowExecutionSettings preserves the focused bootstrap API for callers
|
||||
// that do not own the complete legacy configuration document.
|
||||
// that do not own the complete legacy configuration document. It is the same
|
||||
// producer rule as ImportConfig, at this narrower entry point: a kind the store
|
||||
// holds is left alone, and a kind it does not hold is seeded under the one seed
|
||||
// identity (see seedActor and seedRequestID).
|
||||
func (s *Server) ImportWorkflowExecutionSettings(ctx context.Context, settings workflow.ExecutionSettings) (int64, error) {
|
||||
resource, err := s.store.Resource(ctx, WorkflowExecutionSettingsKind)
|
||||
resource, err := s.store.Resource(ctx, storecontract.DefaultOrgID, WorkflowExecutionSettingsKind)
|
||||
if err == nil {
|
||||
return resource.Version, nil
|
||||
}
|
||||
@@ -45,7 +48,7 @@ func (s *Server) ImportWorkflowExecutionSettings(ctx context.Context, settings w
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
resource, err = s.store.PutResource(ctx, storecontract.ResourceWrite{Kind: WorkflowExecutionSettingsKind, Value: value, Actor: "system:migration", Source: "legacy-config", RequestID: "import:" + WorkflowExecutionSettingsKind, ExpectedVersion: 0, At: time.Now().UTC()})
|
||||
resource, err = s.store.PutResource(ctx, storecontract.ResourceWrite{OrgID: storecontract.DefaultOrgID, Kind: WorkflowExecutionSettingsKind, Value: value, Actor: seedActor, Source: seedSource, RequestID: seedRequestID(WorkflowExecutionSettingsKind, value), ExpectedVersion: 0, At: time.Now().UTC()})
|
||||
return resource.Version, err
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package prbench
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/prreview"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/prreview/bench"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/prsource"
|
||||
)
|
||||
|
||||
func newBenchmarkReviewer(opts Options, cfg config.Config, rt *runtime.Runtime) (bench.Reviewer, error) {
|
||||
if opts.Fixtures != "" {
|
||||
return fixtureReviewer{dir: opts.Fixtures}, nil
|
||||
}
|
||||
if opts.ReviewModel == "" || opts.ClassifyModel == "" {
|
||||
return nil, fmt.Errorf("live review requires both -review-model and -classification-model")
|
||||
}
|
||||
client, err := forge.NewGitHub(opts.GitHubToken, "https://github.com", slog.Default())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
prReader, prOK := client.(forge.PullRequestReader)
|
||||
diffReader, diffOK := client.(forge.PullRequestDiffReader)
|
||||
archiveReader, archiveOK := client.(forge.RepoArchiveReader)
|
||||
if !prOK || !diffOK || !archiveOK {
|
||||
return nil, fmt.Errorf("GitHub client cannot read pull request snapshots")
|
||||
}
|
||||
cfg.Models = map[string]string{"review": opts.ReviewModel, "classification": opts.ClassifyModel}
|
||||
cfg.Review.ApproveBeforePost = false
|
||||
cfg.Review.PrecisionGate = false
|
||||
return &liveReviewer{
|
||||
cfg: cfg, agent: agentexec.NewLoopRunner(rt, slog.Default()),
|
||||
source: prsource.New(forgeSource{PullRequestReader: prReader, PullRequestDiffReader: diffReader, RepoArchiveReader: archiveReader}),
|
||||
}, nil
|
||||
}
|
||||
|
||||
type liveReviewer struct {
|
||||
cfg config.Config
|
||||
agent agentexec.Runner
|
||||
source workflow.PRSource
|
||||
nextID atomic.Int64
|
||||
}
|
||||
|
||||
func (r *liveReviewer) Review(ctx context.Context, p bench.Problem) (bench.Review, error) {
|
||||
owner, repo, number, err := parsePRURL(p.PRURL)
|
||||
if err != nil {
|
||||
return bench.Review{}, err
|
||||
}
|
||||
slog.Info("benchmark review started", "problem", p.ID)
|
||||
tc := &workflow.TaskContext{
|
||||
Task: &workflow.Task{ID: r.nextID.Add(1), Attempt: 1, Owner: owner, Repo: repo, PRNumber: number, Workflow: "pr-review", Inputs: map[string]any{"depth": "deep"}},
|
||||
Cfg: r.cfg, Agent: r.agent, PRSource: r.source, Log: slog.Default(),
|
||||
}
|
||||
decision, err := workflow.ReviewPullRequest(ctx, tc)
|
||||
if err != nil {
|
||||
return bench.Review{}, err
|
||||
}
|
||||
// Non-nil empty comments means a completed pipeline found nothing.
|
||||
if decision.Comments == nil {
|
||||
decision.Comments = []prreview.ScoredFinding{}
|
||||
}
|
||||
slog.Info("benchmark review completed", "problem", p.ID, "comments", len(decision.Comments), "skipped_phases", decision.SkippedPhases)
|
||||
return bench.Review{Comments: decision.Comments, SkippedPhases: decision.SkippedPhases}, nil
|
||||
}
|
||||
|
||||
func parsePRURL(raw string) (string, string, int, error) {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return "", "", 0, fmt.Errorf("invalid pull request URL: %w", err)
|
||||
}
|
||||
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
|
||||
if u.Scheme != "https" || u.Host != "github.com" || len(parts) != 4 || parts[2] != "pull" || u.RawQuery != "" || u.Fragment != "" || u.User != nil {
|
||||
return "", "", 0, fmt.Errorf("benchmark requires a GitHub pull request URL")
|
||||
}
|
||||
n, err := strconv.Atoi(parts[3])
|
||||
if err != nil || n <= 0 || parts[0] == "" || parts[1] == "" {
|
||||
return "", "", 0, fmt.Errorf("invalid pull request URL")
|
||||
}
|
||||
return parts[0], parts[1], n, nil
|
||||
}
|
||||
|
||||
type forgeSource struct {
|
||||
forge.PullRequestReader
|
||||
forge.PullRequestDiffReader
|
||||
forge.RepoArchiveReader
|
||||
}
|
||||
|
||||
func (s forgeSource) GetPullRequest(ctx context.Context, owner, repo string, number int) (prsource.PullRequest, error) {
|
||||
p, err := s.PullRequestReader.GetPullRequest(ctx, owner, repo, number)
|
||||
if err != nil {
|
||||
return prsource.PullRequest{}, err
|
||||
}
|
||||
return prsource.PullRequest{Title: p.Title, Body: p.Body, HeadSHA: p.HeadSHA}, nil
|
||||
}
|
||||
+136
-15
@@ -6,13 +6,14 @@ import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"slices"
|
||||
"sync"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/app/archied"
|
||||
@@ -48,20 +49,21 @@ func Problems(ids []string) ([]bench.Problem, error) {
|
||||
|
||||
// Options configures one benchmark run.
|
||||
type Options struct {
|
||||
Config string
|
||||
Fixtures string
|
||||
JudgeModel string
|
||||
Out string
|
||||
Problems []string
|
||||
Concurrency int
|
||||
Config string
|
||||
Fixtures string
|
||||
JudgeModel string
|
||||
ReviewModel string
|
||||
ClassifyModel string
|
||||
GitHubToken string
|
||||
Resume string
|
||||
Out string
|
||||
Problems []string
|
||||
Concurrency int
|
||||
}
|
||||
|
||||
// Run reviews and judges the selected problems, writes one result file per
|
||||
// problem and a summary to Options.Out, and prints the summary to w.
|
||||
func Run(ctx context.Context, opts Options, w io.Writer) (bench.Summary, error) {
|
||||
if opts.Fixtures == "" {
|
||||
return bench.Summary{}, errors.New("no reviewer: pass a findings fixture directory")
|
||||
}
|
||||
problems, err := Problems(opts.Problems)
|
||||
if err != nil {
|
||||
return bench.Summary{}, err
|
||||
@@ -78,10 +80,17 @@ func Run(ctx context.Context, opts Options, w io.Writer) (bench.Summary, error)
|
||||
return bench.Summary{}, fmt.Errorf("%s configures no providers for the judge", opts.Config)
|
||||
}
|
||||
judge := &modelJudge{runtime: rt, modelRef: opts.JudgeModel}
|
||||
reviewer, err := newBenchmarkReviewer(opts, doc.Config, rt)
|
||||
if err != nil {
|
||||
return bench.Summary{}, err
|
||||
}
|
||||
|
||||
results := bench.Run(ctx, problems, fixtureReviewer{dir: opts.Fixtures}, judge, opts.Concurrency)
|
||||
results, err := runReviews(ctx, problems, reviewer, judge, opts)
|
||||
if err != nil {
|
||||
return bench.Summary{}, err
|
||||
}
|
||||
summary := bench.Summarize(results)
|
||||
if err := writeResults(opts.Out, results, summary); err != nil {
|
||||
if err := writeResults(opts.Out, results, summary, opts); err != nil {
|
||||
return summary, err
|
||||
}
|
||||
for _, r := range results {
|
||||
@@ -92,10 +101,51 @@ func Run(ctx context.Context, opts Options, w io.Writer) (bench.Summary, error)
|
||||
fmt.Fprintf(w, "problems %d (failed %d) recall %.3f (%d/%d) golden-only precision %.3f (%d/%d)\n",
|
||||
summary.Problems, summary.Failed, summary.Recall, summary.Hits, summary.Goldens,
|
||||
summary.Precision, summary.Matched, summary.Comments)
|
||||
if summary.Failed != 0 {
|
||||
return summary, fmt.Errorf("%d benchmark problem(s) failed; results are incomplete", summary.Failed)
|
||||
}
|
||||
if opts.Fixtures == "" && len(opts.Problems) == 0 && summary.Recall < 0.70 {
|
||||
return summary, fmt.Errorf("golden micro-recall %.3f is below 0.70", summary.Recall)
|
||||
}
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
func writeResults(dir string, results []bench.Result, summary bench.Summary) error {
|
||||
func runReviews(ctx context.Context, problems []bench.Problem, reviewer bench.Reviewer, judge bench.Judge, opts Options) ([]bench.Result, error) {
|
||||
results, pending, err := resumeResults(problems, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(opts.Out, "results"), 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := writeJSON(filepath.Join(opts.Out, "run.json"), metadata(opts)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var saveMu sync.Mutex
|
||||
var saveErr error
|
||||
newResults := bench.Run(ctx, pending, reviewer, judge, opts.Concurrency, func(r bench.Result) {
|
||||
if err := writeJSON(filepath.Join(opts.Out, "results", r.Problem.ID+".json"), r); err != nil {
|
||||
saveMu.Lock()
|
||||
saveErr = err
|
||||
saveMu.Unlock()
|
||||
}
|
||||
})
|
||||
if saveErr != nil {
|
||||
return nil, fmt.Errorf("save benchmark result: %w", saveErr)
|
||||
}
|
||||
byID := make(map[string]bench.Result, len(newResults))
|
||||
for _, r := range newResults {
|
||||
byID[r.Problem.ID] = r
|
||||
}
|
||||
for i, r := range results {
|
||||
if r.Problem.ID == "" {
|
||||
results[i] = byID[problems[i].ID]
|
||||
}
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func writeResults(dir string, results []bench.Result, summary bench.Summary, opts Options) error {
|
||||
if err := os.MkdirAll(filepath.Join(dir, "results"), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -104,7 +154,66 @@ func writeResults(dir string, results []bench.Result, summary bench.Summary) err
|
||||
return err
|
||||
}
|
||||
}
|
||||
return writeJSON(filepath.Join(dir, "summary.json"), summary)
|
||||
if err := writeJSON(filepath.Join(dir, "summary.json"), summary); err != nil {
|
||||
return err
|
||||
}
|
||||
return writeJSON(filepath.Join(dir, "run.json"), metadata(opts))
|
||||
}
|
||||
|
||||
type runMetadata struct {
|
||||
ReviewModel string `json:"review_model"`
|
||||
ClassificationModel string `json:"classification_model"`
|
||||
JudgeModel string `json:"judge_model"`
|
||||
Live bool `json:"live"`
|
||||
}
|
||||
|
||||
func metadata(opts Options) runMetadata {
|
||||
return runMetadata{opts.ReviewModel, opts.ClassifyModel, opts.JudgeModel, opts.Fixtures == ""}
|
||||
}
|
||||
|
||||
func resumeResults(problems []bench.Problem, opts Options) ([]bench.Result, []bench.Problem, error) {
|
||||
results := make([]bench.Result, len(problems))
|
||||
if opts.Resume == "" {
|
||||
return results, problems, nil
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(opts.Resume, "run.json"))
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("read benchmark resume metadata: %w", err)
|
||||
}
|
||||
var previous runMetadata
|
||||
if err := json.Unmarshal(data, &previous); err != nil {
|
||||
return nil, nil, fmt.Errorf("decode benchmark resume metadata: %w", err)
|
||||
}
|
||||
if previous != metadata(opts) {
|
||||
return nil, nil, fmt.Errorf("benchmark resume models or mode differ from this run")
|
||||
}
|
||||
var pending []bench.Problem
|
||||
for i, p := range problems {
|
||||
data, err := os.ReadFile(filepath.Join(opts.Resume, "results", p.ID+".json"))
|
||||
if os.IsNotExist(err) {
|
||||
pending = append(pending, p)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("read benchmark result %s: %w", p.ID, err)
|
||||
}
|
||||
var r bench.Result
|
||||
if err := json.Unmarshal(data, &r); err != nil {
|
||||
return nil, nil, fmt.Errorf("decode benchmark result %s: %w", p.ID, err)
|
||||
}
|
||||
if !reflect.DeepEqual(r.Problem, p) {
|
||||
return nil, nil, fmt.Errorf("benchmark result %s belongs to a different problem", p.ID)
|
||||
}
|
||||
if r.Err != "" {
|
||||
pending = append(pending, p)
|
||||
continue
|
||||
}
|
||||
if len(r.Verdicts) != len(p.Goldens) {
|
||||
return nil, nil, fmt.Errorf("benchmark result %s is incomplete or belongs to a different problem", p.ID)
|
||||
}
|
||||
results[i] = r
|
||||
}
|
||||
return results, pending, nil
|
||||
}
|
||||
|
||||
func writeJSON(path string, v any) error {
|
||||
@@ -112,5 +221,17 @@ func writeJSON(path string, v any) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, append(data, '\n'), 0o644)
|
||||
f, err := os.CreateTemp(filepath.Dir(path), ".prbench-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(f.Name())
|
||||
if _, err := f.Write(append(data, '\n')); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(f.Name(), path)
|
||||
}
|
||||
@@ -63,3 +63,21 @@ func TestFixtureReviewer(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumeResultsOnlyReusesCompleteMatchingRun(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
opts := Options{ReviewModel: "openai/review", ClassifyModel: "openai/classify", JudgeModel: "openai/judge", Resume: dir}
|
||||
p := bench.Problem{ID: "first", PRURL: "https://github.com/acme/repo/pull/1", Goldens: []bench.Golden{{Comment: "defect"}}}
|
||||
other := bench.Problem{ID: "second", PRURL: "https://github.com/acme/repo/pull/2", Goldens: []bench.Golden{{Comment: "other"}}}
|
||||
if err := writeResults(dir, []bench.Result{{Problem: p, Verdicts: []bench.Verdict{{Golden: 0, Comment: bench.NoComment}}}}, bench.Summary{}, opts); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
results, pending, err := resumeResults([]bench.Problem{p, other}, opts)
|
||||
if err != nil || len(pending) != 1 || pending[0].ID != other.ID || results[0].Problem.ID != p.ID {
|
||||
t.Fatalf("results = %+v, pending = %+v, err = %v", results, pending, err)
|
||||
}
|
||||
opts.JudgeModel = "openai/different"
|
||||
if _, _, err := resumeResults([]bench.Problem{p}, opts); err == nil {
|
||||
t.Fatal("mixed model results were accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// inboundMedia pairs an inbound attachment with the textual note the
|
||||
// transcript stores in its place: stored history is text-only, so the
|
||||
// note is what later turns read once the attachment's bytes are gone.
|
||||
type inboundMedia struct {
|
||||
attachment messaging.MediaAttachment
|
||||
// note is a bracketed, self-describing placeholder such as "[photo]"
|
||||
// or "[document: report.pdf]".
|
||||
note string
|
||||
}
|
||||
|
||||
// extractInboundMedia maps a Telegram message onto the attachment it
|
||||
// carries. A Telegram message carries at most one file (a photo is the
|
||||
// set of its resolutions and collapses into one image), so the boolean is
|
||||
// false exactly for messages with nothing to download.
|
||||
func extractInboundMedia(msg *models.Message) (inboundMedia, bool) {
|
||||
switch {
|
||||
case len(msg.Photo) > 0:
|
||||
att := messaging.MediaAttachment{Type: "image", MIMEType: "image/jpeg"}
|
||||
for _, size := range msg.Photo {
|
||||
if largestPhoto(size, att) {
|
||||
att.FileID = size.FileID
|
||||
att.Width, att.Height = &size.Width, &size.Height
|
||||
if size.FileSize != 0 {
|
||||
att.FileSize = new(int64(size.FileSize))
|
||||
}
|
||||
}
|
||||
}
|
||||
return inboundMedia{att, "[photo]"}, true
|
||||
|
||||
case msg.Document != nil:
|
||||
return inboundMedia{messaging.MediaAttachment{
|
||||
Type: "document",
|
||||
FileID: msg.Document.FileID,
|
||||
MIMEType: msg.Document.MimeType,
|
||||
FileName: msg.Document.FileName,
|
||||
FileSize: nilIfZero(msg.Document.FileSize),
|
||||
}, documentNote(msg.Document.FileName)}, true
|
||||
|
||||
case msg.Video != nil:
|
||||
return inboundMedia{videoAttachment(msg.Video.FileID, msg.Video.MimeType, nilIfZero(msg.Video.FileSize), &msg.Video.Width, &msg.Video.Height, &msg.Video.Duration), "[video]"}, true
|
||||
|
||||
case msg.VideoNote != nil:
|
||||
size := int64(msg.VideoNote.FileSize)
|
||||
return inboundMedia{videoAttachment(msg.VideoNote.FileID, "video/mp4", nilIfZero(size), nil, nil, &msg.VideoNote.Duration), "[video message]"}, true
|
||||
|
||||
case msg.Audio != nil:
|
||||
return inboundMedia{messaging.MediaAttachment{
|
||||
Type: "audio",
|
||||
FileID: msg.Audio.FileID,
|
||||
MIMEType: msg.Audio.MimeType,
|
||||
FileName: msg.Audio.FileName,
|
||||
FileSize: nilIfZero(msg.Audio.FileSize),
|
||||
Duration: &msg.Audio.Duration,
|
||||
}, "[audio]"}, true
|
||||
|
||||
case msg.Voice != nil:
|
||||
return inboundMedia{messaging.MediaAttachment{
|
||||
Type: "audio",
|
||||
FileID: msg.Voice.FileID,
|
||||
MIMEType: msg.Voice.MimeType,
|
||||
FileSize: nilIfZero(msg.Voice.FileSize),
|
||||
Duration: &msg.Voice.Duration,
|
||||
}, "[voice message]"}, true
|
||||
}
|
||||
return inboundMedia{}, false
|
||||
}
|
||||
|
||||
// largestPhoto reports whether candidate is larger than the best size
|
||||
// recorded so far in att's width/height pair.
|
||||
func largestPhoto(candidate models.PhotoSize, att messaging.MediaAttachment) bool {
|
||||
if att.Width == nil {
|
||||
return true
|
||||
}
|
||||
candidateArea, bestArea := candidate.Width*candidate.Height, *att.Width**att.Height
|
||||
return candidateArea > bestArea
|
||||
}
|
||||
|
||||
func videoAttachment(fileID, mimeType string, fileSize *int64, width, height, duration *int) messaging.MediaAttachment {
|
||||
return messaging.MediaAttachment{
|
||||
Type: "video", FileID: fileID, MIMEType: mimeType,
|
||||
FileSize: fileSize, Width: width, Height: height, Duration: duration,
|
||||
}
|
||||
}
|
||||
|
||||
func documentNote(name string) string {
|
||||
if name == "" {
|
||||
return "[document]"
|
||||
}
|
||||
return fmt.Sprintf("[document: %s]", name)
|
||||
}
|
||||
|
||||
func nilIfZero(v int64) *int64 {
|
||||
if v == 0 {
|
||||
return nil
|
||||
}
|
||||
return &v
|
||||
}
|
||||
|
||||
// maxInboundDownloadBytes is the Bot API download ceiling: bots cannot
|
||||
// fetch files larger than 20 MB through getFile, so a larger attachment
|
||||
// must be refused with a clear notice rather than met with a Bot API 400
|
||||
// nobody reads.
|
||||
var maxInboundDownloadBytes int64 = 20 * 1024 * 1024
|
||||
|
||||
var errInboundMediaTooLarge = errors.New("file exceeds the bot download limit")
|
||||
|
||||
// downloadMedia turns a Telegram file id into the file's bytes: getFile
|
||||
// resolves the transfer path, then the file is fetched from the Bot API
|
||||
// server. Called on the turn lane, which is already running the rest of
|
||||
// the download-and-chat work for this message.
|
||||
func (g *Gateway) downloadMedia(ctx context.Context, b *bot.Bot, att messaging.MediaAttachment) ([]byte, error) {
|
||||
if att.FileID == "" {
|
||||
return nil, fmt.Errorf("media attachment carries no file id")
|
||||
}
|
||||
if att.FileSize != nil && *att.FileSize > maxInboundDownloadBytes {
|
||||
return nil, fmt.Errorf("%w: %d bytes", errInboundMediaTooLarge, *att.FileSize)
|
||||
}
|
||||
file, err := b.GetFile(ctx, &bot.GetFileParams{FileID: att.FileID})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve telegram file: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, b.FileDownloadLink(file), nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("download telegram file: %w", err)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("download telegram file: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("download telegram file: status %d", resp.StatusCode)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, maxInboundDownloadBytes+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("download telegram file: %w", err)
|
||||
}
|
||||
if int64(len(data)) > maxInboundDownloadBytes {
|
||||
return nil, errInboundMediaTooLarge
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// turnMessageText renders the text an inbound message's turn is built
|
||||
// from: plain text as received, or the attachment note plus caption when
|
||||
// the message carries a file. The note is what later turns read from
|
||||
// history, so a captioned photo whose caption alone would read as the
|
||||
// whole message ("what is this?") still names its attachment.
|
||||
func turnMessageText(msg *models.Message, media inboundMedia, hasMedia bool) string {
|
||||
if !hasMedia {
|
||||
return msg.Text
|
||||
}
|
||||
if msg.Caption == "" {
|
||||
return media.note
|
||||
}
|
||||
return media.note + "\n" + msg.Caption
|
||||
}
|
||||
|
||||
// unsupportedMediaNotice returns the refusal for content kinds Archie
|
||||
// cannot read, and "" for update content that is not a message to answer
|
||||
// at all -- a group member change or pin must stay silent, while a
|
||||
// sticker the sender meant Archie to react to must not disappear into the
|
||||
// void.
|
||||
func unsupportedMediaNotice(msg *models.Message) string {
|
||||
switch {
|
||||
case msg.Sticker != nil:
|
||||
return "I can't read stickers — send the image or file directly and I'll take a look."
|
||||
case msg.Location != nil:
|
||||
return "I can't use locations yet."
|
||||
case msg.Contact != nil:
|
||||
return "I can't use contact cards yet."
|
||||
case msg.Poll != nil:
|
||||
return "I can't use polls yet."
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// mediaReplyLabel names an attachment the turn could not serve, in the
|
||||
// sentence the sender reads.
|
||||
func mediaReplyLabel(att messaging.MediaAttachment) string {
|
||||
switch {
|
||||
case att.Type == "image":
|
||||
return "I received your photo "
|
||||
case att.Type == "document" && att.FileName != "":
|
||||
return fmt.Sprintf("I received %s ", att.FileName)
|
||||
case att.Type == "document":
|
||||
return "I received your file "
|
||||
case att.Type == "video":
|
||||
return "I received your video "
|
||||
default:
|
||||
return "I received your audio attachment "
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// recordedAPI captures every Bot API request so a test can assert a reply
|
||||
// was sent (or, equally, that none was).
|
||||
type recordedAPI struct {
|
||||
mu sync.Mutex
|
||||
calls []string // "path body" lines, one per request
|
||||
}
|
||||
|
||||
func newRecordedAPI(t *testing.T, fileRoute func(w http.ResponseWriter, r *http.Request) bool) (*bot.Bot, *recordedAPI) {
|
||||
t.Helper()
|
||||
rec := &recordedAPI{}
|
||||
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if fileRoute != nil && fileRoute(w, r) {
|
||||
return
|
||||
}
|
||||
body := readBody(r)
|
||||
rec.mu.Lock()
|
||||
rec.calls = append(rec.calls, r.URL.Path+" "+body)
|
||||
rec.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if strings.HasSuffix(r.URL.Path, "getFile") {
|
||||
_, _ = w.Write([]byte(`{"ok":true,"result":{"file_path":"photos/pic.jpg"}}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"ok":true,"result":true}`))
|
||||
}))
|
||||
t.Cleanup(api.Close)
|
||||
|
||||
b, err := bot.New("1:test", bot.WithServerURL(api.URL), bot.WithSkipGetMe())
|
||||
if err != nil {
|
||||
t.Fatalf("new test bot: %v", err)
|
||||
}
|
||||
return b, rec
|
||||
}
|
||||
|
||||
func readBody(r *http.Request) string {
|
||||
_ = r.ParseMultipartForm(1 << 20)
|
||||
if r.PostForm != nil {
|
||||
return r.PostForm.Encode()
|
||||
}
|
||||
return r.URL.RawQuery
|
||||
}
|
||||
|
||||
func (rec *recordedAPI) contains(fragment string) bool {
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
for _, call := range rec.calls {
|
||||
if strings.Contains(strings.ToLower(call), strings.ToLower(fragment)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (rec *recordedAPI) callCount() int {
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
return len(rec.calls)
|
||||
}
|
||||
|
||||
func testMediaGateway(b *bot.Bot) *Gateway {
|
||||
g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler))
|
||||
g.bot = b
|
||||
g.turns = messaging.NewTurns(g.log)
|
||||
return g
|
||||
}
|
||||
|
||||
// TestExtractInboundMediaMapsTelegramKinds walks every supported message
|
||||
// kind. A message's media decides the file the bot must download, so a
|
||||
// mapping error sends the wrong file or sends nothing at all.
|
||||
func TestExtractInboundMediaMapsTelegramKinds(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
msg *models.Message
|
||||
wantType string
|
||||
wantFileID string
|
||||
wantMIME string
|
||||
wantName string
|
||||
wantNote string
|
||||
wantNoMedia bool
|
||||
}{
|
||||
{
|
||||
name: "photo picks the largest size",
|
||||
msg: &models.Message{
|
||||
Photo: []models.PhotoSize{
|
||||
{FileID: "small", Width: 90, Height: 80},
|
||||
{FileID: "big", Width: 1280, Height: 960, FileSize: 150000},
|
||||
},
|
||||
},
|
||||
wantType: "image",
|
||||
wantFileID: "big",
|
||||
wantMIME: "image/jpeg",
|
||||
wantNote: "[photo]",
|
||||
},
|
||||
{
|
||||
name: "document",
|
||||
msg: &models.Message{
|
||||
Document: &models.Document{
|
||||
FileID: "doc1", FileName: "report.pdf", MimeType: "application/pdf", FileSize: 2048,
|
||||
},
|
||||
},
|
||||
wantType: "document",
|
||||
wantFileID: "doc1",
|
||||
wantMIME: "application/pdf",
|
||||
wantName: "report.pdf",
|
||||
wantNote: "[document: report.pdf]",
|
||||
},
|
||||
{
|
||||
name: "video",
|
||||
msg: &models.Message{
|
||||
Video: &models.Video{FileID: "vid1", Duration: 12, MimeType: "video/mp4"},
|
||||
},
|
||||
wantType: "video",
|
||||
wantFileID: "vid1",
|
||||
wantMIME: "video/mp4",
|
||||
wantNote: "[video]",
|
||||
},
|
||||
{
|
||||
name: "video note",
|
||||
msg: &models.Message{
|
||||
VideoNote: &models.VideoNote{FileID: "vnote1", Duration: 30},
|
||||
},
|
||||
wantType: "video",
|
||||
wantFileID: "vnote1",
|
||||
wantMIME: "video/mp4",
|
||||
wantNote: "[video message]",
|
||||
},
|
||||
{
|
||||
name: "audio",
|
||||
msg: &models.Message{
|
||||
Audio: &models.Audio{FileID: "aud1", FileName: "song.mp3", MimeType: "audio/mpeg", Duration: 200},
|
||||
},
|
||||
wantType: "audio",
|
||||
wantFileID: "aud1",
|
||||
wantMIME: "audio/mpeg",
|
||||
wantName: "song.mp3",
|
||||
wantNote: "[audio]",
|
||||
},
|
||||
{
|
||||
name: "voice",
|
||||
msg: &models.Message{
|
||||
Voice: &models.Voice{FileID: "voice1", MimeType: "audio/ogg", Duration: 8},
|
||||
},
|
||||
wantType: "audio",
|
||||
wantFileID: "voice1",
|
||||
wantMIME: "audio/ogg",
|
||||
wantNote: "[voice message]",
|
||||
},
|
||||
{
|
||||
name: "plain text message carries no media",
|
||||
msg: &models.Message{Text: "hello"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, ok := extractInboundMedia(tc.msg)
|
||||
if tc.wantType == "" {
|
||||
if ok {
|
||||
t.Fatalf("extractInboundMedia(%s) = ok, want none", tc.name)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
t.Fatalf("extractInboundMedia(%s) missed, want %s", tc.name, tc.wantType)
|
||||
}
|
||||
att := got.attachment
|
||||
if att.Type != tc.wantType {
|
||||
t.Errorf("Type = %q, want %q", att.Type, tc.wantType)
|
||||
}
|
||||
if att.FileID != tc.wantFileID {
|
||||
t.Errorf("FileID = %q, want %q", att.FileID, tc.wantFileID)
|
||||
}
|
||||
if att.MIMEType != tc.wantMIME {
|
||||
t.Errorf("MIMEType = %q, want %q", att.MIMEType, tc.wantMIME)
|
||||
}
|
||||
if att.FileName != tc.wantName {
|
||||
t.Errorf("FileName = %q, want %q", att.FileName, tc.wantName)
|
||||
}
|
||||
if got.note != tc.wantNote {
|
||||
t.Errorf("note = %q, want %q", got.note, tc.wantNote)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTurnMessageTextKeepsCaptionWithPlaceholder: history is text-only, so
|
||||
// the stored turn text must name the attachment and keep any caption.
|
||||
func TestTurnMessageTextKeepsCaptionWithPlaceholder(t *testing.T) {
|
||||
media, ok := extractInboundMedia(&models.Message{
|
||||
Photo: []models.PhotoSize{{FileID: "a", Width: 10, Height: 10}},
|
||||
Caption: "what is this?",
|
||||
})
|
||||
if !ok {
|
||||
t.Fatal("media missed")
|
||||
}
|
||||
got := turnMessageText(&models.Message{Text: "", Caption: "what is this?"}, media, ok)
|
||||
want := "[photo]\nwhat is this?"
|
||||
if got != want {
|
||||
t.Errorf("turnMessageText = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultHandlerSubmitsPhotoTurnWithDownloadedMedia drives the one
|
||||
// behaviour at the heart of the gap: a photo update reaches the chat turn
|
||||
// with the file's bytes attached, not as a dropped message.
|
||||
func TestDefaultHandlerSubmitsPhotoTurnWithDownloadedMedia(t *testing.T) {
|
||||
photoBytes := []byte("jpeg-bytes")
|
||||
var fileServed bool
|
||||
b, rec := newRecordedAPI(t, func(w http.ResponseWriter, r *http.Request) bool {
|
||||
if strings.HasPrefix(r.URL.Path, "/file/bot1:test/") {
|
||||
w.Header().Set("Content-Type", "image/jpeg")
|
||||
_, _ = w.Write(photoBytes)
|
||||
fileServed = true
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
inboundCh := make(chan messaging.Inbound, 1)
|
||||
client := &fakeChatContract{
|
||||
streamFunc: func(_ context.Context, in messaging.Inbound) (<-chan messaging.ChatEvent, error) {
|
||||
inboundCh <- in
|
||||
ch := make(chan messaging.ChatEvent, 2)
|
||||
ch <- messaging.ChatEvent{Kind: "started", SessionID: "s1"}
|
||||
ch <- messaging.ChatEvent{Kind: "done", Text: "done", SessionID: "s1"}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
},
|
||||
}
|
||||
g := testMediaGateway(b)
|
||||
|
||||
handler := g.defaultHandler(client)
|
||||
handler(context.Background(), b, &models.Update{Message: &models.Message{
|
||||
ID: 5,
|
||||
Date: 1,
|
||||
From: &models.User{ID: 42, Username: "sam"},
|
||||
Chat: models.Chat{ID: 7, Type: "private"},
|
||||
Photo: []models.PhotoSize{{FileID: "big", Width: 1280, Height: 960, FileSize: 150000}},
|
||||
Caption: "look at this",
|
||||
}})
|
||||
|
||||
select {
|
||||
case in := <-inboundCh:
|
||||
if len(in.Media) != 1 {
|
||||
t.Fatalf("inbound media = %#v, want one attachment", in.Media)
|
||||
}
|
||||
att := in.Media[0]
|
||||
if att.Type != "image" || att.MIMEType != "image/jpeg" || att.FileID != "big" {
|
||||
t.Errorf("attachment = %#v, want image with the photo's file id", att)
|
||||
}
|
||||
if string(att.Data) != string(photoBytes) {
|
||||
t.Errorf("Data = %q, want the downloaded photo bytes", att.Data)
|
||||
}
|
||||
want := "[photo]\nlook at this"
|
||||
if in.Message.Text != want {
|
||||
t.Errorf("Text = %q, want %q", in.Message.Text, want)
|
||||
}
|
||||
if in.Message.SourceID != "5" {
|
||||
t.Errorf("SourceID = %q, want the Telegram message id", in.Message.SourceID)
|
||||
}
|
||||
if !fileServed {
|
||||
t.Error("download never fetched the file bytes")
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("photo update never reached the chat turn; api calls were:\n%s",
|
||||
strings.Join(rec.calls, "\n"))
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultHandlerRepliesToUnsupportedMedia keeps the gap from returning
|
||||
// silently in the other direction: content types Archie cannot read get a
|
||||
// clear notice rather than the void.
|
||||
func TestDefaultHandlerRepliesToUnsupportedMedia(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
setup func(*models.Message)
|
||||
reply string
|
||||
}{
|
||||
{"sticker", func(m *models.Message) { m.Sticker = &models.Sticker{FileID: "s"} }, "sticker"},
|
||||
{"location", func(m *models.Message) { m.Location = &models.Location{} }, "location"},
|
||||
{"contact", func(m *models.Message) { m.Contact = &models.Contact{} }, "contact"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
b, rec := newRecordedAPI(t, nil)
|
||||
g := testMediaGateway(b)
|
||||
msg := &models.Message{
|
||||
ID: 6,
|
||||
Date: 1,
|
||||
From: &models.User{ID: 42, Username: "sam"},
|
||||
Chat: models.Chat{ID: 7, Type: "private"},
|
||||
}
|
||||
tc.setup(msg)
|
||||
g.defaultHandler(&fakeChatContract{})(context.Background(), b, &models.Update{Message: msg})
|
||||
if !rec.contains(tc.reply) {
|
||||
t.Errorf("no reply mentioning %q was sent; calls:\n%s", tc.reply, strings.Join(rec.calls, "\n"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultHandlerSilentForNonContentMessages guards the other update
|
||||
// kinds a group can carry: no text, no media, no notice -- and so no reply.
|
||||
func TestDefaultHandlerSilentForNonContentMessages(t *testing.T) {
|
||||
b, rec := newRecordedAPI(t, nil)
|
||||
g := testMediaGateway(b)
|
||||
g.defaultHandler(&fakeChatContract{})(context.Background(), b, &models.Update{Message: &models.Message{
|
||||
ID: 7,
|
||||
Date: 1,
|
||||
From: &models.User{ID: 42},
|
||||
Chat: models.Chat{ID: 7, Type: "private"},
|
||||
}})
|
||||
if n := rec.callCount(); n != 0 {
|
||||
t.Errorf("%d API calls for a message with no text, media or notice, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDownloadMediaCoversSuccessAndLimits exercises the download the turn
|
||||
// relies on: the Bot API getFile lookup, the file fetch, and the size gate.
|
||||
func TestDownloadMediaCoversSuccessAndLimits(t *testing.T) {
|
||||
fileBytes := []byte("file-bytes")
|
||||
b, rec := newRecordedAPI(t, func(w http.ResponseWriter, r *http.Request) bool {
|
||||
if strings.HasPrefix(r.URL.Path, "/file/bot1:test/") {
|
||||
_, _ = w.Write(fileBytes)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
g := testMediaGateway(b)
|
||||
|
||||
t.Run("success", func(t *testing.T) {
|
||||
data, err := g.downloadMedia(context.Background(), b,
|
||||
messaging.MediaAttachment{Type: "image", FileID: "f1", MIMEType: "image/jpeg"})
|
||||
if err != nil {
|
||||
t.Fatalf("downloadMedia() error = %v", err)
|
||||
}
|
||||
if string(data) != string(fileBytes) {
|
||||
t.Errorf("downloaded %q, want %q", data, fileBytes)
|
||||
}
|
||||
if !rec.contains("getfile") {
|
||||
t.Error("getFile never resolved the file path")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("oversized declared size is refused before download", func(t *testing.T) {
|
||||
old := maxInboundDownloadBytes
|
||||
maxInboundDownloadBytes = 4
|
||||
t.Cleanup(func() { maxInboundDownloadBytes = old })
|
||||
size := int64(10)
|
||||
if _, err := g.downloadMedia(context.Background(), b,
|
||||
messaging.MediaAttachment{Type: "document", FileID: "f2", FileSize: &size}); err == nil {
|
||||
t.Error("oversized declared size accepted")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("oversized response body is refused", func(t *testing.T) {
|
||||
old := maxInboundDownloadBytes
|
||||
maxInboundDownloadBytes = 4
|
||||
t.Cleanup(func() { maxInboundDownloadBytes = old })
|
||||
if _, err := g.downloadMedia(context.Background(), b,
|
||||
messaging.MediaAttachment{Type: "document", FileID: "f3"}); err == nil {
|
||||
t.Error("response larger than the limit accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -519,7 +519,7 @@ func (g *Gateway) startHandler() bot.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// ── default handler (non-command text → router) ─────────────
|
||||
// ── default handler (commands and non-command messages → router) ─────
|
||||
|
||||
func (g *Gateway) defaultHandler(client messaging.ChatContract) bot.HandlerFunc {
|
||||
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
||||
@@ -529,7 +529,20 @@ func (g *Gateway) defaultHandler(client messaging.ChatContract) bot.HandlerFunc
|
||||
}
|
||||
|
||||
msg, ok := g.authorizedMessage(ctx, b, update)
|
||||
if !ok || msg.Text == "" {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// Media messages arrive before the text gates: a photo has no text,
|
||||
// so checking it first is what keeps attachments from being dropped.
|
||||
if _, isMedia := extractInboundMedia(msg); isMedia {
|
||||
g.submitTurn(ctx, b, msg, client)
|
||||
return
|
||||
}
|
||||
if notice := unsupportedMediaNotice(msg); notice != "" {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, notice)
|
||||
return
|
||||
}
|
||||
if msg.Text == "" {
|
||||
return
|
||||
}
|
||||
if isModelSelectorRequest(msg.Text) {
|
||||
@@ -584,27 +597,52 @@ func (g *Gateway) handleCallback(ctx context.Context, b *bot.Bot, update *models
|
||||
// running here would block delivery of every later update -- including the
|
||||
// /stop meant to cancel it, which would sit unread until the turn it was
|
||||
// aimed at had already finished.
|
||||
// turnInbound renders a Telegram message as the channel-neutral inbound a
|
||||
// chat turn is built from, with media attachments attached. ok is false
|
||||
// for messages with neither text nor media, which are not turns at all.
|
||||
func turnInbound(msg *models.Message) (messaging.Inbound, bool) {
|
||||
media, hasMedia := extractInboundMedia(msg)
|
||||
if !hasMedia && msg.Text == "" {
|
||||
return messaging.Inbound{}, false
|
||||
}
|
||||
gm := messaging.Inbound{
|
||||
Platform: "telegram",
|
||||
Message: messaging.Message{
|
||||
// Telegram's message ID makes persistence idempotent: the store
|
||||
// derives a canonical ID from it, so a redelivered update is a
|
||||
// no-op rather than appending a duplicate or overwriting the
|
||||
// stored record, which must stay immutable. Date is the sender's
|
||||
// clock reading and is what history should be ordered by.
|
||||
SourceID: fmt.Sprintf("%d", msg.ID),
|
||||
ConversationID: conversationID(msg),
|
||||
Sender: msg.From.Username,
|
||||
SenderID: fmt.Sprintf("%d", msg.From.ID),
|
||||
Role: messaging.RoleUser,
|
||||
Text: turnMessageText(msg, media, hasMedia),
|
||||
At: time.Unix(int64(msg.Date), 0).UTC(),
|
||||
},
|
||||
}
|
||||
if hasMedia {
|
||||
gm.Media = []messaging.MediaAttachment{media.attachment}
|
||||
}
|
||||
return gm, true
|
||||
}
|
||||
|
||||
func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Message, client messaging.ChatContract) {
|
||||
gm := messaging.Inbound{Platform: "telegram", Message: messaging.Message{
|
||||
// Telegram's message ID makes persistence idempotent: the store
|
||||
// derives a canonical ID from it, so a redelivered update is a
|
||||
// no-op rather than appending a duplicate or overwriting the
|
||||
// stored record, which must stay immutable. Date is the sender's
|
||||
// clock reading and is what history should be ordered by.
|
||||
SourceID: fmt.Sprintf("%d", msg.ID),
|
||||
ConversationID: conversationID(msg),
|
||||
Sender: msg.From.Username,
|
||||
SenderID: fmt.Sprintf("%d", msg.From.ID),
|
||||
Role: messaging.RoleUser,
|
||||
Text: msg.Text,
|
||||
At: time.Unix(int64(msg.Date), 0).UTC(),
|
||||
}}
|
||||
gm, isTurn := turnInbound(msg)
|
||||
if !isTurn {
|
||||
return
|
||||
}
|
||||
|
||||
// The lane key must be the session, so that /stop -- which resolves
|
||||
// the same key -- reaches the turn the sender is actually watching.
|
||||
session := conversationID(msg).String()
|
||||
chatID, threadID := msg.Chat.ID, msg.MessageThreadID
|
||||
g.turns.Submit(ctx, session, func(turnCtx context.Context) {
|
||||
if !g.fetchTurnMedia(turnCtx, b, &gm, chatID, threadID) {
|
||||
return
|
||||
}
|
||||
|
||||
// If the turn invokes a tool that requires human approval,
|
||||
// the dispatch layer blocks on this approver. Nil is fine
|
||||
// — most turns need no gating.
|
||||
@@ -629,53 +667,92 @@ func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Messag
|
||||
return
|
||||
}
|
||||
|
||||
var reply string
|
||||
var streamErr error
|
||||
for ev := range events {
|
||||
switch ev.Kind {
|
||||
case "delta":
|
||||
live.Delta(ev.Text)
|
||||
case "tool":
|
||||
live.ToolCall(ev.Tool)
|
||||
case "media":
|
||||
live.Media(turnCtx, ev.Media)
|
||||
case "done":
|
||||
reply = ev.Text
|
||||
case "error":
|
||||
streamErr = errors.New(ev.Text)
|
||||
}
|
||||
}
|
||||
stopTyping()
|
||||
|
||||
// A cancelled turn is a /stop, not a fault. The stop handler has
|
||||
// already acknowledged it, and turnCtx is dead, so there is
|
||||
// nothing useful left to send from here -- but whatever was
|
||||
// already streamed stays, minus the cursor that would otherwise
|
||||
// claim the answer is still being written. abandon strips turnCtx's
|
||||
// own cancellation before it edits, so the cursor-drop is not itself
|
||||
// aborted by the /stop that triggered it.
|
||||
//
|
||||
// errors.Is(err, context.Canceled) reliably separates a /stop from a
|
||||
// fault; either way turnCtx is dead by the time we get here. A
|
||||
// genuine fault is marked as failed rather than left as a clean
|
||||
// partial: /stop is an acknowledged interruption, a provider error
|
||||
// is not, and an unmarked partial reads as a finished answer either
|
||||
// way.
|
||||
if streamErr != nil || turnCtx.Err() != nil {
|
||||
if errors.Is(turnCtx.Err(), context.Canceled) || (streamErr != nil && errors.Is(streamErr, context.Canceled)) {
|
||||
g.log.Info("chat turn stopped", "session", session)
|
||||
live.abandon(turnCtx)
|
||||
} else {
|
||||
g.log.Error("stream turn failed", "error", streamErr)
|
||||
live.abandonFailed(turnCtx)
|
||||
}
|
||||
reply, aborted := g.drainTurnEvents(turnCtx, session, live, stopTyping, events)
|
||||
if aborted {
|
||||
return
|
||||
}
|
||||
live.finalize(turnCtx, reply)
|
||||
})
|
||||
}
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────
|
||||
// drainTurnEvents consumes a streamed turn, rendering deltas, tool calls
|
||||
// and media as they arrive, and returns the final reply.
|
||||
//
|
||||
// A cancelled turn is a /stop, not a fault. The stop handler has already
|
||||
// acknowledged it, and turnCtx is dead, so there is
|
||||
// nothing useful left to send from here -- but whatever was
|
||||
// already streamed stays, minus the cursor that would otherwise
|
||||
// claim the answer is still being written. abandon strips turnCtx's
|
||||
// own cancellation before it edits, so the cursor-drop is not itself
|
||||
// aborted by the /stop that triggered it.
|
||||
//
|
||||
// errors.Is(err, context.Canceled) reliably separates a /stop from a
|
||||
// fault; either way turnCtx is dead by the time we get here. A
|
||||
// genuine fault is marked as failed rather than left as a clean
|
||||
// partial: /stop is an acknowledged interruption, a provider error
|
||||
// is not, and an unmarked partial reads as a finished answer either
|
||||
// way.
|
||||
//
|
||||
// aborted means the turn was abandoned (as a stop or a failure) and its
|
||||
// reply must not be finalized.
|
||||
func (g *Gateway) drainTurnEvents(
|
||||
turnCtx context.Context, session string,
|
||||
live *liveReply, stopTyping func(), events <-chan messaging.ChatEvent,
|
||||
) (string, bool) {
|
||||
var reply string
|
||||
var streamErr error
|
||||
for ev := range events {
|
||||
switch ev.Kind {
|
||||
case "delta":
|
||||
live.Delta(ev.Text)
|
||||
case "tool":
|
||||
live.ToolCall(ev.Tool)
|
||||
case "media":
|
||||
live.Media(turnCtx, ev.Media)
|
||||
case "done":
|
||||
reply = ev.Text
|
||||
case "error":
|
||||
streamErr = errors.New(ev.Text)
|
||||
}
|
||||
}
|
||||
stopTyping()
|
||||
|
||||
if streamErr != nil || turnCtx.Err() != nil {
|
||||
if errors.Is(turnCtx.Err(), context.Canceled) || (streamErr != nil && errors.Is(streamErr, context.Canceled)) {
|
||||
g.log.Info("chat turn stopped", "session", session)
|
||||
live.abandon(turnCtx)
|
||||
} else {
|
||||
g.log.Error("stream turn failed", "error", streamErr)
|
||||
live.abandonFailed(turnCtx)
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
return reply, false
|
||||
}
|
||||
|
||||
// fetchTurnMedia downloads the turn's inbound attachment onto the lane,
|
||||
// where waiting for the Telegram API belongs: the update worker stays free
|
||||
// to serve other messages and a /stop while this download progresses. A
|
||||
// failed download is reported as a failed attachment without starting the
|
||||
// turn, so the answer does not pretend the media was read -- a later
|
||||
// turn's history only knows the note, not the picture, and the model must
|
||||
// not reason from what it never saw.
|
||||
func (g *Gateway) fetchTurnMedia(ctx context.Context, b *bot.Bot, gm *messaging.Inbound, chatID int64, threadID int) bool {
|
||||
if len(gm.Media) == 0 || gm.Media[0].Data != nil {
|
||||
return true
|
||||
}
|
||||
data, err := g.downloadMedia(ctx, b, gm.Media[0])
|
||||
if err != nil {
|
||||
g.log.Warn("inbound media download failed", "media_type", gm.Media[0].Type, "error", err)
|
||||
g.sendMessage(ctx, b, chatID, threadID,
|
||||
mediaReplyLabel(gm.Media[0])+"but I couldn't download it — try sending it again.")
|
||||
return false
|
||||
}
|
||||
gm.Media[0].Data = data
|
||||
return true
|
||||
}
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────────
|
||||
|
||||
// conversationID addresses the chat a Telegram message arrived in: the
|
||||
// chat ID, and the topic thread within it for supergroups.
|
||||
|
||||
@@ -95,13 +95,6 @@ type Repo struct {
|
||||
// won't collide (e.g. different base branches or packages per
|
||||
// task). Still bounded by [containers].max_concurrency globally.
|
||||
AllowConcurrent bool `toml:"allow_concurrent" json:"allow_concurrent" yaml:"allow_concurrent"`
|
||||
// ReviewEnabled opts this repo into the adversarial self-review stage
|
||||
// (docs/prds/adversarial-self-review.md): a fresh reviewer agent, with
|
||||
// no path to the implementer's context, runs after gates pass and
|
||||
// before the PR opens. Default false -- an uncalibrated reviewer that
|
||||
// cries wolf is worse than no review, so a repo opts in once it
|
||||
// trusts the stage.
|
||||
ReviewEnabled bool `toml:"review_enabled" json:"review_enabled" yaml:"review_enabled"`
|
||||
}
|
||||
|
||||
// Protected reports whether path matches a protected suffix.
|
||||
@@ -210,6 +203,23 @@ type Forge struct {
|
||||
WebhookAddr string `toml:"webhook_addr" yaml:"webhook_addr"`
|
||||
}
|
||||
|
||||
// Review configures the pr-review workflow (docs/prds/pr-review-agent.md).
|
||||
// Both fields are off by default: the pipeline is recall-first, and posts
|
||||
// automatically, unless an operator opts into either dial.
|
||||
type Review struct {
|
||||
// PrecisionGate runs a post-worthiness pass after phase 4 (review) and
|
||||
// before phase 5 (verification): it keeps every concrete, evidenced
|
||||
// defect, drops nitpicks, style and unverifiable claims, and keeps a
|
||||
// finding when unsure. It trades recall for precision and cuts
|
||||
// verification cost by filtering early.
|
||||
PrecisionGate bool `toml:"precision_gate" yaml:"precision_gate"`
|
||||
// ApproveBeforePost ends the pipeline in waiting_human right after
|
||||
// synthesis, before the merge gate runs, so an operator can choose which
|
||||
// findings to post, reject the review, or ask for a re-review with
|
||||
// instructions. A review with no findings never waits.
|
||||
ApproveBeforePost bool `toml:"approve_before_post" yaml:"approve_before_post"`
|
||||
}
|
||||
|
||||
// Dispatch configures how archied discovers work and reflects task state
|
||||
// onto the forge via labels and reactions.
|
||||
type Dispatch struct {
|
||||
@@ -486,6 +496,7 @@ type Config struct {
|
||||
|
||||
Forge Forge `toml:"forge" yaml:"forge"`
|
||||
Dispatch Dispatch `toml:"dispatch" yaml:"dispatch"`
|
||||
Review Review `toml:"review" yaml:"review"`
|
||||
|
||||
// Models maps a role ("planner", "builder", "triage") to a runtime
|
||||
// model ref ("provider/model").
|
||||
@@ -604,6 +615,7 @@ type TaskConfig struct {
|
||||
Notify Notify `json:"notify"`
|
||||
Forge TaskForge `json:"forge"`
|
||||
ToolPolicy ToolPolicy `json:"tool_policy"`
|
||||
Review Review `json:"review"`
|
||||
}
|
||||
|
||||
// DiffCapOf returns a DiffCapLines value for n. It exists because the field is
|
||||
@@ -644,6 +656,7 @@ func (c Config) ForTask() TaskConfig {
|
||||
Notify: c.Notify,
|
||||
Forge: TaskForge{Host: c.Forge.Host},
|
||||
ToolPolicy: c.Tools.Policy,
|
||||
Review: c.Review,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -663,6 +676,7 @@ func (tc TaskConfig) ToConfig() Config {
|
||||
Notify: tc.Notify,
|
||||
Forge: Forge{Host: tc.Forge.Host},
|
||||
Tools: ToolsConfig{Policy: tc.ToolPolicy},
|
||||
Review: tc.Review,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -157,8 +157,9 @@ func TestConfigForTaskJSONRoundTrip(t *testing.T) {
|
||||
Providers: map[string]Provider{
|
||||
"secret": {APIKeyEnv: "TOP_SECRET_PROVIDER_TOKEN"},
|
||||
},
|
||||
NATS: NATSConfig{TokenEnv: "TOP_SECRET_NATS_TOKEN"},
|
||||
Tools: ToolsConfig{Policy: ToolPolicy{MaxResultChars: 50_000, SpillDir: "/var/tmp/archie-spill"}},
|
||||
NATS: NATSConfig{TokenEnv: "TOP_SECRET_NATS_TOKEN"},
|
||||
Tools: ToolsConfig{Policy: ToolPolicy{MaxResultChars: 50_000, SpillDir: "/var/tmp/archie-spill"}},
|
||||
Review: Review{PrecisionGate: true, ApproveBeforePost: true},
|
||||
}
|
||||
|
||||
want := TaskConfig{
|
||||
@@ -171,6 +172,7 @@ func TestConfigForTaskJSONRoundTrip(t *testing.T) {
|
||||
Notify: cfg.Notify,
|
||||
Forge: TaskForge{Host: cfg.Forge.Host},
|
||||
ToolPolicy: cfg.Tools.Policy,
|
||||
Review: cfg.Review,
|
||||
}
|
||||
got := cfg.ForTask()
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
@@ -197,7 +199,7 @@ func TestConfigForTaskJSONRoundTrip(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertJSONKeys(t, data, "bot_user", "bot_email", "models", "budgets", "dispatch", "diff_cap_lines", "notify", "forge", "tool_policy")
|
||||
assertJSONKeys(t, data, "bot_user", "bot_email", "models", "budgets", "dispatch", "diff_cap_lines", "notify", "forge", "tool_policy", "review")
|
||||
|
||||
var forgePayload map[string]json.RawMessage
|
||||
var payload map[string]json.RawMessage
|
||||
@@ -251,7 +253,6 @@ func TestRepoJSONRoundTrip(t *testing.T) {
|
||||
PersistentStorage: true,
|
||||
MaxRetries: 4,
|
||||
AllowConcurrent: true,
|
||||
ReviewEnabled: true,
|
||||
}
|
||||
|
||||
data, err := json.Marshal(repo)
|
||||
@@ -271,7 +272,6 @@ func TestRepoJSONRoundTrip(t *testing.T) {
|
||||
"persistent_storage",
|
||||
"max_retries",
|
||||
"allow_concurrent",
|
||||
"review_enabled",
|
||||
)
|
||||
|
||||
var got Repo
|
||||
|
||||
@@ -213,6 +213,7 @@ type Resource struct {
|
||||
Version int64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"`
|
||||
ValueJson []byte `protobuf:"bytes,3,opt,name=value_json,json=valueJson,proto3" json:"value_json,omitempty"`
|
||||
UpdatedAt *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"`
|
||||
OrgId string `protobuf:"bytes,5,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -275,9 +276,19 @@ func (x *Resource) GetUpdatedAt() *timestamppb.Timestamp {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Resource) GetOrgId() string {
|
||||
if x != nil {
|
||||
return x.OrgId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Every request that names a resource acts in one org's copy of it. An empty
|
||||
// org_id is the default org.
|
||||
type QueryRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
|
||||
OrgId string `protobuf:"bytes,2,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -319,6 +330,13 @@ func (x *QueryRequest) GetKind() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *QueryRequest) GetOrgId() string {
|
||||
if x != nil {
|
||||
return x.OrgId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type QueryResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Resource *Resource `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"`
|
||||
@@ -454,7 +472,8 @@ type HistoryRequest struct {
|
||||
Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
|
||||
// Limit caps the revisions returned, newest first. Zero means the server's
|
||||
// own default.
|
||||
Limit int32 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"`
|
||||
Limit int32 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"`
|
||||
OrgId string `protobuf:"bytes,3,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -503,6 +522,13 @@ func (x *HistoryRequest) GetLimit() int32 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *HistoryRequest) GetOrgId() string {
|
||||
if x != nil {
|
||||
return x.OrgId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type HistoryResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Revisions []*Revision `protobuf:"bytes,1,rep,name=revisions,proto3" json:"revisions,omitempty"`
|
||||
@@ -790,6 +816,7 @@ type CommandRequest struct {
|
||||
// from browser/request JSON.
|
||||
Actor string `protobuf:"bytes,6,opt,name=actor,proto3" json:"actor,omitempty"`
|
||||
Source string `protobuf:"bytes,7,opt,name=source,proto3" json:"source,omitempty"`
|
||||
OrgId string `protobuf:"bytes,8,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -873,6 +900,13 @@ func (x *CommandRequest) GetSource() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *CommandRequest) GetOrgId() string {
|
||||
if x != nil {
|
||||
return x.OrgId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type CommandResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Resource *Resource `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"`
|
||||
@@ -921,6 +955,7 @@ type WatchRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
|
||||
AfterVersion int64 `protobuf:"varint,2,opt,name=after_version,json=afterVersion,proto3" json:"after_version,omitempty"`
|
||||
OrgId string `protobuf:"bytes,3,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -969,6 +1004,13 @@ func (x *WatchRequest) GetAfterVersion() int64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *WatchRequest) GetOrgId() string {
|
||||
if x != nil {
|
||||
return x.OrgId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type WatchResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Resource *Resource `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"`
|
||||
@@ -1039,16 +1081,18 @@ const file_controlplane_v1_controlplane_proto_rawDesc = "" +
|
||||
"\rdefaults_json\x18\b \x01(\tR\fdefaultsJson\"\x10\n" +
|
||||
"\x0eCatalogRequest\"T\n" +
|
||||
"\x0fCatalogResponse\x12A\n" +
|
||||
"\tresources\x18\x01 \x03(\v2#.controlplane.v1.ResourceDescriptorR\tresources\"\x92\x01\n" +
|
||||
"\tresources\x18\x01 \x03(\v2#.controlplane.v1.ResourceDescriptorR\tresources\"\xa9\x01\n" +
|
||||
"\bResource\x12\x12\n" +
|
||||
"\x04kind\x18\x01 \x01(\tR\x04kind\x12\x18\n" +
|
||||
"\aversion\x18\x02 \x01(\x03R\aversion\x12\x1d\n" +
|
||||
"\n" +
|
||||
"value_json\x18\x03 \x01(\fR\tvalueJson\x129\n" +
|
||||
"\n" +
|
||||
"updated_at\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\"\"\n" +
|
||||
"updated_at\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\x12\x15\n" +
|
||||
"\x06org_id\x18\x05 \x01(\tR\x05orgId\"9\n" +
|
||||
"\fQueryRequest\x12\x12\n" +
|
||||
"\x04kind\x18\x01 \x01(\tR\x04kind\"F\n" +
|
||||
"\x04kind\x18\x01 \x01(\tR\x04kind\x12\x15\n" +
|
||||
"\x06org_id\x18\x02 \x01(\tR\x05orgId\"F\n" +
|
||||
"\rQueryResponse\x125\n" +
|
||||
"\bresource\x18\x01 \x01(\v2\x19.controlplane.v1.ResourceR\bresource\"\xbc\x01\n" +
|
||||
"\bRevision\x12\x18\n" +
|
||||
@@ -1059,10 +1103,11 @@ const file_controlplane_v1_controlplane_proto_rawDesc = "" +
|
||||
"\x06source\x18\x04 \x01(\tR\x06source\x12\x1d\n" +
|
||||
"\n" +
|
||||
"request_id\x18\x05 \x01(\tR\trequestId\x12*\n" +
|
||||
"\x02at\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\x02at\":\n" +
|
||||
"\x02at\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\x02at\"Q\n" +
|
||||
"\x0eHistoryRequest\x12\x12\n" +
|
||||
"\x04kind\x18\x01 \x01(\tR\x04kind\x12\x14\n" +
|
||||
"\x05limit\x18\x02 \x01(\x05R\x05limit\"J\n" +
|
||||
"\x05limit\x18\x02 \x01(\x05R\x05limit\x12\x15\n" +
|
||||
"\x06org_id\x18\x03 \x01(\tR\x05orgId\"J\n" +
|
||||
"\x0fHistoryResponse\x127\n" +
|
||||
"\trevisions\x18\x01 \x03(\v2\x19.controlplane.v1.RevisionR\trevisions\"\xc6\x02\n" +
|
||||
"\n" +
|
||||
@@ -1087,7 +1132,7 @@ const file_controlplane_v1_controlplane_proto_rawDesc = "" +
|
||||
"recordKeys\x12\x14\n" +
|
||||
"\x05limit\x18\x03 \x01(\x05R\x05limit\"F\n" +
|
||||
"\rAuditResponse\x125\n" +
|
||||
"\aentries\x18\x01 \x03(\v2\x1b.controlplane.v1.AuditEntryR\aentries\"\xd5\x01\n" +
|
||||
"\aentries\x18\x01 \x03(\v2\x1b.controlplane.v1.AuditEntryR\aentries\"\xec\x01\n" +
|
||||
"\x0eCommandRequest\x12\x12\n" +
|
||||
"\x04kind\x18\x01 \x01(\tR\x04kind\x12\x18\n" +
|
||||
"\acommand\x18\x02 \x01(\tR\acommand\x12\x1d\n" +
|
||||
@@ -1097,12 +1142,14 @@ const file_controlplane_v1_controlplane_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"request_id\x18\x05 \x01(\tR\trequestId\x12\x14\n" +
|
||||
"\x05actor\x18\x06 \x01(\tR\x05actor\x12\x16\n" +
|
||||
"\x06source\x18\a \x01(\tR\x06source\"H\n" +
|
||||
"\x06source\x18\a \x01(\tR\x06source\x12\x15\n" +
|
||||
"\x06org_id\x18\b \x01(\tR\x05orgId\"H\n" +
|
||||
"\x0fCommandResponse\x125\n" +
|
||||
"\bresource\x18\x01 \x01(\v2\x19.controlplane.v1.ResourceR\bresource\"G\n" +
|
||||
"\bresource\x18\x01 \x01(\v2\x19.controlplane.v1.ResourceR\bresource\"^\n" +
|
||||
"\fWatchRequest\x12\x12\n" +
|
||||
"\x04kind\x18\x01 \x01(\tR\x04kind\x12#\n" +
|
||||
"\rafter_version\x18\x02 \x01(\x03R\fafterVersion\"\\\n" +
|
||||
"\rafter_version\x18\x02 \x01(\x03R\fafterVersion\x12\x15\n" +
|
||||
"\x06org_id\x18\x03 \x01(\tR\x05orgId\"\\\n" +
|
||||
"\rWatchResponse\x125\n" +
|
||||
"\bresource\x18\x01 \x01(\v2\x19.controlplane.v1.ResourceR\bresource\x12\x14\n" +
|
||||
"\x05error\x18\x02 \x01(\tR\x05error2\xd9\x03\n" +
|
||||
|
||||
@@ -161,7 +161,12 @@ type Message struct {
|
||||
// channel, so its own name is "web" even for a Telegram turn, which made
|
||||
// Source.Platform -- the first component of the session natural key -- a
|
||||
// constant. Transport-only, never persisted: the session record keeps it.
|
||||
Platform string `protobuf:"bytes,10,opt,name=platform,proto3" json:"platform,omitempty"`
|
||||
Platform string `protobuf:"bytes,10,opt,name=platform,proto3" json:"platform,omitempty"`
|
||||
// media carries attachment metadata for a message that arrived with a
|
||||
// file. The attachment's bytes never cross this wire: a stored Media
|
||||
// with tool_name empty is a sender attachment, and the tool_name on
|
||||
// tool-produced events stays a stream-only field.
|
||||
Media []*Media `protobuf:"bytes,11,rep,name=media,proto3" json:"media,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -266,6 +271,13 @@ func (x *Message) GetPlatform() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Message) GetMedia() []*Media {
|
||||
if x != nil {
|
||||
return x.Media
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type ToolCall struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
|
||||
@@ -2818,7 +2830,7 @@ const file_gateway_v1_chat_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"created_at\x18\t \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x12@\n" +
|
||||
"\x0elast_active_at\x18\n" +
|
||||
" \x01(\v2\x1a.google.protobuf.TimestampR\flastActiveAt\"\xa4\x02\n" +
|
||||
" \x01(\v2\x1a.google.protobuf.TimestampR\flastActiveAt\"\xcd\x02\n" +
|
||||
"\aMessage\x12\x1d\n" +
|
||||
"\n" +
|
||||
"message_id\x18\x01 \x01(\tR\tmessageId\x12\x1b\n" +
|
||||
@@ -2833,7 +2845,8 @@ const file_gateway_v1_chat_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"budget_key\x18\t \x01(\tR\tbudgetKey\x12\x1a\n" +
|
||||
"\bplatform\x18\n" +
|
||||
" \x01(\tR\bplatform\"|\n" +
|
||||
" \x01(\tR\bplatform\x12'\n" +
|
||||
"\x05media\x18\v \x03(\v2\x11.gateway.v1.MediaR\x05media\"|\n" +
|
||||
"\bToolCall\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" +
|
||||
"\x04name\x18\x02 \x01(\tR\x04name\x12\x1e\n" +
|
||||
@@ -3127,74 +3140,75 @@ var file_gateway_v1_chat_proto_depIdxs = []int32{
|
||||
50, // 0: gateway.v1.Session.created_at:type_name -> google.protobuf.Timestamp
|
||||
50, // 1: gateway.v1.Session.last_active_at:type_name -> google.protobuf.Timestamp
|
||||
50, // 2: gateway.v1.Message.at:type_name -> google.protobuf.Timestamp
|
||||
2, // 3: gateway.v1.Turn.tool_calls:type_name -> gateway.v1.ToolCall
|
||||
50, // 4: gateway.v1.Turn.created_at:type_name -> google.protobuf.Timestamp
|
||||
50, // 5: gateway.v1.Turn.updated_at:type_name -> google.protobuf.Timestamp
|
||||
0, // 6: gateway.v1.SnapshotResponse.sessions:type_name -> gateway.v1.Session
|
||||
48, // 7: gateway.v1.SnapshotResponse.models_by_provider:type_name -> gateway.v1.SnapshotResponse.ModelsByProviderEntry
|
||||
49, // 8: gateway.v1.SnapshotResponse.active_personas:type_name -> gateway.v1.SnapshotResponse.ActivePersonasEntry
|
||||
0, // 9: gateway.v1.GetSessionResponse.session:type_name -> gateway.v1.Session
|
||||
1, // 10: gateway.v1.RecentMessagesResponse.messages:type_name -> gateway.v1.Message
|
||||
4, // 11: gateway.v1.RecentTurnsResponse.turns:type_name -> gateway.v1.Turn
|
||||
1, // 12: gateway.v1.RouteRequest.message:type_name -> gateway.v1.Message
|
||||
1, // 13: gateway.v1.StreamRequest.message:type_name -> gateway.v1.Message
|
||||
2, // 14: gateway.v1.StreamResponse.tool:type_name -> gateway.v1.ToolCall
|
||||
3, // 15: gateway.v1.StreamResponse.media:type_name -> gateway.v1.Media
|
||||
0, // 16: gateway.v1.SaveSessionRequest.session:type_name -> gateway.v1.Session
|
||||
0, // 17: gateway.v1.GetSessionsByChannelResponse.sessions:type_name -> gateway.v1.Session
|
||||
0, // 18: gateway.v1.ListSessionsResponse.sessions:type_name -> gateway.v1.Session
|
||||
1, // 19: gateway.v1.SaveMessageRequest.message:type_name -> gateway.v1.Message
|
||||
1, // 20: gateway.v1.SaveMessagesRequest.messages:type_name -> gateway.v1.Message
|
||||
1, // 21: gateway.v1.ReplaceMessagesRequest.messages:type_name -> gateway.v1.Message
|
||||
1, // 22: gateway.v1.SearchMessagesResponse.messages:type_name -> gateway.v1.Message
|
||||
5, // 23: gateway.v1.SnapshotResponse.ModelsByProviderEntry.value:type_name -> gateway.v1.StringList
|
||||
6, // 24: gateway.v1.ChatService.Snapshot:input_type -> gateway.v1.SnapshotRequest
|
||||
8, // 25: gateway.v1.ChatService.GetSession:input_type -> gateway.v1.GetSessionRequest
|
||||
10, // 26: gateway.v1.ChatService.RecentMessages:input_type -> gateway.v1.RecentMessagesRequest
|
||||
12, // 27: gateway.v1.ChatService.RecentTurns:input_type -> gateway.v1.RecentTurnsRequest
|
||||
14, // 28: gateway.v1.ChatService.Route:input_type -> gateway.v1.RouteRequest
|
||||
16, // 29: gateway.v1.ChatService.Stream:input_type -> gateway.v1.StreamRequest
|
||||
18, // 30: gateway.v1.ChatService.Cancel:input_type -> gateway.v1.CancelRequest
|
||||
20, // 31: gateway.v1.ChatService.SetPersona:input_type -> gateway.v1.SetPersonaRequest
|
||||
22, // 32: gateway.v1.ChatService.ApplyTaskAction:input_type -> gateway.v1.ApplyTaskActionRequest
|
||||
24, // 33: gateway.v1.ChatService.ApplyOperatorTaskAction:input_type -> gateway.v1.ApplyOperatorTaskActionRequest
|
||||
27, // 34: gateway.v1.ChatService.SaveSession:input_type -> gateway.v1.SaveSessionRequest
|
||||
28, // 35: gateway.v1.ChatService.GetSessionsByChannel:input_type -> gateway.v1.GetSessionsByChannelRequest
|
||||
36, // 36: gateway.v1.ChatService.DeleteSession:input_type -> gateway.v1.DeleteSessionRequest
|
||||
37, // 37: gateway.v1.ChatService.TouchSession:input_type -> gateway.v1.TouchSessionRequest
|
||||
38, // 38: gateway.v1.ChatService.ListSessions:input_type -> gateway.v1.ListSessionsRequest
|
||||
39, // 39: gateway.v1.ChatService.SaveMessage:input_type -> gateway.v1.SaveMessageRequest
|
||||
40, // 40: gateway.v1.ChatService.DeleteRecentMessages:input_type -> gateway.v1.DeleteRecentMessagesRequest
|
||||
42, // 41: gateway.v1.ChatService.MessageCount:input_type -> gateway.v1.MessageCountRequest
|
||||
44, // 42: gateway.v1.ChatService.SaveMessages:input_type -> gateway.v1.SaveMessagesRequest
|
||||
45, // 43: gateway.v1.ChatService.ReplaceMessages:input_type -> gateway.v1.ReplaceMessagesRequest
|
||||
46, // 44: gateway.v1.ChatService.SearchMessages:input_type -> gateway.v1.SearchMessagesRequest
|
||||
7, // 45: gateway.v1.ChatService.Snapshot:output_type -> gateway.v1.SnapshotResponse
|
||||
9, // 46: gateway.v1.ChatService.GetSession:output_type -> gateway.v1.GetSessionResponse
|
||||
11, // 47: gateway.v1.ChatService.RecentMessages:output_type -> gateway.v1.RecentMessagesResponse
|
||||
13, // 48: gateway.v1.ChatService.RecentTurns:output_type -> gateway.v1.RecentTurnsResponse
|
||||
15, // 49: gateway.v1.ChatService.Route:output_type -> gateway.v1.RouteResponse
|
||||
17, // 50: gateway.v1.ChatService.Stream:output_type -> gateway.v1.StreamResponse
|
||||
19, // 51: gateway.v1.ChatService.Cancel:output_type -> gateway.v1.CancelResponse
|
||||
21, // 52: gateway.v1.ChatService.SetPersona:output_type -> gateway.v1.SetPersonaResponse
|
||||
23, // 53: gateway.v1.ChatService.ApplyTaskAction:output_type -> gateway.v1.ApplyTaskActionResponse
|
||||
25, // 54: gateway.v1.ChatService.ApplyOperatorTaskAction:output_type -> gateway.v1.ApplyOperatorTaskActionResponse
|
||||
26, // 55: gateway.v1.ChatService.SaveSession:output_type -> gateway.v1.SaveSessionResponse
|
||||
29, // 56: gateway.v1.ChatService.GetSessionsByChannel:output_type -> gateway.v1.GetSessionsByChannelResponse
|
||||
31, // 57: gateway.v1.ChatService.DeleteSession:output_type -> gateway.v1.DeleteSessionResponse
|
||||
32, // 58: gateway.v1.ChatService.TouchSession:output_type -> gateway.v1.TouchSessionResponse
|
||||
30, // 59: gateway.v1.ChatService.ListSessions:output_type -> gateway.v1.ListSessionsResponse
|
||||
33, // 60: gateway.v1.ChatService.SaveMessage:output_type -> gateway.v1.SaveMessageResponse
|
||||
41, // 61: gateway.v1.ChatService.DeleteRecentMessages:output_type -> gateway.v1.DeleteRecentMessagesResponse
|
||||
43, // 62: gateway.v1.ChatService.MessageCount:output_type -> gateway.v1.MessageCountResponse
|
||||
34, // 63: gateway.v1.ChatService.SaveMessages:output_type -> gateway.v1.SaveMessagesResponse
|
||||
35, // 64: gateway.v1.ChatService.ReplaceMessages:output_type -> gateway.v1.ReplaceMessagesResponse
|
||||
47, // 65: gateway.v1.ChatService.SearchMessages:output_type -> gateway.v1.SearchMessagesResponse
|
||||
45, // [45:66] is the sub-list for method output_type
|
||||
24, // [24:45] is the sub-list for method input_type
|
||||
24, // [24:24] is the sub-list for extension type_name
|
||||
24, // [24:24] is the sub-list for extension extendee
|
||||
0, // [0:24] is the sub-list for field type_name
|
||||
3, // 3: gateway.v1.Message.media:type_name -> gateway.v1.Media
|
||||
2, // 4: gateway.v1.Turn.tool_calls:type_name -> gateway.v1.ToolCall
|
||||
50, // 5: gateway.v1.Turn.created_at:type_name -> google.protobuf.Timestamp
|
||||
50, // 6: gateway.v1.Turn.updated_at:type_name -> google.protobuf.Timestamp
|
||||
0, // 7: gateway.v1.SnapshotResponse.sessions:type_name -> gateway.v1.Session
|
||||
48, // 8: gateway.v1.SnapshotResponse.models_by_provider:type_name -> gateway.v1.SnapshotResponse.ModelsByProviderEntry
|
||||
49, // 9: gateway.v1.SnapshotResponse.active_personas:type_name -> gateway.v1.SnapshotResponse.ActivePersonasEntry
|
||||
0, // 10: gateway.v1.GetSessionResponse.session:type_name -> gateway.v1.Session
|
||||
1, // 11: gateway.v1.RecentMessagesResponse.messages:type_name -> gateway.v1.Message
|
||||
4, // 12: gateway.v1.RecentTurnsResponse.turns:type_name -> gateway.v1.Turn
|
||||
1, // 13: gateway.v1.RouteRequest.message:type_name -> gateway.v1.Message
|
||||
1, // 14: gateway.v1.StreamRequest.message:type_name -> gateway.v1.Message
|
||||
2, // 15: gateway.v1.StreamResponse.tool:type_name -> gateway.v1.ToolCall
|
||||
3, // 16: gateway.v1.StreamResponse.media:type_name -> gateway.v1.Media
|
||||
0, // 17: gateway.v1.SaveSessionRequest.session:type_name -> gateway.v1.Session
|
||||
0, // 18: gateway.v1.GetSessionsByChannelResponse.sessions:type_name -> gateway.v1.Session
|
||||
0, // 19: gateway.v1.ListSessionsResponse.sessions:type_name -> gateway.v1.Session
|
||||
1, // 20: gateway.v1.SaveMessageRequest.message:type_name -> gateway.v1.Message
|
||||
1, // 21: gateway.v1.SaveMessagesRequest.messages:type_name -> gateway.v1.Message
|
||||
1, // 22: gateway.v1.ReplaceMessagesRequest.messages:type_name -> gateway.v1.Message
|
||||
1, // 23: gateway.v1.SearchMessagesResponse.messages:type_name -> gateway.v1.Message
|
||||
5, // 24: gateway.v1.SnapshotResponse.ModelsByProviderEntry.value:type_name -> gateway.v1.StringList
|
||||
6, // 25: gateway.v1.ChatService.Snapshot:input_type -> gateway.v1.SnapshotRequest
|
||||
8, // 26: gateway.v1.ChatService.GetSession:input_type -> gateway.v1.GetSessionRequest
|
||||
10, // 27: gateway.v1.ChatService.RecentMessages:input_type -> gateway.v1.RecentMessagesRequest
|
||||
12, // 28: gateway.v1.ChatService.RecentTurns:input_type -> gateway.v1.RecentTurnsRequest
|
||||
14, // 29: gateway.v1.ChatService.Route:input_type -> gateway.v1.RouteRequest
|
||||
16, // 30: gateway.v1.ChatService.Stream:input_type -> gateway.v1.StreamRequest
|
||||
18, // 31: gateway.v1.ChatService.Cancel:input_type -> gateway.v1.CancelRequest
|
||||
20, // 32: gateway.v1.ChatService.SetPersona:input_type -> gateway.v1.SetPersonaRequest
|
||||
22, // 33: gateway.v1.ChatService.ApplyTaskAction:input_type -> gateway.v1.ApplyTaskActionRequest
|
||||
24, // 34: gateway.v1.ChatService.ApplyOperatorTaskAction:input_type -> gateway.v1.ApplyOperatorTaskActionRequest
|
||||
27, // 35: gateway.v1.ChatService.SaveSession:input_type -> gateway.v1.SaveSessionRequest
|
||||
28, // 36: gateway.v1.ChatService.GetSessionsByChannel:input_type -> gateway.v1.GetSessionsByChannelRequest
|
||||
36, // 37: gateway.v1.ChatService.DeleteSession:input_type -> gateway.v1.DeleteSessionRequest
|
||||
37, // 38: gateway.v1.ChatService.TouchSession:input_type -> gateway.v1.TouchSessionRequest
|
||||
38, // 39: gateway.v1.ChatService.ListSessions:input_type -> gateway.v1.ListSessionsRequest
|
||||
39, // 40: gateway.v1.ChatService.SaveMessage:input_type -> gateway.v1.SaveMessageRequest
|
||||
40, // 41: gateway.v1.ChatService.DeleteRecentMessages:input_type -> gateway.v1.DeleteRecentMessagesRequest
|
||||
42, // 42: gateway.v1.ChatService.MessageCount:input_type -> gateway.v1.MessageCountRequest
|
||||
44, // 43: gateway.v1.ChatService.SaveMessages:input_type -> gateway.v1.SaveMessagesRequest
|
||||
45, // 44: gateway.v1.ChatService.ReplaceMessages:input_type -> gateway.v1.ReplaceMessagesRequest
|
||||
46, // 45: gateway.v1.ChatService.SearchMessages:input_type -> gateway.v1.SearchMessagesRequest
|
||||
7, // 46: gateway.v1.ChatService.Snapshot:output_type -> gateway.v1.SnapshotResponse
|
||||
9, // 47: gateway.v1.ChatService.GetSession:output_type -> gateway.v1.GetSessionResponse
|
||||
11, // 48: gateway.v1.ChatService.RecentMessages:output_type -> gateway.v1.RecentMessagesResponse
|
||||
13, // 49: gateway.v1.ChatService.RecentTurns:output_type -> gateway.v1.RecentTurnsResponse
|
||||
15, // 50: gateway.v1.ChatService.Route:output_type -> gateway.v1.RouteResponse
|
||||
17, // 51: gateway.v1.ChatService.Stream:output_type -> gateway.v1.StreamResponse
|
||||
19, // 52: gateway.v1.ChatService.Cancel:output_type -> gateway.v1.CancelResponse
|
||||
21, // 53: gateway.v1.ChatService.SetPersona:output_type -> gateway.v1.SetPersonaResponse
|
||||
23, // 54: gateway.v1.ChatService.ApplyTaskAction:output_type -> gateway.v1.ApplyTaskActionResponse
|
||||
25, // 55: gateway.v1.ChatService.ApplyOperatorTaskAction:output_type -> gateway.v1.ApplyOperatorTaskActionResponse
|
||||
26, // 56: gateway.v1.ChatService.SaveSession:output_type -> gateway.v1.SaveSessionResponse
|
||||
29, // 57: gateway.v1.ChatService.GetSessionsByChannel:output_type -> gateway.v1.GetSessionsByChannelResponse
|
||||
31, // 58: gateway.v1.ChatService.DeleteSession:output_type -> gateway.v1.DeleteSessionResponse
|
||||
32, // 59: gateway.v1.ChatService.TouchSession:output_type -> gateway.v1.TouchSessionResponse
|
||||
30, // 60: gateway.v1.ChatService.ListSessions:output_type -> gateway.v1.ListSessionsResponse
|
||||
33, // 61: gateway.v1.ChatService.SaveMessage:output_type -> gateway.v1.SaveMessageResponse
|
||||
41, // 62: gateway.v1.ChatService.DeleteRecentMessages:output_type -> gateway.v1.DeleteRecentMessagesResponse
|
||||
43, // 63: gateway.v1.ChatService.MessageCount:output_type -> gateway.v1.MessageCountResponse
|
||||
34, // 64: gateway.v1.ChatService.SaveMessages:output_type -> gateway.v1.SaveMessagesResponse
|
||||
35, // 65: gateway.v1.ChatService.ReplaceMessages:output_type -> gateway.v1.ReplaceMessagesResponse
|
||||
47, // 66: gateway.v1.ChatService.SearchMessages:output_type -> gateway.v1.SearchMessagesResponse
|
||||
46, // [46:67] is the sub-list for method output_type
|
||||
25, // [25:46] is the sub-list for method input_type
|
||||
25, // [25:25] is the sub-list for extension type_name
|
||||
25, // [25:25] is the sub-list for extension extendee
|
||||
0, // [0:25] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_gateway_v1_chat_proto_init() }
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -22,6 +22,7 @@ const (
|
||||
StateStoreService_InstallPackage_FullMethodName = "/state.v1.StateStoreService/InstallPackage"
|
||||
StateStoreService_GetInstalledPackage_FullMethodName = "/state.v1.StateStoreService/GetInstalledPackage"
|
||||
StateStoreService_ListInstalledPackages_FullMethodName = "/state.v1.StateStoreService/ListInstalledPackages"
|
||||
StateStoreService_AcceptPackageAuthority_FullMethodName = "/state.v1.StateStoreService/AcceptPackageAuthority"
|
||||
StateStoreService_RemoveInstalledPackage_FullMethodName = "/state.v1.StateStoreService/RemoveInstalledPackage"
|
||||
StateStoreService_RegisterTaskGrant_FullMethodName = "/state.v1.StateStoreService/RegisterTaskGrant"
|
||||
StateStoreService_RevokeTaskGrant_FullMethodName = "/state.v1.StateStoreService/RevokeTaskGrant"
|
||||
@@ -131,6 +132,10 @@ type StateStoreServiceClient interface {
|
||||
InstallPackage(ctx context.Context, in *InstallPackageRequest, opts ...grpc.CallOption) (*InstallPackageResponse, error)
|
||||
GetInstalledPackage(ctx context.Context, in *GetInstalledPackageRequest, opts ...grpc.CallOption) (*GetInstalledPackageResponse, error)
|
||||
ListInstalledPackages(ctx context.Context, in *ListInstalledPackagesRequest, opts ...grpc.CallOption) (*ListInstalledPackagesResponse, error)
|
||||
// AcceptPackageAuthority records the operator's accepted authority against
|
||||
// the pinned digest (the approve action; install is the create action).
|
||||
// Administrative until org-scoped principals land.
|
||||
AcceptPackageAuthority(ctx context.Context, in *AcceptPackageAuthorityRequest, opts ...grpc.CallOption) (*AcceptPackageAuthorityResponse, error)
|
||||
RemoveInstalledPackage(ctx context.Context, in *RemoveInstalledPackageRequest, opts ...grpc.CallOption) (*RemoveInstalledPackageResponse, error)
|
||||
// Administrative task credential lifecycle. Worker credentials cannot call these.
|
||||
RegisterTaskGrant(ctx context.Context, in *RegisterTaskGrantRequest, opts ...grpc.CallOption) (*RegisterTaskGrantResponse, error)
|
||||
@@ -335,6 +340,16 @@ func (c *stateStoreServiceClient) ListInstalledPackages(ctx context.Context, in
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) AcceptPackageAuthority(ctx context.Context, in *AcceptPackageAuthorityRequest, opts ...grpc.CallOption) (*AcceptPackageAuthorityResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(AcceptPackageAuthorityResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_AcceptPackageAuthority_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) RemoveInstalledPackage(ctx context.Context, in *RemoveInstalledPackageRequest, opts ...grpc.CallOption) (*RemoveInstalledPackageResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(RemoveInstalledPackageResponse)
|
||||
@@ -1288,6 +1303,10 @@ type StateStoreServiceServer interface {
|
||||
InstallPackage(context.Context, *InstallPackageRequest) (*InstallPackageResponse, error)
|
||||
GetInstalledPackage(context.Context, *GetInstalledPackageRequest) (*GetInstalledPackageResponse, error)
|
||||
ListInstalledPackages(context.Context, *ListInstalledPackagesRequest) (*ListInstalledPackagesResponse, error)
|
||||
// AcceptPackageAuthority records the operator's accepted authority against
|
||||
// the pinned digest (the approve action; install is the create action).
|
||||
// Administrative until org-scoped principals land.
|
||||
AcceptPackageAuthority(context.Context, *AcceptPackageAuthorityRequest) (*AcceptPackageAuthorityResponse, error)
|
||||
RemoveInstalledPackage(context.Context, *RemoveInstalledPackageRequest) (*RemoveInstalledPackageResponse, error)
|
||||
// Administrative task credential lifecycle. Worker credentials cannot call these.
|
||||
RegisterTaskGrant(context.Context, *RegisterTaskGrantRequest) (*RegisterTaskGrantResponse, error)
|
||||
@@ -1471,6 +1490,9 @@ func (UnimplementedStateStoreServiceServer) GetInstalledPackage(context.Context,
|
||||
func (UnimplementedStateStoreServiceServer) ListInstalledPackages(context.Context, *ListInstalledPackagesRequest) (*ListInstalledPackagesResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ListInstalledPackages not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) AcceptPackageAuthority(context.Context, *AcceptPackageAuthorityRequest) (*AcceptPackageAuthorityResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method AcceptPackageAuthority not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) RemoveInstalledPackage(context.Context, *RemoveInstalledPackageRequest) (*RemoveInstalledPackageResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method RemoveInstalledPackage not implemented")
|
||||
}
|
||||
@@ -1819,6 +1841,24 @@ func _StateStoreService_ListInstalledPackages_Handler(srv interface{}, ctx conte
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_AcceptPackageAuthority_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(AcceptPackageAuthorityRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).AcceptPackageAuthority(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_AcceptPackageAuthority_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).AcceptPackageAuthority(ctx, req.(*AcceptPackageAuthorityRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_RemoveInstalledPackage_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(RemoveInstalledPackageRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -3455,6 +3495,10 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "ListInstalledPackages",
|
||||
Handler: _StateStoreService_ListInstalledPackages_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "AcceptPackageAuthority",
|
||||
Handler: _StateStoreService_AcceptPackageAuthority_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "RemoveInstalledPackage",
|
||||
Handler: _StateStoreService_RemoveInstalledPackage_Handler,
|
||||
|
||||
@@ -29,6 +29,15 @@ func (d *Daemon) activeWorkflows(ctx context.Context) (workflow.WorkflowDefiniti
|
||||
return collection, err
|
||||
}
|
||||
|
||||
// workflowEnablement returns which workflows each org has disabled; with no
|
||||
// source wired every workflow is enabled.
|
||||
func (d *Daemon) workflowEnablement(ctx context.Context) (workflowtask.WorkflowEnablement, error) {
|
||||
if d.WorkflowEnablement == nil {
|
||||
return workflowtask.WorkflowEnablement{}, nil
|
||||
}
|
||||
return d.WorkflowEnablement.WorkflowEnablement(ctx)
|
||||
}
|
||||
|
||||
// resolveBindingTarget checks a matched binding against the workflow it
|
||||
// targets and resolves the task's repository and inputs. A non-empty reason
|
||||
// means the binding does not dispatch and the reason is recorded on it; ok
|
||||
|
||||
+147
-13
@@ -250,6 +250,12 @@ type Daemon struct {
|
||||
WorkflowDefinitions interface {
|
||||
WorkflowDefinitions(context.Context) (workflow.WorkflowDefinitionCollection, int64, error)
|
||||
}
|
||||
// WorkflowEnablement supplies which workflows each org has disabled. A
|
||||
// binding targeting a workflow its org disabled does not dispatch. Nil
|
||||
// means every workflow is enabled.
|
||||
WorkflowEnablement interface {
|
||||
WorkflowEnablement(context.Context) (workflowtask.WorkflowEnablement, error)
|
||||
}
|
||||
|
||||
// ToolRegistry is the central tool registry, wired by the composition
|
||||
// root. MCP-discovered tools and built-in tools are registered here
|
||||
@@ -667,16 +673,27 @@ func (d *Daemon) dispatchBindings(ctx context.Context) {
|
||||
d.Log.Warn("binding dispatch: workflow definitions unavailable", "error", err)
|
||||
return
|
||||
}
|
||||
enablement, err := d.workflowEnablement(ctx)
|
||||
if err != nil {
|
||||
d.Log.Warn("binding dispatch: workflow enablement unavailable", "error", err)
|
||||
return
|
||||
}
|
||||
for _, c := range captures {
|
||||
armed, err := d.BindingDispatcher.ArmedBindingsForSource(ctx, c.Source)
|
||||
if err != nil {
|
||||
d.Log.Warn("armed bindings lookup", "source", c.Source, "error", err)
|
||||
continue
|
||||
}
|
||||
for _, b := range armed {
|
||||
if !b.Matcher.Matches(c.Source, c.Dispatchable()) {
|
||||
continue
|
||||
}
|
||||
d.dispatchCapture(ctx, c, workflows, enablement)
|
||||
}
|
||||
}
|
||||
|
||||
// dispatchCapture offers one capture to every armed binding on its source. A
|
||||
// disabled workflow's binding is skipped like an unarmed one, so the capture
|
||||
// waits rather than recording a failure every cycle.
|
||||
func (d *Daemon) dispatchCapture(ctx context.Context, c storecontract.CapturedEvent, workflows workflow.WorkflowDefinitionCollection, enablement workflowtask.WorkflowEnablement) {
|
||||
armed, err := d.BindingDispatcher.ArmedBindingsForSource(ctx, c.Source)
|
||||
if err != nil {
|
||||
d.Log.Warn("armed bindings lookup", "source", c.Source, "error", err)
|
||||
return
|
||||
}
|
||||
for _, b := range armed {
|
||||
if b.Matcher.Matches(c.Source, c.Dispatchable()) && enablement.Enabled(b.OrgID, b.Workflow) {
|
||||
d.dispatchOneBinding(ctx, b, c, workflows)
|
||||
}
|
||||
}
|
||||
@@ -1402,6 +1419,16 @@ func (d *Daemon) prepareWorkspace(ctx context.Context, task *workflow.Task, tree
|
||||
}
|
||||
return dir, true
|
||||
}
|
||||
// A task that continues an already-open PR branch -- the remediate
|
||||
// workflow -- resumes that branch's remote tip instead of resetting onto
|
||||
// base. Preparing one the ordinary way discarded the commits the implement
|
||||
// run had already pushed, so the agent remediated a PR from a tree that no
|
||||
// longer contained it. This runs before Acquire, because the daemon holds
|
||||
// the forge credential that fetches the branch and the container must find
|
||||
// the PR's work already in place.
|
||||
if continuesOpenPRBranch(task) {
|
||||
return d.resumePRBranchWorkspace(ctx, task, trees)
|
||||
}
|
||||
// Every task gets an independent full clone. The former
|
||||
// PreparePersistent path shared objects with a per-repo bare cache;
|
||||
// go-git has no --dissociate, so a shared cache would stay a live
|
||||
@@ -1420,6 +1447,41 @@ func (d *Daemon) prepareWorkspace(ctx context.Context, task *workflow.Task, tree
|
||||
return dir, true
|
||||
}
|
||||
|
||||
// continuesOpenPRBranch reports whether the task must continue a branch archie
|
||||
// already pushed rather than start from base. Only the remediate workflow does:
|
||||
// it addresses review feedback on an open archie-owned PR and reuses that PR's
|
||||
// branch (docs/prds/pr-review-remediation.md decision 4), while every other
|
||||
// workflow starts fresh work. The workflow is read from the task row, where the
|
||||
// reaction consumer wrote it before queueing the run -- a decision about this
|
||||
// task that no later routing may overturn.
|
||||
func continuesOpenPRBranch(task *workflow.Task) bool {
|
||||
return task.Workflow == "remediate"
|
||||
}
|
||||
|
||||
// resumePRBranchWorkspace prepares a task's worktree on the branch its row
|
||||
// names, never on a branch recomputed from the title or labels: the PR was
|
||||
// opened from the persisted branch, and a retitled issue or relabelled task
|
||||
// would otherwise name a branch that does not exist. It fails closed -- there
|
||||
// is deliberately no fallback to preparing base, because that fallback is the
|
||||
// defect this route removes.
|
||||
func (d *Daemon) resumePRBranchWorkspace(ctx context.Context, task *workflow.Task, trees *worktree.Manager) (string, bool) {
|
||||
if task.Branch == "" {
|
||||
// A remediation task is queued against the branch its implement run
|
||||
// pushed, so an empty branch is a dispatch bug upstream and no retry
|
||||
// can fix it.
|
||||
d.Log.Error("remediate task has no persisted branch", "task", task.ID)
|
||||
d.parkRunningTask(ctx, task.ID, "worktree resume failed: remediate task has no branch to resume", taskstate.ParkNeedsHuman)
|
||||
return "", false
|
||||
}
|
||||
dir := trees.Dir(task.Owner, task.Repo, task.IssueNumber)
|
||||
if err := trees.Resume(ctx, dir, task.Branch); err != nil {
|
||||
d.Log.Error("worktree resume failed", "task", task.ID, "branch", task.Branch, "err", err)
|
||||
d.parkRunningTask(ctx, task.ID, "worktree resume failed: "+err.Error(), taskstate.ParkTransient)
|
||||
return "", false
|
||||
}
|
||||
return dir, true
|
||||
}
|
||||
|
||||
// cleanupTerminalTaskWorktree removes a task's worktree once its forge side is
|
||||
// settled, unless the worktree still holds work no commit captured.
|
||||
//
|
||||
@@ -1522,11 +1584,36 @@ func (d *Daemon) acquireTaskContainer(
|
||||
d.parkRunningTask(ctx, task.ID, reason+": "+err.Error(), taskstate.ParkTransient)
|
||||
}
|
||||
|
||||
// A watched-repositories binding or the operator chat trigger assigns
|
||||
// the pull request generically through Task.Inputs (its declared
|
||||
// pr_number input); archie's own PRs sets PRNumber directly and never
|
||||
// goes through either path. Resolving here, before the brief is
|
||||
// written, means task.json and the prefetch below always agree with
|
||||
// what every later reader (stagePRIntake, output posting) sees.
|
||||
if task.Workflow == "pr-review" {
|
||||
task.PRNumber = task.EffectivePRNumber()
|
||||
}
|
||||
|
||||
if err := writeTaskBrief(workDir, task); err != nil {
|
||||
park("task.json write failed", err)
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
// pr-review needs an external pull request's metadata, diff and head
|
||||
// snapshot inside the container, but the container must never hold a
|
||||
// forge credential (docs/development/agent.md, "Giving the agent
|
||||
// something new"). The daemon fetches it here, before the container
|
||||
// exists, using its own credentialed forge client, and writes the result
|
||||
// into workDir -- the same host directory Docker bind-mounts at
|
||||
// storage.WorktreeMountDir -- so the sandboxed pipeline can read it back
|
||||
// with prsource.MountSource and no network call of its own.
|
||||
if task.Workflow == "pr-review" {
|
||||
if err := prefetchPRReview(ctx, d.forgeFor(task), task.Owner, task.Repo, task.PRNumber, workDir); err != nil {
|
||||
park("pr-review prefetch failed", err)
|
||||
return nil, nil, false
|
||||
}
|
||||
}
|
||||
|
||||
// Guard: Storage may be nil if the daemon was wired incorrectly. In
|
||||
// normal operation, Storage is always set when ContainerPool is set.
|
||||
if d.Storage == nil {
|
||||
@@ -1759,6 +1846,12 @@ func (d *Daemon) pinTaskProfile(ctx context.Context, task *workflow.Task) (confi
|
||||
return config.AgentProfile{}, false
|
||||
}
|
||||
iface, err := workflowtask.ParseWorkflowInterface(task.WorkflowDefinitionYAML)
|
||||
if err == nil {
|
||||
// Every producer meets the declared interface here, including the
|
||||
// ones that cannot read definitions when they enqueue (chat and
|
||||
// dashboard spawns go through the Gateway, which never does).
|
||||
err = iface.CheckInputs(task.Inputs)
|
||||
}
|
||||
if err == nil {
|
||||
var profile config.AgentProfile
|
||||
if profile, err = d.configFor(task).Containers.Profile(iface.Profile); err == nil {
|
||||
@@ -1811,11 +1904,33 @@ func (d *Daemon) publicationGrant(ctx context.Context, task *workflow.Task) (str
|
||||
return grant, revoke, true
|
||||
}
|
||||
|
||||
// pinWorkflowDefinition puts the task's workflow definition pin in the state
|
||||
// the worker's compile requires before it runs a dispatch: a stored definition
|
||||
// that names the workflow the task row names
|
||||
// (agentworker.CompilePinnedWorkflow).
|
||||
//
|
||||
// A pin that is present, hash-valid and id-consistent is reused unchanged, so
|
||||
// the definition an operator had active when the task was pinned survives every
|
||||
// later dispatch even after the active definition moved on. Anything else -- no
|
||||
// pin, or a pin naming a workflow this task no longer runs -- is resolved again
|
||||
// from the active collection for the workflow the task names.
|
||||
//
|
||||
// The re-pin is what makes the waiting_human -> approved requeue dispatchable:
|
||||
// RequeueTask writes the new workflow column and leaves the previous run's
|
||||
// definition pinned, so the requeued row carries the two half-state values the
|
||||
// worker refuses to run. Resolving here, at the write, is where the row
|
||||
// becomes valid; a consumer that repaired it would only be tolerating a state
|
||||
// this producer is responsible for.
|
||||
//
|
||||
// An already-pinned definition is deliberately NOT refreshed to the operator's
|
||||
// current active one: a run's definition is pinned once, so a mid-flight
|
||||
// change to a definition never alters work already in progress.
|
||||
func (d *Daemon) pinWorkflowDefinition(ctx context.Context, task *workflow.Task) error {
|
||||
if task.WorkflowDefinitionYAML != "" {
|
||||
if workflow.DigestDefinition(task.WorkflowDefinitionYAML) != task.WorkflowDefinitionDigest {
|
||||
return fmt.Errorf("stored workflow definition digest mismatch")
|
||||
}
|
||||
pinned, ok, err := pinnedDefinitionID(task)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok && pinned == task.Workflow {
|
||||
return nil
|
||||
}
|
||||
d.runActionPlaybooks(ctx, task)
|
||||
@@ -1829,6 +1944,25 @@ func (d *Daemon) pinWorkflowDefinition(ctx context.Context, task *workflow.Task)
|
||||
return d.pinWorkflowFromCollection(ctx, task, collection, version)
|
||||
}
|
||||
|
||||
// pinnedDefinitionID reports the workflow a task's stored definition pin names,
|
||||
// with ok false for a task carrying no pin. It enforces what this package owns
|
||||
// about a stored pin: the YAML hashes to the digest recorded beside it, and it
|
||||
// declares an id at all. A pin failing either is a row an operator has to
|
||||
// resolve, not one to silently overwrite.
|
||||
func pinnedDefinitionID(task *workflow.Task) (string, bool, error) {
|
||||
if task.WorkflowDefinitionYAML == "" {
|
||||
return "", false, nil
|
||||
}
|
||||
if workflow.DigestDefinition(task.WorkflowDefinitionYAML) != task.WorkflowDefinitionDigest {
|
||||
return "", false, fmt.Errorf("stored workflow definition digest mismatch")
|
||||
}
|
||||
id, err := workflow.DefinitionID(task.WorkflowDefinitionYAML)
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("stored workflow definition: %w", err)
|
||||
}
|
||||
return id, true, nil
|
||||
}
|
||||
|
||||
// runActionPlaybooks runs the action playbooks matching a task that is about
|
||||
// to be pinned, which happens once per task (docs/prds/action-playbook-run.md).
|
||||
// A run never affects routing and its failure never fails the task. A task
|
||||
|
||||
@@ -1911,7 +1911,7 @@ func TestReconcilePRsSkipsChatTasks(t *testing.T) {
|
||||
d, s, fg := testDaemon(t, 3, 0)
|
||||
ctx := context.Background()
|
||||
|
||||
task, err := s.EnqueueChatTask(ctx, "acme", "widget", "chat task", "", "", "")
|
||||
task, err := s.EnqueueChatTask(ctx, "acme", "widget", "chat task", "", "", "", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -2098,7 +2098,7 @@ func TestDispatchCapturesTheAttemptsEffectiveConfig(t *testing.T) {
|
||||
// repositories, identities or lock state.
|
||||
wantKeys := []string{
|
||||
"bot_email", "bot_user", "budgets", "diff_cap_lines", "dispatch",
|
||||
"forge", "model_limits", "models", "notify", "tool_policy",
|
||||
"forge", "model_limits", "models", "notify", "review", "tool_policy",
|
||||
}
|
||||
gotKeys := make([]string, 0, len(doc))
|
||||
for key := range doc {
|
||||
@@ -2412,6 +2412,52 @@ func TestPinTaskProfileRefusesCapturesTheHarnessCannotServe(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinTaskProfileRefusesInputsTheWorkflowDoesNotAccept holds every
|
||||
// producer to the workflow's declared interface at the one point each task
|
||||
// meets its definition. Bindings check inputs before they enqueue; a chat or
|
||||
// dashboard spawn cannot, because the Gateway never reads workflow
|
||||
// definitions, so without this a spawn missing a required input would run
|
||||
// and fail deep inside the workflow instead of parking with the reason.
|
||||
func TestPinTaskProfileRefusesInputsTheWorkflowDoesNotAccept(t *testing.T) {
|
||||
d, s, _ := daemonWithNATS(t)
|
||||
d.WorkflowDefinitions = &workflowDefinitionsStub{collection: workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{
|
||||
{ID: "investigate", YAML: investigateYAML},
|
||||
}}, version: 1}
|
||||
ctx := context.Background()
|
||||
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
inputs map[string]any
|
||||
ok bool
|
||||
reason string
|
||||
}{
|
||||
{"declared inputs run", map[string]any{"src_ip": "10.0.0.1"}, true, ""},
|
||||
{"missing required input parks", nil, false, `input "src_ip" is required`},
|
||||
{"undeclared input parks", map[string]any{"src_ip": "10.0.0.1", "extra": "x"}, false, `input "extra" is not declared`},
|
||||
{"mistyped input parks", map[string]any{"src_ip": 7}, false, `input "src_ip" is number, want string`},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if _, err := s.EnqueueChatTask(ctx, "acme", "widget", tt.name, "", "investigate", "", tt.inputs); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim: (%v, %v)", task, err)
|
||||
}
|
||||
if _, ok := d.pinTaskProfile(ctx, task); ok != tt.ok {
|
||||
t.Fatalf("pinTaskProfile ok = %v, want %v", ok, tt.ok)
|
||||
}
|
||||
if tt.ok {
|
||||
return
|
||||
}
|
||||
got, err := s.TaskByID(ctx, task.ID)
|
||||
if err != nil || got.Status != workflow.StatusParked || !strings.Contains(got.ParkReason, tt.reason) {
|
||||
t.Fatalf("task = %+v, %v; want parked naming %q", got, err, tt.reason)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestWorkflowCallGivesACalleeItsOwnProfile is the harness PRD's "a stage may
|
||||
// name a different profile" (docs/prds/external-agent-harness.md, Selection):
|
||||
// there is no mid-container runner switch, and none is built here. A stage
|
||||
|
||||
@@ -15,6 +15,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/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
@@ -422,3 +423,36 @@ func assertDispatchRecorded(t *testing.T, s *dispatchStores, bindingID string) {
|
||||
t.Fatalf("binding_dispatches row missing: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type staticEnablement struct {
|
||||
value workflowtask.WorkflowEnablement
|
||||
}
|
||||
|
||||
func (e staticEnablement) WorkflowEnablement(context.Context) (workflowtask.WorkflowEnablement, error) {
|
||||
return e.value, nil
|
||||
}
|
||||
|
||||
// A binding whose org disabled its workflow does not dispatch, and the capture
|
||||
// waits: re-enabling the workflow dispatches it on the next cycle.
|
||||
func TestDispatchBindingsSkipsWorkflowItsOrgDisabled(t *testing.T) {
|
||||
s := openDispatchTestStore(t)
|
||||
mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString, Required: true})
|
||||
bindingID, _ := seedArmedBinding(t, s, "sentry", mappingID)
|
||||
seedCapture(t, s, "sentry", true, `{"title":"hello"}`)
|
||||
stored, err := s.EdaStore.GetBinding(t.Context(), bindingID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBinding: %v", err)
|
||||
}
|
||||
|
||||
d := newDispatchDaemon(t, s)
|
||||
var enablement workflowtask.WorkflowEnablement
|
||||
d.WorkflowEnablement = staticEnablement{enablement.SetEnabled(stored.OrgID, stored.Workflow, false)}
|
||||
d.dispatchBindings(t.Context())
|
||||
if tasks, _ := s.Tasks(t.Context(), 10); len(tasks) != 0 {
|
||||
t.Fatalf("Tasks len = %d, want 0 while the workflow is disabled", len(tasks))
|
||||
}
|
||||
|
||||
d.WorkflowEnablement = staticEnablement{enablement.SetEnabled(stored.OrgID, stored.Workflow, true)}
|
||||
d.dispatchBindings(t.Context())
|
||||
assertDispatchRecorded(t, s, bindingID)
|
||||
}
|
||||
Loaded 100 of 329 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user