diff --git a/docs/data/generated/dev-docs.json b/docs/data/generated/dev-docs.json index b738a2f6e..3c02f3448 100644 --- a/docs/data/generated/dev-docs.json +++ b/docs/data/generated/dev-docs.json @@ -484,7 +484,7 @@ "url": "/dev/prds/state-store-contract/", "title": "State Store — contract boundary \u0026 transport (ratification)", "section": "PRDs", - "body": "# State Store — contract boundary \u0026 transport (ratification)\n\n**Status:** Approved\n**Revision:** 2e\n**Date:** 2026-09-06\n\nThis is the pre-implementation design document that Phase 2 subtasks `.4.2` (generalise\n`storerpc` as the State Store gRPC contract) and `.4.3` (stand up `archie-state-store`)\nimplement against.\n**Beads milestone:** archie-core-8cda.4.1\n**Parent:** `docs/prds/service-decomposition.md` (open-question Q4 **RESOLVED**)\n\nThis document fixes the **contract boundary** and **transport** for the State Store service.\nIt does not redesign Archie's domain model, does not invent a second store, and does **not**\nsplit `archie.db`. It records method ownership, DTO/wire representation, error semantics,\nlimits, mode/config shape, local-adapter compatibility, and cutover/deletion rules so that\n`.4.2` and `.4.3` have exactly one authoritative surface to build against.\n\n\u003e **Storage superseded.** The store behind this contract is PostgreSQL:\n\u003e `internal/infrastructure/postgres` implements the producer-owned interfaces in\n\u003e `internal/domain/storecontract` and `workflow.Store`, over the database\n\u003e `database_url` names. `internal/store`, the SQLite file and the local adapter\n\u003e are gone; where this document says `archie.db`, `*store.Store` or\n\u003e `internal/store`, read the State Store's PostgreSQL database and\n\u003e `internal/infrastructure/postgres`. The contract, ownership split, error\n\u003e semantics and cutover rules stand.\n\n\u003e **Current state — read before `.4.2` starts.** The §12 step 2 relocation (`archie-core-8cda.\n4.8`) has landed: `Task`/`Status*`/`Source*` and the 3-method `workflow.Store` now live in\n\u003e `internal/domain/workflow`, the six production workflow files import no `internal/store`\n\u003e symbol, and `storerpc`/the NATS transport assert against `workflow.Store` instead of\n\u003e `store.WorkflowStore`. The broader Phase 2 acceptance criterion (State Store as its own\n\u003e service behind gRPC) is still open — that is what `.4.2`/`.4.3` build next.\n\n\u003e **Relationship to migration-decisions §4 — not replaced.** `docs/architecture/\nmigration-decisions.md` §4 (`store.Task → WorkflowExecution`, `mutable Stage →\nStepExecution history`, `RetryCount/Attempt → Attempt records`, versioned Workflow defs)\n\u003e **remains the authoritative, open document for the long-term Workflow migration.** This PRD\n\u003e does **not** replace it. It only pulls the minimal `Task`/`Status`/`Source` type + interface\n\u003e relocation forward as a Phase 2 prerequisite (because the acceptance criterion requires it);\n\u003e the rest of §4 stays its own migration and stays open.\n\n---\n\n## 1. Decision (the invariant everything follows)\n\nArchie is composed such that a single **`archie-state-store`** service owns the one existing\nSQLite file (`archie.db`) and exposes it over **gRPC behind narrow typed contracts**. There is\nexactly one store, one file, one service. No database-per-service, no distributed\ntransactions, no second store abstraction.\n\nTwo adapter families satisfy the contract interfaces:\n\n- **Local adapter** — `*store.Store` (the in-process SQLite implementation).\n- **Remote adapter** — `*staterpc.Client` (wraps the generated gRPC client).\n\nEach adapter carries an explicit compile-time assertion against the contract interfaces it\nserves. Composition picks local vs. remote by the presence of `[services.state].target`\n(empty = local; set = dial the gRPC service). Default is **local** (the State Store is not yet\nextracted), which is the PRD §3 posture; it differs from the gateway's remote-default only\nbecause the gateway is already a separate deployment and the State Store is not.\n\n\u003e **Contract-ownership fork, decided (rev. 2c — resolves the domain contradiction).**\n\u003e Ownership splits by the consumer's _layer_, per the dependency contract's rule #2\n\u003e (\"a domain defines the smallest interfaces required to perform its work\") and rule #7\n\u003e (\"database rows … MUST NOT leak into domain models\"):\n\u003e\n\u003e - The **workflow domain** (`internal/domain/workflow`) is the only domain-layer consumer of\n\u003e store state. It defines its own **consumer-owned** narrow `Store` interface\n\u003e (Update/Transition/InsertEvent) and its own **domain-owned** `Task` type plus\n\u003e `Status`/`Source` vocabulary. It imports **zero** `internal/store` symbols — satisfying the\n\u003e Phase 2 acceptance criterion. This is the minimal bound of migration-decisions §4\n\u003e (`store.Task → WorkflowExecution`), pulled forward **because** the acceptance criterion\n\u003e requires it.\n\u003e - The **daemon / webui / intake** store surfaces (`TaskStore`, `CaptureStore`,\n\u003e `MappingStore`, `BindingStore`, `BindingDispatcher`, `BindingTaskCreator`) stay\n\u003e **producer-owned** in `internal/store`, because those consumers are application and\n\u003e infrastructure layers, not domains — rule #2 does not apply to them.\n\nSo the State Store contract is **not** uniformly producer-owned: the domain-facing workflow\ncontract is consumer-owned (in the domain), while the daemon/webui store surfaces remain in\n`internal/store`. `internal/store` imports `internal/domain/workflow` for the `Task`/`Status`/\n`Source` types it persists (persistence → domain, the correct direction), and its `Store`\nimplementation satisfies `workflow.Store`. This is the single decision that makes the whole\nPhase 2 acceptance criterion and the architecture's rules simultaneously satisfiable.\n\n\u003e **`internal/store` is a TRANSITIONAL compatibility location (rev. 2c).** The repository's target\n\u003e architecture (`docs/architecture/dependencies-and-contracts.md`, `organisation.md`) places\n\u003e persistence implementations under `internal/infrastructure/\u003ccapability\u003e`. `internal/store`\n\u003e holding the task/capture/mapping/binding implementation and ALSO being the home of the\n\u003e producer-owned daemon/webui interfaces is acceptable **only as a transitional location**. The\n\u003e long-term home for the store implementation is `internal/infrastructure/store`; the\n\u003e producer-owned interfaces may move to the same infrastructure package (or an approved\n\u003e contract location) when the store implementation relocates. Agents must not treat\n\u003e `internal/store` as the final infrastructure boundary.\n\u003e\n\u003e **REV. 2d (archie-core-8cda.5.6): the producer-owned interfaces HAVE moved to an approved\n\u003e contract location** — `internal/domain/storecontract` (package `storecontract`), ahead of the\n\u003e store implementation's own relocation. The UI Service deletion gate required the archie-ui\n\u003e process to hold the contracts without linking `internal/store`'s SQL implementation, and\n\u003e `internal/contracts/` itself is ruled out: that tree is the `buf generate` output and\n\u003e `tools/proto.sh check` deletes hand-written files there. `internal/store` keeps type aliases\n\u003e (`type TaskStore = storecontract.TaskStore`, the sentinel `var`s, the value types) so\n\u003e daemon-side callers are unaffected; the sentinel message strings are unchanged and remain\n\u003e the wire contract (§4).\n\n---\n\n## 2. Contract boundary\n\n**Ownership split** (see the fork in §1): the **workflow-domain consumer contract** is\n`workflow.Store` (consumer-owned, in `internal/domain/workflow`); the **daemon/webui/intake\nstore surfaces** are the producer-owned interfaces in `internal/store/interface.go`.\n`store.WorkflowStore` is **superseded** — it is replaced by the domain-owned `workflow.Store`,\nand `internal/store`'s `Store` implementation satisfies `workflow.Store` directly. `TaskStore`\nremains the only composite; every other interface is flat. Narrow slices are split along\nconsumer-capability lines so no consumer acquires a surface it does not need\n(`interfacebloat` cap = 8).\n\n| Interface (owner) | Embeds | Methods | Local impl | Remote impl |\n| ---------------------------------- | --------------------------------------------------------------------------- | ---------- | ---------- | ------------------ |\n| `TaskStore` (store) | `TaskLifecycle`, `TaskEvents`, `TaskQueries`, `TaskArchiver`, `TaskRetryer` | 24 (union) | `*Store` | `*staterpc.Client` |\n| `TaskLifecycle` (store) | — | 8 | `*Store` | `*staterpc.Client` |\n| `TaskEvents` (store) | — | 7 | `*Store` | `*staterpc.Client` |\n| `TaskQueries` (store) | — | 7 | `*Store` | `*staterpc.Client` |\n| `TaskArchiver` (store) | — | 1 | `*Store` | `*staterpc.Client` |\n| `TaskRetryer` (store) | — | 1 | `*Store` | `*staterpc.Client` |\n| `workflow.Store` (workflow domain) | — | 3 | `*Store` | `*staterpc.Client` |\n| `CaptureStore` (store) | — | 2 | `*Store` | `*staterpc.Client` |\n| `MappingStore` (store) | — | 5 | `*Store` | `*staterpc.Client` |\n| `BindingStore` (store) | — | 6 | `*Store` | `*staterpc.Client` |\n| `BindingDispatcher` (store) | — | 3 | `*Store` | `*staterpc.Client` |\n| `BindingTaskCreator` (store) | — | 1 | `*Store` | `*staterpc.Client` |\n| `PlaybookDispatcher` (store) | — | 2 | `*Store` | `*staterpc.Client` |\n\n**Key property of the remote client:** `*staterpc.Client` is a _single_ adapter that wraps one\n`StateStoreClient` and is asserted against **whichever narrow Go interfaces its caller needs**\n(exactly as `gatewayrpc.Client` asserts both `gateway.ChatContract` and\n`gateway.SessionStore`). The Go contracts stay narrow (≤8, the `interfacebloat` cap); the wire\nis one service. `workflow.Store` introduces **no new RPCs** — it is a narrow consumer face over\nthe same `Update`/`Transition`/`InsertEvent` RPCs.\n\n---\n\n## 3. Method ownership\n\n`*Store` remains the single implementation of the daemon/webui store surfaces and of\n`workflow.Store`. Ownership below is about which **process** is the primary consumer of each\nmethod and therefore which methods are genuinely cross-process on the wire vs.\ndaemon-internal.\n\nProcess legend: **DAEMON** = `archied` (incl. in-process webui + gateway runtime +\n`storerpc.Server`); **AGENT** = `archie-agent` worker (no DB connection); **GATEWAY** = store\naccess through daemon-side narrow adapter interfaces.\n\n| Contract | Primary consumers (process) | Remote on the wire? |\n| ------------------------ | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |\n| `TaskLifecycle` (8) | DAEMON (dispatch, claim, action) + **AGENT** (`Transition`, `Update` via storerpc) | `Transition`/`Update` = **YES** (agent); rest DAEMON |\n| `TaskArchiver` (1) | DAEMON (`taskactions` archive) | not yet |\n| `TaskRetryer` (1) | DAEMON (`taskactions` retry) | not yet |\n| `TaskQueries` (7) | DAEMON + GATEWAY (status/list adapters) | not yet (`OpenPRs`/`Tasks`/`StatusCounts` cross to gateway adapters in-process) |\n| `TaskEvents` (7) | DAEMON + **AGENT** (`InsertEvent` via storerpc) | `InsertEvent` = **YES** (agent); rest DAEMON |\n| `workflow.Store` (3) | **AGENT** only | **YES** (the sole genuinely remote consumer) |\n| `CaptureStore` (2) | DAEMON (webhook intake + mapping editor) | not yet |\n| `MappingStore` (5) | DAEMON (dashboard editor + dispatch loop) | not yet |\n| `BindingStore` (6) | DAEMON (dashboard editor + dispatch loop) | not yet |\n| `BindingDispatcher` (3) | DAEMON (dispatch loop) | not yet |\n| `BindingTaskCreator` (1) | DAEMON (dispatch loop) | not yet |\n| `PlaybookDispatcher` (2) | DAEMON (EDA playbook dispatch loop) | **YES** (side-effecting-action idempotency ledger over gRPC) |\n\n**Consequence for migration order:** the **agent's `workflow.Store` is already cross-process\nalready** (via the NATS `storerpc` surrogate), so it is the first contract to move to gRPC. The\ndaemon-internal surfaces (`Capture`/`Mapping`/`Binding`) stay in-process until the daemon\nitself points at `archie-state-store`. `TaskStore` (the large composite) moves last.\n\n**Two orphan methods** — `TaskQueries.ClearTerminalTasks` and\n`TaskQueries.IncrementRetryCount` have **no production consumer** (only `*Store` tests). They\nremain part of the Go `TaskQueries`/`TaskStore` surface, and therefore part of the wire\ncontract, but are flagged for deletion: they must **not** gain dedicated consumers or wire\nmethods in this work. Do not add the rest of the codebase to them.\n\n---\n\n## 4. Domain-facing types \u0026 consumer-owned contract — resolves the contradiction\n\nThe Phase 2 acceptance criterion (\"`internal/domain/workflow` … no longer import\n`internal/store` directly — they call the State Store contract\") **cannot be met while**\n`store.Task`, `store.Status*`, `store.Source*`, and `store.WorkflowStore` live in\n`internal/store`. This section fixes where they move.\n\n**The relocation (a prerequisite that must land before or with `.4.2`):**\n\n| Current symbol (`internal/store`) | Moves to | Notes |\n| ------------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |\n| `Task` type | `internal/domain/workflow.Task` | The task-execution record the workflow domain operates on. `internal/store` persists this type (persistence → domain). |\n| `Status` + `Status*` constants | `internal/domain/workflow` | e.g. `StatusClosedWontDo`, `StatusMerged`, `StatusPROpen`, `StatusWaitingHuman`, `StatusRunning` — task-lifecycle vocabulary. |\n| `Source` + `Source*` constants | `internal/domain/workflow` | e.g. `SourceChat` — provenance vocabulary, follows `Task`. |\n| `WorkflowStore` interface (3 methods) | `internal/domain/workflow.Store` | **Consumer-owned** (dependency rule #2). Supersedes `store.WorkflowStore`. |\n\n**Resulting dependency direction (correct per the architecture):**\n\n- `internal/domain/workflow` imports **no** `internal/store` symbols → the acceptance\n criterion is satisfied. It consumes `store.Task`'s replacement as `workflow.Task`, uses\n `workflow.Status*`/`workflow.Source*`, and depends on its own `workflow.Store` interface.\n- `internal/store` imports `internal/domain/workflow` for the `Task`/`Status`/`Source` types it\n reads and writes (infrastructure → domain). **NOTE: `internal/store` is a transitional\n compatibility location only** — its long-term home is `internal/infrastructure/store` (see\n the callout in §1). Do not treat `internal/store` as the final infrastructure boundary.\n- Every store test that constructs `store.Task{…}` is updated to the relocated type as part of\n this prerequisite. This is a mechanical rename across ~6 workflow production files\n (`workflow.go`, `steps.go`, `triage.go`, `review.go`, `feasibility.go`, `implement.go`) and\n their tests plus the store tests. `TestRecordDispatchViaExplicitTx` is removed rather than\n updated — its non-nil `*sql.Tx` path has no production consumer (see §5's `RecordDispatch`\n blocker).\n\n**What this does NOT do:** it does not implement the full §4 Workflow migration\n(`mutable Stage → StepExecution history`, `RetryCount/Attempt → Attempt records`,\n`workflow.Registry → versioned Workflow definitions`, etc.). It lands only the minimal\ntask-type + `Status`/`Source` + consumer-owned-interface relocation that the Phase 2\ndomain-decoupling criterion requires. The residue of §4 remains its own migration.\n\n**Forward-compatibility:** because the wire DTOs are derived from the domain `Task`/`Status`\n(§5), when the full §4 migration later renames `workflow.Task` (or refines it into\n`WorkflowExecution`), only `values.go` and the proto field mapping change — the RPC surface and\nconsumer interfaces are unaffected. The wire contract is deliberately type-agnostic at this\nlevel.\n\n---\n\n## 5. DTO / wire representation\n\n### Proto layout\n\n- **Service:** `proto/state/v1/state.proto`, `package state.v1`, **one** `StateStore` service\n (mirrors the gateway's single `ChatService`; proto bypasses the Go `interfacebloat` cap, as\n `ChatContract` does via `//nolint:interfacebloat`).\n- **Codegen:** the existing buf v2 pipeline. `proto/buf.yaml` (module, lint STANDARD, breaking\n FILE against `main`), `proto/buf.gen.yaml` **managed mode** with\n `go_package_prefix → github.com/samcharles93/archie-core/internal/contracts`, plugins\n `protoc-gen-go` + `protoc-gen-go-grpc`, `out: ../internal/contracts`,\n `opt: paths=source_relative`. **No `go_package` in source** — managed mode owns it. Generated\n Go lands in `internal/contracts/state/v1/` (package `statev1`), committed (`proto:check`\n fails on uncommitted/unmodified generated files).\n- **Adapter package:** `internal/infrastructure/staterpc/` with `server.go` (registers the\n generated server over the store), `client.go` (wraps the generated client into `store.*` and\n `workflow.Store` facades), `values.go` (proto ⇄ domain mappers), and `conformance_test.go`\n (bufconn local-vs-grpc dual-adapter suite), mirroring `internal/infrastructure/gatewayrpc/`.\n- **Binary:** `cmd/archie-state-store/main.go`, mirroring `cmd/archie-gateway/main.go` and the\n serve pattern in `internal/app/archied/gateway.go` (`serveGateway`).\n\n### The `StateStore` RPC set (union of the contracts, grouped)\n\nMethods are named after the store methods so the mapping is unambiguous. `workflow.Store` is a\n_view_, not new RPCs — `Update`/`Transition`/`InsertEvent` are shared with\n`TaskLifecycle`/`TaskEvents` and appear once.\n\n| Group | RPCs |\n| ------------------ | -------------------------------------------------------------------------------------------------------------------------- |\n| Lifecycle | `EnqueueIssue`, `EnqueueChatTask`, `ClaimNext`, `ClaimByIssue`, `Transition`, `Update`, `Requeue`, `RecoverStale` |\n| Archive / Retry | `ArchiveTask`, `RetryTask` |\n| Queries | `TaskByIssue`, `OpenTaskByPR`, `TaskByID`, `OpenPRs`, `ClearTerminalTasks`, `Tasks`, `StatusCounts`, `IncrementRetryCount` |\n| Events | `InsertEvent`, `EventsSince`, `TaskEvents`, `WorkflowStats`, `StageStats`, `TokensByDay` |\n| Capture | `InsertCapture`, `ListCaptures` |\n| Mapping | `InsertMapping`, `GetMapping`, `ListMappings`, `UpdateMapping`, `DeleteMapping` |\n| Binding | `InsertBinding`, `GetBinding`, `ListBindings`, `UpdateBinding`, `DeleteBinding`, `ApproveBinding` |\n| Dispatch | `ArmedBindingsForSource`, `RecordDispatch`, `ListUndispatchedCaptures` |\n| Playbook | `RecordPlaybookDispatch`, `DeletePlaybookDispatches` |\n| BindingTaskCreator | `EnqueueBindingTask` |\n| Config snapshot | `PutConfigSnapshot`, `GetConfigSnapshot` |\n| Apply status | `PutApplyStatus`, `ListApplyStatus` |\n| Channel status | `PutChannelStatus`, `ListChannelStatus` |\n| Task log | `ReadTaskLog`, `StreamTaskLogContent` |\n\nThat is **51 unique contract RPCs** across one service (the `TaskEvents.Close` method is dropped).\n`Close()` is **excluded** from the wire (it is server lifecycle, not a client call) — see §11.\n\nThe channel-status pair follows the config snapshot's split for the same reason: the writer is the process that HOSTS the channels -- the Messaging Service, which alone observes whether a channel is starting, running or failed -- and the reader is the UI process. Both RPCs are administrative, so a task-scoped grant reaches neither. A channel's state is runtime state rather than a settings document, which is why it is not a `ControlPlaneService` resource kind: a failed channel is not a document anybody edits. Asking for a reload travels on its own surface rather than through this one; see `docs/architecture/migration-decisions.md`, \"Channel state to the dashboard\".\n\nThe config-snapshot pair was added by `archie-core-ymut` (see\n`docs/architecture/migration-decisions.md`, \"Dashboard configuration page\"). It is the one\nsurface whose writer is the daemon and whose reader is the UI process, and both RPCs are\nadministrative: `authorizesTaskScopedCall` is deny-by-default, so a task-scoped grant reaches\nneither. `ConfigSnapshot.document` is opaque to this contract — the store neither parses nor\nvalidates it, and `schema` names the projection so a reader can refuse a shape it does not\nunderstand.\n\nThe apply-status pair was added by `archie-core-pskb` (see\n`docs/prds/control-plane-apply-status.md`). It is administrative for the same reason as the\nconfig-snapshot pair, and deny-by-default in `authorizesTaskScopedCall` covers it without a\nnew rule. Unlike that pair, the read is a list: `ListApplyStatus` returns every process's\nrecord and an empty slice means nothing has reported yet, so the `found=false` convention for\nabsent single rows does not apply. The rows are keyed on `(process, kind)` and replaced in\nplace, because each process re-stamps its record on an interval and no reader wants a history\nof re-stamps.\n\nThe task-log pair was added by `archie-core-iaqx` (see `docs/prds/ui-service-boundary.md`'s\nroute inventory). It is the one surface whose payload is not a row: the store service reads\nthem out of the state directory it owns with `internal/logging`'s own reader, so the wire\ncarries `logging.Entry`/`logging.Query` values and neither side restates the JSONL format.\n`ReadTaskLog` returns a decoded page and `StreamTaskLogContent` returns the raw bytes\nserver-streamed, because a log file rotates at 20 MB — past gRPC's 4 MiB unary cap — and the\nsame reasoning that made `StreamCaptures` supersede `ListCaptures` applies. `found=false` with\nno error means the attempt has no log; a service with no reader answers `Unavailable` instead,\nand the two answers are load-bearing for the dashboard: only the second is a deployment\ncondition, and the panel that collapsed them told operators task logging was switched off when\nit was not. The Go facade is `storecontract.TaskLogStore` (2 methods), carried by\n`*staterpc.Client` alongside the rest.\n\nThe playbook pair was added by `archie-core-t2db.17`'s implementation (see\n`docs/prds/eda-playbook-engine.md`, execution-time gap 2). It is administrative\nfor the same reason as the config-snapshot and apply-status pairs, and\ndeny-by-default in `authorizesTaskScopedCall` covers it without a new rule. The\nrow is the structural `(playbook_id, playbook_version, event_id, action_id)`\ntuple, written **before** the action's side effect fires (the reverse of\n`binding_dispatches`), so a duplicate returns `store.ErrAlreadyDispatched` and\nthe coordinator skips the invoke rather than repeating a non-revocable side\neffect. `DeletePlaybookDispatches` is the explicit reclamation primitive; nothing\ncalls it automatically, because a playbook file's absence at boot is not a\ndeliberate removal (`eda-playbook-engine.md`, \"Lifetime\"). The Go facade is\n`storecontract.PlaybookDispatcher` (2 methods), carried by `*staterpc.Client`\nalongside the rest.\n\n### Domain types and `values.go` mapping\n\n`values.go` maps proto ⇄ these types. The task model for the **agent** path is the domain-owned\n`workflow.Task` (§4); the daemon/webui store surfaces return the same `workflow.Task` (the store\npersists the domain type).\n\n| Domain type | Package | Notes for `values.go` |\n| ------------------------------------- | -------------------------- | -------------------------------------------------------------------------------------------------------------- |\n| `workflow.Task` | `internal/domain/workflow` | time fields stored as layout strings; convert to/from `google.protobuf.Timestamp` |\n| `events.Event` | `internal/events` | `Timestamp` → `google.protobuf.Timestamp` |\n| `store.CapturedEvent` | `internal/store` | headers/body/remote_addr; body capped 256 KiB |\n| `mapping.Mapping` | `internal/domain/mapping` | JSON-path field bindings |\n| `binding.Binding` | `internal/domain/binding` | secret is **already decrypted** before returning; keep decrypted form out of any durable/logged representation |\n| `workflow.Status` / `workflow.Source` | `internal/domain/workflow` | enum-like; map to proto enum or string, keeping the names stable for compatibility |\n| `store.WorkflowStat` | `internal/store` | aggregate row |\n| `store.StageStat` | `internal/store` | aggregate row |\n| `store.DayTokens` | `internal/store` | aggregate row |\n\n### Wire-contract blocker fixed here: `RecordDispatch`\n\n`store.BindingDispatcher.RecordDispatch(ctx, tx *sql.Tx, bindingID, bindingVersion int64,\ncaptureID int64, taskID int64) error` takes a **`*sql.Tx`** that cannot cross a gRPC boundary.\n\n**Evidence that the `*sql.Tx` is removable:** the dispatch loop calls `RecordDispatch(ctx, nil,\n…)` (`internal/daemon/daemon.go`). The implementation falls back to the store's own\n`*sql.DB` when `tx == nil` (\"best-effort, not atomic\"; the comment and the\n`TestRecordDispatchViaExplicitTx` test are the only consumers of the non-nil `tx` path).\nProduction never opens the explicit transaction.\n\n**Decision:** the contract drops `*sql.Tx` from `RecordDispatch` (the method becomes\n`RecordDispatch(ctx, bindingID, bindingVersion, captureID, taskID) error`). The store service\nowns any transaction boundary internally when atomicity is wanted; the at-most-once\nguarantee is the `INSERT OR IGNORE` dedup row, which is already transactionless in production.\n`TestRecordDispatchViaExplicitTx` is superseded by the store service's own internal-transaction\ntest. **This is a required interface migration that must land before or with `.4.2`** (the\ncurrent `interface.go` signature and test still use the transaction-bearing form).\n\n---\n\n## 6. Agent State Store client handoff\n\nMoving the agent from NATS `storerpc` to gRPC `workflow.Store` requires the agent process to\nreceive a State Store endpoint. The agent already receives its NATS connection settings via\nboot-time env/flags (see `cmd/archie-agent/main.go`: `-nats-url` / `NATS_URL`, `NATS_TOKEN`\nenv), and the daemon injects them into the task container. The State Store handoff follows the\nsame seam.\n\n**Boot handoff contract (additive, not replacing the NATS settings):**\n\n| Field | Where | Source | Notes |\n| ------------------ | ---------------------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |\n| `StateStoreTarget` | `agentworker.Settings` | env `STATE_STORE_URL` (or `-state-store-url` flag), set by the daemon in the container env | `host:port` of the State Store gRPC server. Loopback/Docker-bridge address — the agent reaches it the same way it reaches the daemon's NATS. |\n| `StateStoreToken` | `agentworker.Settings` | env `STATE_STORE_TOKEN` (or `-state-store-token` flag) | Per-task bearer token carried in gRPC metadata by a client interceptor (see §9). |\n| `StoreTimeout` | `agentworker.Settings` | a bounded per-call timeout | Mirrors `natsrpc.Client.Timeout` / the existing `rpcTimeout`; bounds each State Store call when the caller `ctx` has no deadline. |\n\n**Wiring change in the transport façade:**\n\n- `internal/infrastructure/agenttransport/nats.Transport` — `Store(timeout) store.WorkflowStore`\n returns `\u0026storerpc.Client{Conn: t.conn, Timeout: timeout}`. It becomes\n `Store(timeout) workflow.Store` and returns a _single long-lived_ `staterpc.Client` dialled to\n `settings.StateStoreTarget` (with the token interceptor and per-call timeout).\n- `internal/app/agentworker/worker.go` `Settings` gains the three fields above; `taskServiceTransport`\n and `taskDependencies` change their `store` type from `store.WorkflowStore` to\n `workflow.Store` (via `domain/workflow.TaskContext{Store: …}`).\n- Reconnect/deadline: `grpc.NewClient` (or the existing dial path) provides transparent reconnect;\n each RPC is bounded by the per-call context deadline (`StoreTimeout`), matching the\n request/reply timeout the NATS path used. No streaming is involved, so no server-sent\n reconnect semantics apply.\n\n**Deletion rule for the NATS path:** the NATS `storerpc` (Server, Client, subjects\n`archie.store.update|transition|insert_event`) is deleted **only after** the agent has fully\nmoved to gRPC and the container env carries `STATE_STORE_URL`. Until then both paths may coexist\n(agent flips when the daemon starts injecting `STATE_STORE_URL`); there is no dual-live window\nacross a single agent process, which is either NATS-backed or gRPC-backed, never both.\n\n### Operational specifics (in-process listener → address → per-task injection)\n\n- **Who binds the in-process State Store listener:** the daemon (`archied`), at bootstrap, when\n the State Store is served in-process/multiplexed (mirroring `serveGateway` in\n `internal/app/archied/gateway.go`): a `grpc.NewServer()` + `RegisterServer` + graceful stop on\n `ctx.Done()`.\n- **Address selection (Docker-bridge reachable):** reuse the host-gateway resolution already used\n for embedded NATS (`internal/container/network.go` `RequireHostGateway` /\n `resolveHostGateway`). Per §9's single listener-topology rule, the listener binds the\n **host-gateway bridge address** when agent containers consume it (the Phase 2 default), or\n loopback-only when the daemon is the sole consumer. The chosen address is stored on the daemon\n as `d.ConnectedStateStore.URL` (analogous to `d.ConnectedNATS.URL`).\n- **Per-task injection:** `containerEnv(task)` (`internal/daemon/daemon.go`) appends\n `STATE_STORE_URL=\u003cd.ConnectedStateStore.URL\u003e` and `STATE_STORE_TOKEN=\u003ctoken\u003e` alongside the\n existing `NATS_URL`/`NATS_TOKEN`. The agent reads them via env (`-state-store-url` /\n `STATE_STORE_URL`, `-state-store-token` / `STATE_STORE_TOKEN`), the same seam as `NATS_URL`. A\n reloaded `[services.state]` must not point new containers at a store the daemon is not serving\n — the same immutability rule as NATS.\n\n---\n\n## 7. Error semantics\n\n### Current state (both boundaries lose error identity)\n\n- **NATS `natsrpc.Envelope`** (`internal/natsrpc/natsrpc.go`) serialises any error to a single\n `err.Error()` string and rehydrates a fresh `errors.New(string)`. The original type, `%w`\n chain, and sentinel identity are lost → `errors.Is(err, store.ErrStaleTransition)` is\n **false** across the boundary.\n- **gRPC `gatewayrpc`** returns raw `err` from handlers; gRPC-Go converts to\n `codes.Unknown` with only the message. The **only** explicit code in the repo is\n `codes.Unavailable` for a missing session store (`server.go`). No status-code mapping for\n store errors exists.\n\n### Decision — structured mapping so `errors.Is` survives\n\nThe `StateStore` service must map the store's sentinel errors to canonical gRPC codes and\nrehydrate them to the _same_ sentinels on the client, so consumer `errors.Is` checks keep\nworking — an improvement over the flattening it replaces, not a regression.\n\n| Store sentinel / outcome | gRPC code | Client rehydrates to |\n| ------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------- |\n| `store.ErrStaleTransition` | `FailedPrecondition` | `store.ErrStaleTransition` |\n| `store.ErrBindingNotFound` | `NotFound` | `store.ErrBindingNotFound` |\n| `store.ErrMappingNotFound` | `NotFound` | `store.ErrMappingNotFound` |\n| `store.ErrBindingOverlap` | `FailedPrecondition` | `store.ErrBindingOverlap` |\n| `store.ErrBindingTransition` | `FailedPrecondition` | `store.ErrBindingTransition` |\n| `store.ErrAlreadyDispatched` | `AlreadyExists` | `store.ErrAlreadyDispatched` |\n| not-found-as-`(nil,nil)` (`TaskByID`, `GetBinding`, `GetMapping`, `ClaimNext`, `ClaimByIssue`, …) | `NotFound` with a `found=false` field (**not** an error) | `(nil, nil)` |\n| infra / wrapped error | `Internal` (**sanitised** message, see below) | wrapped `fmt.Errorf(...%w)` |\n| capability absent | `Unavailable` | context/typed error |\n\nThe `found=false`-not-error convention matters: the repo deliberately returns `(nil, nil)` for\nnot-found in reads and a sentinel for not-found in writes. The wire must preserve **both**\nconventions (a `GoogleRPCStatus` with `NotFound` is an _error_, which would wrongly surface to\ncallers that expect `(nil, nil)`). Implement `found` as an explicit boolean field on read\nresponses, and map `(nil,nil)` ⇄ `found=false` + `OK`.\n\n### Error-detail sanitisation (rev. 2c)\n\nFull internal error messages must **not** be placed in gRPC `details` for remote callers. SQL\npaths, provider/forge details, secrets, and stack traces are sensitive internals. The rule:\n\n- **Sentinel errors** — the client rehydrates the sentinel from the code; the message string in\n `status.Error` is a short, public, stable phrase (e.g. `\"stale transition\"`), not the raw\n wrapped chain.\n- **Infra errors** — the wire carries a **sanitised** public message + the `Internal` code.\n The **full** error (with `%w` chain, SQL, provider detail) is logged **server-side only** by\n the store service. The client rehydrates a generic wrapped error and must not surface the raw\n text to users.\n\n---\n\n## 8. Limits\n\n**Interface bloat (`interfacebloat` cap = 8)** — `.golangci.yml` `interfacebloat: max: 8`,\nwhich overrides the upstream default of 10. The Go consumer facades must stay ≤8 methods.\n`TaskLifecycle` is exactly 8 (at the cap); `TaskStore` is the 24-method composite that the cap\nis why it is decomposed; proto services bypass the cap (like `ChatContract`).\n\n**Payload caps:**\n\n- Capture body: `defaultCaptureMaxBodyBytes = 256 KiB` (may reduce further; the wire message\n must not exceed gRPC's default 4 MiB receive limit for a single capture). A single capture\n fits, but a _batch_ of them did not: the caller-side cap of up to 100 captures at 256 KiB each\n could exceed 4 MiB in one unary `ListCaptures`/`ListUndispatchedCaptures` response. `.4.7` adds\n `StreamCaptures`/`StreamUndispatchedCaptures` (server-streaming, one capture per message) as\n the path both `staterpc.Client` methods actually call; the original unary RPCs stay defined,\n unmodified and deprecated, only so `buf breaking` protects an in-flight rolling deploy.\n- Task `detail`/`park_reason`/event `Detail`: 4000-char hard cap (`clip(s, 4000)`).\n\n**Retention (stays server-side in the store; the wire does not carry pruning decisions):**\n\n- `events` table: **no prune, unbounded growth** — a known risk to revisit, not changed here.\n- `captured_events`: prune-on-write, default 7 days / 5000 events.\n\n**Pagination/arity:** store read methods take a raw `int limit` (no store-side cap); the\ncaller-side caps (task list 100, log 2000, captures 100, capture scan window 5000, binding\ndispatch batch 100, session list 20) remain caller-side. The wire passes `limit int` and returns\n`[]*` slices, mirroring the existing Go signatures — **no cursor/paging protocol is introduced**\nin this work (the current `EventsSince(sinceID, limit)` offset cursor is the only one, and it\nstays as-is).\n\n---\n\n## 9. Transport security boundary\n\nThe gateway precedent is loopback-only, unauthenticated gRPC. The State Store holds the\ncrown-jewel `archie.db` (task/event/capture/mapping/binding data), so its boundary must be\nstated explicitly rather than left implicit.\n\n**The State Store's equivalent boundary (rev. 2c):**\n\n- **Listener topology — single rule (rev. 2c).** One in-process listener; its bind address is\n chosen by the consumer set, never both at once:\n - _Agent containers consume it_ (the Phase 2 driver during multiplexed serving) → bind to the\n **host-gateway bridge address** so containers can reach it, and **token auth is mandatory**\n (a bridge host is reachable by any process on that bridge). A container **cannot reach the\n host's `127.0.0.1`**, so loopback-only is NOT usable for the agent-consumed path.\n - _Only the daemon consumes it_ (no agent) → bind **loopback-only** (`--listen 127.0.0.1`),\n `insecure` is fine because it is not network-reachable; no token required.\n - There is **no dual-listener** design. The practical default during `.4.2` (the reason\n in-process serving exists is to give the agent a gRPC target) is the **bridge address +\n token**. `127.0.0.1` is reserved for the daemon-local-only case.\n- **Agent access → the container bridge.** The agent runs in a task-scoped container on the\n host and reaches the State Store over the Docker bridge gateway (the bind address from the\n topology rule above), exactly as it reaches the daemon's NATS. To close the \"any host\n process could reach the store\" gap, the agent **authenticates with a per-task bearer token**\n carried in gRPC metadata by a client interceptor (`StateStoreToken`, §6). Network\n reachability + the token is the trust boundary for the default bridge topology.\n- **The daemon** uses the local adapter (`*store.Store`) in-process by default, so no network\n boundary exists until `[services.state].target` is set; when it is set, the daemon client\n authenticates with a token supplied alongside the target.\n- **Non-loopback / k8s:** TLS/mTLS is an **operator decision**, not a default. Any non-loopback\n exposure (e.g. `--listen 0.0.0.0`, a CDN, a cross-host service) requires an explicit decision\n and mTLS or token auth — mirroring the gateway's `--listen`/`--enable-cors-header`\n confirmation caveat. The NATS-KV discovery fallback supplies endpoints but does not add\n transport security; that stays the operator's responsibility.\n\n### Token lifecycle (rev. 2c; scoping added in `.4.7`)\n\n- **Generation:** the daemon generates a per-task bearer token when it acquires the container\n (or per incumbence) and injects it via `containerEnv` as `STATE_STORE_TOKEN`. A single token\n may cover a task's container lifetime.\n- **Registration (`.4.7`, post-standalone-cutover):** the State Store is now its own process\n (`.4.3`/`.4.6`), so the daemon can no longer just hold an in-process issued-token set for the\n server to check — it registers the token at the remote authority via the\n `RegisterTaskGrant`/`RevokeTaskGrant` RPCs (`staterpc.GrantIssuer`, `daemon.StateStoreGrantIssuer`),\n admin-token-authenticated calls a task-scoped token itself can never make.\n- **Lifetime:** tied to the task + container grace period; rotated on a new container acquisition\n for the same task; a token for a released container is invalidated (`RevokeTaskGrant`, deferred\n alongside `ContainerPool.Release`). An unrevoked grant still expires server-side (bounded by\n `RegisterTaskGrantRequest.lifetime_seconds`, capped at 7 days) so a daemon crash before revoke\n cannot leave a grant valid indefinitely.\n- **Validation and scope (`.4.7`):** a gRPC interceptor (`staterpc.TaskGrants.UnaryInterceptor`)\n validates the token against the State Store's own issued-grant set; missing/unknown/expired →\n `codes.Unauthenticated`. Unlike the daemon's own administrative token (full access to all ~40\n RPCs), a task-scoped grant additionally authorises only `Update`/`Transition`/`InsertEvent` on\n its own task ID — every other RPC, including the streaming capture surface and\n `RegisterTaskGrant`/`RevokeTaskGrant` themselves, is `codes.PermissionDenied` for a task-scoped\n caller. The token is carried in gRPC metadata, never in a URL.\n\n### Fail-closed on non-loopback (rev. 2c)\n\nIf `[services.state].target` points to a non-loopback address and **neither** TLS **nor** a token\nis configured, the State Store client (daemon or agent) **fails closed** — it refuses to\nstart/dial rather than fall back to a plaintext, unauthenticated remote connection. This mirrors\nthe gateway's `--listen`/`--enable-cors-header` confinement caveat and prevents a silent\nunauthenticated remote store. The loopback + token default is the only path that starts without\nan explicit operator decision.\n\n---\n\n## 10. Mode / config shape\n\n**Follow the gateway's presence-based `target` seam, not the NATS `mode` enum.**\n\n- **Services are keyed by name, not named as struct fields.** A\n `State ServiceConnection` field per service is the duplication\n `docs/prds/service-registry.md` removes, and this document's summary describes\n the seam as `[services.\u003cname\u003e]`:\n ```go\n type Services map[string]ServiceConnection\n ```\n registered once via `RegisterService(context, name, target, listen, tokenEnv)`. The TOML\n shape below is unchanged, so nothing else in this section is affected; read\n `cfg.Services.Get(\"state\")` wherever it says `cfg.Services.State`.\n- **Empty `Target` → startup error.** The local `*store.Store` adapter default was\n withdrawn when the State Store was extracted (§12 step 7): the standalone `archie-state-store` process\n exclusively owns `archie.db`, so both `archied` and `archie-gateway` now reject an empty\n target (`internal/app/archied/bootstrap.go` and `state_store_client.go`: `services.state.target\nis required`). **Set `Target` → dial gRPC** with `*staterpc.Client`; no client opens the\n database itself. This differs from the gateway, where `Target` is defaulted to\n `127.0.0.1:8585` because `archie-gateway` is already a separate process whose client and\n server share one default.\n- `[services.state]` is present and **uncommented** in `config.example.toml`, with `target`\n marked REQUIRED, because the value is load-bearing for every client. A commented-out\n `target` cannot boot, so the section ships uncommented.\n- Composition root: `internal/app/archied/bootstrap.go` (the daemon) and\n `internal/app/archieui/config.go` (the UI process) both read `cfg.Services.Get(\"state\")` and\n dial the remote State Store. The task store is built only in the standalone\n `archie-state-store` process (`internal/app/archied/state_store.go`), which is the only path\n that opens the task tables.\n\n\u003e **Mode fork, decided.** The gateway uses a single `target` address (no enum). The State Store\n\u003e boundary uses the same seam for symmetry, and **both now require a non-empty `target`**: the\n\u003e State Store's local-store default was withdrawn when the process was extracted (§12 step 7).\n\u003e No `mode` field is added. A companion `STATE_STORE_TOKEN` secret (or a\n\u003e `[services.state] target_token` key) carries authentication.\n\n---\n\n## 11. Local-adapter compatibility + conformance\n\n- `*store.Store` (local) and `*staterpc.Client` (remote) satisfy the **same** contract\n interfaces. Use **explicit** `var _` assertions on **both** adapters (the gateway's local\n adapters use only structural/return-type assertions; the store precedent's explicit `var _`\n style is stronger and should be adopted on both sides).\n ```go\n var _ workflow.Store = (*staterpc.Client)(nil) // first contract to move (agent)\n var _ store.TaskStore = (*staterpc.Client)(nil) // daemon path, added progressively\n var _ store.CaptureStore = (*staterpc.Client)(nil)\n var _ store.MappingStore = (*staterpc.Client)(nil)\n var _ store.BindingStore = (*staterpc.Client)(nil)\n var _ store.BindingDispatcher = (*staterpc.Client)(nil)\n var _ store.BindingTaskCreator = (*staterpc.Client)(nil)\n var _ store.PlaybookDispatcher = (*staterpc.Client)(nil)\n // local side (in store), already present:\n var _ workflow.Store = (*Store)(nil)\n ```\n- **Conformance suite:** a `staterpc/conformance_test.go` bufconn suite runs the **same**\n contract through both `\"local\"` and `\"grpc\"` adapters (mirroring\n `gatewayrpc/conformance_test.go`), asserting error-sentinel fidelity and the\n not-found-as-`(nil,nil)` convention both ways.\n- **`Close()`:** stays on the Go store interfaces (so `TaskStore`/`TaskEvents` remain fully\n satisfiable) but is **not** a `StateStore` RPC. The remote `staterpc.Client` implements\n `Close()` as a **no-op**; the store service owns its own DB lifecycle. When the daemon hands\n the store to `archie-state-store`, `b.cleanup()` no longer calls `store.Close()` on a remote\n client (it is the daemon's own lifecycle only when it owns the store in-process).\n\n---\n\n## 12. Cutover / deletion rules\n\n1. **Ratify the contract (this document).** No code.\n2. **Domain type + interface relocation (prerequisite, coupled with §4).** Move `Task`/`Status`/\n `Source` and the `WorkflowStore` interface into `internal/domain/workflow` (as\n `workflow.Task`/`workflow.Status`/`workflow.Source`/`workflow.Store`), so\n `internal/domain/workflow` imports no `internal/store`. Update the store tests and the 6\n workflow production files. **This must land before or with `.4.2`, because `.4.2` cannot move\n the agent's store contract off `store.WorkflowStore` while the domain still imports it.**\n3. **`.4.2` — generalise `storerpc` to the gRPC contract.** Move the agent's `workflow.Store`\n (`Update`/`Transition`/`InsertEvent`) from NATS JSON `storerpc` to `staterpc.Client` over\n gRPC, using the §6 handoff. The daemon serves the gRPC `StateStore` server **in-process\n (multiplexed)** first so the agent has a gRPC target before the standalone binary exists\n (PRD §3 \"multiplexed in-process is the migration default\"). Bind the in-process listener and\n inject `STATE_STORE_URL`/`STATE_STORE_TOKEN` per task (see §6 \"Operational specifics\"). Also\n land the `RecordDispatch` `*sql.Tx` drop (see §5) in the same span. Flip the agent's\n `Transport.Store` to a gRPC client once `STATE_STORE_URL` is injected.\n4. **Delete NATS `storerpc` only after the agent is fully on gRPC** — delete `internal/storerpc`\n (Server, Client, subjects `archie.store.update|transition|insert_event`), the\n `natsrpc.RegisterAll` registration, and the now-unused `store.WorkflowStore` NATS path in\n `internal/infrastructure/agenttransport/nats`, in the same commit.\n5. **`[services.state].target` stays empty (inproc)** through `.4.2`; the `archie-state-store`\n `cmd/` binary is **`.4.3`** and hosts the same `StateStore` gRPC service.\n6. **Swap daemon-internal contracts one at a time** (only once the daemon points at\n `archie-state-store`): `Capture → Mapping → Binding → TaskStore`. Each swap is independent —\n add the remote-client composition path, run the per-contract conformance suite, flip\n `[services.state].target`, delete the local use. A consumer mixes in-process and remote\n contracts for a contract-code (no dual-live _window_; each contract is either local or remote\n at a time).\n7. **Final flip / deletion of the in-process serving path:** when the daemon no longer owns the\n store (i.e. `TaskStore` has moved), delete the in-process task-store /\n `wireWebStoreSurfaces` path in the daemon in a **same-commit** deletion — no dual-store\n ownership. The single SQLite file remains owned by `archie-state-store`.\n8. **Never** split `archie.db` or add a second store. The gateway keeps its own already-separate\n session SQLite; that is unchanged and out of state-store scope.\n\n---\n\n## 13. Decisions recorded (for the review trail)\n\n- **`internal/store` is a transitional compatibility location** (target\n `internal/infrastructure/store`), not the final infrastructure boundary. The producer-owned\n daemon/webui store surfaces live there now but may relocate with the implementation.\n- **In-process listener + token lifecycle:** the daemon binds the in-process State Store\n listener to the **host-gateway bridge address** when agent containers consume it (the Phase 2\n default) or loopback-only when the daemon is the sole consumer — one listener, one address\n rule, never both (rev. 2c). It selects the bridge address by reusing the embedded-NATS\n host-gateway resolution and injects `STATE_STORE_URL`/`STATE_STORE_TOKEN` per task via\n `containerEnv`. Token is per-incumbence (task + container grace period) and validated by a\n gRPC interceptor → `codes.Unauthenticated` on missing/unknown/expired. Non-loopback targets\n fail closed without TLS or a token.\n- **§12 step 2 (domain type + interface relocation) is done** — `internal/domain/workflow`\n imports no `internal/store` symbol and `store.WorkflowStore` is gone from `TaskContext`. The\n broader Phase 2 acceptance criterion (State Store as its own gRPC service) is still open;\n `.4.2` picks up from here.\n- **Ownership split:** domain-facing workflow contract is **consumer-owned** in the domain\n (`workflow.Store` + `workflow.Task`/`Status`/`Source`, per dependency rules #2 and #7);\n daemon/webui store surfaces stay **producer-owned** in `internal/store`. `store.WorkflowStore`\n is superseded by `workflow.Store`.\n- **One `StateStore` gRPC service** (49 contract RPCs, grouped by contract) + narrow Go consumer facades\n (≤8) on `staterpc.Client` — mirrors the single-`ChatService` precedent.\n- **Domain type relocation** (`Task`/`Status`/`Source` → `internal/domain/workflow`) is a\n Phase 2 prerequisite, pulled forward from migration-decisions §4 (minimal bound,\n `Task → WorkflowExecution`); the rest of §4 stays a separate migration.\n- **`RecordDispatch` drops `*sql.Tx`** (wire-blocker; production passes `nil`) — a\n required interface migration landing before/with `.4.2`.\n- **`Close()` not on the wire**; remote client `Close()` is a no-op.\n- **Structured gRPC error codes** with client rehydration to store sentinels (preserves\n `errors.Is`), a `found=false` + `OK` convention for read not-found, and **sanitised public\n error details** (full detail logged server-side only).\n- **Agent handoff:** `agentworker.Settings` gains `StateStoreTarget`/`StateStoreToken`/\n `StoreTimeout`, injected as `STATE_STORE_URL`/`STATE_STORE_TOKEN` env (mirrors the NATS\n handoff); `Transport.Store` returns a long-lived gRPC `workflow.Store` client.\n- **Transport security + listener topology (rev. 2c):** one in-process listener, bound to the\n host-gateway bridge address when agent containers consume it (the Phase 2 default) or\n loopback-only for a daemon-local-only consumer. `insecure` only on loopback; mandatory\n per-task bearer-token auth on the bridge; TLS/mTLS is an operator choice for any\n non-loopback/k8s topology.\n- **Mode = presence-based `[services.state].target`**, default **local** (not yet extracted);\n add `[services.state]` to `config.example.toml`.\n- **Explicit `var _` assertions on both adapters**; per-contract bufconn conformance.\n- **Migration order:** domain type/interface relocation → `workflow.Store` (agent) → stand up\n `archie-state-store` → `Capture` → `Mapping` → `Binding` → `TaskStore`; NATS `storerpc`\n deleted once the agent is on gRPC; in-process store path deleted in a same-commit flip.\n- **Orphans `ClearTerminalTasks`/`IncrementRetryCount`** retained but not built upon.\n" + "body": "# State Store — contract boundary \u0026 transport (ratification)\n\n**Status:** Approved\n**Revision:** 2e\n**Date:** 2026-09-06\n\nThis is the pre-implementation design document that Phase 2 subtasks `.4.2` (generalise\n`storerpc` as the State Store gRPC contract) and `.4.3` (stand up `archie-state-store`)\nimplement against.\n**Beads milestone:** archie-core-8cda.4.1\n**Parent:** `docs/prds/service-decomposition.md` (open-question Q4 **RESOLVED**)\n\nThis document fixes the **contract boundary** and **transport** for the State Store service.\nIt does not redesign Archie's domain model, does not invent a second store, and does **not**\nsplit `archie.db`. It records method ownership, DTO/wire representation, error semantics,\nlimits, mode/config shape, local-adapter compatibility, and cutover/deletion rules so that\n`.4.2` and `.4.3` have exactly one authoritative surface to build against.\n\n\u003e **Storage superseded.** The store behind this contract is PostgreSQL:\n\u003e `internal/infrastructure/postgres` implements the producer-owned interfaces in\n\u003e `internal/domain/storecontract` and `workflow.Store`, over the database\n\u003e `database_url` names. `internal/store`, the SQLite file and the local adapter\n\u003e are gone; where this document says `archie.db`, `*store.Store` or\n\u003e `internal/store`, read the State Store's PostgreSQL database and\n\u003e `internal/infrastructure/postgres`. The contract, ownership split, error\n\u003e semantics and cutover rules stand.\n\n\u003e **Current state — read before `.4.2` starts.** The §12 step 2 relocation (`archie-core-8cda.\n4.8`) has landed: `Task`/`Status*`/`Source*` and the 3-method `workflow.Store` now live in\n\u003e `internal/domain/workflow`, the six production workflow files import no `internal/store`\n\u003e symbol, and `storerpc`/the NATS transport assert against `workflow.Store` instead of\n\u003e `store.WorkflowStore`. The broader Phase 2 acceptance criterion (State Store as its own\n\u003e service behind gRPC) is still open — that is what `.4.2`/`.4.3` build next.\n\n\u003e **Relationship to migration-decisions §4 — not replaced.** `docs/architecture/\nmigration-decisions.md` §4 (`store.Task → WorkflowExecution`, `mutable Stage →\nStepExecution history`, `RetryCount/Attempt → Attempt records`, versioned Workflow defs)\n\u003e **remains the authoritative, open document for the long-term Workflow migration.** This PRD\n\u003e does **not** replace it. It only pulls the minimal `Task`/`Status`/`Source` type + interface\n\u003e relocation forward as a Phase 2 prerequisite (because the acceptance criterion requires it);\n\u003e the rest of §4 stays its own migration and stays open.\n\n---\n\n## 1. Decision (the invariant everything follows)\n\nArchie is composed such that a single **`archie-state-store`** service owns the one existing\nSQLite file (`archie.db`) and exposes it over **gRPC behind narrow typed contracts**. There is\nexactly one store, one file, one service. No database-per-service, no distributed\ntransactions, no second store abstraction.\n\nTwo adapter families satisfy the contract interfaces:\n\n- **Local adapter** — `*store.Store` (the in-process SQLite implementation).\n- **Remote adapter** — `*staterpc.Client` (wraps the generated gRPC client).\n\nEach adapter carries an explicit compile-time assertion against the contract interfaces it\nserves. Composition picks local vs. remote by the presence of `[services.state].target`\n(empty = local; set = dial the gRPC service). Default is **local** (the State Store is not yet\nextracted), which is the PRD §3 posture; it differs from the gateway's remote-default only\nbecause the gateway is already a separate deployment and the State Store is not.\n\n\u003e **Contract-ownership fork, decided (rev. 2c — resolves the domain contradiction).**\n\u003e Ownership splits by the consumer's _layer_, per the dependency contract's rule #2\n\u003e (\"a domain defines the smallest interfaces required to perform its work\") and rule #7\n\u003e (\"database rows … MUST NOT leak into domain models\"):\n\u003e\n\u003e - The **workflow domain** (`internal/domain/workflow`) is the only domain-layer consumer of\n\u003e store state. It defines its own **consumer-owned** narrow `Store` interface\n\u003e (Update/Transition/InsertEvent) and its own **domain-owned** `Task` type plus\n\u003e `Status`/`Source` vocabulary. It imports **zero** `internal/store` symbols — satisfying the\n\u003e Phase 2 acceptance criterion. This is the minimal bound of migration-decisions §4\n\u003e (`store.Task → WorkflowExecution`), pulled forward **because** the acceptance criterion\n\u003e requires it.\n\u003e - The **daemon / webui / intake** store surfaces (`TaskStore`, `CaptureStore`,\n\u003e `MappingStore`, `BindingStore`, `BindingDispatcher`, `BindingTaskCreator`) stay\n\u003e **producer-owned** in `internal/store`, because those consumers are application and\n\u003e infrastructure layers, not domains — rule #2 does not apply to them.\n\nSo the State Store contract is **not** uniformly producer-owned: the domain-facing workflow\ncontract is consumer-owned (in the domain), while the daemon/webui store surfaces remain in\n`internal/store`. `internal/store` imports `internal/domain/workflow` for the `Task`/`Status`/\n`Source` types it persists (persistence → domain, the correct direction), and its `Store`\nimplementation satisfies `workflow.Store`. This is the single decision that makes the whole\nPhase 2 acceptance criterion and the architecture's rules simultaneously satisfiable.\n\n\u003e **`internal/store` is a TRANSITIONAL compatibility location (rev. 2c).** The repository's target\n\u003e architecture (`docs/architecture/dependencies-and-contracts.md`, `organisation.md`) places\n\u003e persistence implementations under `internal/infrastructure/\u003ccapability\u003e`. `internal/store`\n\u003e holding the task/capture/mapping/binding implementation and ALSO being the home of the\n\u003e producer-owned daemon/webui interfaces is acceptable **only as a transitional location**. The\n\u003e long-term home for the store implementation is `internal/infrastructure/store`; the\n\u003e producer-owned interfaces may move to the same infrastructure package (or an approved\n\u003e contract location) when the store implementation relocates. Agents must not treat\n\u003e `internal/store` as the final infrastructure boundary.\n\u003e\n\u003e **REV. 2d (archie-core-8cda.5.6): the producer-owned interfaces HAVE moved to an approved\n\u003e contract location** — `internal/domain/storecontract` (package `storecontract`), ahead of the\n\u003e store implementation's own relocation. The UI Service deletion gate required the archie-ui\n\u003e process to hold the contracts without linking `internal/store`'s SQL implementation, and\n\u003e `internal/contracts/` itself is ruled out: that tree is the `buf generate` output and\n\u003e `tools/proto.sh check` deletes hand-written files there. `internal/store` keeps type aliases\n\u003e (`type TaskStore = storecontract.TaskStore`, the sentinel `var`s, the value types) so\n\u003e daemon-side callers are unaffected; the sentinel message strings are unchanged and remain\n\u003e the wire contract (§4).\n\n---\n\n## 2. Contract boundary\n\n**Ownership split** (see the fork in §1): the **workflow-domain consumer contract** is\n`workflow.Store` (consumer-owned, in `internal/domain/workflow`); the **daemon/webui/intake\nstore surfaces** are the producer-owned interfaces in `internal/store/interface.go`.\n`store.WorkflowStore` is **superseded** — it is replaced by the domain-owned `workflow.Store`,\nand `internal/store`'s `Store` implementation satisfies `workflow.Store` directly. `TaskStore`\nremains the only composite; every other interface is flat. Narrow slices are split along\nconsumer-capability lines so no consumer acquires a surface it does not need\n(`interfacebloat` cap = 8).\n\n| Interface (owner) | Embeds | Methods | Local impl | Remote impl |\n| ---------------------------------- | --------------------------------------------------------------------------- | ---------- | ---------- | ------------------ |\n| `TaskStore` (store) | `TaskLifecycle`, `TaskEvents`, `TaskQueries`, `TaskArchiver`, `TaskRetryer` | 24 (union) | `*Store` | `*staterpc.Client` |\n| `TaskLifecycle` (store) | — | 8 | `*Store` | `*staterpc.Client` |\n| `TaskEvents` (store) | — | 7 | `*Store` | `*staterpc.Client` |\n| `TaskQueries` (store) | — | 7 | `*Store` | `*staterpc.Client` |\n| `TaskArchiver` (store) | — | 1 | `*Store` | `*staterpc.Client` |\n| `TaskRetryer` (store) | — | 1 | `*Store` | `*staterpc.Client` |\n| `workflow.Store` (workflow domain) | — | 3 | `*Store` | `*staterpc.Client` |\n| `CaptureStore` (store) | — | 2 | `*Store` | `*staterpc.Client` |\n| `MappingStore` (store) | — | 5 | `*Store` | `*staterpc.Client` |\n| `BindingStore` (store) | — | 6 | `*Store` | `*staterpc.Client` |\n| `BindingDispatcher` (store) | — | 3 | `*Store` | `*staterpc.Client` |\n| `BindingTaskCreator` (store) | — | 1 | `*Store` | `*staterpc.Client` |\n| `PlaybookDispatcher` (store) | — | 2 | `*Store` | `*staterpc.Client` |\n\n**Key property of the remote client:** `*staterpc.Client` is a _single_ adapter that wraps one\n`StateStoreClient` and is asserted against **whichever narrow Go interfaces its caller needs**\n(exactly as `gatewayrpc.Client` asserts both `gateway.ChatContract` and\n`gateway.SessionStore`). The Go contracts stay narrow (≤8, the `interfacebloat` cap); the wire\nis one service. `workflow.Store` introduces **no new RPCs** — it is a narrow consumer face over\nthe same `Update`/`Transition`/`InsertEvent` RPCs.\n\n---\n\n## 3. Method ownership\n\n`*Store` remains the single implementation of the daemon/webui store surfaces and of\n`workflow.Store`. Ownership below is about which **process** is the primary consumer of each\nmethod and therefore which methods are genuinely cross-process on the wire vs.\ndaemon-internal.\n\nProcess legend: **DAEMON** = `archied` (incl. in-process webui + gateway runtime +\n`storerpc.Server`); **AGENT** = `archie-agent` worker (no DB connection); **GATEWAY** = store\naccess through daemon-side narrow adapter interfaces.\n\n| Contract | Primary consumers (process) | Remote on the wire? |\n| ------------------------ | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |\n| `TaskLifecycle` (8) | DAEMON (dispatch, claim, action) + **AGENT** (`Transition`, `Update` via storerpc) | `Transition`/`Update` = **YES** (agent); rest DAEMON |\n| `TaskArchiver` (1) | DAEMON (`taskactions` archive) | not yet |\n| `TaskRetryer` (1) | DAEMON (`taskactions` retry) | not yet |\n| `TaskQueries` (7) | DAEMON + GATEWAY (status/list adapters) | not yet (`OpenPRs`/`Tasks`/`StatusCounts` cross to gateway adapters in-process) |\n| `TaskEvents` (7) | DAEMON + **AGENT** (`InsertEvent` via storerpc) | `InsertEvent` = **YES** (agent); rest DAEMON |\n| `workflow.Store` (3) | **AGENT** only | **YES** (the sole genuinely remote consumer) |\n| `CaptureStore` (2) | DAEMON (webhook intake + mapping editor) | not yet |\n| `MappingStore` (5) | DAEMON (dashboard editor + dispatch loop) | not yet |\n| `BindingStore` (6) | DAEMON (dashboard editor + dispatch loop) | not yet |\n| `BindingDispatcher` (3) | DAEMON (dispatch loop) | not yet |\n| `BindingTaskCreator` (1) | DAEMON (dispatch loop) | not yet |\n| `PlaybookDispatcher` (2) | DAEMON (EDA playbook dispatch loop) | **YES** (side-effecting-action idempotency ledger over gRPC) |\n\n**Consequence for migration order:** the **agent's `workflow.Store` is already cross-process\nalready** (via the NATS `storerpc` surrogate), so it is the first contract to move to gRPC. The\ndaemon-internal surfaces (`Capture`/`Mapping`/`Binding`) stay in-process until the daemon\nitself points at `archie-state-store`. `TaskStore` (the large composite) moves last.\n\n**Two orphan methods** — `TaskQueries.ClearTerminalTasks` and\n`TaskQueries.IncrementRetryCount` have **no production consumer** (only `*Store` tests). They\nremain part of the Go `TaskQueries`/`TaskStore` surface, and therefore part of the wire\ncontract, but are flagged for deletion: they must **not** gain dedicated consumers or wire\nmethods in this work. Do not add the rest of the codebase to them.\n\n---\n\n## 4. Domain-facing types \u0026 consumer-owned contract — resolves the contradiction\n\nThe Phase 2 acceptance criterion (\"`internal/domain/workflow` … no longer import\n`internal/store` directly — they call the State Store contract\") **cannot be met while**\n`store.Task`, `store.Status*`, `store.Source*`, and `store.WorkflowStore` live in\n`internal/store`. This section fixes where they move.\n\n**The relocation (a prerequisite that must land before or with `.4.2`):**\n\n| Current symbol (`internal/store`) | Moves to | Notes |\n| ------------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |\n| `Task` type | `internal/domain/workflow.Task` | The task-execution record the workflow domain operates on. `internal/store` persists this type (persistence → domain). |\n| `Status` + `Status*` constants | `internal/domain/workflow` | e.g. `StatusClosedWontDo`, `StatusMerged`, `StatusPROpen`, `StatusWaitingHuman`, `StatusRunning` — task-lifecycle vocabulary. |\n| `Source` + `Source*` constants | `internal/domain/workflow` | e.g. `SourceChat` — provenance vocabulary, follows `Task`. |\n| `WorkflowStore` interface (3 methods) | `internal/domain/workflow.Store` | **Consumer-owned** (dependency rule #2). Supersedes `store.WorkflowStore`. |\n\n**Resulting dependency direction (correct per the architecture):**\n\n- `internal/domain/workflow` imports **no** `internal/store` symbols → the acceptance\n criterion is satisfied. It consumes `store.Task`'s replacement as `workflow.Task`, uses\n `workflow.Status*`/`workflow.Source*`, and depends on its own `workflow.Store` interface.\n- `internal/store` imports `internal/domain/workflow` for the `Task`/`Status`/`Source` types it\n reads and writes (infrastructure → domain). **NOTE: `internal/store` is a transitional\n compatibility location only** — its long-term home is `internal/infrastructure/store` (see\n the callout in §1). Do not treat `internal/store` as the final infrastructure boundary.\n- Every store test that constructs `store.Task{…}` is updated to the relocated type as part of\n this prerequisite. This is a mechanical rename across ~6 workflow production files\n (`workflow.go`, `steps.go`, `triage.go`, `review.go`, `feasibility.go`, `implement.go`) and\n their tests plus the store tests. `TestRecordDispatchViaExplicitTx` is removed rather than\n updated — its non-nil `*sql.Tx` path has no production consumer (see §5's `RecordDispatch`\n blocker).\n\n**What this does NOT do:** it does not implement the full §4 Workflow migration\n(`mutable Stage → StepExecution history`, `RetryCount/Attempt → Attempt records`,\n`workflow.Registry → versioned Workflow definitions`, etc.). It lands only the minimal\ntask-type + `Status`/`Source` + consumer-owned-interface relocation that the Phase 2\ndomain-decoupling criterion requires. The residue of §4 remains its own migration.\n\n**Forward-compatibility:** because the wire DTOs are derived from the domain `Task`/`Status`\n(§5), when the full §4 migration later renames `workflow.Task` (or refines it into\n`WorkflowExecution`), only `values.go` and the proto field mapping change — the RPC surface and\nconsumer interfaces are unaffected. The wire contract is deliberately type-agnostic at this\nlevel.\n\n---\n\n## 5. DTO / wire representation\n\n### Proto layout\n\n- **Service:** `proto/state/v1/state.proto`, `package state.v1`, **one** `StateStore` service\n (mirrors the gateway's single `ChatService`; proto bypasses the Go `interfacebloat` cap, as\n `ChatContract` does via `//nolint:interfacebloat`).\n- **Codegen:** the existing buf v2 pipeline. `proto/buf.yaml` (module, lint STANDARD, breaking\n FILE against `main`), `proto/buf.gen.yaml` **managed mode** with\n `go_package_prefix → github.com/samcharles93/archie-core/internal/contracts`, plugins\n `protoc-gen-go` + `protoc-gen-go-grpc`, `out: ../internal/contracts`,\n `opt: paths=source_relative`. **No `go_package` in source** — managed mode owns it. Generated\n Go lands in `internal/contracts/state/v1/` (package `statev1`), committed (`proto:check`\n fails on uncommitted/unmodified generated files).\n- **Adapter package:** `internal/infrastructure/staterpc/` with `server.go` (registers the\n generated server over the store), `client.go` (wraps the generated client into `store.*` and\n `workflow.Store` facades), `values.go` (proto ⇄ domain mappers), and `conformance_test.go`\n (bufconn local-vs-grpc dual-adapter suite), mirroring `internal/infrastructure/gatewayrpc/`.\n- **Binary:** `cmd/archie-state-store/main.go`, mirroring `cmd/archie-gateway/main.go` and the\n serve pattern in `internal/app/archied/gateway.go` (`serveGateway`).\n\n### The `StateStore` RPC set (union of the contracts, grouped)\n\nMethods are named after the store methods so the mapping is unambiguous. `workflow.Store` is a\n_view_, not new RPCs — `Update`/`Transition`/`InsertEvent` are shared with\n`TaskLifecycle`/`TaskEvents` and appear once.\n\n| Group | RPCs |\n| ------------------ | -------------------------------------------------------------------------------------------------------------------------- |\n| Lifecycle | `EnqueueIssue`, `EnqueueChatTask`, `ClaimNext`, `ClaimByIssue`, `Transition`, `Update`, `Requeue`, `RecoverStale` |\n| Archive / Retry | `ArchiveTask`, `RetryTask` |\n| Queries | `TaskByIssue`, `OpenTaskByPR`, `TaskByID`, `OpenPRs`, `ClearTerminalTasks`, `Tasks`, `StatusCounts`, `IncrementRetryCount` |\n| Events | `InsertEvent`, `EventsSince`, `TaskEvents`, `WorkflowStats`, `StageStats`, `TokensByDay` |\n| Capture | `InsertCapture`, `ListCaptures` |\n| Mapping | `InsertMapping`, `GetMapping`, `ListMappings`, `UpdateMapping`, `DeleteMapping` |\n| Binding | `InsertBinding`, `GetBinding`, `ListBindings`, `UpdateBinding`, `DeleteBinding`, `ApproveBinding` |\n| Dispatch | `ArmedBindingsForSource`, `RecordDispatch`, `ListUndispatchedCaptures` |\n| Playbook | `RecordPlaybookDispatch`, `DeletePlaybookDispatches` |\n| WorkflowCaller | `EnqueueCallTask`, `WorkflowCallStatus` |\n| BindingTaskCreator | `EnqueueBindingTask` |\n| Config snapshot | `PutConfigSnapshot`, `GetConfigSnapshot` |\n| Apply status | `PutApplyStatus`, `ListApplyStatus` |\n| Channel status | `PutChannelStatus`, `ListChannelStatus` |\n| Task log | `ReadTaskLog`, `StreamTaskLogContent` |\n\nThat is **53 unique contract RPCs** across one service (the `TaskEvents.Close` method is dropped).\n`Close()` is **excluded** from the wire (it is server lifecycle, not a client call) — see §11.\n\nThe channel-status pair follows the config snapshot's split for the same reason: the writer is the process that HOSTS the channels -- the Messaging Service, which alone observes whether a channel is starting, running or failed -- and the reader is the UI process. Both RPCs are administrative, so a task-scoped grant reaches neither. A channel's state is runtime state rather than a settings document, which is why it is not a `ControlPlaneService` resource kind: a failed channel is not a document anybody edits. Asking for a reload travels on its own surface rather than through this one; see `docs/architecture/migration-decisions.md`, \"Channel state to the dashboard\".\n\nThe config-snapshot pair was added by `archie-core-ymut` (see\n`docs/architecture/migration-decisions.md`, \"Dashboard configuration page\"). It is the one\nsurface whose writer is the daemon and whose reader is the UI process, and both RPCs are\nadministrative: `authorizesTaskScopedCall` is deny-by-default, so a task-scoped grant reaches\nneither. `ConfigSnapshot.document` is opaque to this contract — the store neither parses nor\nvalidates it, and `schema` names the projection so a reader can refuse a shape it does not\nunderstand.\n\nThe apply-status pair was added by `archie-core-pskb` (see\n`docs/prds/control-plane-apply-status.md`). It is administrative for the same reason as the\nconfig-snapshot pair, and deny-by-default in `authorizesTaskScopedCall` covers it without a\nnew rule. Unlike that pair, the read is a list: `ListApplyStatus` returns every process's\nrecord and an empty slice means nothing has reported yet, so the `found=false` convention for\nabsent single rows does not apply. The rows are keyed on `(process, kind)` and replaced in\nplace, because each process re-stamps its record on an interval and no reader wants a history\nof re-stamps.\n\nThe task-log pair was added by `archie-core-iaqx` (see `docs/prds/ui-service-boundary.md`'s\nroute inventory). It is the one surface whose payload is not a row: the store service reads\nthem out of the state directory it owns with `internal/logging`'s own reader, so the wire\ncarries `logging.Entry`/`logging.Query` values and neither side restates the JSONL format.\n`ReadTaskLog` returns a decoded page and `StreamTaskLogContent` returns the raw bytes\nserver-streamed, because a log file rotates at 20 MB — past gRPC's 4 MiB unary cap — and the\nsame reasoning that made `StreamCaptures` supersede `ListCaptures` applies. `found=false` with\nno error means the attempt has no log; a service with no reader answers `Unavailable` instead,\nand the two answers are load-bearing for the dashboard: only the second is a deployment\ncondition, and the panel that collapsed them told operators task logging was switched off when\nit was not. The Go facade is `storecontract.TaskLogStore` (2 methods), carried by\n`*staterpc.Client` alongside the rest.\n\nThe workflow-caller pair was added by `archie-core-t2db.41` (see\n`docs/prds/workflow-calls.md`). It is the one surface a task-scoped grant\nreaches beyond the three task.Store RPCs: a `workflow.call` step must start\nits callee and, with `wait: true`, read it back, and the callee is the\ncaller's child. Both requests carry the caller's task ID, which the grant\ncheck verifies; `EnqueueCallTask` derives everything else from the caller's\nrow and refuses a caller that is not running or a call past the depth limit\n(`ErrCallCallerNotRunning` / `ErrCallDepthExceeded`), and `WorkflowCallStatus`\nre-checks the parent-child relation against the row before answering\n(`ErrCallNotYours`), so the interceptor itself never reads the database. The\nfacade is `workflow/task.Caller` (2 methods), carried by `*staterpc.Client`\nand the PostgreSQL store alike.\n\nThe playbook pair was added by `archie-core-t2db.17`'s implementation (see\n`docs/prds/eda-playbook-engine.md`, execution-time gap 2). It is administrative\nfor the same reason as the config-snapshot and apply-status pairs, and\ndeny-by-default in `authorizesTaskScopedCall` covers it without a new rule. The\nrow is the structural `(playbook_id, playbook_version, event_id, action_id)`\ntuple, written **before** the action's side effect fires (the reverse of\n`binding_dispatches`), so a duplicate returns `store.ErrAlreadyDispatched` and\nthe coordinator skips the invoke rather than repeating a non-revocable side\neffect. `DeletePlaybookDispatches` is the explicit reclamation primitive; nothing\ncalls it automatically, because a playbook file's absence at boot is not a\ndeliberate removal (`eda-playbook-engine.md`, \"Lifetime\"). The Go facade is\n`storecontract.PlaybookDispatcher` (2 methods), carried by `*staterpc.Client`\nalongside the rest.\n\n### Domain types and `values.go` mapping\n\n`values.go` maps proto ⇄ these types. The task model for the **agent** path is the domain-owned\n`workflow.Task` (§4); the daemon/webui store surfaces return the same `workflow.Task` (the store\npersists the domain type).\n\n| Domain type | Package | Notes for `values.go` |\n| ------------------------------------- | -------------------------- | -------------------------------------------------------------------------------------------------------------- |\n| `workflow.Task` | `internal/domain/workflow` | time fields stored as layout strings; convert to/from `google.protobuf.Timestamp` |\n| `events.Event` | `internal/events` | `Timestamp` → `google.protobuf.Timestamp` |\n| `store.CapturedEvent` | `internal/store` | headers/body/remote_addr; body capped 256 KiB |\n| `mapping.Mapping` | `internal/domain/mapping` | JSON-path field bindings |\n| `binding.Binding` | `internal/domain/binding` | secret is **already decrypted** before returning; keep decrypted form out of any durable/logged representation |\n| `workflow.Status` / `workflow.Source` | `internal/domain/workflow` | enum-like; map to proto enum or string, keeping the names stable for compatibility |\n| `store.WorkflowStat` | `internal/store` | aggregate row |\n| `store.StageStat` | `internal/store` | aggregate row |\n| `store.DayTokens` | `internal/store` | aggregate row |\n\n### Wire-contract blocker fixed here: `RecordDispatch`\n\n`store.BindingDispatcher.RecordDispatch(ctx, tx *sql.Tx, bindingID, bindingVersion int64,\ncaptureID int64, taskID int64) error` takes a **`*sql.Tx`** that cannot cross a gRPC boundary.\n\n**Evidence that the `*sql.Tx` is removable:** the dispatch loop calls `RecordDispatch(ctx, nil,\n…)` (`internal/daemon/daemon.go`). The implementation falls back to the store's own\n`*sql.DB` when `tx == nil` (\"best-effort, not atomic\"; the comment and the\n`TestRecordDispatchViaExplicitTx` test are the only consumers of the non-nil `tx` path).\nProduction never opens the explicit transaction.\n\n**Decision:** the contract drops `*sql.Tx` from `RecordDispatch` (the method becomes\n`RecordDispatch(ctx, bindingID, bindingVersion, captureID, taskID) error`). The store service\nowns any transaction boundary internally when atomicity is wanted; the at-most-once\nguarantee is the `INSERT OR IGNORE` dedup row, which is already transactionless in production.\n`TestRecordDispatchViaExplicitTx` is superseded by the store service's own internal-transaction\ntest. **This is a required interface migration that must land before or with `.4.2`** (the\ncurrent `interface.go` signature and test still use the transaction-bearing form).\n\n---\n\n## 6. Agent State Store client handoff\n\nMoving the agent from NATS `storerpc` to gRPC `workflow.Store` requires the agent process to\nreceive a State Store endpoint. The agent already receives its NATS connection settings via\nboot-time env/flags (see `cmd/archie-agent/main.go`: `-nats-url` / `NATS_URL`, `NATS_TOKEN`\nenv), and the daemon injects them into the task container. The State Store handoff follows the\nsame seam.\n\n**Boot handoff contract (additive, not replacing the NATS settings):**\n\n| Field | Where | Source | Notes |\n| ------------------ | ---------------------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |\n| `StateStoreTarget` | `agentworker.Settings` | env `STATE_STORE_URL` (or `-state-store-url` flag), set by the daemon in the container env | `host:port` of the State Store gRPC server. Loopback/Docker-bridge address — the agent reaches it the same way it reaches the daemon's NATS. |\n| `StateStoreToken` | `agentworker.Settings` | env `STATE_STORE_TOKEN` (or `-state-store-token` flag) | Per-task bearer token carried in gRPC metadata by a client interceptor (see §9). |\n| `StoreTimeout` | `agentworker.Settings` | a bounded per-call timeout | Mirrors `natsrpc.Client.Timeout` / the existing `rpcTimeout`; bounds each State Store call when the caller `ctx` has no deadline. |\n\n**Wiring change in the transport façade:**\n\n- `internal/infrastructure/agenttransport/nats.Transport` — `Store(timeout) store.WorkflowStore`\n returns `\u0026storerpc.Client{Conn: t.conn, Timeout: timeout}`. It becomes\n `Store(timeout) workflow.Store` and returns a _single long-lived_ `staterpc.Client` dialled to\n `settings.StateStoreTarget` (with the token interceptor and per-call timeout).\n- `internal/app/agentworker/worker.go` `Settings` gains the three fields above; `taskServiceTransport`\n and `taskDependencies` change their `store` type from `store.WorkflowStore` to\n `workflow.Store` (via `domain/workflow.TaskContext{Store: …}`).\n- Reconnect/deadline: `grpc.NewClient` (or the existing dial path) provides transparent reconnect;\n each RPC is bounded by the per-call context deadline (`StoreTimeout`), matching the\n request/reply timeout the NATS path used. No streaming is involved, so no server-sent\n reconnect semantics apply.\n\n**Deletion rule for the NATS path:** the NATS `storerpc` (Server, Client, subjects\n`archie.store.update|transition|insert_event`) is deleted **only after** the agent has fully\nmoved to gRPC and the container env carries `STATE_STORE_URL`. Until then both paths may coexist\n(agent flips when the daemon starts injecting `STATE_STORE_URL`); there is no dual-live window\nacross a single agent process, which is either NATS-backed or gRPC-backed, never both.\n\n### Operational specifics (in-process listener → address → per-task injection)\n\n- **Who binds the in-process State Store listener:** the daemon (`archied`), at bootstrap, when\n the State Store is served in-process/multiplexed (mirroring `serveGateway` in\n `internal/app/archied/gateway.go`): a `grpc.NewServer()` + `RegisterServer` + graceful stop on\n `ctx.Done()`.\n- **Address selection (Docker-bridge reachable):** reuse the host-gateway resolution already used\n for embedded NATS (`internal/container/network.go` `RequireHostGateway` /\n `resolveHostGateway`). Per §9's single listener-topology rule, the listener binds the\n **host-gateway bridge address** when agent containers consume it (the Phase 2 default), or\n loopback-only when the daemon is the sole consumer. The chosen address is stored on the daemon\n as `d.ConnectedStateStore.URL` (analogous to `d.ConnectedNATS.URL`).\n- **Per-task injection:** `containerEnv(task)` (`internal/daemon/daemon.go`) appends\n `STATE_STORE_URL=\u003cd.ConnectedStateStore.URL\u003e` and `STATE_STORE_TOKEN=\u003ctoken\u003e` alongside the\n existing `NATS_URL`/`NATS_TOKEN`. The agent reads them via env (`-state-store-url` /\n `STATE_STORE_URL`, `-state-store-token` / `STATE_STORE_TOKEN`), the same seam as `NATS_URL`. A\n reloaded `[services.state]` must not point new containers at a store the daemon is not serving\n — the same immutability rule as NATS.\n\n---\n\n## 7. Error semantics\n\n### Current state (both boundaries lose error identity)\n\n- **NATS `natsrpc.Envelope`** (`internal/natsrpc/natsrpc.go`) serialises any error to a single\n `err.Error()` string and rehydrates a fresh `errors.New(string)`. The original type, `%w`\n chain, and sentinel identity are lost → `errors.Is(err, store.ErrStaleTransition)` is\n **false** across the boundary.\n- **gRPC `gatewayrpc`** returns raw `err` from handlers; gRPC-Go converts to\n `codes.Unknown` with only the message. The **only** explicit code in the repo is\n `codes.Unavailable` for a missing session store (`server.go`). No status-code mapping for\n store errors exists.\n\n### Decision — structured mapping so `errors.Is` survives\n\nThe `StateStore` service must map the store's sentinel errors to canonical gRPC codes and\nrehydrate them to the _same_ sentinels on the client, so consumer `errors.Is` checks keep\nworking — an improvement over the flattening it replaces, not a regression.\n\n| Store sentinel / outcome | gRPC code | Client rehydrates to |\n| ------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------- |\n| `store.ErrStaleTransition` | `FailedPrecondition` | `store.ErrStaleTransition` |\n| `store.ErrBindingNotFound` | `NotFound` | `store.ErrBindingNotFound` |\n| `store.ErrMappingNotFound` | `NotFound` | `store.ErrMappingNotFound` |\n| `store.ErrBindingOverlap` | `FailedPrecondition` | `store.ErrBindingOverlap` |\n| `store.ErrBindingTransition` | `FailedPrecondition` | `store.ErrBindingTransition` |\n| `store.ErrAlreadyDispatched` | `AlreadyExists` | `store.ErrAlreadyDispatched` |\n| not-found-as-`(nil,nil)` (`TaskByID`, `GetBinding`, `GetMapping`, `ClaimNext`, `ClaimByIssue`, …) | `NotFound` with a `found=false` field (**not** an error) | `(nil, nil)` |\n| infra / wrapped error | `Internal` (**sanitised** message, see below) | wrapped `fmt.Errorf(...%w)` |\n| capability absent | `Unavailable` | context/typed error |\n\nThe `found=false`-not-error convention matters: the repo deliberately returns `(nil, nil)` for\nnot-found in reads and a sentinel for not-found in writes. The wire must preserve **both**\nconventions (a `GoogleRPCStatus` with `NotFound` is an _error_, which would wrongly surface to\ncallers that expect `(nil, nil)`). Implement `found` as an explicit boolean field on read\nresponses, and map `(nil,nil)` ⇄ `found=false` + `OK`.\n\n### Error-detail sanitisation (rev. 2c)\n\nFull internal error messages must **not** be placed in gRPC `details` for remote callers. SQL\npaths, provider/forge details, secrets, and stack traces are sensitive internals. The rule:\n\n- **Sentinel errors** — the client rehydrates the sentinel from the code; the message string in\n `status.Error` is a short, public, stable phrase (e.g. `\"stale transition\"`), not the raw\n wrapped chain.\n- **Infra errors** — the wire carries a **sanitised** public message + the `Internal` code.\n The **full** error (with `%w` chain, SQL, provider detail) is logged **server-side only** by\n the store service. The client rehydrates a generic wrapped error and must not surface the raw\n text to users.\n\n---\n\n## 8. Limits\n\n**Interface bloat (`interfacebloat` cap = 8)** — `.golangci.yml` `interfacebloat: max: 8`,\nwhich overrides the upstream default of 10. The Go consumer facades must stay ≤8 methods.\n`TaskLifecycle` is exactly 8 (at the cap); `TaskStore` is the 24-method composite that the cap\nis why it is decomposed; proto services bypass the cap (like `ChatContract`).\n\n**Payload caps:**\n\n- Capture body: `defaultCaptureMaxBodyBytes = 256 KiB` (may reduce further; the wire message\n must not exceed gRPC's default 4 MiB receive limit for a single capture). A single capture\n fits, but a _batch_ of them did not: the caller-side cap of up to 100 captures at 256 KiB each\n could exceed 4 MiB in one unary `ListCaptures`/`ListUndispatchedCaptures` response. `.4.7` adds\n `StreamCaptures`/`StreamUndispatchedCaptures` (server-streaming, one capture per message) as\n the path both `staterpc.Client` methods actually call; the original unary RPCs stay defined,\n unmodified and deprecated, only so `buf breaking` protects an in-flight rolling deploy.\n- Task `detail`/`park_reason`/event `Detail`: 4000-char hard cap (`clip(s, 4000)`).\n\n**Retention (stays server-side in the store; the wire does not carry pruning decisions):**\n\n- `events` table: **no prune, unbounded growth** — a known risk to revisit, not changed here.\n- `captured_events`: prune-on-write, default 7 days / 5000 events.\n\n**Pagination/arity:** store read methods take a raw `int limit` (no store-side cap); the\ncaller-side caps (task list 100, log 2000, captures 100, capture scan window 5000, binding\ndispatch batch 100, session list 20) remain caller-side. The wire passes `limit int` and returns\n`[]*` slices, mirroring the existing Go signatures — **no cursor/paging protocol is introduced**\nin this work (the current `EventsSince(sinceID, limit)` offset cursor is the only one, and it\nstays as-is).\n\n---\n\n## 9. Transport security boundary\n\nThe gateway precedent is loopback-only, unauthenticated gRPC. The State Store holds the\ncrown-jewel `archie.db` (task/event/capture/mapping/binding data), so its boundary must be\nstated explicitly rather than left implicit.\n\n**The State Store's equivalent boundary (rev. 2c):**\n\n- **Listener topology — single rule (rev. 2c).** One in-process listener; its bind address is\n chosen by the consumer set, never both at once:\n - _Agent containers consume it_ (the Phase 2 driver during multiplexed serving) → bind to the\n **host-gateway bridge address** so containers can reach it, and **token auth is mandatory**\n (a bridge host is reachable by any process on that bridge). A container **cannot reach the\n host's `127.0.0.1`**, so loopback-only is NOT usable for the agent-consumed path.\n - _Only the daemon consumes it_ (no agent) → bind **loopback-only** (`--listen 127.0.0.1`),\n `insecure` is fine because it is not network-reachable; no token required.\n - There is **no dual-listener** design. The practical default during `.4.2` (the reason\n in-process serving exists is to give the agent a gRPC target) is the **bridge address +\n token**. `127.0.0.1` is reserved for the daemon-local-only case.\n- **Agent access → the container bridge.** The agent runs in a task-scoped container on the\n host and reaches the State Store over the Docker bridge gateway (the bind address from the\n topology rule above), exactly as it reaches the daemon's NATS. To close the \"any host\n process could reach the store\" gap, the agent **authenticates with a per-task bearer token**\n carried in gRPC metadata by a client interceptor (`StateStoreToken`, §6). Network\n reachability + the token is the trust boundary for the default bridge topology.\n- **The daemon** uses the local adapter (`*store.Store`) in-process by default, so no network\n boundary exists until `[services.state].target` is set; when it is set, the daemon client\n authenticates with a token supplied alongside the target.\n- **Non-loopback / k8s:** TLS/mTLS is an **operator decision**, not a default. Any non-loopback\n exposure (e.g. `--listen 0.0.0.0`, a CDN, a cross-host service) requires an explicit decision\n and mTLS or token auth — mirroring the gateway's `--listen`/`--enable-cors-header`\n confirmation caveat. The NATS-KV discovery fallback supplies endpoints but does not add\n transport security; that stays the operator's responsibility.\n\n### Token lifecycle (rev. 2c; scoping added in `.4.7`)\n\n- **Generation:** the daemon generates a per-task bearer token when it acquires the container\n (or per incumbence) and injects it via `containerEnv` as `STATE_STORE_TOKEN`. A single token\n may cover a task's container lifetime.\n- **Registration (`.4.7`, post-standalone-cutover):** the State Store is now its own process\n (`.4.3`/`.4.6`), so the daemon can no longer just hold an in-process issued-token set for the\n server to check — it registers the token at the remote authority via the\n `RegisterTaskGrant`/`RevokeTaskGrant` RPCs (`staterpc.GrantIssuer`, `daemon.StateStoreGrantIssuer`),\n admin-token-authenticated calls a task-scoped token itself can never make.\n- **Lifetime:** tied to the task + container grace period; rotated on a new container acquisition\n for the same task; a token for a released container is invalidated (`RevokeTaskGrant`, deferred\n alongside `ContainerPool.Release`). An unrevoked grant still expires server-side (bounded by\n `RegisterTaskGrantRequest.lifetime_seconds`, capped at 7 days) so a daemon crash before revoke\n cannot leave a grant valid indefinitely.\n- **Validation and scope (`.4.7`):** a gRPC interceptor (`staterpc.TaskGrants.UnaryInterceptor`)\n validates the token against the State Store's own issued-grant set; missing/unknown/expired →\n `codes.Unauthenticated`. Unlike the daemon's own administrative token (full access to all RPCs),\n a task-scoped grant additionally authorises only `Update`/`Transition`/`InsertEvent` on\n its own task ID, plus the two workflow-caller RPCs naming that same task ID\n (`EnqueueCallTask`/`WorkflowCallStatus`, `docs/prds/workflow-calls.md` — the one\n sanctioned widening: the callee is the caller's child). Every other RPC, including the\n streaming capture surface and\n `RegisterTaskGrant`/`RevokeTaskGrant` themselves, is `codes.PermissionDenied` for a task-scoped\n caller. The token is carried in gRPC metadata, never in a URL.\n\n### Fail-closed on non-loopback (rev. 2c)\n\nIf `[services.state].target` points to a non-loopback address and **neither** TLS **nor** a token\nis configured, the State Store client (daemon or agent) **fails closed** — it refuses to\nstart/dial rather than fall back to a plaintext, unauthenticated remote connection. This mirrors\nthe gateway's `--listen`/`--enable-cors-header` confinement caveat and prevents a silent\nunauthenticated remote store. The loopback + token default is the only path that starts without\nan explicit operator decision.\n\n---\n\n## 10. Mode / config shape\n\n**Follow the gateway's presence-based `target` seam, not the NATS `mode` enum.**\n\n- **Services are keyed by name, not named as struct fields.** A\n `State ServiceConnection` field per service is the duplication\n `docs/prds/service-registry.md` removes, and this document's summary describes\n the seam as `[services.\u003cname\u003e]`:\n ```go\n type Services map[string]ServiceConnection\n ```\n registered once via `RegisterService(context, name, target, listen, tokenEnv)`. The TOML\n shape below is unchanged, so nothing else in this section is affected; read\n `cfg.Services.Get(\"state\")` wherever it says `cfg.Services.State`.\n- **Empty `Target` → startup error.** The local `*store.Store` adapter default was\n withdrawn when the State Store was extracted (§12 step 7): the standalone `archie-state-store` process\n exclusively owns `archie.db`, so both `archied` and `archie-gateway` now reject an empty\n target (`internal/app/archied/bootstrap.go` and `state_store_client.go`: `services.state.target\nis required`). **Set `Target` → dial gRPC** with `*staterpc.Client`; no client opens the\n database itself. This differs from the gateway, where `Target` is defaulted to\n `127.0.0.1:8585` because `archie-gateway` is already a separate process whose client and\n server share one default.\n- `[services.state]` is present and **uncommented** in `config.example.toml`, with `target`\n marked REQUIRED, because the value is load-bearing for every client. A commented-out\n `target` cannot boot, so the section ships uncommented.\n- Composition root: `internal/app/archied/bootstrap.go` (the daemon) and\n `internal/app/archieui/config.go` (the UI process) both read `cfg.Services.Get(\"state\")` and\n dial the remote State Store. The task store is built only in the standalone\n `archie-state-store` process (`internal/app/archied/state_store.go`), which is the only path\n that opens the task tables.\n\n\u003e **Mode fork, decided.** The gateway uses a single `target` address (no enum). The State Store\n\u003e boundary uses the same seam for symmetry, and **both now require a non-empty `target`**: the\n\u003e State Store's local-store default was withdrawn when the process was extracted (§12 step 7).\n\u003e No `mode` field is added. A companion `STATE_STORE_TOKEN` secret (or a\n\u003e `[services.state] target_token` key) carries authentication.\n\n---\n\n## 11. Local-adapter compatibility + conformance\n\n- `*store.Store` (local) and `*staterpc.Client` (remote) satisfy the **same** contract\n interfaces. Use **explicit** `var _` assertions on **both** adapters (the gateway's local\n adapters use only structural/return-type assertions; the store precedent's explicit `var _`\n style is stronger and should be adopted on both sides).\n ```go\n var _ workflow.Store = (*staterpc.Client)(nil) // first contract to move (agent)\n var _ store.TaskStore = (*staterpc.Client)(nil) // daemon path, added progressively\n var _ store.CaptureStore = (*staterpc.Client)(nil)\n var _ store.MappingStore = (*staterpc.Client)(nil)\n var _ store.BindingStore = (*staterpc.Client)(nil)\n var _ store.BindingDispatcher = (*staterpc.Client)(nil)\n var _ store.BindingTaskCreator = (*staterpc.Client)(nil)\n var _ store.PlaybookDispatcher = (*staterpc.Client)(nil)\n // local side (in store), already present:\n var _ workflow.Store = (*Store)(nil)\n ```\n- **Conformance suite:** a `staterpc/conformance_test.go` bufconn suite runs the **same**\n contract through both `\"local\"` and `\"grpc\"` adapters (mirroring\n `gatewayrpc/conformance_test.go`), asserting error-sentinel fidelity and the\n not-found-as-`(nil,nil)` convention both ways.\n- **`Close()`:** stays on the Go store interfaces (so `TaskStore`/`TaskEvents` remain fully\n satisfiable) but is **not** a `StateStore` RPC. The remote `staterpc.Client` implements\n `Close()` as a **no-op**; the store service owns its own DB lifecycle. When the daemon hands\n the store to `archie-state-store`, `b.cleanup()` no longer calls `store.Close()` on a remote\n client (it is the daemon's own lifecycle only when it owns the store in-process).\n\n---\n\n## 12. Cutover / deletion rules\n\n1. **Ratify the contract (this document).** No code.\n2. **Domain type + interface relocation (prerequisite, coupled with §4).** Move `Task`/`Status`/\n `Source` and the `WorkflowStore` interface into `internal/domain/workflow` (as\n `workflow.Task`/`workflow.Status`/`workflow.Source`/`workflow.Store`), so\n `internal/domain/workflow` imports no `internal/store`. Update the store tests and the 6\n workflow production files. **This must land before or with `.4.2`, because `.4.2` cannot move\n the agent's store contract off `store.WorkflowStore` while the domain still imports it.**\n3. **`.4.2` — generalise `storerpc` to the gRPC contract.** Move the agent's `workflow.Store`\n (`Update`/`Transition`/`InsertEvent`) from NATS JSON `storerpc` to `staterpc.Client` over\n gRPC, using the §6 handoff. The daemon serves the gRPC `StateStore` server **in-process\n (multiplexed)** first so the agent has a gRPC target before the standalone binary exists\n (PRD §3 \"multiplexed in-process is the migration default\"). Bind the in-process listener and\n inject `STATE_STORE_URL`/`STATE_STORE_TOKEN` per task (see §6 \"Operational specifics\"). Also\n land the `RecordDispatch` `*sql.Tx` drop (see §5) in the same span. Flip the agent's\n `Transport.Store` to a gRPC client once `STATE_STORE_URL` is injected.\n4. **Delete NATS `storerpc` only after the agent is fully on gRPC** — delete `internal/storerpc`\n (Server, Client, subjects `archie.store.update|transition|insert_event`), the\n `natsrpc.RegisterAll` registration, and the now-unused `store.WorkflowStore` NATS path in\n `internal/infrastructure/agenttransport/nats`, in the same commit.\n5. **`[services.state].target` stays empty (inproc)** through `.4.2`; the `archie-state-store`\n `cmd/` binary is **`.4.3`** and hosts the same `StateStore` gRPC service.\n6. **Swap daemon-internal contracts one at a time** (only once the daemon points at\n `archie-state-store`): `Capture → Mapping → Binding → TaskStore`. Each swap is independent —\n add the remote-client composition path, run the per-contract conformance suite, flip\n `[services.state].target`, delete the local use. A consumer mixes in-process and remote\n contracts for a contract-code (no dual-live _window_; each contract is either local or remote\n at a time).\n7. **Final flip / deletion of the in-process serving path:** when the daemon no longer owns the\n store (i.e. `TaskStore` has moved), delete the in-process task-store /\n `wireWebStoreSurfaces` path in the daemon in a **same-commit** deletion — no dual-store\n ownership. The single SQLite file remains owned by `archie-state-store`.\n8. **Never** split `archie.db` or add a second store. The gateway keeps its own already-separate\n session SQLite; that is unchanged and out of state-store scope.\n\n---\n\n## 13. Decisions recorded (for the review trail)\n\n- **`internal/store` is a transitional compatibility location** (target\n `internal/infrastructure/store`), not the final infrastructure boundary. The producer-owned\n daemon/webui store surfaces live there now but may relocate with the implementation.\n- **In-process listener + token lifecycle:** the daemon binds the in-process State Store\n listener to the **host-gateway bridge address** when agent containers consume it (the Phase 2\n default) or loopback-only when the daemon is the sole consumer — one listener, one address\n rule, never both (rev. 2c). It selects the bridge address by reusing the embedded-NATS\n host-gateway resolution and injects `STATE_STORE_URL`/`STATE_STORE_TOKEN` per task via\n `containerEnv`. Token is per-incumbence (task + container grace period) and validated by a\n gRPC interceptor → `codes.Unauthenticated` on missing/unknown/expired. Non-loopback targets\n fail closed without TLS or a token.\n- **§12 step 2 (domain type + interface relocation) is done** — `internal/domain/workflow`\n imports no `internal/store` symbol and `store.WorkflowStore` is gone from `TaskContext`. The\n broader Phase 2 acceptance criterion (State Store as its own gRPC service) is still open;\n `.4.2` picks up from here.\n- **Ownership split:** domain-facing workflow contract is **consumer-owned** in the domain\n (`workflow.Store` + `workflow.Task`/`Status`/`Source`, per dependency rules #2 and #7);\n daemon/webui store surfaces stay **producer-owned** in `internal/store`. `store.WorkflowStore`\n is superseded by `workflow.Store`.\n- **One `StateStore` gRPC service** (49 contract RPCs, grouped by contract) + narrow Go consumer facades\n (≤8) on `staterpc.Client` — mirrors the single-`ChatService` precedent.\n- **Domain type relocation** (`Task`/`Status`/`Source` → `internal/domain/workflow`) is a\n Phase 2 prerequisite, pulled forward from migration-decisions §4 (minimal bound,\n `Task → WorkflowExecution`); the rest of §4 stays a separate migration.\n- **`RecordDispatch` drops `*sql.Tx`** (wire-blocker; production passes `nil`) — a\n required interface migration landing before/with `.4.2`.\n- **`Close()` not on the wire**; remote client `Close()` is a no-op.\n- **Structured gRPC error codes** with client rehydration to store sentinels (preserves\n `errors.Is`), a `found=false` + `OK` convention for read not-found, and **sanitised public\n error details** (full detail logged server-side only).\n- **Agent handoff:** `agentworker.Settings` gains `StateStoreTarget`/`StateStoreToken`/\n `StoreTimeout`, injected as `STATE_STORE_URL`/`STATE_STORE_TOKEN` env (mirrors the NATS\n handoff); `Transport.Store` returns a long-lived gRPC `workflow.Store` client.\n- **Transport security + listener topology (rev. 2c):** one in-process listener, bound to the\n host-gateway bridge address when agent containers consume it (the Phase 2 default) or\n loopback-only for a daemon-local-only consumer. `insecure` only on loopback; mandatory\n per-task bearer-token auth on the bridge; TLS/mTLS is an operator choice for any\n non-loopback/k8s topology.\n- **Mode = presence-based `[services.state].target`**, default **local** (not yet extracted);\n add `[services.state]` to `config.example.toml`.\n- **Explicit `var _` assertions on both adapters**; per-contract bufconn conformance.\n- **Migration order:** domain type/interface relocation → `workflow.Store` (agent) → stand up\n `archie-state-store` → `Capture` → `Mapping` → `Binding` → `TaskStore`; NATS `storerpc`\n deleted once the agent is on gRPC; in-process store path deleted in a same-commit flip.\n- **Orphans `ClearTerminalTasks`/`IncrementRetryCount`** retained but not built upon.\n" }, { "url": "/dev/prds/status-health-surface/", @@ -533,6 +533,12 @@ "title": "Webhook intake security -- decision", "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 dashboard operator -- the same authorisation boundary as every\nother webui surface, not a separate or lower bar.\n\n## What this does not decide\n\nThe intake family's registration interface (`7d5u.3`), the capture storage\nmechanism (`7d5u.2`, embedded NATS), and the binding data model's persistence\nand versioning (`t2db.4`) are separate decisions. This document constrains\nall three: whatever they build must satisfy points 1-5 above.\n" + }, + { + "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 `call_parent_task_id` (bigint, default 0) and\n`call_depth` (int, default 0); both cross the wire on the `Task` message.\nColumns default so existing writers and rows read as depth-0 root runs.\n\n**The engine capability.** The workflow domain owns a consumer facade,\n`task.Caller` (2 methods), carried by `*staterpc.Client` and wired into\n`TaskContext.Calls` by the agent worker's composition root — the same shape\nas `workflow.Store`. A runner with no `Calls` capability fails a\n`workflow.call` step with a named error rather than pretending.\n\n**Semantics.**\n\n- `wait: false` — start, record a durable `workflow_call_started` event, and\n continue. The callee's outcome is reported on its own run.\n- `wait: true` — start, then poll `WorkflowCallStatus` (2 s, bounded by the\n task's wall clock) until the callee is terminal. `completed`, `pr_open` and\n `merged` succeed the step; `parked`, `failed`, `rejected`, `dead` and\n `closed_wont_do` fail it with the callee's detail in the error. A durable\n `workflow_call_finished` event carries the terminal status and detail.\n- The caller's own stage/attempt accounting is unchanged: the call is one\n stage that took as long as its callee.\n- A callee inherits the caller's task record but is otherwise independent:\n retry, park and cancel of the callee never rewrite the caller. Cancelling a\n caller cancels its callees through the operator action on each\n (`execution-tree-state-machine.md` \"Cancellation\"); until the tree state\n machine lands, a caller cancelled while waiting fails its stage and leaves\n the callee running — the same semantics as `wait: false`.\n\n## What is deliberately not here\n\n- **Declared outputs.** `wait: true` receives the callee's terminal detail,\n not structured outputs; the outputs model is its own bead.\n- **The StepExecution tree.** The `call` kind is designed for in\n `execution-tree-state-machine.md`; this design lands the behaviour without\n the per-step records.\n- **Per-org enablement** — bead `archie-core-t2db.42`'s catalogue is the\n source once it exists." } ], "nav": [ @@ -898,6 +904,10 @@ { "title": "Webhook intake security -- decision", "url": "/dev/prds/webhook-intake-security/" + }, + { + "title": "Workflows calling workflows", + "url": "/dev/prds/workflow-calls/" } ] } diff --git a/docs/prds/state-store-contract.md b/docs/prds/state-store-contract.md index 50f6b518a..55e53d565 100644 --- a/docs/prds/state-store-contract.md +++ b/docs/prds/state-store-contract.md @@ -265,13 +265,14 @@ _view_, not new RPCs — `Update`/`Transition`/`InsertEvent` are shared with | Binding | `InsertBinding`, `GetBinding`, `ListBindings`, `UpdateBinding`, `DeleteBinding`, `ApproveBinding` | | Dispatch | `ArmedBindingsForSource`, `RecordDispatch`, `ListUndispatchedCaptures` | | Playbook | `RecordPlaybookDispatch`, `DeletePlaybookDispatches` | +| WorkflowCaller | `EnqueueCallTask`, `WorkflowCallStatus` | | BindingTaskCreator | `EnqueueBindingTask` | | Config snapshot | `PutConfigSnapshot`, `GetConfigSnapshot` | | Apply status | `PutApplyStatus`, `ListApplyStatus` | | Channel status | `PutChannelStatus`, `ListChannelStatus` | | Task log | `ReadTaskLog`, `StreamTaskLogContent` | -That is **51 unique contract RPCs** across one service (the `TaskEvents.Close` method is dropped). +That is **53 unique contract RPCs** across one service (the `TaskEvents.Close` method is dropped). `Close()` is **excluded** from the wire (it is server lifecycle, not a client call) — see §11. The channel-status pair follows the config snapshot's split for the same reason: the writer is the process that HOSTS the channels -- the Messaging Service, which alone observes whether a channel is starting, running or failed -- and the reader is the UI process. Both RPCs are administrative, so a task-scoped grant reaches neither. A channel's state is runtime state rather than a settings document, which is why it is not a `ControlPlaneService` resource kind: a failed channel is not a document anybody edits. Asking for a reload travels on its own surface rather than through this one; see `docs/architecture/migration-decisions.md`, "Channel state to the dashboard". @@ -306,6 +307,19 @@ condition, and the panel that collapsed them told operators task logging was swi it was not. The Go facade is `storecontract.TaskLogStore` (2 methods), carried by `*staterpc.Client` alongside the rest. +The workflow-caller pair was added by `archie-core-t2db.41` (see +`docs/prds/workflow-calls.md`). It is the one surface a task-scoped grant +reaches beyond the three task.Store RPCs: a `workflow.call` step must start +its callee and, with `wait: true`, read it back, and the callee is the +caller's child. Both requests carry the caller's task ID, which the grant +check verifies; `EnqueueCallTask` derives everything else from the caller's +row and refuses a caller that is not running or a call past the depth limit +(`ErrCallCallerNotRunning` / `ErrCallDepthExceeded`), and `WorkflowCallStatus` +re-checks the parent-child relation against the row before answering +(`ErrCallNotYours`), so the interceptor itself never reads the database. The +facade is `workflow/task.Caller` (2 methods), carried by `*staterpc.Client` +and the PostgreSQL store alike. + The playbook pair was added by `archie-core-t2db.17`'s implementation (see `docs/prds/eda-playbook-engine.md`, execution-time gap 2). It is administrative for the same reason as the config-snapshot and apply-status pairs, and @@ -551,9 +565,12 @@ stated explicitly rather than left implicit. cannot leave a grant valid indefinitely. - **Validation and scope (`.4.7`):** a gRPC interceptor (`staterpc.TaskGrants.UnaryInterceptor`) validates the token against the State Store's own issued-grant set; missing/unknown/expired → - `codes.Unauthenticated`. Unlike the daemon's own administrative token (full access to all ~40 - RPCs), a task-scoped grant additionally authorises only `Update`/`Transition`/`InsertEvent` on - its own task ID — every other RPC, including the streaming capture surface and + `codes.Unauthenticated`. Unlike the daemon's own administrative token (full access to all RPCs), + a task-scoped grant additionally authorises only `Update`/`Transition`/`InsertEvent` on + its own task ID, plus the two workflow-caller RPCs naming that same task ID + (`EnqueueCallTask`/`WorkflowCallStatus`, `docs/prds/workflow-calls.md` — the one + sanctioned widening: the callee is the caller's child). Every other RPC, including the + streaming capture surface and `RegisterTaskGrant`/`RevokeTaskGrant` themselves, is `codes.PermissionDenied` for a task-scoped caller. The token is carried in gRPC metadata, never in a URL. diff --git a/docs/prds/workflow-calls.md b/docs/prds/workflow-calls.md new file mode 100644 index 000000000..bf0301ec3 --- /dev/null +++ b/docs/prds/workflow-calls.md @@ -0,0 +1,128 @@ +# Workflows calling workflows + +**Status:** Draft +**Date:** 2026-09-26 +**Bead:** `archie-core-t2db.41` +**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) + +## The call, end to end + +``` +caller run (in agent container) + workflow.call step ──StartCall──▶ State Store EnqueueCallTask(caller, workflow, inputs) + │ callee task row: org/identity/owner/repo + │ derived from the caller row server-side + ▼ + callee task (queued, org of the caller) + │ daemon claims, pins the callee's OWN + │ definition → its OWN agent profile + ▼ + callee run (its own container, own tree) + wait: true ──poll──▶ State Store WorkflowCallStatus(caller, callee) + wait: false ──continue +``` + +A `workflow.call` step starts the callee as a first-class task and, with +`wait: true`, waits for its terminal state. The callee is never run "inside" +the caller: it gets its own task row, its own pinned definition, its own +profile, its own container, and its own outcome on its own run +(`execution-tree-state-machine.md`). + +## Save-time checks (the collection is the authority) + +All semantic checks run in `workflow.ValidateDefinitionCollection`, the gate +every save and load of the `workflow-definitions` resource passes through. +A single-definition parse cannot see callees, so it validates shape only. + +- **Callee exists.** A call to a workflow outside the collection is refused. +- **Inputs checked.** A call value is a literal or a reference + (`inputs.`) to the calling workflow's declared input. References must + name a declared input; the resolved type must satisfy the callee's declared + type; unknown callee inputs are refused; a required callee input must be + assigned. +- **Self-calls refused.** The call graph over the collection is walked from + every workflow; a workflow that reaches itself, directly or through other + workflows, is refused with the cycle path. (Cycles can otherwise deadlock: + `wait: true` callers hold their containers.) +- **Repository.** `workflow.call` needs no repository, so it is legal in a + `repository: none` workflow: the callee inherits the caller's task record + (owner/repo/identity/org), and the callee's own `repository` mode decides + whether its run clones. +- **Org enablement** (bead `archie-core-t2db.42`): the single + instance-wide collection the current model serves is what "enabled for + the caller's org" resolves against — an undefined callee parks. The + callee's org is derived from the caller's row, so a callee is never + visible outside its caller's org. The per-org enable/disable catalogue + lands with `archie-core-t2db.42` and becomes the one source of this + predicate. + +## Runtime + +**Depth limit.** `workflow.MaxCallDepth` (5). The calling stage refuses a call +that would exceed it; the store re-checks on insert (callee depth = caller +depth + 1), so no path can enqueue past the limit. + +**Starting the callee.** The caller runs inside a container whose task-scoped +State Store grant authorizes only `Update`/`Transition`/`InsertEvent` on its +own task — it can neither enqueue a task nor read another one. One new +contract RPC starts the callee: + +- `EnqueueCallTask(caller_task_id, workflow, inputs_json) → task` + — the store reads the caller row, refuses a caller that is not `running`, + refuses past the depth limit, and inserts the callee row deriving org, + workspace, identity, owner, repo and a fresh synthetic issue number from + the caller (the same org COALESCE `EnqueueIssue`/`InsertChatTask` use). The + callee row carries `call_parent_task_id` and `call_depth`. + +**Waiting on the callee.** One new read RPC returns a call's callee: + +- `WorkflowCallStatus(caller_task_id, call_task_id) → (status, detail)` — the + handler verifies `call_parent_task_id` matches, so a caller reads only its + own callees, and returns the callee's status plus its latest transition + detail (the callee's summary — the wait:true "outputs" until a structured + outputs model lands). + +Both RPCs are admitted to task-scoped grants on `caller_task_id == granted +task ID` (`authorizesTaskScopedCall` gains two request-shape cases). This is +the one sanctioned widening of a task grant: the callee is the caller's child, +and starting it is the mechanism by which one event becomes several runs. The +widenings stay request-shape checks; the parent-child authorization is a +handler-side row check, so the interceptor never reads the database. + +**Schema.** `tasks` gains `call_parent_task_id` (bigint, default 0) and +`call_depth` (int, default 0); both cross the wire on the `Task` message. +Columns default so existing writers and rows read as depth-0 root runs. + +**The engine capability.** The workflow domain owns a consumer facade, +`task.Caller` (2 methods), carried by `*staterpc.Client` and wired into +`TaskContext.Calls` by the agent worker's composition root — the same shape +as `workflow.Store`. A runner with no `Calls` capability fails a +`workflow.call` step with a named error rather than pretending. + +**Semantics.** + +- `wait: false` — start, record a durable `workflow_call_started` event, and + continue. The callee's outcome is reported on its own run. +- `wait: true` — start, then poll `WorkflowCallStatus` (2 s, bounded by the + task's wall clock) until the callee is terminal. `completed`, `pr_open` and + `merged` succeed the step; `parked`, `failed`, `rejected`, `dead` and + `closed_wont_do` fail it with the callee's detail in the error. A durable + `workflow_call_finished` event carries the terminal status and detail. +- The caller's own stage/attempt accounting is unchanged: the call is one + stage that took as long as its callee. +- A callee inherits the caller's task record but is otherwise independent: + retry, park and cancel of the callee never rewrite the caller. Cancelling a + caller cancels its callees through the operator action on each + (`execution-tree-state-machine.md` "Cancellation"); until the tree state + machine lands, a caller cancelled while waiting fails its stage and leaves + the callee running — the same semantics as `wait: false`. + +## What is deliberately not here + +- **Declared outputs.** `wait: true` receives the callee's terminal detail, + not structured outputs; the outputs model is its own bead. +- **The StepExecution tree.** The `call` kind is designed for in + `execution-tree-state-machine.md`; this design lands the behaviour without + the per-step records. +- **Per-org enablement** — bead `archie-core-t2db.42`'s catalogue is the + source once it exists. \ No newline at end of file diff --git a/internal/app/agentworker/task_execution.go b/internal/app/agentworker/task_execution.go index 2f348d5e9..afee06abf 100644 --- a/internal/app/agentworker/task_execution.go +++ b/internal/app/agentworker/task_execution.go @@ -183,6 +183,7 @@ func worktreeOwnerID(env string) int { type taskDependencies struct { forge workflow.Forger store workflow.Store + calls task.Caller trees remoteTrees events agentexec.EventPublisher // steps is the workflow step vocabulary pinned definitions are compiled @@ -314,6 +315,7 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen Cfg: req.Cfg.ToConfig(), Forge: dependencies.forge, Store: dependencies.store, + Calls: dependencies.calls, Trees: trees, Agent: agent, Reviewer: reviewer, diff --git a/internal/app/agentworker/task_execution_test.go b/internal/app/agentworker/task_execution_test.go index 22b2b5502..b72e8da2f 100644 --- a/internal/app/agentworker/task_execution_test.go +++ b/internal/app/agentworker/task_execution_test.go @@ -382,7 +382,7 @@ func startStateStoreGRPC(t *testing.T, local *pgstore.TaskDB) string { eda := pgstore.EDA(t, nil) staterpc.RegisterServer(server, staterpc.Deps{ Tasks: local, Captures: eda, Mappings: eda, Bindings: eda, - BindingDispatcher: eda, BindingTaskCreator: local, + BindingDispatcher: eda, BindingTaskCreator: local, WorkflowCalls: local, }) go func() { _ = server.Serve(listener) }() t.Cleanup(func() { server.Stop(); _ = listener.Close() }) diff --git a/internal/app/agentworker/task_execution_workflow_call_test.go b/internal/app/agentworker/task_execution_workflow_call_test.go new file mode 100644 index 000000000..2dc197ebc --- /dev/null +++ b/internal/app/agentworker/task_execution_workflow_call_test.go @@ -0,0 +1,149 @@ +package agentworker + +import ( + "context" + "log/slog" + "testing" + + "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/org" + "github.com/samcharles93/archie-core/internal/domain/workflow" + workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task" + agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats" + "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore" + "github.com/samcharles93/archie-core/internal/taskrun" +) + +// stubRunner is the agent runner that lets a test workflow end in an +// agent.run tail without an LLM: the call step under test needs no agent, +// but the workflow must still end with an outcome. +type stubRunner struct{} + +func (stubRunner) Run(_ context.Context, _ string, req agentexec.Request, _ agentexec.ToolCallReporter) (agentexec.Result, error) { + return agentexec.Result{ + Version: agentexec.ProtocolVersion, TaskID: req.TaskID, Attempt: req.Attempt, + Stage: req.Stage, Status: agentexec.StatusPassed, Summary: "reported", + }, nil +} + +// fakeScratchTrees is the Trees for a scratch task: the workspace already +// exists (the call step needs none, the agent.run tail works in it), and +// nothing publishes. +type fakeScratchTrees struct { + dir string +} + +func (f *fakeScratchTrees) Prepare(context.Context, string, string, string, int, string, string, string) (string, string, error) { + return f.dir, "", nil +} + +func (*fakeScratchTrees) CommitAll(context.Context, string, string) (bool, error) { return false, nil } +func (*fakeScratchTrees) Push(context.Context) error { return nil } +func (*fakeScratchTrees) Diff(context.Context, string, string) (string, error) { return "", nil } +func (*fakeScratchTrees) ChangedFiles(context.Context, string, string) ([]string, error) { + return nil, nil +} + +func (*fakeScratchTrees) ChangedLines(context.Context, string, string) (int, error) { return 0, nil } +func (*fakeScratchTrees) Snapshot(context.Context, string, string) error { return nil } + +// TestExecuteTaskRequestStartsWorkflowCallCallee proves the engine's +// task.Caller wiring end to end: a run of a repository-none workflow carrying +// one workflow.call step starts a real callee task row through the same +// State Store gRPC contract the production worker dials +// (docs/prds/workflow-calls.md), and the caller carries on to its tail. +func TestExecuteTaskRequestStartsWorkflowCallCallee(t *testing.T) { + ctx := t.Context() + st := pgstore.Open(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", "") + if err != nil { + t.Fatalf("seed caller task: %v", err) + } + if err := st.Transition(ctx, task.ID, task.Status, workflow.StatusRunning, "started"); err != nil { + t.Fatalf("claim caller: %v", err) + } + task.Status = workflow.StatusRunning + task.Inputs = map[string]any{"src_ip": "10.0.0.9"} + task.WorkflowDefinitionYAML = callerYAML + task.WorkflowDefinitionDigest = workflow.DigestDefinition(callerYAML) + if err := st.Update(ctx, task); err != nil { + t.Fatalf("seed caller task: %v", err) + } + + transport, err := agentnats.Connect(ctx, agentnats.Config{StateStoreURL: startStateStoreGRPC(t, st)}, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(transport.Close) + + workDir := t.TempDir() + request := taskrun.Request{ + Task: task, + Repo: config.Repo{}, + Cfg: config.Config{Models: map[string]string{"builder": "p/m"}}.ForTask(), + WorkflowDefinition: callerYAML, + } + dependencies := taskDependencies{ + store: transport.Store(rpcTimeout), + calls: transport.Calls(rpcTimeout), + trees: &fakeScratchTrees{dir: workDir}, + steps: testSteps(t), + } + fakeRunner := runnerFactory(func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner { return stubRunner{} }) + response, err := runTask(ctx, request, dependencies, fakeRunner, workDir, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatal(err) + } + if response.Status != workflow.StatusCompleted { + t.Fatalf("response status = %q (park reason %q), want completed", response.Status, response.Task.ParkReason) + } + + callee := calleeTaskOf(t, ctx, st, task.ID) + if callee.Workflow != "callee" || callee.CallParentTaskID != task.ID || callee.CallDepth != 1 { + t.Fatalf("callee = %+v, want workflow callee linked to task %d at depth 1", callee, task.ID) + } + if callee.Inputs["src_ip"] != "10.0.0.9" { + t.Fatalf("callee inputs = %+v, want the call's resolved reference", callee.Inputs) + } + if callee.Org != org.OrgID("default") { + t.Fatalf("callee org = %q, want the caller's %q", callee.Org, task.Org) + } +} + +// calleeTaskOf reads the one callee task whose call_parent_task_id is +// callerTaskID, straight off the pool the test owns. +func calleeTaskOf(t *testing.T, ctx context.Context, st *pgstore.TaskDB, callerTaskID int64) *workflow.Task { + t.Helper() + rows, err := st.Pool.Query(ctx, + `SELECT id, workflow, call_parent_task_id, call_depth, org_id, inputs + FROM tasks WHERE call_parent_task_id = $1`, callerTaskID) + if err != nil { + t.Fatalf("callee query: %v", err) + } + defer rows.Close() + var callees []*workflow.Task + for rows.Next() { + var id, parent, depth int64 + var wf, orgID, inputs string + if err := rows.Scan(&id, &wf, &parent, &depth, &orgID, &inputs); err != nil { + t.Fatalf("callee scan: %v", err) + } + decoded, _ := workflowtask.DecodeInputs(inputs) + callees = append(callees, &workflow.Task{ + ID: id, Workflow: wf, CallParentTaskID: parent, CallDepth: int(depth), + Org: org.OrgID(orgID), Inputs: decoded, + }) + } + if err := rows.Err(); err != nil { + t.Fatalf("callee rows: %v", err) + } + if len(callees) != 1 { + t.Fatalf("callee tasks of %d = %+v, want exactly one", callerTaskID, callees) + } + return callees[0] +} diff --git a/internal/app/agentworker/worker.go b/internal/app/agentworker/worker.go index 5d279d8ad..73279290f 100644 --- a/internal/app/agentworker/worker.go +++ b/internal/app/agentworker/worker.go @@ -8,6 +8,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/infrastructure/agentboot" "github.com/samcharles93/archie-core/internal/infrastructure/agentgit" agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats" @@ -50,6 +51,7 @@ type workerTransport interface { SubscribeTasks(context.Context, int64, agentnats.TaskHandler, *slog.Logger) (agentnats.Subscription, error) Forger(string, time.Duration) workflow.Forger Store(time.Duration) workflow.Store + Calls(time.Duration) task.Caller Trees(string, string, time.Duration) agentnats.RemoteTrees } @@ -152,6 +154,7 @@ func run(ctx context.Context, settings Settings, log *slog.Logger, dependencies type taskServiceTransport interface { Forger(string, time.Duration) workflow.Forger Store(time.Duration) workflow.Store + Calls(time.Duration) task.Caller Trees(string, string, time.Duration) agentnats.RemoteTrees EventPublisher() agentexec.EventPublisher } @@ -161,6 +164,7 @@ func executeTaskRequest(ctx context.Context, request taskrun.Request, transport dependencies := taskDependencies{ forge: transport.Forger(request.Task.Identity, rpcTimeout), store: transport.Store(rpcTimeout), + calls: transport.Calls(rpcTimeout), trees: transport.Trees(request.Task.Identity, request.WorktreeGrant, rpcTimeout), events: transport.EventPublisher(), steps: steps, diff --git a/internal/app/agentworker/worker_test.go b/internal/app/agentworker/worker_test.go index a50063fb6..9d623ad08 100644 --- a/internal/app/agentworker/worker_test.go +++ b/internal/app/agentworker/worker_test.go @@ -11,6 +11,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats" ) @@ -75,6 +76,8 @@ func (*workerTransportStub) Forger(string, time.Duration) workflow.Forger { retu func (*workerTransportStub) Store(time.Duration) workflow.Store { return nil } +func (*workerTransportStub) Calls(time.Duration) task.Caller { return nil } + func (*workerTransportStub) Trees(string, string, time.Duration) agentnats.RemoteTrees { return nil } func TestRunPassesCompleteTransportConfiguration(t *testing.T) { diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index fe2b606b5..d1e76bc8c 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -284,6 +284,9 @@ func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps { if btc, ok := b.st.(storecontract.BindingTaskCreator); ok { deps.BindingTaskCreator = btc } + if wc, ok := b.st.(storecontract.WorkflowCaller); ok { + deps.WorkflowCalls = wc + } if css, ok := b.st.(storecontract.ConfigSnapshotStore); ok { deps.ConfigSnapshots = css } diff --git a/internal/contracts/state/v1/state.pb.go b/internal/contracts/state/v1/state.pb.go index 38edeb98e..887637d55 100644 --- a/internal/contracts/state/v1/state.pb.go +++ b/internal/contracts/state/v1/state.pb.go @@ -1323,9 +1323,15 @@ type Task struct { // org is the org the task belongs to, derived store-side from the task's // identity when the row is written; a task of a single-operator install // belongs to the default org (docs/prds/orgs-and-access.md). - Org string `protobuf:"bytes,35,opt,name=org,proto3" json:"org,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + Org string `protobuf:"bytes,35,opt,name=org,proto3" json:"org,omitempty"` + // The workflow.call linkage (docs/prds/workflow-calls.md): the task whose + // workflow.call step started this one (0 on a root run) and how many + // call hops this row is from that root. Columns default, so an older + // writer reads as a depth-0 root run. + CallParentTaskId int64 `protobuf:"varint,36,opt,name=call_parent_task_id,json=callParentTaskId,proto3" json:"call_parent_task_id,omitempty"` + CallDepth int32 `protobuf:"varint,37,opt,name=call_depth,json=callDepth,proto3" json:"call_depth,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Task) Reset() { @@ -1603,6 +1609,20 @@ func (x *Task) GetOrg() string { return "" } +func (x *Task) GetCallParentTaskId() int64 { + if x != nil { + return x.CallParentTaskId + } + return 0 +} + +func (x *Task) GetCallDepth() int32 { + if x != nil { + return x.CallDepth + } + return 0 +} + // Event mirrors internal/events.Event. Data is carried as a JSON object // string (matching the store's own on-disk representation) rather than // google.protobuf.Struct, to stay a direct mirror of the existing column. @@ -9106,6 +9126,226 @@ func (x *EnqueueBindingTaskResponse) GetTask() *Task { return nil } +// workflow.call: the caller's grant names the caller; the store derives the +// rest from the caller's row (docs/prds/workflow-calls.md). +type EnqueueCallTaskRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + CallerTaskId int64 `protobuf:"varint,1,opt,name=caller_task_id,json=callerTaskId,proto3" json:"caller_task_id,omitempty"` + Workflow string `protobuf:"bytes,2,opt,name=workflow,proto3" json:"workflow,omitempty"` + InputsJson string `protobuf:"bytes,3,opt,name=inputs_json,json=inputsJson,proto3" json:"inputs_json,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *EnqueueCallTaskRequest) Reset() { + *x = EnqueueCallTaskRequest{} + mi := &file_state_v1_state_proto_msgTypes[170] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *EnqueueCallTaskRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*EnqueueCallTaskRequest) ProtoMessage() {} + +func (x *EnqueueCallTaskRequest) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[170] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use EnqueueCallTaskRequest.ProtoReflect.Descriptor instead. +func (*EnqueueCallTaskRequest) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{170} +} + +func (x *EnqueueCallTaskRequest) GetCallerTaskId() int64 { + if x != nil { + return x.CallerTaskId + } + return 0 +} + +func (x *EnqueueCallTaskRequest) GetWorkflow() string { + if x != nil { + return x.Workflow + } + return "" +} + +func (x *EnqueueCallTaskRequest) GetInputsJson() string { + if x != nil { + return x.InputsJson + } + return "" +} + +type EnqueueCallTaskResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Task *Task `protobuf:"bytes,1,opt,name=task,proto3" json:"task,omitempty"` + Accepted bool `protobuf:"varint,2,opt,name=accepted,proto3" json:"accepted,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *EnqueueCallTaskResponse) Reset() { + *x = EnqueueCallTaskResponse{} + mi := &file_state_v1_state_proto_msgTypes[171] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *EnqueueCallTaskResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*EnqueueCallTaskResponse) ProtoMessage() {} + +func (x *EnqueueCallTaskResponse) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[171] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use EnqueueCallTaskResponse.ProtoReflect.Descriptor instead. +func (*EnqueueCallTaskResponse) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{171} +} + +func (x *EnqueueCallTaskResponse) GetTask() *Task { + if x != nil { + return x.Task + } + return nil +} + +func (x *EnqueueCallTaskResponse) GetAccepted() bool { + if x != nil { + return x.Accepted + } + return false +} + +type WorkflowCallStatusRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + CallerTaskId int64 `protobuf:"varint,1,opt,name=caller_task_id,json=callerTaskId,proto3" json:"caller_task_id,omitempty"` + CallTaskId int64 `protobuf:"varint,2,opt,name=call_task_id,json=callTaskId,proto3" json:"call_task_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowCallStatusRequest) Reset() { + *x = WorkflowCallStatusRequest{} + mi := &file_state_v1_state_proto_msgTypes[172] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowCallStatusRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowCallStatusRequest) ProtoMessage() {} + +func (x *WorkflowCallStatusRequest) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[172] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkflowCallStatusRequest.ProtoReflect.Descriptor instead. +func (*WorkflowCallStatusRequest) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{172} +} + +func (x *WorkflowCallStatusRequest) GetCallerTaskId() int64 { + if x != nil { + return x.CallerTaskId + } + return 0 +} + +func (x *WorkflowCallStatusRequest) GetCallTaskId() int64 { + if x != nil { + return x.CallTaskId + } + return 0 +} + +type WorkflowCallStatusResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + // status is the callee's task status and detail its latest transition + // detail (empty before the callee first moves). + Status string `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"` + Detail string `protobuf:"bytes,2,opt,name=detail,proto3" json:"detail,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowCallStatusResponse) Reset() { + *x = WorkflowCallStatusResponse{} + mi := &file_state_v1_state_proto_msgTypes[173] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowCallStatusResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowCallStatusResponse) ProtoMessage() {} + +func (x *WorkflowCallStatusResponse) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[173] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkflowCallStatusResponse.ProtoReflect.Descriptor instead. +func (*WorkflowCallStatusResponse) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{173} +} + +func (x *WorkflowCallStatusResponse) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +func (x *WorkflowCallStatusResponse) GetDetail() string { + if x != nil { + return x.Detail + } + return "" +} + type InstalledPackage struct { state protoimpl.MessageState `protogen:"open.v1"` OrgId string `protobuf:"bytes,1,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"` @@ -9121,7 +9361,7 @@ type InstalledPackage struct { func (x *InstalledPackage) Reset() { *x = InstalledPackage{} - mi := &file_state_v1_state_proto_msgTypes[170] + mi := &file_state_v1_state_proto_msgTypes[174] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9133,7 +9373,7 @@ func (x *InstalledPackage) String() string { func (*InstalledPackage) ProtoMessage() {} func (x *InstalledPackage) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[170] + mi := &file_state_v1_state_proto_msgTypes[174] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9146,7 +9386,7 @@ func (x *InstalledPackage) ProtoReflect() protoreflect.Message { // Deprecated: Use InstalledPackage.ProtoReflect.Descriptor instead. func (*InstalledPackage) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{170} + return file_state_v1_state_proto_rawDescGZIP(), []int{174} } func (x *InstalledPackage) GetOrgId() string { @@ -9210,7 +9450,7 @@ type InstallPackageRequest struct { func (x *InstallPackageRequest) Reset() { *x = InstallPackageRequest{} - mi := &file_state_v1_state_proto_msgTypes[171] + mi := &file_state_v1_state_proto_msgTypes[175] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9222,7 +9462,7 @@ func (x *InstallPackageRequest) String() string { func (*InstallPackageRequest) ProtoMessage() {} func (x *InstallPackageRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[171] + mi := &file_state_v1_state_proto_msgTypes[175] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9235,7 +9475,7 @@ func (x *InstallPackageRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use InstallPackageRequest.ProtoReflect.Descriptor instead. func (*InstallPackageRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{171} + return file_state_v1_state_proto_rawDescGZIP(), []int{175} } func (x *InstallPackageRequest) GetOrgId() string { @@ -9275,7 +9515,7 @@ type InstallPackageResponse struct { func (x *InstallPackageResponse) Reset() { *x = InstallPackageResponse{} - mi := &file_state_v1_state_proto_msgTypes[172] + mi := &file_state_v1_state_proto_msgTypes[176] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9287,7 +9527,7 @@ func (x *InstallPackageResponse) String() string { func (*InstallPackageResponse) ProtoMessage() {} func (x *InstallPackageResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[172] + mi := &file_state_v1_state_proto_msgTypes[176] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9300,7 +9540,7 @@ func (x *InstallPackageResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use InstallPackageResponse.ProtoReflect.Descriptor instead. func (*InstallPackageResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{172} + return file_state_v1_state_proto_rawDescGZIP(), []int{176} } func (x *InstallPackageResponse) GetPackage() *InstalledPackage { @@ -9320,7 +9560,7 @@ type GetInstalledPackageRequest struct { func (x *GetInstalledPackageRequest) Reset() { *x = GetInstalledPackageRequest{} - mi := &file_state_v1_state_proto_msgTypes[173] + mi := &file_state_v1_state_proto_msgTypes[177] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9332,7 +9572,7 @@ func (x *GetInstalledPackageRequest) String() string { func (*GetInstalledPackageRequest) ProtoMessage() {} func (x *GetInstalledPackageRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[173] + mi := &file_state_v1_state_proto_msgTypes[177] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9345,7 +9585,7 @@ func (x *GetInstalledPackageRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetInstalledPackageRequest.ProtoReflect.Descriptor instead. func (*GetInstalledPackageRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{173} + return file_state_v1_state_proto_rawDescGZIP(), []int{177} } func (x *GetInstalledPackageRequest) GetOrgId() string { @@ -9371,7 +9611,7 @@ type GetInstalledPackageResponse struct { func (x *GetInstalledPackageResponse) Reset() { *x = GetInstalledPackageResponse{} - mi := &file_state_v1_state_proto_msgTypes[174] + mi := &file_state_v1_state_proto_msgTypes[178] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9383,7 +9623,7 @@ func (x *GetInstalledPackageResponse) String() string { func (*GetInstalledPackageResponse) ProtoMessage() {} func (x *GetInstalledPackageResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[174] + mi := &file_state_v1_state_proto_msgTypes[178] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9396,7 +9636,7 @@ func (x *GetInstalledPackageResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetInstalledPackageResponse.ProtoReflect.Descriptor instead. func (*GetInstalledPackageResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{174} + return file_state_v1_state_proto_rawDescGZIP(), []int{178} } func (x *GetInstalledPackageResponse) GetPackage() *InstalledPackage { @@ -9415,7 +9655,7 @@ type ListInstalledPackagesRequest struct { func (x *ListInstalledPackagesRequest) Reset() { *x = ListInstalledPackagesRequest{} - mi := &file_state_v1_state_proto_msgTypes[175] + mi := &file_state_v1_state_proto_msgTypes[179] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9427,7 +9667,7 @@ func (x *ListInstalledPackagesRequest) String() string { func (*ListInstalledPackagesRequest) ProtoMessage() {} func (x *ListInstalledPackagesRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[175] + mi := &file_state_v1_state_proto_msgTypes[179] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9440,7 +9680,7 @@ func (x *ListInstalledPackagesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListInstalledPackagesRequest.ProtoReflect.Descriptor instead. func (*ListInstalledPackagesRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{175} + return file_state_v1_state_proto_rawDescGZIP(), []int{179} } func (x *ListInstalledPackagesRequest) GetOrgId() string { @@ -9459,7 +9699,7 @@ type ListInstalledPackagesResponse struct { func (x *ListInstalledPackagesResponse) Reset() { *x = ListInstalledPackagesResponse{} - mi := &file_state_v1_state_proto_msgTypes[176] + mi := &file_state_v1_state_proto_msgTypes[180] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9471,7 +9711,7 @@ func (x *ListInstalledPackagesResponse) String() string { func (*ListInstalledPackagesResponse) ProtoMessage() {} func (x *ListInstalledPackagesResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[176] + mi := &file_state_v1_state_proto_msgTypes[180] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9484,7 +9724,7 @@ func (x *ListInstalledPackagesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListInstalledPackagesResponse.ProtoReflect.Descriptor instead. func (*ListInstalledPackagesResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{176} + return file_state_v1_state_proto_rawDescGZIP(), []int{180} } func (x *ListInstalledPackagesResponse) GetPackages() []*InstalledPackage { @@ -9504,7 +9744,7 @@ type RemoveInstalledPackageRequest struct { func (x *RemoveInstalledPackageRequest) Reset() { *x = RemoveInstalledPackageRequest{} - mi := &file_state_v1_state_proto_msgTypes[177] + mi := &file_state_v1_state_proto_msgTypes[181] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9516,7 +9756,7 @@ func (x *RemoveInstalledPackageRequest) String() string { func (*RemoveInstalledPackageRequest) ProtoMessage() {} func (x *RemoveInstalledPackageRequest) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[177] + mi := &file_state_v1_state_proto_msgTypes[181] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9529,7 +9769,7 @@ func (x *RemoveInstalledPackageRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RemoveInstalledPackageRequest.ProtoReflect.Descriptor instead. func (*RemoveInstalledPackageRequest) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{177} + return file_state_v1_state_proto_rawDescGZIP(), []int{181} } func (x *RemoveInstalledPackageRequest) GetOrgId() string { @@ -9554,7 +9794,7 @@ type RemoveInstalledPackageResponse struct { func (x *RemoveInstalledPackageResponse) Reset() { *x = RemoveInstalledPackageResponse{} - mi := &file_state_v1_state_proto_msgTypes[178] + mi := &file_state_v1_state_proto_msgTypes[182] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9566,7 +9806,7 @@ func (x *RemoveInstalledPackageResponse) String() string { func (*RemoveInstalledPackageResponse) ProtoMessage() {} func (x *RemoveInstalledPackageResponse) ProtoReflect() protoreflect.Message { - mi := &file_state_v1_state_proto_msgTypes[178] + mi := &file_state_v1_state_proto_msgTypes[182] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9579,7 +9819,7 @@ func (x *RemoveInstalledPackageResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RemoveInstalledPackageResponse.ProtoReflect.Descriptor instead. func (*RemoveInstalledPackageResponse) Descriptor() ([]byte, []int) { - return file_state_v1_state_proto_rawDescGZIP(), []int{178} + return file_state_v1_state_proto_rawDescGZIP(), []int{182} } var File_state_v1_state_proto protoreflect.FileDescriptor @@ -9662,7 +9902,7 @@ const file_state_v1_state_proto_rawDesc = "" + "\asubject\x18\x03 \x01(\tR\asubject\x12-\n" + "\x05audit\x18\x04 \x01(\v2\x17.state.v1.IdentityAuditR\x05audit\"M\n" + "\x1bBindIdentitySubjectResponse\x12.\n" + - "\bidentity\x18\x01 \x01(\v2\x12.state.v1.IdentityR\bidentity\"\x8c\t\n" + + "\bidentity\x18\x01 \x01(\v2\x12.state.v1.IdentityR\bidentity\"\xda\t\n" + "\x04Task\x12\x0e\n" + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x14\n" + "\x05owner\x18\x02 \x01(\tR\x05owner\x12\x12\n" + @@ -9709,7 +9949,10 @@ const file_state_v1_state_proto_rawDesc = "" + "\x12remediation_rounds\x18! \x01(\x05R\x11remediationRounds\x12\x1f\n" + "\vinputs_json\x18\" \x01(\tR\n" + "inputsJson\x12\x10\n" + - "\x03org\x18# \x01(\tR\x03org\"\xf8\x02\n" + + "\x03org\x18# \x01(\tR\x03org\x12-\n" + + "\x13call_parent_task_id\x18$ \x01(\x03R\x10callParentTaskId\x12\x1d\n" + + "\n" + + "call_depth\x18% \x01(\x05R\tcallDepth\"\xf8\x02\n" + "\x05Event\x12\x0e\n" + "\x02id\x18\x01 \x01(\x03R\x02id\x12*\n" + "\x02at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x02at\x12\x12\n" + @@ -10178,7 +10421,22 @@ const file_state_v1_state_proto_rawDesc = "" + "\vinputs_json\x18\t \x01(\tR\n" + "inputsJson\"@\n" + "\x1aEnqueueBindingTaskResponse\x12\"\n" + - "\x04task\x18\x01 \x01(\v2\x0e.state.v1.TaskR\x04task\"\xd7\x01\n" + + "\x04task\x18\x01 \x01(\v2\x0e.state.v1.TaskR\x04task\"{\n" + + "\x16EnqueueCallTaskRequest\x12$\n" + + "\x0ecaller_task_id\x18\x01 \x01(\x03R\fcallerTaskId\x12\x1a\n" + + "\bworkflow\x18\x02 \x01(\tR\bworkflow\x12\x1f\n" + + "\vinputs_json\x18\x03 \x01(\tR\n" + + "inputsJson\"Y\n" + + "\x17EnqueueCallTaskResponse\x12\"\n" + + "\x04task\x18\x01 \x01(\v2\x0e.state.v1.TaskR\x04task\x12\x1a\n" + + "\baccepted\x18\x02 \x01(\bR\baccepted\"c\n" + + "\x19WorkflowCallStatusRequest\x12$\n" + + "\x0ecaller_task_id\x18\x01 \x01(\x03R\fcallerTaskId\x12 \n" + + "\fcall_task_id\x18\x02 \x01(\x03R\n" + + "callTaskId\"L\n" + + "\x1aWorkflowCallStatusResponse\x12\x16\n" + + "\x06status\x18\x01 \x01(\tR\x06status\x12\x16\n" + + "\x06detail\x18\x02 \x01(\tR\x06detail\"\xd7\x01\n" + "\x10InstalledPackage\x12\x15\n" + "\x06org_id\x18\x01 \x01(\tR\x05orgId\x12\x12\n" + "\x04name\x18\x02 \x01(\tR\x04name\x12\x1c\n" + @@ -10206,7 +10464,7 @@ const file_state_v1_state_proto_rawDesc = "" + "\x1dRemoveInstalledPackageRequest\x12\x15\n" + "\x06org_id\x18\x01 \x01(\tR\x05orgId\x12\x12\n" + "\x04name\x18\x02 \x01(\tR\x04name\" \n" + - "\x1eRemoveInstalledPackageResponse2\xd44\n" + + "\x1eRemoveInstalledPackageResponse2\x8d6\n" + "\x11StateStoreService\x12S\n" + "\x0eInstallPackage\x12\x1f.state.v1.InstallPackageRequest\x1a .state.v1.InstallPackageResponse\x12b\n" + "\x13GetInstalledPackage\x12$.state.v1.GetInstalledPackageRequest\x1a%.state.v1.GetInstalledPackageResponse\x12h\n" + @@ -10291,7 +10549,9 @@ const file_state_v1_state_proto_rawDesc = "" + "\x16RecordPlaybookDispatch\x12'.state.v1.RecordPlaybookDispatchRequest\x1a(.state.v1.RecordPlaybookDispatchResponse\x12q\n" + "\x18DeletePlaybookDispatches\x12).state.v1.DeletePlaybookDispatchesRequest\x1a*.state.v1.DeletePlaybookDispatchesResponse\x12y\n" + "\x1aStreamUndispatchedCaptures\x12+.state.v1.StreamUndispatchedCapturesRequest\x1a,.state.v1.StreamUndispatchedCapturesResponse0\x01\x12_\n" + - "\x12EnqueueBindingTask\x12#.state.v1.EnqueueBindingTaskRequest\x1a$.state.v1.EnqueueBindingTaskResponseB\xa4\x01\n" + + "\x12EnqueueBindingTask\x12#.state.v1.EnqueueBindingTaskRequest\x1a$.state.v1.EnqueueBindingTaskResponse\x12V\n" + + "\x0fEnqueueCallTask\x12 .state.v1.EnqueueCallTaskRequest\x1a!.state.v1.EnqueueCallTaskResponse\x12_\n" + + "\x12WorkflowCallStatus\x12#.state.v1.WorkflowCallStatusRequest\x1a$.state.v1.WorkflowCallStatusResponseB\xa4\x01\n" + "\fcom.state.v1B\n" + "StateProtoP\x01ZGgithub.com/samcharles93/archie-core/internal/contracts/state/v1;statev1\xa2\x02\x03SXX\xaa\x02\bState.V1\xca\x02\bState\\V1\xe2\x02\x14State\\V1\\GPBMetadata\xea\x02\tState::V1b\x06proto3" @@ -10307,7 +10567,7 @@ func file_state_v1_state_proto_rawDescGZIP() []byte { return file_state_v1_state_proto_rawDescData } -var file_state_v1_state_proto_msgTypes = make([]protoimpl.MessageInfo, 181) +var file_state_v1_state_proto_msgTypes = make([]protoimpl.MessageInfo, 185) var file_state_v1_state_proto_goTypes = []any{ (*RegisterTaskGrantRequest)(nil), // 0: state.v1.RegisterTaskGrantRequest (*RegisterTaskGrantResponse)(nil), // 1: state.v1.RegisterTaskGrantResponse @@ -10479,22 +10739,26 @@ var file_state_v1_state_proto_goTypes = []any{ (*StreamUndispatchedCapturesResponse)(nil), // 167: state.v1.StreamUndispatchedCapturesResponse (*EnqueueBindingTaskRequest)(nil), // 168: state.v1.EnqueueBindingTaskRequest (*EnqueueBindingTaskResponse)(nil), // 169: state.v1.EnqueueBindingTaskResponse - (*InstalledPackage)(nil), // 170: state.v1.InstalledPackage - (*InstallPackageRequest)(nil), // 171: state.v1.InstallPackageRequest - (*InstallPackageResponse)(nil), // 172: state.v1.InstallPackageResponse - (*GetInstalledPackageRequest)(nil), // 173: state.v1.GetInstalledPackageRequest - (*GetInstalledPackageResponse)(nil), // 174: state.v1.GetInstalledPackageResponse - (*ListInstalledPackagesRequest)(nil), // 175: state.v1.ListInstalledPackagesRequest - (*ListInstalledPackagesResponse)(nil), // 176: state.v1.ListInstalledPackagesResponse - (*RemoveInstalledPackageRequest)(nil), // 177: state.v1.RemoveInstalledPackageRequest - (*RemoveInstalledPackageResponse)(nil), // 178: state.v1.RemoveInstalledPackageResponse - nil, // 179: state.v1.EventType.SchemaEntry - nil, // 180: state.v1.StatusCountsResponse.CountsEntry - (*timestamppb.Timestamp)(nil), // 181: google.protobuf.Timestamp + (*EnqueueCallTaskRequest)(nil), // 170: state.v1.EnqueueCallTaskRequest + (*EnqueueCallTaskResponse)(nil), // 171: state.v1.EnqueueCallTaskResponse + (*WorkflowCallStatusRequest)(nil), // 172: state.v1.WorkflowCallStatusRequest + (*WorkflowCallStatusResponse)(nil), // 173: state.v1.WorkflowCallStatusResponse + (*InstalledPackage)(nil), // 174: state.v1.InstalledPackage + (*InstallPackageRequest)(nil), // 175: state.v1.InstallPackageRequest + (*InstallPackageResponse)(nil), // 176: state.v1.InstallPackageResponse + (*GetInstalledPackageRequest)(nil), // 177: state.v1.GetInstalledPackageRequest + (*GetInstalledPackageResponse)(nil), // 178: state.v1.GetInstalledPackageResponse + (*ListInstalledPackagesRequest)(nil), // 179: state.v1.ListInstalledPackagesRequest + (*ListInstalledPackagesResponse)(nil), // 180: state.v1.ListInstalledPackagesResponse + (*RemoveInstalledPackageRequest)(nil), // 181: state.v1.RemoveInstalledPackageRequest + (*RemoveInstalledPackageResponse)(nil), // 182: state.v1.RemoveInstalledPackageResponse + nil, // 183: state.v1.EventType.SchemaEntry + nil, // 184: state.v1.StatusCountsResponse.CountsEntry + (*timestamppb.Timestamp)(nil), // 185: google.protobuf.Timestamp } var file_state_v1_state_proto_depIdxs = []int32{ - 181, // 0: state.v1.Identity.created_at:type_name -> google.protobuf.Timestamp - 181, // 1: state.v1.Identity.updated_at:type_name -> google.protobuf.Timestamp + 185, // 0: state.v1.Identity.created_at:type_name -> google.protobuf.Timestamp + 185, // 1: state.v1.Identity.updated_at:type_name -> google.protobuf.Timestamp 4, // 2: state.v1.ListIdentitiesResponse.identities:type_name -> state.v1.Identity 4, // 3: state.v1.GetIdentityResponse.identity:type_name -> state.v1.Identity 5, // 4: state.v1.CreateIdentityRequest.audit:type_name -> state.v1.IdentityAudit @@ -10510,24 +10774,24 @@ var file_state_v1_state_proto_depIdxs = []int32{ 4, // 14: state.v1.ResolveIdentitySubjectResponse.identity:type_name -> state.v1.Identity 5, // 15: state.v1.BindIdentitySubjectRequest.audit:type_name -> state.v1.IdentityAudit 4, // 16: state.v1.BindIdentitySubjectResponse.identity:type_name -> state.v1.Identity - 181, // 17: state.v1.Task.created_at:type_name -> google.protobuf.Timestamp - 181, // 18: state.v1.Task.updated_at:type_name -> google.protobuf.Timestamp - 181, // 19: state.v1.Event.at:type_name -> google.protobuf.Timestamp - 181, // 20: state.v1.CapturedEvent.received_at:type_name -> google.protobuf.Timestamp + 185, // 17: state.v1.Task.created_at:type_name -> google.protobuf.Timestamp + 185, // 18: state.v1.Task.updated_at:type_name -> google.protobuf.Timestamp + 185, // 19: state.v1.Event.at:type_name -> google.protobuf.Timestamp + 185, // 20: state.v1.CapturedEvent.received_at:type_name -> google.protobuf.Timestamp 27, // 21: state.v1.EventType.header_conditions:type_name -> state.v1.EventTypeHeaderCondition 28, // 22: state.v1.EventType.payload_conditions:type_name -> state.v1.EventTypePayloadCondition - 179, // 23: state.v1.EventType.schema:type_name -> state.v1.EventType.SchemaEntry - 181, // 24: state.v1.EventType.created_at:type_name -> google.protobuf.Timestamp - 181, // 25: state.v1.EventType.updated_at:type_name -> google.protobuf.Timestamp + 183, // 23: state.v1.EventType.schema:type_name -> state.v1.EventType.SchemaEntry + 185, // 24: state.v1.EventType.created_at:type_name -> google.protobuf.Timestamp + 185, // 25: state.v1.EventType.updated_at:type_name -> google.protobuf.Timestamp 30, // 26: state.v1.Mapping.fields:type_name -> state.v1.MappingField - 181, // 27: state.v1.Mapping.created_at:type_name -> google.protobuf.Timestamp - 181, // 28: state.v1.Mapping.updated_at:type_name -> google.protobuf.Timestamp - 181, // 29: state.v1.Mapping.last_matched_at:type_name -> google.protobuf.Timestamp + 185, // 27: state.v1.Mapping.created_at:type_name -> google.protobuf.Timestamp + 185, // 28: state.v1.Mapping.updated_at:type_name -> google.protobuf.Timestamp + 185, // 29: state.v1.Mapping.last_matched_at:type_name -> google.protobuf.Timestamp 32, // 30: state.v1.Binding.matcher:type_name -> state.v1.BindingMatcher - 181, // 31: state.v1.Binding.created_at:type_name -> google.protobuf.Timestamp - 181, // 32: state.v1.Binding.updated_at:type_name -> google.protobuf.Timestamp - 181, // 33: state.v1.Source.created_at:type_name -> google.protobuf.Timestamp - 181, // 34: state.v1.Source.updated_at:type_name -> google.protobuf.Timestamp + 185, // 31: state.v1.Binding.created_at:type_name -> google.protobuf.Timestamp + 185, // 32: state.v1.Binding.updated_at:type_name -> google.protobuf.Timestamp + 185, // 33: state.v1.Source.created_at:type_name -> google.protobuf.Timestamp + 185, // 34: state.v1.Source.updated_at:type_name -> google.protobuf.Timestamp 24, // 35: state.v1.EnqueueChatTaskResponse.task:type_name -> state.v1.Task 24, // 36: state.v1.ClaimNextResponse.task:type_name -> state.v1.Task 24, // 37: state.v1.ClaimByIssueResponse.task:type_name -> state.v1.Task @@ -10538,25 +10802,25 @@ var file_state_v1_state_proto_depIdxs = []int32{ 24, // 42: state.v1.TaskByIDResponse.task:type_name -> state.v1.Task 24, // 43: state.v1.OpenPRsResponse.tasks:type_name -> state.v1.Task 24, // 44: state.v1.TasksResponse.tasks:type_name -> state.v1.Task - 180, // 45: state.v1.StatusCountsResponse.counts:type_name -> state.v1.StatusCountsResponse.CountsEntry + 184, // 45: state.v1.StatusCountsResponse.counts:type_name -> state.v1.StatusCountsResponse.CountsEntry 25, // 46: state.v1.InsertEventRequest.event:type_name -> state.v1.Event 25, // 47: state.v1.EventsSinceResponse.events:type_name -> state.v1.Event 25, // 48: state.v1.TaskEventsResponse.events:type_name -> state.v1.Event 35, // 49: state.v1.WorkflowStatsResponse.stats:type_name -> state.v1.WorkflowStat 36, // 50: state.v1.StageStatsResponse.stats:type_name -> state.v1.StageStat 37, // 51: state.v1.TokensByDayResponse.tokens:type_name -> state.v1.DayTokens - 181, // 52: state.v1.ConfigSnapshot.published_at:type_name -> google.protobuf.Timestamp + 185, // 52: state.v1.ConfigSnapshot.published_at:type_name -> google.protobuf.Timestamp 92, // 53: state.v1.PutConfigSnapshotRequest.snapshot:type_name -> state.v1.ConfigSnapshot 92, // 54: state.v1.GetConfigSnapshotResponse.snapshot:type_name -> state.v1.ConfigSnapshot - 181, // 55: state.v1.ChannelStatus.observed_at:type_name -> google.protobuf.Timestamp + 185, // 55: state.v1.ChannelStatus.observed_at:type_name -> google.protobuf.Timestamp 97, // 56: state.v1.PutChannelStatusRequest.channels:type_name -> state.v1.ChannelStatus 97, // 57: state.v1.ListChannelStatusResponse.channels:type_name -> state.v1.ChannelStatus - 181, // 58: state.v1.ApplyStatus.reported_at:type_name -> google.protobuf.Timestamp + 185, // 58: state.v1.ApplyStatus.reported_at:type_name -> google.protobuf.Timestamp 102, // 59: state.v1.PutApplyStatusRequest.status:type_name -> state.v1.ApplyStatus 102, // 60: state.v1.ListApplyStatusResponse.statuses:type_name -> state.v1.ApplyStatus - 181, // 61: state.v1.TaskLogEntry.time:type_name -> google.protobuf.Timestamp - 181, // 62: state.v1.ReadTaskLogRequest.since:type_name -> google.protobuf.Timestamp - 181, // 63: state.v1.ReadTaskLogRequest.until:type_name -> google.protobuf.Timestamp + 185, // 61: state.v1.TaskLogEntry.time:type_name -> google.protobuf.Timestamp + 185, // 62: state.v1.ReadTaskLogRequest.since:type_name -> google.protobuf.Timestamp + 185, // 63: state.v1.ReadTaskLogRequest.until:type_name -> google.protobuf.Timestamp 107, // 64: state.v1.ReadTaskLogResponse.entries:type_name -> state.v1.TaskLogEntry 26, // 65: state.v1.InsertCaptureRequest.capture:type_name -> state.v1.CapturedEvent 26, // 66: state.v1.StreamCapturesResponse.capture:type_name -> state.v1.CapturedEvent @@ -10577,172 +10841,177 @@ var file_state_v1_state_proto_depIdxs = []int32{ 33, // 81: state.v1.ArmedBindingsForSourceResponse.bindings:type_name -> state.v1.Binding 26, // 82: state.v1.StreamUndispatchedCapturesResponse.capture:type_name -> state.v1.CapturedEvent 24, // 83: state.v1.EnqueueBindingTaskResponse.task:type_name -> state.v1.Task - 170, // 84: state.v1.InstallPackageResponse.package:type_name -> state.v1.InstalledPackage - 170, // 85: state.v1.GetInstalledPackageResponse.package:type_name -> state.v1.InstalledPackage - 170, // 86: state.v1.ListInstalledPackagesResponse.packages:type_name -> state.v1.InstalledPackage - 171, // 87: state.v1.StateStoreService.InstallPackage:input_type -> state.v1.InstallPackageRequest - 173, // 88: state.v1.StateStoreService.GetInstalledPackage:input_type -> state.v1.GetInstalledPackageRequest - 175, // 89: state.v1.StateStoreService.ListInstalledPackages:input_type -> state.v1.ListInstalledPackagesRequest - 177, // 90: state.v1.StateStoreService.RemoveInstalledPackage:input_type -> state.v1.RemoveInstalledPackageRequest - 0, // 91: state.v1.StateStoreService.RegisterTaskGrant:input_type -> state.v1.RegisterTaskGrantRequest - 2, // 92: state.v1.StateStoreService.RevokeTaskGrant:input_type -> state.v1.RevokeTaskGrantRequest - 6, // 93: state.v1.StateStoreService.ListIdentities:input_type -> state.v1.ListIdentitiesRequest - 8, // 94: state.v1.StateStoreService.GetIdentity:input_type -> state.v1.GetIdentityRequest - 10, // 95: state.v1.StateStoreService.CreateIdentity:input_type -> state.v1.CreateIdentityRequest - 11, // 96: state.v1.StateStoreService.RenameIdentity:input_type -> state.v1.RenameIdentityRequest - 12, // 97: state.v1.StateStoreService.SuspendIdentity:input_type -> state.v1.SuspendIdentityRequest - 13, // 98: state.v1.StateStoreService.ReactivateIdentity:input_type -> state.v1.ReactivateIdentityRequest - 14, // 99: state.v1.StateStoreService.RetireIdentity:input_type -> state.v1.RetireIdentityRequest - 20, // 100: state.v1.StateStoreService.ResolveIdentitySubject:input_type -> state.v1.ResolveIdentitySubjectRequest - 22, // 101: state.v1.StateStoreService.BindIdentitySubject:input_type -> state.v1.BindIdentitySubjectRequest - 38, // 102: state.v1.StateStoreService.EnqueueIssue:input_type -> state.v1.EnqueueIssueRequest - 40, // 103: state.v1.StateStoreService.EnqueueChatTask:input_type -> state.v1.EnqueueChatTaskRequest - 42, // 104: state.v1.StateStoreService.ClaimNext:input_type -> state.v1.ClaimNextRequest - 44, // 105: state.v1.StateStoreService.ClaimByIssue:input_type -> state.v1.ClaimByIssueRequest - 46, // 106: state.v1.StateStoreService.Transition:input_type -> state.v1.TransitionRequest - 48, // 107: state.v1.StateStoreService.Update:input_type -> state.v1.UpdateRequest - 50, // 108: state.v1.StateStoreService.Requeue:input_type -> state.v1.RequeueRequest - 52, // 109: state.v1.StateStoreService.ParkTask:input_type -> state.v1.ParkTaskRequest - 54, // 110: state.v1.StateStoreService.RecoverStale:input_type -> state.v1.RecoverStaleRequest - 56, // 111: state.v1.StateStoreService.ArchiveTask:input_type -> state.v1.ArchiveTaskRequest - 58, // 112: state.v1.StateStoreService.RetryTask:input_type -> state.v1.RetryTaskRequest - 60, // 113: state.v1.StateStoreService.BeginRemediation:input_type -> state.v1.BeginRemediationRequest - 62, // 114: state.v1.StateStoreService.UpdateReviewPayload:input_type -> state.v1.UpdateReviewPayloadRequest - 64, // 115: state.v1.StateStoreService.SetReviewCursors:input_type -> state.v1.SetReviewCursorsRequest - 66, // 116: state.v1.StateStoreService.TaskByIssue:input_type -> state.v1.TaskByIssueRequest - 68, // 117: state.v1.StateStoreService.OpenTaskByPR:input_type -> state.v1.OpenTaskByPRRequest - 70, // 118: state.v1.StateStoreService.TaskByID:input_type -> state.v1.TaskByIDRequest - 72, // 119: state.v1.StateStoreService.OpenPRs:input_type -> state.v1.OpenPRsRequest - 74, // 120: state.v1.StateStoreService.ClearTerminalTasks:input_type -> state.v1.ClearTerminalTasksRequest - 76, // 121: state.v1.StateStoreService.Tasks:input_type -> state.v1.TasksRequest - 78, // 122: state.v1.StateStoreService.StatusCounts:input_type -> state.v1.StatusCountsRequest - 80, // 123: state.v1.StateStoreService.InsertEvent:input_type -> state.v1.InsertEventRequest - 82, // 124: state.v1.StateStoreService.EventsSince:input_type -> state.v1.EventsSinceRequest - 84, // 125: state.v1.StateStoreService.TaskEvents:input_type -> state.v1.TaskEventsRequest - 86, // 126: state.v1.StateStoreService.WorkflowStats:input_type -> state.v1.WorkflowStatsRequest - 88, // 127: state.v1.StateStoreService.StageStats:input_type -> state.v1.StageStatsRequest - 90, // 128: state.v1.StateStoreService.TokensByDay:input_type -> state.v1.TokensByDayRequest - 93, // 129: state.v1.StateStoreService.PutConfigSnapshot:input_type -> state.v1.PutConfigSnapshotRequest - 95, // 130: state.v1.StateStoreService.GetConfigSnapshot:input_type -> state.v1.GetConfigSnapshotRequest - 98, // 131: state.v1.StateStoreService.PutChannelStatus:input_type -> state.v1.PutChannelStatusRequest - 100, // 132: state.v1.StateStoreService.ListChannelStatus:input_type -> state.v1.ListChannelStatusRequest - 103, // 133: state.v1.StateStoreService.PutApplyStatus:input_type -> state.v1.PutApplyStatusRequest - 105, // 134: state.v1.StateStoreService.ListApplyStatus:input_type -> state.v1.ListApplyStatusRequest - 108, // 135: state.v1.StateStoreService.ReadTaskLog:input_type -> state.v1.ReadTaskLogRequest - 110, // 136: state.v1.StateStoreService.StreamTaskLogContent:input_type -> state.v1.StreamTaskLogContentRequest - 112, // 137: state.v1.StateStoreService.InsertCapture:input_type -> state.v1.InsertCaptureRequest - 114, // 138: state.v1.StateStoreService.StreamCaptures:input_type -> state.v1.StreamCapturesRequest - 116, // 139: state.v1.StateStoreService.InsertMapping:input_type -> state.v1.InsertMappingRequest - 118, // 140: state.v1.StateStoreService.GetMapping:input_type -> state.v1.GetMappingRequest - 120, // 141: state.v1.StateStoreService.ListMappings:input_type -> state.v1.ListMappingsRequest - 122, // 142: state.v1.StateStoreService.UpdateMapping:input_type -> state.v1.UpdateMappingRequest - 124, // 143: state.v1.StateStoreService.DeleteMapping:input_type -> state.v1.DeleteMappingRequest - 126, // 144: state.v1.StateStoreService.RecordMappingMatch:input_type -> state.v1.RecordMappingMatchRequest - 128, // 145: state.v1.StateStoreService.InsertEventType:input_type -> state.v1.InsertEventTypeRequest - 130, // 146: state.v1.StateStoreService.UpdateEventType:input_type -> state.v1.UpdateEventTypeRequest - 132, // 147: state.v1.StateStoreService.DeleteEventType:input_type -> state.v1.DeleteEventTypeRequest - 134, // 148: state.v1.StateStoreService.ListEventTypes:input_type -> state.v1.ListEventTypesRequest - 136, // 149: state.v1.StateStoreService.InsertBinding:input_type -> state.v1.InsertBindingRequest - 138, // 150: state.v1.StateStoreService.GetBinding:input_type -> state.v1.GetBindingRequest - 140, // 151: state.v1.StateStoreService.ListBindings:input_type -> state.v1.ListBindingsRequest - 142, // 152: state.v1.StateStoreService.UpdateBinding:input_type -> state.v1.UpdateBindingRequest - 144, // 153: state.v1.StateStoreService.DeleteBinding:input_type -> state.v1.DeleteBindingRequest - 146, // 154: state.v1.StateStoreService.ApproveBinding:input_type -> state.v1.ApproveBindingRequest - 148, // 155: state.v1.StateStoreService.InsertSource:input_type -> state.v1.InsertSourceRequest - 150, // 156: state.v1.StateStoreService.GetSource:input_type -> state.v1.GetSourceRequest - 152, // 157: state.v1.StateStoreService.ListSources:input_type -> state.v1.ListSourcesRequest - 154, // 158: state.v1.StateStoreService.SetSourceSigning:input_type -> state.v1.SetSourceSigningRequest - 156, // 159: state.v1.StateStoreService.SetSourceSecret:input_type -> state.v1.SetSourceSecretRequest - 158, // 160: state.v1.StateStoreService.ArmedBindingsForSource:input_type -> state.v1.ArmedBindingsForSourceRequest - 160, // 161: state.v1.StateStoreService.RecordDispatch:input_type -> state.v1.RecordDispatchRequest - 162, // 162: state.v1.StateStoreService.RecordPlaybookDispatch:input_type -> state.v1.RecordPlaybookDispatchRequest - 164, // 163: state.v1.StateStoreService.DeletePlaybookDispatches:input_type -> state.v1.DeletePlaybookDispatchesRequest - 166, // 164: state.v1.StateStoreService.StreamUndispatchedCaptures:input_type -> state.v1.StreamUndispatchedCapturesRequest - 168, // 165: state.v1.StateStoreService.EnqueueBindingTask:input_type -> state.v1.EnqueueBindingTaskRequest - 172, // 166: state.v1.StateStoreService.InstallPackage:output_type -> state.v1.InstallPackageResponse - 174, // 167: state.v1.StateStoreService.GetInstalledPackage:output_type -> state.v1.GetInstalledPackageResponse - 176, // 168: state.v1.StateStoreService.ListInstalledPackages:output_type -> state.v1.ListInstalledPackagesResponse - 178, // 169: state.v1.StateStoreService.RemoveInstalledPackage:output_type -> state.v1.RemoveInstalledPackageResponse - 1, // 170: state.v1.StateStoreService.RegisterTaskGrant:output_type -> state.v1.RegisterTaskGrantResponse - 3, // 171: state.v1.StateStoreService.RevokeTaskGrant:output_type -> state.v1.RevokeTaskGrantResponse - 7, // 172: state.v1.StateStoreService.ListIdentities:output_type -> state.v1.ListIdentitiesResponse - 9, // 173: state.v1.StateStoreService.GetIdentity:output_type -> state.v1.GetIdentityResponse - 15, // 174: state.v1.StateStoreService.CreateIdentity:output_type -> state.v1.CreateIdentityResponse - 16, // 175: state.v1.StateStoreService.RenameIdentity:output_type -> state.v1.RenameIdentityResponse - 17, // 176: state.v1.StateStoreService.SuspendIdentity:output_type -> state.v1.SuspendIdentityResponse - 18, // 177: state.v1.StateStoreService.ReactivateIdentity:output_type -> state.v1.ReactivateIdentityResponse - 19, // 178: state.v1.StateStoreService.RetireIdentity:output_type -> state.v1.RetireIdentityResponse - 21, // 179: state.v1.StateStoreService.ResolveIdentitySubject:output_type -> state.v1.ResolveIdentitySubjectResponse - 23, // 180: state.v1.StateStoreService.BindIdentitySubject:output_type -> state.v1.BindIdentitySubjectResponse - 39, // 181: state.v1.StateStoreService.EnqueueIssue:output_type -> state.v1.EnqueueIssueResponse - 41, // 182: state.v1.StateStoreService.EnqueueChatTask:output_type -> state.v1.EnqueueChatTaskResponse - 43, // 183: state.v1.StateStoreService.ClaimNext:output_type -> state.v1.ClaimNextResponse - 45, // 184: state.v1.StateStoreService.ClaimByIssue:output_type -> state.v1.ClaimByIssueResponse - 47, // 185: state.v1.StateStoreService.Transition:output_type -> state.v1.TransitionResponse - 49, // 186: state.v1.StateStoreService.Update:output_type -> state.v1.UpdateResponse - 51, // 187: state.v1.StateStoreService.Requeue:output_type -> state.v1.RequeueResponse - 53, // 188: state.v1.StateStoreService.ParkTask:output_type -> state.v1.ParkTaskResponse - 55, // 189: state.v1.StateStoreService.RecoverStale:output_type -> state.v1.RecoverStaleResponse - 57, // 190: state.v1.StateStoreService.ArchiveTask:output_type -> state.v1.ArchiveTaskResponse - 59, // 191: state.v1.StateStoreService.RetryTask:output_type -> state.v1.RetryTaskResponse - 61, // 192: state.v1.StateStoreService.BeginRemediation:output_type -> state.v1.BeginRemediationResponse - 63, // 193: state.v1.StateStoreService.UpdateReviewPayload:output_type -> state.v1.UpdateReviewPayloadResponse - 65, // 194: state.v1.StateStoreService.SetReviewCursors:output_type -> state.v1.SetReviewCursorsResponse - 67, // 195: state.v1.StateStoreService.TaskByIssue:output_type -> state.v1.TaskByIssueResponse - 69, // 196: state.v1.StateStoreService.OpenTaskByPR:output_type -> state.v1.OpenTaskByPRResponse - 71, // 197: state.v1.StateStoreService.TaskByID:output_type -> state.v1.TaskByIDResponse - 73, // 198: state.v1.StateStoreService.OpenPRs:output_type -> state.v1.OpenPRsResponse - 75, // 199: state.v1.StateStoreService.ClearTerminalTasks:output_type -> state.v1.ClearTerminalTasksResponse - 77, // 200: state.v1.StateStoreService.Tasks:output_type -> state.v1.TasksResponse - 79, // 201: state.v1.StateStoreService.StatusCounts:output_type -> state.v1.StatusCountsResponse - 81, // 202: state.v1.StateStoreService.InsertEvent:output_type -> state.v1.InsertEventResponse - 83, // 203: state.v1.StateStoreService.EventsSince:output_type -> state.v1.EventsSinceResponse - 85, // 204: state.v1.StateStoreService.TaskEvents:output_type -> state.v1.TaskEventsResponse - 87, // 205: state.v1.StateStoreService.WorkflowStats:output_type -> state.v1.WorkflowStatsResponse - 89, // 206: state.v1.StateStoreService.StageStats:output_type -> state.v1.StageStatsResponse - 91, // 207: state.v1.StateStoreService.TokensByDay:output_type -> state.v1.TokensByDayResponse - 94, // 208: state.v1.StateStoreService.PutConfigSnapshot:output_type -> state.v1.PutConfigSnapshotResponse - 96, // 209: state.v1.StateStoreService.GetConfigSnapshot:output_type -> state.v1.GetConfigSnapshotResponse - 99, // 210: state.v1.StateStoreService.PutChannelStatus:output_type -> state.v1.PutChannelStatusResponse - 101, // 211: state.v1.StateStoreService.ListChannelStatus:output_type -> state.v1.ListChannelStatusResponse - 104, // 212: state.v1.StateStoreService.PutApplyStatus:output_type -> state.v1.PutApplyStatusResponse - 106, // 213: state.v1.StateStoreService.ListApplyStatus:output_type -> state.v1.ListApplyStatusResponse - 109, // 214: state.v1.StateStoreService.ReadTaskLog:output_type -> state.v1.ReadTaskLogResponse - 111, // 215: state.v1.StateStoreService.StreamTaskLogContent:output_type -> state.v1.StreamTaskLogContentResponse - 113, // 216: state.v1.StateStoreService.InsertCapture:output_type -> state.v1.InsertCaptureResponse - 115, // 217: state.v1.StateStoreService.StreamCaptures:output_type -> state.v1.StreamCapturesResponse - 117, // 218: state.v1.StateStoreService.InsertMapping:output_type -> state.v1.InsertMappingResponse - 119, // 219: state.v1.StateStoreService.GetMapping:output_type -> state.v1.GetMappingResponse - 121, // 220: state.v1.StateStoreService.ListMappings:output_type -> state.v1.ListMappingsResponse - 123, // 221: state.v1.StateStoreService.UpdateMapping:output_type -> state.v1.UpdateMappingResponse - 125, // 222: state.v1.StateStoreService.DeleteMapping:output_type -> state.v1.DeleteMappingResponse - 127, // 223: state.v1.StateStoreService.RecordMappingMatch:output_type -> state.v1.RecordMappingMatchResponse - 129, // 224: state.v1.StateStoreService.InsertEventType:output_type -> state.v1.InsertEventTypeResponse - 131, // 225: state.v1.StateStoreService.UpdateEventType:output_type -> state.v1.UpdateEventTypeResponse - 133, // 226: state.v1.StateStoreService.DeleteEventType:output_type -> state.v1.DeleteEventTypeResponse - 135, // 227: state.v1.StateStoreService.ListEventTypes:output_type -> state.v1.ListEventTypesResponse - 137, // 228: state.v1.StateStoreService.InsertBinding:output_type -> state.v1.InsertBindingResponse - 139, // 229: state.v1.StateStoreService.GetBinding:output_type -> state.v1.GetBindingResponse - 141, // 230: state.v1.StateStoreService.ListBindings:output_type -> state.v1.ListBindingsResponse - 143, // 231: state.v1.StateStoreService.UpdateBinding:output_type -> state.v1.UpdateBindingResponse - 145, // 232: state.v1.StateStoreService.DeleteBinding:output_type -> state.v1.DeleteBindingResponse - 147, // 233: state.v1.StateStoreService.ApproveBinding:output_type -> state.v1.ApproveBindingResponse - 149, // 234: state.v1.StateStoreService.InsertSource:output_type -> state.v1.InsertSourceResponse - 151, // 235: state.v1.StateStoreService.GetSource:output_type -> state.v1.GetSourceResponse - 153, // 236: state.v1.StateStoreService.ListSources:output_type -> state.v1.ListSourcesResponse - 155, // 237: state.v1.StateStoreService.SetSourceSigning:output_type -> state.v1.SetSourceSigningResponse - 157, // 238: state.v1.StateStoreService.SetSourceSecret:output_type -> state.v1.SetSourceSecretResponse - 159, // 239: state.v1.StateStoreService.ArmedBindingsForSource:output_type -> state.v1.ArmedBindingsForSourceResponse - 161, // 240: state.v1.StateStoreService.RecordDispatch:output_type -> state.v1.RecordDispatchResponse - 163, // 241: state.v1.StateStoreService.RecordPlaybookDispatch:output_type -> state.v1.RecordPlaybookDispatchResponse - 165, // 242: state.v1.StateStoreService.DeletePlaybookDispatches:output_type -> state.v1.DeletePlaybookDispatchesResponse - 167, // 243: state.v1.StateStoreService.StreamUndispatchedCaptures:output_type -> state.v1.StreamUndispatchedCapturesResponse - 169, // 244: state.v1.StateStoreService.EnqueueBindingTask:output_type -> state.v1.EnqueueBindingTaskResponse - 166, // [166:245] is the sub-list for method output_type - 87, // [87:166] is the sub-list for method input_type - 87, // [87:87] is the sub-list for extension type_name - 87, // [87:87] is the sub-list for extension extendee - 0, // [0:87] is the sub-list for field type_name + 24, // 84: state.v1.EnqueueCallTaskResponse.task:type_name -> state.v1.Task + 174, // 85: state.v1.InstallPackageResponse.package:type_name -> state.v1.InstalledPackage + 174, // 86: state.v1.GetInstalledPackageResponse.package:type_name -> state.v1.InstalledPackage + 174, // 87: state.v1.ListInstalledPackagesResponse.packages:type_name -> state.v1.InstalledPackage + 175, // 88: state.v1.StateStoreService.InstallPackage:input_type -> state.v1.InstallPackageRequest + 177, // 89: state.v1.StateStoreService.GetInstalledPackage:input_type -> state.v1.GetInstalledPackageRequest + 179, // 90: state.v1.StateStoreService.ListInstalledPackages:input_type -> state.v1.ListInstalledPackagesRequest + 181, // 91: state.v1.StateStoreService.RemoveInstalledPackage:input_type -> state.v1.RemoveInstalledPackageRequest + 0, // 92: state.v1.StateStoreService.RegisterTaskGrant:input_type -> state.v1.RegisterTaskGrantRequest + 2, // 93: state.v1.StateStoreService.RevokeTaskGrant:input_type -> state.v1.RevokeTaskGrantRequest + 6, // 94: state.v1.StateStoreService.ListIdentities:input_type -> state.v1.ListIdentitiesRequest + 8, // 95: state.v1.StateStoreService.GetIdentity:input_type -> state.v1.GetIdentityRequest + 10, // 96: state.v1.StateStoreService.CreateIdentity:input_type -> state.v1.CreateIdentityRequest + 11, // 97: state.v1.StateStoreService.RenameIdentity:input_type -> state.v1.RenameIdentityRequest + 12, // 98: state.v1.StateStoreService.SuspendIdentity:input_type -> state.v1.SuspendIdentityRequest + 13, // 99: state.v1.StateStoreService.ReactivateIdentity:input_type -> state.v1.ReactivateIdentityRequest + 14, // 100: state.v1.StateStoreService.RetireIdentity:input_type -> state.v1.RetireIdentityRequest + 20, // 101: state.v1.StateStoreService.ResolveIdentitySubject:input_type -> state.v1.ResolveIdentitySubjectRequest + 22, // 102: state.v1.StateStoreService.BindIdentitySubject:input_type -> state.v1.BindIdentitySubjectRequest + 38, // 103: state.v1.StateStoreService.EnqueueIssue:input_type -> state.v1.EnqueueIssueRequest + 40, // 104: state.v1.StateStoreService.EnqueueChatTask:input_type -> state.v1.EnqueueChatTaskRequest + 42, // 105: state.v1.StateStoreService.ClaimNext:input_type -> state.v1.ClaimNextRequest + 44, // 106: state.v1.StateStoreService.ClaimByIssue:input_type -> state.v1.ClaimByIssueRequest + 46, // 107: state.v1.StateStoreService.Transition:input_type -> state.v1.TransitionRequest + 48, // 108: state.v1.StateStoreService.Update:input_type -> state.v1.UpdateRequest + 50, // 109: state.v1.StateStoreService.Requeue:input_type -> state.v1.RequeueRequest + 52, // 110: state.v1.StateStoreService.ParkTask:input_type -> state.v1.ParkTaskRequest + 54, // 111: state.v1.StateStoreService.RecoverStale:input_type -> state.v1.RecoverStaleRequest + 56, // 112: state.v1.StateStoreService.ArchiveTask:input_type -> state.v1.ArchiveTaskRequest + 58, // 113: state.v1.StateStoreService.RetryTask:input_type -> state.v1.RetryTaskRequest + 60, // 114: state.v1.StateStoreService.BeginRemediation:input_type -> state.v1.BeginRemediationRequest + 62, // 115: state.v1.StateStoreService.UpdateReviewPayload:input_type -> state.v1.UpdateReviewPayloadRequest + 64, // 116: state.v1.StateStoreService.SetReviewCursors:input_type -> state.v1.SetReviewCursorsRequest + 66, // 117: state.v1.StateStoreService.TaskByIssue:input_type -> state.v1.TaskByIssueRequest + 68, // 118: state.v1.StateStoreService.OpenTaskByPR:input_type -> state.v1.OpenTaskByPRRequest + 70, // 119: state.v1.StateStoreService.TaskByID:input_type -> state.v1.TaskByIDRequest + 72, // 120: state.v1.StateStoreService.OpenPRs:input_type -> state.v1.OpenPRsRequest + 74, // 121: state.v1.StateStoreService.ClearTerminalTasks:input_type -> state.v1.ClearTerminalTasksRequest + 76, // 122: state.v1.StateStoreService.Tasks:input_type -> state.v1.TasksRequest + 78, // 123: state.v1.StateStoreService.StatusCounts:input_type -> state.v1.StatusCountsRequest + 80, // 124: state.v1.StateStoreService.InsertEvent:input_type -> state.v1.InsertEventRequest + 82, // 125: state.v1.StateStoreService.EventsSince:input_type -> state.v1.EventsSinceRequest + 84, // 126: state.v1.StateStoreService.TaskEvents:input_type -> state.v1.TaskEventsRequest + 86, // 127: state.v1.StateStoreService.WorkflowStats:input_type -> state.v1.WorkflowStatsRequest + 88, // 128: state.v1.StateStoreService.StageStats:input_type -> state.v1.StageStatsRequest + 90, // 129: state.v1.StateStoreService.TokensByDay:input_type -> state.v1.TokensByDayRequest + 93, // 130: state.v1.StateStoreService.PutConfigSnapshot:input_type -> state.v1.PutConfigSnapshotRequest + 95, // 131: state.v1.StateStoreService.GetConfigSnapshot:input_type -> state.v1.GetConfigSnapshotRequest + 98, // 132: state.v1.StateStoreService.PutChannelStatus:input_type -> state.v1.PutChannelStatusRequest + 100, // 133: state.v1.StateStoreService.ListChannelStatus:input_type -> state.v1.ListChannelStatusRequest + 103, // 134: state.v1.StateStoreService.PutApplyStatus:input_type -> state.v1.PutApplyStatusRequest + 105, // 135: state.v1.StateStoreService.ListApplyStatus:input_type -> state.v1.ListApplyStatusRequest + 108, // 136: state.v1.StateStoreService.ReadTaskLog:input_type -> state.v1.ReadTaskLogRequest + 110, // 137: state.v1.StateStoreService.StreamTaskLogContent:input_type -> state.v1.StreamTaskLogContentRequest + 112, // 138: state.v1.StateStoreService.InsertCapture:input_type -> state.v1.InsertCaptureRequest + 114, // 139: state.v1.StateStoreService.StreamCaptures:input_type -> state.v1.StreamCapturesRequest + 116, // 140: state.v1.StateStoreService.InsertMapping:input_type -> state.v1.InsertMappingRequest + 118, // 141: state.v1.StateStoreService.GetMapping:input_type -> state.v1.GetMappingRequest + 120, // 142: state.v1.StateStoreService.ListMappings:input_type -> state.v1.ListMappingsRequest + 122, // 143: state.v1.StateStoreService.UpdateMapping:input_type -> state.v1.UpdateMappingRequest + 124, // 144: state.v1.StateStoreService.DeleteMapping:input_type -> state.v1.DeleteMappingRequest + 126, // 145: state.v1.StateStoreService.RecordMappingMatch:input_type -> state.v1.RecordMappingMatchRequest + 128, // 146: state.v1.StateStoreService.InsertEventType:input_type -> state.v1.InsertEventTypeRequest + 130, // 147: state.v1.StateStoreService.UpdateEventType:input_type -> state.v1.UpdateEventTypeRequest + 132, // 148: state.v1.StateStoreService.DeleteEventType:input_type -> state.v1.DeleteEventTypeRequest + 134, // 149: state.v1.StateStoreService.ListEventTypes:input_type -> state.v1.ListEventTypesRequest + 136, // 150: state.v1.StateStoreService.InsertBinding:input_type -> state.v1.InsertBindingRequest + 138, // 151: state.v1.StateStoreService.GetBinding:input_type -> state.v1.GetBindingRequest + 140, // 152: state.v1.StateStoreService.ListBindings:input_type -> state.v1.ListBindingsRequest + 142, // 153: state.v1.StateStoreService.UpdateBinding:input_type -> state.v1.UpdateBindingRequest + 144, // 154: state.v1.StateStoreService.DeleteBinding:input_type -> state.v1.DeleteBindingRequest + 146, // 155: state.v1.StateStoreService.ApproveBinding:input_type -> state.v1.ApproveBindingRequest + 148, // 156: state.v1.StateStoreService.InsertSource:input_type -> state.v1.InsertSourceRequest + 150, // 157: state.v1.StateStoreService.GetSource:input_type -> state.v1.GetSourceRequest + 152, // 158: state.v1.StateStoreService.ListSources:input_type -> state.v1.ListSourcesRequest + 154, // 159: state.v1.StateStoreService.SetSourceSigning:input_type -> state.v1.SetSourceSigningRequest + 156, // 160: state.v1.StateStoreService.SetSourceSecret:input_type -> state.v1.SetSourceSecretRequest + 158, // 161: state.v1.StateStoreService.ArmedBindingsForSource:input_type -> state.v1.ArmedBindingsForSourceRequest + 160, // 162: state.v1.StateStoreService.RecordDispatch:input_type -> state.v1.RecordDispatchRequest + 162, // 163: state.v1.StateStoreService.RecordPlaybookDispatch:input_type -> state.v1.RecordPlaybookDispatchRequest + 164, // 164: state.v1.StateStoreService.DeletePlaybookDispatches:input_type -> state.v1.DeletePlaybookDispatchesRequest + 166, // 165: state.v1.StateStoreService.StreamUndispatchedCaptures:input_type -> state.v1.StreamUndispatchedCapturesRequest + 168, // 166: state.v1.StateStoreService.EnqueueBindingTask:input_type -> state.v1.EnqueueBindingTaskRequest + 170, // 167: state.v1.StateStoreService.EnqueueCallTask:input_type -> state.v1.EnqueueCallTaskRequest + 172, // 168: state.v1.StateStoreService.WorkflowCallStatus:input_type -> state.v1.WorkflowCallStatusRequest + 176, // 169: state.v1.StateStoreService.InstallPackage:output_type -> state.v1.InstallPackageResponse + 178, // 170: state.v1.StateStoreService.GetInstalledPackage:output_type -> state.v1.GetInstalledPackageResponse + 180, // 171: state.v1.StateStoreService.ListInstalledPackages:output_type -> state.v1.ListInstalledPackagesResponse + 182, // 172: state.v1.StateStoreService.RemoveInstalledPackage:output_type -> state.v1.RemoveInstalledPackageResponse + 1, // 173: state.v1.StateStoreService.RegisterTaskGrant:output_type -> state.v1.RegisterTaskGrantResponse + 3, // 174: state.v1.StateStoreService.RevokeTaskGrant:output_type -> state.v1.RevokeTaskGrantResponse + 7, // 175: state.v1.StateStoreService.ListIdentities:output_type -> state.v1.ListIdentitiesResponse + 9, // 176: state.v1.StateStoreService.GetIdentity:output_type -> state.v1.GetIdentityResponse + 15, // 177: state.v1.StateStoreService.CreateIdentity:output_type -> state.v1.CreateIdentityResponse + 16, // 178: state.v1.StateStoreService.RenameIdentity:output_type -> state.v1.RenameIdentityResponse + 17, // 179: state.v1.StateStoreService.SuspendIdentity:output_type -> state.v1.SuspendIdentityResponse + 18, // 180: state.v1.StateStoreService.ReactivateIdentity:output_type -> state.v1.ReactivateIdentityResponse + 19, // 181: state.v1.StateStoreService.RetireIdentity:output_type -> state.v1.RetireIdentityResponse + 21, // 182: state.v1.StateStoreService.ResolveIdentitySubject:output_type -> state.v1.ResolveIdentitySubjectResponse + 23, // 183: state.v1.StateStoreService.BindIdentitySubject:output_type -> state.v1.BindIdentitySubjectResponse + 39, // 184: state.v1.StateStoreService.EnqueueIssue:output_type -> state.v1.EnqueueIssueResponse + 41, // 185: state.v1.StateStoreService.EnqueueChatTask:output_type -> state.v1.EnqueueChatTaskResponse + 43, // 186: state.v1.StateStoreService.ClaimNext:output_type -> state.v1.ClaimNextResponse + 45, // 187: state.v1.StateStoreService.ClaimByIssue:output_type -> state.v1.ClaimByIssueResponse + 47, // 188: state.v1.StateStoreService.Transition:output_type -> state.v1.TransitionResponse + 49, // 189: state.v1.StateStoreService.Update:output_type -> state.v1.UpdateResponse + 51, // 190: state.v1.StateStoreService.Requeue:output_type -> state.v1.RequeueResponse + 53, // 191: state.v1.StateStoreService.ParkTask:output_type -> state.v1.ParkTaskResponse + 55, // 192: state.v1.StateStoreService.RecoverStale:output_type -> state.v1.RecoverStaleResponse + 57, // 193: state.v1.StateStoreService.ArchiveTask:output_type -> state.v1.ArchiveTaskResponse + 59, // 194: state.v1.StateStoreService.RetryTask:output_type -> state.v1.RetryTaskResponse + 61, // 195: state.v1.StateStoreService.BeginRemediation:output_type -> state.v1.BeginRemediationResponse + 63, // 196: state.v1.StateStoreService.UpdateReviewPayload:output_type -> state.v1.UpdateReviewPayloadResponse + 65, // 197: state.v1.StateStoreService.SetReviewCursors:output_type -> state.v1.SetReviewCursorsResponse + 67, // 198: state.v1.StateStoreService.TaskByIssue:output_type -> state.v1.TaskByIssueResponse + 69, // 199: state.v1.StateStoreService.OpenTaskByPR:output_type -> state.v1.OpenTaskByPRResponse + 71, // 200: state.v1.StateStoreService.TaskByID:output_type -> state.v1.TaskByIDResponse + 73, // 201: state.v1.StateStoreService.OpenPRs:output_type -> state.v1.OpenPRsResponse + 75, // 202: state.v1.StateStoreService.ClearTerminalTasks:output_type -> state.v1.ClearTerminalTasksResponse + 77, // 203: state.v1.StateStoreService.Tasks:output_type -> state.v1.TasksResponse + 79, // 204: state.v1.StateStoreService.StatusCounts:output_type -> state.v1.StatusCountsResponse + 81, // 205: state.v1.StateStoreService.InsertEvent:output_type -> state.v1.InsertEventResponse + 83, // 206: state.v1.StateStoreService.EventsSince:output_type -> state.v1.EventsSinceResponse + 85, // 207: state.v1.StateStoreService.TaskEvents:output_type -> state.v1.TaskEventsResponse + 87, // 208: state.v1.StateStoreService.WorkflowStats:output_type -> state.v1.WorkflowStatsResponse + 89, // 209: state.v1.StateStoreService.StageStats:output_type -> state.v1.StageStatsResponse + 91, // 210: state.v1.StateStoreService.TokensByDay:output_type -> state.v1.TokensByDayResponse + 94, // 211: state.v1.StateStoreService.PutConfigSnapshot:output_type -> state.v1.PutConfigSnapshotResponse + 96, // 212: state.v1.StateStoreService.GetConfigSnapshot:output_type -> state.v1.GetConfigSnapshotResponse + 99, // 213: state.v1.StateStoreService.PutChannelStatus:output_type -> state.v1.PutChannelStatusResponse + 101, // 214: state.v1.StateStoreService.ListChannelStatus:output_type -> state.v1.ListChannelStatusResponse + 104, // 215: state.v1.StateStoreService.PutApplyStatus:output_type -> state.v1.PutApplyStatusResponse + 106, // 216: state.v1.StateStoreService.ListApplyStatus:output_type -> state.v1.ListApplyStatusResponse + 109, // 217: state.v1.StateStoreService.ReadTaskLog:output_type -> state.v1.ReadTaskLogResponse + 111, // 218: state.v1.StateStoreService.StreamTaskLogContent:output_type -> state.v1.StreamTaskLogContentResponse + 113, // 219: state.v1.StateStoreService.InsertCapture:output_type -> state.v1.InsertCaptureResponse + 115, // 220: state.v1.StateStoreService.StreamCaptures:output_type -> state.v1.StreamCapturesResponse + 117, // 221: state.v1.StateStoreService.InsertMapping:output_type -> state.v1.InsertMappingResponse + 119, // 222: state.v1.StateStoreService.GetMapping:output_type -> state.v1.GetMappingResponse + 121, // 223: state.v1.StateStoreService.ListMappings:output_type -> state.v1.ListMappingsResponse + 123, // 224: state.v1.StateStoreService.UpdateMapping:output_type -> state.v1.UpdateMappingResponse + 125, // 225: state.v1.StateStoreService.DeleteMapping:output_type -> state.v1.DeleteMappingResponse + 127, // 226: state.v1.StateStoreService.RecordMappingMatch:output_type -> state.v1.RecordMappingMatchResponse + 129, // 227: state.v1.StateStoreService.InsertEventType:output_type -> state.v1.InsertEventTypeResponse + 131, // 228: state.v1.StateStoreService.UpdateEventType:output_type -> state.v1.UpdateEventTypeResponse + 133, // 229: state.v1.StateStoreService.DeleteEventType:output_type -> state.v1.DeleteEventTypeResponse + 135, // 230: state.v1.StateStoreService.ListEventTypes:output_type -> state.v1.ListEventTypesResponse + 137, // 231: state.v1.StateStoreService.InsertBinding:output_type -> state.v1.InsertBindingResponse + 139, // 232: state.v1.StateStoreService.GetBinding:output_type -> state.v1.GetBindingResponse + 141, // 233: state.v1.StateStoreService.ListBindings:output_type -> state.v1.ListBindingsResponse + 143, // 234: state.v1.StateStoreService.UpdateBinding:output_type -> state.v1.UpdateBindingResponse + 145, // 235: state.v1.StateStoreService.DeleteBinding:output_type -> state.v1.DeleteBindingResponse + 147, // 236: state.v1.StateStoreService.ApproveBinding:output_type -> state.v1.ApproveBindingResponse + 149, // 237: state.v1.StateStoreService.InsertSource:output_type -> state.v1.InsertSourceResponse + 151, // 238: state.v1.StateStoreService.GetSource:output_type -> state.v1.GetSourceResponse + 153, // 239: state.v1.StateStoreService.ListSources:output_type -> state.v1.ListSourcesResponse + 155, // 240: state.v1.StateStoreService.SetSourceSigning:output_type -> state.v1.SetSourceSigningResponse + 157, // 241: state.v1.StateStoreService.SetSourceSecret:output_type -> state.v1.SetSourceSecretResponse + 159, // 242: state.v1.StateStoreService.ArmedBindingsForSource:output_type -> state.v1.ArmedBindingsForSourceResponse + 161, // 243: state.v1.StateStoreService.RecordDispatch:output_type -> state.v1.RecordDispatchResponse + 163, // 244: state.v1.StateStoreService.RecordPlaybookDispatch:output_type -> state.v1.RecordPlaybookDispatchResponse + 165, // 245: state.v1.StateStoreService.DeletePlaybookDispatches:output_type -> state.v1.DeletePlaybookDispatchesResponse + 167, // 246: state.v1.StateStoreService.StreamUndispatchedCaptures:output_type -> state.v1.StreamUndispatchedCapturesResponse + 169, // 247: state.v1.StateStoreService.EnqueueBindingTask:output_type -> state.v1.EnqueueBindingTaskResponse + 171, // 248: state.v1.StateStoreService.EnqueueCallTask:output_type -> state.v1.EnqueueCallTaskResponse + 173, // 249: state.v1.StateStoreService.WorkflowCallStatus:output_type -> state.v1.WorkflowCallStatusResponse + 169, // [169:250] is the sub-list for method output_type + 88, // [88:169] is the sub-list for method input_type + 88, // [88:88] is the sub-list for extension type_name + 88, // [88:88] is the sub-list for extension extendee + 0, // [0:88] is the sub-list for field type_name } func init() { file_state_v1_state_proto_init() } @@ -10756,7 +11025,7 @@ func file_state_v1_state_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_state_v1_state_proto_rawDesc), len(file_state_v1_state_proto_rawDesc)), NumEnums: 0, - NumMessages: 181, + NumMessages: 185, NumExtensions: 0, NumServices: 1, }, diff --git a/internal/contracts/state/v1/state_grpc.pb.go b/internal/contracts/state/v1/state_grpc.pb.go index dace4c13c..967633d44 100644 --- a/internal/contracts/state/v1/state_grpc.pb.go +++ b/internal/contracts/state/v1/state_grpc.pb.go @@ -98,6 +98,8 @@ const ( StateStoreService_DeletePlaybookDispatches_FullMethodName = "/state.v1.StateStoreService/DeletePlaybookDispatches" StateStoreService_StreamUndispatchedCaptures_FullMethodName = "/state.v1.StateStoreService/StreamUndispatchedCaptures" StateStoreService_EnqueueBindingTask_FullMethodName = "/state.v1.StateStoreService/EnqueueBindingTask" + StateStoreService_EnqueueCallTask_FullMethodName = "/state.v1.StateStoreService/EnqueueCallTask" + StateStoreService_WorkflowCallStatus_FullMethodName = "/state.v1.StateStoreService/WorkflowCallStatus" ) // StateStoreServiceClient is the client API for StateStoreService service. @@ -243,6 +245,13 @@ type StateStoreServiceClient interface { StreamUndispatchedCaptures(ctx context.Context, in *StreamUndispatchedCapturesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[StreamUndispatchedCapturesResponse], error) // BindingTaskCreator EnqueueBindingTask(ctx context.Context, in *EnqueueBindingTaskRequest, opts ...grpc.CallOption) (*EnqueueBindingTaskResponse, error) + // WorkflowCaller: a workflow.call step starts its callee and, with + // wait:true, reads it back while waiting. Both are the one sanctioned + // widening of a task-scoped grant -- the callee is the caller's child + // (docs/prds/workflow-calls.md). CallStatus re-checks the parent-child + // relation server-side, so the grant only names the caller. + EnqueueCallTask(ctx context.Context, in *EnqueueCallTaskRequest, opts ...grpc.CallOption) (*EnqueueCallTaskResponse, error) + WorkflowCallStatus(ctx context.Context, in *WorkflowCallStatusRequest, opts ...grpc.CallOption) (*WorkflowCallStatusResponse, error) } type stateStoreServiceClient struct { @@ -1070,6 +1079,26 @@ func (c *stateStoreServiceClient) EnqueueBindingTask(ctx context.Context, in *En return out, nil } +func (c *stateStoreServiceClient) EnqueueCallTask(ctx context.Context, in *EnqueueCallTaskRequest, opts ...grpc.CallOption) (*EnqueueCallTaskResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(EnqueueCallTaskResponse) + err := c.cc.Invoke(ctx, StateStoreService_EnqueueCallTask_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *stateStoreServiceClient) WorkflowCallStatus(ctx context.Context, in *WorkflowCallStatusRequest, opts ...grpc.CallOption) (*WorkflowCallStatusResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(WorkflowCallStatusResponse) + err := c.cc.Invoke(ctx, StateStoreService_WorkflowCallStatus_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + // StateStoreServiceServer is the server API for StateStoreService service. // All implementations must embed UnimplementedStateStoreServiceServer // for forward compatibility. @@ -1213,6 +1242,13 @@ type StateStoreServiceServer interface { StreamUndispatchedCaptures(*StreamUndispatchedCapturesRequest, grpc.ServerStreamingServer[StreamUndispatchedCapturesResponse]) error // BindingTaskCreator EnqueueBindingTask(context.Context, *EnqueueBindingTaskRequest) (*EnqueueBindingTaskResponse, error) + // WorkflowCaller: a workflow.call step starts its callee and, with + // wait:true, reads it back while waiting. Both are the one sanctioned + // widening of a task-scoped grant -- the callee is the caller's child + // (docs/prds/workflow-calls.md). CallStatus re-checks the parent-child + // relation server-side, so the grant only names the caller. + EnqueueCallTask(context.Context, *EnqueueCallTaskRequest) (*EnqueueCallTaskResponse, error) + WorkflowCallStatus(context.Context, *WorkflowCallStatusRequest) (*WorkflowCallStatusResponse, error) mustEmbedUnimplementedStateStoreServiceServer() } @@ -1460,6 +1496,12 @@ func (UnimplementedStateStoreServiceServer) StreamUndispatchedCaptures(*StreamUn func (UnimplementedStateStoreServiceServer) EnqueueBindingTask(context.Context, *EnqueueBindingTaskRequest) (*EnqueueBindingTaskResponse, error) { return nil, status.Error(codes.Unimplemented, "method EnqueueBindingTask not implemented") } +func (UnimplementedStateStoreServiceServer) EnqueueCallTask(context.Context, *EnqueueCallTaskRequest) (*EnqueueCallTaskResponse, error) { + return nil, status.Error(codes.Unimplemented, "method EnqueueCallTask not implemented") +} +func (UnimplementedStateStoreServiceServer) WorkflowCallStatus(context.Context, *WorkflowCallStatusRequest) (*WorkflowCallStatusResponse, error) { + return nil, status.Error(codes.Unimplemented, "method WorkflowCallStatus not implemented") +} func (UnimplementedStateStoreServiceServer) mustEmbedUnimplementedStateStoreServiceServer() {} func (UnimplementedStateStoreServiceServer) testEmbeddedByValue() {} @@ -2882,6 +2924,42 @@ func _StateStoreService_EnqueueBindingTask_Handler(srv interface{}, ctx context. return interceptor(ctx, in, info, handler) } +func _StateStoreService_EnqueueCallTask_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(EnqueueCallTaskRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(StateStoreServiceServer).EnqueueCallTask(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: StateStoreService_EnqueueCallTask_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(StateStoreServiceServer).EnqueueCallTask(ctx, req.(*EnqueueCallTaskRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _StateStoreService_WorkflowCallStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(WorkflowCallStatusRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(StateStoreServiceServer).WorkflowCallStatus(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: StateStoreService_WorkflowCallStatus_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(StateStoreServiceServer).WorkflowCallStatus(ctx, req.(*WorkflowCallStatusRequest)) + } + return interceptor(ctx, in, info, handler) +} + // StateStoreService_ServiceDesc is the grpc.ServiceDesc for StateStoreService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -3193,6 +3271,14 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{ MethodName: "EnqueueBindingTask", Handler: _StateStoreService_EnqueueBindingTask_Handler, }, + { + MethodName: "EnqueueCallTask", + Handler: _StateStoreService_EnqueueCallTask_Handler, + }, + { + MethodName: "WorkflowCallStatus", + Handler: _StateStoreService_WorkflowCallStatus_Handler, + }, }, Streams: []grpc.StreamDesc{ { diff --git a/internal/domain/storecontract/storecontract.go b/internal/domain/storecontract/storecontract.go index f4a16a4ba..c577891d7 100644 --- a/internal/domain/storecontract/storecontract.go +++ b/internal/domain/storecontract/storecontract.go @@ -254,6 +254,15 @@ type BindingTaskCreator interface { EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity, bindingID string, bindingVersion int, inputs map[string]any) (*task.Task, error) } +// WorkflowCaller is the consumer surface a workflow.call step crosses to +// start its callee and read it back while waiting (docs/prds/workflow-calls.md). +// It is the workflow engine's own task.Caller contract, satisfied by the +// PostgreSQL store and *staterpc.Client alike -- the same shape as +// workflow.Store. The caller task ID is explicit so both the wire grant and +// the store's own row check answer the same question: is this call this +// task's call? +type WorkflowCaller = task.Caller + // PlaybookDispatcher is the idempotency-ledger surface for side-effecting // playbook actions (docs/prds/eda-playbook-engine.md gap 2). // RecordPlaybookDispatch writes the (playbook, version, event, action) row @@ -421,6 +430,18 @@ var ( // the sentinel is shared so a caller treats "already recorded" the same // way across the two surfaces. ErrAlreadyDispatched = errors.New("store: binding already dispatched for capture") + // ErrCallNotYours is returned when a workflow.call status read names a + // task that is not a callee of the calling task, or the caller itself + // does not exist: a caller reads only the tasks it started + // (docs/prds/workflow-calls.md). + ErrCallNotYours = errors.New("store: task is not a callee of the calling task") + // ErrCallCallerNotRunning is returned when a workflow.call enqueue names + // a caller that is not running: a stale retry, or a bug in the caller. + ErrCallCallerNotRunning = errors.New("store: workflow.call caller is not running") + // ErrCallDepthExceeded is returned when a workflow.call enqueue would + // pass workflow.MaxCallDepth. The engine refuses the same call first; + // the store re-checks because it owns the table. + ErrCallDepthExceeded = errors.New("store: workflow.call would pass the depth limit") // ErrMappingNotFound is returned when a mapping ID does not exist. ErrMappingNotFound = errors.New("store: mapping not found") // ErrEventTypeNotFound is returned when an event type ID does not exist. diff --git a/internal/domain/workflow/definition.go b/internal/domain/workflow/definition.go index f5239bee4..9b5e81177 100644 --- a/internal/domain/workflow/definition.go +++ b/internal/domain/workflow/definition.go @@ -25,8 +25,9 @@ type YAMLDefinition struct { // repoFreeStepTypes are the step types that run without a repository. A // workflow whose repository is not required may use only these, since it may -// run with no worktree at all. -var repoFreeStepTypes = map[string]bool{AgentRunStepName: true} +// run with no worktree at all. workflow.call needs none of the caller's own: +// the callee's own repository mode decides whether its run clones. +var repoFreeStepTypes = map[string]bool{AgentRunStepName: true, WorkflowCallStepName: true} // StepRecord selects one registered step type and supplies its typed settings. type StepRecord struct { @@ -112,9 +113,13 @@ type ( WorkflowDefinitionCollection = task.WorkflowDefinitionCollection ) -// ValidateDefinitionCollection rejects malformed, duplicate, or mismatched definitions. +// ValidateDefinitionCollection rejects malformed, duplicate, or mismatched +// definitions, and every workflow.call step a definition carries: the callee +// must exist, its inputs must be satisfiable, and the call graph must be +// acyclic (docs/prds/workflow-calls.md). func ValidateDefinitionCollection(collection WorkflowDefinitionCollection, registry StepRegistry) error { seen := make(map[string]struct{}, len(collection.Definitions)) + parsed := make(map[string]YAMLDefinition, len(collection.Definitions)) for _, entry := range collection.Definitions { if _, ok := seen[entry.ID]; ok { return fmt.Errorf("duplicate workflow id %q", entry.ID) @@ -127,8 +132,9 @@ func ValidateDefinitionCollection(collection WorkflowDefinitionCollection, regis if definition.ID != entry.ID { return fmt.Errorf("workflow entry id %q does not match YAML id %q", entry.ID, definition.ID) } + parsed[entry.ID] = definition } - return nil + return validateWorkflowCalls(parsed) } // DecodeDefinitionCollection strictly decodes the control-plane projection. diff --git a/internal/domain/workflow/task/caller.go b/internal/domain/workflow/task/caller.go new file mode 100644 index 000000000..a849505c1 --- /dev/null +++ b/internal/domain/workflow/task/caller.go @@ -0,0 +1,21 @@ +package task + +import "context" + +// Caller is what a workflow.call step uses to start a callee run and read it +// back while waiting. It is the consumer-owned contract the workflow engine +// holds (the same shape as Store), satisfied by *staterpc.Client for an +// agent-container run: the callee is a first-class task the State Store +// derives from the caller's row (docs/prds/workflow-calls.md). +type Caller interface { + // StartCall enqueues the callee task for callerTaskID's workflow.call + // step: org, workspace, identity, owner, repo and issue number are + // derived from the caller's row, the callee carries the call's inputs, + // and the callee's depth is the caller's + 1. The store refuses a + // caller that is not running and a call past the depth limit. + StartCall(ctx context.Context, callerTaskID int64, workflow string, inputs map[string]any) (*Task, error) + // CallStatus reads one call's callee: its status and latest transition + // detail. A store only answers for a task whose call_parent_task_id is + // callerTaskID, so a caller reads only its own callees. + CallStatus(ctx context.Context, callerTaskID, callTaskID int64) (status, detail string, err error) +} diff --git a/internal/domain/workflow/task/task.go b/internal/domain/workflow/task/task.go index d0df7a328..2cdbd0070 100644 --- a/internal/domain/workflow/task/task.go +++ b/internal/domain/workflow/task/task.go @@ -122,6 +122,14 @@ type Task struct { // budget: one shared counter made N operator retries eat the // review-remediation budget and vice versa. RemediationRounds int `json:"remediation_rounds"` + // CallParentTaskID is the task whose workflow.call step started this + // one; 0 on a root run. A caller reads only the tasks it started, + // through WorkflowCallStatus. + CallParentTaskID int64 `json:"call_parent_task_id,omitempty"` + // CallDepth counts workflow.call hops from the root run. The engine + // refuses a call past workflow.MaxCallDepth, and the store re-checks on + // insert, so no enqueue path can pass the limit. + CallDepth int `json:"call_depth,omitempty"` // CreatedAt and UpdatedAt are the SQLite row timestamps, exposed so // callers can show a task's age and last activity. They are written by // column defaults and the UPDATE statements, never by the caller. diff --git a/internal/domain/workflow/workflow.go b/internal/domain/workflow/workflow.go index 156202753..5e893cdd4 100644 --- a/internal/domain/workflow/workflow.go +++ b/internal/domain/workflow/workflow.go @@ -17,6 +17,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/skill" "github.com/samcharles93/archie-core/internal/tools" @@ -82,6 +83,11 @@ type TaskContext struct { Store Store Trees Trees Agent agentexec.Runner + // Calls starts workflow.call callees and reads them back while a + // wait:true caller waits. Nil is only safe for a workflow with no + // workflow.call step: such a step in a runner with no capability + // fails the run with a named error (docs/prds/workflow-calls.md). + Calls task.Caller // Reviewer runs the adversarial self-review stage (StageReview). Nil // is only safe when Repo.ReviewEnabled is false; StageReview parks // rather than silently skipping if it is enabled with no Reviewer diff --git a/internal/domain/workflow/workflow_call.go b/internal/domain/workflow/workflow_call.go new file mode 100644 index 000000000..ac33236ce --- /dev/null +++ b/internal/domain/workflow/workflow_call.go @@ -0,0 +1,319 @@ +package workflow + +import ( + "context" + "fmt" + "regexp" + "strings" + "time" + + "gopkg.in/yaml.v3" + + "github.com/samcharles93/archie-core/internal/domain/workflow/task" + "github.com/samcharles93/archie-core/internal/events" +) + +// WorkflowCallStepName is the step type that starts another workflow as its +// own run. The callee is a first-class task the State Store derives from the +// caller's row: its own pinned definition, its own agent profile, its own +// container and its own outcome (docs/prds/workflow-calls.md). +const WorkflowCallStepName = "workflow.call" + +// MaxCallDepth bounds how deep one run may call callees. A cycle is refused +// at save, so the limit is not a loop guard -- it bounds a legitimate fan-out +// chain, and every wait:true caller on the path holds its container while it +// waits, so an unbounded depth would pin unbounded containers. +const MaxCallDepth = 5 + +// callPollInterval is how often a wait:true caller re-reads its callee's +// status. A var so tests do not sleep. +var callPollInterval = 2 * time.Second + +// workflowCallSettings are the workflow.call step's settings. An inputs value +// is either a literal or a reference to the calling workflow's declared +// input, written "inputs." -- the PRD's `inputs: { src_ip: +// inputs.src_ip }` shape. +type workflowCallSettings struct { + Workflow string `yaml:"workflow"` + Inputs map[string]any `yaml:"inputs,omitempty"` + Wait bool `yaml:"wait,omitempty"` +} + +// callReference is the prefix an inputs value must carry to be read as a +// reference to the calling workflow's declared input. +const callReference = "inputs." + +// refName is the identifier grammar a reference suffix must match, shared +// with the workflow interface's input names. +var refName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) + +// WorkflowCallStepType contributes the workflow.call step type. +func WorkflowCallStepType() StepType { + return StepType{Name: WorkflowCallStepName, Factory: newWorkflowCallStage} +} + +func newWorkflowCallStage(settings yaml.Node) (Stage, error) { + var s workflowCallSettings + if settings.Kind == 0 { + return Stage{}, fmt.Errorf("%s: settings.workflow is required", WorkflowCallStepName) + } + if err := settings.Decode(&s); err != nil { + return Stage{}, fmt.Errorf("%s: %w", WorkflowCallStepName, err) + } + if strings.TrimSpace(s.Workflow) == "" { + return Stage{}, fmt.Errorf("%s: settings.workflow is required", WorkflowCallStepName) + } + for name, value := range s.Inputs { + if _, ok := value.(map[string]any); ok { + return Stage{}, fmt.Errorf("%s: input %q must be a literal or an inputs. reference, not a nested document", WorkflowCallStepName, name) + } + if ref, ok := value.(string); ok && strings.HasPrefix(ref, callReference) && !refName.MatchString(strings.TrimPrefix(ref, callReference)) { + return Stage{}, fmt.Errorf("%s: input %q reference %q must name an input as inputs.", WorkflowCallStepName, name, ref) + } + } + return Stage{Name: WorkflowCallStepName, Run: func(ctx context.Context, tc *TaskContext) error { + return runWorkflowCall(ctx, s, tc) + }}, nil +} + +// runWorkflowCall starts the callee and, with wait true, waits for its +// terminal state. The callee reports on its own run; the call is recorded on +// the caller's timeline. +func runWorkflowCall(ctx context.Context, s workflowCallSettings, tc *TaskContext) error { + if tc.Calls == nil { + return fmt.Errorf("%s: this runner carries no callee capability", WorkflowCallStepName) + } + if tc.Task.CallDepth+1 > MaxCallDepth { + return fmt.Errorf("%s: call depth %d would pass the limit of %d", WorkflowCallStepName, tc.Task.CallDepth+1, MaxCallDepth) + } + inputs, err := resolveCallInputs(s.Inputs, tc.Task.Inputs) + if err != nil { + return fmt.Errorf("%s: %w", WorkflowCallStepName, err) + } + callee, err := tc.Calls.StartCall(ctx, tc.Task.ID, s.Workflow, inputs) + if err != nil { + return fmt.Errorf("%s: start %q: %w", WorkflowCallStepName, s.Workflow, err) + } + started := map[string]any{"callee_task_id": callee.ID, "workflow": s.Workflow, "wait": s.Wait} + if err := tc.EmitDurable(ctx, events.KindWorkflowCallStarted, WorkflowCallStepName, + fmt.Sprintf("started %q as task %d", s.Workflow, callee.ID), started); err != nil { + tc.Log.Warn("workflow call start not persisted", "err", err) + } + if !s.Wait { + return nil + } + return awaitCallee(ctx, s, tc, callee.ID) +} + +// resolveCallInputs turns the call's saved values into the callee's inputs: a +// reference reads the caller's actual input, a literal passes through. +func resolveCallInputs(call, callerInputs map[string]any) (map[string]any, error) { + if len(call) == 0 { + return nil, nil + } + resolved := make(map[string]any, len(call)) + for name, value := range call { + if ref, ok := value.(string); ok && isCallReference(ref) { + got, present := callerInputs[strings.TrimPrefix(ref, callReference)] + if !present { + return nil, fmt.Errorf("input %q references %q, which the calling workflow's run does not carry", name, ref) + } + resolved[name] = got + continue + } + resolved[name] = value + } + return resolved, nil +} + +// isCallReference reports whether a saved string value is a reference to the +// calling workflow's declared input. A literal that merely begins with +// "inputs." but does not name an input reads as the literal it is. +func isCallReference(value string) bool { + return strings.HasPrefix(value, callReference) && refName.MatchString(strings.TrimPrefix(value, callReference)) +} + +// callEnded reports whether a callee status ends the caller's wait. A parked +// callee ends it too: the callee will not move without an operator, so the +// caller must not wait for one. +func callEnded(status string) bool { + switch status { + case StatusCompleted, StatusPROpen, StatusMerged, StatusParked, StatusDead, StatusRejected, StatusClosedWontDo: + return true + default: + return false + } +} + +// awaitCallee polls the callee until it is terminal, failing the stage with +// the callee's detail when the callee did not succeed. The caller's own wall +// clock bounds the wait. +func awaitCallee(ctx context.Context, s workflowCallSettings, tc *TaskContext, callTaskID int64) error { + for { + status, detail, err := tc.Calls.CallStatus(ctx, tc.Task.ID, callTaskID) + if err != nil { + return fmt.Errorf("%s: read task %d: %w", WorkflowCallStepName, callTaskID, err) + } + if callEnded(status) { + if callSucceeded(status) { + if err := tc.EmitDurable(ctx, events.KindWorkflowCallFinished, WorkflowCallStepName, + fmt.Sprintf("%q (task %d) finished: %s", s.Workflow, callTaskID, detail), + map[string]any{"callee_task_id": callTaskID, "workflow": s.Workflow, "status": status, "detail": detail}); err != nil { + tc.Log.Warn("workflow call finish not persisted", "err", err) + } + return nil + } + return fmt.Errorf("%s: callee %q (task %d) ended %s: %s", WorkflowCallStepName, s.Workflow, callTaskID, status, detail) + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(callPollInterval): + } + } +} + +// callSucceeded reports whether a callee's terminal state satisfies its +// caller. pr_open and merged are successes: a repository callee opens its PR +// and reports on it as its own outcome. +func callSucceeded(status string) bool { + switch status { + case StatusCompleted, StatusPROpen, StatusMerged: + return true + default: + return false + } +} + +// validateWorkflowCalls checks every workflow.call step against the rest of +// the collection: the callee must exist, the call's inputs must satisfy the +// callee's declared inputs, and no workflow may reach itself through calls +// (docs/prds/workflow-calls.md). +func validateWorkflowCalls(parsed map[string]YAMLDefinition) error { + calls := make(map[string][]string, len(parsed)) + for id, d := range parsed { + for i, step := range d.Steps { + if step.Type != WorkflowCallStepName { + continue + } + s, err := decodeCallSettings(step) + if err != nil { + return fmt.Errorf("workflow %q step %d: %w", id, i+1, err) + } + callee, ok := parsed[s.Workflow] + if !ok { + return fmt.Errorf("workflow %q step %d calls %q, which is not defined", id, i+1, s.Workflow) + } + if err := checkCallInputs(id, i, d.WorkflowInterface, callee, s.Inputs); err != nil { + return err + } + calls[id] = append(calls[id], s.Workflow) + } + } + return refuseCallCycles(calls) +} + +func decodeCallSettings(step StepRecord) (workflowCallSettings, error) { + var s workflowCallSettings + if err := step.Settings.Decode(&s); err != nil { + return workflowCallSettings{}, err + } + return s, nil +} + +// checkCallInputs validates one call's saved inputs against the callee's +// declared inputs, resolving references against the calling workflow's own +// declared input types. Values are not known at save time -- types are. +func checkCallInputs(callerID string, index int, caller task.WorkflowInterface, callee YAMLDefinition, inputs map[string]any) error { + for name, value := range inputs { + spec, ok := callee.Inputs[name] + if !ok { + return fmt.Errorf("workflow %q step %d: input %q is not declared by %q", callerID, index+1, name, callee.ID) + } + resolved, err := callInputType(caller, name, value) + if err != nil { + return fmt.Errorf("workflow %q step %d: %w", callerID, index+1, err) + } + if resolved == "" { + // A null literal satisfies the type check vacuously; the + // callee's own run enforces it against the real value. + continue + } + if !task.TypeAccepts(spec.Type, resolved) { + return fmt.Errorf("workflow %q step %d: input %q is %s, want %s", callerID, index+1, name, resolved, spec.Type) + } + } + for name, spec := range callee.Inputs { + if _, assigned := inputs[name]; !assigned && spec.Required { + return fmt.Errorf("workflow %q step %d: input %q is required by %q", callerID, index+1, name, callee.ID) + } + } + return nil +} + +// callInputType names the type a saved call value carries at run time: a +// reference carries the calling workflow's declared input type, a literal its +// own JSON type. An error means the reference names an input the caller does +// not declare. +func callInputType(caller task.WorkflowInterface, name string, value any) (string, error) { + if ref, ok := value.(string); ok && isCallReference(ref) { + spec, ok := caller.Inputs[strings.TrimPrefix(ref, callReference)] + if !ok { + return "", fmt.Errorf("input %q references %q, which the calling workflow does not declare", name, ref) + } + return spec.Type, nil + } + if value == nil { + return "", nil + } + return task.ValueType(value), nil +} + +// refuseCallCycles walks the call graph from every workflow and refuses one +// that reaches itself, directly or through other workflows, naming the path. +func refuseCallCycles(calls map[string][]string) error { + const ( + unseen = 0 + open = 1 + done = 2 + ) + state := make(map[string]int, len(calls)) + var path []string + var walk func(id string) error + walk = func(id string) error { + state[id] = open + path = append(path, id) + defer func() { state[id] = done; path = path[:len(path)-1] }() + for _, callee := range calls[id] { + switch state[callee] { + case open: + cycle := append(append([]string{}, path[cycleStart(path, callee):]...), callee) + return fmt.Errorf("workflow %q calls itself through %s", callee, strings.Join(cycle, " -> ")) + case unseen: + if err := walk(callee); err != nil { + return err + } + } + } + return nil + } + for id := range calls { + if state[id] == unseen { + if err := walk(id); err != nil { + return err + } + } + } + return nil +} + +// cycleStart finds where the open path enters the cycle, so the reported path +// runs from the cycle's first workflow rather than from the DFS root. +func cycleStart(path []string, cycleRoot string) int { + for i, id := range path { + if id == cycleRoot { + return i + } + } + return 0 +} diff --git a/internal/domain/workflow/workflow_call_test.go b/internal/domain/workflow/workflow_call_test.go new file mode 100644 index 000000000..d66f9fa06 --- /dev/null +++ b/internal/domain/workflow/workflow_call_test.go @@ -0,0 +1,329 @@ +package workflow + +import ( + "context" + "errors" + "log/slog" + "strings" + "testing" + "time" + + "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" + "github.com/samcharles93/archie-core/internal/events" +) + +func callRegistry() StepRegistry { + registry := BuiltinStepRegistry() + registry[AgentRunStepName] = newAgentRunStage + registry[WorkflowCallStepName] = newWorkflowCallStage + return registry +} + +// fakeCaller records StartCall/CallStatus and answers the poll with a +// scripted sequence of statuses. +type fakeCaller struct { + starts []startCall + statuses map[int64][]statusAt + statusErr error + startErr error +} + +type startCall struct { + callerID int64 + workflow string + inputs map[string]any +} + +type statusAt struct { + status string + detail string +} + +func (f *fakeCaller) StartCall(_ context.Context, callerID int64, workflow string, inputs map[string]any) (*task.Task, error) { + if f.startErr != nil { + return nil, f.startErr + } + f.starts = append(f.starts, startCall{callerID: callerID, workflow: workflow, inputs: inputs}) + callee := &task.Task{ID: int64(len(f.starts) + 100), Workflow: workflow, CallParentTaskID: callerID, CallDepth: 1, Status: StatusQueued} + return callee, nil +} + +func (f *fakeCaller) CallStatus(_ context.Context, callerID, callID int64) (string, string, error) { + if f.statusErr != nil { + return "", "", f.statusErr + } + seq := f.statuses[callID] + if len(seq) == 0 { + return "", "", nil + } + at := seq[0] + if len(seq) > 1 { + f.statuses[callID] = seq[1:] + } + return at.status, at.detail, nil +} + +func callerYAML(callee string, extra ...string) string { + body := "id: caller\nsteps:\n - type: workflow.call\n settings:\n workflow: " + callee + "\n" + for _, line := range extra { + body += line + "\n" + } + return body +} + +// ---- Save-time: collection validation ---- + +func TestValidateCollectionWorkflowCalls(t *testing.T) { + for _, test := range []struct { + name string + collection WorkflowDefinitionCollection + want string + }{ + { + name: "callee is not defined", + collection: collectionOf( + callerYAML("missing"), + ), + want: `calls "missing", which is not defined`, + }, + { + name: "direct self-call", + collection: collectionOf( + "id: w\nsteps:\n - type: workflow.call\n settings:\n workflow: w\n", + ), + want: `calls itself through w -> w`, + }, + { + name: "indirect cycle", + collection: collectionOf( + "id: a\nsteps:\n - type: workflow.call\n settings:\n workflow: b\n", + "id: b\nsteps:\n - type: workflow.call\n settings:\n workflow: a\n", + ), + want: "calls itself through a -> b -> a", + }, + { + name: "reference to an undeclared caller input", + collection: collectionOf( + callerYAML("callee", " inputs: {src_ip: \"inputs.missing\"}"), + "id: callee\ninputs:\n src_ip: {type: string}\nsteps:\n - type: agent.run\n settings:\n mission: m\n", + ), + want: `input "src_ip" references "inputs.missing", which the calling workflow does not declare`, + }, + { + name: "callee input type mismatch", + collection: collectionOf( + "id: caller\ninputs:\n src_ip: {type: string}\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n inputs: {src_ip: \"inputs.src_ip\"}\n", + "id: callee\ninputs:\n src_ip: {type: number}\nsteps:\n - type: agent.run\n settings:\n mission: m\n", + ), + want: `input "src_ip" is string, want number`, + }, + { + name: "required callee input is not assigned", + collection: collectionOf( + "id: caller\ninputs:\n src_ip: {type: string}\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n inputs: {severity: \"inputs.src_ip\"}\n", + "id: callee\ninputs:\n src_ip: {type: string, required: true}\n severity: {type: string}\nsteps:\n - type: agent.run\n settings:\n mission: m\n", + ), + want: `input "src_ip" is required by "callee"`, + }, + { + name: "undeclared callee input", + collection: collectionOf( + "id: caller\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n inputs: {extra: 7}\n", + "id: callee\nsteps:\n - type: agent.run\n settings:\n mission: m\n", + ), + want: `input "extra" is not declared by "callee"`, + }, + } { + t.Run(test.name, func(t *testing.T) { + err := ValidateDefinitionCollection(test.collection, callRegistry()) + if err == nil || !strings.Contains(err.Error(), test.want) { + t.Fatalf("ValidateDefinitionCollection() error = %v, want containing %q", err, test.want) + } + }) + } + + valid := collectionOf( + "id: caller\nrepository: none\ninputs:\n src_ip: {type: string, required: true}\n n: {type: number}\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n inputs: {src_ip: \"inputs.src_ip\", n: 3}\n", + "id: callee\ninputs:\n src_ip: {type: string, required: true}\n n: {type: number}\nsteps:\n - type: agent.run\n settings:\n mission: m\n", + ) + if err := ValidateDefinitionCollection(valid, callRegistry()); err != nil { + t.Fatalf("ValidateDefinitionCollection(valid) = %v, want nil", err) + } + + // A chain of distinct workflows is not a cycle. + chain := collectionOf( + "id: a\nsteps:\n - type: workflow.call\n settings:\n workflow: b\n", + "id: b\nsteps:\n - type: workflow.call\n settings:\n workflow: c\n", + "id: c\nsteps:\n - type: agent.run\n settings:\n mission: m\n", + ) + if err := ValidateDefinitionCollection(chain, callRegistry()); err != nil { + t.Fatalf("ValidateDefinitionCollection(chain) = %v, want nil", err) + } +} + +func collectionOf(yamls ...string) WorkflowDefinitionCollection { + c := WorkflowDefinitionCollection{} + for _, y := range yamls { + c.Definitions = append(c.Definitions, WorkflowDefinitionEntry{ID: yamlID(y), YAML: y}) + } + return c +} + +func yamlID(y string) string { + for line := range strings.SplitSeq(y, "\n") { + if after, ok := strings.CutPrefix(line, "id: "); ok { + return after + } + } + return "" +} + +// ---- Runtime: the stage ---- + +func compileCaller(t *testing.T, yaml string) Workflow { + t.Helper() + wf, err := ParseAndCompile(yaml, callRegistry()) + if err != nil { + t.Fatalf("ParseAndCompile: %v", err) + } + return wf +} + +func TestWorkflowCallStageRefusesWithoutCapability(t *testing.T) { + wf := compileCaller(t, "id: caller\nrepository: none\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n") + store := &recordingStore{} + tc := &TaskContext{Task: &Task{ID: 3, Attempt: 1}, Store: store, Trees: &fakeTrees{}, Log: slog.New(slog.DiscardHandler)} + Run(context.Background(), wf, tc) + if !strings.Contains(tc.Task.ParkReason, "callee capability") { + t.Fatalf("park reason %q; want a park naming the missing capability", tc.Task.ParkReason) + } + if len(store.ofKind(events.KindWorkflowCallStarted)) != 0 { + t.Error("a refused call must not record a started event") + } +} + +func TestWorkflowCallStageDepthLimit(t *testing.T) { + wf := compileCaller(t, "id: caller\nrepository: none\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n") + caller := &fakeCaller{} + store := &recordingStore{} + deep := &Task{ID: 3, Attempt: 1, CallDepth: MaxCallDepth} + tc := &TaskContext{Task: deep, Calls: caller, Store: store, Trees: &fakeTrees{}, Log: slog.New(slog.DiscardHandler)} + Run(context.Background(), wf, tc) + if len(caller.starts) != 0 { + t.Fatalf("StartCall ran %d times at the depth limit, want none", len(caller.starts)) + } + if !strings.Contains(deep.ParkReason, "depth") { + t.Fatalf("park reason %q; want a park naming the depth limit", deep.ParkReason) + } +} + +func TestWorkflowCallWaitFalseStartsAndContinues(t *testing.T) { + wf := compileCaller(t, "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") + caller := &fakeCaller{} + store := &recordingStore{} + tc := &TaskContext{ + Task: &Task{ID: 3, Attempt: 1, Inputs: map[string]any{"src_ip": "10.0.0.9"}}, + Calls: caller, Store: store, Trees: &fakeTrees{dir: "/scratch/3"}, Log: slog.New(slog.DiscardHandler), + Agent: &fakeAgentRunner{result: agentexec.Result{Status: agentexec.StatusPassed, Summary: "reported"}}, + Cfg: config.Config{Models: map[string]string{"builder": "p/m"}}, + } + Run(context.Background(), wf, tc) + if len(caller.starts) != 1 { + t.Fatalf("StartCall ran %d times, want exactly one", len(caller.starts)) + } + start := caller.starts[0] + if start.callerID != 3 || start.workflow != "callee" { + t.Errorf("start = %+v, want caller 3 calling callee", start) + } + if got := start.inputs["src_ip"]; got != "10.0.0.9" { + t.Errorf("input src_ip = %v, want the caller's resolved input", got) + } + if tc.Outcome.Status != StatusCompleted { + t.Errorf("outcome = %+v, want the caller to continue and complete", tc.Outcome) + } + started := store.ofKind(events.KindWorkflowCallStarted) + if len(started) != 1 || started[0].Data["callee_task_id"] != int64(101) { + t.Errorf("started events = %+v, want one carrying callee task 101", started) + } +} + +func TestWorkflowCallWaitTrueWaitsForTerminalCallee(t *testing.T) { + wf := compileCaller(t, "id: caller\nrepository: none\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n wait: true\n - type: agent.run\n settings:\n mission: report\n") + caller := &fakeCaller{statuses: map[int64][]statusAt{ + 101: {{StatusQueued, ""}, {StatusRunning, ""}, {StatusCompleted, "contained 10.0.0.9"}}, + }} + store := &recordingStore{} + tc := &TaskContext{ + Task: &Task{ID: 3, Attempt: 1}, Calls: caller, Store: store, + Trees: &fakeTrees{dir: "/scratch/3"}, Log: slog.New(slog.DiscardHandler), + Agent: &fakeAgentRunner{result: agentexec.Result{Status: agentexec.StatusPassed, Summary: "reported"}}, + Cfg: config.Config{Models: map[string]string{"builder": "p/m"}}, + } + callPollInterval = time.Millisecond + defer func() { callPollInterval = 2 * time.Second }() + Run(context.Background(), wf, tc) + if tc.Outcome.Status != StatusCompleted { + t.Errorf("outcome = %+v, want completed after the callee succeeded", tc.Outcome) + } + finished := store.ofKind(events.KindWorkflowCallFinished) + if len(finished) != 1 || finished[0].Data["status"] != StatusCompleted || finished[0].Data["detail"] != "contained 10.0.0.9" { + t.Errorf("finished events = %+v, want the callee's terminal status and detail", finished) + } +} + +func TestWorkflowCallWaitTrueFailsWhenCalleeFails(t *testing.T) { + wf := compileCaller(t, "id: caller\nrepository: none\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n wait: true\n") + caller := &fakeCaller{statuses: map[int64][]statusAt{ + 101: {{StatusParked, "needs an operator"}}, + }} + store := &recordingStore{} + tc := &TaskContext{ + Task: &Task{ID: 3, Attempt: 1}, Calls: caller, Store: store, + Trees: &fakeTrees{}, Log: slog.New(slog.DiscardHandler), + } + callPollInterval = time.Millisecond + defer func() { callPollInterval = 2 * time.Second }() + Run(context.Background(), wf, tc) + if !strings.Contains(tc.Task.ParkReason, "needs an operator") { + t.Fatalf("reason %q; want a park carrying the callee's detail", tc.Task.ParkReason) + } + if len(store.ofKind(events.KindWorkflowCallFinished)) != 0 { + t.Error("a failed call must not record a finished event") + } +} + +func TestWorkflowCallWaitTrueStartFailure(t *testing.T) { + wf := compileCaller(t, "id: caller\nrepository: none\nsteps:\n - type: workflow.call\n settings:\n workflow: callee\n wait: true\n") + caller := &fakeCaller{startErr: errors.New("callee is not enabled for this org")} + store := &recordingStore{} + tc := &TaskContext{ + Task: &Task{ID: 3, Attempt: 1}, Calls: caller, Store: store, + Trees: &fakeTrees{}, Log: slog.New(slog.DiscardHandler), + } + Run(context.Background(), wf, tc) + if !strings.Contains(tc.Task.ParkReason, "callee is not enabled") { + t.Fatalf("reason %q; want the start failure parked", tc.Task.ParkReason) + } +} + +func TestWorkflowCallSettingsValidation(t *testing.T) { + for _, test := range []struct{ name, yaml, want string }{ + {"no workflow named", "id: w\nrepository: none\nsteps:\n - type: workflow.call\n", "settings.workflow is required"}, + {"works in a repository-free workflow", "id: w\nrepository: none\nsteps:\n - type: workflow.call\n settings:\n workflow: other\n", ""}, + } { + t.Run(test.name, func(t *testing.T) { + _, err := ParseDefinition(test.yaml, callRegistry()) + if test.want == "" { + if err != nil { + t.Fatalf("ParseDefinition() = %v, want nil", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), test.want) { + t.Fatalf("ParseDefinition() error = %v, want containing %q", err, test.want) + } + }) + } +} diff --git a/internal/events/events.go b/internal/events/events.go index cb4b7325a..2cf470309 100644 --- a/internal/events/events.go +++ b/internal/events/events.go @@ -119,6 +119,16 @@ const ( // the sender. data: source, capture_id, binding_id. KindUnsignedEvent = "unsigned_event" + // KindWorkflowCallStarted marks the moment a workflow.call step + // started its callee run (docs/prds/workflow-calls.md). data: + // callee_task_id, workflow, wait. + KindWorkflowCallStarted = "workflow_call_started" + // KindWorkflowCallFinished carries the terminal state of a waited-on + // callee back onto the caller's timeline. data: callee_task_id, + // workflow, status, detail. Only a call the caller waited on records + // one; a wait:false callee reports on its own run. + KindWorkflowCallFinished = "workflow_call_finished" + // KindUpdateReport carries the phase-2 outcome of a dashboard-initiated // update -- whether the restarted daemon came back up healthy and on // the version it claimed, relayed once on the boot that finds the diff --git a/internal/infrastructure/agenttransport/nats/transport.go b/internal/infrastructure/agenttransport/nats/transport.go index 233e25a6f..6d53ad787 100644 --- a/internal/infrastructure/agenttransport/nats/transport.go +++ b/internal/infrastructure/agenttransport/nats/transport.go @@ -15,6 +15,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "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/forgerpc" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" @@ -154,6 +155,39 @@ func (t *Transport) Store(timeout time.Duration) workflow.Store { return deadlineStore{Store: t.state, timeout: timeout} } +// Calls constructs the workflow.call RPC client over the same long-lived +// State Store client (docs/prds/workflow-calls.md), bounded by timeout the +// same way Store() is. +func (t *Transport) Calls(timeout time.Duration) task.Caller { + return deadlineCaller{Caller: t.state, timeout: timeout} +} + +// deadlineCaller applies a default per-call timeout to task.Caller calls +// whose context carries no deadline of its own, matching deadlineStore. +type deadlineCaller struct { + task.Caller + timeout time.Duration +} + +func (d deadlineCaller) withDeadline(ctx context.Context) (context.Context, context.CancelFunc) { + if _, ok := ctx.Deadline(); ok || d.timeout <= 0 { + return ctx, func() {} + } + return context.WithTimeout(ctx, d.timeout) +} + +func (d deadlineCaller) StartCall(ctx context.Context, callerTaskID int64, wf string, inputs map[string]any) (*task.Task, error) { + ctx, cancel := d.withDeadline(ctx) + defer cancel() + return d.Caller.StartCall(ctx, callerTaskID, wf, inputs) +} + +func (d deadlineCaller) CallStatus(ctx context.Context, callerTaskID, callTaskID int64) (string, string, error) { + ctx, cancel := d.withDeadline(ctx) + defer cancel() + return d.Caller.CallStatus(ctx, callerTaskID, callTaskID) +} + // deadlineStore applies a default per-call timeout to workflow.Store calls // whose context carries no deadline of its own, matching storerpc.Client's // Timeout field semantics for the gRPC path. diff --git a/internal/infrastructure/postgres/migrations/0015_workflow_calls.sql b/internal/infrastructure/postgres/migrations/0015_workflow_calls.sql new file mode 100644 index 000000000..7900c2ba6 --- /dev/null +++ b/internal/infrastructure/postgres/migrations/0015_workflow_calls.sql @@ -0,0 +1,20 @@ +-- Workflow calls: the callee linkage on the task row +-- (docs/prds/workflow-calls.md). +-- +-- tasks.call_parent_task_id names the task whose workflow.call step started +-- this one (0 on a root run) and call_depth counts workflow.call hops from +-- the root. Both default so every existing row and writer reads as a depth-0 +-- root run; the depth limit itself is re-checked by the engine and the +-- enqueue, so no path can write past it. + +-- +goose Up + +ALTER TABLE tasks ADD COLUMN call_parent_task_id bigint NOT NULL DEFAULT 0; +ALTER TABLE tasks ADD COLUMN call_depth int NOT NULL DEFAULT 0; +CREATE INDEX idx_tasks_call_parent ON tasks (call_parent_task_id); + +-- +goose Down + +DROP INDEX idx_tasks_call_parent; +ALTER TABLE tasks DROP COLUMN call_depth; +ALTER TABLE tasks DROP COLUMN call_parent_task_id; \ No newline at end of file diff --git a/internal/infrastructure/postgres/postgresdb/call_tasks.sql.go b/internal/infrastructure/postgres/postgresdb/call_tasks.sql.go new file mode 100644 index 000000000..5800758a0 --- /dev/null +++ b/internal/infrastructure/postgres/postgresdb/call_tasks.sql.go @@ -0,0 +1,118 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: call_tasks.sql + +package postgresdb + +import ( + "context" +) + +const callStatusDetail = `-- name: CallStatusDetail :one +SELECT detail FROM transitions WHERE task_id = $1 ORDER BY id DESC LIMIT 1 +` + +// The latest transition detail of one call's callee, the summary a wait:true +// caller receives (docs/prds/workflow-calls.md). +func (q *Queries) CallStatusDetail(ctx context.Context, taskID int64) (string, error) { + row := q.db.QueryRow(ctx, callStatusDetail, taskID) + var detail string + err := row.Scan(&detail) + return detail, err +} + +const enqueueCallTask = `-- name: EnqueueCallTask :one +WITH caller AS ( + SELECT t.id, t.owner, t.repo, t.issue_number, t.title, t.body, t.labels, t.status, t.workflow, t.stage, t.branch, t.plan, t.notes, t.pr_number, t.tokens_used, t.iterations, t.attempt, t.park_reason, t.watch_comment_id, t.park_class, t.remediation_rounds, t.retry_count, t.source, t.identity, t.binding_id, t.binding_version, t.review_payload, t.workflow_definition_version, t.workflow_definition_digest, t.workflow_definition_yaml, t.created_at, t.updated_at, t.review_cursor, t.inputs, t.org_id, t.workspace_id, t.call_parent_task_id, t.call_depth FROM tasks t WHERE t.id = $1 FOR UPDATE +) +INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, workspace_id, inputs, call_parent_task_id, call_depth) +SELECT + caller.owner, + caller.repo, + COALESCE(( + SELECT MAX(existing.issue_number) FROM tasks existing + WHERE existing.owner = caller.owner + AND existing.repo = caller.repo + AND existing.source = 'chat' + ), $2::bigint) + 1, + $3, $4, 'chat', $5, 'chat', caller.identity, + caller.org_id, caller.workspace_id, $6, + caller.id, caller.call_depth + 1 +FROM caller +WHERE caller.status = 'running' AND caller.call_depth + 1 <= $7::int +RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth +` + +type EnqueueCallTaskParams struct { + ID int64 + FallbackIssueNumber int64 + Title string + Body string + Workflow string + Inputs string + MaxDepth int32 +} + +// The callee of a workflow.call step (docs/prds/workflow-calls.md). The +// caller row is read FOR UPDATE, so two steps of the same run cannot race a +// depth re-check, and the callee inherits the caller's org, workspace, +// identity, owner and repo: a called workflow works the same run's context +// under its own definition and profile. The issue number is a fresh +// synthetic one for the inherited owner/repo, the same allocator +// InsertChatTask uses. The insert refuses a caller that is not running and +// a call that would pass the depth limit (the engine checks it too; the +// store is what owns the table, so it re-checks). +func (q *Queries) EnqueueCallTask(ctx context.Context, arg EnqueueCallTaskParams) (Task, error) { + row := q.db.QueryRow(ctx, enqueueCallTask, + arg.ID, + arg.FallbackIssueNumber, + arg.Title, + arg.Body, + arg.Workflow, + arg.Inputs, + arg.MaxDepth, + ) + var i Task + err := row.Scan( + &i.ID, + &i.Owner, + &i.Repo, + &i.IssueNumber, + &i.Title, + &i.Body, + &i.Labels, + &i.Status, + &i.Workflow, + &i.Stage, + &i.Branch, + &i.Plan, + &i.Notes, + &i.PrNumber, + &i.TokensUsed, + &i.Iterations, + &i.Attempt, + &i.ParkReason, + &i.WatchCommentID, + &i.ParkClass, + &i.RemediationRounds, + &i.RetryCount, + &i.Source, + &i.Identity, + &i.BindingID, + &i.BindingVersion, + &i.ReviewPayload, + &i.WorkflowDefinitionVersion, + &i.WorkflowDefinitionDigest, + &i.WorkflowDefinitionYaml, + &i.CreatedAt, + &i.UpdatedAt, + &i.ReviewCursor, + &i.Inputs, + &i.OrgID, + &i.WorkspaceID, + &i.CallParentTaskID, + &i.CallDepth, + ) + return i, err +} diff --git a/internal/infrastructure/postgres/postgresdb/models.go b/internal/infrastructure/postgres/postgresdb/models.go index 4b37ddb08..06e7999ec 100644 --- a/internal/infrastructure/postgres/postgresdb/models.go +++ b/internal/infrastructure/postgres/postgresdb/models.go @@ -323,6 +323,8 @@ type Task struct { Inputs string OrgID string WorkspaceID string + CallParentTaskID int64 + CallDepth int32 } type ToolCall struct { diff --git a/internal/infrastructure/postgres/postgresdb/tasks.sql.go b/internal/infrastructure/postgres/postgresdb/tasks.sql.go index 2be9fa4fe..3954a3b0d 100644 --- a/internal/infrastructure/postgres/postgresdb/tasks.sql.go +++ b/internal/infrastructure/postgres/postgresdb/tasks.sql.go @@ -48,7 +48,7 @@ func (q *Queries) BeginRemediationTask(ctx context.Context, arg BeginRemediation const claimByIssue = `-- name: ClaimByIssue :one UPDATE tasks SET status = 'running', attempt = attempt + 1, updated_at = now() WHERE owner = $1 AND repo = $2 AND issue_number = $3 AND status = 'queued' -RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id +RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth ` type ClaimByIssueParams struct { @@ -97,6 +97,8 @@ func (q *Queries) ClaimByIssue(ctx context.Context, arg ClaimByIssueParams) (Tas &i.Inputs, &i.OrgID, &i.WorkspaceID, + &i.CallParentTaskID, + &i.CallDepth, ) return i, err } @@ -111,7 +113,7 @@ WHERE id = ( FOR UPDATE SKIP LOCKED LIMIT 1 ) -RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id +RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth ` // FOR UPDATE SKIP LOCKED replaces the SQLite single-writer assumption: two @@ -157,6 +159,8 @@ func (q *Queries) ClaimNextTask(ctx context.Context) (Task, error) { &i.Inputs, &i.OrgID, &i.WorkspaceID, + &i.CallParentTaskID, + &i.CallDepth, ) return i, err } @@ -266,7 +270,7 @@ VALUES ( 'default' ) ) -RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id +RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth ` type InsertChatTaskParams struct { @@ -331,6 +335,8 @@ func (q *Queries) InsertChatTask(ctx context.Context, arg InsertChatTaskParams) &i.Inputs, &i.OrgID, &i.WorkspaceID, + &i.CallParentTaskID, + &i.CallDepth, ) return i, err } @@ -619,7 +625,7 @@ func (q *Queries) StampTaskBinding(ctx context.Context, arg StampTaskBindingPara } const taskByID = `-- name: TaskByID :one -SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id FROM tasks WHERE id = $1 +SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth FROM tasks WHERE id = $1 ` func (q *Queries) TaskByID(ctx context.Context, id int64) (Task, error) { @@ -662,12 +668,14 @@ func (q *Queries) TaskByID(ctx context.Context, id int64) (Task, error) { &i.Inputs, &i.OrgID, &i.WorkspaceID, + &i.CallParentTaskID, + &i.CallDepth, ) return i, err } const taskByIssue = `-- name: TaskByIssue :one -SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3 +SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3 ` type TaskByIssueParams struct { @@ -716,12 +724,14 @@ func (q *Queries) TaskByIssue(ctx context.Context, arg TaskByIssueParams) (Task, &i.Inputs, &i.OrgID, &i.WorkspaceID, + &i.CallParentTaskID, + &i.CallDepth, ) return i, err } const taskByPR = `-- name: TaskByPR :one -SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4 +SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4 ` type TaskByPRParams struct { @@ -779,6 +789,8 @@ func (q *Queries) TaskByPR(ctx context.Context, arg TaskByPRParams) (Task, error &i.Inputs, &i.OrgID, &i.WorkspaceID, + &i.CallParentTaskID, + &i.CallDepth, ) return i, err } diff --git a/internal/infrastructure/postgres/queries/call_tasks.sql b/internal/infrastructure/postgres/queries/call_tasks.sql new file mode 100644 index 000000000..dd8e42069 --- /dev/null +++ b/internal/infrastructure/postgres/queries/call_tasks.sql @@ -0,0 +1,34 @@ +-- name: EnqueueCallTask :one +-- The callee of a workflow.call step (docs/prds/workflow-calls.md). The +-- caller row is read FOR UPDATE, so two steps of the same run cannot race a +-- depth re-check, and the callee inherits the caller's org, workspace, +-- identity, owner and repo: a called workflow works the same run's context +-- under its own definition and profile. The issue number is a fresh +-- synthetic one for the inherited owner/repo, the same allocator +-- InsertChatTask uses. The insert refuses a caller that is not running and +-- a call that would pass the depth limit (the engine checks it too; the +-- store is what owns the table, so it re-checks). +WITH caller AS ( + SELECT t.* FROM tasks t WHERE t.id = $1 FOR UPDATE +) +INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, workspace_id, inputs, call_parent_task_id, call_depth) +SELECT + caller.owner, + caller.repo, + COALESCE(( + SELECT MAX(existing.issue_number) FROM tasks existing + WHERE existing.owner = caller.owner + AND existing.repo = caller.repo + AND existing.source = 'chat' + ), sqlc.arg('fallback_issue_number')::bigint) + 1, + sqlc.arg(title), sqlc.arg(body), 'chat', sqlc.arg(workflow), 'chat', caller.identity, + caller.org_id, caller.workspace_id, sqlc.arg(inputs), + caller.id, caller.call_depth + 1 +FROM caller +WHERE caller.status = 'running' AND caller.call_depth + 1 <= sqlc.arg('max_depth')::int +RETURNING *; + +-- name: CallStatusDetail :one +-- The latest transition detail of one call's callee, the summary a wait:true +-- caller receives (docs/prds/workflow-calls.md). +SELECT detail FROM transitions WHERE task_id = $1 ORDER BY id DESC LIMIT 1; \ No newline at end of file diff --git a/internal/infrastructure/postgres/store.go b/internal/infrastructure/postgres/store.go index 86872728b..1b5fbeaf3 100644 --- a/internal/infrastructure/postgres/store.go +++ b/internal/infrastructure/postgres/store.go @@ -12,7 +12,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/org" "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" + task "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb" "github.com/samcharles93/archie-core/internal/taskstate" @@ -79,7 +79,7 @@ const syntheticIssueNumberBase = 1_000_000_000_000_000 func taskFromRow(t postgresdb.Task) *workflow.Task { // The inputs column is only ever written by EncodeInputs, so a decode // failure cannot arise from stored data this package produced. - inputs, _ := workflowtask.DecodeInputs(t.Inputs) + inputs, _ := task.DecodeInputs(t.Inputs) return &workflow.Task{ ID: t.ID, Owner: t.Owner, @@ -114,6 +114,8 @@ func taskFromRow(t postgresdb.Task) *workflow.Task { ReviewPayload: t.ReviewPayload, ParkClass: t.ParkClass, RemediationRounds: int(t.RemediationRounds), + CallParentTaskID: t.CallParentTaskID, + CallDepth: int(t.CallDepth), CreatedAt: t.CreatedAt, UpdatedAt: t.UpdatedAt, } @@ -126,6 +128,7 @@ var ( _ storecontract.ConfigSnapshotStore = (*Store)(nil) _ storecontract.ChannelStatusStore = (*Store)(nil) _ storecontract.ApplyStatusStore = (*Store)(nil) + _ task.Caller = (*Store)(nil) _ workflow.Store = (*Store)(nil) ) @@ -159,7 +162,7 @@ func (s *Store) EnqueueChatTask(ctx context.Context, owner, repo, title, body, w // EnqueueBindingTask enqueues a binding-triggered task and stamps its binding // provenance in a second statement (best-effort, as in the SQLite store). func (s *Store) EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity, bindingID string, bindingVersion int, inputs map[string]any) (*workflow.Task, error) { - encoded, err := workflowtask.EncodeInputs(inputs) + encoded, err := task.EncodeInputs(inputs) if err != nil { return nil, err } @@ -539,3 +542,80 @@ func (s *Store) TaskByID(ctx context.Context, taskID int64) (*workflow.Task, err } return taskFromRow(t), nil } + +// StartCall enqueues the callee of callerTaskID's workflow.call step +// (docs/prds/workflow-calls.md). The store owns the table, so it re-checks +// both runtime invariants the engine checks: the caller must be running and +// the call must not pass workflow.MaxCallDepth. The callee inherits the +// caller's org, workspace, identity, owner and repo, and takes a fresh +// synthetic issue number, the same allocator chat tasks use. +func (s *Store) StartCall(ctx context.Context, callerTaskID int64, wf string, inputs map[string]any) (*workflow.Task, error) { + encoded, err := task.EncodeInputs(inputs) + if err != nil { + return nil, err + } + callee, err := s.queries().EnqueueCallTask(ctx, postgresdb.EnqueueCallTaskParams{ + ID: callerTaskID, + FallbackIssueNumber: syntheticIssueNumberBase - 1, + Title: fmt.Sprintf("workflow.call %s from task %d", wf, callerTaskID), + Body: fmt.Sprintf("Started by a workflow.call step from task %d (workflow %q); the call's inputs travel with the task.", callerTaskID, wf), + Workflow: wf, + Inputs: encoded, + MaxDepth: int32(workflow.MaxCallDepth), + }) + if errors.Is(err, pgx.ErrNoRows) { + // The WITH reads the caller FOR UPDATE before inserting, so "no + // rows" means the caller is missing, not running, or past the depth + // limit. Name which, off a plain read. + return nil, s.callRefusal(ctx, callerTaskID) + } + if err != nil { + return nil, err + } + return taskFromRow(callee), nil +} + +// callRefusal names why EnqueueCallTask inserted nothing. The three refusals +// are distinct failures an operator reads differently: a missing caller is a +// problem, a caller that is not running is a stale retry, and a depth +// refusal is the limit doing its job. The two behavioural ones carry the +// caller's detail in the log and the sentinel across the wire. +func (s *Store) callRefusal(ctx context.Context, callerTaskID int64) error { + caller, err := s.queries().TaskByID(ctx, callerTaskID) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("store: workflow.call caller task %d does not exist: %w", callerTaskID, storecontract.ErrCallNotYours) + } + if err != nil { + return err + } + if caller.Status != "running" { + return fmt.Errorf("store: workflow.call caller task %d is %s: %w", callerTaskID, caller.Status, storecontract.ErrCallCallerNotRunning) + } + return fmt.Errorf("store: workflow.call from task %d at depth %d: %w", callerTaskID, caller.CallDepth, storecontract.ErrCallDepthExceeded) +} + +// CallStatus reads one call's callee for a waiting caller: its status and +// latest transition detail. The parent check is the row check the wire grant +// cannot do: a caller reads only the tasks it started. +func (s *Store) CallStatus(ctx context.Context, callerTaskID, callTaskID int64) (string, string, error) { + callee, err := s.queries().TaskByID(ctx, callTaskID) + if errors.Is(err, pgx.ErrNoRows) { + return "", "", storecontract.ErrCallNotYours + } + if err != nil { + return "", "", err + } + if callee.CallParentTaskID != callerTaskID { + return "", "", storecontract.ErrCallNotYours + } + // A callee that has not moved yet has no transition row; its queue + // status is the whole answer, and the empty detail says so. + detail, err := s.queries().CallStatusDetail(ctx, callTaskID) + if errors.Is(err, pgx.ErrNoRows) { + return callee.Status, "", nil + } + if err != nil { + return "", "", err + } + return callee.Status, detail, nil +} diff --git a/internal/infrastructure/staterpc/client.go b/internal/infrastructure/staterpc/client.go index 61de72ba8..2c7efc6e0 100644 --- a/internal/infrastructure/staterpc/client.go +++ b/internal/infrastructure/staterpc/client.go @@ -44,6 +44,7 @@ func (c *Client) Close() error { return nil } var ( _ task.Store = (*Client)(nil) + _ task.Caller = (*Client)(nil) _ storecontract.TaskStore = (*Client)(nil) _ storecontract.TaskLogStore = (*Client)(nil) _ storecontract.CaptureStore = (*Client)(nil) @@ -566,6 +567,32 @@ func (c *Client) EnqueueBindingTask(ctx context.Context, owner, repo, title, bod return taskValue(r.Task), nil } +// WorkflowCaller: the workflow.call step's two RPCs (docs/prds/ +// workflow-calls.md). StartCall encodes the call's inputs in the same form +// every other wire crossing uses; CallStatus rehydrates the sentinels the +// server maps, so a caller's errors.Is(err, storecontract.ErrCallNotYours) +// works across the wire. + +func (c *Client) StartCall(ctx context.Context, callerTaskID int64, wf string, inputs map[string]any) (*task.Task, error) { + encoded, err := task.EncodeInputs(inputs) + if err != nil { + return nil, err + } + r, err := c.client.EnqueueCallTask(ctx, &pb.EnqueueCallTaskRequest{CallerTaskId: callerTaskID, Workflow: wf, InputsJson: encoded}) + if err != nil { + return nil, unmapError(err) + } + return taskValue(r.Task), nil +} + +func (c *Client) CallStatus(ctx context.Context, callerTaskID, callTaskID int64) (string, string, error) { + r, err := c.client.WorkflowCallStatus(ctx, &pb.WorkflowCallStatusRequest{CallerTaskId: callerTaskID, CallTaskId: callTaskID}) + if err != nil { + return "", "", unmapError(err) + } + return r.Status, r.Detail, nil +} + // Task log // TaskLog reads one task attempt's decoded log over the wire. found=false with diff --git a/internal/infrastructure/staterpc/conformance_test.go b/internal/infrastructure/staterpc/conformance_test.go index 987737bff..938c9cbd4 100644 --- a/internal/infrastructure/staterpc/conformance_test.go +++ b/internal/infrastructure/staterpc/conformance_test.go @@ -81,7 +81,7 @@ func remoteTaskStore(t *testing.T, local *pgstore.TaskDB, logs storecontract.Tas listener := bufconn.Listen(1 << 20) server := grpc.NewServer() deps := Deps{ - Tasks: local, BindingTaskCreator: local, + Tasks: local, BindingTaskCreator: local, WorkflowCalls: local, ConfigSnapshots: local, ApplyStatus: local, TaskLogs: logs, } diff --git a/internal/infrastructure/staterpc/server.go b/internal/infrastructure/staterpc/server.go index 7e6e53418..cb3a76bb6 100644 --- a/internal/infrastructure/staterpc/server.go +++ b/internal/infrastructure/staterpc/server.go @@ -42,6 +42,7 @@ var ( errBindingDispatchUnavailable = status.Error(codes.Unavailable, "binding dispatcher unavailable") errBindingTaskCreatorUnavailable = status.Error(codes.Unavailable, "binding task creator unavailable") errPlaybookDispatcherUnavailable = status.Error(codes.Unavailable, "playbook dispatcher unavailable") + errWorkflowCallerUnavailable = status.Error(codes.Unavailable, "workflow caller unavailable") // errTaskLogsUnavailable is the "this process cannot read task logs at // all" answer, and it is deliberately distinct from a found=false read // result: only the first is a deployment matter. A dashboard that receives @@ -89,6 +90,11 @@ type Deps struct { Sources storecontract.SourceStore BindingDispatcher storecontract.BindingDispatcher BindingTaskCreator storecontract.BindingTaskCreator + // WorkflowCalls is the workflow.call surface (docs/prds/workflow-calls.md): + // the workflow engine's task.Caller over this contract. Optional: nil + // answers both RPCs with codes.Unavailable, which is the honest answer + // for a store that owns no task table. + WorkflowCalls storecontract.WorkflowCaller // PlaybookDispatcher is the side-effecting-action idempotency ledger // (docs/prds/eda-playbook-engine.md gap 2). Optional: nil disables the // two playbook dispatch RPCs with codes.Unavailable. @@ -801,6 +807,40 @@ func (s *server) EnqueueBindingTask(ctx context.Context, r *pb.EnqueueBindingTas return &pb.EnqueueBindingTaskResponse{Task: taskProto(t)}, nil } +// WorkflowCaller: a workflow.call step starts its callee and reads it back +// while waiting (docs/prds/workflow-calls.md). The grant already named the +// caller; the store's own row checks are what make both calls answer only +// for this caller's own callees. + +func (s *server) EnqueueCallTask(ctx context.Context, r *pb.EnqueueCallTaskRequest) (*pb.EnqueueCallTaskResponse, error) { + if s.deps.WorkflowCalls == nil { + return nil, errWorkflowCallerUnavailable + } + if r.CallerTaskId <= 0 { + return nil, status.Error(codes.InvalidArgument, "caller task id is required") + } + inputs, err := task.DecodeInputs(r.InputsJson) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + t, err := s.deps.WorkflowCalls.StartCall(ctx, r.CallerTaskId, r.Workflow, inputs) + if err != nil { + return nil, s.logErr("EnqueueCallTask", err) + } + return &pb.EnqueueCallTaskResponse{Task: taskProto(t), Accepted: true}, nil +} + +func (s *server) WorkflowCallStatus(ctx context.Context, r *pb.WorkflowCallStatusRequest) (*pb.WorkflowCallStatusResponse, error) { + if s.deps.WorkflowCalls == nil { + return nil, errWorkflowCallerUnavailable + } + status, detail, err := s.deps.WorkflowCalls.CallStatus(ctx, r.CallerTaskId, r.CallTaskId) + if err != nil { + return nil, s.logErr("WorkflowCallStatus", err) + } + return &pb.WorkflowCallStatusResponse{Status: status, Detail: detail}, nil +} + // Task log func (s *server) taskLogs() (storecontract.TaskLogStore, error) { diff --git a/internal/infrastructure/staterpc/task_grants.go b/internal/infrastructure/staterpc/task_grants.go index 4e7147165..ccbb4ebc4 100644 --- a/internal/infrastructure/staterpc/task_grants.go +++ b/internal/infrastructure/staterpc/task_grants.go @@ -90,10 +90,17 @@ func (g *TaskGrants) taskFor(token string) int64 { return 0 } -// authorizesTaskScopedCall reports whether req -- a call to one of the three -// task.Store RPCs a task grant may ever authorize -- targets taskID. -// Every other RPC (including RegisterTaskGrant/RevokeTaskGrant themselves) -// falls through to false: a task grant can only ever narrow, never expand. +// authorizesTaskScopedCall reports whether req -- a call to one of the RPCs +// a task grant may ever authorize -- targets taskID. Every other RPC +// (including RegisterTaskGrant/RevokeTaskGrant themselves) falls through to +// false: a task grant can only ever narrow, never expand. +// +// The two workflow.call RPCs are the one sanctioned widening +// (docs/prds/workflow-calls.md): a workflow.call step must start its callee +// and read it back, and the callee is the caller's child. Both requests +// carry the caller's own task ID, which the grant check verifies; the +// parent-child relation is a handler-side row check, so this interceptor +// never reads the database. func authorizesTaskScopedCall(fullMethod string, req any, taskID int64) bool { switch fullMethod { case pb.StateStoreService_Update_FullMethodName: @@ -105,6 +112,12 @@ func authorizesTaskScopedCall(fullMethod string, req any, taskID int64) bool { case pb.StateStoreService_InsertEvent_FullMethodName: r, ok := req.(*pb.InsertEventRequest) return ok && r.Event != nil && r.Event.TaskId == taskID + case pb.StateStoreService_EnqueueCallTask_FullMethodName: + r, ok := req.(*pb.EnqueueCallTaskRequest) + return ok && r.CallerTaskId == taskID + case pb.StateStoreService_WorkflowCallStatus_FullMethodName: + r, ok := req.(*pb.WorkflowCallStatusRequest) + return ok && r.CallerTaskId == taskID default: return false } diff --git a/internal/infrastructure/staterpc/task_grants_call_test.go b/internal/infrastructure/staterpc/task_grants_call_test.go new file mode 100644 index 000000000..615e2ffb7 --- /dev/null +++ b/internal/infrastructure/staterpc/task_grants_call_test.go @@ -0,0 +1,87 @@ +package staterpc + +import ( + "errors" + "testing" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" + "github.com/samcharles93/archie-core/internal/domain/storecontract" + "github.com/samcharles93/archie-core/internal/domain/workflow" +) + +// TestTaskGrantAuthorizesTheWorkflowCallRPCs: a workflow.call step starts its +// callee and reads it back while waiting, so the caller's task grant must +// reach the two call RPCs for its own task -- and nothing else's +// (docs/prds/workflow-calls.md). CallStatus's parent check stays server-side, +// so the grant itself only ever verifies the request names the granted task. +func TestTaskGrantAuthorizesTheWorkflowCallRPCs(t *testing.T) { + const adminToken = "daemon-admin-token" + _, dial := grantsServer(t, adminToken) + admin := dial(t, adminToken) + ctx := t.Context() + + caller, err := admin.EnqueueChatTask(ctx, "acme", "widget", "caller", "body", "implement", "") + if err != nil { + t.Fatal(err) + } + other, err := admin.EnqueueChatTask(ctx, "acme", "widget", "other", "body", "implement", "") + if err != nil { + t.Fatal(err) + } + if err := admin.Transition(ctx, caller.ID, caller.Status, workflow.StatusRunning, "started"); err != nil { + t.Fatal(err) + } + + workerToken, err := admin.RegisterTaskGrant(ctx, caller.ID, callGrantLifetime) + if err != nil { + t.Fatalf("RegisterTaskGrant: %v", err) + } + worker := dial(t, workerToken) + + callee, err := worker.StartCall(ctx, caller.ID, "callee", map[string]any{"src_ip": "10.0.0.9"}) + if err != nil { + t.Fatalf("task grant should authorize StartCall on its own task: %v", err) + } + if callee.CallParentTaskID != caller.ID || callee.CallDepth != 1 { + t.Fatalf("callee = %+v, want the parent link and depth 1", callee) + } + if _, _, err := worker.CallStatus(ctx, caller.ID, callee.ID); err != nil { + t.Fatalf("task grant should authorize CallStatus on its own callees: %v", err) + } + if _, _, err := worker.CallStatus(ctx, caller.ID, other.ID); !errors.Is(err, storecontract.ErrCallNotYours) { + t.Fatalf("CallStatus for a task that is not this caller's callee = %v, want ErrCallNotYours", err) + } + + // The grant names one caller: another task's grant cannot start calls + // under it, and the granted caller cannot be named by someone else's + // token -- the request-shape check refuses both before the store runs. + if _, err := worker.StartCall(ctx, other.ID, "callee", nil); status.Code(err) != codes.PermissionDenied { + t.Fatalf("StartCall for another task = %v, want PermissionDenied", err) + } + if _, _, err := worker.CallStatus(ctx, other.ID, callee.ID); status.Code(err) != codes.PermissionDenied { + t.Fatalf("CallStatus for another task = %v, want PermissionDenied", err) + } + + // The sentinels survive the wire: a stale retry surfaces the documented + // refusal, not an opaque internal. The admin dial carries it because the + // worker's grant names a caller that is still running; the refusal is + // what a later grant for a finished caller's task would see. + if _, err := admin.StartCall(ctx, callee.ID, "deeper", nil); !errors.Is(err, storecontract.ErrCallCallerNotRunning) { + t.Fatalf("StartCall from a completed caller = %v, want ErrCallCallerNotRunning", err) + } +} + +// callGrantLifetime mirrors the daemon's defaultGrantLifetime; the value is +// not under test, only the scoping. +const callGrantLifetime = defaultGrantLifetime + +// The wire requests this grant widens are the two call RPCs only; this +// compile-time check pins the full-method names the interceptor cases match +// on, so a rename on the proto side is caught here rather than at runtime. +var ( + _ = pb.StateStoreService_EnqueueCallTask_FullMethodName + _ = pb.StateStoreService_WorkflowCallStatus_FullMethodName +) diff --git a/internal/infrastructure/staterpc/task_grants_test.go b/internal/infrastructure/staterpc/task_grants_test.go index 3094fa592..3f37b5933 100644 --- a/internal/infrastructure/staterpc/task_grants_test.go +++ b/internal/infrastructure/staterpc/task_grants_test.go @@ -41,6 +41,7 @@ func grantsServer(t *testing.T, adminToken string) (grants *TaskGrants, dial fun Tasks: local, ConfigSnapshots: local, ApplyStatus: local, Captures: eda, Mappings: eda, Bindings: eda, BindingDispatcher: eda, PlaybookDispatcher: eda, EventTypes: eda, + BindingTaskCreator: local, WorkflowCalls: local, Grants: grants, }) go func() { _ = server.Serve(listener) }() @@ -163,7 +164,7 @@ func TestUpdateRejectsNilTask(t *testing.T) { // Transition/InsertEvent on its own task ID, never the admin-only surface // (StatusCounts here stands in for any of the other ~37 RPCs) and never // another task's ID. -func TestTaskGrantScopesWorkerToItsOwnThreeRPCs(t *testing.T) { +func TestTaskGrantScopesWorkerToItsOwnRPCs(t *testing.T) { const adminToken = "daemon-admin-token" grants, dial := grantsServer(t, adminToken) admin := dial(t, adminToken) diff --git a/internal/infrastructure/staterpc/values.go b/internal/infrastructure/staterpc/values.go index bb37bf167..dcffa1128 100644 --- a/internal/infrastructure/staterpc/values.go +++ b/internal/infrastructure/staterpc/values.go @@ -80,6 +80,8 @@ func taskProto(t *task.Task) *pb.Task { //nolint:dupl // mirror-image field-by-f WorkflowDefinitionDigest: t.WorkflowDefinitionDigest, WorkflowDefinitionYaml: t.WorkflowDefinitionYAML, Org: string(t.Org), + CallParentTaskId: t.CallParentTaskID, + CallDepth: int32(t.CallDepth), } } @@ -105,6 +107,8 @@ func taskValue(t *pb.Task) *task.Task { //nolint:dupl // see taskProto above WorkflowDefinitionDigest: t.WorkflowDefinitionDigest, WorkflowDefinitionYAML: t.WorkflowDefinitionYaml, Org: org.OrgID(t.Org), + CallParentTaskID: t.CallParentTaskId, + CallDepth: int(t.CallDepth), } } @@ -453,6 +457,9 @@ var wireErrors = []struct { {storecontract.ErrEventTypeNotFound, codes.NotFound, msgEventTypeNotFound}, {storecontract.ErrSourceNotFound, codes.NotFound, msgSourceNotFound}, {storecontract.ErrAlreadyDispatched, codes.AlreadyExists, msgAlreadyDispatched}, + {storecontract.ErrCallNotYours, codes.PermissionDenied, storecontract.ErrCallNotYours.Error()}, + {storecontract.ErrCallCallerNotRunning, codes.FailedPrecondition, storecontract.ErrCallCallerNotRunning.Error()}, + {storecontract.ErrCallDepthExceeded, codes.FailedPrecondition, storecontract.ErrCallDepthExceeded.Error()}, {storecontract.ErrSourcePathTaken, codes.AlreadyExists, msgSourcePathTaken}, {storepkg.ErrNotFound, codes.NotFound, storepkg.ErrNotFound.Error()}, {storepkg.ErrInstalled, codes.AlreadyExists, storepkg.ErrInstalled.Error()}, diff --git a/internal/infrastructure/staterpc/workflow_call_conformance_test.go b/internal/infrastructure/staterpc/workflow_call_conformance_test.go new file mode 100644 index 000000000..4969a889c --- /dev/null +++ b/internal/infrastructure/staterpc/workflow_call_conformance_test.go @@ -0,0 +1,117 @@ +package staterpc + +import ( + "errors" + "testing" + + "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" +) + +// workflowCallerContract is the workflow.call surface both adapters must +// satisfy identically (§11), including refusal-sentinel fidelity across the +// wire (docs/prds/workflow-calls.md). +type workflowCallerContract interface { + storecontract.WorkflowCaller +} + +// TestWorkflowCallerConformance drives StartCall/CallStatus through the local +// PostgreSQL store and a bufconn-backed gRPC client. +func TestWorkflowCallerConformance(t *testing.T) { + for _, mode := range []string{"local", "grpc"} { + t.Run(mode, func(t *testing.T) { + ctx := t.Context() + local := pgstore.Open(t) + var c workflowCallerContract = local + if mode == "grpc" { + c = remoteTaskStore(t, local, nil, nil) + } + + caller, err := local.EnqueueChatTask(ctx, "acme", "widget", "caller", "body", "implement", "") + if err != nil { + t.Fatalf("EnqueueChatTask: %v", err) + } + if err := local.Transition(ctx, caller.ID, caller.Status, workflow.StatusRunning, "started"); err != nil { + t.Fatalf("Transition caller: %v", err) + } + + // A running caller's callee inherits its row and links back to it. + callee, err := c.StartCall(ctx, caller.ID, "callee", map[string]any{"src_ip": "10.0.0.9"}) + if err != nil || callee == nil { + t.Fatalf("StartCall: (%+v, %v)", callee, err) + } + if callee.Workflow != "callee" || callee.CallParentTaskID != caller.ID || callee.CallDepth != 1 { + t.Fatalf("callee = %+v, want the parent link and depth 1", callee) + } + if callee.Org != caller.Org || callee.Identity != caller.Identity { + t.Fatalf("callee org/identity = %q/%q, want the caller's %q/%q", callee.Org, callee.Identity, caller.Org, caller.Identity) + } + if callee.Owner != caller.Owner || callee.Repo != caller.Repo { + t.Fatalf("callee owner/repo = %s/%s, want the caller's %s/%s", callee.Owner, callee.Repo, caller.Owner, caller.Repo) + } + if callee.Source != "chat" || callee.IssueNumber == caller.IssueNumber { + t.Fatalf("callee source/issue = %s/%d, want a chat source with a fresh synthetic number", callee.Source, callee.IssueNumber) + } + if callee.Inputs["src_ip"] != "10.0.0.9" { + t.Fatalf("callee inputs = %+v, want the call's inputs", callee.Inputs) + } + + // A callee that has not moved yet answers its queued status with + // no detail; after a transition the detail is the latest one. + status, detail, err := c.CallStatus(ctx, caller.ID, callee.ID) + if err != nil || status != workflow.StatusQueued || detail != "" { + t.Fatalf("CallStatus queued = (%q, %q, %v), want (queued, \"\", nil)", status, detail, err) + } + if err := local.Transition(ctx, callee.ID, callee.Status, workflow.StatusRunning, "started"); err != nil { + t.Fatalf("Transition callee to running: %v", err) + } + if err := local.Transition(ctx, callee.ID, workflow.StatusRunning, workflow.StatusCompleted, "contained 10.0.0.9"); err != nil { + t.Fatalf("Transition callee to completed: %v", err) + } + status, detail, err = c.CallStatus(ctx, caller.ID, callee.ID) + if err != nil || status != workflow.StatusCompleted || detail != "contained 10.0.0.9" { + t.Fatalf("CallStatus completed = (%q, %q, %v), want the terminal status and detail", status, detail, err) + } + + // A caller reads only its own callees, over both adapters. + _, _, err = c.CallStatus(ctx, 99999, callee.ID) + if !errors.Is(err, storecontract.ErrCallNotYours) { + t.Fatalf("CallStatus foreign caller = %v, want ErrCallNotYours", err) + } + _, _, err = c.CallStatus(ctx, caller.ID, 99999) + if !errors.Is(err, storecontract.ErrCallNotYours) { + t.Fatalf("CallStatus missing callee = %v, want ErrCallNotYours", err) + } + + // Refusals: a caller that is not running, and the depth limit. The + // sentinels cross the wire, so both adapters report the same one. + if _, err := c.StartCall(ctx, callee.ID, "deeper", nil); !errors.Is(err, storecontract.ErrCallCallerNotRunning) { + t.Fatalf("StartCall from a completed caller = %v, want ErrCallCallerNotRunning", err) + } + // The depth limit is re-checked by the store, not just the engine: + // walk a chain of callees, claiming each so it is running, until + // the insert itself refuses at MaxCallDepth. + current, err := c.StartCall(ctx, caller.ID, "deeper", nil) + if err != nil { + t.Fatalf("StartCall at depth 1: %v", err) + } + for current.CallDepth < workflow.MaxCallDepth { + claimed, err := local.ClaimByIssue(ctx, current.Owner, current.Repo, current.IssueNumber) + if err != nil || claimed == nil { + t.Fatalf("claim depth %d callee: (%+v, %v)", current.CallDepth, claimed, err) + } + current, err = c.StartCall(ctx, current.ID, "deeper", nil) + if err != nil { + t.Fatalf("StartCall at depth %d: %v", claimed.CallDepth+1, err) + } + } + if _, err := local.ClaimByIssue(ctx, current.Owner, current.Repo, current.IssueNumber); err != nil { + t.Fatalf("claim depth %d callee: %v", current.CallDepth, err) + } + if _, err := c.StartCall(ctx, current.ID, "deeper", nil); !errors.Is(err, storecontract.ErrCallDepthExceeded) { + t.Fatalf("StartCall past the depth limit = %v, want ErrCallDepthExceeded", err) + } + }) + } +} diff --git a/internal/infrastructure/workflowsteps/workflowsteps.go b/internal/infrastructure/workflowsteps/workflowsteps.go index e44c01fef..ba672b39a 100644 --- a/internal/infrastructure/workflowsteps/workflowsteps.go +++ b/internal/infrastructure/workflowsteps/workflowsteps.go @@ -64,7 +64,7 @@ type eventSteps struct{} func (eventSteps) Name() string { return "event" } func (eventSteps) StepTypes() []workflow.StepType { - return []workflow.StepType{workflow.AgentRunStepType()} + return []workflow.StepType{workflow.AgentRunStepType(), workflow.WorkflowCallStepType()} } // Providers returns the provider set the roots that resolve a workflow step diff --git a/proto/state/v1/state.proto b/proto/state/v1/state.proto index b2a90e523..48fb14798 100644 --- a/proto/state/v1/state.proto +++ b/proto/state/v1/state.proto @@ -157,6 +157,14 @@ service StateStoreService { // BindingTaskCreator rpc EnqueueBindingTask(EnqueueBindingTaskRequest) returns (EnqueueBindingTaskResponse); + + // WorkflowCaller: a workflow.call step starts its callee and, with + // wait:true, reads it back while waiting. Both are the one sanctioned + // widening of a task-scoped grant -- the callee is the caller's child + // (docs/prds/workflow-calls.md). CallStatus re-checks the parent-child + // relation server-side, so the grant only names the caller. + rpc EnqueueCallTask(EnqueueCallTaskRequest) returns (EnqueueCallTaskResponse); + rpc WorkflowCallStatus(WorkflowCallStatusRequest) returns (WorkflowCallStatusResponse); } message RegisterTaskGrantRequest { @@ -282,6 +290,12 @@ message Task { // identity when the row is written; a task of a single-operator install // belongs to the default org (docs/prds/orgs-and-access.md). string org = 35; + // The workflow.call linkage (docs/prds/workflow-calls.md): the task whose + // workflow.call step started this one (0 on a root run) and how many + // call hops this row is from that root. Columns default, so an older + // writer reads as a depth-0 root run. + int64 call_parent_task_id = 36; + int32 call_depth = 37; } // Event mirrors internal/events.Event. Data is carried as a JSON object @@ -862,6 +876,29 @@ message EnqueueBindingTaskRequest { } message EnqueueBindingTaskResponse { Task task = 1; } +// workflow.call: the caller's grant names the caller; the store derives the +// rest from the caller's row (docs/prds/workflow-calls.md). +message EnqueueCallTaskRequest { + int64 caller_task_id = 1; + string workflow = 2; + string inputs_json = 3; +} +message EnqueueCallTaskResponse { + Task task = 1; + bool accepted = 2; +} + +message WorkflowCallStatusRequest { + int64 caller_task_id = 1; + int64 call_task_id = 2; +} +message WorkflowCallStatusResponse { + // status is the callee's task status and detail its latest transition + // detail (empty before the callee first moves). + string status = 1; + string detail = 2; +} + message InstalledPackage { string org_id = 1; string name = 2;