Compare commits
79
Commits
4b5c60330d
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
|
No files matched your search
@@ -1,76 +0,0 @@
|
||||
---
|
||||
name: technical-prose-cleanup
|
||||
description: Use when asked to clean up awkward or machine-generated technical writing in Archie's modules without changing behaviour. Reviews one module at a time.
|
||||
---
|
||||
|
||||
# Technical prose cleanup
|
||||
|
||||
Follow `AGENTS.md`. Improve wording without changing behaviour, contracts or
|
||||
technical meaning. Use Australian English.
|
||||
|
||||
## Set the scope
|
||||
|
||||
1. Check the working tree for existing changes. Inspect `modules/` without
|
||||
editing and choose the smallest module with enough clear problems to justify
|
||||
a pass, unless the maintainer has specified one.
|
||||
2. Set the complete file scope before editing: exactly one module, at most
|
||||
15 files. Do not expand into other modules or start another batch.
|
||||
3. Use subagents only when independent work warrants it. Assign at most three
|
||||
in parallel, each with a disjoint list of owned files, this writing standard
|
||||
and relevant examples. Instruct them to inspect the implementation, leave
|
||||
clear prose alone, report ambiguities and make no commits or pushes.
|
||||
The coordinator owns integration and validation. In a shared worktree,
|
||||
avoid broad staging, resets, checkouts and formatters that rewrite other work.
|
||||
|
||||
## Edit in context
|
||||
|
||||
Check comments, errors, logs, test names, schema descriptions, CLI help,
|
||||
prompts, user-facing strings and module documentation. Look for unnatural word
|
||||
order, awkward possessives, unusual verbs, needless synonyms and wording that
|
||||
obscures the operation. Read the surrounding implementation and tests before
|
||||
rewriting. Do not mechanically replace words or edit text that already reads well.
|
||||
|
||||
Use conventional terms, even when they repeat. Keep established idioms such as
|
||||
“pin a dependency”, “drain a stream” and “acquire a lock”. Prefer precision over
|
||||
brevity when conditions, timing, ownership or guarantees matter.
|
||||
|
||||
| Instead of | Write |
|
||||
| --- | --- |
|
||||
| “PrepareRequest names the release to stage and who hears the outcome.” | “PrepareRequest specifies the release to stage and notification recipients.” |
|
||||
| “ReadOnly leaves the agent only the tools that change nothing.” | “ReadOnly restricts the agent to read-only tools.” |
|
||||
| “a release another key signed” | “a release signed by a different key” |
|
||||
| “it recalls earlier incidents and files what it found” | “it retrieves previous incidents and stores new findings” |
|
||||
|
||||
Comments explain why. Remove narration that adds nothing, but keep
|
||||
non-obvious constraints, invariants and decisions. Retain required Go
|
||||
documentation. Don't shorten a comment about replay into a generic retry
|
||||
description: say what is recorded and what is rebuilt or resolved at runtime.
|
||||
Likewise, distinguish a per-action reapproval limit from a run-wide limit,
|
||||
and escalation within one request from a new request.
|
||||
|
||||
Do not refactor or rename identifiers, configuration keys or API fields.
|
||||
Do not edit generated files by hand, add tooling or dependencies, or reformat
|
||||
unrelated code. Check consumers and tests before changing errors, logs or other
|
||||
output. Keep machine-readable values and exact text used as a contract. If a
|
||||
safe edit needs changes outside the scope or the meaning is unclear, leave
|
||||
the text alone and report why.
|
||||
|
||||
For prompts, preserve instructions, conditions, tool semantics and output
|
||||
requirements. Check what the agent actually sees. For example, judgement runs
|
||||
inside an action tool call; it is not a separate tool the agent calls directly.
|
||||
The investigation prompt says: “If a tool call returns a judgement decision,
|
||||
report the decision and any reasons it gives.” Keep matching fixtures in sync
|
||||
when editing prompt text.
|
||||
|
||||
## Review and stop
|
||||
|
||||
Review the combined diff against both the implementation and the starting
|
||||
working tree. Verify the module and file limits, check that unrelated edits
|
||||
are intact, and confirm that no logic or contract changed. If implementation
|
||||
work already shares a file, keep it out of the prose diff; separate by hunk
|
||||
if asked to commit both.
|
||||
|
||||
Run the relevant checks on the final tree and follow `AGENTS.md` for the
|
||||
commit gate. Report failed or unavailable checks; do not fix unrelated
|
||||
failures in this batch. Summarise the module, file count, main edits,
|
||||
deliberately unchanged ambiguities and validation. Stop after this batch.
|
||||
+10
@@ -52,3 +52,13 @@ __pycache__/
|
||||
/.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,86 @@
|
||||
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
|
||||
|
||||
# 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
|
||||
@@ -116,8 +116,9 @@ When sources disagree, the higher one wins:
|
||||
consumer is a bug. Settings are edited through the control plane (API and
|
||||
dashboard), never by requiring 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
|
||||
|
||||
@@ -140,6 +141,10 @@ When sources disagree, the higher one wins:
|
||||
an established term over inventing a synonym.
|
||||
- Generated files (protobuf, sqlc) are regenerated and committed
|
||||
with the change that caused them, never hand-edited.
|
||||
- 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 point-in-time snapshot fidelity is
|
||||
needed.
|
||||
|
||||
## Tests
|
||||
|
||||
|
||||
+2
-2
@@ -7,9 +7,9 @@ and an ordered list of steps. Definitions are stored in the control plane's
|
||||
`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
|
||||
type's settings schema, in the `workflow-definitions` catalogue entry
|
||||
(`x-step-types`), and validates every definition when it is saved. This file
|
||||
describes that vocabulary; when they disagree, the catalog wins.
|
||||
describes that vocabulary; when they disagree, the catalogue wins.
|
||||
|
||||
```yaml
|
||||
id: implement
|
||||
|
||||
+3529
-213
File diff suppressed because it is too large.
Load diff
@@ -63,6 +63,6 @@ without turning the codebase to garbage.
|
||||
|
||||
- One issue → 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,4 +1,4 @@
|
||||
# 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
|
||||
@@ -33,7 +33,7 @@ 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.
|
||||
|
||||
@@ -47,7 +47,7 @@ authenticated context, never 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.
|
||||
An organisation 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
|
||||
accounts by unverified email, or create an administrator.
|
||||
@@ -59,7 +59,7 @@ accounts by unverified email, or create an administrator.
|
||||
| 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 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 |
|
||||
| First setup: `webui/accounts.go`, `postgres/accounts.go` | Initial organisation, workspace, instance URL, admin identity and password commit together. Transaction lock closes bootstrap after first account; later requests require `manage_members`. | Disposable PostgreSQL smoke verification for bootstrap race and rollback; account policy tests below |
|
||||
| Account creation: `webui/accounts.go`, `staterpc/accounts.go`, `postgres/accounts.go` | Cedar `manage_members` at HTTP and RPC; target org is authenticated context. New local accounts cannot request owner role. | `TestAccountManagementUsesPolicy`, `TestAccountBoundary` |
|
||||
| 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 |
|
||||
@@ -100,7 +100,7 @@ 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
|
||||
begin/finish/list/delete. They do not require an organisation administrator
|
||||
role. `POST /api/accounts` and `/api/authentication` are administrative policy
|
||||
routes.
|
||||
|
||||
@@ -226,7 +226,7 @@ action/resource; the handler may impose a stricter record or instance boundary.
|
||||
|
||||
## Verification limits
|
||||
|
||||
A synthetic browser authenticator verifies protocol behavior, not a physical
|
||||
A synthetic browser authenticator verifies protocol behaviour, 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.
|
||||
@@ -236,8 +236,8 @@ 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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+27
-18
@@ -24,31 +24,32 @@ import (
|
||||
|
||||
// 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
|
||||
chat *chat.Module
|
||||
drafts *drafts.Module
|
||||
notes *memory.Module
|
||||
live *hub.Hub
|
||||
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
|
||||
drafts *drafts.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)
|
||||
@@ -68,13 +69,21 @@ func (m apiModules) register(api huma.API) {
|
||||
// needs no database.
|
||||
func Document() ([]byte, error) {
|
||||
settings := &governance.Module{}
|
||||
api := httpapi.New(http.NewServeMux(), buildinfo.Version, settings.Authenticator(""))
|
||||
_, 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{}, classes: &judgement.Classes{},
|
||||
tell: &deliveries.Module{}, allow: &approvals.Module{}, actionTypes: &judgement.ActionTypes{},
|
||||
policies: &judgement.Policies{}, hear: &events.Module{}, judge: &judgement.Module{},
|
||||
engine: &runs.Engine{}, chat: &chat.Module{}, drafts: &drafts.Module{},
|
||||
notes: &memory.Module{}, live: hub.New(),
|
||||
}.register(api)
|
||||
return api.OpenAPI().YAML()
|
||||
return mux, api
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package archie
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/health"
|
||||
"github.com/samcharles93/archie-core/modules/approvals"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/runs"
|
||||
"github.com/samcharles93/archie-core/modules/system"
|
||||
)
|
||||
|
||||
// healthSources joins what each module knows about itself into the sources the
|
||||
// system health report reads. The report asks them on demand, so nothing here
|
||||
// polls or keeps state.
|
||||
func healthSources(checks *health.Registry, conns *connectors.Module, engine *runs.Engine, allow *approvals.Module) system.Sources {
|
||||
return system.Sources{
|
||||
Checks: func(ctx context.Context) []health.Result {
|
||||
return slices.DeleteFunc(checks.Results(ctx), func(r health.Result) bool {
|
||||
// The report lists each connector with its own cause.
|
||||
return r.Name == "connectors"
|
||||
})
|
||||
},
|
||||
Connectors: conns.Health,
|
||||
Runner: engine.Runner,
|
||||
Waiting: func(ctx context.Context) (system.Waiting, error) {
|
||||
pending, err := allow.Pending(ctx)
|
||||
if err != nil {
|
||||
return system.Waiting{}, fmt.Errorf("list pending approvals: %w", err)
|
||||
}
|
||||
counts, err := engine.Counts(ctx, orgID)
|
||||
if err != nil {
|
||||
return system.Waiting{}, err
|
||||
}
|
||||
return system.Waiting{Approvals: len(pending), Runs: counts}, nil
|
||||
},
|
||||
LastFailedRun: func(ctx context.Context) (*runs.RunView, error) {
|
||||
return engine.LastFailed(ctx, orgID)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,10 @@ import (
|
||||
"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
|
||||
@@ -55,26 +59,44 @@ func (o *operations) Start(ctx context.Context) error {
|
||||
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,
|
||||
Notifier: o.tell, Messenger: o.tell, Memory: o.remember,
|
||||
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)
|
||||
// Administrative writes are checked against the same live policy chain as
|
||||
// every other request.
|
||||
o.settings.UseAuthorizer(access)
|
||||
// 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.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: access, Settings: o.settings, Toolbox: o.conns, Judge: o.judge,
|
||||
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.talk.Work, o.retryDeletionRecord} {
|
||||
@@ -119,7 +141,7 @@ func (o *operations) 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.Install(ctx, orgID, "investigate", runs.InvestigateDocument(), "starter"); err != nil {
|
||||
if _, err := engine.Install(ctx, orgID, "investigate", runs.InvestigateDocument(), string(governance.SystemID)); err != nil {
|
||||
return fmt.Errorf("install the investigate workflow: %w", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
+19
-12
@@ -12,6 +12,7 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
@@ -151,16 +152,18 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary
|
||||
runtime.RegisterBuiltinClasses()
|
||||
settings := governance.NewModule(db, log.With("module", "governance"), orgID)
|
||||
mux := http.NewServeMux()
|
||||
api := httpapi.New(mux, buildinfo.Version, settings.Authenticator(cfg.AdminTokenSHA256))
|
||||
api := httpapi.New(mux, buildinfo.Version, settings.Authenticator(cfg.AdminTokenSHA256), settings)
|
||||
|
||||
conns, err := connectors.NewModule(db, log.With("module", "connectors"), orgID, connectors.Sealing{
|
||||
Identity: cfg.AgeIdentity, Backups: cfg.AgeBackupRecipients,
|
||||
})
|
||||
}, filepath.Join(cfg.StateDir, "extensions"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A model's key is a credential name resolved through the sealed store.
|
||||
settings.UseCredentials(conns)
|
||||
// An account links a channel account on the connectors that can link.
|
||||
settings.UseChannels(conns)
|
||||
|
||||
sys := system.New(system.Bootstrap{
|
||||
Listen: cfg.Listen, Database: DatabaseHost(cfg.Database.URL), Schemas: len(schemas),
|
||||
@@ -177,19 +180,22 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary
|
||||
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, answers{chat: talk, runs: 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.
|
||||
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, tell)
|
||||
hear := events.NewModule(db, log.With("module", "events"), orgID, sealer, conns, engine, allow, settings, tell)
|
||||
hear.Routes(mux)
|
||||
judge := newJudgement(db, log, conns, classes, policies, settings, hear)
|
||||
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.
|
||||
@@ -204,8 +210,9 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary
|
||||
}
|
||||
return nil
|
||||
})
|
||||
sys.UseHealth(healthSources(checks, conns, engine, allow))
|
||||
apiModules{
|
||||
settings: settings, conns: conns, system: sys, tell: tell, allow: allow, classes: classes, policies: policies,
|
||||
settings: settings, conns: conns, system: sys, tell: tell, allow: allow, actionTypes: actionTypes, policies: policies,
|
||||
hear: hear, judge: judge, engine: engine, chat: talk, drafts: drafts.NewModule(db, log.With("module", "drafts"), orgID, hear, engine, policies),
|
||||
notes: remember, live: live,
|
||||
}.register(api)
|
||||
@@ -245,18 +252,18 @@ func (a answers) Signal(ctx context.Context, id uuid.UUID, key string, payload j
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
@@ -739,7 +739,7 @@ type ContainerConfig struct {
|
||||
// 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.
|
||||
@@ -74,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 {
|
||||
@@ -183,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.
|
||||
@@ -227,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()
|
||||
}
|
||||
|
||||
@@ -264,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() {}
|
||||
|
||||
@@ -440,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)
|
||||
@@ -479,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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -95,7 +95,7 @@ func splitOwnerRepo(s string) (owner, repo string, ok bool) {
|
||||
}
|
||||
|
||||
// ChatTaskStatus is the minimal task state StoreTaskController needs to
|
||||
// authorize and validate /approve and /cancel.
|
||||
// authorise and validate /approve and /cancel.
|
||||
type ChatTaskStatus struct {
|
||||
Status string
|
||||
Identity string
|
||||
|
||||
@@ -20,7 +20,7 @@ type TurnPrepareContext struct {
|
||||
Model string
|
||||
Extra []tools.ToolEntry
|
||||
ContextWindow int
|
||||
// Reasoning reports the catalog's class for the active model. It rides
|
||||
// Reasoning reports the catalogue's class for the active model. It rides
|
||||
// the prepare context because the seam that translates a provider-neutral
|
||||
// request into provider options is the only place that knows the wire
|
||||
// parameter differs by class.
|
||||
|
||||
@@ -95,7 +95,7 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// Resolved before the delivery check so the check runs against the
|
||||
// source's owning org, not always the default org. An unknown source
|
||||
// authorizes as the default org.
|
||||
// authorises as the default org.
|
||||
src := rc.resolveSource(r, path)
|
||||
|
||||
if code := rc.refusal(r, path, orgOf(src)); code != 0 {
|
||||
@@ -191,7 +191,7 @@ func (rc *Receiver) refusal(r *http.Request, path string, owner org.OrgID) int {
|
||||
}
|
||||
|
||||
// orgOf reports the org that owns src, or the default org when the source
|
||||
// is unknown: an unknown source has no owner to authorize against.
|
||||
// is unknown: an unknown source has no owner to authorise against.
|
||||
func orgOf(src *source.Source) org.OrgID {
|
||||
if src == nil || src.OrgID == "" {
|
||||
return org.DefaultOrgID
|
||||
|
||||
@@ -100,7 +100,7 @@ func TestPutDraftAttributesTheCaller(t *testing.T) {
|
||||
|
||||
// TestStepTypesReadsTheServedVocabulary pins the catalogue's production
|
||||
// reader: StepTypes returns the x-step-types extension of the
|
||||
// workflow-definitions descriptor the control plane's catalog serves, the
|
||||
// workflow-definitions descriptor the control plane's catalogue serves, the
|
||||
// payload the dashboard workflow editor and the workflow_step_types tool
|
||||
// consume, and it reports an absent catalogue or an unavailable control
|
||||
// plane rather than inventing an empty one.
|
||||
|
||||
@@ -29,7 +29,7 @@ func TestInstanceOnlyKindsRefuseOtherOrgs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCatalogHidesInstanceOnlyKinds pins what the catalog advertises: the
|
||||
// TestCatalogHidesInstanceOnlyKinds pins what the catalogue advertises: the
|
||||
// system org sees an instance setting, another org does not (its write would
|
||||
// be refused), and an org-scoped kind stays visible to both.
|
||||
func TestCatalogHidesInstanceOnlyKinds(t *testing.T) {
|
||||
|
||||
@@ -44,7 +44,7 @@ func operationalDefinitions() []Definition {
|
||||
// Restart-required: the Messaging Service, which owns the channel
|
||||
// transports, reconciles them live and archied re-layers each update, but
|
||||
// the Gateway's chat surfaces (workspace tools, rate limit, model
|
||||
// catalogs) are boot-built, so a change cannot promise live apply
|
||||
// catalogues) are boot-built, so a change cannot promise live apply
|
||||
// everywhere the record reports it.
|
||||
{Kind: ChannelSettingsKind, Title: "Channel settings", ApplyMode: "restart-required", Document: channelSettings{}, Seed: seedChannels, Validate: validateChannels, Normalize: normalizeChannels},
|
||||
{Kind: SchedulingPolicyKind, Title: "Scheduling policy", ApplyMode: "live", Document: schedulingPolicy{}, Seed: func(cfg config.Config) any {
|
||||
|
||||
@@ -35,7 +35,7 @@ type CalloutOptions struct {
|
||||
Tasks TaskAuthority
|
||||
}
|
||||
|
||||
// Callout is the authorization service of an external broker.
|
||||
// Callout is the authorisation service of an external broker.
|
||||
type Callout struct {
|
||||
svc *callout.AuthorizationService
|
||||
nc *natsio.Conn
|
||||
|
||||
@@ -61,7 +61,7 @@ func StartEmbedded(ctx context.Context, opts EmbeddedOptions, log *slog.Logger)
|
||||
Port: opts.Port,
|
||||
JetStream: true,
|
||||
StoreDir: opts.StoreDir,
|
||||
// Replaces token authorization: the instance token and task users
|
||||
// Replaces token authorisation: the instance token and task users
|
||||
// are both checked here.
|
||||
CustomClientAuthentication: authenticator{token: token, tasks: opts.Tasks},
|
||||
NoSigs: true, // the daemon owns signals, not the embedded server
|
||||
|
||||
@@ -55,7 +55,7 @@ func (p *pendingAsks) answer(id, answer string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// remoteAsker poses a turn's questions on its stream. send is serialized with
|
||||
// remoteAsker poses a turn's questions on its stream. send is serialised with
|
||||
// the turn's own frames by the caller.
|
||||
type remoteAsker struct {
|
||||
pending *pendingAsks
|
||||
|
||||
@@ -43,7 +43,7 @@ type CuratorAction struct {
|
||||
}
|
||||
|
||||
// Catalog supplies the process-owned runtime surfaces the dashboard reads over
|
||||
// ChatService. A zero Catalog answers empty lists and an Unavailable reload,
|
||||
// ChatService. A zero Catalogue answers empty lists and an Unavailable reload,
|
||||
// which is the honest answer from a process that hosts none of them.
|
||||
type Catalog struct {
|
||||
// CheckSecret reports whether ref resolves; an error means the engine
|
||||
@@ -55,7 +55,7 @@ type Catalog struct {
|
||||
ReloadChannel func(context.Context, string) error
|
||||
}
|
||||
|
||||
// CatalogClient is the subset of the Gateway client the dashboard's catalog
|
||||
// CatalogClient is the subset of the Gateway client the dashboard's catalogue
|
||||
// surfaces consume.
|
||||
type CatalogClient interface {
|
||||
CheckSecret(context.Context, secret.SecretRef) (bool, error)
|
||||
|
||||
@@ -30,9 +30,9 @@ type server struct {
|
||||
fetch *http.Client
|
||||
}
|
||||
|
||||
// RegisterServer serves the Gateway chat contract. catalog supplies the
|
||||
// RegisterServer serves the Gateway chat contract. catalogue supplies the
|
||||
// process-owned runtime surfaces (skill catalogue, curator registry, channel
|
||||
// reload) the dashboard reads over the same contract; a zero Catalog answers
|
||||
// reload) the dashboard reads over the same contract; a zero Catalogue answers
|
||||
// empty lists and an Unavailable reload.
|
||||
func RegisterServer(registrar grpc.ServiceRegistrar, chat messaging.ChatContract, sessions messaging.SessionStore, catalog Catalog) {
|
||||
pb.RegisterChatServiceServer(registrar, &server{chat: chat, sessions: sessions, catalog: catalog, fetch: publicnet.Client(10*time.Second, 15*time.Second)})
|
||||
|
||||
@@ -107,14 +107,14 @@ func (s *Store) MaxBytes() int {
|
||||
return s.maxBytes
|
||||
}
|
||||
|
||||
// Render returns the current serialized document. Safe for concurrent use.
|
||||
// Render returns the current serialised document. Safe for concurrent use.
|
||||
func (s *Store) Render() string {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return renderSections(s.preamble, s.sections)
|
||||
}
|
||||
|
||||
// Size returns the current serialized document length in bytes.
|
||||
// Size returns the current serialised document length in bytes.
|
||||
func (s *Store) Size() int {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
@@ -267,7 +267,7 @@ func (s *Store) Remove(sectionName, substring string, caseSensitive bool) (Remov
|
||||
rendered := renderSections(s.preamble, candidate)
|
||||
// Removal only ever shrinks the file, but a bound check is kept for
|
||||
// consistency with Add/Replace and to guard against pathological
|
||||
// preamble/header growth from re-serialization.
|
||||
// preamble/header growth from re-serialisation.
|
||||
if len(rendered) > s.maxBytes {
|
||||
return RemoveResult{}, fmt.Errorf("builtin: remove from section %q would exceed max file size (%d > %d bytes)", sectionName, len(rendered), s.maxBytes)
|
||||
}
|
||||
@@ -350,7 +350,7 @@ func splitBlocks(lines []string) []string {
|
||||
return blocks
|
||||
}
|
||||
|
||||
// renderSections serializes a preamble and ordered sections back into the
|
||||
// renderSections serialises a preamble and ordered sections back into the
|
||||
// on-disk markdown format.
|
||||
func renderSections(preamble string, sections []*section) string {
|
||||
var sb strings.Builder
|
||||
@@ -383,7 +383,7 @@ func renderSections(preamble string, sections []*section) string {
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// sectionChars returns the serialized character count of a single section's
|
||||
// sectionChars returns the serialised character count of a single section's
|
||||
// body (blocks only, joined as they would appear on disk).
|
||||
func sectionChars(sec *section) int {
|
||||
return len(strings.Join(sec.blocks, "\n\n"))
|
||||
|
||||
@@ -12,10 +12,10 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// RefreshInterval is how often a running service re-reads the catalog.
|
||||
// RefreshInterval is how often a running service re-reads the catalogue.
|
||||
const RefreshInterval = time.Hour
|
||||
|
||||
// Catalog holds the last model catalog a service loaded.
|
||||
// Catalog holds the last model catalogue a service loaded.
|
||||
type Catalog struct {
|
||||
cachePath string
|
||||
|
||||
@@ -23,7 +23,7 @@ type Catalog struct {
|
||||
snapshot Snapshot
|
||||
}
|
||||
|
||||
// NewCatalog caches the catalog beside the config file at cfgPath.
|
||||
// NewCatalog caches the catalogue beside the config file at cfgPath.
|
||||
func NewCatalog(cfgPath string) *Catalog {
|
||||
return &Catalog{cachePath: filepath.Join(filepath.Dir(cfgPath), "models.json")}
|
||||
}
|
||||
@@ -42,7 +42,7 @@ func (c *Catalog) Set(snapshot Snapshot) {
|
||||
c.snapshot = snapshot
|
||||
}
|
||||
|
||||
// Fetch reads the catalog, resolving provider keys through getenv.
|
||||
// Fetch reads the catalogue, resolving provider keys through getenv.
|
||||
func (c *Catalog) Fetch(ctx context.Context, getenv func(string) string, configured map[string]config.Provider) (Snapshot, error) {
|
||||
return Load(ctx, Options{CachePath: c.cachePath, Getenv: getenv, Configured: configured})
|
||||
}
|
||||
@@ -63,8 +63,8 @@ func Every(ctx context.Context, interval time.Duration, fn func()) {
|
||||
}()
|
||||
}
|
||||
|
||||
// Apply layers the catalog's providers and model limits under cfg's
|
||||
// own and returns the catalog's model references, sorted.
|
||||
// Apply layers the catalogue's providers and model limits under cfg's
|
||||
// own and returns the catalogue's model references, sorted.
|
||||
func Apply(cfg *config.Config, snapshot Snapshot) []string {
|
||||
discovered := make(map[string]config.Provider, len(snapshot.Providers))
|
||||
limits := make(map[string]config.ModelLimits)
|
||||
|
||||
@@ -51,8 +51,8 @@ type Model struct {
|
||||
Cost Cost
|
||||
}
|
||||
|
||||
// Cost is a model's list price in USD per million tokens, as the catalog
|
||||
// publishes it. A zero field means the catalog published no price.
|
||||
// Cost is a model's list price in USD per million tokens, as the catalogue
|
||||
// publishes it. A zero field means the catalogue published no price.
|
||||
type Cost struct {
|
||||
Input float64 `json:"input,omitempty"`
|
||||
Output float64 `json:"output,omitempty"`
|
||||
@@ -78,7 +78,7 @@ func Load(ctx context.Context, opts Options) (Snapshot, error) {
|
||||
snapshot, parseErr := parse(raw, opts)
|
||||
if parseErr == nil {
|
||||
if opts.CachePath != "" {
|
||||
// The downloaded catalog is already usable. A cache persistence
|
||||
// The downloaded catalogue is already usable. A cache persistence
|
||||
// failure must not prevent startup with valid in-memory data.
|
||||
_ = writeCache(opts.CachePath, raw)
|
||||
}
|
||||
@@ -182,8 +182,8 @@ func usableProvider(key string, source catalogProvider, opts Options) (Provider,
|
||||
// providerCredentialEnv returns the environment variable whose value is the
|
||||
// provider's key, and whether the provider may be served at all. A configured
|
||||
// provider is disabled when its key failed to resolve and must never fall
|
||||
// back to the catalog's ambient environment, which would send a turn with a
|
||||
// key the operator did not choose: the catalog names the environment
|
||||
// back to the catalogue's ambient environment, which would send a turn with a
|
||||
// key the operator did not choose: the catalogue names the environment
|
||||
// variables it would use, and a configured provider overrides that with the
|
||||
// variable its own resolution exported.
|
||||
func providerCredentialEnv(configured bool, override config.Provider, source catalogProvider, getenv func(string) string) (string, bool) {
|
||||
|
||||
@@ -12,7 +12,7 @@ func envFrom(values map[string]string) func(string) string {
|
||||
return func(name string) string { return values[name] }
|
||||
}
|
||||
|
||||
// modelProvider is one catalog entry shaped so usableProvider keeps it: it
|
||||
// modelProvider is one catalogue entry shaped so usableProvider keeps it: it
|
||||
// drops any provider with no tool-calling model.
|
||||
func modelProvider(env []string) catalogProvider {
|
||||
return catalogProvider{
|
||||
@@ -96,7 +96,7 @@ func TestUsableProviderCredentials(t *testing.T) {
|
||||
|
||||
// TestMergeProvidersKeepsDisabled covers the other half of a disabled
|
||||
// provider's lifetime: Apply rewrites cfg.Providers through mergeProviders,
|
||||
// and a dropped flag would let the next catalog refresh serve the ambient key
|
||||
// and a dropped flag would let the next catalogue refresh serve the ambient key
|
||||
// again.
|
||||
func TestMergeProvidersKeepsDisabled(t *testing.T) {
|
||||
merged := mergeProviders(
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
// Flow runs the authorization code flow with PKCE, so a person signs in at the
|
||||
// Flow runs the authorisation code flow with PKCE, so a person signs in at the
|
||||
// provider and the dashboard learns who they are without archie ever seeing a
|
||||
// password, holding a session, or writing any of the protocol itself: discovery,
|
||||
// the code exchange, PKCE and token verification are the libraries'.
|
||||
|
||||
@@ -122,7 +122,7 @@ func (s *Store) ResolveLegacyName(ctx context.Context, name string) (identity.Id
|
||||
// Create inserts a new identity, its display-name alias and its create audit
|
||||
// event in one transaction. An agent is assigned in the same transaction to
|
||||
// the org the request acts in, with the shipped developer role, so it is
|
||||
// authorized as soon as it exists.
|
||||
// authorised as soon as it exists.
|
||||
func (s *Store) Create(ctx context.Context, value identity.Identity, audit identity.Audit) (identity.Identity, error) {
|
||||
return s.create(ctx, value, audit, value.Kind.Agent())
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ const (
|
||||
// required frontmatter field.
|
||||
ActionIncomplete = "skill.incomplete"
|
||||
// ActionNormalized records a skill whose content was rewritten by
|
||||
// whitespace normalization.
|
||||
// whitespace normalisation.
|
||||
ActionNormalized = "skill.normalized"
|
||||
)
|
||||
|
||||
@@ -88,7 +88,7 @@ func (c *Curator) Pass(ctx context.Context, in curator.PassInput) (curator.PassR
|
||||
return curator.PassResult{Actions: actions}, nil
|
||||
}
|
||||
|
||||
// reviewOne classifies one skill and writes back a normalized version when
|
||||
// reviewOne classifies one skill and writes back a normalised version when
|
||||
// possible. It returns at most one Action.
|
||||
func (c *Curator) reviewOne(ctx context.Context, name string) ([]curator.Action, error) {
|
||||
sk, err := c.host.Skills.Read(ctx, name)
|
||||
|
||||
@@ -49,7 +49,7 @@ type Runs interface {
|
||||
TaskForCredential(ctx context.Context, token string) (*workflow.Task, error)
|
||||
}
|
||||
|
||||
// Server delivers authorized requests through Deliver.
|
||||
// Server delivers authorised requests through Deliver.
|
||||
type Server struct {
|
||||
Runs Runs
|
||||
// Deliver sends through a channel the run's org owns.
|
||||
|
||||
@@ -71,7 +71,7 @@ func FromJSON(raw jsontext.Value) Payload {
|
||||
}
|
||||
|
||||
// Redact replaces every credential in a JSON value with a marker. A key that
|
||||
// names a credential is redacted whole; a value that reads as an authorization
|
||||
// names a credential is redacted whole; a value that reads as an authorisation
|
||||
// header is redacted wherever it appears. A payload that can't be decoded is
|
||||
// replaced rather than stored unchanged, because its credentials can't be
|
||||
// found.
|
||||
@@ -132,7 +132,7 @@ func sensitiveKey(key string) bool {
|
||||
return compact == "token" || strings.HasSuffix(compact, "token")
|
||||
}
|
||||
|
||||
// looksSecret reports whether a value is an authorization header, whatever
|
||||
// looksSecret reports whether a value is an authorisation header, whatever
|
||||
// key it arrived under.
|
||||
func looksSecret(value string) bool {
|
||||
s := strings.TrimSpace(value)
|
||||
|
||||
@@ -41,14 +41,35 @@ func (r *Registry) Routes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /readyz", r.ready)
|
||||
}
|
||||
|
||||
// Result is the outcome of one readiness check; Error is empty when it passed.
|
||||
type Result struct {
|
||||
Name string `json:"name"`
|
||||
Error string `json:"error,omitzero"`
|
||||
}
|
||||
|
||||
// Results runs every check and returns the outcomes in name order. A failing
|
||||
// check does not stop the others.
|
||||
func (r *Registry) Results(ctx context.Context) []Result {
|
||||
names := r.names()
|
||||
out := make([]Result, 0, len(names))
|
||||
for _, name := range names {
|
||||
res := Result{Name: name}
|
||||
if err := r.check(name)(ctx); err != nil {
|
||||
res.Error = err.Error()
|
||||
}
|
||||
out = append(out, res)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *Registry) ready(w http.ResponseWriter, req *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(req.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
failures := map[string]string{}
|
||||
for _, name := range r.names() {
|
||||
if err := r.check(name)(ctx); err != nil {
|
||||
failures[name] = err.Error()
|
||||
for _, res := range r.Results(ctx) {
|
||||
if res.Error != "" {
|
||||
failures[res.Name] = res.Error
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
@@ -43,50 +43,120 @@ func OK[T any](v T) *Reply[T] {
|
||||
return &Reply[T]{Body: v}
|
||||
}
|
||||
|
||||
type access int
|
||||
// ErrDenied is what an Authorizer returns when the caller's grant does not
|
||||
// cover the operation.
|
||||
var ErrDenied = errors.New("not permitted")
|
||||
|
||||
// ErrUnavailable is what an Authorizer returns when it cannot decide, such as
|
||||
// when the policy chain is not loaded. The operation is then refused.
|
||||
var ErrUnavailable = errors.New("authorization is unavailable")
|
||||
|
||||
// Authorizer decides whether the caller acting in ctx may take action on a
|
||||
// resource of kind. It returns ErrDenied, ErrUnavailable or nil.
|
||||
type Authorizer interface {
|
||||
Allow(ctx context.Context, action, kind string) error
|
||||
}
|
||||
|
||||
type accessKind int
|
||||
|
||||
const (
|
||||
accessAdmin access = iota
|
||||
accessSignedIn
|
||||
// accessUnset is the zero Access. An operation holding it is refused, so
|
||||
// an operation that declares nothing never runs.
|
||||
accessUnset accessKind = iota
|
||||
accessPublic
|
||||
accessAuthorized
|
||||
)
|
||||
|
||||
// Access is how an operation is guarded. Register requires one, and the zero
|
||||
// value refuses every request.
|
||||
type Access struct {
|
||||
kind accessKind
|
||||
action string
|
||||
resource string
|
||||
admin bool
|
||||
}
|
||||
|
||||
// Public is an operation callable without a credential: liveness, setup and
|
||||
// sign-in.
|
||||
func Public() Access { return Access{kind: accessPublic} }
|
||||
|
||||
// Authorized is an operation that needs an authenticated caller whose grant
|
||||
// covers action on a resource of kind, as the policy chain decides.
|
||||
func Authorized[A, K ~string](action A, kind K) Access {
|
||||
return Access{kind: accessAuthorized, action: string(action), resource: string(kind)}
|
||||
}
|
||||
|
||||
// AdminAuthorized is Authorised for an operation that also needs an instance
|
||||
// administrator, whatever the policy chain would allow.
|
||||
func AdminAuthorized[A, K ~string](action A, kind K) Access {
|
||||
a := Authorized(action, kind)
|
||||
a.admin = true
|
||||
return a
|
||||
}
|
||||
|
||||
// Declared reports the action and resource kind an authorised operation is
|
||||
// decided on, and false for any other operation.
|
||||
func (a Access) Declared() (action, kind string, ok bool) {
|
||||
return a.action, a.resource, a.kind == accessAuthorized
|
||||
}
|
||||
|
||||
// IsPublic reports whether the operation needs no credential.
|
||||
func (a Access) IsPublic() bool { return a.kind == accessPublic }
|
||||
|
||||
const accessKey = "archie-access"
|
||||
|
||||
// Public marks op as callable without a credential: signing in, for one.
|
||||
func Public(op huma.Operation) huma.Operation {
|
||||
op.Security = []map[string][]string{{}}
|
||||
return withAccess(op, accessPublic)
|
||||
}
|
||||
|
||||
// SignedIn marks op as callable by any authenticated caller. Every other
|
||||
// operation needs an instance administrator.
|
||||
func SignedIn(op huma.Operation) huma.Operation {
|
||||
return withAccess(op, accessSignedIn)
|
||||
}
|
||||
|
||||
func withAccess(op huma.Operation, a access) huma.Operation {
|
||||
// Register adds an operation guarded as access says. It is the only way to
|
||||
// register one on this API, so every operation declares who may call it.
|
||||
func Register[I, O any](api huma.API, access Access, op huma.Operation, handler func(context.Context, *I) (*O, error)) {
|
||||
if op.Metadata == nil {
|
||||
op.Metadata = map[string]any{}
|
||||
}
|
||||
op.Metadata[accessKey] = a
|
||||
return op
|
||||
op.Metadata[accessKey] = access
|
||||
if access.kind == accessPublic {
|
||||
op.Security = []map[string][]string{{}}
|
||||
}
|
||||
huma.Register(api, op, handler)
|
||||
}
|
||||
|
||||
func accessOf(op *huma.Operation) access {
|
||||
// AccessOf returns how a registered operation is guarded. An operation not
|
||||
// registered through Register has the zero Access.
|
||||
func AccessOf(op *huma.Operation) Access {
|
||||
if op == nil {
|
||||
return accessAdmin
|
||||
return Access{}
|
||||
}
|
||||
a, _ := op.Metadata[accessKey].(access)
|
||||
a, _ := op.Metadata[accessKey].(Access)
|
||||
return a
|
||||
}
|
||||
|
||||
// Route is a registered operation and how it is guarded.
|
||||
type Route struct {
|
||||
ID, Method, Path string
|
||||
Access Access
|
||||
}
|
||||
|
||||
// Routes returns every operation registered on api with how it is guarded.
|
||||
func Routes(api huma.API) []Route {
|
||||
var out []Route
|
||||
for p, item := range api.OpenAPI().Paths {
|
||||
for method, op := range map[string]*huma.Operation{
|
||||
http.MethodGet: item.Get, http.MethodPut: item.Put, http.MethodPost: item.Post,
|
||||
http.MethodDelete: item.Delete, http.MethodPatch: item.Patch, http.MethodHead: item.Head,
|
||||
http.MethodOptions: item.Options, http.MethodTrace: item.Trace,
|
||||
} {
|
||||
if op != nil {
|
||||
out = append(out, Route{ID: op.OperationID, Method: method, Path: p, Access: AccessOf(op)})
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// New returns an API on mux whose operations authenticate through auth.
|
||||
// Every unsafe request must also pass cross-origin protection, since a
|
||||
// browser sends the session cookie with any request to this origin.
|
||||
func New(mux *http.ServeMux, version string, auth Authenticator) huma.API {
|
||||
func New(mux *http.ServeMux, version string, auth Authenticator, authz Authorizer) huma.API {
|
||||
api := humago.New(mux, config(version))
|
||||
api.UseMiddleware(guard(api, auth, http.NewCrossOriginProtection()))
|
||||
api.UseMiddleware(guard(api, auth, authz, http.NewCrossOriginProtection()))
|
||||
return api
|
||||
}
|
||||
|
||||
@@ -106,17 +176,22 @@ func config(version string) huma.Config {
|
||||
return cfg
|
||||
}
|
||||
|
||||
func guard(api huma.API, auth Authenticator, origins *http.CrossOriginProtection) func(huma.Context, func(huma.Context)) {
|
||||
func guard(api huma.API, auth Authenticator, authz Authorizer, origins *http.CrossOriginProtection) func(huma.Context, func(huma.Context)) {
|
||||
return func(ctx huma.Context, next func(huma.Context)) {
|
||||
r, _ := humago.Unwrap(ctx)
|
||||
if err := origins.Check(r); err != nil {
|
||||
_ = huma.WriteErr(api, ctx, http.StatusForbidden, "cross-origin request refused")
|
||||
return
|
||||
}
|
||||
need := accessOf(ctx.Operation())
|
||||
if need == accessPublic {
|
||||
need := AccessOf(ctx.Operation())
|
||||
switch need.kind {
|
||||
case accessPublic:
|
||||
next(ctx)
|
||||
return
|
||||
case accessAuthorized:
|
||||
default:
|
||||
_ = huma.WriteErr(api, ctx, http.StatusForbidden, "operation declares no access")
|
||||
return
|
||||
}
|
||||
acting, admin, err := auth.Authenticate(ctx.Context(), r)
|
||||
switch {
|
||||
@@ -127,14 +202,35 @@ func guard(api huma.API, auth Authenticator, origins *http.CrossOriginProtection
|
||||
case err != nil:
|
||||
_ = huma.WriteErr(api, ctx, http.StatusServiceUnavailable, "authentication is unavailable")
|
||||
return
|
||||
case need == accessAdmin && !admin:
|
||||
case need.admin && !admin:
|
||||
_ = huma.WriteErr(api, ctx, http.StatusForbidden, "instance administrator required")
|
||||
return
|
||||
}
|
||||
if status, msg := decide(acting, authz, need); status != 0 {
|
||||
_ = huma.WriteErr(api, ctx, status, msg)
|
||||
return
|
||||
}
|
||||
next(huma.WithContext(ctx, acting))
|
||||
}
|
||||
}
|
||||
|
||||
// decide asks authz whether the authenticated caller may take the declared
|
||||
// action. It returns a status of 0 to let the request through. With no
|
||||
// authorizer the operation is refused.
|
||||
func decide(acting context.Context, authz Authorizer, need Access) (status int, message string) {
|
||||
if authz == nil {
|
||||
return http.StatusServiceUnavailable, ErrUnavailable.Error()
|
||||
}
|
||||
switch err := authz.Allow(acting, need.action, need.resource); {
|
||||
case err == nil:
|
||||
return 0, ""
|
||||
case errors.Is(err, ErrDenied):
|
||||
return http.StatusForbidden, ErrDenied.Error()
|
||||
default:
|
||||
return http.StatusServiceUnavailable, ErrUnavailable.Error()
|
||||
}
|
||||
}
|
||||
|
||||
// schemaName prefixes a type of Archie's own with its package, since modules
|
||||
// reuse short names like Source and Request.
|
||||
func schemaName(t reflect.Type, hint string) string {
|
||||
|
||||
@@ -26,46 +26,88 @@ func (headerAuth) Authenticate(ctx context.Context, r *http.Request) (context.Co
|
||||
}
|
||||
}
|
||||
|
||||
// TestOperationAccess guards the API's authentication boundary: public
|
||||
// operations need no credential, every other operation needs one, only an
|
||||
// instance administrator reaches an operation not marked otherwise, and a
|
||||
// cross-origin browser request cannot use the session cookie to change
|
||||
// anything.
|
||||
// grants answers Allow from a fixed set of "action kind" pairs and records
|
||||
// what it was asked.
|
||||
type grants struct {
|
||||
allowed map[string]bool
|
||||
err error
|
||||
asked []string
|
||||
}
|
||||
|
||||
func (g *grants) Allow(_ context.Context, action, kind string) error {
|
||||
g.asked = append(g.asked, action+" "+kind)
|
||||
switch {
|
||||
case g.err != nil:
|
||||
return g.err
|
||||
case g.allowed[action+" "+kind]:
|
||||
return nil
|
||||
}
|
||||
return ErrDenied
|
||||
}
|
||||
|
||||
// TestOperationAccess guards the API's enforcement boundary: public
|
||||
// operations need no credential, every other operation needs one and a grant
|
||||
// from the authorizer before its handler runs, an operation that declares no
|
||||
// access never runs, and a cross-origin browser request cannot use the
|
||||
// session cookie to change anything.
|
||||
func TestOperationAccess(t *testing.T) {
|
||||
tests := []struct {
|
||||
name, method, path, caller, fetchSite string
|
||||
grants *grants
|
||||
noAuthorizer bool
|
||||
want int
|
||||
wantRan bool
|
||||
}{
|
||||
{name: "public without a credential", method: http.MethodGet, path: "/public", want: http.StatusOK},
|
||||
{name: "public sign-in from this origin", method: http.MethodPost, path: "/public", fetchSite: "same-origin", want: http.StatusOK},
|
||||
{name: "public without a credential", method: http.MethodGet, path: "/public", want: http.StatusOK, wantRan: true},
|
||||
{name: "public sign-in from this origin", method: http.MethodPost, path: "/public", fetchSite: "same-origin", want: http.StatusOK, wantRan: true},
|
||||
{name: "public sign-in from another origin", method: http.MethodPost, path: "/public", fetchSite: "cross-site", want: http.StatusForbidden},
|
||||
{name: "signed-in without a credential", method: http.MethodGet, path: "/signed-in", want: http.StatusUnauthorized},
|
||||
{name: "signed-in as a person", method: http.MethodGet, path: "/signed-in", caller: "person", want: http.StatusOK},
|
||||
{name: "a stream without a credential", method: http.MethodGet, path: "/stream", want: http.StatusUnauthorized},
|
||||
{name: "a stream as a person", method: http.MethodGet, path: "/stream", caller: "person", want: http.StatusOK},
|
||||
{name: "admin without a credential", method: http.MethodGet, path: "/admin", want: http.StatusUnauthorized},
|
||||
{name: "admin as a person", method: http.MethodGet, path: "/admin", caller: "person", want: http.StatusForbidden},
|
||||
{name: "admin as the admin", method: http.MethodGet, path: "/admin", caller: "admin", want: http.StatusOK},
|
||||
{name: "mutation from this origin", method: http.MethodPost, path: "/admin", caller: "admin", fetchSite: "same-origin", want: http.StatusOK},
|
||||
{name: "mutation from another origin", method: http.MethodPost, path: "/admin", caller: "admin", fetchSite: "cross-site", want: http.StatusForbidden},
|
||||
{name: "a failed lookup is not a refusal", method: http.MethodGet, path: "/admin", caller: "broken", want: http.StatusServiceUnavailable},
|
||||
{name: "authorized without a credential", method: http.MethodGet, path: "/read", want: http.StatusUnauthorized},
|
||||
{name: "authorized and granted", method: http.MethodGet, path: "/read", caller: "person", grants: &grants{allowed: map[string]bool{"read thing": true}}, want: http.StatusOK, wantRan: true},
|
||||
{name: "authorized but not granted", method: http.MethodGet, path: "/read", caller: "person", grants: &grants{}, want: http.StatusForbidden},
|
||||
{name: "authorized while the chain is unavailable", method: http.MethodGet, path: "/read", caller: "person", grants: &grants{err: ErrUnavailable}, want: http.StatusServiceUnavailable},
|
||||
{name: "authorized when the authorizer fails", method: http.MethodGet, path: "/read", caller: "person", grants: &grants{err: errors.New("database down")}, want: http.StatusServiceUnavailable},
|
||||
{name: "authorized with no authorizer", method: http.MethodGet, path: "/read", caller: "admin", noAuthorizer: true, want: http.StatusServiceUnavailable},
|
||||
{name: "a stream not granted", method: http.MethodGet, path: "/stream", caller: "person", grants: &grants{}, want: http.StatusForbidden},
|
||||
{name: "a stream granted", method: http.MethodGet, path: "/stream", caller: "person", grants: &grants{allowed: map[string]bool{"read thing": true}}, want: http.StatusOK, wantRan: true},
|
||||
{name: "admin operation as a person with the grant", method: http.MethodGet, path: "/admin", caller: "person", grants: &grants{allowed: map[string]bool{"update thing": true}}, want: http.StatusForbidden},
|
||||
{name: "admin operation as the admin without the grant", method: http.MethodGet, path: "/admin", caller: "admin", grants: &grants{}, want: http.StatusForbidden},
|
||||
{name: "admin operation as the admin with the grant", method: http.MethodGet, path: "/admin", caller: "admin", grants: &grants{allowed: map[string]bool{"update thing": true}}, want: http.StatusOK, wantRan: true},
|
||||
{name: "an operation that declares nothing", method: http.MethodGet, path: "/undeclared", caller: "admin", grants: &grants{allowed: map[string]bool{" ": true}}, want: http.StatusForbidden},
|
||||
{name: "mutation from this origin", method: http.MethodPost, path: "/admin", caller: "admin", fetchSite: "same-origin", grants: &grants{allowed: map[string]bool{"update thing": true}}, want: http.StatusOK, wantRan: true},
|
||||
{name: "mutation from another origin", method: http.MethodPost, path: "/admin", caller: "admin", fetchSite: "cross-site", grants: &grants{allowed: map[string]bool{"update thing": true}}, want: http.StatusForbidden},
|
||||
{name: "a failed lookup is not a refusal", method: http.MethodGet, path: "/read", caller: "broken", grants: &grants{}, want: http.StatusServiceUnavailable},
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
api := New(mux, "test", headerAuth{})
|
||||
reached := func(context.Context, *struct{}) (*Reply[string], error) { return OK("reached"), nil }
|
||||
for _, method := range []string{http.MethodGet, http.MethodPost} {
|
||||
huma.Register(api, Public(huma.Operation{OperationID: "public-" + method, Method: method, Path: "/public"}), reached)
|
||||
huma.Register(api, SignedIn(huma.Operation{OperationID: "signed-in-" + method, Method: method, Path: "/signed-in"}), reached)
|
||||
huma.Register(api, huma.Operation{OperationID: "admin-" + method, Method: method, Path: "/admin"}, reached)
|
||||
}
|
||||
// A streamed response writes its own status, so it must still pass the
|
||||
// guard before its body runs.
|
||||
huma.Register(api, SignedIn(huma.Operation{OperationID: "stream", Method: http.MethodGet, Path: "/stream"}),
|
||||
func(context.Context, *struct{}) (*huma.StreamResponse, error) {
|
||||
return &huma.StreamResponse{Body: func(hc huma.Context) { hc.SetStatus(http.StatusOK) }}, nil
|
||||
})
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
var authz Authorizer
|
||||
if !tt.noAuthorizer {
|
||||
if tt.grants == nil {
|
||||
tt.grants = &grants{}
|
||||
}
|
||||
authz = tt.grants
|
||||
}
|
||||
api := New(mux, "test", headerAuth{}, authz)
|
||||
ran := false
|
||||
reached := func(context.Context, *struct{}) (*Reply[string], error) {
|
||||
ran = true
|
||||
return OK("reached"), nil
|
||||
}
|
||||
for _, method := range []string{http.MethodGet, http.MethodPost} {
|
||||
Register(api, Public(), huma.Operation{OperationID: "public-" + method, Method: method, Path: "/public"}, reached)
|
||||
Register(api, Authorized("read", "thing"), huma.Operation{OperationID: "read-" + method, Method: method, Path: "/read"}, reached)
|
||||
Register(api, AdminAuthorized("update", "thing"), huma.Operation{OperationID: "admin-" + method, Method: method, Path: "/admin"}, reached)
|
||||
// A direct huma registration declares no access.
|
||||
huma.Register(api, huma.Operation{OperationID: "undeclared-" + method, Method: method, Path: "/undeclared"}, reached)
|
||||
}
|
||||
// A streamed response writes its own status, so it must still pass
|
||||
// the guard before its body runs.
|
||||
Register(api, Authorized("read", "thing"), huma.Operation{OperationID: "stream", Method: http.MethodGet, Path: "/stream"},
|
||||
func(context.Context, *struct{}) (*huma.StreamResponse, error) {
|
||||
ran = true
|
||||
return &huma.StreamResponse{Body: func(hc huma.Context) { hc.SetStatus(http.StatusOK) }}, nil
|
||||
})
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), tt.method, tt.path, nil)
|
||||
if tt.caller != "" {
|
||||
req.Header.Set("X-Test-Caller", tt.caller)
|
||||
@@ -78,6 +120,34 @@ func TestOperationAccess(t *testing.T) {
|
||||
if rec.Code != tt.want {
|
||||
t.Fatalf("status = %d, want %d: %s", rec.Code, tt.want, rec.Body)
|
||||
}
|
||||
if ran != tt.wantRan {
|
||||
t.Fatalf("handler ran = %v, want %v", ran, tt.wantRan)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestOperationsDeclareAccess guards the registry the route table is checked
|
||||
// from: an operation registered through Register reports what it declared, and
|
||||
// one registered directly reports none.
|
||||
func TestOperationsDeclareAccess(t *testing.T) {
|
||||
api := New(http.NewServeMux(), "test", headerAuth{}, nil)
|
||||
noop := func(context.Context, *struct{}) (*Reply[string], error) { return OK(""), nil }
|
||||
Register(api, Public(), huma.Operation{OperationID: "p", Method: http.MethodGet, Path: "/p"}, noop)
|
||||
Register(api, Authorized("read", "thing"), huma.Operation{OperationID: "a", Method: http.MethodGet, Path: "/a"}, noop)
|
||||
huma.Register(api, huma.Operation{OperationID: "u", Method: http.MethodGet, Path: "/u"}, noop)
|
||||
|
||||
got := map[string]Access{}
|
||||
for _, r := range Routes(api) {
|
||||
got[r.ID] = r.Access
|
||||
}
|
||||
if !got["p"].IsPublic() {
|
||||
t.Error("p is not public")
|
||||
}
|
||||
if action, kind, ok := got["a"].Declared(); !ok || action != "read" || kind != "thing" {
|
||||
t.Errorf("a declares %q %q %v", action, kind, ok)
|
||||
}
|
||||
if _, _, ok := got["u"].Declared(); ok || got["u"].IsPublic() {
|
||||
t.Error("u declares access it never registered")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA governance;
|
||||
|
||||
-- A model provider is an API endpoint that serves models: its provider class,
|
||||
-- its base URL and the credential that holds its API key. A model alias refers
|
||||
-- to a provider and one of its models, so several aliases can share a provider.
|
||||
CREATE TABLE governance.model_providers (
|
||||
org_id text NOT NULL,
|
||||
name text NOT NULL CHECK (name ~ '^[a-z0-9][a-z0-9_.-]{0,62}$'),
|
||||
class text NOT NULL,
|
||||
base_url text NOT NULL,
|
||||
api_key_credential text NOT NULL DEFAULT '',
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (org_id, name)
|
||||
);
|
||||
|
||||
-- A model role records the model an organisation uses for one job.
|
||||
CREATE TABLE governance.model_roles (
|
||||
org_id text NOT NULL,
|
||||
role text NOT NULL CHECK ((role = 'agent') OR ((role <> 'agent:default') AND (role ~ '^agent:[a-zA-Z0-9][a-zA-Z0-9_.-]{0,62}$'))),
|
||||
model text NOT NULL,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
provider text NOT NULL,
|
||||
PRIMARY KEY (org_id, role),
|
||||
FOREIGN KEY (org_id, provider) REFERENCES governance.model_providers (org_id, name)
|
||||
);
|
||||
|
||||
-- An organisation's settings are one row. When the row is missing, every
|
||||
-- setting has its default value.
|
||||
--
|
||||
-- The chat limits bound what one person and the whole organisation can spend:
|
||||
-- tokens per turn, turns and tool calls per hour, and tokens per day. A request
|
||||
-- over a limit is refused, never queued.
|
||||
CREATE TABLE governance.settings (
|
||||
org_id text PRIMARY KEY,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
approval_deadline_ms bigint NOT NULL,
|
||||
propose_autonomy_after integer NOT NULL DEFAULT 3 CHECK (propose_autonomy_after BETWEEN 1 AND 100),
|
||||
frozen boolean NOT NULL DEFAULT false,
|
||||
recurrence_threshold integer NOT NULL DEFAULT 5,
|
||||
default_owner text NOT NULL DEFAULT '',
|
||||
escalation jsonb NOT NULL DEFAULT '[]',
|
||||
attempts_per_run integer NOT NULL DEFAULT 20,
|
||||
timing jsonb NOT NULL DEFAULT '{}',
|
||||
actions_per_run integer NOT NULL DEFAULT 10,
|
||||
actions_per_day integer NOT NULL DEFAULT 100,
|
||||
chat_turn_tokens integer NOT NULL DEFAULT 100000 CHECK (chat_turn_tokens > 0),
|
||||
chat_person_turns_per_hour integer NOT NULL DEFAULT 60 CHECK (chat_person_turns_per_hour > 0),
|
||||
chat_org_turns_per_hour integer NOT NULL DEFAULT 600 CHECK (chat_org_turns_per_hour > 0),
|
||||
chat_person_tool_calls_per_hour integer NOT NULL DEFAULT 300 CHECK (chat_person_tool_calls_per_hour > 0),
|
||||
chat_org_tool_calls_per_hour integer NOT NULL DEFAULT 3000 CHECK (chat_org_tool_calls_per_hour > 0),
|
||||
chat_person_tokens_per_day bigint NOT NULL DEFAULT 2000000 CHECK (chat_person_tokens_per_day > 0),
|
||||
chat_org_tokens_per_day bigint NOT NULL DEFAULT 20000000 CHECK (chat_org_tokens_per_day > 0),
|
||||
CHECK (chat_person_turns_per_hour <= chat_org_turns_per_hour),
|
||||
CHECK (chat_person_tool_calls_per_hour <= chat_org_tool_calls_per_hour),
|
||||
CHECK (chat_person_tokens_per_day <= chat_org_tokens_per_day)
|
||||
);
|
||||
|
||||
CREATE TABLE governance.identities (
|
||||
id text PRIMARY KEY,
|
||||
kind text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
lifecycle text NOT NULL,
|
||||
version bigint NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE governance.identity_aliases (
|
||||
alias text PRIMARY KEY,
|
||||
identity_id text NOT NULL REFERENCES governance.identities (id)
|
||||
);
|
||||
CREATE UNIQUE INDEX idx_governance_identity_aliases_alias ON governance.identity_aliases (lower(alias));
|
||||
|
||||
CREATE TABLE governance.identity_events (
|
||||
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
identity_id text NOT NULL,
|
||||
event_type text NOT NULL,
|
||||
from_lifecycle text NOT NULL,
|
||||
to_lifecycle text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
actor_id text NOT NULL,
|
||||
source text NOT NULL,
|
||||
request_id text NOT NULL UNIQUE,
|
||||
at timestamptz NOT NULL,
|
||||
org_id text CHECK ((org_id IS NULL) OR (org_id <> ''))
|
||||
);
|
||||
CREATE INDEX idx_governance_identity_events_identity ON governance.identity_events (identity_id, id);
|
||||
CREATE INDEX idx_governance_identity_events_org_at ON governance.identity_events (org_id, at DESC, id DESC);
|
||||
|
||||
CREATE TABLE governance.identity_subjects (
|
||||
issuer text NOT NULL,
|
||||
subject text NOT NULL,
|
||||
identity_id text NOT NULL REFERENCES governance.identities (id),
|
||||
bound_at timestamptz NOT NULL,
|
||||
name text NOT NULL DEFAULT '',
|
||||
expires_at timestamptz,
|
||||
last_used_at timestamptz,
|
||||
PRIMARY KEY (issuer, subject)
|
||||
);
|
||||
CREATE INDEX idx_governance_identity_subjects_identity ON governance.identity_subjects (identity_id);
|
||||
|
||||
CREATE TABLE governance.orgs (
|
||||
id text PRIMARY KEY,
|
||||
name text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
version bigint NOT NULL DEFAULT 1
|
||||
);
|
||||
|
||||
CREATE TABLE governance.workspaces (
|
||||
id text NOT NULL,
|
||||
org_id text NOT NULL REFERENCES governance.orgs (id),
|
||||
name text NOT NULL,
|
||||
environment text NOT NULL DEFAULT '',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
version bigint NOT NULL DEFAULT 1,
|
||||
PRIMARY KEY (org_id, id)
|
||||
);
|
||||
|
||||
CREATE TABLE governance.memberships (
|
||||
identity_id text NOT NULL REFERENCES governance.identities (id),
|
||||
org_id text NOT NULL REFERENCES governance.orgs (id),
|
||||
workspace_id text,
|
||||
role text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
FOREIGN KEY (org_id, workspace_id) REFERENCES governance.workspaces (org_id, id)
|
||||
);
|
||||
CREATE UNIQUE INDEX idx_governance_memberships_identity ON governance.memberships (identity_id, org_id, COALESCE(workspace_id, ''));
|
||||
CREATE INDEX idx_governance_memberships_org ON governance.memberships (org_id);
|
||||
|
||||
CREATE TABLE governance.org_agents (
|
||||
identity_id text PRIMARY KEY REFERENCES governance.identities (id),
|
||||
org_id text NOT NULL REFERENCES governance.orgs (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX idx_governance_org_agents_org ON governance.org_agents (org_id);
|
||||
|
||||
CREATE TABLE governance.accounts (
|
||||
identity_id text PRIMARY KEY REFERENCES governance.identities (id),
|
||||
email text NOT NULL UNIQUE CHECK (email = lower(email)),
|
||||
password_hash text NOT NULL,
|
||||
recovery_hash text,
|
||||
failed_attempts integer NOT NULL DEFAULT 0,
|
||||
locked_until timestamptz,
|
||||
last_sign_in_at timestamptz
|
||||
);
|
||||
|
||||
CREATE TABLE governance.account_sessions (
|
||||
token_hash text PRIMARY KEY,
|
||||
identity_id text NOT NULL REFERENCES governance.identities (id) ON DELETE CASCADE,
|
||||
expires_at timestamptz NOT NULL,
|
||||
issued_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX idx_governance_account_sessions_identity ON governance.account_sessions (identity_id);
|
||||
CREATE INDEX idx_governance_account_sessions_expiry ON governance.account_sessions (expires_at);
|
||||
|
||||
CREATE TABLE governance.authentication_settings (
|
||||
singleton boolean DEFAULT true PRIMARY KEY CHECK (singleton),
|
||||
public_url text NOT NULL,
|
||||
oidc_issuer text NOT NULL DEFAULT '',
|
||||
oidc_audience text NOT NULL DEFAULT '',
|
||||
oidc_client_id text NOT NULL DEFAULT '',
|
||||
trusted_proxies jsonb NOT NULL DEFAULT '[]'
|
||||
);
|
||||
|
||||
CREATE TABLE governance.passkeys (
|
||||
credential_id text PRIMARY KEY,
|
||||
identity_id text NOT NULL REFERENCES governance.identities (id),
|
||||
name text NOT NULL,
|
||||
credential jsonb NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX idx_governance_passkeys_identity ON governance.passkeys (identity_id);
|
||||
|
||||
CREATE TABLE governance.passkey_ceremonies (
|
||||
token_hash text PRIMARY KEY,
|
||||
identity_id text NOT NULL,
|
||||
registration boolean NOT NULL,
|
||||
session_data jsonb NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
subject text NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX idx_governance_passkey_ceremonies_expiry ON governance.passkey_ceremonies (expires_at);
|
||||
|
||||
CREATE TABLE governance.access_policies (
|
||||
level text NOT NULL CHECK (level IN ('instance', 'org', 'workspace', 'object')),
|
||||
org_id text NOT NULL DEFAULT '',
|
||||
workspace_id text NOT NULL DEFAULT '',
|
||||
object_kind text NOT NULL DEFAULT '',
|
||||
object_id text NOT NULL DEFAULT '',
|
||||
policy_id text NOT NULL,
|
||||
text text NOT NULL,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (level, org_id, workspace_id, object_kind, object_id, policy_id)
|
||||
);
|
||||
|
||||
CREATE TABLE governance.access_policy_versions (
|
||||
level text NOT NULL CHECK (level IN ('instance', 'org', 'workspace', 'object')),
|
||||
org_id text NOT NULL DEFAULT '',
|
||||
workspace_id text NOT NULL DEFAULT '',
|
||||
version bigint NOT NULL DEFAULT 1,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (level, org_id, workspace_id)
|
||||
);
|
||||
|
||||
CREATE TABLE governance.access_policy_revision (
|
||||
only_row boolean DEFAULT true PRIMARY KEY CHECK (only_row),
|
||||
version bigint NOT NULL DEFAULT 1,
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE governance.access_decisions (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
principal text NOT NULL,
|
||||
action text NOT NULL,
|
||||
resource_kind text NOT NULL,
|
||||
resource_id text NOT NULL,
|
||||
level text NOT NULL,
|
||||
policies text[] NOT NULL DEFAULT '{}',
|
||||
minute_at timestamptz NOT NULL DEFAULT date_trunc ('minute', now()),
|
||||
count bigint NOT NULL DEFAULT 1,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
outcome text NOT NULL DEFAULT 'denied' CHECK (outcome IN ('allowed', 'denied'))
|
||||
);
|
||||
CREATE UNIQUE INDEX idx_governance_access_decisions_dedup ON governance.access_decisions (org_id, principal, action, resource_kind, resource_id, outcome, level, policies, minute_at);
|
||||
|
||||
-- Each change to an organisation or workspace name, with who made it and the
|
||||
-- old and new names.
|
||||
CREATE TABLE governance.org_events (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
org_id text NOT NULL REFERENCES governance.orgs (id),
|
||||
workspace_id text NOT NULL DEFAULT '',
|
||||
event_type text NOT NULL,
|
||||
actor_id text NOT NULL,
|
||||
actor_name text NOT NULL,
|
||||
request_id text NOT NULL UNIQUE,
|
||||
old_name text NOT NULL,
|
||||
new_name text NOT NULL,
|
||||
at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX idx_governance_org_events_org_at ON governance.org_events (org_id, at DESC, id DESC);
|
||||
|
||||
-- A link code is a single-use code that links a channel credential to the
|
||||
-- account that requested it. issuer is the connector that redeems the code.
|
||||
-- Only the code's hash is stored.
|
||||
CREATE TABLE governance.link_codes (
|
||||
code_hash text PRIMARY KEY,
|
||||
identity_id text NOT NULL REFERENCES governance.identities (id),
|
||||
issuer text NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
used_at timestamptz
|
||||
);
|
||||
CREATE INDEX idx_governance_link_codes_identity ON governance.link_codes (identity_id);
|
||||
|
||||
-- The organisation's instructions to its agents. They are added to every
|
||||
-- agent's system prompt after Archie's own instructions.
|
||||
CREATE TABLE governance.instructions (
|
||||
org_id text PRIMARY KEY,
|
||||
body text NOT NULL,
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- The model aliases workflows and chat may use. A null list allows any alias.
|
||||
CREATE TABLE governance.model_policy (
|
||||
org_id text PRIMARY KEY,
|
||||
workflow_aliases jsonb,
|
||||
chat_aliases jsonb,
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- The mail server the instance sends invitations through. The password is
|
||||
-- sealed and never read back through the API.
|
||||
CREATE TABLE governance.mail_settings (
|
||||
singleton boolean DEFAULT true PRIMARY KEY CHECK (singleton),
|
||||
host text NOT NULL,
|
||||
port integer NOT NULL CHECK (port BETWEEN 1 AND 65535),
|
||||
security text NOT NULL CHECK (security IN ('tls', 'starttls', 'none')),
|
||||
username text NOT NULL DEFAULT '',
|
||||
password_sealed bytea NOT NULL DEFAULT '\x'::bytea,
|
||||
from_address text NOT NULL,
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- An invitation to join an organisation, sent to an email address that has no
|
||||
-- account yet. Accepting it sets up a local account with the invited role.
|
||||
-- Only the token's hash is stored, and an address has at most one open
|
||||
-- invitation per organisation.
|
||||
CREATE TABLE governance.invites (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL REFERENCES governance.orgs (id),
|
||||
workspace_id text,
|
||||
email text NOT NULL CHECK (email = lower(email)),
|
||||
role text NOT NULL,
|
||||
token_hash text NOT NULL UNIQUE,
|
||||
invited_by_id text NOT NULL REFERENCES governance.identities (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
sent_at timestamptz,
|
||||
send_error text NOT NULL DEFAULT '',
|
||||
accepted_at timestamptz,
|
||||
accepted_identity_id text REFERENCES governance.identities (id),
|
||||
revoked_at timestamptz,
|
||||
FOREIGN KEY (org_id, workspace_id) REFERENCES governance.workspaces (org_id, id),
|
||||
CHECK ((accepted_at IS NULL) = (accepted_identity_id IS NULL)),
|
||||
CHECK ((accepted_at IS NULL) OR (revoked_at IS NULL))
|
||||
);
|
||||
CREATE UNIQUE INDEX invites_open ON governance.invites (org_id, email) WHERE ((accepted_at IS NULL) AND (revoked_at IS NULL));
|
||||
|
||||
-- The audit log records every change on the platform: who or what made it,
|
||||
-- what changed, why, and how it went. org_id is empty for a change to the
|
||||
-- instance itself, such as accepting a package.
|
||||
--
|
||||
-- Entries form one chain: each holds the digest of the entry before it, so a
|
||||
-- missing or edited entry is detectable. The unique prev_digest keeps the
|
||||
-- chain linear when two writers append at once, and only the first entry has
|
||||
-- none.
|
||||
--
|
||||
-- actor_name is the actor's name when the change was made, kept beside its ID
|
||||
-- so the entry still reads correctly after a rename. request and response are
|
||||
-- the payloads of a call that changed something outside Archie, without
|
||||
-- credentials. why holds the cause, the guard verdicts, the approval and the
|
||||
-- evidence the approver saw. context holds what is specific to the kind, such
|
||||
-- as the chat session, the tool version and the policy revision.
|
||||
CREATE TABLE governance.audit_log (
|
||||
seq bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
id uuid NOT NULL UNIQUE,
|
||||
org_id text NOT NULL,
|
||||
at timestamptz NOT NULL DEFAULT now(),
|
||||
kind text NOT NULL,
|
||||
actor_kind text NOT NULL CHECK (actor_kind IN ('person', 'rule', 'guard', 'step', 'system')),
|
||||
actor_id text NOT NULL CHECK (actor_id <> ''),
|
||||
actor_name text NOT NULL DEFAULT '',
|
||||
authority jsonb NOT NULL DEFAULT '{}',
|
||||
target_kind text NOT NULL,
|
||||
target_id text NOT NULL,
|
||||
run_id uuid,
|
||||
workflow_id uuid,
|
||||
decision_id uuid,
|
||||
before jsonb,
|
||||
after jsonb,
|
||||
request jsonb,
|
||||
response jsonb,
|
||||
why jsonb NOT NULL DEFAULT '{}',
|
||||
context jsonb NOT NULL DEFAULT '{}',
|
||||
outcome text NOT NULL CHECK (outcome IN ('succeeded', 'failed', 'refused', 'unknown')),
|
||||
prev_digest bytea UNIQUE,
|
||||
digest bytea NOT NULL UNIQUE
|
||||
);
|
||||
CREATE UNIQUE INDEX audit_log_first ON governance.audit_log ((true)) WHERE (prev_digest IS NULL);
|
||||
CREATE INDEX audit_log_by_org ON governance.audit_log (org_id, at DESC, seq DESC);
|
||||
CREATE INDEX audit_log_by_actor ON governance.audit_log (org_id, actor_id, at DESC);
|
||||
CREATE INDEX audit_log_by_target ON governance.audit_log (org_id, target_kind, target_id, at DESC);
|
||||
CREATE INDEX audit_log_by_kind ON governance.audit_log (org_id, kind, at DESC);
|
||||
CREATE INDEX audit_log_by_run ON governance.audit_log (run_id, seq) WHERE (run_id IS NOT NULL);
|
||||
CREATE INDEX audit_log_by_workflow ON governance.audit_log (workflow_id, at DESC) WHERE (workflow_id IS NOT NULL);
|
||||
|
||||
INSERT INTO governance.access_policy_revision (only_row) VALUES (true);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA governance CASCADE;
|
||||
@@ -1,50 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA runs;
|
||||
|
||||
CREATE TABLE runs.runs (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
workflow text NOT NULL,
|
||||
start_key text,
|
||||
input jsonb NOT NULL,
|
||||
state text NOT NULL CHECK (state IN ('queued', 'running', 'waiting', 'succeeded', 'failed', 'cancelled')),
|
||||
lease_token uuid,
|
||||
lease_owner text,
|
||||
lease_expires_at timestamptz,
|
||||
wake_at timestamptz,
|
||||
waiting_for text,
|
||||
cancel_requested boolean NOT NULL DEFAULT false,
|
||||
attempts integer NOT NULL DEFAULT 0,
|
||||
result jsonb,
|
||||
error text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
finished_at timestamptz,
|
||||
UNIQUE (org_id, start_key)
|
||||
);
|
||||
|
||||
-- Claiming scans only runs that could be claimed.
|
||||
CREATE INDEX runs_claimable ON runs.runs (created_at)
|
||||
WHERE state IN ('queued', 'waiting', 'running');
|
||||
|
||||
CREATE TABLE runs.steps (
|
||||
run_id uuid NOT NULL REFERENCES runs.runs (id) ON DELETE CASCADE,
|
||||
seq integer NOT NULL,
|
||||
name text NOT NULL,
|
||||
outcome text NOT NULL CHECK (outcome IN ('done', 'failed', 'unknown')),
|
||||
output jsonb,
|
||||
error text,
|
||||
recorded_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (run_id, seq)
|
||||
);
|
||||
|
||||
CREATE TABLE runs.signals (
|
||||
run_id uuid NOT NULL REFERENCES runs.runs (id) ON DELETE CASCADE,
|
||||
key text NOT NULL,
|
||||
payload jsonb NOT NULL,
|
||||
received_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (run_id, key)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA runs CASCADE;
|
||||
@@ -0,0 +1,97 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA connectors;
|
||||
|
||||
-- A package is an extension the instance has accepted: its name, contract,
|
||||
-- binary and digest, and the manifest that declares its settings, capabilities
|
||||
-- and effects. It holds no configuration and no credentials, so it is accepted
|
||||
-- once for the whole instance and configured by its installations.
|
||||
CREATE TABLE connectors.packages (
|
||||
id uuid PRIMARY KEY,
|
||||
name text NOT NULL UNIQUE,
|
||||
contract text NOT NULL CHECK (contract IN ('connector', 'secretengine', 'mcp', 'guard')),
|
||||
path text NOT NULL,
|
||||
sha256 text NOT NULL,
|
||||
manifest jsonb,
|
||||
capabilities jsonb,
|
||||
effects jsonb,
|
||||
accepted_by_id text NOT NULL,
|
||||
accepted_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- An installation is one configuration of a package, owned by a scope: the
|
||||
-- instance, one organisation or one person. A binding names an installation or
|
||||
-- inherits one, resolving the person's first, then the organisation's, then the
|
||||
-- instance's. name is unique within its scope, so the same name can resolve to
|
||||
-- a different installation for each organisation or person. tools lists the
|
||||
-- tools an MCP server reported.
|
||||
CREATE TABLE connectors.installations (
|
||||
id uuid PRIMARY KEY,
|
||||
package_id uuid NOT NULL REFERENCES connectors.packages (id) ON DELETE RESTRICT,
|
||||
scope text NOT NULL CHECK (scope IN ('instance', 'org', 'person')),
|
||||
org_id text NOT NULL DEFAULT '',
|
||||
person_id text NOT NULL DEFAULT '',
|
||||
name text NOT NULL,
|
||||
settings jsonb NOT NULL DEFAULT '{}',
|
||||
egress jsonb NOT NULL DEFAULT '[]',
|
||||
env jsonb NOT NULL DEFAULT '[]',
|
||||
credentials jsonb NOT NULL DEFAULT '{}',
|
||||
args jsonb NOT NULL DEFAULT '[]',
|
||||
url text NOT NULL DEFAULT '',
|
||||
tools jsonb NOT NULL DEFAULT '[]',
|
||||
enabled boolean NOT NULL DEFAULT true,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (scope, org_id, person_id, name),
|
||||
CHECK ((scope <> 'instance') OR ((org_id = '') AND (person_id = ''))),
|
||||
CHECK ((scope <> 'org') OR ((org_id <> '') AND (person_id = ''))),
|
||||
CHECK ((scope <> 'person') OR ((org_id = '') AND (person_id <> '')))
|
||||
);
|
||||
CREATE INDEX installations_by_package ON connectors.installations (package_id);
|
||||
|
||||
-- An organisation or a person can switch off an installation it would
|
||||
-- otherwise inherit from a broader scope.
|
||||
CREATE TABLE connectors.installation_overrides (
|
||||
installation_id uuid NOT NULL REFERENCES connectors.installations (id) ON DELETE CASCADE,
|
||||
scope text NOT NULL CHECK (scope IN ('org', 'person')),
|
||||
org_id text NOT NULL DEFAULT '',
|
||||
person_id text NOT NULL DEFAULT '',
|
||||
disabled_by_id text NOT NULL,
|
||||
disabled_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (installation_id, scope, org_id, person_id),
|
||||
CHECK ((scope <> 'org') OR ((org_id <> '') AND (person_id = ''))),
|
||||
CHECK ((scope <> 'person') OR ((org_id = '') AND (person_id <> '')))
|
||||
);
|
||||
|
||||
-- A credential's fields are sealed with age. Each field holds a value or the
|
||||
-- secret engine key the value is read from. A credential is owned by a scope
|
||||
-- and resolved like an installation.
|
||||
CREATE TABLE connectors.credentials (
|
||||
id uuid PRIMARY KEY,
|
||||
scope text NOT NULL CHECK (scope IN ('instance', 'org', 'person')),
|
||||
org_id text NOT NULL DEFAULT '',
|
||||
person_id text NOT NULL DEFAULT '',
|
||||
name text NOT NULL,
|
||||
kind text NOT NULL CHECK (kind IN ('machine', 'age', 'basic', 'bearer')),
|
||||
sealed bytea NOT NULL,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (scope, org_id, person_id, name),
|
||||
CHECK ((scope <> 'instance') OR ((org_id = '') AND (person_id = ''))),
|
||||
CHECK ((scope <> 'org') OR ((org_id <> '') AND (person_id = ''))),
|
||||
CHECK ((scope <> 'person') OR ((org_id = '') AND (person_id <> '')))
|
||||
);
|
||||
|
||||
-- The location of the instance's extension catalogue and the public key that
|
||||
-- verifies its signature. newest_issued_at is the issue time of the newest
|
||||
-- catalogue accepted from it, so an older catalogue replayed by the source or
|
||||
-- the network is refused.
|
||||
CREATE TABLE connectors.catalogue_source (
|
||||
singleton boolean DEFAULT true PRIMARY KEY CHECK (singleton),
|
||||
location text NOT NULL,
|
||||
public_key text NOT NULL,
|
||||
newest_issued_at timestamptz,
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA connectors CASCADE;
|
||||
@@ -1,70 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA connectors;
|
||||
|
||||
CREATE TABLE connectors.accepted (
|
||||
org_id text NOT NULL,
|
||||
name text NOT NULL,
|
||||
path text NOT NULL,
|
||||
sha256 text NOT NULL,
|
||||
egress jsonb NOT NULL DEFAULT '[]',
|
||||
env jsonb NOT NULL DEFAULT '[]',
|
||||
settings jsonb NOT NULL DEFAULT '{}',
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (org_id, name)
|
||||
);
|
||||
|
||||
CREATE SCHEMA events;
|
||||
|
||||
CREATE TABLE events.sources (
|
||||
org_id text NOT NULL,
|
||||
name text NOT NULL,
|
||||
connector text NOT NULL,
|
||||
token_sha256 text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (org_id, name)
|
||||
);
|
||||
|
||||
CREATE TABLE events.events (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
source text NOT NULL,
|
||||
type text NOT NULL,
|
||||
source_event_id text NOT NULL,
|
||||
link_key text,
|
||||
linked_to uuid REFERENCES events.events (id),
|
||||
fields jsonb NOT NULL,
|
||||
occurred_at timestamptz,
|
||||
received_at timestamptz NOT NULL DEFAULT now(),
|
||||
dispatched_at timestamptz,
|
||||
matched boolean NOT NULL DEFAULT false,
|
||||
-- Dedupe is this constraint: a re-delivery conflicts instead of racing.
|
||||
UNIQUE (org_id, source, source_event_id)
|
||||
);
|
||||
|
||||
CREATE INDEX events_undispatched ON events.events (received_at) WHERE dispatched_at IS NULL;
|
||||
CREATE INDEX events_link ON events.events (org_id, source, link_key, received_at) WHERE link_key IS NOT NULL;
|
||||
|
||||
CREATE TABLE events.triggers (
|
||||
org_id text NOT NULL,
|
||||
name text NOT NULL,
|
||||
source text NOT NULL,
|
||||
event_type text NOT NULL,
|
||||
filter jsonb NOT NULL DEFAULT '{}',
|
||||
workflow text NOT NULL,
|
||||
enabled boolean NOT NULL DEFAULT true,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (org_id, name)
|
||||
);
|
||||
|
||||
CREATE TABLE events.dispatches (
|
||||
event_id uuid NOT NULL REFERENCES events.events (id),
|
||||
trigger text NOT NULL,
|
||||
run_id uuid NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (event_id, trigger)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA events CASCADE;
|
||||
DROP SCHEMA connectors CASCADE;
|
||||
@@ -0,0 +1,125 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA events;
|
||||
|
||||
CREATE TABLE events.sources (
|
||||
org_id text NOT NULL,
|
||||
name text NOT NULL,
|
||||
connector text NOT NULL,
|
||||
token_sha256 text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
cursor text NOT NULL DEFAULT '',
|
||||
key_fields jsonb NOT NULL DEFAULT '[]',
|
||||
verification text NOT NULL DEFAULT 'token' CHECK (verification IN ('token', 'hmac', 'none')),
|
||||
hmac_header text NOT NULL DEFAULT '',
|
||||
hmac_prefix text NOT NULL DEFAULT '',
|
||||
hmac_secret_sealed bytea NOT NULL DEFAULT '\x'::bytea,
|
||||
display_name text NOT NULL DEFAULT '',
|
||||
delivery_header text NOT NULL DEFAULT '',
|
||||
unsigned_approved boolean NOT NULL DEFAULT false,
|
||||
capture boolean NOT NULL DEFAULT true,
|
||||
PRIMARY KEY (org_id, name)
|
||||
);
|
||||
|
||||
-- An event type identifies one kind of event from a source by its headers and
|
||||
-- payload paths. schema lists the JSON paths of the example event it was
|
||||
-- created from.
|
||||
CREATE TABLE events.event_types (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
source text NOT NULL,
|
||||
name text NOT NULL,
|
||||
rule jsonb NOT NULL,
|
||||
schema jsonb NOT NULL DEFAULT '{}',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (org_id, source, name)
|
||||
);
|
||||
|
||||
CREATE TABLE events.events (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
source text NOT NULL,
|
||||
type text NOT NULL,
|
||||
source_event_id text NOT NULL,
|
||||
link_key text,
|
||||
linked_to uuid REFERENCES events.events (id),
|
||||
fields jsonb NOT NULL,
|
||||
occurred_at timestamptz,
|
||||
received_at timestamptz NOT NULL DEFAULT now(),
|
||||
dispatched_at timestamptz,
|
||||
matched boolean NOT NULL DEFAULT false,
|
||||
own boolean NOT NULL DEFAULT false,
|
||||
origin_run_id uuid,
|
||||
group_key text,
|
||||
group_filter jsonb,
|
||||
body bytea,
|
||||
verification text NOT NULL DEFAULT '' CHECK (verification IN ('', 'signed', 'token', 'unsigned')),
|
||||
headers jsonb,
|
||||
remote_addr text NOT NULL DEFAULT '',
|
||||
event_type_id uuid REFERENCES events.event_types (id) ON DELETE SET NULL,
|
||||
UNIQUE (org_id, source, source_event_id)
|
||||
);
|
||||
CREATE INDEX events_undispatched ON events.events (received_at) WHERE (dispatched_at IS NULL);
|
||||
CREATE INDEX events_link ON events.events (org_id, source, link_key, received_at) WHERE (link_key IS NOT NULL);
|
||||
|
||||
-- A mapping lists the payload paths a workflow reads from events of one event
|
||||
-- type.
|
||||
CREATE TABLE events.mappings (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
name text NOT NULL,
|
||||
source_hint text NOT NULL DEFAULT '',
|
||||
event_type_id uuid NOT NULL REFERENCES events.event_types (id) ON DELETE RESTRICT,
|
||||
fields jsonb NOT NULL,
|
||||
match_count bigint NOT NULL DEFAULT 0,
|
||||
last_matched_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE events.triggers (
|
||||
org_id text NOT NULL,
|
||||
name text NOT NULL,
|
||||
source text NOT NULL,
|
||||
event_type text NOT NULL,
|
||||
filter jsonb NOT NULL DEFAULT '{}',
|
||||
workflow text NOT NULL,
|
||||
enabled boolean NOT NULL DEFAULT true,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
schedule_every_s integer CHECK (schedule_every_s >= 60),
|
||||
schedule_since timestamptz,
|
||||
approved boolean NOT NULL DEFAULT true,
|
||||
event_type_id uuid REFERENCES events.event_types (id) ON DELETE RESTRICT,
|
||||
mapping_id uuid REFERENCES events.mappings (id) ON DELETE RESTRICT,
|
||||
PRIMARY KEY (org_id, name)
|
||||
);
|
||||
|
||||
CREATE TABLE events.dispatches (
|
||||
event_id uuid NOT NULL REFERENCES events.events (id),
|
||||
trigger text NOT NULL,
|
||||
run_id uuid,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
outcome text NOT NULL DEFAULT 'started' CHECK (outcome IN ('started', 'failed', 'denied', 'disabled')),
|
||||
reason jsonb,
|
||||
PRIMARY KEY (event_id, trigger),
|
||||
CHECK ((outcome = 'started') = (run_id IS NOT NULL))
|
||||
);
|
||||
|
||||
-- A group collects the unmatched events that share a key. Its source, event
|
||||
-- type and filter describe the trigger it suggests.
|
||||
CREATE TABLE events.groups (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
key text NOT NULL,
|
||||
source text NOT NULL,
|
||||
event_type text NOT NULL,
|
||||
filter jsonb NOT NULL,
|
||||
count bigint NOT NULL,
|
||||
first_seen timestamptz NOT NULL,
|
||||
last_seen timestamptz NOT NULL,
|
||||
UNIQUE (org_id, key)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA events CASCADE;
|
||||
@@ -1,17 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA governance;
|
||||
|
||||
-- A model role is the model an organisation chose for one job. Only the agent
|
||||
-- role exists until guards need the judge role.
|
||||
CREATE TABLE governance.model_roles (
|
||||
org_id text NOT NULL,
|
||||
role text NOT NULL CHECK (role IN ('agent')),
|
||||
class text NOT NULL,
|
||||
base_url text NOT NULL,
|
||||
model text NOT NULL,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (org_id, role)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA governance CASCADE;
|
||||
@@ -1,21 +0,0 @@
|
||||
-- +goose Up
|
||||
-- A credential's fields are sealed with age: each holds a value or names the
|
||||
-- secret engine key it is resolved from.
|
||||
CREATE TABLE connectors.credentials (
|
||||
org_id text NOT NULL,
|
||||
name text NOT NULL,
|
||||
kind text NOT NULL CHECK (kind IN ('machine', 'age')),
|
||||
sealed bytea NOT NULL,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (org_id, name)
|
||||
);
|
||||
|
||||
-- contract says which extension contract an accepted package serves; its
|
||||
-- credentials map each slot it declares to a credential by name.
|
||||
ALTER TABLE connectors.accepted
|
||||
ADD COLUMN contract text NOT NULL DEFAULT 'connector' CHECK (contract IN ('connector', 'secretengine')),
|
||||
ADD COLUMN credentials jsonb NOT NULL DEFAULT '{}';
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE connectors.accepted DROP COLUMN credentials, DROP COLUMN contract;
|
||||
DROP TABLE connectors.credentials;
|
||||
@@ -0,0 +1,93 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA runs;
|
||||
|
||||
CREATE TABLE runs.runs (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
workflow text NOT NULL,
|
||||
start_key text,
|
||||
input jsonb NOT NULL,
|
||||
state text NOT NULL CHECK (state IN ('queued', 'running', 'waiting', 'succeeded', 'failed', 'cancelled', 'parked', 'waiting_approval', 'declined')),
|
||||
lease_token uuid,
|
||||
lease_owner text,
|
||||
lease_expires_at timestamptz,
|
||||
wake_at timestamptz,
|
||||
waiting_for text,
|
||||
cancel_requested boolean NOT NULL DEFAULT false,
|
||||
attempts integer NOT NULL DEFAULT 0,
|
||||
result jsonb,
|
||||
error text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
finished_at timestamptz,
|
||||
workflow_version integer NOT NULL DEFAULT 1,
|
||||
dry boolean NOT NULL DEFAULT false,
|
||||
overlay jsonb,
|
||||
detail text,
|
||||
parent_run_id uuid REFERENCES runs.runs (id) ON DELETE CASCADE,
|
||||
parent_signal text,
|
||||
call_depth integer NOT NULL DEFAULT 0,
|
||||
UNIQUE (org_id, start_key)
|
||||
);
|
||||
CREATE INDEX runs_claimable ON runs.runs (created_at) WHERE (state IN ('queued', 'waiting', 'running'));
|
||||
CREATE INDEX runs_runs_parent ON runs.runs (parent_run_id) WHERE (parent_run_id IS NOT NULL);
|
||||
|
||||
CREATE TABLE runs.steps (
|
||||
run_id uuid NOT NULL REFERENCES runs.runs (id) ON DELETE CASCADE,
|
||||
seq integer NOT NULL,
|
||||
name text NOT NULL,
|
||||
outcome text NOT NULL CHECK (outcome IN ('done', 'failed', 'unknown')),
|
||||
output json,
|
||||
error text,
|
||||
recorded_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (run_id, seq)
|
||||
);
|
||||
|
||||
CREATE TABLE runs.signals (
|
||||
run_id uuid NOT NULL REFERENCES runs.runs (id) ON DELETE CASCADE,
|
||||
key text NOT NULL,
|
||||
payload jsonb NOT NULL,
|
||||
received_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (run_id, key)
|
||||
);
|
||||
|
||||
-- A workflow is a document, stored by name and version. A run records the
|
||||
-- version it started with and executes that version.
|
||||
CREATE TABLE runs.workflows (
|
||||
org_id text NOT NULL,
|
||||
name text NOT NULL,
|
||||
version integer NOT NULL,
|
||||
body text NOT NULL,
|
||||
created_by text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (org_id, name, version)
|
||||
);
|
||||
|
||||
-- A draft is the unpublished edit of a workflow. It is stored so the edit
|
||||
-- survives a page reload, and no run uses it until it is published as the next
|
||||
-- version. revision increments on every write, and a write that specifies an
|
||||
-- older revision is refused, so two editors can't overwrite each other's
|
||||
-- changes. base_version is the published version the draft started from, or 0
|
||||
-- for a new workflow.
|
||||
CREATE TABLE runs.workflow_drafts (
|
||||
org_id text NOT NULL,
|
||||
name text NOT NULL,
|
||||
body text NOT NULL,
|
||||
base_version integer NOT NULL,
|
||||
revision integer NOT NULL DEFAULT 1,
|
||||
updated_by text NOT NULL,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (org_id, name)
|
||||
);
|
||||
|
||||
-- A workflow with no row here is enabled. A disabled workflow can't be started
|
||||
-- by a trigger, by another workflow or manually.
|
||||
CREATE TABLE runs.workflow_settings (
|
||||
org_id text NOT NULL,
|
||||
name text NOT NULL,
|
||||
enabled boolean NOT NULL,
|
||||
PRIMARY KEY (org_id, name)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA runs CASCADE;
|
||||
@@ -0,0 +1,96 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA judgement;
|
||||
|
||||
-- A decision is the judgement of one concrete action, with every verdict in
|
||||
-- its body. key identifies the attempt to run the action, so a replayed step
|
||||
-- reads the existing decision instead of judging the action again. connector, action, target_kind and environment
|
||||
-- identify the action type the decision counts towards.
|
||||
CREATE TABLE judgement.decisions (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
run_id uuid NOT NULL,
|
||||
key text NOT NULL,
|
||||
connector text NOT NULL,
|
||||
action text NOT NULL,
|
||||
target_kind text NOT NULL,
|
||||
environment text NOT NULL,
|
||||
level text NOT NULL CHECK (level IN ('act_quietly', 'act_and_tell', 'propose_and_wait', 'escalate', 'never')),
|
||||
body json NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
dry boolean NOT NULL DEFAULT false,
|
||||
UNIQUE (org_id, key)
|
||||
);
|
||||
CREATE INDEX decisions_by_run ON judgement.decisions (org_id, run_id, created_at);
|
||||
CREATE INDEX decisions_by_class ON judgement.decisions (org_id, connector, action, target_kind, environment, created_at);
|
||||
|
||||
CREATE TABLE judgement.action_types (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
connector text NOT NULL,
|
||||
action text NOT NULL,
|
||||
target_kind text NOT NULL,
|
||||
environment text NOT NULL,
|
||||
read_only boolean NOT NULL,
|
||||
level text NOT NULL CHECK (level IN ('act_quietly', 'act_and_tell', 'propose_and_wait', 'escalate', 'never')),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
reset_at timestamptz,
|
||||
tightened_at timestamptz,
|
||||
tightened_because text,
|
||||
UNIQUE (org_id, connector, action, target_kind, environment)
|
||||
);
|
||||
|
||||
CREATE TABLE judgement.action_type_resets (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
action_type_id uuid NOT NULL REFERENCES judgement.action_types (id),
|
||||
from_level text NOT NULL,
|
||||
to_level text NOT NULL,
|
||||
by text NOT NULL,
|
||||
at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX action_type_resets_by_action_type ON judgement.action_type_resets (action_type_id, at);
|
||||
|
||||
CREATE TABLE judgement.action_type_approvals (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
action_type_id uuid NOT NULL REFERENCES judgement.action_types (id),
|
||||
decision_id uuid NOT NULL UNIQUE,
|
||||
by text NOT NULL,
|
||||
by_id text NOT NULL DEFAULT '',
|
||||
at timestamptz NOT NULL,
|
||||
counted boolean NOT NULL DEFAULT true
|
||||
);
|
||||
CREATE INDEX action_type_approvals_counted ON judgement.action_type_approvals (action_type_id, at) WHERE counted;
|
||||
|
||||
CREATE TABLE judgement.autonomy_proposals (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
action_type_id uuid NOT NULL REFERENCES judgement.action_types (id),
|
||||
from_level text NOT NULL,
|
||||
to_level text NOT NULL,
|
||||
evidence jsonb NOT NULL,
|
||||
state text NOT NULL CHECK (state IN ('pending', 'approved', 'denied', 'expired', 'superseded')),
|
||||
deadline timestamptz NOT NULL,
|
||||
proposed_at timestamptz NOT NULL,
|
||||
answered_by text,
|
||||
answered_at timestamptz,
|
||||
answered_by_id text
|
||||
);
|
||||
CREATE UNIQUE INDEX autonomy_proposals_one_pending ON judgement.autonomy_proposals (action_type_id) WHERE (state = 'pending');
|
||||
CREATE INDEX autonomy_proposals_by_action_type ON judgement.autonomy_proposals (action_type_id, proposed_at);
|
||||
|
||||
-- Hard rules and change-request rules are Cedar policy sets, one per kind per
|
||||
-- organisation. Every version is kept, and the highest version is in force.
|
||||
CREATE TABLE judgement.policy_sets (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
kind text NOT NULL CHECK (kind IN ('hard_rules', 'change_request')),
|
||||
version integer NOT NULL,
|
||||
body text NOT NULL,
|
||||
created_by text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (org_id, kind, version)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA judgement CASCADE;
|
||||
@@ -1,29 +0,0 @@
|
||||
-- +goose Up
|
||||
-- An accepted MCP server runs as published: a stdio binary with its arguments,
|
||||
-- or an HTTP endpoint. Tools are what its acceptance declares it may offer.
|
||||
ALTER TABLE connectors.accepted
|
||||
ADD COLUMN args jsonb NOT NULL DEFAULT '[]',
|
||||
ADD COLUMN url text NOT NULL DEFAULT '',
|
||||
ADD COLUMN tools jsonb NOT NULL DEFAULT '[]';
|
||||
|
||||
ALTER TABLE connectors.accepted DROP CONSTRAINT accepted_contract_check;
|
||||
ALTER TABLE connectors.accepted
|
||||
ADD CONSTRAINT accepted_contract_check
|
||||
CHECK (contract IN ('connector', 'secretengine', 'mcp'));
|
||||
|
||||
-- An MCP server's credential slot is an HTTP auth scheme: basic or bearer.
|
||||
ALTER TABLE connectors.credentials DROP CONSTRAINT credentials_kind_check;
|
||||
ALTER TABLE connectors.credentials
|
||||
ADD CONSTRAINT credentials_kind_check
|
||||
CHECK (kind IN ('machine', 'age', 'basic', 'bearer'));
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE connectors.credentials DROP CONSTRAINT credentials_kind_check;
|
||||
ALTER TABLE connectors.credentials
|
||||
ADD CONSTRAINT credentials_kind_check CHECK (kind IN ('machine', 'age'));
|
||||
|
||||
ALTER TABLE connectors.accepted DROP CONSTRAINT accepted_contract_check;
|
||||
ALTER TABLE connectors.accepted
|
||||
ADD CONSTRAINT accepted_contract_check CHECK (contract IN ('connector', 'secretengine'));
|
||||
|
||||
ALTER TABLE connectors.accepted DROP COLUMN tools, DROP COLUMN url, DROP COLUMN args;
|
||||
@@ -0,0 +1,52 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA approvals;
|
||||
|
||||
-- A request is one judged action waiting for a person's answer. key identifies
|
||||
-- the run's wait that the answer resumes. The decision columns bind the answer
|
||||
-- to the judged action, so it can't be applied to a different action.
|
||||
CREATE TABLE approvals.requests (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
run_id uuid NOT NULL,
|
||||
key text NOT NULL,
|
||||
decision_id uuid NOT NULL,
|
||||
digest text NOT NULL,
|
||||
level text NOT NULL CHECK (level IN ('act_quietly', 'act_and_tell', 'propose_and_wait', 'escalate', 'never')),
|
||||
summary text NOT NULL,
|
||||
state text NOT NULL CHECK (state IN ('pending', 'approved', 'denied', 'expired', 'discarded')),
|
||||
deadline timestamptz NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
answered_at timestamptz,
|
||||
answered_by text,
|
||||
answered_via text,
|
||||
connector text NOT NULL,
|
||||
action text NOT NULL,
|
||||
target_kind text NOT NULL,
|
||||
target_id text NOT NULL,
|
||||
kind text NOT NULL DEFAULT 'action' CHECK (kind IN ('action', 'autonomy')),
|
||||
step integer NOT NULL DEFAULT 0,
|
||||
step_deadline timestamptz,
|
||||
change_request boolean NOT NULL DEFAULT false,
|
||||
counted boolean NOT NULL DEFAULT false,
|
||||
discarded_because text,
|
||||
irreversible boolean NOT NULL DEFAULT false,
|
||||
answered_by_id text,
|
||||
UNIQUE (org_id, run_id, key)
|
||||
);
|
||||
CREATE INDEX requests_by_state ON approvals.requests (org_id, state, created_at);
|
||||
|
||||
-- An answer that was refused, and the reason it was refused, so a request that
|
||||
-- was never resolved can be explained.
|
||||
CREATE TABLE approvals.refusals (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
request_id uuid NOT NULL REFERENCES approvals.requests (id) ON DELETE CASCADE,
|
||||
identity text NOT NULL,
|
||||
via text NOT NULL,
|
||||
reason text NOT NULL,
|
||||
at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX refusals_by_request ON approvals.refusals (org_id, request_id, at);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA approvals CASCADE;
|
||||
@@ -1,23 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA deliveries;
|
||||
|
||||
-- A message is one notification on one channel. The composer reads its
|
||||
-- messages straight from here; channels that send (Telegram) get delivery
|
||||
-- attempts when they land.
|
||||
CREATE TABLE deliveries.messages (
|
||||
seq bigserial PRIMARY KEY,
|
||||
id uuid NOT NULL UNIQUE,
|
||||
org_id text NOT NULL,
|
||||
channel text NOT NULL CHECK (channel IN ('composer')),
|
||||
kind text NOT NULL CHECK (kind IN ('notification')),
|
||||
run_id uuid,
|
||||
title text NOT NULL,
|
||||
body text NOT NULL,
|
||||
-- key makes a notification idempotent: a replayed step can't send twice.
|
||||
key text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (org_id, channel, key)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA deliveries CASCADE;
|
||||
@@ -0,0 +1,46 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA deliveries;
|
||||
|
||||
-- A message is one notification on one channel. The composer reads its
|
||||
-- messages from this table. A channel that sends messages, such as Telegram,
|
||||
-- records each delivery attempt in deliveries.attempts.
|
||||
CREATE TABLE deliveries.messages (
|
||||
seq bigserial PRIMARY KEY,
|
||||
id uuid NOT NULL UNIQUE,
|
||||
org_id text NOT NULL,
|
||||
channel text NOT NULL CHECK (channel ~ '^[a-z][a-z0-9-]{0,62}$'),
|
||||
kind text NOT NULL CHECK (kind IN ('notification', 'approval_request', 'approval_answer')),
|
||||
run_id uuid,
|
||||
title text NOT NULL,
|
||||
body text NOT NULL,
|
||||
key text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
request_id uuid,
|
||||
expires_at timestamptz,
|
||||
attempts integer NOT NULL DEFAULT 0,
|
||||
next_attempt_at timestamptz NOT NULL DEFAULT now(),
|
||||
sent_at timestamptz,
|
||||
external_id text,
|
||||
last_error text,
|
||||
failed_at timestamptz,
|
||||
UNIQUE (org_id, channel, key)
|
||||
);
|
||||
CREATE INDEX messages_external ON deliveries.messages (org_id, channel, external_id) WHERE (external_id IS NOT NULL);
|
||||
CREATE INDEX messages_due ON deliveries.messages (next_attempt_at) WHERE ((sent_at IS NULL) AND (failed_at IS NULL));
|
||||
|
||||
-- One row per delivery attempt, so every channel response and failure is kept,
|
||||
-- not only the last error. Rows are never pruned: the volume is low, and the
|
||||
-- attempts are the audit record of a delivery.
|
||||
CREATE TABLE deliveries.attempts (
|
||||
message_seq bigint NOT NULL REFERENCES deliveries.messages (seq) ON DELETE CASCADE,
|
||||
attempt integer NOT NULL,
|
||||
at timestamptz NOT NULL DEFAULT now(),
|
||||
ok boolean NOT NULL,
|
||||
response text NOT NULL DEFAULT '',
|
||||
error text NOT NULL DEFAULT '',
|
||||
duration_ms bigint NOT NULL,
|
||||
PRIMARY KEY (message_seq, attempt)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA deliveries CASCADE;
|
||||
@@ -1,8 +0,0 @@
|
||||
-- +goose Up
|
||||
-- A step's output must replay byte for byte: jsonb reorders keys and drops
|
||||
-- whitespace, so a pinned value (a tool schema) read back differed from the
|
||||
-- one a live attempt used, and a resumed agent diverged from its journal.
|
||||
ALTER TABLE runs.steps ALTER COLUMN output TYPE json USING output::json;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE runs.steps ALTER COLUMN output TYPE jsonb USING output::jsonb;
|
||||
@@ -0,0 +1,26 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA drafts;
|
||||
|
||||
CREATE TABLE drafts.drafts (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
group_id uuid NOT NULL,
|
||||
name text NOT NULL,
|
||||
source text NOT NULL,
|
||||
event_type text NOT NULL,
|
||||
filter jsonb NOT NULL,
|
||||
document text NOT NULL,
|
||||
policy_kind text NOT NULL CHECK (policy_kind IN ('hard_rules', 'change_request')),
|
||||
policy text NOT NULL,
|
||||
dry_run_id uuid,
|
||||
dry_event_id uuid,
|
||||
installed_version integer,
|
||||
published_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (org_id, group_id),
|
||||
UNIQUE (org_id, name)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA drafts CASCADE;
|
||||
@@ -1,27 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA judgement;
|
||||
|
||||
-- A decision is the judgement of one concrete action, with every verdict in
|
||||
-- its body. key identifies the attempt to run it, so a replayed step finds the
|
||||
-- decision already made. The class columns are what earned autonomy is
|
||||
-- counted against.
|
||||
CREATE TABLE judgement.decisions (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
run_id uuid NOT NULL,
|
||||
key text NOT NULL,
|
||||
connector text NOT NULL,
|
||||
action text NOT NULL,
|
||||
target_kind text NOT NULL,
|
||||
environment text NOT NULL,
|
||||
level text NOT NULL CHECK (level IN ('act_quietly', 'act_and_tell', 'propose_and_wait', 'escalate', 'never')),
|
||||
body json NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (org_id, key)
|
||||
);
|
||||
|
||||
CREATE INDEX decisions_by_run ON judgement.decisions (org_id, run_id, created_at);
|
||||
CREATE INDEX decisions_by_class ON judgement.decisions (org_id, connector, action, target_kind, environment, created_at);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA judgement CASCADE;
|
||||
@@ -1,28 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA approvals;
|
||||
|
||||
-- A request is one judged action waiting for a person's answer. key is the run
|
||||
-- wait an answer wakes, and the decision columns bind the answer to the action
|
||||
-- that was judged, so it can't be replayed onto another one.
|
||||
CREATE TABLE approvals.requests (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
run_id uuid NOT NULL,
|
||||
key text NOT NULL,
|
||||
decision_id uuid NOT NULL,
|
||||
digest text NOT NULL,
|
||||
level text NOT NULL CHECK (level IN ('act_quietly', 'act_and_tell', 'propose_and_wait', 'escalate', 'never')),
|
||||
summary text NOT NULL,
|
||||
state text NOT NULL CHECK (state IN ('pending', 'approved', 'denied', 'expired')),
|
||||
deadline timestamptz NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
answered_at timestamptz,
|
||||
answered_by text,
|
||||
answered_via text,
|
||||
UNIQUE (org_id, run_id, key)
|
||||
);
|
||||
|
||||
CREATE INDEX requests_by_state ON approvals.requests (org_id, state, created_at);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA approvals CASCADE;
|
||||
@@ -0,0 +1,104 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA chat;
|
||||
|
||||
-- A session is one conversation between the operator and Archie.
|
||||
CREATE TABLE chat.sessions (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
title text NOT NULL DEFAULT '',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
owner_id text NOT NULL,
|
||||
tainted boolean NOT NULL DEFAULT false
|
||||
);
|
||||
CREATE INDEX sessions_by_owner ON chat.sessions (org_id, owner_id, updated_at DESC);
|
||||
|
||||
-- A turn is one message from the operator and Archie's reply to it. It is
|
||||
-- stored before it is acknowledged and queued until the turn before it in the
|
||||
-- same session has ended. Judgement and approvals record the turn's actions
|
||||
-- with the turn's id as their run id.
|
||||
CREATE TABLE chat.turns (
|
||||
seq bigserial PRIMARY KEY,
|
||||
id uuid NOT NULL UNIQUE,
|
||||
org_id text NOT NULL,
|
||||
session_id uuid NOT NULL REFERENCES chat.sessions (id) ON DELETE CASCADE,
|
||||
state text NOT NULL CHECK (state IN ('queued', 'running', 'succeeded', 'failed', 'cancelled')),
|
||||
text text NOT NULL,
|
||||
page text NOT NULL DEFAULT '',
|
||||
page_label text NOT NULL DEFAULT '',
|
||||
reply text NOT NULL DEFAULT '',
|
||||
reasoning text NOT NULL DEFAULT '',
|
||||
error text NOT NULL DEFAULT '',
|
||||
cancel boolean NOT NULL DEFAULT false,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
started_at timestamptz,
|
||||
finished_at timestamptz,
|
||||
input_tokens bigint NOT NULL DEFAULT 0,
|
||||
output_tokens bigint NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX turns_by_session ON chat.turns (session_id, seq);
|
||||
CREATE INDEX turns_queued ON chat.turns (seq) WHERE (state IN ('queued', 'running'));
|
||||
|
||||
-- An event is one item a turn streamed: reasoning, reply text, a tool call or
|
||||
-- its result, an approval request, or how the turn ended. A client resumes the
|
||||
-- stream by reading the events after the last seq it received.
|
||||
CREATE TABLE chat.events (
|
||||
seq bigserial PRIMARY KEY,
|
||||
turn_id uuid NOT NULL REFERENCES chat.turns (id) ON DELETE CASCADE,
|
||||
kind text NOT NULL,
|
||||
data jsonb NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX events_by_turn ON chat.events (turn_id, seq);
|
||||
|
||||
-- An action is a tool call by a turn's agent that judgement held for approval.
|
||||
-- The answer arrives through approvals, and an approved action runs once.
|
||||
CREATE TABLE chat.actions (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
turn_id uuid NOT NULL REFERENCES chat.turns (id) ON DELETE CASCADE,
|
||||
key text NOT NULL,
|
||||
decision jsonb NOT NULL,
|
||||
request_id uuid NOT NULL,
|
||||
path jsonb NOT NULL,
|
||||
step integer NOT NULL DEFAULT 0,
|
||||
step_due timestamptz NOT NULL,
|
||||
state text NOT NULL CHECK (state IN ('waiting', 'approved', 'running', 'succeeded', 'failed', 'unknown', 'denied', 'expired')),
|
||||
answer jsonb,
|
||||
result text NOT NULL DEFAULT '',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
binding jsonb,
|
||||
binding_digest text NOT NULL DEFAULT '',
|
||||
UNIQUE (turn_id, key)
|
||||
);
|
||||
CREATE INDEX actions_open ON chat.actions (state) WHERE (state IN ('waiting', 'approved', 'running'));
|
||||
|
||||
-- Usage counts the turns, tool calls and tokens of one person or one whole
|
||||
-- organisation in a fixed window, so the limits in governance settings hold
|
||||
-- across sessions, concurrent turns and restarts. A turn or tool call is
|
||||
-- counted, under the limit, in the same statement that checks it.
|
||||
CREATE TABLE chat.usage (
|
||||
org_id text NOT NULL,
|
||||
subject_kind text NOT NULL CHECK (subject_kind IN ('person', 'org')),
|
||||
subject_id text NOT NULL,
|
||||
metric text NOT NULL CHECK (metric IN ('turns', 'tool_calls', 'tokens')),
|
||||
window_start timestamptz NOT NULL,
|
||||
count bigint NOT NULL CHECK (count >= 0),
|
||||
PRIMARY KEY (org_id, subject_kind, subject_id, metric, window_start),
|
||||
CHECK ((subject_kind <> 'org') OR (subject_id = org_id))
|
||||
);
|
||||
|
||||
-- A tool switched off for chat. A disabled tool is left out of a turn's tool
|
||||
-- list and refused if the model calls it anyway. An empty action switches off
|
||||
-- every action of the installation.
|
||||
CREATE TABLE chat.disabled_tools (
|
||||
installation_id uuid NOT NULL,
|
||||
action text NOT NULL DEFAULT '',
|
||||
reason text NOT NULL DEFAULT '',
|
||||
disabled_by_id text NOT NULL,
|
||||
disabled_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (installation_id, action)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA chat CASCADE;
|
||||
@@ -1,15 +0,0 @@
|
||||
-- +goose Up
|
||||
-- An approval request is a message a person answers, so a message grows the
|
||||
-- request it carries and when that request runs out of time.
|
||||
ALTER TABLE deliveries.messages DROP CONSTRAINT messages_kind_check;
|
||||
ALTER TABLE deliveries.messages ADD CONSTRAINT messages_kind_check
|
||||
CHECK (kind IN ('notification', 'approval_request', 'approval_answer'));
|
||||
ALTER TABLE deliveries.messages ADD COLUMN request_id uuid;
|
||||
ALTER TABLE deliveries.messages ADD COLUMN expires_at timestamptz;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE deliveries.messages DROP COLUMN expires_at;
|
||||
ALTER TABLE deliveries.messages DROP COLUMN request_id;
|
||||
ALTER TABLE deliveries.messages DROP CONSTRAINT messages_kind_check;
|
||||
ALTER TABLE deliveries.messages ADD CONSTRAINT messages_kind_check
|
||||
CHECK (kind IN ('notification'));
|
||||
@@ -0,0 +1,91 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA memory;
|
||||
|
||||
-- An incident is one investigation of one target: what the event was, the cause
|
||||
-- the investigation found and what was done about it. The row is created when
|
||||
-- the cause is recorded, and its actions are added when the run settles them.
|
||||
CREATE TABLE memory.incidents (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
run_id uuid NOT NULL,
|
||||
target_kind text NOT NULL,
|
||||
target_id text NOT NULL,
|
||||
cause text NOT NULL,
|
||||
summary text NOT NULL,
|
||||
event jsonb NOT NULL,
|
||||
actions jsonb NOT NULL DEFAULT '[]',
|
||||
at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (org_id, run_id)
|
||||
);
|
||||
CREATE INDEX incidents_by_target ON memory.incidents (org_id, target_kind, target_id, at DESC);
|
||||
|
||||
-- A proposal asks for a root-cause fix when the same cause recurs on a target.
|
||||
-- There is at most one per target and cause.
|
||||
CREATE TABLE memory.proposals (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
target_kind text NOT NULL,
|
||||
target_id text NOT NULL,
|
||||
cause text NOT NULL,
|
||||
incidents integer NOT NULL,
|
||||
body text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (org_id, target_kind, target_id, cause)
|
||||
);
|
||||
|
||||
-- A note is one item of Archie's memory. class is its kind: working context for
|
||||
-- one chat session, episodic history or enterprise retrieval in a collection,
|
||||
-- or a durable fact.
|
||||
CREATE TABLE memory.notes (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
class text NOT NULL CHECK (class IN ('working_context', 'episodic_history', 'enterprise_retrieval', 'durable_fact')),
|
||||
scope text NOT NULL CHECK (scope IN ('person', 'shared')),
|
||||
state text NOT NULL CHECK (state IN ('pending', 'published')),
|
||||
owner_id text NOT NULL,
|
||||
shared_by text NOT NULL DEFAULT '',
|
||||
purpose text NOT NULL CHECK (purpose <> ''),
|
||||
text text NOT NULL CHECK (text <> ''),
|
||||
session_id uuid,
|
||||
collection text,
|
||||
disabled_at timestamptz,
|
||||
retain_until timestamptz,
|
||||
version integer NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
CHECK ((scope <> 'person') OR (state = 'published')),
|
||||
CHECK ((scope <> 'person') OR (owner_id <> '')),
|
||||
CHECK ((scope <> 'shared') OR (shared_by <> '')),
|
||||
CHECK (((state = 'pending') AND (version = 0)) OR ((state = 'published') AND (version > 0))),
|
||||
CHECK ((class <> 'working_context') OR (session_id IS NOT NULL)),
|
||||
CHECK ((class <> 'episodic_history') OR (collection IS NOT NULL)),
|
||||
CHECK ((class <> 'enterprise_retrieval') OR (collection IS NOT NULL)),
|
||||
CHECK ((class <> 'durable_fact') OR ((session_id IS NULL) AND (collection IS NULL)))
|
||||
);
|
||||
CREATE INDEX notes_by_person ON memory.notes (org_id, owner_id, class, created_at DESC) WHERE (scope = 'person');
|
||||
CREATE INDEX notes_published ON memory.notes (org_id, class, created_at DESC) WHERE ((scope = 'shared') AND (state = 'published'));
|
||||
CREATE INDEX notes_pending ON memory.notes (org_id, created_at) WHERE ((scope = 'shared') AND (state = 'pending'));
|
||||
|
||||
-- Every published version of a shared note, so a publication can be rolled
|
||||
-- back and its publisher and purpose read.
|
||||
CREATE TABLE memory.note_versions (
|
||||
note_id uuid NOT NULL REFERENCES memory.notes (id) ON DELETE CASCADE,
|
||||
version integer NOT NULL CHECK (version > 0),
|
||||
text text NOT NULL,
|
||||
purpose text NOT NULL,
|
||||
publisher_id text NOT NULL,
|
||||
published_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (note_id, version)
|
||||
);
|
||||
|
||||
-- Each committed deletion is listed here. The deletion record kept outside the
|
||||
-- database must contain every deletion listed here, so a restore detects a
|
||||
-- missing or incomplete record instead of trusting it.
|
||||
CREATE TABLE memory.deletion_witness (
|
||||
note_id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA memory CASCADE;
|
||||
@@ -0,0 +1,38 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA alerts;
|
||||
|
||||
-- An alert is a condition a source reported, followed from when it opens until
|
||||
-- it resolves. key is the source's own identifier for the condition, such as
|
||||
-- Alertmanager's fingerprint, so a repeat or a resolve from the source finds
|
||||
-- the open alert instead of opening another. run_id is the run working it.
|
||||
CREATE TABLE alerts.alerts (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
source_id uuid NOT NULL,
|
||||
key text NOT NULL,
|
||||
state text NOT NULL CHECK (state IN ('open', 'acknowledged', 'resolved', 'suppressed')),
|
||||
severity text NOT NULL CHECK (severity IN ('critical', 'high', 'medium', 'low', 'info')),
|
||||
title text NOT NULL,
|
||||
summary text NOT NULL DEFAULT '',
|
||||
target_kind text NOT NULL,
|
||||
target_id text NOT NULL,
|
||||
labels jsonb NOT NULL DEFAULT '{}',
|
||||
opened_event_id uuid NOT NULL,
|
||||
resolved_event_id uuid,
|
||||
run_id uuid,
|
||||
opened_at timestamptz NOT NULL,
|
||||
acknowledged_at timestamptz,
|
||||
acknowledged_by_id text,
|
||||
resolved_at timestamptz,
|
||||
suppressed_until timestamptz,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
CHECK ((acknowledged_at IS NULL) = (acknowledged_by_id IS NULL)),
|
||||
CHECK ((state <> 'resolved') OR (resolved_at IS NOT NULL)),
|
||||
CHECK ((state <> 'suppressed') OR (suppressed_until IS NOT NULL))
|
||||
);
|
||||
CREATE UNIQUE INDEX alerts_one_unresolved ON alerts.alerts (org_id, source_id, key) WHERE (state <> 'resolved');
|
||||
CREATE INDEX alerts_by_state ON alerts.alerts (org_id, state, opened_at DESC);
|
||||
CREATE INDEX alerts_by_target ON alerts.alerts (org_id, target_kind, target_id, opened_at DESC);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA alerts CASCADE;
|
||||
@@ -1,12 +0,0 @@
|
||||
-- +goose Up
|
||||
-- An organisation's settings are one row: what Archie does when nobody has
|
||||
-- decided otherwise. A missing row means every field keeps its default.
|
||||
CREATE TABLE governance.settings (
|
||||
org_id text PRIMARY KEY,
|
||||
-- approval_deadline is how long an approval request waits for an answer.
|
||||
approval_deadline interval NOT NULL,
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE governance.settings;
|
||||
@@ -1,11 +0,0 @@
|
||||
-- +goose Up
|
||||
-- A Postgres interval scans as text, so it can't be read straight into a Go
|
||||
-- duration. Milliseconds are exact and scan as a number. The default fills a
|
||||
-- row written before this change; it is dropped straight after.
|
||||
ALTER TABLE governance.settings DROP COLUMN approval_deadline;
|
||||
ALTER TABLE governance.settings ADD COLUMN approval_deadline_ms bigint NOT NULL DEFAULT 86400000;
|
||||
ALTER TABLE governance.settings ALTER COLUMN approval_deadline_ms DROP DEFAULT;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE governance.settings DROP COLUMN approval_deadline_ms;
|
||||
ALTER TABLE governance.settings ADD COLUMN approval_deadline interval NOT NULL DEFAULT '24 hours';
|
||||
@@ -0,0 +1,57 @@
|
||||
-- +goose Up
|
||||
CREATE SCHEMA proposals;
|
||||
|
||||
-- A proposal is a change Archie drafts with its evidence: a root-cause fix, a
|
||||
-- new trigger and workflow, a workflow change or a raised ceiling. change holds
|
||||
-- what publishing it writes, and base_version the version of the target it was
|
||||
-- drafted against, so a target changed since is detected. A policy or ceiling
|
||||
-- change needs a person with authority, and any other change needs the owner.
|
||||
-- A rejection keeps its reason so the next proposal can take it into account.
|
||||
-- prompted_by lists the events that led to it, which a published trigger runs
|
||||
-- for.
|
||||
CREATE TABLE proposals.proposals (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
kind text NOT NULL CHECK (kind IN ('root_cause_fix', 'trigger', 'workflow_change', 'ceiling_raise', 'policy_change')),
|
||||
state text NOT NULL CHECK (state IN ('pending', 'approved', 'rejected', 'published', 'superseded', 'withdrawn')),
|
||||
needs text NOT NULL CHECK (needs IN ('owner', 'authority')),
|
||||
title text NOT NULL,
|
||||
summary text NOT NULL,
|
||||
evidence jsonb NOT NULL,
|
||||
change jsonb NOT NULL,
|
||||
target_kind text NOT NULL,
|
||||
target_id text NOT NULL DEFAULT '',
|
||||
base_version integer,
|
||||
prompted_by uuid[] NOT NULL DEFAULT '{}',
|
||||
origin_run_id uuid,
|
||||
proposed_by_id text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
answered_by_id text,
|
||||
answered_at timestamptz,
|
||||
answer_reason text NOT NULL DEFAULT '',
|
||||
published_at timestamptz,
|
||||
CHECK ((answered_at IS NULL) = (answered_by_id IS NULL)),
|
||||
CHECK ((state IN ('pending', 'withdrawn', 'superseded')) OR (answered_at IS NOT NULL)),
|
||||
CHECK ((state = 'published') = (published_at IS NOT NULL))
|
||||
);
|
||||
CREATE INDEX proposals_by_state ON proposals.proposals (org_id, state, created_at DESC);
|
||||
CREATE INDEX proposals_by_target ON proposals.proposals (org_id, target_kind, target_id, created_at DESC);
|
||||
|
||||
-- The actions a proposal will take when it is approved, in order. Each is
|
||||
-- judged when the proposal is made and shown with it, and approving the
|
||||
-- proposal approves them. digest binds the approval to the exact action.
|
||||
CREATE TABLE proposals.actions (
|
||||
proposal_id uuid NOT NULL REFERENCES proposals.proposals (id) ON DELETE CASCADE,
|
||||
seq integer NOT NULL,
|
||||
installation_id uuid NOT NULL,
|
||||
action text NOT NULL,
|
||||
target_kind text NOT NULL,
|
||||
target_id text NOT NULL,
|
||||
input jsonb NOT NULL,
|
||||
digest text NOT NULL,
|
||||
decision_id uuid NOT NULL,
|
||||
PRIMARY KEY (proposal_id, seq)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP SCHEMA proposals CASCADE;
|
||||
Loaded 100 of 453 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user