Compare commits
184
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
21980f9ced | ||
|
|
08988692c1
|
||
|
|
6b4ff8101a
|
||
|
|
24a3efcf60
|
||
|
|
bc4ac4436d
|
||
|
|
c538017523
|
||
|
|
2ea0062bef
|
||
|
|
5dc2d79fdb | ||
|
|
f0f09e9189 | ||
|
|
8bf3ace96b
|
||
|
|
8dd28b90be
|
||
|
|
e4663c22c0
|
||
|
|
fa4a078a34
|
||
|
|
f27317738d
|
||
|
|
a7686042e5
|
||
|
|
bc031880bf
|
||
|
|
eb7d852567
|
||
|
|
8c9c19efb0
|
||
|
|
cd8fad1b66
|
||
|
|
2d83b50837
|
||
|
|
4b399e44aa
|
||
|
|
7904ccdfe0
|
||
|
|
56dbb31923
|
||
|
|
74a560533e
|
||
|
|
6127ded28d
|
||
|
|
fe4d574976
|
||
|
|
c9ed3b1ae2
|
||
|
|
afdb0a0c97
|
||
|
|
d1e85c6e2a
|
||
|
|
16f17f702c
|
||
|
|
ba077f3779
|
||
|
|
58f1f9ce57
|
||
|
|
19b273a87b
|
||
|
|
ef3b5f98ea
|
||
|
|
26e19f3de4
|
||
|
|
c5591d95da
|
||
|
|
1c10378a40
|
||
|
|
efe7069bc1
|
||
|
|
67ce2901a5
|
||
|
|
21d1d2e8bf
|
||
|
|
dd57e6563a
|
||
|
|
da941f05aa
|
||
|
|
9c04b74e6f
|
||
|
|
152e7b4d2f
|
||
|
|
911152c9d1
|
||
|
|
0d25c93ea0
|
||
|
|
bed51c4bd1
|
||
|
|
f24c2b4455
|
||
|
|
2ae793cc94
|
||
|
|
b47e98e25f
|
||
|
|
8265e99466
|
||
|
|
30aa351eb6
|
||
|
|
7e701f9a50
|
||
|
|
4a9f30ef04
|
||
|
|
eb4136ffe6
|
||
|
|
383d7d6dad
|
||
|
|
dad6924a0c
|
||
|
|
de05bc2cbd
|
||
|
|
2bfb262e9c
|
||
|
|
0ad4374a2a
|
||
|
|
7f5220dea3
|
||
|
|
4b60033429
|
||
|
|
062336db91
|
||
|
|
60d9b6b7aa
|
||
|
|
e1ada94d78
|
||
|
|
8c267b6edd
|
||
|
|
33f7ebdff4
|
||
|
|
e801306c15
|
||
|
|
4707427759
|
||
|
|
faeaa0d7f0
|
||
|
|
240dc52226
|
||
|
|
7f89b03507
|
||
|
|
787a213db6
|
||
|
|
3e4b020311
|
||
|
|
51a1cf5128
|
||
|
|
d9e993e2b9
|
||
|
|
de3bfe296d
|
||
|
|
53719c6859
|
||
|
|
456c08751a
|
||
|
|
07d14c8d50
|
||
|
|
c1b4ba2b6b
|
||
|
|
84284d59c3
|
||
|
|
5c8fb901f9
|
||
|
|
501338ffbd
|
||
|
|
61f576a25c
|
||
|
|
a5826156a3
|
||
|
|
682995bdf7
|
||
|
|
9c0d043b57
|
||
|
|
aefe2b81e9
|
||
|
|
eadb88d3bf
|
||
|
|
8b9f5b2c60
|
||
|
|
a420b742e8
|
||
|
|
bc56b71539
|
||
|
|
a1347dbfc8
|
||
|
|
34c97ce8e8
|
||
|
|
bd212ec9ac
|
||
|
|
037ab0623a
|
||
|
|
9aceaa15bc
|
||
|
|
0a2aeb65ce
|
||
|
|
5004e8b40b
|
||
|
|
9c5af2c2d3
|
||
|
|
f8c572ebef
|
||
|
|
e72d9313e2
|
||
|
|
f4bfa59dec
|
||
|
|
a54654b0c8
|
||
|
|
81dcc7d94e
|
||
|
|
e3130d53e7
|
||
|
|
098d8cc328
|
||
|
|
6c59d6b742
|
||
|
|
1a0c697858
|
||
|
|
65a8b7cd47
|
||
|
|
970fb2ab84
|
||
|
|
e127b2b05d
|
||
|
|
02227a0b22
|
||
|
|
9c0ea938b8
|
||
|
|
763cd0e581
|
||
|
|
48d0212784
|
||
|
|
f6e9d48da6
|
||
|
|
46238afd62
|
||
|
|
4b494bf75b
|
||
|
|
b9a60e03a3
|
||
|
|
bc72655c8e
|
||
|
|
592d36e0d1
|
||
|
|
d318f912a8
|
||
|
|
31b2827048
|
||
|
|
01fd0fbf97
|
||
|
|
9c0da07807
|
||
|
|
14060675cd
|
||
|
|
74928925c8
|
||
|
|
35e2a216ab
|
||
|
|
b6907d8366
|
||
|
|
4b5c60330d
|
||
|
|
69b5b2aba6
|
||
|
|
d6f3a1a01d
|
||
|
|
ca279a200a
|
||
|
|
5d8c9303e0
|
||
|
|
23f23a6cab
|
||
|
|
64ef2c9af7
|
||
|
|
c091d33a44
|
||
|
|
96342c1564
|
||
|
|
a3132792ea
|
||
|
|
1989948ab3
|
||
|
|
2e48acfc92
|
||
|
|
7b6154e7e8
|
||
|
|
3513dad609
|
||
|
|
84e9116877
|
||
|
|
fb5f3ad472
|
||
|
|
a88f5630fe
|
||
|
|
f47e60db00
|
||
|
|
29a06f7c54
|
||
|
|
30b4c28e06
|
||
|
|
01eb4aaf7c
|
||
|
|
b48616798d
|
||
|
|
073959b4f9
|
||
|
|
81bca2251e
|
||
|
|
32fbf8b69c
|
||
|
|
ee66e4f0f3
|
||
|
|
e70c27faf9
|
||
|
|
ae3bbc6cfe
|
||
|
|
98c0c11cbb
|
||
|
|
9af3b29342
|
||
|
|
96fb0afcd9
|
||
|
|
90637aa457
|
||
|
|
0346bfef77
|
||
|
|
b868d450bd
|
||
|
|
064eeab748
|
||
|
|
904c510246
|
||
|
|
cf6108ad14
|
||
|
|
010b964264
|
||
|
|
731417ab48
|
||
|
|
264062866c
|
||
|
|
59b0ac03c9
|
||
|
|
c12f6b7947
|
||
|
|
7673e3a135
|
||
|
|
f47aac477a
|
||
|
|
9e776f23ed
|
||
|
|
5642058fd0
|
||
|
|
cbfcd43018
|
||
|
|
a0d14090ef
|
||
|
|
091d117459
|
||
|
|
0807fe6ad6
|
||
|
|
4db38e0d2a
|
||
|
|
9e8f160f25
|
||
|
|
64dfad6d53
|
No files matched your search
@@ -1,24 +1,20 @@
|
||||
# Live reload for archied during dashboard work.
|
||||
# Live reload for the single archie binary during development.
|
||||
#
|
||||
# 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`.
|
||||
# The frontend has its own loop -- `task dev:ui` runs Vite with HMR and proxies
|
||||
# /api 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.
|
||||
# Built with `-tags no_ui`: during development Vite serves the frontend
|
||||
# directly with HMR, so embedding ui/dist would only slow down reloads.
|
||||
root = "."
|
||||
tmp_dir = ".air"
|
||||
|
||||
[build]
|
||||
cmd = "go build -o ./.air/archied ./cmd/archied"
|
||||
cmd = "go build -tags no_ui -o ./.air/archie ./cmd/archie"
|
||||
# `bin` is deprecated in air; entrypoint is the current key.
|
||||
entrypoint = "./.air/archied"
|
||||
include_ext = ["go", "toml"]
|
||||
entrypoint = "./.air/archie"
|
||||
include_ext = ["go", "toml", "sql", "yaml", "cedar", "tmpl", "md"]
|
||||
exclude_dir = ["ui", "bin", "docs", ".git", ".task", ".air", "tmp"]
|
||||
exclude_regex = ["_test\\.go"]
|
||||
stop_on_error = true
|
||||
|
||||
+11
@@ -51,3 +51,14 @@ __pycache__/
|
||||
.agents-run/
|
||||
/.pnpm-store/
|
||||
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/
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"buildPath": "code",
|
||||
"hook": {
|
||||
"enabled": true,
|
||||
"limits": {
|
||||
"maxFindings": 5,
|
||||
"maxChars": 8000
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
StylesPath = .vale/styles
|
||||
MinAlertLevel = warning
|
||||
Vocab = Archie
|
||||
|
||||
# Run `vale sync` to install external packages and the Go comment grammar.
|
||||
Packages = Google, Microsoft, Voices, TechTerms, Comments, Prompts
|
||||
Grammars = go
|
||||
|
||||
[formats]
|
||||
tmpl = md
|
||||
|
||||
[*.{md,tmpl}]
|
||||
# Ignore Go/workflow template expressions such as {{ steps.plan.summary }}.
|
||||
TokenIgnores = (\{\{[^}]*\}\})
|
||||
|
||||
BasedOnStyles = Vale, Voices, Direct, Google, Archie
|
||||
|
||||
# Australian English and Archie's technical prose conventions:
|
||||
Google.Spelling = NO
|
||||
Google.Quotes = NO
|
||||
Google.DateFormat = NO
|
||||
Google.OxfordComma = NO
|
||||
Google.EmDash = NO
|
||||
Google.Contractions = NO
|
||||
Google.Parens = NO
|
||||
Google.Semicolons = NO
|
||||
Google.Colons = NO
|
||||
Google.Units = NO
|
||||
Google.Acronyms = NO
|
||||
Google.WordList = NO
|
||||
Google.WordListCase = NO
|
||||
|
||||
# Keep style nudges advisory (visible with --minAlertLevel=suggestion).
|
||||
Google.Headings = suggestion
|
||||
Google.Latin = suggestion
|
||||
Google.Exclamation = warning
|
||||
Google.FirstPerson = suggestion
|
||||
Google.We = suggestion
|
||||
Google.Will = suggestion
|
||||
|
||||
# Selective Microsoft rules (UI verbs, inclusive terminology, hyphens) without
|
||||
# pulling in Microsoft-specific product jargon (e.g. agent -> personal digital assistant).
|
||||
Microsoft.UIVerbs = warning
|
||||
Microsoft.BiasFree = warning
|
||||
Microsoft.Auto = warning
|
||||
Microsoft.Suspended = warning
|
||||
Microsoft.Accessibility = suggestion
|
||||
Microsoft.Uppercase = suggestion
|
||||
|
||||
# "Term: explanation" is idiomatic throughout Archie's docs and comments.
|
||||
Voices.ColonReveal = NO
|
||||
|
||||
# Replaced by Archie.Readability and Archie.SentenceLength, calibrated for technical docs.
|
||||
Direct.Ease = NO
|
||||
Direct.Length = NO
|
||||
Direct.Hedging = warning
|
||||
Direct.Preamble = warning
|
||||
|
||||
# Agent instruction and skill files get additional prompt-quality checks.
|
||||
[{AGENTS,CLAUDE,SKILL}.md]
|
||||
BasedOnStyles = Vale, Voices, Direct, Google, Archie, Prompts
|
||||
# A rule file states each rule once, and many of those rules are absolutes.
|
||||
# The prompt heuristic against repeated absolutes does not apply here.
|
||||
Prompts.Absolutes = NO
|
||||
|
||||
# Model prompts are plain text (no Markdown bold) and reference tool names inline.
|
||||
[internal/prompts/*.{md,tmpl}]
|
||||
Vale.Spelling = suggestion
|
||||
Archie.UILabelFormat = NO
|
||||
|
||||
# Go source comments: doc conventions, spelling, clarity, and no migration narration.
|
||||
[*.go]
|
||||
BasedOnStyles = Vale, Voices, Comments, GoDoc, Archie
|
||||
|
||||
# Go comments often mention camelCase/snake_case identifiers without backticks,
|
||||
# so keep spelling advisory here.
|
||||
Vale.Spelling = suggestion
|
||||
|
||||
# Upstream GoDoc.Sentence regex backtracks heavily on long comment blocks.
|
||||
GoDoc.Sentence = NO
|
||||
Voices.ColonReveal = NO
|
||||
Archie.Readability = NO
|
||||
Archie.SentenceLength = NO
|
||||
Archie.UIElementType = NO
|
||||
Archie.UILabelFormat = NO
|
||||
|
||||
# Never lint generated Go files (protobuf, sqlc).
|
||||
[*.{pb,sql}.go]
|
||||
BasedOnStyles =
|
||||
@@ -0,0 +1,154 @@
|
||||
# Enforce Australian English spelling in prose.
|
||||
# Intentionally omits computing standards that use US forms in Australia
|
||||
# (program, disk, artifact) and verb/noun pairs (licence/license, practise/practice).
|
||||
extends: substitution
|
||||
message: "Use Australian English '%s' instead of '%s'."
|
||||
level: warning
|
||||
ignorecase: true
|
||||
action:
|
||||
name: replace
|
||||
# Exact-case exceptions for HTTP headers and Go method names.
|
||||
exceptions:
|
||||
- Authorize
|
||||
- Authorization
|
||||
swap:
|
||||
analyze: analyse
|
||||
analyzed: analysed
|
||||
analyzes: analyses
|
||||
analyzing: analysing
|
||||
authorization: authorisation
|
||||
authorizations: authorisations
|
||||
authorize: authorise
|
||||
authorized: authorised
|
||||
authorizes: authorises
|
||||
authorizing: authorising
|
||||
behavior: behaviour
|
||||
behavioral: behavioural
|
||||
behaviors: behaviours
|
||||
canceled: cancelled
|
||||
canceling: cancelling
|
||||
canonicalize: canonicalise
|
||||
canonicalized: canonicalised
|
||||
canonicalizes: canonicalises
|
||||
canonicalizing: canonicalising
|
||||
catalog: catalogue
|
||||
cataloged: catalogued
|
||||
cataloging: cataloguing
|
||||
catalogs: catalogues
|
||||
categorization: categorisation
|
||||
categorize: categorise
|
||||
categorized: categorised
|
||||
categorizes: categorises
|
||||
categorizing: categorising
|
||||
center: centre
|
||||
centered: centred
|
||||
centering: centring
|
||||
centers: centres
|
||||
color: colour
|
||||
colored: coloured
|
||||
coloring: colouring
|
||||
colors: colours
|
||||
customization: customisation
|
||||
customize: customise
|
||||
customized: customised
|
||||
customizes: customises
|
||||
customizing: customising
|
||||
favor: favour
|
||||
favored: favoured
|
||||
favoring: favouring
|
||||
favorite: favourite
|
||||
favorites: favourites
|
||||
favors: favours
|
||||
finalize: finalise
|
||||
finalized: finalised
|
||||
finalizes: finalises
|
||||
finalizing: finalising
|
||||
fulfill: fulfil
|
||||
fulfillment: fulfilment
|
||||
fulfills: fulfils
|
||||
initialization: initialisation
|
||||
initialize: initialise
|
||||
initialized: initialised
|
||||
initializes: initialises
|
||||
initializing: initialising
|
||||
judgment: judgement
|
||||
judgments: judgements
|
||||
labeled: labelled
|
||||
labeling: labelling
|
||||
maximize: maximise
|
||||
maximized: maximised
|
||||
maximizes: maximises
|
||||
maximizing: maximising
|
||||
minimize: minimise
|
||||
minimized: minimised
|
||||
minimizes: minimises
|
||||
minimizing: minimising
|
||||
modeled: modelled
|
||||
modeling: modelling
|
||||
normalization: normalisation
|
||||
normalize: normalise
|
||||
normalized: normalised
|
||||
normalizes: normalises
|
||||
normalizing: normalising
|
||||
optimization: optimisation
|
||||
optimizations: optimisations
|
||||
optimize: optimise
|
||||
optimized: optimised
|
||||
optimizes: optimises
|
||||
optimizing: optimising
|
||||
organization: organisation
|
||||
organizational: organisational
|
||||
organizations: organisations
|
||||
organize: organise
|
||||
organized: organised
|
||||
organizes: organises
|
||||
organizing: organising
|
||||
parameterize: parameterise
|
||||
parameterized: parameterised
|
||||
parameterizes: parameterises
|
||||
parameterizing: parameterising
|
||||
prioritize: prioritise
|
||||
prioritized: prioritised
|
||||
prioritizes: prioritises
|
||||
prioritizing: prioritising
|
||||
recognize: recognise
|
||||
recognized: recognised
|
||||
recognizes: recognises
|
||||
recognizing: recognising
|
||||
sanitization: sanitisation
|
||||
sanitize: sanitise
|
||||
sanitized: sanitised
|
||||
sanitizes: sanitises
|
||||
sanitizing: sanitising
|
||||
serialization: serialisation
|
||||
serialize: serialise
|
||||
serialized: serialised
|
||||
serializes: serialises
|
||||
serializing: serialising
|
||||
stabilize: stabilise
|
||||
stabilized: stabilised
|
||||
stabilizes: stabilises
|
||||
stabilizing: stabilising
|
||||
summarize: summarise
|
||||
summarized: summarised
|
||||
summarizes: summarises
|
||||
summarizing: summarising
|
||||
synchronization: synchronisation
|
||||
synchronize: synchronise
|
||||
synchronized: synchronised
|
||||
synchronizes: synchronises
|
||||
synchronizing: synchronising
|
||||
unauthorized: unauthorised
|
||||
|
||||
tests:
|
||||
- name: flags US spelling
|
||||
input: |
|
||||
The organization enforces authorization behavior.
|
||||
want: |
|
||||
1:5:Archie.AustralianEnglish:Use Australian English 'organisation' instead of 'organization'.
|
||||
1:27:Archie.AustralianEnglish:Use Australian English 'authorisation' instead of 'authorization'.
|
||||
1:41:Archie.AustralianEnglish:Use Australian English 'behaviour' instead of 'behavior'.
|
||||
- name: accepts Australian spelling and inline code
|
||||
input: |
|
||||
The organisation enforces authorisation behaviour via `behavior_flag`.
|
||||
want: ""
|
||||
@@ -0,0 +1,29 @@
|
||||
# AGENTS.md: "Comments explain why, not what the code already says.
|
||||
# No migration history, phase names or issue narration in code."
|
||||
extends: existence
|
||||
message: "Avoid migration or plan narration ('%s') in code comments. Explain what the code does or why."
|
||||
level: warning
|
||||
scope: comment.go
|
||||
ignorecase: true
|
||||
nonword: true
|
||||
tokens:
|
||||
- '\b(?:phase|wave|slice|sprint)\s+\d+\b'
|
||||
- '\bepic\s+#\d+\b'
|
||||
- '\b(?:formerly|previously)\s+(?:called|named|known as)\b'
|
||||
- '\b(?:migrated|moved|extracted|ported)\s+from\b'
|
||||
|
||||
tests:
|
||||
- name: flags migration narration in Go comments
|
||||
format: go
|
||||
input: |
|
||||
// Phase 2 moved from internal/legacy.
|
||||
package demo
|
||||
want: |
|
||||
1:4:Archie.NoMigrationNarration:Avoid migration or plan narration ('Phase 2') in code comments. Explain what the code does or why.
|
||||
1:12:Archie.NoMigrationNarration:Avoid migration or plan narration ('moved from') in code comments. Explain what the code does or why.
|
||||
- name: allows normal rationale comments
|
||||
format: go
|
||||
input: |
|
||||
// Verify the HMAC before parsing so malformed payloads cannot trigger work.
|
||||
package demo
|
||||
want: ""
|
||||
@@ -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: ""
|
||||
@@ -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: ""
|
||||
@@ -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: ""
|
||||
@@ -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: ""
|
||||
@@ -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: ""
|
||||
@@ -0,0 +1,44 @@
|
||||
# Prefer concise wording over wordy phrases.
|
||||
extends: substitution
|
||||
message: "Use '%s' instead of '%s'."
|
||||
level: warning
|
||||
ignorecase: true
|
||||
action:
|
||||
name: replace
|
||||
swap:
|
||||
a large number of: many
|
||||
a majority of: most
|
||||
a sufficient number of: enough
|
||||
as a means of: to
|
||||
at this point in time: now
|
||||
due to the fact that: because
|
||||
for the purpose of: to
|
||||
has the capability to: can
|
||||
in close proximity to: near
|
||||
in excess of: more than
|
||||
in spite of the fact that: although
|
||||
in the event that: if
|
||||
in the near future: soon
|
||||
make use of: use
|
||||
on a daily basis: daily
|
||||
on a monthly basis: monthly
|
||||
on a weekly basis: weekly
|
||||
prior to: before
|
||||
subsequent to: after
|
||||
take advantage of: use
|
||||
until such time as: until
|
||||
whether or not: whether
|
||||
with regard to: about
|
||||
with respect to: about
|
||||
|
||||
tests:
|
||||
- name: flags wordy phrases
|
||||
input: |
|
||||
Check the signature prior to parsing due to the fact that payloads are untrusted.
|
||||
want: |
|
||||
1:21:Archie.Wordiness:Use 'before' instead of 'prior to'.
|
||||
1:38:Archie.Wordiness:Use 'because' instead of 'due to the fact that'.
|
||||
- name: accepts concise wording
|
||||
input: |
|
||||
Check the signature before parsing because payloads are untrusted.
|
||||
want: ""
|
||||
@@ -0,0 +1,30 @@
|
||||
# Case-insensitive common terms (matched in any capitalisation)
|
||||
(?i)approvers?
|
||||
(?i)archipelago
|
||||
(?i)canonicalis(?:e[ds]?|ing)
|
||||
(?i)carina
|
||||
(?i)confirmers?
|
||||
(?i)fulfilment
|
||||
(?i)passkeys?
|
||||
(?i)reapprovals?
|
||||
(?i)redemptions?
|
||||
(?i)retags?
|
||||
(?i)undispatched
|
||||
(?i)unpushed
|
||||
(?i)worktrees?
|
||||
|
||||
# Proper nouns, tools, and exact-case technical terms
|
||||
archied
|
||||
Catlow
|
||||
depguard
|
||||
gosec
|
||||
govulncheck
|
||||
hclog
|
||||
Huma
|
||||
Miessler
|
||||
Pdeathsig
|
||||
prbench
|
||||
Reka
|
||||
releaseupdate
|
||||
secretengine
|
||||
sqlc
|
||||
@@ -5,9 +5,9 @@ here changes a decision. If a rule stops changing decisions, delete it.
|
||||
|
||||
## What this is
|
||||
|
||||
**archie-core** is event-driven agentic automation. An event (an alert, a
|
||||
webhook, a schedule, a chat message, an issue) is matched to a workflow, the
|
||||
workflow runs an agent whose every action is judged before it runs, and the
|
||||
**archie-core** is event-driven agentic automation. It matches an event (an
|
||||
alert, a webhook, a schedule, a chat message, an issue) to a workflow. 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
|
||||
to a workflow, not the point of the product. A forge is one of many inputs or
|
||||
outputs; core code never assumes one.
|
||||
@@ -33,9 +33,9 @@ there:
|
||||
needs the maintainer's verdict on its row. Before building anything an old
|
||||
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
|
||||
add features to them; fix them only when a bug blocks work.
|
||||
|
||||
@@ -79,13 +79,14 @@ When sources disagree, the higher one wins:
|
||||
the plan, offer options, or ask "shall I proceed?". Stop only for destructive
|
||||
or outward-facing actions (deleting data, pushing, touching a live host).
|
||||
- **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
|
||||
gap, a broken setup path), or looks like the wrong call, say so once in a
|
||||
sentence or two and suggest whether it belongs in the backlog. Then do what
|
||||
was asked: don't repeat the point or hold work back on your own judgement.
|
||||
more urgent, or looks like the wrong call, say so once in a sentence or two.
|
||||
A bug that loses work, a failure that shows nothing, a security gap and a
|
||||
broken setup path are all more urgent. Suggest whether it belongs in the
|
||||
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
|
||||
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
|
||||
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
|
||||
@@ -113,11 +114,12 @@ When sources disagree, the higher one wins:
|
||||
- **No compensating tools.** Do not write a linter, checker or generator to
|
||||
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
|
||||
consumer is a bug. Settings are edited through the control plane (API and
|
||||
dashboard), never by requiring a server login.
|
||||
consumer is a bug. Operators edit settings through the control plane (API and
|
||||
dashboard), never through a server login.
|
||||
- **Ask only for real decisions.** Product direction and trade-offs the
|
||||
maintainer owns are questions. Everything with a conventional answer is not:
|
||||
decide, do it, say what you chose.
|
||||
maintainer owns are questions. Anything with a conventional engineering
|
||||
answer or an existing pattern in the codebase is not: decide, do it, say
|
||||
what you chose.
|
||||
|
||||
## Code
|
||||
|
||||
@@ -127,14 +129,24 @@ When sources disagree, the higher one wins:
|
||||
- Dependencies point inward: `cmd → app → {domain, infrastructure}`,
|
||||
`infrastructure` implements `domain` interfaces, `domain` imports neither.
|
||||
`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`
|
||||
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.
|
||||
- Comments say why, briefly. No migration history, phase names or issue
|
||||
narration in code.
|
||||
- Generated files (protobuf, sqlc) are regenerated and committed
|
||||
with the change that caused them, never hand-edited.
|
||||
- Comments explain why, not what the code already says. No migration
|
||||
history, phase names or issue narration in code.
|
||||
- Write natural, idiomatic technical English in comments, errors, logs,
|
||||
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
|
||||
|
||||
@@ -150,14 +162,14 @@ The default for a change is no new test. Write one only when:
|
||||
A test that exists must catch a real regression, survive refactoring, run fast,
|
||||
and be cheap to keep. Never test wiring, constants, defaults, struct shapes,
|
||||
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:
|
||||
|
||||
- **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
|
||||
can't be reproduced deterministically (a race, say), fix it with an API that
|
||||
rules it out and don't add a test.
|
||||
fail. A test that passes either way proves nothing: delete it. When you
|
||||
can't reproduce a bug deterministically (a race, say), fix it with an API
|
||||
that rules it out and don't add a 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
|
||||
guards.
|
||||
@@ -169,7 +181,7 @@ How to write one:
|
||||
- **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
|
||||
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
|
||||
in a helper in a `_test.go` file, never in production code.
|
||||
|
||||
@@ -177,18 +189,19 @@ How to write one:
|
||||
|
||||
These protect users. Do not weaken them without the maintainer's say-so.
|
||||
|
||||
- A crash loses no accepted work, and a restart resumes every run. Work is
|
||||
acknowledged only once it is durable. A missing dependency is reported
|
||||
unhealthy and retried, never a reason to exit.
|
||||
- A crash loses no accepted work, and a restart resumes every run. The service
|
||||
that accepts the work acknowledges it only once it is durable. A service
|
||||
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 daemon's own credentials never enter an agent container. Containers get
|
||||
task-scoped grants that are revoked when the task ends.
|
||||
- Webhook HMAC is verified before the payload is parsed.
|
||||
task-scoped grants that the daemon revokes when the task ends.
|
||||
- The events module verifies webhook HMAC before it parses the payload.
|
||||
- Task briefs go in `<worktree>/.git/task.json`, never the worktree root.
|
||||
- NATS: task and RPC replies use `msg.Respond`; flush after registering a
|
||||
responder; `ARCHIE_TASKS` is a work queue, so never bind overlapping
|
||||
consumers.
|
||||
- `ai-sdk` `FullStream` must be drained completely.
|
||||
- Drain `ai-sdk` `FullStream` completely.
|
||||
|
||||
## Build and gate
|
||||
|
||||
@@ -216,16 +229,16 @@ Requires Go 1.27, Task, golangci-lint, Node, pnpm and Docker. Adopt `task fmt` a
|
||||
run, say what you did verify.
|
||||
- Commit finished work without asking. Stage only your own paths and commit in
|
||||
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
|
||||
goes in `/tmp`.
|
||||
- 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`.
|
||||
|
||||
## Issues (Gitea)
|
||||
|
||||
Work is tracked as issues on the primary remote, never in Markdown TODO files.
|
||||
Track work as issues on the primary remote, never in Markdown TODO files.
|
||||
GitHub is a read-only mirror; do not open, close or comment there.
|
||||
|
||||
```bash
|
||||
@@ -236,12 +249,12 @@ tea comment 497 "what changed, and what was run"
|
||||
tea issues close 497
|
||||
```
|
||||
|
||||
- An issue is the plan: what is wrong or wanted, and how you know it is done.
|
||||
Keep it to that.
|
||||
- An issue is the plan: what is wrong or wanted, and how you know the work is
|
||||
complete. Keep it to that.
|
||||
- Labels carry state: a type (`bug`, `feature`, `task`, `chore`, `epic`,
|
||||
`decision`, `discovery`), a priority (`critical`, `high`, `medium`, `low`), `in-progress`
|
||||
and `deferred`. Open/closed is the issue state, not a label.
|
||||
- An epic's children are its dependencies: link each one as it is filed (Gitea
|
||||
- An epic's children are its dependencies: link each one as you file it (Gitea
|
||||
MCP `issue_write` `add_dependency`, the epic `blocked_by` the child), plus any
|
||||
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.
|
||||
@@ -258,6 +271,6 @@ tea issues close 497
|
||||
|
||||
## 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.
|
||||
Keep it short enough to read in full every session.
|
||||
@@ -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.
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
# Product
|
||||
|
||||
<!-- impeccable:product-schema 1 -->
|
||||
|
||||
## Platform
|
||||
|
||||
web
|
||||
|
||||
## Users
|
||||
|
||||
Archie's audience comes in two stages.
|
||||
|
||||
1. **Now: the solo operator.** An infrastructure or IT operations engineer who
|
||||
runs their own estate of VMs, containers and on-prem hosts, self-hosts
|
||||
Archie, and wants day-2 operations handled without babysitting: disks filling
|
||||
up, alerts firing, routine maintenance. They use the dashboard on desktop and
|
||||
phone, and talk to Archie through chat channels.
|
||||
2. **Next: the IT operations team.** A team inside an organisation where an
|
||||
application owner (recorded in the CMDB) approves production changes on the
|
||||
servers that belong to their application. Governance, audit and risk
|
||||
controls decide whether the team adopts it.
|
||||
|
||||
## Product Purpose
|
||||
|
||||
Archie is event-driven agentic automation. It hears an event (an alert, a
|
||||
webhook, a schedule, a chat message, an issue), works out what it means, decides
|
||||
what to do, and does the work through an agent. It judges every action before
|
||||
the action runs, and delivers the result wherever it needs review or action.
|
||||
|
||||
Success: an operator connects a source and Archie notices events, acts without
|
||||
being asked when it is allowed to, and calls the operator in only when policy or
|
||||
risk requires it, with an explanation of what it found and did.
|
||||
|
||||
The loop is Hears, Understands, Decides, Defines, Does, Delivers. The platform
|
||||
around it Governs, Reports, Assesses, Manages Risk and Invokes Policy.
|
||||
|
||||
## Positioning
|
||||
|
||||
In order of importance:
|
||||
|
||||
1. **Earned, explained autonomy.** Guards (policy, risk and others, each an
|
||||
extension) score every action before it runs, and those scores set how much
|
||||
the agent may do alone. Autonomy is graded per action, earned from approval
|
||||
history, and always explained. Loosening a ceiling always needs approval from
|
||||
someone with authority; it never happens automatically.
|
||||
2. **Proposals from unhandled events.** The operator states intent rather than
|
||||
wiring steps. Events that nothing handles become proposals, and workflows
|
||||
learn from outcomes. Archie writes, runs and changes its own workflows; the
|
||||
operator can view or edit them but should not need to.
|
||||
3. **Self-hosted operations on VM and on-prem estates.** Archie runs in the
|
||||
operator's own environment and acts directly, or through the automation a
|
||||
team already has (AAP, Semaphore, ServiceNow).
|
||||
|
||||
Archie executes agentic work itself. It is not only a judgement layer, and not
|
||||
another visual workflow builder in the n8n, Zapier or Make mould.
|
||||
|
||||
## Operating Context
|
||||
|
||||
- Events arrive from monitoring (for example Alertmanager on Prometheus),
|
||||
webhooks, schedules, chat channels and forges. A forge is one source among
|
||||
many; a repository is an optional input to a workflow, never the point.
|
||||
- Results and approval requests go out as events to any channel (Telegram,
|
||||
Slack, Discord, email, webhooks, the dashboard chat composer) and come back in.
|
||||
- An approver can be an operator, a rule, a classifier or an automatic decision.
|
||||
Never assume a human approver.
|
||||
- Channels, forges, connectors, secret engines and guards ship as extensions,
|
||||
not in-tree.
|
||||
- The leading demonstration is proactive day-2 operations: a disk-filling alert
|
||||
from Prometheus, investigated and remediated, with the operator told on both a
|
||||
chat channel and the dashboard.
|
||||
|
||||
## Capabilities and Constraints
|
||||
|
||||
- One self-contained binary, `archie`, backed by PostgreSQL. Docker is never
|
||||
the only mechanism for isolation or enforcement.
|
||||
- The dashboard is a Vue single-page app embedded in the binary, used on
|
||||
desktop and phone.
|
||||
- The dashboard is the complete control plane: every configuration and mutable
|
||||
setting is editable there. A setting reachable only through a file, flag or
|
||||
API is a defect. Secrets are write-only.
|
||||
- Every request and response of every judge, guard, action, model call,
|
||||
delivery and evaluation is recorded for audit, never including credentials.
|
||||
- Terminology: source, event, workflow, run, step, guard, approval, proposal,
|
||||
connector, delivery. "Bindings" is a known-obscure name awaiting a
|
||||
replacement.
|
||||
- Undecided: the replacement for bindings and issue routing in the Decide step;
|
||||
how guard scores combine into an autonomy mode; how Deliver works without
|
||||
hard-coded outputs.
|
||||
|
||||
## Brand Commitments
|
||||
|
||||
- Name: Archie. Tagline: "Event-driven Agentic Automation".
|
||||
- Assets in `assets/brand/`: wordmark (light, dark, mono), mark, app icon,
|
||||
social card.
|
||||
- Interface copy states the problem and the action only. It never explains the
|
||||
interface, restates a title, or describes the mechanism behind it.
|
||||
- Never frame the product around coding or a repository.
|
||||
|
||||
## Evidence on Hand
|
||||
|
||||
- Live staging deployment of the single binary, with real Prometheus alerts,
|
||||
Telegram, Semaphore and host connectors.
|
||||
- No customers, testimonials, benchmarks, pricing or press exist. Do not
|
||||
fabricate any.
|
||||
|
||||
## Product Principles
|
||||
|
||||
1. **Governance is the product.** Judgement before every action, a full audit
|
||||
record, and autonomy that is earned and explained are what make Archie worth
|
||||
adopting. Keep them visible, not buried.
|
||||
2. **Intent, not wiring.** The operator says what they want; Archie defines the
|
||||
workflow. Editing is available, never required.
|
||||
3. **Editor and observer are one live surface.** Workflows are defined,
|
||||
connected and watched on the same interactive canvas, updating live as
|
||||
events and runs flow through it. Nodes show what they do.
|
||||
4. **Interrupt only when it matters.** Archie calls the operator in when policy
|
||||
or risk requires it, with what it found and what it did, not to report
|
||||
routine success.
|
||||
5. **Everything operable from the dashboard.** No setting needs a server login.
|
||||
@@ -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
|
||||
context of each event to decide how to accomplish the task.
|
||||
|
||||
Archie is under active development and not every capability below is
|
||||
finished.
|
||||
Archie is under active development and some capabilities below remain
|
||||
unfinished.
|
||||
|
||||
## 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).
|
||||
`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
|
||||
|
||||
- [Your first playbook](docs/guides/first-playbook.md)
|
||||
|
||||
+4
-4
@@ -2,7 +2,7 @@
|
||||
|
||||
One `v*` tag names a release. One version covers every process in the host
|
||||
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.
|
||||
|
||||
## Cutting a release
|
||||
@@ -19,12 +19,12 @@ the deploy.
|
||||
The tag push runs `deploy.yml`:
|
||||
|
||||
- **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
|
||||
again after the gate.
|
||||
same run builds the binaries the zip ships, so it compiles nothing again
|
||||
after the gate.
|
||||
- **Images.** `archied:v<version>` and `archie-agent:v<version>`, plus
|
||||
`sha-<commit>` tags. `:latest` moves only on promotion.
|
||||
- **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
|
||||
`git.catlow.cloud/sam/archie` as `v<version>` and `next`. It never moves
|
||||
`stable`.
|
||||
|
||||
+144
-19
@@ -64,6 +64,18 @@ tasks:
|
||||
- task: db:generate
|
||||
- git diff --exit-code -- internal/infrastructure/postgres/postgresdb
|
||||
|
||||
pages:generate:
|
||||
desc: Write the dashboard's page catalogue to ui/pages/pages.json
|
||||
dir: ui
|
||||
cmds:
|
||||
- node --experimental-strip-types scripts/pages.ts
|
||||
|
||||
pages:check:
|
||||
desc: Regenerate the page catalogue and reject uncommitted differences
|
||||
cmds:
|
||||
- task: pages:generate
|
||||
- git diff --exit-code -- ui/pages/pages.json
|
||||
|
||||
openapi:generate:
|
||||
desc: Write the API's OpenAPI document to api/openapi.yaml
|
||||
cmds:
|
||||
@@ -124,7 +136,11 @@ tasks:
|
||||
- go run ./cmd/archied prbench {{.CLI_ARGS}}
|
||||
|
||||
dev:
|
||||
desc: Run development services and Vite at http://localhost:5173
|
||||
desc: Run archie (with live reload) and Vite at http://localhost:5173
|
||||
deps: [dev:archie, dev:ui]
|
||||
|
||||
dev:legacy:
|
||||
desc: Run the legacy multi-service stack and Vite at http://localhost:5173
|
||||
deps: [dev:daemon, dev:gateway, dev:messaging, dev:state-store, dev:dashboard, dev:ui]
|
||||
|
||||
dev:tls:
|
||||
@@ -163,13 +179,36 @@ tasks:
|
||||
exit 1
|
||||
- |
|
||||
# docker-compose.yml creates the dev database with a superuser named
|
||||
# archie; provision the least-privilege roles deployments/dev.toml
|
||||
# points at. Idempotent, so this also upgrades a volume created before
|
||||
# the role split.
|
||||
go run ./cmd/archie-state-store provision \
|
||||
-admin-url "postgres://archie:archie@127.0.0.1:5432/archie?sslmode=disable" \
|
||||
-runtime-url "postgres://archie_runtime:archie@127.0.0.1:5432/archie?sslmode=disable" \
|
||||
-migration-url "postgres://archie_migrator:archie@127.0.0.1:5432/archie?sslmode=disable"
|
||||
# archie; provision the least-privilege runtime and migrator roles
|
||||
# idempotently without depending on the legacy state-store binary.
|
||||
# Single-binary archie uses its own database (archie_dev) so its goose
|
||||
# migration history does not collide with the legacy archie database.
|
||||
docker compose exec -T postgres psql -v ON_ERROR_STOP=1 -U archie -d postgres <<'SQL'
|
||||
DO $$
|
||||
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:
|
||||
internal: true
|
||||
@@ -183,54 +222,93 @@ tasks:
|
||||
exit 1
|
||||
|
||||
dev:daemon:
|
||||
desc: Run archied with live reload
|
||||
desc: Run legacy archied
|
||||
cmds:
|
||||
- task: dev:wait-state
|
||||
- air -build.args_bin="-config-overlay,deployments/dev.toml"
|
||||
- go run ./cmd/archied -config-overlay deployments/dev.toml
|
||||
|
||||
dev:dashboard:
|
||||
desc: Run the dashboard backend
|
||||
desc: Run the legacy dashboard backend
|
||||
cmds:
|
||||
- go run ./cmd/archie-ui -config-overlay deployments/dev.toml
|
||||
|
||||
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]
|
||||
cmds:
|
||||
- go run ./cmd/archie-state-store -config-overlay deployments/dev.toml
|
||||
|
||||
dev:gateway:
|
||||
desc: Run the development Gateway
|
||||
desc: Run the legacy development Gateway
|
||||
cmds:
|
||||
- task: dev:wait-state
|
||||
- go run ./cmd/archie-gateway -config-overlay deployments/dev.toml
|
||||
|
||||
dev:messaging:
|
||||
desc: Run the development Messaging Service
|
||||
desc: Run the legacy development Messaging Service
|
||||
cmds:
|
||||
- task: dev:wait-state
|
||||
- go run ./cmd/archie-messaging -config-overlay deployments/dev.toml
|
||||
|
||||
dev:archie:
|
||||
desc: Run the single archie binary against the development PostgreSQL (admin token "dev", live reload via air if installed)
|
||||
deps: [dev:postgres]
|
||||
vars:
|
||||
DIR: tmp/dev-archie
|
||||
cmds:
|
||||
- |
|
||||
set -eu
|
||||
mkdir -p {{.DIR}}/state
|
||||
# Generated once: the age identity seals the dev credentials, so keep
|
||||
# it across runs. Roles come from dev:postgres.
|
||||
if [ ! -f {{.DIR}}/config.toml ]; then
|
||||
install -m 0600 /dev/null {{.DIR}}/config.toml
|
||||
{
|
||||
echo 'listen = "127.0.0.1:8484"'
|
||||
echo 'state_dir = "{{.ROOT_DIR}}/{{.DIR}}/state"'
|
||||
echo "admin_token_sha256 = \"$(printf dev | sha256sum | cut -d' ' -f1)\""
|
||||
echo "age_identity = \"$(go run -tags no_ui ./cmd/archie -new-age-identity)\""
|
||||
echo '[database]'
|
||||
echo 'url = "postgres://archie_runtime:archie@127.0.0.1:5432/archie_dev?sslmode=disable"'
|
||||
echo 'owner_url = "postgres://archie_migrator:archie@127.0.0.1:5432/archie_dev?sslmode=disable"'
|
||||
} > {{.DIR}}/config.toml
|
||||
elif ! grep -q '^state_dir' {{.DIR}}/config.toml; then
|
||||
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 -tags no_ui ./cmd/archie -config {{.DIR}}/config.toml
|
||||
|
||||
dev:ui:
|
||||
desc: Run Vite (requires the dashboard backend)
|
||||
desc: Run Vite (proxies API requests to 127.0.0.1:8484 by default; override with ARCHIE_DEV_API)
|
||||
dir: ui
|
||||
deps: [ui:deps]
|
||||
cmds:
|
||||
- pnpm install
|
||||
- pnpm run dev
|
||||
|
||||
e2e:smoke:
|
||||
desc: Run the single-binary smoke check against a disposable archie instance (defaults to dev:archie on 127.0.0.1:8484)
|
||||
cmds:
|
||||
- |
|
||||
ARCHIE_SMOKE_URL="${ARCHIE_SMOKE_URL:-http://127.0.0.1:8484}" \
|
||||
ARCHIE_SMOKE_TOKEN="${ARCHIE_SMOKE_TOKEN:-dev}" \
|
||||
node e2e/archie-smoke.cjs
|
||||
|
||||
e2e:up:
|
||||
desc: Start the local stack without Docker (PostgreSQL 18, services, Vite) and seed it
|
||||
desc: Start the legacy local multi-service stack without Docker (PostgreSQL 18, services, Vite) and seed it
|
||||
cmds:
|
||||
- bash e2e/stack.sh start
|
||||
- bash e2e/seed.sh
|
||||
|
||||
e2e:down:
|
||||
desc: Stop the local e2e stack
|
||||
desc: Stop the legacy local e2e stack
|
||||
cmds:
|
||||
- bash e2e/stack.sh stop
|
||||
|
||||
e2e:check:
|
||||
desc: List browser checks; use -- all or -- CHECK to run, add --headed to watch
|
||||
desc: List legacy browser checks; use -- all or -- CHECK to run, add --headed to watch
|
||||
cmds:
|
||||
- node e2e/run.cjs {{.CLI_ARGS}}
|
||||
|
||||
@@ -252,14 +330,19 @@ tasks:
|
||||
- Taskfile.yml
|
||||
- "**/*.go"
|
||||
# Files the binaries embed.
|
||||
- config.example.toml
|
||||
- "internal/**/*.sql"
|
||||
- "internal/**/*.yaml"
|
||||
- "internal/**/*.json"
|
||||
- "internal/**/*.tpl"
|
||||
- "internal/**/*.tmpl"
|
||||
- "internal/**/*.md"
|
||||
- "modules/**/*.cedar"
|
||||
- "modules/**/*.yaml"
|
||||
- go.mod
|
||||
- go.sum
|
||||
- "ui/dist/**"
|
||||
- ui/pages/pages.json
|
||||
generates:
|
||||
- "{{.BIN_DIR}}/archied"
|
||||
- "{{.BIN_DIR}}/archie-gateway"
|
||||
@@ -320,12 +403,54 @@ tasks:
|
||||
# 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: pages:check
|
||||
- task: fmt
|
||||
- task: proto:check
|
||||
- task: db:check
|
||||
- task: openapi:check
|
||||
- task: check:readonly
|
||||
|
||||
wt:check:
|
||||
desc: "Fix, format and check a worktree's Go packages, and the dashboard if ui/ changed (-- ./pkg/... to name packages; default: those changed since main)"
|
||||
# A worktree has no ui/dist, so the Go steps build with no_ui. The full
|
||||
# gate still runs once, on the merged tree.
|
||||
cmds:
|
||||
- |
|
||||
set -eu
|
||||
base="$(git merge-base HEAD main)"
|
||||
changed="$( { git diff --name-only "$base"; git ls-files --others --exclude-standard; } | sort -u)"
|
||||
pkgs="{{.CLI_ARGS}}"
|
||||
if [ -z "$pkgs" ]; then
|
||||
pkgs="$(printf '%s\n' "$changed" | grep '\.go$' | grep -v '^ui/' | xargs -r -n1 dirname | sort -u | while read -r d; do [ -d "$d" ] && echo "./$d"; done | tr '\n' ' ')"
|
||||
fi
|
||||
if [ -n "$pkgs" ]; then
|
||||
echo "packages: $pkgs"
|
||||
# The same fixes and formatters as task fmt, applied to these
|
||||
# packages only; see fmt for why go fix runs until it converges.
|
||||
converged=false
|
||||
for pass in 1 2 3 4 5 6 7 8 9 10; do
|
||||
go fix -tags no_ui $pkgs
|
||||
if go fix -tags no_ui -diff $pkgs >/dev/null; then
|
||||
converged=true
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [ "$converged" != true ]; then
|
||||
echo "go fix still rewrites these packages after 10 passes" >&2
|
||||
exit 1
|
||||
fi
|
||||
golangci-lint fmt $pkgs
|
||||
go vet -tags no_ui $pkgs
|
||||
go test -short -tags no_ui $pkgs
|
||||
golangci-lint run --build-tags no_ui $pkgs
|
||||
fi
|
||||
if printf '%s\n' "$changed" | grep -q '^ui/'; then
|
||||
"{{.TASK_EXE}}" test:ui
|
||||
fi
|
||||
if [ -z "$pkgs" ] && ! printf '%s\n' "$changed" | grep -q '^ui/'; then
|
||||
echo "nothing changed since main"
|
||||
fi
|
||||
|
||||
check:readonly:
|
||||
internal: true
|
||||
deps:
|
||||
|
||||
+36
-37
@@ -1,15 +1,15 @@
|
||||
# Workflow definitions
|
||||
|
||||
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
|
||||
`workflow-definitions` resource and edited on the dashboard's Workflows page
|
||||
(the Canvas and YAML tabs edit the same document). The shipped workflows are in
|
||||
`internal/domain/workflow/shipped/`.
|
||||
and an ordered list of steps. Definitions live in the control plane's
|
||||
`workflow-definitions` resource, and operators edit them on the dashboard's
|
||||
Workflows page (the Canvas and YAML tabs edit the same document). The shipped
|
||||
workflows are in `internal/domain/workflow/shipped/`.
|
||||
|
||||
The server is the authority. It serves the step vocabulary, including each step
|
||||
type's settings schema, in the `workflow-definitions` catalog entry
|
||||
(`x-step-types`), and validates every definition when it is saved. This file
|
||||
describes that vocabulary; when they disagree, the catalog wins.
|
||||
type's settings schema, in the `workflow-definitions` catalogue entry
|
||||
(`x-step-types`), and validates every definition on save. This file
|
||||
describes that vocabulary; when they disagree, the catalogue wins.
|
||||
|
||||
```yaml
|
||||
id: implement
|
||||
@@ -41,10 +41,10 @@ steps:
|
||||
|---|---|---|
|
||||
| `id` | text | The workflow's name. Required, unique. |
|
||||
| `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> }}`. |
|
||||
| `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. |
|
||||
|
||||
## 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.plan` | The plan a `workflow.approve` step handed over (an approved PRD). |
|
||||
| `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>.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
|
||||
refused when the definition is saved. A value that does not exist at run time
|
||||
(for instance, a step that was skipped) renders empty.
|
||||
Reference only earlier steps; the server refuses a reference to a later or
|
||||
unknown step on save. A value that does not exist at run time (for instance, a
|
||||
step the run skipped) renders empty.
|
||||
|
||||
### 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
|
||||
the run unless it continues on failure.
|
||||
|
||||
A parked run can be retried from a top-level step instead of from the start.
|
||||
The steps before it are skipped and their results stay available to
|
||||
references. The resume point is named by the step's id (else its type), so
|
||||
give an id to any step whose type appears twice. A run with a repository
|
||||
resumes only on its pushed branch: work an earlier step did not push is not
|
||||
there.
|
||||
An operator can retry a parked run from a top-level step instead of from the
|
||||
start. The run skips the steps before it and keeps their results available to
|
||||
references. The step's id (else its type) names the resume point, so give an id
|
||||
to any step whose type appears twice. A run with a repository resumes only on
|
||||
its pushed branch: work an earlier step did not push is not there.
|
||||
|
||||
## Step types
|
||||
|
||||
@@ -129,11 +128,11 @@ _runs without a repository._
|
||||
|---|---|---|
|
||||
| `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. |
|
||||
| `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. |
|
||||
| `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. |
|
||||
| `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`
|
||||
|
||||
@@ -155,12 +154,12 @@ _needs a repository._
|
||||
| `push` | bool | Push the branch after committing. |
|
||||
| `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`
|
||||
and `core.hooksPath`, and the agent never runs git, so `pre-commit`,
|
||||
`commit-msg` and `prepare-commit-msg` in the checkout are inert files. A
|
||||
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
|
||||
reports success and the pull request fails the check afterwards. Put the same
|
||||
Hooks never run. go-git creates the commit, and it ignores `.git/hooks` and
|
||||
`core.hooksPath`; the agent never runs git, so `pre-commit`, `commit-msg` and
|
||||
`prepare-commit-msg` in the checkout are inert files. A
|
||||
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
|
||||
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
|
||||
container before this step.
|
||||
|
||||
@@ -189,7 +188,7 @@ No settings. It runs the repository policy's `tooling` commands, in order, in
|
||||
the task worktree — the installs a gate needs and the container does not ship
|
||||
(protoc plugins, linters, generators). A repository that declares none installs
|
||||
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
|
||||
repository.
|
||||
|
||||
@@ -237,7 +236,7 @@ of sending it.
|
||||
|---|---|---|
|
||||
| `channel` | text | The messaging channel to send through. |
|
||||
| `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
|
||||
`message.send`.
|
||||
@@ -301,16 +300,16 @@ _runs without a repository._
|
||||
|
||||
| Setting | Type | Meaning |
|
||||
|---|---|---|
|
||||
| `detail` | text | Why the task was handed off. |
|
||||
| `workflow` | text | The workflow the task is requeued under. |
|
||||
| `detail` | text | Why the workflow handed off the task. |
|
||||
| `workflow` | text | The workflow the handoff requeues the task under. |
|
||||
|
||||
`command.run` commands are `{name, argv, expect_failure}`: `argv` is the
|
||||
program and its arguments, and `expect_failure` requires a non-zero exit.
|
||||
|
||||
`gate.diff-rules` rules are `{id, level, pattern, path, exclude_path, message}`:
|
||||
`level` (`error` blocks, `warn` reports) and `pattern` (an RE2 expression matched
|
||||
against each added line) are required; `path` and `exclude_path` are RE2
|
||||
expressions that limit which files the rule applies to.
|
||||
the step requires `level` (`error` blocks, `warn` reports) and `pattern` (an RE2
|
||||
expression the gate matches against each added line); `path` and `exclude_path`
|
||||
are RE2 expressions that limit which files the rule applies to.
|
||||
|
||||
## What starts a workflow
|
||||
|
||||
@@ -320,8 +319,8 @@ expressions that limit which files the rule applies to.
|
||||
classifies it and hands off.
|
||||
- **Event bindings**: a webhook source mapped onto a workflow and its inputs
|
||||
(Events page).
|
||||
- **Schedules**: each firing is captured on the reserved `schedule` source as
|
||||
a `Schedule fired` event (`schedule_id`, `name`, `scheduled_for`,
|
||||
- **Schedules**: the scheduler captures each firing on the reserved `schedule`
|
||||
source as a `Schedule fired` event (`schedule_id`, `name`, `scheduled_for`,
|
||||
`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
|
||||
most one task per binding.
|
||||
|
||||
+7139
-343
File diff suppressed because it is too large.
Load diff
@@ -19,20 +19,31 @@ const recoveryUsage = `usage: archie-state-store <command> [flags]
|
||||
|
||||
With no command, archie-state-store serves the State Store gRPC contract.
|
||||
|
||||
The recovery commands are how an operator recovers a database the control
|
||||
plane will not start on. They operate on the PostgreSQL database the
|
||||
configuration's database_url names, through pg_dump and pg_restore (which
|
||||
must be on PATH).
|
||||
The recovery commands operate on the PostgreSQL database configured by
|
||||
database_url. Install the PostgreSQL client tools (pg_dump, pg_restore and
|
||||
psql) and make sure they're on PATH.
|
||||
|
||||
backup takes a consistent snapshot of a serving database. restore is
|
||||
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
|
||||
snapshot is lost. rollback refuses while the State Store serves. There is no
|
||||
automatic schema rollback: the way back from a migration is restoring the
|
||||
snapshot taken before it.
|
||||
while any of them holds its serving claim or the exclusive restore lock, and
|
||||
every write made after the snapshot is lost. rollback refuses while the State
|
||||
Store serves. There is no automatic schema rollback: the way back from a
|
||||
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
|
||||
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
|
||||
the configuration the daemon would boot with
|
||||
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.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.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 stored settings against it.
|
||||
flags.StringVar(&options.Config, "config", configuration.DefaultConfigPath(), "configuration file or directory the daemon boots with")
|
||||
|
||||
@@ -98,6 +98,15 @@ target = "127.0.0.1:9090"
|
||||
# catalogue = "registry.example/owner/archipelago/catalogue"
|
||||
# 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 —
|
||||
# file follow-up issues from recent runs. Definitions are data: the server
|
||||
# validates them and the gateway applies them live.
|
||||
|
||||
+22
-19
@@ -16,10 +16,12 @@ of its own (`deployments/systemd-user-service.md`).
|
||||
|
||||
`archie-agent` (the per-task sandboxed runtime) has no unit of its own. The
|
||||
agent image is a separate thing, pulled for the containers `archied` spawns
|
||||
per task: `[containers].image` defaults to
|
||||
`git.catlow.cloud/sam/archie-agent:latest`, while this archive's `release.json`
|
||||
pins the digest the release published. Set `[containers].registry_auth` when
|
||||
that reference is on a registry that needs a login -- see
|
||||
per task: `[containers].image` has no default, and the daemon reports it as
|
||||
missing at startup. This archive's `release.json` pins the digest the release
|
||||
published, and the deploy step passes it to the install, so a release install
|
||||
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`.
|
||||
|
||||
## Quickstart
|
||||
@@ -45,8 +47,8 @@ that reference is on a registry that needs a login -- see
|
||||
|
||||
3. Start the five processes. Order does not matter: a service whose peer is
|
||||
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
|
||||
is embedded.
|
||||
meanwhile. The Gateway waits for the daemon's NATS endpoint when the daemon
|
||||
runs the embedded broker.
|
||||
|
||||
```bash
|
||||
./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
|
||||
|
||||
This archive's binaries are built from the `archied` release tag in its
|
||||
filename; `archie-ui`, `archie-gateway`, `archie-state-store` and
|
||||
The release pipeline builds this archive's binaries from the `archied` release
|
||||
tag in its filename. `archie-ui`, `archie-gateway`, `archie-state-store` and
|
||||
`archie-messaging` ship at that same version rather than
|
||||
being independently tagged (see `RELEASING.md` in the source repository for why
|
||||
only `archied` and `archie-agent` are independently versioned).
|
||||
|
||||
`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
|
||||
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`.
|
||||
|
||||
### 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
|
||||
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
|
||||
zip must report `X`. It then pulls the agent image the statement pins by digest, backs up the database to
|
||||
`db.pre-update.dump` in the state directory, stages the new binaries beside the
|
||||
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. It stages the new binaries beside the
|
||||
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
|
||||
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
|
||||
`systemctl --user`. archied must report the new version and stay healthy for
|
||||
120 seconds. Otherwise the watchdog restores the previous binaries and image
|
||||
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
|
||||
and the outcome report says that every write since the update began is gone.
|
||||
policy. Data is not rolled back unless the new release migrated the database.
|
||||
Then the previous binaries cannot serve it, so the watchdog restores the
|
||||
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
|
||||
but restarts nothing, and the install reports that the services need a manual
|
||||
restart.
|
||||
@@ -116,10 +119,10 @@ restart.
|
||||
Transactions live in `${XDG_STATE_HOME:-~/.local/state}/archie/update`, outside
|
||||
the binary directory: `transaction/journal.json`, `transaction/previous/`, and
|
||||
`transaction/archied`, the frozen copy of the archied that wrote the journal. On
|
||||
daemon boot, an interrupted transaction is
|
||||
handed to that frozen watchdog with `-recover` before normal startup: a
|
||||
transaction that never started is discarded, one that was switching or observing
|
||||
is rolled back, and a decided one is finished. To recover manually, run
|
||||
daemon boot, archied hands an interrupted transaction to that frozen watchdog
|
||||
with `-recover` before normal startup. The watchdog discards a transaction that
|
||||
never started, rolls back one that was switching or observing, and finishes a
|
||||
decided one. To recover manually, run
|
||||
`transaction/archied update watchdog -recover -bin-dir ~/.local/bin` from that
|
||||
state directory. A failed recovery keeps the journal for another attempt.
|
||||
|
||||
|
||||
+13
-14
@@ -42,9 +42,9 @@ systemctl --user start archied
|
||||
|
||||
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`;
|
||||
`docker compose up -d postgres` provides the default server. Its two login
|
||||
roles are created once per database by `archie-state-store provision` -- see
|
||||
[Database roles](#database-roles).
|
||||
`docker compose up -d postgres` provides the default server.
|
||||
`archie-state-store provision` creates its two login roles once per database --
|
||||
see [Database roles](#database-roles).
|
||||
|
||||
The State Store service (`archie-state-store`) owns the task data in the
|
||||
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.
|
||||
|
||||
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 migration one. The command is idempotent, so re-running it after an upgrade
|
||||
reconciles objects a migration added.
|
||||
@@ -87,7 +87,7 @@ schema and serves, which is what an install that has not split the roles does.
|
||||
|
||||
## Running the dashboard
|
||||
|
||||
The dashboard is served by the standalone UI Service (`archie-ui`), not by
|
||||
The standalone UI Service (`archie-ui`) serves the dashboard, not
|
||||
`archied`.
|
||||
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
|
||||
@@ -99,17 +99,16 @@ archie-ui -config ~/.config/archie/config.toml
|
||||
|
||||
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.
|
||||
`archied` runs no dashboard listener at all, so webhook capture
|
||||
(`POST /webhooks/capture/{source}`) is received by archie-ui and the
|
||||
binding-dispatch loop in `archied` consumes what arrives from the shared
|
||||
State Store.
|
||||
`archied` runs no dashboard listener at all, so archie-ui receives webhook
|
||||
capture (`POST /webhooks/capture/{source}`) and the binding-dispatch loop in
|
||||
`archied` consumes what arrives from the shared State Store.
|
||||
|
||||
The dashboard speaks plain HTTP. A non-loopback bind therefore carries the
|
||||
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
|
||||
(a reverse proxy or the tunnel itself) and set
|
||||
`[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.
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
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
|
||||
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.
|
||||
The readiness probe is the single-writer check the runbook has against a
|
||||
degraded store: a `503` from `/health/detailed` means `archied` should be
|
||||
started only after the store is healthy.
|
||||
degraded store: a `503` from `/health/detailed` means the operator should
|
||||
start `archied` only after the store is healthy.
|
||||
@@ -31,6 +31,8 @@ services:
|
||||
- ./bin/archie:/archie/archie:ro
|
||||
- ./config.toml:/archie/config.toml:ro
|
||||
- ./extensions:/archie/extensions:ro
|
||||
- ./state:/archie/state
|
||||
- ./catalogue:/archie/catalogue:ro
|
||||
ports:
|
||||
- "${ARCHIE_BIND:?}:8080"
|
||||
networks: [internal]
|
||||
|
||||
@@ -14,7 +14,7 @@ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -C "$repo" -trimpath \
|
||||
-ldflags "-X github.com/samcharles93/archie-core/internal/buildinfo.Version=$version" \
|
||||
-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/seccomp.json" "$target:$dir/seccomp.json"
|
||||
scp -q "$here/initdb/01-roles.sh" "$target:$dir/initdb/01-roles.sh"
|
||||
@@ -51,6 +51,11 @@ if ! grep -q '^admin_token_sha256' config.toml; then
|
||||
sed -i "1i admin_token_sha256 = \"$hash\"" config.toml
|
||||
chown 65532:65532 config.toml
|
||||
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
|
||||
# never leaves the host; back it up, or credentials die with it.
|
||||
if ! grep -q '^age_identity' config.toml; then
|
||||
|
||||
@@ -31,6 +31,14 @@ listen = "127.0.0.1:8484"
|
||||
mode = "embedded"
|
||||
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
|
||||
# -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
|
||||
|
||||
@@ -58,3 +58,11 @@ models = [
|
||||
[budgets]
|
||||
max_steps = 60
|
||||
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
|
||||
@@ -11,7 +11,7 @@ This runbook describes how to manage `archied` as a background user service on L
|
||||
with the contents it
|
||||
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
|
||||
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
|
||||
`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`)
|
||||
|
||||
The Telegram, email and webhook channels are served by `archie-messaging`, not
|
||||
by `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
|
||||
`archie-messaging` serves the Telegram, email and webhook channels, not
|
||||
`archied`, since the v1.30.0 extraction. `archied` starts no gateway for them
|
||||
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
|
||||
healthy. `install.sh` writes this unit on a fresh install;
|
||||
`archied update install` refuses an
|
||||
update when a host is missing a unit and names what is missing, which now fires
|
||||
for a host that drifted or predates this release rather than the normal path.
|
||||
healthy. `install.sh` writes this unit on a fresh install.
|
||||
`archied update install` refuses an update when a host is missing a unit and
|
||||
names what is missing. That now fires for a host that drifted or predates this
|
||||
release rather than the normal path.
|
||||
|
||||
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]`.
|
||||
@@ -48,7 +48,7 @@ each service waits for the peers it needs.
|
||||
|
||||
## 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`.
|
||||
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.
|
||||
@@ -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
|
||||
`/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
|
||||
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
|
||||
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
|
||||
interactive chat keeps the host access the operator configured, while every
|
||||
autonomous repository workflow runs in a task-scoped Docker container. No
|
||||
Compose service or host `archie-agent` binary is required.
|
||||
autonomous repository workflow runs in a task-scoped Docker container. The
|
||||
deployment needs no Compose service or host `archie-agent` binary.
|
||||
|
||||
Docker must be installed and reachable by the service user. With no explicit
|
||||
broker or container settings, Archie defaults `containers.image` to
|
||||
`git.catlow.cloud/sam/archie-agent:latest`. `single-forge-github.toml` and
|
||||
`docker-nats-stack.toml` override that default with a pinned reference
|
||||
(`standalone.toml` and `dev.toml` leave it) -- see
|
||||
The operator must install Docker and make it reachable to the service user.
|
||||
`containers.image` has no default: with it unset the daemon refuses to start and
|
||||
names the key, so a fresh install learns about it at startup, not at the first
|
||||
failed pull.
|
||||
`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
|
||||
explicit equivalent, pinned the same way, is:
|
||||
explicit reference, pinned the same way, is:
|
||||
|
||||
```toml
|
||||
[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.
|
||||
|
||||
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
|
||||
`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`
|
||||
with no token is correct.
|
||||
|
||||
@@ -172,8 +174,8 @@ fall back to a host model loop.
|
||||
The release pipeline publishes
|
||||
`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
|
||||
for the agent image, and `:latest` moves only when a release is promoted. A
|
||||
distribution zip pins the image its own release
|
||||
for the agent image, and `:latest` moves only when the release pipeline promotes
|
||||
a release. A distribution zip pins the image its own release
|
||||
published, by digest, in `release.json`, and `archied update install` pulls
|
||||
exactly that.
|
||||
|
||||
@@ -203,8 +205,9 @@ personal access token that can read the package as the password --
|
||||
`{"username":"<user>","password":"<token>"}`. Put it in
|
||||
`~/.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
|
||||
effect on restart; a value that cannot be read logs a warning and pulls
|
||||
anonymously, which is the failure the task reports as a capability error.
|
||||
effect on restart. When the daemon cannot read a value, it logs a warning
|
||||
and pulls anonymously, which is the failure the task reports as a capability
|
||||
error.
|
||||
|
||||
The bundled update adapter snapshots the configured `[containers].image` before
|
||||
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
|
||||
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
|
||||
Compose, and set `NATS_TOKEN` to the same value in both.
|
||||
|
||||
|
||||
+3
-2
@@ -44,6 +44,7 @@ services:
|
||||
|
||||
# ── NATS JetStream ────────────────────────────────────────────────
|
||||
nats:
|
||||
profiles: ["nats"]
|
||||
image: nats:2.14-alpine3.22
|
||||
# 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
|
||||
@@ -51,8 +52,8 @@ services:
|
||||
# the account nkey seed named in [nats] callout_issuer_seed_env.
|
||||
command: ["-c", "/etc/nats/nats.conf"]
|
||||
environment:
|
||||
NATS_TOKEN: ${NATS_TOKEN:?NATS_TOKEN is required}
|
||||
NATS_CALLOUT_ISSUER: ${NATS_CALLOUT_ISSUER:?NATS_CALLOUT_ISSUER is required}
|
||||
- NATS_TOKEN
|
||||
- NATS_CALLOUT_ISSUER
|
||||
ports:
|
||||
- "4222:4222" # client
|
||||
- "127.0.0.1:8222:8222" # monitoring (http://localhost:8222)
|
||||
|
||||
@@ -24,9 +24,9 @@ Archie Core uses the GitHub API to:
|
||||
|
||||
## 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).
|
||||
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).
|
||||
4. Choose an **Expiration** (e.g. 90 days, 1 year, or No expiration for
|
||||
dedicated bot accounts).
|
||||
@@ -35,9 +35,9 @@ Archie Core uses the GitHub API to:
|
||||
commenting, pushing branches, and opening PRs).
|
||||
- **`workflow`** (Optional — required if Archie needs to update GitHub
|
||||
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
|
||||
see it again!
|
||||
see it again.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# Building your first playbook binding
|
||||
|
||||
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
|
||||
This walks through the whole no-code path the event-capture epic promises. Point
|
||||
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
|
||||
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
|
||||
|
||||
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. 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
|
||||
|
||||
Open **Field mappings** (`/mappings`) → **New mapping**. Pick your captured
|
||||
event from the dropdown, then click through its payload tree on the right --
|
||||
every key and value is clickable. Clicking a value binds it as a field (name,
|
||||
event from the dropdown, then select items in its payload tree on the right.
|
||||
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
|
||||
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
|
||||
@@ -56,9 +56,9 @@ Save. The binding starts in **draft** -- nothing fires yet.
|
||||
## 5. Approve it
|
||||
|
||||
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
|
||||
should self-arm. Click **Approve**. Status becomes **armed**.
|
||||
should self-arm. Select **Approve**. Status becomes **armed**.
|
||||
|
||||
## 6. Fire it for real
|
||||
|
||||
@@ -76,14 +76,15 @@ curl -X POST http://localhost:8484/webhooks/capture/sentry \
|
||||
-d "$BODY"
|
||||
```
|
||||
|
||||
This event is captured as **authenticated**, matched against your armed binding,
|
||||
and dispatched into a new task through the exact same gate/worktree/sandbox
|
||||
pipeline every other task goes through. Check the **Tasks** page; a new task
|
||||
should appear, its body built from the fields your mapping resolved.
|
||||
Archie captures this event as **authenticated**, matches it against your armed
|
||||
binding, and dispatches it into a new task through the exact same
|
||||
gate/worktree/sandbox pipeline every other task goes through. Check the
|
||||
**Tasks** page; a new task should appear, its body built from the fields your
|
||||
mapping resolved.
|
||||
|
||||
## Editing a live binding
|
||||
|
||||
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
|
||||
be re-approved. When editing, leave the **Shared secret** field blank to keep
|
||||
Any edit to an armed binding, even a typo fix, drops it back to
|
||||
**`pending_approval`** automatically. You can't bypass this by editing; you have
|
||||
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.
|
||||
@@ -1,24 +1,26 @@
|
||||
# Self-development loop: archie develops its own codebase
|
||||
|
||||
**Status:** Decided, not yet built (2026-11-03, sam) **Scope:** how archie
|
||||
persistently takes on development of archie-core itself. This file records a
|
||||
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
|
||||
keeps developing archie-core itself. This file records a
|
||||
desired state, not an implementation or a product. Nothing below exists unless
|
||||
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
|
||||
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
|
||||
only where it is enforced (the gate, access control, the daemon's git monopoly)
|
||||
and stated in `AGENTS.md`; everywhere else this file is a pointer.
|
||||
on it. Where they disagree, the code wins. The boundary below is load-bearing
|
||||
only where the code enforces it (the gate, access control, the daemon's git
|
||||
monopoly) and only where `AGENTS.md` states it. Everywhere else this file is a
|
||||
pointer.
|
||||
|
||||
## Built today
|
||||
|
||||
The machinery the loop will reuse exists: shipped triage/implement/pr-review
|
||||
workflows, the adversarial self-review stage before a PR opens (epic #1348,
|
||||
closed), the prbench judge for review quality with its acceptance bar, canary
|
||||
releases judged on the installed release (releaseupdate), and the curator
|
||||
engine. What does not exist is the loop itself: no self-intake curator, no
|
||||
approved-issue auto-run, no judge for diffs, no outcome distillation, no canary
|
||||
routing specific to self-directed changes.
|
||||
The machinery the loop will reuse exists. It includes the shipped
|
||||
triage/implement/pr-review workflows and the adversarial self-review stage before
|
||||
a PR opens (epic #1348, closed). It also includes the prbench judge for review
|
||||
quality with its acceptance bar, canary releases judged on the installed release
|
||||
(releaseupdate), and the curator engine. What does not exist is the loop itself:
|
||||
no self-intake curator, no automatic run for approved issues, no judge for
|
||||
diffs, no outcome distillation, no canary routing specific to self-directed
|
||||
changes.
|
||||
|
||||
## 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.
|
||||
Archie files its own work; the maintainer approves priority.
|
||||
2. **Approved-issue loop** (#1771): an approved issue runs the shipped
|
||||
triage/implement workflows end to end — read-only plan, gated build,
|
||||
adversarial self-review, daemon commits and opens a green PR. The maintainer
|
||||
still merges at this stage.
|
||||
triage/implement workflows end to end. The workflow makes a read-only plan
|
||||
and a gated build, then runs the adversarial self-review; the daemon commits
|
||||
and opens a green PR. The maintainer still merges at this stage.
|
||||
3. **Implementation judge** (#1772): the prbench judge pattern scores diffs,
|
||||
calibrated against the maintainer's merge decisions; auto-merge applies only
|
||||
when the gate is green, the review stage is clean, and the judge is above the
|
||||
calibrated bar.
|
||||
calibrated against the maintainer's merge decisions. Automatic merge applies
|
||||
only when the gate is green, the review stage is clean, and the judge is above
|
||||
the calibrated bar.
|
||||
4. **Outcome distillation** (#1773): a curator turns merged-run postmortems into
|
||||
proposals for the repo's agent instructions, each added only because it
|
||||
changes a decision; rules that stop changing decisions are removed.
|
||||
proposals for the repo's agent instructions. The maintainer adds each
|
||||
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
|
||||
window and are judged on the installed release before promotion. Rollback is
|
||||
a plain revert, because every self-directed change is one gated commit.
|
||||
window, and the canary verdict on the installed release gates their
|
||||
promotion. Rollback is a plain revert, because every self-directed change is
|
||||
one gated commit.
|
||||
|
||||
## Boundary
|
||||
|
||||
Enforcement lives in the harness, never in the prompt (#1775). Changes to the
|
||||
commit gate, the invariants in `AGENTS.md`, access control and grant scoping,
|
||||
the daemon-only git path, and webhook HMAC verification may be proposed by
|
||||
archie but are never merged by archie — they require a maintainer merge.
|
||||
Everything else (workflows, curators, memory, docs, the dashboard) is fair game
|
||||
for the loop.
|
||||
Enforcement lives in the code, never in the prompt (#1775). Archie may propose
|
||||
changes to the commit gate, the invariants in `AGENTS.md`, access control and
|
||||
grant scoping, the daemon-only git path, and webhook HMAC verification. It never
|
||||
merges them; those changes require a maintainer merge. Everything else
|
||||
(workflows, curators, memory, docs, the dashboard) is fair game for the loop.
|
||||
|
||||
## Why
|
||||
|
||||
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
|
||||
prompt can. Keeping quality measurable — a judge bar and a canary verdict as
|
||||
numbers, tests guarding the protected seams — is what lets the loop widen
|
||||
without turning the codebase to garbage.
|
||||
The model can argue with a prompt, not with gates, scoped grants or the daemon's
|
||||
monopoly on git. Keeping quality measurable is what lets the loop widen without
|
||||
turning the codebase to garbage: a judge bar and a canary verdict as numbers,
|
||||
and tests guarding the protected seams.
|
||||
|
||||
## 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.
|
||||
- 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
|
||||
them, and `AGENTS.md` stays short enough to read in full every session.
|
||||
@@ -1,31 +1,31 @@
|
||||
# User authorization boundaries
|
||||
# User authorisation boundaries
|
||||
|
||||
Archie separates authentication (which person or service is calling) from
|
||||
permission to act on a resource. This inventory follows the
|
||||
[OWASP Authentication Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html)
|
||||
and
|
||||
[Authorization Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html),
|
||||
including its guidance on attributes and relationships. It describes concrete
|
||||
enforcement points and their regression tests; it is not a compliance
|
||||
certification.
|
||||
[Authorization Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html).
|
||||
It includes the guidance on attributes and relationships from the Authorization
|
||||
Cheat Sheet. It describes concrete enforcement points and their regression
|
||||
tests. It is not a compliance certification.
|
||||
|
||||
## Transport and authority
|
||||
|
||||
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
|
||||
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.
|
||||
|
||||
Instance service credentials are administrative authority. They are not user
|
||||
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
|
||||
authenticated service and enforce their own resource scope. The public HTTP
|
||||
boundary evaluates Cedar before invoking them. Task credentials have a separate,
|
||||
explicit RPC allowlist and cannot call account or identity administration.
|
||||
|
||||
Local service listeners are trusted process boundaries. Loopback is not a
|
||||
substitute for authentication on a remotely reachable listener. OIDC
|
||||
The services treat local service listeners as trusted process boundaries.
|
||||
Loopback does not replace authentication on a remotely reachable listener. OIDC
|
||||
credentials, local browser sessions, personal API tokens, service credentials,
|
||||
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/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
|
||||
fail closed.
|
||||
|
||||
The default policies grant actions through scoped roles. Policies can also
|
||||
restrict a named identity, workspace environment, owner, state, source address,
|
||||
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
|
||||
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
|
||||
history, passkeys, recovery codes and personal tokens are bound to the person.
|
||||
An organization or instance admin role does not override those relationships.
|
||||
Account creation uses `manage_members` policy rather than a hard-coded admin
|
||||
role. Authenticating through OIDC does not automatically grant membership, link
|
||||
Cedar permission is not ownership of another person's private data. The services
|
||||
bind conversation history, passkeys, recovery codes and personal tokens to the
|
||||
person. An organisation or instance admin role does not override those
|
||||
relationships. Account creation uses `manage_members` policy rather than a fixed
|
||||
admin role. An OIDC login does not automatically grant membership, link
|
||||
accounts by unverified email, or create an administrator.
|
||||
|
||||
## Enforcement inventory
|
||||
|
||||
| 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` |
|
||||
| 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 |
|
||||
| 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` |
|
||||
| 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; 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 |
|
||||
| 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` |
|
||||
| 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 |
|
||||
| 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 |
|
||||
| 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` |
|
||||
| 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 questions/approvals: `webui/api_chat_ask.go` | Waiting question is bound 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 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` | 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 |
|
||||
| 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` |
|
||||
| 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` |
|
||||
@@ -86,29 +86,31 @@ accounts by unverified email, or create an administrator.
|
||||
|
||||
The policy HTTP matrix enumerates each registered protected route. It checks
|
||||
both anonymous refusal and refusal by an explicit Cedar forbid, using the real
|
||||
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.
|
||||
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.
|
||||
|
||||
## Public and personal routes
|
||||
|
||||
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/passkey/begin`, `POST /api/auth/passkey/finish`,
|
||||
`GET /oauth2/login`, `GET /oauth2/callback`, health probes and signed webhook
|
||||
intake. Each has its own protocol checks. Static embedded app assets are public;
|
||||
they do not contain user data. `/health/detailed` remains protected.
|
||||
`POST /api/auth/passkey/begin` and `POST /api/auth/passkey/finish`. The
|
||||
remaining entry points are `GET /oauth2/login`, `GET /oauth2/callback`, health
|
||||
probes and signed webhook intake. Each has its own protocol checks. Static
|
||||
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
|
||||
server-derived ownership: password change, recovery-secret generation, passkey
|
||||
begin/finish/list/delete. They do not require an organization administrator
|
||||
role. `POST /api/accounts` and `/api/authentication` are administrative policy
|
||||
routes.
|
||||
server-derived ownership. They cover password change, recovery-secret
|
||||
generation, and passkey begin/finish/list/delete. They do not require an
|
||||
organisation administrator role. `POST /api/accounts` and `/api/authentication`
|
||||
are administrative policy routes.
|
||||
|
||||
## HTTP route inventory
|
||||
|
||||
The following routes are covered by `TestHTTPPolicyCannotBeBypassed` in
|
||||
`internal/webui/authorization_surfaces_test.go`. `authorize.go` maps each to its
|
||||
action/resource; the handler may impose a stricter record or instance boundary.
|
||||
The test `TestHTTPPolicyCannotBeBypassed` covers the following routes. It lives
|
||||
in `internal/webui/authorization_surfaces_test.go`. `authorize.go` maps each to
|
||||
its action/resource. The handler may impose a stricter record or instance
|
||||
boundary.
|
||||
|
||||
| Method | Route example |
|
||||
| ------ | ----------------------------------------------------- |
|
||||
@@ -226,21 +228,23 @@ action/resource; the handler may impose a stricter record or instance boundary.
|
||||
|
||||
## Verification limits
|
||||
|
||||
A synthetic browser authenticator verifies protocol behavior, not a physical
|
||||
security key or every operating system. An OIDC unit test is not acceptance
|
||||
against a deployed provider. Disposable PostgreSQL smoke checks verify real SQL
|
||||
without putting database-dependent tests in the fast unit suite.
|
||||
A synthetic browser authenticator checks protocol behaviour. It does not test a
|
||||
physical security key or every operating system. An OIDC unit test is not
|
||||
acceptance against a deployed provider. Disposable PostgreSQL smoke checks
|
||||
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
|
||||
new person. Existing service credentials remain privileged; this inventory does
|
||||
not claim that all internal gRPC methods have independent Cedar gates.
|
||||
The Gateway retains existing anonymous conversations but does not silently
|
||||
assign them to a new person. Existing service credentials remain privileged.
|
||||
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
|
||||
allow/deny behavior cases. Include another user in the same organization, a
|
||||
caller in another organization, a missing principal, unavailable policy storage,
|
||||
allow/deny behaviour cases. Include another user in the same organisation, a
|
||||
caller in another organisation, a missing principal, unavailable policy storage,
|
||||
and the applicable owner/workspace/instance restrictions.
|
||||
|
||||
Bootstrap is unauthenticated until the first administrator is created. Complete
|
||||
setup before exposing a new installation to untrusted users. Last-active-owner
|
||||
protection for identity suspension/retirement is tracked separately as
|
||||
`archie-core-d7avc`; membership-policy guards are not that lifecycle guard.
|
||||
Bootstrap runs without authentication until the operator creates the first
|
||||
administrator account. Complete setup before exposing a new installation to
|
||||
untrusted users. A separate issue, `archie-core-d7avc`, tracks
|
||||
last-active-owner protection for identity suspension/retirement.
|
||||
Membership-policy guards are not that lifecycle guard.
|
||||
+39
-18
@@ -45,9 +45,30 @@ 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
|
||||
install chromium`. The cloud environment ships Chromium and Playwright
|
||||
preinstalled; run with `NODE_PATH=$(pnpm root -g)`.
|
||||
|
||||
## Single-binary smoke check
|
||||
|
||||
Point this check at an already running, disposable `archie` instance with its
|
||||
own PostgreSQL database and no external delivery connectors. Set
|
||||
`ARCHIE_SMOKE_TOKEN` to that instance's bootstrap token and
|
||||
`ARCHIE_SMOKE_URL` to its IPv4 loopback URL (for example
|
||||
`http://127.0.0.1:8080`), then run:
|
||||
|
||||
```bash
|
||||
node e2e/archie-smoke.cjs
|
||||
```
|
||||
|
||||
The check saves a workflow and a one-minute schedule, then verifies that its
|
||||
run links back to the schedule event and appears in the composer. It disables
|
||||
the schedule after the check but leaves records for inspection. The check needs
|
||||
no model or forge. The legacy `task e2e:up` stack is not the target of this check.
|
||||
If Archie is running in WSL and its loopback URL is not reachable from
|
||||
Windows, run the check with Node in the same Linux environment as Archie.
|
||||
If the schedule starts but the run does not finish, check the `events` and
|
||||
`runs` logs; readiness alone does not verify that either worker can claim work.
|
||||
|
||||
## Release evidence
|
||||
|
||||
```bash
|
||||
@@ -64,53 +85,53 @@ A module in `checks/` exports `async ({ page, go, shot, fail, skip, settled, att
|
||||
- `go(path)` loads a dashboard route: `waitUntil: 'load'` plus 1200ms.
|
||||
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,
|
||||
and records `{file, w, h, check}` in the manifest. The label becomes a slug,
|
||||
so `shot('/')` becomes `routes-home.png`; a viewport other than the
|
||||
1440x900 default adds a suffix (`-390x844`). Repeated labels get `-2`,
|
||||
`-3`, so every capture is kept.
|
||||
`-3`, so the test runner keeps every capture.
|
||||
- `fail(msg)` records a problem without stopping.
|
||||
- `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.
|
||||
- `tolerate(re)` ignores console errors matching `re`, for a response the page survives by design.
|
||||
- `attach(name, data)` saves a non-image artifact as `<check>-<name>`.
|
||||
- `settled(sel?)` waits for a selector or URL, then settles briefly.
|
||||
It is the harness-owned wait; checks need no capture wrapper or
|
||||
It is the test runner's wait; checks need no capture wrapper or
|
||||
ad-hoc sleeps around screenshots.
|
||||
|
||||
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).
|
||||
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), and
|
||||
`workflow-*` for the canvas (loading, validation, phone-layout, logic).
|
||||
`chat-composer` covers chat input, and `chat-dock-*` covers 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
|
||||
`routes` visits `/logs` but the whitespace lint skips it: 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)`
|
||||
plus `skipped`/`skipReason` for skips) and `report.html`. The report is 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
|
||||
2 when the test runner 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 |
|
||||
| State Store exits: server is older than PostgreSQL 18 | another server answered | `stack.sh` uses port 55432; set `ARCHIE_DEV_PGPORT` if another process holds that port |
|
||||
| Startup says a port is in use | a stack or another process already owns it | Run `task e2e:down`, then `task e2e:up`; inspect any remaining listener with `ss -ltnp` |
|
||||
| Your own shell is killed (exit 144) | `pkill -f` matched its own command line | `stack.sh stop` or `restart`, which kill by PID |
|
||||
| `pkill -f` kills your own shell (exit 144) | `pkill -f` matched its own command line | `stack.sh stop` or `restart`, which kill by PID |
|
||||
| Postgres aborts in the cloud | `/tmp/claude-0` is reset to mode 700 | `stack.sh` keeps the root cluster in `/var/lib/archie-dev` |
|
||||
@@ -0,0 +1,75 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const { randomUUID } = require("node:crypto");
|
||||
const { setTimeout: delay } = require("node:timers/promises");
|
||||
|
||||
async function main() {
|
||||
assert.ok(process.env.ARCHIE_SMOKE_URL, "Set ARCHIE_SMOKE_URL to a disposable Archie stack");
|
||||
const origin = new URL(process.env.ARCHIE_SMOKE_URL);
|
||||
const token = process.env.ARCHIE_SMOKE_TOKEN;
|
||||
assert.equal(origin.protocol, "http:");
|
||||
assert.equal(origin.hostname, "127.0.0.1", "Use a disposable Archie stack on IPv4 loopback");
|
||||
assert.ok(token, "Set ARCHIE_SMOKE_TOKEN to the disposable stack's admin token");
|
||||
|
||||
async function request(path, { method = "GET", body, authenticated = true, status = 200 } = {}) {
|
||||
const response = await fetch(new URL(path, origin), {
|
||||
method,
|
||||
redirect: "error",
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
headers: {
|
||||
...(authenticated && { Authorization: `Bearer ${token}` }),
|
||||
...(body !== undefined && { "Content-Type": "application/json" }),
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
}).catch((err) => {
|
||||
throw new Error(`${method} ${path}: could not reach Archie at ${origin.origin}: ${err.cause?.message || err.message}`, { cause: err });
|
||||
});
|
||||
assert.equal(response.status, status, `${method} ${path}: expected HTTP ${status}, got ${response.status}`);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
const ready = await request("/readyz", { authenticated: false });
|
||||
assert.equal(ready.ready, true, "Archie is not ready");
|
||||
await request("/api/workflows", { authenticated: false, status: 401 });
|
||||
|
||||
const name = `smoke-${randomUUID()}`;
|
||||
const saved = await request("/api/workflows", {
|
||||
method: "POST",
|
||||
status: 201,
|
||||
body: { name, body: `repository: none\nsteps:\n - id: notify\n type: run.notify\n settings: {title: ${name}}\n` },
|
||||
});
|
||||
const trigger = { name, workflow_id: saved.id, every: "1m" };
|
||||
const created = await request("/api/triggers", { method: "POST", body: trigger, status: 201 });
|
||||
try {
|
||||
const deadline = Date.now() + 90_000;
|
||||
let last = "no scheduled run";
|
||||
while (Date.now() < deadline) {
|
||||
const recent = await request("/api/runs");
|
||||
const run = recent.find((row) => row.workflow_id === saved.id);
|
||||
if (run) {
|
||||
last = `run ${run.id}: ${run.state}`;
|
||||
assert.ok(!["failed", "cancelled"].includes(run.state), `${last}: ${run.error || "no error returned"}`);
|
||||
if (run.state === "succeeded") {
|
||||
const trail = await request(`/api/runs/${run.id}`);
|
||||
assert.equal(trail.run.workflow_version, saved.version, "Run used the wrong workflow version");
|
||||
assert.equal(trail.origin?.trigger_id, created.id, "Run trail is missing the schedule trigger");
|
||||
assert.ok(trail.origin?.event_id, "Run trail is missing the originating event");
|
||||
assert.equal(trail.origin.declared_event_type, "schedule.tick");
|
||||
const messages = await request("/api/composer/messages");
|
||||
assert.equal(messages.filter((m) => m.run_id === run.id && m.title === name).length, 1,
|
||||
"Expected one composer notification linked to the run");
|
||||
console.log(`Schedule, run trail and composer notification verified for ${run.id}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
await delay(1_000);
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${name}: ${last}`);
|
||||
} finally {
|
||||
await request(`/api/triggers/${created.id}`, { method: "PUT", body: { ...trigger, disabled: true } });
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err.message);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -17,7 +17,7 @@ module.exports = async ({ page, go, shot, settled, tolerate }) => {
|
||||
await page.keyboard.press('Escape');
|
||||
return names;
|
||||
})();
|
||||
assert.deepEqual(offered.sort(), ['Beta', 'E2E'], 'selector must offer exactly the orgs the caller belongs to');
|
||||
assert.deepEqual(offered.sort(), ['Beta', 'System'], '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');
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ py() { python3 -c "import sys, json; d = json.load(sys.stdin); print($1)"; }
|
||||
# This account belongs only to the isolated local test stack.
|
||||
email=${ARCHIE_E2E_EMAIL:-operator@example.test}
|
||||
password=${ARCHIE_E2E_PASSWORD:-archie-local-e2e-password}
|
||||
account=$(python3 -c 'import json,sys; print(json.dumps(dict(email=sys.argv[1], password=sys.argv[2], display_name="E2E operator", organisation_name="E2E", workspace_name="Local test", public_url=sys.argv[3])))' "$email" "$password" "${ARCHIE_E2E_URL:-http://localhost:5173}")
|
||||
account=$(python3 -c 'import json,sys; print(json.dumps(dict(email=sys.argv[1], password=sys.argv[2], display_name="E2E operator", public_url=sys.argv[3])))' "$email" "$password" "${ARCHIE_E2E_URL:-http://localhost:5173}")
|
||||
if [ "$(get /api/auth/status | py 'd["setup_required"]')" = "True" ]; then
|
||||
post /api/auth/setup "$account" >/dev/null
|
||||
else
|
||||
|
||||
@@ -13,7 +13,6 @@ require (
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/cloudflare/circl v1.6.5 // indirect
|
||||
github.com/containerd/errdefs/pkg v0.3.0 // indirect
|
||||
github.com/danielgtaylor/huma/v2 v2.40.0 // indirect
|
||||
github.com/distribution/reference v0.6.0 // indirect
|
||||
github.com/docker/go-connections v0.8.2 // indirect
|
||||
github.com/docker/go-units v0.5.0 // indirect
|
||||
@@ -72,6 +71,7 @@ require (
|
||||
github.com/cedar-policy/cedar-go v1.9.1
|
||||
github.com/containerd/errdefs v1.0.0
|
||||
github.com/coreos/go-oidc/v3 v3.21.0
|
||||
github.com/danielgtaylor/huma/v2 v2.40.0
|
||||
github.com/go-git/go-billy/v6 v6.0.0-beta.1
|
||||
github.com/go-git/go-git/v6 v6.0.0-beta.1
|
||||
github.com/go-jose/go-jose/v4 v4.1.9
|
||||
|
||||
@@ -70,6 +70,8 @@ github.com/fxamacker/cbor/v2 v2.10.0 h1:HVF3T5vYwLqO81ebPirWEPNv2SMrUMD3HLnKgEr6
|
||||
github.com/fxamacker/cbor/v2 v2.10.0/go.mod h1:uSwlToFuT9BZAKRxxVm3qQC8DR4tlWl7D6pf20iRYH4=
|
||||
github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
|
||||
github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU=
|
||||
github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg=
|
||||
github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM=
|
||||
github.com/go-git/gcfg/v2 v2.0.2 h1:MY5SIIfTGGEMhdA7d7JePuVVxtKL7Hp+ApGDJAJ7dpo=
|
||||
github.com/go-git/gcfg/v2 v2.0.2/go.mod h1:/lv2NsxvhepuMrldsFilrgct6pxzpGdSRC13ydTLSLs=
|
||||
github.com/go-git/go-billy/v6 v6.0.0-beta.1 h1:OJ4r207zcEbeq/DJNajQUOMd+pph3r9A7hRq1Sjl1bA=
|
||||
|
||||
@@ -30,14 +30,6 @@ func ClipToolCallDetail(s string) string {
|
||||
return s[:cut] + "…"
|
||||
}
|
||||
|
||||
func ProjectScopedRules(workspace, extra string) string {
|
||||
rule := "Confine discovery to " + workspace + ". Do not inspect home directories, dependency/module caches, or unrelated projects unless the mission explicitly requests that external path."
|
||||
if strings.TrimSpace(extra) == "" {
|
||||
return rule
|
||||
}
|
||||
return rule + "\n" + extra
|
||||
}
|
||||
|
||||
func ProtectionMatcher(p agentrun.Protection, readOnly bool) func(string) bool {
|
||||
if readOnly || len(p.Suffixes)+len(p.Globs) == 0 {
|
||||
return nil
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/domain/agentrun"
|
||||
"github.com/samcharles93/archie-core/internal/prompts"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
@@ -91,7 +92,7 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req agentrun.Req
|
||||
|
||||
MaxParallelToolCalls: MaxParallelToolCalls,
|
||||
Mission: missionWithHistory(req),
|
||||
ExtraRules: agentexec.ProjectScopedRules(workspace, req.ExtraRules),
|
||||
ExtraRules: prompts.ProjectScopedRules(workspace, req.ExtraRules),
|
||||
Notes: notes,
|
||||
Gate: toAgentGate(req.Gate),
|
||||
Preflight: toAgentCommands(req.Preflight),
|
||||
|
||||
@@ -42,7 +42,7 @@ func SamplingMessages(req protocol.SamplingRequest) ([]chat.Message, error) {
|
||||
|
||||
// SamplingMaxTokens returns the request's maxTokens or the default, capped at
|
||||
// the model's ceiling. The ai-sdk runtime picks max_completion_tokens or
|
||||
// max_tokens from the model's catalog metadata, so there is no reasoning
|
||||
// max_tokens from the model's catalogue metadata, so there is no reasoning
|
||||
// branch here.
|
||||
func SamplingMaxTokens(requested, modelCeiling int) int {
|
||||
maxTokens := requested
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package archie
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
)
|
||||
|
||||
// operator authenticates every request as an instance administrator.
|
||||
type operator struct{}
|
||||
|
||||
func (operator) Authenticate(ctx context.Context, _ *http.Request) (context.Context, bool, error) {
|
||||
return ctx, true, nil
|
||||
}
|
||||
|
||||
// refuses answers every Allow with err and records what it was asked.
|
||||
type refuses struct {
|
||||
err error
|
||||
asked []string
|
||||
}
|
||||
|
||||
func (r *refuses) Allow(_ context.Context, action, kind string) error {
|
||||
r.asked = append(r.asked, action+" "+kind)
|
||||
return r.err
|
||||
}
|
||||
|
||||
// publicOperations are the only operations a caller reaches without a
|
||||
// credential: sign-in, setup and the auth status the sign-in page reads.
|
||||
var publicOperations = []string{
|
||||
"begin-oidc-sign-in", "begin-passkey-sign-in", "finish-oidc-sign-in", "finish-passkey-sign-in",
|
||||
"get-auth-status", "recover-account", "set-up-account", "sign-in", "sign-out",
|
||||
}
|
||||
|
||||
var pathParam = regexp.MustCompile(`\{[^}]+\}`)
|
||||
|
||||
// TestEveryOperationIsAuthorized guards deny-by-default across every module's
|
||||
// routes. Each registered operation is either one of the named public
|
||||
// operations or declares a valid action and resource kind, and a request that
|
||||
// fails the grant, or that cannot be decided, is refused before its handler
|
||||
// runs. The handlers here have nothing behind them, so one that ran would
|
||||
// panic.
|
||||
func TestEveryOperationIsAuthorized(t *testing.T) {
|
||||
probe := &refuses{err: httpapi.ErrDenied}
|
||||
mux, api := emptyAPI(operator{}, probe)
|
||||
routes := httpapi.Routes(api)
|
||||
if len(routes) < 100 {
|
||||
t.Fatalf("only %d operations registered", len(routes))
|
||||
}
|
||||
|
||||
var public []string
|
||||
for _, route := range routes {
|
||||
if route.Access.IsPublic() {
|
||||
public = append(public, route.ID)
|
||||
continue
|
||||
}
|
||||
action, kind, ok := route.Access.Declared()
|
||||
if !ok {
|
||||
t.Errorf("%s declares no access", route.ID)
|
||||
continue
|
||||
}
|
||||
if err := governance.Action(action).Validate(); err != nil || kind == "" {
|
||||
t.Errorf("%s declares %q on %q", route.ID, action, kind)
|
||||
}
|
||||
}
|
||||
slices.Sort(public)
|
||||
if !slices.Equal(public, publicOperations) {
|
||||
t.Errorf("public operations = %v, want %v", public, publicOperations)
|
||||
}
|
||||
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
err error
|
||||
want int
|
||||
}{
|
||||
{"a failing grant", httpapi.ErrDenied, http.StatusForbidden},
|
||||
{"an unavailable policy chain", httpapi.ErrUnavailable, http.StatusServiceUnavailable},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
for _, route := range routes {
|
||||
action, kind, ok := route.Access.Declared()
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
probe.err, probe.asked = tt.err, nil
|
||||
req := httptest.NewRequestWithContext(t.Context(), route.Method, pathParam.ReplaceAllString(route.Path, "x"), nil)
|
||||
rec := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec, req)
|
||||
if rec.Code != tt.want {
|
||||
t.Errorf("%s: status = %d, want %d", route.ID, rec.Code, tt.want)
|
||||
}
|
||||
if want := []string{action + " " + kind}; !slices.Equal(probe.asked, want) {
|
||||
t.Errorf("%s: decided on %v, want %v", route.ID, probe.asked, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnwiredAuthorizerRefuses guards the boot order: until the policy chain
|
||||
// is wired, an authorised operation is refused rather than let through.
|
||||
func TestUnwiredAuthorizerRefuses(t *testing.T) {
|
||||
settings := &governance.Module{}
|
||||
if err := settings.Allow(governance.WithPrincipal(t.Context(), governance.SharedTokenOwner()), "read", "run"); !errors.Is(err, httpapi.ErrUnavailable) {
|
||||
t.Fatalf("Allow with no chain = %v, want %v", err, httpapi.ErrUnavailable)
|
||||
}
|
||||
}
|
||||
+48
-21
@@ -7,56 +7,83 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/buildinfo"
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/internal/platform/hub"
|
||||
"github.com/samcharles93/archie-core/modules/approvals"
|
||||
"github.com/samcharles93/archie-core/modules/chat"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/dashboard"
|
||||
"github.com/samcharles93/archie-core/modules/deliveries"
|
||||
"github.com/samcharles93/archie-core/modules/drafts"
|
||||
"github.com/samcharles93/archie-core/modules/events"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/judgement"
|
||||
"github.com/samcharles93/archie-core/modules/memory"
|
||||
"github.com/samcharles93/archie-core/modules/proposals"
|
||||
"github.com/samcharles93/archie-core/modules/runs"
|
||||
"github.com/samcharles93/archie-core/modules/system"
|
||||
)
|
||||
|
||||
// apiModules are the modules that serve the HTTP API.
|
||||
type apiModules struct {
|
||||
settings *governance.Module
|
||||
conns *connectors.Module
|
||||
system *system.Module
|
||||
tell *deliveries.Module
|
||||
allow *approvals.Module
|
||||
classes *judgement.Classes
|
||||
policies *judgement.Policies
|
||||
hear *events.Module
|
||||
judge *judgement.Module
|
||||
engine *runs.Engine
|
||||
drafts *drafts.Module
|
||||
settings *governance.Module
|
||||
conns *connectors.Module
|
||||
system *system.Module
|
||||
tell *deliveries.Module
|
||||
allow *approvals.Module
|
||||
actionTypes *judgement.ActionTypes
|
||||
policies *judgement.Policies
|
||||
hear *events.Module
|
||||
judge *judgement.Module
|
||||
engine *runs.Engine
|
||||
chat *chat.Module
|
||||
proposals *proposals.Module
|
||||
notes *memory.Module
|
||||
live *hub.Hub
|
||||
}
|
||||
|
||||
func (m apiModules) register(api huma.API) {
|
||||
m.settings.Register(api)
|
||||
m.settings.RegisterAccounts(api)
|
||||
m.settings.RegisterOrganisations(api)
|
||||
m.settings.RegisterAccess(api)
|
||||
m.conns.Register(api)
|
||||
m.system.Register(api)
|
||||
m.tell.Register(api)
|
||||
m.allow.Register(api)
|
||||
m.classes.Register(api, m.allow)
|
||||
m.actionTypes.Register(api, m.allow)
|
||||
m.policies.Register(api)
|
||||
m.hear.Register(api)
|
||||
m.judge.Register(api)
|
||||
m.engine.Register(api, orgID, m.hear, m.judge, m.allow)
|
||||
m.drafts.Register(api)
|
||||
m.proposals.Register(api)
|
||||
m.chat.Register(api)
|
||||
// The memory routes are served once the root wires the module, which it
|
||||
// does after the modules that read it are built.
|
||||
if m.notes != nil {
|
||||
m.notes.Register(api)
|
||||
}
|
||||
dashboard.Register(api, m.live)
|
||||
}
|
||||
|
||||
// Document returns the API's OpenAPI document as YAML. It makes the same
|
||||
// registrations the server does, on modules with nothing behind them, so it
|
||||
// needs no database.
|
||||
func Document() ([]byte, error) {
|
||||
api := httpapi.New(http.NewServeMux(), buildinfo.Version, "")
|
||||
apiModules{
|
||||
settings: &governance.Module{}, conns: &connectors.Module{}, system: &system.Module{},
|
||||
tell: &deliveries.Module{}, allow: &approvals.Module{}, classes: &judgement.Classes{},
|
||||
policies: &judgement.Policies{}, hear: &events.Module{}, judge: &judgement.Module{},
|
||||
engine: &runs.Engine{}, drafts: &drafts.Module{},
|
||||
}.register(api)
|
||||
settings := &governance.Module{}
|
||||
_, api := emptyAPI(settings.Authenticator(""), settings)
|
||||
return api.OpenAPI().YAML()
|
||||
}
|
||||
|
||||
// emptyAPI registers every route on modules with nothing behind them.
|
||||
func emptyAPI(auth httpapi.Authenticator, authz httpapi.Authorizer) (*http.ServeMux, huma.API) {
|
||||
mux := http.NewServeMux()
|
||||
settings := &governance.Module{}
|
||||
api := httpapi.New(mux, buildinfo.Version, auth, authz)
|
||||
apiModules{
|
||||
settings: settings, conns: &connectors.Module{}, system: &system.Module{},
|
||||
tell: &deliveries.Module{}, allow: &approvals.Module{}, actionTypes: &judgement.ActionTypes{},
|
||||
policies: &judgement.Policies{}, hear: &events.Module{}, judge: &judgement.Module{},
|
||||
engine: &runs.Engine{}, chat: &chat.Module{}, proposals: &proposals.Module{},
|
||||
notes: &memory.Module{}, live: hub.New(),
|
||||
}.register(api)
|
||||
return mux, api
|
||||
}
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
|
||||
"filippo.io/age"
|
||||
"github.com/BurntSushi/toml"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/deletions"
|
||||
)
|
||||
|
||||
// Config is the bootstrap configuration: only what the binary needs before it
|
||||
@@ -28,6 +30,13 @@ type Config struct {
|
||||
AgeIdentity string `toml:"age_identity"`
|
||||
// AgeBackupRecipients ("age1...") can also open every sealed credential.
|
||||
AgeBackupRecipients []string `toml:"age_backup_recipients"`
|
||||
// StateDir is where the binary keeps state outside the database, including
|
||||
// the record of deletions a restore has to apply again. It defaults to
|
||||
// ${XDG_DATA_HOME:-~/.local/share}/archie, where the other archie binaries
|
||||
// keep their state unless an instance name is set. A leading ~ is the home
|
||||
// directory, and a relative path is refused: the restore that reads this
|
||||
// directory runs as another process.
|
||||
StateDir string `toml:"state_dir"`
|
||||
}
|
||||
|
||||
// DatabaseConfig holds the two connection URLs. The owner runs migrations at
|
||||
@@ -115,6 +124,17 @@ func DefaultConfigPath() string {
|
||||
return filepath.Join(dir, "archie", "config.toml")
|
||||
}
|
||||
|
||||
// DefaultStateDir is ${XDG_DATA_HOME:-~/.local/share}/archie, or the instance's
|
||||
// directory when ARCHIE_INSTANCE names one, resolved the way every archie binary
|
||||
// resolves it.
|
||||
func DefaultStateDir() string {
|
||||
dir, err := deletions.Dir("")
|
||||
if err != nil {
|
||||
return filepath.Join("archie", "state")
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
// NewAgeIdentity writes a new age identity to w, for a config's age_identity.
|
||||
func NewAgeIdentity(w io.Writer) error {
|
||||
id, err := age.GenerateX25519Identity()
|
||||
@@ -127,10 +147,15 @@ func NewAgeIdentity(w io.Writer) error {
|
||||
|
||||
// LoadConfig reads and validates the bootstrap config at path.
|
||||
func LoadConfig(path string) (Config, error) {
|
||||
cfg := Config{Listen: "127.0.0.1:8080"}
|
||||
cfg := Config{Listen: "127.0.0.1:8080", StateDir: DefaultStateDir()}
|
||||
if _, err := toml.DecodeFile(path, &cfg); err != nil {
|
||||
return Config{}, fmt.Errorf("read config %s: %w", path, err)
|
||||
}
|
||||
dir, err := deletions.Dir(cfg.StateDir)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("config %s: %w", path, err)
|
||||
}
|
||||
cfg.StateDir = dir
|
||||
if err := cfg.validate(); err != nil {
|
||||
return Config{}, fmt.Errorf("config %s: %w", path, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
package archie
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/health"
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||
)
|
||||
|
||||
// The two account operations the setup page calls. Every other /api/ route
|
||||
// needs an instance that already has an owner.
|
||||
const (
|
||||
authStatusPath = "/api/auth/status"
|
||||
setUpAccountPath = "/api/auth/setup"
|
||||
)
|
||||
|
||||
// What stopped operations from starting. Readiness reports the stage; the error
|
||||
// text stays in the log, since it can name hosts, roles and tables.
|
||||
const (
|
||||
stageSetupRead = "cannot read whether owner setup is required"
|
||||
stageStartup = "starting operations failed"
|
||||
stageMigrate = "migrating the database failed"
|
||||
)
|
||||
|
||||
// How long a failed boot step waits before it runs again. The delay doubles up
|
||||
// to a ceiling.
|
||||
const (
|
||||
startupRetryMin = 100 * time.Millisecond
|
||||
startupRetryMax = 5 * time.Second
|
||||
)
|
||||
|
||||
// gate is the surface the binary serves. Until the owner setup transaction has
|
||||
// committed it answers only what the setup page needs, and it refuses every
|
||||
// operational route before the handler runs, whatever credential the request
|
||||
// carries. Once the operations are running it passes every request to them.
|
||||
type gate struct {
|
||||
ops http.Handler
|
||||
setup http.Handler
|
||||
|
||||
mu sync.RWMutex
|
||||
open bool
|
||||
problem string
|
||||
}
|
||||
|
||||
// newGate returns a closed gate over the operational handler and the dashboard
|
||||
// build its assets come from.
|
||||
func newGate(ops http.Handler, dist fs.FS) *gate {
|
||||
return &gate{ops: ops, setup: setupSurface(ops, dist)}
|
||||
}
|
||||
|
||||
func (g *gate) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
next := g.setup
|
||||
if g.opened() {
|
||||
next = g.ops
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// publish opens the gate. It is called once, after everything operations need
|
||||
// has started, so a half-wired API is never served.
|
||||
func (g *gate) publish() {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
g.open = true
|
||||
g.problem = ""
|
||||
}
|
||||
|
||||
func (g *gate) opened() bool {
|
||||
g.mu.RLock()
|
||||
defer g.mu.RUnlock()
|
||||
return g.open
|
||||
}
|
||||
|
||||
// stall records the stage that kept the gate closed, so readiness names it rather
|
||||
// than only the missing owner. An empty stage clears it.
|
||||
func (g *gate) stall(stage string) {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
g.problem = stage
|
||||
}
|
||||
|
||||
// check is the readiness check for the gate. An instance still waiting for its
|
||||
// owner is alive but has nothing ready to serve, and that is not a crash.
|
||||
func (g *gate) check(context.Context) error {
|
||||
g.mu.RLock()
|
||||
defer g.mu.RUnlock()
|
||||
switch {
|
||||
case g.open:
|
||||
return nil
|
||||
case g.problem != "":
|
||||
return errors.New(g.problem)
|
||||
}
|
||||
return errors.New("owner setup is incomplete")
|
||||
}
|
||||
|
||||
// serveSurface returns what the binary serves: the health probes throughout,
|
||||
// and the gate for everything else.
|
||||
func serveSurface(checks *health.Registry, g *gate) *http.ServeMux {
|
||||
checks.Register("setup", g.check)
|
||||
mux := http.NewServeMux()
|
||||
checks.Routes(mux)
|
||||
mux.Handle("/", g)
|
||||
return mux
|
||||
}
|
||||
|
||||
// setupSurface answers the routes the setup page needs and refuses the rest.
|
||||
func setupSurface(ops http.Handler, dist fs.FS) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !setupRequest(r, dist) {
|
||||
httpjson.Error(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
ops.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// setupRequest is the whole routing decision while the gate is closed: the setup
|
||||
// page, the files it loads, and the two account operations it calls. Nothing else
|
||||
// passes, so neither a deep link into the SPA nor a setup route called with the
|
||||
// wrong method reaches a handler.
|
||||
func setupRequest(r *http.Request, dist fs.FS) bool {
|
||||
switch r.URL.Path {
|
||||
case setUpAccountPath:
|
||||
return r.Method == http.MethodPost
|
||||
case authStatusPath:
|
||||
return r.Method == http.MethodGet || r.Method == http.MethodHead
|
||||
}
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
return false
|
||||
}
|
||||
return r.URL.Path == "/" || builtFile(r.URL.Path, dist)
|
||||
}
|
||||
|
||||
// builtFile reports whether path names a file in the dashboard build. A route
|
||||
// inside the SPA does not, so a deep link cannot be served the setup page.
|
||||
func builtFile(path string, dist fs.FS) bool {
|
||||
if dist == nil {
|
||||
return false
|
||||
}
|
||||
info, err := fs.Stat(dist, strings.TrimPrefix(path, "/"))
|
||||
return err == nil && !info.IsDir()
|
||||
}
|
||||
|
||||
// setupLookup reads whether owner setup is still required. Durable state is the
|
||||
// only source: nothing a request carries can answer it.
|
||||
type setupLookup func(context.Context) (bool, error)
|
||||
|
||||
// starter is what activation brings up: the operations Run wired. Start is safe
|
||||
// to call again after it returns an error.
|
||||
type starter interface {
|
||||
Start(context.Context) error
|
||||
}
|
||||
|
||||
// activate waits for the owner setup transaction to commit, starts the
|
||||
// operations, and then opens the gate. It runs on the process context: the setup
|
||||
// request that triggered it has been answered by then.
|
||||
func activate(ctx context.Context, log *slog.Logger, lookup setupLookup, done <-chan struct{}, ops starter, g *gate) error {
|
||||
required, err := waitForSetup(ctx, log, lookup, done, g)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if required {
|
||||
select {
|
||||
case <-done:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
if err := retryStartup(ctx, log, g.stall, stageStartup, ops.Start); err != nil {
|
||||
return err
|
||||
}
|
||||
g.publish()
|
||||
log.InfoContext(ctx, "owner setup is complete; serving operations")
|
||||
return nil
|
||||
}
|
||||
|
||||
// waitForSetup answers whether owner setup is still required. A failed read
|
||||
// cannot rule setup out, so it is retried rather than trusted.
|
||||
func waitForSetup(ctx context.Context, log *slog.Logger, lookup setupLookup, done <-chan struct{}, g *gate) (bool, error) {
|
||||
for delay := startupRetryMin; ; delay = min(delay*2, startupRetryMax) {
|
||||
required, err := lookup(ctx)
|
||||
if err == nil {
|
||||
g.stall("")
|
||||
return required, nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return false, ctx.Err()
|
||||
}
|
||||
g.stall(stageSetupRead)
|
||||
log.WarnContext(ctx, "startup step failed; retrying", "stage", stageSetupRead, "err", err, "in", delay)
|
||||
select {
|
||||
case <-time.After(delay):
|
||||
case <-done:
|
||||
// A setup has committed in this process while the reads failed, so an
|
||||
// owner exists whatever the database can answer.
|
||||
g.stall("")
|
||||
return false, nil
|
||||
case <-ctx.Done():
|
||||
return false, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// retryStartup runs a boot step until it succeeds, passing the stage that
|
||||
// failed to mark so readiness can report it. A boot step that reads the database
|
||||
// must not turn a brief outage into a terminated process.
|
||||
func retryStartup(ctx context.Context, log *slog.Logger, mark func(stage string), stage string, attempt func(context.Context) error) error {
|
||||
for delay := startupRetryMin; ; delay = min(delay*2, startupRetryMax) {
|
||||
err := attempt(ctx)
|
||||
if err == nil {
|
||||
mark("")
|
||||
return nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
mark(stage)
|
||||
log.WarnContext(ctx, "startup step failed; retrying", "stage", stage, "err", err, "in", delay)
|
||||
select {
|
||||
case <-time.After(delay):
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
package archie
|
||||
|
||||
import (
|
||||
"context"
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/health"
|
||||
"github.com/samcharles93/archie-core/modules/dashboard"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
)
|
||||
|
||||
//nolint:gosec // G101: a fake credential, sent to prove it opens nothing before an owner exists.
|
||||
const testAdminToken = "Bearer a-bootstrap-admin-token"
|
||||
|
||||
// testLog discards what the gate and activation log.
|
||||
func testLog() *slog.Logger { return slog.New(slog.DiscardHandler) }
|
||||
|
||||
// setUpRequired is durable state on an instance with no owner.
|
||||
func setUpRequired(context.Context) (bool, error) { return true, nil }
|
||||
|
||||
// setUpDone is durable state on an instance whose owner setup has committed.
|
||||
func setUpDone(context.Context) (bool, error) { return false, nil }
|
||||
|
||||
// reached records the requests that get past the gate, so a test can tell a
|
||||
// refusal from a handler that ran.
|
||||
type reached struct {
|
||||
mu sync.Mutex
|
||||
seen []string
|
||||
}
|
||||
|
||||
func (r *reached) handle(w http.ResponseWriter, req *http.Request) {
|
||||
r.mu.Lock()
|
||||
r.seen = append(r.seen, req.Method+" "+req.URL.Path)
|
||||
r.mu.Unlock()
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (r *reached) count() int {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return len(r.seen)
|
||||
}
|
||||
|
||||
func (r *reached) paths() []string {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return append([]string(nil), r.seen...)
|
||||
}
|
||||
|
||||
// testServer builds the surface Run serves, with a stand-in for the API beside
|
||||
// the real dashboard handler. The stand-in answers the routes the setup page
|
||||
// calls and records every other route a request can reach.
|
||||
func testServer(t *testing.T) (*http.ServeMux, *reached, *gate) {
|
||||
t.Helper()
|
||||
hit := &reached{}
|
||||
dist := fstest.MapFS{
|
||||
"index.html": {Data: []byte("<html>archie setup</html>")},
|
||||
"favicon.svg": {Data: []byte("<svg>")},
|
||||
"assets/app.js": {Data: []byte("console.log(1)")},
|
||||
}
|
||||
ops := http.NewServeMux()
|
||||
dashboard.Routes(ops, dist)
|
||||
ops.HandleFunc("GET "+authStatusPath, func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"setup_required":true,"user":null}`))
|
||||
})
|
||||
ops.HandleFunc("POST "+setUpAccountPath, func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
})
|
||||
ops.HandleFunc("GET /api/system/bootstrap", hit.handle)
|
||||
ops.HandleFunc("POST /hooks/{source}", hit.handle)
|
||||
ops.HandleFunc("GET /api/docs", hit.handle)
|
||||
ops.HandleFunc("GET /api/openapi", hit.handle)
|
||||
ops.HandleFunc("POST /api/auth/login", hit.handle)
|
||||
ops.HandleFunc("GET /oauth2/login", hit.handle)
|
||||
ops.HandleFunc("GET /api/tasks", hit.handle)
|
||||
|
||||
checks := health.NewRegistry()
|
||||
checks.Register("database", func(context.Context) error { return nil })
|
||||
g := newGate(ops, dist)
|
||||
return serveSurface(checks, g), hit, g
|
||||
}
|
||||
|
||||
func do(t *testing.T, served http.Handler, method, path string, withAdmin bool) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(context.Background(), method, path, nil)
|
||||
if withAdmin {
|
||||
req.Header.Set("Authorization", testAdminToken)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
served.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// TestClosedGateServesOnlySetup guards the regression this issue was filed for:
|
||||
// with no owner in the database, the bootstrap admin token still reached
|
||||
// GET /api/system/bootstrap, and every other operational route with it.
|
||||
func TestClosedGateServesOnlySetup(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
path string
|
||||
admin bool
|
||||
status int
|
||||
body string
|
||||
// servedAsPage marks a response the dashboard handler writes, which must
|
||||
// keep the CSP that stops chat-rendered Markdown loading a remote image.
|
||||
servedAsPage bool
|
||||
}{
|
||||
{name: "auth status", method: http.MethodGet, path: authStatusPath, status: http.StatusOK, body: `"setup_required":true`},
|
||||
{name: "auth status by head", method: http.MethodHead, path: authStatusPath, status: http.StatusOK},
|
||||
{name: "set up the owner", method: http.MethodPost, path: setUpAccountPath, status: http.StatusCreated},
|
||||
{name: "the setup page", method: http.MethodGet, path: "/", status: http.StatusOK, body: "archie setup", servedAsPage: true},
|
||||
{name: "a script the page loads", method: http.MethodGet, path: "/assets/app.js", status: http.StatusOK, body: "console.log(1)", servedAsPage: true},
|
||||
{name: "the page icon", method: http.MethodGet, path: "/favicon.svg", status: http.StatusOK, body: "<svg>", servedAsPage: true},
|
||||
{name: "liveness", method: http.MethodGet, path: "/healthz", status: http.StatusOK, body: "ok\n"},
|
||||
|
||||
// From here down nothing reaches a handler, credential or not.
|
||||
{name: "operational API", method: http.MethodGet, path: "/api/system/bootstrap", status: http.StatusNotFound},
|
||||
{name: "operational API with the admin token", method: http.MethodGet, path: "/api/system/bootstrap", admin: true, status: http.StatusNotFound},
|
||||
{name: "another operational read", method: http.MethodGet, path: "/api/tasks", status: http.StatusNotFound},
|
||||
{name: "another operational read with the admin token", method: http.MethodGet, path: "/api/tasks", admin: true, status: http.StatusNotFound},
|
||||
{name: "webhook intake", method: http.MethodPost, path: "/hooks/github", status: http.StatusNotFound},
|
||||
{name: "API document", method: http.MethodGet, path: "/api/docs", status: http.StatusNotFound},
|
||||
{name: "OpenAPI document", method: http.MethodGet, path: "/api/openapi", status: http.StatusNotFound},
|
||||
{name: "sign in", method: http.MethodPost, path: "/api/auth/login", status: http.StatusNotFound},
|
||||
{name: "OIDC sign in", method: http.MethodGet, path: "/oauth2/login", status: http.StatusNotFound},
|
||||
{name: "a route inside the SPA", method: http.MethodGet, path: "/tasks", status: http.StatusNotFound},
|
||||
{name: "a route inside the SPA with a trailing slash", method: http.MethodGet, path: "/settings/status/", status: http.StatusNotFound},
|
||||
{name: "setup by GET", method: http.MethodGet, path: setUpAccountPath, status: http.StatusNotFound},
|
||||
{name: "status by POST", method: http.MethodPost, path: authStatusPath, status: http.StatusNotFound},
|
||||
{name: "status with a trailing slash", method: http.MethodGet, path: authStatusPath + "/", status: http.StatusNotFound},
|
||||
{name: "the page by POST", method: http.MethodPost, path: "/", status: http.StatusNotFound},
|
||||
{name: "a script by POST", method: http.MethodPost, path: "/assets/app.js", status: http.StatusNotFound},
|
||||
{name: "a file the build has no name for", method: http.MethodGet, path: "/assets/missing.js", status: http.StatusNotFound},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
served, hit, _ := testServer(t)
|
||||
rec := do(t, served, tc.method, tc.path, tc.admin)
|
||||
if rec.Code != tc.status {
|
||||
t.Fatalf("%s %s: status = %d, want %d", tc.method, tc.path, rec.Code, tc.status)
|
||||
}
|
||||
if tc.body != "" && !strings.Contains(rec.Body.String(), tc.body) {
|
||||
t.Fatalf("%s %s: body = %q, want it to contain %q", tc.method, tc.path, rec.Body.String(), tc.body)
|
||||
}
|
||||
if got := hit.count(); got != 0 {
|
||||
t.Fatalf("%s %s: %d operational handlers ran, want none (reached %v)", tc.method, tc.path, got, hit.paths())
|
||||
}
|
||||
if tc.servedAsPage {
|
||||
// Mirrors the dashboard's own header: the setup page must not lose it.
|
||||
if got := rec.Header().Get("Content-Security-Policy"); got != "img-src 'self' data:" {
|
||||
t.Fatalf("%s %s: Content-Security-Policy = %q, want the dashboard's", tc.method, tc.path, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenGateServesOperations guards the other half: the routes the gate
|
||||
// refuses before setup are the ones that answer after it, so a refusal above
|
||||
// is the gate's decision and not a missing route.
|
||||
func TestOpenGateServesOperations(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
path string
|
||||
admin bool
|
||||
status int
|
||||
handled int
|
||||
body string
|
||||
}{
|
||||
{name: "operational API with the admin token", method: http.MethodGet, path: "/api/system/bootstrap", admin: true, status: http.StatusOK, handled: 1},
|
||||
{name: "another operational read", method: http.MethodGet, path: "/api/tasks", status: http.StatusOK, handled: 1},
|
||||
{name: "webhook intake", method: http.MethodPost, path: "/hooks/github", status: http.StatusOK, handled: 1},
|
||||
{name: "API document", method: http.MethodGet, path: "/api/docs", status: http.StatusOK, handled: 1},
|
||||
{name: "OpenAPI document", method: http.MethodGet, path: "/api/openapi", status: http.StatusOK, handled: 1},
|
||||
{name: "sign in", method: http.MethodPost, path: "/api/auth/login", status: http.StatusOK, handled: 1},
|
||||
{name: "OIDC sign in", method: http.MethodGet, path: "/oauth2/login", status: http.StatusOK, handled: 1},
|
||||
{name: "a route inside the SPA", method: http.MethodGet, path: "/tasks", status: http.StatusOK, body: "archie setup"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
served, hit, g := testServer(t)
|
||||
g.publish()
|
||||
rec := do(t, served, tc.method, tc.path, tc.admin)
|
||||
if rec.Code != tc.status {
|
||||
t.Fatalf("%s %s: status = %d, want %d", tc.method, tc.path, rec.Code, tc.status)
|
||||
}
|
||||
if tc.body != "" && !strings.Contains(rec.Body.String(), tc.body) {
|
||||
t.Fatalf("%s %s: body = %q, want it to contain %q", tc.method, tc.path, rec.Body.String(), tc.body)
|
||||
}
|
||||
if got := hit.count(); got != tc.handled {
|
||||
t.Fatalf("%s %s: %d operational handlers ran, want %d (reached %v)", tc.method, tc.path, got, tc.handled, hit.paths())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGateIsNotBypassedByPathTricks(t *testing.T) {
|
||||
// A path the mux cleans is redirected before the gate sees it, and the
|
||||
// cleaned path is refused in turn, so no spelling reaches a handler.
|
||||
for _, path := range []string{"//api/system/bootstrap", "/api/../api/system/bootstrap", "/api/./system/bootstrap", "/api/auth/../system/bootstrap"} {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
served, hit, _ := testServer(t)
|
||||
rec := do(t, served, http.MethodGet, path, true)
|
||||
if rec.Code == http.StatusOK {
|
||||
t.Fatalf("%s: status 200, want a refusal", path)
|
||||
}
|
||||
if location := rec.Header().Get("Location"); location != "" {
|
||||
if followed := do(t, served, http.MethodGet, location, true); followed.Code != http.StatusNotFound {
|
||||
t.Fatalf("%s redirected to %s, which answered %d, want 404", path, location, followed.Code)
|
||||
}
|
||||
}
|
||||
if got := hit.count(); got != 0 {
|
||||
t.Fatalf("%s: %d operational handlers ran, want none (reached %v)", path, got, hit.paths())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadinessReportsSetupUntilOperationsStart(t *testing.T) {
|
||||
// A missing owner is not a crash: liveness answers, readiness says why the
|
||||
// instance serves nothing operational, and the dependency checks take over
|
||||
// once operations are up.
|
||||
served, _, g := testServer(t)
|
||||
if rec := do(t, served, http.MethodGet, "/healthz", false); rec.Code != http.StatusOK {
|
||||
t.Fatalf("liveness while gated: status = %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
|
||||
rec := do(t, served, http.MethodGet, "/readyz", false)
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("readiness while gated: status = %d, want %d", rec.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
var body struct {
|
||||
Ready bool `json:"ready"`
|
||||
Failures map[string]string `json:"failures"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode readiness: %v (%s)", err, rec.Body.String())
|
||||
}
|
||||
if body.Ready {
|
||||
t.Fatalf("readiness while gated: ready = true, want false")
|
||||
}
|
||||
if !strings.Contains(body.Failures["setup"], "owner setup") {
|
||||
t.Fatalf("readiness while gated: failures = %v, want the setup check", body.Failures)
|
||||
}
|
||||
|
||||
g.publish()
|
||||
if rec := do(t, served, http.MethodGet, "/readyz", false); rec.Code != http.StatusOK {
|
||||
t.Fatalf("readiness once operations serve: status = %d, want %d (%s)", rec.Code, http.StatusOK, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// fakeOperations stands in for the startup work and counts how often it runs.
|
||||
type fakeOperations struct {
|
||||
starts atomic.Int32
|
||||
startFails atomic.Int32
|
||||
startErr error
|
||||
}
|
||||
|
||||
func (f *fakeOperations) Start(context.Context) error {
|
||||
f.starts.Add(1)
|
||||
if f.startFails.Load() > 0 {
|
||||
f.startFails.Add(-1)
|
||||
return f.startErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestActivateStartsOperationsWhenSetupCommits(t *testing.T) {
|
||||
// Nothing starts while the owner is missing, the setup page keeps answering
|
||||
// so the operator can finish, and the commit starts everything once.
|
||||
signal := governance.NewSetupSignal()
|
||||
ops := &fakeOperations{}
|
||||
served, hit, g := testServer(t)
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- activate(context.Background(), testLog(), setUpRequired, signal.Done(), ops, g) }()
|
||||
|
||||
if got := ops.starts.Load(); got != 0 {
|
||||
t.Fatalf("starts before the commit = %d, want 0", got)
|
||||
}
|
||||
if g.opened() {
|
||||
t.Fatalf("the gate is open before the commit")
|
||||
}
|
||||
if rec := do(t, served, http.MethodGet, authStatusPath, false); rec.Code != http.StatusOK {
|
||||
t.Fatalf("auth status while waiting: status = %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
if rec := do(t, served, http.MethodGet, "/api/system/bootstrap", true); rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("operational API while waiting: status = %d, want %d", rec.Code, http.StatusNotFound)
|
||||
}
|
||||
|
||||
signal.Complete()
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("activate: %v", err)
|
||||
}
|
||||
if got := ops.starts.Load(); got != 1 {
|
||||
t.Fatalf("starts after the commit = %d, want 1", got)
|
||||
}
|
||||
if rec := do(t, served, http.MethodGet, "/api/system/bootstrap", true); rec.Code != http.StatusOK {
|
||||
t.Fatalf("operational API after the commit: status = %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
if got := hit.count(); got != 1 {
|
||||
t.Fatalf("operational handlers after the commit = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentSetupCommitsStartOperationsOnce(t *testing.T) {
|
||||
// Two setup transactions can't both commit, but the signal has to hold even
|
||||
// if callers race: one set of workers, one open gate.
|
||||
signal := governance.NewSetupSignal()
|
||||
ops := &fakeOperations{}
|
||||
_, _, g := testServer(t)
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- activate(context.Background(), testLog(), setUpRequired, signal.Done(), ops, g) }()
|
||||
|
||||
var completing sync.WaitGroup
|
||||
for range 8 {
|
||||
completing.Go(signal.Complete)
|
||||
}
|
||||
completing.Wait()
|
||||
signal.Complete()
|
||||
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("activate: %v", err)
|
||||
}
|
||||
if got := ops.starts.Load(); got != 1 {
|
||||
t.Fatalf("starts = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelledBeforeSetupStartsNothing(t *testing.T) {
|
||||
signal := governance.NewSetupSignal()
|
||||
ops := &fakeOperations{}
|
||||
_, _, g := testServer(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- activate(ctx, testLog(), setUpRequired, signal.Done(), ops, g) }()
|
||||
cancel()
|
||||
|
||||
if err := <-done; !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("activate = %v, want context.Canceled", err)
|
||||
}
|
||||
if got := ops.starts.Load(); got != 0 {
|
||||
t.Fatalf("starts after cancellation = %d, want 0", got)
|
||||
}
|
||||
if g.opened() {
|
||||
t.Fatalf("the gate opened on a cancelled activation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompletedSetupStartsWithoutWaiting(t *testing.T) {
|
||||
// The restart after a completed setup: durable state says no owner is
|
||||
// missing, so the process must not wait for a signal this run can never
|
||||
// send.
|
||||
signal := governance.NewSetupSignal() // never completed, as on a restart
|
||||
ops := &fakeOperations{}
|
||||
served, hit, g := testServer(t)
|
||||
|
||||
if err := activate(context.Background(), testLog(), setUpDone, signal.Done(), ops, g); err != nil {
|
||||
t.Fatalf("activate: %v", err)
|
||||
}
|
||||
if got := ops.starts.Load(); got != 1 {
|
||||
t.Fatalf("starts = %d, want 1", got)
|
||||
}
|
||||
if !g.opened() {
|
||||
t.Fatalf("the gate is shut with setup already complete")
|
||||
}
|
||||
if rec := do(t, served, http.MethodGet, "/api/system/bootstrap", true); rec.Code != http.StatusOK {
|
||||
t.Fatalf("operational API after a restart: status = %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
if got := hit.count(); got != 1 {
|
||||
t.Fatalf("operational handlers = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// flakyLookup fails a set number of reads before answering, as a database that
|
||||
// is briefly unreachable does.
|
||||
type flakyLookup struct {
|
||||
failures atomic.Int32
|
||||
required bool
|
||||
reads atomic.Int32
|
||||
}
|
||||
|
||||
// newFlakyLookup fails failures reads before answering required.
|
||||
func newFlakyLookup(failures int32, required bool) *flakyLookup {
|
||||
l := &flakyLookup{required: required}
|
||||
l.failures.Store(failures)
|
||||
return l
|
||||
}
|
||||
|
||||
func (f *flakyLookup) lookup(context.Context) (bool, error) {
|
||||
f.reads.Add(1)
|
||||
if f.failures.Load() > 0 {
|
||||
f.failures.Add(-1)
|
||||
return false, errors.New("connection refused")
|
||||
}
|
||||
return f.required, nil
|
||||
}
|
||||
|
||||
func TestUnreadableSetupStateIsRetried(t *testing.T) {
|
||||
// A database that is briefly unavailable must not hold an instance shut
|
||||
// until someone restarts it: setup state that can't be read is retried, and
|
||||
// readiness reports the failure meanwhile.
|
||||
lookup := newFlakyLookup(2, false)
|
||||
ops := &fakeOperations{}
|
||||
served, hit, g := testServer(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- activate(ctx, testLog(), lookup.lookup, nil, ops, g) }()
|
||||
|
||||
// While the read fails, nothing starts and readiness names the failure.
|
||||
if got := ops.starts.Load(); got != 0 {
|
||||
t.Fatalf("starts while setup state is unreadable = %d, want 0", got)
|
||||
}
|
||||
for range 100 {
|
||||
if strings.Contains(readyzBody(t, served), stageSetupRead) {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
body := readyzBody(t, served)
|
||||
if !strings.Contains(body, stageSetupRead) {
|
||||
t.Fatalf("readiness while setup state is unreadable = %q, want %q", body, stageSetupRead)
|
||||
}
|
||||
if strings.Contains(body, "connection refused") {
|
||||
t.Fatalf("readiness = %q, leaked the database's own error", body)
|
||||
}
|
||||
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("activate: %v", err)
|
||||
}
|
||||
if got := ops.starts.Load(); got != 1 {
|
||||
t.Fatalf("starts after the read recovered = %d, want 1", got)
|
||||
}
|
||||
if got := lookup.reads.Load(); got < 3 {
|
||||
t.Fatalf("reads = %d, want the failed read retried", got)
|
||||
}
|
||||
if rec := do(t, served, http.MethodGet, "/api/system/bootstrap", true); rec.Code != http.StatusOK {
|
||||
t.Fatalf("operational API after the read recovered: status = %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
if got := hit.count(); got != 1 {
|
||||
t.Fatalf("operational handlers after the read recovered = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnreadableSetupStateWaitsForTheCommit(t *testing.T) {
|
||||
// When the read keeps failing, a setup that commits in this process is
|
||||
// still enough: the owner exists, so operations may start.
|
||||
lookup := newFlakyLookup(1000, true)
|
||||
ops := &fakeOperations{}
|
||||
_, _, g := testServer(t)
|
||||
signal := governance.NewSetupSignal()
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- activate(context.Background(), testLog(), lookup.lookup, signal.Done(), ops, g) }()
|
||||
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if got := ops.starts.Load(); got != 0 {
|
||||
t.Fatalf("starts while setup state is unreadable = %d, want 0", got)
|
||||
}
|
||||
signal.Complete()
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("activate: %v", err)
|
||||
}
|
||||
if got := ops.starts.Load(); got != 1 {
|
||||
t.Fatalf("starts after the commit = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func readyzBody(t *testing.T, served http.Handler) string {
|
||||
t.Helper()
|
||||
return do(t, served, http.MethodGet, "/readyz", false).Body.String()
|
||||
}
|
||||
|
||||
func TestOperationsStartIsRetried(t *testing.T) {
|
||||
// connectors.Module.Start returns an error only for the read of accepted
|
||||
// connectors, before anything launches, so a failed Start leaves nothing
|
||||
// running and the next attempt is safe. Without that retry a transient read
|
||||
// error took the process down.
|
||||
ops := &fakeOperations{startErr: errors.New("connection refused")}
|
||||
ops.startFails.Store(2)
|
||||
served, hit, g := testServer(t)
|
||||
signal := governance.NewSetupSignal()
|
||||
signal.Complete()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- activate(ctx, testLog(), setUpDone, signal.Done(), ops, g) }()
|
||||
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("activate: %v", err)
|
||||
}
|
||||
if got := ops.starts.Load(); got != 3 {
|
||||
t.Fatalf("start calls = %d, want the two failures retried", got)
|
||||
}
|
||||
if !g.opened() {
|
||||
t.Fatalf("the gate is shut after a retried start")
|
||||
}
|
||||
if rec := do(t, served, http.MethodGet, "/api/system/bootstrap", true); rec.Code != http.StatusOK {
|
||||
t.Fatalf("operational API after a retried start: status = %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
if got := hit.count(); got != 1 {
|
||||
t.Fatalf("operational handlers = %d, want 1: one surface, not one per attempt", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadinessNamesTheStageWithoutTheRawError(t *testing.T) {
|
||||
// Readiness answers whoever can reach the port, so it names the stage that
|
||||
// failed and keeps the database's own error text in the log.
|
||||
ops := &fakeOperations{startErr: errors.New("pq: password authentication failed for user archie")}
|
||||
ops.startFails.Store(1000)
|
||||
served, _, g := testServer(t)
|
||||
signal := governance.NewSetupSignal()
|
||||
signal.Complete()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- activate(context.Background(), testLog(), setUpDone, signal.Done(), ops, g) }()
|
||||
|
||||
for range 200 {
|
||||
if strings.Contains(readyzBody(t, served), "starting operations failed") {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
body := readyzBody(t, served)
|
||||
if !strings.Contains(body, "starting operations failed") {
|
||||
t.Fatalf("readiness = %q, want it to name the stage", body)
|
||||
}
|
||||
for _, leak := range []string{"pq:", "password", "user archie", "connection refused"} {
|
||||
if strings.Contains(body, leak) {
|
||||
t.Fatalf("readiness = %q, leaked %q", body, leak)
|
||||
}
|
||||
}
|
||||
if g.opened() {
|
||||
t.Fatalf("the gate opened while a startup stage fails")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package archie
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/health"
|
||||
"github.com/samcharles93/archie-core/modules/approvals"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/events"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/runs"
|
||||
"github.com/samcharles93/archie-core/modules/system"
|
||||
)
|
||||
|
||||
// healthSources joins what each module knows about itself into the sources the
|
||||
// system health report reads. The report asks them on demand, so nothing here
|
||||
// polls or keeps state.
|
||||
func healthSources(checks *health.Registry, conns *connectors.Module, engine *runs.Engine, allow *approvals.Module, settings *governance.Module, hear *events.Module) system.Sources {
|
||||
return system.Sources{
|
||||
Checks: func(ctx context.Context) []health.Result {
|
||||
return slices.DeleteFunc(checks.Results(ctx), func(r health.Result) bool {
|
||||
// The report lists each connector with its own cause.
|
||||
return r.Name == "connectors"
|
||||
})
|
||||
},
|
||||
Connectors: conns.Health,
|
||||
Runner: engine.Runner,
|
||||
Waiting: func(ctx context.Context) (system.Waiting, error) {
|
||||
pending, err := allow.Pending(ctx)
|
||||
if err != nil {
|
||||
return system.Waiting{}, fmt.Errorf("list pending approvals: %w", err)
|
||||
}
|
||||
counts, err := engine.Counts(ctx, orgID)
|
||||
if err != nil {
|
||||
return system.Waiting{}, err
|
||||
}
|
||||
return system.Waiting{Approvals: len(pending), Runs: counts}, nil
|
||||
},
|
||||
LastFailedRun: func(ctx context.Context) (*runs.RunView, error) {
|
||||
return engine.LastFailed(ctx, orgID)
|
||||
},
|
||||
Setup: func(ctx context.Context) []system.SetupStep {
|
||||
_, modelErr := settings.AgentModel(ctx)
|
||||
sources, srcErr := hear.SourceCount(ctx)
|
||||
return []system.SetupStep{
|
||||
{
|
||||
Title: "Set an agent model",
|
||||
Detail: "Configure a model provider and assign the agent role so workflows and chat can run.",
|
||||
Done: modelErr == nil,
|
||||
Path: "/settings/models",
|
||||
},
|
||||
{
|
||||
Title: "Add an event source",
|
||||
Detail: "Connect a webhook or polling source to start receiving events.",
|
||||
Done: srcErr == nil && sources > 0,
|
||||
Path: "/events?tab=sources",
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package archie
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/health"
|
||||
"github.com/samcharles93/archie-core/modules/approvals"
|
||||
"github.com/samcharles93/archie-core/modules/chat"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/deliveries"
|
||||
"github.com/samcharles93/archie-core/modules/events"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/judgement"
|
||||
"github.com/samcharles93/archie-core/modules/memory"
|
||||
"github.com/samcharles93/archie-core/modules/proposals"
|
||||
"github.com/samcharles93/archie-core/modules/runs"
|
||||
)
|
||||
|
||||
// catalogueUpdateInterval is how often an extension that follows the catalogue
|
||||
// checks it for a new version.
|
||||
const catalogueUpdateInterval = time.Hour
|
||||
|
||||
// operations is everything the gate holds back: the connectors, the access
|
||||
// chain administrative writes are checked against, the workflow that ships with
|
||||
// the binary, and the loops that do work. Run wires it at boot and Start brings
|
||||
// it up, once, after owner setup has committed.
|
||||
type operations struct {
|
||||
log *slog.Logger
|
||||
checks *health.Registry
|
||||
settings *governance.Module
|
||||
conns *connectors.Module
|
||||
engine *runs.Engine
|
||||
hear *events.Module
|
||||
tell *deliveries.Module
|
||||
talk *chat.Module
|
||||
judge *judgement.Module
|
||||
allow *approvals.Module
|
||||
remember *memory.Module
|
||||
proposed *proposals.Module
|
||||
// completeRecord finishes the record of a committed deletion whose entry could
|
||||
// not be written.
|
||||
completeRecord func(context.Context) (int, error)
|
||||
|
||||
workers sync.WaitGroup
|
||||
}
|
||||
|
||||
// Start brings up every part of the binary that does work, in the order the
|
||||
// other parts depend on: the role policies and access chain, the workflow that
|
||||
// ships with the binary, the connectors, then the loops.
|
||||
//
|
||||
// Calling it again after it returns an error is safe. Every step that can fail
|
||||
// runs before a connector launches, and connectors.Module.Start fails only for
|
||||
// the read of accepted connectors, before launching any. An error therefore
|
||||
// means nothing is running.
|
||||
func (o *operations) Start(ctx context.Context) error {
|
||||
access, err := startAccess(ctx, o.log, o.settings)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Every entry point uses the same chain, and every decision, allowed or
|
||||
// refused, is stored.
|
||||
checked := governance.Recording(access, o.settings, o.log.With("module", "governance"))
|
||||
// A workflow takes its context from the run handle, as a handler takes it
|
||||
// from the request.
|
||||
o.engine.Use(runs.Deps{
|
||||
Settings: o.settings, Toolbox: o.conns, Judge: o.judge, Approver: o.allow,
|
||||
Proposals: o.proposed, Notifier: o.tell, Messenger: o.tell, Memory: o.remember, Capabilities: o.conns,
|
||||
Access: checked,
|
||||
})
|
||||
if err := installStarter(ctx, o.engine); err != nil {
|
||||
return err
|
||||
}
|
||||
// A connector's new declarations are re-checked against the saved
|
||||
// workflows that reference it, so an update that would break them is
|
||||
// refused instead of failing a run later.
|
||||
o.conns.Use(func(ctx context.Context, connector string, caps connectors.Capabilities) error {
|
||||
return o.engine.RecheckConnector(ctx, orgID, connector, caps)
|
||||
})
|
||||
if err := o.conns.Start(ctx); err != nil {
|
||||
return fmt.Errorf("read accepted connectors: %w", err)
|
||||
}
|
||||
|
||||
// Nothing below can fail, so a retry cannot launch a connector or a loop twice.
|
||||
o.checks.Register("connectors", o.conns.Ready)
|
||||
// An extension that follows the catalogue checks it for a new version. With
|
||||
// no catalogue source set it does nothing.
|
||||
o.workers.Go(func() { o.conns.WatchUpdates(ctx, catalogueUpdateInterval) })
|
||||
// Administrative writes, and every API request, are checked against the same
|
||||
// live policy chain as chat and background work. The webhook intake applies
|
||||
// each source's delivery policy from it.
|
||||
o.settings.UseAuthorizer(checked)
|
||||
o.allow.UseAuthorizer(checked)
|
||||
o.proposed.UseAuthorizer(checked)
|
||||
o.tell.UseAccess(checked)
|
||||
o.hear.UseDeliveryPolicy(governance.RecordingDelivery(access, o.settings, o.log.With("module", "governance")))
|
||||
o.hear.UseTrustedProxies(o.settings.TrustedProxies)
|
||||
o.talk.Use(chat.Deps{
|
||||
People: o.settings, Access: checked, Settings: o.settings, Toolbox: o.conns, Judge: o.judge,
|
||||
Approver: o.allow, Memory: o.remember, Runs: o.engine, Notifier: o.tell,
|
||||
})
|
||||
for _, loop := range []func(context.Context){o.engine.Work, o.hear.Work, o.tell.Work, o.proposed.Work, o.talk.Work, o.retryDeletionRecord} {
|
||||
o.workers.Go(func() { loop(ctx) })
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// retryDeletionRecord keeps trying to complete the record of a deletion that
|
||||
// committed while its entry could not be written, so the instance heals without a
|
||||
// restart. It does nothing while the record is complete.
|
||||
func (o *operations) retryDeletionRecord(ctx context.Context) {
|
||||
ticker := time.NewTicker(deletionRecordRetry)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if !o.remember.RecordPending() || o.completeRecord == nil {
|
||||
continue
|
||||
}
|
||||
// The mark is taken before the reconcile: a failure recorded while it
|
||||
// runs must still leave the instance unhealthy.
|
||||
mark := o.remember.FailureMark()
|
||||
added, err := o.completeRecord(ctx)
|
||||
if err != nil {
|
||||
o.log.ErrorContext(ctx, "complete the record of deletions", "error", err)
|
||||
continue
|
||||
}
|
||||
o.remember.MarkRecordComplete(mark)
|
||||
o.log.WarnContext(ctx, "completed the record of deletions", "entries", added)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Wait blocks until every loop Start began has returned.
|
||||
func (o *operations) Wait() {
|
||||
o.workers.Wait()
|
||||
}
|
||||
|
||||
// installStarter puts the workflow that ships with the binary in place. It
|
||||
// belongs to the organisation, so it waits until setup has created one.
|
||||
func installStarter(ctx context.Context, engine *runs.Engine) error {
|
||||
if _, err := engine.InstallShipped(ctx, orgID, "investigate", runs.InvestigateDocument(), string(governance.SystemID)); err != nil {
|
||||
return fmt.Errorf("install the investigate workflow: %w", err)
|
||||
}
|
||||
if _, err := engine.InstallShipped(ctx, orgID, runs.ProposalWorkflow, runs.ProposalDocument(), string(governance.SystemID)); err != nil {
|
||||
return fmt.Errorf("install the proposal workflow: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// startAccess seeds the operating org's shipped role policies and returns the
|
||||
// access policy chain, kept current as policies change.
|
||||
func startAccess(ctx context.Context, log *slog.Logger, settings *governance.Module) (*governance.Live, error) {
|
||||
if err := settings.EnsureShippedOrgPolicies(ctx, governance.DefaultOrgID); err != nil {
|
||||
return nil, fmt.Errorf("seed the role policies: %w", err)
|
||||
}
|
||||
return governance.StartLive(ctx, settings.ListPolicies, settings.PoliciesVersion, log.With("module", "governance")), nil
|
||||
}
|
||||
+194
-62
@@ -5,33 +5,38 @@ package archie
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json/jsontext"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/buildinfo"
|
||||
"github.com/samcharles93/archie-core/internal/platform/deletions"
|
||||
"github.com/samcharles93/archie-core/internal/platform/health"
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/internal/platform/hub"
|
||||
"github.com/samcharles93/archie-core/internal/platform/pg"
|
||||
"github.com/samcharles93/archie-core/internal/platform/seal"
|
||||
"github.com/samcharles93/archie-core/modules/approvals"
|
||||
"github.com/samcharles93/archie-core/modules/chat"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/dashboard"
|
||||
"github.com/samcharles93/archie-core/modules/deliveries"
|
||||
"github.com/samcharles93/archie-core/modules/drafts"
|
||||
"github.com/samcharles93/archie-core/modules/events"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/judgement"
|
||||
"github.com/samcharles93/archie-core/modules/memory"
|
||||
"github.com/samcharles93/archie-core/modules/proposals"
|
||||
"github.com/samcharles93/archie-core/modules/runs"
|
||||
"github.com/samcharles93/archie-core/modules/system"
|
||||
"github.com/samcharles93/archie-core/ui"
|
||||
@@ -39,8 +44,18 @@ import (
|
||||
|
||||
const shutdownGrace = 10 * time.Second
|
||||
|
||||
// deletionRecordRetry is how often an incomplete record of a committed deletion
|
||||
// is retried.
|
||||
const deletionRecordRetry = 30 * time.Second
|
||||
|
||||
// Run boots the binary from the config at configPath and blocks until ctx ends
|
||||
// or the server fails.
|
||||
//
|
||||
// An instance whose owner setup has not committed serves the setup page and
|
||||
// nothing else: connectors, module routes, the shipped workflow and the worker
|
||||
// loops all wait for that transaction. Durable state says whether it has already
|
||||
// happened, so a restart reads that state and starts serving operations
|
||||
// immediately.
|
||||
func Run(ctx context.Context, configPath string) error {
|
||||
log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "archie", "version", buildinfo.Version)
|
||||
|
||||
@@ -48,37 +63,111 @@ func Run(ctx context.Context, configPath string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := pg.Migrate(ctx, log, cfg.Database.OwnerURL, cfg.Database.URL, schemas); err != nil {
|
||||
return err
|
||||
}
|
||||
db, err := pg.Open(ctx, cfg.Database.URL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = db.Close() }()
|
||||
// The serve lock is taken before the schema is touched: a restore holds it
|
||||
// exclusively for as long as it replaces the database and replays the
|
||||
// deletions recorded outside it, and no process may migrate or serve during
|
||||
// that window.
|
||||
holdServe, err := pg.ClaimServe(ctx, db, pg.ServeLockName)
|
||||
if err != nil {
|
||||
_ = db.Close()
|
||||
return fmt.Errorf("claim the database: %w", err)
|
||||
}
|
||||
defer holdServe()
|
||||
// Nothing is served yet, so there is no readiness to report while this retries.
|
||||
migrate := func(ctx context.Context) error {
|
||||
return pg.Migrate(ctx, log, cfg.Database.OwnerURL, cfg.Database.URL, schemas)
|
||||
}
|
||||
if err := retryStartup(ctx, log, func(string) {}, stageMigrate, migrate); err != nil {
|
||||
_ = db.Close()
|
||||
return err
|
||||
}
|
||||
// A deletion whose record did not land is completed before anything serves:
|
||||
// the database is the authority on what was deleted, the record outside it on
|
||||
// what a restore can apply again.
|
||||
if added, err := memory.Reconcile(ctx, db, cfg.StateDir); err != nil {
|
||||
_ = db.Close()
|
||||
return fmt.Errorf("complete the record of deletions: %w", err)
|
||||
} else if added > 0 {
|
||||
log.WarnContext(ctx, "completed the record of deletions", "entries", added)
|
||||
}
|
||||
// The record is applied to whatever database is here before anything serves.
|
||||
// A restore that replaced the database and then failed to apply the record
|
||||
// leaves the notes it recorded behind, and those are the ones nobody may see
|
||||
// again.
|
||||
if applied, err := memory.ReapplyDeletions(ctx, db, cfg.StateDir); err != nil {
|
||||
_ = db.Close()
|
||||
return fmt.Errorf("apply the record of deletions: %w", err)
|
||||
} else if applied > 0 {
|
||||
log.WarnContext(ctx, "applied the record of deletions", "notes", applied)
|
||||
}
|
||||
b, err := wire(log, configPath, cfg, db) //nolint:contextcheck // the API's guard derives its context from each request
|
||||
if err != nil {
|
||||
_ = db.Close()
|
||||
return err
|
||||
}
|
||||
defer b.close()
|
||||
|
||||
work, stop := context.WithCancel(ctx)
|
||||
defer stop()
|
||||
|
||||
started := make(chan struct{})
|
||||
go func() {
|
||||
// Startup failures are retried, so only shutdown ends activation.
|
||||
_ = activate(work, log, b.settings.AccountSetupRequired, b.settings.SetupDone(), b.ops, b.gate)
|
||||
close(started)
|
||||
}()
|
||||
|
||||
serveErr := serve(work, log, cfg.Listen, b.served)
|
||||
stop()
|
||||
<-started
|
||||
// Every loop activation began has returned before the caller closes the
|
||||
// connectors and the database.
|
||||
b.ops.Wait()
|
||||
return serveErr
|
||||
}
|
||||
|
||||
// binary is a wired instance: the surface it serves, and what waits for owner
|
||||
// setup before it does any work.
|
||||
type binary struct {
|
||||
db *sqlx.DB
|
||||
conns *connectors.Module
|
||||
gate *gate
|
||||
served http.Handler
|
||||
|
||||
settings *governance.Module
|
||||
ops *operations
|
||||
}
|
||||
|
||||
// wire builds every module and registers its routes. Nothing operational
|
||||
// starts here: the routes are wired on a mux the gate holds back, and Start
|
||||
// brings them up once owner setup has committed.
|
||||
func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary, error) {
|
||||
checks := health.NewRegistry()
|
||||
checks.Register("database", db.PingContext)
|
||||
mux := http.NewServeMux()
|
||||
checks.Routes(mux)
|
||||
api := httpapi.New(mux, buildinfo.Version, cfg.AdminTokenSHA256)
|
||||
|
||||
runtime.RegisterBuiltinClasses()
|
||||
settings := governance.NewModule(db, log.With("module", "governance"), orgID)
|
||||
mux := http.NewServeMux()
|
||||
api := httpapi.New(mux, buildinfo.Version, settings.Authenticator(cfg.AdminTokenSHA256), settings)
|
||||
|
||||
conns, err := connectors.NewModule(db, log.With("module", "connectors"), orgID, connectors.Sealing{
|
||||
conns, err := connectors.NewModule(db, log.With("module", "connectors"), connectors.Sealing{
|
||||
Identity: cfg.AgeIdentity, Backups: cfg.AgeBackupRecipients,
|
||||
})
|
||||
}, filepath.Join(cfg.StateDir, "extensions"))
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
defer conns.Close()
|
||||
if err := conns.Start(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
checks.Register("connectors", conns.Ready)
|
||||
// A model's key is a credential name resolved through the sealed store.
|
||||
settings.UseCredentials(conns)
|
||||
// A model's key is a credential id resolved through the sealed store in
|
||||
// organisation scope with no person attached.
|
||||
settings.UseCredentials(orgCredentials{conns: conns, orgID: string(governance.DefaultOrgID)})
|
||||
// An account links a channel account on the connectors that can link.
|
||||
settings.UseChannels(conns)
|
||||
// A model's window comes from the published catalogue, cached under the
|
||||
// state directory so a restart reads it from disk.
|
||||
settings.UseModelCatalogue(filepath.Join(cfg.StateDir, "model-catalogue.json"))
|
||||
|
||||
sys := system.New(system.Bootstrap{
|
||||
Listen: cfg.Listen, Database: DatabaseHost(cfg.Database.URL), Schemas: len(schemas),
|
||||
@@ -92,74 +181,117 @@ func Run(ctx context.Context, configPath string) error {
|
||||
tell := deliveries.NewModule(db, log.With("module", "deliveries"), orgID, live, conns)
|
||||
|
||||
engine := runs.New(db, log.With("module", "runs"), runs.Options{Owner: owner()})
|
||||
talk := chat.NewModule(db, log.With("module", "chat"), orgID, live)
|
||||
// A workflow takes its context from the run handle, as a handler takes it
|
||||
// from the request.
|
||||
classes := judgement.NewClasses(db, log.With("module", "judgement"), orgID)
|
||||
actionTypes := judgement.NewActionTypes(db, log.With("module", "judgement"), orgID)
|
||||
// An approval request is carried by deliveries, and its answer wakes the run
|
||||
// that is waiting on it.
|
||||
allow := approvals.NewModule(db, log.With("module", "approvals"), orgID, tell, engine, classes, settings, settings)
|
||||
allow := approvals.NewModule(db, log.With("module", "approvals"), orgID, tell, answers{chat: talk, runs: engine}, actionTypes, settings, settings)
|
||||
// Approving an action that can't be undone needs a fresh passkey assertion.
|
||||
allow.UseConfirmer(settings)
|
||||
policies := judgement.NewPolicies(db, log.With("module", "judgement"), orgID)
|
||||
// An answer a channel delivers is an event, and settles its request.
|
||||
hear := events.NewModule(db, log.With("module", "events"), orgID, conns, engine, allow, tell)
|
||||
hear.Routes(mux)
|
||||
judge := newJudgement(db, log, conns, classes, policies, settings, hear)
|
||||
if err := useWorkflows(ctx, engine, runs.Deps{Settings: settings, Toolbox: conns, Judge: judge, Approver: allow, Notifier: tell, Memory: memory.NewModule(db, orgID)}); err != nil {
|
||||
return err
|
||||
sealer, err := seal.New(cfg.AgeIdentity, cfg.AgeBackupRecipients)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hear := events.NewModule(db, log.With("module", "events"), orgID, sealer, conns, engine, allow, settings, tell)
|
||||
hear.Routes(mux)
|
||||
engine.UseReferrers(hear)
|
||||
judge := newJudgement(db, log, conns, actionTypes, policies, settings, hear)
|
||||
// The record of deletions outlives this process and its database, so the
|
||||
// log exists before anything can be deleted: an instance that has run this
|
||||
// release and lost its log is a different case from one that never deleted.
|
||||
ledger := deletions.NewLog(deletions.Path(cfg.StateDir))
|
||||
if err := ledger.Ensure(); err != nil {
|
||||
return nil, fmt.Errorf("prepare the deletion record: %w", err)
|
||||
}
|
||||
remember := memory.NewModule(db, orgID, log.With("module", "memory"), ledger)
|
||||
checks.Register("deletion record", func(context.Context) error {
|
||||
if remember.RecordPending() {
|
||||
return errors.New("a deletion is committed and its record is still being written")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
proposed := proposals.NewModule(db, log.With("module", "proposals"), orgID, hear, engine, policies, judge)
|
||||
// A cause that keeps recurring becomes a root-cause proposal.
|
||||
remember.UseProposals(proposed)
|
||||
// Approving an action that can't be undone needs a fresh passkey assertion.
|
||||
proposed.UseConfirmer(settings)
|
||||
sys.UseHealth(healthSources(checks, conns, engine, allow, settings, hear))
|
||||
apiModules{
|
||||
settings: settings, conns: conns, system: sys, tell: tell, allow: allow, classes: classes, policies: policies,
|
||||
hear: hear, judge: judge, engine: engine, drafts: drafts.NewModule(db, log.With("module", "drafts"), orgID, hear, engine, policies),
|
||||
settings: settings, conns: conns, system: sys, tell: tell, allow: allow, actionTypes: actionTypes, policies: policies,
|
||||
hear: hear, judge: judge, engine: engine, chat: talk, proposals: proposed,
|
||||
notes: remember, live: live,
|
||||
}.register(api)
|
||||
dashboard.Routes(mux, ui.DistDirFS)
|
||||
|
||||
return serveWithWork(ctx, log, cfg.Listen, mux, engine.Work, hear.Work, tell.Work)
|
||||
g := newGate(mux, ui.DistDirFS)
|
||||
return &binary{
|
||||
db: db, conns: conns, gate: g, served: serveSurface(checks, g), settings: settings,
|
||||
ops: &operations{
|
||||
log: log, checks: checks, settings: settings, conns: conns, engine: engine, hear: hear,
|
||||
tell: tell, talk: talk, judge: judge, allow: allow, remember: remember, proposed: proposed,
|
||||
completeRecord: func(ctx context.Context) (int, error) {
|
||||
return memory.Reconcile(ctx, db, cfg.StateDir)
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// serveWithWork serves mux while the loops run, and stops the loops once it
|
||||
// returns.
|
||||
func serveWithWork(ctx context.Context, log *slog.Logger, addr string, mux *http.ServeMux, loops ...func(context.Context)) error {
|
||||
ctx, stop := context.WithCancel(ctx)
|
||||
defer stop()
|
||||
wait := work(ctx, loops...)
|
||||
err := serve(ctx, log, addr, mux)
|
||||
stop()
|
||||
wait()
|
||||
return err
|
||||
// close stops the connectors and then the database.
|
||||
func (b *binary) close() {
|
||||
b.conns.Close()
|
||||
_ = b.db.Close()
|
||||
}
|
||||
|
||||
// useWorkflows gives the engine what workflow steps use and installs the
|
||||
// workflow that ships with the binary.
|
||||
func useWorkflows(ctx context.Context, engine *runs.Engine, deps runs.Deps) error {
|
||||
engine.Use(deps)
|
||||
if _, err := engine.Install(ctx, orgID, "investigate", runs.InvestigateDocument(), "starter"); err != nil {
|
||||
return fmt.Errorf("install the investigate workflow: %w", err)
|
||||
// orgCredentials confines every model-provider credential lookup to orgID with
|
||||
// no person attached, so a caller's personal credentials are never reachable.
|
||||
type orgCredentials struct {
|
||||
conns *connectors.Module
|
||||
orgID string
|
||||
}
|
||||
|
||||
func (c orgCredentials) BearerTokenByID(ctx context.Context, id uuid.UUID) (string, error) {
|
||||
return c.conns.BearerTokenByID(connectors.WithScope(ctx, connectors.Scope{OrgID: c.orgID}), id)
|
||||
}
|
||||
|
||||
func (c orgCredentials) BearerCredentialName(ctx context.Context, id uuid.UUID) (string, bool, error) {
|
||||
return c.conns.BearerCredentialName(connectors.WithScope(ctx, connectors.Scope{OrgID: c.orgID}), id)
|
||||
}
|
||||
|
||||
func (c orgCredentials) BearerCredentialNames(ctx context.Context) (map[uuid.UUID]string, error) {
|
||||
return c.conns.BearerCredentialNames(connectors.WithScope(ctx, connectors.Scope{OrgID: c.orgID}))
|
||||
}
|
||||
|
||||
// answers wakes whatever asked for an approval: a chat turn, or else the run
|
||||
// waiting on it.
|
||||
type answers struct {
|
||||
chat *chat.Module
|
||||
runs *runs.Engine
|
||||
}
|
||||
|
||||
func (a answers) Signal(ctx context.Context, id uuid.UUID, key string, payload jsontext.Value) error {
|
||||
if ours, err := a.chat.Signal(ctx, id, key, payload); err != nil || ours {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// work runs each loop until ctx ends and returns a function that waits for
|
||||
// them all.
|
||||
func work(ctx context.Context, loops ...func(context.Context)) func() {
|
||||
var workers sync.WaitGroup
|
||||
for _, loop := range loops {
|
||||
workers.Go(func() { loop(ctx) })
|
||||
}
|
||||
return workers.Wait
|
||||
return a.runs.Signal(ctx, id, key, payload)
|
||||
}
|
||||
|
||||
// newJudgement returns the judgement module with its hard rules, data guards
|
||||
// and change-request rules. A failed action tightens its class.
|
||||
func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, classes *judgement.Classes, policies *judgement.Policies, settings *governance.Module, heard judgement.Events) *judgement.Module {
|
||||
// and change-request rules. A failed action tightens its action type.
|
||||
func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, actionTypes *judgement.ActionTypes, policies *judgement.Policies, settings *governance.Module, heard judgement.Events) *judgement.Module {
|
||||
guards := []judgement.Guard{
|
||||
judgement.Impact{Lookup: judgement.RecordedFacts{Source: conns, People: settings}, Defaults: settings},
|
||||
judgement.Impact{Lookup: judgement.RecordedFacts{Source: conns, Accounts: settings}, Defaults: settings},
|
||||
judgement.Reversibility{},
|
||||
judgement.Precedent{Classes: classes},
|
||||
judgement.Precedent{ActionTypes: actionTypes},
|
||||
judgement.Provenance{Events: heard},
|
||||
judgement.Timing{Calendar: settings},
|
||||
judgement.Cost{Budgets: settings, Counts: judgement.NewSpend(db, orgID)},
|
||||
judgement.Freeze{Freezes: settings},
|
||||
}
|
||||
judge := judgement.NewModule(db, log.With("module", "judgement"), orgID, conns, []judgement.HardRule{policies}, guards, classes)
|
||||
judge := judgement.NewModule(db, log.With("module", "judgement"), orgID, conns, []judgement.HardRule{policies}, guards, actionTypes)
|
||||
judge.UseExtensions(conns)
|
||||
judge.UseChangeRules(policies)
|
||||
return judge
|
||||
@@ -169,7 +301,7 @@ func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, class
|
||||
const orgID = "default"
|
||||
|
||||
// schemas are the module schemas the runtime role is granted DML on.
|
||||
var schemas = []string{"runs", "connectors", "events", "governance", "deliveries", "judgement", "approvals", "memory", "drafts"}
|
||||
var schemas = []string{"runs", "connectors", "events", "governance", "deliveries", "judgement", "approvals", "memory", "alerts", "proposals", "chat"}
|
||||
|
||||
// owner names this process in run leases.
|
||||
func owner() string {
|
||||
|
||||
@@ -837,7 +837,7 @@ func (b *boot) addCleanup(fn func()) {
|
||||
|
||||
func (b *boot) catalogState() modelcatalog.Snapshot { return b.catalog.State() }
|
||||
|
||||
// loadCatalog layers the model catalog under the file config. A catalog that
|
||||
// loadCatalog layers the model catalogue under the file config. A catalogue that
|
||||
// cannot be read leaves the configured providers and models in effect.
|
||||
func (b *boot) loadCatalog(ctx context.Context) {
|
||||
snapshot, err := b.catalog.Fetch(ctx, b.secrets.Getenv, b.cfgHolder.Get().Providers)
|
||||
@@ -846,7 +846,7 @@ func (b *boot) loadCatalog(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
models := modelcatalog.Apply(&b.cfg, snapshot)
|
||||
// Layer the catalog over the live config, not b.cfg: b.cfg predates the
|
||||
// Layer the catalogue over the live config, not b.cfg: b.cfg predates the
|
||||
// execution-settings watch, so publishing it would put the file's budgets
|
||||
// back over the control plane's.
|
||||
live := b.cfgHolder.Get().Clone()
|
||||
|
||||
@@ -47,10 +47,10 @@ func (b *boot) loadRuntimeConfig(ctx context.Context) error {
|
||||
// cannot answer aborts the reload: the running config already holds those
|
||||
// values, so publishing the file's over them is the worse outcome.
|
||||
func (b *boot) reloadConfig(ctx context.Context, doc *configuration.Document) error {
|
||||
// Boot merges catalog-discovered providers into cfg before the
|
||||
// Boot merges catalogue-discovered providers into cfg before the
|
||||
// Holders are seeded; publishing the raw reloaded document would
|
||||
// drop them from the running config even though the file is
|
||||
// unchanged. Re-apply the same merge (idempotent: a catalog that
|
||||
// unchanged. Re-apply the same merge (idempotent: a catalogue that
|
||||
// failed to load merges to identity).
|
||||
catalog := b.catalogState()
|
||||
modelcatalog.Apply(&doc.Config, catalog)
|
||||
@@ -376,8 +376,8 @@ func (b *boot) applyRuntimeResourceUpdate(ctx context.Context, kind string, upda
|
||||
}
|
||||
}
|
||||
base := b.cfgHolder.Get()
|
||||
// Boot publishes before the model catalog is merged in, so the snapshot
|
||||
// this read returns can lack the catalog's model limits and discovered
|
||||
// Boot publishes before the model catalogue is merged in, so the snapshot
|
||||
// this read returns can lack the catalogue's model limits and discovered
|
||||
// providers. The merge is idempotent, and reloadConfig re-applies it
|
||||
// before layering for the same reason.
|
||||
catalog := b.catalogState()
|
||||
|
||||
@@ -194,7 +194,7 @@ func Run() int { //nolint:cyclop,funlen // the composition root's setup sequence
|
||||
go presence.Run(ctx, b.processName, servicekit.Build(), ps, b.healthRegistry, b.log)
|
||||
b.reportBrokerPresence(ctx, ps)
|
||||
}
|
||||
// The daemon publishes the configuration view, which carries the catalog's
|
||||
// The daemon publishes the configuration view, which carries the catalogue's
|
||||
// model limits.
|
||||
b.startModelCatalogRefresh(ctx)
|
||||
b.buildWorktreeManager()
|
||||
|
||||
@@ -65,7 +65,7 @@ func TestOpenShellModelEgressHoldsKeysOnTheGateway(t *testing.T) {
|
||||
wantKeys map[string]string // key env -> real key held on the gateway
|
||||
wantHosts []string
|
||||
wantPorts []int // defaults to 443 for each host
|
||||
wantHeader string // header the profile places the key in; empty means a bearer token
|
||||
wantHeader string // header that carries the key; empty means a bearer token
|
||||
}{
|
||||
{
|
||||
name: "secret reference",
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
configtemplate "github.com/samcharles93/archie-core"
|
||||
@@ -76,7 +77,7 @@ func bindSetupFlags(fs *flag.FlagSet) *setupFlags {
|
||||
fs.StringVar(&f.operator, "operator", "", "operator display name (optional)")
|
||||
fs.StringVar(&f.forgeType, "forge-type", "", "forge type: github | gitea | none")
|
||||
fs.StringVar(&f.forgeHost, "forge-host", "", "forge base URL")
|
||||
fs.StringVar(&f.provider, "provider", "", "LLM provider class: openai | anthropic | openrouter | gemini | groq | deepseek | mistral | ollama")
|
||||
fs.StringVar(&f.provider, "provider", "", "LLM provider: "+strings.Join(setup.ProviderNames(), " | "))
|
||||
fs.StringVar(&f.model, "model", "", "bare model name; the provider class prefix is added automatically")
|
||||
fs.StringVar(&f.telegramUserIDs, "telegram-user-ids", "", "comma-separated allowed Telegram user IDs; configuring Telegram requires at least one")
|
||||
// References, not values: engine:key names where a secret already lives, and
|
||||
|
||||
@@ -31,7 +31,7 @@ func stepVocabulary() (*workflow.Manager, error) { return workflowsteps.NewManag
|
||||
// (main.go's Run) before buildDaemon captures the client.
|
||||
//
|
||||
// It is deliberately not part of openStateStoreAdapter, which the gateway root
|
||||
// shares: the gateway reads catalog, runtime settings and SOUL, never a
|
||||
// shares: the gateway reads catalogue, runtime settings and SOUL, never a
|
||||
// workflow definition, so registering a vocabulary there would be the dead
|
||||
// vocabulary this shape removed from internal/app/archiemessaging -- a root that
|
||||
// cannot consume it must not be failed by it.
|
||||
|
||||
@@ -72,8 +72,15 @@ func (d stateDatabase) Backup(ctx context.Context, out string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Restore puts the pre-update snapshot back. Rollback is set because this is the
|
||||
// update transaction rolling itself back: the snapshot is this host's own dump
|
||||
// from minutes earlier, so the deletions that must be applied to it are read from
|
||||
// the difference between it and the live data. An operator restoring by hand goes
|
||||
// through the command, which does not set it.
|
||||
func (d stateDatabase) Restore(ctx context.Context, from string) error {
|
||||
_, err := statestore.RunRecovery(ctx, statestore.RecoveryOptions{Operation: statestore.RecoveryRestore, From: from, Config: d.configPath})
|
||||
_, err := statestore.RunRecovery(ctx, statestore.RecoveryOptions{
|
||||
Operation: statestore.RecoveryRestore, From: from, Config: d.configPath, Rollback: true,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
)
|
||||
|
||||
// chatModelManager owns the model selection for interactive chat. Named
|
||||
// aliases remain defaults; choosing a catalog model does not rewrite them
|
||||
// aliases remain defaults; choosing a catalogue model does not rewrite them
|
||||
// or affect workflow steps.
|
||||
type chatModelManager struct {
|
||||
mu sync.RWMutex
|
||||
@@ -43,7 +43,7 @@ func (m *chatModelManager) SetConfigured(aliases map[string]string) {
|
||||
}
|
||||
|
||||
// SetModelCatalog replaces the provider display names and per-model details
|
||||
// the catalog publishes.
|
||||
// the catalogue publishes.
|
||||
func (m *chatModelManager) SetModelCatalog(snapshot modelcatalog.Snapshot) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
@@ -174,7 +174,7 @@ func (m *chatModelManager) ModelFor(ctx context.Context) (string, error) {
|
||||
}
|
||||
|
||||
// refsLocked keeps tenant choices within their assigned aliases; the system
|
||||
// org can also select from its credential-filtered provider catalog.
|
||||
// org can also select from its credential-filtered provider catalogue.
|
||||
func (m *chatModelManager) refsLocked(id org.OrgID, aliases map[string]string) []string {
|
||||
if id != org.DefaultOrgID {
|
||||
return chatModelRefs(aliases, nil)
|
||||
|
||||
@@ -200,7 +200,7 @@ func (m *preparedChatTurnModel) Generate(
|
||||
// This is one provider response's output allowance, not a turn-
|
||||
// continuation budget. Tool loops remain free to continue. The ai-sdk
|
||||
// runtime picks max_completion_tokens or max_tokens from the model's
|
||||
// catalog metadata.
|
||||
// catalogue metadata.
|
||||
options.MaxTokens = request.MaxOutputTokens
|
||||
// A runtime swapped to nil -- a live update that left no usable provider
|
||||
// configured -- is a refused turn, not a panic.
|
||||
|
||||
@@ -93,7 +93,7 @@ func (s curatorEventSink) Emit(kind, detail string, data map[string]any) {
|
||||
|
||||
// actingPrincipal resolves the identity the instance acts as for automated
|
||||
// work (the default chat identity, falling back to the bot user), so curator
|
||||
// passes authorize guarded tools exactly as that identity would.
|
||||
// passes authorise guarded tools exactly as that identity would.
|
||||
func (b *server) actingPrincipal(ctx context.Context) (access.Principal, error) {
|
||||
name := b.defaultChatIdentity
|
||||
if name == "" {
|
||||
|
||||
@@ -260,7 +260,7 @@ func (b *server) waitForNATSEndpoint(ctx context.Context) (servicekit.NATSEndpoi
|
||||
|
||||
func (b *server) catalogState() modelcatalog.Snapshot { return b.catalog.State() }
|
||||
|
||||
// loadCatalog layers the model catalog under the running config. A catalog
|
||||
// loadCatalog layers the model catalogue under the running config. A catalogue
|
||||
// that cannot be read leaves the configured providers and models in effect.
|
||||
func (b *server) loadCatalog(ctx context.Context) {
|
||||
snapshot, err := b.catalog.Fetch(ctx, b.secrets.Getenv, b.cfg.Providers)
|
||||
|
||||
@@ -70,7 +70,7 @@ func (b *server) refreshSkills(ctx context.Context, applied *string) {
|
||||
}
|
||||
|
||||
// storedSkills reads the skills resource, leaving out any name already in
|
||||
// have. An unreadable resource leaves the running catalog in place.
|
||||
// have. An unreadable resource leaves the running catalogue in place.
|
||||
func (b *server) storedSkills(ctx context.Context, have []skill.CatalogEntry) ([]skill.CatalogEntry, int64, error) {
|
||||
var out []skill.CatalogEntry
|
||||
version, _, err := b.controlPlane.Query(ctx, controlplanestore.SkillsKind, func(value []byte) error {
|
||||
|
||||
@@ -27,7 +27,7 @@ type ServiceTarget struct {
|
||||
|
||||
// Options is the UI-owned input DTO. It carries process-local settings and
|
||||
// endpoint references only -- there is deliberately no config.Config,
|
||||
// config.Holder, forge credential, model catalog or workflow routing field
|
||||
// config.Holder, forge credential, model catalogue or workflow routing field
|
||||
// for daemon configuration to arrive through.
|
||||
type Options struct {
|
||||
// Config and Overlay name the configuration source the process reads a
|
||||
|
||||
@@ -63,7 +63,7 @@ const controlPlaneWatchHealthyMultiple = 2
|
||||
// deliberately: that version is unusable to this build, and resuming before it
|
||||
// would re-offer it on every reconnect for the life of the process. Only a
|
||||
// cancellation stops the loop, and the loop watches for it itself, so shutdown
|
||||
// is prompt however long the current backoff is and whether or not the stream
|
||||
// is prompt however long the current backoff is and whether the stream
|
||||
// is still open.
|
||||
//
|
||||
// The reconnect delay is decided by the attempt that just ended, and only by
|
||||
|
||||
@@ -69,6 +69,17 @@ type RecoveryOptions struct {
|
||||
// Revision is the revision rollback replays. Zero means the newest
|
||||
// revision older than the one the resource carries now.
|
||||
Revision int64
|
||||
// AcceptUnrecordedDeletions acknowledges that a restore may not account for
|
||||
// every deletion this data has seen, so forgotten notes may return. It is
|
||||
// only ever set by an operator asking for it, never by an automatic update.
|
||||
AcceptUnrecordedDeletions bool
|
||||
// Rollback marks the update transaction's own rollback, where the snapshot is
|
||||
// this host's pre-update dump taken minutes earlier, and the deletions the
|
||||
// restore has to apply are read from the difference between the snapshot and
|
||||
// the data it replaces rather than from the witness table. Only the updater
|
||||
// sets it: no command exposes it, and it is not an acknowledgement of
|
||||
// anything.
|
||||
Rollback bool
|
||||
}
|
||||
|
||||
// RunRecovery performs one offline operation on the task database and
|
||||
|
||||
@@ -2,12 +2,26 @@ package statestore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/platform/deletions"
|
||||
"github.com/samcharles93/archie-core/modules/memory"
|
||||
)
|
||||
|
||||
// runPostgresRecovery performs one recovery operation on the PostgreSQL
|
||||
@@ -36,13 +50,7 @@ func runPostgresRecovery(ctx context.Context, options RecoveryOptions) (string,
|
||||
}
|
||||
return "backed up the whole database to " + options.Out, nil
|
||||
case RecoveryRestore:
|
||||
if options.From == "" {
|
||||
return "", errors.New("restore requires -from")
|
||||
}
|
||||
if err := postgres.Restore(ctx, url, options.From); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("restored the whole database from %s; every write made after the snapshot is gone; start the archie services again", options.From), nil
|
||||
return restorePostgres(ctx, url, options, cfg.StateDir)
|
||||
case RecoveryValidate:
|
||||
return validatePostgres(ctx, url, options)
|
||||
case RecoveryRollback:
|
||||
@@ -55,6 +63,309 @@ func runPostgresRecovery(ctx context.Context, options RecoveryOptions) (string,
|
||||
}
|
||||
}
|
||||
|
||||
// restorePostgres replaces the database with the snapshot, refusing first when the
|
||||
// data cannot show the restore is safe.
|
||||
func restorePostgres(ctx context.Context, url string, options RecoveryOptions, stateDir string) (string, error) {
|
||||
if options.From == "" {
|
||||
return "", errors.New("restore requires -from")
|
||||
}
|
||||
dir, err := deletions.Dir(stateDir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// One reading of the record inside the restore's window serves both the check
|
||||
// and the replay, so what was proved safe is what is applied.
|
||||
var recorded []memory.NoteKey
|
||||
if err := postgres.Restore(ctx, url, options.From,
|
||||
func(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
var err error
|
||||
if recorded, err = memory.RecordedNotes(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
if options.Rollback {
|
||||
return requireRollbackReplaysDeletions(ctx, pool, options.From, recorded)
|
||||
}
|
||||
return requireAccountedDeletions(ctx, pool, options.From, recorded, dir, options.AcceptUnrecordedDeletions)
|
||||
},
|
||||
func() (string, error) { return memory.DeletionStatements(recorded), nil }); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("restored the whole database from %s; every write made after the snapshot is gone, and %d recorded deletions were applied again; start the archie services again",
|
||||
options.From, len(recorded)), nil
|
||||
}
|
||||
|
||||
// fileDigest hashes a file without reading it into memory: snapshots of a real
|
||||
// instance are far larger than a process should hold to checksum one.
|
||||
func fileDigest(path string) (string, error) {
|
||||
file, err := os.Open(path) //nolint:gosec // the snapshot the operator named.
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read the snapshot: %w", err)
|
||||
}
|
||||
defer func() { _ = file.Close() }()
|
||||
hash := sha256.New()
|
||||
if _, err := io.Copy(hash, file); err != nil {
|
||||
return "", fmt.Errorf("read the snapshot: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(hash.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// requireAccountedDeletions refuses a restore the record outside the database
|
||||
// cannot account for, and refuses by default when it cannot say whether the data
|
||||
// has seen deletions it does not know about. Freshness cannot be proved from this
|
||||
// data alone: a snapshot and the record from the same backup match perfectly while
|
||||
// later deletions are absent from both, so an operator's acknowledgement is the
|
||||
// only way past a case where accounting is incomplete. It runs before anything is
|
||||
// replaced.
|
||||
func requireAccountedDeletions(ctx context.Context, pool *pgxpool.Pool, from string, recorded []memory.NoteKey, dir string, accepted bool) error {
|
||||
facts, err := gatherRestoreFacts(ctx, pool, from, recorded, dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if accepted {
|
||||
return acknowledge(ctx, from, dir, len(facts.unaccounted))
|
||||
}
|
||||
return refuseUnaccounted(facts, from, deletions.Path(dir))
|
||||
}
|
||||
|
||||
// restoreFacts is what the check can learn before anything is replaced: what the
|
||||
// target and the snapshot witnessed, whether the record outside the database is
|
||||
// still there, and which witnesses it does not list.
|
||||
type restoreFacts struct {
|
||||
live []memory.Witness
|
||||
snapshot []memory.Witness
|
||||
ledgerExists bool
|
||||
unaccounted []memory.Witness
|
||||
}
|
||||
|
||||
// gatherRestoreFacts reads the witnesses from the target database and the
|
||||
// snapshot, and compares them with the record outside the database.
|
||||
func gatherRestoreFacts(ctx context.Context, pool *pgxpool.Pool, from string, recorded []memory.NoteKey, dir string) (restoreFacts, error) {
|
||||
db := sqlx.NewDb(stdlib.OpenDBFromPool(pool), "pgx")
|
||||
var facts restoreFacts
|
||||
records, err := memory.HasWitnessTable(ctx, db)
|
||||
if err != nil {
|
||||
return restoreFacts{}, err
|
||||
}
|
||||
// A database that has never recorded a deletion has no witness table to read.
|
||||
if records {
|
||||
if facts.live, err = memory.Witnesses(ctx, db); err != nil {
|
||||
return restoreFacts{}, fmt.Errorf("read the committed deletions: %w", err)
|
||||
}
|
||||
}
|
||||
if facts.snapshot, _, err = snapshotWitnesses(ctx, from); err != nil {
|
||||
return restoreFacts{}, err
|
||||
}
|
||||
facts.unaccounted = memory.Unaccounted(slices.Concat(facts.live, facts.snapshot), recorded)
|
||||
if facts.ledgerExists, err = deletions.NewLog(deletions.Path(dir)).Exists(); err != nil {
|
||||
return restoreFacts{}, err
|
||||
}
|
||||
return facts, nil
|
||||
}
|
||||
|
||||
// refuseUnaccounted refuses a restore the record outside the database cannot
|
||||
// account for. Nothing it reads can prove the record is current, so every doubt
|
||||
// it cannot settle is a refusal, and an operator's acknowledgement is the one way
|
||||
// past one.
|
||||
func refuseUnaccounted(facts restoreFacts, from, recordPath string) error {
|
||||
// With no record there is nothing to compare, and every deletion this
|
||||
// instance ever made is unaccounted for.
|
||||
if !facts.ledgerExists {
|
||||
return fmt.Errorf("%w: the record outside the database, %s, is missing, so nothing here can show what this data has deleted. Restore the current record, or pass -accept-unrecorded-deletions to accept that forgotten notes may return",
|
||||
ErrUnaccountedDeletions, recordPath)
|
||||
}
|
||||
// The target's own witnesses are the only evidence here about this data's
|
||||
// history that does not come from the snapshot. With none, nothing can show
|
||||
// what was deleted after the snapshot was taken: a fresh target and a target
|
||||
// that has genuinely never deleted a note look the same, so the operator has
|
||||
// to say which it is.
|
||||
if len(facts.live) == 0 {
|
||||
return fmt.Errorf("%w: this database has not recorded a deletion of its own, so nothing here can show what was deleted after %s was taken, and forgotten notes may return. Restore the record that belongs with the snapshot, or pass -accept-unrecorded-deletions to accept that risk",
|
||||
ErrUnaccountedDeletions, from)
|
||||
}
|
||||
if len(facts.unaccounted) > 0 {
|
||||
return fmt.Errorf("%w: the record outside the database does not list %d deletion(s) this data has seen, so a restore would bring forgotten notes back. Restore the current record, or pass -accept-unrecorded-deletions to accept that risk",
|
||||
ErrUnaccountedDeletions, len(facts.unaccounted))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// rollbackFacts is what the update transaction's rollback compares: the notes its
|
||||
// own snapshot holds, the notes the database holds now, and the deletions the
|
||||
// record lists.
|
||||
type rollbackFacts struct {
|
||||
snapshotHasNotes bool
|
||||
snapshot []memory.NoteKey
|
||||
live []memory.NoteKey
|
||||
recorded []memory.NoteKey
|
||||
}
|
||||
|
||||
// requireRollbackReplaysDeletions proves a rollback safe from the data alone. The
|
||||
// snapshot was taken by this host minutes earlier, so every note it holds and the
|
||||
// database no longer has was deleted since, and applying those deletions to the
|
||||
// snapshot is exactly what stops the rollback bringing them back. That proof does
|
||||
// not rest on the witness table, which a migration may have emptied, so it holds
|
||||
// with no witnesses at all; what it does need is every one of those deletions in
|
||||
// the record, because the record is what the restore replays.
|
||||
func requireRollbackReplaysDeletions(ctx context.Context, pool *pgxpool.Pool, from string, recorded []memory.NoteKey) error {
|
||||
db := sqlx.NewDb(stdlib.OpenDBFromPool(pool), "pgx")
|
||||
facts := rollbackFacts{recorded: recorded}
|
||||
var err error
|
||||
if facts.snapshotHasNotes, err = postgres.SnapshotHasTable(ctx, from, "memory.notes"); err != nil {
|
||||
return err
|
||||
}
|
||||
if facts.snapshotHasNotes {
|
||||
if facts.snapshot, err = snapshotNoteKeys(ctx, from); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if facts.live, err = memory.LiveNoteKeys(ctx, db); err != nil {
|
||||
return err
|
||||
}
|
||||
return refuseUnsafeRollback(facts, from)
|
||||
}
|
||||
|
||||
// refuseUnsafeRollback refuses a rollback the data cannot show to be safe.
|
||||
func refuseUnsafeRollback(facts rollbackFacts, from string) error {
|
||||
// A snapshot from before the notes table existed would replace a database that
|
||||
// has notes with one that has none, and holds nothing to compare.
|
||||
if !facts.snapshotHasNotes {
|
||||
if len(facts.live) > 0 {
|
||||
return fmt.Errorf("%w: %s holds no notes table and this database holds %d note(s), so the rollback would drop them with nothing to show what it did",
|
||||
deletions.ErrUnsafeRollback, from, len(facts.live))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
live := make(map[memory.NoteKey]bool, len(facts.live))
|
||||
for _, key := range facts.live {
|
||||
live[key] = true
|
||||
}
|
||||
recorded := make(map[memory.NoteKey]bool, len(facts.recorded))
|
||||
for _, key := range facts.recorded {
|
||||
recorded[key] = true
|
||||
}
|
||||
unrecorded := 0
|
||||
for _, key := range facts.snapshot {
|
||||
if live[key] || recorded[key] {
|
||||
continue
|
||||
}
|
||||
unrecorded++
|
||||
}
|
||||
if unrecorded > 0 {
|
||||
return fmt.Errorf("%w: %s holds %d note(s) this database no longer has and the record does not list, so a rollback would bring them back",
|
||||
deletions.ErrUnsafeRollback, from, unrecorded)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// snapshotNoteKeys reads the notes an archive holds. Only the two columns a note
|
||||
// is identified by are read, so a snapshot from before the memory schema was
|
||||
// scoped can still be compared.
|
||||
func snapshotNoteKeys(ctx context.Context, from string) ([]memory.NoteKey, error) {
|
||||
columns, rows, err := postgres.SnapshotRows(ctx, from, "memory.notes")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
idAt, ok := postgres.Column(columns, "id")
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("postgres: snapshot %s: the notes table has no id", from)
|
||||
}
|
||||
orgAt, ok := postgres.Column(columns, "org_id")
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("postgres: snapshot %s: the notes table has no organisation", from)
|
||||
}
|
||||
out := make([]memory.NoteKey, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if len(row) <= max(idAt, orgAt) {
|
||||
return nil, fmt.Errorf("postgres: snapshot %s: a note is missing a column", from)
|
||||
}
|
||||
id, err := uuid.Parse(strings.TrimSpace(row[idAt]))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("postgres: snapshot %s: read a note: %w", from, err)
|
||||
}
|
||||
out = append(out, memory.NoteKey{OrgID: strings.TrimSpace(row[orgAt]), ID: id})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// acknowledge records that an operator chose to restore data the record cannot
|
||||
// account for. The acknowledgement is written beside the record rather than
|
||||
// instead of anything, so the evidence of what was lost survives.
|
||||
func acknowledge(ctx context.Context, from, dir string, unaccounted int) error {
|
||||
digest, err := fileDigest(from)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
line, err := json.Marshal(map[string]any{
|
||||
"acknowledged_at": time.Now().UTC(),
|
||||
"snapshot": filepath.Base(from),
|
||||
"snapshot_sha256": digest,
|
||||
"unaccounted_deletions": unaccounted,
|
||||
"consequence": "forgotten notes may return",
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
path := filepath.Join(dir, "deletions-acknowledged.jsonl")
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return fmt.Errorf("record the acknowledgement: %w", err)
|
||||
}
|
||||
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) //nolint:gosec // the state directory.
|
||||
if err != nil {
|
||||
return fmt.Errorf("record the acknowledgement: %w", err)
|
||||
}
|
||||
defer func() { _ = file.Close() }()
|
||||
if _, err := file.Write(append(line, '\n')); err != nil {
|
||||
return fmt.Errorf("record the acknowledgement: %w", err)
|
||||
}
|
||||
if err := file.Sync(); err != nil {
|
||||
return fmt.Errorf("record the acknowledgement: %w", err)
|
||||
}
|
||||
// The acknowledgement is evidence, so its name and the directory holding it
|
||||
// have to be as durable as the line itself.
|
||||
return deletions.SyncFileDirs(path)
|
||||
}
|
||||
|
||||
// ErrUnaccountedDeletions is returned when a restore cannot account for deletions
|
||||
// the data has seen.
|
||||
var ErrUnaccountedDeletions = errors.New("the record of deletions does not account for this data")
|
||||
|
||||
// snapshotWitnesses reads the deletions a snapshot's own database witnessed. A
|
||||
// snapshot from before the witness existed reports false: it never recorded any.
|
||||
func snapshotWitnesses(ctx context.Context, from string) ([]memory.Witness, bool, error) {
|
||||
const table = "memory.deletion_witness"
|
||||
holds, err := postgres.SnapshotHasTable(ctx, from, table)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if !holds {
|
||||
return nil, false, nil
|
||||
}
|
||||
columns, rows, err := postgres.SnapshotRows(ctx, from, table)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
noteAt, ok := postgres.Column(columns, "note_id")
|
||||
if !ok {
|
||||
return nil, false, fmt.Errorf("postgres: snapshot %s: the deletion witness has no note id", from)
|
||||
}
|
||||
orgAt, ok := postgres.Column(columns, "org_id")
|
||||
if !ok {
|
||||
return nil, false, fmt.Errorf("postgres: snapshot %s: the deletion witness has no organisation", from)
|
||||
}
|
||||
out := make([]memory.Witness, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if len(row) <= max(noteAt, orgAt) {
|
||||
return nil, false, fmt.Errorf("postgres: snapshot %s: a deletion witness is missing a column", from)
|
||||
}
|
||||
id, err := uuid.Parse(strings.TrimSpace(row[noteAt]))
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("postgres: snapshot %s: read a deletion witness: %w", from, err)
|
||||
}
|
||||
out = append(out, memory.Witness{NoteID: id, OrgID: strings.TrimSpace(row[orgAt])})
|
||||
}
|
||||
return out, true, nil
|
||||
}
|
||||
|
||||
// openRecoveryPool opens the database without migrating it: recovery inspects
|
||||
// or repairs the schema it finds, and refuses one newer than this binary.
|
||||
func openRecoveryPool(ctx context.Context, url string) (*pgxpool.Pool, int64, error) {
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
package statestore
|
||||
|
||||
import (
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/deletions"
|
||||
"github.com/samcharles93/archie-core/modules/memory"
|
||||
)
|
||||
|
||||
// TestRestoreRefusesAnIncompleteRecord guards the privacy boundary a restore
|
||||
// crosses: the record outside the database is the only thing that stops a
|
||||
// snapshot bringing back a note deleted after it was taken, so a restore refuses
|
||||
// unless that record is there and lists every deletion the data has seen.
|
||||
func TestRestoreRefusesAnIncompleteRecord(t *testing.T) {
|
||||
note := uuid.New()
|
||||
other := uuid.New()
|
||||
record := filepath.Join("/state", "archie", deletions.File)
|
||||
cases := []struct {
|
||||
name string
|
||||
facts restoreFacts
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "the record is missing",
|
||||
facts: restoreFacts{live: []memory.Witness{{NoteID: note, OrgID: "default"}}},
|
||||
want: "is missing",
|
||||
},
|
||||
{
|
||||
name: "a fresh target cannot show what was deleted after the snapshot",
|
||||
facts: restoreFacts{ledgerExists: true},
|
||||
want: "has not recorded a deletion of its own",
|
||||
},
|
||||
{
|
||||
name: "the record lists fewer deletions than the data has seen",
|
||||
facts: restoreFacts{
|
||||
ledgerExists: true,
|
||||
live: []memory.Witness{{NoteID: note, OrgID: "default"}},
|
||||
unaccounted: []memory.Witness{{NoteID: other, OrgID: "default"}},
|
||||
},
|
||||
want: "does not list 1 deletion(s)",
|
||||
},
|
||||
{
|
||||
name: "the record accounts for every deletion",
|
||||
facts: restoreFacts{
|
||||
ledgerExists: true,
|
||||
live: []memory.Witness{{NoteID: note, OrgID: "default"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := refuseUnaccounted(tc.facts, "/backups/snapshot.dump", record)
|
||||
if tc.want == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("refused a complete record: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !errors.Is(err, ErrUnaccountedDeletions) {
|
||||
t.Fatalf("err = %v, want an unaccounted deletion", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tc.want) {
|
||||
t.Fatalf("err = %q, want it to say %q", err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAcknowledgedRestoreIsRecorded guards the one way past an incomplete
|
||||
// record: the acknowledgement is written beside the record, naming the snapshot
|
||||
// it covers and how many deletions went unaccounted, so what was lost can be
|
||||
// read afterwards.
|
||||
func TestAcknowledgedRestoreIsRecorded(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
snapshot := filepath.Join(dir, "snapshot.dump")
|
||||
if err := os.WriteFile(snapshot, []byte("an archive"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := filepath.Join(dir, "state")
|
||||
if err := acknowledge(t.Context(), snapshot, state, 2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(state, "deletions-acknowledged.jsonl")) //nolint:gosec // the acknowledgement this test just wrote.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got struct {
|
||||
Snapshot string `json:"snapshot"`
|
||||
Digest string `json:"snapshot_sha256"`
|
||||
UnaccountedDeletions int `json:"unaccounted_deletions"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &got); err != nil {
|
||||
t.Fatalf("the acknowledgement is not one JSON line: %v", err)
|
||||
}
|
||||
if got.Snapshot != "snapshot.dump" {
|
||||
t.Fatalf("snapshot = %q, want the file the restore read", got.Snapshot)
|
||||
}
|
||||
if got.Digest == "" {
|
||||
t.Fatal("the acknowledgement does not name the snapshot's digest")
|
||||
}
|
||||
if got.UnaccountedDeletions != 2 {
|
||||
t.Fatalf("unaccounted deletions = %d, want 2", got.UnaccountedDeletions)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRollbackIsProvedFromTheData guards the update transaction's own rollback:
|
||||
// the snapshot is this host's dump from minutes earlier, so a note it holds and
|
||||
// the database no longer has was deleted since, and the rollback is safe exactly
|
||||
// when the record lists every one of those notes. The witness table is not
|
||||
// consulted, so a migration that emptied it does not make a safe rollback refuse.
|
||||
func TestRollbackIsProvedFromTheData(t *testing.T) {
|
||||
kept, deleted, other := uuid.New(), uuid.New(), uuid.New()
|
||||
cases := []struct {
|
||||
name string
|
||||
facts rollbackFacts
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "nothing was deleted since the snapshot",
|
||||
facts: rollbackFacts{
|
||||
snapshotHasNotes: true,
|
||||
snapshot: []memory.NoteKey{{OrgID: "default", ID: kept}},
|
||||
live: []memory.NoteKey{{OrgID: "default", ID: kept}},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "the record lists the note the snapshot would bring back",
|
||||
facts: rollbackFacts{
|
||||
snapshotHasNotes: true,
|
||||
snapshot: []memory.NoteKey{{OrgID: "default", ID: kept}, {OrgID: "default", ID: deleted}},
|
||||
live: []memory.NoteKey{{OrgID: "default", ID: kept}},
|
||||
recorded: []memory.NoteKey{{OrgID: "default", ID: deleted}},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "the record does not list that note",
|
||||
facts: rollbackFacts{
|
||||
snapshotHasNotes: true,
|
||||
snapshot: []memory.NoteKey{{OrgID: "default", ID: kept}, {OrgID: "default", ID: deleted}},
|
||||
live: []memory.NoteKey{{OrgID: "default", ID: kept}},
|
||||
},
|
||||
want: "1 note(s) this database no longer has",
|
||||
},
|
||||
{
|
||||
name: "the note is in the record under another organisation",
|
||||
facts: rollbackFacts{
|
||||
snapshotHasNotes: true,
|
||||
snapshot: []memory.NoteKey{{OrgID: "default", ID: deleted}},
|
||||
recorded: []memory.NoteKey{{OrgID: "other", ID: deleted}},
|
||||
},
|
||||
want: "does not list",
|
||||
},
|
||||
{
|
||||
name: "a snapshot from before the notes table, onto a database with notes",
|
||||
facts: rollbackFacts{
|
||||
live: []memory.NoteKey{{OrgID: "default", ID: kept}},
|
||||
},
|
||||
want: "holds no notes table",
|
||||
},
|
||||
{
|
||||
name: "a snapshot from before the notes table, onto a database with none",
|
||||
facts: rollbackFacts{live: nil},
|
||||
},
|
||||
{
|
||||
name: "a note the database still holds is not a deletion",
|
||||
facts: rollbackFacts{
|
||||
snapshotHasNotes: true,
|
||||
snapshot: []memory.NoteKey{{OrgID: "default", ID: kept}, {OrgID: "default", ID: other}},
|
||||
live: []memory.NoteKey{{OrgID: "default", ID: kept}, {OrgID: "default", ID: other}},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := refuseUnsafeRollback(tc.facts, "/backups/snapshot.dump")
|
||||
if tc.want == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("refused a safe rollback: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !errors.Is(err, deletions.ErrUnsafeRollback) {
|
||||
t.Fatalf("err = %v, want an unsafe rollback", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tc.want) {
|
||||
t.Fatalf("err = %q, want it to say %q", err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,8 @@ type Sender interface {
|
||||
|
||||
// Reloader is a channel that can re-read its configuration in place. The
|
||||
// capability a status report declares and the reload action both derive from
|
||||
// this interface, so a channel cannot advertise one and answer nothing.
|
||||
// the Reloader interface, so a channel cannot advertise one and answer
|
||||
// nothing.
|
||||
type Reloader interface {
|
||||
Reload() error
|
||||
}
|
||||
|
||||
@@ -219,7 +219,7 @@ type Budgets struct {
|
||||
TaskWallClock Duration `toml:"task_wall_clock" json:"task_wall_clock" yaml:"task_wall_clock"`
|
||||
}
|
||||
|
||||
// Provider configures one LLM provider for the runtime catalog.
|
||||
// Provider configures one LLM provider for the runtime catalogue.
|
||||
type Provider struct {
|
||||
Class string `toml:"class" yaml:"class" json:"class"`
|
||||
APIKeyEnv string `toml:"api_key_env" yaml:"api_key_env" json:"api_key_env"`
|
||||
@@ -228,7 +228,7 @@ type Provider struct {
|
||||
// Disabled marks a configured provider whose api_key could not be
|
||||
// resolved at boot. It is runtime state, not a setting: without it a
|
||||
// disabled provider is indistinguishable from one the operator never
|
||||
// configured, and the model catalog would serve it from an ambient
|
||||
// configured, and the model catalogue would serve it from an ambient
|
||||
// environment variable.
|
||||
Disabled bool `toml:"-" yaml:"-" json:"-"`
|
||||
}
|
||||
@@ -246,7 +246,7 @@ type Dispatch struct {
|
||||
// issues), "label" (poll labelled issues), or "either" (both).
|
||||
Trigger string `toml:"trigger" json:"trigger" yaml:"trigger"`
|
||||
// AckReaction is the emoji reaction posted on issue pickup. Set
|
||||
// ack_reaction = "off" in TOML to disable it; Load normalizes that
|
||||
// ack_reaction = "off" in TOML to disable it; Load normalises that
|
||||
// sentinel to an empty string for callers.
|
||||
AckReaction string `toml:"ack_reaction" json:"ack_reaction" yaml:"ack_reaction"`
|
||||
}
|
||||
@@ -468,7 +468,7 @@ type ModelLimits struct {
|
||||
ContextWindow int `json:"context_window"`
|
||||
MaxOutputTokens int `json:"max_output_tokens"`
|
||||
// Reasoning marks a reasoning-class model. It is derived from the model
|
||||
// catalog (never operator-authored) and carried to the agent worker so a
|
||||
// catalogue (never operator-authored) and carried to the agent worker so a
|
||||
// task-scoped MCP sampling request omits the max-token bound those models
|
||||
// reject, exactly as the daemon's chat path does.
|
||||
Reasoning bool `json:"reasoning,omitempty"`
|
||||
@@ -517,7 +517,7 @@ func (c Config) ForTask() TaskConfig {
|
||||
|
||||
// aliasedModelLimits keeps the limits of the models an alias can resolve to.
|
||||
// Workflows reach a model only through Models, so the rest of the provider
|
||||
// catalog would only bloat every attempt's captured configuration.
|
||||
// catalogue would only bloat every attempt's captured configuration.
|
||||
func (c Config) aliasedModelLimits() map[string]ModelLimits {
|
||||
var out map[string]ModelLimits
|
||||
for _, ref := range c.Models {
|
||||
@@ -734,10 +734,12 @@ type OpenShellConfig struct {
|
||||
|
||||
// ContainerConfig configures Docker sandbox execution of archie-agent.
|
||||
type ContainerConfig struct {
|
||||
// Image is the Docker image to run (e.g. "git.catlow.cloud/sam/archie-agent:latest").
|
||||
// Image is the Docker image task workers run (e.g. "registry.example.com/archie/archie-agent:v1").
|
||||
// There is no default: validation requires it so a fresh instance is told
|
||||
// at startup rather than at the first failed pull.
|
||||
Image string `toml:"image" yaml:"image"`
|
||||
// MaxConcurrency limits simultaneous daemon tasks and containers.
|
||||
// Tasks from the same repository remain serialized. 0 = no limit.
|
||||
// Tasks from the same repository remain serialised. 0 = no limit.
|
||||
MaxConcurrency int `toml:"max_concurrency" yaml:"max_concurrency"`
|
||||
// MaxUptime caps a container's lifetime before recycling.
|
||||
MaxUptime Duration `toml:"max_uptime" yaml:"max_uptime"`
|
||||
|
||||
@@ -281,7 +281,10 @@ type DescribeResponse struct {
|
||||
// which the dashboard renders as a form.
|
||||
Settings []*Setting `protobuf:"bytes,8,rep,name=settings,proto3" json:"settings,omitempty"`
|
||||
// version is the connector's own release.
|
||||
Version string `protobuf:"bytes,9,opt,name=version,proto3" json:"version,omitempty"`
|
||||
Version string `protobuf:"bytes,9,opt,name=version,proto3" json:"version,omitempty"`
|
||||
// links_accounts says the connector serves LinkURL and emits account.link
|
||||
// events, so a person can link their channel identity to an account.
|
||||
LinksAccounts bool `protobuf:"varint,10,opt,name=links_accounts,json=linksAccounts,proto3" json:"links_accounts,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -379,6 +382,13 @@ func (x *DescribeResponse) GetVersion() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *DescribeResponse) GetLinksAccounts() bool {
|
||||
if x != nil {
|
||||
return x.LinksAccounts
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Setting is one value an operator enters for an extension to run.
|
||||
type Setting struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
@@ -679,10 +689,13 @@ func (x *DeliveryType) GetInputSchema() []byte {
|
||||
}
|
||||
|
||||
type LookupType struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
||||
Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"`
|
||||
InputSchema []byte `protobuf:"bytes,3,opt,name=input_schema,json=inputSchema,proto3" json:"input_schema,omitempty"`
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
||||
Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"`
|
||||
InputSchema []byte `protobuf:"bytes,3,opt,name=input_schema,json=inputSchema,proto3" json:"input_schema,omitempty"`
|
||||
// effect declares the lookup's effects. Only the effects_declared,
|
||||
// privilege_change and secret_access fields apply to a lookup.
|
||||
Effect *Effect `protobuf:"bytes,4,opt,name=effect,proto3" json:"effect,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -738,13 +751,30 @@ func (x *LookupType) GetInputSchema() []byte {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *LookupType) GetEffect() *Effect {
|
||||
if x != nil {
|
||||
return x.Effect
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Effect struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
ReadOnly bool `protobuf:"varint,1,opt,name=read_only,json=readOnly,proto3" json:"read_only,omitempty"`
|
||||
Reversibility Reversibility `protobuf:"varint,2,opt,name=reversibility,proto3,enum=connector.v1.Reversibility" json:"reversibility,omitempty"`
|
||||
// summary says in plain words what the action does, for example "delete
|
||||
// files older than 24h under /tmp/runner".
|
||||
Summary string `protobuf:"bytes,3,opt,name=summary,proto3" json:"summary,omitempty"`
|
||||
Summary string `protobuf:"bytes,3,opt,name=summary,proto3" json:"summary,omitempty"`
|
||||
// effects_declared says the connector stated this action's privilege_change
|
||||
// and secret_access explicitly. With it false the two flags mean nothing: an
|
||||
// action that never stated its effects is prohibited in chat, which is not
|
||||
// the same as an action that stated it has none.
|
||||
EffectsDeclared bool `protobuf:"varint,4,opt,name=effects_declared,json=effectsDeclared,proto3" json:"effects_declared,omitempty"`
|
||||
// privilege_change says the action changes who may do what: it grants
|
||||
// roles, changes identities or policies, or changes control-plane settings.
|
||||
PrivilegeChange bool `protobuf:"varint,5,opt,name=privilege_change,json=privilegeChange,proto3" json:"privilege_change,omitempty"`
|
||||
// secret_access says the action reads, exports or reveals a secret.
|
||||
SecretAccess bool `protobuf:"varint,6,opt,name=secret_access,json=secretAccess,proto3" json:"secret_access,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -800,8 +830,29 @@ func (x *Effect) GetSummary() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Effect) GetEffectsDeclared() bool {
|
||||
if x != nil {
|
||||
return x.EffectsDeclared
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *Effect) GetPrivilegeChange() bool {
|
||||
if x != nil {
|
||||
return x.PrivilegeChange
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *Effect) GetSecretAccess() bool {
|
||||
if x != nil {
|
||||
return x.SecretAccess
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Target is what an action acts on. Connector, action, kind and environment
|
||||
// together are the action class.
|
||||
// together are the action type.
|
||||
type Target struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
|
||||
@@ -1223,7 +1274,7 @@ type InvokeResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Output []byte `protobuf:"bytes,1,opt,name=output,proto3" json:"output,omitempty"`
|
||||
// executed_digest is the connector's digest of what it ran. A mismatch is a
|
||||
// finding and tightens the action class.
|
||||
// finding and tightens the action type.
|
||||
ExecutedDigest string `protobuf:"bytes,2,opt,name=executed_digest,json=executedDigest,proto3" json:"executed_digest,omitempty"`
|
||||
// outcome_unknown says the connector can't confirm what its effect did.
|
||||
OutcomeUnknown bool `protobuf:"varint,3,opt,name=outcome_unknown,json=outcomeUnknown,proto3" json:"outcome_unknown,omitempty"`
|
||||
@@ -1705,6 +1756,96 @@ func (x *ListenResponse) GetCursor() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
type LinkURLRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
// code is the single-use link code the person sends to the connector.
|
||||
Code string `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *LinkURLRequest) Reset() {
|
||||
*x = LinkURLRequest{}
|
||||
mi := &file_connector_v1_connector_proto_msgTypes[26]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *LinkURLRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*LinkURLRequest) ProtoMessage() {}
|
||||
|
||||
func (x *LinkURLRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_connector_v1_connector_proto_msgTypes[26]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use LinkURLRequest.ProtoReflect.Descriptor instead.
|
||||
func (*LinkURLRequest) Descriptor() ([]byte, []int) {
|
||||
return file_connector_v1_connector_proto_rawDescGZIP(), []int{26}
|
||||
}
|
||||
|
||||
func (x *LinkURLRequest) GetCode() string {
|
||||
if x != nil {
|
||||
return x.Code
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type LinkURLResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
// url opens the connector's channel with the code attached.
|
||||
Url string `protobuf:"bytes,1,opt,name=url,proto3" json:"url,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *LinkURLResponse) Reset() {
|
||||
*x = LinkURLResponse{}
|
||||
mi := &file_connector_v1_connector_proto_msgTypes[27]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *LinkURLResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*LinkURLResponse) ProtoMessage() {}
|
||||
|
||||
func (x *LinkURLResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_connector_v1_connector_proto_msgTypes[27]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use LinkURLResponse.ProtoReflect.Descriptor instead.
|
||||
func (*LinkURLResponse) Descriptor() ([]byte, []int) {
|
||||
return file_connector_v1_connector_proto_rawDescGZIP(), []int{27}
|
||||
}
|
||||
|
||||
func (x *LinkURLResponse) GetUrl() string {
|
||||
if x != nil {
|
||||
return x.Url
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_connector_v1_connector_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_connector_v1_connector_proto_rawDesc = "" +
|
||||
@@ -1720,7 +1861,7 @@ const file_connector_v1_connector_proto_rawDesc = "" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
||||
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x13\n" +
|
||||
"\x11ConfigureResponse\"\x11\n" +
|
||||
"\x0fDescribeRequest\"\x8d\x03\n" +
|
||||
"\x0fDescribeRequest\"\xb4\x03\n" +
|
||||
"\x10DescribeResponse\x12\x1a\n" +
|
||||
"\bcontract\x18\x01 \x01(\tR\bcontract\x12/\n" +
|
||||
"\x06events\x18\x02 \x03(\v2\x17.connector.v1.EventTypeR\x06events\x122\n" +
|
||||
@@ -1732,7 +1873,9 @@ const file_connector_v1_connector_proto_rawDesc = "" +
|
||||
"\alistens\x18\x06 \x01(\bR\alistens\x12!\n" +
|
||||
"\ftarget_facts\x18\a \x01(\bR\vtargetFacts\x121\n" +
|
||||
"\bsettings\x18\b \x03(\v2\x15.connector.v1.SettingR\bsettings\x12\x18\n" +
|
||||
"\aversion\x18\t \x01(\tR\aversion\"\xd0\x01\n" +
|
||||
"\aversion\x18\t \x01(\tR\aversion\x12%\n" +
|
||||
"\x0elinks_accounts\x18\n" +
|
||||
" \x01(\bR\rlinksAccounts\"\xd0\x01\n" +
|
||||
"\aSetting\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
||||
"\x05label\x18\x02 \x01(\tR\x05label\x12 \n" +
|
||||
@@ -1757,16 +1900,20 @@ const file_connector_v1_connector_proto_rawDesc = "" +
|
||||
"\fDeliveryType\x12\x12\n" +
|
||||
"\x04name\x18\x01 \x01(\tR\x04name\x12 \n" +
|
||||
"\vdescription\x18\x02 \x01(\tR\vdescription\x12!\n" +
|
||||
"\finput_schema\x18\x03 \x01(\fR\vinputSchema\"e\n" +
|
||||
"\finput_schema\x18\x03 \x01(\fR\vinputSchema\"\x93\x01\n" +
|
||||
"\n" +
|
||||
"LookupType\x12\x12\n" +
|
||||
"\x04name\x18\x01 \x01(\tR\x04name\x12 \n" +
|
||||
"\vdescription\x18\x02 \x01(\tR\vdescription\x12!\n" +
|
||||
"\finput_schema\x18\x03 \x01(\fR\vinputSchema\"\x82\x01\n" +
|
||||
"\finput_schema\x18\x03 \x01(\fR\vinputSchema\x12,\n" +
|
||||
"\x06effect\x18\x04 \x01(\v2\x14.connector.v1.EffectR\x06effect\"\xfd\x01\n" +
|
||||
"\x06Effect\x12\x1b\n" +
|
||||
"\tread_only\x18\x01 \x01(\bR\breadOnly\x12A\n" +
|
||||
"\rreversibility\x18\x02 \x01(\x0e2\x1b.connector.v1.ReversibilityR\rreversibility\x12\x18\n" +
|
||||
"\asummary\x18\x03 \x01(\tR\asummary\"n\n" +
|
||||
"\asummary\x18\x03 \x01(\tR\asummary\x12)\n" +
|
||||
"\x10effects_declared\x18\x04 \x01(\bR\x0feffectsDeclared\x12)\n" +
|
||||
"\x10privilege_change\x18\x05 \x01(\bR\x0fprivilegeChange\x12#\n" +
|
||||
"\rsecret_access\x18\x06 \x01(\bR\fsecretAccess\"n\n" +
|
||||
"\x06Target\x12\x12\n" +
|
||||
"\x04kind\x18\x01 \x01(\tR\x04kind\x12\x0e\n" +
|
||||
"\x02id\x18\x02 \x01(\tR\x02id\x12 \n" +
|
||||
@@ -1829,7 +1976,11 @@ const file_connector_v1_connector_proto_rawDesc = "" +
|
||||
"\x06cursor\x18\x01 \x01(\tR\x06cursor\"U\n" +
|
||||
"\x0eListenResponse\x12+\n" +
|
||||
"\x06events\x18\x01 \x03(\v2\x13.connector.v1.EventR\x06events\x12\x16\n" +
|
||||
"\x06cursor\x18\x02 \x01(\tR\x06cursor*\xd9\x01\n" +
|
||||
"\x06cursor\x18\x02 \x01(\tR\x06cursor\"$\n" +
|
||||
"\x0eLinkURLRequest\x12\x12\n" +
|
||||
"\x04code\x18\x01 \x01(\tR\x04code\"#\n" +
|
||||
"\x0fLinkURLResponse\x12\x10\n" +
|
||||
"\x03url\x18\x01 \x01(\tR\x03url*\xd9\x01\n" +
|
||||
"\vSettingType\x12\x1c\n" +
|
||||
"\x18SETTING_TYPE_UNSPECIFIED\x10\x00\x12\x17\n" +
|
||||
"\x13SETTING_TYPE_STRING\x10\x01\x12\x17\n" +
|
||||
@@ -1843,7 +1994,7 @@ const file_connector_v1_connector_proto_rawDesc = "" +
|
||||
"\x19REVERSIBILITY_UNSPECIFIED\x10\x00\x12&\n" +
|
||||
"\"REVERSIBILITY_UNDONE_AUTOMATICALLY\x10\x01\x12\x1d\n" +
|
||||
"\x19REVERSIBILITY_RECOVERABLE\x10\x02\x12\x1e\n" +
|
||||
"\x1aREVERSIBILITY_IRREVERSIBLE\x10\x032\xa2\x05\n" +
|
||||
"\x1aREVERSIBILITY_IRREVERSIBLE\x10\x032\xea\x05\n" +
|
||||
"\x10ConnectorService\x12L\n" +
|
||||
"\tConfigure\x12\x1e.connector.v1.ConfigureRequest\x1a\x1f.connector.v1.ConfigureResponse\x12I\n" +
|
||||
"\bDescribe\x12\x1d.connector.v1.DescribeRequest\x1a\x1e.connector.v1.DescribeResponse\x12@\n" +
|
||||
@@ -1853,7 +2004,8 @@ const file_connector_v1_connector_proto_rawDesc = "" +
|
||||
"\x06Lookup\x12\x1b.connector.v1.LookupRequest\x1a\x1c.connector.v1.LookupResponse\x12F\n" +
|
||||
"\aDeliver\x12\x1c.connector.v1.DeliverRequest\x1a\x1d.connector.v1.DeliverResponse\x12E\n" +
|
||||
"\x06Listen\x12\x1b.connector.v1.ListenRequest\x1a\x1c.connector.v1.ListenResponse0\x01\x12R\n" +
|
||||
"\vTargetFacts\x12 .connector.v1.TargetFactsRequest\x1a!.connector.v1.TargetFactsResponseB\xc4\x01\n" +
|
||||
"\vTargetFacts\x12 .connector.v1.TargetFactsRequest\x1a!.connector.v1.TargetFactsResponse\x12F\n" +
|
||||
"\aLinkURL\x12\x1c.connector.v1.LinkURLRequest\x1a\x1d.connector.v1.LinkURLResponseB\xc4\x01\n" +
|
||||
"\x10com.connector.v1B\x0eConnectorProtoP\x01ZOgithub.com/samcharles93/archie-core/internal/contracts/connector/v1;connectorv1\xa2\x02\x03CXX\xaa\x02\fConnector.V1\xca\x02\fConnector\\V1\xe2\x02\x18Connector\\V1\\GPBMetadata\xea\x02\rConnector::V1b\x06proto3"
|
||||
|
||||
var (
|
||||
@@ -1869,7 +2021,7 @@ func file_connector_v1_connector_proto_rawDescGZIP() []byte {
|
||||
}
|
||||
|
||||
var file_connector_v1_connector_proto_enumTypes = make([]protoimpl.EnumInfo, 2)
|
||||
var file_connector_v1_connector_proto_msgTypes = make([]protoimpl.MessageInfo, 29)
|
||||
var file_connector_v1_connector_proto_msgTypes = make([]protoimpl.MessageInfo, 31)
|
||||
var file_connector_v1_connector_proto_goTypes = []any{
|
||||
(SettingType)(0), // 0: connector.v1.SettingType
|
||||
(Reversibility)(0), // 1: connector.v1.Reversibility
|
||||
@@ -1899,14 +2051,16 @@ var file_connector_v1_connector_proto_goTypes = []any{
|
||||
(*TargetFactsResponse)(nil), // 25: connector.v1.TargetFactsResponse
|
||||
(*ListenRequest)(nil), // 26: connector.v1.ListenRequest
|
||||
(*ListenResponse)(nil), // 27: connector.v1.ListenResponse
|
||||
nil, // 28: connector.v1.ConfigureRequest.SettingsEntry
|
||||
nil, // 29: connector.v1.ConfigureRequest.SecretsEntry
|
||||
nil, // 30: connector.v1.ParseRequest.HeadersEntry
|
||||
(*timestamppb.Timestamp)(nil), // 31: google.protobuf.Timestamp
|
||||
(*LinkURLRequest)(nil), // 28: connector.v1.LinkURLRequest
|
||||
(*LinkURLResponse)(nil), // 29: connector.v1.LinkURLResponse
|
||||
nil, // 30: connector.v1.ConfigureRequest.SettingsEntry
|
||||
nil, // 31: connector.v1.ConfigureRequest.SecretsEntry
|
||||
nil, // 32: connector.v1.ParseRequest.HeadersEntry
|
||||
(*timestamppb.Timestamp)(nil), // 33: google.protobuf.Timestamp
|
||||
}
|
||||
var file_connector_v1_connector_proto_depIdxs = []int32{
|
||||
28, // 0: connector.v1.ConfigureRequest.settings:type_name -> connector.v1.ConfigureRequest.SettingsEntry
|
||||
29, // 1: connector.v1.ConfigureRequest.secrets:type_name -> connector.v1.ConfigureRequest.SecretsEntry
|
||||
30, // 0: connector.v1.ConfigureRequest.settings:type_name -> connector.v1.ConfigureRequest.SettingsEntry
|
||||
31, // 1: connector.v1.ConfigureRequest.secrets:type_name -> connector.v1.ConfigureRequest.SecretsEntry
|
||||
7, // 2: connector.v1.DescribeResponse.events:type_name -> connector.v1.EventType
|
||||
8, // 3: connector.v1.DescribeResponse.actions:type_name -> connector.v1.ActionType
|
||||
10, // 4: connector.v1.DescribeResponse.lookups:type_name -> connector.v1.LookupType
|
||||
@@ -1914,37 +2068,40 @@ var file_connector_v1_connector_proto_depIdxs = []int32{
|
||||
6, // 6: connector.v1.DescribeResponse.settings:type_name -> connector.v1.Setting
|
||||
0, // 7: connector.v1.Setting.type:type_name -> connector.v1.SettingType
|
||||
11, // 8: connector.v1.ActionType.effect:type_name -> connector.v1.Effect
|
||||
1, // 9: connector.v1.Effect.reversibility:type_name -> connector.v1.Reversibility
|
||||
30, // 10: connector.v1.ParseRequest.headers:type_name -> connector.v1.ParseRequest.HeadersEntry
|
||||
15, // 11: connector.v1.ParseResponse.events:type_name -> connector.v1.Event
|
||||
31, // 12: connector.v1.Event.occurred_at:type_name -> google.protobuf.Timestamp
|
||||
12, // 13: connector.v1.ResolveResponse.target:type_name -> connector.v1.Target
|
||||
11, // 14: connector.v1.ResolveResponse.effect:type_name -> connector.v1.Effect
|
||||
12, // 15: connector.v1.TargetFactsRequest.target:type_name -> connector.v1.Target
|
||||
15, // 16: connector.v1.ListenResponse.events:type_name -> connector.v1.Event
|
||||
2, // 17: connector.v1.ConnectorService.Configure:input_type -> connector.v1.ConfigureRequest
|
||||
4, // 18: connector.v1.ConnectorService.Describe:input_type -> connector.v1.DescribeRequest
|
||||
13, // 19: connector.v1.ConnectorService.Parse:input_type -> connector.v1.ParseRequest
|
||||
16, // 20: connector.v1.ConnectorService.Resolve:input_type -> connector.v1.ResolveRequest
|
||||
18, // 21: connector.v1.ConnectorService.Invoke:input_type -> connector.v1.InvokeRequest
|
||||
20, // 22: connector.v1.ConnectorService.Lookup:input_type -> connector.v1.LookupRequest
|
||||
22, // 23: connector.v1.ConnectorService.Deliver:input_type -> connector.v1.DeliverRequest
|
||||
26, // 24: connector.v1.ConnectorService.Listen:input_type -> connector.v1.ListenRequest
|
||||
24, // 25: connector.v1.ConnectorService.TargetFacts:input_type -> connector.v1.TargetFactsRequest
|
||||
3, // 26: connector.v1.ConnectorService.Configure:output_type -> connector.v1.ConfigureResponse
|
||||
5, // 27: connector.v1.ConnectorService.Describe:output_type -> connector.v1.DescribeResponse
|
||||
14, // 28: connector.v1.ConnectorService.Parse:output_type -> connector.v1.ParseResponse
|
||||
17, // 29: connector.v1.ConnectorService.Resolve:output_type -> connector.v1.ResolveResponse
|
||||
19, // 30: connector.v1.ConnectorService.Invoke:output_type -> connector.v1.InvokeResponse
|
||||
21, // 31: connector.v1.ConnectorService.Lookup:output_type -> connector.v1.LookupResponse
|
||||
23, // 32: connector.v1.ConnectorService.Deliver:output_type -> connector.v1.DeliverResponse
|
||||
27, // 33: connector.v1.ConnectorService.Listen:output_type -> connector.v1.ListenResponse
|
||||
25, // 34: connector.v1.ConnectorService.TargetFacts:output_type -> connector.v1.TargetFactsResponse
|
||||
26, // [26:35] is the sub-list for method output_type
|
||||
17, // [17:26] is the sub-list for method input_type
|
||||
17, // [17:17] is the sub-list for extension type_name
|
||||
17, // [17:17] is the sub-list for extension extendee
|
||||
0, // [0:17] is the sub-list for field type_name
|
||||
11, // 9: connector.v1.LookupType.effect:type_name -> connector.v1.Effect
|
||||
1, // 10: connector.v1.Effect.reversibility:type_name -> connector.v1.Reversibility
|
||||
32, // 11: connector.v1.ParseRequest.headers:type_name -> connector.v1.ParseRequest.HeadersEntry
|
||||
15, // 12: connector.v1.ParseResponse.events:type_name -> connector.v1.Event
|
||||
33, // 13: connector.v1.Event.occurred_at:type_name -> google.protobuf.Timestamp
|
||||
12, // 14: connector.v1.ResolveResponse.target:type_name -> connector.v1.Target
|
||||
11, // 15: connector.v1.ResolveResponse.effect:type_name -> connector.v1.Effect
|
||||
12, // 16: connector.v1.TargetFactsRequest.target:type_name -> connector.v1.Target
|
||||
15, // 17: connector.v1.ListenResponse.events:type_name -> connector.v1.Event
|
||||
2, // 18: connector.v1.ConnectorService.Configure:input_type -> connector.v1.ConfigureRequest
|
||||
4, // 19: connector.v1.ConnectorService.Describe:input_type -> connector.v1.DescribeRequest
|
||||
13, // 20: connector.v1.ConnectorService.Parse:input_type -> connector.v1.ParseRequest
|
||||
16, // 21: connector.v1.ConnectorService.Resolve:input_type -> connector.v1.ResolveRequest
|
||||
18, // 22: connector.v1.ConnectorService.Invoke:input_type -> connector.v1.InvokeRequest
|
||||
20, // 23: connector.v1.ConnectorService.Lookup:input_type -> connector.v1.LookupRequest
|
||||
22, // 24: connector.v1.ConnectorService.Deliver:input_type -> connector.v1.DeliverRequest
|
||||
26, // 25: connector.v1.ConnectorService.Listen:input_type -> connector.v1.ListenRequest
|
||||
24, // 26: connector.v1.ConnectorService.TargetFacts:input_type -> connector.v1.TargetFactsRequest
|
||||
28, // 27: connector.v1.ConnectorService.LinkURL:input_type -> connector.v1.LinkURLRequest
|
||||
3, // 28: connector.v1.ConnectorService.Configure:output_type -> connector.v1.ConfigureResponse
|
||||
5, // 29: connector.v1.ConnectorService.Describe:output_type -> connector.v1.DescribeResponse
|
||||
14, // 30: connector.v1.ConnectorService.Parse:output_type -> connector.v1.ParseResponse
|
||||
17, // 31: connector.v1.ConnectorService.Resolve:output_type -> connector.v1.ResolveResponse
|
||||
19, // 32: connector.v1.ConnectorService.Invoke:output_type -> connector.v1.InvokeResponse
|
||||
21, // 33: connector.v1.ConnectorService.Lookup:output_type -> connector.v1.LookupResponse
|
||||
23, // 34: connector.v1.ConnectorService.Deliver:output_type -> connector.v1.DeliverResponse
|
||||
27, // 35: connector.v1.ConnectorService.Listen:output_type -> connector.v1.ListenResponse
|
||||
25, // 36: connector.v1.ConnectorService.TargetFacts:output_type -> connector.v1.TargetFactsResponse
|
||||
29, // 37: connector.v1.ConnectorService.LinkURL:output_type -> connector.v1.LinkURLResponse
|
||||
28, // [28:38] is the sub-list for method output_type
|
||||
18, // [18:28] is the sub-list for method input_type
|
||||
18, // [18:18] is the sub-list for extension type_name
|
||||
18, // [18:18] is the sub-list for extension extendee
|
||||
0, // [0:18] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_connector_v1_connector_proto_init() }
|
||||
@@ -1958,7 +2115,7 @@ func file_connector_v1_connector_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_connector_v1_connector_proto_rawDesc), len(file_connector_v1_connector_proto_rawDesc)),
|
||||
NumEnums: 2,
|
||||
NumMessages: 29,
|
||||
NumMessages: 31,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
|
||||
@@ -28,6 +28,7 @@ const (
|
||||
ConnectorService_Deliver_FullMethodName = "/connector.v1.ConnectorService/Deliver"
|
||||
ConnectorService_Listen_FullMethodName = "/connector.v1.ConnectorService/Listen"
|
||||
ConnectorService_TargetFacts_FullMethodName = "/connector.v1.ConnectorService/TargetFacts"
|
||||
ConnectorService_LinkURL_FullMethodName = "/connector.v1.ConnectorService/LinkURL"
|
||||
)
|
||||
|
||||
// ConnectorServiceClient is the client API for ConnectorService service.
|
||||
@@ -60,6 +61,9 @@ type ConnectorServiceClient interface {
|
||||
// delivery is never offered to an agent: hard rules apply to it, guards
|
||||
// don't. The host retries a failed delivery, so a connector should make a
|
||||
// repeat with the same idempotency key harmless where its service allows.
|
||||
// A connector returns InvalidArgument, FailedPrecondition, PermissionDenied
|
||||
// or NotFound when the service rejects the delivery permanently: the host
|
||||
// records the reason and stops retrying. Any other status is retried.
|
||||
Deliver(ctx context.Context, in *DeliverRequest, opts ...grpc.CallOption) (*DeliverResponse, error)
|
||||
// Listen streams the events of a source the connector holds its own
|
||||
// connection to, such as a chat long poll, from cursor on. Each response
|
||||
@@ -71,6 +75,12 @@ type ConnectorServiceClient interface {
|
||||
// host asks only connectors that declare target_facts, and never stores the
|
||||
// answer.
|
||||
TargetFacts(ctx context.Context, in *TargetFactsRequest, opts ...grpc.CallOption) (*TargetFactsResponse, error)
|
||||
// LinkURL returns the URL a person opens to send a link code to the
|
||||
// connector, such as a deep link into its bot. The host asks only
|
||||
// connectors that declare links_accounts. The connector then emits an
|
||||
// account.link event carrying the code and the sender's channel identity;
|
||||
// the host binds that identity to the account that issued the code.
|
||||
LinkURL(ctx context.Context, in *LinkURLRequest, opts ...grpc.CallOption) (*LinkURLResponse, error)
|
||||
}
|
||||
|
||||
type connectorServiceClient struct {
|
||||
@@ -180,6 +190,16 @@ func (c *connectorServiceClient) TargetFacts(ctx context.Context, in *TargetFact
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *connectorServiceClient) LinkURL(ctx context.Context, in *LinkURLRequest, opts ...grpc.CallOption) (*LinkURLResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(LinkURLResponse)
|
||||
err := c.cc.Invoke(ctx, ConnectorService_LinkURL_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ConnectorServiceServer is the server API for ConnectorService service.
|
||||
// All implementations must embed UnimplementedConnectorServiceServer
|
||||
// for forward compatibility.
|
||||
@@ -210,6 +230,9 @@ type ConnectorServiceServer interface {
|
||||
// delivery is never offered to an agent: hard rules apply to it, guards
|
||||
// don't. The host retries a failed delivery, so a connector should make a
|
||||
// repeat with the same idempotency key harmless where its service allows.
|
||||
// A connector returns InvalidArgument, FailedPrecondition, PermissionDenied
|
||||
// or NotFound when the service rejects the delivery permanently: the host
|
||||
// records the reason and stops retrying. Any other status is retried.
|
||||
Deliver(context.Context, *DeliverRequest) (*DeliverResponse, error)
|
||||
// Listen streams the events of a source the connector holds its own
|
||||
// connection to, such as a chat long poll, from cursor on. Each response
|
||||
@@ -221,6 +244,12 @@ type ConnectorServiceServer interface {
|
||||
// host asks only connectors that declare target_facts, and never stores the
|
||||
// answer.
|
||||
TargetFacts(context.Context, *TargetFactsRequest) (*TargetFactsResponse, error)
|
||||
// LinkURL returns the URL a person opens to send a link code to the
|
||||
// connector, such as a deep link into its bot. The host asks only
|
||||
// connectors that declare links_accounts. The connector then emits an
|
||||
// account.link event carrying the code and the sender's channel identity;
|
||||
// the host binds that identity to the account that issued the code.
|
||||
LinkURL(context.Context, *LinkURLRequest) (*LinkURLResponse, error)
|
||||
mustEmbedUnimplementedConnectorServiceServer()
|
||||
}
|
||||
|
||||
@@ -258,6 +287,9 @@ func (UnimplementedConnectorServiceServer) Listen(*ListenRequest, grpc.ServerStr
|
||||
func (UnimplementedConnectorServiceServer) TargetFacts(context.Context, *TargetFactsRequest) (*TargetFactsResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method TargetFacts not implemented")
|
||||
}
|
||||
func (UnimplementedConnectorServiceServer) LinkURL(context.Context, *LinkURLRequest) (*LinkURLResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method LinkURL not implemented")
|
||||
}
|
||||
func (UnimplementedConnectorServiceServer) mustEmbedUnimplementedConnectorServiceServer() {}
|
||||
func (UnimplementedConnectorServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
@@ -434,6 +466,24 @@ func _ConnectorService_TargetFacts_Handler(srv interface{}, ctx context.Context,
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _ConnectorService_LinkURL_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(LinkURLRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(ConnectorServiceServer).LinkURL(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: ConnectorService_LinkURL_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(ConnectorServiceServer).LinkURL(ctx, req.(*LinkURLRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// ConnectorService_ServiceDesc is the grpc.ServiceDesc for ConnectorService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
@@ -473,6 +523,10 @@ var ConnectorService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "TargetFacts",
|
||||
Handler: _ConnectorService_TargetFacts_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "LinkURL",
|
||||
Handler: _ConnectorService_LinkURL_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{
|
||||
{
|
||||
|
||||
@@ -35,7 +35,7 @@ type TaskTransport interface {
|
||||
}
|
||||
|
||||
// RunCredentialIssuer issues the one credential a task's container holds: it
|
||||
// authorizes the task's own State Store calls and the push of its branch.
|
||||
// authorises the task's own State Store calls and the push of its branch.
|
||||
// It lapses at the task's time limit plus a margin if never revoked.
|
||||
type RunCredentialIssuer interface {
|
||||
Issue(ctx context.Context, task *workflow.Task, limit time.Duration) (token string, revoke func(), err error)
|
||||
|
||||
@@ -58,7 +58,7 @@ func (d *Daemon) adoptWorkflowIdentity(ctx context.Context, task *workflow.Task)
|
||||
}
|
||||
|
||||
// declaredIdentity resolves a workflow's declared identity to the ID it is
|
||||
// authorized as and the name the task carries while it runs.
|
||||
// authorised as and the name the task carries while it runs.
|
||||
func (g *IdentityGate) declaredIdentity(ctx context.Context, task *workflow.Task, ref string) (identity.IdentityID, string, error) {
|
||||
value, err := g.databaseExecutionIdentity(ctx, task, identity.IdentityID(ref))
|
||||
if err != nil {
|
||||
|
||||
@@ -132,7 +132,7 @@ type Usage struct {
|
||||
}
|
||||
|
||||
// Provider describes how the worker resolves a model provider. API keys are
|
||||
// referenced by environment variable name and never serialized.
|
||||
// referenced by environment variable name and never serialised.
|
||||
type Provider struct {
|
||||
Class string `json:"class"`
|
||||
APIKeyEnv string `json:"api_key_env,omitempty"`
|
||||
|
||||
@@ -109,7 +109,7 @@ func NormalizeLimit(limit int) int {
|
||||
return limit
|
||||
}
|
||||
|
||||
// Hash is the fingerprint of the normalized filter a cursor is bound to. A
|
||||
// Hash is the fingerprint of the normalised filter a cursor is bound to. A
|
||||
// cursor replayed with a different filter would resume at a position that no
|
||||
// longer means the same page, so the reader refuses it.
|
||||
func (f *Filter) Hash() string {
|
||||
|
||||
@@ -51,7 +51,7 @@ func (t *activityTracker) record(name string, at time.Time, actions []Action) {
|
||||
// A curator engine may not stamp its own actions (no clock
|
||||
// dependency wired in); the pass's own "at" is the authoritative
|
||||
// time for every action it produced, so backfill rather than let
|
||||
// a zero time.Time reach the wire as "105694 wks ago".
|
||||
// a zero timestamp reach the wire as "105694 wks ago".
|
||||
if action.At.IsZero() {
|
||||
action.At = at
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ type ToolBuilder interface {
|
||||
}
|
||||
|
||||
// SkillStore is the skill-maintenance capability. The implementation owns
|
||||
// the on-disk format and catalog reload rules.
|
||||
// the on-disk format and catalogue reload rules.
|
||||
type SkillStore interface {
|
||||
List(ctx context.Context) ([]SkillRef, error)
|
||||
Read(ctx context.Context, name string) (Skill, error)
|
||||
|
||||
@@ -30,7 +30,7 @@ type RuntimeConfig struct {
|
||||
// defaultPassTimeout (10m).
|
||||
PassTimeout time.Duration
|
||||
// MaxConcurrentPasses caps simultaneous passes across all curators.
|
||||
// Zero uses 1: passes serialize behind a shared slot so a pass burst
|
||||
// Zero uses 1: passes serialise behind a shared slot so a pass burst
|
||||
// can never saturate the model runtime against chat turns.
|
||||
MaxConcurrentPasses int
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ type SubjectBinding interface {
|
||||
BindSubject(context.Context, IdentityID, Subject, Audit) error
|
||||
}
|
||||
|
||||
// LoginFlow is the browser authorization flow an identity provider requires, as
|
||||
// LoginFlow is the browser authorisation flow an identity provider requires, as
|
||||
// a dashboard driving it needs it: the URL to send a browser to, then the
|
||||
// completion of the flow when the browser returns. It is a contract here rather
|
||||
// than in the transport because what it yields is an identity.
|
||||
@@ -83,7 +83,7 @@ type SubjectResolver interface {
|
||||
ClaimSubject(ctx context.Context, placeholder, subject Subject) (Identity, error)
|
||||
}
|
||||
|
||||
// ProviderSession is what a completed authorization flow yields: the credential
|
||||
// ProviderSession is what a completed authorisation flow yields: the credential
|
||||
// the provider proved, and the provider's own token to present on later requests.
|
||||
// Archie holds no session of its own -- the token belongs to the provider and is
|
||||
// re-verified on every later request, so nothing archie stores can outlive it.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package messaging
|
||||
|
||||
// ModelDetails carries read-only catalog metadata for one model reference.
|
||||
// ModelDetails carries read-only catalogue metadata for one model reference.
|
||||
type ModelDetails struct {
|
||||
Ref string `json:"ref"`
|
||||
Name string `json:"name,omitempty"`
|
||||
@@ -14,7 +14,7 @@ type ModelDetails struct {
|
||||
}
|
||||
|
||||
// DetailedModelManager optionally enriches model selection confirmation with
|
||||
// catalog metadata such as context window and modalities.
|
||||
// catalogue metadata such as context window and modalities.
|
||||
type DetailedModelManager interface {
|
||||
ModelDetails(ref string) (ModelDetails, bool)
|
||||
}
|
||||
@@ -46,7 +46,7 @@ const (
|
||||
// TimingCron fires at each cron match in the instance time zone.
|
||||
// Day-of-month and day-of-week are ANDed.
|
||||
TimingCron = "cron"
|
||||
// TimingOnce fires once at At.
|
||||
// TimingOnce fires once when the At time arrives.
|
||||
TimingOnce = "once"
|
||||
)
|
||||
|
||||
|
||||
@@ -20,8 +20,8 @@ const cursorSeparator = "|"
|
||||
// and string comparison of two cursors is the total order (key, id).
|
||||
const cursorIDWidth = 20
|
||||
|
||||
// EventCursor returns the opaque resume cursor for an event that happened at
|
||||
// at with row id id. The cursor is a string so EventSource can carry it
|
||||
// EventCursor returns the opaque resume cursor for an event whose time is at
|
||||
// and whose row id is id. The cursor is a string so EventSource can carry it
|
||||
// verbatim in its id: field and echo it back as the Last-Event-ID header; it
|
||||
// is opaque to every consumer except EventsSince.
|
||||
func EventCursor(at time.Time, id int64) string {
|
||||
|
||||
@@ -25,7 +25,7 @@ var (
|
||||
ErrUnavailable = errors.New("runtime task control is unavailable")
|
||||
)
|
||||
|
||||
// Task is the state needed to authorize and apply an operator action.
|
||||
// Task is the state needed to authorise and apply an operator action.
|
||||
type Task struct {
|
||||
Org org.OrgID
|
||||
ID int64
|
||||
|
||||
@@ -57,9 +57,9 @@ func NormalizeDays(days int) int {
|
||||
return days
|
||||
}
|
||||
|
||||
// ReportWindow is the UTC window a report of days days covers, ending at now:
|
||||
// whole days, today included. Rows are bucketed by UTC day, so the window
|
||||
// starts at a UTC midnight.
|
||||
// ReportWindow is the UTC window a report of the given number of days covers,
|
||||
// ending at now: whole days, today included. Rows are bucketed by UTC day, so
|
||||
// the window starts at a UTC midnight.
|
||||
func ReportWindow(days int, now time.Time) (from, to time.Time) {
|
||||
now = now.UTC()
|
||||
start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
|
||||
@@ -68,7 +68,7 @@ func ReportWindow(days int, now time.Time) (from, to time.Time) {
|
||||
|
||||
// TotalRow is one cell of a usage report: the day, source and model an org's
|
||||
// calls used and the tokens they spent. Cost is not carried; the reader
|
||||
// prices the tokens against the model catalog.
|
||||
// prices the tokens against the model catalogue.
|
||||
type TotalRow struct {
|
||||
Day string
|
||||
Source Source
|
||||
|
||||
@@ -9,6 +9,23 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
)
|
||||
|
||||
// TestMessageSendWithoutRepository guards workflows that only send a message
|
||||
// from being rejected by the worktree requirement.
|
||||
func TestMessageSendWithoutRepository(t *testing.T) {
|
||||
for _, mode := range []string{"none", "optional"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
_, err := ParseDefinition("id: notify\nrepository: "+mode+`
|
||||
steps:
|
||||
- type: message.send
|
||||
settings: {channel: telegram, chat_id: "123", text: "Done"}
|
||||
`, StepRegistry{MessageSendStepName: newMessageSendStage})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateControlTargets(t *testing.T) {
|
||||
registry := StepRegistry{
|
||||
AgentRunStepName: newAgentRunStage,
|
||||
|
||||
@@ -37,6 +37,7 @@ type YAMLDefinition struct {
|
||||
var repoFreeStepTypes = map[string]bool{
|
||||
AgentRunStepName: true, WorkflowCallStepName: true, FinishStepName: true,
|
||||
HandoffStepName: true, ApproveStepName: true, CloseIssueStepName: true, CommentStepName: true,
|
||||
MessageSendStepName: true,
|
||||
}
|
||||
|
||||
// NeedsRepository reports whether a step type can run only with a worktree.
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/agentrun"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/prreview"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/prompts"
|
||||
)
|
||||
|
||||
func stagePRVerification() Stage {
|
||||
@@ -355,15 +356,7 @@ func runAdversary(ctx context.Context, tc *TaskContext, findings []prreview.Find
|
||||
return findings, nil
|
||||
}
|
||||
|
||||
mission := fmt.Sprintf(
|
||||
"You are the adversary reviewing this pull request's findings. For each finding "+
|
||||
"below, confirm it (you agree it is a real defect) or challenge it (you believe "+
|
||||
"it is wrong or not actually a problem). Read the snapshot yourself to check. "+
|
||||
"%s Also look for any defect every reviewer missed and report it as a new "+
|
||||
"finding.\n\n%s\n"+
|
||||
"Call adversary_verdicts exactly once with one verdict per finding index. If you "+
|
||||
"found anything new, call report_findings once too (skip it if you found "+
|
||||
"nothing new). Then call finish with status \"passed\".",
|
||||
mission := prompts.PRReviewAdversary(
|
||||
adversarySkepticism(tc.prReview.aiGenerated), findingsListing(findings),
|
||||
)
|
||||
res, err := runPRReviewAgentRecorded(ctx, tc, tc.prReview.snapshotDir, "adversary", mission, 25, []agentrun.CaptureTool{
|
||||
|
||||
@@ -44,10 +44,10 @@ type StepStart struct {
|
||||
CalledExecutionID int64
|
||||
}
|
||||
|
||||
// StepFinish moves one step from From to its outcome. ExecutionID names the
|
||||
// run the step belongs to: the task-scoped grant check verifies it, and the
|
||||
// store verifies the step really is that execution's, so a caller cannot move
|
||||
// another run's step by naming it.
|
||||
// StepFinish moves one step out of the From status into its outcome.
|
||||
// ExecutionID names the run the step belongs to: the task-scoped grant check
|
||||
// verifies it, and the store verifies the step really is that execution's, so
|
||||
// a caller cannot move another run's step by naming it.
|
||||
type StepFinish struct {
|
||||
StepID int64
|
||||
ExecutionID int64
|
||||
|
||||
@@ -90,7 +90,7 @@ type Task struct {
|
||||
// Identity is the identity that created this task: a chat user, the
|
||||
// polling identity, a calling workflow's declared identity, or System for
|
||||
// instance-level work. Never empty. Used to scope /approve and
|
||||
// /cancel authorization so one identity cannot control another's
|
||||
// /cancel authorisation so one identity cannot control another's
|
||||
// chat-spawned tasks. While the daemon processes the task it holds the
|
||||
// identity the workflow declares, which is never stored here.
|
||||
Identity string `json:"identity"`
|
||||
|
||||
@@ -24,10 +24,11 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// Forger is the subset of forge.Forge that workflow stages call mid-run.
|
||||
// Production reaches it through forgerpc.Client, which proxies each call to the
|
||||
// daemon over NATS -- the worker holds no forge credentials, so the daemon stays
|
||||
// the only caller of forge.Forge. Test fakes implement it directly.
|
||||
// Forger is the subset of the Forge interface in the forge package that
|
||||
// workflow stages call mid-run. Production reaches it through forgerpc.Client,
|
||||
// which proxies each call to the daemon over NATS -- the worker holds no forge
|
||||
// credentials, so the daemon stays the only caller of that interface. Test
|
||||
// fakes implement it directly.
|
||||
type Forger interface {
|
||||
CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error
|
||||
CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error)
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
)
|
||||
|
||||
// ReviewTaskLookup is the authorization query review reactions require.
|
||||
// ReviewTaskLookup is the authorisation query review reactions require.
|
||||
type ReviewTaskLookup interface {
|
||||
OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*workflowtask.Task, error)
|
||||
}
|
||||
@@ -60,7 +60,7 @@ func SubjectFor(identity, base string) string {
|
||||
return "archie.forge." + string(domainidentity.StableID(identity)) + "." + strings.TrimPrefix(base, "archie.forge.")
|
||||
}
|
||||
|
||||
// Target is what every request acts on and the credential that authorizes
|
||||
// Target is what every request acts on and the credential that authorises
|
||||
// it: the run credential of the task asking, which only reaches that task's
|
||||
// own repository.
|
||||
type Target struct {
|
||||
@@ -162,7 +162,8 @@ type Authorities interface {
|
||||
AcceptedAuthority(ctx context.Context, name string) (storepkg.Authority, error)
|
||||
}
|
||||
|
||||
// Server proxies forgerpc requests to a real forge.Forge implementation.
|
||||
// Server proxies forgerpc requests to a real implementation of the Forge
|
||||
// interface.
|
||||
type Server struct {
|
||||
Resolve func(context.Context, *workflow.Task) (forge.Forge, error)
|
||||
Runs Runs
|
||||
@@ -390,7 +391,7 @@ func (s *Server) respond(msg *nats.Msg, v any) {
|
||||
}
|
||||
|
||||
// Client calls the forgerpc Server from archie-agent's process. It
|
||||
// implements the four proxied forge.Forge methods with matching
|
||||
// implements the four proxied methods of the Forge interface with matching
|
||||
// signatures so it can be used as a drop-in for workflow stages.
|
||||
type Client struct {
|
||||
Conn *nats.Conn
|
||||
|
||||
@@ -27,7 +27,7 @@ func (r runsByToken) TaskForCredential(_ context.Context, token string) (*workfl
|
||||
return nil, errors.New("unknown")
|
||||
}
|
||||
|
||||
// TestForgeCallStaysInItsRunsAuthority pins that a forge call is authorized
|
||||
// TestForgeCallStaysInItsRunsAuthority pins that a forge call is authorised
|
||||
// only by a live run credential, on its identity's server, for its own
|
||||
// repository, and for a package's workflow only within the forge permissions
|
||||
// accepted for that package.
|
||||
|
||||
@@ -63,7 +63,7 @@ func CompressionConfigForModel(details ModelDetails, promptReserve int) (Compres
|
||||
cfg := DefaultCompressionConfig()
|
||||
if details.ContextWindow <= 0 {
|
||||
// ModelDetails is an optional extension on ModelManager. Preserve
|
||||
// compatibility for minimal adapters, while production catalog-backed
|
||||
// compatibility for minimal adapters, while production catalogue-backed
|
||||
// managers still take the model-specific path below.
|
||||
cfg.MaxPromptTokens = max(cfg.ContextWindow-max(promptReserve, 0), 1)
|
||||
return cfg, nil
|
||||
|
||||
@@ -8,63 +8,34 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/prompts"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
"github.com/samcharles93/archie-core/ui/pages"
|
||||
)
|
||||
|
||||
// DashboardPage describes one dashboard surface so the chat agent can both
|
||||
// understand what each place is for and point the operator there.
|
||||
// understand what each place is for and point the operator there. It is the
|
||||
// catalogue the dashboard's own navigation renders from (ui/pages), so a page
|
||||
// the assistant can name is a page the operator can reach.
|
||||
type DashboardPage struct {
|
||||
// Path is the route (e.g. "/tasks"). It is what the browser hash becomes.
|
||||
Path string
|
||||
// Label is the human name shown in navigation (e.g. "Tasks").
|
||||
// Label is the human name the navigation shows (e.g. "Tasks").
|
||||
Label string
|
||||
// Description is a one-line plain-language explanation of what the page
|
||||
// shows, so the agent can answer "where do I go for that?" correctly.
|
||||
Description string
|
||||
}
|
||||
|
||||
// dashboardPages lists the dashboard pages the prompt and the
|
||||
// dashboard_navigate tool can name.
|
||||
var dashboardPages = []DashboardPage{
|
||||
{Path: "/", Label: "Dashboard", Description: "Running work, work needing attention, token spend."},
|
||||
{Path: "/tasks", Label: "Tasks", Description: "Picked-up issues and their status."},
|
||||
{Path: "/account", Label: "Your account", Description: "Password, recovery code, passkeys and personal API tokens."},
|
||||
{Path: "/org", Label: "Organisation", Description: "Members, identities, connections, models and automation."},
|
||||
{Path: "/org/members", Label: "Members", Description: "People in the organisation and their roles."},
|
||||
{Path: "/org/agents", Label: "Agents", Description: "Execution identities, their permissions and commit author."},
|
||||
{Path: "/org/workspaces", Label: "Workspaces", Description: "Groups of organisation work and resources."},
|
||||
{Path: "/org/policies", Label: "Policies", Description: "Access rules for the organisation."},
|
||||
{Path: "/org/connections", Label: "Connections", Description: "Forge hosts, credentials and permitted operations."},
|
||||
{Path: "/org/credential-bindings", Label: "Credential bindings", Description: "Service credentials granted to agent identities."},
|
||||
{Path: "/org/models", Label: "Models", Description: "Organisation providers and model aliases."},
|
||||
{Path: "/org/instructions", Label: "Instructions", Description: "Archie's identity, tone and standing instructions for the organisation."},
|
||||
{Path: "/org/playbooks", Label: "Playbooks", Description: "Edit event-driven automation rules."},
|
||||
{Path: "/settings/authentication", Label: "Authentication", Description: "Instance URL and OIDC sign-in."},
|
||||
{Path: "/workflows", Label: "Workflows", Description: "Workflows and run history."},
|
||||
{Path: "/settings/skills", Label: "Skills", Description: "Skills Archie can activate."},
|
||||
{Path: "/settings/curators", Label: "Curators", Description: "Scheduled memory and capture curation."},
|
||||
{Path: "/events", Label: "Events", Description: "Captured events, field mappings, workflow bindings."},
|
||||
{Path: "/logs", Label: "Logs", Description: "Daemon log by level and component."},
|
||||
{Path: "/org/channels", Label: "Channels", Description: "Chat and notification channels."},
|
||||
{Path: "/settings/status", Label: "Status", Description: "Update state, config sources, listen address."},
|
||||
{Path: "/account/appearance", Label: "Appearance", Description: "Theme, density, motion."},
|
||||
{Path: "/settings/task-execution", Label: "Task execution", Description: "Statuses, operator actions, budgets."},
|
||||
{Path: "/settings/models", Label: "Models", Description: "Instance model aliases and providers."},
|
||||
{Path: "/org/repositories", Label: "Repositories", Description: "Watched repositories and gate overrides."},
|
||||
{Path: "/org/scheduling-policy", Label: "Scheduling policy", Description: "Work discovery and forge labels."},
|
||||
{Path: "/settings/tools", Label: "Tools & MCP", Description: "Agent tools and MCP servers."},
|
||||
{Path: "/org/audit", Label: "Audit", Description: "Settings, access, identity and runtime events."},
|
||||
{Path: "/org/denials", Label: "Denials", Description: "Access requests the policy chain refused, newest first."},
|
||||
{Path: "/settings/plugins", Label: "Plugins", Description: "Extension directories loaded at startup."},
|
||||
{Path: "/settings/secret-engines", Label: "Secret engines"},
|
||||
{Path: "/settings/container-runtime", Label: "Container runtime"},
|
||||
{Path: "/settings/agent-profiles", Label: "Agent profiles", Description: "Execution profiles: the image and tools each agent runs with."},
|
||||
}
|
||||
|
||||
// DashboardPages returns a copy of the dashboard page registry.
|
||||
func DashboardPages() []DashboardPage {
|
||||
out := make([]DashboardPage, len(dashboardPages))
|
||||
copy(out, dashboardPages)
|
||||
return out
|
||||
// DashboardPages returns the dashboard's page catalogue, in its own order.
|
||||
func DashboardPages() ([]DashboardPage, error) {
|
||||
catalogue, err := pages.All()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]DashboardPage, 0, len(catalogue))
|
||||
for _, p := range catalogue {
|
||||
out = append(out, DashboardPage{Path: p.Path, Label: p.Label, Description: p.Description})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// PageIndexResult is what page_index returns: the full list of dashboard pages
|
||||
@@ -84,7 +55,11 @@ func pageIndexTool() (tools.ToolEntry, bool) {
|
||||
Description: "List every dashboard page, what it shows, and built-in guidance for creating workflows and using Archie. Use it to tell the operator where to go for something rather than guessing.",
|
||||
Classification: tools.ClassIdempotent,
|
||||
Handler: func(_ context.Context, _ map[string]any) (any, error) {
|
||||
return PageIndexResult{Pages: DashboardPages(), ProductGuide: prompts.ProductGuide()}, nil
|
||||
indexed, err := DashboardPages()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return PageIndexResult{Pages: indexed, ProductGuide: prompts.ProductGuide()}, nil
|
||||
},
|
||||
}
|
||||
return entry, true
|
||||
@@ -114,7 +89,11 @@ func dashboardNavigateTool() (tools.ToolEntry, bool) {
|
||||
if path == "" {
|
||||
return nil, errors.New("dashboard_navigate: path is required")
|
||||
}
|
||||
for _, p := range dashboardPages {
|
||||
indexed, err := DashboardPages()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, p := range indexed {
|
||||
if p.Path == path {
|
||||
return DashboardNavigateResult{Path: p.Path, Label: p.Label}, nil
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ type LLMStreamResponder func(ctx context.Context, in Inbound, stream TurnStream)
|
||||
|
||||
// ModelManager provides access to available models and allows switching the
|
||||
// active LLM model. The daemon supplies an implementation backed by its
|
||||
// runtime provider catalog. When nil on a Router, /model returns a
|
||||
// runtime provider catalogue. When nil on a Router, /model returns a
|
||||
// "not configured" message.
|
||||
type ModelManager interface {
|
||||
ModelsFor(ctx context.Context) ([]string, error)
|
||||
@@ -61,11 +61,11 @@ type ModelManager interface {
|
||||
SetActiveModel(ctx context.Context, selection string) error
|
||||
}
|
||||
|
||||
// ModelDetails is the catalog metadata rendered after an interactive model
|
||||
// selection. Limits are zero when the upstream catalog does not publish them.
|
||||
// ModelDetails is the catalogue metadata rendered after an interactive model
|
||||
// selection. Limits are zero when the upstream catalogue does not publish them.
|
||||
type ModelDetails = messaging.ModelDetails
|
||||
|
||||
// DetailedModelManager is the optional catalog-aware extension used by rich
|
||||
// DetailedModelManager is the optional catalogue-aware extension used by rich
|
||||
// model selectors. Runtime routing remains on ModelManager.
|
||||
type DetailedModelManager interface {
|
||||
ModelManager
|
||||
@@ -300,8 +300,8 @@ func (r *Router) route(ctx context.Context, in Inbound) (string, error) {
|
||||
return reply, err
|
||||
}
|
||||
|
||||
// dispatchLocal handles recognized local commands. Returns (reply,
|
||||
// true) when the command was recognized and handled.
|
||||
// dispatchLocal handles recognised local commands. Returns (reply,
|
||||
// true) when the command was recognised and handled.
|
||||
func (r *Router) dispatchLocal(ctx context.Context, msg messaging.Message, platform, text, cmd string) (string, bool, error) {
|
||||
rest := restAfter(text, cmd, r.gatewayName)
|
||||
|
||||
@@ -344,7 +344,7 @@ func (r *Router) dispatchLocal(ctx context.Context, msg messaging.Message, platf
|
||||
return r.dispatchLocalMisc(ctx, msg, platform, cmd, rest)
|
||||
}
|
||||
|
||||
// dispatchLocalMisc handles the remaining recognized local commands not
|
||||
// dispatchLocalMisc handles the remaining recognised local commands not
|
||||
// covered by dispatchLocal's first switch. Split out to keep cyclomatic
|
||||
// complexity down.
|
||||
func (r *Router) dispatchLocalMisc(ctx context.Context, msg messaging.Message, platform, cmd, rest string) (string, bool, error) {
|
||||
@@ -861,7 +861,7 @@ func formatStatus(ctx context.Context, counts map[string]int, report HealthRepor
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// formatQueueDepth summarizes in-flight work as one line: how many tasks
|
||||
// formatQueueDepth summarises in-flight work as one line: how many tasks
|
||||
// are running, waiting on a human reply, or parked. Queued and terminal
|
||||
// states are excluded -- neither is a health concern an operator needs
|
||||
// /status to surface.
|
||||
|
||||
@@ -18,7 +18,7 @@ const (
|
||||
defaultSessionListLimit = 20
|
||||
|
||||
// maxSessionListLimit bounds what the model can ask for. A chat that has
|
||||
// churned for months could otherwise land its whole session catalog in the
|
||||
// churned for months could otherwise land its whole session catalogue in the
|
||||
// context window whole.
|
||||
maxSessionListLimit = 100
|
||||
|
||||
@@ -120,7 +120,7 @@ func sessionListTool(store SessionStore, platform, channelID string) tools.ToolE
|
||||
if len(all) > limit {
|
||||
all = all[:limit]
|
||||
}
|
||||
// Non-nil even when empty: an empty catalog is an answer, and a
|
||||
// Non-nil even when empty: an empty catalogue is an answer, and a
|
||||
// null would read to the model as a failed call worth retrying.
|
||||
sessions := make([]ChatSessionEntry, 0, len(all))
|
||||
for _, s := range all {
|
||||
@@ -361,7 +361,7 @@ func sessionTranscriptTool(store SessionStore, platform, channelID string) tools
|
||||
return nil, fmt.Errorf("session_transcript: %w", err)
|
||||
}
|
||||
|
||||
// Serialize to JSON
|
||||
// Serialise to JSON
|
||||
data, err := json.MarshalIndent(messages, "", " ")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("session_transcript: %w", err)
|
||||
|
||||
Loaded 100 of 754 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user