Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(routines): trigger routines on GitHub events (#8730)

Eric Hayesef75cc83006b
diff --git a/.github/kafka-cluster-topics.json b/.github/kafka-cluster-topics.json
index 6167bb95fa..a3cb692efb 100644
--- a/.github/kafka-cluster-topics.json
+++ b/.github/kafka-cluster-topics.json
@@ -14,6 +14,7 @@
"macro.example",
"macro.forms",
"macro.github_pull_requests",
+ "macro.github_webhooks",
"macro.initiatives",
"macro.mentions",
"macro.messages",
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 0b53e4a009..475bb5657d 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -4088,9 +4088,11 @@
"crates/folds/agent_fold",
"crates/foreign_entity",
"crates/frecency",
+ "crates/fusionauth",
"crates/genai_telemetry",
"crates/generic_email_domains",
"crates/git_patch",
+ "crates/github",
"crates/github_pull_requests",
"crates/gmail_client",
"crates/google_token",
@@ -8564,9 +8566,11 @@
"crates/folds/agent_fold",
"crates/foreign_entity",
"crates/frecency",
+ "crates/fusionauth",
"crates/genai_telemetry",
"crates/generic_email_domains",
"crates/git_patch",
+ "crates/github",
"crates/github_pull_requests",
"crates/gmail_client",
"crates/google_token",
@@ -11912,9 +11916,11 @@
"crates/folds/agent_fold",
"crates/foreign_entity",
"crates/frecency",
+ "crates/fusionauth",
"crates/genai_telemetry",
"crates/generic_email_domains",
"crates/git_patch",
+ "crates/github",
"crates/github_pull_requests",
"crates/gmail_client",
"crates/google_token",
diff --git a/.sqlx/query-d4e5c358f8bdef259dbb3aa6d7f45ae1bd6b202c7fa8a65efb5a114c6aa0fd6f.json b/.sqlx/query-00c9b729a2000c7917ae4684afb061f766cfc38e9ae7c2f08cfdfc4c71e200a5.json
similarity index 52%
rename from .sqlx/query-d4e5c358f8bdef259dbb3aa6d7f45ae1bd6b202c7fa8a65efb5a114c6aa0fd6f.json
rename to .sqlx/query-00c9b729a2000c7917ae4684afb061f766cfc38e9ae7c2f08cfdfc4c71e200a5.json
index 9f65a6e0fa..ad99cf45b7 100644
--- a/.sqlx/query-d4e5c358f8bdef259dbb3aa6d7f45ae1bd6b202c7fa8a65efb5a114c6aa0fd6f.json
+++ b/.sqlx/query-00c9b729a2000c7917ae4684afb061f766cfc38e9ae7c2f08cfdfc4c71e200a5.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE scheduled_action_event_run SET state = 'finished', finished_at = now(), outcome = $4\n WHERE action_id = $1 AND event_id = $2 AND configuration_revision = $3 AND state = 'pending'\n RETURNING event_id\n ",
+ "query": "\n UPDATE scheduled_action_event_run SET state = 'finished', finished_at = now(), outcome = $4,\n event_context = event_context #- '{github,payload}'\n WHERE action_id = $1 AND event_id = $2 AND configuration_revision = $3 AND state = 'pending'\n RETURNING event_id\n ",
"describe": {
"columns": [
{
@@ -21,5 +21,5 @@
false
]
},
- "hash": "d4e5c358f8bdef259dbb3aa6d7f45ae1bd6b202c7fa8a65efb5a114c6aa0fd6f"
+ "hash": "00c9b729a2000c7917ae4684afb061f766cfc38e9ae7c2f08cfdfc4c71e200a5"
}
diff --git a/.sqlx/query-8aeb6e474551bb19376204018239a63702e2d335f18fd474bd47d74235c9fd74.json b/.sqlx/query-04a082e528cb65df106848f3ae183e7049998696865ba36054f1ca4a41f02d5b.json
similarity index 80%
rename from .sqlx/query-8aeb6e474551bb19376204018239a63702e2d335f18fd474bd47d74235c9fd74.json
rename to .sqlx/query-04a082e528cb65df106848f3ae183e7049998696865ba36054f1ca4a41f02d5b.json
index f3567ed6c2..415609227c 100644
--- a/.sqlx/query-8aeb6e474551bb19376204018239a63702e2d335f18fd474bd47d74235c9fd74.json
+++ b/.sqlx/query-04a082e528cb65df106848f3ae183e7049998696865ba36054f1ca4a41f02d5b.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id AS action_id, owner, enabled, configuration_revision,\n event_filters AS \"event_filters!\", event_activated_at AS \"event_activated_at!\"\n FROM scheduled_action\n WHERE enabled AND event_filters IS NOT NULL\n AND ($1::uuid IS NULL OR id > $1)\n AND event_activated_at <= $2\n AND (event_filters @> jsonb_build_array(jsonb_build_object('events', jsonb_build_array($3::text)))\n OR ($6::text IS NOT NULL AND event_filters @> jsonb_build_array(jsonb_build_object('events', jsonb_build_array($6::text)))))\n AND jsonb_path_exists(event_filters,\n '$[*] ? ((@.events[*] == $event || @.events[*] == $general) && (!exists (@.ids) || @.ids == null || @.ids[*] == $id))',\n jsonb_build_object('event', $3::text, 'general', $6::text, 'id', $4::text))\n ORDER BY id\n LIMIT $5\n ",
+ "query": "\n SELECT id AS action_id, owner, enabled, configuration_revision,\n event_filters AS \"event_filters!\", event_activated_at AS \"event_activated_at!\"\n FROM scheduled_action\n WHERE enabled AND event_filters IS NOT NULL\n AND ($1::uuid IS NULL OR id > $1)\n AND event_activated_at <= $2\n AND (event_filters @> jsonb_build_array(jsonb_build_object('events', jsonb_build_array($3::text)))\n OR ($6::text IS NOT NULL AND event_filters @> jsonb_build_array(jsonb_build_object('events', jsonb_build_array($6::text)))))\n AND jsonb_path_exists(event_filters,\n '$[*] ? ((@.events[*] == $event || @.events[*] == $general) && (!exists (@.ids) || @.ids == null || @.ids[*] == $id) && (!exists (@.github.events) || @.github.events[*] == $github_event))',\n jsonb_build_object('event', $3::text, 'general', $6::text, 'id', $4::text, 'github_event', $7::text))\n ORDER BY id\n LIMIT $5\n ",
"describe": {
"columns": [
{
@@ -41,6 +41,7 @@
"Text",
"Text",
"Int8",
+ "Text",
"Text"
]
},
@@ -53,5 +54,5 @@
true
]
},
- "hash": "8aeb6e474551bb19376204018239a63702e2d335f18fd474bd47d74235c9fd74"
+ "hash": "04a082e528cb65df106848f3ae183e7049998696865ba36054f1ca4a41f02d5b"
}
diff --git a/.sqlx/query-0f1fbb26939196a6023a96fafef0b1370fd5ce57595340bef54eabbfc9011ace.json b/.sqlx/query-0f1fbb26939196a6023a96fafef0b1370fd5ce57595340bef54eabbfc9011ace.json
deleted file mode 100644
index 1880fb2845..0000000000
--- a/.sqlx/query-0f1fbb26939196a6023a96fafef0b1370fd5ce57595340bef54eabbfc9011ace.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE scheduled_action_event_run SET state = 'finished', finished_at = now(), outcome = $4\n WHERE action_id = $1 AND event_id = $2 AND configuration_revision = $3 AND state = 'pending'\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid",
- "Int8",
- "Jsonb"
- ]
- },
- "nullable": []
- },
- "hash": "0f1fbb26939196a6023a96fafef0b1370fd5ce57595340bef54eabbfc9011ace"
-}
diff --git a/.sqlx/query-3741b79aec8ded73b32b3db92fe3108dbae2b110fda7885366431d33ff87d872.json b/.sqlx/query-3741b79aec8ded73b32b3db92fe3108dbae2b110fda7885366431d33ff87d872.json
new file mode 100644
index 0000000000..83f97988d6
--- /dev/null
+++ b/.sqlx/query-3741b79aec8ded73b32b3db92fe3108dbae2b110fda7885366431d33ff87d872.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE scheduled_action_event_run SET state = 'finished', finished_at = now(), outcome = $4,\n event_context = event_context #- '{github,payload}'\n WHERE action_id = $1 AND event_id = $2 AND configuration_revision = $3 AND state = 'pending'\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Int8",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3741b79aec8ded73b32b3db92fe3108dbae2b110fda7885366431d33ff87d872"
+}
diff --git a/.sqlx/query-de4f63dbbf1a6b451b4060195c385d3e810c63d8b993b6788f52975ed31794e8.json b/.sqlx/query-41af30ab22cf1385c6353c3330283e03a7cc4c5d7b0b9021fac14a8d138d4d5a.json
similarity index 59%
rename from .sqlx/query-de4f63dbbf1a6b451b4060195c385d3e810c63d8b993b6788f52975ed31794e8.json
rename to .sqlx/query-41af30ab22cf1385c6353c3330283e03a7cc4c5d7b0b9021fac14a8d138d4d5a.json
index 5fbf3d5708..cfb484810e 100644
--- a/.sqlx/query-de4f63dbbf1a6b451b4060195c385d3e810c63d8b993b6788f52975ed31794e8.json
+++ b/.sqlx/query-41af30ab22cf1385c6353c3330283e03a7cc4c5d7b0b9021fac14a8d138d4d5a.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE scheduled_action_event_run\n SET state = 'finished', finished_at = $3, outcome = $4, execution_record_id = $5\n WHERE action_id = $1 AND event_id = $2\n ",
+ "query": "\n UPDATE scheduled_action_event_run\n SET state = 'finished', finished_at = $3, outcome = $4, execution_record_id = $5,\n event_context = event_context #- '{github,payload}'\n WHERE action_id = $1 AND event_id = $2\n ",
"describe": {
"columns": [],
"parameters": {
@@ -14,5 +14,5 @@
},
"nullable": []
},
- "hash": "de4f63dbbf1a6b451b4060195c385d3e810c63d8b993b6788f52975ed31794e8"
+ "hash": "41af30ab22cf1385c6353c3330283e03a7cc4c5d7b0b9021fac14a8d138d4d5a"
}
diff --git a/.sqlx/query-5fee689d78b6d843632782bfb4b54720c5966e32c57e7a38ac54da51a0012638.json b/.sqlx/query-5fee689d78b6d843632782bfb4b54720c5966e32c57e7a38ac54da51a0012638.json
new file mode 100644
index 0000000000..656da0cc34
--- /dev/null
+++ b/.sqlx/query-5fee689d78b6d843632782bfb4b54720c5966e32c57e7a38ac54da51a0012638.json
@@ -0,0 +1,27 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE scheduled_action_event_run r\n SET state = 'finished', finished_at = $3,\n event_context = r.event_context #- '{github,payload}',\n outcome = CASE WHEN r.state = 'started' THEN $4::jsonb\n WHEN NOT a.enabled THEN $5::jsonb ELSE $6::jsonb END\n FROM scheduled_action a\n WHERE r.action_id = $1 AND r.event_id = $2 AND a.id = r.action_id\n AND ((r.state = 'started' AND r.deadline <= $3)\n OR (r.state = 'pending' AND (NOT a.enabled OR a.event_filters IS NULL\n OR a.configuration_revision <> r.configuration_revision)))\n RETURNING r.claim_token\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "claim_token",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Timestamptz",
+ "Jsonb",
+ "Jsonb",
+ "Jsonb"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "5fee689d78b6d843632782bfb4b54720c5966e32c57e7a38ac54da51a0012638"
+}
diff --git a/.sqlx/query-913ed91869fb2be6290d3a8c53726135a89cc8ba5a1f076ac6f03a429b8c1c2d.json b/.sqlx/query-913ed91869fb2be6290d3a8c53726135a89cc8ba5a1f076ac6f03a429b8c1c2d.json
deleted file mode 100644
index af27e6d879..0000000000
--- a/.sqlx/query-913ed91869fb2be6290d3a8c53726135a89cc8ba5a1f076ac6f03a429b8c1c2d.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE scheduled_action_event_run r\n SET state = 'finished', finished_at = $3,\n outcome = CASE WHEN r.state = 'started' THEN $4::jsonb\n WHEN NOT a.enabled THEN $5::jsonb ELSE $6::jsonb END\n FROM scheduled_action a\n WHERE r.action_id = $1 AND r.event_id = $2 AND a.id = r.action_id\n AND ((r.state = 'started' AND r.deadline <= $3)\n OR (r.state = 'pending' AND (NOT a.enabled OR a.event_filters IS NULL\n OR a.configuration_revision <> r.configuration_revision)))\n RETURNING r.claim_token\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "claim_token",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid",
- "Timestamptz",
- "Jsonb",
- "Jsonb",
- "Jsonb"
- ]
- },
- "nullable": [
- true
- ]
- },
- "hash": "913ed91869fb2be6290d3a8c53726135a89cc8ba5a1f076ac6f03a429b8c1c2d"
-}
diff --git a/.sqlx/query-e9143fe62b3d30824350ef192e09deababb09d166ef240b5be2edf39545ebc85.json b/.sqlx/query-9172bc72a5ab95027cf20132ac1b27460a1bc82e941c2454dce521decd93ecff.json
similarity index 68%
rename from .sqlx/query-e9143fe62b3d30824350ef192e09deababb09d166ef240b5be2edf39545ebc85.json
rename to .sqlx/query-9172bc72a5ab95027cf20132ac1b27460a1bc82e941c2454dce521decd93ecff.json
index 1635e54169..fa2e72494b 100644
--- a/.sqlx/query-e9143fe62b3d30824350ef192e09deababb09d166ef240b5be2edf39545ebc85.json
+++ b/.sqlx/query-9172bc72a5ab95027cf20132ac1b27460a1bc82e941c2454dce521decd93ecff.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id FROM scheduled_action\n WHERE id = $1 AND enabled AND event_filters IS NOT NULL\n AND configuration_revision = $2 AND event_activated_at <= $3\n AND jsonb_path_exists(event_filters,\n '$[*] ? ((@.events[*] == $event || @.events[*] == $general) && (!exists (@.ids) || @.ids == null || @.ids[*] == $id))',\n jsonb_build_object('event', $4::text, 'general', $6::text, 'id', $5::text))\n FOR UPDATE\n ",
+ "query": "\n SELECT id FROM scheduled_action\n WHERE id = $1 AND enabled AND event_filters IS NOT NULL\n AND configuration_revision = $2 AND event_activated_at <= $3\n AND jsonb_path_exists(event_filters,\n '$[*] ? ((@.events[*] == $event || @.events[*] == $general) && (!exists (@.ids) || @.ids == null || @.ids[*] == $id) && (!exists (@.github.events) || @.github.events[*] == $github_event))',\n jsonb_build_object('event', $4::text, 'general', $6::text, 'id', $5::text, 'github_event', $7::text))\n FOR UPDATE\n ",
"describe": {
"columns": [
{
@@ -16,6 +16,7 @@
"Timestamptz",
"Text",
"Text",
+ "Text",
"Text"
]
},
@@ -23,5 +24,5 @@
false
]
},
- "hash": "e9143fe62b3d30824350ef192e09deababb09d166ef240b5be2edf39545ebc85"
+ "hash": "9172bc72a5ab95027cf20132ac1b27460a1bc82e941c2454dce521decd93ecff"
}
diff --git a/.sqlx/query-cd1c68632eb199cf6e08a8aa87497e400f316a4c3674aae1978c6a5d7e38f6f6.json b/.sqlx/query-cd1c68632eb199cf6e08a8aa87497e400f316a4c3674aae1978c6a5d7e38f6f6.json
new file mode 100644
index 0000000000..39de542c99
--- /dev/null
+++ b/.sqlx/query-cd1c68632eb199cf6e08a8aa87497e400f316a4c3674aae1978c6a5d7e38f6f6.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1 FROM github_app_installation i\n WHERE i.id = $1\n AND EXISTS (SELECT 1 FROM github_links l WHERE l.macro_id = $2)\n AND (\n (i.source_type = 'user' AND i.source_id = $2 AND NOT EXISTS (\n SELECT 1 FROM github_app_installation_installer installer\n WHERE installer.installation_id = i.id\n AND installer.github_user_id NOT IN (\n SELECT l.github_user_id FROM github_links l WHERE l.macro_id = $2\n )\n ))\n OR (i.source_type = 'team' AND EXISTS (\n SELECT 1 FROM team_user t\n WHERE t.team_id::text = i.source_id AND t.user_id = $2\n ))\n )\n ) AS \"claimed!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "claimed!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "cd1c68632eb199cf6e08a8aa87497e400f316a4c3674aae1978c6a5d7e38f6f6"
+}
diff --git a/.sqlx/query-ff22001855d6f76e62f05f1d01373a5e50d9531a3f59756ab1af2a90d90e04a4.json b/.sqlx/query-ff22001855d6f76e62f05f1d01373a5e50d9531a3f59756ab1af2a90d90e04a4.json
new file mode 100644
index 0000000000..90b742b570
--- /dev/null
+++ b/.sqlx/query-ff22001855d6f76e62f05f1d01373a5e50d9531a3f59756ab1af2a90d90e04a4.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS (SELECT 1 FROM github_links WHERE macro_id = $1) AS \"linked!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "linked!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "ff22001855d6f76e62f05f1d01373a5e50d9531a3f59756ab1af2a90d90e04a4"
+}
diff --git a/Cargo.lock b/Cargo.lock
index dd26393e4e..e0720ab6ba 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8875,6 +8875,8 @@ dependencies = [
"macro_db_migrator",
"macro_env",
"macro_env_var",
+ "macro_event_broker",
+ "macro_event_topics",
"macro_service_urls",
"macro_user_id",
"macro_uuid",
@@ -17370,6 +17372,8 @@ dependencies = [
"feature_flags",
"frecency",
"futures",
+ "github",
+ "glob",
"jev",
"kafka_util",
"lexical_client",
diff --git a/apps/web/src/features/block-agent/state/prompt-origin.test.ts b/apps/web/src/features/block-agent/state/prompt-origin.test.ts
index 074434da5b..adf51c92fe 100644
--- a/apps/web/src/features/block-agent/state/prompt-origin.test.ts
+++ b/apps/web/src/features/block-agent/state/prompt-origin.test.ts
@@ -501,6 +501,25 @@ describe('promptOrigin', () => {
tail: '· Acme renewal ended',
destination: { kind: 'call', callId: 'call-1' },
});
+
+ expect(
+ routine({
+ type: 'event',
+ event: {
+ event: 'github',
+ delivery: {
+ event: 'workflow_run',
+ action: 'completed',
+ repository: 'macro-inc/macro',
+ },
+ },
+ })
+ ).toEqual({
+ lead: 'via routine',
+ place: 'Watcher',
+ tail: '· GitHub workflow_run completed in macro-inc/macro',
+ destination: { kind: 'routine', routineId: 'r-2' },
+ });
});
it('is undefined when the context names no trigger', () => {
diff --git a/apps/web/src/features/block-agent/state/prompt-origin.ts b/apps/web/src/features/block-agent/state/prompt-origin.ts
index 07a1945376..d4c731e70b 100644
--- a/apps/web/src/features/block-agent/state/prompt-origin.ts
+++ b/apps/web/src/features/block-agent/state/prompt-origin.ts
@@ -322,6 +322,19 @@ function readFiring(trigger: Element): Firing {
tail: `· ${callTitle} ended`,
destination: callDestination,
}))
+ .with('github', () => {
+ const delivery = child(event, 'github');
+ const name = [attribute(delivery, 'event'), attribute(delivery, 'action')]
+ .filter(Boolean)
+ .join(' ');
+ const repository = attribute(delivery, 'repository');
+ return {
+ tail: repository
+ ? `· GitHub ${name} in ${repository}`
+ : `· GitHub ${name}`,
+ destination: undefined,
+ };
+ })
.otherwise(() => ({ tail: undefined, destination: undefined }));
}
diff --git a/apps/web/src/features/email-compose/views/compose-toolbar.tsx b/apps/web/src/features/email-compose/views/compose-toolbar.tsx
index 65a6ee3b8d..d5f9cabf32 100644
--- a/apps/web/src/features/email-compose/views/compose-toolbar.tsx
+++ b/apps/web/src/features/email-compose/views/compose-toolbar.tsx
@@ -86,11 +86,13 @@ export function EmailComposeToolbar(props: {
constrainedMediaDimensions: { width: 542, height: 542 },
})
}
- label="Insert image"
- size="icon-composer"
+ variant="ghost"
+ tooltip="Insert image"
+ aria-label="Insert image"
+ size="icon-md"
disabled={ctx.disabled()}
>
- <ImageIcon />
+ <ImageIcon class="size-4 touch:size-6 shrink-0 pointer-events-none" />
</Button>
</Show>
<Button
diff --git a/apps/web/src/features/routines/components/routine-github-connect.tsx b/apps/web/src/features/routines/components/routine-github-connect.tsx
new file mode 100644
index 0000000000..547c97dfc5
--- /dev/null
+++ b/apps/web/src/features/routines/components/routine-github-connect.tsx
@@ -0,0 +1,24 @@
+import GithubIcon from '@icon/mcp-github.svg';
+import { Button } from '@ui';
+
+/** Asks for a GitHub link before GitHub triggers can be chosen or run. */
+export function RoutineGithubConnect(props: {
+ message: string;
+ connecting: boolean;
+ onConnect: () => void;
+}) {
+ return (
+ <div class="flex flex-col items-start gap-2 px-2 py-2">
+ <p class="text-xs text-ink-muted">{props.message}</p>
+ <Button
+ variant="secondary"
+ size="sm"
+ disabled={props.connecting}
+ onClick={props.onConnect}
+ >
+ <GithubIcon class="size-3.5" />
+ Connect GitHub
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/routines/components/routine-github-settings.tsx b/apps/web/src/features/routines/components/routine-github-settings.tsx
new file mode 100644
index 0000000000..6bd39808bf
--- /dev/null
+++ b/apps/web/src/features/routines/components/routine-github-settings.tsx
@@ -0,0 +1,147 @@
+import { ToggleSwitch } from '@ui';
+import { createSignal, For, Show } from 'solid-js';
+import type {
+ GithubRepositoryOptions,
+ GithubSelectorDraft,
+} from '../core/routine-triggers';
+
+function names(text: string) {
+ return text
+ .split(',')
+ .map((name) => name.trim())
+ .filter(Boolean);
+}
+
+/** A comma-separated list that keeps what the person typed while it parses it. */
+function NameList(props: {
+ label: string;
+ placeholder: string;
+ description: string;
+ value: string[];
+ onChange: (value: string[]) => void;
+}) {
+ const [text, setText] = createSignal(props.value.join(', '));
+ return (
+ <label class="grid gap-1">
+ <span class="text-xs font-medium">{props.label}</span>
+ <input
+ placeholder={props.placeholder}
+ value={text()}
+ onInput={(e) => {
+ setText(e.currentTarget.value);
+ props.onChange(names(e.currentTarget.value));
+ }}
+ class="w-full rounded-md border border-edge-muted bg-input px-2 py-1.5 text-xs outline-none focus:border-accent"
+ />
+ <span class="text-xs text-ink-extra-muted">{props.description}</span>
+ </label>
+ );
+}
+
+/** Which deliveries from Macro's GitHub app the trigger watches. */
+export function RoutineGithubSettings(props: {
+ selector: GithubSelectorDraft;
+ repositories: GithubRepositoryOptions;
+ onChange: (selector: GithubSelectorDraft) => void;
+}) {
+ const [search, setSearch] = createSignal('');
+ const change = (patch: Partial<GithubSelectorDraft>) =>
+ props.onChange({ ...props.selector, ...patch });
+ const selected = (name: string) =>
+ props.selector.repositories.some(
+ (chosen) => chosen.toLowerCase() === name.toLowerCase()
+ );
+ const toggle = (name: string) =>
+ change({
+ repositories: selected(name)
+ ? props.selector.repositories.filter(
+ (chosen) => chosen.toLowerCase() !== name.toLowerCase()
+ )
+ : [...props.selector.repositories, name],
+ });
+ // Chosen repositories stay listed even when the app no longer reaches them.
+ const options = () =>
+ [...new Set([...props.selector.repositories, ...props.repositories.names])]
+ .filter((name) =>
+ name.toLowerCase().includes(search().trim().toLowerCase())
+ )
+ .toSorted(
+ (left, right) => Number(selected(right)) - Number(selected(left))
+ );
+ return (
+ <div class="grid gap-3">
+ <NameList
+ label="GitHub events"
+ placeholder="Any event"
+ description="Names GitHub sends, like workflow_run, pull_request or push."
+ value={props.selector.events}
+ onChange={(events) => change({ events })}
+ />
+ <NameList
+ label="Actions"
+ placeholder="Any action"
+ description="Like completed, opened or closed. Events such as push have none."
+ value={props.selector.actions}
+ onChange={(actions) => change({ actions })}
+ />
+ <div class="grid gap-1">
+ <span class="text-xs font-medium">Repositories</span>
+ <input
+ aria-label="Search repositories"
+ placeholder={
+ props.selector.repositories.length
+ ? `${props.selector.repositories.length} selected · search…`
+ : 'All repositories · search to narrow…'
+ }
+ value={search()}
+ onInput={(e) => setSearch(e.currentTarget.value)}
+ class="w-full rounded-md border border-edge-muted bg-input px-2 py-1.5 text-xs outline-none focus:border-accent"
+ />
+ <div class="max-h-36 overflow-y-auto">
+ <Show
+ when={!props.repositories.loading}
+ fallback={<p class="p-2 text-xs text-ink-muted">Loading…</p>}
+ >
+ <Show when={props.repositories.error}>
+ <p class="p-2 text-xs text-failure">
+ Your repositories couldn’t be listed.
+ </p>
+ </Show>
+ <Show
+ when={options().length}
+ fallback={
+ <p class="p-2 text-xs text-ink-muted">
+ Install Macro’s GitHub app to watch a repository.
+ </p>
+ }
+ >
+ <For each={options()}>
+ {(name) => (
+ <label class="flex items-center gap-2 rounded-md px-2 py-1 text-xs hover:bg-hover">
+ <input
+ type="checkbox"
+ checked={selected(name)}
+ onChange={() => toggle(name)}
+ />
+ <span class="truncate">{name}</span>
+ </label>
+ )}
+ </For>
+ </Show>
+ </Show>
+ </div>
+ </div>
+ <ToggleSwitch
+ label="Also run for bots and apps"
+ checked={props.selector.includeBots}
+ onChange={(includeBots) => change({ includeBots })}
+ />
+ <Show when={props.selector.includeBots}>
+ <p class="text-xs text-ink-muted">
+ Includes Macro’s own app: make sure what this routine does on GitHub
+ doesn’t trigger it again.
+ </p>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/routines/components/routine-payload-tests.tsx b/apps/web/src/features/routines/components/routine-payload-tests.tsx
new file mode 100644
index 0000000000..f5aed377d1
--- /dev/null
+++ b/apps/web/src/features/routines/components/routine-payload-tests.tsx
@@ -0,0 +1,119 @@
+import PlusIcon from '@icon/system/regular/plus.svg';
+import XIcon from '@icon/system/regular/x.svg';
+import { Button } from '@ui';
+import { For, Show } from 'solid-js';
+import {
+ MAX_PAYLOAD_TESTS,
+ type PayloadTestDraft,
+ type PayloadTestOp,
+ payloadTestSchema,
+} from '../core/routine-triggers';
+
+const operations: { value: PayloadTestOp; label: string }[] = [
+ { value: 'equals', label: 'is' },
+ { value: 'in', label: 'is one of' },
+ { value: 'notIn', label: 'is not one of' },
+ { value: 'glob', label: 'matches' },
+ { value: 'exists', label: 'is set' },
+ { value: 'missing', label: 'is not set' },
+];
+
+function valuePlaceholder(op: PayloadTestOp) {
+ if (op === 'in' || op === 'notIn') return 'failure, timed_out';
+ if (op === 'glob') return 'release/*';
+ return 'failure';
+}
+
+/**
+ * Exact tests on a delivery's JSON payload. They run before anything is
+ * queued, so a busy source costs nothing until a delivery passes them all.
+ */
+export function RoutinePayloadTests(props: {
+ tests: PayloadTestDraft[];
+ onChange: (tests: PayloadTestDraft[] | undefined) => void;
+}) {
+ const update = (index: number, patch: Partial<PayloadTestDraft>) =>
+ props.onChange(
+ props.tests.map((test, i) => (i === index ? { ...test, ...patch } : test))
+ );
+ const remove = (index: number) => {
+ const tests = props.tests.filter((_, i) => i !== index);
+ props.onChange(tests.length ? tests : undefined);
+ };
+ return (
+ <div class="mt-3 grid gap-2">
+ <p class="text-xs font-medium">Only when the payload</p>
+ <For each={props.tests}>
+ {(test, index) => (
+ <div class="grid grid-cols-[1fr_auto] gap-1">
+ <div class="grid min-w-0 grid-cols-[1fr_auto] gap-1">
+ <input
+ aria-label="Payload field"
+ placeholder="workflow_run.conclusion"
+ value={test.path}
+ onInput={(e) =>
+ update(index(), { path: e.currentTarget.value.trim() })
+ }
+ class="min-w-0 rounded-md border border-edge-muted bg-input px-2 py-1.5 text-xs outline-none focus:border-accent"
+ />
+ <select
+ aria-label="Comparison"
+ value={test.op}
+ onChange={(e) => {
+ const op = payloadTestSchema.shape.op.safeParse(
+ e.currentTarget.value
+ );
+ if (op.success) update(index(), { op: op.data });
+ }}
+ class="min-w-0 rounded-md border border-edge-muted bg-input px-2 py-1.5 text-xs outline-none focus:border-accent"
+ >
+ <For each={operations}>
+ {(operation) => (
+ <option value={operation.value}>{operation.label}</option>
+ )}
+ </For>
+ </select>
+ <Show when={test.op !== 'exists' && test.op !== 'missing'}>
+ <input
+ aria-label="Value"
+ placeholder={valuePlaceholder(test.op)}
+ value={test.value}
+ onInput={(e) =>
+ update(index(), { value: e.currentTarget.value })
+ }
+ class="col-span-2 min-w-0 rounded-md border border-edge-muted bg-input px-2 py-1.5 text-xs outline-none focus:border-accent"
+ />
+ </Show>
+ </div>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={`Remove test on ${test.path || 'field'}`}
+ onClick={() => remove(index())}
+ >
+ <XIcon class="size-3.5" />
+ </Button>
+ </div>
+ )}
+ </For>
+ <Show when={props.tests.length < MAX_PAYLOAD_TESTS}>
+ <button
+ type="button"
+ class="flex items-center gap-1.5 rounded-md px-1 py-1 text-xs text-ink-muted hover:text-ink"
+ onClick={() =>
+ props.onChange([
+ ...props.tests,
+ { path: '', op: 'equals', value: '' },
+ ])
+ }
+ >
+ <PlusIcon class="size-3" /> Add a field test
+ </button>
+ </Show>
+ <p class="text-xs text-ink-extra-muted">
+ Fields are keys joined by dots; <code>*</code> checks every item of a
+ list, like <code>pull_request.labels.*.name</code>.
+ </p>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/routines/components/routine-triggers.tsx b/apps/web/src/features/routines/components/routine-triggers.tsx
index 2852316984..f2ff059f02 100644
--- a/apps/web/src/features/routines/components/routine-triggers.tsx
+++ b/apps/web/src/features/routines/components/routine-triggers.tsx
@@ -1,3 +1,4 @@
+import GithubIcon from '@icon/mcp-github.svg';
import ArrowLeftIcon from '@icon/system/regular/arrow-left.svg';
import CaretDownIcon from '@icon/system/regular/caret-down.svg';
import CaretRightIcon from '@icon/system/regular/caret-right.svg';
@@ -26,6 +27,7 @@ import {
import {
type EventTriggerDraft,
eventScopeKind,
+ eventTriggerDescription,
eventTriggerLabel,
isGlobalEvent,
newScheduleTrigger,
@@ -48,11 +50,21 @@ type EventSlots = {
trigger: Accessor<EventTriggerDraft>,
change: (ids: string[] | undefined) => void
) => JSX.Element;
+ /** Settings particular to some events, such as GitHub's selector. */
+ renderEventSettings?: (
+ trigger: Accessor<EventTriggerDraft>,
+ change: (patch: Partial<EventTriggerDraft>) => void
+ ) => JSX.Element;
/** Absent where conditions are unavailable. */
renderEventCondition?: (
trigger: Accessor<EventTriggerDraft>,
change: (condition: string | undefined) => void
) => JSX.Element;
+ /** Wraps a group's options, e.g. to ask for an account they need first. */
+ renderEventGroup?: (
+ group: RoutineEventGroup,
+ options: () => JSX.Element
+ ) => JSX.Element;
};
function scheduleSummary(trigger: ScheduleTriggerDraft) {
@@ -86,6 +98,9 @@ function EventIcon(props: { group: RoutineEventGroup; class: string }) {
<Match when={props.group === 'Calls'}>
<PhoneIcon class={props.class} />
</Match>
+ <Match when={props.group === 'GitHub'}>
+ <GithubIcon class={props.class} />
+ </Match>
</Switch>
);
}
@@ -98,6 +113,7 @@ function TriggerIcon(props: { trigger?: RoutineTriggerDraft }) {
if (kind === 'THREAD') return 'Email';
if (kind === 'DOCUMENT') return 'Documents';
if (kind === 'CALL_RECORD') return 'Calls';
+ if (kind === 'GITHUB') return 'GitHub';
return 'Channels';
};
return (
@@ -112,6 +128,7 @@ function TriggerIcon(props: { trigger?: RoutineTriggerDraft }) {
function TriggerChoices(props: {
onSelect: (trigger: RoutineTriggerDraft) => void;
+ renderEventGroup?: EventSlots['renderEventGroup'];
}) {
let inputRef: HTMLInputElement | undefined;
onMount(() => inputRef?.focus());
@@ -209,31 +226,37 @@ function TriggerChoices(props: {
{(group) => (
<Show when={events().some((event) => event.group === group)}>
<p class="px-2 pb-1 pt-3 text-xs text-ink-extra-muted">{group}</p>
- <For each={events().filter((event) => event.group === group)}>
- {(event) => (
- <button
- type="button"
- data-trigger-option
- title={event.description}
- class="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-hover focus-visible:bg-hover outline-none"
- onClick={() =>
- props.onSelect({
- id: crypto.randomUUID(),
- kind: 'event',
- events: [event.value],
- ids: isGlobalEvent([event.value]) ? undefined : [],
- })
- }
- >
- <EventIcon
- group={group}
- class="size-4 shrink-0 text-ink-muted"
- />
- {event.label}
- <CaretRightIcon class="ml-auto size-3 text-ink-muted" />
- </button>
- )}
- </For>
+ {(props.renderEventGroup ?? ((_, options) => options()))(
+ group,
+ () => (
+ <For each={events().filter((event) => event.group === group)}>
+ {(event) => (
+ <button
+ type="button"
+ data-trigger-option
+ title={event.description}
+ class="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-hover focus-visible:bg-hover outline-none"
+ onClick={() =>
+ props.onSelect({
+ id: crypto.randomUUID(),
+ kind: 'event',
+ events: [event.value],
+ ids: isGlobalEvent([event.value]) ? undefined : [],
+ ...structuredClone(event.preset),
+ })
+ }
+ >
+ <EventIcon
+ group={group}
+ class="size-4 shrink-0 text-ink-muted"
+ />
+ {event.label}
+ <CaretRightIcon class="ml-auto size-3 text-ink-muted" />
+ </button>
+ )}
+ </For>
+ )
+ )}
</Show>
)}
</For>
@@ -358,7 +381,15 @@ function TriggerChip(
<Popover.Title class="sr-only">
{props.trigger ? 'Edit trigger' : 'Add trigger'}
</Popover.Title>
- <Show when={pending()} fallback={<TriggerChoices onSelect={edit} />}>
+ <Show
+ when={pending()}
+ fallback={
+ <TriggerChoices
+ onSelect={edit}
+ renderEventGroup={props.renderEventGroup}
+ />
+ }
+ >
<div class="flex shrink-0 items-center gap-2 border-b border-edge-muted px-3 py-2">
<Show when={!props.trigger}>
<Button
@@ -391,14 +422,11 @@ function TriggerChip(
{(value) => (
<>
<p class="mb-3 text-xs text-ink-muted">
- {value()
- .events.map(
- (name) =>
- routineEvents.find((item) => item.value === name)
- ?.description
- )
- .join(' ')}
+ {eventTriggerDescription(value())}
</p>
+ {props.renderEventSettings?.(value, (patch) =>
+ edit({ ...value(), ...patch })
+ )}
{props.renderEventScope(value, (ids) =>
edit({ ...value(), ids })
)}
@@ -458,7 +486,9 @@ export function RoutineTriggers(
trigger={props.triggers.find((trigger) => trigger.id === id)}
renderEventLabel={props.renderEventLabel}
renderEventScope={props.renderEventScope}
+ renderEventSettings={props.renderEventSettings}
renderEventCondition={props.renderEventCondition}
+ renderEventGroup={props.renderEventGroup}
onSave={(value) =>
props.onChange(
props.triggers.map((trigger) =>
@@ -477,7 +507,9 @@ export function RoutineTriggers(
<TriggerChip
renderEventLabel={props.renderEventLabel}
renderEventScope={props.renderEventScope}
+ renderEventSettings={props.renderEventSettings}
renderEventCondition={props.renderEventCondition}
+ renderEventGroup={props.renderEventGroup}
onSave={(trigger) => props.onChange([...props.triggers, trigger])}
/>
</>
diff --git a/apps/web/src/features/routines/core/routine-triggers.ts b/apps/web/src/features/routines/core/routine-triggers.ts
index 7bb44599e6..20d111e90e 100644
--- a/apps/web/src/features/routines/core/routine-triggers.ts
+++ b/apps/web/src/features/routines/core/routine-triggers.ts
@@ -17,6 +17,35 @@ export const scheduleTriggerSchema = z.object({
onceAt: z.string(),
cron: z.string(),
});
+/** One exact test on an external delivery's JSON payload, as the editor holds it. */
+export const payloadTestSchema = z.object({
+ /** Keys from the payload's root, joined with dots; `*` steps into every array item. */
+ path: z.string(),
+ op: z.enum(['equals', 'in', 'notIn', 'glob', 'exists', 'missing']),
+ /** A value, or a comma-separated list for `in` and `notIn`. */
+ value: z.string(),
+});
+export type PayloadTestDraft = z.infer<typeof payloadTestSchema>;
+export type PayloadTestOp = PayloadTestDraft['op'];
+
+/** Which GitHub App deliveries a `github` trigger watches; empty lists match everything. */
+export const githubSelectorSchema = z.object({
+ events: z.array(z.string()),
+ actions: z.array(z.string()),
+ /** `owner/name`. */
+ repositories: z.array(z.string()),
+ includeBots: z.boolean(),
+});
+export type GithubSelectorDraft = z.infer<typeof githubSelectorSchema>;
+
+/** The repositories a GitHub trigger can choose from. */
+export type GithubRepositoryOptions = {
+ /** `owner/name` of every repository Macro's GitHub app reaches for you. */
+ names: string[];
+ loading: boolean;
+ error: boolean;
+};
+
export const routineTriggerSchema = z.discriminatedUnion('kind', [
scheduleTriggerSchema,
z.object({
@@ -40,10 +69,15 @@ export const routineTriggerSchema = z.discriminatedUnion('kind', [
'channel.message_attachment_created',
'call.started',
'call.ended',
+ 'github',
])
)
.min(1),
ids: z.array(z.string().uuid()).optional(),
+ /** Only for `github`. */
+ github: githubSelectorSchema.optional(),
+ /** Only for `github`: payload tests that must all pass. */
+ match: z.array(payloadTestSchema).optional(),
/** Yes/no question the event's content must answer with yes. */
condition: z.string().optional(),
}),
@@ -58,13 +92,29 @@ export const routineEventGroups = [
'Tasks',
'Email',
'Calls',
+ 'GitHub',
] as const;
export type RoutineEventGroup = (typeof routineEventGroups)[number];
+type ExternalPreset = Pick<EventTriggerDraft, 'github' | 'match'>;
+
+function github(
+ events: string[],
+ actions: string[] = [],
+ match?: PayloadTestDraft[]
+): ExternalPreset {
+ return {
+ github: { events, actions, repositories: [], includeBots: false },
+ ...(match ? { match } : {}),
+ };
+}
+
export const routineEvents: {
value: RoutineEventName;
label: string;
group: RoutineEventGroup;
description: string;
+ /** What choosing this item fills in, for events from outside Macro. */
+ preset?: ExternalPreset;
}[] = [
{
value: 'channel.created',
@@ -143,6 +193,101 @@ export const routineEvents: {
description:
'A call you joined ends. The routine gets the call’s participants and transcript.',
},
+ {
+ value: 'github',
+ label: 'Workflow failed',
+ group: 'GitHub',
+ description:
+ 'A GitHub Actions workflow finishes without passing. Test workflow_run.name to watch one workflow.',
+ preset: github(
+ ['workflow_run'],
+ ['completed'],
+ [
+ {
+ path: 'workflow_run.conclusion',
+ op: 'in',
+ value: 'failure, timed_out',
+ },
+ ]
+ ),
+ },
+ {
+ value: 'github',
+ label: 'Workflow finished',
+ group: 'GitHub',
+ description: 'A GitHub Actions workflow finishes, whatever its result.',
+ preset: github(['workflow_run'], ['completed']),
+ },
+ {
+ value: 'github',
+ label: 'Pull request opened',
+ group: 'GitHub',
+ description: 'Someone opens a pull request.',
+ preset: github(['pull_request'], ['opened']),
+ },
+ {
+ value: 'github',
+ label: 'Pull request merged',
+ group: 'GitHub',
+ description: 'A pull request is merged.',
+ preset: github(
+ ['pull_request'],
+ ['closed'],
+ [{ path: 'pull_request.merged', op: 'equals', value: 'true' }]
+ ),
+ },
+ {
+ value: 'github',
+ label: 'Review requested',
+ group: 'GitHub',
+ description: 'Someone asks for a review on a pull request.',
+ preset: github(['pull_request'], ['review_requested']),
+ },
+ {
+ value: 'github',
+ label: 'Review submitted',
+ group: 'GitHub',
+ description:
+ 'Someone approves, comments on, or requests changes to a pull request.',
+ preset: github(['pull_request_review'], ['submitted']),
+ },
+ {
+ value: 'github',
+ label: 'Issue opened',
+ group: 'GitHub',
+ description: 'Someone opens an issue.',
+ preset: github(['issues'], ['opened']),
+ },
+ {
+ value: 'github',
+ label: 'Comment added',
+ group: 'GitHub',
+ description: 'Someone comments on an issue or pull request.',
+ preset: github(['issue_comment'], ['created']),
+ },
+ {
+ value: 'github',
+ label: 'Code pushed',
+ group: 'GitHub',
+ description:
+ 'Commits are pushed. Test ref, e.g. refs/heads/main, to watch one branch.',
+ preset: github(['push']),
+ },
+ {
+ value: 'github',
+ label: 'Release published',
+ group: 'GitHub',
+ description: 'A release is published.',
+ preset: github(['release'], ['published']),
+ },
+ {
+ value: 'github',
+ label: 'Any GitHub event',
+ group: 'GitHub',
+ description:
+ 'Any event Macro’s GitHub app receives, narrowed by the event names, actions, and payload tests you choose.',
+ preset: github([]),
+ },
];
// Preserve saved selectors while keeping the creation menu focused on the
@@ -153,7 +298,16 @@ const legacyEventLabels: Partial<Record<RoutineEventName, string>> = {
'channel.message_attachment_created': 'Attachment added',
};
-export function eventScopeKind(trigger: EventTriggerDraft) {
+export type EventScopeKind =
+ | 'TASK'
+ | 'DOCUMENT'
+ | 'THREAD'
+ | 'CALL_RECORD'
+ | 'CHANNEL'
+ | 'GITHUB';
+
+export function eventScopeKind(trigger: EventTriggerDraft): EventScopeKind {
+ if (trigger.events.includes('github')) return 'GITHUB';
if (trigger.events.every((event) => event.startsWith('task.'))) return 'TASK';
if (trigger.events.every((event) => event.startsWith('document.')))
return 'DOCUMENT';
@@ -173,6 +327,7 @@ export function conditionPlaceholder(trigger: EventTriggerDraft) {
.with('DOCUMENT', () => 'Is this document meeting notes?')
.with('CHANNEL', () => 'Is someone asking for help?')
.with('CALL_RECORD', () => 'Was this a call with a customer?')
+ .with('GITHUB', () => 'Does this failure look like a flaky test?')
.exhaustive();
}
@@ -182,7 +337,8 @@ export function isGlobalEvent(events: readonly RoutineEventName[]) {
event.endsWith('.created') ||
event === 'email.message_received' ||
event === 'call.started' ||
- event === 'call.ended'
+ event === 'call.ended' ||
+ event === 'github'
);
}
@@ -195,7 +351,48 @@ export function callEventScopeLabel(events: readonly RoutineEventName[]) {
return 'Calls you join';
}
+function sameNames(left: readonly string[], right: readonly string[]) {
+ const sorted = right.toSorted();
+ return (
+ left.length === right.length &&
+ left.toSorted().every((name, index) => name === sorted[index])
+ );
+}
+
+/** A preset's label while the selector is still that preset's, else its events. */
+function githubTriggerLabel(selector: GithubSelectorDraft | undefined) {
+ const preset = routineEvents.find(
+ (item) =>
+ item.preset?.github !== undefined &&
+ selector !== undefined &&
+ sameNames(item.preset.github.events, selector.events) &&
+ sameNames(item.preset.github.actions, selector.actions)
+ );
+ if (preset) return preset.label;
+ if (!selector?.events.length) return 'Any GitHub event';
+ return `GitHub ${selector.events.join(', ')}`;
+}
+
+/** What the trigger's events are, for its settings panel. */
+export function eventTriggerDescription(trigger: EventTriggerDraft) {
+ if (trigger.events.includes('github')) {
+ const label = githubTriggerLabel(trigger.github);
+ const github = routineEvents.filter((item) => item.value === 'github');
+ return (
+ github.find((item) => item.label === label) ??
+ github.find((item) => item.preset?.github?.events.length === 0)
+ )?.description;
+ }
+ return trigger.events
+ .map(
+ (name) => routineEvents.find((item) => item.value === name)?.description
+ )
+ .join(' ');
+}
+
export function eventTriggerLabel(trigger: EventTriggerDraft) {
+ if (trigger.events.includes('github'))
+ return githubTriggerLabel(trigger.github);
return trigger.events
.map(
(event) =>
@@ -241,6 +438,65 @@ function validateEventTrigger(
return 'Choose up to 100 items per event trigger.';
if ([...(trigger.condition?.trim() ?? '')].length > MAX_CONDITION_CHARS)
return `Keep the condition under ${MAX_CONDITION_CHARS} characters.`;
+ return (
+ validateGithubSelector(trigger.github) ??
+ validatePayloadTests(trigger.match)
+ );
+}
+
+const GITHUB_NAME = /^[a-z_]{1,64}$/;
+const GITHUB_REPOSITORY = /^[^/\s]+\/[^/\s]+$/;
+export const MAX_PAYLOAD_TESTS = 16;
+const MAX_PAYLOAD_VALUES = 50;
+const MAX_PAYLOAD_VALUE_CHARS = 500;
+
+function validateGithubSelector(
+ selector: GithubSelectorDraft | undefined
+): string | null {
+ if (!selector) return null;
+ if (selector.events.length > 32 || selector.actions.length > 32)
+ return 'Choose up to 32 GitHub events and 32 actions.';
+ if (
+ ![...selector.events, ...selector.actions].every((name) =>
+ GITHUB_NAME.test(name)
+ )
+ )
+ return 'GitHub event and action names are lowercase words joined by underscores, like workflow_run.';
+ if (selector.repositories.length > 100)
+ return 'Choose up to 100 repositories.';
+ if (!selector.repositories.every((name) => GITHUB_REPOSITORY.test(name)))
+ return 'Name repositories as owner/name.';
+ return null;
+}
+
+/** A test's values: its list for `in` and `notIn`, split on commas. */
+export function payloadTestValues(test: PayloadTestDraft): string[] {
+ return test.value
+ .split(',')
+ .map((value) => value.trim())
+ .filter(Boolean);
+}
+
+function validatePayloadTests(
+ tests: PayloadTestDraft[] | undefined
+): string | null {
+ if (!tests) return null;
+ if (tests.length > MAX_PAYLOAD_TESTS)
+ return `Add up to ${MAX_PAYLOAD_TESTS} payload tests.`;
+ for (const test of tests) {
+ const segments = test.path.split('.');
+ if (segments.length > 16 || segments.some((segment) => !segment.trim()))
+ return 'Write each payload field as keys joined by dots, like workflow_run.conclusion.';
+ if (test.op === 'exists' || test.op === 'missing') continue;
+ if (!test.value.trim()) return `Give ${test.path} a value to test.`;
+ if ([...test.value].length > MAX_PAYLOAD_VALUE_CHARS)
+ return `Keep payload test values under ${MAX_PAYLOAD_VALUE_CHARS} characters.`;
+ if (
+ (test.op === 'in' || test.op === 'notIn') &&
+ payloadTestValues(test).length > MAX_PAYLOAD_VALUES
+ )
+ return `List up to ${MAX_PAYLOAD_VALUES} values per payload test.`;
+ }
return null;
}
export function validateTriggers(
diff --git a/apps/web/src/features/routines/queries/github-link.ts b/apps/web/src/features/routines/queries/github-link.ts
new file mode 100644
index 0000000000..2f3e8e09cf
--- /dev/null
+++ b/apps/web/src/features/routines/queries/github-link.ts
@@ -0,0 +1,43 @@
+import { authorizeGithub } from '@core/auth/authorize-github';
+import { toast } from '@core/component/Toast/Toast';
+import {
+ useGithubLinkStatusQuery,
+ useInitGithubLinkMutation,
+} from '@queries/auth';
+import type { Accessor } from 'solid-js';
+
+export type GithubConnection = {
+ /** Undefined until the link status is known. */
+ linked: boolean | undefined;
+ connecting: boolean;
+ connect: () => Promise<void>;
+};
+
+/**
+ * Whether the user has linked GitHub, which GitHub triggers need, and how to
+ * link it. Status-gated, so a pending status never suspends the trigger menu.
+ * On the web, connecting leaves for GitHub and returns to this page; the
+ * routine draft survives the round trip.
+ */
+export function createGithubConnection(): Accessor<GithubConnection> {
+ const status = useGithubLinkStatusQuery();
+ const init = useInitGithubLinkMutation();
+ const connect = async () => {
+ try {
+ const linked = await authorizeGithub(
+ (callbackUrl) => init.mutateAsync(callbackUrl),
+ 'Failed to connect GitHub'
+ );
+ if (linked) toast.success('GitHub connected');
+ } catch (error) {
+ console.error('connect github failed', error);
+ toast.failure('Failed to connect GitHub');
+ }
+ };
+ return () => ({
+ // A link that needs reauthentication still counts: the row routines read exists.
+ linked: status.isSuccess ? status.data.status !== 'unlinked' : undefined,
+ connecting: init.isPending,
+ connect,
+ });
+}
diff --git a/apps/web/src/features/routines/queries/github-repositories.ts b/apps/web/src/features/routines/queries/github-repositories.ts
new file mode 100644
index 0000000000..a74bfb0bb0
--- /dev/null
+++ b/apps/web/src/features/routines/queries/github-repositories.ts
@@ -0,0 +1,24 @@
+import { useAgentRepositoriesQuery } from '@queries/agent-repositories/repositories';
+import type { Accessor } from 'solid-js';
+import { repositoryLabel } from '../../agents-view/core/repository';
+import type { GithubRepositoryOptions } from '../core/routine-triggers';
+
+/**
+ * The repositories Macro's GitHub app reaches for the user, as `owner/name`:
+ * the same listing a coding session picks from. Status-gated, so a pending
+ * listing never suspends the trigger panel.
+ */
+export function createGithubRepositoryOptions(
+ enabled: Accessor<boolean>
+): Accessor<GithubRepositoryOptions> {
+ const query = useAgentRepositoriesQuery(enabled);
+ return () => ({
+ names: query.isSuccess
+ ? query.data.repositories.map((repository) =>
+ repositoryLabel(repository.url)
+ )
+ : [],
+ loading: query.isLoading,
+ error: query.isError,
+ });
+}
diff --git a/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts b/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts
index bd354f69b9..b5514b5cfd 100644
--- a/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts
+++ b/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import {
+ eventTriggerLabel,
newScheduleTrigger,
routineEvents,
routineTriggerSchema,
@@ -233,3 +234,116 @@ describe('completed routine classification', () => {
expect(hasOnlyScheduledTriggers([])).toBe(false);
});
});
+
+describe('GitHub triggers', () => {
+ const workflowFailed = routineEvents.find(
+ (event) => event.label === 'Workflow failed'
+ )!;
+
+ it('sends a GitHub preset as its selector and typed payload tests', () => {
+ const trigger = {
+ id: 'g',
+ kind: 'event' as const,
+ events: [workflowFailed.value],
+ ...structuredClone(workflowFailed.preset),
+ };
+ trigger.github!.repositories = ['macro-inc/macro'];
+ trigger.match!.push(
+ { path: 'workflow_run.name', op: 'equals', value: 'CI' },
+ { path: 'workflow_run.run_attempt', op: 'equals', value: '1' },
+ { path: 'workflow_run.head_branch', op: 'glob', value: 'release/*' },
+ { path: 'workflow_run.pull_requests', op: 'exists', value: '' }
+ );
+
+ const serialized = serializeTriggers([trigger]);
+
+ expect(serialized).toEqual({
+ type: 'events',
+ filters: [
+ {
+ events: ['github'],
+ github: {
+ events: ['workflow_run'],
+ actions: ['completed'],
+ repositories: ['macro-inc/macro'],
+ includeBots: false,
+ },
+ match: [
+ {
+ path: ['workflow_run', 'conclusion'],
+ in: ['failure', 'timed_out'],
+ },
+ { path: ['workflow_run', 'name'], equals: 'CI' },
+ { path: ['workflow_run', 'run_attempt'], equals: 1 },
+ { path: ['workflow_run', 'head_branch'], glob: 'release/*' },
+ { path: ['workflow_run', 'pull_requests'], exists: true },
+ ],
+ },
+ ],
+ });
+ expect(parseRoutineTriggers(serialized)).toEqual([
+ {
+ ...trigger,
+ id: expect.any(String),
+ ids: undefined,
+ condition: undefined,
+ },
+ ]);
+ });
+
+ it('labels a GitHub trigger by its preset until its events change', () => {
+ const trigger = {
+ id: 'g',
+ kind: 'event' as const,
+ events: [workflowFailed.value],
+ ...structuredClone(workflowFailed.preset),
+ };
+ expect(eventTriggerLabel(trigger)).toBe('Workflow failed');
+ trigger.github!.events = ['check_suite'];
+ expect(eventTriggerLabel(trigger)).toBe('GitHub check_suite');
+ });
+
+ it('rejects names GitHub never sends and incomplete payload tests', () => {
+ const github = (patch: object) => [
+ {
+ id: 'g',
+ kind: 'event' as const,
+ events: ['github' as const],
+ github: {
+ events: [],
+ actions: [],
+ repositories: [],
+ includeBots: false,
+ ...patch,
+ },
+ },
+ ];
+ expect(validateTriggers(github({}))).toBeNull();
+ expect(validateTriggers(github({ events: ['Workflow Run'] }))).toMatch(
+ /lowercase/
+ );
+ expect(validateTriggers(github({ repositories: ['macro'] }))).toMatch(
+ /owner\/name/
+ );
+ expect(
+ validateTriggers([
+ {
+ id: 'w',
+ kind: 'event',
+ events: ['github'],
+ match: [{ path: 'status', op: 'equals', value: ' ' }],
+ },
+ ])
+ ).toMatch(/value/);
+ expect(
+ validateTriggers([
+ {
+ id: 'w',
+ kind: 'event',
+ events: ['github'],
+ match: [{ path: 'alert..severity', op: 'exists', value: '' }],
+ },
+ ])
+ ).toMatch(/dots/);
+ });
+});
diff --git a/apps/web/src/features/routines/queries/routine-trigger-mapping.ts b/apps/web/src/features/routines/queries/routine-trigger-mapping.ts
index e221cc0112..02ea74f647 100644
--- a/apps/web/src/features/routines/queries/routine-trigger-mapping.ts
+++ b/apps/web/src/features/routines/queries/routine-trigger-mapping.ts
@@ -1,18 +1,70 @@
import { parseCron } from '@core/util/cron';
import { TZDate } from '@date-fns/tz';
-import type { ActionTrigger } from '@service-scheduled-action/generated/schemas';
+import type {
+ ActionTrigger,
+ EventFilter,
+ PayloadCondition,
+ PayloadScalar,
+} from '@service-scheduled-action/generated/schemas';
import { match } from 'ts-pattern';
import {
type EventTriggerDraft,
newScheduleTrigger,
+ type PayloadTestDraft,
+ payloadTestValues,
type RoutineTriggerDraft,
} from '../core/routine-triggers';
-function serializeFilter(trigger: EventTriggerDraft) {
+/** Typed text as the JSON scalar it names; anything else stays text. */
+function scalar(text: string): PayloadScalar {
+ const value = text.trim();
+ if (value === 'true') return true;
+ if (value === 'false') return false;
+ if (value === 'null') return null;
+ if (/^-?\d+(\.\d+)?$/.test(value)) return Number(value);
+ return value;
+}
+
+function serializePayloadTest(test: PayloadTestDraft): PayloadCondition {
+ const path = test.path.split('.').map((segment) => segment.trim());
+ return match(test.op)
+ .with('equals', () => ({ path, equals: scalar(test.value) }))
+ .with('in', () => ({ path, in: payloadTestValues(test).map(scalar) }))
+ .with('notIn', () => ({
+ path,
+ notIn: payloadTestValues(test).map(scalar),
+ }))
+ .with('glob', () => ({ path, glob: test.value.trim() }))
+ .with('exists', () => ({ path, exists: true }))
+ .with('missing', () => ({ path, exists: false }))
+ .exhaustive(() => {
+ throw new Error('Choose how to test the payload field.');
+ });
+}
+
+function parsePayloadTest(condition: PayloadCondition): PayloadTestDraft {
+ const path = condition.path.join('.');
+ const list = (values: PayloadScalar[]) => values.map(String).join(', ');
+ if (condition.in != null)
+ return { path, op: 'in', value: list(condition.in) };
+ if (condition.notIn != null)
+ return { path, op: 'notIn', value: list(condition.notIn) };
+ if (condition.glob != null)
+ return { path, op: 'glob', value: condition.glob };
+ if (condition.exists != null)
+ return { path, op: condition.exists ? 'exists' : 'missing', value: '' };
+ return { path, op: 'equals', value: String(condition.equals ?? null) };
+}
+
+function serializeFilter(trigger: EventTriggerDraft): EventFilter {
const condition = trigger.condition?.trim();
return {
events: trigger.events,
...(trigger.ids === undefined ? {} : { ids: trigger.ids }),
+ ...(trigger.github ? { github: trigger.github } : {}),
+ ...(trigger.match?.length
+ ? { match: trigger.match.map(serializePayloadTest) }
+ : {}),
...(condition ? { condition } : {}),
};
}
@@ -79,6 +131,15 @@ export function parseRoutineTriggers(
kind: 'event',
events: filter.events,
ids: filter.ids ?? undefined,
+ github: filter.github
+ ? {
+ events: filter.github.events ?? [],
+ actions: filter.github.actions ?? [],
+ repositories: filter.github.repositories ?? [],
+ includeBots: filter.github.includeBots ?? false,
+ }
+ : undefined,
+ match: filter.match?.map(parsePayloadTest),
condition: filter.condition ?? undefined,
}));
const draft = {
diff --git a/apps/web/src/features/routines/routine-creator.test.tsx b/apps/web/src/features/routines/routine-creator.test.tsx
index 8e98d01767..922df2513d 100644
--- a/apps/web/src/features/routines/routine-creator.test.tsx
+++ b/apps/web/src/features/routines/routine-creator.test.tsx
@@ -26,6 +26,8 @@ const host = vi.hoisted(() => ({
success: vi.fn(),
alert: vi.fn(),
editorMount: vi.fn(),
+ githubLinked: true as boolean | undefined,
+ connectGithub: vi.fn(),
}));
vi.mock('@app/lib/analytics/posthog', () => ({
useFeatureFlag: (flag: { key: string }) => () => ({
@@ -38,6 +40,26 @@ vi.mock('@components/app/split-layout/layout', () => ({
vi.mock('@components/app/split-layout/layoutUtils', () => ({
useSplitPanelOrThrow: () => ({ handle: { close: vi.fn() } }),
}));
+vi.mock('@queries/agent-repositories/repositories', () => ({
+ useAgentRepositoriesQuery: () => ({
+ isSuccess: true,
+ isLoading: false,
+ isError: false,
+ data: {
+ repositories: [
+ { url: 'https://github.com/macro-inc/macro' },
+ { url: 'https://github.com/macro-inc/docs' },
+ ],
+ },
+ }),
+}));
+vi.mock('./queries/github-link', () => ({
+ createGithubConnection: () => () => ({
+ linked: host.githubLinked,
+ connecting: false,
+ connect: host.connectGithub,
+ }),
+}));
vi.mock('./routine-event-scope', () => ({
RoutineEventScope: () => <span>Any document</span>,
RoutineEventScopeLabel: () => <span>Any document</span>,
@@ -140,6 +162,7 @@ vi.mock('@queries/agents/models', () => ({
let styles: HTMLStyleElement;
beforeEach(() => {
vi.clearAllMocks();
+ host.githubLinked = true;
localStorage.clear();
setCatalogState('success');
styles = document.createElement('style');
@@ -565,6 +588,77 @@ describe('routine composer execution selection', () => {
});
});
+ it('saves a GitHub workflow trigger narrowed to one repository and workflow', async () => {
+ host.create.mockImplementation(async (body) => created(body));
+ await mount();
+ inputPrompt();
+ fireEvent.click(screen.getByRole('button', { name: 'Add trigger' }));
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Workflow failed' })
+ );
+ const panel = screen.getByRole('dialog', { name: 'Add trigger' });
+ fireEvent.click(
+ within(panel).getByRole('checkbox', { name: 'macro-inc/macro' })
+ );
+ fireEvent.click(
+ within(panel).getByRole('button', { name: 'Add a field test' })
+ );
+ const fields = within(panel).getAllByRole('textbox', {
+ name: 'Payload field',
+ });
+ fireEvent.input(fields[1], { target: { value: 'workflow_run.name' } });
+ const values = within(panel).getAllByRole('textbox', { name: 'Value' });
+ fireEvent.input(values[1], { target: { value: 'CI' } });
+ fireEvent.click(within(panel).getByRole('button', { name: 'Add trigger' }));
+ expect(
+ screen.getByRole('button', { name: 'Edit Workflow failed trigger' })
+ .textContent
+ ).toContain('Workflow failed · macro-inc/macro');
+ fireEvent.click(screen.getByRole('button', { name: /Create routine/i }));
+ await waitFor(() => expect(host.create).toHaveBeenCalledTimes(1));
+ expect(host.create.mock.calls[0][0]).toMatchObject({
+ trigger: {
+ type: 'events',
+ filters: [
+ {
+ events: ['github'],
+ github: {
+ events: ['workflow_run'],
+ actions: ['completed'],
+ repositories: ['macro-inc/macro'],
+ includeBots: false,
+ },
+ match: [
+ {
+ path: ['workflow_run', 'conclusion'],
+ in: ['failure', 'timed_out'],
+ },
+ { path: ['workflow_run', 'name'], equals: 'CI' },
+ ],
+ },
+ ],
+ },
+ });
+ });
+
+ it('asks to connect GitHub before offering GitHub triggers', async () => {
+ host.githubLinked = false;
+ await mount();
+ inputPrompt();
+ fireEvent.click(screen.getByRole('button', { name: 'Add trigger' }));
+ const panel = await screen.findByRole('dialog', { name: 'Add trigger' });
+ expect(
+ within(panel).queryByRole('button', { name: 'Workflow failed' })
+ ).toBeNull();
+ expect(
+ within(panel).queryByRole('button', { name: 'Webhook received' })
+ ).toBeNull();
+ fireEvent.click(
+ within(panel).getByRole('button', { name: 'Connect GitHub' })
+ );
+ expect(host.connectGithub).toHaveBeenCalledOnce();
+ });
+
it('keeps trigger edits local until confirmed and leaves an add chip', async () => {
await mount();
const editor = inputPrompt();
diff --git a/apps/web/src/features/routines/routine-triggers.tsx b/apps/web/src/features/routines/routine-triggers.tsx
index 3ab584c7f3..a7657aed51 100644
--- a/apps/web/src/features/routines/routine-triggers.tsx
+++ b/apps/web/src/features/routines/routine-triggers.tsx
@@ -2,25 +2,74 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { enableRoutineConditions } from '@core/constant/featureFlags';
import { Show, Suspense } from 'solid-js';
import { RoutineEventCondition } from './components/routine-event-condition';
+import { RoutineGithubConnect } from './components/routine-github-connect';
+import { RoutineGithubSettings } from './components/routine-github-settings';
+import { RoutinePayloadTests } from './components/routine-payload-tests';
import { RoutineTriggers as TriggerList } from './components/routine-triggers';
import {
+ type EventTriggerDraft,
eventScopeKind,
isGlobalEvent,
type RoutineTriggerDraft,
} from './core/routine-triggers';
+import { createGithubConnection } from './queries/github-link';
+import { createGithubRepositoryOptions } from './queries/github-repositories';
import {
RoutineEventScope,
RoutineEventScopeLabel,
} from './routine-event-scope';
+/** The Macro entity kind a trigger narrows to; GitHub has none. */
+function entityKind(trigger: EventTriggerDraft) {
+ const kind = eventScopeKind(trigger);
+ return kind === 'GITHUB' ? undefined : kind;
+}
+
+function RepositoryScopeLabel(props: { trigger: EventTriggerDraft }) {
+ const label = () => {
+ const repositories = props.trigger.github?.repositories ?? [];
+ if (!repositories.length) return 'All repositories';
+ if (repositories.length > 1) return `${repositories.length} repositories`;
+ return repositories[0];
+ };
+ return <span title={label()}>{label()}</span>;
+}
+
export function RoutineTriggers(props: {
triggers: RoutineTriggerDraft[];
onChange: (triggers: RoutineTriggerDraft[]) => void;
}) {
const conditions = useFeatureFlag(enableRoutineConditions);
+ const github = createGithubConnection();
+ const repositories = createGithubRepositoryOptions(
+ () =>
+ github().linked === true &&
+ props.triggers.some(
+ (trigger) =>
+ trigger.kind === 'event' && trigger.events.includes('github')
+ )
+ );
+ const connect = (message: string) => (
+ <RoutineGithubConnect
+ message={message}
+ connecting={github().connecting}
+ onConnect={() => github().connect()}
+ />
+ );
return (
<TriggerList
- {...props}
+ triggers={props.triggers}
+ onChange={props.onChange}
+ renderEventGroup={(group, options) => (
+ <Show
+ when={group !== 'GitHub' || github().linked !== false}
+ fallback={connect(
+ 'Connect your GitHub account to run this routine on GitHub events.'
+ )}
+ >
+ {options()}
+ </Show>
+ )}
renderEventCondition={
conditions().enabled
? (trigger, onChange) => (
@@ -28,24 +77,59 @@ export function RoutineTriggers(props: {
)
: undefined
}
- renderEventLabel={(trigger) => (
- <Suspense fallback={<span>Selected items</span>}>
- <RoutineEventScopeLabel
- kind={eventScopeKind(trigger())}
- ids={trigger().ids}
- events={trigger().events}
- />
- </Suspense>
+ renderEventSettings={(trigger, onChange) => (
+ <Show when={trigger().github}>
+ {(selector) => (
+ <Show
+ when={github().linked !== false}
+ fallback={connect(
+ 'GitHub isn’t connected, so this trigger can’t run. Connect it to turn the routine on.'
+ )}
+ >
+ <RoutineGithubSettings
+ selector={selector()}
+ repositories={repositories()}
+ onChange={(github) => onChange({ github })}
+ />
+ <RoutinePayloadTests
+ tests={trigger().match ?? []}
+ onChange={(match) => onChange({ match })}
+ />
+ </Show>
+ )}
+ </Show>
)}
- renderEventScope={(trigger, onChange) => (
+ renderEventLabel={(trigger) => (
<Show
- when={!isGlobalEvent(trigger().events) || trigger().ids !== undefined}
+ when={entityKind(trigger())}
+ fallback={<RepositoryScopeLabel trigger={trigger()} />}
>
- <RoutineEventScope
- kind={eventScopeKind(trigger())}
- ids={trigger().ids}
- onChange={onChange}
- />
+ {(kind) => (
+ <Suspense fallback={<span>Selected items</span>}>
+ <RoutineEventScopeLabel
+ kind={kind()}
+ ids={trigger().ids}
+ events={trigger().events}
+ />
+ </Suspense>
+ )}
+ </Show>
+ )}
+ renderEventScope={(trigger, onChange) => (
+ <Show when={entityKind(trigger())}>
+ {(kind) => (
+ <Show
+ when={
+ !isGlobalEvent(trigger().events) || trigger().ids !== undefined
+ }
+ >
+ <RoutineEventScope
+ kind={kind()}
+ ids={trigger().ids}
+ onChange={onChange}
+ />
+ </Show>
+ )}
</Show>
)}
/>
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilter.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilter.ts
index 90d01fe701..5c635cd4a9 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilter.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilter.ts
@@ -6,12 +6,19 @@
* OpenAPI spec version: 0.1.0
*/
import type { EventFilterCondition } from './eventFilterCondition';
+import type { EventFilterGithub } from './eventFilterGithub';
import type { EventFilterIds } from './eventFilterIds';
+import type { EventFilterMatch } from './eventFilterMatch';
import type { EventName } from './eventName';
/**
* An event name AND an entity ID must match within the same filter. A
condition further requires the event's content to answer it with yes.
+
+`github` comes from outside Macro and carries its payload: it stands
+alone in its filter, takes no ids, and may require
+exact payload values with `match`. A `github` filter narrows deliveries
+with its `github` selector.
*/
export interface EventFilter {
/**
@@ -21,5 +28,8 @@ invoice?". The routine runs only when the answer is yes.
*/
condition?: EventFilterCondition;
events: EventName[];
+ github?: EventFilterGithub;
ids?: EventFilterIds;
+ /** Exact tests on the payload, all of which must pass. */
+ match?: EventFilterMatch;
}
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilterGithub.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilterGithub.ts
new file mode 100644
index 0000000000..cd4ef97fc4
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilterGithub.ts
@@ -0,0 +1,10 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GithubSelector } from './githubSelector';
+
+export type EventFilterGithub = null | GithubSelector;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilterMatch.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilterMatch.ts
new file mode 100644
index 0000000000..a2cdb57da4
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilterMatch.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PayloadCondition } from './payloadCondition';
+
+/**
+ * Exact tests on the payload, all of which must pass.
+ */
+export type EventFilterMatch = PayloadCondition[] | null;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventName.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventName.ts
index 9e61c99ca2..2c8a39fd08 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventName.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventName.ts
@@ -29,4 +29,5 @@ export const EventName = {
channelmessage_attachment_created: 'channel.message_attachment_created',
callstarted: 'call.started',
callended: 'call.ended',
+ github: 'github',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/githubSelector.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/githubSelector.ts
new file mode 100644
index 0000000000..2463bb2024
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/githubSelector.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Which GitHub deliveries match.
+ */
+export interface GithubSelector {
+ /** Payload actions, such as `completed` or `opened`; any when empty. */
+ actions?: string[];
+ /** GitHub event names, such as `workflow_run` or `pull_request`; any when empty. */
+ events?: string[];
+ /** Also run for deliveries caused by bots and apps, including Macro's own. */
+ includeBots?: boolean;
+ /** Repositories as `owner/name`, matched without regard to case; every
+repository the owner's installations cover when empty. A renamed
+repository stops matching until it is chosen again. */
+ repositories?: string[];
+}
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts
index 95e8f53ebb..70ed6c2585 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts
@@ -39,7 +39,9 @@ export * from './createScheduledAction';
export * from './emptyResponse';
export * from './eventFilter';
export * from './eventFilterCondition';
+export * from './eventFilterGithub';
export * from './eventFilterIds';
+export * from './eventFilterMatch';
export * from './eventFilters';
export * from './eventName';
export * from './executionResource';
@@ -48,12 +50,20 @@ export * from './executionResult';
export * from './executionResultCondition';
export * from './executionResultError';
export * from './executionResultResource';
+export * from './githubSelector';
export * from './inProgressExecution';
export * from './inProgressExecutionChatId';
export * from './inProgressExecutionResource';
export * from './legacyActionConfiguration';
export * from './legacyActionConfigurationTask';
export * from './listScheduledActionsParams';
+export * from './payloadCondition';
+export * from './payloadConditionEquals';
+export * from './payloadConditionExists';
+export * from './payloadConditionGlob';
+export * from './payloadConditionIn';
+export * from './payloadConditionNotIn';
+export * from './payloadScalar';
export * from './routineModelId';
export * from './routineTemplate';
export * from './routineTemplateTask';
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadCondition.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadCondition.ts
new file mode 100644
index 0000000000..e534ef143e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadCondition.ts
@@ -0,0 +1,31 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PayloadConditionEquals } from './payloadConditionEquals';
+import type { PayloadConditionExists } from './payloadConditionExists';
+import type { PayloadConditionGlob } from './payloadConditionGlob';
+import type { PayloadConditionIn } from './payloadConditionIn';
+import type { PayloadConditionNotIn } from './payloadConditionNotIn';
+
+/**
+ * `path` walks objects by key; `*` steps into every element of an array and
+a number into one. Give exactly one test. `notIn` also passes when the
+path finds nothing.
+ */
+export interface PayloadCondition {
+ equals?: PayloadConditionEquals;
+ /** Whether the path finds a non-null value. */
+ exists?: PayloadConditionExists;
+ /** Some text found matches this glob; `*` matches any run of characters. */
+ glob?: PayloadConditionGlob;
+ /** Some value found is one of these. */
+ in?: PayloadConditionIn;
+ /** No value found is one of these. */
+ notIn?: PayloadConditionNotIn;
+ /** Keys from the payload's root, e.g. `["workflow_run", "conclusion"]`. */
+ path: string[];
+}
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadConditionEquals.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadConditionEquals.ts
new file mode 100644
index 0000000000..c4720c8180
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadConditionEquals.ts
@@ -0,0 +1,10 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PayloadScalar } from './payloadScalar';
+
+export type PayloadConditionEquals = null | PayloadScalar;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadConditionExists.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadConditionExists.ts
new file mode 100644
index 0000000000..a92d1f7ad1
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadConditionExists.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Whether the path finds a non-null value.
+ */
+export type PayloadConditionExists = boolean | null;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadConditionGlob.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadConditionGlob.ts
new file mode 100644
index 0000000000..a5f050e258
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadConditionGlob.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Some text found matches this glob; `*` matches any run of characters.
+ */
+export type PayloadConditionGlob = string | null;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadConditionIn.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadConditionIn.ts
new file mode 100644
index 0000000000..eb4137a558
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadConditionIn.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PayloadScalar } from './payloadScalar';
+
+/**
+ * Some value found is one of these.
+ */
+export type PayloadConditionIn = PayloadScalar[] | null;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadConditionNotIn.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadConditionNotIn.ts
new file mode 100644
index 0000000000..21dd63700a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadConditionNotIn.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PayloadScalar } from './payloadScalar';
+
+/**
+ * No value found is one of these.
+ */
+export type PayloadConditionNotIn = PayloadScalar[] | null;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadScalar.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadScalar.ts
new file mode 100644
index 0000000000..aa717b8f31
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/payloadScalar.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * scheduled_action
+ * API for managing scheduled actions
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * A JSON text, number, boolean or null that payload values are compared with.
+ */
+export type PayloadScalar = null | boolean | number | string;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
index 0838f601a3..b70de562b6 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
@@ -1168,7 +1168,7 @@
},
"EventFilter": {
"type": "object",
- "description": "An event name AND an entity ID must match within the same filter. A\ncondition further requires the event's content to answer it with yes.",
+ "description": "An event name AND an entity ID must match within the same filter. A\ncondition further requires the event's content to answer it with yes.\n\n`github` comes from outside Macro and carries its payload: it stands\nalone in its filter, takes no ids, and may require\nexact payload values with `match`. A `github` filter narrows deliveries\nwith its `github` selector.",
"required": ["events"],
"properties": {
"condition": {
@@ -1182,11 +1182,29 @@
"$ref": "#/components/schemas/EventName"
}
},
+ "github": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/GithubSelector",
+ "description": "Which GitHub deliveries match; required for, and only for, `github`."
+ }
+ ]
+ },
"ids": {
"type": ["array", "null"],
"items": {
"type": "string"
}
+ },
+ "match": {
+ "type": ["array", "null"],
+ "items": {
+ "$ref": "#/components/schemas/PayloadCondition"
+ },
+ "description": "Exact tests on the payload, all of which must pass."
}
}
},
@@ -1215,7 +1233,8 @@
"channel.message_patched",
"channel.message_attachment_created",
"call.started",
- "call.ended"
+ "call.ended",
+ "github"
]
},
"ExecutionResource": {
@@ -1272,6 +1291,38 @@
}
}
},
+ "GithubSelector": {
+ "type": "object",
+ "description": "Which GitHub deliveries match.",
+ "properties": {
+ "actions": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Payload actions, such as `completed` or `opened`; any when empty."
+ },
+ "events": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "GitHub event names, such as `workflow_run` or `pull_request`; any when empty."
+ },
+ "includeBots": {
+ "type": "boolean",
+ "description": "Also run for deliveries caused by bots and apps, including Macro's own."
+ },
+ "repositories": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Repositories as `owner/name`, matched without regard to case; every\nrepository the owner's installations cover when empty. A renamed\nrepository stops matching until it is chosen again."
+ }
+ },
+ "additionalProperties": false
+ },
"InProgressExecution": {
"type": "object",
"required": ["action_id"],
@@ -1322,6 +1373,73 @@
},
"additionalProperties": false
},
+ "PayloadCondition": {
+ "type": "object",
+ "description": "`path` walks objects by key; `*` steps into every element of an array and\na number into one. Give exactly one test. `notIn` also passes when the\npath finds nothing.",
+ "required": ["path"],
+ "properties": {
+ "equals": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/PayloadScalar",
+ "description": "Some value found equals this."
+ }
+ ]
+ },
+ "exists": {
+ "type": ["boolean", "null"],
+ "description": "Whether the path finds a non-null value."
+ },
+ "glob": {
+ "type": ["string", "null"],
+ "description": "Some text found matches this glob; `*` matches any run of characters."
+ },
+ "in": {
+ "type": ["array", "null"],
+ "items": {
+ "$ref": "#/components/schemas/PayloadScalar"
+ },
+ "description": "Some value found is one of these."
+ },
+ "notIn": {
+ "type": ["array", "null"],
+ "items": {
+ "$ref": "#/components/schemas/PayloadScalar"
+ },
+ "description": "No value found is one of these."
+ },
+ "path": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Keys from the payload's root, e.g. `[\"workflow_run\", \"conclusion\"]`."
+ }
+ },
+ "additionalProperties": false
+ },
+ "PayloadScalar": {
+ "oneOf": [
+ {
+ "type": "null",
+ "default": null
+ },
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "number",
+ "format": "double"
+ },
+ {
+ "type": "string"
+ }
+ ],
+ "description": "A JSON text, number, boolean or null that payload values are compared with."
+ },
"RoutineModelId": {
"type": "string",
"description": "A nonblank model identifier. Runtime catalogs, not the scheduler, own availability."
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index 9eabe022cf..0ecb4d4ef2 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -439,9 +439,12 @@
"ActionTrigger": "# Type Alias: ActionTrigger\n\n> **ActionTrigger** = \\{ `schedule`: `Schedule`; `timezone`: `string`; `type`: `\"cron\"`; \\} \\| \\{ `filters`: `EventFilters`; `type`: `\"events\"`; \\} \\| \\{ `triggers`: `RoutineTriggers`; `type`: `\"multiple\"`; \\}\n\nA routine may run on one trigger or any of several schedules and Macro events.",
"scheduled-action.AgentMcpServer": "# Type Alias: AgentMcpServer\n\n> **AgentMcpServer** = \\{ `app_slug`: `string`; `server_name`: `string`; \\}\n\nOne Pipedream app an agent lists under [`AgentMcpServers::Selected`].\n\nOnly the catalog identity is stored. Whether a given person has connected\nthe app is theirs, resolved at call time by the egress proxy, never here.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-app_slug\"></a> `app_slug` | `string` | Pipedream app slug, e.g. `linear`. |\n| <a id=\"property-server_name\"></a> `server_name` | `string` | Display name, e.g. `Linear`. |",
"AgentTaskAgent": "# Type Alias: AgentTaskAgent\n\n> **AgentTaskAgent** = \\{ `bot_id`: `string`; \\}\n\nA persona selection, independent of its runtime and current default model.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-bot_id\"></a> `bot_id` | `string` |",
- "EventFilter": "# Type Alias: EventFilter\n\n> **EventFilter** = \\{ `condition?`: `string` \\| `null`; `events`: `EventName`[]; `ids?`: `string`[] \\| `null`; \\}\n\nAn event name AND an entity ID must match within the same filter. A\ncondition further requires the event's content to answer it with yes.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-condition\"></a> `condition?` | `string` \\| `null` | Yes/no question about the triggering content, e.g. \"Is this email an invoice?\". The routine runs only when the answer is yes. |\n| <a id=\"property-events\"></a> `events` | `EventName`[] | - |\n| <a id=\"property-ids\"></a> `ids?` | `string`[] \\| `null` | - |",
+ "EventFilter": "# Type Alias: EventFilter\n\n> **EventFilter** = \\{ `condition?`: `string` \\| `null`; `events`: `EventName`[]; `github?`: `null` \\| `GithubSelector`; `ids?`: `string`[] \\| `null`; `match?`: `PayloadCondition`[] \\| `null`; \\}\n\nAn event name AND an entity ID must match within the same filter. A\ncondition further requires the event's content to answer it with yes.\n\n`github` comes from outside Macro and carries its payload: it stands\nalone in its filter, takes no ids, and may require\nexact payload values with `match`. A `github` filter narrows deliveries\nwith its `github` selector.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-condition\"></a> `condition?` | `string` \\| `null` | Yes/no question about the triggering content, e.g. \"Is this email an invoice?\". The routine runs only when the answer is yes. |\n| <a id=\"property-events\"></a> `events` | `EventName`[] | - |\n| <a id=\"property-github\"></a> `github?` | `null` \\| `GithubSelector` | - |\n| <a id=\"property-ids\"></a> `ids?` | `string`[] \\| `null` | - |\n| <a id=\"property-match\"></a> `match?` | `PayloadCondition`[] \\| `null` | Exact tests on the payload, all of which must pass. |",
"EventFilters": "# Type Alias: EventFilters\n\n> **EventFilters** = `EventFilter`[]\n\nBounded nonempty OR of filters, canonicalized to remove duplicates.",
- "EventName": "# Type Alias: EventName\n\n> **EventName** = `\"document.created\"` \\| `\"document.updated\"` \\| `\"document.deleted\"` \\| `\"task.created\"` \\| `\"task.status_changed\"` \\| `\"task.priority_changed\"` \\| `\"task.property_changed\"` \\| `\"email.message_received\"` \\| `\"channel.created\"` \\| `\"channel.message_posted\"` \\| `\"channel.mentioned\"` \\| `\"channel.message_patched\"` \\| `\"channel.message_attachment_created\"` \\| `\"call.started\"` \\| `\"call.ended\"`\n\nClosed allowlist: unknown names, deletions and ambiguous attribution are not\nselectors. Adding a broker variant does not automatically enable routines.",
+ "EventName": "# Type Alias: EventName\n\n> **EventName** = `\"document.created\"` \\| `\"document.updated\"` \\| `\"document.deleted\"` \\| `\"task.created\"` \\| `\"task.status_changed\"` \\| `\"task.priority_changed\"` \\| `\"task.property_changed\"` \\| `\"email.message_received\"` \\| `\"channel.created\"` \\| `\"channel.message_posted\"` \\| `\"channel.mentioned\"` \\| `\"channel.message_patched\"` \\| `\"channel.message_attachment_created\"` \\| `\"call.started\"` \\| `\"call.ended\"` \\| `\"github\"`\n\nClosed allowlist: unknown names, deletions and ambiguous attribution are not\nselectors. Adding a broker variant does not automatically enable routines.",
+ "GithubSelector": "# Type Alias: GithubSelector\n\n> **GithubSelector** = \\{ `actions?`: `string`[]; `events?`: `string`[]; `includeBots?`: `boolean`; `repositories?`: `string`[]; \\}\n\nWhich GitHub deliveries match.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-actions\"></a> `actions?` | `string`[] | Payload actions, such as `completed` or `opened`; any when empty. |\n| <a id=\"property-events\"></a> `events?` | `string`[] | GitHub event names, such as `workflow_run` or `pull_request`; any when empty. |\n| <a id=\"property-includebots\"></a> `includeBots?` | `boolean` | Also run for deliveries caused by bots and apps, including Macro's own. |\n| <a id=\"property-repositories\"></a> `repositories?` | `string`[] | Repositories as `owner/name`, matched without regard to case; every repository the owner's installations cover when empty. A renamed repository stops matching until it is chosen again. |",
+ "PayloadCondition": "# Type Alias: PayloadCondition\n\n> **PayloadCondition** = \\{ `equals?`: `null` \\| `PayloadScalar`; `exists?`: `boolean` \\| `null`; `glob?`: `string` \\| `null`; `in?`: `PayloadScalar`[] \\| `null`; `notIn?`: `PayloadScalar`[] \\| `null`; `path`: `string`[]; \\}\n\n`path` walks objects by key; `*` steps into every element of an array and\na number into one. Give exactly one test. `notIn` also passes when the\npath finds nothing.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-equals\"></a> `equals?` | `null` \\| `PayloadScalar` | - |\n| <a id=\"property-exists\"></a> `exists?` | `boolean` \\| `null` | Whether the path finds a non-null value. |\n| <a id=\"property-glob\"></a> `glob?` | `string` \\| `null` | Some text found matches this glob; `*` matches any run of characters. |\n| <a id=\"property-in\"></a> `in?` | `PayloadScalar`[] \\| `null` | Some value found is one of these. |\n| <a id=\"property-notin\"></a> `notIn?` | `PayloadScalar`[] \\| `null` | No value found is one of these. |\n| <a id=\"property-path\"></a> `path` | `string`[] | Keys from the payload's root, e.g. `[\"workflow_run\", \"conclusion\"]`. |",
+ "PayloadScalar": "# Type Alias: PayloadScalar\n\n> **PayloadScalar** = `null` \\| `boolean` \\| `number` \\| `string`\n\nA JSON text, number, boolean or null that payload values are compared with.",
"scheduled-action.RoutineTemplate": "# Type Alias: RoutineTemplate\n\n> **RoutineTemplate** = \\{ `active_count`: `number`; `author`: `string`; `created_at`: `string`; `description`: `string`; `id`: `string`; `name`: `string`; `task`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `trigger`: `ActionTrigger`; `updated_at`: `string`; `variables`: `TemplateVariable`[]; \\}\n\nA shared routine's snapshot, readable by signed-in users with sharing enabled.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-active_count\"></a> `active_count` | `number` | Routines activated from this template, including stopped ones. |\n| <a id=\"property-author\"></a> `author` | `string` | Who shared it: the source routine's owner. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-description\"></a> `description` | `string` | - |\n| <a id=\"property-id\"></a> `id` | `string` | The routine it was shared from. |\n| <a id=\"property-name\"></a> `name` | `string` | - |\n| <a id=\"property-task\"></a> `task` | \\{\\[`key`: `string`\\]: `unknown`; \\} | - |\n| <a id=\"property-trigger\"></a> `trigger` | `ActionTrigger` | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n| <a id=\"property-variables\"></a> `variables` | `TemplateVariable`[] | - |",
"RoutineTrigger": "# Type Alias: RoutineTrigger\n\n> **RoutineTrigger** = \\{ `schedule`: `Schedule`; `timezone`: `string`; `type`: `\"cron\"`; \\} \\| \\{ `filters`: `EventFilters`; `type`: `\"events\"`; \\}\n\nAn individual trigger in a routine's trigger list.",
"RoutineTriggers": "# Type Alias: RoutineTriggers\n\n> **RoutineTriggers** = `RoutineTrigger`[]\n\nBounded schedules and one combined set of event filters.",
diff --git a/crates/github/AGENTS.md b/crates/github/AGENTS.md
index 262df68f63..d61e2deac9 100644
--- a/crates/github/AGENTS.md
+++ b/crates/github/AGENTS.md
@@ -14,6 +14,9 @@ link flow, following the hexagonal architecture pattern.
- `src/inbound/github_sync_router.rs`: GitHub App install redirect, OAuth
callback, and the webhook handler.
- `src/inbound/pull_request_index_router.rs`: the HTTP surface for indexed PRs.
+- `src/broker.rs` + `src/domain/models/webhook_delivery.rs`: every verified
+ delivery, whatever its event, published to `macro.github_webhooks` for
+ subscribers such as routines.
- `src/outbound/github_sync_client.rs`, `src/outbound/github_auth_client.rs`:
GitHub's own REST/App API clients.
- `src/outbound/pg_github_repo.rs`, `src/outbound/pg_github_sync_repo.rs`: the
@@ -23,6 +26,10 @@ link flow, following the hexagonal architecture pattern.
- Owns: account linking (`link` feature), the App installation/webhook sync
(`sync` feature), and the Axum router/webhook verification for both.
+ The `installation_claims` feature exposes whether a user has linked GitHub
+ and who may see an installation's deliveries, without the rest of the sync
+ stack. A personal installation counts only while the account that installed
+ it is the one linked.
- Not here: the pull request model, merge rules, and PR listing/service →
`crates/github_pull_requests`, which this crate re-exports and calls into.
@@ -32,7 +39,7 @@ link flow, following the hexagonal architecture pattern.
`documents`, `fusionauth`, `connection_gateway_client`, `macro_service_urls`,
`notification`/`model_notifications`.
- Used by: `agent_harness_service`, `agent_harness`, `agent_egress`,
- `document_storage_service`, `authentication_service`.
+ `document_storage_service`, `authentication_service`, `scheduled_action`.
## Recipes
diff --git a/crates/github/Cargo.toml b/crates/github/Cargo.toml
index 207ee59e72..750ddd29fa 100644
--- a/crates/github/Cargo.toml
+++ b/crates/github/Cargo.toml
@@ -16,6 +16,8 @@ axum = [
]
default = ["axum", "inbound", "link", "outbound", "ports", "sync"]
inbound = ["axum", "ports"]
+# Who may see an installation's deliveries, without the rest of the sync stack.
+installation_claims = ["dep:sqlx", "ports"]
link = ["dep:entity_access", "github_pull_requests/ports", "ports"]
outbound = [
"dep:connection_gateway_client",
@@ -63,6 +65,8 @@ hmac = { workspace = true }
jsonwebtoken = { workspace = true }
lru = { workspace = true }
macro_env = { path = "../macro_env" }
+macro_event_broker = { path = "../macro_event_broker", default-features = false }
+macro_event_topics = { path = "../macro_event_topics" }
macro_env_var = { path = "../macro_env_var" }
macro_authorization = { path = "../macro_authorization", default-features = false, features = [
"axum",
diff --git a/crates/github/src/broker.rs b/crates/github/src/broker.rs
new file mode 100644
index 0000000000..95b01f98fb
--- /dev/null
+++ b/crates/github/src/broker.rs
@@ -0,0 +1,81 @@
+//! Broker envelope and publication for verified GitHub App deliveries.
+
+use crate::domain::models::GithubWebhookReceived;
+use macro_event_broker::{Event, MacroEvent, TopicEvent};
+use macro_event_topics::MacroGithubWebhooksTopic;
+use serde::{Deserialize, Serialize};
+
+/// Facts published to `macro.github_webhooks`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "event_type", content = "metadata")]
+pub enum GithubWebhookTopicEvent {
+ /// The GitHub App received and verified a delivery.
+ #[serde(rename = "github_webhook.received")]
+ Received(GithubWebhookReceived),
+}
+
+impl TopicEvent for GithubWebhookTopicEvent {
+ type Topic = MacroGithubWebhooksTopic;
+ const SCHEMA_VERSION: u8 = 1;
+}
+
+/// A delivery keyed by installation, so one installation's deliveries keep
+/// their order.
+#[derive(Debug, Clone)]
+pub struct GithubWebhookMacroEvent {
+ key: String,
+ event: Event<GithubWebhookTopicEvent>,
+}
+
+impl GithubWebhookMacroEvent {
+ /// Wrap a verified delivery.
+ pub fn received(delivery: GithubWebhookReceived) -> Self {
+ Self {
+ key: delivery.installation_id.to_string(),
+ event: Event::new(GithubWebhookTopicEvent::Received(delivery)),
+ }
+ }
+}
+
+impl MacroEvent for GithubWebhookMacroEvent {
+ type EventPayload = GithubWebhookTopicEvent;
+ fn key(&self) -> &str {
+ &self.key
+ }
+ fn event(&self) -> &Event<Self::EventPayload> {
+ &self.event
+ }
+ fn from_event(key: String, event: Event<Self::EventPayload>) -> Self {
+ Self { key, event }
+ }
+}
+
+/// Publishes deliveries through the shared event broker.
+#[cfg(feature = "sync")]
+pub struct BrokerGithubWebhookPublisher<B>(pub B);
+
+#[cfg(feature = "sync")]
+impl<B: macro_event_broker::MacroEventBroker> crate::domain::ports::GithubWebhookPublisher
+ for BrokerGithubWebhookPublisher<B>
+{
+ fn publish_received(
+ &self,
+ delivery: GithubWebhookReceived,
+ ) -> std::pin::Pin<
+ Box<
+ dyn std::future::Future<Output = Result<(), crate::domain::models::GithubError>>
+ + Send
+ + '_,
+ >,
+ > {
+ Box::pin(async move {
+ self.0
+ .send_event(&GithubWebhookMacroEvent::received(delivery))
+ .map_err(anyhow::Error::from)?
+ .await
+ .map_err(anyhow::Error::from)?
+ .map_err(anyhow::Error::from)?;
+ Ok(())
+ })
+ }
+}
diff --git a/crates/github/src/domain/models.rs b/crates/github/src/domain/models.rs
index b71306c1d2..0b4512b60f 100644
--- a/crates/github/src/domain/models.rs
+++ b/crates/github/src/domain/models.rs
@@ -9,6 +9,7 @@ mod installation_state;
mod link;
mod repository;
mod sync;
+mod webhook_delivery;
#[cfg(feature = "sync")]
pub use app_jwt::AppJwt;
@@ -44,6 +45,9 @@ pub use sync::{
TeamTaskReference, ValidatedGithubWebhookEvent, extract_github_mentions,
pull_request_task_reference, strip_markdown_code,
};
+pub use webhook_delivery::{
+ GithubWebhookReceived, GithubWebhookRepository, GithubWebhookSender, MAX_WEBHOOK_PAYLOAD_BYTES,
+};
/// Errors that can occur during github operations.
#[derive(Debug, thiserror::Error)]
pub enum GithubError {
diff --git a/crates/github/src/domain/models/sync.rs b/crates/github/src/domain/models/sync.rs
index 9103ee8ee9..07e88d3ee2 100644
--- a/crates/github/src/domain/models/sync.rs
+++ b/crates/github/src/domain/models/sync.rs
@@ -145,6 +145,8 @@ pub struct ValidatedGithubWebhookEvent {
pub event_type: String,
/// The parsed JSON payload
pub payload: serde_json::Value,
+ /// The `X-GitHub-Delivery` header, when the request carried one.
+ pub delivery_id: Option<String>,
}
impl ValidatedGithubWebhookEvent {
@@ -153,9 +155,16 @@ impl ValidatedGithubWebhookEvent {
Self {
event_type,
payload,
+ delivery_id: None,
}
}
+ /// Record the delivery id GitHub sent with the event.
+ pub fn with_delivery_id(mut self, delivery_id: Option<String>) -> Self {
+ self.delivery_id = delivery_id;
+ self
+ }
+
/// Parse the raw event type string into a [`GithubWebhookEventType`].
pub fn parsed_event_type(&self) -> GithubWebhookEventType {
GithubWebhookEventType::from_event_header(&self.event_type)
diff --git a/crates/github/src/domain/models/test.rs b/crates/github/src/domain/models/test.rs
index d95d5b9aef..2cf325657c 100644
--- a/crates/github/src/domain/models/test.rs
+++ b/crates/github/src/domain/models/test.rs
@@ -630,3 +630,68 @@ fn pull_request_task_reference_falls_back_to_the_macro_id() {
assert_eq!(reference, format!("MACRO-{SHORT_UUID_A}"));
assert_eq!(MacroTaskId::extract_from_text(&reference), [task]);
}
+
+#[test]
+fn a_delivery_keeps_its_meaning_and_drops_api_links() {
+ let body = serde_json::json!({
+ "action": "completed",
+ "installation": { "id": 77, "node_id": "x" },
+ "repository": {
+ "id": 42,
+ "full_name": "macro-inc/macro",
+ "url": "https://api.github.com/repos/macro-inc/macro",
+ "html_url": "https://github.com/macro-inc/macro",
+ "hooks_url": "https://api.github.com/repos/macro-inc/macro/hooks",
+ },
+ "sender": { "login": "dependabot[bot]", "type": "Bot", "avatar_url": "https://x" },
+ "workflow_run": { "name": "CI", "conclusion": "failure", "jobs_url": "https://x" },
+ });
+
+ let delivery = GithubWebhookReceived::from_delivery(
+ Some("d-1".to_owned()),
+ "workflow_run".to_owned(),
+ &body,
+ )
+ .unwrap();
+
+ assert_eq!(delivery.installation_id, 77);
+ assert_eq!(delivery.action.as_deref(), Some("completed"));
+ assert_eq!(delivery.repository.as_ref().unwrap().id, 42);
+ assert!(delivery.sender.as_ref().unwrap().bot);
+ assert_eq!(
+ delivery.payload,
+ Some(serde_json::json!({
+ "action": "completed",
+ "repository": {
+ "id": 42,
+ "full_name": "macro-inc/macro",
+ "html_url": "https://github.com/macro-inc/macro",
+ },
+ "sender": { "login": "dependabot[bot]", "type": "Bot" },
+ "workflow_run": { "name": "CI", "conclusion": "failure" },
+ }))
+ );
+}
+
+#[test]
+fn a_delivery_without_an_installation_is_nobodys() {
+ let body =
+ serde_json::json!({ "action": "revoked", "sender": { "login": "a", "type": "User" } });
+
+ assert!(
+ GithubWebhookReceived::from_delivery(None, "github_app_authorization".to_owned(), &body)
+ .is_none()
+ );
+}
+
+#[test]
+fn an_oversized_payload_travels_without_it() {
+ let body = serde_json::json!({
+ "installation": { "id": 1 },
+ "commits": [{ "message": "x".repeat(MAX_WEBHOOK_PAYLOAD_BYTES) }],
+ });
+
+ let delivery = GithubWebhookReceived::from_delivery(None, "push".to_owned(), &body).unwrap();
+
+ assert_eq!(delivery.payload, None);
+}
diff --git a/crates/github/src/domain/models/webhook_delivery.rs b/crates/github/src/domain/models/webhook_delivery.rs
new file mode 100644
index 0000000000..95526efadc
--- /dev/null
+++ b/crates/github/src/domain/models/webhook_delivery.rs
@@ -0,0 +1,138 @@
+//! A verified delivery from Macro's GitHub App, as other domains receive it.
+//!
+//! Every delivery the App verifies is published, whatever its event, so a
+//! subscriber can act on events this crate never handles itself. A delivery is
+//! untrusted content from GitHub and grants nothing.
+
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+/// Largest payload carried, in bytes of JSON once API links are removed. A
+/// larger delivery travels without its payload, never truncated into
+/// something that reads as a different event.
+pub const MAX_WEBHOOK_PAYLOAD_BYTES: usize = 64 * 1024;
+
+/// One delivery from Macro's GitHub App.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct GithubWebhookReceived {
+ /// GitHub's `X-GitHub-Delivery` id. A redelivery from GitHub's settings
+ /// repeats it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub delivery_id: Option<String>,
+ /// The `X-GitHub-Event` header, such as `workflow_run`.
+ pub event: String,
+ /// The payload's `action`, such as `completed`; absent for events like `push`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub action: Option<String>,
+ /// The App installation the delivery came through.
+ pub installation_id: u64,
+ /// The repository it is about, when it is about one.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub repository: Option<GithubWebhookRepository>,
+ /// Who caused it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub sender: Option<GithubWebhookSender>,
+ /// The body without API links, node ids and the installation. Absent when
+ /// it is still larger than [`MAX_WEBHOOK_PAYLOAD_BYTES`].
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub payload: Option<Value>,
+}
+
+/// A repository named in a delivery.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct GithubWebhookRepository {
+ /// GitHub's numeric id, which survives renames and transfers.
+ pub id: u64,
+ /// `owner/name` at the time of the delivery.
+ pub full_name: String,
+}
+
+/// The account that caused a delivery.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct GithubWebhookSender {
+ /// GitHub login, such as `octocat` or `dependabot[bot]`.
+ pub login: String,
+ /// Whether GitHub calls the account a bot, including apps acting for themselves.
+ pub bot: bool,
+}
+
+#[derive(Deserialize)]
+struct DeliveryFields {
+ action: Option<String>,
+ installation: Option<IdField>,
+ repository: Option<RepositoryFields>,
+ sender: Option<SenderFields>,
+}
+
+#[derive(Deserialize)]
+struct IdField {
+ id: u64,
+}
+
+#[derive(Deserialize)]
+struct RepositoryFields {
+ id: u64,
+ full_name: String,
+}
+
+#[derive(Deserialize)]
+struct SenderFields {
+ login: String,
+ #[serde(rename = "type")]
+ kind: String,
+}
+
+impl GithubWebhookReceived {
+ /// Read a verified delivery. None when it came through no installation,
+ /// as App-level events such as `github_app_authorization` do: nobody in
+ /// Macro can be shown those.
+ pub fn from_delivery(delivery_id: Option<String>, event: String, body: &Value) -> Option<Self> {
+ let fields = DeliveryFields::deserialize(body).ok()?;
+ let installation_id = fields.installation?.id;
+ Some(Self {
+ delivery_id,
+ event,
+ action: fields.action,
+ installation_id,
+ repository: fields.repository.map(|repository| GithubWebhookRepository {
+ id: repository.id,
+ full_name: repository.full_name,
+ }),
+ sender: fields.sender.map(|sender| GithubWebhookSender {
+ bot: sender.kind == "Bot",
+ login: sender.login,
+ }),
+ payload: compact_payload(body),
+ })
+ }
+}
+
+/// GitHub repeats an API link for nearly every object it sends, which is
+/// most of a payload's size and none of its meaning. Web links (`html_url`)
+/// stay: they are what a reader follows.
+fn compact_payload(body: &Value) -> Option<Value> {
+ let mut payload = body.clone();
+ if let Value::Object(fields) = &mut payload {
+ fields.remove("installation");
+ }
+ strip_links(&mut payload);
+ let size = serde_json::to_vec(&payload).ok()?.len();
+ (size <= MAX_WEBHOOK_PAYLOAD_BYTES).then_some(payload)
+}
+
+fn strip_links(value: &mut Value) {
+ match value {
+ Value::Object(fields) => {
+ fields.retain(|key, _| {
+ key == "html_url"
+ || !(key == "url"
+ || key.ends_with("_url")
+ || key == "node_id"
+ || key == "gravatar_id")
+ });
+ fields.values_mut().for_each(strip_links);
+ }
+ Value::Array(items) => items.iter_mut().for_each(strip_links),
+ _ => {}
+ }
+}
diff --git a/crates/github/src/domain/ports/installation_claims.rs b/crates/github/src/domain/ports/installation_claims.rs
new file mode 100644
index 0000000000..27654ec43b
--- /dev/null
+++ b/crates/github/src/domain/ports/installation_claims.rs
@@ -0,0 +1,25 @@
+//! Who may see what a GitHub App installation delivers.
+
+use std::future::Future;
+
+use macro_user_id::user_id::MacroUserIdStr;
+
+use crate::domain::models::GithubError;
+
+/// What GitHub a user reaches through their currently linked account.
+pub trait GithubInstallationClaims: Send + Sync + 'static {
+ /// Whether `user` has linked a GitHub account.
+ fn is_linked(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<bool, GithubError>> + Send;
+
+ /// Whether `user`, while linked, has a claim to the installation: a team
+ /// they belong to installed it, or they installed it with the GitHub
+ /// account linked now. False for an installation Macro has no record of.
+ fn has_claim(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ installation_id: u64,
+ ) -> impl Future<Output = Result<bool, GithubError>> + Send;
+}
diff --git a/crates/github/src/domain/ports/mod.rs b/crates/github/src/domain/ports/mod.rs
index 7dcc6fa7d7..456b151fd1 100644
--- a/crates/github/src/domain/ports/mod.rs
+++ b/crates/github/src/domain/ports/mod.rs
@@ -2,11 +2,15 @@
//!
//! These traits define the contracts that adapters must implement.
+#[cfg(feature = "installation_claims")]
+mod installation_claims;
#[cfg(feature = "link")]
mod link;
#[cfg(feature = "sync")]
mod sync;
+#[cfg(feature = "installation_claims")]
+pub use installation_claims::GithubInstallationClaims;
#[cfg(feature = "link")]
pub use link::{Auth, GithubLinkService, GithubOauth, GithubRepo};
#[cfg(all(test, feature = "sync"))]
@@ -14,5 +18,5 @@ pub use sync::MockGithubSyncRepo;
#[cfg(feature = "sync")]
pub use sync::{
GithubInstallationLister, GithubPullRequestIndex, GithubRepositoryClient, GithubSyncClient,
- GithubSyncRealtime, GithubSyncRepo, GithubSyncService,
+ GithubSyncRealtime, GithubSyncRepo, GithubSyncService, GithubWebhookPublisher,
};
diff --git a/crates/github/src/domain/ports/sync.rs b/crates/github/src/domain/ports/sync.rs
index a68b0c22d1..f681eeba32 100644
--- a/crates/github/src/domain/ports/sync.rs
+++ b/crates/github/src/domain/ports/sync.rs
@@ -343,3 +343,14 @@ pub trait GithubRepositoryClient: Send + Sync + 'static {
installation_id: u64,
) -> impl Future<Output = Result<Vec<GithubRepository>, GithubError>> + Send;
}
+
+/// Publishes every verified delivery for other domains to act on.
+///
+/// Object-safe so read-only service instances can go without one.
+pub trait GithubWebhookPublisher: Send + Sync + 'static {
+ /// Await publication of one delivery.
+ fn publish_received(
+ &self,
+ delivery: crate::domain::models::GithubWebhookReceived,
+ ) -> std::pin::Pin<Box<dyn Future<Output = Result<(), GithubError>> + Send + '_>>;
+}
diff --git a/crates/github/src/domain/service/sync.rs b/crates/github/src/domain/service/sync.rs
index abff4bb618..fb7de310ec 100644
--- a/crates/github/src/domain/service/sync.rs
+++ b/crates/github/src/domain/service/sync.rs
@@ -17,11 +17,14 @@ use crate::domain::{
GithubInstallationAccessToken, GithubInstallationSetupAction, GithubKey,
GithubPullRequestDetails, GithubPullRequestLabel, GithubPullRequestReview,
GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser,
- GithubWebhookEventType, InstallationState, MacroTaskId, ResolvedTeamTaskReference,
- TeamTaskReference, ValidatedGithubWebhookEvent, latest_reviews, sign_installation_state,
- verify_installation_state,
+ GithubWebhookEventType, GithubWebhookReceived, InstallationState, MacroTaskId,
+ ResolvedTeamTaskReference, TeamTaskReference, ValidatedGithubWebhookEvent, latest_reviews,
+ sign_installation_state, verify_installation_state,
+ },
+ ports::{
+ GithubSyncClient, GithubSyncRealtime, GithubSyncRepo, GithubSyncService,
+ GithubWebhookPublisher,
},
- ports::{GithubSyncClient, GithubSyncRealtime, GithubSyncRepo, GithubSyncService},
};
use documents::domain::{models::DocumentError, ports::DocumentService};
use entity_access::domain::models::{EditAccessLevel, ViewAccessLevel};
@@ -78,6 +81,7 @@ pub struct GithubSyncServiceImpl<
realtime: P,
repo: R,
pub(crate) client: C,
+ webhook_publisher: Option<Arc<dyn GithubWebhookPublisher>>,
}
impl<
@@ -107,8 +111,33 @@ impl<
realtime,
repo,
client,
+ webhook_publisher: None,
}
}
+
+ /// Publish every verified delivery for other domains, such as routines.
+ pub fn with_webhook_publisher(mut self, publisher: impl GithubWebhookPublisher) -> Self {
+ self.webhook_publisher = Some(Arc::new(publisher));
+ self
+ }
+
+ async fn publish_webhook_event(
+ &self,
+ webhook_event: &ValidatedGithubWebhookEvent,
+ ) -> Result<(), GithubError> {
+ let Some(publisher) = &self.webhook_publisher else {
+ return Ok(());
+ };
+ let Some(delivery) = GithubWebhookReceived::from_delivery(
+ webhook_event.delivery_id.clone(),
+ webhook_event.event_type.clone(),
+ &webhook_event.payload,
+ ) else {
+ tracing::debug!("skipping publication of a delivery without an installation");
+ return Ok(());
+ };
+ publisher.publish_received(delivery).await
+ }
}
/// Metadata needed to interact with a pull request via the GitHub API.
@@ -919,7 +948,9 @@ impl<
let action = webhook_event.action();
tracing::info!(event_type=?event_type, action, "processing github webhook event");
- match event_type {
+ // Routines subscribe to every delivery, so sync failing must not keep
+ // one from being published.
+ let synced = match event_type {
GithubWebhookEventType::Unknown(ref name) => {
tracing::debug!(event_type=%name, "skipping unknown event type");
Ok(())
@@ -1008,7 +1039,9 @@ impl<
Ok(())
}
},
- }
+ };
+ let published = self.publish_webhook_event(webhook_event).await;
+ synced.and(published)
}
#[tracing::instrument(skip(self), fields(macro_user_id = %macro_user_id), err)]
diff --git a/crates/github/src/domain/service/sync/test.rs b/crates/github/src/domain/service/sync/test.rs
index a707b8b845..b5e4b255bb 100644
--- a/crates/github/src/domain/service/sync/test.rs
+++ b/crates/github/src/domain/service/sync/test.rs
@@ -6131,3 +6131,46 @@ async fn realtime_delivery_failure_keeps_the_saved_mapping() {
assert_eq!(upserts.len(), 1);
assert_eq!(service.foreign_entity_service.foreign_entities().len(), 1);
}
+
+struct RecordingPublisher(Arc<Mutex<Vec<crate::domain::models::GithubWebhookReceived>>>);
+
+impl crate::domain::ports::GithubWebhookPublisher for RecordingPublisher {
+ fn publish_received(
+ &self,
+ delivery: crate::domain::models::GithubWebhookReceived,
+ ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), GithubError>> + Send + '_>>
+ {
+ self.0.lock().unwrap().push(delivery);
+ Box::pin(async { Ok(()) })
+ }
+}
+
+#[tokio::test]
+async fn every_installation_delivery_is_published_even_events_sync_ignores() {
+ let TestGithubSyncService { service, .. } = make_sync_service();
+ let published = Arc::new(Mutex::new(Vec::new()));
+ let service = service.with_webhook_publisher(RecordingPublisher(Arc::clone(&published)));
+
+ let workflow_run = ValidatedGithubWebhookEvent::new(
+ "workflow_run".to_string(),
+ serde_json::json!({
+ "action": "completed",
+ "installation": { "id": 12345 },
+ "workflow_run": { "name": "CI", "conclusion": "failure" },
+ }),
+ )
+ .with_delivery_id(Some("delivery-1".to_string()));
+ let app_level = ValidatedGithubWebhookEvent::new(
+ "github_app_authorization".to_string(),
+ serde_json::json!({ "action": "revoked" }),
+ );
+
+ service.process_webhook_event(&workflow_run).await.unwrap();
+ service.process_webhook_event(&app_level).await.unwrap();
+
+ let published = published.lock().unwrap();
+ assert_eq!(published.len(), 1);
+ assert_eq!(published[0].event, "workflow_run");
+ assert_eq!(published[0].delivery_id.as_deref(), Some("delivery-1"));
+ assert_eq!(published[0].installation_id, 12345);
+}
diff --git a/crates/github/src/inbound/github_sync_router.rs b/crates/github/src/inbound/github_sync_router.rs
index 7bb8f33cdf..8a32e5a987 100644
--- a/crates/github/src/inbound/github_sync_router.rs
+++ b/crates/github/src/inbound/github_sync_router.rs
@@ -240,6 +240,12 @@ where
.and_then(|v| v.strip_prefix("sha256="))
.ok_or(GithubError::InvalidWebhookSignature)?;
+ let delivery_id = parts
+ .headers
+ .get("X-GitHub-Delivery")
+ .and_then(|v| v.to_str().ok())
+ .map(str::to_owned);
+
let body = axum::body::to_bytes(body, usize::MAX)
.await
.map_err(|e| GithubError::Internal(e.into()))?;
@@ -247,7 +253,8 @@ where
let event = state
.service
.validate_webhook_event(event_type, signature, &body)
- .await?;
+ .await?
+ .with_delivery_id(delivery_id);
Ok(GithubWebhookEventExtractor(event))
}
diff --git a/crates/github/src/lib.rs b/crates/github/src/lib.rs
index 61e630155e..1d0ea1ea20 100644
--- a/crates/github/src/lib.rs
+++ b/crates/github/src/lib.rs
@@ -11,7 +11,13 @@
#![deny(missing_docs)]
pub mod domain;
-#[cfg(any(feature = "outbound", feature = "sync"))]
+pub mod broker;
+
+#[cfg(any(
+ feature = "outbound",
+ feature = "sync",
+ feature = "installation_claims"
+))]
pub mod outbound;
#[cfg(feature = "inbound")]
diff --git a/crates/github/src/outbound.rs b/crates/github/src/outbound.rs
index fffc471acc..3eb0813742 100644
--- a/crates/github/src/outbound.rs
+++ b/crates/github/src/outbound.rs
@@ -10,6 +10,8 @@ pub mod github_sync_client;
pub mod pg_github_repo;
#[cfg(feature = "sync")]
pub mod pg_github_sync_repo;
+#[cfg(feature = "installation_claims")]
+pub mod pg_installation_claims;
#[cfg(feature = "sync")]
pub mod pull_request_diff;
#[cfg(any(feature = "link", feature = "sync"))]
diff --git a/crates/github/src/outbound/pg_installation_claims.rs b/crates/github/src/outbound/pg_installation_claims.rs
new file mode 100644
index 0000000000..35da748c08
--- /dev/null
+++ b/crates/github/src/outbound/pg_installation_claims.rs
@@ -0,0 +1,73 @@
+//! Installation claims read from MacroDB.
+
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+
+use crate::domain::{models::GithubError, ports::GithubInstallationClaims};
+
+#[cfg(test)]
+mod test;
+
+/// Reads GitHub links, installations, installers and team membership.
+#[derive(Clone)]
+pub struct PgGithubInstallationClaims {
+ pool: PgPool,
+}
+
+impl PgGithubInstallationClaims {
+ /// Create the adapter over the MacroDB pool.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+impl GithubInstallationClaims for PgGithubInstallationClaims {
+ #[tracing::instrument(skip(self), err)]
+ async fn is_linked(&self, user: &MacroUserIdStr<'_>) -> Result<bool, GithubError> {
+ sqlx::query_scalar!(
+ r#"SELECT EXISTS (SELECT 1 FROM github_links WHERE macro_id = $1) AS "linked!""#,
+ user.as_ref(),
+ )
+ .fetch_one(&self.pool)
+ .await
+ .map_err(|error| GithubError::Internal(error.into()))
+ }
+
+ // A personal installation follows the account linked now: one made with an
+ // account the user has since disconnected no longer counts. Installations
+ // from before installers were recorded have no installer to compare.
+ #[tracing::instrument(skip(self), err)]
+ async fn has_claim(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ installation_id: u64,
+ ) -> Result<bool, GithubError> {
+ sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1 FROM github_app_installation i
+ WHERE i.id = $1
+ AND EXISTS (SELECT 1 FROM github_links l WHERE l.macro_id = $2)
+ AND (
+ (i.source_type = 'user' AND i.source_id = $2 AND NOT EXISTS (
+ SELECT 1 FROM github_app_installation_installer installer
+ WHERE installer.installation_id = i.id
+ AND installer.github_user_id NOT IN (
+ SELECT l.github_user_id FROM github_links l WHERE l.macro_id = $2
+ )
+ ))
+ OR (i.source_type = 'team' AND EXISTS (
+ SELECT 1 FROM team_user t
+ WHERE t.team_id::text = i.source_id AND t.user_id = $2
+ ))
+ )
+ ) AS "claimed!"
+ "#,
+ installation_id.to_string(),
+ user.as_ref(),
+ )
+ .fetch_one(&self.pool)
+ .await
+ .map_err(|error| GithubError::Internal(error.into()))
+ }
+}
diff --git a/crates/github/src/outbound/pg_installation_claims/test.rs b/crates/github/src/outbound/pg_installation_claims/test.rs
new file mode 100644
index 0000000000..6624865b30
--- /dev/null
+++ b/crates/github/src/outbound/pg_installation_claims/test.rs
@@ -0,0 +1,143 @@
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::{Pool, Postgres};
+
+use super::PgGithubInstallationClaims;
+use crate::domain::ports::GithubInstallationClaims;
+
+const SOLO: &str = "macro|[email protected]";
+const SOLO_GITHUB: &str = "67890";
+
+async fn install(pool: &Pool<Postgres>, installation_id: &str, source_id: &str, source_type: &str) {
+ sqlx::query!(
+ r#"
+ INSERT INTO github_app_installation (id, source_id, source_type)
+ VALUES ($1, $2, $3::text::github_app_installation_source_type)
+ "#,
+ installation_id,
+ source_id,
+ source_type,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+async fn installed_by(pool: &Pool<Postgres>, installation_id: &str, github_user_id: &str) {
+ sqlx::query!(
+ "INSERT INTO github_app_installation_installer (installation_id, github_user_id) VALUES ($1, $2)",
+ installation_id,
+ github_user_id,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+/// Disconnects `user`'s GitHub, then optionally links another account.
+async fn relink(pool: &Pool<Postgres>, user: &str, github_user_id: Option<&str>) {
+ sqlx::query!("DELETE FROM github_links WHERE macro_id = $1", user)
+ .execute(pool)
+ .await
+ .unwrap();
+ if let Some(github_user_id) = github_user_id {
+ sqlx::query!(
+ r#"
+ INSERT INTO github_links (id, macro_id, fusionauth_user_id, github_username, github_user_id)
+ VALUES (gen_random_uuid(), $1, gen_random_uuid(), 'other', $2)
+ "#,
+ user,
+ github_user_id,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ }
+}
+
+fn user(id: &'static str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str(id).unwrap()
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_installation_test_data"))
+)]
+async fn a_claim_comes_from_installing_or_from_a_team(pool: Pool<Postgres>) {
+ install(&pool, "100", SOLO, "user").await;
+ install(&pool, "200", "dddddddd-dddd-dddd-dddd-dddddddddddd", "team").await;
+ let claims = PgGithubInstallationClaims::new(pool);
+ let solo = user(SOLO);
+ let alpha_member = user("macro|[email protected]");
+ let beta_member = user("macro|[email protected]");
+
+ assert!(claims.has_claim(&solo, 100).await.unwrap());
+ assert!(!claims.has_claim(&solo, 200).await.unwrap());
+ assert!(claims.has_claim(&alpha_member, 200).await.unwrap());
+ assert!(!claims.has_claim(&alpha_member, 100).await.unwrap());
+ assert!(!claims.has_claim(&beta_member, 200).await.unwrap());
+ assert!(!claims.has_claim(&solo, 300).await.unwrap());
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_installation_test_data"))
+)]
+async fn linking_is_per_user(pool: Pool<Postgres>) {
+ let claims = PgGithubInstallationClaims::new(pool);
+
+ assert!(claims.is_linked(&user(SOLO)).await.unwrap());
+ assert!(
+ !claims
+ .is_linked(&user("macro|[email protected]"))
+ .await
+ .unwrap()
+ );
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_installation_test_data"))
+)]
+async fn nothing_is_claimed_while_github_is_disconnected(pool: Pool<Postgres>) {
+ install(&pool, "100", SOLO, "user").await;
+ installed_by(&pool, "100", SOLO_GITHUB).await;
+ install(&pool, "200", "dddddddd-dddd-dddd-dddd-dddddddddddd", "team").await;
+ relink(&pool, SOLO, None).await;
+ relink(&pool, "macro|[email protected]", None).await;
+ let claims = PgGithubInstallationClaims::new(pool);
+
+ assert!(!claims.has_claim(&user(SOLO), 100).await.unwrap());
+ assert!(
+ !claims
+ .has_claim(&user("macro|[email protected]"), 200)
+ .await
+ .unwrap()
+ );
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_installation_test_data"))
+)]
+async fn a_personal_installation_follows_the_linked_account(pool: Pool<Postgres>) {
+ install(&pool, "100", SOLO, "user").await;
+ installed_by(&pool, "100", SOLO_GITHUB).await;
+ install(&pool, "101", SOLO, "user").await;
+ installed_by(&pool, "101", "55555").await;
+ install(&pool, "200", "dddddddd-dddd-dddd-dddd-dddddddddddd", "team").await;
+ relink(&pool, SOLO, Some("55555")).await;
+ relink(&pool, "macro|[email protected]", Some("55555")).await;
+ let claims = PgGithubInstallationClaims::new(pool);
+
+ // Made with the account solo disconnected; made with the one linked now.
+ assert!(!claims.has_claim(&user(SOLO), 100).await.unwrap());
+ assert!(claims.has_claim(&user(SOLO), 101).await.unwrap());
+ // A team's installation stays whichever account a member links.
+ assert!(
+ claims
+ .has_claim(&user("macro|[email protected]"), 200)
+ .await
+ .unwrap()
+ );
+}
diff --git a/crates/graphql_scheduled_action/src/objects.rs b/crates/graphql_scheduled_action/src/objects.rs
index d65e40df83..eab36f8b95 100644
--- a/crates/graphql_scheduled_action/src/objects.rs
+++ b/crates/graphql_scheduled_action/src/objects.rs
@@ -70,10 +70,27 @@ pub(crate) struct GraphqlScheduledActionEventFilter {
events: Vec<GraphqlScheduledActionEventName>,
/// Entity ids that can satisfy this filter. Null matches every id; an empty list matches nothing.
entity_ids: Option<Vec<ID>>,
+ /// Which GitHub App deliveries satisfy a `GITHUB` filter.
+ github: Option<GraphqlScheduledActionGithubSelector>,
+ /// Exact payload tests a GitHub delivery must pass, as a reader would state them.
+ payload_match: Vec<String>,
/// Yes/no question the triggering content must answer with yes before the routine runs.
condition: Option<String>,
}
+/// GitHub deliveries a filter watches. Empty lists match everything.
+#[derive(SimpleObject)]
+pub(crate) struct GraphqlScheduledActionGithubSelector {
+ /// GitHub event names, such as `workflow_run`.
+ events: Vec<String>,
+ /// Payload actions, such as `completed`.
+ actions: Vec<String>,
+ /// Repositories, as `owner/name`.
+ repositories: Vec<String>,
+ /// Whether deliveries caused by bots also match.
+ include_bots: bool,
+}
+
/// The agent task a routine runs.
#[derive(SimpleObject)]
pub(crate) struct GraphqlScheduledActionAgentTask {
@@ -127,6 +144,8 @@ pub(crate) enum GraphqlScheduledActionEventName {
CallStarted,
/// A call the routine's owner joined ended.
CallEnded,
+ /// Macro's GitHub App received a delivery.
+ Github,
}
impl From<EventName> for GraphqlScheduledActionEventName {
@@ -147,6 +166,7 @@ impl From<EventName> for GraphqlScheduledActionEventName {
EventName::ChannelMessageAttachmentCreated => Self::ChannelMessageAttachmentCreated,
EventName::CallStarted => Self::CallStarted,
EventName::CallEnded => Self::CallEnded,
+ EventName::Github => Self::Github,
}
}
}
@@ -249,6 +269,24 @@ fn event_filters(
entity_ids: filter
.ids()
.map(|ids| ids.iter().map(|id| ID(id.to_string())).collect()),
+ github: filter
+ .github()
+ .map(|selector| GraphqlScheduledActionGithubSelector {
+ events: selector.events().to_vec(),
+ actions: selector.actions().to_vec(),
+ repositories: selector.repositories().to_vec(),
+ include_bots: selector.include_bots(),
+ }),
+ payload_match: filter
+ .payload()
+ .map(|conditions| {
+ conditions
+ .as_slice()
+ .iter()
+ .map(|condition| condition.describe())
+ .collect()
+ })
+ .unwrap_or_default(),
condition: filter
.condition()
.map(|condition| condition.as_str().to_owned()),
diff --git a/crates/macro_db_migrator/AGENTS.md b/crates/macro_db_migrator/AGENTS.md
index 49cf9bef3f..34ebed59c4 100644
--- a/crates/macro_db_migrator/AGENTS.md
+++ b/crates/macro_db_migrator/AGENTS.md
@@ -28,6 +28,9 @@ Migration files belong in `../macro_db_client/migrations/`.
- Use SQL fixtures for statements that target a historical schema; current-schema
SQLx macros cannot validate columns that have since been removed or added.
- Exercise concurrent indexes through SQLx's migrator, outside explicit transactions.
+- Keep the migrations fingerprint `build.rs` passes as a cfg: sccache keys this
+ crate on its arguments, and without it CI reused a migrator missing a renamed
+ migration.
## Related
diff --git a/crates/macro_db_migrator/build.rs b/crates/macro_db_migrator/build.rs
index 027eafdbec..2901ac2902 100644
--- a/crates/macro_db_migrator/build.rs
+++ b/crates/macro_db_migrator/build.rs
@@ -1,5 +1,30 @@
+use std::hash::{DefaultHasher, Hash, Hasher};
+
+const MIGRATIONS: &str = "../macro_db_client/migrations";
+
fn main() {
// sqlx::migrate! tracks existing files, but stable Rust does not track newly
// added migrations. Rebuild the embedded migrator when the directory changes.
- println!("cargo:rerun-if-changed=../macro_db_client/migrations");
+ println!("cargo:rerun-if-changed={MIGRATIONS}");
+
+ // sccache keys this crate on its compiler arguments, not on the files the
+ // macro reads, so a renamed or added migration could reuse a stale build.
+ // Fingerprinting the migrations into a cfg puts them in that key.
+ let mut entries: Vec<_> = std::fs::read_dir(MIGRATIONS)
+ .expect("the migrations directory sits beside this crate")
+ .map(|entry| entry.expect("migration entries are readable").path())
+ .collect();
+ entries.sort();
+ let mut hasher = DefaultHasher::new();
+ for path in entries {
+ path.file_name().hash(&mut hasher);
+ std::fs::read(&path)
+ .expect("migration files are readable")
+ .hash(&mut hasher);
+ }
+ println!("cargo::rustc-check-cfg=cfg(macro_db_migrations, values(any()))");
+ println!(
+ "cargo:rustc-cfg=macro_db_migrations=\"{:016x}\"",
+ hasher.finish()
+ );
}
diff --git a/crates/macro_event_topics/src/lib.rs b/crates/macro_event_topics/src/lib.rs
index 2190c246e7..679296d5b0 100644
--- a/crates/macro_event_topics/src/lib.rs
+++ b/crates/macro_event_topics/src/lib.rs
@@ -55,6 +55,8 @@ topics! {
MacroDocumentsTopic => "macro.documents",
/// Committed GitHub pull request updates.
MacroGithubPullRequestsTopic => "macro.github_pull_requests",
+ /// Every delivery the GitHub App verified, whatever its event.
+ MacroGithubWebhooksTopic => "macro.github_webhooks",
/// User-scoped full Soup items produced from entity updates.
MacroSoupRealtimeTopic => "macro.soup",
/// Project lifecycle events (created, updated, deleted, restored, permanently deleted, and uploaded).
diff --git a/crates/scheduled_action/AGENTS.md b/crates/scheduled_action/AGENTS.md
index efa8140e28..563d282ba6 100644
--- a/crates/scheduled_action/AGENTS.md
+++ b/crates/scheduled_action/AGENTS.md
@@ -14,6 +14,8 @@ each run.
and the ports its adapters implement.
- `src/domain/event_trigger.rs` + `src/domain/target_runner.rs`: how an event
(Kafka or polled) turns into a dispatched run.
+- `src/domain/event_trigger/github_selector.rs`, `payload_match.rs`: the
+ `github` selector and the exact payload `match` GitHub filters take.
- `src/inbound/axum_router.rs`, `src/inbound/kafka_consumer.rs`,
`src/inbound/event_run_worker.rs`: the three inbound adapters.
- `src/domain/templates.rs` + `src/inbound/template_router.rs`: sharing a
@@ -40,7 +42,8 @@ each run.
## Boundaries
- Depends on: `agent_session`, `trigger_context`, `jev`, `channels`, `crm`,
- `documents`, `macro_event_broker`/`macro_event_topics` (Kafka), `macro_db_client`.
+ `documents`, `github` (delivery fact and installation claims only),
+ `macro_event_broker`/`macro_event_topics` (Kafka), `macro_db_client`.
- Used by: the web app's automations/routines UI and agent tooling, through
the gateway.
@@ -74,7 +77,13 @@ that listener is ready. Cancellation can stop the gate before startup finishes.
`RoutineSessions::prepare` checks again on every run, then adds them to an
agent limited to selected apps. An update that omits the key is rejected
when the stored task has apps (`require_explicit_selection`).
-
+- Macro events store only ids and are read again, as the owner, at dispatch.
+ GitHub deliveries can't be read again, so their event runs keep the bounded
+ payload in `event_context`; access for them is the owner's installation
+ claim, which needs a linked GitHub account and, for a personal installation,
+ that the linked account installed it.
+- Enabling a GitHub trigger needs the owner's GitHub link
+ (`with_github_links`); without it the service returns `GithubNotLinked`.
- `TODO.md` tracks open follow-ups (unified history list, delete schedules,
sharing/permissions) — check it before assuming a listed gap is unintentional.
- A new configuration field needs `#[serde(default)]` in `ActionConfiguration`
diff --git a/crates/scheduled_action/Cargo.toml b/crates/scheduled_action/Cargo.toml
index 3d2a4eca56..87ed1ec2fa 100644
--- a/crates/scheduled_action/Cargo.toml
+++ b/crates/scheduled_action/Cargo.toml
@@ -25,6 +25,8 @@ crm = { path = "../crm", default-features = false, features = ["ports"] }
documents = { path = "../documents", default-features = false, features = ["outbound", "ports"] }
document_sub_type = { path = "../document_sub_type" }
email = { path = "../email", default-features = false, features = ["outbound"] }
+github = { path = "../github", default-features = false, features = ["installation_claims"] }
+glob = { workspace = true }
entity_access_management = { path = "../entity_access_management" }
frecency = { path = "../frecency", features = ["postgres"] }
feature_flags = { path = "../feature_flags" }
diff --git a/crates/scheduled_action/src/domain/event_runs.rs b/crates/scheduled_action/src/domain/event_runs.rs
index e914abb857..b16691849e 100644
--- a/crates/scheduled_action/src/domain/event_runs.rs
+++ b/crates/scheduled_action/src/domain/event_runs.rs
@@ -13,7 +13,8 @@ use rootcause::Report;
use serde::{Deserialize, Serialize};
use super::event_trigger::{
- EventEntityType, EventFilters, EventId, EventReference, EventRejection, IncomingEvent,
+ EventEntityType, EventFilters, EventId, EventReference, EventRejection, EventSource,
+ IncomingEvent,
};
use super::models::{ActionExecutionRecord, ScheduledAction};
@@ -22,7 +23,7 @@ pub mod condition;
pub mod dispatch;
#[cfg(test)]
-mod test_support;
+pub(crate) mod test_support;
/// Independent of `updated_at`, which execution bookkeeping also changes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -210,6 +211,11 @@ pub enum EventAccessCapability {
Channel(EntityAccessReceipt<ViewOnly>),
EmailThread(EntityAccessReceipt<ViewAccessLevel>),
Call(EntityAccessReceipt<ViewAccessLevel>),
+ /// The owner has a claim to the GitHub App installation that delivered.
+ GithubInstallation {
+ owner: MacroUserIdStr<'static>,
+ installation_id: u64,
+ },
}
impl EventAccessCapability {
@@ -229,6 +235,19 @@ impl EventAccessCapability {
(Self::Call(receipt), EventEntityType::Call) => {
receipt_matches(receipt, owner, event, EntityType::Call)
}
+ (
+ Self::GithubInstallation {
+ owner: claimant,
+ installation_id,
+ },
+ EventEntityType::GithubInstallation,
+ ) => {
+ claimant == owner
+ && matches!(
+ event.source(),
+ EventSource::Github(delivery) if delivery.installation_id == *installation_id
+ )
+ }
_ => false,
}
}
@@ -244,7 +263,9 @@ fn receipt_matches<T: RequiredPermission>(
.get_authenticated_user()
.is_ok_and(|user| user == owner)
&& receipt.entity().entity_type == kind
- && Uuid::parse_str(&receipt.entity().entity_id).ok() == Some(event.entity_id())
+ && event
+ .entity_id()
+ .is_some_and(|id| Uuid::parse_str(&receipt.entity().entity_id).ok() == Some(id))
}
/// Receipt minted for the current action owner and triggering entity.
@@ -384,7 +405,8 @@ pub trait EventRunRepository: Send + Sync + 'static {
) -> impl Future<Output = Result<Option<ClaimedEventRun>, Report>> + Send;
/// Idempotent bookkeeping only: history, terminal outcome and fenced action
- /// release must commit together. Retain the deduplication row until deletion.
+ /// release must commit together. Retain the deduplication row until deletion,
+ /// without an external delivery's payload: nothing reads a finished run's event.
fn finalize(
&self,
run: FinalizeEventRun,
diff --git a/crates/scheduled_action/src/domain/event_runs/admission.rs b/crates/scheduled_action/src/domain/event_runs/admission.rs
index b2e293e400..a671c23fb5 100644
--- a/crates/scheduled_action/src/domain/event_runs/admission.rs
+++ b/crates/scheduled_action/src/domain/event_runs/admission.rs
@@ -26,6 +26,44 @@ impl<R, A> EventAdmissionService<R, A> {
}
}
+impl<R: EventRunRepository, A: CurrentOwnerAccess> EventAdmissionService<R, A> {
+ /// Admit `event` to one candidate if it is eligible now. False when it is
+ /// not: disabled, changed, filtered out, or not the owner's to see.
+ async fn admit_candidate(
+ &self,
+ configuration: EventActionConfiguration,
+ event: &EventReference,
+ incoming: Option<&IncomingEvent>,
+ ) -> Result<bool, Report> {
+ let pending = PendingEventRun {
+ action_id: configuration.action_id,
+ revision: configuration.revision,
+ event: event.clone(),
+ admitted_at: Utc::now(),
+ };
+ if configuration.check_pending(&pending).is_err() {
+ return Ok(false);
+ }
+ let Owner::User(owner) = &configuration.owner else {
+ return Ok(false);
+ };
+ if incoming.is_some_and(|incoming| !incoming.is_for_owner(owner)) {
+ return Ok(false);
+ }
+ let Some(access) = self.access.authorize(owner, event).await? else {
+ return Ok(false);
+ };
+ if AuthorizedEventRun::prepare(pending, &configuration, access).is_err() {
+ return Ok(false);
+ }
+ Ok(self
+ .repository
+ .admit(configuration.action_id, configuration.revision, event)
+ .await?
+ == AdmissionResult::Admitted)
+ }
+}
+
impl<R: EventRunRepository, A: CurrentOwnerAccess> EventIngestion for EventAdmissionService<R, A> {
async fn ingest(&self, incoming: &IncomingEvent) -> Result<EventIngestionResult, Report> {
let event = match incoming.normalize() {
@@ -56,32 +94,9 @@ impl<R: EventRunRepository, A: CurrentOwnerAccess> EventIngestion for EventAdmis
return Err(rootcause::report!("event candidate page is not ordered"));
}
after = Some(configuration.action_id);
- let pending = PendingEventRun {
- action_id: configuration.action_id,
- revision: configuration.revision,
- event: event.clone(),
- admitted_at: Utc::now(),
- };
- if configuration.check_pending(&pending).is_err() {
- continue;
- }
- let Owner::User(owner) = &configuration.owner else {
- continue;
- };
- if !incoming.is_for_owner(owner) {
- continue;
- }
- let Some(access) = self.access.authorize(owner, &event).await? else {
- continue;
- };
- if AuthorizedEventRun::prepare(pending, &configuration, access).is_err() {
- continue;
- }
if self
- .repository
- .admit(configuration.action_id, configuration.revision, &event)
+ .admit_candidate(configuration, &event, Some(incoming))
.await?
- == AdmissionResult::Admitted
{
inserted += 1;
}
diff --git a/crates/scheduled_action/src/domain/event_runs/admission/test.rs b/crates/scheduled_action/src/domain/event_runs/admission/test.rs
index 228e136c1b..ae6be031e8 100644
--- a/crates/scheduled_action/src/domain/event_runs/admission/test.rs
+++ b/crates/scheduled_action/src/domain/event_runs/admission/test.rs
@@ -200,3 +200,89 @@ async fn mentions_mail_and_calls_only_admit_their_recipient_even_when_others_hav
);
}
}
+
+fn github_delivery(conclusion: &str, sender_type: &str) -> IncomingEvent {
+ let body = json!({
+ "action": "completed",
+ "installation": { "id": 77 },
+ "repository": { "id": 42, "full_name": "macro-inc/macro", "url": "https://api.github.com/x" },
+ "sender": { "login": "octocat", "type": sender_type },
+ "workflow_run": { "name": "CI", "conclusion": conclusion },
+ });
+ let delivery = github::domain::models::GithubWebhookReceived::from_delivery(
+ Some("delivery".to_owned()),
+ "workflow_run".to_owned(),
+ &body,
+ )
+ .unwrap();
+ IncomingEvent {
+ event_id: generate_uuid_v7(),
+ schema_version: 1,
+ payload: crate::domain::event_trigger::EventPayload::Github(
+ github::broker::GithubWebhookTopicEvent::Received(delivery),
+ ),
+ }
+}
+
+fn failed_ci_routine() -> EventActionConfiguration {
+ EventActionConfiguration {
+ filters: serde_json::from_value(json!([{
+ "events": ["github"],
+ "github": {
+ "events": ["workflow_run"],
+ "actions": ["completed"],
+ "repositories": ["Macro-Inc/macro"],
+ },
+ "match": [
+ { "path": ["workflow_run", "name"], "equals": "CI" },
+ { "path": ["workflow_run", "conclusion"], "equals": "failure" },
+ ],
+ }]))
+ .unwrap(),
+ ..configuration()
+ }
+}
+
+#[tokio::test]
+async fn github_deliveries_run_routines_whose_selector_and_payload_match() {
+ let repo = Arc::new(Repo::default());
+ repo.0.lock().unwrap().configurations = vec![failed_ci_routine()];
+ let service = EventAdmissionService::new(
+ repo.clone(),
+ Arc::new(Access::default()),
+ 10.try_into().unwrap(),
+ );
+
+ for (event, inserted) in [
+ (github_delivery("success", "User"), 0),
+ (github_delivery("failure", "Bot"), 0),
+ (github_delivery("failure", "User"), 1),
+ ] {
+ assert_eq!(
+ service.ingest(&event).await.unwrap(),
+ EventIngestionResult::Admitted { inserted }
+ );
+ }
+ let pending = &repo.0.lock().unwrap().pending;
+ assert!(matches!(
+ pending[0].event.source(),
+ EventSource::Github(delivery) if delivery.installation_id == 77
+ ));
+}
+
+#[tokio::test]
+async fn github_deliveries_need_a_claim_to_the_installation() {
+ let repo = Arc::new(Repo::default());
+ repo.0.lock().unwrap().configurations = vec![failed_ci_routine()];
+ let access = Arc::new(Access::default());
+ *access.denied.lock().unwrap() = true;
+ let service = EventAdmissionService::new(repo.clone(), access, 10.try_into().unwrap());
+
+ assert_eq!(
+ service
+ .ingest(&github_delivery("failure", "User"))
+ .await
+ .unwrap(),
+ EventIngestionResult::Admitted { inserted: 0 }
+ );
+}
diff --git a/crates/scheduled_action/src/domain/event_runs/dispatch/test.rs b/crates/scheduled_action/src/domain/event_runs/dispatch/test.rs
index 68518c0f11..4d394bf478 100644
--- a/crates/scheduled_action/src/domain/event_runs/dispatch/test.rs
+++ b/crates/scheduled_action/src/domain/event_runs/dispatch/test.rs
@@ -266,7 +266,7 @@ fn preparation_binds_receipt_to_authenticated_owner_entity_and_kind() {
let receipt = EntityAccessReceipt::try_new(
auth,
Entity {
- entity_id: pending.event.entity_id().to_string(),
+ entity_id: pending.event.entity_id().unwrap().to_string(),
entity_type: EntityType::Document,
},
EntityPermission::AccessLevel {
@@ -285,7 +285,7 @@ fn preparation_binds_receipt_to_authenticated_owner_entity_and_kind() {
}
for (id, kind) in [
(generate_uuid_v7(), EntityType::Document),
- (pending.event.entity_id(), EntityType::Chat),
+ (pending.event.entity_id().unwrap(), EntityType::Chat),
] {
let receipt = EntityAccessReceipt::try_new_authenticated_user(
user(),
diff --git a/crates/scheduled_action/src/domain/event_runs/test_support.rs b/crates/scheduled_action/src/domain/event_runs/test_support.rs
index c9951aea7d..3be7239c74 100644
--- a/crates/scheduled_action/src/domain/event_runs/test_support.rs
+++ b/crates/scheduled_action/src/domain/event_runs/test_support.rs
@@ -56,13 +56,25 @@ pub fn pending(configuration: &EventActionConfiguration) -> PendingEventRun {
}
pub fn capability(owner: MacroUserIdStr<'static>, event: &EventReference) -> EventAccessCapability {
+ match event.source() {
+ EventSource::Github(delivery) => {
+ return EventAccessCapability::GithubInstallation {
+ owner,
+ installation_id: delivery.installation_id,
+ };
+ }
+ EventSource::Entity { .. } => {}
+ }
let entity = Entity {
- entity_id: event.entity_id().to_string(),
+ entity_id: event.entity_id().unwrap().to_string(),
entity_type: match event.entity_type() {
EventEntityType::Document => EntityType::Document,
EventEntityType::Channel => EntityType::Channel,
EventEntityType::EmailThread => EntityType::EmailThread,
EventEntityType::Call => EntityType::Call,
+ EventEntityType::GithubInstallation => {
+ unreachable!("external events returned above")
+ }
},
};
match event.entity_type() {
@@ -104,6 +116,9 @@ pub fn capability(owner: MacroUserIdStr<'static>, event: &EventReference) -> Eve
)
.unwrap(),
),
+ EventEntityType::GithubInstallation => {
+ unreachable!("external events returned above")
+ }
}
}
diff --git a/crates/scheduled_action/src/domain/event_trigger.rs b/crates/scheduled_action/src/domain/event_trigger.rs
index b154f27e95..421514f05c 100644
--- a/crates/scheduled_action/src/domain/event_trigger.rs
+++ b/crates/scheduled_action/src/domain/event_trigger.rs
@@ -1,8 +1,9 @@
//! Routine-owned event eligibility and exact selector matching.
//!
//! Adapters strip the broker envelope into [`IncomingEvent`]. Only explicitly
-//! allowlisted human actions, inbound emails and call lifecycle events become
-//! compact [`EventReference`]s.
+//! allowlisted human actions, inbound emails, call lifecycle events and GitHub
+//! App deliveries become [`EventReference`]s. GitHub deliveries can also be
+//! filtered on exact payload values.
use activity::Actor;
use call::domain::events::CallTopicEvent;
@@ -12,6 +13,8 @@ use chrono_tz::Tz;
use document_sub_type::DocumentSubType;
use documents::domain::events::DocumentTopicEvent;
use email::domain::events::EmailTopicEvent;
+use github::broker::GithubWebhookTopicEvent;
+use github::domain::models::GithubWebhookReceived;
use jev::domain::YesNoQuestion;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
@@ -25,11 +28,20 @@ use messages::domain::{
use models_properties::EntityType as PropertyEntityType;
use properties::domain::events::PropertyTopicEvent;
use serde::{Deserialize, Serialize};
+use serde_json::Value;
use system_properties::SystemPropertyKey;
use utoipa::ToSchema;
use super::models::Schedule;
+mod github_selector;
+mod payload_match;
+
+pub use github_selector::{GithubSelector, GithubSelectorError, GithubSelectorInput};
+pub use payload_match::{
+ PayloadConditionInput, PayloadConditions, PayloadMatchError, PayloadScalar,
+};
+
#[cfg(test)]
mod test;
@@ -186,6 +198,9 @@ pub enum EventName {
CallStarted,
#[serde(rename = "call.ended")]
CallEnded,
+ /// A delivery from Macro's GitHub App; the filter's `github` selector narrows it.
+ #[serde(rename = "github")]
+ Github,
}
impl EventName {
@@ -206,6 +221,7 @@ impl EventName {
Self::ChannelMessageAttachmentCreated => "channel.message_attachment_created",
Self::CallStarted => "call.started",
Self::CallEnded => "call.ended",
+ Self::Github => "github",
}
}
@@ -225,9 +241,16 @@ impl EventName {
| Self::ChannelMentioned
| Self::ChannelMessagePatched
| Self::ChannelMessageAttachmentCreated => EventEntityType::Channel,
+ Self::Github => EventEntityType::GithubInstallation,
}
}
+ /// Events from outside Macro: they carry their payload, take a payload
+ /// match, and stand alone in their filter.
+ const fn is_external(self) -> bool {
+ matches!(self, Self::Github)
+ }
+
const fn has_message(self) -> bool {
matches!(
self,
@@ -256,6 +279,8 @@ pub enum EventEntityType {
Channel,
EmailThread,
Call,
+ /// The GitHub App installation a delivery came through.
+ GithubInstallation,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
@@ -266,10 +291,25 @@ pub enum FilterValidationError {
EventCount,
#[error("expected at most 100 entity IDs per filter")]
IdCount,
+ #[error("github needs a filter of its own, without ids")]
+ ExternalEventMix,
+ #[error("a github filter needs a github selector, and only it takes one")]
+ GithubSelector,
+ #[error("only github filters take a payload match")]
+ PayloadMatch,
+ #[error(transparent)]
+ Github(#[from] GithubSelectorError),
+ #[error(transparent)]
+ Payload(#[from] PayloadMatchError),
}
/// An event name AND an entity ID must match within the same filter. A
/// condition further requires the event's content to answer it with yes.
+///
+/// `github` comes from outside Macro and carries its payload: it stands
+/// alone in its filter, takes no ids, and may require
+/// exact payload values with `match`. A `github` filter narrows deliveries
+/// with its `github` selector.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, ToSchema)]
#[serde(try_from = "FilterInput")]
pub struct EventFilter {
@@ -277,6 +317,14 @@ pub struct EventFilter {
#[serde(skip_serializing_if = "Option::is_none")]
#[schema(value_type = Option<Vec<String>>)]
ids: Option<Vec<Uuid>>,
+ /// Which GitHub deliveries match; required for, and only for, `github`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schema(value_type = Option<GithubSelectorInput>)]
+ github: Option<GithubSelector>,
+ /// Exact tests on the payload, all of which must pass.
+ #[serde(rename = "match", skip_serializing_if = "Option::is_none")]
+ #[schema(value_type = Option<Vec<PayloadConditionInput>>)]
+ payload: Option<PayloadConditions>,
/// Yes/no question about the triggering content, e.g. "Is this email an
/// invoice?". The routine runs only when the answer is yes.
#[serde(skip_serializing_if = "Option::is_none")]
@@ -291,6 +339,10 @@ struct FilterInput {
#[serde(default)]
ids: Option<Vec<Uuid>>,
#[serde(default)]
+ github: Option<GithubSelector>,
+ #[serde(default, rename = "match")]
+ payload: Option<PayloadConditions>,
+ #[serde(default)]
condition: Option<YesNoQuestion>,
}
@@ -298,7 +350,9 @@ impl TryFrom<FilterInput> for EventFilter {
type Error = FilterValidationError;
fn try_from(input: FilterInput) -> Result<Self, Self::Error> {
- Ok(Self::new(input.events, input.ids)?.with_condition(input.condition))
+ Self::new(input.events, input.ids)?
+ .with_condition(input.condition)
+ .with_external(input.github, input.payload)
}
}
@@ -316,6 +370,9 @@ impl EventFilter {
{
return Err(FilterValidationError::IdCount);
}
+ if events.iter().any(|name| name.is_external()) && (events.len() > 1 || ids.is_some()) {
+ return Err(FilterValidationError::ExternalEventMix);
+ }
events.sort_unstable();
events.dedup();
if let Some(ids) = &mut ids {
@@ -325,6 +382,8 @@ impl EventFilter {
Ok(Self {
events,
ids,
+ github: None,
+ payload: None,
condition: None,
})
}
@@ -334,6 +393,24 @@ impl EventFilter {
self
}
+ /// Attach the GitHub selector and payload match an external filter takes.
+ pub fn with_external(
+ mut self,
+ github: Option<GithubSelector>,
+ payload: Option<PayloadConditions>,
+ ) -> Result<Self, FilterValidationError> {
+ let is_github = self.events == [EventName::Github];
+ if is_github != github.is_some() {
+ return Err(FilterValidationError::GithubSelector);
+ }
+ if payload.is_some() && !self.events.iter().any(|name| name.is_external()) {
+ return Err(FilterValidationError::PayloadMatch);
+ }
+ self.github = github;
+ self.payload = payload;
+ Ok(self)
+ }
+
pub fn events(&self) -> &[EventName] {
&self.events
}
@@ -343,16 +420,42 @@ impl EventFilter {
self.ids.as_deref()
}
+ pub fn github(&self) -> Option<&GithubSelector> {
+ self.github.as_ref()
+ }
+
+ pub fn payload(&self) -> Option<&PayloadConditions> {
+ self.payload.as_ref()
+ }
+
pub fn condition(&self) -> Option<&YesNoQuestion> {
self.condition.as_ref()
}
- pub fn accepts(&self, name: EventName, entity_id: Uuid) -> bool {
- (self.events.contains(&name)
+ pub fn accepts(&self, event: &EventReference) -> bool {
+ let name = event.event_name;
+ let named = self.events.contains(&name)
|| name
.general_event()
- .is_some_and(|general| self.events.contains(&general)))
- && self.ids.as_ref().is_none_or(|ids| ids.contains(&entity_id))
+ .is_some_and(|general| self.events.contains(&general));
+ named
+ && match &event.source {
+ EventSource::Entity { entity_id, .. } => {
+ self.ids.as_ref().is_none_or(|ids| ids.contains(entity_id))
+ }
+ EventSource::Github(delivery) => {
+ self.github
+ .as_ref()
+ .is_some_and(|selector| selector.accepts(delivery))
+ && self.payload_accepts(delivery.payload.as_ref())
+ }
+ }
+ }
+
+ fn payload_accepts(&self, payload: Option<&Value>) -> bool {
+ self.payload
+ .as_ref()
+ .is_none_or(|conditions| conditions.matches(payload))
}
}
@@ -388,27 +491,25 @@ impl EventFilters {
/// Publication time comes only from the UUIDv7, never ingestion or metadata
/// timestamps. The activation boundary is inclusive.
pub fn matches(&self, event: &EventReference, activated_at: DateTime<Utc>) -> bool {
- event.published_at() >= activated_at
- && self
- .0
- .iter()
- .any(|filter| filter.accepts(event.event_name, event.entity_id))
+ event.published_at() >= activated_at && self.0.iter().any(|filter| filter.accepts(event))
}
pub fn has_conditions(&self) -> bool {
self.0.iter().any(|filter| filter.condition.is_some())
}
+ pub fn watches_github(&self) -> bool {
+ self.0
+ .iter()
+ .any(|filter| filter.events.contains(&EventName::Github))
+ }
+
/// What a matching event must satisfy before its run starts. A matching
/// filter without a condition runs unconditionally; otherwise any one of
/// the matching filters' conditions is enough.
pub fn condition_requirement(&self, event: &EventReference) -> ConditionRequirement {
let mut conditions = Vec::new();
- for filter in self
- .0
- .iter()
- .filter(|filter| filter.accepts(event.event_name, event.entity_id))
- {
+ for filter in self.0.iter().filter(|filter| filter.accepts(event)) {
match &filter.condition {
None => return ConditionRequirement::Unconditional,
Some(condition) => conditions.push(condition.clone()),
@@ -470,42 +571,98 @@ impl EventId {
}
}
-/// Minimal durable context. No content, actor, owner or full envelope is kept.
+/// Durable context. A Macro event keeps no content, actor, owner or full
+/// envelope: dispatch reads its content again, as the routine's owner. An
+/// external delivery has nothing to read again, so it keeps its payload.
/// The entity kind and publication timestamp derive from the name and event ID.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(try_from = "EventReferenceInput")]
+#[serde(try_from = "EventReferenceInput", into = "EventReferenceInput")]
pub struct EventReference {
event_id: EventId,
event_name: EventName,
- entity_id: Uuid,
- message_id: Option<Uuid>,
+ source: EventSource,
}
-#[derive(Deserialize)]
+/// What an event is about.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum EventSource {
+ /// A Macro entity, and the message the event concerns.
+ Entity {
+ entity_id: Uuid,
+ message_id: Option<Uuid>,
+ },
+ /// A delivery from Macro's GitHub App. Boxed: it carries its payload.
+ Github(Box<GithubWebhookReceived>),
+}
+
+#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct EventReferenceInput {
event_id: EventId,
event_name: EventName,
- entity_id: Uuid,
- message_id: Option<Uuid>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ entity_id: Option<Uuid>,
+ /// Always written for Macro events, which predate external ones.
+ #[serde(default, skip_serializing_if = "skip_message_id")]
+ message_id: Option<Option<Uuid>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ github: Option<Box<GithubWebhookReceived>>,
+}
+
+fn skip_message_id(message_id: &Option<Option<Uuid>>) -> bool {
+ message_id.is_none()
}
impl TryFrom<EventReferenceInput> for EventReference {
type Error = EventRejection;
fn try_from(input: EventReferenceInput) -> Result<Self, Self::Error> {
- if input.event_name.has_message() != input.message_id.is_some() {
- return Err(EventRejection::InvalidContext);
- }
+ let name = input.event_name;
+ let source = match (input.entity_id, input.github) {
+ (Some(entity_id), None) if !name.is_external() => {
+ let message_id = input.message_id.flatten();
+ if name.has_message() != message_id.is_some() {
+ return Err(EventRejection::InvalidContext);
+ }
+ EventSource::Entity {
+ entity_id,
+ message_id,
+ }
+ }
+ (None, Some(delivery)) if name == EventName::Github => EventSource::Github(delivery),
+ _ => return Err(EventRejection::InvalidContext),
+ };
Ok(Self {
event_id: input.event_id,
- event_name: input.event_name,
- entity_id: input.entity_id,
- message_id: input.message_id,
+ event_name: name,
+ source,
})
}
}
+impl From<EventReference> for EventReferenceInput {
+ fn from(event: EventReference) -> Self {
+ let mut input = Self {
+ event_id: event.event_id,
+ event_name: event.event_name,
+ entity_id: None,
+ message_id: None,
+ github: None,
+ };
+ match event.source {
+ EventSource::Entity {
+ entity_id,
+ message_id,
+ } => {
+ input.entity_id = Some(entity_id);
+ input.message_id = Some(message_id);
+ }
+ EventSource::Github(delivery) => input.github = Some(delivery),
+ }
+ input
+ }
+}
+
impl EventReference {
pub fn event_id(&self) -> EventId {
self.event_id
@@ -516,11 +673,21 @@ impl EventReference {
pub fn entity_type(&self) -> EventEntityType {
self.event_name.entity_type()
}
- pub fn entity_id(&self) -> Uuid {
- self.entity_id
+ pub fn source(&self) -> &EventSource {
+ &self.source
+ }
+ /// The Macro entity the event is about; None for external deliveries.
+ pub fn entity_id(&self) -> Option<Uuid> {
+ match self.source {
+ EventSource::Entity { entity_id, .. } => Some(entity_id),
+ EventSource::Github(_) => None,
+ }
}
pub fn message_id(&self) -> Option<Uuid> {
- self.message_id
+ match self.source {
+ EventSource::Entity { message_id, .. } => message_id,
+ EventSource::Github(_) => None,
+ }
}
pub fn published_at(&self) -> DateTime<Utc> {
self.event_id.published_at()
@@ -536,6 +703,7 @@ pub enum EventPayload {
Property(PropertyTopicEvent),
Email(EmailTopicEvent),
Call(CallTopicEvent),
+ Github(GithubWebhookTopicEvent),
}
/// The message facts routines can trigger on, from `macro.messages`. Anything
@@ -747,12 +915,26 @@ impl IncomingEvent {
(EventName::CallEnded, data.call_id, None)
}
EventPayload::Call(_) => return Err(EventRejection::UnsupportedEvent),
+ EventPayload::Github(GithubWebhookTopicEvent::Received(delivery)) => {
+ // Every event GitHub sends may trigger; its name only has to be one
+ // a selector could name. Bots are left to each filter.
+ if !github_selector::valid_event_name(&delivery.event) {
+ return Err(EventRejection::UnsupportedEvent);
+ }
+ return Ok(EventReference {
+ event_id,
+ event_name: EventName::Github,
+ source: EventSource::Github(Box::new(delivery.clone())),
+ });
+ }
};
Ok(EventReference {
event_id,
event_name,
- entity_id,
- message_id,
+ source: EventSource::Entity {
+ entity_id,
+ message_id,
+ },
})
}
}
diff --git a/crates/scheduled_action/src/domain/event_trigger/github_selector.rs b/crates/scheduled_action/src/domain/event_trigger/github_selector.rs
new file mode 100644
index 0000000000..729b00fed4
--- /dev/null
+++ b/crates/scheduled_action/src/domain/event_trigger/github_selector.rs
@@ -0,0 +1,157 @@
+//! Which deliveries from Macro's GitHub App a routine watches.
+
+use github::domain::models::GithubWebhookReceived;
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+
+#[cfg(test)]
+mod test;
+
+pub const MAX_GITHUB_NAMES: usize = 32;
+pub const MAX_GITHUB_REPOSITORIES: usize = 100;
+const MAX_NAME_CHARS: usize = 64;
+const MAX_FULL_NAME_CHARS: usize = 200;
+
+/// Narrows a GitHub event filter. Lists left empty match everything; the
+/// lists combine with AND.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
+#[serde(try_from = "GithubSelectorInput", into = "GithubSelectorInput")]
+pub struct GithubSelector {
+ events: Vec<String>,
+ actions: Vec<String>,
+ repositories: Vec<String>,
+ include_bots: bool,
+}
+
+/// Which GitHub deliveries match.
+#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+#[schema(as = GithubSelector)]
+pub struct GithubSelectorInput {
+ /// GitHub event names, such as `workflow_run` or `pull_request`; any when empty.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub events: Vec<String>,
+ /// Payload actions, such as `completed` or `opened`; any when empty.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub actions: Vec<String>,
+ /// Repositories as `owner/name`, matched without regard to case; every
+ /// repository the owner's installations cover when empty. A renamed
+ /// repository stops matching until it is chosen again.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub repositories: Vec<String>,
+ /// Also run for deliveries caused by bots and apps, including Macro's own.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub include_bots: bool,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum GithubSelectorError {
+ #[error(
+ "GitHub event and action names are 1 to 64 lowercase letters or underscores, at most 32 of each"
+ )]
+ Names,
+ #[error("expected at most 100 repositories, each named owner/name")]
+ Repositories,
+}
+
+/// `owner/name`, as GitHub names a repository.
+fn valid_full_name(name: &str) -> bool {
+ name.chars().count() <= MAX_FULL_NAME_CHARS
+ && name.matches('/').count() == 1
+ && !name.starts_with('/')
+ && !name.ends_with('/')
+ && !name.contains(char::is_whitespace)
+}
+
+/// GitHub's event and action names are snake_case words.
+fn valid_name(name: &str) -> bool {
+ !name.is_empty()
+ && name.len() <= MAX_NAME_CHARS
+ && name.chars().all(|c| c.is_ascii_lowercase() || c == '_')
+}
+
+fn names(mut names: Vec<String>) -> Result<Vec<String>, GithubSelectorError> {
+ if names.len() > MAX_GITHUB_NAMES || !names.iter().all(|name| valid_name(name)) {
+ return Err(GithubSelectorError::Names);
+ }
+ names.sort_unstable();
+ names.dedup();
+ Ok(names)
+}
+
+impl TryFrom<GithubSelectorInput> for GithubSelector {
+ type Error = GithubSelectorError;
+
+ fn try_from(input: GithubSelectorInput) -> Result<Self, Self::Error> {
+ if input.repositories.len() > MAX_GITHUB_REPOSITORIES
+ || !input.repositories.iter().all(|name| valid_full_name(name))
+ {
+ return Err(GithubSelectorError::Repositories);
+ }
+ let mut repositories: Vec<String> = input
+ .repositories
+ .iter()
+ .map(|name| name.to_lowercase())
+ .collect();
+ repositories.sort_unstable();
+ repositories.dedup();
+ Ok(Self {
+ events: names(input.events)?,
+ actions: names(input.actions)?,
+ repositories,
+ include_bots: input.include_bots,
+ })
+ }
+}
+
+impl From<GithubSelector> for GithubSelectorInput {
+ fn from(selector: GithubSelector) -> Self {
+ Self {
+ events: selector.events,
+ actions: selector.actions,
+ repositories: selector.repositories,
+ include_bots: selector.include_bots,
+ }
+ }
+}
+
+impl GithubSelector {
+ pub fn events(&self) -> &[String] {
+ &self.events
+ }
+
+ pub fn actions(&self) -> &[String] {
+ &self.actions
+ }
+
+ /// Lowercased `owner/name`s.
+ pub fn repositories(&self) -> &[String] {
+ &self.repositories
+ }
+
+ pub fn include_bots(&self) -> bool {
+ self.include_bots
+ }
+
+ /// Bots are left out unless asked for: a routine whose agent acts through
+ /// Macro's App would otherwise trigger itself.
+ pub fn accepts(&self, delivery: &GithubWebhookReceived) -> bool {
+ (self.events.is_empty() || self.events.contains(&delivery.event))
+ && (self.actions.is_empty()
+ || delivery
+ .action
+ .as_ref()
+ .is_some_and(|action| self.actions.contains(action)))
+ && (self.repositories.is_empty()
+ || delivery.repository.as_ref().is_some_and(|repository| {
+ self.repositories
+ .contains(&repository.full_name.to_lowercase())
+ }))
+ && (self.include_bots || !delivery.sender.as_ref().is_some_and(|sender| sender.bot))
+ }
+}
+
+/// Whether a delivery's event name can be stored and matched at all.
+pub fn valid_event_name(name: &str) -> bool {
+ valid_name(name)
+}
diff --git a/crates/scheduled_action/src/domain/event_trigger/github_selector/test.rs b/crates/scheduled_action/src/domain/event_trigger/github_selector/test.rs
new file mode 100644
index 0000000000..8d13233e4f
--- /dev/null
+++ b/crates/scheduled_action/src/domain/event_trigger/github_selector/test.rs
@@ -0,0 +1,94 @@
+use github::domain::models::{GithubWebhookRepository, GithubWebhookSender};
+use serde_json::{Value, json};
+
+use super::*;
+
+fn delivery(
+ event: &str,
+ action: Option<&str>,
+ repository: &str,
+ bot: bool,
+) -> GithubWebhookReceived {
+ GithubWebhookReceived {
+ delivery_id: Some("d".to_owned()),
+ event: event.to_owned(),
+ action: action.map(str::to_owned),
+ installation_id: 1,
+ repository: Some(GithubWebhookRepository {
+ id: 1,
+ full_name: repository.to_owned(),
+ }),
+ sender: Some(GithubWebhookSender {
+ login: if bot { "macro[bot]" } else { "octocat" }.to_owned(),
+ bot,
+ }),
+ payload: None,
+ }
+}
+
+fn selector(value: Value) -> GithubSelector {
+ serde_json::from_value(value).unwrap()
+}
+
+#[test]
+fn every_list_narrows_and_empty_lists_match_all() {
+ let completed_runs_in_one_repo = selector(json!({
+ "events": ["workflow_run"],
+ "actions": ["completed"],
+ "repositories": ["Macro-Inc/macro"],
+ }));
+
+ assert!(completed_runs_in_one_repo.accepts(&delivery(
+ "workflow_run",
+ Some("completed"),
+ "macro-inc/macro",
+ false
+ )));
+ assert!(!completed_runs_in_one_repo.accepts(&delivery(
+ "workflow_run",
+ Some("requested"),
+ "macro-inc/macro",
+ false
+ )));
+ assert!(!completed_runs_in_one_repo.accepts(&delivery(
+ "workflow_run",
+ Some("completed"),
+ "macro-inc/other",
+ false
+ )));
+ assert!(!completed_runs_in_one_repo.accepts(&delivery("push", None, "macro-inc/macro", false)));
+ assert!(selector(json!({})).accepts(&delivery("push", None, "macro-inc/macro", false)));
+}
+
+#[test]
+fn an_action_list_never_matches_an_event_without_actions() {
+ assert!(
+ !selector(json!({ "actions": ["opened"] })).accepts(&delivery(
+ "push",
+ None,
+ "macro-inc/macro",
+ false
+ ))
+ );
+}
+
+#[test]
+fn bots_run_a_routine_only_when_it_asks_for_them() {
+ let pushes = delivery("push", None, "macro-inc/macro", true);
+
+ assert!(!selector(json!({})).accepts(&pushes));
+ assert!(selector(json!({ "includeBots": true })).accepts(&pushes));
+}
+
+#[test]
+fn names_are_github_snake_case() {
+ let parse = |value: Value| serde_json::from_value::<GithubSelector>(value);
+
+ assert!(parse(json!({ "events": ["pull_request_review"] })).is_ok());
+ assert!(parse(json!({ "events": ["Pull-Request"] })).is_err());
+ assert!(parse(json!({ "actions": [""] })).is_err());
+ assert!(parse(json!({ "repositories": ["macro"] })).is_err());
+ assert!(parse(json!({ "repositories": ["macro-inc/macro/x"] })).is_err());
+ assert!(parse(json!({ "repositories": [" /macro"] })).is_err());
+ assert!(parse(json!({ "unknown": true })).is_err());
+}
diff --git a/crates/scheduled_action/src/domain/event_trigger/payload_match.rs b/crates/scheduled_action/src/domain/event_trigger/payload_match.rs
new file mode 100644
index 0000000000..2e2e8fef1b
--- /dev/null
+++ b/crates/scheduled_action/src/domain/event_trigger/payload_match.rs
@@ -0,0 +1,320 @@
+//! Exact tests on a delivery's JSON payload, such as "this workflow's
+//! conclusion is failure". They run for free at admission, before a run is
+//! queued or a condition is asked, so a busy source costs nothing until one
+//! of its deliveries matches.
+
+use std::cmp::Ordering;
+
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use utoipa::ToSchema;
+
+#[cfg(test)]
+mod test;
+
+pub const MAX_PAYLOAD_CONDITIONS: usize = 16;
+pub const MAX_PATH_SEGMENTS: usize = 16;
+pub const MAX_SEGMENT_CHARS: usize = 128;
+pub const MAX_VALUES: usize = 50;
+pub const MAX_VALUE_CHARS: usize = 500;
+
+/// Every listed test must pass. A payload that is absent, as for a GitHub
+/// delivery too large to carry, passes none.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
+#[serde(try_from = "Vec<PayloadCondition>", into = "Vec<PayloadCondition>")]
+pub struct PayloadConditions(Vec<PayloadCondition>);
+
+impl TryFrom<Vec<PayloadCondition>> for PayloadConditions {
+ type Error = PayloadMatchError;
+
+ fn try_from(mut conditions: Vec<PayloadCondition>) -> Result<Self, Self::Error> {
+ if conditions.is_empty() || conditions.len() > MAX_PAYLOAD_CONDITIONS {
+ return Err(PayloadMatchError::ConditionCount);
+ }
+ conditions.sort_unstable();
+ conditions.dedup();
+ Ok(Self(conditions))
+ }
+}
+
+impl From<PayloadConditions> for Vec<PayloadCondition> {
+ fn from(conditions: PayloadConditions) -> Self {
+ conditions.0
+ }
+}
+
+impl PayloadConditions {
+ pub fn as_slice(&self) -> &[PayloadCondition] {
+ &self.0
+ }
+
+ pub fn matches(&self, payload: Option<&Value>) -> bool {
+ payload.is_some_and(|payload| self.0.iter().all(|condition| condition.matches(payload)))
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum PayloadMatchError {
+ #[error("expected between 1 and 16 payload tests")]
+ ConditionCount,
+ #[error("a payload path needs 1 to 16 nonblank segments of at most 128 characters")]
+ Path,
+ #[error("each payload test takes exactly one of equals, in, notIn, glob or exists")]
+ Test,
+ #[error("payload test values must be text, numbers, booleans or null, at most 50 of them")]
+ Values,
+ #[error("invalid glob pattern")]
+ Glob,
+}
+
+/// One test on the values found at `path`.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
+#[serde(try_from = "PayloadConditionInput", into = "PayloadConditionInput")]
+pub struct PayloadCondition {
+ path: Vec<PathSegment>,
+ test: PayloadTest,
+}
+
+/// `path` walks objects by key; `*` steps into every element of an array and
+/// a number into one. Give exactly one test. `notIn` also passes when the
+/// path finds nothing.
+#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+#[schema(as = PayloadCondition)]
+pub struct PayloadConditionInput {
+ /// Keys from the payload's root, e.g. `["workflow_run", "conclusion"]`.
+ pub path: Vec<String>,
+ /// Some value found equals this.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub equals: Option<PayloadScalar>,
+ /// Some value found is one of these.
+ #[serde(default, rename = "in", skip_serializing_if = "Option::is_none")]
+ pub one_of: Option<Vec<PayloadScalar>>,
+ /// No value found is one of these.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub not_in: Option<Vec<PayloadScalar>>,
+ /// Some text found matches this glob; `*` matches any run of characters.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub glob: Option<String>,
+ /// Whether the path finds a non-null value.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub exists: Option<bool>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
+enum PathSegment {
+ Key(String),
+ Index(usize),
+ Every,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
+enum PayloadTest {
+ Equals(PayloadScalar),
+ In(Vec<PayloadScalar>),
+ NotIn(Vec<PayloadScalar>),
+ Glob(glob::Pattern),
+ Exists(bool),
+}
+
+/// A JSON text, number, boolean or null that payload values are compared with.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
+#[serde(untagged)]
+pub enum PayloadScalar {
+ Null,
+ Boolean(bool),
+ #[schema(value_type = f64)]
+ Number(serde_json::Number),
+ Text(String),
+}
+
+impl PayloadScalar {
+ fn value(&self) -> Value {
+ match self {
+ Self::Null => Value::Null,
+ Self::Boolean(value) => Value::Bool(*value),
+ Self::Number(number) => Value::Number(number.clone()),
+ Self::Text(text) => Value::String(text.clone()),
+ }
+ }
+}
+
+/// Ordered by JSON text, so filters canonicalize.
+impl Ord for PayloadScalar {
+ fn cmp(&self, other: &Self) -> Ordering {
+ self.value().to_string().cmp(&other.value().to_string())
+ }
+}
+
+impl PartialOrd for PayloadScalar {
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+ Some(self.cmp(other))
+ }
+}
+
+fn scalar(value: PayloadScalar) -> Result<PayloadScalar, PayloadMatchError> {
+ match &value {
+ PayloadScalar::Text(text) if text.chars().count() > MAX_VALUE_CHARS => {
+ Err(PayloadMatchError::Values)
+ }
+ _ => Ok(value),
+ }
+}
+
+fn scalars(values: Vec<PayloadScalar>) -> Result<Vec<PayloadScalar>, PayloadMatchError> {
+ if values.is_empty() || values.len() > MAX_VALUES {
+ return Err(PayloadMatchError::Values);
+ }
+ let mut scalars = values
+ .into_iter()
+ .map(scalar)
+ .collect::<Result<Vec<_>, _>>()?;
+ scalars.sort_unstable();
+ scalars.dedup();
+ Ok(scalars)
+}
+
+impl TryFrom<String> for PathSegment {
+ type Error = PayloadMatchError;
+
+ fn try_from(segment: String) -> Result<Self, Self::Error> {
+ if segment.trim().is_empty() || segment.chars().count() > MAX_SEGMENT_CHARS {
+ return Err(PayloadMatchError::Path);
+ }
+ Ok(if segment == "*" {
+ Self::Every
+ } else if let Ok(index) = segment.parse::<usize>() {
+ Self::Index(index)
+ } else {
+ Self::Key(segment)
+ })
+ }
+}
+
+impl From<&PathSegment> for String {
+ fn from(segment: &PathSegment) -> Self {
+ match segment {
+ PathSegment::Key(key) => key.clone(),
+ PathSegment::Index(index) => index.to_string(),
+ PathSegment::Every => "*".to_owned(),
+ }
+ }
+}
+
+impl TryFrom<PayloadConditionInput> for PayloadCondition {
+ type Error = PayloadMatchError;
+
+ fn try_from(input: PayloadConditionInput) -> Result<Self, Self::Error> {
+ if input.path.is_empty() || input.path.len() > MAX_PATH_SEGMENTS {
+ return Err(PayloadMatchError::Path);
+ }
+ let path = input
+ .path
+ .into_iter()
+ .map(PathSegment::try_from)
+ .collect::<Result<Vec<_>, _>>()?;
+ let test = match (
+ input.equals,
+ input.one_of,
+ input.not_in,
+ input.glob,
+ input.exists,
+ ) {
+ (Some(value), None, None, None, None) => PayloadTest::Equals(scalar(value)?),
+ (None, Some(values), None, None, None) => PayloadTest::In(scalars(values)?),
+ (None, None, Some(values), None, None) => PayloadTest::NotIn(scalars(values)?),
+ (None, None, None, Some(pattern), None) => {
+ if pattern.chars().count() > MAX_VALUE_CHARS {
+ return Err(PayloadMatchError::Glob);
+ }
+ PayloadTest::Glob(
+ glob::Pattern::new(&pattern).map_err(|_| PayloadMatchError::Glob)?,
+ )
+ }
+ (None, None, None, None, Some(exists)) => PayloadTest::Exists(exists),
+ _ => return Err(PayloadMatchError::Test),
+ };
+ Ok(Self { path, test })
+ }
+}
+
+impl From<PayloadCondition> for PayloadConditionInput {
+ fn from(condition: PayloadCondition) -> Self {
+ let path = condition.path.iter().map(String::from).collect();
+ let values = Some;
+ let mut input = Self {
+ path,
+ ..Self::default()
+ };
+ match condition.test {
+ PayloadTest::Equals(value) => input.equals = Some(value),
+ PayloadTest::In(scalars) => input.one_of = values(scalars),
+ PayloadTest::NotIn(scalars) => input.not_in = values(scalars),
+ PayloadTest::Glob(pattern) => input.glob = Some(pattern.as_str().to_owned()),
+ PayloadTest::Exists(exists) => input.exists = Some(exists),
+ }
+ input
+ }
+}
+
+impl PayloadCondition {
+ fn matches(&self, payload: &Value) -> bool {
+ let mut found = vec![payload];
+ for segment in &self.path {
+ found = found
+ .into_iter()
+ .flat_map(|value| step(value, segment))
+ .collect();
+ }
+ match &self.test {
+ PayloadTest::Equals(expected) => found.iter().any(|value| **value == expected.value()),
+ PayloadTest::In(expected) => found
+ .iter()
+ .any(|value| expected.iter().any(|scalar| scalar.value() == **value)),
+ PayloadTest::NotIn(excluded) => !found
+ .iter()
+ .any(|value| excluded.iter().any(|scalar| scalar.value() == **value)),
+ PayloadTest::Glob(pattern) => found
+ .iter()
+ .any(|value| value.as_str().is_some_and(|text| pattern.matches(text))),
+ PayloadTest::Exists(exists) => found.iter().any(|value| !value.is_null()) == *exists,
+ }
+ }
+
+ /// How a reader would state the test, e.g. `workflow_run.conclusion in ["failure"]`.
+ pub fn describe(&self) -> String {
+ let path = self
+ .path
+ .iter()
+ .map(String::from)
+ .collect::<Vec<_>>()
+ .join(".");
+ let list = |scalars: &[PayloadScalar]| {
+ let values = scalars
+ .iter()
+ .map(|s| s.value().to_string())
+ .collect::<Vec<_>>();
+ format!("[{}]", values.join(", "))
+ };
+ match &self.test {
+ PayloadTest::Equals(value) => format!("{path} = {}", value.value()),
+ PayloadTest::In(scalars) => format!("{path} in {}", list(scalars)),
+ PayloadTest::NotIn(scalars) => format!("{path} not in {}", list(scalars)),
+ PayloadTest::Glob(pattern) => format!("{path} matches {}", pattern.as_str()),
+ PayloadTest::Exists(true) => format!("{path} is set"),
+ PayloadTest::Exists(false) => format!("{path} is not set"),
+ }
+ }
+}
+
+fn step<'a>(value: &'a Value, segment: &PathSegment) -> Vec<&'a Value> {
+ match (value, segment) {
+ (Value::Object(fields), PathSegment::Key(key)) => fields.get(key).into_iter().collect(),
+ (Value::Object(fields), PathSegment::Index(index)) => {
+ fields.get(&index.to_string()).into_iter().collect()
+ }
+ (Value::Array(items), PathSegment::Index(index)) => items.get(*index).into_iter().collect(),
+ (Value::Array(items), PathSegment::Every) => items.iter().collect(),
+ _ => Vec::new(),
+ }
+}
diff --git a/crates/scheduled_action/src/domain/event_trigger/payload_match/test.rs b/crates/scheduled_action/src/domain/event_trigger/payload_match/test.rs
new file mode 100644
index 0000000000..08bf302226
--- /dev/null
+++ b/crates/scheduled_action/src/domain/event_trigger/payload_match/test.rs
@@ -0,0 +1,151 @@
+use serde_json::{Value, json};
+
+use super::*;
+
+fn conditions(value: Value) -> PayloadConditions {
+ serde_json::from_value(value).unwrap()
+}
+
+fn workflow_run(name: &str, branch: &str, conclusion: Value) -> Value {
+ json!({
+ "action": "completed",
+ "workflow_run": {
+ "name": name,
+ "head_branch": branch,
+ "conclusion": conclusion,
+ "pull_requests": [{ "number": 7 }, { "number": 9 }],
+ }
+ })
+}
+
+#[test]
+fn a_specific_workflow_failing_on_release_branches_matches_only_that() {
+ let failed_ci_on_release = conditions(json!([
+ { "path": ["workflow_run", "name"], "equals": "CI" },
+ { "path": ["workflow_run", "head_branch"], "glob": "release/*" },
+ { "path": ["workflow_run", "conclusion"], "in": ["failure", "timed_out"] },
+ ]));
+
+ let matches = |payload: Value| failed_ci_on_release.matches(Some(&payload));
+ assert!(matches(workflow_run("CI", "release/2.1", json!("failure"))));
+ assert!(matches(workflow_run(
+ "CI",
+ "release/2.1",
+ json!("timed_out")
+ )));
+ assert!(!matches(workflow_run(
+ "CI",
+ "release/2.1",
+ json!("success")
+ )));
+ assert!(!matches(workflow_run(
+ "Lint",
+ "release/2.1",
+ json!("failure")
+ )));
+ assert!(!matches(workflow_run("CI", "main", json!("failure"))));
+}
+
+#[test]
+fn not_in_passes_when_no_value_is_listed_including_none_at_all() {
+ let not_success = conditions(json!([
+ { "path": ["workflow_run", "conclusion"], "notIn": ["success"] },
+ ]));
+
+ assert!(not_success.matches(Some(&workflow_run("CI", "main", json!("failure")))));
+ assert!(not_success.matches(Some(&workflow_run("CI", "main", Value::Null))));
+ assert!(not_success.matches(Some(&json!({}))));
+ assert!(!not_success.matches(Some(&workflow_run("CI", "main", json!("success")))));
+}
+
+#[test]
+fn every_element_step_matches_any_array_item() {
+ let labelled_bug = conditions(json!([
+ { "path": ["pull_request", "labels", "*", "name"], "equals": "bug" },
+ ]));
+ let pr = |labels: Value| json!({ "pull_request": { "labels": labels } });
+
+ assert!(labelled_bug.matches(Some(&pr(json!([{ "name": "ui" }, { "name": "bug" }])))));
+ assert!(!labelled_bug.matches(Some(&pr(json!([{ "name": "ui" }])))));
+ assert!(!labelled_bug.matches(Some(&pr(json!([])))));
+}
+
+#[test]
+fn index_step_reads_one_element() {
+ let first_pr = conditions(json!([
+ { "path": ["workflow_run", "pull_requests", "0", "number"], "equals": 7 },
+ ]));
+
+ assert!(first_pr.matches(Some(&workflow_run("CI", "main", json!("failure")))));
+}
+
+#[test]
+fn exists_treats_null_as_absent() {
+ let concluded = conditions(json!([
+ { "path": ["workflow_run", "conclusion"], "exists": true },
+ ]));
+ let running = conditions(json!([
+ { "path": ["workflow_run", "conclusion"], "exists": false },
+ ]));
+ let in_progress = workflow_run("CI", "main", Value::Null);
+
+ assert!(!concluded.matches(Some(&in_progress)));
+ assert!(running.matches(Some(&in_progress)));
+ assert!(concluded.matches(Some(&workflow_run("CI", "main", json!("success")))));
+}
+
+#[test]
+fn an_absent_payload_matches_nothing() {
+ let not_success = conditions(json!([
+ { "path": ["workflow_run", "conclusion"], "notIn": ["success"] },
+ ]));
+
+ assert!(!not_success.matches(None));
+}
+
+#[test]
+fn a_test_needs_exactly_one_comparison_and_scalar_values() {
+ let parse = |value: Value| serde_json::from_value::<PayloadConditions>(value);
+
+ assert!(parse(json!([{ "path": ["a"] }])).is_err());
+ assert!(parse(json!([{ "path": ["a"], "equals": 1, "exists": true }])).is_err());
+ assert!(parse(json!([{ "path": ["a"], "equals": { "b": 1 } }])).is_err());
+ assert!(parse(json!([{ "path": ["a"], "in": [] }])).is_err());
+ assert!(parse(json!([{ "path": [], "equals": 1 }])).is_err());
+ assert!(parse(json!([{ "path": [" "], "equals": 1 }])).is_err());
+ assert!(parse(json!([{ "path": ["a"], "glob": "[" }])).is_err());
+ assert!(parse(json!([])).is_err());
+}
+
+#[test]
+fn conditions_round_trip_in_canonical_order() {
+ let parsed = conditions(json!([
+ { "path": ["b"], "in": ["y", "x", "x"] },
+ { "path": ["a"], "equals": true },
+ ]));
+
+ assert_eq!(
+ serde_json::to_value(&parsed).unwrap(),
+ json!([
+ { "path": ["a"], "equals": true },
+ { "path": ["b"], "in": ["x", "y"] },
+ ])
+ );
+}
+
+#[test]
+fn descriptions_read_as_the_test() {
+ let parsed = conditions(json!([
+ { "path": ["workflow_run", "conclusion"], "in": ["failure"] },
+ { "path": ["ref"], "glob": "refs/heads/*" },
+ ]));
+ let described: Vec<String> = parsed.as_slice().iter().map(|c| c.describe()).collect();
+
+ assert_eq!(
+ described,
+ vec![
+ "ref matches refs/heads/*",
+ "workflow_run.conclusion in [\"failure\"]",
+ ]
+ );
+}
diff --git a/crates/scheduled_action/src/domain/event_trigger/test.rs b/crates/scheduled_action/src/domain/event_trigger/test.rs
index 4394fa8b14..fd2f019155 100644
--- a/crates/scheduled_action/src/domain/event_trigger/test.rs
+++ b/crates/scheduled_action/src/domain/event_trigger/test.rs
@@ -108,7 +108,7 @@ fn all_allowlisted_human_events_normalize_to_minimal_context() {
] {
let event = incoming(name, metadata()).normalize().unwrap();
assert_eq!(event.event_name().as_str(), name);
- assert_eq!(event.entity_id().to_string(), ENTITY_ID);
+ assert_eq!(event.entity_id().unwrap().to_string(), ENTITY_ID);
assert_eq!(
event.message_id().is_some(),
name.starts_with("channel.") && name != "channel.created"
@@ -497,11 +497,11 @@ fn task_changes_match_specific_and_any_property_selectors() {
let event = property_event(source, data.clone()).normalize().unwrap();
assert_eq!(event.event_name(), name);
let any = EventFilter::new(vec![EventName::TaskPropertyChanged], None).unwrap();
- assert!(any.accepts(event.event_name(), event.entity_id()));
+ assert!(any.accepts(&event));
let other_task =
EventFilter::new(vec![name], Some(vec![Uuid::parse_str(OTHER_ID).unwrap()]))
.unwrap();
- assert!(!other_task.accepts(name, event.entity_id()));
+ assert!(!other_task.accepts(&event));
let stored = serde_json::to_value(&event).unwrap();
assert_eq!(stored.as_object().unwrap().len(), 4);
assert_eq!(
@@ -584,7 +584,7 @@ fn started_calls_keep_only_ids_and_belong_to_who_created_them() {
let normalized = event.normalize().unwrap();
assert_eq!(normalized.event_name(), EventName::CallStarted);
assert_eq!(normalized.entity_type(), EventEntityType::Call);
- assert_eq!(normalized.entity_id().to_string(), ENTITY_ID);
+ assert_eq!(normalized.entity_id().unwrap().to_string(), ENTITY_ID);
assert_eq!(normalized.message_id(), None);
let stored = serde_json::to_string(&normalized).unwrap();
assert!(!stored.contains("example.com"));
@@ -602,7 +602,7 @@ fn ended_calls_keep_only_ids_and_belong_to_the_people_who_joined() {
let normalized = event.normalize().unwrap();
assert_eq!(normalized.event_name(), EventName::CallEnded);
assert_eq!(normalized.entity_type(), EventEntityType::Call);
- assert_eq!(normalized.entity_id().to_string(), ENTITY_ID);
+ assert_eq!(normalized.entity_id().unwrap().to_string(), ENTITY_ID);
assert_eq!(normalized.message_id(), None);
let stored = serde_json::to_string(&normalized).unwrap();
assert!(!stored.contains("example.com"));
@@ -667,3 +667,62 @@ fn email_receipts_keep_only_ids_and_exclude_spam_and_backfills() {
));
assert_eq!(event.normalize(), Err(EventRejection::UnsupportedEvent));
}
+
+#[test]
+fn github_stands_alone_and_only_it_takes_a_payload_match() {
+ let parse = |filter: serde_json::Value| serde_json::from_value::<EventFilter>(filter);
+
+ assert!(parse(json!({ "events": ["github"], "github": {} })).is_ok());
+ assert!(
+ parse(json!({
+ "events": ["github"],
+ "github": {},
+ "match": [{ "path": ["status"], "equals": "failed" }],
+ }))
+ .is_ok()
+ );
+ // Generic webhooks are not a trigger.
+ assert!(parse(json!({ "events": ["webhook.received"] })).is_err());
+ // A github filter names which deliveries; nothing else takes a selector.
+ assert!(parse(json!({ "events": ["github"] })).is_err());
+ // GitHub does not combine with Macro events or entity ids.
+ assert!(parse(json!({ "events": ["github", "document.created"], "github": {} })).is_err());
+ assert!(parse(json!({ "events": ["github"], "github": {}, "ids": [] })).is_err());
+ // Macro events are read again at dispatch; they have no payload to match.
+ assert!(
+ parse(json!({
+ "events": ["document.created"],
+ "match": [{ "path": ["name"], "equals": "x" }],
+ }))
+ .is_err()
+ );
+}
+
+#[test]
+fn github_deliveries_normalize_with_their_payload_and_reject_odd_names() {
+ let incoming = |event: &str| IncomingEvent {
+ event_id: macro_uuid::generate_uuid_v7(),
+ schema_version: 1,
+ payload: EventPayload::Github(github::broker::GithubWebhookTopicEvent::Received(
+ serde_json::from_value(json!({
+ "event": event,
+ "installation_id": 5,
+ "payload": { "ref": "refs/heads/main" },
+ }))
+ .unwrap(),
+ )),
+ };
+
+ let event = incoming("push").normalize().unwrap();
+ assert_eq!(event.event_name(), EventName::Github);
+ assert_eq!(event.entity_id(), None);
+ let stored = serde_json::to_value(&event).unwrap();
+ assert_eq!(
+ serde_json::from_value::<EventReference>(stored).unwrap(),
+ event
+ );
+ assert_eq!(
+ incoming("Not-An-Event").normalize(),
+ Err(EventRejection::UnsupportedEvent)
+ );
+}
diff --git a/crates/scheduled_action/src/domain/models.rs b/crates/scheduled_action/src/domain/models.rs
index cc842a8674..eebbab674a 100644
--- a/crates/scheduled_action/src/domain/models.rs
+++ b/crates/scheduled_action/src/domain/models.rs
@@ -313,6 +313,8 @@ pub enum ActionPolicyError {
EventManagementDisabled,
#[error("trigger conditions are not enabled")]
ConditionsDisabled,
+ #[error("connect GitHub before enabling a GitHub trigger")]
+ GithubNotLinked,
#[error("scheduled action changed or is running; reload before updating")]
UpdateConflict,
}
diff --git a/crates/scheduled_action/src/domain/service.rs b/crates/scheduled_action/src/domain/service.rs
index 20b409878e..9b80d08397 100644
--- a/crates/scheduled_action/src/domain/service.rs
+++ b/crates/scheduled_action/src/domain/service.rs
@@ -10,6 +10,7 @@ use entity_access::domain::{
ports::ScheduledActionGrants,
};
use entity_registry::OwnedPurgeOutcome;
+use github::domain::{models::GithubError, ports::GithubInstallationClaims};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use model_owner::{CreationPrincipal, Owner};
@@ -29,7 +30,13 @@ use super::target_validation::{ModelOnlyTargets, require_explicit_selection};
#[cfg(test)]
pub(crate) mod test;
-pub struct ScheduledActionServiceImpl<Rpo, Exe, Grants, Targets = ModelOnlyTargets> {
+pub struct ScheduledActionServiceImpl<
+ Rpo,
+ Exe,
+ Grants,
+ Targets = ModelOnlyTargets,
+ Github = NoGithubLinks,
+> {
repo: Arc<Rpo>,
executor: Arc<Exe>,
grants: Arc<Grants>,
@@ -37,6 +44,25 @@ pub struct ScheduledActionServiceImpl<Rpo, Exe, Grants, Targets = ModelOnlyTarge
event_management_enabled: bool,
conditions_enabled: bool,
targets: Targets,
+ github: Github,
+}
+
+/// Composition without GitHub: no owner counts as linked, so GitHub triggers
+/// cannot be enabled.
+pub struct NoGithubLinks;
+
+impl GithubInstallationClaims for NoGithubLinks {
+ async fn is_linked(&self, _user: &MacroUserIdStr<'_>) -> Result<bool, GithubError> {
+ Ok(false)
+ }
+
+ async fn has_claim(
+ &self,
+ _user: &MacroUserIdStr<'_>,
+ _installation_id: u64,
+ ) -> Result<bool, GithubError> {
+ Ok(false)
+ }
}
impl<Rpo: ScheduledActionRepo, Exe, Grants> ScheduledActionServiceImpl<Rpo, Exe, Grants> {
@@ -55,17 +81,18 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants> ScheduledActionServiceImpl<Rpo, Exe,
event_management_enabled: false,
conditions_enabled: false,
targets: ModelOnlyTargets,
+ github: NoGithubLinks,
}
}
}
-impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>
- ScheduledActionServiceImpl<Rpo, Exe, Grants, Targets>
+impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets, Github>
+ ScheduledActionServiceImpl<Rpo, Exe, Grants, Targets, Github>
{
pub fn with_target_validation<T: TaskTargetValidator>(
self,
targets: T,
- ) -> ScheduledActionServiceImpl<Rpo, Exe, Grants, T> {
+ ) -> ScheduledActionServiceImpl<Rpo, Exe, Grants, T, Github> {
ScheduledActionServiceImpl {
repo: self.repo,
executor: self.executor,
@@ -74,6 +101,24 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>
event_management_enabled: self.event_management_enabled,
conditions_enabled: self.conditions_enabled,
targets,
+ github: self.github,
+ }
+ }
+
+ /// Lets owners with a linked GitHub account enable GitHub triggers.
+ pub fn with_github_links<G: GithubInstallationClaims>(
+ self,
+ github: G,
+ ) -> ScheduledActionServiceImpl<Rpo, Exe, Grants, Targets, G> {
+ ScheduledActionServiceImpl {
+ repo: self.repo,
+ executor: self.executor,
+ grants: self.grants,
+ dispatcher_tx: self.dispatcher_tx,
+ event_management_enabled: self.event_management_enabled,
+ conditions_enabled: self.conditions_enabled,
+ targets: self.targets,
+ github,
}
}
@@ -92,22 +137,7 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>
&self,
receipt: &EntityAccessReceipt<T>,
) -> Result<ScheduledAction> {
- if receipt.entity().entity_type != EntityType::ScheduledAction {
- bail!("scheduled action receipt has the wrong entity type");
- }
- let Ok(id) = receipt.entity().entity_id.parse::<Uuid>() else {
- bail!("scheduled action receipt id is not a uuid");
- };
- match self.repo.get_action(&id).await? {
- Some(action)
- if receipt
- .acting_user_id()
- .is_some_and(|user| action.owner.is_user(user)) =>
- {
- Ok(action)
- }
- _ => Err(ActionPolicyError::NotFound.into()),
- }
+ granted_action(self.repo.as_ref(), receipt).await
}
/// Delete `action` and hand its removal to the dispatcher. The permit is
@@ -146,6 +176,7 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>
) -> Result<ScheduledAction>
where
Targets: TaskTargetValidator,
+ Github: GithubInstallationClaims,
{
let owner = principal.owner();
let owner_user = owner.as_user().ok_or(OwnerNotUserError {
@@ -155,6 +186,9 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>
self.check_event_management(&input.trigger)?;
self.check_conditions(&input.trigger)?;
self.targets.validate_task(&input.task, owner_user).await?;
+ if input.enabled {
+ self.check_github(&input.trigger, owner_user).await?;
+ }
let now = Utc::now();
let next_run_at = next_run(&input.trigger)?;
let event_activated_at = input.trigger.event_filters().is_some().then_some(now);
@@ -185,6 +219,21 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>
Ok(created)
}
+ /// An enabled GitHub trigger needs its owner to have linked GitHub.
+ async fn check_github(&self, trigger: &ActionTrigger, owner: &MacroUserIdStr<'_>) -> Result<()>
+ where
+ Github: GithubInstallationClaims,
+ {
+ if trigger
+ .event_filters()
+ .is_some_and(|filters| filters.watches_github())
+ && !self.github.is_linked(owner).await?
+ {
+ return Err(ActionPolicyError::GithubNotLinked.into());
+ }
+ Ok(())
+ }
+
async fn replace_configuration(
&self,
mut action: ScheduledAction,
@@ -192,6 +241,7 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>
) -> Result<ScheduledAction>
where
Targets: TaskTargetValidator,
+ Github: GithubInstallationClaims,
{
require_explicit_selection(&action.task, &input.task)?;
let trigger_changed = !same_trigger(&action.trigger, &input.trigger);
@@ -216,6 +266,10 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>
self.targets
.validate_task(&input.task, action.owner_user()?)
.await?;
+ if input.enabled {
+ self.check_github(&input.trigger, action.owner_user()?)
+ .await?;
+ }
if trigger_changed || (!action.enabled && input.enabled) {
action.next_run_at = next_run(&input.trigger)?;
}
@@ -247,6 +301,29 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>
}
}
+/// The routine a receipt names, when the receipt's user owns it.
+pub(crate) async fn granted_action<R: ScheduledActionRepo, T: RequiredPermission>(
+ repo: &R,
+ receipt: &EntityAccessReceipt<T>,
+) -> Result<ScheduledAction> {
+ if receipt.entity().entity_type != EntityType::ScheduledAction {
+ bail!("scheduled action receipt has the wrong entity type");
+ }
+ let Ok(id) = receipt.entity().entity_id.parse::<Uuid>() else {
+ bail!("scheduled action receipt id is not a uuid");
+ };
+ match repo.get_action(&id).await? {
+ Some(action)
+ if receipt
+ .acting_user_id()
+ .is_some_and(|user| action.owner.is_user(user)) =>
+ {
+ Ok(action)
+ }
+ _ => Err(ActionPolicyError::NotFound.into()),
+ }
+}
+
fn next_run(trigger: &ActionTrigger) -> Result<Option<DateTime<Utc>>> {
let next = trigger.next_run_after(Utc::now());
if trigger.has_schedule() && next.is_none() && trigger.event_filters().is_none() {
@@ -291,9 +368,10 @@ fn same_trigger(left: &ActionTrigger, right: &ActionTrigger) -> bool {
left == right
}
-impl<Rpo, Exe, Grants, Targets> ScheduledActionService
- for ScheduledActionServiceImpl<Rpo, Exe, Grants, Targets>
+impl<Rpo, Exe, Grants, Targets, Github> ScheduledActionService
+ for ScheduledActionServiceImpl<Rpo, Exe, Grants, Targets, Github>
where
+ Github: GithubInstallationClaims,
Rpo: ScheduledActionRepo,
Grants: ScheduledActionGrants,
Targets: TaskTargetValidator,
diff --git a/crates/scheduled_action/src/domain/service/test.rs b/crates/scheduled_action/src/domain/service/test.rs
index 91c2a29f08..eff6e6f9ab 100644
--- a/crates/scheduled_action/src/domain/service/test.rs
+++ b/crates/scheduled_action/src/domain/service/test.rs
@@ -1399,3 +1399,84 @@ fn conditions_are_trimmed_bounded_and_round_trip() {
json!([{"events": ["document.created"]}])
);
}
+
+/// Whether the owner has linked GitHub.
+struct Linked(bool);
+impl github::domain::ports::GithubInstallationClaims for Linked {
+ async fn is_linked(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ ) -> Result<bool, github::domain::models::GithubError> {
+ Ok(self.0)
+ }
+
+ async fn has_claim(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ _: u64,
+ ) -> Result<bool, github::domain::models::GithubError> {
+ Ok(self.0)
+ }
+}
+
+fn github_configuration(enabled: bool) -> ActionConfiguration {
+ ActionConfiguration {
+ trigger: serde_json::from_value(json!({
+ "type": "events",
+ "filters": [{"events": ["github"], "github": {"events": ["workflow_run"]}}]
+ }))
+ .unwrap(),
+ enabled,
+ ..configuration(true)
+ }
+}
+
+#[tokio::test]
+async fn a_github_trigger_runs_only_once_github_is_linked() {
+ let unlinked = service(true);
+ assert_policy(
+ unlinked
+ .create_action(
+ &user_principal(),
+ CreateScheduledAction::Canonical(github_configuration(true)),
+ )
+ .await,
+ ActionPolicyError::GithubNotLinked,
+ );
+ // A paused GitHub routine can still be drafted and edited, but not resumed.
+ let paused = unlinked
+ .create_action(
+ &user_principal(),
+ CreateScheduledAction::Canonical(github_configuration(false)),
+ )
+ .await
+ .unwrap();
+ let id = paused.id.unwrap();
+ assert_policy(
+ unlinked.set_enabled(edit_receipt(id), true).await,
+ ActionPolicyError::GithubNotLinked,
+ );
+
+ let linked = TestService::new(
+ unlinked.repo.clone(),
+ unlinked.executor.clone(),
+ unlinked.dispatcher_tx.clone(),
+ grants(&unlinked.repo),
+ )
+ .with_event_management_enabled(true)
+ .with_github_links(Linked(true));
+ assert!(
+ linked
+ .set_enabled(edit_receipt(id), true)
+ .await
+ .unwrap()
+ .enabled
+ );
+ linked
+ .create_action(
+ &user_principal(),
+ CreateScheduledAction::Canonical(github_configuration(true)),
+ )
+ .await
+ .unwrap();
+}
diff --git a/crates/scheduled_action/src/domain/target_runner.rs b/crates/scheduled_action/src/domain/target_runner.rs
index 6a348900ed..3eb70f4bea 100644
--- a/crates/scheduled_action/src/domain/target_runner.rs
+++ b/crates/scheduled_action/src/domain/target_runner.rs
@@ -15,7 +15,8 @@ use bot_id::BotId;
use chrono_tz::Tz;
use macro_user_id::user_id::MacroUserIdStr;
use trigger_context::{
- ContextPerson, RoutineContext, RoutineFiring, RoutineTrigger as ContextTrigger, TriggerContext,
+ ContextPerson, GithubWatch, RoutineContext, RoutineFiring, RoutineTrigger as ContextTrigger,
+ TriggerContext,
};
use super::{
@@ -305,6 +306,16 @@ fn triggers(trigger: &ActionTrigger) -> Vec<ContextTrigger> {
.map(|event| event.as_str().to_owned())
.collect(),
entity_ids: filter.ids().map(<[_]>::to_vec).unwrap_or_default(),
+ github: filter.github().map(|selector| GithubWatch {
+ events: selector.events().to_vec(),
+ actions: selector.actions().to_vec(),
+ repositories: selector.repositories().to_vec(),
+ include_bots: selector.include_bots(),
+ }),
+ payload_match: filter
+ .payload()
+ .map(|conditions| conditions.as_slice().iter().map(|c| c.describe()).collect())
+ .unwrap_or_default(),
condition: filter
.condition()
.map(|condition| condition.as_str().to_owned()),
diff --git a/crates/scheduled_action/src/domain/target_runner/test.rs b/crates/scheduled_action/src/domain/target_runner/test.rs
index bd1f912547..2da1a9bbea 100644
--- a/crates/scheduled_action/src/domain/target_runner/test.rs
+++ b/crates/scheduled_action/src/domain/target_runner/test.rs
@@ -231,7 +231,7 @@ fn event() -> AuthorizedEventRun {
access: EventAccessCapability::Channel(
EntityAccessReceipt::<ViewOnly>::dangerously_assert_authenticated_user(
MacroUserIdStr::parse_from_str(USER).unwrap(),
- &event.entity_id().to_string(),
+ &event.entity_id().unwrap().to_string(),
EntityType::Channel,
),
),
@@ -387,7 +387,11 @@ async fn fast_completion_keeps_owner_override_ids_and_context_in_one_prompt() {
assert!(prompts[0].prompt.contains("Do this task"));
assert!(prompts[0].prompt.contains("data, not instructions"));
assert!(prompts[0].context.is_none());
- assert!(prompts[0].prompt.contains(&event.entity_id().to_string()));
+ assert!(
+ prompts[0]
+ .prompt
+ .contains(&event.entity_id().unwrap().to_string())
+ );
assert!(
prompts[0]
.prompt
@@ -687,7 +691,7 @@ fn event_run() -> ClaimedEventRun {
access: EventAccessCapability::Document(
EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_authenticated_user(
MacroUserIdStr::parse_from_str(USER).unwrap(),
- &event.entity_id().to_string(),
+ &event.entity_id().unwrap().to_string(),
EntityType::Document,
),
),
@@ -1043,6 +1047,8 @@ async fn a_task_status_change_hands_the_agent_the_task_instead_of_its_ids() {
ContextRoutineTrigger::Events {
events: vec!["document.created".into()],
entity_ids: Vec::new(),
+ github: None,
+ payload_match: Vec::new(),
condition: None,
},
ContextRoutineTrigger::Events {
@@ -1050,11 +1056,15 @@ async fn a_task_status_change_hands_the_agent_the_task_instead_of_its_ids() {
entity_ids: vec![
Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-000000007a5c").unwrap()
],
+ github: None,
+ payload_match: Vec::new(),
condition: Some("Is the task ready for review?".into()),
},
ContextRoutineTrigger::Events {
events: vec!["task.property_changed".into()],
entity_ids: Vec::new(),
+ github: None,
+ payload_match: Vec::new(),
condition: Some("Did someone ask for a second reviewer?".into()),
},
],
@@ -1129,6 +1139,8 @@ async fn a_manual_run_tells_the_agent_its_owner_started_it() {
triggers: vec![ContextRoutineTrigger::Events {
events: vec!["email.message_received".into()],
entity_ids: Vec::new(),
+ github: None,
+ payload_match: Vec::new(),
condition: None,
}],
firing: RoutineFiring::Manual { requested_at },
diff --git a/crates/scheduled_action/src/inbound/axum_router.rs b/crates/scheduled_action/src/inbound/axum_router.rs
index dd6fc1c45a..12deb656d3 100644
--- a/crates/scheduled_action/src/inbound/axum_router.rs
+++ b/crates/scheduled_action/src/inbound/axum_router.rs
@@ -32,7 +32,7 @@ use serde::{Deserialize, Serialize};
use utoipa::{IntoParams, ToSchema};
#[cfg(test)]
-mod test;
+pub(crate) mod test;
/// Canonical trigger plus deprecated cron fields for existing clients. Event
/// responses omit legacy fields rather than inventing a schedule or timezone.
@@ -519,7 +519,8 @@ impl IntoResponse for ScheduledActionApiError {
ActionPolicyError::UpdateConflict => StatusCode::CONFLICT,
ActionPolicyError::NoFutureFirings
| ActionPolicyError::EventManagementDisabled
- | ActionPolicyError::ConditionsDisabled => StatusCode::BAD_REQUEST,
+ | ActionPolicyError::ConditionsDisabled
+ | ActionPolicyError::GithubNotLinked => StatusCode::BAD_REQUEST,
};
return (status, policy.to_string()).into_response();
}
diff --git a/crates/scheduled_action/src/inbound/axum_router/test.rs b/crates/scheduled_action/src/inbound/axum_router/test.rs
index d74c918c7c..d045b6a9a9 100644
--- a/crates/scheduled_action/src/inbound/axum_router/test.rs
+++ b/crates/scheduled_action/src/inbound/axum_router/test.rs
@@ -108,7 +108,7 @@ const BOT_TOKEN: &str = "team-bot-token";
const TEAM_ID: macro_uuid::Uuid = macro_uuid::Uuid::from_u128(0x7EA4);
#[derive(Clone)]
-struct FakeAuth;
+pub(crate) struct FakeAuth;
impl MacroAuthorizationService for FakeAuth {
async fn authorize(&self, jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
@@ -189,12 +189,12 @@ impl MacroAuthorizationService for FakeAuth {
}
#[derive(Clone)]
-struct FakeEntityAccessService {
+pub(crate) struct FakeEntityAccessService {
levels: HashMap<String, AccessLevel>,
}
impl FakeEntityAccessService {
- fn owner_only() -> Self {
+ pub(crate) fn owner_only() -> Self {
Self {
levels: HashMap::from([(USER.to_owned(), AccessLevel::Owner)]),
}
@@ -361,7 +361,7 @@ fn router_with<S: ScheduledActionService>(
})
}
-async fn request(
+pub(crate) async fn request(
router: &Router,
method: &str,
uri: &str,
diff --git a/crates/scheduled_action/src/inbound/kafka_consumer.rs b/crates/scheduled_action/src/inbound/kafka_consumer.rs
index 0f8076f67a..2254dcfaa2 100644
--- a/crates/scheduled_action/src/inbound/kafka_consumer.rs
+++ b/crates/scheduled_action/src/inbound/kafka_consumer.rs
@@ -11,6 +11,7 @@ use call::domain::events::CallMacroEvent;
use channels::domain::broker_events::ChannelMacroEvent;
use documents::domain::events::DocumentMacroEvent;
use email::domain::events::EmailMacroEvent;
+use github::broker::GithubWebhookMacroEvent;
use kafka_util::{GroupName, InitialOffset, KafkaEventConsumer};
use macro_event_broker::{
EventBrokerError, EventConsumer, KafkaConsumerAdapter, MacroEvent as _,
@@ -32,14 +33,15 @@ macro_event_broker::declare_topics!(
MessageMacroEvent,
PropertyMacroEvent,
EmailMacroEvent,
- CallMacroEvent
+ CallMacroEvent,
+ GithubWebhookMacroEvent
);
struct ScheduledActionEventIngestionGroup;
impl GroupName for ScheduledActionEventIngestionGroup {
const GROUP_NAME: &'static str = "scheduled-action-event-ingestion";
- // Topics such as `macro.messages` and `macro.calls` joined this group's
+ // Topics such as `macro.messages`, `macro.calls` and `macro.github_webhooks` joined this group's
// subscription with no committed offset; starting at their head avoids
// replaying each topic's retention.
const INITIAL_OFFSET: InitialOffset = InitialOffset::Latest;
@@ -116,6 +118,14 @@ fn incoming_event(event: DeclaredMacroEvent) -> IncomingEvent {
payload: EventPayload::Call(envelope.event.clone()),
}
}
+ DeclaredMacroEvent::GithubWebhookMacroEvent(event) => {
+ let envelope = event.event();
+ IncomingEvent {
+ event_id: envelope.event_id,
+ schema_version: envelope.schema_version,
+ payload: EventPayload::Github(envelope.event.clone()),
+ }
+ }
}
}
diff --git a/crates/scheduled_action/src/inbound/kafka_consumer/test.rs b/crates/scheduled_action/src/inbound/kafka_consumer/test.rs
index 7f8dd5830d..dbbd0d8656 100644
--- a/crates/scheduled_action/src/inbound/kafka_consumer/test.rs
+++ b/crates/scheduled_action/src/inbound/kafka_consumer/test.rs
@@ -185,7 +185,8 @@ fn subscriptions_are_exact_and_group_is_dedicated() {
"macro.messages",
"macro.properties",
"macro.email",
- "macro.calls"
+ "macro.calls",
+ "macro.github_webhooks"
]
);
assert_eq!(
diff --git a/crates/scheduled_action/src/outbound/event_access.rs b/crates/scheduled_action/src/outbound/event_access.rs
index e9e6d8d3f3..a35384b3c2 100644
--- a/crates/scheduled_action/src/outbound/event_access.rs
+++ b/crates/scheduled_action/src/outbound/event_access.rs
@@ -1,28 +1,32 @@
//! Translate the owning entity-access service's typed receipts, not permission
//! tables or event actors, into the routine domain's narrow capability port.
+//! GitHub deliveries are the owner's when they hold a claim to the delivering
+//! installation, as the GitHub domain decides it.
use entity_access::domain::{
models::{AccessError, EntityType, ViewAccessLevel, ViewOnly},
ports::EntityAccessService,
};
+use github::domain::ports::GithubInstallationClaims;
use macro_user_id::user_id::MacroUserIdStr;
use rootcause::Report;
use crate::domain::{
event_runs::{CurrentOwnerAccess, EventAccessCapability},
- event_trigger::{EventEntityType, EventReference},
+ event_trigger::{EventEntityType, EventReference, EventSource},
};
#[cfg(test)]
mod test;
-pub struct EventAccessAdapter<S> {
+pub struct EventAccessAdapter<S, G> {
service: S,
+ github: G,
}
-impl<S> EventAccessAdapter<S> {
- pub fn new(service: S) -> Self {
- Self { service }
+impl<S, G> EventAccessAdapter<S, G> {
+ pub fn new(service: S, github: G) -> Self {
+ Self { service, github }
}
}
@@ -39,27 +43,43 @@ fn access_result<T>(result: Result<T, AccessError>) -> Result<Option<T>, Report>
}
}
-impl<S: EntityAccessService> CurrentOwnerAccess for EventAccessAdapter<S> {
+impl<S: EntityAccessService, G: GithubInstallationClaims> CurrentOwnerAccess
+ for EventAccessAdapter<S, G>
+{
async fn authorize(
&self,
owner: &MacroUserIdStr<'static>,
event: &EventReference,
) -> Result<Option<EventAccessCapability>, Report> {
- let id = event.entity_id().to_string();
+ let entity_id = match event.source() {
+ EventSource::Entity { entity_id, .. } => entity_id.to_string(),
+ EventSource::Github(delivery) => {
+ let claimed = self
+ .github
+ .has_claim(owner, delivery.installation_id)
+ .await
+ .map_err(|error| Report::new(error).into_dynamic())?;
+ return Ok(claimed.then(|| EventAccessCapability::GithubInstallation {
+ owner: owner.clone(),
+ installation_id: delivery.installation_id,
+ }));
+ }
+ };
+ let id = &entity_id;
let result = match event.entity_type() {
EventEntityType::Document => self
.service
.generate_entity_access_receipt::<ViewAccessLevel>(
owner,
None,
- &id,
+ id,
EntityType::Document,
)
.await
.map(EventAccessCapability::Document),
EventEntityType::Channel => self
.service
- .generate_entity_access_receipt::<ViewOnly>(owner, None, &id, EntityType::Channel)
+ .generate_entity_access_receipt::<ViewOnly>(owner, None, id, EntityType::Channel)
.await
.map(EventAccessCapability::Channel),
EventEntityType::EmailThread => self
@@ -67,7 +87,7 @@ impl<S: EntityAccessService> CurrentOwnerAccess for EventAccessAdapter<S> {
.generate_entity_access_receipt::<ViewAccessLevel>(
owner,
None,
- &id,
+ id,
EntityType::EmailThread,
)
.await
@@ -77,11 +97,16 @@ impl<S: EntityAccessService> CurrentOwnerAccess for EventAccessAdapter<S> {
.generate_entity_access_receipt::<ViewAccessLevel>(
owner,
None,
- &id,
+ id,
EntityType::Call,
)
.await
.map(EventAccessCapability::Call),
+ EventEntityType::GithubInstallation => {
+ return Err(rootcause::report!(
+ "an entity event named an external source"
+ ));
+ }
};
access_result(result)
}
diff --git a/crates/scheduled_action/src/outbound/event_access/test.rs b/crates/scheduled_action/src/outbound/event_access/test.rs
index 40e0671438..eb43095a40 100644
--- a/crates/scheduled_action/src/outbound/event_access/test.rs
+++ b/crates/scheduled_action/src/outbound/event_access/test.rs
@@ -166,13 +166,17 @@ async fn mints_entity_specific_receipts_for_exact_owner_and_entity() {
permission,
calls: Arc::default(),
};
- let adapter = EventAccessAdapter::new(service.clone());
+ let adapter = EventAccessAdapter::new(service.clone(), Claims(false));
let event: EventReference = serde_json::from_value(json!({"event_id":generate_uuid_v7(), "event_name":name, "entity_id":generate_uuid_v7(), "message_id": if name == "email.message_received" {Some(generate_uuid_v7())} else {None}})).unwrap();
let receipt = adapter.authorize(&owner, &event).await.unwrap().unwrap();
assert!(receipt.authorizes(&owner, &event));
assert_eq!(
*service.calls.lock().unwrap(),
- vec![(owner.to_string(), event.entity_id().to_string(), kind)]
+ vec![(
+ owner.to_string(),
+ event.entity_id().unwrap().to_string(),
+ kind
+ )]
);
}
}
@@ -191,10 +195,13 @@ async fn wrong_permission_family_is_denied_not_reinterpreted() {
},
),
] {
- let adapter = EventAccessAdapter::new(AccessService {
- permission,
- calls: Arc::default(),
- });
+ let adapter = EventAccessAdapter::new(
+ AccessService {
+ permission,
+ calls: Arc::default(),
+ },
+ Claims(false),
+ );
let event = serde_json::from_value(json!({"event_id":generate_uuid_v7(), "event_name":name, "entity_id":generate_uuid_v7(), "message_id":null})).unwrap();
assert!(adapter.authorize(&owner, &event).await.unwrap().is_none());
}
@@ -217,3 +224,54 @@ fn denial_and_missing_entities_are_distinct_from_infrastructure_failures() {
assert!(access_result::<()>(Err(error)).is_err());
}
}
+
+/// Whether every user has a claim to every installation.
+struct Claims(bool);
+impl GithubInstallationClaims for Claims {
+ async fn is_linked(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ ) -> Result<bool, github::domain::models::GithubError> {
+ Ok(self.0)
+ }
+
+ async fn has_claim(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ _: u64,
+ ) -> Result<bool, github::domain::models::GithubError> {
+ Ok(self.0)
+ }
+}
+
+fn github_event(installation_id: u64) -> EventReference {
+ serde_json::from_value(json!({
+ "event_id": generate_uuid_v7(),
+ "event_name": "github",
+ "github": { "event": "push", "installation_id": installation_id },
+ }))
+ .unwrap()
+}
+
+#[tokio::test]
+async fn github_deliveries_follow_the_installation_claim_and_bind_to_it() {
+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let service = AccessService {
+ permission: EntityPermission::AccessLevel {
+ access_level: AccessLevel::View,
+ },
+ calls: Arc::default(),
+ };
+ let event = github_event(7);
+
+ let claimed = EventAccessAdapter::new(service.clone(), Claims(true));
+ let capability = claimed.authorize(&owner, &event).await.unwrap().unwrap();
+ assert!(capability.authorizes(&owner, &event));
+ assert!(!capability.authorizes(&owner, &github_event(8)));
+ let stranger = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ assert!(!capability.authorizes(&stranger, &event));
+
+ let unclaimed = EventAccessAdapter::new(service.clone(), Claims(false));
+ assert!(unclaimed.authorize(&owner, &event).await.unwrap().is_none());
+ assert!(service.calls.lock().unwrap().is_empty());
+}
diff --git a/crates/scheduled_action/src/outbound/event_content.rs b/crates/scheduled_action/src/outbound/event_content.rs
index f9ee4a4081..9035ed9786 100644
--- a/crates/scheduled_action/src/outbound/event_content.rs
+++ b/crates/scheduled_action/src/outbound/event_content.rs
@@ -20,6 +20,7 @@ use email::domain::{
ports::EmailContentService,
};
use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel, ViewOnly};
+use github::domain::models::GithubWebhookReceived;
use lexical_client::{LexicalClient, parse_markdown::MarkdownTarget};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
@@ -41,7 +42,7 @@ use trigger_context::RoutineEvent;
use crate::domain::{
event_runs::{AuthorizedEventRun, EventAccessCapability, condition::EventContentReader},
- event_trigger::{EventName, EventReference},
+ event_trigger::{EventName, EventReference, EventSource},
ports::RoutineEventReader,
};
@@ -152,6 +153,8 @@ enum EventContent {
},
/// The ended call; None once its record has been deleted.
Call(Option<CallRecord>),
+ /// A GitHub delivery, as it was received.
+ Github(Box<GithubWebhookReceived>),
}
struct ChannelMessage {
@@ -186,6 +189,13 @@ where
EventAccessCapability::Call(receipt) => {
Ok(EventContent::Call(self.call(receipt.clone()).await?))
}
+ // External deliveries carry their own content; there is nothing to read.
+ EventAccessCapability::GithubInstallation { .. } => match event.source() {
+ EventSource::Github(delivery) => Ok(EventContent::Github(delivery.clone())),
+ EventSource::Entity { .. } => Err(rootcause::report!(
+ "an external capability was minted for a Macro event"
+ )),
+ },
}
}
@@ -224,7 +234,7 @@ where
) -> Result<EventContent, Report> {
let channel = self
.channels
- .get_channel_metadata(event.entity_id(), owner.clone())
+ .get_channel_metadata(entity_id(event)?, owner.clone())
.await
.map_err(|error| Report::new(error).into_dynamic())?;
let Some(message_id) = event.message_id() else {
@@ -283,7 +293,7 @@ where
receipt: &EntityAccessReceipt<ViewAccessLevel>,
event: &EventReference,
) -> Result<EventContent, Report> {
- let id = event.entity_id().to_string();
+ let id = entity_id(event)?.to_string();
let document = self
.documents
.get_basic_document(&id)
@@ -364,9 +374,30 @@ fn content_json(event: &EventReference, content: &EventContent) -> Value {
call_json,
),
}),
+ EventContent::Github(delivery) => json!({ "github": github_json(delivery) }),
}
}
+/// The Macro entity a Macro event names.
+fn entity_id(event: &EventReference) -> Result<Uuid, Report> {
+ event
+ .entity_id()
+ .ok_or_else(|| rootcause::report!("a Macro event without its entity"))
+}
+
+fn github_json(delivery: &GithubWebhookReceived) -> Value {
+ json!({
+ "event": delivery.event,
+ "action": delivery.action,
+ "repository": delivery.repository.as_ref().map(|repository| &repository.full_name),
+ "sender": delivery.sender.as_ref().map(|sender| &sender.login),
+ "payload": delivery
+ .payload
+ .clone()
+ .unwrap_or_else(|| unavailable("the payload was too large to carry")),
+ })
+}
+
/// What every condition can rely on: what happened, when, and to whom.
fn envelope(owner: &MacroUserIdStr<'static>, event: &EventReference, content: Value) -> Value {
let mut value = json!({
diff --git a/crates/scheduled_action/src/outbound/event_content/routine_event.rs b/crates/scheduled_action/src/outbound/event_content/routine_event.rs
index 6ba083f20b..43bf8cef0a 100644
--- a/crates/scheduled_action/src/outbound/event_content/routine_event.rs
+++ b/crates/scheduled_action/src/outbound/event_content/routine_event.rs
@@ -20,7 +20,7 @@ use system_properties::SystemPropertyKey;
use trigger_context::{
CallSnapshot, CallStartedSnapshot, ChannelType, ContextAttachment, ContextMessage,
ContextPerson, ContextThread, DiscussionContext, DiscussionSurface, DocumentSnapshot,
- EmailSnapshot, ReplyTarget, RoutineEvent, TaskSnapshot, TranscriptLine,
+ EmailSnapshot, GithubDelivery, ReplyTarget, RoutineEvent, TaskSnapshot, TranscriptLine,
};
use super::{
@@ -41,6 +41,7 @@ pub(super) fn routine_event(
content: EventContent,
) -> Result<RoutineEvent, Report> {
let name = event.event_name();
+ let entity_id = || super::entity_id(event);
match content {
EventContent::Document {
document,
@@ -49,7 +50,7 @@ pub(super) fn routine_event(
} => document_event(name, document, &properties, markdown.as_deref()),
EventContent::Email(message) => match (name, message) {
(EventName::EmailMessageReceived, Some(message)) => Ok(RoutineEvent::EmailReceived {
- email: email_snapshot(event.entity_id(), &message),
+ email: email_snapshot(entity_id()?, &message),
}),
(EventName::EmailMessageReceived, None) => {
Err(rootcause::report!("the email is no longer available"))
@@ -57,20 +58,29 @@ pub(super) fn routine_event(
(name, _) => Err(mismatch(name)),
},
EventContent::Channel { channel, message } => {
- channel_event(name, event.entity_id(), channel, message)
+ channel_event(name, entity_id()?, channel, message)
}
EventContent::Call(record) => match (name, record) {
(EventName::CallStarted, Some(record)) => Ok(RoutineEvent::CallStarted {
- call: call_started_snapshot(event.entity_id(), record)?,
+ call: call_started_snapshot(entity_id()?, record)?,
}),
(EventName::CallEnded, Some(record)) => Ok(RoutineEvent::CallEnded {
- call: call_snapshot(event.entity_id(), record)?,
+ call: call_snapshot(entity_id()?, record)?,
}),
(EventName::CallStarted | EventName::CallEnded, None) => {
Err(rootcause::report!("the call record is no longer available"))
}
(name, _) => Err(mismatch(name)),
},
+ EventContent::Github(delivery) => Ok(RoutineEvent::Github {
+ delivery: GithubDelivery {
+ event: delivery.event,
+ action: delivery.action,
+ repository: delivery.repository.map(|repository| repository.full_name),
+ sender: delivery.sender.map(|sender| sender.login),
+ payload: delivery.payload,
+ },
+ }),
}
}
diff --git a/crates/scheduled_action/src/outbound/pg_event_run_repo.rs b/crates/scheduled_action/src/outbound/pg_event_run_repo.rs
index bb338dd2d7..3e5aed2eab 100644
--- a/crates/scheduled_action/src/outbound/pg_event_run_repo.rs
+++ b/crates/scheduled_action/src/outbound/pg_event_run_repo.rs
@@ -15,7 +15,7 @@ use crate::domain::event_runs::{
ClaimedEventRun, ConfigurationRevision, EventActionConfiguration, EventRunKey, EventRunOutcome,
EventRunRepository, FinalizationResult, FinalizeEventRun, PageSize, PendingEventRun,
};
-use crate::domain::event_trigger::{ActionTrigger, EventReference};
+use crate::domain::event_trigger::{ActionTrigger, EventReference, EventSource};
use crate::domain::models::{ActionExecutionRecord, MAX_ACTION_TIME, ScheduledAction};
#[cfg(test)]
@@ -97,6 +97,14 @@ impl TryFrom<PendingRow> for PendingEventRun {
}
}
+/// The GitHub event name a delivery's filters narrow on, if it is one.
+fn github_event(event: &EventReference) -> Option<&str> {
+ match event.source() {
+ EventSource::Github(delivery) => Some(delivery.event.as_str()),
+ EventSource::Entity { .. } => None,
+ }
+}
+
/// All paths use this lock order, including cancellation and maintenance. Skip
/// locked actions rather than holding a worker behind another routine's work.
async fn lock_action(tx: &mut Transaction<'_, Postgres>, action_id: Uuid) -> Result<bool, Report> {
@@ -128,17 +136,18 @@ impl EventRunRepository for PgEventRunRepo {
AND (event_filters @> jsonb_build_array(jsonb_build_object('events', jsonb_build_array($3::text)))
OR ($6::text IS NOT NULL AND event_filters @> jsonb_build_array(jsonb_build_object('events', jsonb_build_array($6::text)))))
AND jsonb_path_exists(event_filters,
- '$[*] ? ((@.events[*] == $event || @.events[*] == $general) && (!exists (@.ids) || @.ids == null || @.ids[*] == $id))',
- jsonb_build_object('event', $3::text, 'general', $6::text, 'id', $4::text))
+ '$[*] ? ((@.events[*] == $event || @.events[*] == $general) && (!exists (@.ids) || @.ids == null || @.ids[*] == $id) && (!exists (@.github.events) || @.github.events[*] == $github_event))',
+ jsonb_build_object('event', $3::text, 'general', $6::text, 'id', $4::text, 'github_event', $7::text))
ORDER BY id
LIMIT $5
"#,
after,
event.published_at(),
event.event_name().as_str(),
- event.entity_id().to_string(),
+ event.entity_id().map(|id| id.to_string()),
i64::from(limit.get()),
event.event_name().general_event().map(|name| name.as_str()),
+ github_event(event),
)
.fetch_all(&self.pool)
.await?;
@@ -195,27 +204,28 @@ impl EventRunRepository for PgEventRunRepo {
WHERE id = $1 AND enabled AND event_filters IS NOT NULL
AND configuration_revision = $2 AND event_activated_at <= $3
AND jsonb_path_exists(event_filters,
- '$[*] ? ((@.events[*] == $event || @.events[*] == $general) && (!exists (@.ids) || @.ids == null || @.ids[*] == $id))',
- jsonb_build_object('event', $4::text, 'general', $6::text, 'id', $5::text))
+ '$[*] ? ((@.events[*] == $event || @.events[*] == $general) && (!exists (@.ids) || @.ids == null || @.ids[*] == $id) && (!exists (@.github.events) || @.github.events[*] == $github_event))',
+ jsonb_build_object('event', $4::text, 'general', $6::text, 'id', $5::text, 'github_event', $7::text))
FOR UPDATE
"#,
action_id,
revision.get(),
event.published_at(),
event.event_name().as_str(),
- event.entity_id().to_string(),
+ event.entity_id().map(|id| id.to_string()),
event.event_name().general_event().map(|name| name.as_str()),
+ github_event(event),
)
.fetch_optional(&mut *tx)
.await?;
if eligible.is_none() {
return Ok(AdmissionResult::Ineligible);
}
- let context = json!({
- "event_name": event.event_name(),
- "entity_id": event.entity_id(),
- "message_id": event.message_id(),
- });
+ // The event id is the row's key, not part of its context.
+ let mut context = serde_json::to_value(event)?;
+ if let Value::Object(fields) = &mut context {
+ fields.remove("event_id");
+ }
let inserted = sqlx::query!(
r#"
INSERT INTO scheduled_action_event_run (action_id, event_id, configuration_revision, event_context)
@@ -463,7 +473,8 @@ impl EventRunRepository for PgEventRunRepo {
sqlx::query!(
r#"
UPDATE scheduled_action_event_run
- SET state = 'finished', finished_at = $3, outcome = $4, execution_record_id = $5
+ SET state = 'finished', finished_at = $3, outcome = $4, execution_record_id = $5,
+ event_context = event_context #- '{github,payload}'
WHERE action_id = $1 AND event_id = $2
"#,
run.key.action_id,
@@ -494,7 +505,8 @@ impl EventRunRepository for PgEventRunRepo {
.await?;
sqlx::query!(
r#"
- UPDATE scheduled_action_event_run SET state = 'finished', finished_at = now(), outcome = $4
+ UPDATE scheduled_action_event_run SET state = 'finished', finished_at = now(), outcome = $4,
+ event_context = event_context #- '{github,payload}'
WHERE action_id = $1 AND event_id = $2 AND configuration_revision = $3 AND state = 'pending'
"#,
key.action_id,
@@ -527,7 +539,8 @@ impl EventRunRepository for PgEventRunRepo {
.await?;
let skipped = sqlx::query_scalar!(
r#"
- UPDATE scheduled_action_event_run SET state = 'finished', finished_at = now(), outcome = $4
+ UPDATE scheduled_action_event_run SET state = 'finished', finished_at = now(), outcome = $4,
+ event_context = event_context #- '{github,payload}'
WHERE action_id = $1 AND event_id = $2 AND configuration_revision = $3 AND state = 'pending'
RETURNING event_id
"#,
@@ -602,6 +615,7 @@ impl EventRunRepository for PgEventRunRepo {
r#"
UPDATE scheduled_action_event_run r
SET state = 'finished', finished_at = $3,
+ event_context = r.event_context #- '{github,payload}',
outcome = CASE WHEN r.state = 'started' THEN $4::jsonb
WHEN NOT a.enabled THEN $5::jsonb ELSE $6::jsonb END
FROM scheduled_action a
diff --git a/crates/scheduled_action/src/outbound/pg_event_run_repo/test.rs b/crates/scheduled_action/src/outbound/pg_event_run_repo/test.rs
index b96e4b3ff7..0984d97ff1 100644
--- a/crates/scheduled_action/src/outbound/pg_event_run_repo/test.rs
+++ b/crates/scheduled_action/src/outbound/pg_event_run_repo/test.rs
@@ -81,7 +81,7 @@ async fn admit(repo: &PgEventRunRepo, action_id: Uuid, event: &EventReference) {
fn authorized(pending: PendingEventRun) -> AuthorizedEventRun {
let access = EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_authenticated_user(
MacroUserIdStr::parse_from_str(USER).unwrap(),
- &pending.event.entity_id().to_string(),
+ &pending.event.entity_id().unwrap().to_string(),
EntityType::Document,
);
AuthorizedEventRun {
@@ -217,12 +217,16 @@ async fn candidates_exact_recheck_activation_and_keyset_pages(pool: PgPool) {
.candidate_actions(&event, first.next_after, page(1))
.await
.unwrap();
+ // Pages follow action id order, and v7 ids minted in the same millisecond
+ // need not sort in creation order.
+ let mut expected = [null_ids, exact];
+ expected.sort();
assert_eq!(
[
first.configurations[0].action_id,
second.configurations[0].action_id
],
- [null_ids, exact]
+ expected
);
assert!(
repo.candidate_actions(&event, Some(exact), page(1))
@@ -269,7 +273,7 @@ impl crate::domain::event_runs::CurrentOwnerAccess for AllowAccess {
crate::domain::event_runs::EventAccessCapability::Document(
EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_authenticated_user(
owner.clone(),
- &event.entity_id().to_string(),
+ &event.entity_id().unwrap().to_string(),
EntityType::Document,
),
),
@@ -399,7 +403,7 @@ fn invalid_configuration_classifications_do_not_include_persisted_content() {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn two_workers_fifo_and_independent_actions(pool: PgPool) {
let (repo, id, earlier_event) = setup(&pool).await;
- let later_event = new_event(earlier_event.entity_id());
+ let later_event = new_event(earlier_event.entity_id().unwrap());
// Admission order, deliberately opposite publication order.
admit(&repo, id, &later_event).await;
admit(&repo, id, &earlier_event).await;
@@ -485,7 +489,7 @@ async fn manual_claim_blocks_events_and_foreign_tokens_cannot_finalize(pool: PgP
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn expired_started_is_interrupted_and_never_requeued(pool: PgPool) {
let (repo, id, first) = setup(&pool).await;
- let second = new_event(first.entity_id());
+ let second = new_event(first.entity_id().unwrap());
admit(&repo, id, &first).await;
admit(&repo, id, &second).await;
let pending = repo.pending_runs(page(1)).await.unwrap().remove(0);
@@ -603,7 +607,7 @@ async fn revision_disable_and_cancellation_rechecks(pool: PgPool) {
state(&pool, pending.key()).await.1,
Some(json!({"type": "cancelled", "reason": "superseded"}))
);
- let next_event = new_event(event.entity_id());
+ let next_event = new_event(event.entity_id().unwrap());
assert_eq!(
repo.admit(
id,
@@ -641,7 +645,7 @@ async fn rejected_claims_release_locks_for_immediate_retry(pool: PgPool) {
// flush a queued rollback by reusing the claim's connection.
let mut observer = pool.begin().await.unwrap();
let mut stale = pending.clone();
- stale.event = new_event(event.entity_id());
+ stale.event = new_event(event.entity_id().unwrap());
assert!(claim(&repo, stale).await.is_none());
assert!(lock_action(&mut observer, id).await.unwrap());
observer.rollback().await.unwrap();
@@ -779,8 +783,8 @@ async fn admission_waits_for_configuration_lock_and_rechecks_disable(pool: PgPoo
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn reconcile_is_bounded_and_stale_configuration_does_not_cancel_started(pool: PgPool) {
let (repo, id, first) = setup(&pool).await;
- let second = new_event(first.entity_id());
- let third = new_event(first.entity_id());
+ let second = new_event(first.entity_id().unwrap());
+ let third = new_event(first.entity_id().unwrap());
admit(&repo, id, &first).await;
admit(&repo, id, &second).await;
admit(&repo, id, &third).await;
@@ -1074,3 +1078,86 @@ async fn conditions_do_not_change_candidate_matching(pool: PgPool) {
assert!(page.configurations[0].filters.has_conditions());
admit(&repo, id, &event).await;
}
+
+fn github_event(event: &str) -> EventReference {
+ serde_json::from_value(json!({
+ "event_id": generate_uuid_v7(),
+ "event_name": "github",
+ "github": {
+ "delivery_id": "d-1",
+ "event": event,
+ "action": "completed",
+ "installation_id": 77,
+ "repository": { "id": 42, "full_name": "macro-inc/macro" },
+ "payload": { "workflow_run": { "conclusion": "failure" } },
+ },
+ }))
+ .unwrap()
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn github_candidates_narrow_on_the_event_and_keep_the_payload(pool: PgPool) {
+ let workflow_runs = action(
+ &pool,
+ json!([{"events": ["github"], "github": {"events": ["workflow_run"]}}]),
+ )
+ .await;
+ let everything = action(&pool, json!([{"events": ["github"], "github": {}}])).await;
+ action(
+ &pool,
+ json!([{"events": ["github"], "github": {"events": ["push"]}}]),
+ )
+ .await;
+ action(&pool, json!([{"events": ["document.updated"]}])).await;
+ let repo = PgEventRunRepo::new(pool.clone());
+ let event = github_event("workflow_run");
+
+ let candidates_page = repo
+ .candidate_actions(&event, None, page(10))
+ .await
+ .unwrap();
+ let mut candidates: Vec<_> = candidates_page
+ .configurations
+ .iter()
+ .map(|configuration| configuration.action_id)
+ .collect();
+ candidates.sort();
+ let mut expected = vec![workflow_runs, everything];
+ expected.sort();
+ assert_eq!(candidates, expected);
+
+ admit(&repo, workflow_runs, &event).await;
+ let pending = repo.pending_runs(page(10)).await.unwrap();
+ assert_eq!(pending.len(), 1);
+ assert_eq!(pending[0].event, event);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_finished_github_run_keeps_no_payload(pool: PgPool) {
+ let id = action(&pool, json!([{"events": ["github"], "github": {}}])).await;
+ let repo = PgEventRunRepo::new(pool.clone());
+ let event = github_event("workflow_run");
+
+ admit(&repo, id, &event).await;
+
+ let pending = repo.pending_runs(page(10)).await.unwrap();
+ assert_eq!(pending[0].event, event);
+
+ // A finished run is only a deduplication tombstone; it keeps no payload.
+ repo.cancel_pending(
+ pending[0].key(),
+ ConfigurationRevision::INITIAL,
+ CancellationReason::Disabled,
+ )
+ .await
+ .unwrap();
+ let context = sqlx::query_scalar!(
+ "SELECT event_context FROM scheduled_action_event_run WHERE action_id = $1",
+ id,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert!(context["github"].get("payload").is_none());
+ assert_eq!(context["github"]["event"], "workflow_run");
+}
diff --git a/crates/scheduled_action/src/swagger.rs b/crates/scheduled_action/src/swagger.rs
index 49b2c7acac..7206932cf2 100644
--- a/crates/scheduled_action/src/swagger.rs
+++ b/crates/scheduled_action/src/swagger.rs
@@ -17,7 +17,10 @@ use crate::inbound::template_router::{
__path_activate_template, __path_get_template, __path_share_template, __path_unshare_template,
};
-use crate::domain::event_trigger::{ActionTrigger, EventFilter, EventFilters, EventName};
+use crate::domain::event_trigger::{
+ ActionTrigger, EventFilter, EventFilters, EventName, GithubSelectorInput,
+ PayloadConditionInput, PayloadScalar,
+};
use crate::domain::models::{
ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, AgentTask,
AgentTaskAgent, CreateScheduledAction, ExecutionResource, ExecutionResourceType,
@@ -63,6 +66,9 @@ use model::response::EmptyResponse;
EventFilter,
EventFilters,
EventName,
+ GithubSelectorInput,
+ PayloadConditionInput,
+ PayloadScalar,
CreateScheduledAction,
UpdateScheduledAction,
SetScheduledActionEnabled,
diff --git a/crates/scheduled_action/tests/event_routines.rs b/crates/scheduled_action/tests/event_routines.rs
index a16bc1b2d2..854dddfdf5 100644
--- a/crates/scheduled_action/tests/event_routines.rs
+++ b/crates/scheduled_action/tests/event_routines.rs
@@ -117,12 +117,15 @@ impl CurrentOwnerAccess for FakeAccess {
// The event actor is intentionally different from the routine owner.
assert_eq!(owner.as_ref(), USER);
let entity = Entity {
- entity_id: event.entity_id().to_string(),
+ entity_id: event.entity_id().unwrap().to_string(),
entity_type: match event.entity_type() {
EventEntityType::Document => EntityType::Document,
EventEntityType::Channel => EntityType::Channel,
EventEntityType::EmailThread => EntityType::EmailThread,
EventEntityType::Call => EntityType::Call,
+ EventEntityType::GithubInstallation => {
+ unreachable!("these routines watch Macro events only")
+ }
},
};
let access = match event.entity_type() {
@@ -164,6 +167,9 @@ impl CurrentOwnerAccess for FakeAccess {
)
.unwrap(),
),
+ EventEntityType::GithubInstallation => {
+ unreachable!("these routines watch Macro events only")
+ }
};
Ok(Some(access))
}
diff --git a/crates/trigger_context/Cargo.toml b/crates/trigger_context/Cargo.toml
index 793e35ac75..beea462596 100644
--- a/crates/trigger_context/Cargo.toml
+++ b/crates/trigger_context/Cargo.toml
@@ -11,8 +11,6 @@ version = "0.1.0"
bot_id = { path = "../bot_id" }
chrono = { workspace = true, features = ["serde"] }
serde = { workspace = true }
+serde_json = { workspace = true }
uuid = { workspace = true, features = ["serde"] }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
-
-[dev-dependencies]
-serde_json = { workspace = true }
diff --git a/crates/trigger_context/src/lib.rs b/crates/trigger_context/src/lib.rs
index 541459058c..7f48f09021 100644
--- a/crates/trigger_context/src/lib.rs
+++ b/crates/trigger_context/src/lib.rs
@@ -9,6 +9,7 @@
use bot_id::BotId;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
+use serde_json::Value;
use uuid::Uuid;
#[cfg(test)]
@@ -463,12 +464,35 @@ pub enum RoutineTrigger {
/// Only these entities, when the routine narrows to some.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
entity_ids: Vec<Uuid>,
+ /// Which GitHub deliveries, for the `github` event.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ github: Option<GithubWatch>,
+ /// Exact payload tests a GitHub delivery must pass, as a
+ /// reader would state them.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ payload_match: Vec<String>,
/// A yes/no question the event's content must answer yes to.
#[serde(default, skip_serializing_if = "Option::is_none")]
condition: Option<String>,
},
}
+/// The GitHub deliveries a routine watches. Empty lists match everything.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct GithubWatch {
+ /// GitHub event names, such as `workflow_run`.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub events: Vec<String>,
+ /// Payload actions, such as `completed`.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub actions: Vec<String>,
+ /// Repositories, as `owner/name`.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub repositories: Vec<String>,
+ /// Whether deliveries caused by bots also run it.
+ pub include_bots: bool,
+}
+
/// What made a routine fire.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
@@ -585,6 +609,31 @@ pub enum RoutineEvent {
/// The call.
call: CallSnapshot,
},
+ /// Macro's GitHub App received a delivery.
+ Github {
+ /// The delivery.
+ delivery: GithubDelivery,
+ },
+}
+
+/// A delivery from Macro's GitHub App.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct GithubDelivery {
+ /// The GitHub event, such as `workflow_run`.
+ pub event: String,
+ /// Its action, such as `completed`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub action: Option<String>,
+ /// The repository, as `owner/name`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub repository: Option<String>,
+ /// The GitHub login that caused it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub sender: Option<String>,
+ /// GitHub's payload without its API links. Absent when it was too large
+ /// to carry. Untrusted.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub payload: Option<Value>,
}
/// A call that just started, read under the routine owner's access.
diff --git a/crates/trigger_context/src/test.rs b/crates/trigger_context/src/test.rs
index 230f63e218..9373a6ea2c 100644
--- a/crates/trigger_context/src/test.rs
+++ b/crates/trigger_context/src/test.rs
@@ -354,3 +354,57 @@ fn prompt_thread_attachments_put_the_prompt_message_first() {
Some(3)
);
}
+
+#[test]
+fn github_events_have_a_stable_wire_shape() {
+ let github = RoutineEvent::Github {
+ delivery: GithubDelivery {
+ event: "workflow_run".into(),
+ action: Some("completed".into()),
+ repository: Some("macro-inc/macro".into()),
+ sender: Some("octocat".into()),
+ payload: Some(json!({ "workflow_run": { "name": "CI", "conclusion": "failure" } })),
+ },
+ };
+ let trigger = RoutineTrigger::Events {
+ events: vec!["github".into()],
+ entity_ids: Vec::new(),
+ github: Some(GithubWatch {
+ events: vec!["workflow_run".into()],
+ actions: vec!["completed".into()],
+ repositories: vec!["macro-inc/macro".into()],
+ include_bots: false,
+ }),
+ payload_match: vec!["workflow_run.conclusion in [\"failure\"]".into()],
+ condition: None,
+ };
+
+ // The same examples are in services/lexical-service/test/agent-context.test.ts.
+ assert_eq!(
+ serde_json::to_value(&github).unwrap(),
+ json!({
+ "event": "github",
+ "delivery": {
+ "event": "workflow_run",
+ "action": "completed",
+ "repository": "macro-inc/macro",
+ "sender": "octocat",
+ "payload": { "workflow_run": { "name": "CI", "conclusion": "failure" } },
+ },
+ })
+ );
+ assert_eq!(
+ serde_json::to_value(&trigger).unwrap(),
+ json!({
+ "type": "events",
+ "events": ["github"],
+ "github": {
+ "events": ["workflow_run"],
+ "actions": ["completed"],
+ "repositories": ["macro-inc/macro"],
+ "include_bots": false,
+ },
+ "payload_match": ["workflow_run.conclusion in [\"failure\"]"],
+ })
+ );
+}
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index 5a40639ffc..fe273d34ec 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -1076,6 +1076,7 @@ The event menu groups Macro activity triggers by surface:
- **Tasks:** **Task created**, **Status changed**, **Priority changed**, and **Any property changed**.
- **Email:** **New email received** in the routine owner's inbox, excluding spam, trash, drafts, and historical imports.
- **Calls:** **Call started**, for calls the routine owner starts (receives the call and who has joined so far); and **Call ended**, for channel calls and meetings the owner joined (receives participants and transcript, cut short for long calls).
+- **GitHub:** presets for **Workflow failed**, **Workflow finished**, **Pull request opened**, **Pull request merged**, **Review requested**, **Review submitted**, **Issue opened**, **Comment added**, **Code pushed**, **Release published**, and **Any GitHub event**, from repositories Macro's GitHub app reaches for the routine owner. Until the owner connects GitHub, the group shows **Connect GitHub** instead.
For messages, mentions, deletion, and task changes, choose specific accessible
channels/documents/tasks or any accessible item in the same panel. Creation
@@ -1084,10 +1085,24 @@ triggers cover newly created accessible items; email covers the owner's inbox;
join** — neither has an item picker. Calls the owner did not start never trigger
**Call started**; calls they did not join never trigger **Call ended**. Mentions match only @ mentions of the routine owner. **Any property changed**
also includes status and priority; overlapping selectors start only one run for
-the same event. These are Macro events, not incoming HTTP webhooks. Bot-authored
-or delegated changes do not retrigger routines. Saved legacy selectors remain
+the same event. Bot-authored or delegated Macro changes do not retrigger
+routines. Saved legacy selectors remain
editable but are no longer offered in the new-trigger menu.
+A GitHub trigger panel edits the preset's **GitHub events** and **Actions**
+(comma-separated names GitHub sends, such as `workflow_run` and `completed`;
+empty means any), checks **Repositories** from the owner's reachable list
+(none checked means all), and **Also run for bots and apps** (off by default, so
+an agent acting through Macro's app can't retrigger itself). Deliveries only
+reach owners whose currently linked GitHub account installed the delivering
+installation, or whose team did. While GitHub is disconnected the panel shows
+**Connect GitHub** instead, and an enabled GitHub routine can't be saved. The
+panel also has **Only when the payload…** rows: a dotted field (`*` checks every list
+item, e.g. `pull_request.labels.*.name`), a comparison (**is**, **is one of**,
+**is not one of**, **matches** glob, **is set**, **is not set**) and a value.
+Every row must pass before the run is queued. The chip shows the repository
+after the trigger's label.
+
When `enable-routine-conditions` is on, every activity trigger panel has an
**Only run if** box for an optional yes/no question about each event, such as
**Is this email an invoice or a receipt?** Before a run starts, the event's
diff --git a/packages/lexical-core/tests/agent-trigger-context.test.ts b/packages/lexical-core/tests/agent-trigger-context.test.ts
index 3e7e977ee6..357faeb466 100644
--- a/packages/lexical-core/tests/agent-trigger-context.test.ts
+++ b/packages/lexical-core/tests/agent-trigger-context.test.ts
@@ -10,6 +10,96 @@ function hiddenContext(markdown: string): string | undefined {
return (first as SerializedAgentContextNode).text;
}
+describe('composeAgentContextPrompt with an external routine event', () => {
+ it('renders a GitHub delivery with the selector and payload tests that let it through', () => {
+ const markdown = composeAgentContextPrompt({
+ promptMarkdown: 'Fix it.',
+ trigger: {
+ kind: 'routine',
+ routine_id: 'r-9',
+ name: 'Fix CI',
+ owner: { id: 'macro|[email protected]', name: 'Julia' },
+ instructions: 'Find why CI failed.',
+ triggers: [
+ {
+ type: 'events',
+ events: ['github'],
+ github: {
+ events: ['workflow_run'],
+ actions: ['completed'],
+ repositories: ['macro-inc/macro'],
+ include_bots: false,
+ },
+ payload_match: ['workflow_run.conclusion in ["failure"]'],
+ },
+ ],
+ firing: {
+ type: 'event',
+ event: {
+ event: 'github',
+ delivery: {
+ event: 'workflow_run',
+ action: 'completed',
+ repository: 'macro-inc/macro',
+ sender: 'octocat',
+ payload: { workflow_run: { name: 'CI', conclusion: 'failure' } },
+ },
+ },
+ },
+ },
+ });
+
+ expect(hiddenContext(markdown)).toBe(
+ [
+ '<trigger kind="routine">',
+ ' <note>The routine Fix CI, owned by Julia, fired. The prompt is what the routine asks you to do.</note>',
+ ' <routine id="r-9" name="Fix CI" owner="Julia" owner_id="macro|[email protected]"/>',
+ ' <instructions>Find why CI failed.</instructions>',
+ ' <triggers>',
+ ' <events names="github">',
+ ' <github events="workflow_run" actions="completed" repositories="macro-inc/macro" bots="ignored"/>',
+ ' <match>workflow_run.conclusion in [&quot;failure&quot;]</match>',
+ ' </events>',
+ ' </triggers>',
+ ' <event type="github">',
+ ' <github event="workflow_run" action="completed" repository="macro-inc/macro" sender="octocat">',
+ ' <payload>{&quot;workflow_run&quot;:{&quot;name&quot;:&quot;CI&quot;,&quot;conclusion&quot;:&quot;failure&quot;}}</payload>',
+ ' </github>',
+ ' </event>',
+ '</trigger>',
+ ].join('\n')
+ );
+ });
+
+ it('says when a GitHub payload was too large to carry', () => {
+ const markdown = composeAgentContextPrompt({
+ promptMarkdown: 'Look.',
+ trigger: {
+ kind: 'routine',
+ routine_id: 'r-10',
+ name: 'Pushes',
+ owner: { id: 'macro|[email protected]', name: 'Julia' },
+ instructions: 'Summarize the push.',
+ triggers: [
+ {
+ type: 'events',
+ events: ['github'],
+ github: { include_bots: true },
+ },
+ ],
+ firing: {
+ type: 'event',
+ event: { event: 'github', delivery: { event: 'push' } },
+ },
+ },
+ });
+
+ expect(hiddenContext(markdown)).toContain(
+ '<note>The payload was too large to carry; read the details from GitHub.</note>'
+ );
+ });
+});
+
describe('composeAgentContextPrompt with a trigger', () => {
it('renders a mention that opened the session with its document comment discussion', () => {
const markdown = composeAgentContextPrompt({
diff --git a/packages/lexical-core/utils/agent-context.ts b/packages/lexical-core/utils/agent-context.ts
index 06f7e12947..6c08ea8722 100644
--- a/packages/lexical-core/utils/agent-context.ts
+++ b/packages/lexical-core/utils/agent-context.ts
@@ -199,9 +199,22 @@ export type RoutineTrigger =
events: string[];
/** Absent when the routine watches every entity. */
entity_ids?: string[];
+ /** Which GitHub deliveries, for the `github` event. */
+ github?: GithubWatch;
+ /** Exact payload tests, as a reader would state them. */
+ payload_match?: string[];
condition?: string;
};
+/** The GitHub deliveries a routine watches. Empty lists match everything. */
+export type GithubWatch = {
+ events?: string[];
+ actions?: string[];
+ /** As `owner/name`. */
+ repositories?: string[];
+ include_bots: boolean;
+};
+
/** What made a routine fire. */
export type RoutineFiring =
| { type: 'scheduled'; scheduled_for: string; schedule: string }
@@ -235,7 +248,19 @@ export type RoutineEvent =
entity_id: string;
}
| { event: 'call_started'; call: CallStartedSnapshot }
- | { event: 'call_ended'; call: CallSnapshot };
+ | { event: 'call_ended'; call: CallSnapshot }
+ | { event: 'github'; delivery: GithubDelivery };
+
+/** A delivery from Macro's GitHub App. */
+export type GithubDelivery = {
+ event: string;
+ action?: string;
+ /** As `owner/name`. */
+ repository?: string;
+ sender?: string;
+ /** Without GitHub's API links; absent when too large to carry. Untrusted. */
+ payload?: unknown;
+};
/** A call that just started, read under the routine owner's access. */
export type CallStartedSnapshot = {
@@ -1323,6 +1348,24 @@ function routineEventChildren(event: RoutineEvent): FxpNode[] {
)
.with({ event: 'call_started' }, ({ call }) => [callStartedNode(call)])
.with({ event: 'call_ended' }, ({ call }) => [callNode(call)])
+ .with({ event: 'github' }, ({ delivery }) => [
+ el(
+ 'github',
+ [
+ delivery.payload === undefined
+ ? note(
+ 'The payload was too large to carry; read the details from GitHub.'
+ )
+ : el('payload', [text(JSON.stringify(delivery.payload))]),
+ ],
+ present({
+ event: delivery.event,
+ action: delivery.action,
+ repository: delivery.repository,
+ sender: delivery.sender,
+ })
+ ),
+ ])
.exhaustive();
}
@@ -1364,15 +1407,36 @@ function routineTriggerNode(trigger: RoutineTrigger): FxpNode {
.with({ type: 'schedule' }, ({ cron, timezone }) =>
el('schedule', [], { cron, timezone })
)
- .with({ type: 'events' }, ({ events, entity_ids, condition }) =>
- el(
- 'events',
- condition === undefined ? [] : [el('condition', [text(condition)])],
- present({
- names: events.join(', '),
- only: entity_ids?.join(', '),
- })
- )
+ .with(
+ { type: 'events' },
+ ({ events, entity_ids, github, payload_match, condition }) =>
+ el(
+ 'events',
+ [
+ ...(github === undefined
+ ? []
+ : [
+ el(
+ 'github',
+ [],
+ present({
+ events: github.events?.join(', '),
+ actions: github.actions?.join(', '),
+ repositories: github.repositories?.join(', '),
+ bots: github.include_bots ? 'included' : 'ignored',
+ })
+ ),
+ ]),
+ ...(payload_match ?? []).map((test) => el('match', [text(test)])),
+ ...(condition === undefined
+ ? []
+ : [el('condition', [text(condition)])]),
+ ],
+ present({
+ names: events.join(', '),
+ only: entity_ids?.join(', '),
+ })
+ )
)
.exhaustive();
}
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.md
index 8d16caa64b..f39c7b0a26 100644
--- a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.md
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.md
@@ -51,6 +51,7 @@
- [GetScheduledActionTemplateErrors](type-aliases/GetScheduledActionTemplateErrors.md)
- [GetScheduledActionTemplateResponse](type-aliases/GetScheduledActionTemplateResponse.md)
- [GetScheduledActionTemplateResponses](type-aliases/GetScheduledActionTemplateResponses.md)
+- [GithubSelector](type-aliases/GithubSelector.md)
- [InProgressExecution](type-aliases/InProgressExecution.md)
- [LegacyActionConfiguration](type-aliases/LegacyActionConfiguration.md)
- [ListScheduledActionHistoryData](type-aliases/ListScheduledActionHistoryData.md)
@@ -63,6 +64,8 @@
- [ListScheduledActionsErrors](type-aliases/ListScheduledActionsErrors.md)
- [ListScheduledActionsResponse](type-aliases/ListScheduledActionsResponse.md)
- [ListScheduledActionsResponses](type-aliases/ListScheduledActionsResponses.md)
+- [PayloadCondition](type-aliases/PayloadCondition.md)
+- [PayloadScalar](type-aliases/PayloadScalar.md)
- [RoutineModelId](type-aliases/RoutineModelId.md)
- [RoutineTemplate](type-aliases/RoutineTemplate.md)
- [RoutineTrigger](type-aliases/RoutineTrigger.md)
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/EventFilter.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/EventFilter.md
index 20bc02428b..9de976fa29 100644
--- a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/EventFilter.md
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/EventFilter.md
@@ -1,14 +1,21 @@
# Type Alias: EventFilter
-> **EventFilter** = \{ `condition?`: `string` \| `null`; `events`: [`EventName`](EventName.md)[]; `ids?`: `string`[] \| `null`; \}
+> **EventFilter** = \{ `condition?`: `string` \| `null`; `events`: [`EventName`](EventName.md)[]; `github?`: `null` \| [`GithubSelector`](GithubSelector.md); `ids?`: `string`[] \| `null`; `match?`: [`PayloadCondition`](PayloadCondition.md)[] \| `null`; \}
An event name AND an entity ID must match within the same filter. A
condition further requires the event's content to answer it with yes.
+`github` comes from outside Macro and carries its payload: it stands
+alone in its filter, takes no ids, and may require
+exact payload values with `match`. A `github` filter narrows deliveries
+with its `github` selector.
+
## Properties
| Property | Type | Description |
| ------ | ------ | ------ |
| <a id="property-condition"></a> `condition?` | `string` \| `null` | Yes/no question about the triggering content, e.g. "Is this email an invoice?". The routine runs only when the answer is yes. |
| <a id="property-events"></a> `events` | [`EventName`](EventName.md)[] | - |
+| <a id="property-github"></a> `github?` | `null` \| [`GithubSelector`](GithubSelector.md) | - |
| <a id="property-ids"></a> `ids?` | `string`[] \| `null` | - |
+| <a id="property-match"></a> `match?` | [`PayloadCondition`](PayloadCondition.md)[] \| `null` | Exact tests on the payload, all of which must pass. |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/EventName.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/EventName.md
index 4251c10463..b1405f618e 100644
--- a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/EventName.md
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/EventName.md
@@ -1,6 +1,6 @@
# Type Alias: EventName
-> **EventName** = `"document.created"` \| `"document.updated"` \| `"document.deleted"` \| `"task.created"` \| `"task.status_changed"` \| `"task.priority_changed"` \| `"task.property_changed"` \| `"email.message_received"` \| `"channel.created"` \| `"channel.message_posted"` \| `"channel.mentioned"` \| `"channel.message_patched"` \| `"channel.message_attachment_created"` \| `"call.started"` \| `"call.ended"`
+> **EventName** = `"document.created"` \| `"document.updated"` \| `"document.deleted"` \| `"task.created"` \| `"task.status_changed"` \| `"task.priority_changed"` \| `"task.property_changed"` \| `"email.message_received"` \| `"channel.created"` \| `"channel.message_posted"` \| `"channel.mentioned"` \| `"channel.message_patched"` \| `"channel.message_attachment_created"` \| `"call.started"` \| `"call.ended"` \| `"github"`
Closed allowlist: unknown names, deletions and ambiguous attribution are not
selectors. Adding a broker variant does not automatically enable routines.
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GithubSelector.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GithubSelector.md
new file mode 100644
index 0000000000..319048d146
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/GithubSelector.md
@@ -0,0 +1,14 @@
+# Type Alias: GithubSelector
+
+> **GithubSelector** = \{ `actions?`: `string`[]; `events?`: `string`[]; `includeBots?`: `boolean`; `repositories?`: `string`[]; \}
+
+Which GitHub deliveries match.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-actions"></a> `actions?` | `string`[] | Payload actions, such as `completed` or `opened`; any when empty. |
+| <a id="property-events"></a> `events?` | `string`[] | GitHub event names, such as `workflow_run` or `pull_request`; any when empty. |
+| <a id="property-includebots"></a> `includeBots?` | `boolean` | Also run for deliveries caused by bots and apps, including Macro's own. |
+| <a id="property-repositories"></a> `repositories?` | `string`[] | Repositories as `owner/name`, matched without regard to case; every repository the owner's installations cover when empty. A renamed repository stops matching until it is chosen again. |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/PayloadCondition.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/PayloadCondition.md
new file mode 100644
index 0000000000..00f6ca9356
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/PayloadCondition.md
@@ -0,0 +1,18 @@
+# Type Alias: PayloadCondition
+
+> **PayloadCondition** = \{ `equals?`: `null` \| [`PayloadScalar`](PayloadScalar.md); `exists?`: `boolean` \| `null`; `glob?`: `string` \| `null`; `in?`: [`PayloadScalar`](PayloadScalar.md)[] \| `null`; `notIn?`: [`PayloadScalar`](PayloadScalar.md)[] \| `null`; `path`: `string`[]; \}
+
+`path` walks objects by key; `*` steps into every element of an array and
+a number into one. Give exactly one test. `notIn` also passes when the
+path finds nothing.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-equals"></a> `equals?` | `null` \| [`PayloadScalar`](PayloadScalar.md) | - |
+| <a id="property-exists"></a> `exists?` | `boolean` \| `null` | Whether the path finds a non-null value. |
+| <a id="property-glob"></a> `glob?` | `string` \| `null` | Some text found matches this glob; `*` matches any run of characters. |
+| <a id="property-in"></a> `in?` | [`PayloadScalar`](PayloadScalar.md)[] \| `null` | Some value found is one of these. |
+| <a id="property-notin"></a> `notIn?` | [`PayloadScalar`](PayloadScalar.md)[] \| `null` | No value found is one of these. |
+| <a id="property-path"></a> `path` | `string`[] | Keys from the payload's root, e.g. `["workflow_run", "conclusion"]`. |
diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/PayloadScalar.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/PayloadScalar.md
new file mode 100644
index 0000000000..0d92b2a091
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/PayloadScalar.md
@@ -0,0 +1,5 @@
+# Type Alias: PayloadScalar
+
+> **PayloadScalar** = `null` \| `boolean` \| `number` \| `string`
+
+A JSON text, number, boolean or null that payload values are compared with.
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index c3da1a3b4f..f92e41ee86 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -407,6 +407,28 @@ Publishing, reading, and activating templates require the caller's
404 (`template()` returns `undefined`). `stopSharingTemplate()` stays available
to owners, and previously activated routines continue working.
+A GitHub trigger takes a filter of its own, with optional exact payload tests in
+`match`. It needs the owner to have connected GitHub:
+
+```ts
+await routine.update({
+ ...options,
+ trigger: {
+ type: 'events',
+ filters: [
+ {
+ events: ['github'],
+ github: { events: ['workflow_run'], actions: ['completed'], repositories: ['macro-inc/macro'] },
+ match: [
+ { path: ['workflow_run', 'name'], equals: 'CI' },
+ { path: ['workflow_run', 'conclusion'], in: ['failure', 'timed_out'] },
+ ],
+ },
+ ],
+ },
+});
+```
+
### Agents, conversations and hosts
`macro.agents.list/create/byId` manage agent configuration. `AgentOptions` takes
diff --git a/packages/sdk/generated/scheduled-action/index.ts b/packages/sdk/generated/scheduled-action/index.ts
index fe4045f79a..3cca95d2b7 100644
--- a/packages/sdk/generated/scheduled-action/index.ts
+++ b/packages/sdk/generated/scheduled-action/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, ActionTrigger, ActivateScheduledActionTemplateData, ActivateScheduledActionTemplateError, ActivateScheduledActionTemplateErrors, ActivateScheduledActionTemplateResponse, ActivateScheduledActionTemplateResponses, AgentMcpServer, AgentTask, AgentTaskAgent, AiAdmissionErrorBody, ClientOptions, ConditionResult, CreateScheduledAction, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, GetScheduledActionData, GetScheduledActionError, GetScheduledActionErrors, GetScheduledActionResponse, GetScheduledActionResponses, GetScheduledActionTemplateData, GetScheduledActionTemplateError, GetScheduledActionTemplateErrors, GetScheduledActionTemplateResponse, GetScheduledActionTemplateResponses, InProgressExecution, LegacyActionConfiguration, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, RoutineModelId, RoutineTemplate, RoutineTrigger, RoutineTriggers, RunVisibility, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, SetScheduledActionEnabled, SetScheduledActionEnabledData, SetScheduledActionEnabledError, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponse, SetScheduledActionEnabledResponses, ShareRoutineTemplate, ShareScheduledActionTemplateData, ShareScheduledActionTemplateError, ShareScheduledActionTemplateErrors, ShareScheduledActionTemplateResponse, ShareScheduledActionTemplateResponses, TemplateVariable, UnshareScheduledActionTemplateData, UnshareScheduledActionTemplateError, UnshareScheduledActionTemplateErrors, UnshareScheduledActionTemplateResponse, UnshareScheduledActionTemplateResponses, UpdateScheduledAction, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses, VariableFill } from './types.gen';
+export type { ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, ActionTrigger, ActivateScheduledActionTemplateData, ActivateScheduledActionTemplateError, ActivateScheduledActionTemplateErrors, ActivateScheduledActionTemplateResponse, ActivateScheduledActionTemplateResponses, AgentMcpServer, AgentTask, AgentTaskAgent, AiAdmissionErrorBody, ClientOptions, ConditionResult, CreateScheduledAction, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, GetScheduledActionData, GetScheduledActionError, GetScheduledActionErrors, GetScheduledActionResponse, GetScheduledActionResponses, GetScheduledActionTemplateData, GetScheduledActionTemplateError, GetScheduledActionTemplateErrors, GetScheduledActionTemplateResponse, GetScheduledActionTemplateResponses, GithubSelector, InProgressExecution, LegacyActionConfiguration, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, PayloadCondition, PayloadScalar, RoutineModelId, RoutineTemplate, RoutineTrigger, RoutineTriggers, RunVisibility, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, SetScheduledActionEnabled, SetScheduledActionEnabledData, SetScheduledActionEnabledError, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponse, SetScheduledActionEnabledResponses, ShareRoutineTemplate, ShareScheduledActionTemplateData, ShareScheduledActionTemplateError, ShareScheduledActionTemplateErrors, ShareScheduledActionTemplateResponse, ShareScheduledActionTemplateResponses, TemplateVariable, UnshareScheduledActionTemplateData, UnshareScheduledActionTemplateError, UnshareScheduledActionTemplateErrors, UnshareScheduledActionTemplateResponse, UnshareScheduledActionTemplateResponses, UpdateScheduledAction, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses, VariableFill } from './types.gen';
diff --git a/packages/sdk/generated/scheduled-action/types.gen.ts b/packages/sdk/generated/scheduled-action/types.gen.ts
index 50fb3f03fa..464a6d170a 100644
--- a/packages/sdk/generated/scheduled-action/types.gen.ts
+++ b/packages/sdk/generated/scheduled-action/types.gen.ts
@@ -155,6 +155,11 @@ export type EmptyResponse = {
/**
* An event name AND an entity ID must match within the same filter. A
* condition further requires the event's content to answer it with yes.
+ *
+ * `github` comes from outside Macro and carries its payload: it stands
+ * alone in its filter, takes no ids, and may require
+ * exact payload values with `match`. A `github` filter narrows deliveries
+ * with its `github` selector.
*/
export type EventFilter = {
/**
@@ -163,7 +168,12 @@ export type EventFilter = {
*/
condition?: string | null;
events: Array<EventName>;
+ github?: null | GithubSelector;
ids?: Array<string> | null;
+ /**
+ * Exact tests on the payload, all of which must pass.
+ */
+ match?: Array<PayloadCondition> | null;
};
/**
@@ -175,7 +185,7 @@ export type EventFilters = Array<EventFilter>;
* Closed allowlist: unknown names, deletions and ambiguous attribution are not
* selectors. Adding a broker variant does not automatically enable routines.
*/
-export type EventName = 'document.created' | 'document.updated' | 'document.deleted' | 'task.created' | 'task.status_changed' | 'task.priority_changed' | 'task.property_changed' | 'email.message_received' | 'channel.created' | 'channel.message_posted' | 'channel.mentioned' | 'channel.message_patched' | 'channel.message_attachment_created' | 'call.started' | 'call.ended';
+export type EventName = 'document.created' | 'document.updated' | 'document.deleted' | 'task.created' | 'task.status_changed' | 'task.priority_changed' | 'task.property_changed' | 'email.message_received' | 'channel.created' | 'channel.message_posted' | 'channel.mentioned' | 'channel.message_patched' | 'channel.message_attachment_created' | 'call.started' | 'call.ended' | 'github';
/**
* Transcript resource created by a run. Never infer this from current task configuration.
@@ -201,6 +211,30 @@ export type ExecutionResult = {
version: number;
};
+/**
+ * Which GitHub deliveries match.
+ */
+export type GithubSelector = {
+ /**
+ * Payload actions, such as `completed` or `opened`; any when empty.
+ */
+ actions?: Array<string>;
+ /**
+ * GitHub event names, such as `workflow_run` or `pull_request`; any when empty.
+ */
+ events?: Array<string>;
+ /**
+ * Also run for deliveries caused by bots and apps, including Macro's own.
+ */
+ includeBots?: boolean;
+ /**
+ * Repositories as `owner/name`, matched without regard to case; every
+ * repository the owner's installations cover when empty. A renamed
+ * repository stops matching until it is chosen again.
+ */
+ repositories?: Array<string>;
+};
+
export type InProgressExecution = {
action_id: string;
chat_id?: string | null;
@@ -221,6 +255,40 @@ export type LegacyActionConfiguration = {
timezone: string;
};
+/**
+ * `path` walks objects by key; `*` steps into every element of an array and
+ * a number into one. Give exactly one test. `notIn` also passes when the
+ * path finds nothing.
+ */
+export type PayloadCondition = {
+ equals?: null | PayloadScalar;
+ /**
+ * Whether the path finds a non-null value.
+ */
+ exists?: boolean | null;
+ /**
+ * Some text found matches this glob; `*` matches any run of characters.
+ */
+ glob?: string | null;
+ /**
+ * Some value found is one of these.
+ */
+ in?: Array<PayloadScalar> | null;
+ /**
+ * No value found is one of these.
+ */
+ notIn?: Array<PayloadScalar> | null;
+ /**
+ * Keys from the payload's root, e.g. `["workflow_run", "conclusion"]`.
+ */
+ path: Array<string>;
+};
+
+/**
+ * A JSON text, number, boolean or null that payload values are compared with.
+ */
+export type PayloadScalar = null | boolean | number | string;
+
/**
* A nonblank model identifier. Runtime catalogs, not the scheduler, own availability.
*/
diff --git a/packages/sdk/specs/scheduled-action.json b/packages/sdk/specs/scheduled-action.json
index 0838f601a3..b70de562b6 100644
--- a/packages/sdk/specs/scheduled-action.json
+++ b/packages/sdk/specs/scheduled-action.json
@@ -1168,7 +1168,7 @@
},
"EventFilter": {
"type": "object",
- "description": "An event name AND an entity ID must match within the same filter. A\ncondition further requires the event's content to answer it with yes.",
+ "description": "An event name AND an entity ID must match within the same filter. A\ncondition further requires the event's content to answer it with yes.\n\n`github` comes from outside Macro and carries its payload: it stands\nalone in its filter, takes no ids, and may require\nexact payload values with `match`. A `github` filter narrows deliveries\nwith its `github` selector.",
"required": ["events"],
"properties": {
"condition": {
@@ -1182,11 +1182,29 @@
"$ref": "#/components/schemas/EventName"
}
},
+ "github": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/GithubSelector",
+ "description": "Which GitHub deliveries match; required for, and only for, `github`."
+ }
+ ]
+ },
"ids": {
"type": ["array", "null"],
"items": {
"type": "string"
}
+ },
+ "match": {
+ "type": ["array", "null"],
+ "items": {
+ "$ref": "#/components/schemas/PayloadCondition"
+ },
+ "description": "Exact tests on the payload, all of which must pass."
}
}
},
@@ -1215,7 +1233,8 @@
"channel.message_patched",
"channel.message_attachment_created",
"call.started",
- "call.ended"
+ "call.ended",
+ "github"
]
},
"ExecutionResource": {
@@ -1272,6 +1291,38 @@
}
}
},
+ "GithubSelector": {
+ "type": "object",
+ "description": "Which GitHub deliveries match.",
+ "properties": {
+ "actions": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Payload actions, such as `completed` or `opened`; any when empty."
+ },
+ "events": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "GitHub event names, such as `workflow_run` or `pull_request`; any when empty."
+ },
+ "includeBots": {
+ "type": "boolean",
+ "description": "Also run for deliveries caused by bots and apps, including Macro's own."
+ },
+ "repositories": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Repositories as `owner/name`, matched without regard to case; every\nrepository the owner's installations cover when empty. A renamed\nrepository stops matching until it is chosen again."
+ }
+ },
+ "additionalProperties": false
+ },
"InProgressExecution": {
"type": "object",
"required": ["action_id"],
@@ -1322,6 +1373,73 @@
},
"additionalProperties": false
},
+ "PayloadCondition": {
+ "type": "object",
+ "description": "`path` walks objects by key; `*` steps into every element of an array and\na number into one. Give exactly one test. `notIn` also passes when the\npath finds nothing.",
+ "required": ["path"],
+ "properties": {
+ "equals": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/PayloadScalar",
+ "description": "Some value found equals this."
+ }
+ ]
+ },
+ "exists": {
+ "type": ["boolean", "null"],
+ "description": "Whether the path finds a non-null value."
+ },
+ "glob": {
+ "type": ["string", "null"],
+ "description": "Some text found matches this glob; `*` matches any run of characters."
+ },
+ "in": {
+ "type": ["array", "null"],
+ "items": {
+ "$ref": "#/components/schemas/PayloadScalar"
+ },
+ "description": "Some value found is one of these."
+ },
+ "notIn": {
+ "type": ["array", "null"],
+ "items": {
+ "$ref": "#/components/schemas/PayloadScalar"
+ },
+ "description": "No value found is one of these."
+ },
+ "path": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Keys from the payload's root, e.g. `[\"workflow_run\", \"conclusion\"]`."
+ }
+ },
+ "additionalProperties": false
+ },
+ "PayloadScalar": {
+ "oneOf": [
+ {
+ "type": "null",
+ "default": null
+ },
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "number",
+ "format": "double"
+ },
+ {
+ "type": "string"
+ }
+ ],
+ "description": "A JSON text, number, boolean or null that payload values are compared with."
+ },
"RoutineModelId": {
"type": "string",
"description": "A nonblank model identifier. Runtime catalogs, not the scheduler, own availability."
diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.toml
index c1f49bf16a..0931edf682 100644
--- a/services/agent_harness_service/Cargo.toml
+++ b/services/agent_harness_service/Cargo.toml
@@ -101,7 +101,7 @@ foreign_entity = { path = "../../crates/foreign_entity" }
frecency = { path = "../../crates/frecency", features = ["outbound", "postgres"] }
fusionauth = { path = "../../crates/fusionauth" }
futures = { workspace = true }
-github = { path = "../../crates/github", default-features = false, features = ["outbound", "ports", "sync"] }
+github = { path = "../../crates/github", default-features = false, features = ["installation_claims", "outbound", "ports", "sync"] }
github_pull_requests = { path = "../../crates/github_pull_requests", features = ["outbound", "s3", "service"] }
granola_sync = { path = "../../crates/granola_sync" }
harness_id = { path = "../../crates/harness_id" }
diff --git a/services/agent_harness_service/src/scheduling.rs b/services/agent_harness_service/src/scheduling.rs
index 35435d880c..8f3568be16 100644
--- a/services/agent_harness_service/src/scheduling.rs
+++ b/services/agent_harness_service/src/scheduling.rs
@@ -7,6 +7,7 @@ use connection_gateway_client::client::ConnectionGatewayClient;
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
use entity_registry::OwnerGrantPolicy;
use entity_registry_db_utils::OwnedEntityRegistrar;
+use github::outbound::pg_installation_claims::PgGithubInstallationClaims;
use jev::{domain::JevClassifier, outbound::SystemOneJev};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_authorization::{
@@ -110,7 +111,10 @@ pub async fn build(
let access = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
db.clone(),
)));
- let event_access = Arc::new(EventAccessAdapter::new(access.as_ref().clone()));
+ let event_access = Arc::new(EventAccessAdapter::new(
+ access.as_ref().clone(),
+ PgGithubInstallationClaims::new(db.clone()),
+ ));
let ai_admission = ai_billing::composition::pg_admission_service(
db.clone(),
config.enable_ai_usage_enforcement,
@@ -263,7 +267,8 @@ pub async fn build(
.with_target_validation(TargetValidation::new(
sessions,
config.routine_agents_enabled,
- )),
+ ))
+ .with_github_links(PgGithubInstallationClaims::new(db.clone())),
);
let template_flags = config
.posthog_api_key
diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rs
index d892f47202..1c0cfad704 100644
--- a/services/document_storage_service/src/server.rs
+++ b/services/document_storage_service/src/server.rs
@@ -654,7 +654,10 @@ pub async fn run() -> anyhow::Result<()> {
PgGithubSyncRepo::new(db.clone()),
GithubSyncClientImpl::default(),
ConnectionGatewayGithubRealtime::new(conn_gateway_client.clone()),
- );
+ )
+ .with_webhook_publisher(github::broker::BrokerGithubWebhookPublisher(
+ macro_event_broker.clone(),
+ ));
let github_pull_request_index_state = PullRequestIndexRouterState {
service: Arc::new(PullRequestIndexService::new(
diff --git a/services/lexical-service/src/endpoints/agent-context.ts b/services/lexical-service/src/endpoints/agent-context.ts
index 762efd9f03..7c332ceade 100644
--- a/services/lexical-service/src/endpoints/agent-context.ts
+++ b/services/lexical-service/src/endpoints/agent-context.ts
@@ -296,6 +296,16 @@ const routineEvent = z.discriminatedUnion('event', [
}),
z.object({ event: z.literal('call_started'), call: callStartedSnapshot }),
z.object({ event: z.literal('call_ended'), call: callSnapshot }),
+ z.object({
+ event: z.literal('github'),
+ delivery: z.object({
+ event: z.string().min(1),
+ action: z.string().min(1).optional(),
+ repository: z.string().min(1).optional(),
+ sender: z.string().min(1).optional(),
+ payload: z.unknown().optional(),
+ }),
+ }),
]);
const routineFiring = z.discriminatedUnion('type', [
@@ -325,6 +335,15 @@ const routineTrigger = z.discriminatedUnion('type', [
type: z.literal('events'),
events: z.array(z.string().min(1)),
entity_ids: z.array(z.string().min(1)).optional(),
+ github: z
+ .object({
+ events: z.array(z.string().min(1)).optional(),
+ actions: z.array(z.string().min(1)).optional(),
+ repositories: z.array(z.string().min(1)).optional(),
+ include_bots: z.boolean(),
+ })
+ .optional(),
+ payload_match: z.array(z.string().min(1)).optional(),
condition: z.string().optional(),
}),
]);
diff --git a/services/lexical-service/test/agent-context.test.ts b/services/lexical-service/test/agent-context.test.ts
index e99fe39795..ab42d13635 100644
--- a/services/lexical-service/test/agent-context.test.ts
+++ b/services/lexical-service/test/agent-context.test.ts
@@ -167,6 +167,44 @@ const callEndedRoutineWire = {
},
};
+const githubRoutineWire = {
+ kind: 'routine',
+ routine_id: '00000000-0000-0000-0000-0000000000f2',
+ name: 'Fix failing CI',
+ owner: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ instructions: 'Find why CI failed and open a fix.',
+ triggers: [
+ {
+ type: 'events',
+ events: ['github'],
+ github: {
+ events: ['workflow_run'],
+ actions: ['completed'],
+ repositories: ['macro-inc/macro'],
+ include_bots: false,
+ },
+ payload_match: ['workflow_run.conclusion in ["failure"]'],
+ },
+ ],
+ firing: {
+ type: 'event',
+ event: {
+ event: 'github',
+ delivery: {
+ event: 'workflow_run',
+ action: 'completed',
+ repository: 'macro-inc/macro',
+ sender: 'octocat',
+ payload: { workflow_run: { name: 'CI', conclusion: 'failure' } },
+ },
+ },
+ },
+};
+
function endpoint() {
const app = new Hono();
fromHono(app).post('/agent-context', AgentContextEndpoint);
@@ -186,6 +224,7 @@ describe('agent-context request schema', () => {
dispatchedWire,
callStartedRoutineWire,
callEndedRoutineWire,
+ githubRoutineWire,
]) {
const parsed = agentContextRequest.safeParse({
promptMarkdown: 'please fix',
@@ -234,6 +273,7 @@ describe('POST /agent-context', () => {
dispatchedWire,
callStartedRoutineWire,
callEndedRoutineWire,
+ githubRoutineWire,
]) {
const response = await post({ promptMarkdown: 'please fix', trigger });
expect(response.status).toBe(200);
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index e8a867d38e..ef150c8be5 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -6844,6 +6844,14 @@ type GraphqlScheduledActionEventFilter {
"""
entityIds: [ID!]
"""
+ Which GitHub App deliveries satisfy a `GITHUB` filter.
+ """
+ github: GraphqlScheduledActionGithubSelector
+ """
+ Exact payload tests a GitHub delivery must pass, as a reader would state them.
+ """
+ payloadMatch: [String!]!
+ """
Yes/no question the triggering content must answer with yes before the routine runs.
"""
condition: String
@@ -6913,6 +6921,10 @@ enum GraphqlScheduledActionEventName {
A call the routine's owner joined ended.
"""
CALL_ENDED
+ """
+ Macro's GitHub App received a delivery.
+ """
+ GITHUB
}
"""
@@ -6925,6 +6937,28 @@ type GraphqlScheduledActionEventsTrigger {
filters: [GraphqlScheduledActionEventFilter!]!
}
+"""
+GitHub deliveries a filter watches. Empty lists match everything.
+"""
+type GraphqlScheduledActionGithubSelector {
+ """
+ GitHub event names, such as `workflow_run`.
+ """
+ events: [String!]!
+ """
+ Payload actions, such as `completed`.
+ """
+ actions: [String!]!
+ """
+ Repositories, as `owner/name`.
+ """
+ repositories: [String!]!
+ """
+ Whether deliveries caused by bots also match.
+ """
+ includeBots: Boolean!
+}
+
"""
Any of several schedules and optional Macro event filters.
"""