refactor: strip doc and issue narration from code comments
Remove PRD/doc paths, bead IDs, phase notes and deleted-test references from comments; drop test-only hooks left by the test deletion. Includes in-progress archied bootstrap, gateway and query changes.
This commit is contained in:
269 files changed
+1201
-2609
No files matched your search
@@ -3,7 +3,7 @@
|
||||
// validation against the shipped Cedar schema, and the chain evaluation:
|
||||
// instance ▶ org ▶ workspace ▶ object, where a level with policies must
|
||||
// permit, a forbid at any level wins, and with no permit the request is
|
||||
// denied (docs/prds/orgs-and-access.md).
|
||||
// denied.
|
||||
//
|
||||
// The cross-org forbid is enforced here, structurally, before any Cedar
|
||||
// runs: a principal never reaches a resource outside its org. It is not a
|
||||
@@ -50,7 +50,6 @@ const schemaText = `namespace Archie {
|
||||
|
||||
// Problem is one stored policy the engine could not validate. It is what a
|
||||
// health issue names: the policy and the error
|
||||
// (docs/prds/orgs-and-access.md, "Storing and changing policies").
|
||||
type Problem struct {
|
||||
Policy access.Policy
|
||||
Err error
|
||||
|
||||
@@ -23,11 +23,10 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/worktreerpc"
|
||||
)
|
||||
|
||||
// Config contains the broker endpoint and credential for the worker
|
||||
// transport, plus the State Store gRPC target (docs/prds/
|
||||
// state-store-contract.md §6). StateStoreURL is required: the agent is fully
|
||||
// on gRPC for its store calls, and the legacy NATS storerpc path is deleted
|
||||
// (docs/prds/state-store-contract.md §12 step 4).
|
||||
// Config contains the broker endpoint and credential for the worker transport,
|
||||
// plus the State Store gRPC target. StateStoreURL is required: the agent is
|
||||
// fully on gRPC for its store calls, and the legacy NATS storerpc path is
|
||||
// deleted
|
||||
type Config struct {
|
||||
URL string
|
||||
Token string
|
||||
@@ -63,7 +62,7 @@ type Transport struct {
|
||||
|
||||
// Connect establishes the worker's core-NATS connection and, when
|
||||
// Config.StateStoreURL is set, a long-lived gRPC connection to the State
|
||||
// Store (docs/prds/state-store-contract.md §6, §9). A non-loopback
|
||||
// Store. A non-loopback
|
||||
// StateStoreURL with no token fails closed rather than dialing an
|
||||
// unauthenticated remote store.
|
||||
func Connect(ctx context.Context, config Config, log *slog.Logger) (*Transport, error) {
|
||||
@@ -87,10 +86,9 @@ func Connect(ctx context.Context, config Config, log *slog.Logger) (*Transport,
|
||||
}
|
||||
log.Info("worker transport connected", "url", conn.ConnectedUrl())
|
||||
|
||||
// The agent is fully on gRPC for its store calls; the legacy NATS
|
||||
// storerpc path is deleted (docs/prds/state-store-contract.md §12 step
|
||||
// 4). A missing StateStoreURL fails fast rather than letting Store()
|
||||
// hand back a client over a nil connection.
|
||||
// The agent is fully on gRPC for its store calls; the legacy NATS storerpc
|
||||
// path is deleted. A missing StateStoreURL fails fast rather than letting
|
||||
// Store() hand back a client over a nil connection.
|
||||
if config.StateStoreURL == "" {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("state store target is required: archie-agent no longer supports the legacy NATS storerpc path (docs/prds/state-store-contract.md §12 step 4)")
|
||||
@@ -146,9 +144,9 @@ func (t *Transport) Forger(identity string, timeout time.Duration) workflow.Forg
|
||||
}
|
||||
|
||||
// Store constructs the workflow store RPC client over the long-lived State
|
||||
// Store client (docs/prds/state-store-contract.md §6). Each call is bounded
|
||||
// Store client. Each call is bounded
|
||||
// by timeout when the caller's context carries no deadline of its own. The
|
||||
// legacy NATS storerpc path is deleted (§12 step 4); a transport without a
|
||||
// legacy NATS storerpc path is deleted; a transport without a
|
||||
// State Store client cannot reach Store() because Connect refused to build
|
||||
// one.
|
||||
func (t *Transport) Store(timeout time.Duration) workflow.Store {
|
||||
@@ -156,7 +154,7 @@ func (t *Transport) Store(timeout time.Duration) workflow.Store {
|
||||
}
|
||||
|
||||
// Calls constructs the workflow.call RPC client over the same long-lived
|
||||
// State Store client (docs/prds/workflow-calls.md), bounded by timeout the
|
||||
// State Store client, bounded by timeout the
|
||||
// same way Store() is.
|
||||
func (t *Transport) Calls(timeout time.Duration) task.Caller {
|
||||
return deadlineCaller{Caller: t.state, timeout: timeout}
|
||||
|
||||
@@ -25,7 +25,7 @@ const bindingNonceLen = 12
|
||||
|
||||
// Domain is an envelope's marker and additional-authenticated-data: the
|
||||
// separator that stops a ciphertext sealed for one column being relocated to
|
||||
// a different one and still authenticating (docs/prds/binding-secret-encryption.md).
|
||||
// a different one and still authenticating.
|
||||
// Domains share the same keyring; only the marker and AAD differ.
|
||||
type Domain struct {
|
||||
marker string
|
||||
@@ -40,7 +40,7 @@ var (
|
||||
// meaningful attack.
|
||||
BindingDomain = Domain{marker: "arcie-binding", aad: []byte("arcie-binding-secret")}
|
||||
// HarnessSecretDomain seals harness OAuth token sets
|
||||
// (docs/prds/external-agent-harness.md, Credentials) -- its own
|
||||
// -- its own
|
||||
// separator, so a row cannot be moved from oauth_secrets into a
|
||||
// bindings-secret column (or back) and still authenticate.
|
||||
HarnessSecretDomain = Domain{marker: "arcie-harness", aad: []byte("arcie-harness-secret")}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
// Package captureintake is the HTTP receiver for inbound webhooks archie has
|
||||
// no binding for yet: it persists what arrives so an operator can inspect it
|
||||
// and build one (docs/prds/event-capture-storage.md).
|
||||
// and build one.
|
||||
//
|
||||
// It belongs to the process that owns work intake, not to the dashboard that
|
||||
// displays captures. It served from the dashboard's listener while the two
|
||||
// shared a process; the split gives the read to the dashboard, over the State
|
||||
// Store, and keeps the write here (archie-core-8cda.5.4). From the cutover
|
||||
// Store, and keeps the write here. From the cutover
|
||||
// change in the same bead it is a persistence shim over the State Store
|
||||
// contract mounted by the UI process -- the only dashboard listener left --
|
||||
// while the daemon's binding-dispatch loop consumes captures from the same
|
||||
@@ -117,8 +117,7 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
// A body that isn't JSON has no key-value structure for the heuristic to
|
||||
// match against, so there is nothing to redact -- store it as received
|
||||
// rather than dropping or mangling it. Best-effort, per
|
||||
// docs/prds/webhook-intake-security.md point 5.
|
||||
// rather than dropping or mangling it. Best-effort.
|
||||
redactedBody, err := webhookguard.RedactPayload(body)
|
||||
if err != nil {
|
||||
redactedBody = body
|
||||
@@ -141,13 +140,8 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
// Reuses the existing activity-event pipeline rather than inventing
|
||||
// separate push plumbing -- see docs/prds/event-capture-storage.md.
|
||||
// Deliberately LIGHTWEIGHT: the events table this feeds has no retention
|
||||
// or row-count prune, unlike captured_events, so embedding the full (up
|
||||
// to MaxBodyBytes) body/headers here would duplicate the payload into an
|
||||
// unbounded table and defeat InsertCapture's own disk-bound guarantee.
|
||||
// The captures view treats this purely as an invalidation signal and
|
||||
// refetches the list for the actual row data.
|
||||
// separate push plumbing. The captures view treats this purely as an
|
||||
// invalidation signal and refetches the list for the actual row data.
|
||||
if rc.Publish != nil {
|
||||
rc.Publish(r.Context(), events.Event{
|
||||
Kind: "capture",
|
||||
@@ -204,13 +198,7 @@ func (rc *Receiver) logger() *slog.Logger {
|
||||
}
|
||||
|
||||
// fallbackMaxBodyBytes bounds a capture body when MaxBodyBytes is left unset
|
||||
// (zero). The size cap is the only one of the three disk-bound mechanics in
|
||||
// docs/prds/event-capture-storage.md that limits a SINGLE payload rather than
|
||||
// total row count or write rate -- a table pruned to maxEvents rows still
|
||||
// holds one arbitrarily large row if nothing ever bounded that row's size, so
|
||||
// this must never be skippable by a missing wiring value the way the rate
|
||||
// limiter (best-effort, not disk-bound-load-bearing on its own) is allowed to
|
||||
// be.
|
||||
// (zero).
|
||||
const fallbackMaxBodyBytes = 256 * 1024
|
||||
|
||||
func maxBodyBytesOrFallback(configured int64) int64 {
|
||||
|
||||
@@ -38,9 +38,7 @@ const (
|
||||
// small enough that a large download cannot occupy the daemon.
|
||||
defaultWebFetchMaxBytes = 2_000_000
|
||||
|
||||
// Capture defaults, per docs/prds/event-capture-storage.md's disk-bound
|
||||
// mechanics: retention + row cap + per-request size cap + per-source
|
||||
// rate limit, composed.
|
||||
// Capture defaults.
|
||||
defaultCaptureRetention = 7 * 24 * time.Hour
|
||||
defaultCaptureMaxEvents = 5000
|
||||
defaultCaptureMaxBodyBytes = 256 * 1024
|
||||
@@ -121,8 +119,8 @@ func applyMemoryDefaults(cfg *config.Config) {
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultCapture returns the webhook capture endpoint's default settings
|
||||
// (docs/prds/event-capture-storage.md). applyCaptureDefaults fills a decoded
|
||||
// DefaultCapture returns the webhook capture endpoint's default settings.
|
||||
// applyCaptureDefaults fills a decoded
|
||||
// config with them; the UI process composes the same capture receiver and
|
||||
// must produce the same effective values when it is driven by flags alone
|
||||
// and no configuration file projected [capture] to it.
|
||||
|
||||
@@ -7,7 +7,7 @@ package configuration
|
||||
// API returns 4xx) and again in the overlay's Set, not silently dropped at
|
||||
// read time. Owned here rather than in the overlay package so the webui
|
||||
// config renderer can reference the policy without linking the overlay's
|
||||
// SQLite store (archie-core-8cda.5.6).
|
||||
// SQLite store.
|
||||
var DeniedKeys = map[string]string{
|
||||
"database_url": "required for bootstrap; cannot be changed at runtime",
|
||||
"state_dir": "required for bootstrap; cannot be changed at runtime",
|
||||
|
||||
@@ -13,18 +13,16 @@
|
||||
// # Why this package exists
|
||||
//
|
||||
// Loading used to live inside internal/config, alongside the runtime types
|
||||
// every package imports. That made the shared model responsible for file
|
||||
// I/O, so a package that merely wanted a settings struct also pulled in a
|
||||
// TOML decoder, and defaulting, validation and decoding were interleaved in
|
||||
// one function. See docs/architecture/configuration.md.
|
||||
// every package imports. That made the shared model responsible for file I/O,
|
||||
// so a package that merely wanted a settings struct also pulled in a TOML
|
||||
// decoder, and defaulting, validation and decoding were interleaved in one
|
||||
// function.
|
||||
//
|
||||
// # The temporary seam
|
||||
//
|
||||
// docs/architecture/configuration.md requires a private input document that
|
||||
// is translated into per-domain settings and never returned as the
|
||||
// application's runtime model. [Document.Config] is not that yet: it is the
|
||||
// existing internal/config.Config, exposed here so this package can take
|
||||
// over loading without every consumer changing at once.
|
||||
// [Document.Config] is not that yet: it is the existing internal/config.Config,
|
||||
// exposed here so this package can take over loading without every consumer
|
||||
// changing at once.
|
||||
//
|
||||
// It is deliberately a named field rather than a bare return value so the
|
||||
// compromise is visible at each use site. It should be replaced by typed
|
||||
|
||||
@@ -16,9 +16,7 @@ import (
|
||||
type Document struct {
|
||||
// Config is the translated settings.
|
||||
//
|
||||
// TEMPORARY. docs/architecture/configuration.md requires this to become
|
||||
// typed per-domain sections that never expose a whole-application model.
|
||||
// It stays for now so this package can own loading without every
|
||||
// TEMPORARY. It stays for now so this package can own loading without every
|
||||
// consumer changing at once. Delete when internal/config is dissolved.
|
||||
Config config.Config
|
||||
// Scheduling is the decoded [scheduling] input. Application composition
|
||||
@@ -402,11 +400,7 @@ func (l *Loader) loadDir(doc *Document, dir string, layer Layer) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// decodeMain decodes the daemon-level file in whichever format it uses. An
|
||||
// overlay layer's file is FOLDED over what the base layer decoded, the same way
|
||||
// a single overlay file folds over its base -- otherwise a map-valued entry it
|
||||
// only partly addresses would clear the fields it does not name, which is the
|
||||
// archie-core-e2e2 failure on the directory form of the same flag.
|
||||
// decodeMain decodes the daemon-level file in whichever format it uses.
|
||||
func (l *Loader) decodeMain(doc *Document, path string, isYAMLFile bool, layer Layer) error {
|
||||
if layer == LayerOverlay {
|
||||
cfgKeys, err := applyOverlayFile(path, &doc.Config)
|
||||
|
||||
@@ -10,12 +10,8 @@ import (
|
||||
)
|
||||
|
||||
// cloudProvider is one selectable cloud LLM provider: the config class it
|
||||
// writes and the env var name its secret is stored under. Both the
|
||||
// provider step (which writes providers.<name>.api_key = {engine, key})
|
||||
// and the secret sink (which is asked to store the value under exactly
|
||||
// that key) read from this single table, so the two can never name the
|
||||
// secret differently -- the exact class of bug archie-core-cbk exists to
|
||||
// close for forge tokens, applied the same way to provider keys.
|
||||
// writes and the env var its secret is stored under. The provider step and the
|
||||
// secret sink both read this table, so they always name the same secret.
|
||||
type cloudProvider struct {
|
||||
name string
|
||||
class string
|
||||
|
||||
@@ -4,14 +4,12 @@
|
||||
//
|
||||
// # Why not decode/re-marshal
|
||||
//
|
||||
// BurntSushi/toml (this project's TOML library, and every other Go TOML
|
||||
// encoder evaluated for archie-core-rs9) does not round-trip comments: a
|
||||
// Decode followed by an Encode reproduces the data but discards every
|
||||
// comment. config.example.toml carries substantial documentation as inline
|
||||
// comments that operators are meant to read and hand-edit, and archied
|
||||
// setup must be able to write into that same file -- and be re-run later
|
||||
// to change one value -- without deleting it. A full re-marshal was
|
||||
// rejected for that reason (archie-core-rs9).
|
||||
// BurntSushi/toml does not round-trip comments: a Decode followed by an Encode
|
||||
// reproduces the data but discards every comment. config.example.toml carries
|
||||
// substantial documentation as inline comments that operators are meant to read
|
||||
// and hand-edit, and archied setup must be able to write into that same file --
|
||||
// and be re-run later to change one value -- without deleting it. A full
|
||||
// re-marshal was rejected for that reason.
|
||||
//
|
||||
// # The chosen strategy
|
||||
//
|
||||
@@ -25,14 +23,11 @@
|
||||
// the document). Every line Apply was not asked to touch is copied through
|
||||
// unchanged, byte for byte.
|
||||
//
|
||||
// This trades generality for the property archie-core-rs9 requires: a
|
||||
// second setup run that changes one value leaves every other line --
|
||||
// comments included -- identical to the first run's output. It only
|
||||
// understands single-line scalar and inline-table values (strings,
|
||||
// It only understands single-line scalar and inline-table values (strings,
|
||||
// numbers, booleans, `{ engine = "...", key = "..." }` secret refs), which
|
||||
// covers everything archied setup writes. Multi-line arrays and
|
||||
// [[array-of-tables]] entries are not targets for Apply; other code paths
|
||||
// (e.g. adding a [[repos]] entry) must not use it.
|
||||
// [[array-of-tables]] entries are not targets for Apply; other code paths (e.g.
|
||||
// adding a [[repos]] entry) must not use it.
|
||||
package tomlwrite
|
||||
|
||||
import (
|
||||
|
||||
@@ -84,16 +84,14 @@ func validate(cfg *config.Config) error {
|
||||
// State Store. [Loader] applies this to every file source.
|
||||
//
|
||||
// It deliberately omits the settings the control plane stores, because a stale
|
||||
// TOML value in one of them must not be able to fail a process's startup
|
||||
// (docs/prds/runtime-control-plane.md, "Bootstrap, migration, and recovery":
|
||||
// after migration, settings in TOML are ignored and cannot block State Store
|
||||
// startup). archie-state-store resolves its file config and seeds the
|
||||
// control-plane resources from that same document on a fresh database, and a
|
||||
// seed it cannot validate is skipped rather than fatal
|
||||
// (controlplane.Server.ImportConfig), so a check left here is a check that can
|
||||
// still block it. Those checks live in validateDatabaseOwned and run on the
|
||||
// effective document instead -- which is where the process that uses the value
|
||||
// refuses it, and where the operator's fix is the file again.
|
||||
// TOML value in one of them must not be able to fail a process's startup.
|
||||
// archie-state-store resolves its file config and seeds the control-plane
|
||||
// resources from that same document on a fresh database, and a seed it cannot
|
||||
// validate is skipped rather than fatal (controlplane.Server.ImportConfig), so
|
||||
// a check left here is a check that can still block it. Those checks live in
|
||||
// validateDatabaseOwned and run on the effective document instead -- which is
|
||||
// where the process that uses the value refuses it, and where the operator's
|
||||
// fix is the file again.
|
||||
func validateBootstrap(cfg *config.Config) error {
|
||||
if err := validateForgeIntake(cfg); err != nil {
|
||||
return err
|
||||
@@ -394,7 +392,6 @@ func validateSingleIdentity(cfg *config.Config) error {
|
||||
// the only point the value being judged is the one a process will use. The
|
||||
// per-identity lists are verified there for a different reason: no resource
|
||||
// carries them, and the daemon is the only process that reads them
|
||||
// (docs/architecture/configuration.md's IdentityConfig note).
|
||||
func validateRepositoryContents(cfg *config.Config) error {
|
||||
if len(cfg.Identities) == 0 {
|
||||
return ValidateRepositories(cfg.Repos)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// contract: the generic resource client, the channel-settings document it
|
||||
// projects, and the wire sentinels both sides match on. It exists so a service
|
||||
// that only reads stored settings does not link the store-backed server, the
|
||||
// workflow engine or the SQLite driver (archie-core-1ng1).
|
||||
// workflow engine or the SQLite driver.
|
||||
package controlplanerpc
|
||||
|
||||
import (
|
||||
|
||||
@@ -5,12 +5,10 @@ import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
// GrantResolver is the production Resolver: it holds, per active run, only
|
||||
// the secrets a caller explicitly Grant-ed it -- the intersection a run
|
||||
// credential carries (docs/prds/external-agent-harness.md, Credentials;
|
||||
// docs/prds/orgs-and-access.md, "Agents: decided once, carried as a run
|
||||
// credential"). It never derives a secret from anything else, so a service
|
||||
// nobody granted, or granted to a different run, always answers ErrUnbound.
|
||||
// GrantResolver is the production Resolver: it holds, per active run, only the
|
||||
// secrets a caller explicitly Grant-ed it -- the intersection a run credential
|
||||
// carries. It never derives a secret from anything else, so a service nobody
|
||||
// granted, or granted to a different run, always answers ErrUnbound.
|
||||
type GrantResolver struct {
|
||||
mu sync.RWMutex
|
||||
grants map[string]map[string]string
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
const maxTokenExchange = 1 << 20
|
||||
|
||||
// OAuthStore persists one org's OAuth token set per credential binding
|
||||
// service (docs/prds/external-agent-harness.md, Credentials). It is
|
||||
// service. It is
|
||||
// storecontract.HarnessSecretStore's method set, declared narrow here.
|
||||
type OAuthStore interface {
|
||||
GetHarnessSecret(ctx context.Context, org, service string) (harnesssecret.Secret, error)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
// Callers receive [Message], not jetstream.Msg, and publish [TaskEnvelope] or
|
||||
// [Request], not *nats.Msg. That keeps the broker replaceable and stops SDK
|
||||
// types leaking into domain packages, per
|
||||
// docs/architecture/dependencies-and-contracts.md.
|
||||
//
|
||||
// Layout:
|
||||
//
|
||||
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
//
|
||||
// The daemon embeds one of these for single-process deployments so reaction
|
||||
// delivery and task distribution share the same transport whether NATS runs
|
||||
// as a separate server or in-process (docs/prds/embedded-nats.md). The daemon
|
||||
// as a separate server or in-process. The daemon
|
||||
// owns the lifecycle: StartEmbedded before dialing the client, Shutdown after
|
||||
// the client closes.
|
||||
type EmbeddedServer struct {
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
|
||||
// tokenMetadataKey is the gRPC metadata key the Gateway Bearer [REDACTED]
|
||||
// travels in. Metadata, never a URL, mirroring the State Store's
|
||||
// token lifecycle (docs/prds/state-store-contract.md §9).
|
||||
// token lifecycle.
|
||||
const tokenMetadataKey = "gateway-token"
|
||||
|
||||
// TargetIsLoopback reports whether addr's host is a loopback address. Both
|
||||
|
||||
@@ -28,13 +28,11 @@ const (
|
||||
credentialFileMode = "0600"
|
||||
)
|
||||
|
||||
// renderCredentialFile renders c's oauth.credentialFile: the declared
|
||||
// structure with the Kit's sentinels substituted for the token placeholders,
|
||||
// the stored token set's scopes for {{.Scopes}} and its expiry for
|
||||
// {{.ExpiresAt}}, encoded in the declared format. facts is the only thing the
|
||||
// renderer receives about the stored token set, so a real token cannot reach
|
||||
// the file (docs/prds/external-agent-harness.md, "Verification: the credential
|
||||
// file holds only sentinels").
|
||||
// renderCredentialFile renders c's oauth.credentialFile: the declared structure
|
||||
// with the Kit's sentinels substituted for the token placeholders, the stored
|
||||
// token set's scopes for {{.Scopes}} and its expiry for {{.ExpiresAt}}, encoded
|
||||
// in the declared format. facts is the only thing the renderer receives about
|
||||
// the stored token set, so a real token cannot reach the file.
|
||||
func renderCredentialFile(c spec.CredentialCapability, facts OAuthFacts) (string, error) {
|
||||
cf := c.OAuth.CredentialFile
|
||||
var sentinels spec.Sentinels
|
||||
|
||||
@@ -152,7 +152,7 @@ func FromMerge(merged *spec.MergeResult) (*Plan, error) {
|
||||
}
|
||||
|
||||
// ValidateNeeds rejects a Plan that cannot meet what the workflow's stages
|
||||
// declared they need (docs/prds/external-agent-harness.md, "Contract"): a
|
||||
// declared they need: a
|
||||
// gate that may retry needs the Kit's agent-sessions resume verb, because
|
||||
// archie resumes the session with the gate's output rather than starting
|
||||
// over. gateRetries is zero for a workflow with no gated stage, which no
|
||||
|
||||
@@ -42,7 +42,6 @@ type Grants interface {
|
||||
// Kit's credential file can render that set's expiry. It is the store's read
|
||||
// half only: kitrun never writes a token set, and nothing but the expiry
|
||||
// leaves oauthExpiries, so a real token cannot reach the credential file
|
||||
// (docs/prds/external-agent-harness.md, "Verification").
|
||||
type OAuthSecrets interface {
|
||||
GetHarnessSecret(ctx context.Context, org, service string) (harnesssecret.Secret, error)
|
||||
}
|
||||
@@ -66,11 +65,9 @@ type Launcher struct {
|
||||
// construction: credential bindings are their own live control-plane
|
||||
// resource (controlplane.CredentialBindingsKind), so a binding added or
|
||||
// changed after this daemon started must take effect on the very next
|
||||
// dispatch, the same way an agent profile already does
|
||||
// (docs/prds/external-agent-harness.md, "Selection": applies without a
|
||||
// restart). A nil Secrets or Grants degrades every credential to unbound
|
||||
// rather than panicking: a daemon with no Kit profile configured wires
|
||||
// neither.
|
||||
// dispatch, the same way an agent profile already does. A nil Secrets or
|
||||
// Grants degrades every credential to unbound rather than panicking: a
|
||||
// daemon with no Kit profile configured wires neither.
|
||||
Config *config.Holder
|
||||
Secrets SecretResolver
|
||||
Grants Grants
|
||||
@@ -100,13 +97,10 @@ type Request struct {
|
||||
// a positive one, and Launch refuses it rather than starting a
|
||||
// container no gate failure could ever resume.
|
||||
GateRetries int
|
||||
// Org and GrantedServices are the dispatching identity's own facts
|
||||
// (config.Config.Org, config.Config.GrantedCredentials), carried here
|
||||
// because kitrun holds no store or config of its own. Launch resolves a
|
||||
// Kit credential only where these agree with a configured
|
||||
// CredentialBinding and the Kit's own declared service -- the
|
||||
// declared-and-granted intersection docs/prds/external-agent-harness.md
|
||||
// and orgs-and-access.md both require; neither side widens the other.
|
||||
// Org and GrantedServices are the dispatching identity's own facts. A Kit
|
||||
// credential resolves only where these agree with a configured
|
||||
// CredentialBinding and the Kit's declared service; neither side widens the
|
||||
// other.
|
||||
Org string
|
||||
GrantedServices []string
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
// Package memory implements domain/memory.MemoryEngine over concrete
|
||||
// backends. The builtin engine persists each scope's records as markdown
|
||||
// under its root -- human-readable and hand-editable -- with a per-scope
|
||||
// HISTORY.md retaining the states that are no longer live. See
|
||||
// docs/prds/memory-engine-unification.md for the decision this implements.
|
||||
// Package memory implements domain/memory.MemoryEngine over concrete backends.
|
||||
// The builtin engine persists each scope's records as markdown under its root
|
||||
// -- human-readable and hand-editable -- with a per-scope HISTORY.md retaining
|
||||
// the states that are no longer live.
|
||||
package memory
|
||||
|
||||
import (
|
||||
@@ -45,7 +44,6 @@ const defaultQueryLimit = 100
|
||||
// contentScanner is the family's content scanner, applied in Create and
|
||||
// Update. Those two are the one choke point every producer crosses, so the
|
||||
// curator's model-extracted content is covered as well as the chat tool's
|
||||
// (docs/prds/memory-engine-unification.md §7).
|
||||
var contentScanner domainmemory.Scanner = &domainmemory.DefaultScanner{}
|
||||
|
||||
// scopeStores is one scope's on-disk pair: the heads, and the states that
|
||||
@@ -403,13 +401,13 @@ func (e *BuiltinEngine) Update(_ context.Context, in domainmemory.RecordUpdate)
|
||||
}
|
||||
|
||||
// Read the document as it is on disk before anything is decided from it.
|
||||
// This engine caches the scope's document and rewrites it whole (the PRD
|
||||
// leaves "two processes, one scope file" undecided), so the copy it holds
|
||||
// can be a whole write out of date -- the Expected check below would
|
||||
// compare against a revision that is already superseded, and the rewrite
|
||||
// that follows it would write the stale copy back over the current one.
|
||||
// What this does not fix: the rewrite is still last-writer-wins for this
|
||||
// record and every other one, between the reload and the write.
|
||||
// This engine caches the scope's document and rewrites it whole, so the
|
||||
// copy it holds can be a whole write out of date -- the Expected check
|
||||
// below would compare against a revision that is already superseded, and
|
||||
// the rewrite that follows it would write the stale copy back over the
|
||||
// current one. What this does not fix: the rewrite is still
|
||||
// last-writer-wins for this record and every other one, between the reload
|
||||
// and the write.
|
||||
if err := stores.live.Reload(); err != nil {
|
||||
return domainmemory.Record{}, err
|
||||
}
|
||||
@@ -436,7 +434,6 @@ func (e *BuiltinEngine) Update(_ context.Context, in domainmemory.RecordUpdate)
|
||||
// Crash safety, in this order: the superseded state is durable in
|
||||
// HISTORY.md before the live block is touched. A crash between the two
|
||||
// leaves an extra history entry and an unchanged record -- recoverable,
|
||||
// per §2 -- and never a record whose previous state is gone.
|
||||
if err := appendHistory(stores.history, current.marker, current.content(), now, false); err != nil {
|
||||
return domainmemory.Record{}, err
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
// historyFileName is the second document in each scope's directory: every
|
||||
// state the scope's records no longer live in -- superseded by an Update, or
|
||||
// removed by a Forget -- so a record's provenance outlives its content
|
||||
// (docs/prds/memory-engine-unification.md §2).
|
||||
const historyFileName = "HISTORY.md"
|
||||
|
||||
// historySectionName is the single section every retained state is appended
|
||||
@@ -23,14 +22,10 @@ const historySectionName = "history"
|
||||
// the live document's bound (builtin's 100KB default, which is what
|
||||
// production passes: bootstrap builds the engine with a 0 maxFileBytes).
|
||||
//
|
||||
// It has its own bound because history grows on every Update and every
|
||||
// Forget while the live document does not. Inheriting the live document's
|
||||
// bound would make a scope start refusing updates after a handful of
|
||||
// revisions of one large record -- trading the PRD's open "unbounded
|
||||
// history" question ("Not determined", no compaction policy) for a new
|
||||
// failure mode at the point of write. That question stays open; this bound
|
||||
// only makes reaching it a deliberate, enormous amount of history rather
|
||||
// than an accident.
|
||||
// It has its own bound because history grows on every Update and every Forget
|
||||
// while the live document does not. That question stays open; this bound only
|
||||
// makes reaching it a deliberate, enormous amount of history rather than an
|
||||
// accident.
|
||||
const historyMaxFileBytes = 4 * 1024 * 1024
|
||||
|
||||
// appendHistory appends one retained state -- the record as it was while
|
||||
@@ -54,7 +49,7 @@ func appendHistory(h *builtin.Store, m markerData, content string, at time.Time,
|
||||
// oldest first. Document order is append order, and a retained state is
|
||||
// appended exactly when it stops being live, so no sort is needed -- or
|
||||
// wanted: a crash between a history append and the live write leaves two
|
||||
// entries for one revision (§2, recoverable), and sorting would not make
|
||||
// entries for one revision, and sorting would not make
|
||||
// that less true.
|
||||
func revisionsOf(h *builtin.Store, scope domainmemory.Scope, id domainmemory.RecordID) []domainmemory.Revision {
|
||||
var revisions []domainmemory.Revision
|
||||
|
||||
@@ -8,14 +8,9 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// The engine writes each record as one blank-line-delimited markdown block
|
||||
// whose first line is a marker comment followed by the record's content, so
|
||||
// a block stays readable and editable by hand. The marker began life as a
|
||||
// bare id (`<!--mem:<ulid>-->`, the incumbent format); it is JSON now
|
||||
// because the retained provenance -- revision, kind, author, originating
|
||||
// user, source and both timestamps -- has nowhere else to live, which is
|
||||
// exactly what the PRD's Settles table records the bare form could not
|
||||
// carry.
|
||||
// Each record is one blank-line-delimited markdown block whose first line is a
|
||||
// JSON marker comment carrying the record's provenance, followed by its
|
||||
// content, so a block stays editable by hand.
|
||||
const (
|
||||
markerPrefix = "<!--mem:"
|
||||
markerSuffix = "-->"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Access policies and denial records: the Postgres implementation of
|
||||
// internal/domain/access's PolicyStore, Resetter and DenialStore
|
||||
// (docs/prds/orgs-and-access.md). Policy changes are versioned per level
|
||||
// internal/domain/access's PolicyStore, Resetter and DenialStore.
|
||||
// Policy changes are versioned per level
|
||||
// scope and audited as one sys_audit row per change naming who made it.
|
||||
package postgres
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
// Orgs, workspaces, memberships and agent assignments: the Postgres
|
||||
// implementation of internal/domain/org's contracts, plus the resumable
|
||||
// default org/workspace upgrade the State Store runs at boot
|
||||
// (docs/prds/orgs-and-access.md, "Upgrading existing installs").
|
||||
//
|
||||
// The upgrade refuses nothing itself; the refusal to serve scoped calls
|
||||
// until it has finished is enforced by the boot order -- the State Store
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
// Package pgtest runs a throwaway PostgreSQL 18 container for one test binary
|
||||
// and gives each test its own database on it.
|
||||
//
|
||||
// A package using it calls Main from TestMain:
|
||||
//
|
||||
// func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
//
|
||||
// It needs a running Docker daemon.
|
||||
|
||||
@@ -19,9 +19,6 @@ type CountShippedOrgPoliciesParams struct {
|
||||
Column2 []string
|
||||
}
|
||||
|
||||
// How many of an org's shipped role policies are stored. The seeding runs
|
||||
// only when the org carries none of them, so a restart never overwrites an
|
||||
// edited role policy (the shipped IDs are reserved for the shipped text).
|
||||
func (q *Queries) CountShippedOrgPolicies(ctx context.Context, arg CountShippedOrgPoliciesParams) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, countShippedOrgPolicies, arg.OrgID, arg.Column2)
|
||||
var count int64
|
||||
@@ -72,7 +69,6 @@ type DeleteAccessPolicyVersionParams struct {
|
||||
WorkspaceID string
|
||||
}
|
||||
|
||||
// Tidy a level-scope with no policies left: its version row has no reader.
|
||||
func (q *Queries) DeleteAccessPolicyVersion(ctx context.Context, arg DeleteAccessPolicyVersionParams) error {
|
||||
_, err := q.db.Exec(ctx, deleteAccessPolicyVersion, arg.Level, arg.OrgID, arg.WorkspaceID)
|
||||
return err
|
||||
@@ -88,8 +84,6 @@ type DeleteOrgPoliciesNotShippedParams struct {
|
||||
Column2 []string
|
||||
}
|
||||
|
||||
// The org reset's removal half: every org-level policy except the shipped
|
||||
// role set.
|
||||
func (q *Queries) DeleteOrgPoliciesNotShipped(ctx context.Context, arg DeleteOrgPoliciesNotShippedParams) error {
|
||||
_, err := q.db.Exec(ctx, deleteOrgPoliciesNotShipped, arg.OrgID, arg.Column2)
|
||||
return err
|
||||
@@ -139,8 +133,6 @@ type InsertAccessPolicyAuditParams struct {
|
||||
RequestID string
|
||||
}
|
||||
|
||||
// One audit row per policy change: the policy's old and new text
|
||||
// (docs/prds/orgs-and-access.md, "Storing and changing policies").
|
||||
func (q *Queries) InsertAccessPolicyAudit(ctx context.Context, arg InsertAccessPolicyAuditParams) error {
|
||||
_, err := q.db.Exec(ctx, insertAccessPolicyAudit,
|
||||
arg.RecordKey,
|
||||
@@ -159,9 +151,6 @@ INSERT INTO sys_audit (at, table_name, record_key, field, record_version, actor,
|
||||
VALUES (now(), 'access_policies', $1, 'reset', 1, 'archied access reset', 'archied', '')
|
||||
`
|
||||
|
||||
// The one audit row a reset is recorded as; the reset's policy changes
|
||||
// carry their own rows (docs/prds/orgs-and-access.md, "Recovering from a
|
||||
// locked-out org").
|
||||
func (q *Queries) InsertAccessResetAudit(ctx context.Context, recordKey string) error {
|
||||
_, err := q.db.Exec(ctx, insertAccessResetAudit, recordKey)
|
||||
return err
|
||||
@@ -173,9 +162,7 @@ SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text, upd
|
||||
FROM access_policies ORDER BY level, org_id, workspace_id, object_kind, object_id, policy_id
|
||||
`
|
||||
|
||||
// Access policies and denial records (internal/domain/access): the durable
|
||||
// half of the policy-chain contract. Versioning is per level-scope; every
|
||||
// policy change writes one sys_audit row naming who made it.
|
||||
// Access policies and denial records (internal/domain/access)
|
||||
func (q *Queries) ListAccessPolicies(ctx context.Context) ([]AccessPolicy, error) {
|
||||
rows, err := q.db.Query(ctx, listAccessPolicies)
|
||||
if err != nil {
|
||||
@@ -266,8 +253,6 @@ type RecordDenialParams struct {
|
||||
}
|
||||
|
||||
// One row per (principal, action, resource, level, policies, minute);
|
||||
// a repeat inside the minute bumps the count (docs/prds/orgs-and-access.md,
|
||||
// "Audit retention").
|
||||
func (q *Queries) RecordDenial(ctx context.Context, arg RecordDenialParams) error {
|
||||
_, err := q.db.Exec(ctx, recordDenial,
|
||||
arg.OrgID,
|
||||
|
||||
@@ -81,8 +81,6 @@ type InsertResourceAuditParams struct {
|
||||
Value []byte
|
||||
}
|
||||
|
||||
// Records the fields one resource write changed, against the version it
|
||||
// replaced. Runs in the write's own transaction.
|
||||
func (q *Queries) InsertResourceAudit(ctx context.Context, arg InsertResourceAuditParams) error {
|
||||
_, err := q.db.Exec(ctx, insertResourceAudit,
|
||||
arg.At,
|
||||
|
||||
@@ -54,15 +54,7 @@ type EnqueueCallTaskParams struct {
|
||||
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).
|
||||
// The callee of a workflow.call step (docs/prds/workflow-calls.md)
|
||||
func (q *Queries) EnqueueCallTask(ctx context.Context, arg EnqueueCallTaskParams) (Task, error) {
|
||||
row := q.db.QueryRow(ctx, enqueueCallTask,
|
||||
arg.ID,
|
||||
|
||||
@@ -757,9 +757,6 @@ type ListUndispatchedCapturesParams struct {
|
||||
EntryLimit int32
|
||||
}
|
||||
|
||||
// A capture is undispatched while some armed binding on its source, whose
|
||||
// mapping belongs to the capture's event type, has not dispatched it. An
|
||||
// unidentified capture has no event type, so it is never listed.
|
||||
func (q *Queries) ListUndispatchedCaptures(ctx context.Context, arg ListUndispatchedCapturesParams) ([]Capture, error) {
|
||||
rows, err := q.db.Query(ctx, listUndispatchedCaptures, arg.Sources, arg.EntryLimit)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
-- Access policies and denial records (internal/domain/access): the durable
|
||||
-- half of the policy-chain contract. Versioning is per level-scope; every
|
||||
-- policy change writes one sys_audit row naming who made it.
|
||||
-- Access policies and denial records (internal/domain/access)
|
||||
|
||||
-- name: ListAccessPolicies :many
|
||||
SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text, updated_at
|
||||
@@ -23,15 +21,10 @@ WHERE level = $1 AND org_id = $2 AND workspace_id = $3 AND object_kind = $4
|
||||
AND object_id = $5 AND policy_id = $6;
|
||||
|
||||
-- name: CountShippedOrgPolicies :one
|
||||
-- How many of an org's shipped role policies are stored. The seeding runs
|
||||
-- only when the org carries none of them, so a restart never overwrites an
|
||||
-- edited role policy (the shipped IDs are reserved for the shipped text).
|
||||
SELECT count(*) FROM access_policies
|
||||
WHERE level = 'org' AND org_id = $1 AND policy_id = ANY($2::text[]);
|
||||
|
||||
-- name: DeleteOrgPoliciesNotShipped :exec
|
||||
-- The org reset's removal half: every org-level policy except the shipped
|
||||
-- role set.
|
||||
DELETE FROM access_policies
|
||||
WHERE level = 'org' AND org_id = $1 AND NOT (policy_id = ANY($2::text[]));
|
||||
|
||||
@@ -45,22 +38,17 @@ DO UPDATE SET version = access_policy_versions.version + 1, updated_at = now()
|
||||
RETURNING version;
|
||||
|
||||
-- name: DeleteAccessPolicyVersion :exec
|
||||
-- Tidy a level-scope with no policies left: its version row has no reader.
|
||||
DELETE FROM access_policy_versions v
|
||||
WHERE v.level = $1 AND v.org_id = $2 AND v.workspace_id = $3
|
||||
AND NOT EXISTS (SELECT 1 FROM access_policies p
|
||||
WHERE p.level = v.level AND p.org_id = v.org_id AND p.workspace_id = v.workspace_id);
|
||||
|
||||
-- name: InsertAccessPolicyAudit :exec
|
||||
-- One audit row per policy change: the policy's old and new text
|
||||
-- (docs/prds/orgs-and-access.md, "Storing and changing policies").
|
||||
INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id)
|
||||
VALUES (now(), 'access_policies', $1, 'text', $2, $3, $4, $5, $6, $7);
|
||||
|
||||
-- name: RecordDenial :exec
|
||||
-- One row per (principal, action, resource, level, policies, minute);
|
||||
-- a repeat inside the minute bumps the count (docs/prds/orgs-and-access.md,
|
||||
-- "Audit retention").
|
||||
INSERT INTO access_denials (org_id, principal, action, resource_kind, resource_id, level, policies)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
ON CONFLICT (org_id, principal, action, resource_kind, resource_id, level, policies, minute_at)
|
||||
@@ -69,9 +57,7 @@ DO UPDATE SET count = access_denials.count + 1, updated_at = now();
|
||||
-- name: ListDenials :many
|
||||
SELECT id, org_id, principal, action, resource_kind, resource_id, level, policies, minute_at, count, created_at, updated_at
|
||||
FROM access_denials WHERE org_id = $1 ORDER BY id DESC LIMIT $2;
|
||||
|
||||
-- name: InsertAccessResetAudit :exec
|
||||
-- The one audit row a reset is recorded as; the reset's policy changes
|
||||
-- carry their own rows (docs/prds/orgs-and-access.md, "Recovering from a
|
||||
-- locked-out org").
|
||||
INSERT INTO sys_audit (at, table_name, record_key, field, record_version, actor, source, request_id)
|
||||
VALUES (now(), 'access_policies', $1, 'reset', 1, 'archied access reset', 'archied', '');
|
||||
@@ -1,6 +1,4 @@
|
||||
-- name: InsertResourceAudit :exec
|
||||
-- Records the fields one resource write changed, against the version it
|
||||
-- replaced. Runs in the write's own transaction.
|
||||
INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id)
|
||||
SELECT sqlc.arg(at)::timestamptz, 'resources', sqlc.arg(record_key)::text, d.field, d.old_value, d.new_value,
|
||||
sqlc.arg(version)::bigint, sqlc.arg(actor)::text, sqlc.arg(source)::text, sqlc.arg(request_id)::text
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
-- 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).
|
||||
-- The callee of a workflow.call step (docs/prds/workflow-calls.md)
|
||||
WITH caller AS (
|
||||
SELECT t.* FROM tasks t WHERE t.id = $1 FOR UPDATE
|
||||
)
|
||||
|
||||
@@ -11,9 +11,6 @@ ORDER BY received_at DESC
|
||||
LIMIT $1;
|
||||
|
||||
-- name: ListUndispatchedCaptures :many
|
||||
-- A capture is undispatched while some armed binding on its source, whose
|
||||
-- mapping belongs to the capture's event type, has not dispatched it. An
|
||||
-- unidentified capture has no event type, so it is never listed.
|
||||
SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.unsigned, c.event_type, c.org_id, c.workspace_id
|
||||
FROM captures c
|
||||
WHERE c.source = ANY(@sources::text[])
|
||||
|
||||
@@ -16,13 +16,9 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// The step-execution writes of docs/prds/execution-tree-state-machine.md.
|
||||
// Each is one transaction: the guarded row write, and the domain event row
|
||||
// the step transition produces, so the events table records exactly the
|
||||
// transitions the step row does. The events land in the table; the caller
|
||||
// publishes the returned event to its bus after the write commits, and the
|
||||
// daemon's event sink skips already-persisted rows by their assigned ID --
|
||||
// the EmitDurable convention.
|
||||
// The events land in the table; the caller publishes the returned event to its
|
||||
// bus after the write commits, and the daemon's event sink skips
|
||||
// already-persisted rows by their assigned ID -- the EmitDurable convention.
|
||||
|
||||
// StartStep records a StepExecution entering running: the row is created
|
||||
// pending, guarded into running under the shared step transition table, and
|
||||
@@ -251,7 +247,7 @@ func stepEventData(to taskstate.StepStatus, durationMS int64, detail string) map
|
||||
|
||||
// ListSteps reads one execution's recorded steps, every attempt oldest first
|
||||
// when attempt is 0, or just the one it names. It is the dashboard run
|
||||
// detail's authoritative source (docs/prds/execution-tree-state-machine.md),
|
||||
// detail's authoritative source,
|
||||
// replacing the fold over stage_start/stage_finish events tasks.stage used to
|
||||
// back -- unlike StartStep/FinishStep, this is a plain read with no
|
||||
// transition to guard, so it takes no transaction.
|
||||
@@ -291,14 +287,14 @@ func stepParentID(parentID int64) pgtype.Int8 {
|
||||
return pgtype.Int8{Int64: parentID, Valid: parentID != 0}
|
||||
}
|
||||
|
||||
// CancelExecution is the one cancel path (docs/prds/execution-tree-state-machine.md,
|
||||
// "Cancellation"): one transaction moves every non-terminal StepExecution of
|
||||
// the execution's current attempt to cancelled -- one event row each -- and
|
||||
// the execution itself to the status the operator action names, under the
|
||||
// shared execution transition table. Staleness is decided before legality, as
|
||||
// guardTransition decides it, and the audit row lands in the same write. The
|
||||
// caller cancels the in-memory context after this commits; the worker's next
|
||||
// step write then fails ErrStaleTransition and stops.
|
||||
// CancelExecution is the one cancel path: one transaction moves every
|
||||
// non-terminal StepExecution of the execution's current attempt to cancelled --
|
||||
// one event row each -- and the execution itself to the status the operator
|
||||
// action names, under the shared execution transition table. Staleness is
|
||||
// decided before legality, as guardTransition decides it, and the audit row
|
||||
// lands in the same write. The caller cancels the in-memory context after this
|
||||
// commits; the worker's next step write then fails ErrStaleTransition and
|
||||
// stops.
|
||||
func (s *Store) CancelExecution(ctx context.Context, taskID int64, reason, to string) ([]int64, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
|
||||
@@ -40,8 +40,8 @@ func (s *Store) queries() *postgresdb.Queries {
|
||||
// guardTransition locks the task's row and checks the status write the caller
|
||||
// is about to perform: a row whose status is not the expected from is stale
|
||||
// (ErrStaleTransition), a from->to pair outside the shared transition table is
|
||||
// refused with ErrIllegalTransition
|
||||
// (docs/prds/execution-tree-state-machine.md). Staleness is decided first, so
|
||||
// refused with ErrIllegalTransition.
|
||||
// Staleness is decided first, so
|
||||
// a caller that is wrong about the row's state gets the stale sentinel even
|
||||
// when its pair is also unroutable. The row stays locked for the caller's
|
||||
// transaction, so the checks cannot race the guarded write that follows.
|
||||
@@ -78,7 +78,7 @@ const syntheticIssueNumberBase = 1_000_000_000_000_000
|
||||
// structured payload (review_payload today, task outputs now). A value that
|
||||
// would exceed it is refused for outputs -- clipped JSON does not parse, and a
|
||||
// caller must receive an object or nothing -- where the legacy review payload
|
||||
// is still clipped (docs/prds/workflow-call-outputs.md, "Storage and wire").
|
||||
// is still clipped.
|
||||
const structuredPayloadBytes = 4000
|
||||
|
||||
// taskFromRow maps the generated task row to the workflow.Task the daemon and
|
||||
@@ -295,7 +295,7 @@ func (s *Store) ParkTask(ctx context.Context, taskID int64, from, detail, class
|
||||
|
||||
// Update persists mutable task fields written by workflows.
|
||||
func (s *Store) Update(ctx context.Context, t *workflow.Task) error {
|
||||
// The row write is where a run's outputs land (docs/prds/workflow-call-outputs.md).
|
||||
// The row write is where a run's outputs land.
|
||||
// An encoded set past the bound the store applies to a structured payload
|
||||
// is refused rather than clipped: clipped JSON does not parse, and a caller
|
||||
// would receive a broken object as a value. The engine turns the refusal
|
||||
@@ -414,8 +414,8 @@ func (s *Store) RetryTask(ctx context.Context, taskID int64, fromStatus, wf, ret
|
||||
})
|
||||
}
|
||||
|
||||
// RespondReviewGate is the review gate response write
|
||||
// (docs/prds/pr-review-operator-response.md, Decision 2): one guarded
|
||||
// RespondReviewGate is the review gate response write:
|
||||
// one guarded
|
||||
// requeue that records the operator's answer, increments rereview_rounds for
|
||||
// a re-review only, and writes one audit row -- all in one transaction. The
|
||||
// cap is checked under the row lock the transition guard takes, so two
|
||||
@@ -522,13 +522,9 @@ func (s *Store) ArchiveTask(ctx context.Context, taskID int64, fromStatus string
|
||||
|
||||
// RecoverStale re-queues tasks left running by a crashed or replaced daemon
|
||||
// and, in the same transaction, moves the steps those executions left running
|
||||
// to the step transition table's interrupted outcome
|
||||
// (docs/prds/execution-tree-state-machine.md, "Crash recovery"): one event row
|
||||
// per step transition and the execution's audit row land in the same write.
|
||||
// Both edges are pinned in SQL (the execution's running->queued, the step's
|
||||
// running->interrupted) and pinned to the tables by
|
||||
// TestSQLPinnedTransitionsAreTableLegal. The next attempt starts with fresh
|
||||
// steps; earlier attempts are never rewritten.
|
||||
// to the step transition table's interrupted outcome: one event row per step
|
||||
// transition and the execution's audit row land in the same write. The next
|
||||
// attempt starts with fresh steps; earlier attempts are never rewritten.
|
||||
func (s *Store) RecoverStale(ctx context.Context) (int64, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
@@ -675,8 +671,8 @@ 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
|
||||
// StartCall enqueues the callee of callerTaskID's workflow.call step.
|
||||
// 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
|
||||
@@ -741,8 +737,8 @@ func (s *Store) CallStatus(ctx context.Context, callerTaskID, callTaskID int64)
|
||||
if callee.CallParentTaskID != callerTaskID {
|
||||
return "", "", nil, storecontract.ErrCallNotYours
|
||||
}
|
||||
// The row is the callee's own; its outputs travel beside status and detail
|
||||
// (docs/prds/workflow-call-outputs.md, "Storage and wire"). The caller
|
||||
// The row is the callee's own; its outputs travel beside status and detail.
|
||||
// The caller
|
||||
// decides whether to use them -- only a successful terminal state's values
|
||||
// reach it.
|
||||
outputs, _ := task.DecodeOutputs(callee.Outputs)
|
||||
|
||||
@@ -12,14 +12,13 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// extractTarGz extracts a gzipped tar stream into destDir, stripping a
|
||||
// single common leading path component when every entry shares one (the
|
||||
// wrapper directory GitHub's and Gitea's repository archives both add,
|
||||
// named after the repo and ref -- e.g. "acme-widget-deadbeef/"). A .git
|
||||
// entry is never written: PRSource's isolation contract (docs/prds/
|
||||
// pr-review-agent.md) requires the pipeline to read a .git-free snapshot,
|
||||
// and a malicious PR's own tarball is exactly the input this cannot trust,
|
||||
// so an entry escaping destDir via ".." or an absolute path is refused
|
||||
// extractTarGz extracts a gzipped tar stream into destDir, stripping a single
|
||||
// common leading path component when every entry shares one (the wrapper
|
||||
// directory GitHub's and Gitea's repository archives both add, named after the
|
||||
// repo and ref -- e.g. "acme-widget-deadbeef/"). A.git entry is never written:
|
||||
// PRSource's isolation contract requires the pipeline to read a.git-free
|
||||
// snapshot, and a malicious PR's own tarball is exactly the input this cannot
|
||||
// trust, so an entry escaping destDir via ".." or an absolute path is refused
|
||||
// rather than silently written outside it.
|
||||
func extractTarGz(r io.Reader, destDir string) error {
|
||||
gz, err := gzip.NewReader(r)
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
// Package prsource implements workflow.PRSource: fetching an arbitrary
|
||||
// external pull request's metadata, diff and a read-only snapshot of its
|
||||
// head, for the pr-review pipeline (docs/prds/pr-review-agent.md). It is
|
||||
// head, for the pr-review pipeline. It is
|
||||
// the PR-under-review counterpart to worktree.Manager's use as the task's
|
||||
// own Trees: that path only ever reaches the task's own worktree, never a
|
||||
// third-party PR being reviewed.
|
||||
//
|
||||
// Every call goes over the forge's HTTP API -- never a git-shell checkout.
|
||||
// The pipeline's Stage.Run bodies execute inside the sandboxed archie-agent
|
||||
// process, which holds no forge credential and no git-level credential
|
||||
// either; a git clone would need one. An HTTP call carries only whatever
|
||||
// bearer token the forge client was constructed with, matching the PRD's
|
||||
// Isolation rule ("no pipeline agent holds a forge credential") for the
|
||||
// pipeline's own agent calls, while this package's construction site is the
|
||||
// one place a forge-reading token is actually held.
|
||||
// Every call goes over the forge's HTTP API -- never a git-shell checkout. The
|
||||
// pipeline's Stage.Run bodies execute inside the sandboxed archie-agent
|
||||
// process, which holds no forge credential and no git-level credential either;
|
||||
// a git clone would need one.
|
||||
package prsource
|
||||
|
||||
import (
|
||||
@@ -59,10 +55,10 @@ func New(forge Forge) *Source {
|
||||
return &Source{forge: forge}
|
||||
}
|
||||
|
||||
// Metadata returns the pull request's title and body. Commit messages are
|
||||
// left empty: no existing Forge capability returns them, and they are only
|
||||
// ever one of three inputs to the hallucination-check heuristic (docs/prds/
|
||||
// pr-review-agent.md, phase 1), not load-bearing on their own.
|
||||
// Metadata returns the pull request's title and body. Commit messages are left
|
||||
// empty: no existing Forge capability returns them, and they are only ever one
|
||||
// of three inputs to the hallucination-check heuristic, not load-bearing on
|
||||
// their own.
|
||||
func (s *Source) Metadata(ctx context.Context, owner, repo string, number int) (workflow.PRMetadata, error) {
|
||||
pr, err := s.forge.GetPullRequest(ctx, owner, repo, number)
|
||||
if err != nil {
|
||||
|
||||
@@ -62,9 +62,8 @@ func (p *StoreProbe) Check(ctx context.Context) health.Result {
|
||||
// ContractProbe reports whether a service this process consumes over the wire
|
||||
// answers a cheap call within a bounded timeout. It is the readiness signal
|
||||
// available to a process that depends on a service it does not own: the probe
|
||||
// consumes the dependency's own result and never inspects its manager,
|
||||
// registry or database (docs/prds/ui-service-boundary.md, "Listen,
|
||||
// authentication, and readiness").
|
||||
// consumes the dependency's own result and never inspects its manager, registry
|
||||
// or database.
|
||||
type ContractProbe struct {
|
||||
ProbeName string
|
||||
Timeout time.Duration
|
||||
@@ -99,7 +98,7 @@ func (p *ContractProbe) Check(ctx context.Context) health.Result {
|
||||
// PolicyProblems reports the stored access policies this process's engine
|
||||
// could not validate. The policy chain is the source; a policy that failed
|
||||
// startup re-validation denies its level and must be named here with its
|
||||
// error (docs/prds/orgs-and-access.md, "Storing and changing policies").
|
||||
// error.
|
||||
type PolicyProblems interface {
|
||||
Problems() []access.Problem
|
||||
}
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
// Package nats is the NATS JetStream KV transport for service discovery.
|
||||
//
|
||||
// It implements the broker-neutral
|
||||
// [servicediscovery.ServiceRegistry] contract against a JetStream KeyValue
|
||||
// store, and additionally provides the registration side a service uses to
|
||||
// announce itself. It is the fallback discovery mechanism for single-host,
|
||||
// no-Kubernetes installs (Path B of
|
||||
// docs/inspiration/service-discovery-research-2026-09-05.md); the
|
||||
// It implements the broker-neutral [servicediscovery.ServiceRegistry] contract
|
||||
// against a JetStream KeyValue store, and additionally provides the
|
||||
// registration side a service uses to announce itself. It is the fallback
|
||||
// discovery mechanism for single-host, no-Kubernetes installs; the
|
||||
// Kubernetes-native primary is a sibling implementation of the same contract.
|
||||
//
|
||||
// # Two buckets: presence versus liveness
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
// Package sessioncurator implements domain/curator.CuratorEngine for
|
||||
// session memory extraction. See docs/prds/session-memory-curator.md for
|
||||
// what a pass does and why, and the scope this package deliberately does
|
||||
// not cover.
|
||||
// Package sessioncurator implements domain/curator.CuratorEngine for session
|
||||
// memory extraction.
|
||||
package sessioncurator
|
||||
|
||||
import (
|
||||
@@ -15,9 +13,9 @@ import (
|
||||
)
|
||||
|
||||
// Adapter implements curator.ConversationSource over a real
|
||||
// gateway.SessionStore, narrowed to the two read-only operations a
|
||||
// curator needs -- never the full session CRUD/branch/search surface a
|
||||
// chat gateway exposes. See docs/prds/session-memory-curator.md.
|
||||
// gateway.SessionStore, narrowed to the two read-only operations a curator
|
||||
// needs -- never the full session CRUD/branch/search surface a chat gateway
|
||||
// exposes.
|
||||
type Adapter struct {
|
||||
store gateway.SessionStore
|
||||
agentID string
|
||||
@@ -38,7 +36,7 @@ func NewAdapter(store gateway.SessionStore, agentID string) *Adapter {
|
||||
// RecentSessions returns sessions active at or after since, newest first.
|
||||
// AgentID is the agent every session's memory is addressed by -- the
|
||||
// composition's configured bot user, the same value a chat turn addresses
|
||||
// its own reads with (see docs/architecture/identity.md).
|
||||
// its own reads with.
|
||||
func (a *Adapter) RecentSessions(ctx context.Context, since time.Time) ([]curator.SessionSummary, error) {
|
||||
sessions, err := a.store.List(ctx)
|
||||
if err != nil {
|
||||
|
||||
@@ -33,9 +33,9 @@ const ActionSkipped = "memory.skipped"
|
||||
const DefaultInterval = time.Hour
|
||||
|
||||
const (
|
||||
// messageTailSize bounds how much of a session's history one pass
|
||||
// reads, deliberately generous against the model's context rather
|
||||
// than tuned tightly. See docs/prds/session-memory-curator.md.
|
||||
// messageTailSize bounds how much of a session's history one pass reads,
|
||||
// deliberately generous against the model's context rather than tuned
|
||||
// tightly.
|
||||
messageTailSize = 40
|
||||
// maxObservationsPerSession caps how many facts one pass writes for
|
||||
// one session -- a prompt-precision problem to fix, not a limit to
|
||||
@@ -46,10 +46,7 @@ const (
|
||||
defaultLookback = 24 * time.Hour
|
||||
)
|
||||
|
||||
// Curator implements domain/curator.CuratorEngine. See
|
||||
// docs/prds/session-memory-curator.md for what a pass does and why:
|
||||
// session-scoped extraction only, written through the bound memory
|
||||
// engine, no cross-session consolidation, no forgetting.
|
||||
// Curator implements domain/curator.CuratorEngine.
|
||||
type Curator struct {
|
||||
interval time.Duration
|
||||
engineName string
|
||||
@@ -94,10 +91,9 @@ func (c *Curator) Check(ctx context.Context) (bool, error) {
|
||||
return len(sessions) > 0, nil
|
||||
}
|
||||
|
||||
// Pass extracts durable observations from every session active since the
|
||||
// last pass (or defaultLookback on the first pass) and writes them
|
||||
// through the bound memory engine. See docs/prds/session-memory-curator.md
|
||||
// for the exact extraction and classification rules.
|
||||
// Pass extracts durable observations from every session active since the last
|
||||
// pass (or defaultLookback on the first pass) and writes them through the bound
|
||||
// memory engine.
|
||||
func (c *Curator) Pass(ctx context.Context, in curator.PassInput) (curator.PassResult, error) {
|
||||
engine, ok := c.host.MemoryEngines.Get(c.engineName)
|
||||
if !ok {
|
||||
|
||||
@@ -30,10 +30,7 @@ const (
|
||||
ActionNormalized = "skill.normalized"
|
||||
)
|
||||
|
||||
// Curator implements domain/curator.CuratorEngine. See
|
||||
// docs/prds/skill-curator.md for what a pass does and why: mechanical
|
||||
// validation and safe whitespace normalization only -- no LLM-authored
|
||||
// rewrites, no deletion.
|
||||
// Curator implements domain/curator.CuratorEngine.
|
||||
type Curator struct {
|
||||
interval time.Duration
|
||||
host curator.Registrar
|
||||
@@ -71,11 +68,9 @@ func (c *Curator) Check(ctx context.Context) (bool, error) {
|
||||
return len(refs) > 0, nil
|
||||
}
|
||||
|
||||
// Pass reviews every skill currently on disk. There is no per-skill
|
||||
// "already reviewed" state: each pass re-checks everything, which is
|
||||
// cheap (file reads, no model calls) and errs toward catching a
|
||||
// regression over missing one. See docs/prds/skill-curator.md for the
|
||||
// exact classification rules.
|
||||
// Pass reviews every skill currently on disk. There is no per-skill "already
|
||||
// reviewed" state: each pass re-checks everything, which is cheap (file reads,
|
||||
// no model calls) and errs toward catching a regression over missing one.
|
||||
func (c *Curator) Pass(ctx context.Context, in curator.PassInput) (curator.PassResult, error) {
|
||||
refs, err := c.host.Skills.List(ctx)
|
||||
if err != nil {
|
||||
@@ -107,11 +102,10 @@ func (c *Curator) reviewOne(ctx context.Context, name string) ([]curator.Action,
|
||||
|
||||
fm, _, fail := skill.Parse([]byte(sk.Content))
|
||||
if fail != nil {
|
||||
// A parse failure is a per-skill finding to report, not an
|
||||
// execution error to propagate: Pass()'s loop aborts the whole
|
||||
// batch on a non-nil error, which would stop reviewing every
|
||||
// other skill over one bad file (see skillcurator_test.go's
|
||||
// "must not abort review of the others").
|
||||
// A parse failure is a per-skill finding to report, not an execution
|
||||
// error to propagate: Pass()'s loop aborts the whole batch on a non-nil
|
||||
// error, which would stop reviewing every other skill over one bad
|
||||
// file.
|
||||
return invalidFinding(name, fail)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
// Package skillcurator implements domain/curator.CuratorEngine for skill
|
||||
// maintenance. See docs/prds/skill-curator.md for what a pass does and
|
||||
// why, and the scope this package deliberately does not cover.
|
||||
// maintenance.
|
||||
package skillcurator
|
||||
|
||||
import (
|
||||
@@ -14,7 +13,7 @@ import (
|
||||
)
|
||||
|
||||
// skillsDir mirrors internal/skill's own unexported constant of the same
|
||||
// name and value -- the discovery convention (.agents/skills/) is fixed
|
||||
// name and value -- the discovery convention is fixed
|
||||
// across both packages, not configurable per caller.
|
||||
const skillsDir = ".agents/skills"
|
||||
|
||||
@@ -22,16 +21,16 @@ const skillsDir = ".agents/skills"
|
||||
// its own directory under skillsDir.
|
||||
const skillFile = "SKILL.md"
|
||||
|
||||
// Store implements curator.SkillStore over one root directory's
|
||||
// .agents/skills/*/SKILL.md files. List and Read never parse frontmatter
|
||||
// themselves beyond a best-effort Description: a per-skill parse failure is
|
||||
// the curator's problem to report as an Action, not this store's problem to
|
||||
// abort on. See docs/prds/skill-curator.md.
|
||||
// Store implements curator.SkillStore over one root directory's.
|
||||
// agents/skills/*/SKILL.md files. List and Read never parse frontmatter
|
||||
// themselves beyond a best-effort Description: a per-skill parse failure is the
|
||||
// curator's problem to report as an Action, not this store's problem to abort
|
||||
// on.
|
||||
type Store struct {
|
||||
root string
|
||||
}
|
||||
|
||||
// NewStore builds a Store rooted at root (root/.agents/skills/...).
|
||||
// NewStore builds a Store rooted at root.
|
||||
func NewStore(root string) *Store {
|
||||
return &Store{root: root}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Access: the policy-chain and denial-record RPCs (docs/prds/orgs-and-access.md).
|
||||
// Access: the policy-chain and denial-record RPCs.
|
||||
// The policies surface is the engine's snapshot plus the administrative
|
||||
// writes; the denials surface is the two callers' write path and the
|
||||
// operator's read.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Access: the client half of the policy-chain and denial-record RPCs
|
||||
// (docs/prds/orgs-and-access.md). The reset surface is deliberately absent:
|
||||
// Access: the client half of the policy-chain and denial-record RPCs.
|
||||
// The reset surface is deliberately absent:
|
||||
// `archied access reset` runs on the State Store host, never over the wire.
|
||||
package staterpc
|
||||
|
||||
|
||||
@@ -8,13 +8,12 @@ import (
|
||||
)
|
||||
|
||||
// tokenMetadataKey is the gRPC metadata key the bearer token travels in.
|
||||
// Metadata, never a URL, per docs/prds/state-store-contract.md §9's token
|
||||
// lifecycle note.
|
||||
// Metadata, never a URL.
|
||||
const tokenMetadataKey = "state-store-token"
|
||||
|
||||
// UnaryClientTokenInterceptor attaches token to every outgoing call's
|
||||
// metadata under tokenMetadataKey. One token covers a task's container
|
||||
// lifetime (§9's per-incumbence lifecycle) so it does not need to be
|
||||
// lifetime so it does not need to be
|
||||
// refreshed mid-connection. Used by the agent's long-lived client
|
||||
// connection to the State Store's bridge-address listener.
|
||||
func UnaryClientTokenInterceptor(token string) grpc.UnaryClientInterceptor {
|
||||
|
||||
@@ -25,14 +25,14 @@ import (
|
||||
// Client is the single remote adapter wrapping one StateStoreServiceClient,
|
||||
// asserted against whichever narrow Go interfaces its caller needs -- exactly
|
||||
// as gatewayrpc.Client asserts both messaging.ChatContract and
|
||||
// messaging.SessionStore. See docs/prds/state-store-contract.md §2.
|
||||
// messaging.SessionStore.
|
||||
type Client struct {
|
||||
client pb.StateStoreServiceClient
|
||||
controlPlane controlpb.ControlPlaneServiceClient
|
||||
}
|
||||
|
||||
// NewClient wraps conn's generated client. Close is a no-op: the store
|
||||
// service owns its own DB lifecycle (§11).
|
||||
// service owns its own DB lifecycle.
|
||||
func NewClient(conn grpc.ClientConnInterface) *Client {
|
||||
return &Client{client: pb.NewStateStoreServiceClient(conn), controlPlane: controlpb.NewControlPlaneServiceClient(conn)}
|
||||
}
|
||||
@@ -115,7 +115,7 @@ func (c *Client) Transition(ctx context.Context, taskID int64, from, to, detail
|
||||
}
|
||||
|
||||
// StartStep and FinishStep record the run's step executions
|
||||
// (docs/prds/execution-tree-state-machine.md) under the run credential, which
|
||||
// under the run credential, which
|
||||
// the State Store's grant interceptor scopes to the execution the requests
|
||||
// name. Each returns the transition's persisted event for the caller's
|
||||
// post-commit publish.
|
||||
@@ -135,7 +135,7 @@ func (c *Client) StartStep(ctx context.Context, s task.StepStart) (int64, events
|
||||
return r.StepId, event, nil
|
||||
}
|
||||
|
||||
// CancelExecution is the one cancel path (docs/prds/execution-tree-state-machine.md):
|
||||
// CancelExecution is the one cancel path:
|
||||
// the State Store records the cancellation -- every non-terminal step of the
|
||||
// current attempt plus the execution's own move -- and returns the steps it
|
||||
// cancelled; the caller cancels the run's in-memory context afterwards.
|
||||
@@ -641,11 +641,10 @@ 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.
|
||||
// WorkflowCaller: the workflow.call step's two RPCs. 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)
|
||||
|
||||
@@ -12,11 +12,11 @@ import (
|
||||
)
|
||||
|
||||
// Dial returns a State Store contract client for target, applying the
|
||||
// transport security boundary (docs/prds/state-store-contract.md §9): a
|
||||
// transport security boundary: a
|
||||
// loopback target dials insecure with no credential, while a non-loopback
|
||||
// target requires a bearer token and fails closed without one. The returned
|
||||
// cleanup closes the connection; Client.Close is a no-op because the store
|
||||
// service owns its own DB lifecycle (§11).
|
||||
// service owns its own DB lifecycle.
|
||||
//
|
||||
// The rule lives here rather than in a composition root so the server side
|
||||
// (which decides whether to install the token interceptors) and every client
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
// Package staterpc adapts the State Store contract (internal/domain/storecontract's
|
||||
// producer-owned surfaces plus the consumer-owned workflow.Store) to gRPC.
|
||||
// See docs/prds/state-store-contract.md for the ratified contract this
|
||||
// package implements against.
|
||||
// Package staterpc adapts the State Store contract
|
||||
// (internal/domain/storecontract's producer-owned surfaces plus the
|
||||
// consumer-owned workflow.Store) to gRPC.
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
@@ -30,9 +29,8 @@ import (
|
||||
)
|
||||
|
||||
// Unavailable-capability errors, mirroring gatewayrpc's missing-session-store
|
||||
// pattern (docs/prds/state-store-contract.md §7's "capability absent ->
|
||||
// Unavailable" row): a nil optional Deps field maps to codes.Unavailable
|
||||
// rather than a nil-pointer panic.
|
||||
// pattern: a nil optional Deps field maps to codes.Unavailable rather than a
|
||||
// nil-pointer panic.
|
||||
var (
|
||||
errCaptureUnavailable = status.Error(codes.Unavailable, "capture store unavailable")
|
||||
errConfigSnapshotsUnavailable = status.Error(codes.Unavailable, "config snapshot store unavailable")
|
||||
@@ -92,38 +90,38 @@ type Deps struct {
|
||||
Sources storecontract.SourceStore
|
||||
BindingDispatcher storecontract.BindingDispatcher
|
||||
BindingTaskCreator storecontract.BindingTaskCreator
|
||||
// WorkflowCalls is the workflow.call surface (docs/prds/workflow-calls.md):
|
||||
// WorkflowCalls is the workflow.call surface:
|
||||
// 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
|
||||
// Steps is the step-execution write surface
|
||||
// (docs/prds/execution-tree-state-machine.md): the guarded row writes the
|
||||
// Steps is the step-execution write surface:
|
||||
// the guarded row writes the
|
||||
// workflow engine's run credential calls. Optional: nil answers both RPCs
|
||||
// with codes.Unavailable.
|
||||
Steps storecontract.StepRecorder
|
||||
// Canceller is the one cancel path (docs/prds/execution-tree-state-machine.md):
|
||||
// Canceller is the one cancel path:
|
||||
// an operator action's guarded write over the execution and its steps.
|
||||
// Optional: nil answers the RPC with codes.Unavailable.
|
||||
Canceller storecontract.ExecutionCanceller
|
||||
// StepReader lists an execution's recorded steps for the dashboard/API
|
||||
// (docs/prds/execution-tree-state-machine.md): a plain read, never
|
||||
// StepReader lists an execution's recorded steps for the dashboard/API:
|
||||
// a plain read, never
|
||||
// task-scoped-grant callable. Optional: nil answers ListSteps with
|
||||
// codes.Unavailable.
|
||||
StepReader storecontract.StepReader
|
||||
// HarnessSecrets persists harness OAuth token sets
|
||||
// (docs/prds/external-agent-harness.md, Credentials). Optional: nil
|
||||
// HarnessSecrets persists harness OAuth token sets.
|
||||
// Optional: nil
|
||||
// answers both RPCs with codes.Unavailable.
|
||||
HarnessSecrets storecontract.HarnessSecretStore
|
||||
// PlaybookDispatcher is the side-effecting-action idempotency ledger
|
||||
// (docs/prds/eda-playbook-engine.md gap 2). Optional: nil disables the
|
||||
// PlaybookDispatcher is the side-effecting-action idempotency ledger.
|
||||
// Optional: nil disables the
|
||||
// two playbook dispatch RPCs with codes.Unavailable.
|
||||
PlaybookDispatcher storecontract.PlaybookDispatcher
|
||||
// Principals assembles the access principal for one identity: the org it
|
||||
// serves and its memberships. Optional: nil answers GetPrincipal with
|
||||
// codes.Unavailable.
|
||||
Principals access.PrincipalSource
|
||||
// Policies is the stored policy chain (docs/prds/orgs-and-access.md).
|
||||
// Policies is the stored policy chain.
|
||||
// Optional: nil answers the access RPCs with codes.Unavailable. The reset
|
||||
// surface is deliberately not an RPC: `archied access reset` runs on the
|
||||
// State Store host, never over the network.
|
||||
@@ -148,8 +146,8 @@ type server struct {
|
||||
|
||||
// RegisterServer registers the StateStore gRPC service against registrar,
|
||||
// backed by deps. Optionally wrap registrar's interceptor chain with
|
||||
// TokenInterceptor for the bridge-address (agent-consumed) topology; the
|
||||
// caller decides, per docs/prds/state-store-contract.md §9's listener rule.
|
||||
// TokenInterceptor for the bridge-address (agent-consumed) topology; the caller
|
||||
// decides.
|
||||
func RegisterServer(registrar grpc.ServiceRegistrar, deps Deps) {
|
||||
if deps.Log == nil {
|
||||
deps.Log = slog.New(slog.DiscardHandler)
|
||||
@@ -223,8 +221,8 @@ func (s *server) Transition(ctx context.Context, r *pb.TransitionRequest) (*pb.T
|
||||
return &pb.TransitionResponse{}, nil
|
||||
}
|
||||
|
||||
// StartStep and FinishStep are the step-execution writes
|
||||
// (docs/prds/execution-tree-state-machine.md). Each is the store's own
|
||||
// StartStep and FinishStep are the step-execution writes.
|
||||
// Each is the store's own
|
||||
// transaction -- guarded row write plus the event row -- and the store's
|
||||
// response carries the persisted event back for the caller's post-commit
|
||||
// publish.
|
||||
@@ -243,7 +241,7 @@ func (s *server) StartStep(ctx context.Context, r *pb.StartStepRequest) (*pb.Sta
|
||||
return &pb.StartStepResponse{StepId: stepID, Event: eventProto(event)}, nil
|
||||
}
|
||||
|
||||
// CancelExecution is the one cancel path (docs/prds/execution-tree-state-machine.md):
|
||||
// CancelExecution is the one cancel path:
|
||||
// the store records the cancellation and returns the steps it cancelled; the
|
||||
// caller delivers it by cancelling the run's in-memory context afterwards.
|
||||
func (s *server) CancelExecution(ctx context.Context, r *pb.CancelExecutionRequest) (*pb.CancelExecutionResponse, error) {
|
||||
@@ -621,7 +619,6 @@ func (s *server) InsertCapture(ctx context.Context, r *pb.InsertCaptureRequest)
|
||||
|
||||
// StreamCaptures streams one capture per message: a batch of large capture
|
||||
// bodies in one unary response can exceed gRPC's 4MiB message cap
|
||||
// (docs/prds/state-store-contract.md).
|
||||
func (s *server) StreamCaptures(r *pb.StreamCapturesRequest, stream pb.StateStoreService_StreamCapturesServer) error {
|
||||
cs, err := s.capture()
|
||||
if err != nil {
|
||||
@@ -959,7 +956,7 @@ func (s *server) EnqueueBindingTask(ctx context.Context, r *pb.EnqueueBindingTas
|
||||
}
|
||||
|
||||
// WorkflowCaller: a workflow.call step starts its callee and reads it back
|
||||
// while waiting (docs/prds/workflow-calls.md). The grant already named the
|
||||
// while waiting. 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.
|
||||
|
||||
|
||||
@@ -90,19 +90,11 @@ func (g *TaskGrants) taskFor(token string) int64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
// 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 and the two step-execution writes are the
|
||||
// sanctioned widenings: a workflow.call step must start its callee and read it
|
||||
// back, the callee being the caller's child (docs/prds/workflow-calls.md), and
|
||||
// the container records its stages and its own agent calls under the run
|
||||
// credential of docs/prds/execution-tree-state-machine.md. The step requests
|
||||
// carry the caller's own task ID, which the grant check verifies; the step's
|
||||
// membership in that execution is a handler-side row check, so this
|
||||
// interceptor never reads the database.
|
||||
// authorizesTaskScopedCall reports whether a task-scoped token may make this
|
||||
// call: only when the RPC is in taskScopedTargets and targets taskID. Every
|
||||
// other RPC, including grant registration, is refused, so a task grant only
|
||||
// narrows. workflow.call and step-execution writes carry the caller's own task
|
||||
// ID; the handler checks step membership, so this never reads the database.
|
||||
func authorizesTaskScopedCall(fullMethod string, req any, taskID int64) bool {
|
||||
target := taskScopedTargets[fullMethod]
|
||||
return target != nil && target(req) == taskID
|
||||
|
||||
@@ -393,7 +393,7 @@ func dayTokensValue(d *pb.DayTokens) storecontract.DayTokens {
|
||||
return storecontract.DayTokens{Day: d.Day, Tokens: int(d.Tokens)}
|
||||
}
|
||||
|
||||
// Canonical public phrases for sentinel errors (rev. 2c §7). These strings
|
||||
// Canonical public phrases for sentinel errors. These strings
|
||||
// are the wire contract for sentinel identity -- the client rehydrates by
|
||||
// matching (code, message), never by parsing free-form text.
|
||||
const (
|
||||
@@ -431,13 +431,13 @@ const (
|
||||
// codes.Internal with a sanitised message; the caller is expected to log the
|
||||
// full error server-side before calling mapError.
|
||||
//
|
||||
// A context cancellation/deadline raised by the store (or by a caller ctx that
|
||||
// expires mid-call, §6) must retain its identity, not be folded into
|
||||
// codes.Internal: gRPC-Go surfaces context.Canceled/DeadlineExceeded to the
|
||||
// client only for those exact codes, and the agent's workflow consumer
|
||||
// depends on errors.Is(err, context.DeadlineExceeded) to distinguish an
|
||||
// interrupted stage from a failed one. So a context error maps to its own
|
||||
// gRPC code (and unmapError rehydrates it back to the sentinel).
|
||||
// A context cancellation/deadline raised by the store must retain its identity,
|
||||
// not be folded into codes.Internal: gRPC-Go surfaces
|
||||
// context.Canceled/DeadlineExceeded to the client only for those exact codes,
|
||||
// and the agent's workflow consumer depends on errors.Is(err,
|
||||
// context.DeadlineExceeded) to distinguish an interrupted stage from a failed
|
||||
// one. So a context error maps to its own gRPC code (and unmapError rehydrates
|
||||
// it back to the sentinel).
|
||||
func mapError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
@@ -461,7 +461,7 @@ func mapError(err error) error {
|
||||
// the wire. A non-status error (e.g. a transport failure) is returned
|
||||
// unchanged.
|
||||
//
|
||||
// The deadline/cancel identity must survive too (§6): the agent's
|
||||
// The deadline/cancel identity must survive too: the agent's
|
||||
// deadlineStore bounds each Store call with context.WithTimeout, and the
|
||||
// workflow consumer checks errors.Is(err, context.DeadlineExceeded) to
|
||||
// decide whether a stage was interrupted by shutdown rather than failed
|
||||
@@ -497,7 +497,7 @@ func unmapError(err error) error {
|
||||
|
||||
// sentinelForStatus maps a status to the store or logging sentinel it stands
|
||||
// for, matched on (code, exact canonical message) -- those message constants
|
||||
// are part of the wire contract (§4). A code whose message is not one this
|
||||
// are part of the wire contract. A code whose message is not one this
|
||||
// package defines returns nil, so the caller falls back to the wrapped form.
|
||||
func sentinelForStatus(st *status.Status) error {
|
||||
return wireSentinels[wireStatus{st.Code(), st.Message()}]
|
||||
|
||||
@@ -20,8 +20,8 @@ func (s Store) TaskByID(ctx context.Context, id int64) (*taskactions.Task, error
|
||||
return &taskactions.Task{ID: t.ID, Owner: t.Owner, Repo: t.Repo, Identity: t.Identity, Status: t.Status, ParkReason: t.ParkReason, IssueNumber: t.IssueNumber, RetryCount: t.RetryCount, Attempt: t.Attempt, Branch: t.Branch, RetryMode: t.RetryMode, ForgeBacked: t.IsForgeBacked(), ReviewGate: t.ReviewGate, RereviewRounds: t.RereviewRounds}, nil
|
||||
}
|
||||
|
||||
// CancelExecution delegates to the store's one cancel path
|
||||
// (docs/prds/execution-tree-state-machine.md). Both adapters -- the
|
||||
// CancelExecution delegates to the store's one cancel path.
|
||||
// Both adapters -- the
|
||||
// PostgreSQL store and the remote gRPC client -- implement it; the type
|
||||
// assertion failing would be a composition bug, so it is named rather than
|
||||
// panicked over.
|
||||
|
||||
@@ -67,19 +67,9 @@ func (eventSteps) StepTypes() []workflow.StepType {
|
||||
return []workflow.StepType{workflow.AgentRunStepType(), workflow.WorkflowCallStepType()}
|
||||
}
|
||||
|
||||
// commandSteps is the provider for the command.run step type: the single step
|
||||
// type the maintainer's command-step trust decision allows
|
||||
// (archie-core-ndm8), and the migration target that the refusal of
|
||||
// .archie/stages/*.go now names.
|
||||
//
|
||||
// It is a contributor of exactly one step type, which is the shape
|
||||
// docs/prds/workflow-step-vocabulary.md prescribes for this case -- "a new
|
||||
// contributor of exactly one step type at a named provider" -- and it is a
|
||||
// provider of its own rather than part of repoHooks because a command step is
|
||||
// not a repository hook: repoHooks carries the replacement for .archie/gate.go,
|
||||
// whose rules the *repository* authored, while this carries the replacement for
|
||||
// .archie/stages/*.go, whose commands the *operator* authors in the stored
|
||||
// definition.
|
||||
// commandSteps provides the command.run step type: operator-authored commands
|
||||
// from the stored workflow definition. It is separate from repoHooks, which
|
||||
// carries repository-authored gate rules.
|
||||
type commandSteps struct{}
|
||||
|
||||
func (commandSteps) Name() string { return "command" }
|
||||
|
||||
Reference in new issue
Block a user