Compare commits

...
248 Commits
Author SHA1 Message Date
sam b4931be894 docs: track issues on the archie-platform GitHub organisation 2026-11-28 14:14:43 +11:00
sam 099ce3fcaa feat(deploy): run the dashboard as its own workload behind path routing 2026-11-28 14:12:17 +11:00
sam 378560175f refactor(archie,webui,gateway): remove the dashboard, which now ships from archie-frontend 2026-11-28 14:12:17 +11:00
sam 47ad825bfa fix(chat): check dashboard links by shape, not the page catalogue 2026-11-28 13:44:26 +11:00
sam 9df6813d1a docs(enterprise): move the readiness plan to private docs 2026-11-28 13:34:57 +11:00
sam 56f1356d75 refactor(archie,system): remove runtime config writes and finish track 1 (#2153) 2026-11-28 11:33:13 +11:00
sam 3107a9fbe3 fix(telemetry,ui): preserve http.Flusher for SSE and stop polling missing runs 2026-11-28 01:57:04 +11:00
sam 5505bef5ee docs: resolve Vale prose and spelling findings 2026-11-28 01:32:50 +11:00
sam 59d85e197f feat(ui): add enterprise auth, audit log, four-eyes SoD, and promotion bundles UI (#2153) 2026-11-28 00:58:01 +11:00
sam d0d79cbf91 feat(audit,approvals,deliveries): wire audit producers, ITSM change requests, and fix Dockerfile.archie (#2153) 2026-11-28 00:42:37 +11:00
sam fdfcbab4bd feat(catalogue,helm,ci): add private OCI auth, offline catalogue mirror, CI image/SBOM, metrics config, and OpenShift overlay (#2153) 2026-11-27 22:13:30 +11:00
sam dd38d93a29 feat(archie): wire enterprise rekey, OIDC/SoD, audit, telemetry, and bundles (#2153, #2154, #2155, #2156, #2157, #2158) 2026-11-27 21:20:33 +11:00
sam 07d30c95ca Merge branch 'swarm/oidc-sod' 2026-11-27 21:14:37 +11:00
sam 0999b7d84d feat(governance,approvals): add enterprise OIDC controls and four-eyes SoD (#2155) 2026-11-27 21:13:52 +11:00
sam 6bc78bdce8 Merge branch 'swarm/bundles' 2026-11-27 21:12:13 +11:00
sam 16abc47613 feat(archie): add declarative multi-stage promotion bundles (#2157) 2026-11-27 21:11:28 +11:00
sam 81278b37e3 Merge branches 'swarm/rekey', 'swarm/audit-otel' and 'swarm/helm-docs' 2026-11-27 21:08:07 +11:00
sam 571254dbf7 docs,deploy(enterprise): add Helm chart, hardened Compose, and enterprise runbooks (#2158) 2026-11-27 21:07:25 +11:00
sam 5c3b0b9714 feat(audit,telemetry): add append-only audit module, OTel tracing, and /metrics (#2156) 2026-11-27 21:06:32 +11:00
sam e80b18208e feat(connectors): pick a local or remote runtime for every extension
Track 2 of the enterprise readiness plan. Extensions now start through a
Runtime: RemoteGRPCRuntime dials an endpoint the operator mapped, over mTLS for
TCP, and LocalNamespaceRuntime runs the verified binary in its own user and
network namespace. A mapped endpoint is the only runtime that may serve that
extension, so a broken endpoint refuses instead of quietly falling back to a
subprocess.

Local availability is checked instead of assumed: user and network namespace
limits read from /proc/sys/user report a stage that disabled them, which is what
restricted Pod Security Standards and hardened kernels do. A host where the
chosen runtime cannot run refuses the extension and names why both runtimes
declined, so the operator learns to configure a remote endpoint.
2026-11-27 21:04:49 +11:00
sam efd71ff71f feat(archie): add age sealing key rotation (#2154) 2026-11-27 21:04:21 +11:00
sam 47e8db7453 feat(archie): add headless bootstrap command and remote extension wiring 2026-11-27 20:51:52 +11:00
sam 6791125aab feat(connectors): add remote gRPC mTLS runtime and default catalogue override 2026-11-27 20:51:52 +11:00
sam 86b89a5957 feat(archie): add container runtime, migrate command, secret files, and proxy egress 2026-11-27 20:36:52 +11:00
sam 7630a14705 docs(enterprise): lock in v1 and v2 enterprise readiness decisions 2026-11-27 20:36:52 +11:00
sam cb6e2a039c docs(enterprise): add enterprise readiness design and plan 2026-11-27 20:11:15 +11:00
sam 95ce309b3a fix(connectors): leave a package with no declared egress on the host's network
Confining it was pointless: the relay the namespace exists for is only started
when egress is non-empty, so the package got loopback and a proxy address
nothing served. Any client honouring the proxy variables then reported a dial
refused at the relay rather than reaching the host it was configured for.

Fixes #2152.
2026-11-27 20:06:45 +11:00
sam 34482c8b0c fix(dashboard): re-read on the live stream instead of polling
Every view listing runs or approvals polled on a timer: the home page made
four requests every five seconds per open tab, two of them the same run list,
and the needs-attention card asked for 200 runs to render five.

A run or an approval request moving is now published on the hub and framed on
the dashboard stream, so those views re-read on the change. A reconnect still
re-reads everything, and the hub drops a reader that falls behind, which ends
its stream and reconnects it.
2026-11-27 19:44:21 +11:00
sam ace8c1be44 chore(deploy): wire the age secret engine into the staging stack
The engine reads AGE_FILE and AGE_IDENTITY from its environment, so the
compose file names both paths in the mounted state directory and the deploy
creates the identity when the host has age-keygen.
2026-11-27 19:42:20 +11:00
sam bf17e2471b fix(ui): stop offering an organisation the binary cannot create (#2150)
The organisations page could create one, and POST /api/orgs is not served: the
binary resolves a single organisation from the credential. The dialog and the
client method go, and the page lists what exists.

The gateway test missed it because it compared paths, not methods. It now reads
each request the client makes with the method it asks for, so a call to a path
the binary serves for another verb fails the gate.
2026-11-27 19:40:21 +11:00
sam 61d486fdc0 fix(ui): count what needs a person from served reads (#2145)
The shell's attention badge counted the task board's summary, which the binary
does not serve, so #2121 removed the badge with the board and nothing said, on
every page, how much work waits on a person.

The count now comes from the two operations that answer it: pending approval
requests and parked runs. The rule lives in ui/src/lib/needs-attention.ts, so
the dashboard's list and the shell's badge agree on what waiting means, and the
count is read through a small store so both read it once.
2026-11-27 19:37:46 +11:00
sam 77e291fdfc fix(governance): report only the dashboard sections that exist (#2147)
#2121 removed the pages behind sixteen sections and both capability handlers
still named them, so GET /api/capabilities advertised sections nothing can
render and the old service probed for pages that are gone.

The single binary now reports an organisation as unavailable (its page exists,
its writes do not) and lists nothing else it has no page for; the old service
reports only the sections and probes its pages still make.
2026-11-27 19:35:01 +11:00
sam 6a25153659 docs(vale): reject em dashes, and remove the ones on the tree (#2149)
AGENTS.md forbids em dashes in prose, comments and user-facing strings, and
nothing checked it: Google.EmDash only flags a dash with a space on both sides,
so a bare U+2014 passed.

Archie.EmDash rejects U+2014 for Markdown, templates and Go, with a message
naming the alternatives. The 40 occurrences it finds are rewritten as a comma,
a colon, brackets or a second sentence, and scratch trees are out of scope so a
run over the repository reports on what the repository holds.
2026-11-27 19:33:06 +11:00
sam 15efad9ad7 fix(ui): render system identity as System in UserReference 2026-11-27 19:28:48 +11:00
sam fa96ee852c fix(governance): refuse to delete a model alias a saved workflow names (#2097)
The delete refused only a missing alias, so removing the default model, or an
alias a saved workflow still names, succeeded and those workflows failed at
their agent step.

The runs module now reports the saved workflows that give an agent step a
model, treating a step that names none as the default, and the delete is
refused with a conflict that names them. The dashboard already shows a delete's
failure inline beside the alias, so the operator sees which workflows to move
first.
2026-11-27 19:28:13 +11:00
sam a101b64703 fix(runs): a cancelled run's trail records who stopped it (#2100)
Cancelling a run moved it and the runs it called to cancelled and wrote nothing
to either trail, so a stopped run could not say when it stopped or who asked.

The stop now returns the runs it stopped and records one cancel entry on each,
in the same transaction, naming the principal that asked. The entry is a step
named cancel with the caller's identity, so the run detail shows it with the
rest of the trail.
2026-11-27 19:24:19 +11:00
sam 5e53e8ec0e fix(ui): keep the tab title until the route resolves (#2115)
Opening a page by URL showed "Page not found" in the tab while the router was
still at its start location, which carries no label, so the not-found copy
stood in for the page for as long as the resolution took.

The title is now written only once the router has resolved the address, and the
rule lives in ui/src/lib/page-title.ts so the start location's silence is
tested.
2026-11-27 19:21:04 +11:00
sam 65cd993ee6 fix(events): keep a mapped number's exact text (#2118)
The payload was decoded into float64, so an integer id past 2^53 was rounded
before it reached the run: the event named one record and the run acted on the
one next to it.

The mapping now decodes with json.Number, which marshals back as the exact
digits the event carried, and the type check accepts it for a number field.
2026-11-27 19:18:21 +11:00
sam 27cd2d0df1 fix(memory): reach every note a person may read (#2141)
maxNotes bounds what a conversation is given, and it was also the only bound on
the inspection read a person makes and on the shared list, so past 200 notes of
one class the oldest ones were unreachable, with no total and no offset to say
the list had been cut.

The conversation read keeps the bound. The read of a person's own notes and the
shared list pass no bound, which the store reads as LIMIT NULL, so both reach
everything the caller may read.
2026-11-27 19:16:08 +11:00
sam f1c595d39b fix(ui): name only the pages the sidebars can open (#2148)
Removing the old services' pages left their entries in the sidebar specs, and a
nav entry with no route threw during the first render, so the shell drew
nothing and every page was blank. The chat browser test caught it, which is
the failure #2148 recorded; it passes again.

The spec list moves to ui/src/lib/nav-specs.ts, which imports nothing, so a
test can check every address it names against the generated page catalogue.
That is the guard: deleting a page without updating the sidebars now fails
the gate instead of the browser.
2026-11-27 19:13:33 +11:00
sam 5cc59c31c6 fix(ui): edit the approvals that earn an autonomy proposal (#2124)
propose_autonomy_after is part of the organisation settings but the approvals
page had no control for it, so the value could only be read and changed through
the API, against the rule that every setting is editable in the dashboard.

The page now edits it within the 1 to 100 the server accepts and shows the
saved value after saving. The draft and the save body live in a page-local
module so the shape of a save is tested without a browser.
2026-11-27 19:10:16 +11:00
sam 35688b449a fix(governance): invite a member by email without an identity provider (#2110)
Adding a member by email refused with a 409 whenever no OIDC issuer was set,
so an install with local accounts only could not invite anyone by address.

An address now reserves the identity under a local issuer instead, and a local
account made with that address adopts it: the invitation's roles carry over and
the organisation shows one member, not two. A provider subject still needs the
provider that asserts it, and the refusal says so.
2026-11-27 19:08:08 +11:00
sam ea6385879f fix(ui): stop calling operations the binary does not serve (#2121)
The dashboard is embedded in the single binary, which serves api/openapi.yaml.
It was still calling the old services' routes, so pages that read them answered
with a not-found: the task board, its activity feed and setup panel, logs,
alerts, audit and its export, bindings, schedules, channels, repositories,
skills, curators, the control-plane settings pages, identities and org agents,
the org switcher, secret-reference checks, task metadata, and the audit, usage,
summary and version reads.

Each of those surfaces is removed, and a test compares every /api path in the
dashboard's source with api/openapi.yaml so the next one fails the gate
instead of the browser. Settings that the binary does serve (model providers,
instructions, policies, members) keep their pages.
2026-11-27 19:03:02 +11:00
sam a23417f392 docs(agents): prompts live in internal/platform/prompts
The five module files that read prompts already use internal/platform/prompts, and modules may only reach internal/platform. The old internal/prompts serves the six services until they go.
2026-11-27 18:31:33 +11:00
sam db2cfe172e Merge pull request '2069 scoped chat memory' (#2142) from 2069-scoped-chat-memory into main
Reviewed-on: #2142
2026-11-27 07:29:06 +00:00
sam 79be5aad96 fix(webui): hide the memory pages this process cannot serve (#2069)
Quality / check (pull_request) Successful in 3m7s
The dashboard is served by both binaries, and internal/webui serves no
/api/memory route. Reporting the memory sections as unavailable drops both pages
from the navigation there instead of offering pages whose every read and write
answers not found.
2026-11-27 18:25:20 +11:00
sam aa3568dd52 fix(memory): refuse a credential written out in prose (#2069)
A note saying "the deploy token is 1234567890abcdef" was neither redacted nor
refused, because the credential check only recognised a value after a colon or
an equals sign. The copula now counts as the separator, so a credential written
out in a sentence is refused the way an assignment is.

The version read is scoped to the organisation as every other note read is, so a
note id from another organisation answers nothing, and the doc comments on
Forget and Revoke describe the order the code actually commits in. The
deletion-recording schema constant had no consumer and is removed.
2026-11-27 18:25:20 +11:00
sam 368d484410 test(memory): cover the shared half of the read boundary (#2069)
The fake's Notes filter modelled only the owner half of store.Notes, so a
regression that stopped sharing published notes would still pass. It now mirrors
the statement, and the test asserts a published note reaches both people, a
proposal reaches neither, and a disabled note is left out of a conversation read.
2026-11-27 18:19:33 +11:00
sam 9b8de57a33 refactor(ui): colocate Events files and split Extensions into nested routes 2026-11-27 17:08:31 +11:00
sam 6356aa5d52 feat(api): filter lists by sys_query
sys_query is conditions joined by ^, each field=value, field!=value or fieldLIKEtext. A bad condition or a field a list does not offer is a 400 naming the fields it accepts, so a typo never reads as an empty page. Runs, workflows, proposals, guards and action types take it, and the dashboard keeps the filter in the URL so a filtered list is a link.

The guard control API is list-guard-controls at /api/controls/guards: list-guards belongs to the connectors extension list, and the resource is a guard. JudgeStanding keeps its name, since it is the model judgement a guard recorded.
2026-11-27 17:06:30 +11:00
sam 6a3bf1e200 refactor(ui): split Events tabs into nested file-based routes 2026-11-27 16:45:42 +11:00
sam a8628de625 fix(ui): merge folder parent routes so nav shows labels; drop dead legacy redirects 2026-11-27 16:38:02 +11:00
sam 0d267170c6 refactor(ui): add page layout system under src/layouts 2026-11-27 16:34:05 +11:00
sam ccb36a1ca9 refactor(ui): drive sidebar and topbar breadcrumbs from file-based routes 2026-11-27 16:32:06 +11:00
sam 936c5267f0 refactor(ui): adopt vue-router file-based routing under src/pages 2026-11-27 16:29:38 +11:00
sam 1e105ff4c8 Merge pull request 'Staging/ui regressions' (#2134) from staging/ui-regressions into main
Reviewed-on: #2134
2026-11-27 05:03:28 +00:00
sam 2e9d14412e fix(ui): keep proposals visible during background refresh
Quality / check (pull_request) Successful in 3m9s
(cherry picked from commit 7334f659fd14f68186f009279dc6cda4c4cd56fd)
2026-11-27 15:59:18 +11:00
sam f6eff43ca4 fix(ui): restore staged review for models and instructions
Apply reviewed edits through the module APIs one request at a time. Keep failed and untouched drafts for retry, and remove successful edits from the review.

(cherry picked from commit 952215e36325b76f6e3364d713263f502acf6d02)
2026-11-27 15:51:34 +11:00
sam a2141ed4bb fix(ui): let settings saves recover from version conflicts
Keep the conflict visible after reloading the resource so the draft rebases onto the latest version. Require another Save to submit it, and keep the draft against its original version if the refresh fails.

(cherry picked from commit 0d4b63c906363c4343e8f8a8f4163c96b0c3378f)
2026-11-27 15:51:34 +11:00
sam 90e58a67e9 fix(ui): link user attribution to member records
(cherry picked from commit d30901653a181041b2424389baceb056f16ec7c9)
2026-11-27 15:51:34 +11:00
sam 5dc5dbbafc fix(ui): preserve modal focus rings and discard policy drafts
(cherry picked from commit a2eff9938d1d2c22c16e73f790a7c32f9c150a23)
2026-11-27 15:51:34 +11:00
sam 74deeb74d5 Merge pull request 'fix(ui): preview extensions and modal-edit policies' (#2133) from fix/ui-screen-consistency into main
Reviewed-on: #2133
2026-11-27 02:57:57 +00:00
sam 3afc693063 fix(ui): preview extensions and modal-edit policies
Quality / check (pull_request) Successful in 3m0s
2026-11-27 13:47:40 +11:00
sam 2794416272 Merge pull request 'fix(ui): include base URL when creating providers' (#2132) from fix/provider-url-input into main
Reviewed-on: #2132
2026-11-27 01:44:04 +00:00
sam 21980f9ced fix(ui): include base URL when creating providers
Quality / check (pull_request) Successful in 3m2s
2026-11-27 05:17:07 +11:00
sam 08988692c1 docs: standardise british spellings in ui docs 2026-11-27 03:14:53 +11:00
sam 6b4ff8101a fix(governance): ask for the public URL during owner setup (#2076) 2026-11-27 02:33:15 +11:00
sam 24a3efcf60 fix(connectors): keep published settings and let admins reset the catalogue (#2119) 2026-11-27 02:29:39 +11:00
sam bc4ac4436d docs(connectors): clarify catalogue and guard comments (#2119) 2026-11-27 02:21:13 +11:00
sam c538017523 fix(connectors): verify the default catalogue and roll back failed updates (#2119)
Adapt OCI reads from internal/infrastructure/signedoci and internal/infrastructure/storepkg. Keep the legacy readers while their callers still use them.
2026-11-27 02:19:21 +11:00
sam 2ea0062bef feat(ui,judgement,system): unify nav, surface built-in guards, readiness and decision reasoning 2026-11-27 02:13:28 +11:00
sam 5dc2d79fdb Merge pull request 'fix(events): scope mappings to source owners' (#2131) from fix/events-private-source-mapping-visibility into main
Reviewed-on: #2131
2026-11-26 10:49:47 +00:00
sam f0f09e9189 fix(events): enforce source ownership for mappings
Quality / check (pull_request) Successful in 10m21s
2026-11-26 20:35:40 +11:00
sam 8bf3ace96b feat(governance,chat): size a model's chat history by its own window (#2018)
The replay budget was fixed at half of an assumed 128k window, so a small
local model was still handed more history than it accepts.

A model now carries the context window and output limit the published
catalogue gives it, read once into the state directory and cached on
disk. Chat holds its replay to the window minus the reply and an eighth
for the system prompt and tools, and keeps the assumed budget only for a
model the catalogue publishes nothing about.
2026-11-26 04:20:11 +11:00
sam 8dd28b90be feat(chat): hold a long conversation inside the model's window (#2018)
A reply was replayed with a fixed twenty earlier turns, so a long
conversation either lost its older context or, with large replies, sent
more than the model accepts and failed the request. The replay now reads
up to two hundred turns and replaces the middle of what it cannot carry
with one summary message, keeping the newest twenty messages and always
the question being answered.

Carried from internal/gateway's compression.go before that package is
retired: the same conservative token estimate (four ASCII characters or
one non-ASCII rune), the same 50%-of-window budget, and a summary that
says what was dropped. The budget is fixed rather than derived from the
model because the module is told a model's name and nothing about its
window.
2026-11-26 04:17:16 +11:00
sam e4663c22c0 fix(ui/events): frame the Map and Bind steps as cards
Both steps drew their actions in a bare row above a bare empty state, so
they looked like nothing else on the page. Each is now one card with its
actions in the header, and the Installed playbooks link is a button
rather than a stray underline beside one.
2026-11-26 03:47:57 +11:00
sam fa4a078a34 fix(ui/settings): filter packages in place instead of remounting
The list was keyed on the active kind, so every switch remounted it and
showed its skeleton before the same packages came back. The rows are
already filtered from one read, so the keys only threw work away.
2026-11-26 03:47:57 +11:00
sam f27317738d fix(ui/events): mount every step so switching shows no loading state
KeepAlive removed the skeleton on a revisit but not on a first visit, so
tabbing through the steps still flashed. Every panel now mounts when the
page opens and only the active one is on screen, so a switch shows what
was already read. The wrapper is a single element because a panel whose
template is a fragment cannot be hidden with v-show.

usePoll goes back to reading only document.hidden, since nothing is kept
alive and deactivated any more.
2026-11-26 03:47:57 +11:00
sam a7686042e5 fix(ui/dashboard): filter recent runs with tabs
Every other list that switches between a few states uses Tabs, such as
Proposals. Recent Runs was the only one built from ToggleGroup, which is
a form choice elsewhere.
2026-11-26 01:59:32 +11:00
sam bc031880bf fix(ui/events): keep the open step alive across tab switches
Each switch remounted the panel under `<component :is>`'s key, so it
started with no data and showed its skeleton before the read landed.
KeepAlive keeps every visited step mounted, so returning shows what it
already read. A step that is only polled (Events) pauses while hidden.
2026-11-26 01:59:29 +11:00
sam eb7d852567 refactor(ui/chat): remove chat features the server never sends
The dashboard talks only to the modules/chat API, which sends no slash
commands, model list, voice support, attachments or any question other
than an approval, so the UI built on those could never appear:

- the slash command menu, Retry, Undo, Branch and Preview compression in
  the More menu, and the /model, /update and /new handling
- the model picker, the update card and the api.update* calls
- voice recording and the task tags nothing ever added
- the questionnaire, picker and clarify cards, and the "Always this
  session" answer, so components/ui/questionnaire loses its last user
- channel.ts, command-scroll.ts and turn.ts, which nothing imported
- the old dock-storage migration and the second capitalised spelling of
  message and tool fields

Tasks are gone from the binary too, so chat links and prompts speak of
runs: the #N task-link step in the markdown renderer goes, since an agent
already links pages through dashboard_navigate.

state.ts keeps the shared state and actions; types.ts, stream.ts,
transcript.ts, escape.ts and dock-window.ts hold the types, the stream
reader, turn-to-message building, Escape layers and the dock's pointer
and keyboard handling. ChatDock.vue drops from 560 lines to 307.
2026-11-26 01:59:26 +11:00
sam 8c9c19efb0 chore(ui/accounts): tighten account page copy per Vale 2026-11-26 00:03:20 +11:00
sam cd8fad1b66 fix(ui/accounts): fill password input column flush with submit button 2026-11-25 23:55:28 +11:00
sam 2d83b50837 fix(ui/accounts): fix welcome banner wrapping and unify account section layout 2026-11-25 23:34:16 +11:00
sam 4b399e44aa fix(ui/chat): fix dock drag/resize bounds and dynamic slash command loader 2026-11-25 23:34:16 +11:00
sam 7904ccdfe0 fix(ui/chat): wrap TokenInput children in flex row and fix placeholder 2026-11-25 23:06:46 +11:00
sam 56dbb31923 build(dev,chat): point dev server at archie and wire chat pages catalogue 2026-11-25 23:05:04 +11:00
sam 74a560533e feat(ui): integrate @ui-sdk for schedules, chat composer, and agent bridge 2026-11-25 22:40:44 +11:00
sam 6127ded28d Revert "feat(ui): add an isolated UI SDK lab under devtools"
This reverts commit fe4d574976.
2026-11-25 22:12:57 +11:00
sam fe4d574976 feat(ui): add an isolated UI SDK lab under devtools
The lab is a dev-only route and a standalone entry so beta SDK patterns stay
out of shipped pages while they are evaluated.
2026-11-25 22:11:42 +11:00
sam c9ed3b1ae2 feat(connectors): version packages and pin installations
A package is now a set of immutable versions with declared grants and a
default version that installations run unless they pin another. Adopting a
version is what accepts its grants, replacing the per-extension lifecycle
actions with version, pin and update-policy commands.
2026-11-25 22:10:06 +11:00
sam afdb0a0c97 fix(ui): improve contrast across shared surfaces 2026-11-24 08:50:30 +11:00
sam d1e85c6e2a fix(ui): use dashboard typography in traces 2026-11-24 08:36:30 +11:00
sam 16f17f702c fix(ui): unify dashboard surfaces and selection 2026-11-24 08:33:07 +11:00
sam ba077f3779 fix(events): route webhooks by source UUID (#2127) 2026-11-24 08:07:09 +11:00
sam 58f1f9ce57 fix(ui): consolidate webhook source management 2026-11-24 07:59:24 +11:00
sam 19b273a87b fix(ui): label the add source form 2026-11-24 07:50:57 +11:00
sam ef3b5f98ea chore: cleanup spotnote 2026-11-24 07:50:13 +11:00
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
1295 changed files with 61722 additions and 66070 deletions

No files matched your search

+6 -17
View File
@@ -1,25 +1,14 @@
# Live reload for archied during dashboard work. # Live reload for the single archie binary during development. The dashboard
# # lives in archie-frontend and runs its own Vite server against this one.
# The frontend has its own loop -- `task ui:dev` runs Vite with HMR and proxies
# /api and /events here -- so this watcher deliberately ignores ui/. Watching
# it would rebuild the Go binary on every keystroke in a CSS file, and
# rebuilding on ui/dist changes would loop against `task ui`.
#
# ui/dist is NOT rebuilt here. During development the Vite server serves the
# frontend directly with HMR, so dist is not what you are looking at; it only
# matters for the embedded build, and `task ui` produces it before a commit.
# An earlier rule here claimed to keep dist current and never ran: air
# requires a file to satisfy include_dir AND include_file together, and ui/ is
# excluded from the walk anyway.
root = "." root = "."
tmp_dir = ".air" tmp_dir = ".air"
[build] [build]
cmd = "go build -o ./.air/archied ./cmd/archied" cmd = "go build -o ./.air/archie ./cmd/archie"
# `bin` is deprecated in air; entrypoint is the current key. # `bin` is deprecated in air; entrypoint is the current key.
entrypoint = "./.air/archied" entrypoint = "./.air/archie"
include_ext = ["go", "toml"] include_ext = ["go", "toml", "sql", "yaml", "cedar", "tmpl", "md"]
exclude_dir = ["ui", "bin", "docs", ".git", ".task", ".air", "tmp"] exclude_dir = ["bin", "docs", ".git", ".task", ".air", "tmp"]
exclude_regex = ["_test\\.go"] exclude_regex = ["_test\\.go"]
stop_on_error = true stop_on_error = true
delay = 400 delay = 400
+2 -2
View File
@@ -13,8 +13,8 @@ docs/
tmp/ tmp/
.playwright-mcp/ .playwright-mcp/
# A trailing-slash pattern matches only the context root, so this is written to # A trailing-slash pattern matches only the context root, so this is written to
# match a node_modules at any depth: ui/node_modules alone is 200MB and the # match a node_modules at any depth; the agent image compiles Go, which needs
# agent image compiles Go, which needs none of it. # none of it.
**/node_modules/ **/node_modules/
# Stray host-built binaries committed at the repo root. # Stray host-built binaries committed at the repo root.
+48 -9
View File
@@ -43,15 +43,6 @@ jobs:
go-version-file: go.mod go-version-file: go.mod
cache: false cache: false
- uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1
with:
package_json_file: ui/package.json
- name: Set up Node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version: "24"
- name: Install quality tools - name: Install quality tools
run: | run: |
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@$(cat .golangci-version) go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@$(cat .golangci-version)
@@ -167,6 +158,54 @@ jobs:
cache-from: type=gha,scope=archie-agent cache-from: type=gha,scope=archie-agent
cache-to: type=gha,mode=max,scope=archie-agent cache-to: type=gha,mode=max,scope=archie-agent
archie-image:
needs: [plan, gate]
outputs:
archie_digest: ${{ steps.archie.outputs.digest }}
runs-on: self-hosted
steps:
- name: Checkout
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f
with:
name: archie-ci
cleanup: false
- name: Log in to the Gitea registry
run: echo "${{ secrets.DEPLOY_TOKEN }}" | docker login git.catlow.cloud -u "${{ github.actor }}" --password-stdin
- name: Build and push archie
id: archie
uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8
with:
context: .
file: Dockerfile.archie
push: true
sbom: true
provenance: mode=max
tags: |
git.catlow.cloud/sam/archie:v${{ needs.plan.outputs.archied_version }}
git.catlow.cloud/sam/archie:sha-${{ needs.plan.outputs.sha }}
build-args: |
VERSION=${{ needs.plan.outputs.archied_version }}
REVISION=${{ needs.plan.outputs.sha }}
cache-from: type=gha,scope=archie
cache-to: type=gha,mode=max,scope=archie
- name: Sign image with cosign
if: env.COSIGN_PRIVATE_KEY != ''
env:
COSIGN_PRIVATE_KEY: ${{ secrets.COSIGN_PRIVATE_KEY }}
COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }}
run: |
if command -v cosign >/dev/null 2>&1; then
cosign sign --yes --key env://COSIGN_PRIVATE_KEY "git.catlow.cloud/sam/archie@${{ steps.archie.outputs.digest }}"
else
echo "::warning::cosign binary not installed on runner; skipping signature"
fi
dist-zip: dist-zip:
needs: [plan, gate, archied-image, agent-image] needs: [plan, gate, archied-image, agent-image]
runs-on: self-hosted runs-on: self-hosted
-8
View File
@@ -25,14 +25,6 @@ jobs:
with: with:
go-version-file: go.mod go-version-file: go.mod
- uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1
with:
package_json_file: ui/package.json
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version: "24"
- name: Install quality tools - name: Install quality tools
run: | run: |
go install github.com/go-task/task/v3/cmd/task@v3.48.0 go install github.com/go-task/task/v3/cmd/task@v3.48.0
+11 -4
View File
@@ -23,10 +23,6 @@ config.production.toml
*.png *.png
# Frontend # Frontend
/ui/node_modules/
/ui/.vite/
/ui/*.tsbuildinfo
/ui/dist/
# air live-reload # air live-reload
/.air/ /.air/
@@ -51,3 +47,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/
-6
View File
@@ -172,12 +172,6 @@ linters:
exclusions: exclusions:
generated: lax generated: lax
warn-unused: true warn-unused: true
# npm dependencies are not this module's code. `flatted`, pulled in
# transitively by the dashboard toolchain, ships a Go implementation
# alongside its JavaScript, and linting a vendored third-party file fails
# the gate on complexity nobody here can fix.
paths:
- ui/node_modules
presets: presets:
- comments - comments
- common-false-positives - common-false-positives
+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."
]
}
}
+104
View File
@@ -0,0 +1,104 @@
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 =
# Scratch checkouts, installed skills and generated output are not Archie's
# prose: a run over the repository must report on what the repository holds.
[tmp/**]
BasedOnStyles =
[.local/**]
BasedOnStyles =
[.agents/**]
BasedOnStyles =
[archipelago/**]
BasedOnStyles =
[.agents-run/**]
BasedOnStyles =
[.impeccable/**]
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: ""
+7
View File
@@ -0,0 +1,7 @@
extends: existence
message: "No em dashes. Use a comma, brackets, a colon, or a second sentence."
level: error
nonword: true
scope: raw
tokens:
- '\u2014'
@@ -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,32 @@
# Case-insensitive common terms (matched in any capitalisation)
(?i)approvers?
(?i)archipelago
(?i)canonicalis(?:e[ds]?|ing)
(?i)carina
(?i)confirmers?
(?i)fulfilment
(?i)glassmorphism
(?i)passkeys?
(?i)reapprovals?
(?i)redemptions?
(?i)retags?
(?i)undispatched
(?i)unpushed
(?i)wordmarks?
(?i)worktrees?
# Proper nouns, tools, and exact-case technical terms
archied
Catlow
depguard
gosec
govulncheck
hclog
Huma
Miessler
Pdeathsig
prbench
Reka
releaseupdate
secretengine
sqlc
+69 -63
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.
@@ -58,8 +58,11 @@ services: a core binary starts the extension as a plugin process and dials it.
`internal/domain` holds behaviour and interfaces; `internal/infrastructure` `internal/domain` holds behaviour and interfaces; `internal/infrastructure`
implements them. Every instruction sent to a model is a file in implements them. Every instruction sent to a model is a file in
`internal/prompts`, read through that package; never inline a prompt in code. `internal/platform/prompts`, read through that package; never inline a prompt in
Dashboard work follows `ui/CLAUDE.md`. Workflow YAML and its step vocabulary code. The old `internal/prompts` serves the services until they go.
The dashboard is its own repository, archie-frontend, and ships as its own
image; it reaches this backend only through `/api`, `/oauth2` and `/hooks`.
Workflow YAML and its step vocabulary
are in `WORKFLOWS.md`; the server catalogue is authoritative. are in `WORKFLOWS.md`; the server catalogue is authoritative.
## Authority ## Authority
@@ -69,7 +72,7 @@ When sources disagree, the higher one wins:
1. The maintainer's instruction in this session. 1. The maintainer's instruction in this session.
2. This file. 2. This file.
3. The code as it is in the tree. 3. The code as it is in the tree.
4. Gitea issues (`tea issues view <n>`): the plan for a piece of work. 4. GitHub issues (`gh issue view <n>`): the plan for a piece of work.
5. Everything else (memories, comments, old docs) is a hint. Verify it against 5. Everything else (memories, comments, old docs) is a hint. Verify it against
the code before acting on it. the code before acting on it.
@@ -79,13 +82,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 +117,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 +132,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 +165,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 +184,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,38 +192,37 @@ 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
```bash ```bash
task build # binaries into bin/ task build # binaries into bin/
task test # go test -short ./... task test # go test -short ./...
task ui # dashboard into ui/dist
task check # the gate task check # the gate
go test -short ./internal/domain/workflow -run TestName # one test go test -short ./internal/domain/workflow -run TestName # one test
task dev # every service + Vite at http://localhost:5173, from deployments/dev.toml task dev # archie with live reload on 127.0.0.1:8484
task e2e:up # seeded local stack; task e2e:check -- all runs the browser checks
``` ```
`task proto:generate`, `task db:generate` and `task openapi:generate` write `task proto:generate`, `task db:generate` and `task openapi:generate` write
the committed generated output for `proto/`, `internal/infrastructure/postgres/` the committed generated output for `proto/`, `internal/infrastructure/postgres/`
and `api/openapi.yaml`; `task check` runs their check variants and rejects stale and `api/openapi.yaml`; `task check` runs their check variants and rejects stale
output. The e2e stack is not part of the gate. output.
Requires Go 1.27, Task, golangci-lint, Node, pnpm and Docker. Adopt `task fmt` and Requires Go 1.27, Task, golangci-lint and Docker. Adopt `task fmt` and
`go fix` output as-is. `go fix` output as-is.
- `task check` gates the commit: `task check && git commit ...`. Never claim a - `task check` gates the commit: `task check && git commit ...`. Never claim a
@@ -216,48 +230,40 @@ 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
Work is tracked as issues on the primary remote, never in Markdown TODO files. Track work as issues on `archie-platform/archie-core`, never in Markdown TODO
GitHub is a read-only mirror; do not open, close or comment there. files. Dashboard work goes on `archie-platform/archie-frontend`.
```bash ```bash
tea issues list -r sam/archie --state open --labels critical gh issue list --label critical
tea issues view 497 gh issue view 497
tea issues edit 497 --add-labels in-progress --add-assignees sam gh issue edit 497 --add-label in-progress --add-assignee @me
tea comment 497 "what changed, and what was run" gh issue comment 497 --body "what changed, and what was run"
tea issues close 497 gh issue 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 sub-issues: add each one as you file it. No
MCP `issue_write` `add_dependency`, the epic `blocked_by` the child), plus any `epic/<slug>` label.
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.
- `tea` drops labels on `issues create` and `edit --add-labels`. Label through
the Gitea MCP connector, by label ID: it resolves names from the first 50
labels only.
- Cite the issue number in commits and comments. - Cite the issue number in commits and comments.
- `tea issues list --labels` silently ignores an unknown name and returns every - The repository is public: no host names, IPs, paths, PIDs or credentials in
issue. Check the count is plausible before trusting a filtered list. an issue, a commit or the code.
- The API caps `limit` at 50 regardless of what you pass.
- No host names, IPs, paths, PIDs or credentials in an issue: the text outlives
the change that wrote it.
- File follow-up work you find as an issue. Do not fix it in passing. - File follow-up work you find as an issue. Do not fix it in passing.
## 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.
+411
View File
@@ -0,0 +1,411 @@
---
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: "#e9eaec"
paper-workspace: "#f3f4f5"
paper-card: "#ffffff"
paper-hover: "#e7e9ec"
paper-hairline: "#d2d5da"
paper-border: "#d5d8dc"
paper-border-strong: "#bec3c9"
paper-input: "#838890"
paper-text: "#202327"
paper-text-muted: "#585d64"
paper-text-subtle: "#656a72"
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: "#5b6068"
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.
Graphite dark and Neutral light share one accent, Signal Sage. Neutral surfaces,
hairlines and type weight set the hierarchy. Solid sage marks the primary action;
a sage line or outline marks selection and focus. Labelled badges carry status.
Both themes use the same tokens, and the operator's OS chooses the theme 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:**
- Neutral light and Graphite dark, with one sage accent.
- 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.
## Colours
Neutral greys carry the structure. Signal Sage marks actions and selection;
status colours retain their meaning across both themes.
### 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** (#e9eaec): the page behind
everything.
- **Graphite Workspace** (#16171a) / **Paper Workspace** (#f3f4f5): 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** (#e7e9ec): hover, secondary and
muted surfaces (shadcn's `accent`, `muted` and `secondary` all share it).
- **Hairline, Border, Border Strong** (#2a2c30, #313338, #3c3f45 dark; #d2d5da,
#d5d8dc, #bec3c9 light): dividers, card edges and the top bar's bottom edge.
- **Input stroke** (#70727a dark, #838890 light): field borders.
- **Text, Text Muted, Text Subtle** (#e8e6e1, #a6a39b, #99968f dark; #202327,
#585d64, #656a72 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, #5b6068 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.
- **Edges:** a 1px border ring, without a shadow.
- **Internal Padding:** 16px, or 12px for the small size. Section wraps a card
with a title; an edited section shows a sage ring.
- **Data tables:** card surface, muted header and a border, without card padding
or a shadow.
- **Alerts:** use the semantic soft fill and a matching border so they don't
look like regular cards.
### 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.
- **Selection:** the active tab uses a sage underline. Pressed toggles use a
sage outline and a soft fill.
### 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.
+28
View File
@@ -0,0 +1,28 @@
# Production single-binary image for cmd/archie.
# Build: docker build -f Dockerfile.archie --build-arg VERSION=v1.0.0 -t archie:v1.0.0 .
# ── builder ──
FROM golang:1.27-trixie AS builder
ARG VERSION=dev
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 go build -trimpath \
-ldflags "-s -w -X github.com/samcharles93/archie-core/internal/buildinfo.Version=${VERSION}" \
-o /usr/local/bin/archie ./cmd/archie
# ── runtime ──
FROM gcr.io/distroless/static-debian12:nonroot
ARG VERSION=dev
ARG REVISION=unknown
LABEL org.opencontainers.image.title="archie" \
org.opencontainers.image.description="Event-driven agentic automation" \
org.opencontainers.image.version="${VERSION}" \
org.opencontainers.image.revision="${REVISION}"
COPY --from=builder /usr/local/bin/archie /archie
EXPOSE 8080
ENTRYPOINT ["/archie"]
-9
View File
@@ -1,14 +1,6 @@
# archied — the archie daemon # archied — the archie daemon
# Run via docker compose alongside NATS. # Run via docker compose alongside NATS.
FROM node:24-trixie-slim AS dashboard
WORKDIR /src/ui
RUN corepack enable
COPY ui/package.json ui/pnpm-lock.yaml ui/pnpm-workspace.yaml ./
RUN pnpm install --frozen-lockfile
COPY ui/ ./
RUN pnpm run build
FROM golang:1.27-trixie AS builder FROM golang:1.27-trixie AS builder
WORKDIR /src WORKDIR /src
COPY go.mod go.sum ./ COPY go.mod go.sum ./
@@ -16,7 +8,6 @@ COPY go.mod go.sum ./
# them COPY . . makes every commit a cold compile. # them COPY . . makes every commit a cold compile.
RUN --mount=type=cache,target=/go/pkg/mod go mod download RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . . COPY . .
COPY --from=dashboard /src/ui/dist ./ui/dist
ARG GATEWAY_VERSION=dev ARG GATEWAY_VERSION=dev
ARG RUNTIME_VERSION=dev ARG RUNTIME_VERSION=dev
RUN --mount=type=cache,target=/go/pkg/mod \ RUN --mount=type=cache,target=/go/pkg/mod \
+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 and self-hosts
Archie. They want 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, acting without
being asked when allowed. It calls the operator in only when policy or risk
requires it, explaining 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`.
+112 -72
View File
@@ -91,41 +91,18 @@ tasks:
cmds: cmds:
- golangci-lint run ./... - golangci-lint run ./...
ui:deps:
desc: Install dashboard dependencies
internal: true
# Parallel UI checks must share one dependency install.
run: once
dir: ui
cmds:
- pnpm install --frozen-lockfile
ui:
desc: Build the dashboard into ui/dist, which the Go build embeds
# check builds the dashboard and then build depends on it again; a second
# build empties ui/dist under the Go steps that embed it.
run: once
dir: ui
deps: [ui:deps]
cmds:
- pnpm run build
test:ui:
desc: Test and type-check the dashboard
dir: ui
deps: [ui:deps]
cmds:
- pnpm test
- pnpm run typecheck
bench:prreview: bench:prreview:
desc: Run the PR review benchmark on the configured models and write docs/benchmarks/pr-review-*.md (-- -model ALIAS -judge-model REF; --help for flags) desc: Run the PR review benchmark on the configured models and write docs/benchmarks/pr-review-*.md (-- -model ALIAS -judge-model REF; --help for flags)
cmds: cmds:
- go run ./cmd/archied prbench {{.CLI_ARGS}} - go run ./cmd/archied prbench {{.CLI_ARGS}}
dev: dev:
desc: Run development services and Vite at http://localhost:5173 desc: Run archie with live reload on 127.0.0.1:8484; run the dashboard from archie-frontend
deps: [dev:daemon, dev:gateway, dev:messaging, dev:state-store, dev:dashboard, dev:ui] deps: [dev:archie]
dev:legacy:
desc: Run the legacy multi-service stack
deps: [dev:daemon, dev:gateway, dev:messaging, dev:state-store, dev:dashboard]
dev:tls: dev:tls:
desc: Issue the development CA and service certificates deployments/dev.toml names desc: Issue the development CA and service certificates deployments/dev.toml names
@@ -163,13 +140,36 @@ tasks:
exit 1 exit 1
- | - |
# docker-compose.yml creates the dev database with a superuser named # docker-compose.yml creates the dev database with a superuser named
# archie; provision the least-privilege roles deployments/dev.toml # archie; provision the least-privilege runtime and migrator roles
# points at. Idempotent, so this also upgrades a volume created before # idempotently without depending on the legacy state-store binary.
# the role split. # Single-binary archie uses its own database (archie_dev) so its goose
go run ./cmd/archie-state-store provision \ # migration history does not collide with the legacy archie database.
-admin-url "postgres://archie:archie@127.0.0.1:5432/archie?sslmode=disable" \ docker compose exec -T postgres psql -v ON_ERROR_STOP=1 -U archie -d postgres <<'SQL'
-runtime-url "postgres://archie_runtime:archie@127.0.0.1:5432/archie?sslmode=disable" \ DO $$
-migration-url "postgres://archie_migrator:archie@127.0.0.1:5432/archie?sslmode=disable" BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'archie_migrator') THEN
CREATE ROLE archie_migrator LOGIN PASSWORD 'archie';
ELSE
ALTER ROLE archie_migrator WITH LOGIN PASSWORD 'archie';
END IF;
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'archie_runtime') THEN
CREATE ROLE archie_runtime LOGIN PASSWORD 'archie';
ELSE
ALTER ROLE archie_runtime WITH LOGIN PASSWORD 'archie';
END IF;
END
$$;
SELECT 'CREATE DATABASE archie_dev OWNER archie_migrator'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'archie_dev')\gexec
GRANT CREATE, CONNECT ON DATABASE archie TO archie_migrator;
GRANT CONNECT ON DATABASE archie TO archie_runtime;
GRANT CREATE, CONNECT ON DATABASE archie_dev TO archie_migrator;
GRANT CONNECT ON DATABASE archie_dev TO archie_runtime;
SQL
docker compose exec -T postgres psql -v ON_ERROR_STOP=1 -U archie -d archie \
-c "GRANT CREATE, USAGE ON SCHEMA public TO archie_migrator; GRANT USAGE ON SCHEMA public TO archie_runtime;"
docker compose exec -T postgres psql -v ON_ERROR_STOP=1 -U archie -d archie_dev \
-c "GRANT CREATE, USAGE ON SCHEMA public TO archie_migrator; GRANT USAGE ON SCHEMA public TO archie_runtime;"
dev:wait-state: dev:wait-state:
internal: true internal: true
@@ -183,60 +183,67 @@ tasks:
exit 1 exit 1
dev:daemon: dev:daemon:
desc: Run archied with live reload desc: Run legacy archied
cmds: cmds:
- task: dev:wait-state - task: dev:wait-state
- air -build.args_bin="-config-overlay,deployments/dev.toml" - go run ./cmd/archied -config-overlay deployments/dev.toml
dev:dashboard: dev:dashboard:
desc: Run the dashboard backend desc: Run the legacy dashboard backend
cmds: cmds:
- go run ./cmd/archie-ui -config-overlay deployments/dev.toml - go run ./cmd/archie-ui -config-overlay deployments/dev.toml
dev:state-store: dev:state-store:
desc: Run the State Store with development PostgreSQL desc: Run the legacy State Store with development PostgreSQL
deps: [dev:postgres, dev:tls] deps: [dev:postgres, dev:tls]
cmds: cmds:
- go run ./cmd/archie-state-store -config-overlay deployments/dev.toml - go run ./cmd/archie-state-store -config-overlay deployments/dev.toml
dev:gateway: dev:gateway:
desc: Run the development Gateway desc: Run the legacy development Gateway
cmds: cmds:
- task: dev:wait-state - task: dev:wait-state
- go run ./cmd/archie-gateway -config-overlay deployments/dev.toml - go run ./cmd/archie-gateway -config-overlay deployments/dev.toml
dev:messaging: dev:messaging:
desc: Run the development Messaging Service desc: Run the legacy development Messaging Service
cmds: cmds:
- 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:ui: dev:archie:
desc: Run Vite (requires the dashboard backend) desc: Run the single archie binary against the development PostgreSQL (admin token "dev", live reload via air if installed)
dir: ui deps: [dev:postgres]
vars:
DIR: tmp/dev-archie
cmds: cmds:
- pnpm install - |
- pnpm run dev set -eu
mkdir -p {{.DIR}}/state
e2e:up: # Generated once: the age identity seals the dev credentials, so keep
desc: Start the local stack without Docker (PostgreSQL 18, services, Vite) and seed it # it across runs. Roles come from dev:postgres.
cmds: if [ ! -f {{.DIR}}/config.toml ]; then
- bash e2e/stack.sh start install -m 0600 /dev/null {{.DIR}}/config.toml
- bash e2e/seed.sh {
echo 'listen = "127.0.0.1:8484"'
e2e:down: echo 'state_dir = "{{.ROOT_DIR}}/{{.DIR}}/state"'
desc: Stop the local e2e stack echo "admin_token_sha256 = \"$(printf dev | sha256sum | cut -d' ' -f1)\""
cmds: echo "age_identity = \"$(go run ./cmd/archie -new-age-identity)\""
- bash e2e/stack.sh stop echo '[database]'
echo 'url = "postgres://archie_runtime:archie@127.0.0.1:5432/archie_dev?sslmode=disable"'
e2e:check: echo 'owner_url = "postgres://archie_migrator:archie@127.0.0.1:5432/archie_dev?sslmode=disable"'
desc: List browser checks; use -- all or -- CHECK to run, add --headed to watch } > {{.DIR}}/config.toml
cmds: elif ! grep -q '^state_dir' {{.DIR}}/config.toml; then
- node e2e/run.cjs {{.CLI_ARGS}} sed -i '1i state_dir = "{{.ROOT_DIR}}/{{.DIR}}/state"' {{.DIR}}/config.toml
fi
- |
if command -v air >/dev/null 2>&1; then
exec air -build.args_bin="-config,{{.DIR}}/config.toml"
fi
exec go run ./cmd/archie -config {{.DIR}}/config.toml
build: build:
desc: Build archie services and agent binaries desc: Build archie services and agent binaries
deps: [ui]
# Static, like the binaries a release ships, so `dist` reuses these # Static, like the binaries a release ships, so `dist` reuses these
# compiled packages and only links again. # compiled packages and only links again.
env: env:
@@ -252,14 +259,17 @@ tasks:
- Taskfile.yml - Taskfile.yml
- "**/*.go" - "**/*.go"
# Files the binaries embed. # Files the binaries embed.
- config.example.toml
- "internal/**/*.sql" - "internal/**/*.sql"
- "internal/**/*.yaml" - "internal/**/*.yaml"
- "internal/**/*.json" - "internal/**/*.json"
- "internal/**/*.tpl" - "internal/**/*.tpl"
- "internal/**/*.tmpl"
- "internal/**/*.md" - "internal/**/*.md"
- "modules/**/*.cedar"
- "modules/**/*.yaml"
- go.mod - go.mod
- go.sum - go.sum
- "ui/dist/**"
generates: generates:
- "{{.BIN_DIR}}/archied" - "{{.BIN_DIR}}/archied"
- "{{.BIN_DIR}}/archie-gateway" - "{{.BIN_DIR}}/archie-gateway"
@@ -277,7 +287,6 @@ tasks:
dist: dist:
desc: Build the linux/amd64 binaries a release ships into dist/ (VERSION=1.2.3; needs jq) desc: Build the linux/amd64 binaries a release ships into dist/ (VERSION=1.2.3; needs jq)
deps: [ui]
env: env:
GOOS: linux GOOS: linux
GOARCH: amd64 GOARCH: amd64
@@ -315,17 +324,49 @@ tasks:
desc: Run the full quality gate desc: Run the full quality gate
# Finish mutations before starting parallel checks. # Finish mutations before starting parallel checks.
cmds: cmds:
# Node packages land under ui/, which `go test ./...` walks: installing
# them while the parallel checks scan the tree makes a lockfile update
# 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.
- task: ui
- 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 (-- ./pkg/... to name packages; default: those changed since main)"
# 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$' | 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 $pkgs
if go fix -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 $pkgs
go test -short $pkgs
golangci-lint run $pkgs
fi
if [ -z "$pkgs" ]; then
echo "nothing changed since main"
fi
check:readonly: check:readonly:
internal: true internal: true
deps: deps:
@@ -334,7 +375,6 @@ tasks:
- task: lint - task: lint
- task: build - task: build
- task: test - task: test
- task: test:ui
release: release:
desc: "Tag main as a release (RELEASE=major|minor|patch|1.2.3)" desc: "Tag main as a release (RELEASE=major|minor|patch|1.2.3)"
+37 -38
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.
@@ -186,10 +185,10 @@ _needs a repository._
_needs a repository._ _needs a repository._
No settings. It runs the repository policy's `tooling` commands, in order, in 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.
+7763 -387
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")
+82 -1
View File
@@ -4,18 +4,27 @@ package main
import ( import (
"context" "context"
"errors"
"flag" "flag"
"fmt" "fmt"
"os" "os"
"os/signal" "os/signal"
"strings"
"syscall" "syscall"
"github.com/samcharles93/archie-core/internal/app/archie" "github.com/samcharles93/archie-core/internal/app/archie"
"github.com/samcharles93/archie-core/internal/buildinfo" "github.com/samcharles93/archie-core/internal/buildinfo"
) )
type exitCodeError int
func (e exitCodeError) Error() string { return fmt.Sprintf("exit %d", int(e)) }
func main() { func main() {
if err := run(); err != nil { if err := run(); err != nil {
if code, ok := errors.AsType[exitCodeError](err); ok {
os.Exit(int(code))
}
fmt.Fprintln(os.Stderr, "archie:", err) fmt.Fprintln(os.Stderr, "archie:", err)
os.Exit(1) os.Exit(1)
} }
@@ -23,10 +32,11 @@ func main() {
func run() error { func run() error {
configPath := flag.String("config", archie.DefaultConfigPath(), "path to the bootstrap config file") configPath := flag.String("config", archie.DefaultConfigPath(), "path to the bootstrap config file")
specPath := flag.String("spec", "", "path to the bootstrap spec file (used by 'archie bootstrap')")
newIdentity := flag.Bool("new-age-identity", false, "print a new age identity for age_identity and exit") newIdentity := flag.Bool("new-age-identity", false, "print a new age identity for age_identity and exit")
showVersion := buildinfo.RegisterVersionFlag("archie") showVersion := buildinfo.RegisterVersionFlag("archie")
flag.Usage = func() { flag.Usage = func() {
_, _ = fmt.Fprintln(flag.CommandLine.Output(), "usage: archie [flags]\n archie openapi print the API's OpenAPI document") _, _ = fmt.Fprintln(flag.CommandLine.Output(), "usage: archie [flags]\n archie migrate apply database migrations and runtime grants\n archie bootstrap idempotently provision initial owner and SSO settings\n archie rekey rotate age sealing identities in one transaction\n archie bundle validate, export, diff, or apply promotion bundles\n archie catalogue generate keys or mirror extension catalogues offline\n archie openapi print the API's OpenAPI document")
flag.PrintDefaults() flag.PrintDefaults()
} }
flag.Parse() flag.Parse()
@@ -36,6 +46,25 @@ func run() error {
} }
switch flag.Arg(0) { switch flag.Arg(0) {
case "": case "":
case "migrate":
return runMigrate(*configPath, flag.Args()[1:])
case "bootstrap":
return runBootstrap(*configPath, *specPath, flag.Args()[1:])
case "rekey":
return runRekey(*configPath, flag.Args()[1:])
case "bundle":
code, err := runBundle(*configPath, flag.Args()[1:])
if err != nil {
return err
}
if code != 0 {
return exitCodeError(code)
}
return nil
case "catalogue":
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
return archie.RunCatalogueCLI(ctx, flag.Args()[1:], os.Stdout)
case "openapi": case "openapi":
doc, err := archie.Document() doc, err := archie.Document()
if err != nil { if err != nil {
@@ -51,3 +80,55 @@ func run() error {
defer stop() defer stop()
return archie.Run(ctx, *configPath) return archie.Run(ctx, *configPath)
} }
func runRekey(configPath string, args []string) error {
fs := flag.NewFlagSet("rekey", flag.ContinueOnError)
oldIdentity := fs.String("old-identity", "", "current age identity (or ARCHIE_OLD_AGE_IDENTITY[_FILE])")
newIdentity := fs.String("new-identity", "", "replacement age identity (or ARCHIE_NEW_AGE_IDENTITY[_FILE])")
newBackupsRaw := fs.String("new-backups", "", "comma-separated age backup recipients for re-sealed values")
if err := fs.Parse(args); err != nil {
return err
}
var newBackups []string
for r := range strings.SplitSeq(*newBackupsRaw, ",") {
if r = strings.TrimSpace(r); r != "" {
newBackups = append(newBackups, r)
}
}
rcfg, err := archie.LoadRekeyConfig(*oldIdentity, *newIdentity, newBackups)
if err != nil {
return err
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
return archie.Rekey(ctx, configPath, rcfg)
}
func runMigrate(defaultConfig string, args []string) error {
fs := flag.NewFlagSet("migrate", flag.ContinueOnError)
configPath := fs.String("config", defaultConfig, "path to the bootstrap config file")
if err := fs.Parse(args); err != nil {
return err
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
return archie.Migrate(ctx, *configPath)
}
func runBootstrap(defaultConfig, defaultSpec string, args []string) error {
fs := flag.NewFlagSet("bootstrap", flag.ContinueOnError)
configPath := fs.String("config", defaultConfig, "path to the bootstrap config file")
specPath := fs.String("spec", defaultSpec, "path to the bootstrap spec file")
if err := fs.Parse(args); err != nil {
return err
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
return archie.Bootstrap(ctx, *configPath, *specPath)
}
func runBundle(configPath string, args []string) (int, error) {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
return archie.RunBundleCLI(ctx, configPath, args, os.Stdout)
}
+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.
+23 -20
View File
@@ -16,17 +16,19 @@ 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
1. Pick a starting configuration. The full set of annotated templates lives 1. Pick a starting configuration. The full set of annotated templates lives
in this repository's `deployments/` directory on GitHub in this repository's `deployments/` directory on GitHub
(<https://offloaded.dev>) — (<https://offloaded.dev>):
`standalone.toml` (no forge, the simplest start), `standalone.toml` (no forge, the simplest start),
`single-forge-github.toml` and `docker-nats-stack.toml` cover the common cases. Every one needs `single-forge-github.toml` and `docker-nats-stack.toml` cover the common cases. Every one needs
PostgreSQL 18 with the `archie_migrator` and `archie_runtime` roles created PostgreSQL 18 with the `archie_migrator` and `archie_runtime` roles created
@@ -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.
+14 -15
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,8 +87,8 @@ 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's API, not
`archied`. `archied`. The dashboard itself ships from archie-frontend as its own image.
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
default). Start it after the Gateway and the State Store: default). Start it after the Gateway and the State Store:
@@ -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.
+80
View File
@@ -0,0 +1,80 @@
# Hardened enterprise overlay for deployments/archie/compose.yml.
# Usage: docker compose -f compose.yml -f compose.enterprise.yml up -d
#
# Ensure ./config.toml omits database.owner_url and ./secrets/* holds:
# - db_runtime_url (DML-only archie_app connection string)
# - db_owner_url (DDL archie_owner connection string, mounted only in archie-migrate)
# - age_identity (AGE-SECRET-KEY-1...)
# - admin_token_sha256 (hex SHA-256)
services:
archie-migrate:
image: ${ARCHIE_IMAGE:-gcr.io/distroless/static-debian12:nonroot}
restart: "no"
user: "65532:65532"
read_only: true
tmpfs:
- /tmp:rw,noexec,nosuid,nodev,size=64m
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
entrypoint: ["/archie/archie"]
command: ["-config", "", "migrate"]
environment:
HOME: /tmp
SSL_CERT_FILE: /etc/ssl/certs/enterprise-ca.crt
ARCHIE_DATABASE_URL_FILE: /run/secrets/db_runtime_url
ARCHIE_DATABASE_OWNER_URL_FILE: /run/secrets/db_owner_url
secrets:
- db_runtime_url
- db_owner_url
volumes:
- ./bin/archie:/archie/archie:ro
- ${ARCHIE_CA_BUNDLE:-./certs/enterprise-ca.crt}:/etc/ssl/certs/enterprise-ca.crt:ro
networks: [internal]
depends_on:
archie-db:
condition: service_healthy
archie:
image: ${ARCHIE_IMAGE:-gcr.io/distroless/static-debian12:nonroot}
user: "65532:65532"
read_only: true
tmpfs:
- /tmp:rw,noexec,nosuid,nodev,size=128m
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
- seccomp=./seccomp.json
environment:
HOME: /tmp
SSL_CERT_FILE: /etc/ssl/certs/enterprise-ca.crt
HTTPS_PROXY: ${HTTPS_PROXY:-}
HTTP_PROXY: ${HTTP_PROXY:-}
NO_PROXY: ${NO_PROXY:-localhost,127.0.0.1,archie-db}
ARCHIE_DATABASE_URL_FILE: /run/secrets/db_runtime_url
ARCHIE_AGE_IDENTITY_FILE: /run/secrets/age_identity
ARCHIE_ADMIN_TOKEN_SHA256_FILE: /run/secrets/admin_token_sha256
secrets:
- db_runtime_url
- age_identity
- admin_token_sha256
volumes:
- ${ARCHIE_CA_BUNDLE:-./certs/enterprise-ca.crt}:/etc/ssl/certs/enterprise-ca.crt:ro
depends_on:
archie-db:
condition: service_healthy
archie-migrate:
condition: service_completed_successfully
secrets:
db_runtime_url:
file: ./secrets/db_runtime_url
db_owner_url:
file: ./secrets/db_owner_url
age_identity:
file: ./secrets/age_identity
admin_token_sha256:
file: ./secrets/admin_token_sha256
+36 -2
View File
@@ -23,6 +23,12 @@ services:
image: gcr.io/distroless/static-debian12:nonroot image: gcr.io/distroless/static-debian12:nonroot
restart: unless-stopped restart: unless-stopped
command: ["/archie/archie", "-config", "/archie/config.toml"] command: ["/archie/archie", "-config", "/archie/config.toml"]
environment:
# The age secret engine resolves secret:// references from this file with
# this identity. Both are paths the state mount already holds, so no key
# is in this file.
AGE_FILE: /archie/state/age/secrets.age
AGE_IDENTITY: /archie/state/age/identity.txt
# Docker's default seccomp profile plus the one clone the extension host # Docker's default seccomp profile plus the one clone the extension host
# needs to confine an extension in its own user and network namespace. # needs to confine an extension in its own user and network namespace.
security_opt: security_opt:
@@ -31,12 +37,40 @@ services:
- ./bin/archie:/archie/archie:ro - ./bin/archie:/archie/archie:ro
- ./config.toml:/archie/config.toml:ro - ./config.toml:/archie/config.toml:ro
- ./extensions:/archie/extensions:ro - ./extensions:/archie/extensions:ro
ports: - ./state:/archie/state
- "${ARCHIE_BIND:?}:8080" - ./catalogue:/archie/catalogue:ro
networks: [internal] networks: [internal]
depends_on: depends_on:
archie-db: archie-db:
condition: service_healthy condition: service_healthy
archie-frontend:
image: ${ARCHIE_FRONTEND_IMAGE:-ghcr.io/archie-platform/archie-frontend:v0.1.0}
restart: unless-stopped
read_only: true
tmpfs:
- /tmp
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
networks: [internal]
# The ingress: one host, routed by path to the backend or the dashboard.
edge:
image: nginxinc/nginx-unprivileged:1.29-alpine
restart: unless-stopped
read_only: true
tmpfs:
- /tmp
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
volumes:
- ./edge.conf:/etc/nginx/conf.d/default.conf:ro
ports:
- "${ARCHIE_BIND:?}:8080"
networks: [internal]
depends_on: [archie, archie-frontend]
networks: networks:
internal: {} internal: {}
+33 -4
View File
@@ -1,26 +1,36 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Deploys the single binary's stack to a host over ssh: deploy.sh root@staging-host. # Deploys the single binary's stack to a host over ssh: deploy.sh root@staging-host.
# The first run creates the secrets on the host; they never leave it. # The first run creates the secrets on the host; they never leave it. The
# dashboard image is built from an archie-frontend checkout beside this one, or
# from ARCHIE_FRONTEND.
set -euo pipefail set -euo pipefail
target=${1:?usage: deploy.sh user@host [bind-address:port]} target=${1:?usage: deploy.sh user@host [bind-address:port]}
bind=${2:-} bind=${2:-}
here=$(cd "$(dirname "$0")" && pwd) here=$(cd "$(dirname "$0")" && pwd)
repo=$(cd "$here/../.." && pwd) repo=$(cd "$here/../.." && pwd)
frontend=${ARCHIE_FRONTEND:-"$(cd "$repo/.." && pwd)/archie-frontend"}
dir=/root/archie dir=/root/archie
version=$(git -C "$repo" describe --tags --always --dirty) version=$(git -C "$repo" describe --tags --always --dirty)
frontend_version=$(git -C "$frontend" describe --tags --always --dirty)
frontend_image="archie-frontend:$frontend_version"
docker build -q --build-arg VERSION="$frontend_version" \
--build-arg REVISION="$(git -C "$frontend" rev-parse HEAD)" \
-t "$frontend_image" "$frontend" >/dev/null
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -C "$repo" -trimpath \ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -C "$repo" -trimpath \
-ldflags "-X github.com/samcharles93/archie-core/internal/buildinfo.Version=$version" \ -ldflags "-X github.com/samcharles93/archie-core/internal/buildinfo.Version=$version" \
-o "$here/.build/archie" ./cmd/archie -o "$here/.build/archie" ./cmd/archie
ssh "$target" "mkdir -p $dir/bin $dir/initdb $dir/extensions" ssh "$target" "mkdir -p $dir/bin $dir/initdb $dir/extensions $dir/catalogue $dir/state && chown 65532:65532 $dir/state"
scp -q "$here/compose.yml" "$target:$dir/compose.yml" scp -q "$here/compose.yml" "$target:$dir/compose.yml"
scp -q "$here/edge.conf" "$target:$dir/edge.conf"
docker save "$frontend_image" | ssh "$target" docker load -q
scp -q "$here/seccomp.json" "$target:$dir/seccomp.json" scp -q "$here/seccomp.json" "$target:$dir/seccomp.json"
scp -q "$here/initdb/01-roles.sh" "$target:$dir/initdb/01-roles.sh" scp -q "$here/initdb/01-roles.sh" "$target:$dir/initdb/01-roles.sh"
scp -q "$here/.build/archie" "$target:$dir/bin/archie.new" scp -q "$here/.build/archie" "$target:$dir/bin/archie.new"
ssh "$target" BIND="$bind" DIR="$dir" bash -s <<'REMOTE' ssh "$target" BIND="$bind" DIR="$dir" FRONTEND_IMAGE="$frontend_image" bash -s <<'REMOTE'
set -euo pipefail set -euo pipefail
cd "$DIR" cd "$DIR"
chmod 755 initdb/01-roles.sh chmod 755 initdb/01-roles.sh
@@ -51,6 +61,11 @@ if ! grep -q '^admin_token_sha256' config.toml; then
sed -i "1i admin_token_sha256 = \"$hash\"" config.toml sed -i "1i admin_token_sha256 = \"$hash\"" config.toml
chown 65532:65532 config.toml chown 65532:65532 config.toml
fi fi
# Fetched extension binaries and other state outside the database live in
# the mounted state directory, so they survive the container being recreated.
if ! grep -q '^state_dir' config.toml; then
sed -i '1i state_dir = "/archie/state"' config.toml
fi
# The age identity seals the credentials Archie keeps. It is made here and # The age identity seals the credentials Archie keeps. It is made here and
# never leaves the host; back it up, or credentials die with it. # never leaves the host; back it up, or credentials die with it.
if ! grep -q '^age_identity' config.toml; then if ! grep -q '^age_identity' config.toml; then
@@ -60,7 +75,21 @@ if ! grep -q '^age_identity' config.toml; then
unset identity unset identity
chown 65532:65532 config.toml chown 65532:65532 config.toml
fi fi
# The age secret engine resolves secret:// references from this key and the
# file sealed to it. Skipped, not fatal, where age isn't installed: the engine
# simply has nothing to read.
if [ ! -f state/age/identity.txt ] && command -v age-keygen >/dev/null; then
umask 077
mkdir -p state/age
age-keygen -o state/age/identity.txt 2>/dev/null
chown -R 65532:65532 state/age
echo "age secret engine recipient: $(age-keygen -y state/age/identity.txt)"
fi
sed -i '/^ARCHIE_FRONTEND_IMAGE=/d' .env
echo "ARCHIE_FRONTEND_IMAGE=$FRONTEND_IMAGE" >> .env
docker compose up -d --remove-orphans docker compose up -d --remove-orphans
docker compose up -d --force-recreate archie docker compose up -d --force-recreate archie
# edge.conf is a bind mount, so a changed route table needs a restart.
docker compose restart edge
REMOTE REMOTE
echo "deployed $version to $target" echo "deployed $version and dashboard $frontend_version to $target"
+33
View File
@@ -0,0 +1,33 @@
# The Compose stack's ingress: API, sign-in and webhook paths go to the
# backend, every other path to the dashboard, all on one host.
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 8080;
server_name _;
server_tokens off;
client_max_body_size 64m;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# TLS ends at the proxy in front of this one, so keep the scheme it saw.
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
location ~ ^/(api|oauth2|hooks)(/|$) {
# The dashboard's live stream is a long-lived response; buffering it
# would hold every update back.
proxy_buffering off;
proxy_read_timeout 1h;
proxy_pass http://archie:8080;
}
location / {
proxy_pass http://archie-frontend:8080;
}
}
+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
+13
View File
@@ -0,0 +1,13 @@
apiVersion: v2
name: archie
description: Event-driven agentic automation platform with pre-action governance and isolated extension execution.
type: application
version: 0.1.0
appVersion: "1.0.0"
keywords:
- archie
- automation
- governance
- enterprise
maintainers:
- name: Archie Platform Team
@@ -0,0 +1,129 @@
{{/*
Expand the name of the chart.
*/}}
{{- define "archie.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Create a default fully qualified app name.
*/}}
{{- define "archie.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}
{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "archie.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Common labels.
*/}}
{{- define "archie.labels" -}}
helm.sh/chart: {{ include "archie.chart" . }}
{{ include "archie.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
{{/*
Selector labels.
*/}}
{{- define "archie.selectorLabels" -}}
app.kubernetes.io/name: {{ include "archie.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{/*
ServiceAccount name.
*/}}
{{- define "archie.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }}
{{- default (include "archie.fullname" .) .Values.serviceAccount.name }}
{{- else }}
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}
{{/*
Container image reference, preferring digest pinning when configured.
*/}}
{{- define "archie.image" -}}
{{- if .Values.image.digest }}
{{- printf "%s@%s" .Values.image.repository .Values.image.digest }}
{{- else }}
{{- printf "%s:%s" .Values.image.repository (default .Chart.AppVersion .Values.image.tag) }}
{{- end }}
{{- end }}
{{/*
Migration secret name.
*/}}
{{- define "archie.migrateSecretName" -}}
{{- default .Values.secrets.existingSecret .Values.migrate.existingSecret }}
{{- end }}
{{/*
Render a map to YAML while omitting keys whose value is null (used so OpenShift
restricted-v2 overlays can unset runAsUser, runAsGroup, and fsGroup cleanly).
*/}}
{{- define "archie.compactYaml" -}}
{{- $out := dict -}}
{{- range $k, $v := . -}}
{{- if not (kindIs "invalid" $v) -}}
{{- if kindIs "map" $v -}}
{{- $sub := include "archie.compactYaml" $v -}}
{{- if $sub -}}
{{- $_ := set $out $k (fromYaml $sub) -}}
{{- end -}}
{{- else -}}
{{- $_ := set $out $k $v -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- if $out -}}
{{- toYaml $out -}}
{{- end -}}
{{- end }}
{{/*
Dashboard name and selector labels. The name differs from the API's, so the
API's Service and NetworkPolicy never select dashboard pods.
*/}}
{{- define "archie.frontendFullname" -}}
{{- printf "%s-frontend" (include "archie.fullname" .) | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- define "archie.frontendSelectorLabels" -}}
app.kubernetes.io/name: {{ printf "%s-frontend" (include "archie.name" .) | trunc 63 | trimSuffix "-" }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{- define "archie.frontendLabels" -}}
helm.sh/chart: {{ include "archie.chart" . }}
{{ include "archie.frontendSelectorLabels" . }}
app.kubernetes.io/component: frontend
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
{{- define "archie.frontendImage" -}}
{{- if .Values.frontend.image.digest }}
{{- printf "%s@%s" .Values.frontend.image.repository .Values.frontend.image.digest }}
{{- else }}
{{- printf "%s:%s" .Values.frontend.image.repository .Values.frontend.image.tag }}
{{- end }}
{{- end }}
@@ -0,0 +1,71 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: {{ include "archie.fullname" . }}-config
labels:
{{- include "archie.labels" . | nindent 4 }}
data:
config.toml: |
listen = {{ .Values.config.listen | quote }}
{{- if .Values.metrics.enabled }}
metrics_listen = {{ printf "0.0.0.0:%v" .Values.metrics.port | quote }}
{{- end }}
state_dir = {{ .Values.config.stateDir | quote }}
shutdown_grace = {{ .Values.config.shutdownGrace | quote }}
{{- if .Values.config.ageBackupRecipients }}
age_backup_recipients = [
{{- range $i, $r := .Values.config.ageBackupRecipients }}
{{ $r | quote }}{{ if lt $i (sub (len $.Values.config.ageBackupRecipients) 1) }},{{ end }}
{{- end }}
]
{{- end }}
[catalogue]
disable_auto_update = {{ .Values.config.catalogue.disableAutoUpdate }}
{{- if .Values.config.catalogue.location }}
location = {{ .Values.config.catalogue.location | quote }}
{{- end }}
{{- if .Values.config.catalogue.publicKey }}
public_key = {{ .Values.config.catalogue.publicKey | quote }}
{{- end }}
{{- if .Values.config.catalogue.authSecret }}
auth_file = "/run/secrets/archie-catalogue/config.json"
{{- end }}
[extensions]
require_remote = {{ .Values.config.extensions.requireRemote }}
{{- if .Values.config.extensions.tls.existingSecret }}
ca_file = {{ printf "%s/ca.crt" .Values.config.extensions.tls.mountPath | quote }}
cert_file = {{ printf "%s/tls.crt" .Values.config.extensions.tls.mountPath | quote }}
key_file = {{ printf "%s/tls.key" .Values.config.extensions.tls.mountPath | quote }}
{{- end }}
{{- range $name, $ep := .Values.config.extensions.remote }}
[extensions.remote.{{ $name }}]
address = {{ $ep.address | quote }}
{{- if $ep.serverName }}
server_name = {{ $ep.serverName | quote }}
{{- end }}
{{- end }}
{{- if and .Values.bootstrap.enabled .Values.bootstrap.publicUrl }}
bootstrap.toml: |
public_url = {{ .Values.bootstrap.publicUrl | quote }}
{{- if .Values.bootstrap.trustedProxies }}
trusted_proxies = [
{{- range $i, $p := .Values.bootstrap.trustedProxies }}
{{ $p | quote }}{{ if lt $i (sub (len $.Values.bootstrap.trustedProxies) 1) }},{{ end }}
{{- end }}
]
{{- end }}
[owner]
email = {{ .Values.bootstrap.owner.email | quote }}
display_name = {{ .Values.bootstrap.owner.displayName | quote }}
{{- if .Values.bootstrap.oidc.issuer }}
[oidc]
issuer = {{ .Values.bootstrap.oidc.issuer | quote }}
audience = {{ .Values.bootstrap.oidc.audience | quote }}
client_id = {{ .Values.bootstrap.oidc.clientId | quote }}
{{- end }}
{{- end }}
@@ -0,0 +1,31 @@
{{- if .Values.externalSecret.enabled -}}
# Example ExternalSecret for External Secrets Operator (Vault / OpenBao / KMS).
# Enable with externalSecret.enabled=true or copy into your GitOps manifest repo.
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: {{ .Values.secrets.existingSecret }}
labels:
{{- include "archie.labels" . | nindent 4 }}
spec:
refreshInterval: {{ .Values.externalSecret.refreshInterval }}
secretStoreRef:
name: {{ .Values.externalSecret.secretStoreRef.name }}
kind: {{ .Values.externalSecret.secretStoreRef.kind }}
target:
name: {{ .Values.secrets.existingSecret }}
creationPolicy: Owner
data:
- secretKey: {{ .Values.secrets.keys.databaseUrl }}
remoteRef:
key: {{ .Values.externalSecret.remoteRefs.databaseUrlKey }}
property: {{ .Values.externalSecret.remoteRefs.databaseUrlProperty }}
- secretKey: {{ .Values.secrets.keys.ageIdentity }}
remoteRef:
key: {{ .Values.externalSecret.remoteRefs.ageIdentityKey }}
property: {{ .Values.externalSecret.remoteRefs.ageIdentityProperty }}
- secretKey: {{ .Values.secrets.keys.adminTokenSha256 }}
remoteRef:
key: {{ .Values.externalSecret.remoteRefs.adminTokenSha256Key }}
property: {{ .Values.externalSecret.remoteRefs.adminTokenSha256Property }}
{{- end }}
@@ -0,0 +1,128 @@
{{- if .Values.frontend.enabled }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "archie.frontendFullname" . }}
labels:
{{- include "archie.frontendLabels" . | nindent 4 }}
spec:
{{- if not .Values.frontend.autoscaling.enabled }}
replicas: {{ .Values.frontend.replicaCount }}
{{- end }}
selector:
matchLabels:
{{- include "archie.frontendSelectorLabels" . | nindent 6 }}
template:
metadata:
labels:
{{- include "archie.frontendLabels" . | nindent 8 }}
spec:
automountServiceAccountToken: false
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
securityContext:
{{- include "archie.compactYaml" .Values.frontend.podSecurityContext | nindent 8 }}
containers:
- name: frontend
image: {{ include "archie.frontendImage" . }}
imagePullPolicy: {{ .Values.frontend.image.pullPolicy }}
securityContext:
{{- include "archie.compactYaml" .Values.frontend.securityContext | nindent 12 }}
ports:
- name: http
containerPort: 8080
protocol: TCP
livenessProbe:
httpGet:
path: /healthz
port: http
readinessProbe:
httpGet:
path: /healthz
port: http
resources:
{{- toYaml .Values.frontend.resources | nindent 12 }}
volumeMounts:
# nginx keeps its pid file and temporary files here; the root
# filesystem is read-only.
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir:
sizeLimit: 64Mi
---
apiVersion: v1
kind: Service
metadata:
name: {{ include "archie.frontendFullname" . }}
labels:
{{- include "archie.frontendLabels" . | nindent 4 }}
spec:
type: ClusterIP
ports:
- name: http
port: {{ .Values.frontend.service.port }}
targetPort: http
protocol: TCP
selector:
{{- include "archie.frontendSelectorLabels" . | nindent 4 }}
{{- if .Values.frontend.autoscaling.enabled }}
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: {{ include "archie.frontendFullname" . }}
labels:
{{- include "archie.frontendLabels" . | nindent 4 }}
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: {{ include "archie.frontendFullname" . }}
minReplicas: {{ .Values.frontend.autoscaling.minReplicas }}
maxReplicas: {{ .Values.frontend.autoscaling.maxReplicas }}
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: {{ .Values.frontend.autoscaling.targetCPUUtilizationPercentage }}
{{- end }}
{{- if .Values.networkPolicy.enabled }}
---
# The dashboard only answers the internal ingress and calls nothing.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: {{ include "archie.frontendFullname" . }}
labels:
{{- include "archie.frontendLabels" . | nindent 4 }}
spec:
podSelector:
matchLabels:
{{- include "archie.frontendSelectorLabels" . | nindent 6 }}
policyTypes:
- Ingress
- Egress
ingress:
- ports:
- protocol: TCP
port: 8080
{{- if or .Values.networkPolicy.ingress.internal.namespaceSelector .Values.networkPolicy.ingress.internal.podSelector }}
from:
- {{- if .Values.networkPolicy.ingress.internal.namespaceSelector }}
namespaceSelector:
{{- toYaml .Values.networkPolicy.ingress.internal.namespaceSelector | nindent 12 }}
{{- end }}
{{- if .Values.networkPolicy.ingress.internal.podSelector }}
podSelector:
{{- toYaml .Values.networkPolicy.ingress.internal.podSelector | nindent 12 }}
{{- end }}
{{- end }}
egress: []
{{- end }}
{{- end }}
@@ -0,0 +1,82 @@
{{- if .Values.ingress.perimeter.enabled }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: {{ include "archie.fullname" . }}-perimeter
labels:
{{- include "archie.labels" . | nindent 4 }}
app.kubernetes.io/component: perimeter-ingress
{{- with .Values.ingress.perimeter.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- if .Values.ingress.perimeter.className }}
ingressClassName: {{ .Values.ingress.perimeter.className }}
{{- end }}
{{- with .Values.ingress.perimeter.tls }}
tls:
{{- toYaml . | nindent 4 }}
{{- end }}
rules:
{{- range .Values.ingress.perimeter.hosts }}
- host: {{ .host | quote }}
http:
paths:
{{- range .paths }}
- path: {{ . }}
pathType: Prefix
backend:
service:
name: {{ include "archie.fullname" $ }}
port:
name: http
{{- end }}
{{- end }}
{{- end }}
{{- if .Values.ingress.internal.enabled }}
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: {{ include "archie.fullname" . }}-internal
labels:
{{- include "archie.labels" . | nindent 4 }}
app.kubernetes.io/component: internal-ingress
{{- with .Values.ingress.internal.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- if .Values.ingress.internal.className }}
ingressClassName: {{ .Values.ingress.internal.className }}
{{- end }}
{{- with .Values.ingress.internal.tls }}
tls:
{{- toYaml . | nindent 4 }}
{{- end }}
rules:
{{- range .Values.ingress.internal.hosts }}
- host: {{ .host | quote }}
http:
paths:
{{- range $.Values.ingress.internal.backendPaths }}
- path: {{ . }}
pathType: Prefix
backend:
service:
name: {{ include "archie.fullname" $ }}
port:
name: http
{{- end }}
{{- if $.Values.frontend.enabled }}
- path: /
pathType: Prefix
backend:
service:
name: {{ include "archie.frontendFullname" $ }}
port:
name: http
{{- end }}
{{- end }}
{{- end }}
@@ -0,0 +1,109 @@
{{- if .Values.bootstrap.enabled -}}
apiVersion: batch/v1
kind: Job
metadata:
name: {{ include "archie.fullname" . }}-bootstrap
labels:
{{- include "archie.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": post-install,post-upgrade
"helm.sh/hook-weight": {{ .Values.bootstrap.hookWeight | quote }}
"helm.sh/hook-delete-policy": {{ .Values.bootstrap.hookDeletePolicy | quote }}
spec:
backoffLimit: {{ .Values.bootstrap.backoffLimit }}
activeDeadlineSeconds: {{ .Values.bootstrap.activeDeadlineSeconds }}
template:
metadata:
labels:
{{- include "archie.labels" . | nindent 8 }}
app.kubernetes.io/component: bootstrap
spec:
restartPolicy: OnFailure
serviceAccountName: {{ include "archie.serviceAccountName" . }}
automountServiceAccountToken: {{ .Values.serviceAccount.automountServiceAccountToken }}
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with (include "archie.compactYaml" .Values.podSecurityContext) }}
securityContext:
{{- . | nindent 8 }}
{{- end }}
containers:
- name: bootstrap
image: {{ include "archie.image" . }}
imagePullPolicy: {{ .Values.image.pullPolicy }}
args:
- "-config"
- ""
- "-spec"
- "/etc/archie/bootstrap.toml"
- "bootstrap"
{{- with (include "archie.compactYaml" .Values.securityContext) }}
securityContext:
{{- . | nindent 12 }}
{{- end }}
env:
- name: HOME
value: "/tmp"
- name: ARCHIE_DATABASE_URL_FILE
value: /run/secrets/archie/{{ .Values.secrets.keys.databaseUrl }}
- name: ARCHIE_BOOTSTRAP_OWNER_PASSWORD_FILE
value: /run/secrets/archie-bootstrap/{{ .Values.bootstrap.owner.passwordSecretKey }}
{{- if .Values.caBundle.enabled }}
- name: SSL_CERT_FILE
value: {{ .Values.caBundle.mountPath | quote }}
{{- end }}
resources:
{{- toYaml .Values.bootstrap.resources | nindent 12 }}
volumeMounts:
- name: config
mountPath: /etc/archie/bootstrap.toml
subPath: bootstrap.toml
readOnly: true
- name: runtime-secrets
mountPath: /run/secrets/archie
readOnly: true
- name: bootstrap-secrets
mountPath: /run/secrets/archie-bootstrap
readOnly: true
- name: tmp
mountPath: /tmp
{{- if .Values.caBundle.enabled }}
- name: ca-bundle
mountPath: {{ .Values.caBundle.mountPath }}
subPath: {{ .Values.caBundle.key }}
readOnly: true
{{- end }}
volumes:
- name: config
configMap:
name: {{ include "archie.fullname" . }}-config
- name: runtime-secrets
secret:
secretName: {{ .Values.secrets.existingSecret }}
defaultMode: 0400
items:
- key: {{ .Values.secrets.keys.databaseUrl }}
path: {{ .Values.secrets.keys.databaseUrl }}
- name: bootstrap-secrets
secret:
secretName: {{ .Values.bootstrap.owner.passwordSecretName }}
defaultMode: 0400
items:
- key: {{ .Values.bootstrap.owner.passwordSecretKey }}
path: {{ .Values.bootstrap.owner.passwordSecretKey }}
- name: tmp
emptyDir: {}
{{- if .Values.caBundle.enabled }}
- name: ca-bundle
{{- if .Values.caBundle.existingSecret }}
secret:
secretName: {{ .Values.caBundle.existingSecret }}
defaultMode: 0444
{{- else }}
configMap:
name: {{ .Values.caBundle.existingConfigMap }}
{{- end }}
{{- end }}
{{- end }}
@@ -0,0 +1,127 @@
{{- if .Values.bundleSync.enabled -}}
apiVersion: batch/v1
kind: Job
metadata:
name: {{ include "archie.fullname" . }}-bundle-sync
labels:
{{- include "archie.labels" . | nindent 4 }}
annotations:
{{- if .Values.bundleSync.hooks.helm }}
"helm.sh/hook": post-install,post-upgrade
"helm.sh/hook-weight": {{ .Values.bundleSync.hookWeight | quote }}
"helm.sh/hook-delete-policy": {{ .Values.bundleSync.hookDeletePolicy | quote }}
{{- end }}
{{- if .Values.bundleSync.hooks.argocd }}
"argocd.argoproj.io/hook": PostSync
"argocd.argoproj.io/hook-delete-policy": BeforeHookCreation
{{- end }}
spec:
backoffLimit: {{ .Values.bundleSync.backoffLimit }}
activeDeadlineSeconds: {{ .Values.bundleSync.activeDeadlineSeconds }}
template:
metadata:
labels:
{{- include "archie.labels" . | nindent 8 }}
app.kubernetes.io/component: bundle-sync
spec:
restartPolicy: OnFailure
serviceAccountName: {{ include "archie.serviceAccountName" . }}
automountServiceAccountToken: {{ .Values.serviceAccount.automountServiceAccountToken }}
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with (include "archie.compactYaml" .Values.podSecurityContext) }}
securityContext:
{{- . | nindent 8 }}
{{- end }}
containers:
- name: bundle-sync
image: {{ include "archie.image" . }}
imagePullPolicy: {{ .Values.image.pullPolicy }}
args:
- "-config"
- ""
- "bundle"
- "apply"
- "--bundle"
- "/etc/archie/bundle/bundle.yaml"
{{- if .Values.bundleSync.bindings.enabled }}
- "--bindings"
- "/etc/archie/bindings/bindings.yaml"
{{- end }}
{{- if .Values.bundleSync.expectDigest }}
- "--expect-digest"
- {{ .Values.bundleSync.expectDigest | quote }}
{{- end }}
{{- if .Values.bundleSync.dryRun }}
- "--dry-run"
{{- end }}
{{- with (include "archie.compactYaml" .Values.securityContext) }}
securityContext:
{{- . | nindent 12 }}
{{- end }}
env:
- name: HOME
value: "/tmp"
# Uses only the DML runtime role (archie_app), never owner_url.
- name: ARCHIE_DATABASE_URL_FILE
value: /run/secrets/archie/{{ .Values.secrets.keys.databaseUrl }}
{{- if .Values.caBundle.enabled }}
- name: SSL_CERT_FILE
value: {{ .Values.caBundle.mountPath | quote }}
{{- end }}
resources:
{{- toYaml .Values.bundleSync.resources | nindent 12 }}
volumeMounts:
- name: bundle
mountPath: /etc/archie/bundle/bundle.yaml
subPath: {{ .Values.bundleSync.bundleKey }}
readOnly: true
{{- if .Values.bundleSync.bindings.enabled }}
- name: bindings
mountPath: /etc/archie/bindings/bindings.yaml
subPath: {{ .Values.bundleSync.bindings.key }}
readOnly: true
{{- end }}
- name: runtime-secrets
mountPath: /run/secrets/archie
readOnly: true
- name: tmp
mountPath: /tmp
{{- if .Values.caBundle.enabled }}
- name: ca-bundle
mountPath: {{ .Values.caBundle.mountPath }}
subPath: {{ .Values.caBundle.key }}
readOnly: true
{{- end }}
volumes:
- name: bundle
configMap:
name: {{ default (printf "%s-bundle" (include "archie.fullname" .)) .Values.bundleSync.existingConfigMap }}
{{- if .Values.bundleSync.bindings.enabled }}
- name: bindings
configMap:
name: {{ default (default (printf "%s-bundle" (include "archie.fullname" .)) .Values.bundleSync.existingConfigMap) .Values.bundleSync.bindings.existingConfigMap }}
{{- end }}
- name: runtime-secrets
secret:
secretName: {{ .Values.secrets.existingSecret }}
defaultMode: 0400
items:
- key: {{ .Values.secrets.keys.databaseUrl }}
path: {{ .Values.secrets.keys.databaseUrl }}
- name: tmp
emptyDir: {}
{{- if .Values.caBundle.enabled }}
- name: ca-bundle
{{- if .Values.caBundle.existingSecret }}
secret:
secretName: {{ .Values.caBundle.existingSecret }}
defaultMode: 0444
{{- else }}
configMap:
name: {{ .Values.caBundle.existingConfigMap }}
{{- end }}
{{- end }}
{{- end }}
@@ -0,0 +1,92 @@
{{- if .Values.migrate.enabled -}}
apiVersion: batch/v1
kind: Job
metadata:
name: {{ include "archie.fullname" . }}-migrate
labels:
{{- include "archie.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": pre-install,pre-upgrade
"helm.sh/hook-weight": {{ .Values.migrate.hookWeight | quote }}
"helm.sh/hook-delete-policy": {{ .Values.migrate.hookDeletePolicy | quote }}
spec:
backoffLimit: {{ .Values.migrate.backoffLimit }}
activeDeadlineSeconds: {{ .Values.migrate.activeDeadlineSeconds }}
template:
metadata:
labels:
{{- include "archie.labels" . | nindent 8 }}
app.kubernetes.io/component: migrate
spec:
restartPolicy: OnFailure
serviceAccountName: {{ include "archie.serviceAccountName" . }}
automountServiceAccountToken: {{ .Values.serviceAccount.automountServiceAccountToken }}
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with (include "archie.compactYaml" .Values.podSecurityContext) }}
securityContext:
{{- . | nindent 8 }}
{{- end }}
containers:
- name: migrate
image: {{ include "archie.image" . }}
imagePullPolicy: {{ .Values.image.pullPolicy }}
args:
- "-config"
- ""
- "migrate"
{{- with (include "archie.compactYaml" .Values.securityContext) }}
securityContext:
{{- . | nindent 12 }}
{{- end }}
env:
- name: HOME
value: "/tmp"
- name: ARCHIE_DATABASE_URL_FILE
value: /run/secrets/archie-migrate/{{ .Values.secrets.keys.databaseUrl }}
- name: ARCHIE_DATABASE_OWNER_URL_FILE
value: /run/secrets/archie-migrate/{{ .Values.secrets.keys.databaseOwnerUrl }}
{{- if .Values.caBundle.enabled }}
- name: SSL_CERT_FILE
value: {{ .Values.caBundle.mountPath | quote }}
{{- end }}
resources:
{{- toYaml .Values.migrate.resources | nindent 12 }}
volumeMounts:
- name: migrate-secrets
mountPath: /run/secrets/archie-migrate
readOnly: true
- name: tmp
mountPath: /tmp
{{- if .Values.caBundle.enabled }}
- name: ca-bundle
mountPath: {{ .Values.caBundle.mountPath }}
subPath: {{ .Values.caBundle.key }}
readOnly: true
{{- end }}
volumes:
- name: migrate-secrets
secret:
secretName: {{ include "archie.migrateSecretName" . }}
defaultMode: 0400
items:
- key: {{ .Values.secrets.keys.databaseUrl }}
path: {{ .Values.secrets.keys.databaseUrl }}
- key: {{ .Values.secrets.keys.databaseOwnerUrl }}
path: {{ .Values.secrets.keys.databaseOwnerUrl }}
- name: tmp
emptyDir: {}
{{- if .Values.caBundle.enabled }}
- name: ca-bundle
{{- if .Values.caBundle.existingSecret }}
secret:
secretName: {{ .Values.caBundle.existingSecret }}
defaultMode: 0444
{{- else }}
configMap:
name: {{ .Values.caBundle.existingConfigMap }}
{{- end }}
{{- end }}
{{- end }}
@@ -0,0 +1,189 @@
{{- if .Values.networkPolicy.enabled -}}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: {{ include "archie.fullname" . }}-default-deny
labels:
{{- include "archie.labels" . | nindent 4 }}
spec:
podSelector:
matchLabels:
{{- include "archie.selectorLabels" . | nindent 6 }}
policyTypes:
- Ingress
- Egress
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: {{ include "archie.fullname" . }}-allow
labels:
{{- include "archie.labels" . | nindent 4 }}
spec:
podSelector:
matchLabels:
{{- include "archie.selectorLabels" . | nindent 6 }}
policyTypes:
- Ingress
- Egress
ingress:
{{- if .Values.ingress.perimeter.enabled }}
- ports:
- protocol: TCP
port: 8080
{{- if or .Values.networkPolicy.ingress.perimeter.namespaceSelector .Values.networkPolicy.ingress.perimeter.podSelector }}
from:
- {{- if .Values.networkPolicy.ingress.perimeter.namespaceSelector }}
namespaceSelector:
{{- toYaml .Values.networkPolicy.ingress.perimeter.namespaceSelector | nindent 12 }}
{{- end }}
{{- if .Values.networkPolicy.ingress.perimeter.podSelector }}
podSelector:
{{- toYaml .Values.networkPolicy.ingress.perimeter.podSelector | nindent 12 }}
{{- end }}
{{- end }}
{{- end }}
{{- if .Values.ingress.internal.enabled }}
- ports:
- protocol: TCP
port: 8080
{{- if or .Values.networkPolicy.ingress.internal.namespaceSelector .Values.networkPolicy.ingress.internal.podSelector }}
from:
- {{- if .Values.networkPolicy.ingress.internal.namespaceSelector }}
namespaceSelector:
{{- toYaml .Values.networkPolicy.ingress.internal.namespaceSelector | nindent 12 }}
{{- end }}
{{- if .Values.networkPolicy.ingress.internal.podSelector }}
podSelector:
{{- toYaml .Values.networkPolicy.ingress.internal.podSelector | nindent 12 }}
{{- end }}
{{- end }}
{{- end }}
{{- if .Values.metrics.serviceMonitor.enabled }}
- ports:
- protocol: TCP
port: {{ .Values.metrics.port }}
{{- if or .Values.networkPolicy.ingress.metrics.namespaceSelector .Values.networkPolicy.ingress.metrics.podSelector }}
from:
- {{- if .Values.networkPolicy.ingress.metrics.namespaceSelector }}
namespaceSelector:
{{- toYaml .Values.networkPolicy.ingress.metrics.namespaceSelector | nindent 12 }}
{{- end }}
{{- if .Values.networkPolicy.ingress.metrics.podSelector }}
podSelector:
{{- toYaml .Values.networkPolicy.ingress.metrics.podSelector | nindent 12 }}
{{- end }}
{{- end }}
{{- end }}
egress:
# DNS resolution
- ports:
- protocol: UDP
port: 53
- protocol: TCP
port: 53
{{- if or .Values.networkPolicy.egress.dns.namespaceSelector .Values.networkPolicy.egress.dns.podSelector }}
to:
- {{- if .Values.networkPolicy.egress.dns.namespaceSelector }}
namespaceSelector:
{{- toYaml .Values.networkPolicy.egress.dns.namespaceSelector | nindent 12 }}
{{- end }}
{{- if .Values.networkPolicy.egress.dns.podSelector }}
podSelector:
{{- toYaml .Values.networkPolicy.egress.dns.podSelector | nindent 12 }}
{{- end }}
{{- end }}
# PostgreSQL / PgBouncer session pool
- ports:
- protocol: TCP
port: {{ .Values.networkPolicy.egress.postgres.port }}
{{- if or .Values.networkPolicy.egress.postgres.cidrs .Values.networkPolicy.egress.postgres.namespaceSelector .Values.networkPolicy.egress.postgres.podSelector }}
to:
{{- range .Values.networkPolicy.egress.postgres.cidrs }}
- ipBlock:
cidr: {{ . | quote }}
{{- end }}
{{- if or .Values.networkPolicy.egress.postgres.namespaceSelector .Values.networkPolicy.egress.postgres.podSelector }}
- {{- if .Values.networkPolicy.egress.postgres.namespaceSelector }}
namespaceSelector:
{{- toYaml .Values.networkPolicy.egress.postgres.namespaceSelector | nindent 12 }}
{{- end }}
{{- if .Values.networkPolicy.egress.postgres.podSelector }}
podSelector:
{{- toYaml .Values.networkPolicy.egress.postgres.podSelector | nindent 12 }}
{{- end }}
{{- end }}
{{- end }}
# OIDC Identity Provider
- ports:
- protocol: TCP
port: {{ .Values.networkPolicy.egress.oidc.port }}
{{- if .Values.networkPolicy.egress.oidc.cidrs }}
to:
{{- range .Values.networkPolicy.egress.oidc.cidrs }}
- ipBlock:
cidr: {{ . | quote }}
{{- end }}
{{- end }}
{{- if or .Values.proxy.httpsProxy .Values.proxy.httpProxy .Values.networkPolicy.egress.proxy.cidrs }}
# Corporate egress proxy
- ports:
- protocol: TCP
port: {{ .Values.networkPolicy.egress.proxy.port }}
{{- if .Values.networkPolicy.egress.proxy.cidrs }}
to:
{{- range .Values.networkPolicy.egress.proxy.cidrs }}
- ipBlock:
cidr: {{ . | quote }}
{{- end }}
{{- end }}
{{- end }}
{{- if or .Values.config.extensions.remote .Values.networkPolicy.egress.extensions.cidrs .Values.networkPolicy.egress.extensions.namespaceSelector .Values.networkPolicy.egress.extensions.podSelector }}
# Remote gRPC+mTLS extension endpoints
- ports:
{{- range .Values.networkPolicy.egress.extensions.ports }}
- protocol: TCP
port: {{ . }}
{{- end }}
{{- if or .Values.networkPolicy.egress.extensions.cidrs .Values.networkPolicy.egress.extensions.namespaceSelector .Values.networkPolicy.egress.extensions.podSelector }}
to:
{{- range .Values.networkPolicy.egress.extensions.cidrs }}
- ipBlock:
cidr: {{ . | quote }}
{{- end }}
{{- if or .Values.networkPolicy.egress.extensions.namespaceSelector .Values.networkPolicy.egress.extensions.podSelector }}
- {{- if .Values.networkPolicy.egress.extensions.namespaceSelector }}
namespaceSelector:
{{- toYaml .Values.networkPolicy.egress.extensions.namespaceSelector | nindent 12 }}
{{- end }}
{{- if .Values.networkPolicy.egress.extensions.podSelector }}
podSelector:
{{- toYaml .Values.networkPolicy.egress.extensions.podSelector | nindent 12 }}
{{- end }}
{{- end }}
{{- end }}
{{- end }}
{{- if or .Values.telemetry.otlpEndpoint .Values.networkPolicy.egress.otlp.cidrs .Values.networkPolicy.egress.otlp.namespaceSelector .Values.networkPolicy.egress.otlp.podSelector }}
# OpenTelemetry collector
- ports:
- protocol: TCP
port: {{ .Values.networkPolicy.egress.otlp.port }}
{{- if or .Values.networkPolicy.egress.otlp.cidrs .Values.networkPolicy.egress.otlp.namespaceSelector .Values.networkPolicy.egress.otlp.podSelector }}
to:
{{- range .Values.networkPolicy.egress.otlp.cidrs }}
- ipBlock:
cidr: {{ . | quote }}
{{- end }}
{{- if or .Values.networkPolicy.egress.otlp.namespaceSelector .Values.networkPolicy.egress.otlp.podSelector }}
- {{- if .Values.networkPolicy.egress.otlp.namespaceSelector }}
namespaceSelector:
{{- toYaml .Values.networkPolicy.egress.otlp.namespaceSelector | nindent 12 }}
{{- end }}
{{- if .Values.networkPolicy.egress.otlp.podSelector }}
podSelector:
{{- toYaml .Values.networkPolicy.egress.otlp.podSelector | nindent 12 }}
{{- end }}
{{- end }}
{{- end }}
{{- end }}
{{- end }}
@@ -0,0 +1,17 @@
{{- if .Values.podDisruptionBudget.enabled -}}
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: {{ include "archie.fullname" . }}
labels:
{{- include "archie.labels" . | nindent 4 }}
spec:
{{- if not (kindIs "invalid" .Values.podDisruptionBudget.minAvailable) }}
minAvailable: {{ .Values.podDisruptionBudget.minAvailable }}
{{- else }}
maxUnavailable: {{ .Values.podDisruptionBudget.maxUnavailable }}
{{- end }}
selector:
matchLabels:
{{- include "archie.selectorLabels" . | nindent 6 }}
{{- end }}
@@ -0,0 +1,23 @@
apiVersion: v1
kind: Service
metadata:
name: {{ include "archie.fullname" . }}
labels:
{{- include "archie.labels" . | nindent 4 }}
{{- with .Values.service.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
type: {{ .Values.service.type }}
ports:
- name: http
port: {{ .Values.service.port }}
targetPort: http
protocol: TCP
- name: metrics
port: {{ .Values.service.metricsPort }}
targetPort: metrics
protocol: TCP
selector:
{{- include "archie.selectorLabels" . | nindent 4 }}
@@ -0,0 +1,13 @@
{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
name: {{ include "archie.serviceAccountName" . }}
labels:
{{- include "archie.labels" . | nindent 4 }}
{{- with .Values.serviceAccount.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
automountServiceAccountToken: {{ .Values.serviceAccount.automountServiceAccountToken }}
{{- end }}
@@ -0,0 +1,20 @@
{{- if .Values.metrics.serviceMonitor.enabled -}}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: {{ include "archie.fullname" . }}
labels:
{{- include "archie.labels" . | nindent 4 }}
{{- with .Values.metrics.serviceMonitor.labels }}
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
selector:
matchLabels:
{{- include "archie.selectorLabels" . | nindent 6 }}
endpoints:
- port: metrics
path: {{ .Values.metrics.path }}
interval: {{ .Values.metrics.serviceMonitor.interval }}
scrapeTimeout: {{ .Values.metrics.serviceMonitor.scrapeTimeout }}
{{- end }}
@@ -0,0 +1,208 @@
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: {{ include "archie.fullname" . }}
labels:
{{- include "archie.labels" . | nindent 4 }}
spec:
serviceName: {{ include "archie.fullname" . }}
# Active-Passive HA in Enterprise v1 requires a single active replica.
replicas: {{ .Values.replicaCount }}
selector:
matchLabels:
{{- include "archie.selectorLabels" . | nindent 6 }}
template:
metadata:
annotations:
checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
{{- with .Values.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
labels:
{{- include "archie.labels" . | nindent 8 }}
{{- with .Values.podLabels }}
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
serviceAccountName: {{ include "archie.serviceAccountName" . }}
automountServiceAccountToken: {{ .Values.serviceAccount.automountServiceAccountToken }}
terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with (include "archie.compactYaml" .Values.podSecurityContext) }}
securityContext:
{{- . | nindent 8 }}
{{- end }}
containers:
- name: archie
image: {{ include "archie.image" . }}
imagePullPolicy: {{ .Values.image.pullPolicy }}
args:
- "-config"
- "/etc/archie/config.toml"
{{- with (include "archie.compactYaml" .Values.securityContext) }}
securityContext:
{{- . | nindent 12 }}
{{- end }}
ports:
- name: http
containerPort: 8080
protocol: TCP
- name: metrics
containerPort: {{ .Values.metrics.port }}
protocol: TCP
env:
- name: HOME
value: "/tmp"
- name: ARCHIE_DATABASE_URL_FILE
value: /run/secrets/archie/{{ .Values.secrets.keys.databaseUrl }}
- name: ARCHIE_AGE_IDENTITY_FILE
value: /run/secrets/archie/{{ .Values.secrets.keys.ageIdentity }}
- name: ARCHIE_ADMIN_TOKEN_SHA256_FILE
value: /run/secrets/archie/{{ .Values.secrets.keys.adminTokenSha256 }}
{{- if .Values.caBundle.enabled }}
- name: SSL_CERT_FILE
value: {{ .Values.caBundle.mountPath | quote }}
{{- end }}
{{- if .Values.proxy.httpsProxy }}
- name: HTTPS_PROXY
value: {{ .Values.proxy.httpsProxy | quote }}
{{- end }}
{{- if .Values.proxy.httpProxy }}
- name: HTTP_PROXY
value: {{ .Values.proxy.httpProxy | quote }}
{{- end }}
{{- if or .Values.proxy.httpsProxy .Values.proxy.httpProxy }}
- name: NO_PROXY
value: {{ .Values.proxy.noProxy | quote }}
{{- end }}
{{- if .Values.telemetry.otlpEndpoint }}
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: {{ .Values.telemetry.otlpEndpoint | quote }}
{{- end }}
{{- with .Values.extraEnv }}
{{- toYaml . | nindent 12 }}
{{- end }}
startupProbe:
httpGet:
path: /startupz
port: http
initialDelaySeconds: {{ .Values.probes.startup.initialDelaySeconds }}
periodSeconds: {{ .Values.probes.startup.periodSeconds }}
timeoutSeconds: {{ .Values.probes.startup.timeoutSeconds }}
failureThreshold: {{ .Values.probes.startup.failureThreshold }}
livenessProbe:
httpGet:
path: /healthz
port: http
initialDelaySeconds: {{ .Values.probes.liveness.initialDelaySeconds }}
periodSeconds: {{ .Values.probes.liveness.periodSeconds }}
timeoutSeconds: {{ .Values.probes.liveness.timeoutSeconds }}
failureThreshold: {{ .Values.probes.liveness.failureThreshold }}
readinessProbe:
httpGet:
path: /readyz
port: http
initialDelaySeconds: {{ .Values.probes.readiness.initialDelaySeconds }}
periodSeconds: {{ .Values.probes.readiness.periodSeconds }}
timeoutSeconds: {{ .Values.probes.readiness.timeoutSeconds }}
failureThreshold: {{ .Values.probes.readiness.failureThreshold }}
resources:
{{- toYaml .Values.resources | nindent 12 }}
volumeMounts:
- name: config
mountPath: /etc/archie/config.toml
subPath: config.toml
readOnly: true
- name: runtime-secrets
mountPath: /run/secrets/archie
readOnly: true
- name: tmp
mountPath: /tmp
- name: state
mountPath: {{ .Values.config.stateDir }}
{{- if .Values.caBundle.enabled }}
- name: ca-bundle
mountPath: {{ .Values.caBundle.mountPath }}
subPath: {{ .Values.caBundle.key }}
readOnly: true
{{- end }}
{{- if .Values.config.extensions.tls.existingSecret }}
- name: extensions-tls
mountPath: {{ .Values.config.extensions.tls.mountPath }}
readOnly: true
{{- end }}
{{- if .Values.config.catalogue.authSecret }}
- name: catalogue-auth
mountPath: /run/secrets/archie-catalogue
readOnly: true
{{- end }}
volumes:
- name: config
configMap:
name: {{ include "archie.fullname" . }}-config
- name: runtime-secrets
secret:
secretName: {{ .Values.secrets.existingSecret }}
defaultMode: 0400
items:
- key: {{ .Values.secrets.keys.databaseUrl }}
path: {{ .Values.secrets.keys.databaseUrl }}
- key: {{ .Values.secrets.keys.ageIdentity }}
path: {{ .Values.secrets.keys.ageIdentity }}
- key: {{ .Values.secrets.keys.adminTokenSha256 }}
path: {{ .Values.secrets.keys.adminTokenSha256 }}
- name: tmp
emptyDir: {}
{{- if not .Values.persistence.enabled }}
- name: state
emptyDir: {}
{{- else if .Values.persistence.existingClaim }}
- name: state
persistentVolumeClaim:
claimName: {{ .Values.persistence.existingClaim }}
{{- end }}
{{- if .Values.caBundle.enabled }}
- name: ca-bundle
{{- if .Values.caBundle.existingSecret }}
secret:
secretName: {{ .Values.caBundle.existingSecret }}
defaultMode: 0444
{{- else }}
configMap:
name: {{ .Values.caBundle.existingConfigMap }}
{{- end }}
{{- end }}
{{- if .Values.config.extensions.tls.existingSecret }}
- name: extensions-tls
secret:
secretName: {{ .Values.config.extensions.tls.existingSecret }}
defaultMode: 0400
{{- end }}
{{- if .Values.config.catalogue.authSecret }}
- name: catalogue-auth
secret:
secretName: {{ .Values.config.catalogue.authSecret }}
defaultMode: 0400
items:
- key: {{ .Values.config.catalogue.authSecretKey }}
path: config.json
{{- end }}
{{- if and .Values.persistence.enabled (not .Values.persistence.existingClaim) }}
volumeClaimTemplates:
- metadata:
name: state
labels:
{{- include "archie.labels" . | nindent 10 }}
spec:
accessModes:
{{- toYaml .Values.persistence.accessModes | nindent 10 }}
{{- if .Values.persistence.storageClass }}
storageClassName: {{ .Values.persistence.storageClass | quote }}
{{- end }}
resources:
requests:
storage: {{ .Values.persistence.size | quote }}
{{- end }}
+32
View File
@@ -0,0 +1,32 @@
# Development stage overlay: isolated non-prod database, key, and relaxed egress for local testing.
image:
tag: "dev"
pullPolicy: IfNotPresent
config:
catalogue:
disableAutoUpdate: false
extensions:
requireRemote: true
persistence:
size: "2Gi"
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "512Mi"
networkPolicy:
enabled: false
podDisruptionBudget:
enabled: false
metrics:
serviceMonitor:
enabled: false
@@ -0,0 +1,32 @@
# OpenShift restricted-v2 SCC overlay: let OpenShift allocate namespace UIDs
# and GID 0 rather than pinning UID/GID 65532.
# Example:
# helm upgrade --install archie deployments/helm/archie \
# -f deployments/helm/archie/values-prod.yaml \
# -f deployments/helm/archie/values-openshift.yaml
podSecurityContext:
runAsNonRoot: true
runAsUser: null
runAsGroup: null
fsGroup: null
fsGroupChangePolicy: OnRootMismatch
seccompProfile:
type: RuntimeDefault
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
runAsNonRoot: true
runAsUser: null
capabilities:
drop:
- ALL
frontend:
podSecurityContext:
runAsNonRoot: true
runAsUser: null
runAsGroup: null
seccompProfile:
type: RuntimeDefault
+68
View File
@@ -0,0 +1,68 @@
# Production stage overlay: full restricted hardening, split ingress, remote mTLS extensions, and PDB.
replicaCount: 1
image:
# Always pin an immutable cosign-verified digest in production (for example "sha256:...").
digest: ""
pullPolicy: IfNotPresent
terminationGracePeriodSeconds: 45
config:
shutdownGrace: "30s"
catalogue:
disableAutoUpdate: true
extensions:
requireRemote: true
persistence:
enabled: true
size: "20Gi"
resources:
requests:
cpu: "500m"
memory: "512Mi"
limits:
cpu: "2000m"
memory: "2Gi"
ingress:
perimeter:
enabled: true
className: "external-nginx"
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "true"
nginx.ingress.kubernetes.io/limit-rps: "25"
hosts:
- host: hooks.archie.example.com
paths:
- /hooks
- /webhooks
tls:
- secretName: archie-prod-perimeter-tls
hosts:
- hooks.archie.example.com
internal:
enabled: true
className: "internal-nginx"
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "true"
hosts:
- host: archie.internal.example.com
tls:
- secretName: archie-prod-internal-tls
hosts:
- archie.internal.example.com
networkPolicy:
enabled: true
metrics:
serviceMonitor:
enabled: true
podDisruptionBudget:
enabled: true
maxUnavailable: 1
@@ -0,0 +1,55 @@
# Staging stage overlay: mirrors production hardening and ingress isolation with its own DB and keys.
image:
# Pin digest before promoting from dev to staging.
digest: ""
config:
catalogue:
disableAutoUpdate: true
extensions:
requireRemote: true
persistence:
size: "5Gi"
resources:
requests:
cpu: "250m"
memory: "256Mi"
limits:
cpu: "1000m"
memory: "1Gi"
ingress:
perimeter:
enabled: true
className: "external-nginx"
hosts:
- host: hooks.staging.archie.example.com
paths:
- /hooks
- /webhooks
tls:
- secretName: archie-staging-perimeter-tls
hosts:
- hooks.staging.archie.example.com
internal:
enabled: true
className: "internal-nginx"
hosts:
- host: archie.staging.internal.example.com
tls:
- secretName: archie-staging-internal-tls
hosts:
- archie.staging.internal.example.com
networkPolicy:
enabled: true
metrics:
serviceMonitor:
enabled: true
podDisruptionBudget:
enabled: false
+332
View File
@@ -0,0 +1,332 @@
# Default production-oriented values for Archie Enterprise (Active-Passive v1).
# Pair with values-dev.yaml, values-staging.yaml, or values-prod.yaml.
replicaCount: 1
image:
repository: ghcr.io/samcharles93/archie
tag: "v1.0.0"
# Set digest (e.g. "sha256:...") to pin the exact immutable artifact in staging and prod.
digest: ""
pullPolicy: IfNotPresent
imagePullSecrets: []
nameOverride: ""
fullnameOverride: ""
serviceAccount:
create: true
name: ""
annotations: {}
automountServiceAccountToken: false
# Exceeds config.shutdownGrace (30s) so active requests and run checkpoints drain on SIGTERM.
terminationGracePeriodSeconds: 45
podAnnotations: {}
podLabels: {}
podSecurityContext:
runAsNonRoot: true
runAsUser: 65532
runAsGroup: 65532
fsGroup: 65532
fsGroupChangePolicy: OnRootMismatch
seccompProfile:
type: RuntimeDefault
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
runAsNonRoot: true
runAsUser: 65532
capabilities:
drop:
- ALL
config:
listen: "0.0.0.0:8080"
stateDir: "/var/lib/archie"
shutdownGrace: "30s"
# Public age1... backup recipients used alongside the primary sealing identity.
ageBackupRecipients: []
catalogue:
# Must be set together with publicKey when overriding the default catalogue mirror.
location: ""
publicKey: ""
disableAutoUpdate: true
# Optional Secret containing Docker config.json for private OCI catalogue registries.
authSecret: ""
authSecretKey: "config.json"
extensions:
# Kubernetes restricted PSS forbids CLONE_NEWUSER namespaces; require remote gRPC+mTLS extensions.
requireRemote: true
tls:
# Secret holding ca.crt, tls.crt, and tls.key for mTLS client authentication to extensions.
existingSecret: ""
mountPath: "/etc/archie/extensions-tls"
# Map extension key or name to { address: "ext.ns.svc:50051", serverName: "ext.internal" }.
remote: {}
secrets:
# Secret holding database-url, age-identity, and admin-token-sha256 for runtime pods.
existingSecret: "archie-runtime-secrets"
keys:
databaseUrl: "database-url"
databaseOwnerUrl: "database-owner-url"
ageIdentity: "age-identity"
adminTokenSha256: "admin-token-sha256"
caBundle:
enabled: false
existingConfigMap: ""
existingSecret: ""
key: "ca-certificates.crt"
mountPath: "/etc/ssl/certs/archie-ca.crt"
proxy:
httpsProxy: ""
httpProxy: ""
noProxy: "localhost,127.0.0.1,.svc,.cluster.local"
telemetry:
otlpEndpoint: ""
extraEnv: []
persistence:
enabled: true
existingClaim: ""
storageClass: ""
accessModes:
- ReadWriteOnce
size: "10Gi"
resources:
requests:
cpu: "250m"
memory: "256Mi"
limits:
cpu: "1000m"
memory: "1Gi"
probes:
startup:
initialDelaySeconds: 2
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 30
liveness:
initialDelaySeconds: 10
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3
readiness:
initialDelaySeconds: 2
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
migrate:
enabled: true
# Dedicated migration secret holding database-owner-url and database-url.
# Keeps DDL credentials completely out of the runtime StatefulSet.
existingSecret: "archie-migrate-secrets"
hookWeight: "-5"
hookDeletePolicy: "before-hook-creation,hook-succeeded"
backoffLimit: 3
activeDeadlineSeconds: 300
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "256Mi"
bootstrap:
enabled: false
hookWeight: "-1"
hookDeletePolicy: "before-hook-creation,hook-succeeded"
backoffLimit: 2
activeDeadlineSeconds: 180
publicUrl: ""
trustedProxies: []
owner:
email: ""
displayName: "Platform Owner"
passwordSecretName: "archie-bootstrap-secrets"
passwordSecretKey: "owner-password"
oidc:
issuer: ""
audience: ""
clientId: ""
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "256Mi"
bundleSync:
enabled: false
hooks:
helm: true
argocd: true
hookWeight: "5"
hookDeletePolicy: "before-hook-creation,hook-succeeded"
backoffLimit: 2
activeDeadlineSeconds: 180
# ConfigMap holding bundle.yaml (and optional bindings.yaml).
existingConfigMap: ""
bundleKey: "bundle.yaml"
bindings:
enabled: true
# Optional separate ConfigMap for stage-local bindings; falls back to bundleSync.existingConfigMap.
existingConfigMap: ""
key: "bindings.yaml"
expectDigest: ""
dryRun: false
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "256Mi"
service:
type: ClusterIP
port: 8080
metricsPort: 9090
annotations: {}
metrics:
enabled: true
port: 9090
path: "/metrics"
serviceMonitor:
enabled: false
interval: "30s"
scrapeTimeout: "10s"
labels: {}
# The dashboard: static files served by its own image, routed by the internal
# ingress on the same host as the API.
frontend:
enabled: true
replicaCount: 2
image:
repository: ghcr.io/archie-platform/archie-frontend
tag: "v0.1.0"
digest: ""
pullPolicy: IfNotPresent
podSecurityContext:
runAsNonRoot: true
runAsUser: 101
runAsGroup: 101
seccompProfile:
type: RuntimeDefault
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
runAsNonRoot: true
capabilities:
drop:
- ALL
resources:
requests:
cpu: "25m"
memory: "32Mi"
limits:
cpu: "250m"
memory: "128Mi"
autoscaling:
enabled: false
minReplicas: 2
maxReplicas: 6
targetCPUUtilizationPercentage: 70
service:
port: 8080
ingress:
# External edge ingress admitting webhook intake (/hooks/ and /webhooks/) only.
perimeter:
enabled: false
className: ""
annotations: {}
hosts: []
tls: []
# Internal corporate VPN / SSO ingress. On each host, backendPaths go to the
# API and every other path to the dashboard.
internal:
enabled: false
className: ""
annotations: {}
hosts: []
backendPaths:
- /api
- /oauth2
- /hooks
tls: []
networkPolicy:
enabled: true
ingress:
perimeter:
namespaceSelector: {}
podSelector: {}
internal:
namespaceSelector: {}
podSelector: {}
metrics:
namespaceSelector: {}
podSelector: {}
egress:
dns:
namespaceSelector:
kubernetes.io/metadata.name: kube-system
podSelector:
k8s-app: kube-dns
postgres:
port: 5432
cidrs: []
namespaceSelector: {}
podSelector: {}
oidc:
port: 443
cidrs: []
proxy:
port: 3128
cidrs: []
extensions:
ports:
- 50051
cidrs: []
namespaceSelector: {}
podSelector: {}
otlp:
port: 4317
cidrs: []
namespaceSelector: {}
podSelector: {}
podDisruptionBudget:
enabled: false
maxUnavailable: 1
minAvailable: null
externalSecret:
enabled: false
refreshInterval: "1h"
secretStoreRef:
name: "vault-backend"
kind: "ClusterSecretStore"
remoteRefs:
databaseUrlKey: "archie/prod/database"
databaseUrlProperty: "runtime_url"
ageIdentityKey: "archie/prod/age"
ageIdentityProperty: "identity"
adminTokenSha256Key: "archie/prod/admin"
adminTokenSha256Property: "token_sha256"
+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.
+3 -2
View File
@@ -44,6 +44,7 @@ services:
# ── NATS JetStream ──────────────────────────────────────────────── # ── NATS JetStream ────────────────────────────────────────────────
nats: nats:
profiles: ["nats"]
image: nats:2.14-alpine3.22 image: nats:2.14-alpine3.22
# The client port is published on every interface (agent containers reach # The client port is published on every interface (agent containers reach
# it over the bridge), so it defers every login to archied. Set NATS_TOKEN # it over the bridge), so it defers every login to archied. Set NATS_TOKEN
@@ -51,8 +52,8 @@ services:
# the account nkey seed named in [nats] callout_issuer_seed_env. # the account nkey seed named in [nats] callout_issuer_seed_env.
command: ["-c", "/etc/nats/nats.conf"] command: ["-c", "/etc/nats/nats.conf"]
environment: environment:
NATS_TOKEN: ${NATS_TOKEN:?NATS_TOKEN is required} - NATS_TOKEN
NATS_CALLOUT_ISSUER: ${NATS_CALLOUT_ISSUER:?NATS_CALLOUT_ISSUER is required} - NATS_CALLOUT_ISSUER
ports: ports:
- "4222:4222" # client - "4222:4222" # client
- "127.0.0.1:8222:8222" # monitoring (http://localhost:8222) - "127.0.0.1:8222:8222" # monitoring (http://localhost:8222)
@@ -0,0 +1,54 @@
# Enterprise Compliance Control Mapping
Archie enforces preventive, detective, and corrective controls in code and deployment files. This guide maps each control to its source code, deployment files, `go test -short` tests, and compliance frameworks. It covers SOC 2 (CC6, CC7, CC8), ISO/IEC 27001:2022, SOX ITGC, and APRA CPS 234.
## Control Matrix
| Control area | Archie code | Deployment files | Automated test proof | Framework mapping |
| --- | --- | --- | --- | --- |
| Database role split | `pg.Migrate` (`owner_url`) vs DML-only `url` checked by `pg.VerifySchema` (`internal/platform/pg/pg.go`) | `job-migrate.yaml` mounts `owner_url`; `statefulset.yaml` and `compose.enterprise.yml` omit `owner_url` | `TestMissingMigrations` (`internal/platform/pg/pg_test.go`), `TestLoadMigrateConfigRequiresOnlyDatabaseRoles` (`internal/app/archie/config_test.go`) | SOC 2 CC6.1, CC6.3; ISO 27001 A.5.15, A.8.2; SOX ITGC Access; CPS 234 (15-17) |
| API and setup gate | Cedar policy checks on every route (`internal/app/archie/api.go`, `modules/governance/access.go`) and closed gate (`internal/app/archie/gate.go`) | Split internal vs perimeter ingress (`ingress.yaml`) | `TestEveryOperationIsAuthorized`, `TestUnwiredAuthorizerRefuses` (`internal/app/archie/access_test.go`), `TestClosedGateServesOnlySetup`, `TestGateIsNotBypassedByPathTricks` (`internal/app/archie/gate_test.go`), `TestEnforcementFailsClosedAndRecordsDecisions` (`modules/governance/enforce_test.go`) | SOC 2 CC6.1, CC6.2; ISO 27001 A.5.15, A.8.3; SOX ITGC Access; CPS 234 (15-18) |
| Identity and SSO | Confidential OIDC, role mapping, SSO-only mode, session limits, and back-channel logout (`modules/governance/oidc.go`, `identity.go`) | Headless `archie bootstrap` (`job-bootstrap.yaml`, `internal/app/archie/bootstrap.go`) | `TestAuthenticateRequest` (`modules/governance/auth_test.go`), `TestAuthenticationSettingsRejectUntrustedOrigins`, `TestPasswordVerification` (`modules/governance/identity_test.go`), `TestLoadBootstrapSpecAndEnvFiles` (`internal/app/archie/bootstrap_test.go`) | SOC 2 CC6.1, CC6.2; ISO 27001 A.5.17, A.8.5; SOX ITGC Access; CPS 234 (15-17) |
| Four-eyes SoD and step-up | Cedar judgement (`modules/judgement/`), passkey checks (`modules/approvals/`), and SoD rule blocking self-approval | Stage-local autonomy caps; prod approval gates | `TestDashboardAnswerComesFromAnAccountWhoseRoleMayApprove`, `TestIrreversibleActionsNeedFreshAuthentication` (`modules/approvals/dashboard_test.go`), `TestExecuteApprovedRunsOnlyWhatThePersonSaw` (`modules/judgement/judgement_test.go`), `TestChatProhibitsPrivilegedActions` (`modules/judgement/chat_test.go`) | SOC 2 CC6.3, CC8.1; ISO 27001 A.5.3; SOX ITGC Changes; CPS 234 (16-18) |
| Keys and secrets | Label-bound `age` X25519 sealing (`internal/platform/seal/seal.go`), `*_FILE` loading (`config.go`), `archie rekey`, and log redaction (`auditjson/`) | `*_FILE` mounts in `statefulset.yaml` and `compose.enterprise.yml`; `externalsecret.example.yaml` | `TestSealedValueOpensOnlyWhereItBelongs` (`internal/platform/seal/seal_test.go`), `TestCredentialRoutesNeverReturnASecret`, `TestBearerTokenByIDRespectsScope` (`modules/connectors/credentials_test.go`), `TestStoredPayloadKeepsCredentialsOut` (`internal/platform/auditjson/auditjson_test.go`), `TestLoadConfigRuntimeAndEnvFiles` (`internal/app/archie/config_test.go`) | SOC 2 CC6.1, CC6.7; ISO 27001 A.8.24; SOX ITGC Access; CPS 234 (15-20) |
| Pod and extension isolation | `RemoteGRPCRuntime` over mTLS (`modules/connectors/internal/host/remote.go`) and `LocalNamespaceRuntime` with egress tunnel (`egress/tunnel.go`) | `restricted` PSS in `statefulset.yaml`; `seccomp.json` in `compose.enterprise.yml`; `networkpolicy.yaml` | `TestRemoteGRPCRequiresMTLSAndEnforcesTrust` (`modules/connectors/internal/host/remote_test.go`), `TestCommandConfinesOnlyWithEgress`, `TestNamespaceLimitRefusesDisabledNamespaces` (`modules/connectors/internal/host/host_test.go`), `TestTunnelEnforcesAllowListBeforeCorporateProxy` (`modules/connectors/internal/egress/tunnel_test.go`) | SOC 2 CC6.6, CC6.7; ISO 27001 A.8.20, A.8.22; SOX ITGC Ops; CPS 234 (16-18) |
| Supply chain and webhooks | Ed25519-signed catalogues with SHA-256 checks (`catalogue/`) and pre-parse HMAC checks (`modules/events/verify.go`) | Digest-pinned images (`values-prod.yaml`); `[catalogue]` mirror; perimeter `/hooks/` ingress | `TestFetchRefusesAnArtifactWhoseDigestDoesNotMatch`, `TestAcceptRefusesGrantsTheExtensionNeverDeclared`, `TestVerifyRefusesAForgedOrMalformedCatalogue` (`modules/connectors/internal/catalogue/catalogue_test.go`), `TestReadOCIChecksSignatureAndPackagePin` (`oci_test.go`), `TestHMACSourceVerifiesBeforeParsing` (`modules/events/verify_test.go`) | SOC 2 CC7.1, CC8.1; ISO 27001 A.8.25, A.8.28; SOX ITGC Changes; CPS 234 (21-22) |
| Audit, tracing, and changes | Append-only `audit.events` (`SELECT`, `INSERT`), stdout JSON audit logs, OTel trace IDs, `archie bundle`, and change windows | `servicemonitor.yaml`; SIEM log shipping; `values-{dev,staging,prod}.yaml` | `TestEveryDecisionIsRecorded`, `TestAllowedDecisionNeedsItsRecord` (`modules/governance/decisions_test.go`), `TestReadAuditRoleBoundary` (`modules/governance/access_test.go`), `TestTimingHoldsChangingActionsOutsideTheSchedule` (`modules/governance/timing_test.go`), `TestAutonomyIsEarnedSlowlyAndLostAtOnce` (`modules/judgement/autonomy_test.go`) | SOC 2 CC7.2, CC7.3, CC8.1; ISO 27001 A.8.15, A.8.32; SOX ITGC Changes, Ops; CPS 234 (23-28) |
| Availability and deletion record | `/healthz`, `/startupz`, `/readyz` (`health/health.go`), `ClaimServe` lock (`pg/pg.go`), and deletion ledger (`deletions/deletions.go`) | RWO PVC in `statefulset.yaml`; `poddisruptionbudget.yaml`; `dr-and-backup.md` drill | `TestProbesSeparateStartupFromReadiness` (`internal/platform/health/health_test.go`), `TestLogRecordsEachDeletion` (`internal/platform/deletions/deletions_test.go`), `TestForgetCommitsThenRecords`, `TestReapplyDeletionsAppliesEveryRecordedNote` (`modules/memory/notes_test.go`) | SOC 2 CC7.4, A1.2; ISO 27001 A.5.30; SOX ITGC Ops; CPS 234 (19, 25) |
## Framework Alignment Summary
### SOC 2 (CC6, CC7, CC8)
- **CC6 (Access Controls):** Archie enforces OIDC SSO, Cedar checks on every route (`TestEveryOperationIsAuthorized`), DML-only database roles, `age` sealing, and default-deny `NetworkPolicy`.
- **CC7 (System Operations):** Archie checks webhook HMACs before parsing (`TestHMACSourceVerifiesBeforeParsing`), runs as UID `65532` with a read-only root filesystem, and exposes `/healthz`, `/startupz`, `/readyz`, stdout JSON audit logs, and `/metrics`.
- **CC8 (Change Management):** Archie splits `archie migrate` from serving pods, signs extension catalogues, promotes stages with `archie bundle`, checks change windows (`TestTimingHoldsChangingActionsOutsideTheSchedule`), and enforces SoD on approvals.
### ISO/IEC 27001:2022
- **Access Rights (A.5.15, A.5.17, A.8.2, A.8.5):** Separate `archie_owner` and `archie_app` roles limit schema rights. OIDC role mapping, SSO-only mode, and passkey checks gate high-risk actions.
- **Crypto and Networks (A.8.20, A.8.22, A.8.24):** Deployments use PostgreSQL `sslmode=verify-full`, TLS 1.3 mTLS for remote gRPC extensions, `age` keys with backup recipients, and `HTTPS_PROXY` allow-lists.
- **Logs, Supply Chain, and Continuity (A.8.15, A.8.25, A.8.32, A.5.30):** Append-only audit logs, Ed25519-signed catalogues, `task check` (`golangci-lint`, `gosec`, `go test -short`), and quarterly DR drills cover daily operations.
### SOX ITGC
- **Access to Programs and Data:** Only `archie migrate` holds DDL rights. Runtime pods cannot change schemas, edit audit rows, or return secrets (`TestCredentialRoutesNeverReturnASecret`).
- **Program Changes:** Stages stay isolated across `dev`, `staging`, and `prod`. Digest-pinned OCI images, `archie bundle diff` and `apply`, and four-eyes SoD gate all changes.
- **Computer Operations:** `ClaimServe` blocks serving pods during database restores. `shutdown_grace` drains active runs cleanly. `memory.ReapplyDeletions` keeps deleted notes removed after a snapshot restore.
### APRA CPS 234
- **Asset Controls and Testing (Paragraphs 15-22):** Controls scale with impact via Cedar guards, extension trust ceilings (`TestGuardExtensionsDecideAtTheLowestCeiling`), mTLS checks, and automated `task check` suites.
- **Detection and Recovery (Paragraphs 23-28):** Pre-parse webhook checks, stdout JSON audit streams to SIEM/WORM storage, OpenTelemetry trace IDs, and quarterly DR drills provide full audit trails.
## Continuous Gate
Run the repository gate, Helm lint, and prose checks before each release and audit:
```bash
task check
helm lint deployments/helm/archie -f deployments/helm/archie/values-prod.yaml
vale docs/enterprise/*.md
```
`task check` runs `go test -short ./...`, `golangci-lint` (including `gosec`), and generated schema and OpenAPI checks.
@@ -0,0 +1,99 @@
# Enterprise Deployment Architecture
Archie runs as a single static binary (`cmd/archie`) backed by PostgreSQL. Regulated deployments isolate each stage, separate DDL from DML credentials, split external webhook ingress from internal operator access, and enforce strict pod or container boundaries.
## Multi-Stage Isolation Zones
Deploy Archie into three independent stages: `dev`, `staging`, and `prod`. Each stage runs its own Archie instance and shares no runtime state with any other stage.
| Resource | `dev` | `staging` | `prod` |
| --- | --- | --- | --- |
| Kubernetes namespace or host | `archie-dev` | `archie-staging` | `archie-prod` |
| PostgreSQL database | Isolated dev instance | Isolated staging instance | Managed HA PostgreSQL (`sslmode=verify-full`) |
| `age` sealing key | Stage-local `age_identity` | Stage-local `age_identity` | Stage-local `age_identity` with offline `age_backup_recipients` |
| OIDC client | Non-prod IdP client | Staging IdP client | Production IdP confidential client |
| Earned autonomy | Local to `dev` | Local to `staging` | Built independently in `prod` |
| Helm overlay | `values-dev.yaml` | `values-staging.yaml` | `values-prod.yaml` |
Earned autonomy in `staging` never promotes to `prod`. Promote declarative configuration (workflows, Cedar policies, judgement rules, and action-type metadata) with `archie bundle`. Keep credentials, OIDC bindings, target hosts, and autonomy counters local to each stage.
Pin container images by immutable SHA-256 digest (`image.digest` in Helm) and verify cosign signatures before deploying to `staging` and `prod`. Set `[catalogue]` `disable_auto_update = true` and mirror signed extension catalogues internally in air-gapped stages.
### Stage Promotion Models
Choose one of two promotion workflows depending on your delivery pipeline:
1. **Push CI/CD (GitHub Actions, GitLab CI, or Jenkins):**
- On pull requests, run `archie bundle validate` offline to check workflow YAML, Cedar policy syntax, judgement rules, and stage `Bindings` without database access.
- Export the tested bundle from `staging` and record its canonical SHA-256 digest (`Bundle.Digest()`).
- After manual change approval, the `prod` pipeline runs `archie bundle apply --expect-digest <sha256>` over HTTPS using `ARCHIE_URL` and `ARCHIE_TOKEN_FILE`. The CI runner never touches PostgreSQL directly.
2. **Pull GitOps (Argo CD or Flux):**
- Store the stage Helm values (`values-staging.yaml`, `values-prod.yaml`), `bundle.yaml`, and stage-local `bindings.yaml` in Git.
- Enable `bundleSync.enabled: true` in `deployments/helm/archie` to run `templates/job-bundle-sync.yaml` as an Argo CD `PostSync` or Helm `post-install,post-upgrade` Job.
- The Job mounts the bundle `ConfigMap`, uses only the runtime `archie_app` database secret (`ARCHIE_DATABASE_URL_FILE`), and applies unchanged bundles idempotently with optional `expectDigest` verification.
## Split Ingress and Network Boundaries
Separate external webhook delivery from operator and administrator access using two ingress resources (`deployments/helm/archie/templates/ingress.yaml`):
1. **Perimeter webhook ingress (`ingress.perimeter`):** Expose only webhook intake paths (`/hooks/` for `cmd/archie` intake and `/webhooks/` where routed by a reverse proxy). Terminate TLS at the edge and apply rate limits. The `events` module verifies each payload's HMAC signature before parsing JSON (`modules/events/verify.go`).
2. **Internal operator ingress (`ingress.internal`):** Serve the Dashboard, `/api/`, and OIDC routes behind a corporate VPN or internal load balancer. Never expose `/api/` or the setup surface on the perimeter ingress.
Enforce default-deny `NetworkPolicy` rules (`deployments/helm/archie/templates/networkpolicy.yaml`) in `staging` and `prod`. Permit ingress only from the perimeter ingress controller (port `8080`), internal ingress controller (port `8080`), and Prometheus scraper (port `9090` on `/metrics`). Permit egress only to DNS (`53`), PostgreSQL or PgBouncer (`5432`), the OIDC issuer (`443`), configured remote extension endpoints, the corporate proxy (`HTTPS_PROXY`), and the OpenTelemetry collector (`4317`).
## Database Role Split and PgBouncer Session Pooling
Archie separates schema ownership from runtime operations across two PostgreSQL roles:
- **`archie_owner` (`ARCHIE_DATABASE_OWNER_URL_FILE`):** Holds DDL rights. Used only by `archie migrate` inside the Helm pre-install/pre-upgrade `Job` (`job-migrate.yaml`) or the Compose `archie-migrate` init service (`deployments/archie/compose.enterprise.yml`).
- **`archie_app` (`ARCHIE_DATABASE_URL_FILE`):** Holds only `USAGE` and DML privileges (`SELECT`, `INSERT`, `UPDATE`, `DELETE`, and `SELECT` on `public.goose_db_version`). The runtime `StatefulSet` and Compose `archie` service mount only this credential. At startup, `pg.VerifySchema` (`internal/platform/pg/pg.go`) checks that every embedded migration is applied and fails closed if the schema lags behind.
### PgBouncer Session-Pooling Requirement for `ClaimServe`
At boot, `cmd/archie` calls `pg.ClaimServe` (`internal/platform/pg/pg.go`). `ClaimServe` opens a dedicated connection via `db.Conn(ctx)` and acquires a shared PostgreSQL session advisory lock (`pg_try_advisory_lock_shared(hashtextextended('archie.serve.owner', 0))`). It holds that lock for the entire lifetime of the serving process. A database restore takes the same key exclusively so no serving pod can start or run during a restore window.
If you deploy PgBouncer in front of PostgreSQL, configure `pool_mode = session` for Archie's runtime pool. PgBouncer `transaction` and `statement` pooling modes share server backends across clients and release or drop session advisory locks between transactions. Direct connections to the HA PostgreSQL primary also satisfy this requirement.
## Pod Security and Extension Confinement
Extension execution differs between Kubernetes and Docker Compose because Kubernetes `restricted` Pod Security Standards forbid user namespaces.
| Control | Kubernetes (`deployments/helm/archie`) | Hardened Compose (`deployments/archie/compose.enterprise.yml`) |
| --- | --- | --- |
| User and root filesystem | `runAsNonRoot: true`, UID/GID `65532`, read-only root filesystem, `allowPrivilegeEscalation: false`, `capabilities.drop: [ALL]` | `user: "65532:65532"`, `read_only: true`, `tmpfs: /tmp`, `cap_drop: [ALL]`, `no-new-privileges:true` |
| Seccomp profile | `seccompProfile.type: RuntimeDefault` | `deployments/archie/seccomp.json` (Docker default plus `clone` for namespaces) |
| Extension runtime | `RemoteGRPCRuntime` over mTLS or Unix socket (`require_remote = true`) | `LocalNamespaceRuntime` (`CLONE_NEWUSER` and `CLONE_NEWNET`) |
| Egress proxy and PKI | `HTTPS_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` propagated to runtime and `NetworkPolicy` | `HTTPS_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` propagated into confined namespaces |
In Kubernetes, run extensions as separate Pods or sidecars under `restricted` Pod Security Standards and isolate them with `NetworkPolicy`. Configure `[extensions]` in `config.toml` (`templates/configmap.yaml`) with `require_remote = true`, TLS 1.3 mTLS certificates (`ca_file`, `cert_file`, `key_file`), and explicit `[extensions.remote.<name>]` targets. If neither `RemoteGRPCRuntime` nor `LocalNamespaceRuntime` is available, `modules/connectors/internal/host/remote.go` fails closed.
In Docker Compose and VM hosts, `LocalNamespaceRuntime` confines each extension binary in its own user and network namespace behind an allow-list forward proxy (`modules/connectors/internal/egress/tunnel.go`). The tunnel enforces Archie's host allow-list and loopback checks before chaining allowed traffic through `HTTPS_PROXY`.
### OpenShift `restricted-v2` SCC
OpenShift's default `restricted-v2` security context rejects pinned `runAsUser`, `runAsGroup`, and `fsGroup` values because it assigns UIDs per namespace. Add [values-openshift.yaml](../../deployments/helm/archie/values-openshift.yaml) alongside `values-prod.yaml` to omit those numeric IDs while keeping `runAsNonRoot: true`, `allowPrivilegeEscalation: false`, and a read-only root filesystem.
## Private OCI and Air-Gapped Catalogues
Private OCI registries authenticate through `[catalogue]` in `config.toml` or container environment variables:
- **Docker config file:** Set `catalogue.auth_file` (`ARCHIE_CATALOGUE_AUTH_FILE`) or set `config.catalogue.authSecret` in Helm to mount a registry `config.json` Secret.
- **Direct credentials:** Set `catalogue.username` and `catalogue.password` via `ARCHIE_CATALOGUE_USERNAME` and `ARCHIE_CATALOGUE_PASSWORD_FILE`.
In air-gapped stages, mirror a verified catalogue to local storage and re-sign it with an internal Ed25519 key:
1. Generate an internal signing keypair with `archie catalogue keygen`.
2. Download, verify, and re-sign the catalogue and binaries with `archie catalogue mirror -to /var/lib/archie/mirror -sign-key-file /etc/archie/mirror.key`.
3. Transfer the mirror directory into the isolated environment and point `[catalogue]` `location` and `public_key` at the mirrored `catalogue.json` and internal public key.
## Probes, Graceful Drain, and High Availability
`cmd/archie` exposes three health endpoints (`internal/platform/health/health.go`):
- `/healthz`: Liveness probe. Returns `200` while the HTTP server process is alive.
- `/startupz`: Startup probe. Verifies database connectivity and confirms the deletion ledger is consistent before Kubernetes routes traffic or triggers liveness checks.
- `/readyz`: Readiness probe. Requires `/startupz` checks plus completion of owner setup (`gate.go`), and returns `503` as soon as `SIGTERM` begins draining.
Set `terminationGracePeriodSeconds` (`45` seconds in `values-prod.yaml`) higher than `shutdown_grace` (`30s`) so in-flight HTTP requests and run checkpoints finish before `SIGKILL`.
Enterprise v1 runs Active-Passive HA with `replicaCount: 1` on a `StatefulSet` backed by a `ReadWriteOnce` PVC for `state_dir`. Never scale `replicaCount` above `1` in v1 without shared `state_dir` storage and v2 Active-Active coordination (`LISTEN/NOTIFY` hub, lease election, and object-lock deletion ledger).
+65
View File
@@ -0,0 +1,65 @@
# Disaster Recovery and Backup Runbook
Archie keeps durable state across three separate stores: PostgreSQL, the `age` sealing keys, and the external deletion ledger (`deletions.jsonl`). Back up and protect each store independently. Restoring PostgreSQL alone is never enough if `age` keys or the deletion ledger are lost.
## Recovery Objectives
| Store | What it holds | RPO target | RTO target | Backup mechanism |
| --- | --- | --- | --- | --- |
| PostgreSQL (`archie` database) | Workflows, runs, approvals, events, governance, sealed credentials, audit events | 5 minutes or less | 30 minutes | Automated base snapshots plus continuous WAL archiving (PITR) |
| `age` recovery keys (`age_backup_recipients`) | Ability to open sealed connector credentials and event HMAC secrets | Zero key loss | Immediate on restore | Offline escrow in enterprise secret manager or HSM vault |
| Deletion ledger (`state_dir/deletions.jsonl`) | Append-only record of deleted memory notes | Zero acknowledged deletion loss | 15 minutes | Independent PVC or host volume snapshots replicated off-cluster |
## Independent Backup Strategy
### 1. PostgreSQL Database
Back up the PostgreSQL cluster using continuous WAL archiving and scheduled base backups so you can restore to a point in time.
- Back up as the `postgres` or `archie_owner` administrative role, not `archie_app`.
- Include the `public.goose_db_version` table and every Archie module schema (`runs`, `connectors`, `events`, `governance`, `deliveries`, `judgement`, `approvals`, `memory`, `alerts`, `proposals`, `chat`, and `audit`).
- Exclude `state_dir` and `age` private keys from database backup media so a database dump alone cannot decrypt stored credentials.
### 2. `age` Sealing Keys and Key Rotation
`internal/platform/seal/seal.go` seals connector credentials (`connectors.credentials`) and webhook secrets (`events.sources.hmac_secret_sealed`) with `age` X25519 keys bound to record labels. If the active `age_identity` and all `age_backup_recipients` are lost, every sealed secret in the database is unrecoverable.
Protect sealing keys with two controls:
1. **Configure offline backup recipients:** Generate a recovery `age` keypair in your enterprise vault (`archie -new-age-identity` or `age-keygen`) and list its public `age1...` string under `age_backup_recipients` in `config.toml`. Keep the matching `AGE-SECRET-KEY-1...` offline in your secret manager.
2. **Rotate keys with `archie rekey`:** Rotate compromised or expiring `age` identities atomically using `archie rekey`. The command takes a PostgreSQL advisory lock (`archie.rekey.owner`). It opens every sealed credential and webhook secret with the old identity, re-seals and checks decryption with the new identity in one transaction, and writes a JSON audit log.
Never delete the old identity from your vault until the post-rotation database backup completes.
### 3. External Deletion Ledger (`deletions.jsonl`)
When a user deletes a memory note, `modules/memory` commits the deletion in PostgreSQL and appends an `Entry` (`table`, `org_id`, `id`, `at`) to `deletions.jsonl` inside `state_dir` (`internal/platform/deletions/deletions.go`). Each append uses `flock` and `fsync` on both the file and parent directories so the record outlives the database.
Keep `state_dir` on an independent `ReadWriteOnce` persistent volume (or dedicated host volume in Compose) and snapshot it separately from PostgreSQL. Never restore `state_dir` from a snapshot older than the database snapshot you are restoring. If `deletions.jsonl` is lost on an instance that previously recorded deletions, `memory.ReapplyDeletions` returns `deletions.ErrUnsafeRollback` and stops startup rather than exposing deleted notes.
## Restore Procedure
Follow these steps to recover a stage from backup:
1. **Stop active Archie pods or containers:** Scale the `StatefulSet` to `0` (`kubectl scale statefulset archie --replicas=0`) or run `docker compose stop archie`.
2. **Acquire the exclusive serve lock:** If restoring onto an active PostgreSQL instance, hold `pg_advisory_lock(hashtextextended('archie.serve.owner', 0))` in your restore session so no stray Archie process can pass `pg.ClaimServe` before recovery finishes.
3. **Restore PostgreSQL:** Restore the base snapshot and replay WAL logs to the target recovery timestamp. Verify `public.goose_db_version` is intact.
4. **Restore or preserve `state_dir`:** Keep the existing `state_dir` volume containing the latest `deletions.jsonl`, or restore the newest `state_dir` backup taken at or after the database restore timestamp.
5. **Restore `age` key material:** Ensure `ARCHIE_AGE_IDENTITY_FILE` mounts a valid `age_identity` (or the backup identity stored in your vault if the primary key was lost). If you recover with the backup identity, run `archie rekey` right after startup to rotate to a new runtime key.
6. **Run migrations and start Archie:** Run the `archie migrate` Job if the restored snapshot precedes the deployed binary schema version, then scale the `StatefulSet` back to `1`.
7. **Verify reconciliation and readiness:** Watch stdout JSON logs for `applied the record of deletions` (`memory.ReapplyDeletions`) and confirm `/startupz` and `/readyz` return `200`.
## Restore Verification Drill
Run this drill in `staging` each quarter and after any backup architecture change. Record the completion timestamp, operator, and measured RTO in your compliance log.
1. Sign in to the `staging` instance and create a test memory note. Record its note ID and confirm it appears in `GET /api/memory/notes`.
2. Take an on-demand PostgreSQL snapshot (`pre-deletion snapshot`).
3. Delete the test memory note through the UI or API. Verify `state_dir/deletions.jsonl` contains a new JSON line matching the deleted note ID.
4. Scale the `staging` Archie `StatefulSet` to `0`.
5. Restore the `staging` PostgreSQL database to the `pre-deletion snapshot` taken in step 2. Leave `state_dir` untouched.
6. Verify the deleted note row is temporarily present again in PostgreSQL before Archie starts.
7. Scale the `staging` Archie `StatefulSet` back to `1`.
8. Check pod logs for `applied the record of deletions` and wait for `/readyz` to return `200`.
9. Query `GET /api/memory/notes` and PostgreSQL to confirm the test note remains deleted.
10. Verify credential decryption works using the backup `age` recipient key (or perform a test `archie rekey` rotation and confirm an existing connector still passes health checks).
+6 -6
View File
@@ -24,20 +24,20 @@ 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).
5. Select the required scope: 5. Select the required scope:
- **`repo`** (Full control of private repositories — required for polling, - **`repo`** (Full control of private repositories: required for polling,
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.
-2
View File
@@ -1,2 +0,0 @@
node_modules/
out/
-116
View File
@@ -1,116 +0,0 @@
# e2e
Validation of the whole stack, run by hand or by an agent, never by
`task check` or CI. It needs PostgreSQL 18, five services, Vite and a browser,
which the gate must not. Docker is not needed: without it tasks queue and
park, which is useful data for the dashboard.
| File | What it does |
| --- | --- |
| `stack.sh` | Starts PostgreSQL 18 (port 55432) and the five services as local processes, then Vite on 5173 |
| `seed.sh` | Seeds the stack through the dashboard API; safe to rerun |
| `run.cjs` | Runs `checks/*.cjs` in Chromium; screenshots, manifest and `report.html` to `out/<stamp>/` |
| `checks/` | One module per behaviour |
| `results/` | One committed report per release |
## Run
```bash
task e2e:up # build, start everything, seed
task e2e:check # list available checks (no stack needed)
task e2e:check -- list # explicitly list checks
task e2e:check -- audit-redirect # one check
task e2e:check -- all # all checks
task e2e:check -- --headed accessibility # watch a check in Chromium
task e2e:check -- --headed all # watch every check
task e2e:down # stop; e2e/stack.sh reset also deletes the data
```
Headless is the default. `--headed` opens visible Chromium and slows browser
actions to 150ms so you can follow them; assertions and saved evidence are the
same in both modes. The terminal prints each check before it starts. Headed mode
requires a graphical desktop.
Nothing reads the installed config: `stack.sh` points the XDG directories at
`${ARCHIE_DEV_DIR:-~/.local/state/archie-dev}` and writes its overlay from
`deployments/dev.toml`. Logs are in its `logs/`. `e2e/stack.sh restart archied`
restarts one service. Run `task e2e:down` before starting again: startup refuses
occupied service ports and checks that each launched process stays alive.
The seed creates a local test administrator: `operator@example.test`, password
`archie-local-e2e-password`. Use it at `http://localhost:5173`; the browser
checks sign in with the same account. These are test fixtures for this
loopback-only stack. To use an existing test account, set `ARCHIE_E2E_EMAIL`
and `ARCHIE_E2E_PASSWORD` for both seeding and browser checks. Seeding never
resets an existing account or deletes test data.
The first run needs `pnpm install --dir e2e` and `pnpm --dir e2e exec playwright
install chromium`. In the cloud environment, Chromium and Playwright are
preinstalled; run with `NODE_PATH=$(pnpm root -g)`.
## Release evidence
```bash
node e2e/run.cjs --record v1.54.0 all
```
writes `results/v1.54.0.md`, the pass, fail or skip of every check for
that release. Commit it with the release. Screenshots stay in `out/`.
## Writing a check
A module in `checks/` exports `async ({ page, go, shot, fail, skip, settled, attach, tolerate })`.
- `go(path)` loads a dashboard route: `waitUntil: 'load'` plus 1200ms.
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,
and records `{file, w, h, check}` in the manifest. The label is slugified,
so `shot('/')` becomes `routes-home.png`; a viewport other than the
1440x900 default adds a suffix (`-390x844`). Repeated labels get `-2`,
`-3`, so every capture is kept.
- `fail(msg)` records a problem without stopping.
- `skip(reason)` stops the check and records a skip: a missing
precondition, never a failure.
- `tolerate(re)` ignores console errors matching `re`, for a response the page is designed to survive.
- `attach(name, data)` saves a non-image artifact as `<check>-<name>`.
- `settled(sel?)` waits for a selector or URL, then settles briefly.
It is the harness-owned wait; checks need no capture wrapper or
ad-hoc sleeps around screenshots.
Each check gets a fresh page at 1440x900 with the login `storageState`;
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
console or page error fails the check. One module covers one behaviour;
families share a prefix: `audit-*` for the audit page (redirect,
filters, revert, runtime, views-export, retention-live, phone),
`workflow-*` for the canvas (loading, validation, phone-layout, logic),
`chat-composer` for chat input, `chat-dock-*` for the chat dock (pin, drag-cancel,
layout, resize, drafts, picker, phone).
`routes` loads every static route and flags text with stray leading,
trailing or doubled spaces. `seeded` checks the seed is visible.
`/logs` is visited but skipped by the whitespace lint: log lines are
data, not copy.
## Output
Every run writes `out/<stamp>/` with the screenshots,
`results.json` (the manifest: `{check, ok, ms, problems, artifacts[]}`,
plus `skipped`/`skipReason` for skips) and `report.html`: a self-contained
test record with the commit, totals and one row per check (status, 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
`failure` screenshot.
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
a dashboard other than `http://localhost:5173`.
## Pitfalls
| 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 |
| 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 |
| Postgres aborts in the cloud | `/tmp/claude-0` is reset to mode 700 | `stack.sh` keeps the root cluster in `/var/lib/archie-dev` |
-176
View File
@@ -1,176 +0,0 @@
// Keyboard and phone access: the task dialog fits and tabs in order, pages
// title correctly, the skip link and palette focus main content, and
// query-only tab switches keep focus where it is. Then the audit's two
// static sweeps (#1767): no unnamed controls on any route, and every keyboard
// focus stop's indicator clears 3:1 against the background behind it.
const assert = require('node:assert/strict');
const { staticRoutes } = require('./helpers/routes.cjs');
module.exports = async ({ page, go, shot, fail, settled, tolerate }) => {
// The extension catalogue 502 is a stack-environment issue, not this check.
tolerate(/extensions\/catalogue/);
await page.setViewportSize({ width: 390, height: 844 });
await go('/tasks');
await page.getByRole('button', { name: 'Jump to', exact: true }).click();
await page.getByRole('option', { name: 'New task', exact: true }).click();
const dialog = page.getByRole('dialog', { name: 'New task' });
await dialog.waitFor();
await settled();
const bounds = await dialog.boundingBox();
assert.ok(bounds.y >= 0 && bounds.y + bounds.height <= 844, 'New task dialog extends outside viewport');
await shot('phone-task-dialog-top');
const start = dialog.getByRole('button', { name: 'Start task', exact: true });
await start.scrollIntoViewIfNeeded();
const button = await start.boundingBox();
assert.ok(button.y >= 0 && button.y + button.height <= 844, 'Start task cannot be reached by scrolling');
await shot('phone-task-dialog');
const close = dialog.getByRole('button', { name: 'Close', exact: true });
await dialog.getByRole('button', { name: 'Cancel', exact: true }).focus();
await page.keyboard.press('Tab');
assert.ok(await close.evaluate(el => el === document.activeElement), 'Close is missing from keyboard tab order');
const closeBounds = await close.boundingBox();
assert.ok(closeBounds.y >= 0 && closeBounds.y + closeBounds.height <= 844, 'Close cannot be reached by keyboard');
await page.keyboard.press('Escape');
for (const [path, title] of [['/tasks', 'Tasks'], ['/events', 'Events'], ['/account', 'Your account'], ['/settings/models', 'Models | Instance'], ['/org/models', 'Models | Organisation']]) {
await go(path);
assert.equal(await page.title(), `${title} | Archie`);
}
await page.keyboard.press('Tab');
const skip = page.getByRole('link', { name: 'Skip to main content', exact: true });
assert.ok(await skip.evaluate(el => el === document.activeElement), 'Skip link is not the first keyboard stop');
await page.keyboard.press('Enter');
assert.equal(await page.evaluate(() => document.activeElement?.id), 'main-content');
await page.getByRole('button', { name: 'Sections', exact: true }).click();
await page.getByRole('menuitem', { name: 'Tasks', exact: true }).click();
await page.waitForFunction(() => document.activeElement?.id === 'main-content', null, { timeout: 5000 }).catch(() => {});
assert.equal(await page.evaluate(() => document.activeElement?.id), 'main-content', 'route navigation did not focus main');
await page.getByRole('button', { name: 'Jump to', exact: true }).click();
await page.getByRole('option', { name: 'Events', exact: true }).click();
await page.waitForFunction(() => document.activeElement?.id === 'main-content', null, { timeout: 5000 }).catch(() => {});
assert.equal(await page.evaluate(() => document.activeElement?.id), 'main-content', 'palette navigation did not focus main');
// The conversation panel is only open on some entries to this page; the
// focus check below needs it closed either way.
const hide = page.getByRole('button', { name: 'Hide conversation', exact: true });
if (await hide.count()) await hide.click();
const tab = page.getByRole('tab', { name: /^Map/ });
await tab.click();
assert.ok(await tab.evaluate(el => el === document.activeElement), 'query-only navigation stole focus');
await page.setViewportSize({ width: 1440, height: 900 });
// Unnamed controls: every visible input, textarea, select, button or
// widget role on each static route needs an accessible name (accname
// order: labelledby, label, content, value, placeholder, title).
for (const r of staticRoutes()) {
await go(r);
const unnamed = await page.evaluate(() => {
const name = (el) => {
const by = el.getAttribute('aria-labelledby');
if (by) {
const t = by.split(/\s+/).map((id) => (document.getElementById(id)?.textContent || '')).join(' ').trim();
if (t) return t;
}
const al = el.getAttribute('aria-label');
if (al && al.trim()) return al.trim();
if (el.id) {
const l = document.querySelector(`label[for="${CSS.escape(el.id)}"]`);
if (l && l.textContent.trim()) return l.textContent.trim();
}
const wrap = el.closest('label');
if (wrap && wrap.textContent.trim()) return wrap.textContent.trim();
if (el.tagName === 'BUTTON' || el.getAttribute('role') === 'button' || el.getAttribute('role') === 'tab' || el.getAttribute('role') === 'switch') return el.textContent.trim();
if (el.tagName === 'INPUT') {
const t = (el.getAttribute('type') || 'text').toLowerCase();
if (t === 'submit' || t === 'button' || t === 'reset') return el.value.trim();
if (t === 'image') return (el.getAttribute('alt') || '').trim();
}
return (el.getAttribute('placeholder') || el.getAttribute('title') || '').trim();
};
return [...document.querySelectorAll('button, input, textarea, select, [role="button"], [role="tab"], [role="switch"], [role="checkbox"]')]
.filter((el) => el.type !== 'hidden' && el.getClientRects().length)
.filter((el) => !name(el))
.map((el) => `${el.tagName.toLowerCase()}${el.id ? '#' + el.id : ''}: ${el.outerHTML.slice(0, 120)}`);
});
for (const u of unnamed) fail(`unnamed control on ${r}: ${u}`);
}
// Focus contrast: Tab through each static route; the focused element's
// outline or ring must clear 3:1 against the effective background behind it.
const focusProbe = () => page.evaluate(() => {
const el = document.activeElement;
if (!el || el === document.body || el === document.documentElement) return null;
const cs = getComputedStyle(el);
const parse = (c) => {
c = String(c).trim();
let m = c.match(/rgba?\(([^)]+)\)/);
if (m) {
const p = m[1].split(',').map(Number);
return { r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1 };
}
m = c.match(/^#([0-9a-f]{3,8})$/i);
if (m) {
let h = m[1];
if (h.length === 3 || h.length === 4) h = [...h].map((x) => x + x).join('');
const n = parseInt(h.slice(0, 6), 16);
return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255, a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1 };
}
return null;
};
const bgBehind = (start) => {
for (let n = start; n; n = n.parentElement) {
const c = parse(getComputedStyle(n).backgroundColor);
if (c && c.a > 0) return c;
}
return { r: 255, g: 255, b: 255, a: 1 };
};
// An outer ring or outline is painted over the parent's background; an
// inset one over the element's own. Score against whichever is higher.
const bgSelf = bgBehind(el);
const bgParent = bgBehind(el.parentElement);
const over = (fg, bg) => {
const a = fg.a + bg.a * (1 - fg.a);
if (a === 0) return { r: 0, g: 0, b: 0 };
return { r: (fg.r * fg.a + bg.r * bg.a * (1 - fg.a)) / a, g: (fg.g * fg.a + bg.g * bg.a * (1 - fg.a)) / a, b: (fg.b * fg.a + bg.b * bg.a * (1 - fg.a)) / a };
};
const lum = (c) => {
const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
return 0.2126 * f(c.r) + 0.7152 * f(c.g) + 0.0722 * f(c.b);
};
const ratio = (c1, c2) => {
const l1 = lum(c1), l2 = lum(c2);
return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
};
let fg = null;
// The ring lives in --tw-ring-shadow on :focus-visible; read the var
// directly, then fall back to outline, any shadow layer, focus border.
if (el.matches(':focus-visible')) {
const m = cs.getPropertyValue('--tw-ring-shadow').match(/rgba?\([^)]+\)|#[0-9a-f]{3,8}\b/i);
if (m) { const c = parse(m[0]); if (c && c.a > 0) fg = c; }
}
if (!fg && cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) fg = parse(cs.outlineColor === 'currentcolor' ? cs.color : cs.outlineColor);
if (!fg && cs.boxShadow && cs.boxShadow !== 'none') {
for (const m of cs.boxShadow.matchAll(/rgba?\([^)]+\)|#[0-9a-f]{3,8}\b/gi)) {
const c = parse(m[0]);
if (c && c.a > 0) { fg = c; break; }
}
}
if (!fg && el.matches(':focus-visible') && parseFloat(cs.borderTopWidth) > 0) {
const c = parse(cs.borderTopColor);
if (c && c.a > 0) fg = c;
}
const sig = `${el.tagName}#${el.id}:${(el.textContent || '').trim().slice(0, 30)}`;
if (!fg) return { sig, ratio: 0 };
return { sig, ratio: Math.max(ratio(over(fg, bgSelf), bgSelf), ratio(over(fg, bgParent), bgParent)) };
});
for (const r of staticRoutes()) {
await go(r);
let prev = '';
for (let i = 0; i < 40; i++) {
await page.keyboard.press('Tab');
const info = await focusProbe();
if (!info || info.sig === prev) break;
prev = info.sig;
if (info.ratio < 3) fail(`focus indicator under 3:1 on ${r} at ${info.sig} (ratio ${info.ratio.toFixed(2)})`);
}
}
};
-113
View File
@@ -1,113 +0,0 @@
// Audit filters are server-evaluated through the URL contract: search,
// category, time range, back/forward restore, denied, and the actor filter.
const assert = require('node:assert/strict');
const { trackAudit } = require('./helpers/audit-helpers.cjs');
module.exports = async ({ page, go, shot, fail }) => {
const { requestMatching, waitForUrl } = trackAudit(page);
await go('/org/audit');
const status = await page.evaluate(async () => (await fetch('/api/auth/status')).json());
const actor = status?.user?.id;
assert.ok(actor, 'signed-in identity has no id');
const search = page.getByLabel('Search events', { exact: true });
let request = await requestMatching(
() => search.fill('repository'),
(u) => u.searchParams.get('q') === 'repository',
);
assert.ok(request, 'search issued no matching /api/audit request');
await waitForUrl((u) => u.searchParams.get('q') === 'repository');
assert.equal((await search.inputValue()), 'repository');
await go('/org/audit');
request = await requestMatching(
() => page.getByRole('button', { name: 'Runtime', exact: true }).click(),
(u) => u.searchParams.get('categories') === 'runtime',
);
assert.ok(request, 'category filter issued no matching /api/audit request');
await waitForUrl((u) => u.searchParams.get('categories') === 'runtime');
assert.equal(
await page.getByRole('button', { name: 'Runtime', exact: true }).getAttribute('aria-pressed'),
'true',
);
// Time: Any time drops the window from the request rather than guessing one.
await page.getByRole('combobox', { name: 'Time range', exact: true }).click();
request = await requestMatching(
() => page.getByRole('option', { name: 'Any time', exact: true }).click(),
(u) => u.searchParams.get('from') === null && u.searchParams.get('categories') === 'runtime',
);
assert.ok(request, 'Any time issued no matching /api/audit request');
await waitForUrl((u) => u.searchParams.get('since') === 'any');
assert.equal(await page.getByRole('combobox', { name: 'Time range', exact: true }).innerText(), 'Any time');
// Back/forward restore the controls the URL describes.
const backRequest = page.waitForRequest(
(r) => {
const u = new URL(r.url());
return u.pathname === '/api/audit' && u.searchParams.get('categories') === 'runtime' && !!u.searchParams.get('from');
},
{ timeout: 8000 },
);
await page.goBack();
await backRequest;
await waitForUrl((u) => u.searchParams.get('categories') === 'runtime' && u.searchParams.get('since') === null);
assert.equal(await page.getByRole('combobox', { name: 'Time range', exact: true }).innerText(), 'Last 30 days');
assert.equal(
await page.getByRole('button', { name: 'Runtime', exact: true }).getAttribute('aria-pressed'),
'true',
'back did not restore the category toggle',
);
const forwardRequest = page.waitForRequest(
(r) => {
const u = new URL(r.url());
return u.pathname === '/api/audit' && u.searchParams.get('categories') === 'runtime' && u.searchParams.get('from') === null;
},
{ timeout: 8000 },
);
await page.goForward();
await forwardRequest;
await waitForUrl((u) => u.searchParams.get('since') === 'any');
assert.equal(await page.getByRole('combobox', { name: 'Time range', exact: true }).innerText(), 'Any time');
// Denied reaches the server through the same URL contract as the other
// filters. It must both update the URL and issue a request.
await go('/org/audit');
const denied = page.getByRole('button', { name: 'Denied', exact: true });
request = await requestMatching(
() => denied.click(),
(u) => u.searchParams.get('outcome') === 'denied',
3000,
);
const deniedUrl = new URL(page.url());
if (!request || deniedUrl.searchParams.get('outcome') !== 'denied') {
await shot('denied');
fail(
`Denied filter did not reach the server: URL ${page.url()} has outcome=${deniedUrl.searchParams.get('outcome') ?? 'absent'}, ` +
`aria-pressed=${await denied.getAttribute('aria-pressed')}, no /api/audit request with outcome=denied`,
);
} else {
assert.equal(await denied.getAttribute('aria-pressed'), 'true');
}
// Advanced actor filter: server-evaluated, in the URL, shown as a chip.
await go('/org/audit');
await page.getByRole('button', { name: 'Filters', exact: true }).click();
const actorInput = page.getByLabel('Actor', { exact: true });
request = await requestMatching(
async () => {
await actorInput.fill(actor);
await actorInput.press('Enter');
},
(u) => u.searchParams.get('actor') === actor,
);
assert.ok(request, 'advanced actor filter issued no matching /api/audit request');
await waitForUrl((u) => u.searchParams.get('actor') === actor);
assert.match(
await page.locator('ul[aria-label="Active filters"] li', { hasText: 'Actor:' }).first().innerText(),
new RegExp(actor),
);
await shot('filters');
await page.keyboard.press('Escape');
};
-42
View File
@@ -1,42 +0,0 @@
// The audit page at phone width: secondary columns collapse, and the list,
// an expanded row and the filters dialog fit without horizontal overflow.
const assert = require('node:assert/strict');
const { trackAudit } = require('./helpers/audit-helpers.cjs');
module.exports = async ({ page, go, shot, fail, settled }) => {
trackAudit(page);
await page.setViewportSize({ width: 390, height: 844 });
await go('/org/audit');
const assertNoOverflow = async (label) => {
const { scrollWidth, innerWidth } = await page.evaluate(() => ({
scrollWidth: document.documentElement.scrollWidth,
innerWidth,
}));
if (scrollWidth > innerWidth) {
fail(`${label} overflows 390px: documentElement.scrollWidth=${scrollWidth} > innerWidth=${innerWidth}`);
}
};
await page.locator('[data-row-key]').first().waitFor();
await assertNoOverflow('audit list');
assert.equal(
await page.locator('thead th', { hasText: 'Target' }).first().evaluate((el) => getComputedStyle(el).display),
'none',
'secondary columns are still rendered on the phone',
);
await shot('list');
const phoneRow = page.locator('[data-row-key]').first();
await phoneRow.focus();
await page.keyboard.press('Enter');
await settled();
assert.equal(await phoneRow.getAttribute('aria-expanded'), 'true', 'phone row did not expand');
await assertNoOverflow('expanded change set');
await shot('expanded');
await page.getByRole('button', { name: 'Filters', exact: true }).click();
await page.getByRole('dialog').first().waitFor();
await settled();
await assertNoOverflow('advanced filters');
await shot('filters');
};
-50
View File
@@ -1,50 +0,0 @@
// A deep link to the old history route redirects to the audit page keeping
// section, actor, since and the hash, and the feed loads with filter chips.
const assert = require('node:assert/strict');
const { trackAudit } = require('./helpers/audit-helpers.cjs');
module.exports = async ({ page, go, shot, fail }) => {
const { lastRequest } = trackAudit(page);
await go('/org/audit');
const status = await page.evaluate(async () => (await fetch('/api/auth/status')).json());
const actor = status?.user?.id;
assert.ok(actor, 'signed-in identity has no id');
const deepLink = `/settings/history?section=container-runtime-policies&actor=${encodeURIComponent(actor)}&since=30d#deep`;
await go(deepLink);
assert.match(page.url(), /\/org\/audit\?/, 'history did not redirect to the audit route');
assert.match(page.url(), /section=container-runtime-policies/, 'redirect dropped section');
assert.match(page.url(), new RegExp(`actor=${encodeURIComponent(actor)}`), 'redirect dropped actor');
assert.match(page.url(), /since=30d/, 'redirect dropped since');
assert.match(page.url(), /#deep$/, 'redirect dropped the hash');
const redirected = lastRequest();
assert.ok(redirected, 'the redirect issued no /api/audit request');
assert.equal(redirected.searchParams.get('kind'), 'container-runtime-policies');
assert.equal(redirected.searchParams.get('actor'), actor);
// The feed must be readable before anything below can mean anything. A 500
// here is the whole page: say what the server answered instead of timing out.
const probe = await page.evaluate(async () => {
const response = await fetch('/api/audit?limit=1');
return { status: response.status, body: await response.text() };
});
if (probe.status !== 200) {
await shot('unavailable');
fail(`GET /api/audit returned ${probe.status}: ${probe.body.slice(0, 200)}`);
return;
}
const kindChip = page.locator('ul[aria-label="Active filters"] li', { hasText: 'Kind:' });
await kindChip.first().waitFor({ timeout: 8000 });
assert.match(await kindChip.first().innerText(), /Container runtime policies/, 'kind chip missing its catalog title');
assert.match(
await page.locator('ul[aria-label="Active filters"] li', { hasText: 'Actor:' }).first().innerText(),
new RegExp(actor),
'actor chip missing',
);
await shot('redirect');
await go('/org/audit');
await page.locator('[data-row-key]').first().waitFor();
await shot('desktop');
};
-148
View File
@@ -1,148 +0,0 @@
// Audit retention reads the stored resource, the live tail prepends new rows
// without a reload and holds them behind a button while scrolled away, and a
// retention save persists. The save stays last: it must not stop the rest.
const assert = require('node:assert/strict');
const { trackAudit } = require('./helpers/audit-helpers.cjs');
module.exports = async ({ page, go, shot, fail, settled }) => {
const { loadCount } = trackAudit(page);
await go('/org/audit');
const resourceResponse = await page.request.get(`${new URL(page.url()).origin}/api/control-plane/resources/audit-retention`);
assert.equal(resourceResponse.status(), 200, 'audit-retention resource is unreadable');
const retentionResource = await resourceResponse.json();
const retentionHours = (value) => {
const match = String(value || '').match(/^(\d+)h$/);
return match ? Number(match[1]) : 0;
};
const originalHours = retentionHours(retentionResource.resource.value.runtime_event_retention);
const openRetention = async () => {
await page.getByRole('button', { name: 'Audit actions', exact: true }).click();
await page.getByRole('menuitem', { name: 'Retention', exact: true }).click();
const dialog = page.getByRole('dialog');
await dialog.waitFor();
await dialog.getByLabel('Runtime event retention (hours)', { exact: true }).waitFor();
return dialog;
};
let retentionDialog = await openRetention();
assert.match(await retentionDialog.innerText(), /Audit retention/);
assert.equal(
await retentionDialog.getByLabel('Runtime event retention (hours)', { exact: true }).inputValue(),
String(originalHours),
'retention dialog did not read the stored resource',
);
await retentionDialog.getByRole('button', { name: 'Cancel', exact: true }).click();
await retentionDialog.waitFor({ state: 'hidden', timeout: 5000 }).catch(() => {});
assert.ok(!(await retentionDialog.isVisible().catch(() => false)), 'Cancel left the retention dialog open');
// ---- live tail -----------------------------------------------------------
await go('/org/audit');
await page.evaluate(() => window.scrollTo(0, 0));
await settled();
const topKey = await page.locator('[data-row-key]').first().getAttribute('data-row-key');
const loadsBeforeWrite = loadCount();
let resource = await (await page.request.get(`${new URL(page.url()).origin}/api/control-plane/resources/audit-retention`)).json();
const toggleRetention = async () => {
const current = retentionHours(resource.resource.value.runtime_event_retention);
const next = current === 2160 ? 2161 : 2160;
const written = await page.request.post(
`${new URL(page.url()).origin}/api/control-plane/resources/audit-retention/commands/replace`,
{
headers: { 'X-Archie-CSRF': '1', Origin: new URL(page.url()).origin },
data: { value: { runtime_event_retention: `${next}h` }, expected_version: resource.resource.version },
},
);
const body = await written.text();
assert.equal(written.status(), 200, `retention write answered ${written.status()}: ${body.slice(0, 200)}`);
resource = JSON.parse(body);
};
await toggleRetention();
let liveKey = null;
for (let attempt = 0; attempt < 40; attempt += 1) {
const key = await page.locator('[data-row-key]').first().getAttribute('data-row-key');
if (key !== topKey) {
liveKey = key;
break;
}
await page.waitForTimeout(300);
}
if (!liveKey) {
fail('live tail did not show a new row within 12s of a write');
await shot('live');
} else {
assert.equal(loadCount(), loadsBeforeWrite, 'the live row required a page reload');
assert.match(
await page.locator(`[data-row-key="${liveKey}"]`).innerText(),
/audit-retention/i,
'the live row is not the write that caused it',
);
await shot('live');
}
// Scrolled away, a new event is held behind a button instead of jumping the
// list under the operator.
await page.evaluate(() => window.scrollTo(0, 900));
await settled();
const scrolledTo = await page.evaluate(() => window.scrollY);
assert.ok(scrolledTo > 80, 'the feed is too short to test held new events');
const heldTop = await page.locator('[data-row-key]').first().getAttribute('data-row-key');
await toggleRetention();
const heldButton = page.getByRole('button', { name: /^\d+ new events?$/ }).first();
let held = false;
for (let attempt = 0; attempt < 40; attempt += 1) {
if ((await heldButton.count()) && (await heldButton.isVisible().catch(() => false))) {
held = true;
break;
}
await page.waitForTimeout(300);
}
if (!held) {
fail('held new events did not appear while scrolled away');
await shot('held');
} else {
assert.equal(
await page.locator('[data-row-key]').first().getAttribute('data-row-key'),
heldTop,
'a new row was prepended while the operator was scrolled away',
);
await shot('held');
await heldButton.click();
await page.waitForFunction(
(top) => document.querySelector('[data-row-key]')?.getAttribute('data-row-key') !== top,
heldTop,
{ timeout: 8000 },
).catch(() => {});
await settled();
assert.notEqual(
await page.locator('[data-row-key]').first().getAttribute('data-row-key'),
heldTop,
'showing held events did not prepend the new row',
);
assert.ok((await page.evaluate(() => window.scrollY)) < 10, 'showing held events did not return to the top');
}
// ---- retention: save -----------------------------------------------------
// Kept last: the page error this currently raises must not stop the rest.
await go('/org/audit');
retentionDialog = await openRetention();
const hoursField = retentionDialog.getByLabel('Runtime event retention (hours)', { exact: true });
const beforeSave = await (await page.request.get(`${new URL(page.url()).origin}/api/control-plane/resources/audit-retention`)).json();
const beforeHours = retentionHours(beforeSave.resource.value.runtime_event_retention);
const wanted = beforeHours === 2160 ? 2161 : 2160;
await hoursField.fill(String(wanted));
await retentionDialog.getByRole('button', { name: 'Save', exact: true }).click();
await retentionDialog.waitFor({ state: 'hidden', timeout: 5000 }).catch(() => {});
const stillOpen = await retentionDialog.isVisible().catch(() => false);
const afterSave = await (await page.request.get(`${new URL(page.url()).origin}/api/control-plane/resources/audit-retention`)).json();
const afterHours = retentionHours(afterSave.resource.value.runtime_event_retention);
if (stillOpen || afterHours !== wanted) {
await shot('retention-save');
fail(
`retention save did not complete: dialog ${stillOpen ? 'stayed open' : 'closed'}, ` +
`stored retention is ${afterHours}h (wanted ${wanted}h), URL ${page.url()}`,
);
}
};
-69
View File
@@ -1,69 +0,0 @@
// A revertable change set expands to its Before/After diff, offers one Revert
// action whose dialog cancels cleanly, and toggles from the keyboard.
const assert = require('node:assert/strict');
const { DEFAULT_WINDOW_MS, trackAudit } = require('./helpers/audit-helpers.cjs');
module.exports = async ({ page, go, shot, fail, settled }) => {
trackAudit(page);
await go('/org/audit');
await page.locator('[data-row-key]').first().waitFor();
const from = new Date(Date.now() - DEFAULT_WINDOW_MS).toISOString();
// The feed page size is 100: only rows in this response are rendered.
const feed = await page.evaluate(
async (iso) => (await fetch(`/api/audit?limit=100&from=${encodeURIComponent(iso)}`)).json(),
from,
);
const records = feed.records || [];
assert.ok(records.length, 'the seeded feed is empty');
const changeSet = records.find(
(row) =>
row.target?.kind === 'resource' &&
(row.detail?.fields || []).length > 0 &&
(row.detail?.version ?? 0) > 1,
);
if (!changeSet) {
fail('no revertable settings change set in the feed; cannot exercise the diff or Revert');
return;
}
const row = page.locator(`[data-row-key="${changeSet.id}"]`);
await row.waitFor();
await row.scrollIntoViewIfNeeded();
await row.locator('td').first().click();
assert.equal(await row.getAttribute('aria-expanded'), 'true', 'click did not expand the change set');
const detail = row.locator('xpath=following-sibling::tr[1]');
await detail.getByText('Before:', { exact: false }).first().waitFor();
assert.match(await detail.innerText(), /After:/, 'expanded change set has no after value');
assert.equal(
await detail.getByRole('button', { name: /^Revert \S/ }).count(),
0,
'the audit diff offers a per-field revert',
);
const revertAll = page.getByRole('button', { name: 'Revert', exact: true });
assert.ok((await revertAll.count()) > 0, 'no Revert action on a revertable change set');
await shot('change-set');
await revertAll.first().click();
const dialog = page.getByRole('alertdialog');
await dialog.waitFor();
assert.match(await dialog.innerText(), /Revert this change\?/);
assert.match(await dialog.innerText(), /previous version opens for review/i);
await dialog.getByRole('button', { name: 'Cancel', exact: true }).click();
await dialog.waitFor({ state: 'hidden', timeout: 5000 }).catch(() => {});
assert.ok(!(await dialog.isVisible().catch(() => false)), 'Cancel left the revert dialog open');
assert.equal(
await page.getByRole('region', { name: 'Unsaved changes' }).count(),
0,
'Cancel touched the save bar',
);
// Enter is the keyboard equivalent of clicking the row.
await row.click();
assert.equal(await row.getAttribute('aria-expanded'), 'false', 'the row did not collapse');
await row.focus();
await page.keyboard.press('Enter');
await settled();
assert.equal(await row.getAttribute('aria-expanded'), 'true', 'Enter did not expand the change set');
};
-36
View File
@@ -1,36 +0,0 @@
// A runtime event with a task target expands to its metadata and links to
// the task. The seed's work requests park and record the event; the feed is
// filtered to it so settings noise cannot push it off the page. Without it
// there is nothing to exercise, so the check skips instead of failing.
const assert = require('node:assert/strict');
const { DEFAULT_WINDOW_MS, trackAudit } = require('./helpers/audit-helpers.cjs');
module.exports = async ({ page, go, skip }) => {
trackAudit(page);
await go('/org/audit?kind=parked');
await page.locator('[data-row-key]').first().waitFor();
const from = new Date(Date.now() - DEFAULT_WINDOW_MS).toISOString();
// The feed page size is 100: only rows in this response are rendered.
const feed = await page.evaluate(
async (iso) => (await fetch(`/api/audit?limit=100&kind=parked&from=${encodeURIComponent(iso)}`)).json(),
from,
);
const records = feed.records || [];
const runtime = records.find((row) => row.category === 'runtime' && row.target?.kind === 'task' && row.target?.id);
if (!runtime) {
skip('no runtime event with a task target in the feed');
}
const row = page.locator(`[data-row-key="${runtime.id}"]`);
await row.waitFor();
await row.scrollIntoViewIfNeeded();
await row.locator('td').first().click();
assert.equal(await row.getAttribute('aria-expanded'), 'true', 'runtime row did not expand');
const detail = row.locator('xpath=following-sibling::tr[1]');
await detail.locator('dl dt', { hasText: 'Target' }).first().waitFor();
assert.match(await detail.innerText(), /Table/, 'runtime metadata has no table row');
const link = detail.getByRole('link', { name: runtime.target.label || runtime.target.id, exact: true });
assert.equal(await link.count(), 1, 'runtime target is not a link');
assert.equal(await link.getAttribute('href'), `/tasks/${runtime.target.id}`);
};
-50
View File
@@ -1,50 +0,0 @@
// Audit saved views round-trip through the URL, and CSV/JSON exports carry
// the resolved window and arrive as attachments.
const assert = require('node:assert/strict');
const { trackAudit, exportOnce } = require('./helpers/audit-helpers.cjs');
module.exports = async ({ page, go, shot, fail, settled }) => {
const { waitForUrl } = trackAudit(page);
await go('/org/audit');
await page.getByRole('button', { name: 'Runtime', exact: true }).click();
await waitForUrl((u) => u.searchParams.get('categories') === 'runtime');
const viewName = `e2e-view-${Date.now()}`;
await page.getByRole('button', { name: 'Audit actions', exact: true }).click();
await page.getByRole('menuitem', { name: 'Save view…', exact: true }).click();
const saveDialog = page.getByRole('dialog');
await saveDialog.waitFor();
await saveDialog.getByLabel('Name', { exact: true }).fill(viewName);
await saveDialog.getByRole('button', { name: 'Save', exact: true }).click();
await settled();
await saveDialog.waitFor({ state: 'hidden', timeout: 5000 }).catch(() => {});
const savedView = page.getByRole('combobox', { name: 'Saved view', exact: true });
await savedView.waitFor();
assert.equal((await savedView.innerText()).trim(), viewName);
await shot('saved-view');
await page.getByRole('button', { name: 'Runtime', exact: true }).click();
await waitForUrl((u) => u.searchParams.get('categories') === null);
await savedView.click();
await page.getByRole('option', { name: viewName, exact: true }).click();
await waitForUrl((u) => u.searchParams.get('categories') === 'runtime');
assert.equal((await savedView.innerText()).trim(), viewName, 'applying the saved view did not restore it');
await page.getByRole('button', { name: 'Audit actions', exact: true }).click();
await page.getByRole('menuitem', { name: 'Delete view', exact: true }).click();
await savedView.waitFor({ state: 'detached', timeout: 5000 }).catch(() => {});
assert.equal(await savedView.count(), 0, 'deleting the saved view left it in the picker');
await go('/org/audit');
await page.getByRole('button', { name: 'Export', exact: true }).click();
await page.getByRole('menuitem', { name: 'CSV', exact: true }).waitFor();
await shot('export');
await page.keyboard.press('Escape');
const csvBody = await exportOnce(page, fail, 'CSV', 'csv');
if (csvBody !== null) assert.ok(csvBody.split('\n')[0].trim().length > 0, 'CSV export is empty');
const jsonBody = await exportOnce(page, fail, 'JSON', 'json');
if (jsonBody !== null) assert.ok(jsonBody.trimStart().startsWith('['), 'JSON export is not an array');
};
-70
View File
@@ -1,70 +0,0 @@
// The chat composer: IME confirmation never submits the draft, Shift+Enter
// inserts a newline, ordinary Enter submits and clears, and # attaches a task.
const assert = require('node:assert/strict');
module.exports = async ({ page, go, shot, tolerate }) => {
tolerate(/api\/tasks/);
await go('/events');
const composer = page.getByRole('combobox', { name: 'Message Archie', exact: true });
await composer.waitFor();
await composer.fill('Composition in progress');
const sent = [];
await page.route('**/api/chat/stream', async route => {
sent.push(route.request().postDataJSON().text);
await route.fulfill({ contentType: 'text/event-stream', body: 'data: {"type":"done","text":"Test response"}\n\n' });
});
for (const event of [{ isComposing: true }, { keyCode: 229 }]) {
await composer.dispatchEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true, ...event });
assert.equal(await composer.inputValue(), 'Composition in progress', 'IME confirmation submitted the draft');
}
assert.equal(sent.length, 0);
await composer.press('Shift+Enter');
assert.ok((await composer.inputValue()).includes('\n'), 'Shift+Enter no longer inserts a newline');
await composer.fill('Ordinary Enter submits');
const request = page.waitForRequest('**/api/chat/stream');
await composer.press('Enter');
assert.equal((await request).postDataJSON().text, 'Ordinary Enter submits');
assert.equal(await composer.inputValue(), '');
let failTasks = true;
await page.route('**/api/tasks?*', async route => {
if (failTasks) return route.fulfill({ status: 500, contentType: 'text/plain', body: 'task store down' });
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify([
{ id: 1861, title: "Chat composer: '#' context dropdown", status: 'running' },
{ id: 1842, title: 'Retry stalled task runs', status: 'done' },
]),
});
});
const tasksPalette = page.getByRole('listbox', { name: 'Tasks' });
await composer.fill('Look at #');
await tasksPalette.getByRole('alert').waitFor();
assert.equal(await tasksPalette.getByRole('option').count(), 0);
failTasks = false;
await tasksPalette.getByRole('button', { name: 'Retry' }).click();
await tasksPalette.getByRole('option').first().waitFor();
assert.equal(await tasksPalette.getByRole('option').count(), 2);
await composer.press('Escape');
await tasksPalette.waitFor({ state: 'hidden' });
await composer.fill('Look at #184 now');
await composer.evaluate(el => el.setSelectionRange(12, 12));
await composer.dispatchEvent('input');
await tasksPalette.getByRole('option').first().waitFor();
assert.equal(await tasksPalette.getByRole('option').count(), 1);
await composer.press('Tab');
await tasksPalette.waitFor({ state: 'hidden' });
assert.equal(await composer.inputValue(), 'Look at now');
await page.getByRole('list', { name: 'Attached tasks' }).getByText('#1842').waitFor();
const tagged = page.waitForRequest('**/api/chat/stream');
await composer.press('Enter');
const text = (await tagged).postDataJSON().text;
assert.ok(text.startsWith('Look at now') && text.includes('#1842 Retry stalled task runs'), text);
assert.equal(await page.getByRole('list', { name: 'Attached tasks' }).count(), 0);
await shot('chat-composition');
};
-42
View File
@@ -1,42 +0,0 @@
// Each conversation keeps its own unsent text and attached tasks. Starting a
// new chat opens an empty composer, switching back restores the earlier
// draft, and hiding and reopening the conversation loses nothing.
const assert = require('node:assert/strict');
const h = require('./helpers/chat-dock.cjs');
module.exports = async ({ page, go, shot }) => {
await page.route('**/api/tasks?*', (route) =>
route.fulfill({ contentType: 'application/json', body: JSON.stringify([{ id: 1861, title: 'Task picker', status: 'running' }]) }),
);
await h.load(page, go);
await h.expand(page);
const composer = h.composerOf(page);
const tags = page.getByRole('list', { name: 'Attached tasks' });
await composer.fill('draft for the first chat');
await composer.fill('#');
await page.getByRole('listbox', { name: 'Tasks' }).getByRole('option').first().click();
await tags.getByText('#1861').waitFor();
await composer.fill('draft for the first chat');
await page.getByRole('button', { name: 'New chat' }).click();
await h.until(async () => (await composer.inputValue()) === '' && (await tags.count()) === 0, 'a new chat inherited the first chat draft');
await composer.fill('draft for the second chat');
await h.hideOf(page).click();
await h.expand(page);
assert.equal(await composer.inputValue(), 'draft for the second chat', 'hiding the conversation lost the draft');
const pick = async (index) => {
await page.getByRole('combobox', { name: 'Conversation' }).click();
await page.getByRole('option').nth(index).click();
};
await pick(1);
await h.until(async () => (await composer.inputValue()) === 'draft for the first chat', 'switching back did not restore the first draft');
await tags.getByText('#1861').waitFor();
await shot('first-chat-draft');
await pick(0);
await h.until(async () => (await composer.inputValue()) === 'draft for the second chat', 'switching forward did not restore the second draft');
assert.equal(await tags.count(), 0, 'the first chat task tag leaked into the second chat');
};
-27
View File
@@ -1,27 +0,0 @@
// A drag the browser cancels (a touch turned into a scroll, a lost pointer)
// leaves the dock where it was: nothing pins, nothing stays offset, and the
// next drag still works.
const assert = require('node:assert/strict');
const h = require('./helpers/chat-dock.cjs');
module.exports = async ({ page, go }) => {
await h.load(page, go);
await h.expand(page);
const dock = h.dockOf(page);
const before = await dock.boundingBox();
const header = dock.locator('div.cursor-grab');
await h.dragTo(page, 1430);
const dragging = await dock.getAttribute('style');
assert.ok(/translate/.test(dragging || ''), 'the drag never started, so cancelling it proves nothing');
await header.dispatchEvent('pointercancel');
await page.mouse.up();
await h.until(async () => !/translate/.test((await dock.getAttribute('style')) || ''), 'the dock stayed offset after the drag was cancelled');
assert.deepEqual(await dock.boundingBox(), before, 'cancelling the drag moved the dock');
assert.equal((await h.saved(page)).side, null, 'a cancelled drag pinned the dock');
await h.dragTo(page, 1430);
await page.mouse.up();
await h.until(async () => (await h.saved(page)).side === 'right', 'a drag after a cancelled one did not pin');
};
-46
View File
@@ -1,46 +0,0 @@
// The saved dock layout: a stored mode and width are honoured, widths outside
// the allowed range are clamped, unreadable JSON falls back to a usable
// floating dock that saves again, and visiting phone width never overwrites
// the desktop choice.
const assert = require('node:assert/strict');
const h = require('./helpers/chat-dock.cjs');
module.exports = async ({ page, go, shot, tolerate }) => {
tolerate(/JSON|SyntaxError/);
const dock = h.dockOf(page);
await h.load(page, go, JSON.stringify({ mode: 'left', w: 500 }));
await h.expand(page);
let box = await dock.boundingBox();
h.near(box.x, 0, 'saved left pin');
h.near(box.width, 500, 'saved width');
assert.ok((await h.mainRect(page)).x >= 499, 'page did not reflow beside the restored dock');
await h.load(page, go, JSON.stringify({ mode: 'right', w: -4 }));
await h.expand(page);
h.near((await dock.boundingBox()).width, 320, 'a negative width clamps to the minimum');
await h.load(page, go, JSON.stringify({ mode: 'right', w: 9999 }));
await h.expand(page);
h.near((await dock.boundingBox()).width, 720, 'a huge width clamps to the maximum');
await h.load(page, go, '{broken');
await h.expand(page);
box = await dock.boundingBox();
assert.ok(box.height < 900 && box.x > 0 && box.x + box.width < 1440, 'unreadable layout did not fall back to a floating dock');
await h.composerOf(page).fill('still usable');
await h.dragTo(page, 1430);
await page.mouse.up();
await h.until(async () => (await h.saved(page)).mode === 'right', 'the dock did not save a layout over the unreadable one');
await shot('recovered');
await h.load(page, go, JSON.stringify({ mode: 'left', w: 460 }));
const layout = await h.stored(page);
await page.setViewportSize({ width: 390, height: 844 });
await h.expand(page);
box = await dock.boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= 390, 'the dock overflows the phone viewport');
await page.setViewportSize({ width: 1440, height: 900 });
assert.equal(await h.stored(page), layout, 'visiting phone width rewrote the saved layout');
await h.until(async () => Math.abs((await dock.boundingBox()).width - 460) <= 1, 'the desktop layout did not return after phone width');
};
-41
View File
@@ -1,41 +0,0 @@
// The chat dock at phone width: the bar and the open conversation fit the
// screen on a few pages, a stored desktop pin is ignored, the composer stays
// reachable, and the dock adds no sideways scroll. The page's own overflow is
// phone-overflow's to report, so the dock is measured against the page
// without it.
const assert = require('node:assert/strict');
const h = require('./helpers/chat-dock.cjs');
module.exports = async ({ page, go, shot, tolerate }) => {
tolerate(/extensions\/catalogue/);
await page.setViewportSize({ width: 390, height: 844 });
const fits = async (label) => {
const { scroll, bare, inner } = await page.evaluate(() => {
const root = document.querySelector('aside[aria-label="Chat with Archie"]').parentElement;
const scroll = document.documentElement.scrollWidth;
root.style.display = 'none';
const bare = document.documentElement.scrollWidth;
root.style.display = '';
return { scroll, bare, inner: window.innerWidth };
});
assert.ok(scroll <= Math.max(bare, inner), `${label}: the dock widens the page (${scroll} > ${Math.max(bare, inner)})`);
const box = await h.dockOf(page).boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= inner, `${label}: dock leaves the screen (${box.x}..${box.x + box.width})`);
assert.ok(box.y >= 0 && box.y + box.height <= 844, `${label}: dock leaves the screen vertically`);
};
for (const path of ['/events', '/account', '/org/agents']) {
await h.load(page, go, JSON.stringify({ side: 'right', width: 420 }));
await go(path);
await fits(`${path} collapsed`);
await h.expand(page);
await fits(`${path} open`);
assert.equal(await page.evaluate(() => document.documentElement.style.getPropertyValue('--chat-pin-r')), '0px', `${path}: the page reserved room for a pin on a phone`);
const composer = await h.composerOf(page).boundingBox();
assert.ok(composer.y + composer.height <= 844 && composer.x >= 0 && composer.x + composer.width <= 390, `${path}: composer is off screen`);
assert.equal(await h.dividerOf(page).count(), 0, `${path}: a phone shows the pin divider`);
await h.composerOf(page).fill('A long unbroken line '.repeat(20));
await fits(`${path} long draft`);
await shot(path);
}
};
-59
View File
@@ -1,59 +0,0 @@
// The # task picker by keyboard: arrows move the selection and wrap, Enter
// attaches the selected task, Escape closes the picker and leaves the
// conversation open, and an IME confirmation Enter never picks.
const assert = require('node:assert/strict');
const h = require('./helpers/chat-dock.cjs');
const tasks = [
{ id: 1861, title: 'Task picker', status: 'running' },
{ id: 1842, title: 'Retry stalled task runs', status: 'done' },
{ id: 1830, title: 'Filter forge text', status: 'queued' },
];
module.exports = async ({ page, go, shot }) => {
await page.route('**/api/tasks?*', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify(tasks) }));
await h.load(page, go);
await h.expand(page);
const composer = h.composerOf(page);
const palette = page.getByRole('listbox', { name: 'Tasks' });
const options = palette.getByRole('option');
const selected = () => options.evaluateAll((els) => els.findIndex((el) => el.getAttribute('aria-selected') === 'true'));
const tags = page.getByRole('list', { name: 'Attached tasks' });
await composer.fill('Look at #');
await options.first().waitFor();
assert.equal(await options.count(), 3);
assert.equal(await selected(), 0);
await shot('picker');
await composer.press('ArrowDown');
assert.equal(await selected(), 1);
assert.equal(await composer.getAttribute('aria-activedescendant'), 'slash-palette-option-1');
await composer.press('ArrowUp');
await composer.press('ArrowUp');
assert.equal(await selected(), 2, 'ArrowUp from the first row did not wrap to the last');
await composer.press('ArrowDown');
assert.equal(await selected(), 0, 'ArrowDown from the last row did not wrap to the first');
await composer.press('ArrowDown');
for (const event of [{ isComposing: true }, { keyCode: 229 }]) {
await composer.dispatchEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true, ...event });
assert.equal(await options.count(), 3, 'an IME confirmation closed the picker');
assert.equal(await tags.count(), 0, 'an IME confirmation attached a task');
}
await composer.press('Enter');
await palette.waitFor({ state: 'hidden' });
await tags.getByText('#1842').waitFor();
assert.equal(await tags.getByRole('listitem').count(), 1);
assert.equal(await composer.inputValue(), 'Look at ', 'the # token stayed in the text');
assert.ok(await composer.evaluate((el) => document.activeElement === el), 'focus left the composer');
await composer.fill('Look at #');
await options.first().waitFor();
await composer.press('Escape');
await palette.waitFor({ state: 'hidden' });
assert.equal(await h.hideOf(page).isVisible(), true, 'Escape on the picker also closed the conversation');
await composer.press('Escape');
await h.hideOf(page).waitFor({ state: 'hidden' });
};
-52
View File
@@ -1,52 +0,0 @@
// Pinning the chat dock: dragging its header to an edge pins it there and the
// page reflows beside it; double-clicking the header unpins it; hiding the
// conversation gives the page back its width; the choice survives a reload.
const assert = require('node:assert/strict');
const h = require('./helpers/chat-dock.cjs');
module.exports = async ({ page, go, shot }) => {
await h.load(page, go);
await h.expand(page);
const dock = h.dockOf(page);
const free = await h.mainRect(page);
const floating = await dock.boundingBox();
assert.ok(floating.height < 900, 'the dock starts as a floating card');
await h.dragTo(page, 1430);
await page.mouse.up();
await h.until(async () => (await h.saved(page)).side === 'right', 'dragging to the right edge did not pin right');
const right = await dock.boundingBox();
h.near(right.x + right.width, 1440, 'right pin touches the right edge');
h.near(right.height, 900, 'a pinned dock is full height');
const reflowed = await h.mainRect(page);
assert.ok(reflowed.x + reflowed.width <= right.x + 1, `page content runs under the pinned dock: ${reflowed.x + reflowed.width} > ${right.x}`);
assert.ok(reflowed.width < free.width, 'the page did not give up any width');
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), 'pinning made the page scroll sideways');
await shot('pinned-right');
await page.reload();
await h.expand(page);
await h.until(async () => Math.abs((await dock.boundingBox()).x - right.x) <= 1, 'the right pin did not survive a reload');
await h.hideOf(page).click();
await h.until(async () => Math.abs((await h.mainRect(page)).width - free.width) <= 1, 'hiding the conversation kept the page narrowed');
await h.expand(page);
await h.until(async () => Math.abs((await dock.boundingBox()).x - right.x) <= 1, 'reopening did not restore the pin');
const strip = await h.grip(page);
await page.mouse.dblclick(strip.x, strip.y);
await h.until(async () => (await h.saved(page)).side === null, 'double-clicking the header did not unpin');
assert.ok((await dock.boundingBox()).height < 900, 'an unpinned dock is a floating card again');
h.near((await h.mainRect(page)).width, free.width, 'the page returns to its full width');
await h.dragTo(page, 10);
await page.mouse.up();
await h.until(async () => (await h.saved(page)).side === 'left', 'dragging to the left edge did not pin left');
const left = await dock.boundingBox();
h.near(left.x, 0, 'left pin touches the left edge');
assert.ok((await h.mainRect(page)).x >= left.x + left.width - 1, 'page content runs under the left-pinned dock');
await shot('pinned-left');
await page.mouse.dblclick((await h.grip(page)).x, (await h.grip(page)).y);
await h.until(async () => (await h.saved(page)).side === null, 'double-clicking did not unpin the left pin');
};
-37
View File
@@ -1,37 +0,0 @@
// The pinned dock's divider is a keyboard separator: the arrow toward the
// page widens the dock, the arrow away narrows it, both stop at the allowed
// range, and the width is saved.
const assert = require('node:assert/strict');
const h = require('./helpers/chat-dock.cjs');
const width = (page) => h.dockOf(page).boundingBox().then((b) => Math.round(b.width));
const value = (page) => h.dividerOf(page).getAttribute('aria-valuenow').then(Number);
module.exports = async ({ page, go }) => {
const divider = h.dividerOf(page);
for (const [side, grow, shrink] of [['right', 'ArrowLeft', 'ArrowRight'], ['left', 'ArrowRight', 'ArrowLeft']]) {
await h.load(page, go, JSON.stringify({ side, width: 420 }));
await h.expand(page);
await divider.focus();
assert.equal(await value(page), 420);
assert.equal(await divider.getAttribute('aria-valuemin'), '320');
await page.keyboard.press(grow);
await h.until(async () => (await value(page)) === 436 && (await width(page)) === 436, `${side}: ${grow} did not widen by 16`);
await page.keyboard.press(shrink);
await page.keyboard.press(shrink);
await h.until(async () => (await value(page)) === 404 && (await width(page)) === 404, `${side}: ${shrink} did not narrow by 16`);
assert.equal((await h.saved(page)).width, 404, `${side}: the width was not saved`);
await page.keyboard.press('ArrowUp');
assert.equal(await value(page), 404, `${side}: a vertical arrow resized the dock`);
for (let i = 0; i < 12; i++) await page.keyboard.press(shrink);
await h.until(async () => (await width(page)) === 320, `${side}: the dock narrowed past its minimum`);
assert.equal(await value(page), 320);
for (let i = 0; i < 30; i++) await page.keyboard.press(grow);
await h.until(async () => (await width(page)) === 720, `${side}: the dock widened past its maximum`);
assert.equal(await value(page), 720);
}
};
-49
View File
@@ -1,49 +0,0 @@
// Real local API records; workflow edits stay unsaved and the test agent retires.
const assert = require('node:assert/strict');
module.exports = async ({ page, go, shot }) => {
const base = process.env.ARCHIE_E2E_URL || 'http://localhost:5173';
const headers = { 'X-Archie-CSRF': '1', Origin: base };
let agent;
const command = async (name, display_name = '') => {
const response = await page.request.post(`${base}/api/identities/${agent.id}/${name}`, {
headers, data: { expected_version: agent.version, display_name },
});
assert.equal(response.ok(), true, await response.text());
agent = await response.json();
};
const openSettings = async () => {
await go('/workflows/implement');
const runPicker = page.getByRole('combobox', { name: 'Run shown on the canvas' });
if (await runPicker.count()) { await runPicker.click(); await page.getByRole('option', { name: 'Definition', exact: true }).click(); }
await page.locator('.vue-flow__node').filter({ hasText: 'Workflow' }).first().click();
return page.getByRole('combobox', { name: 'Execution identity', exact: true });
};
try {
const created = await page.request.post(`${base}/api/identities`, {
headers, data: { display_name: `E2E execution agent ${Date.now()}`, kind: 'bot' },
});
assert.equal(created.ok(), true, await created.text());
agent = await created.json();
const trigger = await openSettings();
await page.waitForFunction(() => !document.querySelector('[aria-label="Execution identity"]')?.hasAttribute('disabled'));
await trigger.click();
await page.getByRole('option', { name: agent.display_name, exact: true }).click();
assert.match(await trigger.innerText(), new RegExp(agent.display_name));
await shot('named-execution-identity');
await command('rename', agent.display_name + ' renamed');
await page.reload();
const renamed = await openSettings();
await page.waitForFunction(() => !document.querySelector('[aria-label="Execution identity"]')?.hasAttribute('disabled'));
await renamed.click();
await page.getByRole('option', { name: agent.display_name, exact: true }).waitFor();
await page.keyboard.press('Escape');
await command('suspend');
await page.reload();
const suspended = await openSettings();
await page.waitForFunction(() => !document.querySelector('[aria-label="Execution identity"]')?.hasAttribute('disabled'));
await suspended.click();
assert.equal(await page.getByRole('option', { name: agent.display_name, exact: true }).and(page.locator(':not([data-disabled])')).count(), 0);
} finally {
if (agent && agent.lifecycle !== 'retired') await command('retire');
}
};
-103
View File
@@ -1,103 +0,0 @@
// Shared setup for the audit-* checks: feed request tracking, URL waits,
// and the export download-or-popup accept. One behaviour per check module;
// this file holds only what several of them need.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const DEFAULT_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
function isAudit(u) {
return u.pathname === '/api/audit';
}
// Installs request tracking on a fresh check page. Returns the helpers the
// audit checks share; a check destructures only what it uses.
function trackAudit(page) {
page.setDefaultTimeout(10000);
const auditRequests = [];
page.on('request', (request) => {
try {
const url = new URL(request.url());
if (isAudit(url) || url.pathname === '/api/audit/export') auditRequests.push(url);
} catch {
// A non-URL request cannot be an audit call.
}
});
let loads = 0;
page.on('load', () => (loads += 1));
const requestMatching = async (action, predicate, timeout = 6000) => {
const waiter = page
.waitForRequest(
(request) => {
try {
const url = new URL(request.url());
return (isAudit(url) || url.pathname === '/api/audit/export') && predicate(url);
} catch {
return false;
}
},
{ timeout },
)
.catch(() => null);
await action();
return waiter;
};
const waitForUrl = (predicate, timeout = 8000) =>
page.waitForURL((url) => predicate(new URL(url)), { timeout });
const lastRequest = () => auditRequests[auditRequests.length - 1] || null;
const loadCount = () => loads;
return { requestMatching, waitForUrl, lastRequest, loadCount };
}
// Export resolves its window at click time and opens a tab. A successful
// export arrives as an attachment download; a failed one stays visible in
// that tab, so the check accepts either and reads the response from it.
async function exportOnce(page, fail, label, extension) {
await page.getByRole('button', { name: 'Export', exact: true }).click();
const item = page.getByRole('menuitem', { name: label, exact: true });
await item.waitFor();
const downloadP = page.waitForEvent('download', { timeout: 15000 }).then((download) => ({ download })).catch(() => null);
const popupP = page.waitForEvent('popup', { timeout: 15000 }).then((popup) => ({ popup })).catch(() => null);
await item.click();
const settled = await Promise.race([downloadP, popupP]);
if (!settled) {
fail(`${label} export neither downloaded nor opened a tab`);
return null;
}
if (settled.popup) {
await settled.popup.waitForLoadState('load').catch(() => {});
const url = new URL(settled.popup.url());
assert.equal(url.pathname, '/api/audit/export', `${label} opened ${url.href}`);
assert.equal(url.searchParams.get('format'), extension);
assert.ok(url.searchParams.get('from'), `${label} export has no explicit start`);
assert.ok(url.searchParams.get('to'), `${label} export has no explicit end`);
const response = await page.request.get(url.href);
const body = await response.text();
if (response.status() !== 200) {
fail(`${label} export failed (${response.status()}): ${body.slice(0, 200)}`);
return null;
}
if (!new RegExp(`attachment;.*\\.${extension}`).test(response.headers()['content-disposition'] || '')) {
fail(`${label} export opened a tab without an attachment filename`);
return null;
}
return body;
}
if (!new RegExp(`\\.${extension}$`).test(settled.download.suggestedFilename())) {
fail(`${label} export did not download a .${extension} file`);
return null;
}
const failure = await settled.download.failure();
if (failure) {
fail(`${label} download failed: ${failure}`);
return null;
}
const saved = await settled.download.path();
return saved ? fs.readFileSync(saved, 'utf8') : '';
}
module.exports = { DEFAULT_WINDOW_MS, isAudit, trackAudit, exportOnce };
-63
View File
@@ -1,63 +0,0 @@
// Shared handles for the chat dock checks: the dock's own storage key, its
// landmarks, and the pointer gestures that pin it.
const assert = require('node:assert/strict');
const KEY = 'archie.chat.dock.v2';
const dockOf = (page) => page.getByRole('complementary', { name: 'Chat with Archie' });
const composerOf = (page) => page.getByRole('combobox', { name: 'Message Archie', exact: true });
const hideOf = (page) => page.getByRole('button', { name: 'Hide conversation' });
const dividerOf = (page) => page.getByRole('separator', { name: 'Resize chat' });
const stored = (page) => page.evaluate((key) => localStorage.getItem(key), KEY);
const saved = async (page) => JSON.parse(await stored(page));
// Loads /events with the given stored layout (a string, or null for none).
async function load(page, go, layout = null) {
await go('/events');
await page.evaluate(([key, value]) => (value === null ? localStorage.removeItem(key) : localStorage.setItem(key, value)), [KEY, layout]);
await go('/events');
}
// Focusing the composer is how the operator opens the conversation.
async function expand(page) {
await composerOf(page).focus();
await hideOf(page).waitFor();
}
// Retries an assertion until it holds: the dock settles over a few frames.
async function until(check, message, timeout = 5000) {
const end = Date.now() + timeout;
let last;
for (;;) {
try {
const ok = await check();
if (ok) return;
last = ok;
} catch (e) {
last = e;
}
if (Date.now() > end) throw new Error(`${message}${last instanceof Error ? `: ${last.message}` : ''}`);
await new Promise((r) => setTimeout(r, 50));
}
}
const near = (a, b, message, tolerance = 1) => assert.ok(Math.abs(a - b) <= tolerance, `${message}: ${a} is not within ${tolerance} of ${b}`);
// The empty strip at the top of the header, where a drag starts.
async function grip(page) {
const box = await dockOf(page).boundingBox();
return { x: box.x + box.width / 2, y: box.y + 8 };
}
async function dragTo(page, x, steps = 10) {
const from = await grip(page);
await page.mouse.move(from.x, from.y);
await page.mouse.down();
await page.mouse.move(x, from.y, { steps });
return from;
}
const mainRect = (page) => page.locator('#main-content').boundingBox();
module.exports = { KEY, dockOf, composerOf, hideOf, dividerOf, stored, saved, load, expand, until, near, grip, dragTo, mainRect };
-18
View File
@@ -1,18 +0,0 @@
// Shared by the org-* and setup checks: acting in a seeded org and the 404s a
// fresh org's pages are built to survive.
const ORG = { home: 'org-sys', beta: 'org-beta', outsider: 'org-gamma' };
// A new org has written no documents, and the instance-only reads answer
// not found outside the system org.
const ABSENT = /status of 404.*\/api\/(control-plane|schedules|identities)/;
// Selects an org the way the topbar does, over the page's own session.
async function selectOrg(page, id) {
const origin = new URL(page.url() === 'about:blank' ? 'http://localhost:5173' : page.url()).origin;
return page.request.put(`${origin}/api/orgs/current`, {
headers: { 'X-Archie-CSRF': '1', Origin: origin },
data: { id },
});
}
module.exports = { ORG, ABSENT, selectOrg };
-19
View File
@@ -1,19 +0,0 @@
// The dashboard's static routes, read from the router source so a new page is
// swept automatically. Parameterised and redirect routes are skipped.
const fs = require('fs');
const path = require('path');
function staticRoutes() {
const src = fs.readFileSync(path.join(__dirname, '../../../ui/src/router/index.ts'), 'utf8');
const out = [];
for (const line of src.split('\n')) {
if (/redirect:/.test(line)) continue;
const m = line.match(/path: "([^"]*)"/);
if (!m || m[1].includes(':')) continue;
if (m[1].startsWith('/')) out.push(m[1]);
else if (m[1]) out.push('/org/' + m[1]);
}
return [...new Set(out)];
}
module.exports = { staticRoutes };
-36
View File
@@ -1,36 +0,0 @@
const assert=require('node:assert/strict');
module.exports=async({page,go,shot,tolerate})=>{
// The extension catalogue 502 is a stack-environment issue, not this check.
tolerate(/extensions\/catalogue/);
await page.route('**/api/access/policies',async route=>{await new Promise(r=>setTimeout(r,2200));await route.continue()});
await go('/access/policies');
assert.equal(await page.getByText('No policies yet.',{exact:true}).count(),0);
await page.getByText('Loading policies…',{exact:true}).waitFor({state:'hidden'});
await page.route('**/api/tasks?**',async route=>{
if(new URL(route.request().url()).searchParams.has('workflow')) await route.fulfill({status:200,contentType:'application/json',body:'unreadable response'});
else await route.continue();
});
await go('/workflows/implement');
await page.getByRole('alert').filter({hasText:'Could not load recent runs'}).waitFor();
await page.getByRole('tab',{name:/^Runs/}).click();
assert.equal(await page.getByText('No runs yet',{exact:true}).count(),0);
await page.unroute('**/api/tasks?**');
await page.getByRole('button',{name:'Retry runs',exact:true}).click();
await page.getByRole('alert').filter({hasText:'Could not load recent runs'}).waitFor({state:'hidden'});
await shot('recovered');
// A failed list read is an error, never the empty state (#1767): force each
// page's list API to 500 and check its empty-state copy stays hidden.
const failList = async (pattern,path,emptyTexts,errorSel='[role=alert]')=>{
await page.route(pattern,route=>route.fulfill({status:200,contentType:'application/json',body:'unreadable response'}));
await go(path);
await page.locator(errorSel).first().waitFor();
for(const text of emptyTexts) assert.equal(await page.getByText(text,{exact:true}).count(),0,`${path} shows its empty state ("${text}") while the list read fails`);
await page.unroute(pattern);
};
await failList('**/api/tasks*','/tasks',['No tasks yet'],'text=Archie is not responding');
await failList('**/api/captures*','/events',['No captures yet']);
await failList('**/api/event-types*','/events',['No event types yet']);
await failList('**/api/tokens*','/account',['No tokens yet']);
await failList('**/api/access/policies*','/org/policies',['No policies yet']);
await shot('failed-reads-show-errors');
};
-18
View File
@@ -1,18 +0,0 @@
// The save response is mocked; this checks the page's save path without changing models.
const assert=require('node:assert/strict');
module.exports=async({page,go,shot})=>{
let submitted;
await page.route('**/api/control-plane/resources/model-aliases/commands/replace',async route=>{
submitted=route.request().postDataJSON();
await route.fulfill({json:{resource:{kind:'model-aliases',version:submitted.expected_version+1,value:submitted.value}}});
});
await go('/access/models');
await page.getByLabel('New alias',{exact:true}).fill('e2e-test');
await page.getByRole('button',{name:'Add alias',exact:true}).click();
await page.getByLabel('e2e-test',{exact:true}).fill('test/model');
await page.getByRole('button',{name:'Review and save',exact:true}).click();
await page.getByRole('button',{name:'Save',exact:true}).click();
await page.getByRole('heading',{name:/^Review \d/}).waitFor({state:'hidden'});
assert.equal(submitted?.value['e2e-test'],'test/model');
await shot('saved');
};
-30
View File
@@ -1,30 +0,0 @@
// The organisation pages: each loads its form in the selected org, and the old
// settings audit route lands on the organisation's audit page.
const assert = require('node:assert/strict');
const { trackAudit } = require('./helpers/audit-helpers.cjs');
const PAGES = [
{ path: '/org/channels', heading: 'Channels', text: 'Chat session defaults' },
{ path: '/org/scheduling-policy', heading: 'Scheduling policy', text: 'Retries and polling' },
{ path: '/org/alerts', heading: 'Alert webhook', text: 'Webhook severity' },
];
module.exports = async ({ page, go, shot }) => {
for (const { path, heading, text } of PAGES) {
await go(path);
await page.getByRole('heading', { name: heading, exact: true }).waitFor();
await page.getByText(text, { exact: true }).first().waitFor();
assert.equal(new URL(page.url()).pathname, path);
await shot(path);
}
trackAudit(page);
await go('/org/audit');
await page.getByRole('heading', { name: 'Audit', exact: true }).first().waitFor();
await page.locator('[data-row-key]').first().waitFor();
await shot('/org/audit');
await go('/settings/audit?since=7d');
assert.equal(new URL(page.url()).pathname, '/org/audit', '/settings/audit did not redirect');
assert.equal(new URL(page.url()).searchParams.get('since'), '7d', 'redirect dropped the query');
await page.locator('[data-row-key]').first().waitFor();
};
-31
View File
@@ -1,31 +0,0 @@
// A non-system org can arm a schedule trigger: the schedule source's built-in
// mapping is readable there, so a binding on it is accepted. The editor's own
// schedule list is instance-only, so the binding is written over the API.
const assert = require('node:assert/strict');
const { ORG, ABSENT, selectOrg } = require('./helpers/org-helpers.cjs');
module.exports = async ({ page, go, shot, tolerate }) => {
tolerate(ABSENT);
await go('/');
assert.equal((await selectOrg(page, ORG.beta)).status(), 204);
await go('/workflows/feasibility');
const origin = new URL(page.url()).origin;
const headers = { 'X-Archie-CSRF': '1', Origin: origin };
const created = await page.request.post(`${origin}/api/bindings`, {
headers,
data: {
name: 'e2e schedule trigger', matcher: { source: 'schedule' }, mapping_id: 'schedule-fired',
filter: 'schedule_id == "issue-discovery"', workflow: 'feasibility', repo_param: '', owner: '', repo: '', inputs: {},
},
});
try {
assert.equal(created.status(), 201, `binding on the built-in schedule mapping refused: ${await created.text()}`);
const binding = await created.json();
assert.equal(binding.org_id, ORG.beta);
await go('/workflows/feasibility');
await page.getByText('Starts when').first().waitFor();
await shot('beta-trigger');
} finally {
if (created.ok()) await page.request.delete(`${origin}/api/bindings/${(await created.json()).id}`, { headers });
}
};
-44
View File
@@ -1,44 +0,0 @@
// The sidebar org switcher: choosing a member org reloads the dashboard into it,
// Tasks and Workflows then show only that org's work, and the API refuses an
// org the caller is not a member of.
const assert = require('node:assert/strict');
const { ORG, ABSENT, selectOrg } = require('./helpers/org-helpers.cjs');
module.exports = async ({ page, go, shot, settled, tolerate }) => {
tolerate(ABSENT);
await go('/tasks');
await page.getByText('Fix flaky login test').first().waitFor();
const picker = page.getByRole('button', { name: /^Organisation: / });
await picker.waitFor();
const offered = await (async () => {
await picker.click();
await page.getByRole('menuitem').first().waitFor();
const names = (await page.getByRole('menuitem').allInnerTexts()).map(t => t.trim().split('\n').pop().trim());
await page.keyboard.press('Escape');
return names;
})();
assert.deepEqual(offered.sort(), ['Beta', 'E2E'], 'selector must offer exactly the orgs the caller belongs to');
await go('/workflows');
await page.getByText('Parked', { exact: true }).first().waitFor();
await shot('home-org-workflows');
await picker.click();
await Promise.all([page.waitForEvent('load'), page.getByRole('menuitem', { name: 'Beta' }).click()]);
await settled('/workflows');
await page.getByRole('button', { name: /^Organisation: / }).waitFor();
assert.equal(await page.getByText('Parked', { exact: true }).count(), 0, 'workflow run counts leaked across orgs');
await shot('beta-workflows');
await go('/tasks');
await page.getByText('No tasks yet').waitFor();
assert.equal(await page.getByText('Fix flaky login test').count(), 0, 'tasks leaked across orgs');
await shot('beta-tasks');
// The selector never writes an org the caller is outside of; the server decides.
const refused = await selectOrg(page, ORG.outsider);
assert.equal(refused.status(), 403, 'selecting a non-member org must be forbidden');
await go('/tasks');
await page.getByText('No tasks yet').waitFor();
assert.equal((await selectOrg(page, ORG.home)).status(), 204);
await go('/tasks');
await page.getByText('Fix flaky login test').first().waitFor();
};
-69
View File
@@ -1,69 +0,0 @@
// Phone-width sweep of the views the November audit flagged (#1757): at
// 390x844 each must fit without horizontal scroll or clipped controls. The
// topbar (with its instance badge) is on every page; /account holds the
// token form, /org/agents the agent rows and the grants card, /events the
// sources table, the event-type rule editor and the mapping editor dialog.
const assert = require('node:assert/strict');
const { staticRoutes } = require('./helpers/routes.cjs');
module.exports = async ({ page, go, shot, fail, settled, tolerate }) => {
// The extension catalogue 502 is a stack-environment issue, not this check.
tolerate(/extensions\/catalogue/);
await page.setViewportSize({ width: 390, height: 844 });
const assertNoOverflow = async (label) => {
const { scrollWidth, innerWidth } = await page.evaluate(() => ({
scrollWidth: document.documentElement.scrollWidth,
innerWidth: window.innerWidth,
}));
if (scrollWidth > innerWidth) {
fail(`${label} overflows 390px: scrollWidth=${scrollWidth} > innerWidth=${innerWidth}`);
}
};
const visit = async (path, label, waitFor) => {
await go(path);
if (waitFor) await settled(waitFor);
await assertNoOverflow(label);
await shot(label);
};
await visit('/account', 'account-tokens', 'text=API tokens');
await visit('/org/agents', 'org-agents', 'text=Credential grants');
await go('/events');
await settled('[role=tab]');
await assertNoOverflow('events');
await shot('events');
// The seeded event type's rule editor (RuleEditor's condition row) opens
// from the Edit button on its row.
const editType = page.locator('button[aria-label^="Edit "]').first();
if (await editType.count()) {
await editType.click();
await page.getByRole('dialog').first().waitFor();
await settled();
await assertNoOverflow('event-type rule editor');
await shot('rule-editor');
await page.keyboard.press('Escape');
await settled();
}
// The mappings tab's editor dialog carries the payload tree.
await page.getByRole('tab', { name: 'Map' }).click();
await settled('text=New mapping');
await assertNoOverflow('mappings list');
const editMapping = page.locator('button', { hasText: 'Edit' }).first();
if (await editMapping.count()) {
await editMapping.click();
await page.getByRole('dialog').first().waitFor();
await settled();
await assertNoOverflow('mapping editor dialog');
await shot('mapping-editor');
}
// Every static route fits 390px (#1767): horizontal scroll fails.
for (const r of staticRoutes()) {
await visit(r, `route ${r}`, null);
}
};
-13
View File
@@ -1,13 +0,0 @@
// Repositories and connections say what stops them serving work: the seeded
// repository has no connection, and the seeded connection's forge is not enabled.
module.exports = async ({ page, go, shot }) => {
await go('/org/repositories');
await page.getByText('acme/widgets', { exact: true }).first().waitFor();
await page.getByText('No connection', { exact: true }).waitFor();
await shot('repositories');
await go('/org/connections');
await page.getByText('github.com', { exact: true }).first().waitFor();
await page.getByText('Forge not enabled', { exact: true }).waitFor();
await shot('connections');
};
-22
View File
@@ -1,22 +0,0 @@
// Every static route loads without errors, renders, and shows no text with
// stray leading, trailing or doubled spaces.
const { staticRoutes } = require('./helpers/routes.cjs');
module.exports = async ({ page, go, shot, fail }) => {
const stray = new Map();
for (const r of staticRoutes()) {
await go(r);
await shot(r);
// Log lines are data, not copy.
if (r === '/logs') continue;
const bad = await page.evaluate(() => [...document.querySelectorAll('body *')]
.filter((el) => !el.children.length && !el.closest('pre,code,textarea,.xterm') && el.getClientRects().length && !getComputedStyle(el).whiteSpace.startsWith('pre'))
.map((el) => el.textContent)
.filter((t) => t.trim() && (t !== t.trim() || / /.test(t.trim()))));
for (const t of bad) {
const key = JSON.stringify(t.length > 60 ? t.slice(0, 60) + '…' : t);
stray.set(key, (stray.get(key) || new Set()).add(r));
}
}
for (const [text, where] of stray) fail(`stray whitespace ${text} on ${[...where].join(', ')}`);
};
Loaded 100 of 1295 files, more files were not shown because too many files have changed in this diff. Show more