Commit Graph
16 Commits
Author SHA1 Message Date
sam 3960a00f5d Feat/org epic (#1634)
* fix(postgres): scope OpenPRs to the caller's org

A principal-carrying caller read every org's pr_open tasks. The query now
honours the request scope; the daemon's unscoped review scan still sees all
orgs.

Issue: archie-core-kgxw.23

* fix(statestore): serve task logs only to the task's org

ReadTaskLog and StreamTaskLogContent took a task ID and read the file with
no org check. The State Store's task-log reader now confirms the task is
visible under the caller's scope first; unscoped services read as before.

Issue: archie-core-kgxw.24

* fix(postgres): scope ListPolicies to the caller's org

Every org's policy text reached any principal-carrying caller. A scoped read
now sees its own org's policies, plus instance policies when scoped to the
system org. The engines and the lockout guard decide for every org, so they
read the full chain unscoped: the dashboard engine loads without the
request's principal and the guard lifts the caller's scope.

Issue: archie-core-kgxw.25

* fix(postgres): scope identity reads to the caller's org

ListIdentities and GetIdentity (and its alias fallback) returned every
identity to any caller. A caller scoped to an org now sees only that org's
members and assigned agents; the system org and unscoped services still see
the whole instance.

Issue: archie-core-kgxw.26

* fix(postgres): hide instance status from other orgs

ListPresence, ListChannelStatus, ListApplyStatus and GetConfigSnapshot
answered any org principal with instance-wide state. They now return nothing
unless the request is unscoped or scoped to the system org. The dashboard
reads the published config as itself, since its handlers project it for
callers of every org.

Issue: archie-core-kgxw.27

* feat(postgres): assign new agents an org and role at creation

A bot or service account created through the API served no org until the
next State Store boot granted it one. Create now assigns it to the org the
request acts in with the developer role in the same transaction, so it is
authorized immediately.

Issue: archie-core-kgxw.14

* feat(edastore): create event records in a chosen workspace

Sources are created in a workspace of the caller's org, the default one when
none is named; event types and bindings take their source's workspace and
mappings their event type's, the same rule the org backfill applied. The
binding, mapping and event type contracts carry the workspace, the four list
endpoints accept ?workspace=, and the Events page has a workspace selector
that filters every step and picks where a new source goes.

Issue: archie-core-kgxw.11

* feat(webui): authorize a record in its workspace

The API built every access request with no workspace, so workspace
policies and per-workspace roles never applied. A request naming a source,
binding, mapping, event type or task now reads the record's workspace under
the caller's scope and authorizes in it; tasks carry their workspace on the
State Store contract for this.

Issue: archie-core-kgxw.9

* feat(access): expose workspace environment to policies

Policies can test resource.workspace.environment. The workspace attribute
is the workspace entity, which carries its environment; the principal
brings its org's workspaces from the State Store, so the dashboard and the
daemon's run checks describe a resource's workspace without another lookup,
and the daemon now authorizes runs in the task's or binding's workspace.

Issue: archie-core-kgxw.10

* fix(webui): ask read_secret when a source secret is read

Rotating a source's secret returns its value, but the route asked update,
which every developer holds, so no policy could narrow who reads a secret.
It now asks read_secret on the secret, which the shipped roles give admins
and an object policy can narrow further.

Issue: archie-core-kgxw.17

* refactor(org): delete the unused upgrade-incomplete sentinel

Nothing returns org.ErrUpgradeIncomplete: the State Store finishes the org
upgrade before it serves.

Issue: archie-core-kgxw.18
2026-10-12 03:24:04 +11:00
sam 0788f5ab8a feat(eda): pause and resume a binding; resuming goes back through approval 2026-10-05 20:44:25 +11:00
sam 20d5624840 refactor: cut remaining long comments down to what the code does 2026-10-03 22:06:57 +10:00
sam 96e5d7b84b 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.
2026-10-03 21:47:46 +10:00
sam 15e64d3de2 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 47fae672f1 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 bbaca2a39d 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 879d87831c 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 684ec1263a 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 d180e624d9 fix(bindings): a new binding is created pending approval
Nothing moved a binding out of draft except an unrelated edit, so a newly created binding could not be approved and the dashboard showed no Approve button. Draft is removed; existing draft rows are promoted to pending_approval when the EDA store opens.
2026-09-23 23:13:49 +10:00
sam ba52a34d83 feat(edastore)!: move event capture and bindings onto PocketBase collections
The event-capture tables (captures, mappings, bindings, binding_dispatches,
playbook_dispatches) now live in PocketBase-owned collections and their ids
are opaque record ids rather than autoincrement integers. The task lifecycle
stays on SQLite: tasks/transitions/events carry FIFO claim ordering, id-cursor
pagination and the task-grant map, none of which gain anything from being
hand-editable. binding_dispatches.task_id is the single seam and stays an
integer addressing that store.

BREAKING: CapturedEvent.Id, Mapping.Id, Binding.Id and Binding.MappingId are
strings on the wire, as are the ids in the capture/mapping/binding requests.
RecordDispatchRequest.task_id is deliberately unchanged.

What the collections buy, beyond storage: a payload nobody has modelled yet is
inspectable, a mapping is editable at runtime, and a binding's relation to its
mapping is enforced. The old schema declared no FOREIGN KEY on that link, so a
dangling mapping_id was previously possible and is now refused.

Behaviour preserved deliberately, each recovered from the SQLite version
rather than reimplemented from memory:
  - draft -> pending_approval -> armed, with approval only from
    pending_approval and an edit always returning a binding for re-approval
  - one binding per source, guarded on insert, update and approve
  - an empty secret on update keeps the stored one, so an edit form that does
    not echo it back cannot silently disarm a binding
  - ErrMappingNotFound / ErrBindingNotFound on a missing delete target
  - sentinels are re-exported from storecontract, never redefined: staterpc
    matches on exact canonical message to rehydrate them, so a second
    definition would break errors.Is across the wire invisibly

Two implementation notes worth keeping:
  - at-most-once dispatch is now a unique index rather than INSERT OR IGNORE.
    Only the unique-violation maps to ErrAlreadyDispatched; any other save
    error is returned, because treating them all as "already recorded" would
    turn the ledger into a silent at-least-once dispatcher.
  - captures store received_at themselves at nanosecond precision in a
    fixed-width layout. PocketBase autodates are millisecond and record ids
    are random, so same-millisecond captures would otherwise order
    arbitrarily; the old store got insertion order free from autoincrement.
  - ListUndispatchedCaptures is raw SQL: the anti-join is a subquery and
    PocketBase's filter DSL is not SQL. A read fires no hooks either way.

Adds tool_calls, which had no persistence at all: tool calls only ever reached
the on-disk task log, readable as text but never queryable or watchable.
Nothing writes it yet.

The binding secret cipher moves with the bindings it protects.
2026-09-23 02:19:28 +10:00
sam 41ad0d48ec refactor(binding): delete dead Matcher.Overlaps method
DELETE: no document in docs/architecture/ or docs/prds/ specifies a
consumer for binding.Matcher.Overlaps, and it has no caller or test
caller. The store enforces the overlap invariant with its own SQL
(internal/store/bindings.go InsertBinding/UpdateBinding), which is out
of this lane's ownership and left untouched. The doc comment's
empty-Source rule is already covered by Binding.validateCommon's
"matcher.source is required" check, so nothing needs moving.
2026-09-15 13:12:22 +10:00
sam 89c74d7097 refactor(archied): move webhook capture intake to the process that owns work intake
The dashboard's POST /webhooks/capture/{source} handler becomes
internal/infrastructure/captureintake.Receiver, mounted by the daemon on
the same bypass mux through webui.Server.CaptureIntake; the dashboard
keeps only the GET /api/captures read and the mapping preview's scan
window. The UI process now mounts no intake route at all instead of one
that answers 503 (archie-core-8cda.5.4).
2026-09-10 00:35:14 +10:00
sam 912db8f590 fix(binding): split ValidateForUpdate so edits can preserve the secret
Real bug found via browser-testing the new bindings UI (t2db.8):
UpdateBinding's own store-layer contract documents that an empty
Secret means "preserve the existing one" (COALESCE against NULLIF),
but handleBindingUpdate validated with the create-time Validate(),
which unconditionally requires a full-length secret -- rejecting the
exact "leave blank to keep it" edit flow the store was built to allow.

Root-cause fix, not a UI workaround: Binding.Validate() (create,
unchanged, still requires a real secret -- there's nothing to fall
back to on insert) now delegates shared field checks to a private
validateCommon(); a new ValidateForUpdate() reuses the same checks but
only enforces the secret-length floor when the caller actually
supplied a new one. handleBindingUpdate now calls ValidateForUpdate.

3 new domain tests + 1 new API-layer test pin: empty secret accepted
on update, a genuinely-short new secret still rejected on update,
empty secret still rejected on create.
2026-09-03 06:17:43 +10:00
sam 7705fda777 fix(binding): add Owner/Repo pin, fixing multi-repo dispatch
Root-cause fix for the correctness gap named in archie-core-t2db.8:
resolveBindingRepo refused to dispatch with zero or multiple configured
repos, meaning a multi-repo deployment could never use bindings at all.

- binding.Binding gains optional Owner/Repo fields; Validate rejects
  setting only one (a pin is a complete pair or not a pin at all).
- Persisted as new owner/repo columns (NOT NULL DEFAULT '', additive --
  no migration needed since bindings is a CREATE TABLE IF NOT EXISTS
  with no existing deployment yet).
- resolveBindingRepo now takes the binding: a pinned binding dispatches
  to its own owner/repo unconditionally; an unpinned binding keeps
  today's single-configured-repo fallback (0 or 2+ repos still refuses,
  unchanged -- verified by a dedicated regression test, not just
  assumed preserved).
- Wired through the API request/response shape (create/update accept
  and return owner/repo); no repo-existence validation against config
  added -- smallest workable change, not the named bug.

Red-green throughout: 8 new tests across domain/store/daemon/webui
layers, each proven to fail before the corresponding implementation
step. Zero regressions in existing binding/dispatch test suites.
Dashboard UI to expose this (the other half of t2db.8) is unstarted --
this closes the backend correctness gap only.
2026-09-03 04:38:45 +10:00
sam 543c10ac9a feat(webui): playbook bindings -- matcher + mapping + workflow, HMAC-gated
Implements archie-core-t2db.4: the runtime-editable binding entity that
turns a captured webhook into an archie task, plus the per-source HMAC
verification at handleCapture that makes t2db.5's 'unauthenticated event
cannot trigger a binding' invariant structurally enforceable.

Captures, mappings and bindings are now separate concerns on the same
single *store.Store; the new BindingStore / BindingDispatcher /
BindingTaskCreator split keeps each interface under the interfacebloat
limit (8 methods).

State machine: draft -> pending_approval -> armed; any edit on an armed
binding drops it back to pending_approval, enforced in SQL via
status='pending_approval' on UPDATE so the rule cannot be bypassed by a
direct status field in the request body. Approve is the only sanctioned
transition into armed (WHERE status='pending_approval' guard).

Overlap: two bindings may not share a source in any status; enforced at
InsertBinding and UpdateBinding (transaction-local SELECT). Approve has
a separate TOCTOU guard so a race between Insert and Approve cannot
// bypass the check.

HMAC at handleCapture: reads X-Hub-Signature-256 (then X-Signature-256)
// fallback, verifies via webhookguard.VerifyHMAC against the binding's
// per-source secret, marks CapturedEvent.Authenticated=true on match.
// Captures with no armed binding, missing signature, or wrong signature
all persist as authenticated=false -- the dispatch loop's
binding.Matcher.Matches gate (requires authenticated) is what stops
them from spawning a task. Two armed bindings for one source returns
409 at capture time as a belt-and-braces TOCTOU guard.

Dispatch loop: added Daemon.dispatchBindings, called from both Cycle
and maintainAndDrain between poll and drain. Walks
captured_events where authenticated=1 AND source IN armed bindings
AND id NOT IN binding_dispatches, runs the binding's matcher, resolves
the mapping, enqueues a chat-style task with binding_id /
// binding_version provenance stamped in the same transaction as the
// row insert. The binding_dispatches ledger (composite PK on
(binding_id, capture_id)) is the at-most-once guarantee across cycles
// and daemon restarts.

Tasks schema migration: binding_id INTEGER NOT NULL DEFAULT 0 +
binding_version INTEGER NOT NULL DEFAULT 0 (taskSchemaVersion bumped
1 -> 2). Existing tasks keep 0 / 0.

Out of scope (documented follow-ups):
- secret encryption at rest (plaintext today)
- full dashboard HTML for the binding editor (CRUD API only this bead)
- per-binding rate limits (existing per-remote-address limit applies)
- binding.Owner / binding.Repo fields (dispatch falls back to the
  single configured repo; multi-repo deployments log and skip)
2026-09-02 23:09:25 +10:00