Repository navigation
Replies: 2 comments
|
A data point for open question 6 (trigger-created agent lifecycle) and the What we see. Each agent gets one task at creation ( What the code does (read at
Why this matters for the plan. The requirements written for ptone#194 treat Suggestion. Two small pieces that fit the ephemeral work:
Until then we stop the agents ourselves as soon as the Hub reports |
|
A full explainer site on the design https://serve-dot-zipline.appspot.com/asset/6e2f0b6a-7b1f-5375-bb02-081032eb0241/zpc/84upejvmkvc/ |
Uh oh!
There was an error while loading. Please reload this page.
Trigger System: landscape review and staged plan
new/skip;reusein Stage 3), D6 = (a) public-internet ingress for workstation hubs out of scope and not a documented mode.main@2486d72.landscape-appendix.md(file-level survey of the scheduler, delivery/notification and GitHub/ingress code this plan builds on).This is a plan, not an implementation design. Each stage below gets its own design document (and, where marked, its own sub-architect) before implementation. The purpose of this document is to fix the shared model, the stage boundaries and the decisions ptone must make, so that the stage designs do not contradict each other.
1. Summary
Scion already has one trigger: the scheduler. A schedule is "when the clock says X, do action Y as principal Z". Everything that makes it safe to run an action later on someone's behalf — the initiator attribution, the frozen authorization revision, fire-time re-authorization, standing checks, tracked fires, history, pause/resume, the
skippedoutcome — is not time-specific. It is the trigger core, and today it is welded to the clock.The plan:
Trigger(rule),TriggerEvent(durable inbox) andTriggerFire(history) resources; prove them end to end with the smallest possible generic webhook: one project webhook endpoint → HMAC verify → inbox → one rule →messageaction to one existing agent. Schedules keep their tables and API but fire through the core.dispatch_agentaction from a webhook, CLI and web surfaces, docs.@scion /commandcomments), dispatch agents with event context, subject-keyed coalescing (one agent per PR/issue), reply-back using the App's installation token.Stage 1 is the load-bearing one: the event envelope, the rule shape, the authority model and the subject/concurrency policy are the things that are expensive to change once GitHub routing is built on them. Everything else is comparatively reversible.
2. Landscape: what exists today
Detail and file references are in
landscape-appendix.md; this section is the summary an implementer needs.2.1 The scheduler (the first trigger)
Schedule(recurring, cron with IANA time zone, pause/resume, name unique per project, run counters) andScheduledEvent(one-shot, or the per-fire instance of a recurring schedule;pending → fired | failed | cancelled | expired, plusskippedarriving with exec schedules).RegisterEventHandler):message(deliver text to an agent, optional--wake,--interrupt) anddispatch_agent(create an agent from a template with a task).exec(argv in the agent's container over Conduit) is designed and partly landed (Scheduler: exec-only schedules that run a command in an agent's container without an LLM turn (needs permission/security design) ptone/scion#7818, Phases A/B).InitiatorAttributionMixin(principal + credential kind/id,authorization_revision) and a frozenEffectCeilingMixin(authority_*); the revision bumps on any edit that changes a future dispatch. At fire time the hub resolves the recorded authority (resolveScheduledAuthority, fail closed on legacy rows), checks the frozen ceiling, re-runs the live authorization for the action (authorizeScheduledMessageFire/authorizeScheduledAgentCreate), then checks standing (held target, suspended or deleted creator). Creator deleted → schedules pause withstatus_reason. Rows the scheduler writes (delegation edges, SA assignments) carryAuthorityProvenanceMixinwithsource_credential_kind = scheduler. This is the model triggers must inherit, not re-invent.schedule-evaluatorsingleton under a cluster-wide advisory lock plusSKIP LOCKED(multi-instance safe) for recurring; in-memory timers for one-shot with an atomic DB claim; "tracked fires" for work that outlives the evaluator (wake, exec); askippedoutcome that does not count as an error; onescheduled_eventsrow per fire as history (scion schedule history, 7-day retention). No retries by design; missed cron slots collapse into one fire.systemmessage withsystem_category: schedulerand no persisted conversation row; the compat layer renders it astype: event,event.type: schedule.fired. The envelope'seventbody is{type, subject, status, reason, url}and forschedule.firedonlytypeis set: no schedule id, event id, name or fire time reach the agent. Delivery goes through the broker (runtime exec paste) or the agent's Conduit session (hub.conduit_deliver, slices still landing).createAgentInProjectis HTTP-shaped (takesw, r); the scheduler'sdispatch_agenthandler is the only headless precedent and it does not accept labels. A trigger core needs a real internal create function with labels.scion schedule {create, create-recurring, list, get, history, pause, resume, cancel, delete}(agent mode: agents see only schedules they created); project schedules page and admin scheduler page in the web UI; authz operations inauthzop/catalog_projects.go(schedule.*,scheduled_event.*); experiments per sub-feature.2.2 Message and event delivery
deliverToAgent: authorize → phase/hold gates → persiststore.Message→ render envelope →dispatchWithBrokerRetry→ broker paste or Conduitdeliver-message). Everything the trigger system delivers to an existing agent should go through it unchanged; the trigger system only decides what to send and as whom.DispatchState: pendingrows are written only by agent-to-agent DMs and re-driven only on broker reconnect; a suspended/stopped target yields 409agent_not_running(or--wake). "Queue while the agent is offline" (Feature: Per-Agent Inbound Webhook Endpoints ptone/scion#304) therefore has to live in the trigger inbox, not in messaging.messaging.EventTypeenum isagent.state-changed, agent.input-needed, delivery.failed, schedule.fired, port.exposed, artifact.review; new sources need new members and a richereventbody (identifiers, source, attributes). This is apkg/messagingchange that Stage 1 owns and the messaging skill text must follow.scion notifications) are outbound fan-out of agent activity to users/agents/channels;channels_webhook.gois an outbound notification channel (NotificationChannel.Deliver, filter by message type). Neither is an inbound trigger, but trigger failures should surface through notifications (SCHEDULE_BLOCKEDprecedent) rather than a parallel path.pkg/eventbus, NATS-style topics, payload fixed toStructuredMessage) is in-process per replica and feeds chat spokes and SSE; it is not a durable trigger transport. Thehub.lifecycle_eventsoutbox (agent_lifecycle_outbox:lease_owner,lease_until,attempts,next_attempt_at, claim/renew/complete/fail store API, multi-replica drainers) is the closest existing durable event pipeline and the right template for the trigger inbox..design/lifecycle-hooks.md, shipped) fire HTTP-only actions on agent phase transitions with a store-backed transition deduper and an SSRF-safe client. Two precedents matter here: the fire-authorization gate, and${VAR}templating that separates trusted vars from untrusted ones (AGENT_NAME,TASK_SUMMARY…: body-only, JSON-escaped, opt-in viaallowedUntrustedVars). Task templating from webhook payloads should copy that rule. Hooks are a source candidate for Stage 4, not a delivery mechanism.2.3 GitHub App integration and inbound ingress
.design/github-app.md, Rev 5; "webhook-driven agent creation" is an explicit non-goal there, deferred to this work). The hub stores app id andwebhooks_enabled(admin-asserted "my hub is publicly reachable") in thegithub_appsettings section, the private key and webhook secret as hub-scoped secrets, records installations (github_installations), associates a project to one installation (project.github_installation_id) by normalised git remote with an ownership proof, and mints repo-scoped installation tokens for agents (GITHUB_TOKEN+sciontool credential-helper/gh-wrapper, refresh viaPOST /agents/{id}/refresh-token). Default token permissions already include Issues/PRs write. The App is told to subscribe only to Installation events today; there is no docs-site setup page, only.design/docs/github-app-setup.md.POST /api/v1/webhooks/githubis the only inbound unauthenticated route (RouteWebhook; signature verified in the handler; fails closed when no secret is configured, fixed 2026-09 after a private security finding; 10 MiB body limit).X-GitHub-Event/X-GitHub-Deliveryare only logged;ping,installation,installation_repositoriesare handled; all content events get200 ignored. No delivery-id dedup store, no rate limiter, no audit record for receipt. Adding a new unauthenticated signature-verified route touches seven places (route table, authz manifest posturewebhook,isUnauthenticatedEndpoint,authzopexemption or operation, route-metadata/bearer-disposition tests, proxy-mode write guard) — listed in the appendix.GET /github-app/setupis a public GET with side effects (records installations from data fetched under the App's credentials). Flagged in the same security review as needing its own look; it matters more once GitHub events can start agents.server.hub.public_url,HubEndpointFor(use)), used for invite links, OIDC issuer, Conduit and chat bridges, so webhook endpoint URLs can be rendered by the hub; the GitHub App's own setup/webhook URLs are still hand-pasted by the admin. The workstation server (scion server start) binds127.0.0.1by default. A workstation hub cannot receive webhooks from the public internet without a tunnel the user supplies. Nothing existing gives a hub inbound HTTP from outside:scion expose/tunnelare agent-port features and the Conduit relay terminates agent/broker sessions, not hub ingress.csp_reports.gois the trusted-proxy-aware per-IP + hub-wide example;keyedRateLimiterfor per-principal).2.4 What the two issues ask for, and where they meet
Roadmap triage already sized #304 Large (Medium for an MVP) and said both need one shared design pass; the triage also named the security surface: a new public, unauthenticated ingress and prompt-injection exposure of agents. A community fork (krohnjw, comment on #836) runs
@scion /plan|/implement|/review|/fixcomment commands with per-command templates; Stage 3 should make that pattern expressible as rules rather than code.2.5 In-flight work this plan must not collide with
execevent type, theskippedstatus, the tracked-fire generalisation (detachedFireRun),scheduled_exec_runs, and the response serializer with argv redaction. The trigger core must treatexecas a third action with that design's authority rules, and must not forkwakeFireRun/detachedFireRuna second time. Stage 1 should start after Phase 1 of exec schedules has merged, or coordinate branch order explicitly.2.6 Related open issues and proposed scope (from roadmap-lead's survey, 2026-11-14)
chatsource over the same matcher and actions; the only new concept is history-window injection. Not before Stage 3.ephemeralflag: auto-delete agents on completiondelete_agentaction first. Small, lifecycle area; could be done by small-issues before Stage 2/3 needs it.dispatch_agentserver.hub.public_url,HubEndpointFor); if #555 changes how that is configured, the webhook use follows it.githubbut keeps the normalised attribute vocabulary provider-neutral (repo, number, action, sender, base_ref, head_sha, labels, title, body) so a latergitlabsource reuses the rule shape. Provider app integrations stay in #1421.execis the third action; Stage 1 extracts after its Phase 1. Owner stays exec-schedules-owner.deletedlifecycle-hook triggeragent_lifecyclesource would consume the same phase events; whoever addsdeletedthere helps Stage 4.chatsource +conversationaction but not worth coupling to this workstream.a2asource is conceivable but has no asker.3. Core abstractions
The vocabulary below is proposed for
GLOSSARY.md. Note the existing collisions: notifications speak of "trigger activities", and lifecycle hooks have "triggers". This plan uses Trigger for the rule resource only; the other two should be renamed in docs over time ("activity filter", "hook event").3.1 Source
Where events come from. A source kind is code (a Go implementation); a source instance is a row (where one is needed) that the rule points at.
scheduleSchedule/ one-shotScheduledEventwebhookWebhookEndpoint(project-scoped URL + secret)githubchatagent_lifecycleA source's job is narrow: authenticate the inbound thing, bound it, normalise it into an
Event, resolve the project(s) it belongs to, and hand it to the inbox. Sources never run actions.3.2 Event
One normalised envelope for every source. Load-bearing: rules, templates and the agent-facing envelope all read it.
3.3 Trigger (the rule)
A project-scoped resource. The thing users list, pause and audit.
A schedule is then a trigger whose source is the clock and whose match is "every fire". Whether schedules become literal
Triggerrows is decision D1 (§5.1, agreed: not yet); either way the fields are the same, which is what keeps the two surfaces coherent.3.4 Action and target
Actions are the scheduler's event handlers, renamed and made callable without a schedule. The registry stays by type; the handler signature gains the event:
messagewake,interrupt)dispatch_agentissue=owner/repo#N,trigger=<id>); event JSON written to the agent (env + file, §4.6)execconversation3.5 Fire record
One row per (event, trigger): status (
fired | failed | refused | skipped), generic error text (detailed reasons go to audit/slog, exec-schedules precedent), action result reference (message id, created agent id, exec run id), executor identity. This is the scheduler's history generalised;scion schedule historycan read it through the same serializer.3.6 Durable delivery primitive (condition on D3)
The inbox is not a trigger-specific table with a trigger-specific loop. Stage 1 builds a generic leased-row work queue (working name
pkg/durablequeue) and the trigger inbox is its first consumer:Rules that keep it generic: no trigger types in the package;
Kindselects the handler;DedupKeyuniqueness is per(Kind, DedupKey); the payload is opaque; project scoping is a column for fair scheduling and purge, not a semantic. Consumers named now:trigger.event(Stage 1), the existingagent_lifecycle_outbox(optional follow-up: migrate it onto the queue as the proof of generality), and message delivery (todayDispatchState=pendingrows are re-driven only on broker reconnect, §2.2; amessage.deliverkind would give messages retry, offline queuing and replay — a separate issue to file once Stage 1 has the primitive). Scheduled fires could also enqueue through it later, which is what makes the Stage 4 convergence cheap.3.7 Rule language (D4 = CEL)
The rule engine is CEL (
github.com/google/cel-go), with a structured layer on top for common cases. Shape:Match.Types []string: event types the rule listens to (exact or prefixgithub.pull_request.*). Stored as a list and indexed, so the drainer prefilters candidate rules in SQL before evaluating any expression. Required; a rule cannot match "everything".Match.CEL string: optional predicate, compiled at authoring time against a declared environment and cached per rule revision. Empty means "all events of those types".event.type,event.source.kind,event.source.id,event.subject,event.occurred_at,event.attributes(map(string, dyn), the normalised facts the source extracted),event.payload(dyn, the bounded raw payload parsed as JSON, so power users can reach provider fields the normaliser did not lift),trigger.name,trigger.project_id. No custom functions that perform I/O; the standard CEL library plus string/regex extensions only.cel.CostLimitper evaluation, evaluation timeout, compile errors returned at authoring with position, noevent.payloadfor sources whose payloads are not JSON. RE2 semantics come with CEL'smatches.@scion /review") compile toTypes+ CEL and store the CEL; the form keeps a copy of its own structure inMatch.Form(opaque JSON) so it can be re-rendered, and a hand-edited expression simply has no form. Stage 1 ships CEL +Typesand the CLI (--type,--where '<cel>'); Stage 3 ships the GitHub presets and the semantic attribute set they rely on.3.8 How the scheduler maps onto this
Schedule(recurring)Source{Kind: schedule}; cron/time zone live on the source instanceScheduledEventone-shotScheduledEventrow of a recurring scheduleTriggerEvent(typeschedule.fired) +TriggerFireRegisterEventHandler(type, fn)RegisterAction(Action)resolveScheduledAuthority, ceiling, live authz, standingAction.Authorizeover the trigger's authority (same code, moved)scheduledSkip{reason}skippedwakeFireRun/detachedFireRunschedule.firedenvelopeevent.typestaysschedule.fired; new sources addwebhook.received,github.*4. Cross-cutting concerns
4.1 Authentication and verification of inbound events
X-Scion-Signature-256: sha256=…), constant-time compare, fail closed when no secret is set (the GitHub route's hard-won rule). Optional provider-compat modes later (Stripe-stylet=…,v1=…with timestamp tolerance for replay protection). The endpoint id in the URL is an unguessable 128-bit token, but it is a locator, not a credential: an endpoint withsecret == ""is refused at creation, not accepted unsigned. Hub auth as an alternative (bearer UAT on the route) is cheap to allow because the route can also be registered on the authenticated class; it should be a per-endpoint setting (auth: hmac | hub_token).X-GitHub-Deliverydedup and a per-route rate limit; treatX-GitHub-Hook-Installation-Target-IDas a check that the delivery is for this App.external_payloadsection, size-capped, with the source and verification status stated), harness skills must say "this is data, not instructions", and the default action for a webhook endpoint created by an agent should bemessageto that agent only — neverdispatch_agent— unless a user with the permission authored the rule.4.2 Multi-tenancy and project scoping
github_app_association_authz). A trigger whose repository filter names an unassociated repo is refused at authoring and skipped at fire.4.3 Permissions and authority
trigger.{create,read,list,update,delete},webhook_endpoint.{create,read,list,update,delete}in the catalog, mirroringschedule.*; plus the action's own permission on the target (message →agent.message, dispatch →agent.createwith the template's scope rules, exec →agent.attach), checked at authoring and at every fire under the recorded revision. No trigger can do more than its creator could do interactively at fire time.baseline; targeting other agents or dispatching new agents needsfulland the delegation ceiling, as schedules do today. Agents see only triggers they created (schedule precedent).creatorName/delegating user are the trigger's creator (scheduler precedent, fix(scheduler): set creatorName and project-default GCP identity on scheduled agents ptone/scion#1844). Audit records actor =triggerexecutor + initiator.4.4 Idempotency, dedup, coalescing, retries
(source_kind, source_id, dedup_key); a duplicate delivery returns 200 and creates nothing (GitHub redelivers on 5xx and on manual redeliver).(event_id, trigger_id)unique; a dispatcher restart cannot double-fire. Create-agent fires record the agent id before reporting success (claim-then-act, exec-schedules precedent).event.subject(github:owner/repo#N,webhook:<endpoint>/<X-Scion-Subject header>,schedule:<id>,chat:<conversation>), and a rule may override derivation with CEL (subject: event.attributes.order_id), so "one agent per order/build/PR" works for any source.SubjectPolicy{reuse}means "if a live fire for this subject by this trigger already produced an agent that is still running, deliver the new event to that agent as a message instead of dispatching another".coalesce_window(for example 30 s) foldssynchronizebursts into one fire.pendinguntil its fires are recorded, so a hub restart replays it. Events for an offline target stay queued up to a per-endpoint TTL/limit (the feat(store): Postgres backend — pgx driver, Ent schema parity, full store port, LISTEN/NOTIFY #304 "queue while offline");messagewithwakeis the alternative.4.5 Rate limiting and quotas
keyedRateLimiter); 429 withRetry-After. Per-triggermax_concurrent_dispatchesand a per-project cap on live trigger-created agents (constants first, settings later — exec-schedules precedent; Feature: Project-wide and Hub-wide Rate Limiting and Quotas ptone/scion#302 is the general quota work).hub.artifactsdependency → open question).4.6 Delivering context to the agent
type: event,event.type= the event type, withtrigger: {id, name},source,subject,attributesand the boundedexternal_payload. Full payload fetchable with the agent's own token:scion trigger event get <id>(new, agent-allowed, project-scoped read).SCION_TRIGGER_EVENT_ID,SCION_TRIGGER_IDenv; the event JSON written into the agent home at a documented path (~/.scion/trigger-event.json) at provisioning; labels for discovery (scion list --label trigger=<id>).4.7 Observability and history
scion trigger history <id>andscion trigger events(inbox view with status), web pages under the project; fires and refusals go to the audit logger (content-free: no payload bodies); counters on the trigger; Prometheus/OTel counters per source kind and outcome.4.8 Hosted vs workstation
curlfrom scripts, another local process). Anything that needs public-internet ingress is out of scope (D6): no relay, and user-run tunnels (ngrok, cloudflared,ssh -R) are not a documented workstation mode — docs say only that endpoints are reachable wherever the hub is. GitHub routing on a workstation hub is not a goal of any stage.4.9 Multi-instance hubs
lease_owner,lease_until,attempts,next_attempt_at; every replica runs a drainer that claims a bounded batch (ClaimTriggerEvents(owner, now, leaseUntil, limit)), renews the lease per fire, completes or fails with backoff, and a maintenance pass trims old rows. Ingress handlers only write (and wake the local drainer post-commit); they never fire inline, so any replica can receive. SQLite gets the same code path with one drainer.4.10 Experiment gating
hub.triggers(server + web): the trigger resources, inbox, dispatcher and generic webhook ingress route (404 while off).hub.github_triggers(server + web, requireshub.triggers): content-event normalisation and routing on the GitHub route (while off the route keeps today'signoredbehaviour).hub.triggersoff.5. Decisions for ptone
Each has a recommendation. D1–D3 shape Stage 1 and are needed before its design starts; D4–D6 can wait for the Stage 2/3 designs but affect the Stage 1 schema.
D1 — How deep does the scheduler unification go? — AGREED (a) (ptone, 2026-11-14, msg 5c316309)
schedules/scheduled_eventstables, API, CLI and web stay as they are; they call the core. Newtriggers,trigger_events,trigger_fires,webhook_endpointstables for event-driven sources. Later (Stage 4)scion trigger listcan show schedules read-only. Cost: two resource families for a while. Benefit: no migration of a live, tested surface; exec-schedules lands undisturbed; the abstraction is validated by a second consumer before any migration.scheduled_event.*vstrigger.*), two CLI groups, two web pages; duplicated handlers/serializers; two concepts for users. Containment, as Stage 1 acceptance criteria: (1) a schedule row maps field-for-field onto a trigger row (same mixins, status machine and fire record) — if not, the Stage 1 schema is wrong; (2) all fire/authority/history code lives in the core, the scheduler keeps thin adapters and gains no scheduler-only logic after Stage 1; (3) a scheduled migration of schedules into triggers in Stage 4 once the trigger CLI/web exist (alpha: no deprecation path, downgrade-floor bump). Migrating now would be a destructive migration plus a surface rewrite before the schema is validated by a second source, would collide with exec schedules landing on the same tables, and would delay webhooks.Trigger{Source: schedule}rows; migrate data; rewrite CLI/web/authz for schedules. Cleanest end state, but it is a destructive migration (downgrade floor bump), it churns the surface exec-schedules is still landing on, and it front-loads the riskiest refactor before the model has been validated by webhooks or GitHub.D2 — Who owns a webhook endpoint? — AGREED (a) (ptone, 2026-11-14, msg 5876b558: "agree a, project owned")
webhook_endpoints.project_idalways;bound_agent_idoptional. An agent that callsscion trigger webhook create --to-selfgets an endpoint bound to it plus a defaultmessagetrigger targeting itself; deleting the agent deletes bound endpoints (the feat(store): Postgres backend — pgx driver, Ent schema parity, full store port, LISTEN/NOTIFY #304 "agent-lifetime" scope) unless--persistent. Project admins can list every endpoint. This serves feat(store): Postgres backend — pgx driver, Ent schema parity, full store port, LISTEN/NOTIFY #304 verbatim while keeping one ownership model for build(deps): bump svgo from 4.0.1 to 4.0.2 in /docs-site #836./agents/{id}/webhooks/{name}as feat(store): Postgres backend — pgx driver, Ent schema parity, full store port, LISTEN/NOTIFY #304 sketches). Simple mental model, but persistent hooks that survive agent recreation then need an owner that is not the agent anyway, and GitHub rules cannot be agent-owned.D3 — Synchronous delivery or a durable inbox? — AGREED (a), conditional (ptone, 2026-11-14, msg 61a46e56: build it as a hub-wide delivery primitive, "as well factored and useful across the hub as possible", with message delivery as a prospective later consumer)
agent_lifecycle_outboxpattern, already multi-replica) matches and fires. Gives replay after restart, offline queuing (messaging has no durable retry queue of its own, §2.2), multi-instance receive, an inspectable event list, and keeps provider timeouts (GitHub: 10 s) out of the action path (agent creation can take longer than that).D4 — Match language — AGREED (b) CEL (ptone, 2026-11-14, msg 49c27a73: CEL is the underlying rule engine; higher-level UX for common cases, and something semantically GitHub-specific, layered on top)
types: [github.pull_request.opened, github.pull_request.synchronize],where: [{attr: base_ref, op: eq, value: main}, {attr: labels, op: contains, value: scion}, {attr: comment_body, op: regex, value: '^@scion\s+/review\b'}]. Cheap, safe, indexable (typescan prefilter in SQL), renders in a form, auditable. Regex only against attributes, compiled once with RE2 semantics (Goregexpis RE2: no catastrophic backtracking).google/cel-go). More expressive, familiar to GCP users, but a new dependency, a new sandboxing surface, harder to render in a UI, and nothing in feat(store): Postgres backend — pgx driver, Ent schema parity, full store port, LISTEN/NOTIFY #304/build(deps): bump svgo from 4.0.1 to 4.0.2 in /docs-site #836/fix(hub): add as_needed second-pass resolution to DispatchFinalizeEnv #994 needs more than (a). Can be added aswhere_cellater without changing the schema.D5 — Subject and concurrency policy in the core from day one? — AGREED (a) (ptone, 2026-11-14, msg b1b51b48; confirmed source-agnostic)
Subjecton the event (sources fill it:github:owner/repo#N,webhook:<endpoint>+ optional header,schedule:<id>),SubjectPolicy{new | reuse | skip, coalesce_window}on the trigger, enforced by the dispatcher with a per-(trigger, subject) live-fire record. GitHub is unusable without "one agent per PR"; adding this after Stage 1 means a schema change plus a retrofit of the dispatcher's claim logic. Stage 1 implements onlynewandskip;reuselands in Stage 3 with the agent lookup it needs.D6 — Workstation hubs and public ingress — AGREED (a), stricter (ptone, 2026-11-14, msg 6f62d6ef: anything requiring public-internet ingress is out of scope; users who tunnel a local hub with cloudflare/ngrok do so on their own, and it is not a documented workstation mode)
6. Open questions (not decisions; carried into stage designs)
hub.artifactsis default-off). Recommendation: inline ≤ 64 KiB, larger bodies rejected for generic endpoints in Stage 1 and stored as attachments in Stage 2 once the artifact dependency is decided.pull_request,issues,issue_comment,pull_request_review,pull_request_review_commentand hold Issues/PRs read-write for reply-back; existing installations need the admin to accept new permissions on GitHub. The Stage 3 design must specify the upgrade flow and the hub-side check (DefaultTokenPermissions()).@scioncommand replies, but the Stage 3 design should decide whether a comment-command's reply should name the triggering user and how a loop (App comments →issue_commentevent → App) is prevented (ignoresender.type == Botand the App's own login by default)./github-app/setuppublic GET with side effects (flagged in the 2026-09 security review). Should be fixed before GitHub events can start agents; owner TBD (security lane, not this project).@scion /review [args]as krohnjw's fork does, versus labels, versus both. Grammar and arg parsing are Stage 3 design scope; the core only needscomment_bodyas an attribute.ephemeralcreate flag settable per trigger rule (not hub-forced); terminal = activitycompletedorlimits_exceeded, or phasestopped/error/halted; neverwaiting_for_input/blocked/stalled; grace = the 60-minute purge cadence with a minimum age since the terminal transition; soft delete with a recorded reason (ephemeral_reaped); no unpushed-work guard in v1 (product call, ptone to confirm if contested). Trigger-side obligations: subject-reuse and concurrency lookups (D5) exclude soft-deleted agents; trigger-created agents get unique names. Adelete_agentaction (for example on PR close) remains a Stage 4 candidate.scion triggeras the command group (sub-commandswebhook,event,history) vsscion webhook+scion trigger. Recommendation: one group,scion trigger.7. Stages
Sizes use the project's scale (XS/S/M/L/XL). "Sub-architect" means a dedicated design pass and document before implementation; "security review" means the design and the first PR get a security reviewer (the triage flagged this as a new public ingress).
Stage 1 — Trigger core + one webhook slice (tracked as ptone#7961; owner triggers-s1-coord, staffed 2026-11-14; design now, coding after ptone#7883 and #7884 merge)
pkg/hub/triggerorpkg/triggercore): action registry (message,dispatch_agent,execadapter), authority resolution and fire-time authorization (resolveScheduledAuthorityand friends, renamed), tracked fires,skippedsentinel, fire history writer. Scheduler handlers become thin adapters. No behaviour change to schedules (existing tests are the regression suite). Includes the one piece the hub lacks today: a headless create-agent function (lifted fromdispatchAgentEventHandler) that accepts labels and an event context.webhook_endpoints,triggers,trigger_events(lease columns as inagent_lifecycle_outbox),trigger_fires(additive; no downgrade floor change). Authz operations fortrigger.*andwebhook_endpoint.*(catalog, permission registry, drift tests); route metadata and manifest;hub.triggersexperiment.POST /api/v1/hooks/{endpointID}(RouteWebhook class, HMAC, fail closed, size limit, dedup, 202); endpoint URL rendered fromHubEndpointFor(webhook); per-endpoint and per-IP token buckets (csp_reports.gopattern).Typesprefilter (§3.7); subject policynew | skip(D5a).scion trigger webhook create|list|delete,scion trigger create|list|get|pause|resume|delete,scion trigger history,scion trigger event get(agent-allowed read). Agent-mode availability decided per the CLI-modes rule.messaging.EventTypemembers (webhook.received, andtrigger.firedas the generic fallback), aneventbody that carriestrigger,event_id,source,subject,attributesand a size-cappedexternal_payloadsection; the same identifiers added toschedule.firedwhile the code is open (today it carries none); skill text update (scion-messagingevents list). Task/message templating from event attributes follows the lifecycle-hook trusted/untrusted variable rule.messageaction → envelope in a real agent → fire row visible inscion trigger history. Fan-out to the remaining Stage 1 items only after this slice is validated end to end.message.deliveron the queue is filed when Stage 1 ships.Stage 2 — General webhooks complete (ptone#304)
--to-selfconvenience;dispatch_agentaction from a webhook with task templating and event injection (§4.6); offline queuing semantics and TTL; per-endpoint auth modes (hmac,hub_token), optional timestamp replay window; ingress rate limits and quotas; payload attachment for large bodies (open question 1); web UI (project Triggers page: endpoints, rules, events, history); docs page andscion-triggersskill; notify-on-failure (shared with Schedules: notify a conversation on run failure (exec and message) ptone/scion#7895).Stage 3 — GitHub event routing (ptone#836)
githubsource on the existing App webhook: content-event normalisation (pull_request,issues,issue_comment,pull_request_review,pull_request_review_comment,pushoptional) intoEvent.Attributes(repo, number, action, sender, sender_type, base_ref, head_sha, labels, title, comment_body, html_url…); repository → project fan-out (a project binds to one installation; several projects may share a repository, so one delivery can become several events) with the installation-target-id check; delivery-id dedup and route rate limit; a receipt audit record; per-project rule authoring restricted to associated repositories; subjectgithub:owner/repo#NandSubjectPolicy{reuse}with running-agent lookup;coalesce_window; comment-command convention and bot-loop guard;dispatch_agentwith labelsissue=owner/repo#N; reply-back guidance using the installation token already available to agents; App permission/event upgrade flow and hub-side check;hub.github_triggersexperiment; web rule editor presets compiled toTypes+ CEL ("review every PR to main", "plan on@scion /plan"), the semantic GitHub attribute set they rely on; docs.dispatch_agent-from-event and templating (can be pulled forward into Stage 3 if Stage 2 is deferred); open questions 2–5; the/github-app/setupfix (security lane).Stage 4 — Convergence and new sources (optional)
scion trigger listincludesschedulesource; shared web page); migrate rows only if D1 is revisited.chatsource for feat(chat): content-based routing rules — watch channels for patterns and relay to agents with history ptone/scion#994 content routing (the same matcher over message attributes; history-window injection is the only new concept).agent_lifecyclesource (hook events as triggers; closes the loop with.design/lifecycle-hooks.md),conversationaction,delete_agentaction for PR-close cleanup.Ordering
Stage 2 and Stage 3 can run in parallel after Stage 1 if two sub-architects are staffed; Stage 3 then owns the
dispatch_agent-from-event work and Stage 2 rebases on it.Coordinated items relative to this work (agreed split, ptone 2026-11-14):
server.hub.public_urlconstraint; #2884 low priority)8. Acceptance criteria for the plan (what "agreed" means) — met 2026-11-14 (D1–D6 answered; stages and staffing accepted by ptone's agreement to the proposals; vocabulary as proposed in §3; open questions assigned to stage designs)
9. Revision log
All reactions