A seed was consulted only for a resource kind the store did not hold, so a
document that changed in the build never reached a database an earlier
release had seeded. For workflow-definitions that is not a stale setting but
a total outage: the collection validates as one document, so a stored step
type this build no longer has fails every task's pin, whatever workflow the
task names. The seed's request ID was stable per kind and the store answers a
known request ID from resource_history, which outlives the resource, so the
documented recovery -- remove the resource and restart -- wrote nothing
either.
Seeds now carry one identity the reader can name, and a kind the store holds
is refreshed only when the seed itself wrote the newest revision: a
file-derived value stays the store's, and an operator's replacement is never
undone. The request ID is derived from the value, so an idempotent replay is
still one revision without making a second, changed document impossible. A
replay whose resource is gone re-creates it from the ledger's revision.
The shipped-vs-file-derived distinction is the seed's to make, so it is a
property of the definition (Defaults is set exactly for the kinds that ship a
document) rather than a check at each consumer.
review_pr self-omitted since 625ead95 deleted the synchronous reviewer it
called. It is rebuilt on the task enqueue path everything else uses: the
tool resolves the identity's configured repo, then queues a pr-review task
naming the pull request through the workflow's declared pr_number input,
which is the same generic input mechanism a watched-repos binding uses.
That input has to reach the store with the task, so
EnqueueChatTaskRequest gains inputs_json and the tasks insert writes the
inputs column directly. StampTaskBinding no longer writes it: the insert is
now the column's only writer, and a chat task must not acquire binding
provenance just to carry an input.
ChatPRReviewer, its result shape and the reviewer wiring are deleted with
the path they served.
Recover the OAuth storage slice from f6079e9d and the missing workflow persistence error handling from f07c314e, adapted to the current step contract. Require encryption for OAuth token storage and verify RPC round trips and task-grant denial.
Plan item 4 of docs/prds/execution-tree-state-machine.md (archie-core-1216),
plus the callee half of CancelExecution that plan item 5 deferred until the
tree could decide it.
Every agent call a stage makes records itself: AgentStage's bridge, the
baseline-fix auto-fix run, the adversarial reviewer and a workflow.call each
start a child StepExecution of kind agent or call under the stage's own step
-- TaskContext.StepID, which the engine sets before the stage body starts and
clears when it returns -- and finish it with the call's own outcome and the
tokens it accounted. A child's recording write failure parks the execution
the same way a stage's does: an agent call that ran unrecorded is the
invisibility the step table exists to end. A stage invoked outside the
engine's recorded run -- the stage unit tests -- records no child and runs
unchanged.
The call step is what makes the callee half of the PRD's Cancellation section
decidable, and this lands it: a call step closes when its callee ends, so an
open call step is a callee the caller waits on (wait:true) and a closed one
is a wait:false callee that runs on. CancelExecution reads the open call
steps before its sweep closes them and cancels each named callee through its
own CancelExecution in the caller's write's aftermath -- the callee's own
steps, its own events, its own move to the same destination, and the callee's
own wait:true callees beyond it, the depth the enqueue enforces bounding the
recursion. A callee that cannot be cancelled is reported and the caller's own
record stands.
StartStep refuses a call step whose callee is not this run's own (the
callee's call_parent_task_id must name the recording execution): a
compromised container could otherwise record a step naming a foreign
execution and cancel it. StartStepRequest gains called_execution_id (field 6;
non-breaking, the column and its named consumer already exist) and
StepStart carries it.
PRD decisions recorded here:
- The reviewer records as one agent child named "review": the Reviewer
contract runs one subagent per review, the PRD model's review:1/review:2
are illustrative of depth-1 children. A completed report closes it
succeeded, a not-run review failed with the skip reason; the contract
carries no usage, so tokens are 0.
- A failed-callee call step closes as failed with the callee's detail when
the wait ends otherwise; the single open case is the caller itself being
cancelled, whose CancelExecution already swept this step -- a late write
must not pretend the wait is still the caller's business.
- A call step's callee is cancelled to the same destination the caller's
action named (parked stays parked, closed_wont_do ends the whole chain),
and a callee that cannot be cancelled is reported while the caller's own
record stands either way.
- The agent child's detail is the result summary on success and the error's
text on failure, with the call's own TokensUsed -- the PRD's only usage
field, untracked per call for the reviewer contract.
docs/prds/execution-tree-state-machine.md: step_executions (0017) is now the
durable per-step record; the dashboard's run detail (GET /api/tasks/{id}/
attempts) still folded stage_start/stage_finish events into a rail by hand,
and tasks.stage duplicated what StartStep/FinishStep already record properly.
Added the missing read:
- ListSteps(execution_id, attempt) -- attempt 0 lists every attempt of the
execution, oldest first, so the rail renders every attempt from one call.
New storecontract.StepReader (separate from StepRecorder: this is a
dashboard/API/dispatch action per the PRD's wire contract, never
task-scoped-grant callable), postgresdb.ListStepExecutions, staterpc
client/server/values.go plumbing, wired through state_store.go's Deps and
archieui/compose.go's Server.Steps the same optional-capability pattern
every other dashboard read uses.
- internal/webui/api_tasks_attempts.go: stageViewsFromSteps replaces
foldStages/finishStage/stageOutcome. Attempt bounds, event_count and which
attempt numbers exist stay sourced from events (an attempt can carry
events -- agent calls -- with no step), only the stage list itself moves.
The wire JSON contract is unchanged, so no frontend change was needed;
`task ui` confirms ui/dist still matches a fresh build.
- A running step past the task's own current attempt reads interrupted, not
running: RecoverStale (archie-core, still open per #1214) is what corrects
a crashed run's stale "running" row, and until it does this is the honest
read rather than trusting a row that may be stale.
Dropped tasks.stage and every reader, no fallback:
- Migration 0018 drops the column; tasks.sql's INSERT/UPDATE/RETURNING lists
and the sqlc-generated code no longer carry it.
- workflow.Task.Stage is gone; workflow.Run's in-flight "which stage is this"
bookkeeping moves to TaskContext.Stage (execution-time only, never
persisted -- park/finish's event tagging is its only reader).
- pb.Task.stage (wire field 10) is `[deprecated = true]`, not deleted (never
reuse a field number); staterpc's taskProto/taskValue no longer map it.
- taskactions.Task.Stage and the retry event's "previous_stage" data field
are gone: the operator-action package had no reader for the column beyond
echoing it.
- The chat /tasks command's per-task "workflow/stage" display drops to
workflow-only (ChatTaskSummary.Stage removed, workflowStage() deleted):
it was a genuine reader with no replacement in scope for this change.
Read the archie-web-ui skill and the state-store/daemon docs/development
pages first, per instruction. Stayed out of cancel/stop code throughout
(Pi's concurrent CancelExecution work); the only shared files touched
(workflow.go, daemon-adjacent SQL) got the smallest possible diff.
Plan item 6 of docs/prds/execution-tree-state-machine.md (archie-core-1214),
the crash-recovery sweep the step table made decidable. RecoverStale used to be
one bare UPDATE of tasks running -> queued; the steps an interrupted execution
left running stayed running forever, so the next attempt started under steps
that were never closed.
Recovery is now one transaction: the running executions are locked, every step
each one's current attempt left running moves to the step transition table's
interrupted outcome with one stage_finish event row carrying the
interruption marker -- the same document stageOutcome reads, so the attempt
view renders the interruption the way the pre-step-table producer wrote it --
each execution's audit row lands in the same write, and the existing
running->queued requeue query runs last inside it. Both edges are pinned in
SQL and pinned to their tables (the execution pair beside claim and
BeginRemediation, the step pair in its own test, because the two tables are
different tables), so a query edit cannot move a write off a table.
Deliberately running-only, per the PRD's letter: pending rows never persist
outside StartStep's own transaction, so a crashed attempt leaves only running
rows, and a finished step is never rewritten. The interrupted steps' events
render as the PRD's interrupted -- distinct from cancelled, which an operator
or parent asked for, and from failed, which the step reported.
The wait:true-callee and agent-child sweeps ride #1216's tree, and the
dashboard's ListSteps read is plan item 7; both untouched here, and the
RecoverStale signature and RPC are unchanged.
Plan item 5 of docs/prds/execution-tree-state-machine.md (archie-core-1217).
Until now a stop was a context cancel plus a caller-side transition, and the
step rows a worker still held running could never be told: the execution moved
while the work carried on, and the old interrupt-first ordering existed only
because the record could not defend itself. The step table can: the PRD's
ordering -- the store is the record, the context cancel is the delivery --
became safe the moment a worker's next step write fails ErrStaleTransition
against a cancelled step.
- storecontract.ExecutionCanceller and the CancelExecution RPC: one
transaction moves every non-terminal StepExecution of the execution's
current attempt to cancelled (one event row each, in the same
transaction), and the execution itself to the status the operator action
names, under the shared transition table with its audit row. Staleness is
decided before legality, the way guardTransition decides it. Earlier
attempts are never rewritten. Deliberately administrative: the
deny-by-default grant rule covers it, pinned by a test.
- taskactions.Service routes stop, cancel, abandon and reject through it and
the old Transition/CancelTask combinations are deleted; the daemon's
in-memory cancel is demoted to the delivery hook the PRD names, called
after the store record.
- The gateway's chat controller records first and delivers second, the same
order, and records even when no runtime is wired here (a standalone
gateway cannot reach the daemon's goroutines): the record is what unsticks
a lost-cancel task, and the delivery is best effort. StopRunning and
TaskRuntime.CancelRunningTasks are deleted outright -- no production
caller remained once the task_action tool owned stopping, and the daemon's
CancelRunningTasks/runningTasks.stopAll go with them.
- The gateway's chat adapter writes through CancelExecution instead of a
bare Transition, so chat /cancel and the dashboard's action service land
on the same path.
PRD decisions recorded here:
- Each cancelled step's event row is stage_finish with {cancelled: true} and
the reason as its detail -- the exact-one-event-per-step-transition rule
covers the pending -> cancelled transition too, even for a step that never
ran.
- A parked cancel carries the needs_human class, matching the Transition
path this replaces; the transient class stays with parkRunningTask's
unwind parks, which now meet ErrStaleTransition for cancelled runs and are
ignored there.
- Cancelling a wait:true callee is deferred to #1216's agent-call children:
the callee's own tree and the wait flag are what make
"cancelling a caller cancels each callee it waits on" decidable, and the
callee writes it cannot fake are this issue's half of the contract.
- RecoverStale's interrupted sweep is plan item 6, untouched here.
Plan item 3 of docs/prds/execution-tree-state-machine.md (archie-core-1220), on
top of the transition tables and ErrIllegalTransition enforcement (1214/1215,
archie-core-qdbo.5):
- Migration 0017 adds step_executions -- id, org_id, workspace_id, execution_id,
attempt, parent_id, depth, kind, name, called_execution_id, status, detail,
tokens_used, started_at, finished_at, indexed on (execution_id, attempt, id).
Ownership fields are stamped from the execution's row; depth is derived from
the parent, never supplied by a caller. Existing rows gain no backfilled
steps.
- task.Store (the workflow engine's mid-run facade) gains StartStep/FinishStep
(5 methods, within the 8 cap), with storecontract.StepRecorder fronting them
on the server; deadlineStore wraps both with its per-call timeout.
- The store enforces each write as one transaction: the guarded row write
under the shared step transition table plus the transition's own
stage_start/stage_finish event row. Staleness is decided before legality,
the way guardTransition decides it, and the store returns the persisted
event for the caller's post-commit publish -- the EmitDurable convention
(the daemon's event sink skips already-persisted rows by assigned ID), which
is why workflow.Run stops emitting stage events beside the store and no
longer discards step-write errors: a failed start or finish parks the
execution, and the stage does not run unrecorded. An interrupted stage
records interrupted rather than failed; a recording failure on that
shutdown path is logged and left to RecoverStale, which owns the
interrupted-execution sweep in plan item 6.
- The run credential of docs/prds/orgs-and-access.md authorises StartStep and
FinishStep on its own execution only: both requests carry the execution ID
the grant check verifies (FinishStep carries it because the interceptor
never reads the database), and FinishStep verifies handler-side that the
step really is that execution's. authorizesTaskScopedCall's sanctioned
widenings are now held as a lookup table so the next one stops growing a
switch.
- The PRD's wire contract is StartStep(execution, attempt, parent, kind, name)
-> step id; the responses also carry the persisted event (needed for the
post-commit publish) and FinishStep's request carries execution_id (needed
for the grant check) -- both noted here as deliberate additions to the PRD's
shorthand. called_execution_id exists in the table but not yet on the wire:
its named consumer is the workflow-call recording of plan item 4 (#1216).
Conformance drives both adapters; grant tests pin the own-execution scoping;
the wire sentinel set gains ErrInvalidStep (InvalidArgument, "step execution
invalid") for a step kind no consumer names.
Every caller-supplied status write (Transition, ParkTask, Requeue,
RetryTask, BeginRemediation) now checks the shared taskstate transition
table inside the write's transaction, after the from guard decides
staleness. An off-table pair returns the new storecontract.ErrIllegalTransition,
carried over gRPC through mapError/unmapError on (FailedPrecondition,
"illegal transition"). Claim, BeginRemediation and RecoverStale pin
their pairs in SQL; a test pins those pairs to the table so a query
edit cannot move a write off it. Requeue/RetryTask share one guarded
requeue body. (archie-core-qdbo.5)
The transition table moved the no-change outcomes to StatusCompleted, so a
run that opens no pull request now ends in a status the per-workflow stats
did not count at all: it was not merged, not in review, not parked, and the
workflows page would have shown it as a run that went nowhere. The count
travels the whole State Store path, since every dashboard consumer reads it
through the gRPC client rather than the local store.
- WorkflowStats filters `completed` beside merged and pr_open; the SQL is
the count, so a wrong filter reads as zero rather than failing, and
TestWorkflowStatsCountsCompletedRuns holds it against a real store.
- storecontract.WorkflowStat gains Completed (json "completed"), the proto
message gains field 9, and workflowStatProto/workflowStatValue carry it;
TestWorkflowStatProtoCarriesEveryField round-trips every field by name.
- The gateway's chat task report names the status.
- The dashboard counts a completed run as delivered in GatePulseCard's
totals and badge numerator, and the WorkflowStat/WorkflowStats/WorkflowRow
interfaces carry the field.
- TestOutcomeSitesAreTransitionsFromRunning is the guard that keeps the
producer and the table agreeing: it re-reads this package's tc.Outcome
assignment sites from source and requires each status to be one
internal/taskstate allows from running, so a new or moved site has to be
adjudicated against the table instead of discovered on a live run.
Every install serves from Postgres, so the legacyread/legacyimport packages,
the archie-state-store import command, the boot gate that refused to serve
over unimported SQLite files, and db_path (which only located those files)
go. Migration 0010 drops the import_completion table.
ClearTerminalTasks now deletes completed tasks, with a test that holds its
SQL list to taskstate.Terminal. The AllowTools comment says agentloop's
built-in file tools are outside the allowlist and why. The PRD model
diagram lists only what a profile holds (image, tools), and the profile
field and AgentProfile say a workflow's profile name is resolved at
dispatch, not when the workflow is saved.
Workflow definitions declare inputs, repository (none, optional or
required; default required) and profile. A binding assigns each input
from a mapped parameter or a constant and may take its repository from a
parameter, which must name a configured repo; both are checked when the
binding is saved and again at dispatch. Inputs travel as structured task
data (tasks.inputs, the task brief, and a JSON block in the agent's
mission), never as body text.
A task with no repository runs in a per-task scratch workspace with no
clone and no publication grant. The agent.run step runs one mission
without a repository and finishes the task in the new completed status.
Agent profiles live under [containers.profiles.<name>]: an image and an
allowlist over the tools archie adds (MCP, scripts, plugins).
[containers].image is the default profile; an unconfigured profile parks
the task. The workflow is now pinned before the container starts so the
profile can choose its image.
Also stop two archied tests writing embedded NATS state into the package
directory, refuse an empty state_dir for embedded NATS, and drop the NATS
store files an earlier lane commit tracked.
A mapping belongs to an event type and is checked against its inferred
schema on save. Each event a mapping resolves is counted once in
mapping_matches (migration 0008), read back as match_count and
last_matched_at. Bindings carry an optional CEL filter over the mapping's
parameters, checked on save. The per-source unique indexes are dropped:
every armed binding whose mapping matches the capture's event type and
whose filter admits it dispatches once, claimed in the per-binding ledger
before its task is enqueued. The State Store gains RecordMappingMatch and
the new mapping and binding fields.
Resolves against t2db.36: captures carry both event_type and unsigned (proto field 10), the State Store serves sources and event types from the Postgres EDA store, the capture row shows event type and signature together, and the staterpc sentinels map both ways from one table.
A source is the capture endpoint: a UUIDv7 path by default or a unique
URL-safe custom path, signed by default with an Archie-generated secret
(encrypted via the bindings cipher), or unsigned after an approval.
Intake verifies X-Hub-Signature-256/X-Signature-256 against the source
secret before redaction; an unauthenticated event on a signed source is
captured but never dispatched, an event on an approved unsigned source
dispatches and is marked unsigned. The binding secret is retired; migration
0006 derives sources from existing binding and capture source strings,
moving each binding's secret onto its source. SourceStore crosses the
State Store gRPC contract. The dashboard gains a sources panel and flags
unsigned in the capture inspector, binding list and task timeline.
The State Store's task and event-capture stores and the conversation store
read by archied and served by archie-gateway now open on database_url.
Every serving process refuses to start when legacy SQLite data exists and no
import completion is recorded, naming archie-state-store import; a fresh
install records completion itself. The Gateway holds its Postgres serve
claim for its lifetime and releases it before the pool closes.
archie-state-store import copies the State Store task database, the
PocketBase event store and the Gateway conversation store, all named from
db_path, into Postgres in one transaction. The bead asked for an archied
command; offline maintenance of a store belongs to the binary that owns it,
so it sits beside backup/restore/validate/rollback instead.
It refuses rather than guesses: while the state-store or gateway ownership
claim is held, when a domain it imports already holds rows (an allowlist of
that domain's tables, checked after Migrate), on a completed prior import,
on FK orphans, alias case collisions, duplicate bindings, events whose (at,
id) order microsecond storage would change, schema gaps, and any value the
target column cannot hold, naming table, row, value and rule. Historical ids
are kept and every identity sequence is set from AUTOINCREMENT's high-water
mark. After loading it compares key sets, event order, resource blobs and
binding secrets byte for byte and the next id of every sequence, checks the
source files were not written while read, and only then writes an
import_completion row (migration 0005) in the same transaction.
postgres.ImportComplete and legacyimport.HasLegacyData are the two halves
of the boot gate: legacy data without a completed import must not serve.
CHECKPOINT -- the full State Store port is in progress; this lands the
compile-clean core so the review pass has a diff to work against. Remaining:
advisory-lock ownership, event-insert serialization, maintenance, and the
ported test battery.
Two corrections to behaviour that already shipped, not new features:
- UpdateTask wrote park_reason raw where SQLite applies clip(park_reason,
4000); the PostgreSQL adapter now clips before binding (clip.go).
- tasks.review_cursor existed on the protobuf wire and in workflow.Task but
not in the PostgreSQL schema; 0004 adds it as a NEW migration rather than
amending 0001 because a dev database may already have applied 0001 and
goose tracks version numbers, not checksums.
Also moves the control-plane Resource/ResourceWrite types and their sentinels
into storecontract so the postgres package can stop importing internal/store
(they stay aliased there for daemon callers).
L2 of the PocketBase->Postgres migration (bead archie-core-7r0x.3): a new
Postgres-backed EDA adapter (postgres.EDA) plus its goose migration
(0002_edastore.sql) and sqlc queries (queries/edastore.sql), satisfying the
same storecontract surfaces as internal/infrastructure/edastore.Store so the
cutover wave can swap them behind the contract. The PocketBase opener in
internal/app/archied/state_store.go is untouched: production still opens
SQLite, and the cutover waits for the one-time import.
Three recon-found hazards, each pinned by a test, not a comment:
1. Empty-secret early return. applyBinding deliberately never writes the
secret column when the incoming secret is empty, so an edit form that does
not echo the secret must not blank an armed binding's HMAC key. The
UpdateBinding query keeps the stored secret via
`secret = CASE WHEN $secret = '' THEN secret ELSE $secret END`; pinned by
TestUpdateBindingEmptySecretPreservesStored (raw column unchanged across an
empty-secret edit).
2. Unique-violation detection by SQLSTATE. isUniqueViolation previously grepped
the driver's error text for "unique"/"already exists"; Postgres reports
SQLSTATE 23505 and the text match would not fire, losing ErrAlreadyDispatched.
The adapter detects by pgconn.PgError.Code == "23505"; pinned by
TestIsUniqueViolationDetectsBySQLState (23505 with a message lacking those
words is detected; a non-23505 whose text says "unique" is not).
3. One-binding-per-source / one-armed-binding-per-source were read-then-refuse
with no transaction and a non-unique idx_bindings_source_status. Made them
constraints: UNIQUE(source) plus a partial UNIQUE(source) WHERE
status='armed' (the full unique subsumes the armed rule today, kept explicit
for a future matcher extension). A concurrent insert for one source yields
exactly one success and one ErrBindingOverlap; pinned by
TestConcurrentInsertBindingSameSource.
Dispatch ledgers kept exactly: UNIQUE(binding, capture) and
UNIQUE(playbook_id, playbook_version, event_id, action_id); binding_version is
stored but deliberately not part of the key (pinned by
TestBindingDispatchVersionBumpDoesNotPermitRedispatch). The cipher is
unchanged: AES-256-GCM, key = SHA-256(material), decrypt stays in the store and
the gRPC wire still carries plaintext.
Notify is left as an injected callback (EDA.SetNotify) and is NOT wired to
LISTEN/NOTIFY. It is dead code today: edastore.Config.Notify is omitted at its
only production construction and no consumer maps binding_changed/
mapping_changed, so building a LISTEN/NOTIFY path would be building for a
consumer that does not exist. Wired or not is a separate decision.
Move sessions, messages, turns and full-text search off the per-process
SQLite file onto Postgres behind the existing messaging.SessionStore
contract. New adapter internal/gateway/session_store_postgres.go, sqlc
queries/gateway.sql, migration 0003_gateway.sql, regenerated postgresdb.
FTS5 becomes a STORED generated tsvector column over (sender, text) plus
GIN. plainto_tsquery is the tsvector analog of ftsMatchQuery's
quote-escaping: query text is parsed as plain text, never query syntax, and
the surviving terms are ANDed. MessagePage.Truncated stays always-false on
Postgres too: the result set is counted exactly.
On internal/domain/messaging/session_store.go: this is a comment-only edit
to the MessagePage.Truncated doc comment (the brief's own "change the
comment" instruction). It changes no type, method or value, so L2 and the
import lane still build against an unchanged contract and the wire is
unaffected. No interface widened or altered.
Semantics preserved verbatim:
- The timestamp clamp is SQL-atomic (INSERT ... SELECT MAX(ts)+1). Appends to
one session are serialised by a transaction-scoped advisory lock keyed on
the session so two concurrent appends cannot read the same MAX(ts); a Go
clamp would race (proven by the new cross-handle monotonicity test).
- Session ordering is GREATEST(last_active_at, created_at) with a matching
expression index.
- ClaimTurn is insert-first (ON CONFLICT DO NOTHING), with a race test across
two handles.
State outside the store is NOT made shared by this change, and none of it is
silently improved or worsened:
- sessionTracker.active, Router.titling and per-session persona selection are
in-memory, per-process caches; a second Gateway still diverges from the
first.
- messaging.Turns lanes and the per-process recovery latch stay per-process.
- RecoverTurns still fails every turn owned by another process, so a second
Gateway starting would still fail the first's in-flight turns. This lane
does NOT make that safe and does not try to: the safeguard is D4.1's
single-Gateway advisory serve-ownership lock (not implemented here), which
prevents a second Gateway from serving at all. The turn-recovery semantics
are left exactly as they were.
Production openers still return SQLite; this lane adds the adapter and tests
only. The cutover and the state-sharing questions remain follow-up work.
goose migration 0001 lands the twelve State Store tables on Postgres, and sqlc generates the task queries from it. Two behaviours that genuinely differ from SQLite are pinned by tests against a real PG 18: claiming takes the oldest queued row with FOR UPDATE SKIP LOCKED (without the clause a second claimer blocks, which the test shows by timing out), and every column behind a Go int is bigint -- SQLite's INTEGER is 64-bit, and the chat issue-number allocator seeds at 10^15, which does not fit an int4.
task db:generate writes the committed postgresdb package; task db:check regenerates it in the gate, as proto:check and ui:check do.
The remaining store methods (events, resources, identities, the status tables) still run on SQLite: porting them is the rest of archie-core-7r0x.2.