Commit Graph
54 Commits
Author SHA1 Message Date
sam 2ed9cb7455 feat(telegram): carry inbound media through the chat turn
Telegram dropped every incoming photo, document, video and audio
message: the default handler required message text, and nothing on the
turn path knew media existed. The receiving path now closes the gap
end to end.

- telegram: extract the attachment from the update (largest photo, plus
  document, video, video-note, audio and voice kinds), download its
  bytes on the turn lane through getFile + the Bot API file link with a
  20 MB gate, submit the turn with the attachment, and answer
  unsupported content kinds (sticker, location, contact, poll) with a
  clear notice instead of silence
- messaging: Inbound carries turn-scoped transport media and
  MediaAttachment a Data field for in-process bytes; Message gains
  Media attachment metadata which stores persist (Postgres jsonb via
 migration 0020, memory store) with Data stripped at the persist
  boundary, and pb.Message carries the metadata on the gateway wire
- gateway: TurnModelRequest threads the turn's media to the model seam
- archied: the chat turn model merges the attachments into the final
  user message as ai-sdk image/file part entries, so vision-capable
  models see the file for the turn it arrived in; stored history keeps
  the placeholder note plus caption

Session log: messages carry what was sent as data (the attachment
metadata), not just prose. Transcript rendering of attachments and a
re-look capability are tracked as archie-core-jaba.
2026-09-30 03:07:54 +10:00
sam dc1b61d394 feat(eda): per-org workflow enable/disable gating bindings
A workflow-enablement control-plane resource lists, per org, the workflows
that org has disabled. A binding targeting a disabled workflow is skipped at
dispatch like an unarmed one, is refused on save, and is flagged on the
binding list; the workflows page toggles it. Bindings now carry the org_id
column they already had in storage, over the State Store wire too.

Org-owned workflow definitions are deferred to a follow-up bead: they need
the caller's org, which the access chain resolves.
2026-09-30 02:59:23 +10:00
sam 64a4210b1f fix(controlplane): refresh a stale seeded resource and re-seed a removed one
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.
2026-09-29 14:27:57 +10:00
sam 5c91575166 feat(pr-review): operator/chat trigger queues a pr-review task
review_pr self-omitted since 7299b923 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.
2026-09-28 18:24:36 +10:00
sam 45cf3bc2c8 feat(harness): ingest OAuth storage and recover workflow write handling
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.
2026-09-27 13:09:41 +10:00
sam b3e9159dce Merge crew/pi-dashboard-sweep: agent-call children, call steps, and the waited-on callee sweep
# Conflicts:
#	internal/domain/workflow/workflow.go
#	internal/infrastructure/postgres/queries/steps.sql
2026-09-27 07:16:35 +10:00
sam 0b8014516a feat(workflow): agent-call children, call steps, and the waited-on callee sweep
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.
2026-09-27 07:14:15 +10:00
sam 7876bb4c0a feat(state-store): ListSteps, dashboard run detail reads it; drop tasks.stage
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.
2026-09-27 06:57:47 +10:00
sam 23e5c3f68f feat(statestore): RecoverStale interrupts the steps a crash left running
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.
2026-09-27 06:47:29 +10:00
sam 5f26b1e9dd feat(statestore): CancelExecution, and one cancel path for daemon stop and operator actions
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.
2026-09-27 06:34:01 +10:00
sam f884777c5b feat(statestore): step_executions, StartStep/FinishStep under the run credential
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.
2026-09-27 05:42:32 +10:00
sam 8f4165256c test(store): a resource request ID is idempotent per kind
The per-kind request-ID dedup was fixed in e8f86622 for the SQLite store and
carried into the PostgreSQL rewrite (05ee5eff) from day one: ResourceByRequest
filters WHERE kind = $1 AND request_id = $2 and resource_history carries
UNIQUE(kind, request_id). What neither rewrite kept is the test that pins the
cross-kind half of the contract -- the deleted internal/store suite had one, and
the Postgres suite only covers same-kind replay.

Pin it, and prove the failure mode it guards against: with the kind filter
dropped from the query, a request ID reused across two kinds silently returns
the first kind's history row under the second kind's write -- wrong kind, wrong
value, no error (archie-core-1179's latent hazard). Restore the filter and both
kinds write their own revisions, with per-kind replay still idempotent.
2026-09-26 20:29:49 +10:00
sam c8f9571448 feat(access): archied access reset --org/--instance on the State Store host (archie-core-qc8p) 2026-09-26 15:23:32 +10:00
sam 7c765dad9d feat(access): policy, denial and principal persistence on the State Store contract (archie-core-qc8p) 2026-09-26 15:23:32 +10:00
sam 484ea701fe feat(store): workflow.call contract — callee enqueue, parent-scoped status read, task-scoped grant widening (archie-core-t2db.41) 2026-09-26 13:36:41 +10:00
sam a7023bb2c3 feat(statestore): enforce the execution transition table and map ErrIllegalTransition over the wire
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)
2026-09-26 13:13:20 +10:00
sam fa19c459c7 fix(postgres): renumber org migrations past 0012, already taken by installed-packages 2026-09-26 11:44:21 +10:00
sam e0e9a17bd8 feat(org): idempotency key org/identity/owner/repo/number in one place, task uniqueness to match (archie-core-e5fn) 2026-09-26 11:43:10 +10:00
sam 47485d2751 feat(org): Postgres tenant tables, org-aware store and resumable default upgrade (archie-core-e5fn) 2026-09-26 11:43:10 +10:00
sam b361f8d90f feat(storepkg): install digest-pinned packages 2026-09-26 10:48:23 +10:00
sam c0413fc5e8 test(taskstate): seed fixture task states along the transition table
The execution transition table refuses most of the pairs shipped fixtures
wrote to build a finished task -- running -> merged, queued -> parked,
queued -> waiting_human, queued -> merged -- so those fixtures fail the
moment the store enforces it.

internal/taskstate/taskstatetest seeds a status by walking the table's
legal edges (shortest route, computed from taskstate.CanTransition), so a
fixture cannot write an illegal pair and fails loudly when no route
exists. The fixtures in internal/daemon, internal/app/archied,
internal/webui and internal/infrastructure/postgres go through it, and
the table's own test names running -> merged as refused.
2026-09-26 04:01:08 +10:00
sam 038fd2c7ec feat(taskstate): count completed runs in the per-workflow stats
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.
2026-09-26 04:01:08 +10:00
sam 0083cfaf5f feat(controlplane): field-level sys_audit table, audit view on settings pages, whole-task time limit 2026-09-25 09:54:30 +10:00
sam 8c55b5d4e4 chore(state-store): remove the one-time SQLite import and db_path
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.
2026-09-25 00:40:48 +10:00
sam 7b7aa62c28 fix(eda): clear completed tasks; document the tool allowlist's reach and unchecked profile names
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.
2026-09-24 20:53:51 +10:00
sam c431834e2b feat(eda): workflow inputs, optional repository and agent profiles
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.
2026-09-24 20:29:33 +10:00
sam f68355ca77 Merge branch 'pg/foundation' into worktree-agent-a96503bc8828fc104
# Conflicts:
#	docs/data/generated/dev-docs.json
#	internal/app/archied/state_store_test.go
#	internal/app/archied/state_store_toolcalls_test.go
#	internal/contracts/state/v1/state.pb.go
#	internal/daemon/dispatch_bindings_test.go
#	internal/infrastructure/bindingcipher/cipher_test.go
#	internal/infrastructure/captureintake/receiver_test.go
#	internal/infrastructure/edastore/contracts_binding.go
#	internal/infrastructure/edastore/testsupport_test.go
#	internal/infrastructure/postgres/edastore.go
#	internal/infrastructure/postgres/edastore_test.go
#	internal/infrastructure/staterpc/error_test.go
#	internal/store/store.go
#	internal/webui/api_binding_test.go
2026-09-24 19:47:00 +10:00
sam 0495af7c3d docs(store): drop residual SQLite references; fix lane lint findings 2026-09-24 19:39:06 +10:00
sam 0471899318 Merge remote-tracking branch 'origin/pg/foundation' into worktree-agent-a62864fcfbdb43f5a
# Conflicts:
#	internal/app/archied/state_store.go
#	internal/contracts/state/v1/state.pb.go
#	internal/daemon/daemon.go
#	internal/infrastructure/captureintake/receiver.go
#	internal/infrastructure/captureintake/receiver_test.go
#	internal/infrastructure/legacyimport/load.go
#	internal/infrastructure/postgres/edastore_test.go
#	internal/infrastructure/postgres/postgresdb/edastore.sql.go
#	internal/infrastructure/postgres/queries/edastore.sql
#	internal/infrastructure/staterpc/client.go
#	internal/infrastructure/staterpc/values.go
#	internal/webui/api_binding.go
#	internal/webui/api_binding_test.go
#	ui/dist/assets/index.js
#	ui/src/bindings/BindingEditor.vue
#	ui/src/bindings/BindingRow.vue
2026-09-24 19:34:31 +10:00
sam bf3e688bfe refactor(store)!: remove the SQLite task store, the PocketBase event store and the SQLite session store
The State Store, event capture and Gateway conversations already serve from
PostgreSQL. This deletes internal/store and internal/infrastructure/edastore,
the SQLite gateway session store and openProductionTaskStore, and the -db
recovery path on a legacy task file; backup, restore, validate and rollback
work on the database database_url names.

- The binding-secret cipher moves to internal/infrastructure/bindingcipher and
  ToolCall to internal/infrastructure/postgres.
- NewSessionStoreMemory is now a pure in-memory store that passes the shared
  SessionStore conformance suite.
- Tests run against PostgreSQL through internal/infrastructure/postgres/pgstore;
  legacyimport/legacyfixture writes the legacy files the import and the boot
  gate read.
- The cron dialect is owned in internal/domain/scheduling, so
  github.com/pocketbase/pocketbase and pocketbase/dbx leave go.mod.
  modernc.org/sqlite stays for the one-time import (legacyread).
- The UI and Messaging architecture gates ban the Postgres and legacy readers
  in place of internal/store.
2026-09-24 14:43:50 +10:00
sam b9d3acd31c feat(eda): mappings per event type, match counts, several bindings per source
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.
2026-09-24 14:42:58 +10:00
sam 3fce04bf5d merge: t2db.40 sources and signing into pg/foundation
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.
2026-09-24 14:38:40 +10:00
sam 963f967c56 feat(eda): sources own signing, with UUIDv7 paths and approved unsigned option
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.
2026-09-24 14:26:21 +10:00
sam 7d02351442 Merge branch 'worktree-agent-a88b86b51f454341b' into worktree-giggly-marinating-lamport 2026-09-24 14:21:53 +10:00
sam 79b352dc44 feat(eventtype): infer event types from captures and gate dispatch on identification 2026-09-24 14:21:20 +10:00
sam a31ac8f675 Merge branch 'worktree-agent-a2b33953bdffebf56' into worktree-giggly-marinating-lamport
# Conflicts:
#	docs/data/generated/dev-docs.json
#	internal/app/archied/state_store_pool.go
2026-09-24 10:06:00 +10:00
sam 970a65fe36 feat(archied): serve the State Store, event store and Gateway conversations from Postgres
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.
2026-09-24 10:01:54 +10:00
sam 9f5f072fe7 Merge branch 'worktree-agent-a091696d945ed3377' into worktree-giggly-marinating-lamport
# Conflicts:
#	cmd/archie-state-store/recovery.go
2026-09-24 09:56:10 +10:00
sam 42dcc80754 feat(state-store): one-time import of the legacy SQLite stores into Postgres
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.
2026-09-24 09:45:26 +10:00
sam b39f7c682f feat(postgres): whole-database backup and offline restore on pg_dump/pg_restore
Restore claims every service role (state-store and gateway) non-blockingly
and refuses if any is held or the claim cannot be checked; it drops tables a
later migration added before pg_restore --clean so a restored schema matches
the snapshot. Backup validates the archive before replacing the previous one.
Ports the store's write-side clip, park-class and transition-audit coverage
from internal/store.
2026-09-24 09:32:39 +10:00
sam 922fbf5696 fix(postgres): lock keys follow D3.7/D4.3; event reader never sees a later id before an earlier one 2026-09-24 03:23:38 +10:00
sam 51836297b4 feat(postgres): event inserts take a transaction advisory lock so ids commit in order 2026-09-24 03:01:41 +10:00
sam a71d062b4a feat(postgres): State Store claims serve ownership with a session advisory lock 2026-09-24 02:57:38 +10:00
sam 972355fc63 refactor(postgres): resources and statestore tests use storecontract, not internal/store 2026-09-24 02:47:06 +10:00
sam 850b588777 style(postgres,gateway): adopt task fmt rewrites from the lane merge 2026-09-24 02:41:34 +10:00
sam b41161e0df fix(postgres): one isUniqueViolation after merging the EDA and status lanes 2026-09-24 02:33:52 +10:00
sam a5cc0acb86 Merge branch 'run/pg-w2-5' into worktree-giggly-marinating-lamport
# Conflicts:
#	internal/infrastructure/postgres/postgresdb/models.go
2026-09-24 02:31:06 +10:00
sam 0335beabae Merge branch 'run/pg-w2-3' into worktree-giggly-marinating-lamport 2026-09-24 02:30:51 +10:00
sam c833081544 feat(postgres): port events/identities/status surfaces, fix shipped defects
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).
2026-09-24 02:17:44 +10:00
sam 6d0b817b2c feat(postgres): port EDA store to Postgres (captures, mappings, bindings, ledgers, tool_calls)
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.
2026-09-24 02:17:31 +10:00