Compare commits

..
150 Commits
Author SHA1 Message Date
sam 26e19f3de4 feat(governance,connectors,ui): identify model providers and keys by UUID (#2129) 2026-11-24 06:52:58 +11:00
sam c5591d95da feat(judgement,approvals): link decisions and approval requests by action_type_id (#2130) 2026-11-24 06:23:19 +11:00
sam 1c10378a40 refactor(events,proposals,runs,ui): rename declared event type fields to declared_event_type (#2128) 2026-11-24 06:19:35 +11:00
sam efe7069bc1 feat(events,proposals,ui): identify triggers by immutable UUID (#2126) 2026-11-24 05:36:52 +11:00
sam 67ce2901a5 feat(runs,events,ui): identify workflows by immutable UUID (#2125) 2026-11-24 05:20:18 +11:00
sam 21d1d2e8bf docs: add design system and product specs
- Add DESIGN.md and .impeccable tokens/config for the Archie design system
- Add PRODUCT.md capturing platform, users and positioning
2026-11-24 04:52:58 +11:00
sam dd57e6563a docs: use active voice across rules, docs and prompts
Fix every Google.Passive finding in the tracked tree: 161 reports across 24 files, including the AGENTS.md symlink duplicate. Vale at suggestion level now reports none. Every rule, invariant, prompt instruction, placeholder and technical claim is preserved.
2026-11-24 03:42:29 +11:00
sam da941f05aa docs(ui): use active voice in the UI rules
Vale suggestion level is now clean for the file. The same pass replaced the e.g. abbreviations, removed the first-person asides, and replaced the anthropomorphic 'sees'.
2026-11-24 03:34:52 +11:00
sam 9c04b74e6f docs: fix Vale prose findings across comments, docs and prompts
Run Vale over every tracked Go, Markdown and template file and fix the remaining findings: long sentences, repetition, UI verbs, identifiers that should be backticked, and migration narration in comments.

AGENTS.md and CLAUDE.md keep their absolute rules; the prompt heuristic against repeated absolutes is disabled for rule files.
2026-11-24 03:26:16 +11:00
sam 152e7b4d2f chore(ui): add proposals to the page catalogue (#1995) 2026-11-24 03:11:35 +11:00
sam 911152c9d1 merge: proposals module (#1995)
# Conflicts:
#	internal/platform/pg/migrations/00008_drafts.sql
#	modules/drafts/drafts.go
#	modules/drafts/internal/store/store.go
2026-11-24 03:11:07 +11:00
sam 0d25c93ea0 merge: event source IDs and scopes (#2127, #2027)
# Conflicts:
#	api/openapi.yaml
#	modules/events/events.go
2026-11-24 03:09:12 +11:00
sam bed51c4bd1 merge: connector packages and scoped installations (#2027) 2026-11-24 03:08:52 +11:00
sam f24c2b4455 feat(connectors): separate packages from scoped installations (#2027)
Packages are accepted once by the instance. Installations configure them at the instance, an organisation or a person; bindings and credentials resolve the person's, then their organisation's, then the instance's. Decisions, approval requests and held chat actions record the installation and scope that acted.

The dashboard lists packages separately from installations, shows every installation's scope, and creates, edits and disables installations at their scope.
2026-11-24 03:05:27 +11:00
sam 2ae793cc94 feat(ui): replace the drafts page with proposals (#1995) 2026-11-24 02:44:31 +11:00
sam b47e98e25f feat(proposals): add the proposals module and fold drafts and memory proposals into it (#1995) 2026-11-24 02:44:31 +11:00
sam 8265e99466 feat(runs): run an approved proposal's actions in a durable workflow step (#1995) 2026-11-24 02:44:31 +11:00
sam 30aa351eb6 feat(events,drafts): give sources an immutable id and a scope (#2127, #2027)
A source is keyed by a uuid, owned by the organisation or one person, and
labelled within that scope. The webhook path is a separate unique column, so
renaming either leaves stored events, event types, triggers, groups, mappings
and drafts alone. Delivery policies, sealed secrets and group keys use the id.
2026-11-24 02:43:51 +11:00
sam 7e701f9a50 feat(pg): add alerts, proposals, audit log, invites, chat limits and connector installations to the baselines (#2025, #1995, #2019, #2110, #2074, #2075, #2124, #2027) 2026-11-24 02:28:56 +11:00
sam 4a9f30ef04 fix(judgement,runs,approvals): record immutable identity IDs for attribution (#2122) 2026-11-24 02:23:23 +11:00
sam eb4136ffe6 chore(pg): squash module schemas into baseline migrations 2026-11-24 02:23:23 +11:00
sam 383d7d6dad chore(vale): configure Vale prose linting and house rules 2026-11-24 02:02:00 +11:00
sam dad6924a0c docs: normalise Australian English and prose across comments and docs 2026-11-24 02:02:00 +11:00
sam de05bc2cbd feat(runs): show each step's summary and target on the run page
- a finished top-level step records its summary and target in a done marker; stages return them
- a message step's summary is the message, and its target the channel and chat
- the trail no longer lists the engine's markers as entries
- run page: short run ID in the breadcrumb, copyable IDs, version badge, step rows from stages, No output for an empty result
- event detail: No payload for an empty body, and links only the dispatches that started a run
- ui/AGENTS.md lists the components that exist
2026-11-24 00:04:20 +11:00
sam 2bfb262e9c docs(judgement,events): state comments plainly 2026-11-23 23:46:27 +11:00
sam 0ad4374a2a refactor(judgement): rename action classes to action types and raises to autonomy proposals
- tables judgement.action_types, action_type_resets, action_type_approvals and autonomy_proposals (migration 00063)
- governance setting propose_autonomy_after, approval request kind autonomy, policy resource kind action_type
- /api/action-types replaces /api/classes; the detail lists autonomy_proposals
- an autonomy proposal stores the identity ID of the account that answered it
2026-11-23 23:43:45 +11:00
sam 7f5220dea3 feat(events): record failed, denied and disabled trigger outcomes (#2117)
- a mapping failure is recorded as failed, with the value found at each mistyped path
- an access policy refusal and a disabled workflow are recorded as denied and disabled
- migration 00062 renames existing skipped dispatches to failed
2026-11-23 23:35:35 +11:00
sam 4b60033429 docs: clarify decision and attribution guidance
- clarify that existing codebase patterns also count as decisions not to ask about
- add guidance that foreign keys reference immutable primary IDs, with labels stored separately only for snapshots
2026-11-23 23:32:40 +11:00
sam 062336db91 refactor: rename denial records to access decisions
- rename governance.access_denials table, indexes and API types via migration 00061
- expose /api/access/decisions and decisions payload; keep audit auth unchanged
- rename UI store, page and route from denials to decisions
2026-11-23 02:03:35 +11:00
sam 60d9b6b7aa feat: record access decisions, not just denials
- add an outcome column and migration so allowed and denied decisions share one audit trail
- fail closed when an allowed decision cannot be recorded
- expose outcome filtering in the API and dashboard

Route chat through the recording authorizer so its decisions are audited too.
2026-11-23 01:00:46 +11:00
sam e1ada94d78 fix: redact link codes and guard shipped policies
- redact single-use link codes from stored account.link events after handling, with a migration to scrub existing rows
- refuse deletion of shipped org policies and hide the delete action in the UI
- validate agent step models against the workflow model policy at save time, including the default model
2026-11-23 00:38:54 +11:00
sam 8c267b6edd feat: record skipped dispatches and approver ids
- store trigger dispatches as started or skipped, with a JSON reason surfaced in the API and UI
- persist the answering account's identity id beside its display name for approvals and judgements
- save connector acceptances and their declarations in one transaction so a refused change stores nothing
2026-11-22 23:24:30 +11:00
sam 33f7ebdff4 feat: add member candidates endpoint and approvals page
- serve active identities outside the org at /api/orgs/{id}/member-candidates and back the members page from it
- add an org approvals page for default owner, deadline and escalation path over /api/settings
2026-11-22 23:03:01 +11:00
sam e801306c15 docs(deliveries): say what each field, lease and refusal does 2026-11-22 22:31:55 +11:00
sam 4707427759 feat: trust configured proxies for webhook intake
- add trusted proxy settings, migration, API, and UI
- derive client addresses from X-Forwarded-For behind trusted hops
- enforce delivery policy for listener batches and record denials
2026-11-22 22:29:36 +11:00
sam faeaa0d7f0 fix: deny orgs without active org policies
- refuse authorization when an org has no stored org-level policies instead of falling through the narrowed chain
- seed tests with shipped org policies and cover the deny-by-default cases
2026-11-22 22:19:07 +11:00
sam 240dc52226 chore: remove technical-prose-cleanup skill 2026-11-22 20:02:26 +11:00
sam 7f89b03507 chore(ui/settings): delete the unused forge connection card (#2063) 2026-11-22 15:44:17 +11:00
sam 787a213db6 Merge branch 'main' into worktree-agent-ac0944b265396932d
# Conflicts:
#	modules/governance/accounts_api.go
2026-11-22 15:42:43 +11:00
sam 3e4b020311 feat(ui): extensions and models pages run on the binary's API (#2063) 2026-11-22 15:41:44 +11:00
sam 51a1cf5128 feat(governance): model aliases resolve through providers with a policy (#2063) 2026-11-22 15:41:40 +11:00
sam d9e993e2b9 feat(connectors): install and update extensions from a signed catalogue (#2063) 2026-11-22 15:41:33 +11:00
sam de3bfe296d refactor(runs): adopt go fix output in the workflow catalogue test (#2061) 2026-11-22 13:54:09 +11:00
sam 53719c6859 fix(ui/workflows): a deleted workflow is not written back and a started run is followed (#2061) 2026-11-22 13:54:09 +11:00
sam 456c08751a refactor(ui/workflows): read triggers from the binary's API (#2061) 2026-11-22 13:54:09 +11:00
sam 07d14c8d50 merge main into the workflow editor branch (#2061) 2026-11-22 11:48:30 +11:00
sam c1b4ba2b6b wip(ui/workflows): visual editor on the binary's API (#2061) 2026-11-22 11:48:13 +11:00
sam 84284d59c3 refactor(events): split trigger firing and target checks to keep complexity in bounds (#2062) 2026-11-22 11:47:32 +11:00
sam 5c8fb901f9 feat(ui/events): captures, mappings and bindings run on the binary's API (#2062, #2098)
The Capture, Map and Bind steps read the module's captures, event types,
mappings and triggers. A binding is a trigger bound to an event type; the
sources panel creates HMAC sources and shows each delivery's verification
result. The workspace filter is removed: the binary has one workspace per
organisation and the data carries none.
2026-11-22 11:46:02 +11:00
sam 501338ffbd fix(events): a delete blocked by a restricting reference answers 409 (#2062) 2026-11-22 11:46:02 +11:00
sam 61f576a25c feat(events): capture, event types, mappings and trigger approval on the binary (#2062, #2098)
Event types, field mappings and the stored-delivery inspector move into
modules/events: copied from internal/domain/eventtype and
internal/domain/mapping, which the old services still import. Each stored
event records how its delivery was verified; a source that checks nothing
refuses deliveries until approved; triggers gain approve, pause, resume,
event-type and mapping binding, dispatch history and delete. The captures,
mappings and bindings sections are reported as served.
2026-11-22 11:39:46 +11:00
sam a5826156a3 feat(runs): filter runs by workflow and name each tool call in a trail entry (#2061) 2026-11-22 11:36:08 +11:00
sam 682995bdf7 feat(runs): workflow drafts, publish with an expected version, delete, enabled flag, run on demand, run stages and statistics (#2061, #2113, #2098)
A disabled workflow is never started by a trigger, another workflow or a
person. Delete is refused while a trigger, another workflow or a run in
progress names it. A parked or ended run restarts from a step.
2026-11-22 11:34:49 +11:00
sam 9c0d043b57 fix(ui): list only organisation pages in the organisation sidebar (#2023) 2026-11-22 11:26:23 +11:00
sam aefe2b81e9 Merge branch 'main' into worktree-org-config
# Conflicts:
#	ui/src/schedules/SchedulesPage.vue
2026-11-22 11:24:30 +11:00
sam eadb88d3bf feat(governance): serve the organisation's instructions to every agent (#2023)
The organisation's standing instructions are stored per organisation and
join the system prompt of chat turns and workflow agent steps. The Org
configuration group is served: schedules, alert webhook, playbooks,
models, connections and credential bindings open the page that already
owns the concept.
2026-11-22 11:24:25 +11:00
sam 8b9f5b2c60 Merge branch 'worktree-agent-ac438bec8bd1f2684' 2026-11-22 11:21:44 +11:00
sam a420b742e8 fix(events): save token and none sources with an empty secret instead of NULL (#2112) 2026-11-22 11:21:28 +11:00
sam bc56b71539 Merge branch 'main' into worktree-agent-a6a4a1df2423fa389 2026-11-22 11:18:05 +11:00
sam a1347dbfc8 fix(ui/data-table): keep the growing column readable and hide secondary columns on narrow screens (#2023) 2026-11-22 11:18:04 +11:00
sam 34c97ce8e8 chore(ui): regenerate the page catalogue for the Status page (#2023) 2026-11-22 11:17:23 +11:00
sam bd212ec9ac Merge branch 'worktree-agent-a521e2c3ea8457fdc'
# Conflicts:
#	modules/governance/accounts_api.go
2026-11-22 11:16:42 +11:00
sam 037ab0623a feat(ui): serve Home and Status from the binary's health, approvals and runs (#2023) 2026-11-22 02:44:14 +11:00
sam 9aceaa15bc feat(system): report module, connector and runner health and what waits on a person (#2023) 2026-11-22 02:44:13 +11:00
sam 0a2aeb65ce feat(ui): members, policies and denials pages use the binary's access API (#2023) 2026-11-22 02:43:06 +11:00
sam 5004e8b40b feat(governance): serve members, access policies and denials (#2023) 2026-11-22 02:43:06 +11:00
sam 9c5af2c2d3 feat(ui/events,settings): give the event, source, trigger, model, credential and extension lists the original layout (#2023)
Tables use fixed column widths and the ghost add button. The models page
keeps the aliases section with one inline row per alias.
2026-11-22 02:36:13 +11:00
sam f8c572ebef feat(ui/controls): split the controls page into rules, guards and action classes (#2023) 2026-11-22 02:34:14 +11:00
sam e72d9313e2 feat(ui/runs): compose the runs list and run page from the workflow list patterns (#2023)
The list has a filter and a right-click menu, an error column and
fixed widths. The run page merges its details and where the run came from,
and leaves out sections that have nothing in them.
2026-11-22 02:33:37 +11:00
sam f4bfa59dec feat(ui/workflows): restore the workflow list and page on the archie binary (#2023)
The list and page keep the original layout and read the binary's API.
Duplicate triggers are grouped. Runs and run pages use the shared table.
The older editor stays on its hidden route as WorkflowEditorPage.
2026-11-22 02:32:12 +11:00
sam a54654b0c8 fix(ui/data-table): lay out columns at fixed widths with middle-aligned rows (#2023)
Columns take a width from their definition, the first one takes the rest,
and a column can hide below a breakpoint. Rows may carry a right-click menu.
2026-11-22 02:32:12 +11:00
sam 81dcc7d94e fix(ui): let a pending channel link code be cancelled (#2095) 2026-11-22 02:23:25 +11:00
sam e3130d53e7 Merge branch 'worktree-agent-a82ec64b6cc1a2809'
# Conflicts:
#	internal/app/archie/operations.go
#	modules/events/events.go
#	modules/governance/accounts_api.go
#	modules/governance/governance.go
2026-11-22 02:16:56 +11:00
sam 098d8cc328 feat(runs): authorize runs, deliveries and intake as the workload principal (#2078)
Trigger dispatch, run start, every run claim, every delivery attempt and
webhook intake now ask the policy chain. Background work acts as the
workload principal; a refusal is final and recorded on the run or the
delivery, and an undecidable chain leaves the work queued for another
attempt. Intake applies the per-source delivery policy after source
verification.
2026-11-22 02:15:05 +11:00
sam 6c59d6b742 feat(httpapi): refuse every API operation that does not declare its access (#2078)
Operations register through httpapi.Register with Public, Authorized or
AdminAuthorized, and the guard asks the policy chain for the declared
action and resource kind before the handler runs. An undeclared operation
and an undecidable chain are refused. The workload principal, its shipped
policy, a self-service policy and Recording for denials are added in
governance.
2026-11-22 02:15:02 +11:00
sam 1a0c697858 Merge branch 'worktree-agent-a124e124e24c6a56b' 2026-11-22 02:13:32 +11:00
sam 65a8b7cd47 Merge branch 'worktree-agent-a559cecce669715a6' 2026-11-22 02:13:32 +11:00
sam 970fb2ab84 feat(ui): link channel accounts from the account page and remove the People page (#2095) 2026-11-22 02:13:08 +11:00
sam e127b2b05d feat(approvals): gate answers by role and link channel accounts through single-use codes, replacing the people model (#2095) 2026-11-22 02:13:08 +11:00
sam 02227a0b22 feat(connectors): let a connector declare it links accounts and return the link URL for a code (#2095) 2026-11-22 02:13:08 +11:00
sam 9c0ea938b8 fix(chat): canonicalise a held action's stored input before comparing it (#2072, #2096)
The binding is read back from a jsonb column with a space after every colon,
so an unchanged approved action failed the byte comparison and never ran.
2026-11-22 02:09:32 +11:00
sam 763cd0e581 feat(governance): delete a model or alias from /settings/models (#2090) 2026-11-22 02:03:24 +11:00
sam 48d0212784 style: fix gofmt alignment for maxBackoff 2026-11-21 23:18:43 +11:00
sam f6e9d48da6 fix(chat): mount the model list only while it is open
reka-ui mounts every item of a closed Select to resolve the selected label, so opening the More menu rendered the whole model catalogue first. With 400 models the menu took about 400 ms to open; it now takes about 30 ms.
2026-11-21 22:36:30 +11:00
sam 46238afd62 chore(ui): regenerate the page catalogue for the People page (#2072) 2026-11-21 21:38:39 +11:00
sam 4b494bf75b feat(approvals): add a People page, leave channel approvals unchanged, make a binding's target optional (#2072) 2026-11-21 21:37:42 +11:00
sam b9a60e03a3 feat(chat): bind held-action approvals to the whole action and require fresh passkey confirmation for irreversible ones (#2072) 2026-11-21 21:35:27 +11:00
sam bc72655c8e feat(judgement): refuse privileged and undeclared actions in chat (#2071)
Connector actions and lookups now declare privilege change and secret access,
and an MCP server declares both per installation. Chat withholds and refuses
any tool that has either effect or declared nothing, in judgement and at
execution, so an approval cannot convert the refusal. Workflows and the
dashboard are unchanged.
2026-11-21 21:28:06 +11:00
sam 592d36e0d1 feat(connectors): re-check saved workflows on capability change; validate core delivery schemas (#2091, #2092)
When a connector loads with new declarations, the saved workflows that
reference it are re-checked against them (via a Recheck hook wired to
runs.Engine.RecheckConnector); if any would become invalid, the new
declarations are refused and the connector fails to start, so the breakage
surfaces at update time instead of mid-run. The previous declarations stay
in force.

A connector that declares the message or chat_message delivery now has its
declared input schema checked against every payload shape core sends on it
when it loads; a rejecting schema fails the connector. The delivery names
are exported from the connectors module and used by core's senders, so the
contract has one definition.
2026-11-21 18:34:47 +11:00
sam d318f912a8 fix(runs): cancel a run from the API and the dashboard (#2088)
POST /api/runs/{id}/cancel now reaches Engine.Cancel, which cancels the
run and the runs it started with workflow.call, and returns the run.
Cancelling a run that has already ended is refused with a 409, and a run
from another organisation is not found. The run page shows a Cancel
action for a run that has not ended.
2026-11-21 18:21:31 +11:00
sam 31b2827048 fix(connectors): read a connector's capabilities before it has ever loaded (#2087) 2026-11-21 17:32:20 +11:00
sam 01fd0fbf97 fix(pg): drop the runs state check by the name Postgres gave it 2026-11-21 17:26:02 +11:00
sam 9c0da07807 Merge branch 'worktree-agent-af2ebbb817db9f5f2' 2026-11-21 17:14:35 +11:00
sam 14060675cd feat(connectors): check workflow and trigger references against declared capabilities (#2087) 2026-11-21 17:14:00 +11:00
sam 74928925c8 Merge commit '35e2a216a' 2026-11-21 15:20:36 +11:00
sam 35e2a216ab fix(runs): refuse a message.send step whose channel can't send to a chat (#2085) 2026-11-21 15:18:16 +11:00
sam b6907d8366 fix(runs): cancel the runs a cancelled run called (#2086) 2026-11-21 15:17:13 +11:00
sam 4b5c60330d docs(runs): plain the call wait comment (#2044) 2026-11-21 15:00:21 +11:00
sam 69b5b2aba6 Merge branch 'worktree-agent-aa1d52313cfc167e1' 2026-11-21 15:00:11 +11:00
sam d6f3a1a01d docs(connectors): describe the extension kinds table accurately (#2084) 2026-11-21 15:00:01 +11:00
sam ca279a200a Merge branch 'worktree-agent-a773715d74288076a' 2026-11-21 14:59:56 +11:00
sam 5d8c9303e0 feat(runs): workflow.call, workflow.handoff, workflow.approve and message.send (#2044) 2026-11-21 14:59:49 +11:00
sam 23f23a6cab fix(connectors): refuse to store a contract that has no group (#2084) 2026-11-21 14:59:48 +11:00
sam 64ef2c9af7 feat(connectors): group extensions as platform, integration or agent (#2084) 2026-11-21 14:58:53 +11:00
sam c091d33a44 Merge branch 'worktree-agent-aa841596124924756' 2026-11-21 14:53:51 +11:00
sam 96342c1564 Merge branch 'worktree-agent-ab17a07f2d3e45187' 2026-11-21 14:53:51 +11:00
sam a3132792ea build(wt:check): apply go fix and the formatters before checking 2026-11-21 14:53:45 +11:00
sam 1989948ab3 fix(runs): encode agent prompts and action input with sorted keys (#2083) 2026-11-21 14:53:36 +11:00
sam 2e48acfc92 fix(pg): hold one advisory lock across migration and grants (#2082) 2026-11-21 14:53:17 +11:00
sam 7b6154e7e8 docs(runs): plain the comments on run endings (#2042) 2026-11-21 13:55:46 +11:00
sam 3513dad609 Merge branch 'worktree-agent-a3fd604fba0fb36cc' 2026-11-21 13:55:00 +11:00
sam 84e9116877 build: add task wt:check for checking a worktree's changed packages 2026-11-21 13:55:00 +11:00
sam fb5f3ad472 refactor(runs): run the document's steps in their own function (#2042) 2026-11-21 13:54:34 +11:00
sam a88f5630fe feat(runs): the first step that sets an outcome ends the run (#2042)
Add workflow.finish (completed, parked, waiting_approval, declined). A failed
step parks the run unless it continues on failure, and a parked run retries
from a top-level step, replaying the earlier steps' recorded results. Adds the
retry-run operation and a Retry button on the run page.
2026-11-21 13:52:52 +11:00
sam f47e60db00 refactor(events,deliveries): split source saving and plain the new prose (#2021, #2016) 2026-11-21 13:52:33 +11:00
sam 29a06f7c54 Merge branch 'worktree-agent-a2d0eb6dd8a9d5b66' 2026-11-21 13:47:46 +11:00
sam 30b4c28e06 fix(events): a source save keeps its stored verification (#2021)
A PUT that names no verification keeps the stored scheme, token hash and
sealed secret, and an hmac save with a blank secret keeps the sealed one.
The sources page gains an Edit action that reuses the add dialog.
2026-11-21 13:47:37 +11:00
sam 01eb4aaf7c fix(events): verify webhook signatures before parsing (#2021)
A source now declares how its deliveries prove themselves: token (the
default, unchanged), hmac (HMAC-SHA256 over the raw body, per-source header
and prefix, secret sealed at rest and write-only) or none. The events module
verifies before the connector parses, answers 401 and logs the refusal.

The digest comparison is ported from internal/webhookguard/hmac.go and the
header-borne signature from internal/infrastructure/captureintake/receiver.go;
the old copies stay until their service goes. The seal package moves to
internal/platform/seal so events can seal the secret.
2026-11-21 13:46:48 +11:00
sam b48616798d fix(deliveries): stop retrying a delivery the channel rejects for good (#2016) 2026-11-21 13:45:31 +11:00
sam 073959b4f9 feat(memory): scope chat notes and preserve deletions on restore (#2069)
Keep personal notes private by default and require review before publishing shared notes. Restore backups and replay forgotten notes in one transaction, and retain the installed release when an unattended rollback could bring back forgotten notes.
2026-11-21 13:20:31 +11:00
sam 81bca2251e fix(app): retry startup and atomically seed policies (#2081) 2026-11-21 11:45:18 +11:00
sam 32fbf8b69c refactor(gateway,ui): the page catalogue is generated from the router (#2050)
The assistant's catalogue was a 33-entry literal in Go, hand-maintained beside
the dashboard's routes: eight real pages were missing from it, so page_index
could not name them, and descriptions had drifted where both copies existed.

The routes move to ui/src/router/routes.ts, free of component imports, and
ui/scripts/pages.ts writes the catalogue from them. The nav and page_index now
read the same generated file, and task pages:check fails when it is stale, the
way the proto, sqlc and OpenAPI outputs do.
2026-11-21 03:53:10 +11:00
sam ee66e4f0f3 refactor(prompts): the last three instructions written in Go are files (#2051)
AGENTS.md sends every instruction to a file in internal/prompts, and the
workspace scoping rule, the PR-review adversary mission and the model probe
were the three that still read as Go string literals. The text is unchanged:
the templates render the same bytes the concatenations built.
2026-11-21 03:48:42 +11:00
sam e70c27faf9 fix(configuration): one provider table, so OpenRouter gets an endpoint (#2048)
The provider step wrote class "openrouter", which no ai-sdk class serves and
which egress cannot resolve a host for, so a provider the wizard offered could
never build a model session. The table now names the class that serves each
provider and the base URL it needs where the class has no default, setup writes
base_url with it, and the flag help is built from the same list.
2026-11-21 03:48:28 +11:00
sam ae3bbc6cfe fix(app): serve only setup until the owner setup transaction commits
The binary started connectors, module routes, the starter workflow and the
worker loops at boot whatever the database said, so an instance with no owner
answered operational requests, the bootstrap admin token among them. The
governance module now signals once the bootstrap registration has committed,
and the composition root holds every operational route, connector and loop back
until it does. Liveness stays up and readiness reports the missing owner.
2026-11-21 03:40:02 +11:00
sam 98c0c11cbb feat(chat): track session taint and hold mutations in tainted conversations (#2068)
A conversation gets a persisted tainted flag (migration 00040), set the
first time output from a tool whose declaration trust level is not
"trusted" enters the turn, before that output reaches the model. The
flag is only ever set, never cleared, so later turns and resumed
processes inherit it. In a tainted conversation every non-read-only
action is raised to a floor of propose_and_wait, so the existing hold
path renders the approval card with the exact judged action; read-only
lookups still run, and a hard-rule refusal stays a refusal. An
unreadable taint state or a failed taint write fails closed. Trust
levels live on connectors.Declaration; unknown levels are untrusted.
2026-11-21 03:15:04 +11:00
sam 9af3b29342 fix(dashboard): drop remote images from chat Markdown and add an image-only CSP (#2073)
SAFE_SRC in ui/src/chat/markdown.ts now keeps only same-origin
root-relative paths and data:image/ URLs, rejecting http(s),
protocol-relative and backslash-after-slash forms that the browser
would read as a remote host. The shared parser also covers task
approvals, plans and run transcripts. modules/dashboard sets
Content-Security-Policy: img-src 'self' data: on every non-API
response (page, assets, errors, no-build fallback) as the browser
backstop; the /api/ JSON fallback is unchanged. No proxy, no
migration: stored replies re-render from their text.
2026-11-21 02:52:11 +11:00
sam 96fb0afcd9 feat(chat): offer the model only the tools its person may use (#2067)
Discovery now applies the same per-tool policy decision as invocation: a connector lookup needs read, an action needs run, and each builtin carries the action and resource kind it checks. The model's tool schemas and the system prompt's summaries come from that one filtered set. A name that two declarations, or a declaration and a builtin, both claim is withheld from all of them.

The stream client fixes the wire tools for the whole turn, so a guarded provider re-reads the owner's access and the running declarations before every model request. If an offered tool is no longer permitted or declared, the turn stops before the request instead of describing a stale set. A call to a declaration the registry no longer holds is refused before anything runs, naming nothing.

Memory notes are left out of the prompt when the person may not read settings, so the tool filter is not bypassed by prompt context.
2026-11-21 01:45:03 +11:00
sam 90637aa457 fix(runs): settle held actions a skipped or failed approval would leave
The end-of-run decision read the document's last approval step alone, so a conditional approval that was skipped, or one that continued past a failure, let a run finish without ever putting its held actions to people. Those approvals no longer count as settling. Resume still replays the agent and the request exactly once.

Triggers and dry runs now refuse a document that names an identity or profile, dry runs check required inputs, and step ids cannot contain dots that references read as separators.

The shipped investigate document gains a test that holds an action, suspends, resumes through the journal and reports one approved action.

Refs #2039
2026-11-21 01:20:21 +11:00
sam 0346bfef77 fix(configuration): require containers.image instead of a private-registry default (#2054)
applyContainerDefaults no longer fills containers.image with a hard-coded
private-registry reference. An unset image now fails configuration
validation with 'containers.image is required for autonomous workflow
workers', so a fresh instance is told at startup (and via the readiness
probe at runtime) instead of at the first failed container pull.

Configs that relied on the default now set it explicitly: dev.toml (the
local task image:agent build, which e2e also overlays), plus commented
[containers] blocks in config.example.toml and standalone.toml. The
deploy docs no longer describe a code-level default.
2026-11-21 01:16:41 +11:00
sam b868d450bd fix(ui): leave the older organisation page working without rename support
The dashboard is shared with the retired dashboard service, which reports neither a role nor a revision: the workspace form stays available there, and the rename control and name history appear only where the server serves them.

Refs #2077
2026-11-20 21:12:55 +11:00
sam 064eeab748 feat(governance): let owners rename the organisation and workspaces
Adds the organisation routes the single binary's dashboard needs (list, get, workspace list and create) plus owner-only renames of the organisation and its workspaces. A rename is guarded by the version the caller read, writes only the display label, and appends an actor-attributed event in governance.org_events in the same transaction. The Organisation page shows those name changes, and a deep link is no longer replaced by the landing page while the router is still resolving it.

Refs #2077
2026-11-20 21:10:34 +11:00
sam 904c510246 feat(ui/accounts): ask for setup one thing at a time
Organisation, first workspace and the admin account are separate steps. The
instance URL is no longer asked for: it is the address the operator already
reached, and Settings, authentication already edits it.
2026-11-20 19:32:24 +11:00
samandCopilot cf6108ad14 feat(chat): conversations belong to their person and act with their access (#2065)
Sessions carry an owner; every chat route serves only the caller's own
conversations (others are 404). Each turn and each approved held action
acts as its owner's principal, checked against the access rules before
judgement, so an operator's chat can't do what the operator can't. Chat is
open to any signed-in person, and the stream sends chat updates only to
the owner.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-20 19:05:20 +11:00
samandCopilot 010b964264 chore(ui): delete the binary's separate SPA in ui/src/archie
The Vue dashboard now serves the binary, so archie.html, ui/src/archie
and its client test go.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-20 01:47:20 +11:00
samandCopilot 731417ab48 feat(ui/chat): run the Vue chat on the archie binary (#2023)
Sessions, turns, streamed replies, thinking and tool cards, held-action
approvals and resume now use modules/chat; /api/stream forwards the chat
topic. Sub-features the binary can't back yet stay hidden.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-20 01:45:35 +11:00
samandCopilot 264062866c feat(ui): run events, workflows, runs, controls and settings pages on the archie binary (#2023)
Events (sources, triggers), workflows (list, document, YAML publish,
read-only canvas), runs with approvals and the decision trail, controls
(policies, guards, action classes), agent models, accepted extensions,
secret engines and credentials now read the binary's API. Capabilities
name every section, so pages the binary can't back yet (the visual
workflow editor, captures, mappings, bindings, the extension catalogue,
model aliases and the rest) stay in the tree, hidden. Adds
GET /api/credential-kinds for the credentials form.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-20 01:04:29 +11:00
samandCopilot 59b0ac03c9 feat(dashboard): serve the live stream the Vue dashboard connects to
Same frames as internal/webui/sse.go with a keepalive; signed-in only.
Topics are added as each page moves onto the binary.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-20 00:34:46 +11:00
samandCopilot c12f6b7947 feat(governance): sign in to the archie binary from the Vue dashboard (#2017)
The binary serves the account routes the Vue client already calls: status,
setup, password and passkey sign-in, recovery, sign-out, OIDC, account
passkeys, password and recovery codes, personal tokens and capabilities.
The API authenticates a session cookie, a personal token or the bootstrap
admin token, and unsafe requests pass cross-origin protection. The
dashboard serves the Vue app at /.

Copied from internal/webui/{accounts,passkeys,personal_tokens,
api_capabilities,auth}.go, internal/infrastructure/oidc/{flow,oidc}.go and
internal/app/archieui/account_oidc.go, which archie-ui still imports.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-20 00:30:11 +11:00
samandCopilot 7673e3a135 feat(ui/chat): render Markdown with remark and rehype; remove the React reference
Chat replies, approvals, plans and agent transcripts now parse GitHub
flavoured Markdown with unified (remark-parse, remark-gfm, remark-rehype)
and render the HTML tree as Vue nodes. Raw HTML is dropped, links and
images keep only safe URLs, and #N task references stay linked.

The Astryx React prototype, its dependencies, scripts, theme file and
agent notes are removed.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-19 23:35:31 +11:00
samandCopilot f47aac477a fix(ui/astryx-reference): show runs as short facts with one status indicator
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-19 23:01:57 +11:00
samandCopilot 9e776f23ed fix(ui/astryx-reference): remove internal stage vocabulary from reference pages
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-19 22:33:42 +11:00
samandCopilot 5642058fd0 feat(ui): make the composer the chat with Archie (#2018)
The composer is the chat again: the old dashboard's chat, copied from
ui/src/chat and moved onto the chat module's API. It is the full /composer
page and a dock on every other page, with the session list, session menu,
left, right and floating positions and a full-screen sheet at phone width.
A message carries the page it was asked from and the page's suggested
prompts; a reply streams its thinking, tool calls and text, Stop cancels it,
and a message sent meanwhile is queued by the server. Workflow notifications
and approval requests show in the conversation as cards, and an approval is
answered only with its card's Approve or Deny.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-19 19:43:21 +11:00
samandCopilot cbfcd43018 feat(chat): add the chat module to the archie binary (#2018)
Conversations are the chat module's own tables. A turn is stored before it
is acknowledged, runs after the turns before it in its session, and records
everything it streams, so a reader replays it from a cursor. The agent uses
the configured agent model, the same connector tools as a run and the
dashboard's own reads; every action is judged, and one judgement holds is
put to people through approvals and run once when approved. A restart fails
the turns it interrupted visibly and never restarts a started action.

Conversation memory is a set of notes in the memory module. The chat
prompts are copied from internal/prompts (chat-system.tmpl, soul.md,
session-title.md) into internal/platform/prompts while the gateway still
reads them; the tool parameter redaction is copied from
internal/domain/messaging/tool_parameters.go.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-19 19:40:44 +11:00
sam a0d14090ef feat: add astryx design reference prototype
- scaffold a React/Vite reference app under ui/astryx-reference with shell, composer, runs, and area pages
- wire @astryxdesign packages, a neutral-derived theme, and reference dev/build scripts
- document the astryx workflow in ui/AGENTS.md
2026-11-19 17:36:22 +11:00
samandCopilot 091d117459 feat(ui): use Archie components for activity and approvals
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-19 11:23:15 +11:00
samandCopilot 0807fe6ad6 feat(ui): prioritise recent activity and pending approvals
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-19 11:16:25 +11:00
sam 4db38e0d2a chore: add .codebase-memory plugin to .gitignore 2026-11-19 10:09:54 +11:00
samandCopilot 9e8f160f25 fix(ui): reject unsafe composer admin tokens (#2047)
Validate bearer tokens before header construction and return users to sign-in when a saved token contains unsupported characters.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-19 10:08:59 +11:00
samandCopilot 64dfad6d53 feat(runs): add typed results and model aliases (#2043)
Also fix repository-free message.send validation (#2046) and add a single-binary development smoke path (#1977).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-18 23:47:35 +11:00
646 changed files with 54936 additions and 16882 deletions

No files matched your search

+11
View File
@@ -51,3 +51,14 @@ __pycache__/
.agents-run/ .agents-run/
/.pnpm-store/ /.pnpm-store/
deployments/archie/.build/ deployments/archie/.build/
.codebase-memory/
# Vale synced packages, dictionaries, and grammars (recreated by `vale sync`).
# Local house rules (.vale/styles/Archie/) and vocabulary stay tracked.
/.vale/styles/*
!/.vale/styles/Archie/
!/.vale/styles/config/
/.vale/styles/config/*
!/.vale/styles/config/vocabularies/
/.vale/styles/config/vocabularies/*
!/.vale/styles/config/vocabularies/Archie/
+10
View File
@@ -0,0 +1,10 @@
{
"buildPath": "code",
"hook": {
"enabled": true,
"limits": {
"maxFindings": 5,
"maxChars": 8000
}
}
}
+141
View File
@@ -0,0 +1,141 @@
{
"schemaVersion": 2,
"generatedAt": "2026-11-24T00:00:00+11:00",
"title": "Design System: Archie",
"extensions": {
"colorMeta": {
"signal-sage": { "role": "primary", "displayName": "Signal Sage", "canonical": "#51a580", "tonalRamp": ["#0f2a1e", "#17402e", "#1f5740", "#2e795a", "#51a580", "#7dbf9f", "#acd8c2", "#dcefe5"] },
"signal-sage-deep": { "role": "primary", "displayName": "Signal Sage Deep", "canonical": "#2e795a" },
"signal-sage-ink": { "role": "primary", "displayName": "Signal Sage Ink", "canonical": "#0c6f4d" },
"graphite-card": { "role": "neutral", "displayName": "Graphite Card", "canonical": "#1c1d21", "tonalRamp": ["#0e0f10", "#16171a", "#1c1d21", "#26282c", "#3c3f45", "#70727a", "#a6a39b", "#e8e6e1"] },
"paper-canvas": { "role": "neutral", "displayName": "Paper Canvas", "canonical": "#e9e7e2", "tonalRamp": ["#1f1f1d", "#5c5a55", "#8a877f", "#c7c4bd", "#dcdad4", "#e9e7e2", "#f5f4f1", "#ffffff"] },
"amber-warn": { "role": "tertiary", "displayName": "Amber Warn", "canonical": "#d9a45b", "tonalRamp": ["#3a2a10", "#5c4116", "#8a5a12", "#b5833a", "#d9a45b", "#e5bf87", "#efd7b3", "#f8eddc"] },
"clay-danger": { "role": "tertiary", "displayName": "Clay Danger", "canonical": "#d9776b", "tonalRamp": ["#3d1714", "#5e2420", "#b3413a", "#c75d53", "#d9776b", "#e49d94", "#eec3bd", "#f8e6e3"] },
"slate-info": { "role": "tertiary", "displayName": "Slate Info", "canonical": "#8aa4c2", "tonalRamp": ["#17222f", "#24364b", "#3d5f86", "#6283a8", "#8aa4c2", "#adc0d5", "#cfdae6", "#ecf1f6"] },
"stone-idle": { "role": "neutral", "displayName": "Stone Idle", "canonical": "#9a978f" }
},
"typographyMeta": {
"page-title": { "displayName": "Page title", "purpose": "One per page, in PageHeader beside the page's actions." },
"title": { "displayName": "Title", "purpose": "Card and panel titles." },
"label": { "displayName": "Label", "purpose": "Body copy, rows, navigation, buttons and fields." },
"caption": { "displayName": "Caption", "purpose": "Metadata, column labels, step-type labels and badges." },
"section-label": { "displayName": "Section label", "purpose": "Uppercase group headings in sidebars and settings navigation." },
"micro": { "displayName": "Micro", "purpose": "The smallest annotations, used sparingly." },
"mono": { "displayName": "Mono", "purpose": "IDs, short hashes, durations, log fields and code." }
},
"shadows": [
{ "name": "rest", "value": "0 1px 2px rgba(0, 0, 0, 0.4)", "purpose": "Top bar and canvas nodes at rest (dark). Light: 0 1px 2px rgba(31, 31, 29, 0.06)." },
{ "name": "float", "value": "0 8px 28px rgba(0, 0, 0, 0.4)", "purpose": "Popovers, menus, dialogs and the expanded step node (dark). Light: 0 8px 28px rgba(31, 31, 29, 0.1)." }
],
"motion": [
{ "name": "transition", "value": "140ms cubic-bezier(0.4, 0, 0.2, 1)", "purpose": "Default colour and state transitions." },
{ "name": "node-expand", "value": "200ms", "purpose": "Step node width and shadow when it expands in place." },
{ "name": "reduced-motion", "value": "0.01ms", "purpose": "All animation and transition durations under prefers-reduced-motion or the reduced-motion setting." }
],
"breakpoints": [
{ "name": "sm", "value": "640px" },
{ "name": "md", "value": "768px" },
{ "name": "lg", "value": "1024px" }
]
},
"components": [
{
"name": "Primary Button",
"kind": "button",
"refersTo": "button-primary",
"description": "The one filled action per view.",
"html": "<button class=\"ds-btn-primary\">Run workflow</button>",
"css": ".ds-btn-primary { height: 36px; padding: 0 10px; border: 1px solid transparent; border-radius: 8px; background: var(--primary, #2e795a); color: var(--primary-foreground, #fff); font: 500 0.8125rem 'IBM Plex Sans Variable', system-ui, sans-serif; cursor: pointer; transition: all 140ms cubic-bezier(0.4, 0, 0.2, 1); } .ds-btn-primary:hover { background: color-mix(in srgb, var(--primary, #2e795a) 80%, transparent); } .ds-btn-primary:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--ring, #51a580); } .ds-btn-primary:active { transform: translateY(1px); }"
},
{
"name": "Ghost Button",
"kind": "button",
"refersTo": "button-ghost",
"description": "Default for secondary and contextual actions.",
"html": "<button class=\"ds-btn-ghost\">Cancel</button>",
"css": ".ds-btn-ghost { height: 36px; padding: 0 10px; border: 1px solid transparent; border-radius: 8px; background: transparent; color: var(--foreground, #e8e6e1); font: 500 0.8125rem 'IBM Plex Sans Variable', system-ui, sans-serif; cursor: pointer; transition: all 140ms cubic-bezier(0.4, 0, 0.2, 1); } .ds-btn-ghost:hover { background: var(--muted, #26282c); } .ds-btn-ghost:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--ring, #51a580); } .ds-btn-ghost:active { transform: translateY(1px); }"
},
{
"name": "Attention Button",
"kind": "button",
"refersTo": "button-attention",
"description": "An action that exists because something is waiting.",
"html": "<button class=\"ds-btn-attention\">Review approval</button>",
"css": ".ds-btn-attention { height: 36px; padding: 0 10px; border: 1px solid var(--warn, #d9a45b); border-radius: 8px; background: var(--warn-soft, rgba(217,164,91,0.08)); color: var(--warn, #d9a45b); font: 500 0.8125rem 'IBM Plex Sans Variable', system-ui, sans-serif; cursor: pointer; transition: all 140ms cubic-bezier(0.4, 0, 0.2, 1); } .ds-btn-attention:hover { background: rgba(217,164,91,0.16); } .ds-btn-attention:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--ring, #51a580); }"
},
{
"name": "Text Input",
"kind": "input",
"refersTo": "input",
"description": "Single-line field on the card surface.",
"html": "<input class=\"ds-input\" placeholder=\"Workflow name\" />",
"css": ".ds-input { height: 36px; width: 240px; padding: 4px 10px; border: 1px solid var(--input, #70727a); border-radius: 8px; background: var(--card, #1c1d21); color: var(--foreground, #e8e6e1); font: 400 0.8125rem 'IBM Plex Sans Variable', system-ui, sans-serif; outline: none; transition: border-color 140ms, box-shadow 140ms; } .ds-input::placeholder { color: var(--fg-muted, #a6a39b); } .ds-input:focus-visible { border-color: var(--ring, #51a580); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ring, #51a580) 50%, transparent); }"
},
{
"name": "Status Badges",
"kind": "chip",
"refersTo": "badge-ok",
"description": "Solid tone on its soft background; the only place status colour is decided.",
"html": "<span class=\"ds-badge ds-ok\">Succeeded</span> <span class=\"ds-badge ds-warn\">Waiting</span> <span class=\"ds-badge ds-danger\">Failed</span> <span class=\"ds-badge ds-info\">Working</span> <span class=\"ds-badge ds-idle\">Idle</span>",
"css": ".ds-badge { display: inline-flex; align-items: center; height: 20px; padding: 2px 8px; border-radius: 4px; font: 500 0.6875rem 'IBM Plex Sans Variable', system-ui, sans-serif; white-space: nowrap; } .ds-ok { background: var(--ok-soft, rgba(81,165,128,0.12)); color: var(--ok, #51a580); } .ds-warn { background: var(--warn-soft, rgba(217,164,91,0.08)); color: var(--warn, #d9a45b); } .ds-danger { background: var(--danger-soft, rgba(217,119,107,0.08)); color: var(--danger, #d9776b); } .ds-info { background: var(--info-soft, rgba(138,164,194,0.1)); color: var(--info, #8aa4c2); } .ds-idle { background: var(--idle-soft, rgba(143,140,133,0.1)); color: var(--idle, #9a978f); }"
},
{
"name": "Section Card",
"kind": "card",
"refersTo": "card",
"description": "Titled card on the workspace; ring, no shadow.",
"html": "<section class=\"ds-card\"><h3 class=\"ds-card-title\">Event sources</h3><p class=\"ds-card-body\">prometheus <span class=\"ds-mono\">a41f9c2e</span></p></section>",
"css": ".ds-card { width: 320px; padding: 16px; border-radius: 12px; background: var(--card, #1c1d21); color: var(--card-foreground, #e8e6e1); box-shadow: 0 0 0 1px color-mix(in srgb, var(--foreground, #e8e6e1) 10%, transparent); font-family: 'IBM Plex Sans Variable', system-ui, sans-serif; } .ds-card-title { margin: 0 0 8px; font-size: 0.9375rem; font-weight: 500; line-height: 1.375; } .ds-card-body { margin: 0; font-size: 0.8125rem; color: var(--fg-muted, #a6a39b); } .ds-mono { font-family: 'IBM Plex Mono', ui-monospace, monospace; font-size: 0.6875rem; color: var(--fg-subtle, #99968f); }"
},
{
"name": "Top Bar",
"kind": "nav",
"refersTo": "top-bar",
"description": "Sticky 56px bar with breadcrumb and account controls.",
"html": "<header class=\"ds-topbar\"><nav class=\"ds-crumbs\"><a href=\"#\">Workflows</a><span>/</span><span class=\"ds-current\">disk-pressure</span></nav><span class=\"ds-pill\"><i></i>Connected</span></header>",
"css": ".ds-topbar { display: flex; align-items: center; justify-content: space-between; height: 56px; padding: 0 16px; background: var(--card, #1c1d21); border-bottom: 1px solid var(--border-strong, #3c3f45); box-shadow: 0 1px 2px rgba(0,0,0,0.4); font: 400 0.8125rem 'IBM Plex Sans Variable', system-ui, sans-serif; } .ds-crumbs { display: flex; gap: 6px; color: var(--fg-muted, #a6a39b); } .ds-crumbs a { color: inherit; text-decoration: none; } .ds-crumbs a:hover { color: var(--foreground, #e8e6e1); } .ds-crumbs a:focus-visible { outline: 2px solid var(--ring, #51a580); outline-offset: 2px; } .ds-current { color: var(--foreground, #e8e6e1); } .ds-pill { display: inline-flex; align-items: center; gap: 6px; font-size: 0.6875rem; color: var(--fg-muted, #a6a39b); } .ds-pill i { width: 6px; height: 6px; border-radius: 9999px; background: var(--ok, #51a580); }"
},
{
"name": "Step Node",
"kind": "custom",
"refersTo": "step-node",
"description": "The workflow canvas card; the same card shows edit state and live run state.",
"html": "<div class=\"ds-node\" tabindex=\"0\"><div class=\"ds-node-meta\"><svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M12 8V4H8\"/><rect width=\"16\" height=\"12\" x=\"4\" y=\"8\" rx=\"2\"/></svg><span>Agent</span><span class=\"ds-node-dur\">4.2s</span><i class=\"ds-node-dot\"></i></div><div class=\"ds-node-title\">2 Investigate disk usage</div></div>",
"css": ".ds-node { width: 240px; padding: 10px 12px; border: 1px solid var(--border, #313338); border-radius: 8px; background: var(--card, #1c1d21); box-shadow: 0 1px 2px rgba(0,0,0,0.4); font-family: 'IBM Plex Sans Variable', system-ui, sans-serif; color: var(--foreground, #e8e6e1); cursor: pointer; transition: width 200ms, box-shadow 200ms, border-color 140ms; } .ds-node:hover { border-color: var(--muted-foreground, #a6a39b); } .ds-node:focus-visible { outline: none; width: 416px; box-shadow: 0 8px 28px rgba(0,0,0,0.4), 0 0 0 2px var(--ring, #51a580); } .ds-node-meta { display: flex; align-items: center; gap: 6px; font-size: 0.6875rem; color: var(--fg-muted, #a6a39b); } .ds-node-meta svg { color: var(--link, #51a580); } .ds-node-dur { margin-left: auto; font-family: 'IBM Plex Mono', ui-monospace, monospace; color: var(--fg-subtle, #99968f); } .ds-node-dot { width: 6px; height: 6px; border-radius: 9999px; background: var(--info, #8aa4c2); } .ds-node-title { margin-top: 6px; font-size: 0.8125rem; font-weight: 500; }"
}
],
"narrative": {
"northStar": "The Operations Console",
"overview": "Archie's dashboard is a calm instrument panel for someone responsible for a live estate. It is dense and legible, and it stays quiet until something needs the operator. The mood is calm, precise and trustworthy: restraint is how the interface shows it is in control, and nothing raises its voice unless state demands it.\n\nThe palette is Graphite: warm neutral greys with no hue cast and a single accent, Signal Sage. Hierarchy comes from surface steps, hairlines and type weight, never from tinted backgrounds. Colour is a signal, not decoration. Sage marks what is live, healthy or actionable, and the four status hues (amber, clay, slate, stone) each keep one meaning everywhere they appear. Dark and light themes carry the same variable set and the same rules; the operator's OS chooses unless they pick one.\n\nDensity is a first-class setting. The default is already compact, and compact mode tightens the whole spacing scale without shrinking text or hit targets. Controls are compact and contextual: they appear where the work is, on hover or focus, rather than as permanent chrome. The interface never looks like a toy and never borrows generic SaaS gloss.",
"keyCharacteristics": [
"Warm graphite neutrals, one sage accent, four fixed status hues.",
"IBM Plex Sans with Plex Mono for IDs, durations and payloads, on a compact type scale (11 to 15px).",
"Flat tonal layers; shadows only for things that float.",
"Compact density by default, with a tighter compact mode.",
"Both themes, reduced motion and keyboard focus are invariants, not options."
],
"rules": [
{ "name": "The Semantic Names Rule", "body": "Components reference `--primary`, `--ok`, `--warn` and the rest, never a raw hex or a hue name such as `--violet`. A palette change is one file.", "section": "colors" },
{ "name": "The One Meaning Rule", "body": "A status colour means the same thing wherever it appears: a task state, a gate result, a log level and a trend all draw from the same five tones.", "section": "colors" },
{ "name": "The Measured Contrast Rule", "body": "Every foreground is checked against every surface it lands on, hover states included, at 4.5:1. Nothing dimmer than Text Subtle is allowed as text.", "section": "colors" },
{ "name": "The Type Scale Rule", "body": "Use the named steps (`text-micro`, `text-caption`, `text-label`, `text-title`), never pixel sizes. Headings are separated by weight and placement, not by size jumps.", "section": "typography" },
{ "name": "The Data Is Mono Rule", "body": "Anything the operator might copy or compare (an ID, a version, a duration, a payload) is set in Plex Mono.", "section": "typography" },
{ "name": "The Flat By Default Rule", "body": "Cards sit on the page with a 1px ring, not a shadow. A larger shadow means the element floats above the page.", "section": "elevation" }
],
"dos": [
"Do use semantic tokens (`bg-card`, `text-fg-muted`, `bg-ok-soft`) and the named type steps, so both themes and compact density work without extra code.",
"Do keep one filled primary button per view; everything else is ghost, outline or secondary.",
"Do set IDs, versions, durations and payloads in Plex Mono.",
"Do show actions on hover or focus where the work is, and make every hover action reachable by keyboard.",
"Do honour reduced motion: nothing animates when the operator asks it not to."
],
"donts": [
"Don't use generic SaaS gloss: no purple or multicolour gradients, no glow shadows, no glassmorphism cards, no gradient text.",
"Don't make it toy-like on phones: no blanket 44px minimum sizes on buttons, links and fields. Widen the tap area invisibly with `touch-hit` instead.",
"Don't tint backgrounds for hierarchy; use surface steps and borders.",
"Don't introduce a new hue or reuse a status colour for decoration.",
"Don't put white text on a status fill; use the soft background and the solid tone.",
"Don't add a shadow to a resting card."
]
}
}
+89
View File
@@ -0,0 +1,89 @@
StylesPath = .vale/styles
MinAlertLevel = warning
Vocab = Archie
# Run `vale sync` to install external packages and the Go comment grammar.
Packages = Google, Microsoft, Voices, TechTerms, Comments, Prompts
Grammars = go
[formats]
tmpl = md
[*.{md,tmpl}]
# Ignore Go/workflow template expressions such as {{ steps.plan.summary }}.
TokenIgnores = (\{\{[^}]*\}\})
BasedOnStyles = Vale, Voices, Direct, Google, Archie
# Australian English and Archie's technical prose conventions:
Google.Spelling = NO
Google.Quotes = NO
Google.DateFormat = NO
Google.OxfordComma = NO
Google.EmDash = NO
Google.Contractions = NO
Google.Parens = NO
Google.Semicolons = NO
Google.Colons = NO
Google.Units = NO
Google.Acronyms = NO
Google.WordList = NO
Google.WordListCase = NO
# Keep style nudges advisory (visible with --minAlertLevel=suggestion).
Google.Headings = suggestion
Google.Latin = suggestion
Google.Exclamation = warning
Google.FirstPerson = suggestion
Google.We = suggestion
Google.Will = suggestion
# Selective Microsoft rules (UI verbs, inclusive terminology, hyphens) without
# pulling in Microsoft-specific product jargon (e.g. agent -> personal digital assistant).
Microsoft.UIVerbs = warning
Microsoft.BiasFree = warning
Microsoft.Auto = warning
Microsoft.Suspended = warning
Microsoft.Accessibility = suggestion
Microsoft.Uppercase = suggestion
# "Term: explanation" is idiomatic throughout Archie's docs and comments.
Voices.ColonReveal = NO
# Replaced by Archie.Readability and Archie.SentenceLength, calibrated for technical docs.
Direct.Ease = NO
Direct.Length = NO
Direct.Hedging = warning
Direct.Preamble = warning
# Agent instruction and skill files get additional prompt-quality checks.
[{AGENTS,CLAUDE,SKILL}.md]
BasedOnStyles = Vale, Voices, Direct, Google, Archie, Prompts
# A rule file states each rule once, and many of those rules are absolutes.
# The prompt heuristic against repeated absolutes does not apply here.
Prompts.Absolutes = NO
# Model prompts are plain text (no Markdown bold) and reference tool names inline.
[internal/prompts/*.{md,tmpl}]
Vale.Spelling = suggestion
Archie.UILabelFormat = NO
# Go source comments: doc conventions, spelling, clarity, and no migration narration.
[*.go]
BasedOnStyles = Vale, Voices, Comments, GoDoc, Archie
# Go comments often mention camelCase/snake_case identifiers without backticks,
# so keep spelling advisory here.
Vale.Spelling = suggestion
# Upstream GoDoc.Sentence regex backtracks heavily on long comment blocks.
GoDoc.Sentence = NO
Voices.ColonReveal = NO
Archie.Readability = NO
Archie.SentenceLength = NO
Archie.UIElementType = NO
Archie.UILabelFormat = NO
# Never lint generated Go files (protobuf, sqlc).
[*.{pb,sql}.go]
BasedOnStyles =
+154
View File
@@ -0,0 +1,154 @@
# Enforce Australian English spelling in prose.
# Intentionally omits computing standards that use US forms in Australia
# (program, disk, artifact) and verb/noun pairs (licence/license, practise/practice).
extends: substitution
message: "Use Australian English '%s' instead of '%s'."
level: warning
ignorecase: true
action:
name: replace
# Exact-case exceptions for HTTP headers and Go method names.
exceptions:
- Authorize
- Authorization
swap:
analyze: analyse
analyzed: analysed
analyzes: analyses
analyzing: analysing
authorization: authorisation
authorizations: authorisations
authorize: authorise
authorized: authorised
authorizes: authorises
authorizing: authorising
behavior: behaviour
behavioral: behavioural
behaviors: behaviours
canceled: cancelled
canceling: cancelling
canonicalize: canonicalise
canonicalized: canonicalised
canonicalizes: canonicalises
canonicalizing: canonicalising
catalog: catalogue
cataloged: catalogued
cataloging: cataloguing
catalogs: catalogues
categorization: categorisation
categorize: categorise
categorized: categorised
categorizes: categorises
categorizing: categorising
center: centre
centered: centred
centering: centring
centers: centres
color: colour
colored: coloured
coloring: colouring
colors: colours
customization: customisation
customize: customise
customized: customised
customizes: customises
customizing: customising
favor: favour
favored: favoured
favoring: favouring
favorite: favourite
favorites: favourites
favors: favours
finalize: finalise
finalized: finalised
finalizes: finalises
finalizing: finalising
fulfill: fulfil
fulfillment: fulfilment
fulfills: fulfils
initialization: initialisation
initialize: initialise
initialized: initialised
initializes: initialises
initializing: initialising
judgment: judgement
judgments: judgements
labeled: labelled
labeling: labelling
maximize: maximise
maximized: maximised
maximizes: maximises
maximizing: maximising
minimize: minimise
minimized: minimised
minimizes: minimises
minimizing: minimising
modeled: modelled
modeling: modelling
normalization: normalisation
normalize: normalise
normalized: normalised
normalizes: normalises
normalizing: normalising
optimization: optimisation
optimizations: optimisations
optimize: optimise
optimized: optimised
optimizes: optimises
optimizing: optimising
organization: organisation
organizational: organisational
organizations: organisations
organize: organise
organized: organised
organizes: organises
organizing: organising
parameterize: parameterise
parameterized: parameterised
parameterizes: parameterises
parameterizing: parameterising
prioritize: prioritise
prioritized: prioritised
prioritizes: prioritises
prioritizing: prioritising
recognize: recognise
recognized: recognised
recognizes: recognises
recognizing: recognising
sanitization: sanitisation
sanitize: sanitise
sanitized: sanitised
sanitizes: sanitises
sanitizing: sanitising
serialization: serialisation
serialize: serialise
serialized: serialised
serializes: serialises
serializing: serialising
stabilize: stabilise
stabilized: stabilised
stabilizes: stabilises
stabilizing: stabilising
summarize: summarise
summarized: summarised
summarizes: summarises
summarizing: summarising
synchronization: synchronisation
synchronize: synchronise
synchronized: synchronised
synchronizes: synchronises
synchronizing: synchronising
unauthorized: unauthorised
tests:
- name: flags US spelling
input: |
The organization enforces authorization behavior.
want: |
1:5:Archie.AustralianEnglish:Use Australian English 'organisation' instead of 'organization'.
1:27:Archie.AustralianEnglish:Use Australian English 'authorisation' instead of 'authorization'.
1:41:Archie.AustralianEnglish:Use Australian English 'behaviour' instead of 'behavior'.
- name: accepts Australian spelling and inline code
input: |
The organisation enforces authorisation behaviour via `behavior_flag`.
want: ""
@@ -0,0 +1,29 @@
# AGENTS.md: "Comments explain why, not what the code already says.
# No migration history, phase names or issue narration in code."
extends: existence
message: "Avoid migration or plan narration ('%s') in code comments. Explain what the code does or why."
level: warning
scope: comment.go
ignorecase: true
nonword: true
tokens:
- '\b(?:phase|wave|slice|sprint)\s+\d+\b'
- '\bepic\s+#\d+\b'
- '\b(?:formerly|previously)\s+(?:called|named|known as)\b'
- '\b(?:migrated|moved|extracted|ported)\s+from\b'
tests:
- name: flags migration narration in Go comments
format: go
input: |
// Phase 2 moved from internal/legacy.
package demo
want: |
1:4:Archie.NoMigrationNarration:Avoid migration or plan narration ('Phase 2') in code comments. Explain what the code does or why.
1:12:Archie.NoMigrationNarration:Avoid migration or plan narration ('moved from') in code comments. Explain what the code does or why.
- name: allows normal rationale comments
format: go
input: |
// Verify the HMAC before parsing so malformed payloads cannot trigger work.
package demo
want: ""
+21
View File
@@ -0,0 +1,21 @@
# Calibrated for developer documentation: crisp technical docs with domain
# terminology typically score 8-11 on Flesch-Kincaid; higher scores usually
# signal dense paragraphs that benefit from simpler structure.
extends: metric
message: "Try to keep the Flesch-Kincaid grade level (%s) at or below 11."
link: https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests
level: warning
formula: |
(0.39 * (words / sentences)) + (11.8 * (syllables / words)) - 15.59
condition: "> 11"
tests:
- name: flags dense technical prose
input: |
Notwithstanding architectural encapsulation prerequisites, interdepartmental orchestration mechanisms necessitate comprehensive deterministic authentication verification across heterogeneous distributed administrative infrastructures.
want: |
1:1:Archie.Readability:Try to keep the Flesch-Kincaid grade level (42.40) at or below 11.
- name: accepts clear technical prose
input: |
A source receives events and checks their HMAC signature. A mapping extracts named fields from the payload. A binding selects the workflow to run.
want: ""
+17
View File
@@ -0,0 +1,17 @@
# Flag overly long sentences in documentation. Set to 35 words so precise
# technical constraints fit comfortably while runaway sentences are caught.
extends: Std.Readability.SentenceLength
message: "This sentence has %d words. Consider splitting it for readability."
level: warning
max: 35
tests:
- name: flags long sentence
input: |
When the daemon starts a new workflow run for an incoming event that matched a signed binding, it loads the published workflow definition from storage, allocates an isolated container workspace, prepares task-scoped credentials, and dispatches the first step immediately without waiting.
want: |
1:1:Archie.SentenceLength:This sentence has 42 words. Consider splitting it for readability.
- name: accepts concise technical sentences
input: |
The daemon loads the published workflow definition and allocates an isolated container workspace. It prepares task-scoped credentials before dispatching the first step.
want: ""
+22
View File
@@ -0,0 +1,22 @@
# Microsoft Writing Style Guide: "Don't include the type of UI element, such as
# button or checkbox, unless including it adds needed clarity."
extends: existence
message: "Omit the UI element type after a bold label ('%s') unless it adds clarity."
link: https://learn.microsoft.com/en-us/style-guide/procedures-instructions/describing-interactions-with-ui
level: warning
scope: raw
nonword: true
tokens:
- '\*\*[^*\n]{1,40}\*\*\s+(?:button|checkbox|check box|dropdown|drop-down|field|icon|link|menu|option|switch|tab|toggle)\b'
tests:
- name: flags bold label followed by UI element type
input: |
Select the **Save** button and leave the **Shared secret** field blank.
want: |
1:12:Archie.UIElementType:Omit the UI element type after a bold label ('**Save** button') unless it adds clarity.
1:42:Archie.UIElementType:Omit the UI element type after a bold label ('**Shared secret** field') unless it adds clarity.
- name: allows bold UI label without element type
input: |
Select **Save** and leave **Shared secret** blank.
want: ""
+46
View File
@@ -0,0 +1,46 @@
# Input-neutral UI interaction verbs complementing Microsoft.UIVerbs.
# Based on Microsoft Writing Style Guide: Describing interactions with UI.
extends: substitution
message: "Use the input-neutral UI verb '%s' instead of '%s'."
link: https://learn.microsoft.com/en-us/style-guide/procedures-instructions/describing-interactions-with-ui
level: warning
ignorecase: true
action:
name: replace
swap:
deselect: clear
deselected: cleared
deselecting: clearing
deselects: clears
drag and drop: drag
drag-and-drop: drag
key in: enter
keyed in: entered
keying in: entering
mouse over: hover over
moused over: hovered over
mousing over: hovering over
navigate to: go to
navigated to: went to
navigating to: going to
press and hold: select and hold
tap and hold: select and hold
tap on: select
tapped on: selected
tapping on: selecting
uncheck: clear
unchecking: clearing
unchecks: clears
tests:
- name: flags input-specific UI verbs
input: |
Navigate to Settings, uncheck Auto-save, and mouse over the badge.
want: |
1:1:Archie.UIInteractions:Use the input-neutral UI verb 'go to' instead of 'Navigate to'.
1:23:Archie.UIInteractions:Use the input-neutral UI verb 'clear' instead of 'uncheck'.
1:46:Archie.UIInteractions:Use the input-neutral UI verb 'hover over' instead of 'mouse over'.
- name: accepts input-neutral UI verbs
input: |
Go to Settings, clear Auto-save, and hover over the badge.
want: ""
+26
View File
@@ -0,0 +1,26 @@
# Microsoft Writing Style Guide:
# - Use bold formatting for UI element names, not quotation marks.
# - Omit trailing colons or ellipses from UI labels in instructions.
extends: existence
message: "Format UI labels in bold without quotes or trailing punctuation ('%s')."
link: https://learn.microsoft.com/en-us/style-guide/procedures-instructions/describing-interactions-with-ui
level: warning
scope: raw
ignorecase: true
nonword: true
tokens:
- '\b(?:select|choose|open|clear|go to|hover over)\s+"[^"\n]{1,40}"'
- '\b(?:select|choose|open|clear|go to|hover over)\s+\*\*[^*\n]{1,40}(?::|\.{3}|…)\*\*'
tests:
- name: flags quoted UI labels and trailing punctuation
input: |
Select "Save" or choose **Export...** and open **Settings:**.
want: |
1:1:Archie.UILabelFormat:Format UI labels in bold without quotes or trailing punctuation ('Select "Save"').
1:18:Archie.UILabelFormat:Format UI labels in bold without quotes or trailing punctuation ('choose **Export...**').
1:43:Archie.UILabelFormat:Format UI labels in bold without quotes or trailing punctuation ('open **Settings:**').
- name: accepts clean bold UI labels
input: |
Select **Save**, choose **Export**, and open **Settings**.
want: ""
+44
View File
@@ -0,0 +1,44 @@
# Prefer concise wording over wordy phrases.
extends: substitution
message: "Use '%s' instead of '%s'."
level: warning
ignorecase: true
action:
name: replace
swap:
a large number of: many
a majority of: most
a sufficient number of: enough
as a means of: to
at this point in time: now
due to the fact that: because
for the purpose of: to
has the capability to: can
in close proximity to: near
in excess of: more than
in spite of the fact that: although
in the event that: if
in the near future: soon
make use of: use
on a daily basis: daily
on a monthly basis: monthly
on a weekly basis: weekly
prior to: before
subsequent to: after
take advantage of: use
until such time as: until
whether or not: whether
with regard to: about
with respect to: about
tests:
- name: flags wordy phrases
input: |
Check the signature prior to parsing due to the fact that payloads are untrusted.
want: |
1:21:Archie.Wordiness:Use 'before' instead of 'prior to'.
1:38:Archie.Wordiness:Use 'because' instead of 'due to the fact that'.
- name: accepts concise wording
input: |
Check the signature before parsing because payloads are untrusted.
want: ""
@@ -0,0 +1,30 @@
# Case-insensitive common terms (matched in any capitalisation)
(?i)approvers?
(?i)archipelago
(?i)canonicalis(?:e[ds]?|ing)
(?i)carina
(?i)confirmers?
(?i)fulfilment
(?i)passkeys?
(?i)reapprovals?
(?i)redemptions?
(?i)retags?
(?i)undispatched
(?i)unpushed
(?i)worktrees?
# Proper nouns, tools, and exact-case technical terms
archied
Catlow
depguard
gosec
govulncheck
hclog
Huma
Miessler
Pdeathsig
prbench
Reka
releaseupdate
secretengine
sqlc
+50 -37
View File
@@ -5,9 +5,9 @@ here changes a decision. If a rule stops changing decisions, delete it.
## What this is ## What this is
**archie-core** is event-driven agentic automation. An event (an alert, a **archie-core** is event-driven agentic automation. It matches an event (an
webhook, a schedule, a chat message, an issue) is matched to a workflow, the alert, a webhook, a schedule, a chat message, an issue) to a workflow. The
workflow runs an agent whose every action is judged before it runs, and the workflow runs an agent, and archie-core judges every action before it runs. The
result lands somewhere for review or action. A repository is an optional input result lands somewhere for review or action. A repository is an optional input
to a workflow, not the point of the product. A forge is one of many inputs or to a workflow, not the point of the product. A forge is one of many inputs or
outputs; core code never assumes one. outputs; core code never assumes one.
@@ -33,9 +33,9 @@ there:
needs the maintainer's verdict on its row. Before building anything an old needs the maintainer's verdict on its row. Before building anything an old
package already does, read that package and carry its behaviour. package already does, read that package and carry its behaviour.
### The services being replaced ### The services the binary replaces
The six services below are deleted slice by slice as the binary replaces them, Delete the six services below slice by slice as the binary replaces them,
each only once MIGRATION.md has a verdict for every package it holds. Don't each only once MIGRATION.md has a verdict for every package it holds. Don't
add features to them; fix them only when a bug blocks work. add features to them; fix them only when a bug blocks work.
@@ -79,13 +79,14 @@ When sources disagree, the higher one wins:
the plan, offer options, or ask "shall I proceed?". Stop only for destructive the plan, offer options, or ask "shall I proceed?". Stop only for destructive
or outward-facing actions (deleting data, pushing, touching a live host). or outward-facing actions (deleting data, pushing, touching a live host).
- **Push back when it matters.** If a request competes with something clearly - **Push back when it matters.** If a request competes with something clearly
more urgent (a bug that loses work, a failure that shows nothing, a security more urgent, or looks like the wrong call, say so once in a sentence or two.
gap, a broken setup path), or looks like the wrong call, say so once in a A bug that loses work, a failure that shows nothing, a security gap and a
sentence or two and suggest whether it belongs in the backlog. Then do what broken setup path are all more urgent. Suggest whether it belongs in the
was asked: don't repeat the point or hold work back on your own judgement. backlog. Then do what the maintainer asked: don't repeat the point or hold
work back on your own judgement.
- **Post outside the repo only when told.** Chat, tickets and any external - **Post outside the repo only when told.** Chat, tickets and any external
service get a message only on the maintainer's instruction. service get a message only on the maintainer's instruction.
- **Report, don't narrate.** Final replies say what changed, what was verified, - **Report, don't narrate.** Final replies say what changed, what you verified,
and anything blocked, in a few lines. No preamble, no recap of the request, no and anything blocked, in a few lines. No preamble, no recap of the request, no
closing offers of more help. Leave out what the maintainer can see or infer: closing offers of more help. Leave out what the maintainer can see or infer:
a clean tree, unpushed commits, a passing gate (commits imply it), and steps a clean tree, unpushed commits, a passing gate (commits imply it), and steps
@@ -113,11 +114,12 @@ When sources disagree, the higher one wins:
- **No compensating tools.** Do not write a linter, checker or generator to - **No compensating tools.** Do not write a linter, checker or generator to
enforce something a simpler design would make unnecessary. Fix the design. enforce something a simpler design would make unnecessary. Fix the design.
- **A setting must work end to end.** A config field that parses but has no - **A setting must work end to end.** A config field that parses but has no
consumer is a bug. Settings are edited through the control plane (API and consumer is a bug. Operators edit settings through the control plane (API and
dashboard), never by requiring a server login. dashboard), never through a server login.
- **Ask only for real decisions.** Product direction and trade-offs the - **Ask only for real decisions.** Product direction and trade-offs the
maintainer owns are questions. Everything with a conventional answer is not: maintainer owns are questions. Anything with a conventional engineering
decide, do it, say what you chose. answer or an existing pattern in the codebase is not: decide, do it, say
what you chose.
## Code ## Code
@@ -127,14 +129,24 @@ When sources disagree, the higher one wins:
- Dependencies point inward: `cmd → app → {domain, infrastructure}`, - Dependencies point inward: `cmd → app → {domain, infrastructure}`,
`infrastructure` implements `domain` interfaces, `domain` imports neither. `infrastructure` implements `domain` interfaces, `domain` imports neither.
`cmd/` parses flags and calls `app`, nothing else. `cmd/` parses flags and calls `app`, nothing else.
- Fix invalid state where it is produced, not with checks where it is consumed. - Fix invalid state where the code produces it, not with checks where the
code consumes it.
- Log through the service's injected `*slog.Logger` with the `...Context` - Log through the service's injected `*slog.Logger` with the `...Context`
methods, so lines carry the OpenTelemetry trace id. Never the global `slog`. methods, so lines carry the OpenTelemetry trace id. Never the global `slog`.
- If a fix fails twice, throw the block away and rewrite it simply. - If a fix fails twice, throw the block away and rewrite it simply.
- Comments say why, briefly. No migration history, phase names or issue - Comments explain why, not what the code already says. No migration
narration in code. history, phase names or issue narration in code.
- Generated files (protobuf, sqlc) are regenerated and committed - Write natural, idiomatic technical English in comments, errors, logs,
with the change that caused them, never hand-edited. test names, descriptions, prompts and user-facing text. Use conventional
terminology and normal word order. Avoid invented metaphors, awkward
possessives, inverted sentences and clever paraphrases. Prefer repeating
an established term over inventing a synonym.
- Regenerate generated files (protobuf, sqlc) and commit them with the change
that caused them; never hand-edit them.
- Foreign keys and attribution always reference immutable primary IDs, never
mutable or non-unique attributes (display names, slugs, emails). Store
display labels alongside an ID only when you need point-in-time snapshot
fidelity.
## Tests ## Tests
@@ -150,14 +162,14 @@ The default for a change is no new test. Write one only when:
A test that exists must catch a real regression, survive refactoring, run fast, A test that exists must catch a real regression, survive refactoring, run fast,
and be cheap to keep. Never test wiring, constants, defaults, struct shapes, and be cheap to keep. Never test wiring, constants, defaults, struct shapes,
fakes, or call order. Prefer making an invalid state unrepresentable to testing fakes, or call order. Prefer making an invalid state unrepresentable to testing
that it is rejected. that the code rejects it.
How to write one: How to write one:
- **Prove it.** Run the new test against the code before the fix and see it - **Prove it.** Run the new test against the code before the fix and see it
fail. A test that passes either way proves nothing: delete it. When a bug fail. A test that passes either way proves nothing: delete it. When you
can't be reproduced deterministically (a race, say), fix it with an API that can't reproduce a bug deterministically (a race, say), fix it with an API
rules it out and don't add a test. that rules it out and don't add a test.
- **One table per behaviour.** Extend the table instead of adding a second test. - **One table per behaviour.** Extend the table instead of adding a second test.
Name the test after the behaviour, and say in its comment what regression it Name the test after the behaviour, and say in its comment what regression it
guards. guards.
@@ -169,7 +181,7 @@ How to write one:
- **Isolated.** Use `t.TempDir()` and `t.Setenv`, never host state. A test that - **Isolated.** Use `t.TempDir()` and `t.Setenv`, never host state. A test that
commits with git sets `GIT_CONFIG_GLOBAL` to `os.DevNull`. No test opens a commits with git sets `GIT_CONFIG_GLOBAL` to `os.DevNull`. No test opens a
real database or needs Docker: test SQL semantics at the interceptor or domain real database or needs Docker: test SQL semantics at the interceptor or domain
level with fakes. Files are written `0o600`, or `0o700` for a script. level with fakes. Tests write files `0o600`, or `0o700` for a script.
- **Shared setup in helpers.** When several tests repeat the same setup, put it - **Shared setup in helpers.** When several tests repeat the same setup, put it
in a helper in a `_test.go` file, never in production code. in a helper in a `_test.go` file, never in production code.
@@ -177,18 +189,19 @@ How to write one:
These protect users. Do not weaken them without the maintainer's say-so. These protect users. Do not weaken them without the maintainer's say-so.
- A crash loses no accepted work, and a restart resumes every run. Work is - A crash loses no accepted work, and a restart resumes every run. The service
acknowledged only once it is durable. A missing dependency is reported that accepts the work acknowledges it only once it is durable. A service
unhealthy and retried, never a reason to exit. reports a missing dependency as unhealthy and retries it; that is never a
reason to exit.
- The model never runs git. Commits and pushes go through the daemon. - The model never runs git. Commits and pushes go through the daemon.
- The daemon's own credentials never enter an agent container. Containers get - The daemon's own credentials never enter an agent container. Containers get
task-scoped grants that are revoked when the task ends. task-scoped grants that the daemon revokes when the task ends.
- Webhook HMAC is verified before the payload is parsed. - The events module verifies webhook HMAC before it parses the payload.
- Task briefs go in `<worktree>/.git/task.json`, never the worktree root. - Task briefs go in `<worktree>/.git/task.json`, never the worktree root.
- NATS: task and RPC replies use `msg.Respond`; flush after registering a - NATS: task and RPC replies use `msg.Respond`; flush after registering a
responder; `ARCHIE_TASKS` is a work queue, so never bind overlapping responder; `ARCHIE_TASKS` is a work queue, so never bind overlapping
consumers. consumers.
- `ai-sdk` `FullStream` must be drained completely. - Drain `ai-sdk` `FullStream` completely.
## Build and gate ## Build and gate
@@ -216,16 +229,16 @@ Requires Go 1.27, Task, golangci-lint, Node, pnpm and Docker. Adopt `task fmt` a
run, say what you did verify. run, say what you did verify.
- Commit finished work without asking. Stage only your own paths and commit in - Commit finished work without asking. Stage only your own paths and commit in
the same command. Conventional Commits scoped by package, short messages. Push the same command. Conventional Commits scoped by package, short messages. Push
every commit as soon as it is made; a local-only commit is not acceptable. every commit as soon as you make it; a local-only commit is not acceptable.
- Never commit binaries, build output, scratch files or `.references/`. Scratch - Never commit binaries, build output, scratch files or `.references/`. Scratch
goes in `/tmp`. goes in `/tmp`.
- Runtime config lives at `${XDG_CONFIG_HOME:-~/.config}/archie/config.toml`. - Runtime config lives at `${XDG_CONFIG_HOME:-~/.config}/archie/config.toml`.
Nothing in the working tree is read at runtime. Systemd is optional. The runtime reads nothing in the working tree. Systemd is optional.
- Releases: `RELEASING.md`. - Releases: `RELEASING.md`.
## Issues (Gitea) ## Issues (Gitea)
Work is tracked as issues on the primary remote, never in Markdown TODO files. Track work as issues on the primary remote, never in Markdown TODO files.
GitHub is a read-only mirror; do not open, close or comment there. GitHub is a read-only mirror; do not open, close or comment there.
```bash ```bash
@@ -236,12 +249,12 @@ tea comment 497 "what changed, and what was run"
tea issues close 497 tea issues close 497
``` ```
- An issue is the plan: what is wrong or wanted, and how you know it is done. - An issue is the plan: what is wrong or wanted, and how you know the work is
Keep it to that. complete. Keep it to that.
- Labels carry state: a type (`bug`, `feature`, `task`, `chore`, `epic`, - Labels carry state: a type (`bug`, `feature`, `task`, `chore`, `epic`,
`decision`, `discovery`), a priority (`critical`, `high`, `medium`, `low`), `in-progress` `decision`, `discovery`), a priority (`critical`, `high`, `medium`, `low`), `in-progress`
and `deferred`. Open/closed is the issue state, not a label. and `deferred`. Open/closed is the issue state, not a label.
- An epic's children are its dependencies: link each one as it is filed (Gitea - An epic's children are its dependencies: link each one as you file it (Gitea
MCP `issue_write` `add_dependency`, the epic `blocked_by` the child), plus any MCP `issue_write` `add_dependency`, the epic `blocked_by` the child), plus any
real blocker between children. No `epic/<slug>` label; the dependencies are real blocker between children. No `epic/<slug>` label; the dependencies are
the link, and the only place the web UI shows an epic's children. the link, and the only place the web UI shows an epic's children.
@@ -258,6 +271,6 @@ tea issues close 497
## Changing this file ## Changing this file
A rule is added only after a real failure it would have prevented, and it must Add a rule only after a real failure it would have prevented, and it must
say which decision it changes. Remove rules that no longer change decisions. say which decision it changes. Remove rules that no longer change decisions.
Keep it short enough to read in full every session. Keep it short enough to read in full every session.
+407
View File
@@ -0,0 +1,407 @@
---
name: Archie
description: Event-driven Agentic Automation
colors:
signal-sage: "#51a580"
signal-sage-deep: "#2e795a"
signal-sage-ink: "#0c6f4d"
graphite-canvas: "#0e0f10"
graphite-workspace: "#16171a"
graphite-card: "#1c1d21"
graphite-popover: "#202226"
graphite-hover: "#26282c"
graphite-hairline: "#2a2c30"
graphite-border: "#313338"
graphite-border-strong: "#3c3f45"
graphite-input: "#70727a"
graphite-text: "#e8e6e1"
graphite-text-muted: "#a6a39b"
graphite-text-subtle: "#99968f"
paper-canvas: "#e9e7e2"
paper-workspace: "#f5f4f1"
paper-card: "#ffffff"
paper-hover: "#ecebe7"
paper-hairline: "#d6d3cc"
paper-border: "#dcdad4"
paper-border-strong: "#c7c4bd"
paper-input: "#8a877f"
paper-text: "#1f1f1d"
paper-text-muted: "#5c5a55"
paper-text-subtle: "#66635d"
amber-warn: "#d9a45b"
amber-warn-ink: "#8a5a12"
clay-danger: "#d9776b"
clay-danger-ink: "#b3413a"
slate-info: "#8aa4c2"
slate-info-ink: "#3d5f86"
stone-idle: "#9a978f"
stone-idle-ink: "#5f5d58"
typography:
title:
fontFamily: "IBM Plex Sans Variable, system-ui, sans-serif"
fontSize: "0.9375rem"
fontWeight: 500
lineHeight: 1.375
page-title:
fontFamily: "IBM Plex Sans Variable, system-ui, sans-serif"
fontSize: "0.9375rem"
fontWeight: 600
lineHeight: 1.25
letterSpacing: "-0.025em"
label:
fontFamily: "IBM Plex Sans Variable, system-ui, sans-serif"
fontSize: "0.8125rem"
fontWeight: 400
caption:
fontFamily: "IBM Plex Sans Variable, system-ui, sans-serif"
fontSize: "0.6875rem"
fontWeight: 500
section-label:
fontFamily: "IBM Plex Sans Variable, system-ui, sans-serif"
fontSize: "0.6875rem"
fontWeight: 500
letterSpacing: "0.06em"
micro:
fontFamily: "IBM Plex Sans Variable, system-ui, sans-serif"
fontSize: "0.625rem"
mono:
fontFamily: "IBM Plex Mono, ui-monospace, monospace"
fontSize: "0.6875rem"
fontWeight: 400
rounded:
sm: "4px"
md: "6px"
lg: "8px"
xl: "12px"
full: "9999px"
spacing:
unit: "0.25rem"
unit-compact: "0.225rem"
control-gap: "0.375rem"
card-x: "1rem"
card-y: "1rem"
page-x: "1.5rem"
page-y: "1.25rem"
components:
button-primary:
backgroundColor: "{colors.signal-sage-deep}"
textColor: "#ffffff"
typography: "{typography.label}"
rounded: "{rounded.lg}"
padding: "0 10px"
height: "36px"
button-ghost:
backgroundColor: "transparent"
textColor: "{colors.graphite-text}"
typography: "{typography.label}"
rounded: "{rounded.lg}"
padding: "0 10px"
height: "36px"
button-ghost-hover:
backgroundColor: "{colors.graphite-hover}"
button-attention:
backgroundColor: "rgba(217, 164, 91, 0.08)"
textColor: "{colors.amber-warn}"
typography: "{typography.label}"
rounded: "{rounded.lg}"
padding: "0 10px"
height: "36px"
button-destructive:
backgroundColor: "rgba(217, 119, 107, 0.2)"
textColor: "{colors.clay-danger}"
typography: "{typography.label}"
rounded: "{rounded.lg}"
padding: "0 10px"
height: "36px"
input:
backgroundColor: "{colors.graphite-card}"
textColor: "{colors.graphite-text}"
typography: "{typography.label}"
rounded: "{rounded.lg}"
padding: "4px 10px"
height: "36px"
card:
backgroundColor: "{colors.graphite-card}"
textColor: "{colors.graphite-text}"
rounded: "{rounded.xl}"
padding: "16px"
badge-ok:
backgroundColor: "rgba(81, 165, 128, 0.12)"
textColor: "{colors.signal-sage}"
typography: "{typography.caption}"
rounded: "{rounded.sm}"
padding: "2px 8px"
height: "20px"
badge-warn:
backgroundColor: "rgba(217, 164, 91, 0.08)"
textColor: "{colors.amber-warn}"
typography: "{typography.caption}"
rounded: "{rounded.sm}"
padding: "2px 8px"
height: "20px"
badge-danger:
backgroundColor: "rgba(217, 119, 107, 0.08)"
textColor: "{colors.clay-danger}"
typography: "{typography.caption}"
rounded: "{rounded.sm}"
padding: "2px 8px"
height: "20px"
status-dot:
rounded: "{rounded.full}"
size: "6px"
top-bar:
backgroundColor: "{colors.graphite-card}"
height: "56px"
padding: "0 16px"
step-node:
backgroundColor: "{colors.graphite-card}"
rounded: "{rounded.lg}"
padding: "10px 12px"
width: "240px"
step-node-expanded:
width: "416px"
---
# Design System: Archie
## Overview
**Creative North Star: "The Operations Console"**
Archie's dashboard is a calm instrument panel for someone responsible for a live
estate. It is dense and legible, and it stays quiet until something needs the
operator. The mood is calm, precise and trustworthy: restraint is how the
interface shows it is in control, and nothing raises its voice unless state
demands it.
The palette is Graphite: warm neutral greys with no hue cast and a single accent,
Signal Sage. Hierarchy comes from surface steps, hairlines and type weight, never
from tinted backgrounds. Colour is a signal, not decoration. Sage marks what is
live, healthy or actionable, and the four status hues (amber, clay, slate, stone)
each keep one meaning everywhere they appear. Dark and light themes carry the same
variable set and the same rules; the operator's OS chooses unless they pick one.
Density is a first-class setting. The default is already compact, and compact mode
tightens the whole spacing scale without shrinking text or hit targets. Controls
are compact and contextual: they appear where the work is, on hover or focus,
rather than as permanent chrome. The interface never looks like a toy and never
borrows generic SaaS gloss.
**Key Characteristics:**
- Warm graphite neutrals, one sage accent, four fixed status hues.
- IBM Plex Sans with Plex Mono for IDs, durations and payloads, on a compact type
scale (11 to 15px).
- Flat tonal layers; shadows only for things that float.
- Compact density by default, with a tighter compact mode.
- Both themes, reduced motion and keyboard focus are invariants, not options.
## Colors
Warm graphite greys carry the structure; Signal Sage and four status hues carry
meaning, and each one means the same thing everywhere.
### Primary
- **Signal Sage** (#51a580): the mark, accents, focus rings and links in dark mode,
and the `ok` state there. On a dark card it is 5.7:1 as text.
- **Signal Sage Deep** (#2e795a): the primary button fill in both themes (white on
it is 5.3:1) and the focus ring on paper, where bright sage falls under 3:1.
- **Signal Sage Ink** (#0c6f4d): links and `ok` text in the light theme, 5.0:1 on
the paper canvas.
### Neutral
- **Graphite Canvas** (#0e0f10) / **Paper Canvas** (#e9e7e2): the page behind
everything.
- **Graphite Workspace** (#16171a) / **Paper Workspace** (#f5f4f1): the main
content area inside the sidebar shell.
- **Graphite Card** (#1c1d21) / **Paper Card** (#ffffff): cards, the top bar,
inputs and canvas nodes. **Graphite Popover** (#202226) lifts menus one step
above cards in dark mode.
- **Graphite Hover** (#26282c) / **Paper Hover** (#ecebe7): hover, secondary and
muted surfaces (shadcn's `accent`, `muted` and `secondary` all share it).
- **Hairline, Border, Border Strong** (#2a2c30, #313338, #3c3f45 dark; #d6d3cc,
#dcdad4, #c7c4bd light): dividers, card edges and the top bar's bottom edge.
- **Input stroke** (#70727a dark, #8a877f light): field borders, 3.5:1 or better
against the card.
- **Text, Text Muted, Text Subtle** (#e8e6e1, #a6a39b, #99968f dark; #1f1f1d,
#5c5a55, #66635d light): primary copy, secondary copy, and the dimmest text
allowed, for hints and captions only.
### Status
- **Amber Warn** (#d9a45b dark, #8a5a12 light): waiting, needs attention, the
`attention` button.
- **Clay Danger** (#d9776b dark, #b3413a light): failures and destructive
actions.
- **Slate Info** (#8aa4c2 dark, #3d5f86 light): an agent that is working.
- **Stone Idle** (#9a978f dark, #5f5d58 light): idle, inactive or unknown.
Each status hue has a soft background at 8 to 12% alpha of its own tone. Status
badges put the solid tone on the soft background, never white text on a fill.
### Named Rules
**The Semantic Names Rule.** Components reference `--primary`, `--ok`, `--warn`
and the rest, never a raw hex or a hue name such as `--violet`. A palette change is
one file.
**The One Meaning Rule.** A status colour means the same thing wherever it
appears: a task state, a gate result, a log level and a trend all draw from the
same five tones.
**The Measured Contrast Rule.** Every foreground is checked against every surface
it lands on, hover states included, at 4.5:1. Nothing dimmer than Text Subtle is
allowed as text.
## Typography
**Body Font:** IBM Plex Sans Variable (with system-ui, sans-serif)
**Label/Mono Font:** IBM Plex Mono (with ui-monospace, monospace)
**Character:** A sober, engineered grotesque paired with its own monospace, so
identifiers, durations and payloads read as data without changing voice.
### Hierarchy
- **Page title** (600, 0.9375rem, 1.25, -0.025em): one per page, in PageHeader
beside the page's actions.
- **Title** (500, 0.9375rem, 1.375): card and panel titles.
- **Label** (400 to 500, 0.8125rem): body copy, rows, navigation, buttons and
fields. The default text size of the dashboard.
- **Caption** (500, 0.6875rem): metadata, column labels, step-type labels and
badges.
- **Section label** (500, 0.6875rem, 0.06em, uppercase): group headings in
sidebars and settings navigation only.
- **Micro** (0.625rem): the smallest annotations, used sparingly.
- **Mono** (400, caption size): IDs, short hashes, durations, log fields and code.
### Named Rules
**The Type Scale Rule.** Use the named steps (`text-micro`, `text-caption`,
`text-label`, `text-title`), never pixel sizes. Headings are separated by weight
and placement, not by size jumps.
**The Data Is Mono Rule.** Anything the operator might copy or compare (an ID, a
version, a duration, a payload) is set in Plex Mono.
## Layout
The app shell is a collapsible sidebar plus a sticky 56px top bar holding the
breadcrumb and account controls. Page content sits in the workspace surface with
1.5rem by 1.25rem padding, dropping to 1rem below the large breakpoint, and a
bottom clearance for the docked chat composer. The chat can pin to either side,
and the workspace shifts to make room for it.
Spacing is Tailwind's 0.25rem scale; compact density sets the unit to 0.225rem,
so every gap and padding tightens together and components keep their relative
rhythm. Pages use container queries (`@container`) so panels respond to the space
they actually have, not the viewport.
Phone width is a real target. Desktop layouts collapse to dropdowns instead of
side lists and to stacked panes, and nothing overlaps the canvas. Controls keep
their desktop size on touch screens; a `touch-hit` utility widens the tap area to
44px invisibly, and only rows in floating menus grow to 2.75rem.
The workflow canvas is the one full-bleed surface: on phones it takes the full
viewport height, and steps expand in place rather than opening side panels.
## Elevation & Depth
The system is flat, with tonal layers. Depth comes from surface steps (canvas,
workspace, card, popover) and from hairlines and 1px rings. Shadows are reserved
for things that float above the page: menus, popovers, dialogs and an expanded
canvas node.
### Shadow Vocabulary
- **Rest** (`box-shadow: 0 1px 2px rgba(0, 0, 0, 0.4)` dark, `0 1px 2px
rgba(31, 31, 29, 0.06)` light): the top bar and canvas nodes at rest; barely
there.
- **Float** (`box-shadow: 0 8px 28px rgba(0, 0, 0, 0.4)` dark, `0 8px 28px
rgba(31, 31, 29, 0.1)` light): popovers, menus, dialogs and the expanded step
node.
### Named Rules
**The Flat By Default Rule.** Cards sit on the page with a 1px ring, not a
shadow. A larger shadow means the element floats above the page.
## Shapes
Gently rounded and consistent. Controls, inputs and canvas nodes use 8px corners
(`rounded.lg`); cards use 12px (`rounded.xl`); badges use 4px (`rounded.sm`), and
small buttons step down to 6px. Status dots and avatars are the only full circles.
Borders are 1px and quiet; a strong border marks structural edges such as the top
bar. Focus is always a visible 2px ring offset by 2px, in sage.
## Components
Compact and contextual: small controls that appear where the work is.
### Buttons
- **Shape:** gently rounded (8px), 36px tall by default, with 32px and 24px sizes
and square icon variants.
- **Primary:** Signal Sage Deep fill with white label text. At most one per view.
- **Ghost / Outline / Secondary:** transparent or hover-surface fills that pick
up the hover surface on hover; the default for everything that is not the main
action.
- **Attention:** amber stroke and soft amber fill, for an action that exists
because something is waiting. Not destructive.
- **Destructive:** soft clay fill with clay text, never a solid red block.
- **Hover / Focus:** 140ms colour transitions, a 3px sage focus ring, and a 1px
downward press on active.
### Chips (Badges)
- **Style:** 20px tall, 4px corners, caption type. Status badges (`ok`, `warn`,
`danger`, `info`, `idle`) set the solid tone on its soft background.
- **State:** the badge and the StatusDot are the only places status colour is
decided.
### Cards / Containers
- **Corner Style:** 12px.
- **Background:** the card surface on the workspace.
- **Shadow Strategy:** none; a 1px foreground ring at 10% (see Elevation).
- **Internal Padding:** 16px, or 12px for the small size. Section wraps a card
with a title; an edited section shows a sage ring.
### Inputs / Fields
- **Style:** card background, 1px input stroke, 8px corners, 36px tall, label
size (title size on touch screens so phones do not zoom).
- **Focus:** the border turns sage with a 3px sage ring.
- **Error / Disabled:** a clay border and ring; disabled fields drop to 50%
opacity.
### Navigation
- **Sidebar:** card surface, label-size rows, uppercase section labels in Text
Subtle, the hover surface on hover and active. Collapses on phones.
- **Top bar:** card surface, 56px, strong bottom border with the rest shadow,
breadcrumb on the left and a connection pill and account menu on the right.
### Status Dot
A 6px circle in one of the five status tones. It pulses (motion-safe only) while
the thing it marks is live.
### Step Node (Signature Component)
The workflow canvas card. 240px wide at rest, with an 8px corner, the rest shadow
and a caption row naming the step type with a sage icon. The run duration sits on
the right in mono, beside a status icon. The title below is label size and medium
weight. Selecting it expands it in place to 416px with the float shadow and a 2px
sage ring, main field first. The same card shows the step's live run state:
editor and observer are one surface. Added, removed and changed steps are marked
in the sage, clay and amber tones.
## Do's and Don'ts
### Do:
- **Do** use semantic tokens (`bg-card`, `text-fg-muted`, `bg-ok-soft`) and the
named type steps, so both themes and compact density work without extra code.
- **Do** keep one filled primary button per view; everything else is ghost,
outline or secondary.
- **Do** set IDs, versions, durations and payloads in Plex Mono.
- **Do** show actions on hover or focus where the work is, and make every hover
action reachable by keyboard.
- **Do** honour reduced motion: nothing animates when the operator asks it not to.
### Don't:
- **Don't** use generic SaaS gloss: no purple or multicolour gradients, no glow
shadows, no glassmorphism cards, no gradient text.
- **Don't** make it toy-like on phones: no blanket 44px minimum sizes on buttons,
links and fields. Widen the tap area invisibly with `touch-hit` instead.
- **Don't** tint backgrounds for hierarchy; use surface steps and borders.
- **Don't** introduce a new hue or reuse a status colour for decoration.
- **Don't** put white text on a status fill; use the soft background and the
solid tone.
- **Don't** add a shadow to a resting card.
+119
View File
@@ -0,0 +1,119 @@
# Product
<!-- impeccable:product-schema 1 -->
## Platform
web
## Users
Archie's audience comes in two stages.
1. **Now: the solo operator.** An infrastructure or IT operations engineer who
runs their own estate of VMs, containers and on-prem hosts, self-hosts
Archie, and wants day-2 operations handled without babysitting: disks filling
up, alerts firing, routine maintenance. They use the dashboard on desktop and
phone, and talk to Archie through chat channels.
2. **Next: the IT operations team.** A team inside an organisation where an
application owner (recorded in the CMDB) approves production changes on the
servers that belong to their application. Governance, audit and risk
controls decide whether the team adopts it.
## Product Purpose
Archie is event-driven agentic automation. It hears an event (an alert, a
webhook, a schedule, a chat message, an issue), works out what it means, decides
what to do, and does the work through an agent. It judges every action before
the action runs, and delivers the result wherever it needs review or action.
Success: an operator connects a source and Archie notices events, acts without
being asked when it is allowed to, and calls the operator in only when policy or
risk requires it, with an explanation of what it found and did.
The loop is Hears, Understands, Decides, Defines, Does, Delivers. The platform
around it Governs, Reports, Assesses, Manages Risk and Invokes Policy.
## Positioning
In order of importance:
1. **Earned, explained autonomy.** Guards (policy, risk and others, each an
extension) score every action before it runs, and those scores set how much
the agent may do alone. Autonomy is graded per action, earned from approval
history, and always explained. Loosening a ceiling always needs approval from
someone with authority; it never happens automatically.
2. **Proposals from unhandled events.** The operator states intent rather than
wiring steps. Events that nothing handles become proposals, and workflows
learn from outcomes. Archie writes, runs and changes its own workflows; the
operator can view or edit them but should not need to.
3. **Self-hosted operations on VM and on-prem estates.** Archie runs in the
operator's own environment and acts directly, or through the automation a
team already has (AAP, Semaphore, ServiceNow).
Archie executes agentic work itself. It is not only a judgement layer, and not
another visual workflow builder in the n8n, Zapier or Make mould.
## Operating Context
- Events arrive from monitoring (for example Alertmanager on Prometheus),
webhooks, schedules, chat channels and forges. A forge is one source among
many; a repository is an optional input to a workflow, never the point.
- Results and approval requests go out as events to any channel (Telegram,
Slack, Discord, email, webhooks, the dashboard chat composer) and come back in.
- An approver can be an operator, a rule, a classifier or an automatic decision.
Never assume a human approver.
- Channels, forges, connectors, secret engines and guards ship as extensions,
not in-tree.
- The leading demonstration is proactive day-2 operations: a disk-filling alert
from Prometheus, investigated and remediated, with the operator told on both a
chat channel and the dashboard.
## Capabilities and Constraints
- One self-contained binary, `archie`, backed by PostgreSQL. Docker is never
the only mechanism for isolation or enforcement.
- The dashboard is a Vue single-page app embedded in the binary, used on
desktop and phone.
- The dashboard is the complete control plane: every configuration and mutable
setting is editable there. A setting reachable only through a file, flag or
API is a defect. Secrets are write-only.
- Every request and response of every judge, guard, action, model call,
delivery and evaluation is recorded for audit, never including credentials.
- Terminology: source, event, workflow, run, step, guard, approval, proposal,
connector, delivery. "Bindings" is a known-obscure name awaiting a
replacement.
- Undecided: the replacement for bindings and issue routing in the Decide step;
how guard scores combine into an autonomy mode; how Deliver works without
hard-coded outputs.
## Brand Commitments
- Name: Archie. Tagline: "Event-driven Agentic Automation".
- Assets in `assets/brand/`: wordmark (light, dark, mono), mark, app icon,
social card.
- Interface copy states the problem and the action only. It never explains the
interface, restates a title, or describes the mechanism behind it.
- Never frame the product around coding or a repository.
## Evidence on Hand
- Live staging deployment of the single binary, with real Prometheus alerts,
Telegram, Semaphore and host connectors.
- No customers, testimonials, benchmarks, pricing or press exist. Do not
fabricate any.
## Product Principles
1. **Governance is the product.** Judgement before every action, a full audit
record, and autonomy that is earned and explained are what make Archie worth
adopting. Keep them visible, not buried.
2. **Intent, not wiring.** The operator says what they want; Archie defines the
workflow. Editing is available, never required.
3. **Editor and observer are one live surface.** Workflows are defined,
connected and watched on the same interactive canvas, updating live as
events and runs flow through it. Nodes show what they do.
4. **Interrupt only when it matters.** Archie calls the operator in when policy
or risk requires it, with what it found and what it did, not to report
routine success.
5. **Everything operable from the dashboard.** No setting needs a server login.
+6 -2
View File
@@ -17,8 +17,8 @@ network operations, service management, and software delivery. You define the
process and the access it requires; agents work through its stages, using the process and the access it requires; agents work through its stages, using the
context of each event to decide how to accomplish the task. context of each event to decide how to accomplish the task.
Archie is under active development and not every capability below is Archie is under active development and some capabilities below remain
finished. unfinished.
## From an event to an outcome ## From an event to an outcome
@@ -150,6 +150,10 @@ another [deployment template](deployments/README.md).
<http://localhost:5173>, using [`deployments/dev.toml`](deployments/dev.toml). <http://localhost:5173>, using [`deployments/dev.toml`](deployments/dev.toml).
`task check` is the quality gate; [AGENTS.md](AGENTS.md) lists its tools. `task check` is the quality gate; [AGENTS.md](AGENTS.md) lists its tools.
| Project skill | Use |
| --- | --- |
| [`/technical-prose-cleanup`](.github/skills/technical-prose-cleanup/SKILL.md) | Review technical writing in one module without changing behaviour. |
## Documentation ## Documentation
- [Your first playbook](docs/guides/first-playbook.md) - [Your first playbook](docs/guides/first-playbook.md)
+4 -4
View File
@@ -2,7 +2,7 @@
One `v*` tag names a release. One version covers every process in the host One `v*` tag names a release. One version covers every process in the host
bundle (`archied`, `archie-gateway`, `archie-state-store`, `archie-ui`, bundle (`archied`, `archie-gateway`, `archie-state-store`, `archie-ui`,
`archie-messaging`) and the `archie-agent` image. Nothing is released from a `archie-messaging`) and the `archie-agent` image. No release comes from a
laptop. laptop.
## Cutting a release ## Cutting a release
@@ -19,12 +19,12 @@ the deploy.
The tag push runs `deploy.yml`: The tag push runs `deploy.yml`:
- **Gate.** `task check dist TEST_FLAGS=-count=1` and `govulncheck`. The - **Gate.** `task check dist TEST_FLAGS=-count=1` and `govulncheck`. The
binaries the zip ships are built in the same run, so nothing is compiled same run builds the binaries the zip ships, so it compiles nothing again
again after the gate. after the gate.
- **Images.** `archied:v<version>` and `archie-agent:v<version>`, plus - **Images.** `archied:v<version>` and `archie-agent:v<version>`, plus
`sha-<commit>` tags. `:latest` moves only on promotion. `sha-<commit>` tags. `:latest` moves only on promotion.
- **The signed release.** `archied release publish` signs a statement - **The signed release.** `archied release publish` signs a statement
(version, issued_at, zip digest, agent image by digest) with (version, `issued_at`, zip digest, agent image by digest) with
`RELEASE_SIGNING_KEY` and pushes it with the distribution zip to `RELEASE_SIGNING_KEY` and pushes it with the distribution zip to
`git.catlow.cloud/sam/archie` as `v<version>` and `next`. It never moves `git.catlow.cloud/sam/archie` as `v<version>` and `next`. It never moves
`stable`. `stable`.
+78
View File
@@ -64,6 +64,18 @@ tasks:
- task: db:generate - task: db:generate
- git diff --exit-code -- internal/infrastructure/postgres/postgresdb - git diff --exit-code -- internal/infrastructure/postgres/postgresdb
pages:generate:
desc: Write the dashboard's page catalogue to ui/pages/pages.json
dir: ui
cmds:
- node --experimental-strip-types scripts/pages.ts
pages:check:
desc: Regenerate the page catalogue and reject uncommitted differences
cmds:
- task: pages:generate
- git diff --exit-code -- ui/pages/pages.json
openapi:generate: openapi:generate:
desc: Write the API's OpenAPI document to api/openapi.yaml desc: Write the API's OpenAPI document to api/openapi.yaml
cmds: cmds:
@@ -211,6 +223,30 @@ tasks:
- task: dev:wait-state - task: dev:wait-state
- go run ./cmd/archie-messaging -config-overlay deployments/dev.toml - go run ./cmd/archie-messaging -config-overlay deployments/dev.toml
dev:archie:
desc: Run the single archie binary against the development PostgreSQL (admin token "dev")
deps: [dev:postgres]
vars:
DIR: tmp/dev-archie
cmds:
- |
set -eu
mkdir -p {{.DIR}}
# Generated once: the age identity seals the dev credentials, so keep
# it across runs. Roles come from dev:postgres.
if [ ! -f {{.DIR}}/config.toml ]; then
umask 077
{
echo 'listen = "127.0.0.1:8080"'
echo "admin_token_sha256 = \"$(printf dev | sha256sum | cut -d' ' -f1)\""
echo "age_identity = \"$(go run ./cmd/archie -new-age-identity)\""
echo '[database]'
echo 'url = "postgres://archie_runtime:archie@127.0.0.1:5432/archie?sslmode=disable"'
echo 'owner_url = "postgres://archie_migrator:archie@127.0.0.1:5432/archie?sslmode=disable"'
} > {{.DIR}}/config.toml
fi
- go run ./cmd/archie -config {{.DIR}}/config.toml
dev:ui: dev:ui:
desc: Run Vite (requires the dashboard backend) desc: Run Vite (requires the dashboard backend)
dir: ui dir: ui
@@ -320,12 +356,54 @@ tasks:
# delete Go sources mid-walk. Install first, then fan out. Every Go step # delete Go sources mid-walk. Install first, then fan out. Every Go step
# embeds ui/dist, so the dashboard is built before any of them. # embeds ui/dist, so the dashboard is built before any of them.
- task: ui - task: ui
- task: pages:check
- task: fmt - task: fmt
- task: proto:check - task: proto:check
- task: db:check - task: db:check
- task: openapi:check - task: openapi:check
- task: check:readonly - task: check:readonly
wt:check:
desc: "Fix, format and check a worktree's Go packages, and the dashboard if ui/ changed (-- ./pkg/... to name packages; default: those changed since main)"
# A worktree has no ui/dist, so the Go steps build with no_ui. The full
# gate still runs once, on the merged tree.
cmds:
- |
set -eu
base="$(git merge-base HEAD main)"
changed="$( { git diff --name-only "$base"; git ls-files --others --exclude-standard; } | sort -u)"
pkgs="{{.CLI_ARGS}}"
if [ -z "$pkgs" ]; then
pkgs="$(printf '%s\n' "$changed" | grep '\.go$' | grep -v '^ui/' | xargs -r -n1 dirname | sort -u | while read -r d; do [ -d "$d" ] && echo "./$d"; done | tr '\n' ' ')"
fi
if [ -n "$pkgs" ]; then
echo "packages: $pkgs"
# The same fixes and formatters as task fmt, applied to these
# packages only; see fmt for why go fix runs until it converges.
converged=false
for pass in 1 2 3 4 5 6 7 8 9 10; do
go fix -tags no_ui $pkgs
if go fix -tags no_ui -diff $pkgs >/dev/null; then
converged=true
break
fi
done
if [ "$converged" != true ]; then
echo "go fix still rewrites these packages after 10 passes" >&2
exit 1
fi
golangci-lint fmt $pkgs
go vet -tags no_ui $pkgs
go test -short -tags no_ui $pkgs
golangci-lint run --build-tags no_ui $pkgs
fi
if printf '%s\n' "$changed" | grep -q '^ui/'; then
"{{.TASK_EXE}}" test:ui
fi
if [ -z "$pkgs" ] && ! printf '%s\n' "$changed" | grep -q '^ui/'; then
echo "nothing changed since main"
fi
check:readonly: check:readonly:
internal: true internal: true
deps: deps:
+36 -37
View File
@@ -1,15 +1,15 @@
# Workflow definitions # Workflow definitions
A workflow is a YAML document: an id, what it declares to whatever starts it, A workflow is a YAML document: an id, what it declares to whatever starts it,
and an ordered list of steps. Definitions are stored in the control plane's and an ordered list of steps. Definitions live in the control plane's
`workflow-definitions` resource and edited on the dashboard's Workflows page `workflow-definitions` resource, and operators edit them on the dashboard's
(the Canvas and YAML tabs edit the same document). The shipped workflows are in Workflows page (the Canvas and YAML tabs edit the same document). The shipped
`internal/domain/workflow/shipped/`. workflows are in `internal/domain/workflow/shipped/`.
The server is the authority. It serves the step vocabulary, including each step The server is the authority. It serves the step vocabulary, including each step
type's settings schema, in the `workflow-definitions` catalog entry type's settings schema, in the `workflow-definitions` catalogue entry
(`x-step-types`), and validates every definition when it is saved. This file (`x-step-types`), and validates every definition on save. This file
describes that vocabulary; when they disagree, the catalog wins. describes that vocabulary; when they disagree, the catalogue wins.
```yaml ```yaml
id: implement id: implement
@@ -41,10 +41,10 @@ steps:
|---|---|---| |---|---|---|
| `id` | text | The workflow's name. Required, unique. | | `id` | text | The workflow's name. Required, unique. |
| `steps` | list | The steps, run in order. At least one. | | `steps` | list | The steps, run in order. At least one. |
| `repository` | `required` \| `optional` \| `none` | `required` (the default) clones the task's repository into a worktree. `optional` clones one when the run names a repository and uses a scratch workspace otherwise. `none` never clones; only steps that run without a repository may be used. | | `repository` | `required` \| `optional` \| `none` | `required` (the default) clones the task's repository into a worktree. `optional` clones one when the run names a repository and uses a scratch workspace otherwise. `none` never clones; the workflow may use only steps that run without a repository. |
| `inputs` | mapping | Named, typed values whatever starts the run must supply: `{type, required}`, where type is `string`, `number`, `bool`, `object`, `array` or `any`. Steps read them as `{{ inputs.<name> }}`. | | `inputs` | mapping | Named, typed values whatever starts the run must supply: `{type, required}`, where type is `string`, `number`, `bool`, `object`, `array` or `any`. Steps read them as `{{ inputs.<name> }}`. |
| `outputs` | mapping | Named, typed results the run writes once each (same shape as inputs). A required output the run never writes parks it. A calling workflow reads them. | | `outputs` | mapping | Named, typed results the run writes once each (same shape as inputs). A required output the run never writes parks it. A calling workflow reads them. |
| `profile` | text | The container profile (`[containers.profiles]`) the run's agents use. Resolved when the task is dispatched. | | `profile` | text | The container profile (`[containers.profiles]`) the run's agents use. Resolution happens at dispatch. |
| `identity` | text | The identity every run acts as, whatever started it. Empty runs as the starter. | | `identity` | text | The identity every run acts as, whatever started it. Empty runs as the starter. |
## A step ## A step
@@ -72,13 +72,13 @@ Any string setting may contain `{{ path }}`, replaced when the step runs:
| `task.issue`, `task.pr` | Issue and pull request numbers. | | `task.issue`, `task.pr` | Issue and pull request numbers. |
| `task.plan` | The plan a `workflow.approve` step handed over (an approved PRD). | | `task.plan` | The plan a `workflow.approve` step handed over (an approved PRD). |
| `task.review` | The review comments a remediation round addresses. | | `task.review` | The review comments a remediation round addresses. |
| `inputs.<name>` | A declared input; an undeclared one is refused at save. | | `inputs.<name>` | A declared input; the server refuses an undeclared one at save. |
| `steps.<id>.summary` | What an earlier step reported, e.g. an agent's finish summary or a gate's output. | | `steps.<id>.summary` | What an earlier step reported, e.g. an agent's finish summary or a gate's output. |
| `steps.<id>.result.<field>` | A field of an earlier agent's structured result, or an output of an earlier `workflow.call` that waits. A field the agent's `result` schema or the callee's `outputs` does not declare is refused at save. | | `steps.<id>.result.<field>` | A field of an earlier agent's structured result, or an output of an earlier `workflow.call` that waits. At save, the server refuses a field that the agent's `result` schema or the callee's `outputs` does not declare. |
Only earlier steps may be referenced; a reference to a later or unknown step is Reference only earlier steps; the server refuses a reference to a later or
refused when the definition is saved. A value that does not exist at run time unknown step on save. A value that does not exist at run time (for instance, a
(for instance, a step that was skipped) renders empty. step the run skipped) renders empty.
### Conditions ### Conditions
@@ -112,12 +112,11 @@ A run ends at the first step that sets an outcome: `workflow.finish`,
completes, with the last step's summary as its detail. A step that fails parks completes, with the last step's summary as its detail. A step that fails parks
the run unless it continues on failure. the run unless it continues on failure.
A parked run can be retried from a top-level step instead of from the start. An operator can retry a parked run from a top-level step instead of from the
The steps before it are skipped and their results stay available to start. The run skips the steps before it and keeps their results available to
references. The resume point is named by the step's id (else its type), so references. The step's id (else its type) names the resume point, so give an id
give an id to any step whose type appears twice. A run with a repository to any step whose type appears twice. A run with a repository resumes only on
resumes only on its pushed branch: work an earlier step did not push is not its pushed branch: work an earlier step did not push is not there.
there.
## Step types ## Step types
@@ -129,11 +128,11 @@ _runs without a repository._
|---|---|---| |---|---|---|
| `extra_rules` | text | Appended to the agent system prompt. | | `extra_rules` | text | Appended to the agent system prompt. |
| `gate` | `repository` \| `test-failure` | Hold the agent to the repository gate before it may finish; test-failure requires the tests to fail. | | `gate` | `repository` \| `test-failure` | Hold the agent to the repository gate before it may finish; test-failure requires the tests to fail. |
| `mission` | text | What the agent is asked to do. May reference {{ task.* }}, {{ inputs.* }} and {{ steps.<id>.* }}. | | `mission` | text | What the step asks the agent to do. May reference {{ task.* }}, {{ inputs.* }} and {{ steps.<id>.* }}. |
| `protect_tests` | bool | Write-block the repository test files. | | `protect_tests` | bool | Write-block the repository test files. |
| `read_only` | bool | Restrict the agent to read-only tools. | | `read_only` | bool | Restrict the agent to read-only tools. |
| `result` | mapping | A JSON Schema object the agent must return; later steps read it as steps.<id>.result. | | `result` | mapping | A JSON Schema object the agent must return; later steps read it as steps.<id>.result. |
| `model` | text | The model alias that runs the agent, e.g. default or fast. Empty means default. | | `model` | text | A model alias configured under Settings > Agent models, such as `fast`. Omit it or use `default` to select the organisation's default agent model. |
### `command.run` ### `command.run`
@@ -155,12 +154,12 @@ _needs a repository._
| `push` | bool | Push the branch after committing. | | `push` | bool | Push the branch after committing. |
| `reference` | `Fixes` \| `Implements` \| `Refs` | How the commit links to the task issue. | | `reference` | `Fixes` \| `Implements` \| `Refs` | How the commit links to the task issue. |
Hooks never run. The commit is created by go-git, which ignores `.git/hooks` Hooks never run. go-git creates the commit, and it ignores `.git/hooks` and
and `core.hooksPath`, and the agent never runs git, so `pre-commit`, `core.hooksPath`; the agent never runs git, so `pre-commit`, `commit-msg` and
`commit-msg` and `prepare-commit-msg` in the checkout are inert files. A `prepare-commit-msg` in the checkout are inert files. A
repository whose rules live only in a hook — a formatter, a secret scanner, repository whose rules live only in a hook (a formatter, a secret scanner,
commitlint, a DCO trailer — gets a commit that does not satisfy them: the run commitlint, a DCO trailer) gets a commit that does not satisfy them. The run
reports success and the pull request fails the check afterwards. Put the same reports success, but the pull request fails the check afterwards. Put the same
commands in `command.run` or the repository gate, which both run in the task commands in `command.run` or the repository gate, which both run in the task
container before this step. container before this step.
@@ -189,7 +188,7 @@ No settings. It runs the repository policy's `tooling` commands, in order, in
the task worktree — the installs a gate needs and the container does not ship the task worktree — the installs a gate needs and the container does not ship
(protoc plugins, linters, generators). A repository that declares none installs (protoc plugins, linters, generators). A repository that declares none installs
nothing and the step succeeds. Place it after `repo.prepare` and before any nothing and the step succeeds. Place it after `repo.prepare` and before any
`gate.*` step: a failing install fails the step with the command and its output `gate.*` step. A failing install fails the step with the command and its output,
and says the gate did not run, so a missing toolchain is not read as a red and says the gate did not run, so a missing toolchain is not read as a red
repository. repository.
@@ -237,7 +236,7 @@ of sending it.
|---|---|---| |---|---|---|
| `channel` | text | The messaging channel to send through. | | `channel` | text | The messaging channel to send through. |
| `chat_id` | text | The channel's identifier for the chat. | | `chat_id` | text | The channel's identifier for the chat. |
| `text` | text | The message. References are filled in. | | `text` | text | The message. The run fills in references. |
A scheduled message is a schedule bound to a workflow whose only step is A scheduled message is a schedule bound to a workflow whose only step is
`message.send`. `message.send`.
@@ -301,16 +300,16 @@ _runs without a repository._
| Setting | Type | Meaning | | Setting | Type | Meaning |
|---|---|---| |---|---|---|
| `detail` | text | Why the task was handed off. | | `detail` | text | Why the workflow handed off the task. |
| `workflow` | text | The workflow the task is requeued under. | | `workflow` | text | The workflow the handoff requeues the task under. |
`command.run` commands are `{name, argv, expect_failure}`: `argv` is the `command.run` commands are `{name, argv, expect_failure}`: `argv` is the
program and its arguments, and `expect_failure` requires a non-zero exit. program and its arguments, and `expect_failure` requires a non-zero exit.
`gate.diff-rules` rules are `{id, level, pattern, path, exclude_path, message}`: `gate.diff-rules` rules are `{id, level, pattern, path, exclude_path, message}`:
`level` (`error` blocks, `warn` reports) and `pattern` (an RE2 expression matched the step requires `level` (`error` blocks, `warn` reports) and `pattern` (an RE2
against each added line) are required; `path` and `exclude_path` are RE2 expression the gate matches against each added line); `path` and `exclude_path`
expressions that limit which files the rule applies to. are RE2 expressions that limit which files the rule applies to.
## What starts a workflow ## What starts a workflow
@@ -320,8 +319,8 @@ expressions that limit which files the rule applies to.
classifies it and hands off. classifies it and hands off.
- **Event bindings**: a webhook source mapped onto a workflow and its inputs - **Event bindings**: a webhook source mapped onto a workflow and its inputs
(Events page). (Events page).
- **Schedules**: each firing is captured on the reserved `schedule` source as - **Schedules**: the scheduler captures each firing on the reserved `schedule`
a `Schedule fired` event (`schedule_id`, `name`, `scheduled_for`, source as a `Schedule fired` event (`schedule_id`, `name`, `scheduled_for`,
`fired_at`). A schedule trigger is a binding on that source using the `fired_at`). A schedule trigger is a binding on that source using the
`schedule-fired` mapping, filtered to one `schedule_id`. A firing starts at `schedule-fired` mapping, filtered to one `schedule_id`. A firing starts at
most one task per binding. most one task per binding.
+7085 -342
View File
File diff suppressed because it is too large. Load diff
+21 -8
View File
@@ -19,20 +19,31 @@ const recoveryUsage = `usage: archie-state-store <command> [flags]
With no command, archie-state-store serves the State Store gRPC contract. With no command, archie-state-store serves the State Store gRPC contract.
The recovery commands are how an operator recovers a database the control The recovery commands operate on the PostgreSQL database configured by
plane will not start on. They operate on the PostgreSQL database the database_url. Install the PostgreSQL client tools (pg_dump, pg_restore and
configuration's database_url names, through pg_dump and pg_restore (which psql) and make sure they're on PATH.
must be on PATH).
backup takes a consistent snapshot of a serving database. restore is backup takes a consistent snapshot of a serving database. restore is
destructive and offline: stop every archie service first, since it refuses destructive and offline: stop every archie service first, since it refuses
while any of them holds its ownership claim, and every write made after the while any of them holds its serving claim or the exclusive restore lock, and
snapshot is lost. rollback refuses while the State Store serves. There is no every write made after the snapshot is lost. rollback refuses while the State
automatic schema rollback: the way back from a migration is restoring the Store serves. There is no automatic schema rollback: the way back from a
snapshot taken before it. migration is restoring the snapshot taken before it.
restore re-applies the deletions recorded outside the database, and refuses when
the record cannot account for them. Keep that record with your snapshots: a
snapshot restored without the current record cannot show which notes were
forgotten after it was taken. Nothing about a snapshot and a record can prove the
record is the newest one; that is the operator's responsibility, and this is why
a restore that cannot account for the data needs -accept-unrecorded-deletions,
which means forgotten notes may return.
backup -out FILE write a snapshot of the database backup -out FILE write a snapshot of the database
restore -from FILE replace the database with a snapshot restore -from FILE replace the database with a snapshot
[-accept-unrecorded-deletions]
proceed although the record of deletions
cannot account for this data, so forgotten
notes may return
validate check the database, its stored settings and validate check the database, its stored settings and
the configuration the daemon would boot with the configuration the daemon would boot with
rollback -kind KIND replay an earlier revision of a stored rollback -kind KIND replay an earlier revision of a stored
@@ -67,6 +78,8 @@ func runRecovery(args []string, stdout, stderr io.Writer) int {
flags.StringVar(&options.From, "from", "", "snapshot file restore reads") flags.StringVar(&options.From, "from", "", "snapshot file restore reads")
flags.StringVar(&options.Kind, "kind", "", "control-plane resource kind rollback replays") flags.StringVar(&options.Kind, "kind", "", "control-plane resource kind rollback replays")
flags.Int64Var(&options.Revision, "revision", 0, "revision rollback replays (default: the newest one older than the current value)") flags.Int64Var(&options.Revision, "revision", 0, "revision rollback replays (default: the newest one older than the current value)")
flags.BoolVar(&options.AcceptUnrecordedDeletions, "accept-unrecorded-deletions", false,
"restore although the record of deletions cannot account for this data: forgotten notes may return")
// The configuration names the PostgreSQL database, and validate also checks // The configuration names the PostgreSQL database, and validate also checks
// the stored settings against it. // the stored settings against it.
flags.StringVar(&options.Config, "config", configuration.DefaultConfigPath(), "configuration file or directory the daemon boots with") flags.StringVar(&options.Config, "config", configuration.DefaultConfigPath(), "configuration file or directory the daemon boots with")
+9
View File
@@ -98,6 +98,15 @@ target = "127.0.0.1:9090"
# catalogue = "registry.example/owner/archipelago/catalogue" # catalogue = "registry.example/owner/archipelago/catalogue"
# catalogue_key = "base64 public key" # catalogue_key = "base64 public key"
# The image task containers run. There is no default: the daemon reports a
# missing containers.image at startup instead of guessing a registry, so set
# your own pinned reference -- see
# deployments/systemd-user-service.md#6-pinning-the-archie-agent-image.
# [containers]
# image = "registry.example.com/archie/archie-agent@sha256:<digest>"
# pull_policy = "missing"
# registry_auth = { engine = "env", key = "ARCHIE_REGISTRY_AUTH" } # when the registry needs a login
# Long-running agent loops that maintain memory, skills and — in dry run — # Long-running agent loops that maintain memory, skills and — in dry run —
# file follow-up issues from recent runs. Definitions are data: the server # file follow-up issues from recent runs. Definitions are data: the server
# validates them and the gateway applies them live. # validates them and the gateway applies them live.
+22 -19
View File
@@ -16,10 +16,12 @@ of its own (`deployments/systemd-user-service.md`).
`archie-agent` (the per-task sandboxed runtime) has no unit of its own. The `archie-agent` (the per-task sandboxed runtime) has no unit of its own. The
agent image is a separate thing, pulled for the containers `archied` spawns agent image is a separate thing, pulled for the containers `archied` spawns
per task: `[containers].image` defaults to per task: `[containers].image` has no default, and the daemon reports it as
`git.catlow.cloud/sam/archie-agent:latest`, while this archive's `release.json` missing at startup. This archive's `release.json` pins the digest the release
pins the digest the release published. Set `[containers].registry_auth` when published, and the deploy step passes it to the install, so a release install
that reference is on a registry that needs a login -- see needs nothing by hand; a from-source install sets the image itself. Set
`[containers].registry_auth` when the reference is on a registry that needs a
login -- see
`deployments/systemd-user-service.md#6-pinning-the-archie-agent-image`. `deployments/systemd-user-service.md#6-pinning-the-archie-agent-image`.
## Quickstart ## Quickstart
@@ -45,8 +47,8 @@ that reference is on a registry that needs a login -- see
3. Start the five processes. Order does not matter: a service whose peer is 3. Start the five processes. Order does not matter: a service whose peer is
not up yet waits for it and reports it as degraded on its health surface not up yet waits for it and reports it as degraded on its health surface
meanwhile. The Gateway waits for the daemon's NATS endpoint when the broker meanwhile. The Gateway waits for the daemon's NATS endpoint when the daemon
is embedded. runs the embedded broker.
```bash ```bash
./archie-state-store -config ~/.config/archie/config.toml -listen 127.0.0.1:9090 & ./archie-state-store -config ~/.config/archie/config.toml -listen 127.0.0.1:9090 &
@@ -66,16 +68,16 @@ that reference is on a registry that needs a login -- see
## Version ## Version
This archive's binaries are built from the `archied` release tag in its The release pipeline builds this archive's binaries from the `archied` release
filename; `archie-ui`, `archie-gateway`, `archie-state-store` and tag in its filename. `archie-ui`, `archie-gateway`, `archie-state-store` and
`archie-messaging` ship at that same version rather than `archie-messaging` ship at that same version rather than
being independently tagged (see `RELEASING.md` in the source repository for why being independently tagged (see `RELEASING.md` in the source repository for why
only `archied` and `archie-agent` are independently versioned). only `archied` and `archie-agent` are independently versioned).
`archie-state-store`, `archie-gateway`, `archie-messaging`, `archie-ui` and `archie-state-store`, `archie-gateway`, `archie-messaging`, `archie-ui` and
`archied` are services that must be running and addressable; `archie-messaging` `archied` are services that must be running and addressable. `archie-messaging`
carries the Telegram, email and webhook channels since the v1.30.0 extraction, so carries the Telegram, email and webhook channels since the v1.30.0 extraction, so
an install (or an upgrade across v1.30.0) needs its unit as well -- see an install (or an upgrade across v1.30.0) needs its unit as well. See
`deployments/systemd-user-service.md`. `deployments/systemd-user-service.md`.
### Native self-update ### Native self-update
@@ -84,8 +86,8 @@ Install on Settings → Status runs `archied update install -version X` against
the release source in the update settings. It fetches release `vX`, refuses it the release source in the update settings. It fetches release `vX`, refuses it
unless the source's key signed its statement, and downloads the Linux/amd64 zip unless the source's key signed its statement, and downloads the Linux/amd64 zip
only if it hashes to the digest that statement names. Every host binary in the only if it hashes to the digest that statement names. Every host binary in the
zip must report `X`. It then pulls the agent image the statement pins by digest, backs up the database to zip must report `X`. It then pulls the agent image the statement pins by digest and backs up the database to
`db.pre-update.dump` in the state directory, stages the new binaries beside the `db.pre-update.dump` in the state directory. It stages the new binaries beside the
live ones and hands the transaction to `archied update watchdog` in a process of live ones and hands the transaction to `archied update watchdog` in a process of
its own (a transient systemd user unit). Nothing that runs changes until the its own (a transient systemd user unit). Nothing that runs changes until the
watchdog takes over. watchdog takes over.
@@ -106,9 +108,10 @@ staged executables by rename, switches the control-plane image policy (only the
image field, with conflict detection), and restarts the units in order through image field, with conflict detection), and restarts the units in order through
`systemctl --user`. archied must report the new version and stay healthy for `systemctl --user`. archied must report the new version and stay healthy for
120 seconds. Otherwise the watchdog restores the previous binaries and image 120 seconds. Otherwise the watchdog restores the previous binaries and image
policy. Data is not rolled back unless the new release migrated the database: policy. Data is not rolled back unless the new release migrated the database.
then the previous binaries cannot serve it, so the pre-update backup is restored Then the previous binaries cannot serve it, so the watchdog restores the
and the outcome report says that every write since the update began is gone. pre-update backup, and the outcome report says that the restore discarded every
write since the update began.
Without a systemd user manager the watchdog switches binaries and image policy Without a systemd user manager the watchdog switches binaries and image policy
but restarts nothing, and the install reports that the services need a manual but restarts nothing, and the install reports that the services need a manual
restart. restart.
@@ -116,10 +119,10 @@ restart.
Transactions live in `${XDG_STATE_HOME:-~/.local/state}/archie/update`, outside Transactions live in `${XDG_STATE_HOME:-~/.local/state}/archie/update`, outside
the binary directory: `transaction/journal.json`, `transaction/previous/`, and the binary directory: `transaction/journal.json`, `transaction/previous/`, and
`transaction/archied`, the frozen copy of the archied that wrote the journal. On `transaction/archied`, the frozen copy of the archied that wrote the journal. On
daemon boot, an interrupted transaction is daemon boot, archied hands an interrupted transaction to that frozen watchdog
handed to that frozen watchdog with `-recover` before normal startup: a with `-recover` before normal startup. The watchdog discards a transaction that
transaction that never started is discarded, one that was switching or observing never started, rolls back one that was switching or observing, and finishes a
is rolled back, and a decided one is finished. To recover manually, run decided one. To recover manually, run
`transaction/archied update watchdog -recover -bin-dir ~/.local/bin` from that `transaction/archied update watchdog -recover -bin-dir ~/.local/bin` from that
state directory. A failed recovery keeps the journal for another attempt. state directory. A failed recovery keeps the journal for another attempt.
+13 -14
View File
@@ -42,9 +42,9 @@ systemctl --user start archied
Start order does not matter: a service waits for its peers and reports them as Start order does not matter: a service waits for its peers and reports them as
degraded meanwhile. Every template needs PostgreSQL 18 at `database_url`; degraded meanwhile. Every template needs PostgreSQL 18 at `database_url`;
`docker compose up -d postgres` provides the default server. Its two login `docker compose up -d postgres` provides the default server.
roles are created once per database by `archie-state-store provision` -- see `archie-state-store provision` creates its two login roles once per database --
[Database roles](#database-roles). see [Database roles](#database-roles).
The State Store service (`archie-state-store`) owns the task data in the The State Store service (`archie-state-store`) owns the task data in the
PostgreSQL database `database_url` names and serves the `StateStore` gRPC PostgreSQL database `database_url` names and serves the `StateStore` gRPC
@@ -69,7 +69,7 @@ database and hands the schema to one of them:
change the schema. change the schema.
Run it once per database with a role allowed to create roles and take ownership Run it once per database with a role allowed to create roles and take ownership
of the schema (the database owner or a superuser), then point the templates at of the schema (the database owner or a superuser). Then point the templates at
the two roles: `database_url` is the runtime URL and `migration_database_url` the two roles: `database_url` is the runtime URL and `migration_database_url`
the migration one. The command is idempotent, so re-running it after an upgrade the migration one. The command is idempotent, so re-running it after an upgrade
reconciles objects a migration added. reconciles objects a migration added.
@@ -87,7 +87,7 @@ schema and serves, which is what an install that has not split the roles does.
## Running the dashboard ## Running the dashboard
The dashboard is served by the standalone UI Service (`archie-ui`), not by The standalone UI Service (`archie-ui`) serves the dashboard, not
`archied`. `archied`.
It reads the same `config.toml`, dials the Gateway and State Store targets It reads the same `config.toml`, dials the Gateway and State Store targets
already configured there, and binds `[web].listen` (`127.0.0.1:8484` by already configured there, and binds `[web].listen` (`127.0.0.1:8484` by
@@ -99,17 +99,16 @@ archie-ui -config ~/.config/archie/config.toml
Open the dashboard to configure the organisation, workspace and first administrator account. Open the dashboard to configure the organisation, workspace and first administrator account.
Use HTTPS through a reverse proxy for remote access, and complete setup before exposing it publicly. Use HTTPS through a reverse proxy for remote access, and complete setup before exposing it publicly.
`archied` runs no dashboard listener at all, so webhook capture `archied` runs no dashboard listener at all, so archie-ui receives webhook
(`POST /webhooks/capture/{source}`) is received by archie-ui and the capture (`POST /webhooks/capture/{source}`) and the binding-dispatch loop in
binding-dispatch loop in `archied` consumes what arrives from the shared `archied` consumes what arrives from the shared State Store.
State Store.
The dashboard speaks plain HTTP. A non-loopback bind therefore carries the The dashboard speaks plain HTTP. A non-loopback bind therefore carries the
session cookie and the provider token in clear over the network, and session cookie and the provider token in clear over the network, and
archie-ui warns about exactly that at startup. Terminate TLS in front of it archie-ui warns about exactly that at startup. Terminate TLS in front of it
(a reverse proxy or the tunnel itself) and set (a reverse proxy or the tunnel itself) and set
`[web].trust_forwarded_headers = true` to declare the proxy and silence the `[web].trust_forwarded_headers = true` to declare the proxy and silence the
warning; leaving it off while exposing the port directly is the case the warning. Leaving it off while exposing the port directly is the case the
warning names. warning names.
Auth note: archie-ui authenticates to its dependencies with its `[tls]` Auth note: archie-ui authenticates to its dependencies with its `[tls]`
@@ -150,10 +149,10 @@ curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:9091/healthz #
curl -s http://127.0.0.1:9091/health/detailed # state_db component -> 200, or 503 when degraded curl -s http://127.0.0.1:9091/health/detailed # state_db component -> 200, or 503 when degraded
``` ```
A running State Store holds the `state-store` ownership lock on its database; A running State Store holds the `state-store` ownership lock on its database.
`archied` and `archie-gateway` never open the task tables directly, so a second `archied` and `archie-gateway` never open the task tables directly, so a second
store process on the same `database_url` refuses to start, and a consumer that store process on the same `database_url` refuses to start. A consumer that
opens the task tables indicates dual-store ownership. opens the task tables indicates dual-store ownership.
The readiness probe is the single-writer check the runbook has against a The readiness probe is the single-writer check the runbook has against a
degraded store: a `503` from `/health/detailed` means `archied` should be degraded store: a `503` from `/health/detailed` means the operator should
started only after the store is healthy. start `archied` only after the store is healthy.
+8
View File
@@ -31,6 +31,14 @@ listen = "127.0.0.1:8484"
mode = "embedded" mode = "embedded"
url = "" url = ""
# Task containers run the agent image `task image:agent` builds locally
# (docker-compose.yml tags it git.catlow.cloud/sam/archie-agent:latest), and
# the "missing" pull policy never pulls over the local build. There is no
# code-level default image: an unset containers.image fails validation at
# startup.
[containers]
image = "git.catlow.cloud/sam/archie-agent:latest"
# `task dev` runs archie-state-store via dev:state-store, which passes no # `task dev` runs archie-state-store via dev:state-store, which passes no
# -listen, so the listen below is the port the store binds. It must agree with # -listen, so the listen below is the port the store binds. It must agree with
# the target: these two lines are the only place that pair is stated. Move them # the target: these two lines are the only place that pair is stated. Move them
+8
View File
@@ -58,3 +58,11 @@ models = [
[budgets] [budgets]
max_steps = 60 max_steps = 60
wall_clock = "30m" wall_clock = "30m"
# The image task containers run. There is no default: the daemon refuses to
# start without it and names the key, so set your own pinned reference here --
# see deployments/systemd-user-service.md#6-pinning-the-archie-agent-image.
# [containers]
# image = "registry.example.com/archie/archie-agent@sha256:<digest>"
# pull_policy = "missing"
# registry_auth = { engine = "env", key = "ARCHIE_REGISTRY_AUTH" } # when the registry needs a login
+29 -26
View File
@@ -11,7 +11,7 @@ This runbook describes how to manage `archied` as a background user service on L
with the contents it with the contents it
ships. This page describes what runs and why; the installer owns the contents, ships. This page describes what runs and why; the installer owns the contents,
so inspect a unit with `systemctl --user cat <unit>` rather than copying it from so inspect a unit with `systemctl --user cat <unit>` rather than copying it from
here, where it would drift from what is written. here, where it would drift from what `install.sh` writes.
The Gateway unit is `archie-gateway.service`, written by `install.sh` beside The Gateway unit is `archie-gateway.service`, written by `install.sh` beside
`archied.service`. `archied.service`.
@@ -30,14 +30,14 @@ Docker bridge gateway address, and a non-loopback bind needs `[tls]` (see
### Messaging Service Unit (`~/.config/systemd/user/archie-messaging.service`) ### Messaging Service Unit (`~/.config/systemd/user/archie-messaging.service`)
The Telegram, email and webhook channels are served by `archie-messaging`, not `archie-messaging` serves the Telegram, email and webhook channels, not
by `archied`, since the v1.30.0 extraction. `archied` starts no gateway for them `archied`, since the v1.30.0 extraction. `archied` starts no gateway for them
and logs nothing when one is absent, so a host that updates across v1.30.0 and logs nothing when one is absent. A host that updates across v1.30.0
without this unit runs on with dead channels and a daemon that looks perfectly without this unit runs on with dead channels and a daemon that looks perfectly
healthy. `install.sh` writes this unit on a fresh install; healthy. `install.sh` writes this unit on a fresh install.
`archied update install` refuses an `archied update install` refuses an update when a host is missing a unit and
update when a host is missing a unit and names what is missing, which now fires names what is missing. That now fires for a host that drifted or predates this
for a host that drifted or predates this release rather than the normal path. release rather than the normal path.
It dials the Gateway for the chat contract and the State Store for the stored It dials the Gateway for the chat contract and the State Store for the stored
channel settings, and reads the same `config.toml`, including `[tls]`. channel settings, and reads the same `config.toml`, including `[tls]`.
@@ -48,7 +48,7 @@ each service waits for the peers it needs.
## 2. UI Service Unit (`~/.config/systemd/user/archie-ui.service`) ## 2. UI Service Unit (`~/.config/systemd/user/archie-ui.service`)
The dashboard is served by the standalone UI Service, not by `archied`. It reads the same `config.toml`, dials The standalone UI Service serves the dashboard, not `archied`. It reads the same `config.toml`, dials
the Gateway and State Store targets already in it, and binds `[web].listen`. the Gateway and State Store targets already in it, and binds `[web].listen`.
Open the dashboard to configure the organisation, workspace and first administrator account. Open the dashboard to configure the organisation, workspace and first administrator account.
Complete setup before exposing it publicly; remote access requires an HTTPS reverse proxy. Complete setup before exposing it publicly; remote access requires an HTTPS reverse proxy.
@@ -61,10 +61,10 @@ probe (token-free by design); the authenticated readiness surface lives at
the dashboard's health endpoint behind account authentication. A watchdog can curl the dashboard's health endpoint behind account authentication. A watchdog can curl
`/healthz` without credentials. `/healthz` without credentials.
`install.sh` writes `archie-ui.service`. Browser accounts are configured through the dashboard. `install.sh` writes `archie-ui.service`. Operators configure browser accounts through the dashboard.
`After=` orders the start, it does not wait for the store to bind. The UI `After=` orders the start, it does not wait for the store to bind. The UI
process closes that gap itself: its event pump retries priming with backoff process closes that gap itself. Its event pump retries priming with backoff
until the State Store answers, so the activity feed goes live once the store until the State Store answers, so the activity feed goes live once the store
is up rather than staying history-only until the next restart. is up rather than staying history-only until the next restart.
@@ -129,16 +129,18 @@ systemctl --user stop archied
Embedded NATS is the default. The systemd service runs `archied` natively, so Embedded NATS is the default. The systemd service runs `archied` natively, so
interactive chat keeps the host access the operator configured, while every interactive chat keeps the host access the operator configured, while every
autonomous repository workflow runs in a task-scoped Docker container. No autonomous repository workflow runs in a task-scoped Docker container. The
Compose service or host `archie-agent` binary is required. deployment needs no Compose service or host `archie-agent` binary.
Docker must be installed and reachable by the service user. With no explicit The operator must install Docker and make it reachable to the service user.
broker or container settings, Archie defaults `containers.image` to `containers.image` has no default: with it unset the daemon refuses to start and
`git.catlow.cloud/sam/archie-agent:latest`. `single-forge-github.toml` and names the key, so a fresh install learns about it at startup, not at the first
`docker-nats-stack.toml` override that default with a pinned reference failed pull.
(`standalone.toml` and `dev.toml` leave it) -- see `single-forge-github.toml` and `docker-nats-stack.toml` set a pinned
reference; `standalone.toml` and `dev.toml` leave it for the operator to set
-- see
[Pinning the archie-agent image](#6-pinning-the-archie-agent-image) below. An [Pinning the archie-agent image](#6-pinning-the-archie-agent-image) below. An
explicit equivalent, pinned the same way, is: explicit reference, pinned the same way, is:
```toml ```toml
[nats] [nats]
@@ -155,9 +157,9 @@ and passes the resulting endpoint to each worker. There is no port to publish
and no broker URL to maintain. and no broker URL to maintain.
The State Store is a separate process and, with a container-mode agent, must The State Store is a separate process and, with a container-mode agent, must
be reachable from the container, so bind it to the same bridge gateway with a be reachable from the container. Bind it to the same bridge gateway with a
token and point `[services.state].target` at it (start token and point `[services.state].target` at it (start
`archie-state-store` with `-listen <bridge>:9090 -token <token>`); without a `archie-state-store` with `-listen <bridge>:9090 -token <token>`). Without a
token a non-loopback bind fails closed. For a host-only agent, `127.0.0.1:9090` token a non-loopback bind fails closed. For a host-only agent, `127.0.0.1:9090`
with no token is correct. with no token is correct.
@@ -172,8 +174,8 @@ fall back to a host model loop.
The release pipeline publishes The release pipeline publishes
`git.catlow.cloud/sam/archie-agent` as `:v<version>` and `:sha-<commit>` when `git.catlow.cloud/sam/archie-agent` as `:v<version>` and `:sha-<commit>` when
the commit carries a release tag; an ordinary push to `main` publishes nothing the commit carries a release tag; an ordinary push to `main` publishes nothing
for the agent image, and `:latest` moves only when a release is promoted. A for the agent image, and `:latest` moves only when the release pipeline promotes
distribution zip pins the image its own release a release. A distribution zip pins the image its own release
published, by digest, in `release.json`, and `archied update install` pulls published, by digest, in `release.json`, and `archied update install` pulls
exactly that. exactly that.
@@ -203,8 +205,9 @@ personal access token that can read the package as the password --
`{"username":"<user>","password":"<token>"}`. Put it in `{"username":"<user>","password":"<token>"}`. Put it in
`~/.config/archie/env` as `ARCHIE_REGISTRY_AUTH` so it stays out of `~/.config/archie/env` as `ARCHIE_REGISTRY_AUTH` so it stays out of
`config.toml`. The field is file-owned and settled at boot, so a change takes `config.toml`. The field is file-owned and settled at boot, so a change takes
effect on restart; a value that cannot be read logs a warning and pulls effect on restart. When the daemon cannot read a value, it logs a warning
anonymously, which is the failure the task reports as a capability error. and pulls anonymously, which is the failure the task reports as a capability
error.
The bundled update adapter snapshots the configured `[containers].image` before The bundled update adapter snapshots the configured `[containers].image` before
rebuilding it and restores that image if the restarted daemon fails its health rebuilding it and restores that image if the restarted daemon fails its health
@@ -234,7 +237,7 @@ network = "archie-core_default"
The broker defers every login to archied (NATS auth callout), so a worker logs The broker defers every login to archied (NATS auth callout), so a worker logs
in with its run credential and reaches only its own task's subjects. Generate in with its run credential and reaches only its own task's subjects. Generate
an account nkey (`nk -gen account -pubout`), export its seed as an account nKey (`nk -gen account -pubout`), export its seed as
`NATS_CALLOUT_SEED` for archied and its public key as `NATS_CALLOUT_ISSUER` for `NATS_CALLOUT_SEED` for archied and its public key as `NATS_CALLOUT_ISSUER` for
Compose, and set `NATS_TOKEN` to the same value in both. Compose, and set `NATS_TOKEN` to the same value in both.
+4 -4
View File
@@ -24,9 +24,9 @@ Archie Core uses the GitHub API to:
## Step-by-Step Instructions: Creating a Classic Token ## Step-by-Step Instructions: Creating a Classic Token
1. Navigate to 1. Go to
[GitHub Settings → Developer Settings → Tokens (classic)](https://github.com/settings/tokens). [GitHub Settings → Developer Settings → Tokens (classic)](https://github.com/settings/tokens).
2. Click **Generate new token** → **Generate new token (classic)**. 2. Select **Generate new token** → **Generate new token (classic)**.
3. Set the **Note**: `Archie Core` (or your bot's name). 3. Set the **Note**: `Archie Core` (or your bot's name).
4. Choose an **Expiration** (e.g. 90 days, 1 year, or No expiration for 4. Choose an **Expiration** (e.g. 90 days, 1 year, or No expiration for
dedicated bot accounts). dedicated bot accounts).
@@ -35,9 +35,9 @@ Archie Core uses the GitHub API to:
commenting, pushing branches, and opening PRs). commenting, pushing branches, and opening PRs).
- **`workflow`** (Optional — required if Archie needs to update GitHub - **`workflow`** (Optional — required if Archie needs to update GitHub
Actions workflows). Actions workflows).
6. Scroll to the bottom and click **Generate token**. 6. Scroll to the bottom and select **Generate token**.
7. **Copy your token immediately** (starts with `ghp_...`). You won't be able to 7. **Copy your token immediately** (starts with `ghp_...`). You won't be able to
see it again! see it again.
--- ---
+16 -15
View File
@@ -1,13 +1,13 @@
# Building your first playbook binding # Building your first playbook binding
This walks through the whole no-code path the event-capture epic promises: point This walks through the whole no-code path the event-capture epic promises. Point
an external app's webhook at archie, see the real payload it sends, map the an external app's webhook at archie and see the real payload it sends. Map the
fields you care about, bind them to a workflow, and watch the next matching fields you care about, bind them to a workflow, and watch the next matching
event turn into a task -- no code, no redeploy, no restart. event turn into a task. No code, no redeploy, no restart.
## 1. Create a source and send a test event ## 1. Create a source and send a test event
Open **Events → Inspector** and click **New source**. Archie shows the source's Open **Events → Inspector** and select **New source**. Archie shows the source's
URL and signing secret once; copy both. Point the external app's webhook at that URL and signing secret once; copy both. Point the external app's webhook at that
URL. Send one real event however is easiest for a first test, e.g.: URL. Send one real event however is easiest for a first test, e.g.:
@@ -30,8 +30,8 @@ actual payload from the actual sender, not guessing at a schema in advance.
## 3. Map the fields you care about ## 3. Map the fields you care about
Open **Field mappings** (`/mappings`) → **New mapping**. Pick your captured Open **Field mappings** (`/mappings`) → **New mapping**. Pick your captured
event from the dropdown, then click through its payload tree on the right -- event from the dropdown, then select items in its payload tree on the right.
every key and value is clickable. Clicking a value binds it as a field (name, Every key and value is selectable, and selecting one binds it as a field (name,
JSON path, and an inferred type you can change). Add whichever fields your JSON path, and an inferred type you can change). Add whichever fields your
workflow needs (e.g. the issue title), mark the ones that must be present as workflow needs (e.g. the issue title), mark the ones that must be present as
**Required**, hit **Preview** to confirm they resolve correctly against the real **Required**, hit **Preview** to confirm they resolve correctly against the real
@@ -56,9 +56,9 @@ Save. The binding starts in **draft** -- nothing fires yet.
## 5. Approve it ## 5. Approve it
A **draft** or freshly-**edited** binding needs explicit approval before it can A **draft** or freshly-**edited** binding needs explicit approval before it can
ever match a live event -- this is deliberate, not a missing step: an operator ever match a live event. This is deliberate, not a missing step: an operator
authoring a binding is a considered act, an event arriving is not, and nothing authoring a binding is a considered act, an event arriving is not, and nothing
should self-arm. Click **Approve**. Status becomes **armed**. should self-arm. Select **Approve**. Status becomes **armed**.
## 6. Fire it for real ## 6. Fire it for real
@@ -76,14 +76,15 @@ curl -X POST http://localhost:8484/webhooks/capture/sentry \
-d "$BODY" -d "$BODY"
``` ```
This event is captured as **authenticated**, matched against your armed binding, Archie captures this event as **authenticated**, matches it against your armed
and dispatched into a new task through the exact same gate/worktree/sandbox binding, and dispatches it into a new task through the exact same
pipeline every other task goes through. Check the **Tasks** page; a new task gate/worktree/sandbox pipeline every other task goes through. Check the
should appear, its body built from the fields your mapping resolved. **Tasks** page; a new task should appear, its body built from the fields your
mapping resolved.
## Editing a live binding ## Editing a live binding
Any edit to an armed binding -- even a typo fix -- drops it back to Any edit to an armed binding, even a typo fix, drops it back to
**pending_approval** automatically. This can't be bypassed by editing; it has to **`pending_approval`** automatically. You can't bypass this by editing; you have
be re-approved. When editing, leave the **Shared secret** field blank to keep to re-approve it. When editing, leave **Shared secret** blank to keep
the existing secret; only fill it in if you're deliberately rotating it. the existing secret; only fill it in if you're deliberately rotating it.
+38 -35
View File
@@ -1,24 +1,26 @@
# Self-development loop: archie develops its own codebase # Self-development loop: archie develops its own codebase
**Status:** Decided, not yet built (2026-11-03, sam) **Scope:** how archie **Status:** Decided, not yet built (2026-11-03, sam) **Scope:** how archie
persistently takes on development of archie-core itself. This file records a keeps developing archie-core itself. This file records a
desired state, not an implementation or a product: nothing below exists unless desired state, not an implementation or a product. Nothing below exists unless
the "Built today" section says so. The plan is tracked as epic #1769 with child the "Built today" section says so. Epic #1769 tracks the plan, with child
issues #1770–#1775. This file is a record, not a mechanism: agents only see what issues #1770–#1775. This file is a record, not a mechanism: agents only see what
is in their context, so verify every claim here against the code before acting is in their context, so verify every claim here against the code before acting
on it — where they disagree, the code wins. The boundary below is load-bearing on it. Where they disagree, the code wins. The boundary below is load-bearing
only where it is enforced (the gate, access control, the daemon's git monopoly) only where the code enforces it (the gate, access control, the daemon's git
and stated in `AGENTS.md`; everywhere else this file is a pointer. monopoly) and only where `AGENTS.md` states it. Everywhere else this file is a
pointer.
## Built today ## Built today
The machinery the loop will reuse exists: shipped triage/implement/pr-review The machinery the loop will reuse exists. It includes the shipped
workflows, the adversarial self-review stage before a PR opens (epic #1348, triage/implement/pr-review workflows and the adversarial self-review stage before
closed), the prbench judge for review quality with its acceptance bar, canary a PR opens (epic #1348, closed). It also includes the prbench judge for review
releases judged on the installed release (releaseupdate), and the curator quality with its acceptance bar, canary releases judged on the installed release
engine. What does not exist is the loop itself: no self-intake curator, no (releaseupdate), and the curator engine. What does not exist is the loop itself:
approved-issue auto-run, no judge for diffs, no outcome distillation, no canary no self-intake curator, no automatic run for approved issues, no judge for
routing specific to self-directed changes. diffs, no outcome distillation, no canary routing specific to self-directed
changes.
## Decision ## Decision
@@ -28,41 +30,42 @@ Archie improves its own codebase through a closed loop, built in stages:
gate failures and alerts, dedupes against open issues, and files new issues. gate failures and alerts, dedupes against open issues, and files new issues.
Archie files its own work; the maintainer approves priority. Archie files its own work; the maintainer approves priority.
2. **Approved-issue loop** (#1771): an approved issue runs the shipped 2. **Approved-issue loop** (#1771): an approved issue runs the shipped
triage/implement workflows end to end — read-only plan, gated build, triage/implement workflows end to end. The workflow makes a read-only plan
adversarial self-review, daemon commits and opens a green PR. The maintainer and a gated build, then runs the adversarial self-review; the daemon commits
still merges at this stage. and opens a green PR. The maintainer still merges at this stage.
3. **Implementation judge** (#1772): the prbench judge pattern scores diffs, 3. **Implementation judge** (#1772): the prbench judge pattern scores diffs,
calibrated against the maintainer's merge decisions; auto-merge applies only calibrated against the maintainer's merge decisions. Automatic merge applies
when the gate is green, the review stage is clean, and the judge is above the only when the gate is green, the review stage is clean, and the judge is above
calibrated bar. the calibrated bar.
4. **Outcome distillation** (#1773): a curator turns merged-run postmortems into 4. **Outcome distillation** (#1773): a curator turns merged-run postmortems into
proposals for the repo's agent instructions, each added only because it proposals for the repo's agent instructions. The maintainer adds each
changes a decision; rules that stop changing decisions are removed. proposal only because it changes a decision, and removes rules that stop
changing decisions.
5. **Canary** (#1774): self-directed changes ship through the canary release 5. **Canary** (#1774): self-directed changes ship through the canary release
window and are judged on the installed release before promotion. Rollback is window, and the canary verdict on the installed release gates their
a plain revert, because every self-directed change is one gated commit. promotion. Rollback is a plain revert, because every self-directed change is
one gated commit.
## Boundary ## Boundary
Enforcement lives in the harness, never in the prompt (#1775). Changes to the Enforcement lives in the code, never in the prompt (#1775). Archie may propose
commit gate, the invariants in `AGENTS.md`, access control and grant scoping, changes to the commit gate, the invariants in `AGENTS.md`, access control and
the daemon-only git path, and webhook HMAC verification may be proposed by grant scoping, the daemon-only git path, and webhook HMAC verification. It never
archie but are never merged by archie — they require a maintainer merge. merges them; those changes require a maintainer merge. Everything else
Everything else (workflows, curators, memory, docs, the dashboard) is fair game (workflows, curators, memory, docs, the dashboard) is fair game for the loop.
for the loop.
## Why ## Why
Self-improvement degrades when it relies on the model choosing to follow rules. Self-improvement degrades when it relies on the model choosing to follow rules.
Gates, scoped grants and the daemon's monopoly on git cannot be argued with; a The model can argue with a prompt, not with gates, scoped grants or the daemon's
prompt can. Keeping quality measurable — a judge bar and a canary verdict as monopoly on git. Keeping quality measurable is what lets the loop widen without
numbers, tests guarding the protected seams — is what lets the loop widen turning the codebase to garbage: a judge bar and a canary verdict as numbers,
without turning the codebase to garbage. and tests guarding the protected seams.
## Consequences ## Consequences
- One issue → one small PR applies doubly to self-directed work: past about 100 - One issue to one small PR applies doubly to self-directed work. Past about 100
lines or any new mechanism, the change stops and reassesses. lines or any new mechanism, the change stops and reassesses.
- Every self-directed commit cites the issue that authorized it. - Every self-directed commit cites the issue that authorised it.
- Rule proposals from the distillation curator must name the run that triggered - Rule proposals from the distillation curator must name the run that triggered
them, and `AGENTS.md` stays short enough to read in full every session. them, and `AGENTS.md` stays short enough to read in full every session.
+55 -51
View File
@@ -1,31 +1,31 @@
# User authorization boundaries # User authorisation boundaries
Archie separates authentication (which person or service is calling) from Archie separates authentication (which person or service is calling) from
permission to act on a resource. This inventory follows the permission to act on a resource. This inventory follows the
[OWASP Authentication Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html) [OWASP Authentication Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html)
and and
[Authorization Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html), [Authorization Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html).
including its guidance on attributes and relationships. It describes concrete It includes the guidance on attributes and relationships from the Authorization
enforcement points and their regression tests; it is not a compliance Cheat Sheet. It describes concrete enforcement points and their regression
certification. tests. It is not a compliance certification.
## Transport and authority ## Transport and authority
The browser uses HTTP/JSON and SSE to the UI service. The UI service calls State The browser uses HTTP/JSON and SSE to the UI service. The UI service calls State
Store, Gateway, Messaging and the daemon through their gRPC contracts. Only the Store, Gateway, Messaging and the daemon through their gRPC contracts. Only the
State Store opens the task/control-plane/account database; Gateway owns State Store opens the task/control-plane/account database. Gateway owns
conversation storage. Browser HTTP handlers never open either database. conversation storage. Browser HTTP handlers never open either database.
Instance service credentials are administrative authority. They are not user Instance service credentials are administrative authority. They are not user
sessions and must never reach a browser, model, or agent container. A service sessions and must never reach a browser, model, or agent container. A service
forwarding a principal preserves attribution and tenant scope; forwarding alone forwarding a principal preserves attribution and tenant scope. Forwarding alone
does not mean every internal RPC evaluates Cedar. Most internal RPCs trust the does not mean every internal RPC evaluates Cedar. Most internal RPCs trust the
authenticated service and enforce their own resource scope. The public HTTP authenticated service and enforce their own resource scope. The public HTTP
boundary evaluates Cedar before invoking them. Task credentials have a separate, boundary evaluates Cedar before invoking them. Task credentials have a separate,
explicit RPC allowlist and cannot call account or identity administration. explicit RPC allowlist and cannot call account or identity administration.
Local service listeners are trusted process boundaries. Loopback is not a The services treat local service listeners as trusted process boundaries.
substitute for authentication on a remotely reachable listener. OIDC Loopback does not replace authentication on a remotely reachable listener. OIDC
credentials, local browser sessions, personal API tokens, service credentials, credentials, local browser sessions, personal API tokens, service credentials,
and task grants must remain distinct. and task grants must remain distinct.
@@ -33,52 +33,52 @@ and task grants must remain distinct.
`internal/domain/access` defines actions, resources, principals and memberships. `internal/domain/access` defines actions, resources, principals and memberships.
`internal/infrastructure/access` assembles Cedar entities and evaluates the `internal/infrastructure/access` assembles Cedar entities and evaluates the
instance → organization → workspace → object chain. A forbid wins; each instance → organisation → workspace → object chain. A forbid wins. Each
applicable level must permit the operation. Missing or invalid policy chains applicable level must permit the operation. Missing or invalid policy chains
fail closed. fail closed.
The default policies grant actions through scoped roles. Policies can also The default policies grant actions through scoped roles. Policies can also
restrict a named identity, workspace environment, owner, state, source address, restrict a named identity, workspace environment, owner, state, source address,
signature, run or step. HTTP task decisions now include the stored initiating signature, run or step. HTTP task decisions now include the stored initiating
identity and task state; binding decisions include the stored binding state. The identity and task state. Binding decisions include the stored binding state. The
HTTP source address is the actual connection peer, not an unverified forwarded HTTP source address is the actual connection peer, not an unverified forwarded
header. Membership and resource attributes must come from stored records or header. Membership and resource attributes must come from stored records or
authenticated context, never a request's assertion about itself. authenticated context. They never come from a request's assertion about itself.
Cedar permission is not ownership of another person's private data. Conversation Cedar permission is not ownership of another person's private data. The services
history, passkeys, recovery codes and personal tokens are bound to the person. bind conversation history, passkeys, recovery codes and personal tokens to the
An organization or instance admin role does not override those relationships. person. An organisation or instance admin role does not override those
Account creation uses `manage_members` policy rather than a hard-coded admin relationships. Account creation uses `manage_members` policy rather than a fixed
role. Authenticating through OIDC does not automatically grant membership, link admin role. An OIDC login does not automatically grant membership, link
accounts by unverified email, or create an administrator. accounts by unverified email, or create an administrator.
## Enforcement inventory ## Enforcement inventory
| Location | Enforcement | Regression evidence | | Location | Enforcement | Regression evidence |
| ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Browser credential gate: `webui/auth.go`, `accounts.go` | Account session or verified provider identity; shared dashboard token is not a person when accounts are enabled. No API data before authentication. | `TestAccountBoundary`, `TestAccountSessionFailureIsClosed` | | Browser credential gate: `webui/auth.go`, `accounts.go` | Account session or verified provider identity; shared dashboard token is not a person once setup creates an account. No API data before authentication. | `TestAccountBoundary`, `TestAccountSessionFailureIsClosed` |
| Browser policy gate: `webui/authorize.go` | Resolve principal from stored identity; evaluate action against stored org/workspace and resource kind before handler. Missing chain refuses. | `TestHTTPPolicyCannotBeBypassed`, `TestAuthorizeRefusesWithoutAChain`, `TestAuthorizeRecord`, `TestTaskAuthorizationUsesStoredAttributes`, `TestAuthorizeCreateIn` | | Browser policy gate: `webui/authorize.go` | Resolve principal from stored identity; evaluate action against stored org/workspace and resource kind before handler. Missing chain refuses. | `TestHTTPPolicyCannotBeBypassed`, `TestAuthorizeRefusesWithoutAChain`, `TestAuthorizeRecord`, `TestTaskAuthorizationUsesStoredAttributes`, `TestAuthorizeCreateIn` |
| Instance-only HTTP surfaces: `webui/instance_only.go`, server route registration | Hide instance-owned configuration and diagnostics from another org; policy still applies first. | `TestInstanceOnlyHidesTheInstanceFromOtherOrgs`, `TestInstanceAdminOrgs` | | Instance-only HTTP surfaces: `webui/instance_only.go`, server route registration | Hide instance-owned configuration and diagnostics from another org; policy still applies first. | `TestInstanceOnlyHidesTheInstanceFromOtherOrgs`, `TestInstanceAdminOrgs` |
| First setup: `webui/accounts.go`, `postgres/accounts.go` | Initial organization, workspace, instance URL, admin identity and password commit together. Transaction lock closes bootstrap after first account; later requests require `manage_members`. | Disposable PostgreSQL smoke verification for bootstrap race and rollback; account policy tests below | | First setup: `webui/accounts.go`, `postgres/accounts.go` | Initial organisation, workspace, instance URL, admin identity and password commit together. Transaction lock closes bootstrap after first account; later requests require `manage_members`. | Disposable PostgreSQL smoke verification for bootstrap race and rollback; account policy tests below |
| Account creation: `webui/accounts.go`, `staterpc/accounts.go`, `postgres/accounts.go` | Cedar `manage_members` at HTTP and RPC; target org is authenticated context. New local accounts cannot request owner role. | `TestAccountManagementUsesPolicy`, `TestAccountBoundary` | | Account creation: `webui/accounts.go`, `staterpc/accounts.go`, `postgres/accounts.go` | Cedar `manage_members` at HTTP and RPC; derive the target org from the authenticated context. New local accounts cannot request owner role. | `TestAccountManagementUsesPolicy`, `TestAccountBoundary` |
| Local passwords and sessions: `identity/password.go`, `postgres/accounts.go` | Argon2id, independent salts, length/common-password checks, generic login refusal, account throttling, session hashes and expiry, revocation on logout/password change/suspension. | `TestPasswordVerification`, `TestAccountBoundary`; disposable PostgreSQL session verification | | Local passwords and sessions: `identity/password.go`, `postgres/accounts.go` | Argon2id, independent salts, length/common-password checks, generic login refusal, account throttling, session hashes and expiry, revocation on logout/password change/suspension. | `TestPasswordVerification`, `TestAccountBoundary`; disposable PostgreSQL session verification |
| Transport and CSRF: `webui/accounts.go`, `api_tasks.go` | Password/account mutations require HTTPS or localhost development, JSON, custom CSRF header and same-origin requests. Forwarded headers require explicit trusted-proxy configuration. | `TestAuthenticationTransport`, existing mutation security tests | | Transport and CSRF: `webui/accounts.go`, `api_tasks.go` | Password/account mutations require HTTPS or localhost development, JSON, custom CSRF header and same-origin requests. Forwarded headers require explicit trusted-proxy configuration. | `TestAuthenticationTransport`, existing mutation security tests |
| Personal account routes: `webui/accounts.go` | Active signed-in person; principal supplied by server. Password change verifies current password. Sensitive authenticator changes require recent sign-in. No caller-supplied target identity. | `TestAccountBoundary` | | Personal account routes: `webui/accounts.go` | Active signed-in person; principal supplied by server. Password change verifies current password. Sensitive authenticator changes require recent sign-in. No caller-supplied target identity. | `TestAccountBoundary` |
| Recovery: `postgres/account_security.go`, `webui/accounts.go` | Fresh authenticated owner generates a hashed, one-use recovery secret. Redemption replaces password and revokes all sessions atomically. No email-existence disclosure. | Disposable PostgreSQL recovery verification | | Recovery: `postgres/account_security.go`, `webui/accounts.go` | Fresh authenticated owner generates a hashed, one-use recovery secret. Redemption replaces password and revokes all sessions atomically. No email-existence disclosure. | Disposable PostgreSQL recovery verification |
| Passkeys: `postgres/passkeys.go`, `webui/passkeys.go` | Configured RP origin, browser-bound one-use expiring challenge, verified credential signature and user verification. Enrollment/management belong to caller. Credential counters persist under a row lock. | Disposable browser virtual-authenticator verification; task-grant denial tests | | Passkeys: `postgres/passkeys.go`, `webui/passkeys.go` | Configured RP origin, browser-bound one-use expiring challenge, verified credential signature and user verification. Enrollment/management belong to caller. Credential counters persist under a row lock. | Disposable browser virtual-authenticator verification; task-grant denial tests |
| OIDC: `infrastructure/oidc`, `archieui/account_oidc.go`, `webui/auth.go` | Discovery and signed ID token with issuer/client audience/expiry, PKCE, state and nonce. Verified subject resolves to active identity. Browser-local session cannot outlive provider token, and provider credential remains checked. | `TestBrowserFlowVerifiesIDToken`, `TestProviderOutageIsUnavailableThenRecovers`, subject-claim tests; no external provider acceptance implied | | OIDC: `infrastructure/oidc`, `archieui/account_oidc.go`, `webui/auth.go` | Discovery and signed ID token with issuer/client audience/expiry, PKCE, state and nonce. Verified subject resolves to active identity. Browser-local session cannot outlive provider token, and provider credential remains checked. | `TestBrowserFlowVerifiesIDToken`, `TestProviderOutageIsUnavailableThenRecovers`, subject-claim tests; no external provider acceptance implied |
| OIDC settings: `webui/accounts.go`, `postgres/authentication.go` | Instance ownership plus policy; recent sign-in for changes. Public URL cannot change while enrolled passkeys would be orphaned. | `TestAccountBoundary`, `TestAuthenticationSettingsRejectUntrustedOrigins` | | OIDC settings: `webui/accounts.go`, `postgres/authentication.go` | Instance ownership plus policy; recent sign-in for changes. The instance refuses a public URL change that would orphan enrolled passkeys. | `TestAccountBoundary`, `TestAuthenticationSettingsRejectUntrustedOrigins` |
| Org membership/workspaces/agent assignment: `webui/api_orgs.go`, `staterpc/orgs.go`, `postgres/orgs.go` | Own org or instance-owner relationship, allowed role vocabulary, membership escalation/last-owner guards, tenant-scoped SQL. | `TestOrgRPCsActInTheCallersOrg`, `TestSetMembershipRefusesUnknownRole`, org HTTP tests | | Org membership/workspaces/agent assignment: `webui/api_orgs.go`, `staterpc/orgs.go`, `postgres/orgs.go` | Own org or instance-owner relationship, allowed role vocabulary, membership escalation/last-owner guards, tenant-scoped SQL. | `TestOrgRPCsActInTheCallersOrg`, `TestSetMembershipRefusesUnknownRole`, org HTTP tests |
| Personal API tokens: `webui/api_personal_tokens.go`, `staterpc/personal_tokens.go`, `postgres/personal_tokens.go` | Token owner comes from principal; store only token hash; revoke only caller's binding. | `TestPersonalTokensWithoutPerson`, `TestPersonalTokenOwner` | | Personal API tokens: `webui/api_personal_tokens.go`, `staterpc/personal_tokens.go`, `postgres/personal_tokens.go` | Token owner comes from principal; store only token hash; revoke only caller's binding. | `TestPersonalTokensWithoutPerson`, `TestPersonalTokenOwner` |
| gRPC caller attribution: `rpcidentity/identity.go` | Authenticated service may forward a principal; State Store resolves memberships/org itself. Task grant metadata is stripped. | `TestCallerAttribution` | | gRPC caller attribution: `rpcidentity/identity.go` | Authenticated service may forward a principal; State Store resolves memberships/org itself. State Store strips task grant metadata. | `TestCallerAttribution` |
| Agent/task gRPC: `staterpc/task_grants.go` | Durable task-scoped grant, explicit allowed RPC and target task, no definition-pin replacement, no account RPCs. | `TestTaskCredentialsCannotManageAccounts`, `TestTaskCredentialCannotReplaceItsPin`, `TestRecordUsageAuthority`, `TestWorkerPresenceAuthority` | | Agent/task gRPC: `staterpc/task_grants.go` | Durable task-scoped grant, explicit allowed RPC and target task, no definition-pin replacement, no account RPCs. | `TestTaskCredentialsCannotManageAccounts`, `TestTaskCredentialCannotReplaceItsPin`, `TestRecordUsageAuthority`, `TestWorkerPresenceAuthority` |
| Chat HTTP: `webui/api_chat.go` | Server stamps sender and person thread; lists/read/turns/cancel/persona verify session ownership. Browser cannot submit another sender identity. | `TestWebChatOwnership`, `TestWebChatSenderCannotBeSuppliedByBrowser`; HTTP deny matrix | | Chat HTTP: `webui/api_chat.go` | Server stamps sender and person thread; lists/read/turns/cancel/persona verify session ownership. Browser cannot submit another sender identity. | `TestWebChatOwnership`, `TestWebChatSenderCannotBeSuppliedByBrowser`; HTTP deny matrix |
| Chat history, slash commands and model session tools: `gateway/session_store_postgres.go` | Store filters `Get`, `List`, `GetByChannel`; shared read/write guards check person ownership as well as org. A saved session cannot change its conversation source to claim another person's history. Service curation runs without a person principal. | `TestSessionVisibility`; PostgreSQL smoke for history isolation | | Chat history, slash commands and model session tools: `gateway/session_store_postgres.go` | Store filters `Get`, `List`, `GetByChannel`; shared read/write guards check person ownership as well as org. A saved session cannot change its conversation source to claim another person's history. Service curation runs without a person principal. | `TestSessionVisibility`; PostgreSQL smoke for history isolation |
| Chat questions/approvals: `webui/api_chat_ask.go` | Waiting question is bound to the initiating person, in addition to its unguessable ID. | `TestChatQuestionBelongsToInitiatingPerson` | | Chat questions/approvals: `webui/api_chat_ask.go` | The UI service binds the waiting question to the initiating person, in addition to its unguessable ID. | `TestChatQuestionBelongsToInitiatingPerson` |
| Chat downloads: `webui/api_chat_files.go` | Offered file token expires and is bound to the initiating person; requests cannot supply a filesystem path. | `TestChatFileDownload` | | Chat downloads: `webui/api_chat_files.go` | The UI service binds the offered file token to the initiating person, and the token expires; requests cannot supply a filesystem path. | `TestChatFileDownload` |
| Per-person memory: `archiegateway/chat_identity.go`, gateway memory tools, `sessioncurator` | Verified web sender identity scopes reads/writes. Curator refuses unidentified or mixed participants instead of guessing a person. | Gateway memory and session-curator tests | | Per-person memory: `archiegateway/chat_identity.go`, gateway memory tools, `sessioncurator` | Verified web sender identity scopes reads/writes. Curator refuses unidentified or mixed participants instead of guessing a person. | Gateway memory and session-curator tests |
| Workflow/task actions: `webui/api_tasks.go`, `domain/taskactions`, `staterpc` | Policy and stored workspace before action; domain transition, authority and durable dispatch guards remain in force. | HTTP deny matrix, task action/domain tests, task grant tests | | Workflow/task actions: `webui/api_tasks.go`, `domain/taskactions`, `staterpc` | Policy and stored workspace before action; domain transition, authority and durable dispatch guards remain in force. | HTTP deny matrix, task action/domain tests, task grant tests |
| Incoming webhooks: `captureintake`, access delivery engine | Verify HMAC before parsing; derive source/org from stored source; evaluate source delivery policies and egress rules. No browser-user credential is inferred. | Capture tests, `TestAuthorizeDelivery` | | Incoming webhooks: `captureintake`, access delivery engine | Verify HMAC before parsing; derive source/org from stored source; evaluate source delivery policies and egress rules. The capture intake never infers a browser-user credential. | Capture tests, `TestAuthorizeDelivery` |
| Control-plane configuration, secrets and extensions | Browser policy and instance-only restrictions where registered; service contracts carry principal/org; task grants cannot invoke administrative RPCs. | HTTP deny matrix, `TestAdministrationRoutes`, `TestChannelReloadRoute` | | Control-plane configuration, secrets and extensions | Browser policy and instance-only restrictions where registered; service contracts carry principal/org; task grants cannot invoke administrative RPCs. | HTTP deny matrix, `TestAdministrationRoutes`, `TestChannelReloadRoute` |
| Audit feed: `webui/api_audit.go`, `domain/audit` | `read_audit` on the `audit` resource; org scope and the instance-wide exception come from the authenticated principal, never the query string. Export carries the same grant, needs an explicit range of at most a year, and is rate-limited per identity, one at a time. Redaction runs in the State Store adapter before an entry crosses gRPC. | `TestReadAuditRoleBoundary`, `TestAuditRoutesFollowTheReadAuditRole`, `TestHTTPPolicyCannotBeBypassed`, `TestAuditErrorMapping`, `TestAuditCSVCellNeutralisesFormulas` | | Audit feed: `webui/api_audit.go`, `domain/audit` | `read_audit` on the `audit` resource; org scope and the instance-wide exception come from the authenticated principal, never the query string. Export carries the same grant, needs an explicit range of at most a year, and is rate-limited per identity, one at a time. Redaction runs in the State Store adapter before an entry crosses gRPC. | `TestReadAuditRoleBoundary`, `TestAuditRoutesFollowTheReadAuditRole`, `TestHTTPPolicyCannotBeBypassed`, `TestAuditErrorMapping`, `TestAuditCSVCellNeutralisesFormulas` |
| Live HTTP/SSE and diagnostics | Authenticated policy gate applies before stream creation; org-scoped event reads; instance logs require administrative visibility. | HTTP deny matrix, instance-only tests, `TestServiceLogsRequireInstanceCredential` | | Live HTTP/SSE and diagnostics | Authenticated policy gate applies before stream creation; org-scoped event reads; instance logs require administrative visibility. | HTTP deny matrix, instance-only tests, `TestServiceLogsRequireInstanceCredential` |
@@ -86,29 +86,31 @@ accounts by unverified email, or create an administrator.
The policy HTTP matrix enumerates each registered protected route. It checks The policy HTTP matrix enumerates each registered protected route. It checks
both anonymous refusal and refusal by an explicit Cedar forbid, using the real both anonymous refusal and refusal by an explicit Cedar forbid, using the real
handler stack. Separate tests exercise allowed requests and personal ownership; handler stack. Separate tests exercise allowed requests and personal ownership.
a denied-request matrix alone is not proof that a workflow works end to end. A denied-request matrix alone is not proof that a workflow works end to end.
## Public and personal routes ## Public and personal routes
Public protocol entry points are `GET /api/auth/status`, `POST /api/auth/setup`, Public protocol entry points are `GET /api/auth/status`, `POST /api/auth/setup`,
`POST /api/auth/login`, `POST /api/auth/logout`, `POST /api/auth/recover`, `POST /api/auth/login`, `POST /api/auth/logout`, `POST /api/auth/recover`,
`POST /api/auth/passkey/begin`, `POST /api/auth/passkey/finish`, `POST /api/auth/passkey/begin` and `POST /api/auth/passkey/finish`. The
`GET /oauth2/login`, `GET /oauth2/callback`, health probes and signed webhook remaining entry points are `GET /oauth2/login`, `GET /oauth2/callback`, health
intake. Each has its own protocol checks. Static embedded app assets are public; probes and signed webhook intake. Each has its own protocol checks. Static
they do not contain user data. `/health/detailed` remains protected. embedded app assets are public. They do not contain user data.
`/health/detailed` remains protected.
Personal routes under `/api/account/` require an active signed-in person and Personal routes under `/api/account/` require an active signed-in person and
server-derived ownership: password change, recovery-secret generation, passkey server-derived ownership. They cover password change, recovery-secret
begin/finish/list/delete. They do not require an organization administrator generation, and passkey begin/finish/list/delete. They do not require an
role. `POST /api/accounts` and `/api/authentication` are administrative policy organisation administrator role. `POST /api/accounts` and `/api/authentication`
routes. are administrative policy routes.
## HTTP route inventory ## HTTP route inventory
The following routes are covered by `TestHTTPPolicyCannotBeBypassed` in The test `TestHTTPPolicyCannotBeBypassed` covers the following routes. It lives
`internal/webui/authorization_surfaces_test.go`. `authorize.go` maps each to its in `internal/webui/authorization_surfaces_test.go`. `authorize.go` maps each to
action/resource; the handler may impose a stricter record or instance boundary. its action/resource. The handler may impose a stricter record or instance
boundary.
| Method | Route example | | Method | Route example |
| ------ | ----------------------------------------------------- | | ------ | ----------------------------------------------------- |
@@ -226,21 +228,23 @@ action/resource; the handler may impose a stricter record or instance boundary.
## Verification limits ## Verification limits
A synthetic browser authenticator verifies protocol behavior, not a physical A synthetic browser authenticator checks protocol behaviour. It does not test a
security key or every operating system. An OIDC unit test is not acceptance physical security key or every operating system. An OIDC unit test is not
against a deployed provider. Disposable PostgreSQL smoke checks verify real SQL acceptance against a deployed provider. Disposable PostgreSQL smoke checks
without putting database-dependent tests in the fast unit suite. verify real SQL. They keep database tests out of the fast unit suite.
Existing anonymous conversations are retained but are not silently assigned to a The Gateway retains existing anonymous conversations but does not silently
new person. Existing service credentials remain privileged; this inventory does assign them to a new person. Existing service credentials remain privileged.
not claim that all internal gRPC methods have independent Cedar gates. This inventory does not claim that all internal gRPC methods have independent
Cedar gates.
When changing a user-facing operation, update its inventory entry and its When changing a user-facing operation, update its inventory entry and its
allow/deny behavior cases. Include another user in the same organization, a allow/deny behaviour cases. Include another user in the same organisation, a
caller in another organization, a missing principal, unavailable policy storage, caller in another organisation, a missing principal, unavailable policy storage,
and the applicable owner/workspace/instance restrictions. and the applicable owner/workspace/instance restrictions.
Bootstrap is unauthenticated until the first administrator is created. Complete Bootstrap runs without authentication until the operator creates the first
setup before exposing a new installation to untrusted users. Last-active-owner administrator account. Complete setup before exposing a new installation to
protection for identity suspension/retirement is tracked separately as untrusted users. A separate issue, `archie-core-d7avc`, tracks
`archie-core-d7avc`; membership-policy guards are not that lifecycle guard. last-active-owner protection for identity suspension/retirement.
Membership-policy guards are not that lifecycle guard.
+39 -18
View File
@@ -45,9 +45,30 @@ and `ARCHIE_E2E_PASSWORD` for both seeding and browser checks. Seeding never
resets an existing account or deletes test data. resets an existing account or deletes test data.
The first run needs `pnpm install --dir e2e` and `pnpm --dir e2e exec playwright The first run needs `pnpm install --dir e2e` and `pnpm --dir e2e exec playwright
install chromium`. In the cloud environment, Chromium and Playwright are install chromium`. The cloud environment ships Chromium and Playwright
preinstalled; run with `NODE_PATH=$(pnpm root -g)`. preinstalled; run with `NODE_PATH=$(pnpm root -g)`.
## Single-binary smoke check
Point this check at an already running, disposable `archie` instance with its
own PostgreSQL database and no external delivery connectors. Set
`ARCHIE_SMOKE_TOKEN` to that instance's bootstrap token and
`ARCHIE_SMOKE_URL` to its IPv4 loopback URL (for example
`http://127.0.0.1:8080`), then run:
```bash
node e2e/archie-smoke.cjs
```
The check saves a workflow and a one-minute schedule, then verifies that its
run links back to the schedule event and appears in the composer. It disables
the schedule after the check but leaves records for inspection. The check needs
no model or forge. The legacy `task e2e:up` stack is not the target of this check.
If Archie is running in WSL and its loopback URL is not reachable from
Windows, run the check with Node in the same Linux environment as Archie.
If the schedule starts but the run does not finish, check the `events` and
`runs` logs; readiness alone does not verify that either worker can claim work.
## Release evidence ## Release evidence
```bash ```bash
@@ -64,53 +85,53 @@ A module in `checks/` exports `async ({ page, go, shot, fail, skip, settled, att
- `go(path)` loads a dashboard route: `waitUntil: 'load'` plus 1200ms. - `go(path)` loads a dashboard route: `waitUntil: 'load'` plus 1200ms.
Wait for elements, never for `networkidle`: the event stream never goes idle. Wait for elements, never for `networkidle`: the event stream never goes idle.
- `shot(label)` saves `<check>-<kebab>[-<w>x<h>].png` after a short settle, - `shot(label)` saves `<check>-<kebab>[-<w>x<h>].png` after a short settle,
and records `{file, w, h, check}` in the manifest. The label is slugified, and records `{file, w, h, check}` in the manifest. The label becomes a slug,
so `shot('/')` becomes `routes-home.png`; a viewport other than the so `shot('/')` becomes `routes-home.png`; a viewport other than the
1440x900 default adds a suffix (`-390x844`). Repeated labels get `-2`, 1440x900 default adds a suffix (`-390x844`). Repeated labels get `-2`,
`-3`, so every capture is kept. `-3`, so the test runner keeps every capture.
- `fail(msg)` records a problem without stopping. - `fail(msg)` records a problem without stopping.
- `skip(reason)` stops the check and records a skip: a missing - `skip(reason)` stops the check and records a skip: a missing
precondition, never a failure. precondition, never a failure.
- `tolerate(re)` ignores console errors matching `re`, for a response the page is designed to survive. - `tolerate(re)` ignores console errors matching `re`, for a response the page survives by design.
- `attach(name, data)` saves a non-image artifact as `<check>-<name>`. - `attach(name, data)` saves a non-image artifact as `<check>-<name>`.
- `settled(sel?)` waits for a selector or URL, then settles briefly. - `settled(sel?)` waits for a selector or URL, then settles briefly.
It is the harness-owned wait; checks need no capture wrapper or It is the test runner's wait; checks need no capture wrapper or
ad-hoc sleeps around screenshots. ad-hoc sleeps around screenshots.
Each check gets a fresh page at 1440x900 with the login `storageState`; Each check gets a fresh page at 1440x900 with the login `storageState`;
a check that needs a phone viewport resizes it itself to 390x844. a check that needs a phone viewport resizes it itself to 390x844.
Those are the only two viewports in use. A throw, a `fail`, or any Those are the only two viewports in use. A throw, a `fail`, or any
console or page error fails the check. One module covers one behaviour; console or page error fails the check. One module covers one behaviour.
families share a prefix: `audit-*` for the audit page (redirect, Families share a prefix: `audit-*` for the audit page (redirect,
filters, revert, runtime, views-export, retention-live, phone), filters, revert, runtime, views-export, retention-live, phone), and
`workflow-*` for the canvas (loading, validation, phone-layout, logic), `workflow-*` for the canvas (loading, validation, phone-layout, logic).
`chat-composer` for chat input, `chat-dock-*` for the chat dock (pin, drag-cancel, `chat-composer` covers chat input, and `chat-dock-*` covers the chat dock (pin,
layout, resize, drafts, picker, phone). drag-cancel, layout, resize, drafts, picker, phone).
`routes` loads every static route and flags text with stray leading, `routes` loads every static route and flags text with stray leading,
trailing or doubled spaces. `seeded` checks the seed is visible. trailing or doubled spaces. `seeded` checks the seed is visible.
`/logs` is visited but skipped by the whitespace lint: log lines are `routes` visits `/logs` but the whitespace lint skips it: log lines are
data, not copy. data, not copy.
## Output ## Output
Every run writes `out/<stamp>/` with the screenshots, Every run writes `out/<stamp>/` with the screenshots,
`results.json` (the manifest: `{check, ok, ms, problems, artifacts[]}`, `results.json` (the manifest: `{check, ok, ms, problems, artifacts[]}`,
plus `skipped`/`skipReason` for skips) and `report.html`: a self-contained plus `skipped`/`skipReason` for skips) and `report.html`. The report is a
test record with the commit, totals and one row per check (status, time, self-contained test record with the commit, totals and one row per check (status,
message and that check's artifacts, screenshots inline). `attach(name, data)` time, message and that check's artifacts, screenshots inline). `attach(name, data)`
adds a non-image artifact to the current check; a failed check also gets a adds a non-image artifact to the current check; a failed check also gets a
`failure` screenshot. `failure` screenshot.
Exits: 0 when every check passes or skips, 1 when any check fails, Exits: 0 when every check passes or skips, 1 when any check fails,
2 when the harness itself errors. `ARCHIE_E2E_URL` points the run at 2 when the test runner itself errors. `ARCHIE_E2E_URL` points the run at
a dashboard other than `http://localhost:5173`. a dashboard other than `http://localhost:5173`.
## Pitfalls ## Pitfalls
| Symptom | Cause | Fix | | Symptom | Cause | Fix |
| --- | --- | --- | | --- | --- | --- |
| State Store exits: server is older than PostgreSQL 18 | another server answered | `stack.sh` uses port 55432; set `ARCHIE_DEV_PGPORT` if that is taken | | State Store exits: server is older than PostgreSQL 18 | another server answered | `stack.sh` uses port 55432; set `ARCHIE_DEV_PGPORT` if another process holds that port |
| Startup says a port is in use | a stack or another process already owns it | Run `task e2e:down`, then `task e2e:up`; inspect any remaining listener with `ss -ltnp` | | Startup says a port is in use | a stack or another process already owns it | Run `task e2e:down`, then `task e2e:up`; inspect any remaining listener with `ss -ltnp` |
| Your own shell is killed (exit 144) | `pkill -f` matched its own command line | `stack.sh stop` or `restart`, which kill by PID | | `pkill -f` kills your own shell (exit 144) | `pkill -f` matched its own command line | `stack.sh stop` or `restart`, which kill by PID |
| Postgres aborts in the cloud | `/tmp/claude-0` is reset to mode 700 | `stack.sh` keeps the root cluster in `/var/lib/archie-dev` | | Postgres aborts in the cloud | `/tmp/claude-0` is reset to mode 700 | `stack.sh` keeps the root cluster in `/var/lib/archie-dev` |
+75
View File
@@ -0,0 +1,75 @@
const assert = require("node:assert/strict");
const { randomUUID } = require("node:crypto");
const { setTimeout: delay } = require("node:timers/promises");
async function main() {
assert.ok(process.env.ARCHIE_SMOKE_URL, "Set ARCHIE_SMOKE_URL to a disposable Archie stack");
const origin = new URL(process.env.ARCHIE_SMOKE_URL);
const token = process.env.ARCHIE_SMOKE_TOKEN;
assert.equal(origin.protocol, "http:");
assert.equal(origin.hostname, "127.0.0.1", "Use a disposable Archie stack on IPv4 loopback");
assert.ok(token, "Set ARCHIE_SMOKE_TOKEN to the disposable stack's admin token");
async function request(path, { method = "GET", body, authenticated = true, status = 200 } = {}) {
const response = await fetch(new URL(path, origin), {
method,
redirect: "error",
signal: AbortSignal.timeout(10_000),
headers: {
...(authenticated && { Authorization: `Bearer ${token}` }),
...(body !== undefined && { "Content-Type": "application/json" }),
},
body: body === undefined ? undefined : JSON.stringify(body),
}).catch((err) => {
throw new Error(`${method} ${path}: could not reach Archie at ${origin.origin}: ${err.cause?.message || err.message}`, { cause: err });
});
assert.equal(response.status, status, `${method} ${path}: expected HTTP ${status}, got ${response.status}`);
return response.json();
}
const ready = await request("/readyz", { authenticated: false });
assert.equal(ready.ready, true, "Archie is not ready");
await request("/api/workflows", { authenticated: false, status: 401 });
const name = `smoke-${randomUUID()}`;
const saved = await request("/api/workflows", {
method: "POST",
status: 201,
body: { name, body: `repository: none\nsteps:\n - id: notify\n type: run.notify\n settings: {title: ${name}}\n` },
});
const trigger = { name, workflow_id: saved.id, every: "1m" };
const created = await request("/api/triggers", { method: "POST", body: trigger, status: 201 });
try {
const deadline = Date.now() + 90_000;
let last = "no scheduled run";
while (Date.now() < deadline) {
const recent = await request("/api/runs");
const run = recent.find((row) => row.workflow_id === saved.id);
if (run) {
last = `run ${run.id}: ${run.state}`;
assert.ok(!["failed", "cancelled"].includes(run.state), `${last}: ${run.error || "no error returned"}`);
if (run.state === "succeeded") {
const trail = await request(`/api/runs/${run.id}`);
assert.equal(trail.run.workflow_version, saved.version, "Run used the wrong workflow version");
assert.equal(trail.origin?.trigger_id, created.id, "Run trail is missing the schedule trigger");
assert.ok(trail.origin?.event_id, "Run trail is missing the originating event");
assert.equal(trail.origin.declared_event_type, "schedule.tick");
const messages = await request("/api/composer/messages");
assert.equal(messages.filter((m) => m.run_id === run.id && m.title === name).length, 1,
"Expected one composer notification linked to the run");
console.log(`Schedule, run trail and composer notification verified for ${run.id}`);
return;
}
}
await delay(1_000);
}
throw new Error(`Timed out waiting for ${name}: ${last}`);
} finally {
await request(`/api/triggers/${created.id}`, { method: "PUT", body: { ...trigger, disabled: true } });
}
}
main().catch((err) => {
console.error(err.message);
process.exitCode = 1;
});
+1 -1
View File
@@ -13,7 +13,6 @@ require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cloudflare/circl v1.6.5 // indirect github.com/cloudflare/circl v1.6.5 // indirect
github.com/containerd/errdefs/pkg v0.3.0 // indirect github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/danielgtaylor/huma/v2 v2.40.0 // indirect
github.com/distribution/reference v0.6.0 // indirect github.com/distribution/reference v0.6.0 // indirect
github.com/docker/go-connections v0.8.2 // indirect github.com/docker/go-connections v0.8.2 // indirect
github.com/docker/go-units v0.5.0 // indirect github.com/docker/go-units v0.5.0 // indirect
@@ -72,6 +71,7 @@ require (
github.com/cedar-policy/cedar-go v1.9.1 github.com/cedar-policy/cedar-go v1.9.1
github.com/containerd/errdefs v1.0.0 github.com/containerd/errdefs v1.0.0
github.com/coreos/go-oidc/v3 v3.21.0 github.com/coreos/go-oidc/v3 v3.21.0
github.com/danielgtaylor/huma/v2 v2.40.0
github.com/go-git/go-billy/v6 v6.0.0-beta.1 github.com/go-git/go-billy/v6 v6.0.0-beta.1
github.com/go-git/go-git/v6 v6.0.0-beta.1 github.com/go-git/go-git/v6 v6.0.0-beta.1
github.com/go-jose/go-jose/v4 v4.1.9 github.com/go-jose/go-jose/v4 v4.1.9
+2
View File
@@ -70,6 +70,8 @@ github.com/fxamacker/cbor/v2 v2.10.0 h1:HVF3T5vYwLqO81ebPirWEPNv2SMrUMD3HLnKgEr6
github.com/fxamacker/cbor/v2 v2.10.0/go.mod h1:uSwlToFuT9BZAKRxxVm3qQC8DR4tlWl7D6pf20iRYH4= github.com/fxamacker/cbor/v2 v2.10.0/go.mod h1:uSwlToFuT9BZAKRxxVm3qQC8DR4tlWl7D6pf20iRYH4=
github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c= github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU= github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU=
github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg=
github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM=
github.com/go-git/gcfg/v2 v2.0.2 h1:MY5SIIfTGGEMhdA7d7JePuVVxtKL7Hp+ApGDJAJ7dpo= github.com/go-git/gcfg/v2 v2.0.2 h1:MY5SIIfTGGEMhdA7d7JePuVVxtKL7Hp+ApGDJAJ7dpo=
github.com/go-git/gcfg/v2 v2.0.2/go.mod h1:/lv2NsxvhepuMrldsFilrgct6pxzpGdSRC13ydTLSLs= github.com/go-git/gcfg/v2 v2.0.2/go.mod h1:/lv2NsxvhepuMrldsFilrgct6pxzpGdSRC13ydTLSLs=
github.com/go-git/go-billy/v6 v6.0.0-beta.1 h1:OJ4r207zcEbeq/DJNajQUOMd+pph3r9A7hRq1Sjl1bA= github.com/go-git/go-billy/v6 v6.0.0-beta.1 h1:OJ4r207zcEbeq/DJNajQUOMd+pph3r9A7hRq1Sjl1bA=
-8
View File
@@ -30,14 +30,6 @@ func ClipToolCallDetail(s string) string {
return s[:cut] + "…" return s[:cut] + "…"
} }
func ProjectScopedRules(workspace, extra string) string {
rule := "Confine discovery to " + workspace + ". Do not inspect home directories, dependency/module caches, or unrelated projects unless the mission explicitly requests that external path."
if strings.TrimSpace(extra) == "" {
return rule
}
return rule + "\n" + extra
}
func ProtectionMatcher(p agentrun.Protection, readOnly bool) func(string) bool { func ProtectionMatcher(p agentrun.Protection, readOnly bool) func(string) bool {
if readOnly || len(p.Suffixes)+len(p.Globs) == 0 { if readOnly || len(p.Suffixes)+len(p.Globs) == 0 {
return nil return nil
+2 -1
View File
@@ -17,6 +17,7 @@ import (
"github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/domain/agentrun" "github.com/samcharles93/archie-core/internal/domain/agentrun"
"github.com/samcharles93/archie-core/internal/prompts"
"github.com/samcharles93/archie-core/internal/taskstate" "github.com/samcharles93/archie-core/internal/taskstate"
"github.com/samcharles93/archie-core/internal/tools" "github.com/samcharles93/archie-core/internal/tools"
) )
@@ -91,7 +92,7 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req agentrun.Req
MaxParallelToolCalls: MaxParallelToolCalls, MaxParallelToolCalls: MaxParallelToolCalls,
Mission: missionWithHistory(req), Mission: missionWithHistory(req),
ExtraRules: agentexec.ProjectScopedRules(workspace, req.ExtraRules), ExtraRules: prompts.ProjectScopedRules(workspace, req.ExtraRules),
Notes: notes, Notes: notes,
Gate: toAgentGate(req.Gate), Gate: toAgentGate(req.Gate),
Preflight: toAgentCommands(req.Preflight), Preflight: toAgentCommands(req.Preflight),
+1 -1
View File
@@ -42,7 +42,7 @@ func SamplingMessages(req protocol.SamplingRequest) ([]chat.Message, error) {
// SamplingMaxTokens returns the request's maxTokens or the default, capped at // SamplingMaxTokens returns the request's maxTokens or the default, capped at
// the model's ceiling. The ai-sdk runtime picks max_completion_tokens or // the model's ceiling. The ai-sdk runtime picks max_completion_tokens or
// max_tokens from the model's catalog metadata, so there is no reasoning // max_tokens from the model's catalogue metadata, so there is no reasoning
// branch here. // branch here.
func SamplingMaxTokens(requested, modelCeiling int) int { func SamplingMaxTokens(requested, modelCeiling int) int {
maxTokens := requested maxTokens := requested
+113
View File
@@ -0,0 +1,113 @@
package archie
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"regexp"
"slices"
"testing"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/modules/governance"
)
// operator authenticates every request as an instance administrator.
type operator struct{}
func (operator) Authenticate(ctx context.Context, _ *http.Request) (context.Context, bool, error) {
return ctx, true, nil
}
// refuses answers every Allow with err and records what it was asked.
type refuses struct {
err error
asked []string
}
func (r *refuses) Allow(_ context.Context, action, kind string) error {
r.asked = append(r.asked, action+" "+kind)
return r.err
}
// publicOperations are the only operations a caller reaches without a
// credential: sign-in, setup and the auth status the sign-in page reads.
var publicOperations = []string{
"begin-oidc-sign-in", "begin-passkey-sign-in", "finish-oidc-sign-in", "finish-passkey-sign-in",
"get-auth-status", "recover-account", "set-up-account", "sign-in", "sign-out",
}
var pathParam = regexp.MustCompile(`\{[^}]+\}`)
// TestEveryOperationIsAuthorized guards deny-by-default across every module's
// routes. Each registered operation is either one of the named public
// operations or declares a valid action and resource kind, and a request that
// fails the grant, or that cannot be decided, is refused before its handler
// runs. The handlers here have nothing behind them, so one that ran would
// panic.
func TestEveryOperationIsAuthorized(t *testing.T) {
probe := &refuses{err: httpapi.ErrDenied}
mux, api := emptyAPI(operator{}, probe)
routes := httpapi.Routes(api)
if len(routes) < 100 {
t.Fatalf("only %d operations registered", len(routes))
}
var public []string
for _, route := range routes {
if route.Access.IsPublic() {
public = append(public, route.ID)
continue
}
action, kind, ok := route.Access.Declared()
if !ok {
t.Errorf("%s declares no access", route.ID)
continue
}
if err := governance.Action(action).Validate(); err != nil || kind == "" {
t.Errorf("%s declares %q on %q", route.ID, action, kind)
}
}
slices.Sort(public)
if !slices.Equal(public, publicOperations) {
t.Errorf("public operations = %v, want %v", public, publicOperations)
}
for _, tt := range []struct {
name string
err error
want int
}{
{"a failing grant", httpapi.ErrDenied, http.StatusForbidden},
{"an unavailable policy chain", httpapi.ErrUnavailable, http.StatusServiceUnavailable},
} {
t.Run(tt.name, func(t *testing.T) {
for _, route := range routes {
action, kind, ok := route.Access.Declared()
if !ok {
continue
}
probe.err, probe.asked = tt.err, nil
req := httptest.NewRequestWithContext(t.Context(), route.Method, pathParam.ReplaceAllString(route.Path, "x"), nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != tt.want {
t.Errorf("%s: status = %d, want %d", route.ID, rec.Code, tt.want)
}
if want := []string{action + " " + kind}; !slices.Equal(probe.asked, want) {
t.Errorf("%s: decided on %v, want %v", route.ID, probe.asked, want)
}
}
})
}
}
// TestUnwiredAuthorizerRefuses guards the boot order: until the policy chain
// is wired, an authorised operation is refused rather than let through.
func TestUnwiredAuthorizerRefuses(t *testing.T) {
settings := &governance.Module{}
if err := settings.Allow(governance.WithPrincipal(t.Context(), governance.SharedTokenOwner()), "read", "run"); !errors.Is(err, httpapi.ErrUnavailable) {
t.Fatalf("Allow with no chain = %v, want %v", err, httpapi.ErrUnavailable)
}
}
+48 -21
View File
@@ -7,56 +7,83 @@ import (
"github.com/samcharles93/archie-core/internal/buildinfo" "github.com/samcharles93/archie-core/internal/buildinfo"
"github.com/samcharles93/archie-core/internal/platform/httpapi" "github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/internal/platform/hub"
"github.com/samcharles93/archie-core/modules/approvals" "github.com/samcharles93/archie-core/modules/approvals"
"github.com/samcharles93/archie-core/modules/chat"
"github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/dashboard"
"github.com/samcharles93/archie-core/modules/deliveries" "github.com/samcharles93/archie-core/modules/deliveries"
"github.com/samcharles93/archie-core/modules/drafts"
"github.com/samcharles93/archie-core/modules/events" "github.com/samcharles93/archie-core/modules/events"
"github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/governance"
"github.com/samcharles93/archie-core/modules/judgement" "github.com/samcharles93/archie-core/modules/judgement"
"github.com/samcharles93/archie-core/modules/memory"
"github.com/samcharles93/archie-core/modules/proposals"
"github.com/samcharles93/archie-core/modules/runs" "github.com/samcharles93/archie-core/modules/runs"
"github.com/samcharles93/archie-core/modules/system" "github.com/samcharles93/archie-core/modules/system"
) )
// apiModules are the modules that serve the HTTP API. // apiModules are the modules that serve the HTTP API.
type apiModules struct { type apiModules struct {
settings *governance.Module settings *governance.Module
conns *connectors.Module conns *connectors.Module
system *system.Module system *system.Module
tell *deliveries.Module tell *deliveries.Module
allow *approvals.Module allow *approvals.Module
classes *judgement.Classes actionTypes *judgement.ActionTypes
policies *judgement.Policies policies *judgement.Policies
hear *events.Module hear *events.Module
judge *judgement.Module judge *judgement.Module
engine *runs.Engine engine *runs.Engine
drafts *drafts.Module chat *chat.Module
proposals *proposals.Module
notes *memory.Module
live *hub.Hub
} }
func (m apiModules) register(api huma.API) { func (m apiModules) register(api huma.API) {
m.settings.Register(api) m.settings.Register(api)
m.settings.RegisterAccounts(api)
m.settings.RegisterOrganisations(api)
m.settings.RegisterAccess(api)
m.conns.Register(api) m.conns.Register(api)
m.system.Register(api) m.system.Register(api)
m.tell.Register(api) m.tell.Register(api)
m.allow.Register(api) m.allow.Register(api)
m.classes.Register(api, m.allow) m.actionTypes.Register(api, m.allow)
m.policies.Register(api) m.policies.Register(api)
m.hear.Register(api) m.hear.Register(api)
m.judge.Register(api) m.judge.Register(api)
m.engine.Register(api, orgID, m.hear, m.judge, m.allow) m.engine.Register(api, orgID, m.hear, m.judge, m.allow)
m.drafts.Register(api) m.proposals.Register(api)
m.chat.Register(api)
// The memory routes are served once the root wires the module, which it
// does after the modules that read it are built.
if m.notes != nil {
m.notes.Register(api)
}
dashboard.Register(api, m.live)
} }
// Document returns the API's OpenAPI document as YAML. It makes the same // Document returns the API's OpenAPI document as YAML. It makes the same
// registrations the server does, on modules with nothing behind them, so it // registrations the server does, on modules with nothing behind them, so it
// needs no database. // needs no database.
func Document() ([]byte, error) { func Document() ([]byte, error) {
api := httpapi.New(http.NewServeMux(), buildinfo.Version, "") settings := &governance.Module{}
apiModules{ _, api := emptyAPI(settings.Authenticator(""), settings)
settings: &governance.Module{}, conns: &connectors.Module{}, system: &system.Module{},
tell: &deliveries.Module{}, allow: &approvals.Module{}, classes: &judgement.Classes{},
policies: &judgement.Policies{}, hear: &events.Module{}, judge: &judgement.Module{},
engine: &runs.Engine{}, drafts: &drafts.Module{},
}.register(api)
return api.OpenAPI().YAML() return api.OpenAPI().YAML()
} }
// emptyAPI registers every route on modules with nothing behind them.
func emptyAPI(auth httpapi.Authenticator, authz httpapi.Authorizer) (*http.ServeMux, huma.API) {
mux := http.NewServeMux()
settings := &governance.Module{}
api := httpapi.New(mux, buildinfo.Version, auth, authz)
apiModules{
settings: settings, conns: &connectors.Module{}, system: &system.Module{},
tell: &deliveries.Module{}, allow: &approvals.Module{}, actionTypes: &judgement.ActionTypes{},
policies: &judgement.Policies{}, hear: &events.Module{}, judge: &judgement.Module{},
engine: &runs.Engine{}, chat: &chat.Module{}, proposals: &proposals.Module{},
notes: &memory.Module{}, live: hub.New(),
}.register(api)
return mux, api
}
+26 -1
View File
@@ -12,6 +12,8 @@ import (
"filippo.io/age" "filippo.io/age"
"github.com/BurntSushi/toml" "github.com/BurntSushi/toml"
"github.com/samcharles93/archie-core/internal/platform/deletions"
) )
// Config is the bootstrap configuration: only what the binary needs before it // Config is the bootstrap configuration: only what the binary needs before it
@@ -28,6 +30,13 @@ type Config struct {
AgeIdentity string `toml:"age_identity"` AgeIdentity string `toml:"age_identity"`
// AgeBackupRecipients ("age1...") can also open every sealed credential. // AgeBackupRecipients ("age1...") can also open every sealed credential.
AgeBackupRecipients []string `toml:"age_backup_recipients"` AgeBackupRecipients []string `toml:"age_backup_recipients"`
// StateDir is where the binary keeps state outside the database, including
// the record of deletions a restore has to apply again. It defaults to
// ${XDG_DATA_HOME:-~/.local/share}/archie, where the other archie binaries
// keep their state unless an instance name is set. A leading ~ is the home
// directory, and a relative path is refused: the restore that reads this
// directory runs as another process.
StateDir string `toml:"state_dir"`
} }
// DatabaseConfig holds the two connection URLs. The owner runs migrations at // DatabaseConfig holds the two connection URLs. The owner runs migrations at
@@ -115,6 +124,17 @@ func DefaultConfigPath() string {
return filepath.Join(dir, "archie", "config.toml") return filepath.Join(dir, "archie", "config.toml")
} }
// DefaultStateDir is ${XDG_DATA_HOME:-~/.local/share}/archie, or the instance's
// directory when ARCHIE_INSTANCE names one, resolved the way every archie binary
// resolves it.
func DefaultStateDir() string {
dir, err := deletions.Dir("")
if err != nil {
return filepath.Join("archie", "state")
}
return dir
}
// NewAgeIdentity writes a new age identity to w, for a config's age_identity. // NewAgeIdentity writes a new age identity to w, for a config's age_identity.
func NewAgeIdentity(w io.Writer) error { func NewAgeIdentity(w io.Writer) error {
id, err := age.GenerateX25519Identity() id, err := age.GenerateX25519Identity()
@@ -127,10 +147,15 @@ func NewAgeIdentity(w io.Writer) error {
// LoadConfig reads and validates the bootstrap config at path. // LoadConfig reads and validates the bootstrap config at path.
func LoadConfig(path string) (Config, error) { func LoadConfig(path string) (Config, error) {
cfg := Config{Listen: "127.0.0.1:8080"} cfg := Config{Listen: "127.0.0.1:8080", StateDir: DefaultStateDir()}
if _, err := toml.DecodeFile(path, &cfg); err != nil { if _, err := toml.DecodeFile(path, &cfg); err != nil {
return Config{}, fmt.Errorf("read config %s: %w", path, err) return Config{}, fmt.Errorf("read config %s: %w", path, err)
} }
dir, err := deletions.Dir(cfg.StateDir)
if err != nil {
return Config{}, fmt.Errorf("config %s: %w", path, err)
}
cfg.StateDir = dir
if err := cfg.validate(); err != nil { if err := cfg.validate(); err != nil {
return Config{}, fmt.Errorf("config %s: %w", path, err) return Config{}, fmt.Errorf("config %s: %w", path, err)
} }
+232
View File
@@ -0,0 +1,232 @@
package archie
import (
"context"
"errors"
"io/fs"
"log/slog"
"net/http"
"strings"
"sync"
"time"
"github.com/samcharles93/archie-core/internal/platform/health"
"github.com/samcharles93/archie-core/internal/platform/httpjson"
)
// The two account operations the setup page calls. Every other /api/ route
// needs an instance that already has an owner.
const (
authStatusPath = "/api/auth/status"
setUpAccountPath = "/api/auth/setup"
)
// What stopped operations from starting. Readiness reports the stage; the error
// text stays in the log, since it can name hosts, roles and tables.
const (
stageSetupRead = "cannot read whether owner setup is required"
stageStartup = "starting operations failed"
stageMigrate = "migrating the database failed"
)
// How long a failed boot step waits before it runs again. The delay doubles up
// to a ceiling.
const (
startupRetryMin = 100 * time.Millisecond
startupRetryMax = 5 * time.Second
)
// gate is the surface the binary serves. Until the owner setup transaction has
// committed it answers only what the setup page needs, and it refuses every
// operational route before the handler runs, whatever credential the request
// carries. Once the operations are running it passes every request to them.
type gate struct {
ops http.Handler
setup http.Handler
mu sync.RWMutex
open bool
problem string
}
// newGate returns a closed gate over the operational handler and the dashboard
// build its assets come from.
func newGate(ops http.Handler, dist fs.FS) *gate {
return &gate{ops: ops, setup: setupSurface(ops, dist)}
}
func (g *gate) ServeHTTP(w http.ResponseWriter, r *http.Request) {
next := g.setup
if g.opened() {
next = g.ops
}
next.ServeHTTP(w, r)
}
// publish opens the gate. It is called once, after everything operations need
// has started, so a half-wired API is never served.
func (g *gate) publish() {
g.mu.Lock()
defer g.mu.Unlock()
g.open = true
g.problem = ""
}
func (g *gate) opened() bool {
g.mu.RLock()
defer g.mu.RUnlock()
return g.open
}
// stall records the stage that kept the gate closed, so readiness names it rather
// than only the missing owner. An empty stage clears it.
func (g *gate) stall(stage string) {
g.mu.Lock()
defer g.mu.Unlock()
g.problem = stage
}
// check is the readiness check for the gate. An instance still waiting for its
// owner is alive but has nothing ready to serve, and that is not a crash.
func (g *gate) check(context.Context) error {
g.mu.RLock()
defer g.mu.RUnlock()
switch {
case g.open:
return nil
case g.problem != "":
return errors.New(g.problem)
}
return errors.New("owner setup is incomplete")
}
// serveSurface returns what the binary serves: the health probes throughout,
// and the gate for everything else.
func serveSurface(checks *health.Registry, g *gate) *http.ServeMux {
checks.Register("setup", g.check)
mux := http.NewServeMux()
checks.Routes(mux)
mux.Handle("/", g)
return mux
}
// setupSurface answers the routes the setup page needs and refuses the rest.
func setupSurface(ops http.Handler, dist fs.FS) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !setupRequest(r, dist) {
httpjson.Error(w, http.StatusNotFound, "not found")
return
}
ops.ServeHTTP(w, r)
})
}
// setupRequest is the whole routing decision while the gate is closed: the setup
// page, the files it loads, and the two account operations it calls. Nothing else
// passes, so neither a deep link into the SPA nor a setup route called with the
// wrong method reaches a handler.
func setupRequest(r *http.Request, dist fs.FS) bool {
switch r.URL.Path {
case setUpAccountPath:
return r.Method == http.MethodPost
case authStatusPath:
return r.Method == http.MethodGet || r.Method == http.MethodHead
}
if r.Method != http.MethodGet && r.Method != http.MethodHead {
return false
}
return r.URL.Path == "/" || builtFile(r.URL.Path, dist)
}
// builtFile reports whether path names a file in the dashboard build. A route
// inside the SPA does not, so a deep link cannot be served the setup page.
func builtFile(path string, dist fs.FS) bool {
if dist == nil {
return false
}
info, err := fs.Stat(dist, strings.TrimPrefix(path, "/"))
return err == nil && !info.IsDir()
}
// setupLookup reads whether owner setup is still required. Durable state is the
// only source: nothing a request carries can answer it.
type setupLookup func(context.Context) (bool, error)
// starter is what activation brings up: the operations Run wired. Start is safe
// to call again after it returns an error.
type starter interface {
Start(context.Context) error
}
// activate waits for the owner setup transaction to commit, starts the
// operations, and then opens the gate. It runs on the process context: the setup
// request that triggered it has been answered by then.
func activate(ctx context.Context, log *slog.Logger, lookup setupLookup, done <-chan struct{}, ops starter, g *gate) error {
required, err := waitForSetup(ctx, log, lookup, done, g)
if err != nil {
return err
}
if required {
select {
case <-done:
case <-ctx.Done():
return ctx.Err()
}
}
if err := retryStartup(ctx, log, g.stall, stageStartup, ops.Start); err != nil {
return err
}
g.publish()
log.InfoContext(ctx, "owner setup is complete; serving operations")
return nil
}
// waitForSetup answers whether owner setup is still required. A failed read
// cannot rule setup out, so it is retried rather than trusted.
func waitForSetup(ctx context.Context, log *slog.Logger, lookup setupLookup, done <-chan struct{}, g *gate) (bool, error) {
for delay := startupRetryMin; ; delay = min(delay*2, startupRetryMax) {
required, err := lookup(ctx)
if err == nil {
g.stall("")
return required, nil
}
if ctx.Err() != nil {
return false, ctx.Err()
}
g.stall(stageSetupRead)
log.WarnContext(ctx, "startup step failed; retrying", "stage", stageSetupRead, "err", err, "in", delay)
select {
case <-time.After(delay):
case <-done:
// A setup has committed in this process while the reads failed, so an
// owner exists whatever the database can answer.
g.stall("")
return false, nil
case <-ctx.Done():
return false, ctx.Err()
}
}
}
// retryStartup runs a boot step until it succeeds, passing the stage that
// failed to mark so readiness can report it. A boot step that reads the database
// must not turn a brief outage into a terminated process.
func retryStartup(ctx context.Context, log *slog.Logger, mark func(stage string), stage string, attempt func(context.Context) error) error {
for delay := startupRetryMin; ; delay = min(delay*2, startupRetryMax) {
err := attempt(ctx)
if err == nil {
mark("")
return nil
}
if ctx.Err() != nil {
return ctx.Err()
}
mark(stage)
log.WarnContext(ctx, "startup step failed; retrying", "stage", stage, "err", err, "in", delay)
select {
case <-time.After(delay):
case <-ctx.Done():
return ctx.Err()
}
}
}
+554
View File
@@ -0,0 +1,554 @@
package archie
import (
"context"
json "encoding/json/v2"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"testing/fstest"
"time"
"github.com/samcharles93/archie-core/internal/platform/health"
"github.com/samcharles93/archie-core/modules/dashboard"
"github.com/samcharles93/archie-core/modules/governance"
)
//nolint:gosec // G101: a fake credential, sent to prove it opens nothing before an owner exists.
const testAdminToken = "Bearer a-bootstrap-admin-token"
// testLog discards what the gate and activation log.
func testLog() *slog.Logger { return slog.New(slog.DiscardHandler) }
// setUpRequired is durable state on an instance with no owner.
func setUpRequired(context.Context) (bool, error) { return true, nil }
// setUpDone is durable state on an instance whose owner setup has committed.
func setUpDone(context.Context) (bool, error) { return false, nil }
// reached records the requests that get past the gate, so a test can tell a
// refusal from a handler that ran.
type reached struct {
mu sync.Mutex
seen []string
}
func (r *reached) handle(w http.ResponseWriter, req *http.Request) {
r.mu.Lock()
r.seen = append(r.seen, req.Method+" "+req.URL.Path)
r.mu.Unlock()
w.WriteHeader(http.StatusOK)
}
func (r *reached) count() int {
r.mu.Lock()
defer r.mu.Unlock()
return len(r.seen)
}
func (r *reached) paths() []string {
r.mu.Lock()
defer r.mu.Unlock()
return append([]string(nil), r.seen...)
}
// testServer builds the surface Run serves, with a stand-in for the API beside
// the real dashboard handler. The stand-in answers the routes the setup page
// calls and records every other route a request can reach.
func testServer(t *testing.T) (*http.ServeMux, *reached, *gate) {
t.Helper()
hit := &reached{}
dist := fstest.MapFS{
"index.html": {Data: []byte("<html>archie setup</html>")},
"favicon.svg": {Data: []byte("<svg>")},
"assets/app.js": {Data: []byte("console.log(1)")},
}
ops := http.NewServeMux()
dashboard.Routes(ops, dist)
ops.HandleFunc("GET "+authStatusPath, func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"setup_required":true,"user":null}`))
})
ops.HandleFunc("POST "+setUpAccountPath, func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusCreated)
})
ops.HandleFunc("GET /api/system/bootstrap", hit.handle)
ops.HandleFunc("POST /hooks/{source}", hit.handle)
ops.HandleFunc("GET /api/docs", hit.handle)
ops.HandleFunc("GET /api/openapi", hit.handle)
ops.HandleFunc("POST /api/auth/login", hit.handle)
ops.HandleFunc("GET /oauth2/login", hit.handle)
ops.HandleFunc("GET /api/tasks", hit.handle)
checks := health.NewRegistry()
checks.Register("database", func(context.Context) error { return nil })
g := newGate(ops, dist)
return serveSurface(checks, g), hit, g
}
func do(t *testing.T, served http.Handler, method, path string, withAdmin bool) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequestWithContext(context.Background(), method, path, nil)
if withAdmin {
req.Header.Set("Authorization", testAdminToken)
}
rec := httptest.NewRecorder()
served.ServeHTTP(rec, req)
return rec
}
// TestClosedGateServesOnlySetup guards the regression this issue was filed for:
// with no owner in the database, the bootstrap admin token still reached
// GET /api/system/bootstrap, and every other operational route with it.
func TestClosedGateServesOnlySetup(t *testing.T) {
tests := []struct {
name string
method string
path string
admin bool
status int
body string
// servedAsPage marks a response the dashboard handler writes, which must
// keep the CSP that stops chat-rendered Markdown loading a remote image.
servedAsPage bool
}{
{name: "auth status", method: http.MethodGet, path: authStatusPath, status: http.StatusOK, body: `"setup_required":true`},
{name: "auth status by head", method: http.MethodHead, path: authStatusPath, status: http.StatusOK},
{name: "set up the owner", method: http.MethodPost, path: setUpAccountPath, status: http.StatusCreated},
{name: "the setup page", method: http.MethodGet, path: "/", status: http.StatusOK, body: "archie setup", servedAsPage: true},
{name: "a script the page loads", method: http.MethodGet, path: "/assets/app.js", status: http.StatusOK, body: "console.log(1)", servedAsPage: true},
{name: "the page icon", method: http.MethodGet, path: "/favicon.svg", status: http.StatusOK, body: "<svg>", servedAsPage: true},
{name: "liveness", method: http.MethodGet, path: "/healthz", status: http.StatusOK, body: "ok\n"},
// From here down nothing reaches a handler, credential or not.
{name: "operational API", method: http.MethodGet, path: "/api/system/bootstrap", status: http.StatusNotFound},
{name: "operational API with the admin token", method: http.MethodGet, path: "/api/system/bootstrap", admin: true, status: http.StatusNotFound},
{name: "another operational read", method: http.MethodGet, path: "/api/tasks", status: http.StatusNotFound},
{name: "another operational read with the admin token", method: http.MethodGet, path: "/api/tasks", admin: true, status: http.StatusNotFound},
{name: "webhook intake", method: http.MethodPost, path: "/hooks/github", status: http.StatusNotFound},
{name: "API document", method: http.MethodGet, path: "/api/docs", status: http.StatusNotFound},
{name: "OpenAPI document", method: http.MethodGet, path: "/api/openapi", status: http.StatusNotFound},
{name: "sign in", method: http.MethodPost, path: "/api/auth/login", status: http.StatusNotFound},
{name: "OIDC sign in", method: http.MethodGet, path: "/oauth2/login", status: http.StatusNotFound},
{name: "a route inside the SPA", method: http.MethodGet, path: "/tasks", status: http.StatusNotFound},
{name: "a route inside the SPA with a trailing slash", method: http.MethodGet, path: "/settings/status/", status: http.StatusNotFound},
{name: "setup by GET", method: http.MethodGet, path: setUpAccountPath, status: http.StatusNotFound},
{name: "status by POST", method: http.MethodPost, path: authStatusPath, status: http.StatusNotFound},
{name: "status with a trailing slash", method: http.MethodGet, path: authStatusPath + "/", status: http.StatusNotFound},
{name: "the page by POST", method: http.MethodPost, path: "/", status: http.StatusNotFound},
{name: "a script by POST", method: http.MethodPost, path: "/assets/app.js", status: http.StatusNotFound},
{name: "a file the build has no name for", method: http.MethodGet, path: "/assets/missing.js", status: http.StatusNotFound},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
served, hit, _ := testServer(t)
rec := do(t, served, tc.method, tc.path, tc.admin)
if rec.Code != tc.status {
t.Fatalf("%s %s: status = %d, want %d", tc.method, tc.path, rec.Code, tc.status)
}
if tc.body != "" && !strings.Contains(rec.Body.String(), tc.body) {
t.Fatalf("%s %s: body = %q, want it to contain %q", tc.method, tc.path, rec.Body.String(), tc.body)
}
if got := hit.count(); got != 0 {
t.Fatalf("%s %s: %d operational handlers ran, want none (reached %v)", tc.method, tc.path, got, hit.paths())
}
if tc.servedAsPage {
// Mirrors the dashboard's own header: the setup page must not lose it.
if got := rec.Header().Get("Content-Security-Policy"); got != "img-src 'self' data:" {
t.Fatalf("%s %s: Content-Security-Policy = %q, want the dashboard's", tc.method, tc.path, got)
}
}
})
}
}
// TestOpenGateServesOperations guards the other half: the routes the gate
// refuses before setup are the ones that answer after it, so a refusal above
// is the gate's decision and not a missing route.
func TestOpenGateServesOperations(t *testing.T) {
tests := []struct {
name string
method string
path string
admin bool
status int
handled int
body string
}{
{name: "operational API with the admin token", method: http.MethodGet, path: "/api/system/bootstrap", admin: true, status: http.StatusOK, handled: 1},
{name: "another operational read", method: http.MethodGet, path: "/api/tasks", status: http.StatusOK, handled: 1},
{name: "webhook intake", method: http.MethodPost, path: "/hooks/github", status: http.StatusOK, handled: 1},
{name: "API document", method: http.MethodGet, path: "/api/docs", status: http.StatusOK, handled: 1},
{name: "OpenAPI document", method: http.MethodGet, path: "/api/openapi", status: http.StatusOK, handled: 1},
{name: "sign in", method: http.MethodPost, path: "/api/auth/login", status: http.StatusOK, handled: 1},
{name: "OIDC sign in", method: http.MethodGet, path: "/oauth2/login", status: http.StatusOK, handled: 1},
{name: "a route inside the SPA", method: http.MethodGet, path: "/tasks", status: http.StatusOK, body: "archie setup"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
served, hit, g := testServer(t)
g.publish()
rec := do(t, served, tc.method, tc.path, tc.admin)
if rec.Code != tc.status {
t.Fatalf("%s %s: status = %d, want %d", tc.method, tc.path, rec.Code, tc.status)
}
if tc.body != "" && !strings.Contains(rec.Body.String(), tc.body) {
t.Fatalf("%s %s: body = %q, want it to contain %q", tc.method, tc.path, rec.Body.String(), tc.body)
}
if got := hit.count(); got != tc.handled {
t.Fatalf("%s %s: %d operational handlers ran, want %d (reached %v)", tc.method, tc.path, got, tc.handled, hit.paths())
}
})
}
}
func TestGateIsNotBypassedByPathTricks(t *testing.T) {
// A path the mux cleans is redirected before the gate sees it, and the
// cleaned path is refused in turn, so no spelling reaches a handler.
for _, path := range []string{"//api/system/bootstrap", "/api/../api/system/bootstrap", "/api/./system/bootstrap", "/api/auth/../system/bootstrap"} {
t.Run(path, func(t *testing.T) {
served, hit, _ := testServer(t)
rec := do(t, served, http.MethodGet, path, true)
if rec.Code == http.StatusOK {
t.Fatalf("%s: status 200, want a refusal", path)
}
if location := rec.Header().Get("Location"); location != "" {
if followed := do(t, served, http.MethodGet, location, true); followed.Code != http.StatusNotFound {
t.Fatalf("%s redirected to %s, which answered %d, want 404", path, location, followed.Code)
}
}
if got := hit.count(); got != 0 {
t.Fatalf("%s: %d operational handlers ran, want none (reached %v)", path, got, hit.paths())
}
})
}
}
func TestReadinessReportsSetupUntilOperationsStart(t *testing.T) {
// A missing owner is not a crash: liveness answers, readiness says why the
// instance serves nothing operational, and the dependency checks take over
// once operations are up.
served, _, g := testServer(t)
if rec := do(t, served, http.MethodGet, "/healthz", false); rec.Code != http.StatusOK {
t.Fatalf("liveness while gated: status = %d, want %d", rec.Code, http.StatusOK)
}
rec := do(t, served, http.MethodGet, "/readyz", false)
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("readiness while gated: status = %d, want %d", rec.Code, http.StatusServiceUnavailable)
}
var body struct {
Ready bool `json:"ready"`
Failures map[string]string `json:"failures"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("decode readiness: %v (%s)", err, rec.Body.String())
}
if body.Ready {
t.Fatalf("readiness while gated: ready = true, want false")
}
if !strings.Contains(body.Failures["setup"], "owner setup") {
t.Fatalf("readiness while gated: failures = %v, want the setup check", body.Failures)
}
g.publish()
if rec := do(t, served, http.MethodGet, "/readyz", false); rec.Code != http.StatusOK {
t.Fatalf("readiness once operations serve: status = %d, want %d (%s)", rec.Code, http.StatusOK, rec.Body.String())
}
}
// fakeOperations stands in for the startup work and counts how often it runs.
type fakeOperations struct {
starts atomic.Int32
startFails atomic.Int32
startErr error
}
func (f *fakeOperations) Start(context.Context) error {
f.starts.Add(1)
if f.startFails.Load() > 0 {
f.startFails.Add(-1)
return f.startErr
}
return nil
}
func TestActivateStartsOperationsWhenSetupCommits(t *testing.T) {
// Nothing starts while the owner is missing, the setup page keeps answering
// so the operator can finish, and the commit starts everything once.
signal := governance.NewSetupSignal()
ops := &fakeOperations{}
served, hit, g := testServer(t)
done := make(chan error, 1)
go func() { done <- activate(context.Background(), testLog(), setUpRequired, signal.Done(), ops, g) }()
if got := ops.starts.Load(); got != 0 {
t.Fatalf("starts before the commit = %d, want 0", got)
}
if g.opened() {
t.Fatalf("the gate is open before the commit")
}
if rec := do(t, served, http.MethodGet, authStatusPath, false); rec.Code != http.StatusOK {
t.Fatalf("auth status while waiting: status = %d, want %d", rec.Code, http.StatusOK)
}
if rec := do(t, served, http.MethodGet, "/api/system/bootstrap", true); rec.Code != http.StatusNotFound {
t.Fatalf("operational API while waiting: status = %d, want %d", rec.Code, http.StatusNotFound)
}
signal.Complete()
if err := <-done; err != nil {
t.Fatalf("activate: %v", err)
}
if got := ops.starts.Load(); got != 1 {
t.Fatalf("starts after the commit = %d, want 1", got)
}
if rec := do(t, served, http.MethodGet, "/api/system/bootstrap", true); rec.Code != http.StatusOK {
t.Fatalf("operational API after the commit: status = %d, want %d", rec.Code, http.StatusOK)
}
if got := hit.count(); got != 1 {
t.Fatalf("operational handlers after the commit = %d, want 1", got)
}
}
func TestConcurrentSetupCommitsStartOperationsOnce(t *testing.T) {
// Two setup transactions can't both commit, but the signal has to hold even
// if callers race: one set of workers, one open gate.
signal := governance.NewSetupSignal()
ops := &fakeOperations{}
_, _, g := testServer(t)
done := make(chan error, 1)
go func() { done <- activate(context.Background(), testLog(), setUpRequired, signal.Done(), ops, g) }()
var completing sync.WaitGroup
for range 8 {
completing.Go(signal.Complete)
}
completing.Wait()
signal.Complete()
if err := <-done; err != nil {
t.Fatalf("activate: %v", err)
}
if got := ops.starts.Load(); got != 1 {
t.Fatalf("starts = %d, want 1", got)
}
}
func TestCancelledBeforeSetupStartsNothing(t *testing.T) {
signal := governance.NewSetupSignal()
ops := &fakeOperations{}
_, _, g := testServer(t)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- activate(ctx, testLog(), setUpRequired, signal.Done(), ops, g) }()
cancel()
if err := <-done; !errors.Is(err, context.Canceled) {
t.Fatalf("activate = %v, want context.Canceled", err)
}
if got := ops.starts.Load(); got != 0 {
t.Fatalf("starts after cancellation = %d, want 0", got)
}
if g.opened() {
t.Fatalf("the gate opened on a cancelled activation")
}
}
func TestCompletedSetupStartsWithoutWaiting(t *testing.T) {
// The restart after a completed setup: durable state says no owner is
// missing, so the process must not wait for a signal this run can never
// send.
signal := governance.NewSetupSignal() // never completed, as on a restart
ops := &fakeOperations{}
served, hit, g := testServer(t)
if err := activate(context.Background(), testLog(), setUpDone, signal.Done(), ops, g); err != nil {
t.Fatalf("activate: %v", err)
}
if got := ops.starts.Load(); got != 1 {
t.Fatalf("starts = %d, want 1", got)
}
if !g.opened() {
t.Fatalf("the gate is shut with setup already complete")
}
if rec := do(t, served, http.MethodGet, "/api/system/bootstrap", true); rec.Code != http.StatusOK {
t.Fatalf("operational API after a restart: status = %d, want %d", rec.Code, http.StatusOK)
}
if got := hit.count(); got != 1 {
t.Fatalf("operational handlers = %d, want 1", got)
}
}
// flakyLookup fails a set number of reads before answering, as a database that
// is briefly unreachable does.
type flakyLookup struct {
failures atomic.Int32
required bool
reads atomic.Int32
}
// newFlakyLookup fails failures reads before answering required.
func newFlakyLookup(failures int32, required bool) *flakyLookup {
l := &flakyLookup{required: required}
l.failures.Store(failures)
return l
}
func (f *flakyLookup) lookup(context.Context) (bool, error) {
f.reads.Add(1)
if f.failures.Load() > 0 {
f.failures.Add(-1)
return false, errors.New("connection refused")
}
return f.required, nil
}
func TestUnreadableSetupStateIsRetried(t *testing.T) {
// A database that is briefly unavailable must not hold an instance shut
// until someone restarts it: setup state that can't be read is retried, and
// readiness reports the failure meanwhile.
lookup := newFlakyLookup(2, false)
ops := &fakeOperations{}
served, hit, g := testServer(t)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
done := make(chan error, 1)
go func() { done <- activate(ctx, testLog(), lookup.lookup, nil, ops, g) }()
// While the read fails, nothing starts and readiness names the failure.
if got := ops.starts.Load(); got != 0 {
t.Fatalf("starts while setup state is unreadable = %d, want 0", got)
}
for range 100 {
if strings.Contains(readyzBody(t, served), stageSetupRead) {
break
}
time.Sleep(10 * time.Millisecond)
}
body := readyzBody(t, served)
if !strings.Contains(body, stageSetupRead) {
t.Fatalf("readiness while setup state is unreadable = %q, want %q", body, stageSetupRead)
}
if strings.Contains(body, "connection refused") {
t.Fatalf("readiness = %q, leaked the database's own error", body)
}
if err := <-done; err != nil {
t.Fatalf("activate: %v", err)
}
if got := ops.starts.Load(); got != 1 {
t.Fatalf("starts after the read recovered = %d, want 1", got)
}
if got := lookup.reads.Load(); got < 3 {
t.Fatalf("reads = %d, want the failed read retried", got)
}
if rec := do(t, served, http.MethodGet, "/api/system/bootstrap", true); rec.Code != http.StatusOK {
t.Fatalf("operational API after the read recovered: status = %d, want %d", rec.Code, http.StatusOK)
}
if got := hit.count(); got != 1 {
t.Fatalf("operational handlers after the read recovered = %d, want 1", got)
}
}
func TestUnreadableSetupStateWaitsForTheCommit(t *testing.T) {
// When the read keeps failing, a setup that commits in this process is
// still enough: the owner exists, so operations may start.
lookup := newFlakyLookup(1000, true)
ops := &fakeOperations{}
_, _, g := testServer(t)
signal := governance.NewSetupSignal()
done := make(chan error, 1)
go func() { done <- activate(context.Background(), testLog(), lookup.lookup, signal.Done(), ops, g) }()
time.Sleep(50 * time.Millisecond)
if got := ops.starts.Load(); got != 0 {
t.Fatalf("starts while setup state is unreadable = %d, want 0", got)
}
signal.Complete()
if err := <-done; err != nil {
t.Fatalf("activate: %v", err)
}
if got := ops.starts.Load(); got != 1 {
t.Fatalf("starts after the commit = %d, want 1", got)
}
}
func readyzBody(t *testing.T, served http.Handler) string {
t.Helper()
return do(t, served, http.MethodGet, "/readyz", false).Body.String()
}
func TestOperationsStartIsRetried(t *testing.T) {
// connectors.Module.Start returns an error only for the read of accepted
// connectors, before anything launches, so a failed Start leaves nothing
// running and the next attempt is safe. Without that retry a transient read
// error took the process down.
ops := &fakeOperations{startErr: errors.New("connection refused")}
ops.startFails.Store(2)
served, hit, g := testServer(t)
signal := governance.NewSetupSignal()
signal.Complete()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
done := make(chan error, 1)
go func() { done <- activate(ctx, testLog(), setUpDone, signal.Done(), ops, g) }()
if err := <-done; err != nil {
t.Fatalf("activate: %v", err)
}
if got := ops.starts.Load(); got != 3 {
t.Fatalf("start calls = %d, want the two failures retried", got)
}
if !g.opened() {
t.Fatalf("the gate is shut after a retried start")
}
if rec := do(t, served, http.MethodGet, "/api/system/bootstrap", true); rec.Code != http.StatusOK {
t.Fatalf("operational API after a retried start: status = %d, want %d", rec.Code, http.StatusOK)
}
if got := hit.count(); got != 1 {
t.Fatalf("operational handlers = %d, want 1: one surface, not one per attempt", got)
}
}
func TestReadinessNamesTheStageWithoutTheRawError(t *testing.T) {
// Readiness answers whoever can reach the port, so it names the stage that
// failed and keeps the database's own error text in the log.
ops := &fakeOperations{startErr: errors.New("pq: password authentication failed for user archie")}
ops.startFails.Store(1000)
served, _, g := testServer(t)
signal := governance.NewSetupSignal()
signal.Complete()
done := make(chan error, 1)
go func() { done <- activate(context.Background(), testLog(), setUpDone, signal.Done(), ops, g) }()
for range 200 {
if strings.Contains(readyzBody(t, served), "starting operations failed") {
break
}
time.Sleep(10 * time.Millisecond)
}
body := readyzBody(t, served)
if !strings.Contains(body, "starting operations failed") {
t.Fatalf("readiness = %q, want it to name the stage", body)
}
for _, leak := range []string{"pq:", "password", "user archie", "connection refused"} {
if strings.Contains(body, leak) {
t.Fatalf("readiness = %q, leaked %q", body, leak)
}
}
if g.opened() {
t.Fatalf("the gate opened while a startup stage fails")
}
}
+43
View File
@@ -0,0 +1,43 @@
package archie
import (
"context"
"fmt"
"slices"
"github.com/samcharles93/archie-core/internal/platform/health"
"github.com/samcharles93/archie-core/modules/approvals"
"github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/runs"
"github.com/samcharles93/archie-core/modules/system"
)
// healthSources joins what each module knows about itself into the sources the
// system health report reads. The report asks them on demand, so nothing here
// polls or keeps state.
func healthSources(checks *health.Registry, conns *connectors.Module, engine *runs.Engine, allow *approvals.Module) system.Sources {
return system.Sources{
Checks: func(ctx context.Context) []health.Result {
return slices.DeleteFunc(checks.Results(ctx), func(r health.Result) bool {
// The report lists each connector with its own cause.
return r.Name == "connectors"
})
},
Connectors: conns.Health,
Runner: engine.Runner,
Waiting: func(ctx context.Context) (system.Waiting, error) {
pending, err := allow.Pending(ctx)
if err != nil {
return system.Waiting{}, fmt.Errorf("list pending approvals: %w", err)
}
counts, err := engine.Counts(ctx, orgID)
if err != nil {
return system.Waiting{}, err
}
return system.Waiting{Approvals: len(pending), Runs: counts}, nil
},
LastFailedRun: func(ctx context.Context) (*runs.RunView, error) {
return engine.LastFailed(ctx, orgID)
},
}
}
+163
View File
@@ -0,0 +1,163 @@
package archie
import (
"context"
"fmt"
"log/slog"
"sync"
"time"
"github.com/samcharles93/archie-core/internal/platform/health"
"github.com/samcharles93/archie-core/modules/approvals"
"github.com/samcharles93/archie-core/modules/chat"
"github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/deliveries"
"github.com/samcharles93/archie-core/modules/events"
"github.com/samcharles93/archie-core/modules/governance"
"github.com/samcharles93/archie-core/modules/judgement"
"github.com/samcharles93/archie-core/modules/memory"
"github.com/samcharles93/archie-core/modules/proposals"
"github.com/samcharles93/archie-core/modules/runs"
)
// catalogueUpdateInterval is how often an extension that follows the catalogue
// checks it for a new version.
const catalogueUpdateInterval = time.Hour
// operations is everything the gate holds back: the connectors, the access
// chain administrative writes are checked against, the workflow that ships with
// the binary, and the loops that do work. Run wires it at boot and Start brings
// it up, once, after owner setup has committed.
type operations struct {
log *slog.Logger
checks *health.Registry
settings *governance.Module
conns *connectors.Module
engine *runs.Engine
hear *events.Module
tell *deliveries.Module
talk *chat.Module
judge *judgement.Module
allow *approvals.Module
remember *memory.Module
proposed *proposals.Module
// completeRecord finishes the record of a committed deletion whose entry could
// not be written.
completeRecord func(context.Context) (int, error)
workers sync.WaitGroup
}
// Start brings up every part of the binary that does work, in the order the
// other parts depend on: the role policies and access chain, the workflow that
// ships with the binary, the connectors, then the loops.
//
// Calling it again after it returns an error is safe. Every step that can fail
// runs before a connector launches, and connectors.Module.Start fails only for
// the read of accepted connectors, before launching any. An error therefore
// means nothing is running.
func (o *operations) Start(ctx context.Context) error {
access, err := startAccess(ctx, o.log, o.settings)
if err != nil {
return err
}
// Every entry point uses the same chain, and every decision, allowed or
// refused, is stored.
checked := governance.Recording(access, o.settings, o.log.With("module", "governance"))
// A workflow takes its context from the run handle, as a handler takes it
// from the request.
o.engine.Use(runs.Deps{
Settings: o.settings, Toolbox: o.conns, Judge: o.judge, Approver: o.allow,
Proposals: o.proposed, Notifier: o.tell, Messenger: o.tell, Memory: o.remember, Capabilities: o.conns,
Access: checked,
})
if err := installStarter(ctx, o.engine); err != nil {
return err
}
// A connector's new declarations are re-checked against the saved
// workflows that reference it, so an update that would break them is
// refused instead of failing a run later.
o.conns.Use(func(ctx context.Context, connector string, caps connectors.Capabilities) error {
return o.engine.RecheckConnector(ctx, orgID, connector, caps)
})
if err := o.conns.Start(ctx); err != nil {
return fmt.Errorf("read accepted connectors: %w", err)
}
// Nothing below can fail, so a retry cannot launch a connector or a loop twice.
o.checks.Register("connectors", o.conns.Ready)
// An extension that follows the catalogue checks it for a new version. With
// no catalogue source set it does nothing.
o.workers.Go(func() { o.conns.WatchUpdates(ctx, catalogueUpdateInterval) })
// Administrative writes, and every API request, are checked against the same
// live policy chain as chat and background work. The webhook intake applies
// each source's delivery policy from it.
o.settings.UseAuthorizer(checked)
o.allow.UseAuthorizer(checked)
o.proposed.UseAuthorizer(checked)
o.tell.UseAccess(checked)
o.hear.UseDeliveryPolicy(governance.RecordingDelivery(access, o.settings, o.log.With("module", "governance")))
o.hear.UseTrustedProxies(o.settings.TrustedProxies)
o.talk.Use(chat.Deps{
People: o.settings, Access: checked, Settings: o.settings, Toolbox: o.conns, Judge: o.judge,
Approver: o.allow, Memory: o.remember, Runs: o.engine, Notifier: o.tell,
})
for _, loop := range []func(context.Context){o.engine.Work, o.hear.Work, o.tell.Work, o.proposed.Work, o.talk.Work, o.retryDeletionRecord} {
o.workers.Go(func() { loop(ctx) })
}
return nil
}
// retryDeletionRecord keeps trying to complete the record of a deletion that
// committed while its entry could not be written, so the instance heals without a
// restart. It does nothing while the record is complete.
func (o *operations) retryDeletionRecord(ctx context.Context) {
ticker := time.NewTicker(deletionRecordRetry)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if !o.remember.RecordPending() || o.completeRecord == nil {
continue
}
// The mark is taken before the reconcile: a failure recorded while it
// runs must still leave the instance unhealthy.
mark := o.remember.FailureMark()
added, err := o.completeRecord(ctx)
if err != nil {
o.log.ErrorContext(ctx, "complete the record of deletions", "error", err)
continue
}
o.remember.MarkRecordComplete(mark)
o.log.WarnContext(ctx, "completed the record of deletions", "entries", added)
}
}
}
// Wait blocks until every loop Start began has returned.
func (o *operations) Wait() {
o.workers.Wait()
}
// installStarter puts the workflow that ships with the binary in place. It
// belongs to the organisation, so it waits until setup has created one.
func installStarter(ctx context.Context, engine *runs.Engine) error {
if _, err := engine.InstallShipped(ctx, orgID, "investigate", runs.InvestigateDocument(), string(governance.SystemID)); err != nil {
return fmt.Errorf("install the investigate workflow: %w", err)
}
if _, err := engine.InstallShipped(ctx, orgID, runs.ProposalWorkflow, runs.ProposalDocument(), string(governance.SystemID)); err != nil {
return fmt.Errorf("install the proposal workflow: %w", err)
}
return nil
}
// startAccess seeds the operating org's shipped role policies and returns the
// access policy chain, kept current as policies change.
func startAccess(ctx context.Context, log *slog.Logger, settings *governance.Module) (*governance.Live, error) {
if err := settings.EnsureShippedOrgPolicies(ctx, governance.DefaultOrgID); err != nil {
return nil, fmt.Errorf("seed the role policies: %w", err)
}
return governance.StartLive(ctx, settings.ListPolicies, settings.PoliciesVersion, log.With("module", "governance")), nil
}
+191 -62
View File
@@ -5,33 +5,38 @@ package archie
import ( import (
"context" "context"
"encoding/json/jsontext"
"errors" "errors"
"fmt" "fmt"
"log/slog" "log/slog"
"net" "net"
"net/http" "net/http"
"os" "os"
"path/filepath"
"strconv" "strconv"
"sync"
"time" "time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/samcharles93/ai-sdk/runtime" "github.com/samcharles93/ai-sdk/runtime"
"github.com/samcharles93/archie-core/internal/buildinfo" "github.com/samcharles93/archie-core/internal/buildinfo"
"github.com/samcharles93/archie-core/internal/platform/deletions"
"github.com/samcharles93/archie-core/internal/platform/health" "github.com/samcharles93/archie-core/internal/platform/health"
"github.com/samcharles93/archie-core/internal/platform/httpapi" "github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/internal/platform/hub" "github.com/samcharles93/archie-core/internal/platform/hub"
"github.com/samcharles93/archie-core/internal/platform/pg" "github.com/samcharles93/archie-core/internal/platform/pg"
"github.com/samcharles93/archie-core/internal/platform/seal"
"github.com/samcharles93/archie-core/modules/approvals" "github.com/samcharles93/archie-core/modules/approvals"
"github.com/samcharles93/archie-core/modules/chat"
"github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/dashboard" "github.com/samcharles93/archie-core/modules/dashboard"
"github.com/samcharles93/archie-core/modules/deliveries" "github.com/samcharles93/archie-core/modules/deliveries"
"github.com/samcharles93/archie-core/modules/drafts"
"github.com/samcharles93/archie-core/modules/events" "github.com/samcharles93/archie-core/modules/events"
"github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/governance"
"github.com/samcharles93/archie-core/modules/judgement" "github.com/samcharles93/archie-core/modules/judgement"
"github.com/samcharles93/archie-core/modules/memory" "github.com/samcharles93/archie-core/modules/memory"
"github.com/samcharles93/archie-core/modules/proposals"
"github.com/samcharles93/archie-core/modules/runs" "github.com/samcharles93/archie-core/modules/runs"
"github.com/samcharles93/archie-core/modules/system" "github.com/samcharles93/archie-core/modules/system"
"github.com/samcharles93/archie-core/ui" "github.com/samcharles93/archie-core/ui"
@@ -39,8 +44,18 @@ import (
const shutdownGrace = 10 * time.Second const shutdownGrace = 10 * time.Second
// deletionRecordRetry is how often an incomplete record of a committed deletion
// is retried.
const deletionRecordRetry = 30 * time.Second
// Run boots the binary from the config at configPath and blocks until ctx ends // Run boots the binary from the config at configPath and blocks until ctx ends
// or the server fails. // or the server fails.
//
// An instance whose owner setup has not committed serves the setup page and
// nothing else: connectors, module routes, the shipped workflow and the worker
// loops all wait for that transaction. Durable state says whether it has already
// happened, so a restart reads that state and starts serving operations
// immediately.
func Run(ctx context.Context, configPath string) error { func Run(ctx context.Context, configPath string) error {
log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "archie", "version", buildinfo.Version) log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "archie", "version", buildinfo.Version)
@@ -48,37 +63,108 @@ func Run(ctx context.Context, configPath string) error {
if err != nil { if err != nil {
return err return err
} }
if err := pg.Migrate(ctx, log, cfg.Database.OwnerURL, cfg.Database.URL, schemas); err != nil {
return err
}
db, err := pg.Open(ctx, cfg.Database.URL) db, err := pg.Open(ctx, cfg.Database.URL)
if err != nil { if err != nil {
return err return err
} }
defer func() { _ = db.Close() }() // The serve lock is taken before the schema is touched: a restore holds it
// exclusively for as long as it replaces the database and replays the
// deletions recorded outside it, and no process may migrate or serve during
// that window.
holdServe, err := pg.ClaimServe(ctx, db, pg.ServeLockName)
if err != nil {
_ = db.Close()
return fmt.Errorf("claim the database: %w", err)
}
defer holdServe()
// Nothing is served yet, so there is no readiness to report while this retries.
migrate := func(ctx context.Context) error {
return pg.Migrate(ctx, log, cfg.Database.OwnerURL, cfg.Database.URL, schemas)
}
if err := retryStartup(ctx, log, func(string) {}, stageMigrate, migrate); err != nil {
_ = db.Close()
return err
}
// A deletion whose record did not land is completed before anything serves:
// the database is the authority on what was deleted, the record outside it on
// what a restore can apply again.
if added, err := memory.Reconcile(ctx, db, cfg.StateDir); err != nil {
_ = db.Close()
return fmt.Errorf("complete the record of deletions: %w", err)
} else if added > 0 {
log.WarnContext(ctx, "completed the record of deletions", "entries", added)
}
// The record is applied to whatever database is here before anything serves.
// A restore that replaced the database and then failed to apply the record
// leaves the notes it recorded behind, and those are the ones nobody may see
// again.
if applied, err := memory.ReapplyDeletions(ctx, db, cfg.StateDir); err != nil {
_ = db.Close()
return fmt.Errorf("apply the record of deletions: %w", err)
} else if applied > 0 {
log.WarnContext(ctx, "applied the record of deletions", "notes", applied)
}
b, err := wire(log, configPath, cfg, db) //nolint:contextcheck // the API's guard derives its context from each request
if err != nil {
_ = db.Close()
return err
}
defer b.close()
work, stop := context.WithCancel(ctx)
defer stop()
started := make(chan struct{})
go func() {
// Startup failures are retried, so only shutdown ends activation.
_ = activate(work, log, b.settings.AccountSetupRequired, b.settings.SetupDone(), b.ops, b.gate)
close(started)
}()
serveErr := serve(work, log, cfg.Listen, b.served)
stop()
<-started
// Every loop activation began has returned before the caller closes the
// connectors and the database.
b.ops.Wait()
return serveErr
}
// binary is a wired instance: the surface it serves, and what waits for owner
// setup before it does any work.
type binary struct {
db *sqlx.DB
conns *connectors.Module
gate *gate
served http.Handler
settings *governance.Module
ops *operations
}
// wire builds every module and registers its routes. Nothing operational
// starts here: the routes are wired on a mux the gate holds back, and Start
// brings them up once owner setup has committed.
func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary, error) {
checks := health.NewRegistry() checks := health.NewRegistry()
checks.Register("database", db.PingContext) checks.Register("database", db.PingContext)
mux := http.NewServeMux()
checks.Routes(mux)
api := httpapi.New(mux, buildinfo.Version, cfg.AdminTokenSHA256)
runtime.RegisterBuiltinClasses() runtime.RegisterBuiltinClasses()
settings := governance.NewModule(db, log.With("module", "governance"), orgID) settings := governance.NewModule(db, log.With("module", "governance"), orgID)
mux := http.NewServeMux()
api := httpapi.New(mux, buildinfo.Version, settings.Authenticator(cfg.AdminTokenSHA256), settings)
conns, err := connectors.NewModule(db, log.With("module", "connectors"), orgID, connectors.Sealing{ conns, err := connectors.NewModule(db, log.With("module", "connectors"), connectors.Sealing{
Identity: cfg.AgeIdentity, Backups: cfg.AgeBackupRecipients, Identity: cfg.AgeIdentity, Backups: cfg.AgeBackupRecipients,
}) }, filepath.Join(cfg.StateDir, "extensions"))
if err != nil { if err != nil {
return err return nil, err
} }
defer conns.Close() // A model's key is a credential id resolved through the sealed store in
if err := conns.Start(ctx); err != nil { // organisation scope with no person attached.
return err settings.UseCredentials(orgCredentials{conns: conns, orgID: string(governance.DefaultOrgID)})
} // An account links a channel account on the connectors that can link.
checks.Register("connectors", conns.Ready) settings.UseChannels(conns)
// A model's key is a credential name resolved through the sealed store.
settings.UseCredentials(conns)
sys := system.New(system.Bootstrap{ sys := system.New(system.Bootstrap{
Listen: cfg.Listen, Database: DatabaseHost(cfg.Database.URL), Schemas: len(schemas), Listen: cfg.Listen, Database: DatabaseHost(cfg.Database.URL), Schemas: len(schemas),
@@ -92,74 +178,117 @@ func Run(ctx context.Context, configPath string) error {
tell := deliveries.NewModule(db, log.With("module", "deliveries"), orgID, live, conns) tell := deliveries.NewModule(db, log.With("module", "deliveries"), orgID, live, conns)
engine := runs.New(db, log.With("module", "runs"), runs.Options{Owner: owner()}) engine := runs.New(db, log.With("module", "runs"), runs.Options{Owner: owner()})
talk := chat.NewModule(db, log.With("module", "chat"), orgID, live)
// A workflow takes its context from the run handle, as a handler takes it // A workflow takes its context from the run handle, as a handler takes it
// from the request. // from the request.
classes := judgement.NewClasses(db, log.With("module", "judgement"), orgID) actionTypes := judgement.NewActionTypes(db, log.With("module", "judgement"), orgID)
// An approval request is carried by deliveries, and its answer wakes the run // An approval request is carried by deliveries, and its answer wakes the run
// that is waiting on it. // that is waiting on it.
allow := approvals.NewModule(db, log.With("module", "approvals"), orgID, tell, engine, classes, settings, settings) allow := approvals.NewModule(db, log.With("module", "approvals"), orgID, tell, answers{chat: talk, runs: engine}, actionTypes, settings, settings)
// Approving an action that can't be undone needs a fresh passkey assertion.
allow.UseConfirmer(settings)
policies := judgement.NewPolicies(db, log.With("module", "judgement"), orgID) policies := judgement.NewPolicies(db, log.With("module", "judgement"), orgID)
// An answer a channel delivers is an event, and settles its request. // An answer a channel delivers is an event, and settles its request.
hear := events.NewModule(db, log.With("module", "events"), orgID, conns, engine, allow, tell) sealer, err := seal.New(cfg.AgeIdentity, cfg.AgeBackupRecipients)
hear.Routes(mux) if err != nil {
judge := newJudgement(db, log, conns, classes, policies, settings, hear) return nil, err
if err := useWorkflows(ctx, engine, runs.Deps{Settings: settings, Toolbox: conns, Judge: judge, Approver: allow, Notifier: tell, Memory: memory.NewModule(db, orgID)}); err != nil {
return err
} }
hear := events.NewModule(db, log.With("module", "events"), orgID, sealer, conns, engine, allow, settings, tell)
hear.Routes(mux)
engine.UseReferrers(hear)
judge := newJudgement(db, log, conns, actionTypes, policies, settings, hear)
// The record of deletions outlives this process and its database, so the
// log exists before anything can be deleted: an instance that has run this
// release and lost its log is a different case from one that never deleted.
ledger := deletions.NewLog(deletions.Path(cfg.StateDir))
if err := ledger.Ensure(); err != nil {
return nil, fmt.Errorf("prepare the deletion record: %w", err)
}
remember := memory.NewModule(db, orgID, log.With("module", "memory"), ledger)
checks.Register("deletion record", func(context.Context) error {
if remember.RecordPending() {
return errors.New("a deletion is committed and its record is still being written")
}
return nil
})
proposed := proposals.NewModule(db, log.With("module", "proposals"), orgID, hear, engine, policies, judge)
// A cause that keeps recurring becomes a root-cause proposal.
remember.UseProposals(proposed)
// Approving an action that can't be undone needs a fresh passkey assertion.
proposed.UseConfirmer(settings)
sys.UseHealth(healthSources(checks, conns, engine, allow))
apiModules{ apiModules{
settings: settings, conns: conns, system: sys, tell: tell, allow: allow, classes: classes, policies: policies, settings: settings, conns: conns, system: sys, tell: tell, allow: allow, actionTypes: actionTypes, policies: policies,
hear: hear, judge: judge, engine: engine, drafts: drafts.NewModule(db, log.With("module", "drafts"), orgID, hear, engine, policies), hear: hear, judge: judge, engine: engine, chat: talk, proposals: proposed,
notes: remember, live: live,
}.register(api) }.register(api)
dashboard.Routes(mux, ui.DistDirFS) dashboard.Routes(mux, ui.DistDirFS)
return serveWithWork(ctx, log, cfg.Listen, mux, engine.Work, hear.Work, tell.Work) g := newGate(mux, ui.DistDirFS)
return &binary{
db: db, conns: conns, gate: g, served: serveSurface(checks, g), settings: settings,
ops: &operations{
log: log, checks: checks, settings: settings, conns: conns, engine: engine, hear: hear,
tell: tell, talk: talk, judge: judge, allow: allow, remember: remember, proposed: proposed,
completeRecord: func(ctx context.Context) (int, error) {
return memory.Reconcile(ctx, db, cfg.StateDir)
},
},
}, nil
} }
// serveWithWork serves mux while the loops run, and stops the loops once it // close stops the connectors and then the database.
// returns. func (b *binary) close() {
func serveWithWork(ctx context.Context, log *slog.Logger, addr string, mux *http.ServeMux, loops ...func(context.Context)) error { b.conns.Close()
ctx, stop := context.WithCancel(ctx) _ = b.db.Close()
defer stop()
wait := work(ctx, loops...)
err := serve(ctx, log, addr, mux)
stop()
wait()
return err
} }
// useWorkflows gives the engine what workflow steps use and installs the // orgCredentials confines every model-provider credential lookup to orgID with
// workflow that ships with the binary. // no person attached, so a caller's personal credentials are never reachable.
func useWorkflows(ctx context.Context, engine *runs.Engine, deps runs.Deps) error { type orgCredentials struct {
engine.Use(deps) conns *connectors.Module
if _, err := engine.Install(ctx, orgID, "investigate", runs.InvestigateDocument(), "starter"); err != nil { orgID string
return fmt.Errorf("install the investigate workflow: %w", err) }
func (c orgCredentials) BearerTokenByID(ctx context.Context, id uuid.UUID) (string, error) {
return c.conns.BearerTokenByID(connectors.WithScope(ctx, connectors.Scope{OrgID: c.orgID}), id)
}
func (c orgCredentials) BearerCredentialName(ctx context.Context, id uuid.UUID) (string, bool, error) {
return c.conns.BearerCredentialName(connectors.WithScope(ctx, connectors.Scope{OrgID: c.orgID}), id)
}
func (c orgCredentials) BearerCredentialNames(ctx context.Context) (map[uuid.UUID]string, error) {
return c.conns.BearerCredentialNames(connectors.WithScope(ctx, connectors.Scope{OrgID: c.orgID}))
}
// answers wakes whatever asked for an approval: a chat turn, or else the run
// waiting on it.
type answers struct {
chat *chat.Module
runs *runs.Engine
}
func (a answers) Signal(ctx context.Context, id uuid.UUID, key string, payload jsontext.Value) error {
if ours, err := a.chat.Signal(ctx, id, key, payload); err != nil || ours {
return err
} }
return nil return a.runs.Signal(ctx, id, key, payload)
}
// work runs each loop until ctx ends and returns a function that waits for
// them all.
func work(ctx context.Context, loops ...func(context.Context)) func() {
var workers sync.WaitGroup
for _, loop := range loops {
workers.Go(func() { loop(ctx) })
}
return workers.Wait
} }
// newJudgement returns the judgement module with its hard rules, data guards // newJudgement returns the judgement module with its hard rules, data guards
// and change-request rules. A failed action tightens its class. // and change-request rules. A failed action tightens its action type.
func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, classes *judgement.Classes, policies *judgement.Policies, settings *governance.Module, heard judgement.Events) *judgement.Module { func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, actionTypes *judgement.ActionTypes, policies *judgement.Policies, settings *governance.Module, heard judgement.Events) *judgement.Module {
guards := []judgement.Guard{ guards := []judgement.Guard{
judgement.Impact{Lookup: judgement.RecordedFacts{Source: conns, People: settings}, Defaults: settings}, judgement.Impact{Lookup: judgement.RecordedFacts{Source: conns, Accounts: settings}, Defaults: settings},
judgement.Reversibility{}, judgement.Reversibility{},
judgement.Precedent{Classes: classes}, judgement.Precedent{ActionTypes: actionTypes},
judgement.Provenance{Events: heard}, judgement.Provenance{Events: heard},
judgement.Timing{Calendar: settings}, judgement.Timing{Calendar: settings},
judgement.Cost{Budgets: settings, Counts: judgement.NewSpend(db, orgID)}, judgement.Cost{Budgets: settings, Counts: judgement.NewSpend(db, orgID)},
judgement.Freeze{Freezes: settings}, judgement.Freeze{Freezes: settings},
} }
judge := judgement.NewModule(db, log.With("module", "judgement"), orgID, conns, []judgement.HardRule{policies}, guards, classes) judge := judgement.NewModule(db, log.With("module", "judgement"), orgID, conns, []judgement.HardRule{policies}, guards, actionTypes)
judge.UseExtensions(conns) judge.UseExtensions(conns)
judge.UseChangeRules(policies) judge.UseChangeRules(policies)
return judge return judge
@@ -169,7 +298,7 @@ func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, class
const orgID = "default" const orgID = "default"
// schemas are the module schemas the runtime role is granted DML on. // schemas are the module schemas the runtime role is granted DML on.
var schemas = []string{"runs", "connectors", "events", "governance", "deliveries", "judgement", "approvals", "memory", "drafts"} var schemas = []string{"runs", "connectors", "events", "governance", "deliveries", "judgement", "approvals", "memory", "alerts", "proposals", "chat"}
// owner names this process in run leases. // owner names this process in run leases.
func owner() string { func owner() string {
+2 -2
View File
@@ -837,7 +837,7 @@ func (b *boot) addCleanup(fn func()) {
func (b *boot) catalogState() modelcatalog.Snapshot { return b.catalog.State() } func (b *boot) catalogState() modelcatalog.Snapshot { return b.catalog.State() }
// loadCatalog layers the model catalog under the file config. A catalog that // loadCatalog layers the model catalogue under the file config. A catalogue that
// cannot be read leaves the configured providers and models in effect. // cannot be read leaves the configured providers and models in effect.
func (b *boot) loadCatalog(ctx context.Context) { func (b *boot) loadCatalog(ctx context.Context) {
snapshot, err := b.catalog.Fetch(ctx, b.secrets.Getenv, b.cfgHolder.Get().Providers) snapshot, err := b.catalog.Fetch(ctx, b.secrets.Getenv, b.cfgHolder.Get().Providers)
@@ -846,7 +846,7 @@ func (b *boot) loadCatalog(ctx context.Context) {
return return
} }
models := modelcatalog.Apply(&b.cfg, snapshot) models := modelcatalog.Apply(&b.cfg, snapshot)
// Layer the catalog over the live config, not b.cfg: b.cfg predates the // Layer the catalogue over the live config, not b.cfg: b.cfg predates the
// execution-settings watch, so publishing it would put the file's budgets // execution-settings watch, so publishing it would put the file's budgets
// back over the control plane's. // back over the control plane's.
live := b.cfgHolder.Get().Clone() live := b.cfgHolder.Get().Clone()
+4 -4
View File
@@ -47,10 +47,10 @@ func (b *boot) loadRuntimeConfig(ctx context.Context) error {
// cannot answer aborts the reload: the running config already holds those // cannot answer aborts the reload: the running config already holds those
// values, so publishing the file's over them is the worse outcome. // values, so publishing the file's over them is the worse outcome.
func (b *boot) reloadConfig(ctx context.Context, doc *configuration.Document) error { func (b *boot) reloadConfig(ctx context.Context, doc *configuration.Document) error {
// Boot merges catalog-discovered providers into cfg before the // Boot merges catalogue-discovered providers into cfg before the
// Holders are seeded; publishing the raw reloaded document would // Holders are seeded; publishing the raw reloaded document would
// drop them from the running config even though the file is // drop them from the running config even though the file is
// unchanged. Re-apply the same merge (idempotent: a catalog that // unchanged. Re-apply the same merge (idempotent: a catalogue that
// failed to load merges to identity). // failed to load merges to identity).
catalog := b.catalogState() catalog := b.catalogState()
modelcatalog.Apply(&doc.Config, catalog) modelcatalog.Apply(&doc.Config, catalog)
@@ -376,8 +376,8 @@ func (b *boot) applyRuntimeResourceUpdate(ctx context.Context, kind string, upda
} }
} }
base := b.cfgHolder.Get() base := b.cfgHolder.Get()
// Boot publishes before the model catalog is merged in, so the snapshot // Boot publishes before the model catalogue is merged in, so the snapshot
// this read returns can lack the catalog's model limits and discovered // this read returns can lack the catalogue's model limits and discovered
// providers. The merge is idempotent, and reloadConfig re-applies it // providers. The merge is idempotent, and reloadConfig re-applies it
// before layering for the same reason. // before layering for the same reason.
catalog := b.catalogState() catalog := b.catalogState()
+1 -1
View File
@@ -194,7 +194,7 @@ func Run() int { //nolint:cyclop,funlen // the composition root's setup sequence
go presence.Run(ctx, b.processName, servicekit.Build(), ps, b.healthRegistry, b.log) go presence.Run(ctx, b.processName, servicekit.Build(), ps, b.healthRegistry, b.log)
b.reportBrokerPresence(ctx, ps) b.reportBrokerPresence(ctx, ps)
} }
// The daemon publishes the configuration view, which carries the catalog's // The daemon publishes the configuration view, which carries the catalogue's
// model limits. // model limits.
b.startModelCatalogRefresh(ctx) b.startModelCatalogRefresh(ctx)
b.buildWorktreeManager() b.buildWorktreeManager()
@@ -65,7 +65,7 @@ func TestOpenShellModelEgressHoldsKeysOnTheGateway(t *testing.T) {
wantKeys map[string]string // key env -> real key held on the gateway wantKeys map[string]string // key env -> real key held on the gateway
wantHosts []string wantHosts []string
wantPorts []int // defaults to 443 for each host wantPorts []int // defaults to 443 for each host
wantHeader string // header the profile places the key in; empty means a bearer token wantHeader string // header that carries the key; empty means a bearer token
}{ }{
{ {
name: "secret reference", name: "secret reference",
+2 -1
View File
@@ -9,6 +9,7 @@ import (
"os" "os"
"os/signal" "os/signal"
"path/filepath" "path/filepath"
"strings"
"syscall" "syscall"
configtemplate "github.com/samcharles93/archie-core" configtemplate "github.com/samcharles93/archie-core"
@@ -76,7 +77,7 @@ func bindSetupFlags(fs *flag.FlagSet) *setupFlags {
fs.StringVar(&f.operator, "operator", "", "operator display name (optional)") fs.StringVar(&f.operator, "operator", "", "operator display name (optional)")
fs.StringVar(&f.forgeType, "forge-type", "", "forge type: github | gitea | none") fs.StringVar(&f.forgeType, "forge-type", "", "forge type: github | gitea | none")
fs.StringVar(&f.forgeHost, "forge-host", "", "forge base URL") fs.StringVar(&f.forgeHost, "forge-host", "", "forge base URL")
fs.StringVar(&f.provider, "provider", "", "LLM provider class: openai | anthropic | openrouter | gemini | groq | deepseek | mistral | ollama") fs.StringVar(&f.provider, "provider", "", "LLM provider: "+strings.Join(setup.ProviderNames(), " | "))
fs.StringVar(&f.model, "model", "", "bare model name; the provider class prefix is added automatically") fs.StringVar(&f.model, "model", "", "bare model name; the provider class prefix is added automatically")
fs.StringVar(&f.telegramUserIDs, "telegram-user-ids", "", "comma-separated allowed Telegram user IDs; configuring Telegram requires at least one") fs.StringVar(&f.telegramUserIDs, "telegram-user-ids", "", "comma-separated allowed Telegram user IDs; configuring Telegram requires at least one")
// References, not values: engine:key names where a secret already lives, and // References, not values: engine:key names where a secret already lives, and
+1 -1
View File
@@ -31,7 +31,7 @@ func stepVocabulary() (*workflow.Manager, error) { return workflowsteps.NewManag
// (main.go's Run) before buildDaemon captures the client. // (main.go's Run) before buildDaemon captures the client.
// //
// It is deliberately not part of openStateStoreAdapter, which the gateway root // It is deliberately not part of openStateStoreAdapter, which the gateway root
// shares: the gateway reads catalog, runtime settings and SOUL, never a // shares: the gateway reads catalogue, runtime settings and SOUL, never a
// workflow definition, so registering a vocabulary there would be the dead // workflow definition, so registering a vocabulary there would be the dead
// vocabulary this shape removed from internal/app/archiemessaging -- a root that // vocabulary this shape removed from internal/app/archiemessaging -- a root that
// cannot consume it must not be failed by it. // cannot consume it must not be failed by it.
+8 -1
View File
@@ -72,8 +72,15 @@ func (d stateDatabase) Backup(ctx context.Context, out string) error {
return err return err
} }
// Restore puts the pre-update snapshot back. Rollback is set because this is the
// update transaction rolling itself back: the snapshot is this host's own dump
// from minutes earlier, so the deletions that must be applied to it are read from
// the difference between it and the live data. An operator restoring by hand goes
// through the command, which does not set it.
func (d stateDatabase) Restore(ctx context.Context, from string) error { func (d stateDatabase) Restore(ctx context.Context, from string) error {
_, err := statestore.RunRecovery(ctx, statestore.RecoveryOptions{Operation: statestore.RecoveryRestore, From: from, Config: d.configPath}) _, err := statestore.RunRecovery(ctx, statestore.RecoveryOptions{
Operation: statestore.RecoveryRestore, From: from, Config: d.configPath, Rollback: true,
})
return err return err
} }
+3 -3
View File
@@ -14,7 +14,7 @@ import (
) )
// chatModelManager owns the model selection for interactive chat. Named // chatModelManager owns the model selection for interactive chat. Named
// aliases remain defaults; choosing a catalog model does not rewrite them // aliases remain defaults; choosing a catalogue model does not rewrite them
// or affect workflow steps. // or affect workflow steps.
type chatModelManager struct { type chatModelManager struct {
mu sync.RWMutex mu sync.RWMutex
@@ -43,7 +43,7 @@ func (m *chatModelManager) SetConfigured(aliases map[string]string) {
} }
// SetModelCatalog replaces the provider display names and per-model details // SetModelCatalog replaces the provider display names and per-model details
// the catalog publishes. // the catalogue publishes.
func (m *chatModelManager) SetModelCatalog(snapshot modelcatalog.Snapshot) { func (m *chatModelManager) SetModelCatalog(snapshot modelcatalog.Snapshot) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
@@ -174,7 +174,7 @@ func (m *chatModelManager) ModelFor(ctx context.Context) (string, error) {
} }
// refsLocked keeps tenant choices within their assigned aliases; the system // refsLocked keeps tenant choices within their assigned aliases; the system
// org can also select from its credential-filtered provider catalog. // org can also select from its credential-filtered provider catalogue.
func (m *chatModelManager) refsLocked(id org.OrgID, aliases map[string]string) []string { func (m *chatModelManager) refsLocked(id org.OrgID, aliases map[string]string) []string {
if id != org.DefaultOrgID { if id != org.DefaultOrgID {
return chatModelRefs(aliases, nil) return chatModelRefs(aliases, nil)
@@ -200,7 +200,7 @@ func (m *preparedChatTurnModel) Generate(
// This is one provider response's output allowance, not a turn- // This is one provider response's output allowance, not a turn-
// continuation budget. Tool loops remain free to continue. The ai-sdk // continuation budget. Tool loops remain free to continue. The ai-sdk
// runtime picks max_completion_tokens or max_tokens from the model's // runtime picks max_completion_tokens or max_tokens from the model's
// catalog metadata. // catalogue metadata.
options.MaxTokens = request.MaxOutputTokens options.MaxTokens = request.MaxOutputTokens
// A runtime swapped to nil -- a live update that left no usable provider // A runtime swapped to nil -- a live update that left no usable provider
// configured -- is a refused turn, not a panic. // configured -- is a refused turn, not a panic.
+1 -1
View File
@@ -93,7 +93,7 @@ func (s curatorEventSink) Emit(kind, detail string, data map[string]any) {
// actingPrincipal resolves the identity the instance acts as for automated // actingPrincipal resolves the identity the instance acts as for automated
// work (the default chat identity, falling back to the bot user), so curator // work (the default chat identity, falling back to the bot user), so curator
// passes authorize guarded tools exactly as that identity would. // passes authorise guarded tools exactly as that identity would.
func (b *server) actingPrincipal(ctx context.Context) (access.Principal, error) { func (b *server) actingPrincipal(ctx context.Context) (access.Principal, error) {
name := b.defaultChatIdentity name := b.defaultChatIdentity
if name == "" { if name == "" {
+1 -1
View File
@@ -260,7 +260,7 @@ func (b *server) waitForNATSEndpoint(ctx context.Context) (servicekit.NATSEndpoi
func (b *server) catalogState() modelcatalog.Snapshot { return b.catalog.State() } func (b *server) catalogState() modelcatalog.Snapshot { return b.catalog.State() }
// loadCatalog layers the model catalog under the running config. A catalog // loadCatalog layers the model catalogue under the running config. A catalogue
// that cannot be read leaves the configured providers and models in effect. // that cannot be read leaves the configured providers and models in effect.
func (b *server) loadCatalog(ctx context.Context) { func (b *server) loadCatalog(ctx context.Context) {
snapshot, err := b.catalog.Fetch(ctx, b.secrets.Getenv, b.cfg.Providers) snapshot, err := b.catalog.Fetch(ctx, b.secrets.Getenv, b.cfg.Providers)
+1 -1
View File
@@ -70,7 +70,7 @@ func (b *server) refreshSkills(ctx context.Context, applied *string) {
} }
// storedSkills reads the skills resource, leaving out any name already in // storedSkills reads the skills resource, leaving out any name already in
// have. An unreadable resource leaves the running catalog in place. // have. An unreadable resource leaves the running catalogue in place.
func (b *server) storedSkills(ctx context.Context, have []skill.CatalogEntry) ([]skill.CatalogEntry, int64, error) { func (b *server) storedSkills(ctx context.Context, have []skill.CatalogEntry) ([]skill.CatalogEntry, int64, error) {
var out []skill.CatalogEntry var out []skill.CatalogEntry
version, _, err := b.controlPlane.Query(ctx, controlplanestore.SkillsKind, func(value []byte) error { version, _, err := b.controlPlane.Query(ctx, controlplanestore.SkillsKind, func(value []byte) error {
+1 -1
View File
@@ -27,7 +27,7 @@ type ServiceTarget struct {
// Options is the UI-owned input DTO. It carries process-local settings and // Options is the UI-owned input DTO. It carries process-local settings and
// endpoint references only -- there is deliberately no config.Config, // endpoint references only -- there is deliberately no config.Config,
// config.Holder, forge credential, model catalog or workflow routing field // config.Holder, forge credential, model catalogue or workflow routing field
// for daemon configuration to arrive through. // for daemon configuration to arrive through.
type Options struct { type Options struct {
// Config and Overlay name the configuration source the process reads a // Config and Overlay name the configuration source the process reads a
+1 -1
View File
@@ -63,7 +63,7 @@ const controlPlaneWatchHealthyMultiple = 2
// deliberately: that version is unusable to this build, and resuming before it // deliberately: that version is unusable to this build, and resuming before it
// would re-offer it on every reconnect for the life of the process. Only a // would re-offer it on every reconnect for the life of the process. Only a
// cancellation stops the loop, and the loop watches for it itself, so shutdown // cancellation stops the loop, and the loop watches for it itself, so shutdown
// is prompt however long the current backoff is and whether or not the stream // is prompt however long the current backoff is and whether the stream
// is still open. // is still open.
// //
// The reconnect delay is decided by the attempt that just ended, and only by // The reconnect delay is decided by the attempt that just ended, and only by
+11
View File
@@ -69,6 +69,17 @@ type RecoveryOptions struct {
// Revision is the revision rollback replays. Zero means the newest // Revision is the revision rollback replays. Zero means the newest
// revision older than the one the resource carries now. // revision older than the one the resource carries now.
Revision int64 Revision int64
// AcceptUnrecordedDeletions acknowledges that a restore may not account for
// every deletion this data has seen, so forgotten notes may return. It is
// only ever set by an operator asking for it, never by an automatic update.
AcceptUnrecordedDeletions bool
// Rollback marks the update transaction's own rollback, where the snapshot is
// this host's pre-update dump taken minutes earlier, and the deletions the
// restore has to apply are read from the difference between the snapshot and
// the data it replaces rather than from the witness table. Only the updater
// sets it: no command exposes it, and it is not an acknowledgement of
// anything.
Rollback bool
} }
// RunRecovery performs one offline operation on the task database and // RunRecovery performs one offline operation on the task database and
+318 -7
View File
@@ -2,12 +2,26 @@ package statestore
import ( import (
"context" "context"
"crypto/sha256"
"encoding/hex"
json "encoding/json/v2"
"errors" "errors"
"fmt" "fmt"
"io"
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/pgx/v5/stdlib"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres" "github.com/samcharles93/archie-core/internal/infrastructure/postgres"
"github.com/samcharles93/archie-core/internal/platform/deletions"
"github.com/samcharles93/archie-core/modules/memory"
) )
// runPostgresRecovery performs one recovery operation on the PostgreSQL // runPostgresRecovery performs one recovery operation on the PostgreSQL
@@ -36,13 +50,7 @@ func runPostgresRecovery(ctx context.Context, options RecoveryOptions) (string,
} }
return "backed up the whole database to " + options.Out, nil return "backed up the whole database to " + options.Out, nil
case RecoveryRestore: case RecoveryRestore:
if options.From == "" { return restorePostgres(ctx, url, options, cfg.StateDir)
return "", errors.New("restore requires -from")
}
if err := postgres.Restore(ctx, url, options.From); err != nil {
return "", err
}
return fmt.Sprintf("restored the whole database from %s; every write made after the snapshot is gone; start the archie services again", options.From), nil
case RecoveryValidate: case RecoveryValidate:
return validatePostgres(ctx, url, options) return validatePostgres(ctx, url, options)
case RecoveryRollback: case RecoveryRollback:
@@ -55,6 +63,309 @@ func runPostgresRecovery(ctx context.Context, options RecoveryOptions) (string,
} }
} }
// restorePostgres replaces the database with the snapshot, refusing first when the
// data cannot show the restore is safe.
func restorePostgres(ctx context.Context, url string, options RecoveryOptions, stateDir string) (string, error) {
if options.From == "" {
return "", errors.New("restore requires -from")
}
dir, err := deletions.Dir(stateDir)
if err != nil {
return "", err
}
// One reading of the record inside the restore's window serves both the check
// and the replay, so what was proved safe is what is applied.
var recorded []memory.NoteKey
if err := postgres.Restore(ctx, url, options.From,
func(ctx context.Context, pool *pgxpool.Pool) error {
var err error
if recorded, err = memory.RecordedNotes(dir); err != nil {
return err
}
if options.Rollback {
return requireRollbackReplaysDeletions(ctx, pool, options.From, recorded)
}
return requireAccountedDeletions(ctx, pool, options.From, recorded, dir, options.AcceptUnrecordedDeletions)
},
func() (string, error) { return memory.DeletionStatements(recorded), nil }); err != nil {
return "", err
}
return fmt.Sprintf("restored the whole database from %s; every write made after the snapshot is gone, and %d recorded deletions were applied again; start the archie services again",
options.From, len(recorded)), nil
}
// fileDigest hashes a file without reading it into memory: snapshots of a real
// instance are far larger than a process should hold to checksum one.
func fileDigest(path string) (string, error) {
file, err := os.Open(path) //nolint:gosec // the snapshot the operator named.
if err != nil {
return "", fmt.Errorf("read the snapshot: %w", err)
}
defer func() { _ = file.Close() }()
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return "", fmt.Errorf("read the snapshot: %w", err)
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
// requireAccountedDeletions refuses a restore the record outside the database
// cannot account for, and refuses by default when it cannot say whether the data
// has seen deletions it does not know about. Freshness cannot be proved from this
// data alone: a snapshot and the record from the same backup match perfectly while
// later deletions are absent from both, so an operator's acknowledgement is the
// only way past a case where accounting is incomplete. It runs before anything is
// replaced.
func requireAccountedDeletions(ctx context.Context, pool *pgxpool.Pool, from string, recorded []memory.NoteKey, dir string, accepted bool) error {
facts, err := gatherRestoreFacts(ctx, pool, from, recorded, dir)
if err != nil {
return err
}
if accepted {
return acknowledge(ctx, from, dir, len(facts.unaccounted))
}
return refuseUnaccounted(facts, from, deletions.Path(dir))
}
// restoreFacts is what the check can learn before anything is replaced: what the
// target and the snapshot witnessed, whether the record outside the database is
// still there, and which witnesses it does not list.
type restoreFacts struct {
live []memory.Witness
snapshot []memory.Witness
ledgerExists bool
unaccounted []memory.Witness
}
// gatherRestoreFacts reads the witnesses from the target database and the
// snapshot, and compares them with the record outside the database.
func gatherRestoreFacts(ctx context.Context, pool *pgxpool.Pool, from string, recorded []memory.NoteKey, dir string) (restoreFacts, error) {
db := sqlx.NewDb(stdlib.OpenDBFromPool(pool), "pgx")
var facts restoreFacts
records, err := memory.HasWitnessTable(ctx, db)
if err != nil {
return restoreFacts{}, err
}
// A database that has never recorded a deletion has no witness table to read.
if records {
if facts.live, err = memory.Witnesses(ctx, db); err != nil {
return restoreFacts{}, fmt.Errorf("read the committed deletions: %w", err)
}
}
if facts.snapshot, _, err = snapshotWitnesses(ctx, from); err != nil {
return restoreFacts{}, err
}
facts.unaccounted = memory.Unaccounted(slices.Concat(facts.live, facts.snapshot), recorded)
if facts.ledgerExists, err = deletions.NewLog(deletions.Path(dir)).Exists(); err != nil {
return restoreFacts{}, err
}
return facts, nil
}
// refuseUnaccounted refuses a restore the record outside the database cannot
// account for. Nothing it reads can prove the record is current, so every doubt
// it cannot settle is a refusal, and an operator's acknowledgement is the one way
// past one.
func refuseUnaccounted(facts restoreFacts, from, recordPath string) error {
// With no record there is nothing to compare, and every deletion this
// instance ever made is unaccounted for.
if !facts.ledgerExists {
return fmt.Errorf("%w: the record outside the database, %s, is missing, so nothing here can show what this data has deleted. Restore the current record, or pass -accept-unrecorded-deletions to accept that forgotten notes may return",
ErrUnaccountedDeletions, recordPath)
}
// The target's own witnesses are the only evidence here about this data's
// history that does not come from the snapshot. With none, nothing can show
// what was deleted after the snapshot was taken: a fresh target and a target
// that has genuinely never deleted a note look the same, so the operator has
// to say which it is.
if len(facts.live) == 0 {
return fmt.Errorf("%w: this database has not recorded a deletion of its own, so nothing here can show what was deleted after %s was taken, and forgotten notes may return. Restore the record that belongs with the snapshot, or pass -accept-unrecorded-deletions to accept that risk",
ErrUnaccountedDeletions, from)
}
if len(facts.unaccounted) > 0 {
return fmt.Errorf("%w: the record outside the database does not list %d deletion(s) this data has seen, so a restore would bring forgotten notes back. Restore the current record, or pass -accept-unrecorded-deletions to accept that risk",
ErrUnaccountedDeletions, len(facts.unaccounted))
}
return nil
}
// rollbackFacts is what the update transaction's rollback compares: the notes its
// own snapshot holds, the notes the database holds now, and the deletions the
// record lists.
type rollbackFacts struct {
snapshotHasNotes bool
snapshot []memory.NoteKey
live []memory.NoteKey
recorded []memory.NoteKey
}
// requireRollbackReplaysDeletions proves a rollback safe from the data alone. The
// snapshot was taken by this host minutes earlier, so every note it holds and the
// database no longer has was deleted since, and applying those deletions to the
// snapshot is exactly what stops the rollback bringing them back. That proof does
// not rest on the witness table, which a migration may have emptied, so it holds
// with no witnesses at all; what it does need is every one of those deletions in
// the record, because the record is what the restore replays.
func requireRollbackReplaysDeletions(ctx context.Context, pool *pgxpool.Pool, from string, recorded []memory.NoteKey) error {
db := sqlx.NewDb(stdlib.OpenDBFromPool(pool), "pgx")
facts := rollbackFacts{recorded: recorded}
var err error
if facts.snapshotHasNotes, err = postgres.SnapshotHasTable(ctx, from, "memory.notes"); err != nil {
return err
}
if facts.snapshotHasNotes {
if facts.snapshot, err = snapshotNoteKeys(ctx, from); err != nil {
return err
}
}
if facts.live, err = memory.LiveNoteKeys(ctx, db); err != nil {
return err
}
return refuseUnsafeRollback(facts, from)
}
// refuseUnsafeRollback refuses a rollback the data cannot show to be safe.
func refuseUnsafeRollback(facts rollbackFacts, from string) error {
// A snapshot from before the notes table existed would replace a database that
// has notes with one that has none, and holds nothing to compare.
if !facts.snapshotHasNotes {
if len(facts.live) > 0 {
return fmt.Errorf("%w: %s holds no notes table and this database holds %d note(s), so the rollback would drop them with nothing to show what it did",
deletions.ErrUnsafeRollback, from, len(facts.live))
}
return nil
}
live := make(map[memory.NoteKey]bool, len(facts.live))
for _, key := range facts.live {
live[key] = true
}
recorded := make(map[memory.NoteKey]bool, len(facts.recorded))
for _, key := range facts.recorded {
recorded[key] = true
}
unrecorded := 0
for _, key := range facts.snapshot {
if live[key] || recorded[key] {
continue
}
unrecorded++
}
if unrecorded > 0 {
return fmt.Errorf("%w: %s holds %d note(s) this database no longer has and the record does not list, so a rollback would bring them back",
deletions.ErrUnsafeRollback, from, unrecorded)
}
return nil
}
// snapshotNoteKeys reads the notes an archive holds. Only the two columns a note
// is identified by are read, so a snapshot from before the memory schema was
// scoped can still be compared.
func snapshotNoteKeys(ctx context.Context, from string) ([]memory.NoteKey, error) {
columns, rows, err := postgres.SnapshotRows(ctx, from, "memory.notes")
if err != nil {
return nil, err
}
idAt, ok := postgres.Column(columns, "id")
if !ok {
return nil, fmt.Errorf("postgres: snapshot %s: the notes table has no id", from)
}
orgAt, ok := postgres.Column(columns, "org_id")
if !ok {
return nil, fmt.Errorf("postgres: snapshot %s: the notes table has no organisation", from)
}
out := make([]memory.NoteKey, 0, len(rows))
for _, row := range rows {
if len(row) <= max(idAt, orgAt) {
return nil, fmt.Errorf("postgres: snapshot %s: a note is missing a column", from)
}
id, err := uuid.Parse(strings.TrimSpace(row[idAt]))
if err != nil {
return nil, fmt.Errorf("postgres: snapshot %s: read a note: %w", from, err)
}
out = append(out, memory.NoteKey{OrgID: strings.TrimSpace(row[orgAt]), ID: id})
}
return out, nil
}
// acknowledge records that an operator chose to restore data the record cannot
// account for. The acknowledgement is written beside the record rather than
// instead of anything, so the evidence of what was lost survives.
func acknowledge(ctx context.Context, from, dir string, unaccounted int) error {
digest, err := fileDigest(from)
if err != nil {
return err
}
line, err := json.Marshal(map[string]any{
"acknowledged_at": time.Now().UTC(),
"snapshot": filepath.Base(from),
"snapshot_sha256": digest,
"unaccounted_deletions": unaccounted,
"consequence": "forgotten notes may return",
})
if err != nil {
return err
}
path := filepath.Join(dir, "deletions-acknowledged.jsonl")
if err := os.MkdirAll(dir, 0o700); err != nil {
return fmt.Errorf("record the acknowledgement: %w", err)
}
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) //nolint:gosec // the state directory.
if err != nil {
return fmt.Errorf("record the acknowledgement: %w", err)
}
defer func() { _ = file.Close() }()
if _, err := file.Write(append(line, '\n')); err != nil {
return fmt.Errorf("record the acknowledgement: %w", err)
}
if err := file.Sync(); err != nil {
return fmt.Errorf("record the acknowledgement: %w", err)
}
// The acknowledgement is evidence, so its name and the directory holding it
// have to be as durable as the line itself.
return deletions.SyncFileDirs(path)
}
// ErrUnaccountedDeletions is returned when a restore cannot account for deletions
// the data has seen.
var ErrUnaccountedDeletions = errors.New("the record of deletions does not account for this data")
// snapshotWitnesses reads the deletions a snapshot's own database witnessed. A
// snapshot from before the witness existed reports false: it never recorded any.
func snapshotWitnesses(ctx context.Context, from string) ([]memory.Witness, bool, error) {
const table = "memory.deletion_witness"
holds, err := postgres.SnapshotHasTable(ctx, from, table)
if err != nil {
return nil, false, err
}
if !holds {
return nil, false, nil
}
columns, rows, err := postgres.SnapshotRows(ctx, from, table)
if err != nil {
return nil, false, err
}
noteAt, ok := postgres.Column(columns, "note_id")
if !ok {
return nil, false, fmt.Errorf("postgres: snapshot %s: the deletion witness has no note id", from)
}
orgAt, ok := postgres.Column(columns, "org_id")
if !ok {
return nil, false, fmt.Errorf("postgres: snapshot %s: the deletion witness has no organisation", from)
}
out := make([]memory.Witness, 0, len(rows))
for _, row := range rows {
if len(row) <= max(noteAt, orgAt) {
return nil, false, fmt.Errorf("postgres: snapshot %s: a deletion witness is missing a column", from)
}
id, err := uuid.Parse(strings.TrimSpace(row[noteAt]))
if err != nil {
return nil, false, fmt.Errorf("postgres: snapshot %s: read a deletion witness: %w", from, err)
}
out = append(out, memory.Witness{NoteID: id, OrgID: strings.TrimSpace(row[orgAt])})
}
return out, true, nil
}
// openRecoveryPool opens the database without migrating it: recovery inspects // openRecoveryPool opens the database without migrating it: recovery inspects
// or repairs the schema it finds, and refuses one newer than this binary. // or repairs the schema it finds, and refuses one newer than this binary.
func openRecoveryPool(ctx context.Context, url string) (*pgxpool.Pool, int64, error) { func openRecoveryPool(ctx context.Context, url string) (*pgxpool.Pool, int64, error) {
@@ -0,0 +1,197 @@
package statestore
import (
json "encoding/json/v2"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/platform/deletions"
"github.com/samcharles93/archie-core/modules/memory"
)
// TestRestoreRefusesAnIncompleteRecord guards the privacy boundary a restore
// crosses: the record outside the database is the only thing that stops a
// snapshot bringing back a note deleted after it was taken, so a restore refuses
// unless that record is there and lists every deletion the data has seen.
func TestRestoreRefusesAnIncompleteRecord(t *testing.T) {
note := uuid.New()
other := uuid.New()
record := filepath.Join("/state", "archie", deletions.File)
cases := []struct {
name string
facts restoreFacts
want string
}{
{
name: "the record is missing",
facts: restoreFacts{live: []memory.Witness{{NoteID: note, OrgID: "default"}}},
want: "is missing",
},
{
name: "a fresh target cannot show what was deleted after the snapshot",
facts: restoreFacts{ledgerExists: true},
want: "has not recorded a deletion of its own",
},
{
name: "the record lists fewer deletions than the data has seen",
facts: restoreFacts{
ledgerExists: true,
live: []memory.Witness{{NoteID: note, OrgID: "default"}},
unaccounted: []memory.Witness{{NoteID: other, OrgID: "default"}},
},
want: "does not list 1 deletion(s)",
},
{
name: "the record accounts for every deletion",
facts: restoreFacts{
ledgerExists: true,
live: []memory.Witness{{NoteID: note, OrgID: "default"}},
},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := refuseUnaccounted(tc.facts, "/backups/snapshot.dump", record)
if tc.want == "" {
if err != nil {
t.Fatalf("refused a complete record: %v", err)
}
return
}
if !errors.Is(err, ErrUnaccountedDeletions) {
t.Fatalf("err = %v, want an unaccounted deletion", err)
}
if !strings.Contains(err.Error(), tc.want) {
t.Fatalf("err = %q, want it to say %q", err, tc.want)
}
})
}
}
// TestAcknowledgedRestoreIsRecorded guards the one way past an incomplete
// record: the acknowledgement is written beside the record, naming the snapshot
// it covers and how many deletions went unaccounted, so what was lost can be
// read afterwards.
func TestAcknowledgedRestoreIsRecorded(t *testing.T) {
dir := t.TempDir()
snapshot := filepath.Join(dir, "snapshot.dump")
if err := os.WriteFile(snapshot, []byte("an archive"), 0o600); err != nil {
t.Fatal(err)
}
state := filepath.Join(dir, "state")
if err := acknowledge(t.Context(), snapshot, state, 2); err != nil {
t.Fatal(err)
}
raw, err := os.ReadFile(filepath.Join(state, "deletions-acknowledged.jsonl")) //nolint:gosec // the acknowledgement this test just wrote.
if err != nil {
t.Fatal(err)
}
var got struct {
Snapshot string `json:"snapshot"`
Digest string `json:"snapshot_sha256"`
UnaccountedDeletions int `json:"unaccounted_deletions"`
}
if err := json.Unmarshal(raw, &got); err != nil {
t.Fatalf("the acknowledgement is not one JSON line: %v", err)
}
if got.Snapshot != "snapshot.dump" {
t.Fatalf("snapshot = %q, want the file the restore read", got.Snapshot)
}
if got.Digest == "" {
t.Fatal("the acknowledgement does not name the snapshot's digest")
}
if got.UnaccountedDeletions != 2 {
t.Fatalf("unaccounted deletions = %d, want 2", got.UnaccountedDeletions)
}
}
// TestRollbackIsProvedFromTheData guards the update transaction's own rollback:
// the snapshot is this host's dump from minutes earlier, so a note it holds and
// the database no longer has was deleted since, and the rollback is safe exactly
// when the record lists every one of those notes. The witness table is not
// consulted, so a migration that emptied it does not make a safe rollback refuse.
func TestRollbackIsProvedFromTheData(t *testing.T) {
kept, deleted, other := uuid.New(), uuid.New(), uuid.New()
cases := []struct {
name string
facts rollbackFacts
want string
}{
{
name: "nothing was deleted since the snapshot",
facts: rollbackFacts{
snapshotHasNotes: true,
snapshot: []memory.NoteKey{{OrgID: "default", ID: kept}},
live: []memory.NoteKey{{OrgID: "default", ID: kept}},
},
},
{
name: "the record lists the note the snapshot would bring back",
facts: rollbackFacts{
snapshotHasNotes: true,
snapshot: []memory.NoteKey{{OrgID: "default", ID: kept}, {OrgID: "default", ID: deleted}},
live: []memory.NoteKey{{OrgID: "default", ID: kept}},
recorded: []memory.NoteKey{{OrgID: "default", ID: deleted}},
},
},
{
name: "the record does not list that note",
facts: rollbackFacts{
snapshotHasNotes: true,
snapshot: []memory.NoteKey{{OrgID: "default", ID: kept}, {OrgID: "default", ID: deleted}},
live: []memory.NoteKey{{OrgID: "default", ID: kept}},
},
want: "1 note(s) this database no longer has",
},
{
name: "the note is in the record under another organisation",
facts: rollbackFacts{
snapshotHasNotes: true,
snapshot: []memory.NoteKey{{OrgID: "default", ID: deleted}},
recorded: []memory.NoteKey{{OrgID: "other", ID: deleted}},
},
want: "does not list",
},
{
name: "a snapshot from before the notes table, onto a database with notes",
facts: rollbackFacts{
live: []memory.NoteKey{{OrgID: "default", ID: kept}},
},
want: "holds no notes table",
},
{
name: "a snapshot from before the notes table, onto a database with none",
facts: rollbackFacts{live: nil},
},
{
name: "a note the database still holds is not a deletion",
facts: rollbackFacts{
snapshotHasNotes: true,
snapshot: []memory.NoteKey{{OrgID: "default", ID: kept}, {OrgID: "default", ID: other}},
live: []memory.NoteKey{{OrgID: "default", ID: kept}, {OrgID: "default", ID: other}},
},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := refuseUnsafeRollback(tc.facts, "/backups/snapshot.dump")
if tc.want == "" {
if err != nil {
t.Fatalf("refused a safe rollback: %v", err)
}
return
}
if !errors.Is(err, deletions.ErrUnsafeRollback) {
t.Fatalf("err = %v, want an unsafe rollback", err)
}
if !strings.Contains(err.Error(), tc.want) {
t.Fatalf("err = %q, want it to say %q", err, tc.want)
}
})
}
}
+2 -1
View File
@@ -35,7 +35,8 @@ type Sender interface {
// Reloader is a channel that can re-read its configuration in place. The // Reloader is a channel that can re-read its configuration in place. The
// capability a status report declares and the reload action both derive from // capability a status report declares and the reload action both derive from
// this interface, so a channel cannot advertise one and answer nothing. // the Reloader interface, so a channel cannot advertise one and answer
// nothing.
type Reloader interface { type Reloader interface {
Reload() error Reload() error
} }
+9 -7
View File
@@ -219,7 +219,7 @@ type Budgets struct {
TaskWallClock Duration `toml:"task_wall_clock" json:"task_wall_clock" yaml:"task_wall_clock"` TaskWallClock Duration `toml:"task_wall_clock" json:"task_wall_clock" yaml:"task_wall_clock"`
} }
// Provider configures one LLM provider for the runtime catalog. // Provider configures one LLM provider for the runtime catalogue.
type Provider struct { type Provider struct {
Class string `toml:"class" yaml:"class" json:"class"` Class string `toml:"class" yaml:"class" json:"class"`
APIKeyEnv string `toml:"api_key_env" yaml:"api_key_env" json:"api_key_env"` APIKeyEnv string `toml:"api_key_env" yaml:"api_key_env" json:"api_key_env"`
@@ -228,7 +228,7 @@ type Provider struct {
// Disabled marks a configured provider whose api_key could not be // Disabled marks a configured provider whose api_key could not be
// resolved at boot. It is runtime state, not a setting: without it a // resolved at boot. It is runtime state, not a setting: without it a
// disabled provider is indistinguishable from one the operator never // disabled provider is indistinguishable from one the operator never
// configured, and the model catalog would serve it from an ambient // configured, and the model catalogue would serve it from an ambient
// environment variable. // environment variable.
Disabled bool `toml:"-" yaml:"-" json:"-"` Disabled bool `toml:"-" yaml:"-" json:"-"`
} }
@@ -246,7 +246,7 @@ type Dispatch struct {
// issues), "label" (poll labelled issues), or "either" (both). // issues), "label" (poll labelled issues), or "either" (both).
Trigger string `toml:"trigger" json:"trigger" yaml:"trigger"` Trigger string `toml:"trigger" json:"trigger" yaml:"trigger"`
// AckReaction is the emoji reaction posted on issue pickup. Set // AckReaction is the emoji reaction posted on issue pickup. Set
// ack_reaction = "off" in TOML to disable it; Load normalizes that // ack_reaction = "off" in TOML to disable it; Load normalises that
// sentinel to an empty string for callers. // sentinel to an empty string for callers.
AckReaction string `toml:"ack_reaction" json:"ack_reaction" yaml:"ack_reaction"` AckReaction string `toml:"ack_reaction" json:"ack_reaction" yaml:"ack_reaction"`
} }
@@ -468,7 +468,7 @@ type ModelLimits struct {
ContextWindow int `json:"context_window"` ContextWindow int `json:"context_window"`
MaxOutputTokens int `json:"max_output_tokens"` MaxOutputTokens int `json:"max_output_tokens"`
// Reasoning marks a reasoning-class model. It is derived from the model // Reasoning marks a reasoning-class model. It is derived from the model
// catalog (never operator-authored) and carried to the agent worker so a // catalogue (never operator-authored) and carried to the agent worker so a
// task-scoped MCP sampling request omits the max-token bound those models // task-scoped MCP sampling request omits the max-token bound those models
// reject, exactly as the daemon's chat path does. // reject, exactly as the daemon's chat path does.
Reasoning bool `json:"reasoning,omitempty"` Reasoning bool `json:"reasoning,omitempty"`
@@ -517,7 +517,7 @@ func (c Config) ForTask() TaskConfig {
// aliasedModelLimits keeps the limits of the models an alias can resolve to. // aliasedModelLimits keeps the limits of the models an alias can resolve to.
// Workflows reach a model only through Models, so the rest of the provider // Workflows reach a model only through Models, so the rest of the provider
// catalog would only bloat every attempt's captured configuration. // catalogue would only bloat every attempt's captured configuration.
func (c Config) aliasedModelLimits() map[string]ModelLimits { func (c Config) aliasedModelLimits() map[string]ModelLimits {
var out map[string]ModelLimits var out map[string]ModelLimits
for _, ref := range c.Models { for _, ref := range c.Models {
@@ -734,10 +734,12 @@ type OpenShellConfig struct {
// ContainerConfig configures Docker sandbox execution of archie-agent. // ContainerConfig configures Docker sandbox execution of archie-agent.
type ContainerConfig struct { type ContainerConfig struct {
// Image is the Docker image to run (e.g. "git.catlow.cloud/sam/archie-agent:latest"). // Image is the Docker image task workers run (e.g. "registry.example.com/archie/archie-agent:v1").
// There is no default: validation requires it so a fresh instance is told
// at startup rather than at the first failed pull.
Image string `toml:"image" yaml:"image"` Image string `toml:"image" yaml:"image"`
// MaxConcurrency limits simultaneous daemon tasks and containers. // MaxConcurrency limits simultaneous daemon tasks and containers.
// Tasks from the same repository remain serialized. 0 = no limit. // Tasks from the same repository remain serialised. 0 = no limit.
MaxConcurrency int `toml:"max_concurrency" yaml:"max_concurrency"` MaxConcurrency int `toml:"max_concurrency" yaml:"max_concurrency"`
// MaxUptime caps a container's lifetime before recycling. // MaxUptime caps a container's lifetime before recycling.
MaxUptime Duration `toml:"max_uptime" yaml:"max_uptime"` MaxUptime Duration `toml:"max_uptime" yaml:"max_uptime"`
+212 -55
View File
@@ -281,7 +281,10 @@ type DescribeResponse struct {
// which the dashboard renders as a form. // which the dashboard renders as a form.
Settings []*Setting `protobuf:"bytes,8,rep,name=settings,proto3" json:"settings,omitempty"` Settings []*Setting `protobuf:"bytes,8,rep,name=settings,proto3" json:"settings,omitempty"`
// version is the connector's own release. // version is the connector's own release.
Version string `protobuf:"bytes,9,opt,name=version,proto3" json:"version,omitempty"` Version string `protobuf:"bytes,9,opt,name=version,proto3" json:"version,omitempty"`
// links_accounts says the connector serves LinkURL and emits account.link
// events, so a person can link their channel identity to an account.
LinksAccounts bool `protobuf:"varint,10,opt,name=links_accounts,json=linksAccounts,proto3" json:"links_accounts,omitempty"`
unknownFields protoimpl.UnknownFields unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache sizeCache protoimpl.SizeCache
} }
@@ -379,6 +382,13 @@ func (x *DescribeResponse) GetVersion() string {
return "" return ""
} }
func (x *DescribeResponse) GetLinksAccounts() bool {
if x != nil {
return x.LinksAccounts
}
return false
}
// Setting is one value an operator enters for an extension to run. // Setting is one value an operator enters for an extension to run.
type Setting struct { type Setting struct {
state protoimpl.MessageState `protogen:"open.v1"` state protoimpl.MessageState `protogen:"open.v1"`
@@ -679,10 +689,13 @@ func (x *DeliveryType) GetInputSchema() []byte {
} }
type LookupType struct { type LookupType struct {
state protoimpl.MessageState `protogen:"open.v1"` state protoimpl.MessageState `protogen:"open.v1"`
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"`
InputSchema []byte `protobuf:"bytes,3,opt,name=input_schema,json=inputSchema,proto3" json:"input_schema,omitempty"` InputSchema []byte `protobuf:"bytes,3,opt,name=input_schema,json=inputSchema,proto3" json:"input_schema,omitempty"`
// effect declares the lookup's effects. Only the effects_declared,
// privilege_change and secret_access fields apply to a lookup.
Effect *Effect `protobuf:"bytes,4,opt,name=effect,proto3" json:"effect,omitempty"`
unknownFields protoimpl.UnknownFields unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache sizeCache protoimpl.SizeCache
} }
@@ -738,13 +751,30 @@ func (x *LookupType) GetInputSchema() []byte {
return nil return nil
} }
func (x *LookupType) GetEffect() *Effect {
if x != nil {
return x.Effect
}
return nil
}
type Effect struct { type Effect struct {
state protoimpl.MessageState `protogen:"open.v1"` state protoimpl.MessageState `protogen:"open.v1"`
ReadOnly bool `protobuf:"varint,1,opt,name=read_only,json=readOnly,proto3" json:"read_only,omitempty"` ReadOnly bool `protobuf:"varint,1,opt,name=read_only,json=readOnly,proto3" json:"read_only,omitempty"`
Reversibility Reversibility `protobuf:"varint,2,opt,name=reversibility,proto3,enum=connector.v1.Reversibility" json:"reversibility,omitempty"` Reversibility Reversibility `protobuf:"varint,2,opt,name=reversibility,proto3,enum=connector.v1.Reversibility" json:"reversibility,omitempty"`
// summary says in plain words what the action does, for example "delete // summary says in plain words what the action does, for example "delete
// files older than 24h under /tmp/runner". // files older than 24h under /tmp/runner".
Summary string `protobuf:"bytes,3,opt,name=summary,proto3" json:"summary,omitempty"` Summary string `protobuf:"bytes,3,opt,name=summary,proto3" json:"summary,omitempty"`
// effects_declared says the connector stated this action's privilege_change
// and secret_access explicitly. With it false the two flags mean nothing: an
// action that never stated its effects is prohibited in chat, which is not
// the same as an action that stated it has none.
EffectsDeclared bool `protobuf:"varint,4,opt,name=effects_declared,json=effectsDeclared,proto3" json:"effects_declared,omitempty"`
// privilege_change says the action changes who may do what: it grants
// roles, changes identities or policies, or changes control-plane settings.
PrivilegeChange bool `protobuf:"varint,5,opt,name=privilege_change,json=privilegeChange,proto3" json:"privilege_change,omitempty"`
// secret_access says the action reads, exports or reveals a secret.
SecretAccess bool `protobuf:"varint,6,opt,name=secret_access,json=secretAccess,proto3" json:"secret_access,omitempty"`
unknownFields protoimpl.UnknownFields unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache sizeCache protoimpl.SizeCache
} }
@@ -800,8 +830,29 @@ func (x *Effect) GetSummary() string {
return "" return ""
} }
func (x *Effect) GetEffectsDeclared() bool {
if x != nil {
return x.EffectsDeclared
}
return false
}
func (x *Effect) GetPrivilegeChange() bool {
if x != nil {
return x.PrivilegeChange
}
return false
}
func (x *Effect) GetSecretAccess() bool {
if x != nil {
return x.SecretAccess
}
return false
}
// Target is what an action acts on. Connector, action, kind and environment // Target is what an action acts on. Connector, action, kind and environment
// together are the action class. // together are the action type.
type Target struct { type Target struct {
state protoimpl.MessageState `protogen:"open.v1"` state protoimpl.MessageState `protogen:"open.v1"`
Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"` Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
@@ -1223,7 +1274,7 @@ type InvokeResponse struct {
state protoimpl.MessageState `protogen:"open.v1"` state protoimpl.MessageState `protogen:"open.v1"`
Output []byte `protobuf:"bytes,1,opt,name=output,proto3" json:"output,omitempty"` Output []byte `protobuf:"bytes,1,opt,name=output,proto3" json:"output,omitempty"`
// executed_digest is the connector's digest of what it ran. A mismatch is a // executed_digest is the connector's digest of what it ran. A mismatch is a
// finding and tightens the action class. // finding and tightens the action type.
ExecutedDigest string `protobuf:"bytes,2,opt,name=executed_digest,json=executedDigest,proto3" json:"executed_digest,omitempty"` ExecutedDigest string `protobuf:"bytes,2,opt,name=executed_digest,json=executedDigest,proto3" json:"executed_digest,omitempty"`
// outcome_unknown says the connector can't confirm what its effect did. // outcome_unknown says the connector can't confirm what its effect did.
OutcomeUnknown bool `protobuf:"varint,3,opt,name=outcome_unknown,json=outcomeUnknown,proto3" json:"outcome_unknown,omitempty"` OutcomeUnknown bool `protobuf:"varint,3,opt,name=outcome_unknown,json=outcomeUnknown,proto3" json:"outcome_unknown,omitempty"`
@@ -1705,6 +1756,96 @@ func (x *ListenResponse) GetCursor() string {
return "" return ""
} }
type LinkURLRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// code is the single-use link code the person sends to the connector.
Code string `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *LinkURLRequest) Reset() {
*x = LinkURLRequest{}
mi := &file_connector_v1_connector_proto_msgTypes[26]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *LinkURLRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*LinkURLRequest) ProtoMessage() {}
func (x *LinkURLRequest) ProtoReflect() protoreflect.Message {
mi := &file_connector_v1_connector_proto_msgTypes[26]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use LinkURLRequest.ProtoReflect.Descriptor instead.
func (*LinkURLRequest) Descriptor() ([]byte, []int) {
return file_connector_v1_connector_proto_rawDescGZIP(), []int{26}
}
func (x *LinkURLRequest) GetCode() string {
if x != nil {
return x.Code
}
return ""
}
type LinkURLResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// url opens the connector's channel with the code attached.
Url string `protobuf:"bytes,1,opt,name=url,proto3" json:"url,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *LinkURLResponse) Reset() {
*x = LinkURLResponse{}
mi := &file_connector_v1_connector_proto_msgTypes[27]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *LinkURLResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*LinkURLResponse) ProtoMessage() {}
func (x *LinkURLResponse) ProtoReflect() protoreflect.Message {
mi := &file_connector_v1_connector_proto_msgTypes[27]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use LinkURLResponse.ProtoReflect.Descriptor instead.
func (*LinkURLResponse) Descriptor() ([]byte, []int) {
return file_connector_v1_connector_proto_rawDescGZIP(), []int{27}
}
func (x *LinkURLResponse) GetUrl() string {
if x != nil {
return x.Url
}
return ""
}
var File_connector_v1_connector_proto protoreflect.FileDescriptor var File_connector_v1_connector_proto protoreflect.FileDescriptor
const file_connector_v1_connector_proto_rawDesc = "" + const file_connector_v1_connector_proto_rawDesc = "" +
@@ -1720,7 +1861,7 @@ const file_connector_v1_connector_proto_rawDesc = "" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x13\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x13\n" +
"\x11ConfigureResponse\"\x11\n" + "\x11ConfigureResponse\"\x11\n" +
"\x0fDescribeRequest\"\x8d\x03\n" + "\x0fDescribeRequest\"\xb4\x03\n" +
"\x10DescribeResponse\x12\x1a\n" + "\x10DescribeResponse\x12\x1a\n" +
"\bcontract\x18\x01 \x01(\tR\bcontract\x12/\n" + "\bcontract\x18\x01 \x01(\tR\bcontract\x12/\n" +
"\x06events\x18\x02 \x03(\v2\x17.connector.v1.EventTypeR\x06events\x122\n" + "\x06events\x18\x02 \x03(\v2\x17.connector.v1.EventTypeR\x06events\x122\n" +
@@ -1732,7 +1873,9 @@ const file_connector_v1_connector_proto_rawDesc = "" +
"\alistens\x18\x06 \x01(\bR\alistens\x12!\n" + "\alistens\x18\x06 \x01(\bR\alistens\x12!\n" +
"\ftarget_facts\x18\a \x01(\bR\vtargetFacts\x121\n" + "\ftarget_facts\x18\a \x01(\bR\vtargetFacts\x121\n" +
"\bsettings\x18\b \x03(\v2\x15.connector.v1.SettingR\bsettings\x12\x18\n" + "\bsettings\x18\b \x03(\v2\x15.connector.v1.SettingR\bsettings\x12\x18\n" +
"\aversion\x18\t \x01(\tR\aversion\"\xd0\x01\n" + "\aversion\x18\t \x01(\tR\aversion\x12%\n" +
"\x0elinks_accounts\x18\n" +
" \x01(\bR\rlinksAccounts\"\xd0\x01\n" +
"\aSetting\x12\x10\n" + "\aSetting\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05label\x18\x02 \x01(\tR\x05label\x12 \n" + "\x05label\x18\x02 \x01(\tR\x05label\x12 \n" +
@@ -1757,16 +1900,20 @@ const file_connector_v1_connector_proto_rawDesc = "" +
"\fDeliveryType\x12\x12\n" + "\fDeliveryType\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\x12 \n" + "\x04name\x18\x01 \x01(\tR\x04name\x12 \n" +
"\vdescription\x18\x02 \x01(\tR\vdescription\x12!\n" + "\vdescription\x18\x02 \x01(\tR\vdescription\x12!\n" +
"\finput_schema\x18\x03 \x01(\fR\vinputSchema\"e\n" + "\finput_schema\x18\x03 \x01(\fR\vinputSchema\"\x93\x01\n" +
"\n" + "\n" +
"LookupType\x12\x12\n" + "LookupType\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\x12 \n" + "\x04name\x18\x01 \x01(\tR\x04name\x12 \n" +
"\vdescription\x18\x02 \x01(\tR\vdescription\x12!\n" + "\vdescription\x18\x02 \x01(\tR\vdescription\x12!\n" +
"\finput_schema\x18\x03 \x01(\fR\vinputSchema\"\x82\x01\n" + "\finput_schema\x18\x03 \x01(\fR\vinputSchema\x12,\n" +
"\x06effect\x18\x04 \x01(\v2\x14.connector.v1.EffectR\x06effect\"\xfd\x01\n" +
"\x06Effect\x12\x1b\n" + "\x06Effect\x12\x1b\n" +
"\tread_only\x18\x01 \x01(\bR\breadOnly\x12A\n" + "\tread_only\x18\x01 \x01(\bR\breadOnly\x12A\n" +
"\rreversibility\x18\x02 \x01(\x0e2\x1b.connector.v1.ReversibilityR\rreversibility\x12\x18\n" + "\rreversibility\x18\x02 \x01(\x0e2\x1b.connector.v1.ReversibilityR\rreversibility\x12\x18\n" +
"\asummary\x18\x03 \x01(\tR\asummary\"n\n" + "\asummary\x18\x03 \x01(\tR\asummary\x12)\n" +
"\x10effects_declared\x18\x04 \x01(\bR\x0feffectsDeclared\x12)\n" +
"\x10privilege_change\x18\x05 \x01(\bR\x0fprivilegeChange\x12#\n" +
"\rsecret_access\x18\x06 \x01(\bR\fsecretAccess\"n\n" +
"\x06Target\x12\x12\n" + "\x06Target\x12\x12\n" +
"\x04kind\x18\x01 \x01(\tR\x04kind\x12\x0e\n" + "\x04kind\x18\x01 \x01(\tR\x04kind\x12\x0e\n" +
"\x02id\x18\x02 \x01(\tR\x02id\x12 \n" + "\x02id\x18\x02 \x01(\tR\x02id\x12 \n" +
@@ -1829,7 +1976,11 @@ const file_connector_v1_connector_proto_rawDesc = "" +
"\x06cursor\x18\x01 \x01(\tR\x06cursor\"U\n" + "\x06cursor\x18\x01 \x01(\tR\x06cursor\"U\n" +
"\x0eListenResponse\x12+\n" + "\x0eListenResponse\x12+\n" +
"\x06events\x18\x01 \x03(\v2\x13.connector.v1.EventR\x06events\x12\x16\n" + "\x06events\x18\x01 \x03(\v2\x13.connector.v1.EventR\x06events\x12\x16\n" +
"\x06cursor\x18\x02 \x01(\tR\x06cursor*\xd9\x01\n" + "\x06cursor\x18\x02 \x01(\tR\x06cursor\"$\n" +
"\x0eLinkURLRequest\x12\x12\n" +
"\x04code\x18\x01 \x01(\tR\x04code\"#\n" +
"\x0fLinkURLResponse\x12\x10\n" +
"\x03url\x18\x01 \x01(\tR\x03url*\xd9\x01\n" +
"\vSettingType\x12\x1c\n" + "\vSettingType\x12\x1c\n" +
"\x18SETTING_TYPE_UNSPECIFIED\x10\x00\x12\x17\n" + "\x18SETTING_TYPE_UNSPECIFIED\x10\x00\x12\x17\n" +
"\x13SETTING_TYPE_STRING\x10\x01\x12\x17\n" + "\x13SETTING_TYPE_STRING\x10\x01\x12\x17\n" +
@@ -1843,7 +1994,7 @@ const file_connector_v1_connector_proto_rawDesc = "" +
"\x19REVERSIBILITY_UNSPECIFIED\x10\x00\x12&\n" + "\x19REVERSIBILITY_UNSPECIFIED\x10\x00\x12&\n" +
"\"REVERSIBILITY_UNDONE_AUTOMATICALLY\x10\x01\x12\x1d\n" + "\"REVERSIBILITY_UNDONE_AUTOMATICALLY\x10\x01\x12\x1d\n" +
"\x19REVERSIBILITY_RECOVERABLE\x10\x02\x12\x1e\n" + "\x19REVERSIBILITY_RECOVERABLE\x10\x02\x12\x1e\n" +
"\x1aREVERSIBILITY_IRREVERSIBLE\x10\x032\xa2\x05\n" + "\x1aREVERSIBILITY_IRREVERSIBLE\x10\x032\xea\x05\n" +
"\x10ConnectorService\x12L\n" + "\x10ConnectorService\x12L\n" +
"\tConfigure\x12\x1e.connector.v1.ConfigureRequest\x1a\x1f.connector.v1.ConfigureResponse\x12I\n" + "\tConfigure\x12\x1e.connector.v1.ConfigureRequest\x1a\x1f.connector.v1.ConfigureResponse\x12I\n" +
"\bDescribe\x12\x1d.connector.v1.DescribeRequest\x1a\x1e.connector.v1.DescribeResponse\x12@\n" + "\bDescribe\x12\x1d.connector.v1.DescribeRequest\x1a\x1e.connector.v1.DescribeResponse\x12@\n" +
@@ -1853,7 +2004,8 @@ const file_connector_v1_connector_proto_rawDesc = "" +
"\x06Lookup\x12\x1b.connector.v1.LookupRequest\x1a\x1c.connector.v1.LookupResponse\x12F\n" + "\x06Lookup\x12\x1b.connector.v1.LookupRequest\x1a\x1c.connector.v1.LookupResponse\x12F\n" +
"\aDeliver\x12\x1c.connector.v1.DeliverRequest\x1a\x1d.connector.v1.DeliverResponse\x12E\n" + "\aDeliver\x12\x1c.connector.v1.DeliverRequest\x1a\x1d.connector.v1.DeliverResponse\x12E\n" +
"\x06Listen\x12\x1b.connector.v1.ListenRequest\x1a\x1c.connector.v1.ListenResponse0\x01\x12R\n" + "\x06Listen\x12\x1b.connector.v1.ListenRequest\x1a\x1c.connector.v1.ListenResponse0\x01\x12R\n" +
"\vTargetFacts\x12 .connector.v1.TargetFactsRequest\x1a!.connector.v1.TargetFactsResponseB\xc4\x01\n" + "\vTargetFacts\x12 .connector.v1.TargetFactsRequest\x1a!.connector.v1.TargetFactsResponse\x12F\n" +
"\aLinkURL\x12\x1c.connector.v1.LinkURLRequest\x1a\x1d.connector.v1.LinkURLResponseB\xc4\x01\n" +
"\x10com.connector.v1B\x0eConnectorProtoP\x01ZOgithub.com/samcharles93/archie-core/internal/contracts/connector/v1;connectorv1\xa2\x02\x03CXX\xaa\x02\fConnector.V1\xca\x02\fConnector\\V1\xe2\x02\x18Connector\\V1\\GPBMetadata\xea\x02\rConnector::V1b\x06proto3" "\x10com.connector.v1B\x0eConnectorProtoP\x01ZOgithub.com/samcharles93/archie-core/internal/contracts/connector/v1;connectorv1\xa2\x02\x03CXX\xaa\x02\fConnector.V1\xca\x02\fConnector\\V1\xe2\x02\x18Connector\\V1\\GPBMetadata\xea\x02\rConnector::V1b\x06proto3"
var ( var (
@@ -1869,7 +2021,7 @@ func file_connector_v1_connector_proto_rawDescGZIP() []byte {
} }
var file_connector_v1_connector_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_connector_v1_connector_proto_enumTypes = make([]protoimpl.EnumInfo, 2)
var file_connector_v1_connector_proto_msgTypes = make([]protoimpl.MessageInfo, 29) var file_connector_v1_connector_proto_msgTypes = make([]protoimpl.MessageInfo, 31)
var file_connector_v1_connector_proto_goTypes = []any{ var file_connector_v1_connector_proto_goTypes = []any{
(SettingType)(0), // 0: connector.v1.SettingType (SettingType)(0), // 0: connector.v1.SettingType
(Reversibility)(0), // 1: connector.v1.Reversibility (Reversibility)(0), // 1: connector.v1.Reversibility
@@ -1899,14 +2051,16 @@ var file_connector_v1_connector_proto_goTypes = []any{
(*TargetFactsResponse)(nil), // 25: connector.v1.TargetFactsResponse (*TargetFactsResponse)(nil), // 25: connector.v1.TargetFactsResponse
(*ListenRequest)(nil), // 26: connector.v1.ListenRequest (*ListenRequest)(nil), // 26: connector.v1.ListenRequest
(*ListenResponse)(nil), // 27: connector.v1.ListenResponse (*ListenResponse)(nil), // 27: connector.v1.ListenResponse
nil, // 28: connector.v1.ConfigureRequest.SettingsEntry (*LinkURLRequest)(nil), // 28: connector.v1.LinkURLRequest
nil, // 29: connector.v1.ConfigureRequest.SecretsEntry (*LinkURLResponse)(nil), // 29: connector.v1.LinkURLResponse
nil, // 30: connector.v1.ParseRequest.HeadersEntry nil, // 30: connector.v1.ConfigureRequest.SettingsEntry
(*timestamppb.Timestamp)(nil), // 31: google.protobuf.Timestamp nil, // 31: connector.v1.ConfigureRequest.SecretsEntry
nil, // 32: connector.v1.ParseRequest.HeadersEntry
(*timestamppb.Timestamp)(nil), // 33: google.protobuf.Timestamp
} }
var file_connector_v1_connector_proto_depIdxs = []int32{ var file_connector_v1_connector_proto_depIdxs = []int32{
28, // 0: connector.v1.ConfigureRequest.settings:type_name -> connector.v1.ConfigureRequest.SettingsEntry 30, // 0: connector.v1.ConfigureRequest.settings:type_name -> connector.v1.ConfigureRequest.SettingsEntry
29, // 1: connector.v1.ConfigureRequest.secrets:type_name -> connector.v1.ConfigureRequest.SecretsEntry 31, // 1: connector.v1.ConfigureRequest.secrets:type_name -> connector.v1.ConfigureRequest.SecretsEntry
7, // 2: connector.v1.DescribeResponse.events:type_name -> connector.v1.EventType 7, // 2: connector.v1.DescribeResponse.events:type_name -> connector.v1.EventType
8, // 3: connector.v1.DescribeResponse.actions:type_name -> connector.v1.ActionType 8, // 3: connector.v1.DescribeResponse.actions:type_name -> connector.v1.ActionType
10, // 4: connector.v1.DescribeResponse.lookups:type_name -> connector.v1.LookupType 10, // 4: connector.v1.DescribeResponse.lookups:type_name -> connector.v1.LookupType
@@ -1914,37 +2068,40 @@ var file_connector_v1_connector_proto_depIdxs = []int32{
6, // 6: connector.v1.DescribeResponse.settings:type_name -> connector.v1.Setting 6, // 6: connector.v1.DescribeResponse.settings:type_name -> connector.v1.Setting
0, // 7: connector.v1.Setting.type:type_name -> connector.v1.SettingType 0, // 7: connector.v1.Setting.type:type_name -> connector.v1.SettingType
11, // 8: connector.v1.ActionType.effect:type_name -> connector.v1.Effect 11, // 8: connector.v1.ActionType.effect:type_name -> connector.v1.Effect
1, // 9: connector.v1.Effect.reversibility:type_name -> connector.v1.Reversibility 11, // 9: connector.v1.LookupType.effect:type_name -> connector.v1.Effect
30, // 10: connector.v1.ParseRequest.headers:type_name -> connector.v1.ParseRequest.HeadersEntry 1, // 10: connector.v1.Effect.reversibility:type_name -> connector.v1.Reversibility
15, // 11: connector.v1.ParseResponse.events:type_name -> connector.v1.Event 32, // 11: connector.v1.ParseRequest.headers:type_name -> connector.v1.ParseRequest.HeadersEntry
31, // 12: connector.v1.Event.occurred_at:type_name -> google.protobuf.Timestamp 15, // 12: connector.v1.ParseResponse.events:type_name -> connector.v1.Event
12, // 13: connector.v1.ResolveResponse.target:type_name -> connector.v1.Target 33, // 13: connector.v1.Event.occurred_at:type_name -> google.protobuf.Timestamp
11, // 14: connector.v1.ResolveResponse.effect:type_name -> connector.v1.Effect 12, // 14: connector.v1.ResolveResponse.target:type_name -> connector.v1.Target
12, // 15: connector.v1.TargetFactsRequest.target:type_name -> connector.v1.Target 11, // 15: connector.v1.ResolveResponse.effect:type_name -> connector.v1.Effect
15, // 16: connector.v1.ListenResponse.events:type_name -> connector.v1.Event 12, // 16: connector.v1.TargetFactsRequest.target:type_name -> connector.v1.Target
2, // 17: connector.v1.ConnectorService.Configure:input_type -> connector.v1.ConfigureRequest 15, // 17: connector.v1.ListenResponse.events:type_name -> connector.v1.Event
4, // 18: connector.v1.ConnectorService.Describe:input_type -> connector.v1.DescribeRequest 2, // 18: connector.v1.ConnectorService.Configure:input_type -> connector.v1.ConfigureRequest
13, // 19: connector.v1.ConnectorService.Parse:input_type -> connector.v1.ParseRequest 4, // 19: connector.v1.ConnectorService.Describe:input_type -> connector.v1.DescribeRequest
16, // 20: connector.v1.ConnectorService.Resolve:input_type -> connector.v1.ResolveRequest 13, // 20: connector.v1.ConnectorService.Parse:input_type -> connector.v1.ParseRequest
18, // 21: connector.v1.ConnectorService.Invoke:input_type -> connector.v1.InvokeRequest 16, // 21: connector.v1.ConnectorService.Resolve:input_type -> connector.v1.ResolveRequest
20, // 22: connector.v1.ConnectorService.Lookup:input_type -> connector.v1.LookupRequest 18, // 22: connector.v1.ConnectorService.Invoke:input_type -> connector.v1.InvokeRequest
22, // 23: connector.v1.ConnectorService.Deliver:input_type -> connector.v1.DeliverRequest 20, // 23: connector.v1.ConnectorService.Lookup:input_type -> connector.v1.LookupRequest
26, // 24: connector.v1.ConnectorService.Listen:input_type -> connector.v1.ListenRequest 22, // 24: connector.v1.ConnectorService.Deliver:input_type -> connector.v1.DeliverRequest
24, // 25: connector.v1.ConnectorService.TargetFacts:input_type -> connector.v1.TargetFactsRequest 26, // 25: connector.v1.ConnectorService.Listen:input_type -> connector.v1.ListenRequest
3, // 26: connector.v1.ConnectorService.Configure:output_type -> connector.v1.ConfigureResponse 24, // 26: connector.v1.ConnectorService.TargetFacts:input_type -> connector.v1.TargetFactsRequest
5, // 27: connector.v1.ConnectorService.Describe:output_type -> connector.v1.DescribeResponse 28, // 27: connector.v1.ConnectorService.LinkURL:input_type -> connector.v1.LinkURLRequest
14, // 28: connector.v1.ConnectorService.Parse:output_type -> connector.v1.ParseResponse 3, // 28: connector.v1.ConnectorService.Configure:output_type -> connector.v1.ConfigureResponse
17, // 29: connector.v1.ConnectorService.Resolve:output_type -> connector.v1.ResolveResponse 5, // 29: connector.v1.ConnectorService.Describe:output_type -> connector.v1.DescribeResponse
19, // 30: connector.v1.ConnectorService.Invoke:output_type -> connector.v1.InvokeResponse 14, // 30: connector.v1.ConnectorService.Parse:output_type -> connector.v1.ParseResponse
21, // 31: connector.v1.ConnectorService.Lookup:output_type -> connector.v1.LookupResponse 17, // 31: connector.v1.ConnectorService.Resolve:output_type -> connector.v1.ResolveResponse
23, // 32: connector.v1.ConnectorService.Deliver:output_type -> connector.v1.DeliverResponse 19, // 32: connector.v1.ConnectorService.Invoke:output_type -> connector.v1.InvokeResponse
27, // 33: connector.v1.ConnectorService.Listen:output_type -> connector.v1.ListenResponse 21, // 33: connector.v1.ConnectorService.Lookup:output_type -> connector.v1.LookupResponse
25, // 34: connector.v1.ConnectorService.TargetFacts:output_type -> connector.v1.TargetFactsResponse 23, // 34: connector.v1.ConnectorService.Deliver:output_type -> connector.v1.DeliverResponse
26, // [26:35] is the sub-list for method output_type 27, // 35: connector.v1.ConnectorService.Listen:output_type -> connector.v1.ListenResponse
17, // [17:26] is the sub-list for method input_type 25, // 36: connector.v1.ConnectorService.TargetFacts:output_type -> connector.v1.TargetFactsResponse
17, // [17:17] is the sub-list for extension type_name 29, // 37: connector.v1.ConnectorService.LinkURL:output_type -> connector.v1.LinkURLResponse
17, // [17:17] is the sub-list for extension extendee 28, // [28:38] is the sub-list for method output_type
0, // [0:17] is the sub-list for field type_name 18, // [18:28] is the sub-list for method input_type
18, // [18:18] is the sub-list for extension type_name
18, // [18:18] is the sub-list for extension extendee
0, // [0:18] is the sub-list for field type_name
} }
func init() { file_connector_v1_connector_proto_init() } func init() { file_connector_v1_connector_proto_init() }
@@ -1958,7 +2115,7 @@ func file_connector_v1_connector_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(), GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_connector_v1_connector_proto_rawDesc), len(file_connector_v1_connector_proto_rawDesc)), RawDescriptor: unsafe.Slice(unsafe.StringData(file_connector_v1_connector_proto_rawDesc), len(file_connector_v1_connector_proto_rawDesc)),
NumEnums: 2, NumEnums: 2,
NumMessages: 29, NumMessages: 31,
NumExtensions: 0, NumExtensions: 0,
NumServices: 1, NumServices: 1,
}, },
@@ -28,6 +28,7 @@ const (
ConnectorService_Deliver_FullMethodName = "/connector.v1.ConnectorService/Deliver" ConnectorService_Deliver_FullMethodName = "/connector.v1.ConnectorService/Deliver"
ConnectorService_Listen_FullMethodName = "/connector.v1.ConnectorService/Listen" ConnectorService_Listen_FullMethodName = "/connector.v1.ConnectorService/Listen"
ConnectorService_TargetFacts_FullMethodName = "/connector.v1.ConnectorService/TargetFacts" ConnectorService_TargetFacts_FullMethodName = "/connector.v1.ConnectorService/TargetFacts"
ConnectorService_LinkURL_FullMethodName = "/connector.v1.ConnectorService/LinkURL"
) )
// ConnectorServiceClient is the client API for ConnectorService service. // ConnectorServiceClient is the client API for ConnectorService service.
@@ -60,6 +61,9 @@ type ConnectorServiceClient interface {
// delivery is never offered to an agent: hard rules apply to it, guards // delivery is never offered to an agent: hard rules apply to it, guards
// don't. The host retries a failed delivery, so a connector should make a // don't. The host retries a failed delivery, so a connector should make a
// repeat with the same idempotency key harmless where its service allows. // repeat with the same idempotency key harmless where its service allows.
// A connector returns InvalidArgument, FailedPrecondition, PermissionDenied
// or NotFound when the service rejects the delivery permanently: the host
// records the reason and stops retrying. Any other status is retried.
Deliver(ctx context.Context, in *DeliverRequest, opts ...grpc.CallOption) (*DeliverResponse, error) Deliver(ctx context.Context, in *DeliverRequest, opts ...grpc.CallOption) (*DeliverResponse, error)
// Listen streams the events of a source the connector holds its own // Listen streams the events of a source the connector holds its own
// connection to, such as a chat long poll, from cursor on. Each response // connection to, such as a chat long poll, from cursor on. Each response
@@ -71,6 +75,12 @@ type ConnectorServiceClient interface {
// host asks only connectors that declare target_facts, and never stores the // host asks only connectors that declare target_facts, and never stores the
// answer. // answer.
TargetFacts(ctx context.Context, in *TargetFactsRequest, opts ...grpc.CallOption) (*TargetFactsResponse, error) TargetFacts(ctx context.Context, in *TargetFactsRequest, opts ...grpc.CallOption) (*TargetFactsResponse, error)
// LinkURL returns the URL a person opens to send a link code to the
// connector, such as a deep link into its bot. The host asks only
// connectors that declare links_accounts. The connector then emits an
// account.link event carrying the code and the sender's channel identity;
// the host binds that identity to the account that issued the code.
LinkURL(ctx context.Context, in *LinkURLRequest, opts ...grpc.CallOption) (*LinkURLResponse, error)
} }
type connectorServiceClient struct { type connectorServiceClient struct {
@@ -180,6 +190,16 @@ func (c *connectorServiceClient) TargetFacts(ctx context.Context, in *TargetFact
return out, nil return out, nil
} }
func (c *connectorServiceClient) LinkURL(ctx context.Context, in *LinkURLRequest, opts ...grpc.CallOption) (*LinkURLResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(LinkURLResponse)
err := c.cc.Invoke(ctx, ConnectorService_LinkURL_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// ConnectorServiceServer is the server API for ConnectorService service. // ConnectorServiceServer is the server API for ConnectorService service.
// All implementations must embed UnimplementedConnectorServiceServer // All implementations must embed UnimplementedConnectorServiceServer
// for forward compatibility. // for forward compatibility.
@@ -210,6 +230,9 @@ type ConnectorServiceServer interface {
// delivery is never offered to an agent: hard rules apply to it, guards // delivery is never offered to an agent: hard rules apply to it, guards
// don't. The host retries a failed delivery, so a connector should make a // don't. The host retries a failed delivery, so a connector should make a
// repeat with the same idempotency key harmless where its service allows. // repeat with the same idempotency key harmless where its service allows.
// A connector returns InvalidArgument, FailedPrecondition, PermissionDenied
// or NotFound when the service rejects the delivery permanently: the host
// records the reason and stops retrying. Any other status is retried.
Deliver(context.Context, *DeliverRequest) (*DeliverResponse, error) Deliver(context.Context, *DeliverRequest) (*DeliverResponse, error)
// Listen streams the events of a source the connector holds its own // Listen streams the events of a source the connector holds its own
// connection to, such as a chat long poll, from cursor on. Each response // connection to, such as a chat long poll, from cursor on. Each response
@@ -221,6 +244,12 @@ type ConnectorServiceServer interface {
// host asks only connectors that declare target_facts, and never stores the // host asks only connectors that declare target_facts, and never stores the
// answer. // answer.
TargetFacts(context.Context, *TargetFactsRequest) (*TargetFactsResponse, error) TargetFacts(context.Context, *TargetFactsRequest) (*TargetFactsResponse, error)
// LinkURL returns the URL a person opens to send a link code to the
// connector, such as a deep link into its bot. The host asks only
// connectors that declare links_accounts. The connector then emits an
// account.link event carrying the code and the sender's channel identity;
// the host binds that identity to the account that issued the code.
LinkURL(context.Context, *LinkURLRequest) (*LinkURLResponse, error)
mustEmbedUnimplementedConnectorServiceServer() mustEmbedUnimplementedConnectorServiceServer()
} }
@@ -258,6 +287,9 @@ func (UnimplementedConnectorServiceServer) Listen(*ListenRequest, grpc.ServerStr
func (UnimplementedConnectorServiceServer) TargetFacts(context.Context, *TargetFactsRequest) (*TargetFactsResponse, error) { func (UnimplementedConnectorServiceServer) TargetFacts(context.Context, *TargetFactsRequest) (*TargetFactsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method TargetFacts not implemented") return nil, status.Error(codes.Unimplemented, "method TargetFacts not implemented")
} }
func (UnimplementedConnectorServiceServer) LinkURL(context.Context, *LinkURLRequest) (*LinkURLResponse, error) {
return nil, status.Error(codes.Unimplemented, "method LinkURL not implemented")
}
func (UnimplementedConnectorServiceServer) mustEmbedUnimplementedConnectorServiceServer() {} func (UnimplementedConnectorServiceServer) mustEmbedUnimplementedConnectorServiceServer() {}
func (UnimplementedConnectorServiceServer) testEmbeddedByValue() {} func (UnimplementedConnectorServiceServer) testEmbeddedByValue() {}
@@ -434,6 +466,24 @@ func _ConnectorService_TargetFacts_Handler(srv interface{}, ctx context.Context,
return interceptor(ctx, in, info, handler) return interceptor(ctx, in, info, handler)
} }
func _ConnectorService_LinkURL_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(LinkURLRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ConnectorServiceServer).LinkURL(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ConnectorService_LinkURL_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ConnectorServiceServer).LinkURL(ctx, req.(*LinkURLRequest))
}
return interceptor(ctx, in, info, handler)
}
// ConnectorService_ServiceDesc is the grpc.ServiceDesc for ConnectorService service. // ConnectorService_ServiceDesc is the grpc.ServiceDesc for ConnectorService service.
// It's only intended for direct use with grpc.RegisterService, // It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy) // and not to be introspected or modified (even as a copy)
@@ -473,6 +523,10 @@ var ConnectorService_ServiceDesc = grpc.ServiceDesc{
MethodName: "TargetFacts", MethodName: "TargetFacts",
Handler: _ConnectorService_TargetFacts_Handler, Handler: _ConnectorService_TargetFacts_Handler,
}, },
{
MethodName: "LinkURL",
Handler: _ConnectorService_LinkURL_Handler,
},
}, },
Streams: []grpc.StreamDesc{ Streams: []grpc.StreamDesc{
{ {
+1 -1
View File
@@ -35,7 +35,7 @@ type TaskTransport interface {
} }
// RunCredentialIssuer issues the one credential a task's container holds: it // RunCredentialIssuer issues the one credential a task's container holds: it
// authorizes the task's own State Store calls and the push of its branch. // authorises the task's own State Store calls and the push of its branch.
// It lapses at the task's time limit plus a margin if never revoked. // It lapses at the task's time limit plus a margin if never revoked.
type RunCredentialIssuer interface { type RunCredentialIssuer interface {
Issue(ctx context.Context, task *workflow.Task, limit time.Duration) (token string, revoke func(), err error) Issue(ctx context.Context, task *workflow.Task, limit time.Duration) (token string, revoke func(), err error)
+1 -1
View File
@@ -58,7 +58,7 @@ func (d *Daemon) adoptWorkflowIdentity(ctx context.Context, task *workflow.Task)
} }
// declaredIdentity resolves a workflow's declared identity to the ID it is // declaredIdentity resolves a workflow's declared identity to the ID it is
// authorized as and the name the task carries while it runs. // authorised as and the name the task carries while it runs.
func (g *IdentityGate) declaredIdentity(ctx context.Context, task *workflow.Task, ref string) (identity.IdentityID, string, error) { func (g *IdentityGate) declaredIdentity(ctx context.Context, task *workflow.Task, ref string) (identity.IdentityID, string, error) {
value, err := g.databaseExecutionIdentity(ctx, task, identity.IdentityID(ref)) value, err := g.databaseExecutionIdentity(ctx, task, identity.IdentityID(ref))
if err != nil { if err != nil {
+1 -1
View File
@@ -132,7 +132,7 @@ type Usage struct {
} }
// Provider describes how the worker resolves a model provider. API keys are // Provider describes how the worker resolves a model provider. API keys are
// referenced by environment variable name and never serialized. // referenced by environment variable name and never serialised.
type Provider struct { type Provider struct {
Class string `json:"class"` Class string `json:"class"`
APIKeyEnv string `json:"api_key_env,omitempty"` APIKeyEnv string `json:"api_key_env,omitempty"`
+1 -1
View File
@@ -109,7 +109,7 @@ func NormalizeLimit(limit int) int {
return limit return limit
} }
// Hash is the fingerprint of the normalized filter a cursor is bound to. A // Hash is the fingerprint of the normalised filter a cursor is bound to. A
// cursor replayed with a different filter would resume at a position that no // cursor replayed with a different filter would resume at a position that no
// longer means the same page, so the reader refuses it. // longer means the same page, so the reader refuses it.
func (f *Filter) Hash() string { func (f *Filter) Hash() string {
+1 -1
View File
@@ -51,7 +51,7 @@ func (t *activityTracker) record(name string, at time.Time, actions []Action) {
// A curator engine may not stamp its own actions (no clock // A curator engine may not stamp its own actions (no clock
// dependency wired in); the pass's own "at" is the authoritative // dependency wired in); the pass's own "at" is the authoritative
// time for every action it produced, so backfill rather than let // time for every action it produced, so backfill rather than let
// a zero time.Time reach the wire as "105694 wks ago". // a zero timestamp reach the wire as "105694 wks ago".
if action.At.IsZero() { if action.At.IsZero() {
action.At = at action.At = at
} }
+1 -1
View File
@@ -91,7 +91,7 @@ type ToolBuilder interface {
} }
// SkillStore is the skill-maintenance capability. The implementation owns // SkillStore is the skill-maintenance capability. The implementation owns
// the on-disk format and catalog reload rules. // the on-disk format and catalogue reload rules.
type SkillStore interface { type SkillStore interface {
List(ctx context.Context) ([]SkillRef, error) List(ctx context.Context) ([]SkillRef, error)
Read(ctx context.Context, name string) (Skill, error) Read(ctx context.Context, name string) (Skill, error)
+1 -1
View File
@@ -30,7 +30,7 @@ type RuntimeConfig struct {
// defaultPassTimeout (10m). // defaultPassTimeout (10m).
PassTimeout time.Duration PassTimeout time.Duration
// MaxConcurrentPasses caps simultaneous passes across all curators. // MaxConcurrentPasses caps simultaneous passes across all curators.
// Zero uses 1: passes serialize behind a shared slot so a pass burst // Zero uses 1: passes serialise behind a shared slot so a pass burst
// can never saturate the model runtime against chat turns. // can never saturate the model runtime against chat turns.
MaxConcurrentPasses int MaxConcurrentPasses int
} }
+2 -2
View File
@@ -57,7 +57,7 @@ type SubjectBinding interface {
BindSubject(context.Context, IdentityID, Subject, Audit) error BindSubject(context.Context, IdentityID, Subject, Audit) error
} }
// LoginFlow is the browser authorization flow an identity provider requires, as // LoginFlow is the browser authorisation flow an identity provider requires, as
// a dashboard driving it needs it: the URL to send a browser to, then the // a dashboard driving it needs it: the URL to send a browser to, then the
// completion of the flow when the browser returns. It is a contract here rather // completion of the flow when the browser returns. It is a contract here rather
// than in the transport because what it yields is an identity. // than in the transport because what it yields is an identity.
@@ -83,7 +83,7 @@ type SubjectResolver interface {
ClaimSubject(ctx context.Context, placeholder, subject Subject) (Identity, error) ClaimSubject(ctx context.Context, placeholder, subject Subject) (Identity, error)
} }
// ProviderSession is what a completed authorization flow yields: the credential // ProviderSession is what a completed authorisation flow yields: the credential
// the provider proved, and the provider's own token to present on later requests. // the provider proved, and the provider's own token to present on later requests.
// Archie holds no session of its own -- the token belongs to the provider and is // Archie holds no session of its own -- the token belongs to the provider and is
// re-verified on every later request, so nothing archie stores can outlive it. // re-verified on every later request, so nothing archie stores can outlive it.
+2 -2
View File
@@ -1,6 +1,6 @@
package messaging package messaging
// ModelDetails carries read-only catalog metadata for one model reference. // ModelDetails carries read-only catalogue metadata for one model reference.
type ModelDetails struct { type ModelDetails struct {
Ref string `json:"ref"` Ref string `json:"ref"`
Name string `json:"name,omitempty"` Name string `json:"name,omitempty"`
@@ -14,7 +14,7 @@ type ModelDetails struct {
} }
// DetailedModelManager optionally enriches model selection confirmation with // DetailedModelManager optionally enriches model selection confirmation with
// catalog metadata such as context window and modalities. // catalogue metadata such as context window and modalities.
type DetailedModelManager interface { type DetailedModelManager interface {
ModelDetails(ref string) (ModelDetails, bool) ModelDetails(ref string) (ModelDetails, bool)
} }
+1 -1
View File
@@ -46,7 +46,7 @@ const (
// TimingCron fires at each cron match in the instance time zone. // TimingCron fires at each cron match in the instance time zone.
// Day-of-month and day-of-week are ANDed. // Day-of-month and day-of-week are ANDed.
TimingCron = "cron" TimingCron = "cron"
// TimingOnce fires once at At. // TimingOnce fires once when the At time arrives.
TimingOnce = "once" TimingOnce = "once"
) )
+2 -2
View File
@@ -20,8 +20,8 @@ const cursorSeparator = "|"
// and string comparison of two cursors is the total order (key, id). // and string comparison of two cursors is the total order (key, id).
const cursorIDWidth = 20 const cursorIDWidth = 20
// EventCursor returns the opaque resume cursor for an event that happened at // EventCursor returns the opaque resume cursor for an event whose time is at
// at with row id id. The cursor is a string so EventSource can carry it // and whose row id is id. The cursor is a string so EventSource can carry it
// verbatim in its id: field and echo it back as the Last-Event-ID header; it // verbatim in its id: field and echo it back as the Last-Event-ID header; it
// is opaque to every consumer except EventsSince. // is opaque to every consumer except EventsSince.
func EventCursor(at time.Time, id int64) string { func EventCursor(at time.Time, id int64) string {
+1 -1
View File
@@ -25,7 +25,7 @@ var (
ErrUnavailable = errors.New("runtime task control is unavailable") ErrUnavailable = errors.New("runtime task control is unavailable")
) )
// Task is the state needed to authorize and apply an operator action. // Task is the state needed to authorise and apply an operator action.
type Task struct { type Task struct {
Org org.OrgID Org org.OrgID
ID int64 ID int64
+4 -4
View File
@@ -57,9 +57,9 @@ func NormalizeDays(days int) int {
return days return days
} }
// ReportWindow is the UTC window a report of days days covers, ending at now: // ReportWindow is the UTC window a report of the given number of days covers,
// whole days, today included. Rows are bucketed by UTC day, so the window // ending at now: whole days, today included. Rows are bucketed by UTC day, so
// starts at a UTC midnight. // the window starts at a UTC midnight.
func ReportWindow(days int, now time.Time) (from, to time.Time) { func ReportWindow(days int, now time.Time) (from, to time.Time) {
now = now.UTC() now = now.UTC()
start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC) start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
@@ -68,7 +68,7 @@ func ReportWindow(days int, now time.Time) (from, to time.Time) {
// TotalRow is one cell of a usage report: the day, source and model an org's // TotalRow is one cell of a usage report: the day, source and model an org's
// calls used and the tokens they spent. Cost is not carried; the reader // calls used and the tokens they spent. Cost is not carried; the reader
// prices the tokens against the model catalog. // prices the tokens against the model catalogue.
type TotalRow struct { type TotalRow struct {
Day string Day string
Source Source Source Source
@@ -9,6 +9,23 @@ import (
"github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/domain/workflow/task"
) )
// TestMessageSendWithoutRepository guards workflows that only send a message
// from being rejected by the worktree requirement.
func TestMessageSendWithoutRepository(t *testing.T) {
for _, mode := range []string{"none", "optional"} {
t.Run(mode, func(t *testing.T) {
_, err := ParseDefinition("id: notify\nrepository: "+mode+`
steps:
- type: message.send
settings: {channel: telegram, chat_id: "123", text: "Done"}
`, StepRegistry{MessageSendStepName: newMessageSendStage})
if err != nil {
t.Fatal(err)
}
})
}
}
func TestValidateControlTargets(t *testing.T) { func TestValidateControlTargets(t *testing.T) {
registry := StepRegistry{ registry := StepRegistry{
AgentRunStepName: newAgentRunStage, AgentRunStepName: newAgentRunStage,
+1
View File
@@ -37,6 +37,7 @@ type YAMLDefinition struct {
var repoFreeStepTypes = map[string]bool{ var repoFreeStepTypes = map[string]bool{
AgentRunStepName: true, WorkflowCallStepName: true, FinishStepName: true, AgentRunStepName: true, WorkflowCallStepName: true, FinishStepName: true,
HandoffStepName: true, ApproveStepName: true, CloseIssueStepName: true, CommentStepName: true, HandoffStepName: true, ApproveStepName: true, CloseIssueStepName: true, CommentStepName: true,
MessageSendStepName: true,
} }
// NeedsRepository reports whether a step type can run only with a worktree. // NeedsRepository reports whether a step type can run only with a worktree.
@@ -11,6 +11,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/agentrun" "github.com/samcharles93/archie-core/internal/domain/agentrun"
"github.com/samcharles93/archie-core/internal/domain/workflow/prreview" "github.com/samcharles93/archie-core/internal/domain/workflow/prreview"
"github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/prompts"
) )
func stagePRVerification() Stage { func stagePRVerification() Stage {
@@ -355,15 +356,7 @@ func runAdversary(ctx context.Context, tc *TaskContext, findings []prreview.Find
return findings, nil return findings, nil
} }
mission := fmt.Sprintf( mission := prompts.PRReviewAdversary(
"You are the adversary reviewing this pull request's findings. For each finding "+
"below, confirm it (you agree it is a real defect) or challenge it (you believe "+
"it is wrong or not actually a problem). Read the snapshot yourself to check. "+
"%s Also look for any defect every reviewer missed and report it as a new "+
"finding.\n\n%s\n"+
"Call adversary_verdicts exactly once with one verdict per finding index. If you "+
"found anything new, call report_findings once too (skip it if you found "+
"nothing new). Then call finish with status \"passed\".",
adversarySkepticism(tc.prReview.aiGenerated), findingsListing(findings), adversarySkepticism(tc.prReview.aiGenerated), findingsListing(findings),
) )
res, err := runPRReviewAgentRecorded(ctx, tc, tc.prReview.snapshotDir, "adversary", mission, 25, []agentrun.CaptureTool{ res, err := runPRReviewAgentRecorded(ctx, tc, tc.prReview.snapshotDir, "adversary", mission, 25, []agentrun.CaptureTool{
+4 -4
View File
@@ -44,10 +44,10 @@ type StepStart struct {
CalledExecutionID int64 CalledExecutionID int64
} }
// StepFinish moves one step from From to its outcome. ExecutionID names the // StepFinish moves one step out of the From status into its outcome.
// run the step belongs to: the task-scoped grant check verifies it, and the // ExecutionID names the run the step belongs to: the task-scoped grant check
// store verifies the step really is that execution's, so a caller cannot move // verifies it, and the store verifies the step really is that execution's, so
// another run's step by naming it. // a caller cannot move another run's step by naming it.
type StepFinish struct { type StepFinish struct {
StepID int64 StepID int64
ExecutionID int64 ExecutionID int64
+1 -1
View File
@@ -90,7 +90,7 @@ type Task struct {
// Identity is the identity that created this task: a chat user, the // Identity is the identity that created this task: a chat user, the
// polling identity, a calling workflow's declared identity, or System for // polling identity, a calling workflow's declared identity, or System for
// instance-level work. Never empty. Used to scope /approve and // instance-level work. Never empty. Used to scope /approve and
// /cancel authorization so one identity cannot control another's // /cancel authorisation so one identity cannot control another's
// chat-spawned tasks. While the daemon processes the task it holds the // chat-spawned tasks. While the daemon processes the task it holds the
// identity the workflow declares, which is never stored here. // identity the workflow declares, which is never stored here.
Identity string `json:"identity"` Identity string `json:"identity"`
+5 -4
View File
@@ -24,10 +24,11 @@ import (
"github.com/samcharles93/archie-core/internal/tools" "github.com/samcharles93/archie-core/internal/tools"
) )
// Forger is the subset of forge.Forge that workflow stages call mid-run. // Forger is the subset of the Forge interface in the forge package that
// Production reaches it through forgerpc.Client, which proxies each call to the // workflow stages call mid-run. Production reaches it through forgerpc.Client,
// daemon over NATS -- the worker holds no forge credentials, so the daemon stays // which proxies each call to the daemon over NATS -- the worker holds no forge
// the only caller of forge.Forge. Test fakes implement it directly. // credentials, so the daemon stays the only caller of that interface. Test
// fakes implement it directly.
type Forger interface { type Forger interface {
CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error
CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error) CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error)
@@ -6,7 +6,7 @@ import (
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task" workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
) )
// ReviewTaskLookup is the authorization query review reactions require. // ReviewTaskLookup is the authorisation query review reactions require.
type ReviewTaskLookup interface { type ReviewTaskLookup interface {
OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*workflowtask.Task, error) OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*workflowtask.Task, error)
} }
+4 -3
View File
@@ -60,7 +60,7 @@ func SubjectFor(identity, base string) string {
return "archie.forge." + string(domainidentity.StableID(identity)) + "." + strings.TrimPrefix(base, "archie.forge.") return "archie.forge." + string(domainidentity.StableID(identity)) + "." + strings.TrimPrefix(base, "archie.forge.")
} }
// Target is what every request acts on and the credential that authorizes // Target is what every request acts on and the credential that authorises
// it: the run credential of the task asking, which only reaches that task's // it: the run credential of the task asking, which only reaches that task's
// own repository. // own repository.
type Target struct { type Target struct {
@@ -162,7 +162,8 @@ type Authorities interface {
AcceptedAuthority(ctx context.Context, name string) (storepkg.Authority, error) AcceptedAuthority(ctx context.Context, name string) (storepkg.Authority, error)
} }
// Server proxies forgerpc requests to a real forge.Forge implementation. // Server proxies forgerpc requests to a real implementation of the Forge
// interface.
type Server struct { type Server struct {
Resolve func(context.Context, *workflow.Task) (forge.Forge, error) Resolve func(context.Context, *workflow.Task) (forge.Forge, error)
Runs Runs Runs Runs
@@ -390,7 +391,7 @@ func (s *Server) respond(msg *nats.Msg, v any) {
} }
// Client calls the forgerpc Server from archie-agent's process. It // Client calls the forgerpc Server from archie-agent's process. It
// implements the four proxied forge.Forge methods with matching // implements the four proxied methods of the Forge interface with matching
// signatures so it can be used as a drop-in for workflow stages. // signatures so it can be used as a drop-in for workflow stages.
type Client struct { type Client struct {
Conn *nats.Conn Conn *nats.Conn
+1 -1
View File
@@ -27,7 +27,7 @@ func (r runsByToken) TaskForCredential(_ context.Context, token string) (*workfl
return nil, errors.New("unknown") return nil, errors.New("unknown")
} }
// TestForgeCallStaysInItsRunsAuthority pins that a forge call is authorized // TestForgeCallStaysInItsRunsAuthority pins that a forge call is authorised
// only by a live run credential, on its identity's server, for its own // only by a live run credential, on its identity's server, for its own
// repository, and for a package's workflow only within the forge permissions // repository, and for a package's workflow only within the forge permissions
// accepted for that package. // accepted for that package.
+1 -1
View File
@@ -63,7 +63,7 @@ func CompressionConfigForModel(details ModelDetails, promptReserve int) (Compres
cfg := DefaultCompressionConfig() cfg := DefaultCompressionConfig()
if details.ContextWindow <= 0 { if details.ContextWindow <= 0 {
// ModelDetails is an optional extension on ModelManager. Preserve // ModelDetails is an optional extension on ModelManager. Preserve
// compatibility for minimal adapters, while production catalog-backed // compatibility for minimal adapters, while production catalogue-backed
// managers still take the model-specific path below. // managers still take the model-specific path below.
cfg.MaxPromptTokens = max(cfg.ContextWindow-max(promptReserve, 0), 1) cfg.MaxPromptTokens = max(cfg.ContextWindow-max(promptReserve, 0), 1)
return cfg, nil return cfg, nil
+26 -47
View File
@@ -8,63 +8,34 @@ import (
"github.com/samcharles93/archie-core/internal/prompts" "github.com/samcharles93/archie-core/internal/prompts"
"github.com/samcharles93/archie-core/internal/tools" "github.com/samcharles93/archie-core/internal/tools"
"github.com/samcharles93/archie-core/ui/pages"
) )
// DashboardPage describes one dashboard surface so the chat agent can both // DashboardPage describes one dashboard surface so the chat agent can both
// understand what each place is for and point the operator there. // understand what each place is for and point the operator there. It is the
// catalogue the dashboard's own navigation renders from (ui/pages), so a page
// the assistant can name is a page the operator can reach.
type DashboardPage struct { type DashboardPage struct {
// Path is the route (e.g. "/tasks"). It is what the browser hash becomes. // Path is the route (e.g. "/tasks"). It is what the browser hash becomes.
Path string Path string
// Label is the human name shown in navigation (e.g. "Tasks"). // Label is the human name the navigation shows (e.g. "Tasks").
Label string Label string
// Description is a one-line plain-language explanation of what the page // Description is a one-line plain-language explanation of what the page
// shows, so the agent can answer "where do I go for that?" correctly. // shows, so the agent can answer "where do I go for that?" correctly.
Description string Description string
} }
// dashboardPages lists the dashboard pages the prompt and the // DashboardPages returns the dashboard's page catalogue, in its own order.
// dashboard_navigate tool can name. func DashboardPages() ([]DashboardPage, error) {
var dashboardPages = []DashboardPage{ catalogue, err := pages.All()
{Path: "/", Label: "Dashboard", Description: "Running work, work needing attention, token spend."}, if err != nil {
{Path: "/tasks", Label: "Tasks", Description: "Picked-up issues and their status."}, return nil, err
{Path: "/account", Label: "Your account", Description: "Password, recovery code, passkeys and personal API tokens."}, }
{Path: "/org", Label: "Organisation", Description: "Members, identities, connections, models and automation."}, out := make([]DashboardPage, 0, len(catalogue))
{Path: "/org/members", Label: "Members", Description: "People in the organisation and their roles."}, for _, p := range catalogue {
{Path: "/org/agents", Label: "Agents", Description: "Execution identities, their permissions and commit author."}, out = append(out, DashboardPage{Path: p.Path, Label: p.Label, Description: p.Description})
{Path: "/org/workspaces", Label: "Workspaces", Description: "Groups of organisation work and resources."}, }
{Path: "/org/policies", Label: "Policies", Description: "Access rules for the organisation."}, return out, nil
{Path: "/org/connections", Label: "Connections", Description: "Forge hosts, credentials and permitted operations."},
{Path: "/org/credential-bindings", Label: "Credential bindings", Description: "Service credentials granted to agent identities."},
{Path: "/org/models", Label: "Models", Description: "Organisation providers and model aliases."},
{Path: "/org/instructions", Label: "Instructions", Description: "Archie's identity, tone and standing instructions for the organisation."},
{Path: "/org/playbooks", Label: "Playbooks", Description: "Edit event-driven automation rules."},
{Path: "/settings/authentication", Label: "Authentication", Description: "Instance URL and OIDC sign-in."},
{Path: "/workflows", Label: "Workflows", Description: "Workflows and run history."},
{Path: "/settings/skills", Label: "Skills", Description: "Skills Archie can activate."},
{Path: "/settings/curators", Label: "Curators", Description: "Scheduled memory and capture curation."},
{Path: "/events", Label: "Events", Description: "Captured events, field mappings, workflow bindings."},
{Path: "/logs", Label: "Logs", Description: "Daemon log by level and component."},
{Path: "/org/channels", Label: "Channels", Description: "Chat and notification channels."},
{Path: "/settings/status", Label: "Status", Description: "Update state, config sources, listen address."},
{Path: "/account/appearance", Label: "Appearance", Description: "Theme, density, motion."},
{Path: "/settings/task-execution", Label: "Task execution", Description: "Statuses, operator actions, budgets."},
{Path: "/settings/models", Label: "Models", Description: "Instance model aliases and providers."},
{Path: "/org/repositories", Label: "Repositories", Description: "Watched repositories and gate overrides."},
{Path: "/org/scheduling-policy", Label: "Scheduling policy", Description: "Work discovery and forge labels."},
{Path: "/settings/tools", Label: "Tools & MCP", Description: "Agent tools and MCP servers."},
{Path: "/org/audit", Label: "Audit", Description: "Settings, access, identity and runtime events."},
{Path: "/org/denials", Label: "Denials", Description: "Access requests the policy chain refused, newest first."},
{Path: "/settings/plugins", Label: "Plugins", Description: "Extension directories loaded at startup."},
{Path: "/settings/secret-engines", Label: "Secret engines"},
{Path: "/settings/container-runtime", Label: "Container runtime"},
{Path: "/settings/agent-profiles", Label: "Agent profiles", Description: "Execution profiles: the image and tools each agent runs with."},
}
// DashboardPages returns a copy of the dashboard page registry.
func DashboardPages() []DashboardPage {
out := make([]DashboardPage, len(dashboardPages))
copy(out, dashboardPages)
return out
} }
// PageIndexResult is what page_index returns: the full list of dashboard pages // PageIndexResult is what page_index returns: the full list of dashboard pages
@@ -84,7 +55,11 @@ func pageIndexTool() (tools.ToolEntry, bool) {
Description: "List every dashboard page, what it shows, and built-in guidance for creating workflows and using Archie. Use it to tell the operator where to go for something rather than guessing.", Description: "List every dashboard page, what it shows, and built-in guidance for creating workflows and using Archie. Use it to tell the operator where to go for something rather than guessing.",
Classification: tools.ClassIdempotent, Classification: tools.ClassIdempotent,
Handler: func(_ context.Context, _ map[string]any) (any, error) { Handler: func(_ context.Context, _ map[string]any) (any, error) {
return PageIndexResult{Pages: DashboardPages(), ProductGuide: prompts.ProductGuide()}, nil indexed, err := DashboardPages()
if err != nil {
return nil, err
}
return PageIndexResult{Pages: indexed, ProductGuide: prompts.ProductGuide()}, nil
}, },
} }
return entry, true return entry, true
@@ -114,7 +89,11 @@ func dashboardNavigateTool() (tools.ToolEntry, bool) {
if path == "" { if path == "" {
return nil, errors.New("dashboard_navigate: path is required") return nil, errors.New("dashboard_navigate: path is required")
} }
for _, p := range dashboardPages { indexed, err := DashboardPages()
if err != nil {
return nil, err
}
for _, p := range indexed {
if p.Path == path { if p.Path == path {
return DashboardNavigateResult{Path: p.Path, Label: p.Label}, nil return DashboardNavigateResult{Path: p.Path, Label: p.Label}, nil
} }
+8 -8
View File
@@ -52,7 +52,7 @@ type LLMStreamResponder func(ctx context.Context, in Inbound, stream TurnStream)
// ModelManager provides access to available models and allows switching the // ModelManager provides access to available models and allows switching the
// active LLM model. The daemon supplies an implementation backed by its // active LLM model. The daemon supplies an implementation backed by its
// runtime provider catalog. When nil on a Router, /model returns a // runtime provider catalogue. When nil on a Router, /model returns a
// "not configured" message. // "not configured" message.
type ModelManager interface { type ModelManager interface {
ModelsFor(ctx context.Context) ([]string, error) ModelsFor(ctx context.Context) ([]string, error)
@@ -61,11 +61,11 @@ type ModelManager interface {
SetActiveModel(ctx context.Context, selection string) error SetActiveModel(ctx context.Context, selection string) error
} }
// ModelDetails is the catalog metadata rendered after an interactive model // ModelDetails is the catalogue metadata rendered after an interactive model
// selection. Limits are zero when the upstream catalog does not publish them. // selection. Limits are zero when the upstream catalogue does not publish them.
type ModelDetails = messaging.ModelDetails type ModelDetails = messaging.ModelDetails
// DetailedModelManager is the optional catalog-aware extension used by rich // DetailedModelManager is the optional catalogue-aware extension used by rich
// model selectors. Runtime routing remains on ModelManager. // model selectors. Runtime routing remains on ModelManager.
type DetailedModelManager interface { type DetailedModelManager interface {
ModelManager ModelManager
@@ -300,8 +300,8 @@ func (r *Router) route(ctx context.Context, in Inbound) (string, error) {
return reply, err return reply, err
} }
// dispatchLocal handles recognized local commands. Returns (reply, // dispatchLocal handles recognised local commands. Returns (reply,
// true) when the command was recognized and handled. // true) when the command was recognised and handled.
func (r *Router) dispatchLocal(ctx context.Context, msg messaging.Message, platform, text, cmd string) (string, bool, error) { func (r *Router) dispatchLocal(ctx context.Context, msg messaging.Message, platform, text, cmd string) (string, bool, error) {
rest := restAfter(text, cmd, r.gatewayName) rest := restAfter(text, cmd, r.gatewayName)
@@ -344,7 +344,7 @@ func (r *Router) dispatchLocal(ctx context.Context, msg messaging.Message, platf
return r.dispatchLocalMisc(ctx, msg, platform, cmd, rest) return r.dispatchLocalMisc(ctx, msg, platform, cmd, rest)
} }
// dispatchLocalMisc handles the remaining recognized local commands not // dispatchLocalMisc handles the remaining recognised local commands not
// covered by dispatchLocal's first switch. Split out to keep cyclomatic // covered by dispatchLocal's first switch. Split out to keep cyclomatic
// complexity down. // complexity down.
func (r *Router) dispatchLocalMisc(ctx context.Context, msg messaging.Message, platform, cmd, rest string) (string, bool, error) { func (r *Router) dispatchLocalMisc(ctx context.Context, msg messaging.Message, platform, cmd, rest string) (string, bool, error) {
@@ -861,7 +861,7 @@ func formatStatus(ctx context.Context, counts map[string]int, report HealthRepor
return b.String() return b.String()
} }
// formatQueueDepth summarizes in-flight work as one line: how many tasks // formatQueueDepth summarises in-flight work as one line: how many tasks
// are running, waiting on a human reply, or parked. Queued and terminal // are running, waiting on a human reply, or parked. Queued and terminal
// states are excluded -- neither is a health concern an operator needs // states are excluded -- neither is a health concern an operator needs
// /status to surface. // /status to surface.
+3 -3
View File
@@ -18,7 +18,7 @@ const (
defaultSessionListLimit = 20 defaultSessionListLimit = 20
// maxSessionListLimit bounds what the model can ask for. A chat that has // maxSessionListLimit bounds what the model can ask for. A chat that has
// churned for months could otherwise land its whole session catalog in the // churned for months could otherwise land its whole session catalogue in the
// context window whole. // context window whole.
maxSessionListLimit = 100 maxSessionListLimit = 100
@@ -120,7 +120,7 @@ func sessionListTool(store SessionStore, platform, channelID string) tools.ToolE
if len(all) > limit { if len(all) > limit {
all = all[:limit] all = all[:limit]
} }
// Non-nil even when empty: an empty catalog is an answer, and a // Non-nil even when empty: an empty catalogue is an answer, and a
// null would read to the model as a failed call worth retrying. // null would read to the model as a failed call worth retrying.
sessions := make([]ChatSessionEntry, 0, len(all)) sessions := make([]ChatSessionEntry, 0, len(all))
for _, s := range all { for _, s := range all {
@@ -361,7 +361,7 @@ func sessionTranscriptTool(store SessionStore, platform, channelID string) tools
return nil, fmt.Errorf("session_transcript: %w", err) return nil, fmt.Errorf("session_transcript: %w", err)
} }
// Serialize to JSON // Serialise to JSON
data, err := json.MarshalIndent(messages, "", " ") data, err := json.MarshalIndent(messages, "", " ")
if err != nil { if err != nil {
return nil, fmt.Errorf("session_transcript: %w", err) return nil, fmt.Errorf("session_transcript: %w", err)
+1 -1
View File
@@ -95,7 +95,7 @@ func splitOwnerRepo(s string) (owner, repo string, ok bool) {
} }
// ChatTaskStatus is the minimal task state StoreTaskController needs to // ChatTaskStatus is the minimal task state StoreTaskController needs to
// authorize and validate /approve and /cancel. // authorise and validate /approve and /cancel.
type ChatTaskStatus struct { type ChatTaskStatus struct {
Status string Status string
Identity string Identity string
+5 -5
View File
@@ -20,7 +20,7 @@ type TurnPrepareContext struct {
Model string Model string
Extra []tools.ToolEntry Extra []tools.ToolEntry
ContextWindow int ContextWindow int
// Reasoning reports the catalog's class for the active model. It rides // Reasoning reports the catalogue's class for the active model. It rides
// the prepare context because the seam that translates a provider-neutral // the prepare context because the seam that translates a provider-neutral
// request into provider options is the only place that knows the wire // request into provider options is the only place that knows the wire
// parameter differs by class. // parameter differs by class.
@@ -115,10 +115,10 @@ type TurnRunnerConfig struct {
// in prepareTurn. Nil disables the <memory> block entirely (renderMemory // in prepareTurn. Nil disables the <memory> block entirely (renderMemory
// treats a nil store the same as a failed read). // treats a nil store the same as a failed read).
MemoryEngine MemoryStore MemoryEngine MemoryStore
// MemoryWriter is the write surface the per-turn memory tool (slice 4) // MemoryWriter is the write surface the per-turn memory tools use to
// uses to build memory_create/memory_update/memory_delete/memory_list. // build memory_create/memory_update/memory_delete/memory_list. Nil omits
// Nil omits those tools entirely (MemoryTools treats a nil store the // those tools entirely (MemoryTools treats a nil store the same as a
// same as a subject with no writable scope: no tools registered). // subject with no writable scope: no tools registered).
MemoryWriter MemoryWriteStore MemoryWriter MemoryWriteStore
// UserIdentity resolves the sending user's identity for an inbound message. // UserIdentity resolves the sending user's identity for an inbound message.
// False or nil means no per-user memory scope. // False or nil means no per-user memory scope.
+3 -3
View File
@@ -22,9 +22,9 @@ const memoryRecordsPerScope = 20
const memoryBlockByteCap = 8192 const memoryBlockByteCap = 8192
// MemoryStore is the read surface prepareTurn needs from a memory engine: a // MemoryStore is the read surface prepareTurn needs from a memory engine: a
// scope-only Query, nothing else. Narrowed from domainmemory.Store (which // scope-only Query, nothing else. It is narrowed from domainmemory.Store, which
// also carries the write operations slice 4 uses) so this package's read // also carries the write operations, so this package's read path cannot
// path cannot accidentally reach for Create/Update/Forget. // accidentally reach for Create/Update/Forget.
type MemoryStore interface { type MemoryStore interface {
Query(ctx context.Context, q domainmemory.Query) ([]domainmemory.Record, error) Query(ctx context.Context, q domainmemory.Query) ([]domainmemory.Record, error)
} }
@@ -95,7 +95,7 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Resolved before the delivery check so the check runs against the // Resolved before the delivery check so the check runs against the
// source's owning org, not always the default org. An unknown source // source's owning org, not always the default org. An unknown source
// authorizes as the default org. // authorises as the default org.
src := rc.resolveSource(r, path) src := rc.resolveSource(r, path)
if code := rc.refusal(r, path, orgOf(src)); code != 0 { if code := rc.refusal(r, path, orgOf(src)); code != 0 {
@@ -191,7 +191,7 @@ func (rc *Receiver) refusal(r *http.Request, path string, owner org.OrgID) int {
} }
// orgOf reports the org that owns src, or the default org when the source // orgOf reports the org that owns src, or the default org when the source
// is unknown: an unknown source has no owner to authorize against. // is unknown: an unknown source has no owner to authorise against.
func orgOf(src *source.Source) org.OrgID { func orgOf(src *source.Source) org.OrgID {
if src == nil || src.OrgID == "" { if src == nil || src.OrgID == "" {
return org.DefaultOrgID return org.DefaultOrgID
@@ -91,7 +91,7 @@ func foldOverrides(cfg reflect.Value, doc map[string]any) (map[string]any, error
} }
// foldMapEntries returns one map field's override with each entry the overlay // foldMapEntries returns one map field's override with each entry the overlay
// names carried forward from the entry of the same key in cfg. // names carried forward from the cfg entry with the same key.
func foldMapEntries(field reflect.Value, doc map[string]any) (map[string]any, error) { func foldMapEntries(field reflect.Value, doc map[string]any) (map[string]any, error) {
if field.IsNil() || field.Type().Key().Kind() != reflect.String { if field.IsNil() || field.Type().Key().Kind() != reflect.String {
return doc, nil return doc, nil
@@ -26,7 +26,6 @@ const (
defaultContainerUptime = 5 * time.Hour defaultContainerUptime = 5 * time.Hour
defaultVolumeTTL = 72 * time.Hour defaultVolumeTTL = 72 * time.Hour
defaultPullPolicy = "missing" defaultPullPolicy = "missing"
defaultContainerImage = "git.catlow.cloud/sam/archie-agent:latest"
// defaultMaxResultChars bounds one tool result. // defaultMaxResultChars bounds one tool result.
defaultMaxResultChars = 50_000 defaultMaxResultChars = 50_000
@@ -322,12 +321,11 @@ func DefaultBotEmail(forgeType, user, email string) string {
return email return email
} }
// applyContainerDefaults makes managed task workers usable without an explicit // applyContainerDefaults fills the optional [containers] values. There is
// [containers] section. A negative VolumeTTL is left for validation to reject. // deliberately no default image: validateContainers reports a missing
// containers.image at startup instead of pointing task workers at one
// registry. A negative VolumeTTL is left for validation to reject.
func applyContainerDefaults(cfg *config.Config) { func applyContainerDefaults(cfg *config.Config) {
if cfg.Containers.Image == "" {
cfg.Containers.Image = defaultContainerImage
}
if cfg.Containers.MaxUptime == 0 { if cfg.Containers.MaxUptime == 0 {
cfg.Containers.MaxUptime = config.Duration(defaultContainerUptime) cfg.Containers.MaxUptime = config.Duration(defaultContainerUptime)
} }
Loaded 100 of 646 files, more files were not shown because too many files have changed in this diff. Show more