diff --git a/docs/CLOUD.md b/docs/CLOUD.md index bdd1e8b65..a53382a74 100644 --- a/docs/CLOUD.md +++ b/docs/CLOUD.md @@ -647,7 +647,7 @@ decides which form is meant. `--on [:key=value,…]` takes `github` (`repository`, `labels`, `contains`, `events`, and the pull-request subscription opt-outs `reviews`, `checks`, `comments`), `gitlab` (`project`, `labels`, `contains`, `events`), -`slack` (`channel`, `contains`), `linear` (`team`, `project`, `labels`, +`slack` (`channel`, `contains`, `mentioned`), `linear` (`team`, `project`, `labels`, `contains`, `events`), `jira` (`project`, `labels`, `contains`) or `shortcut` (`workspace`, `team`, `labels`, `contains`), each at most once. A Linear `team` matches the team's name or its key. A Linear `events` is `issues` (the diff --git a/examples/nabis-uc1/README.md b/examples/nabis-uc1/README.md new file mode 100644 index 000000000..3e361a1b7 --- /dev/null +++ b/examples/nabis-uc1/README.md @@ -0,0 +1,201 @@ +# Nabis UC1 — pickup routing demo + +A Slack message starts a run for a fictional pickup-routing change. A planner +generates a task graph at runtime. Coders run in dependency order and produce a +JSON rule table. The demo asks the coders to omit the held-pickup rule on the +first pass. A reviewer rejects that omission, a repair agent adds the rule, and +a second review and deterministic routing checks must both pass. + +The thread shows the lead's assignments, the first coder build, the reviewer's +send-back, the repair, the approval pause, and the lead's summary. Flows +posts the approval prompt in the originating thread and parks on +`f.human`. A verified reply from the designated user must match the +workspace, channel, thread, and open wait. The local bridge also checks the run reference. Approval records +the repaired table as a simulated shipment in the local journal. Decline +closes the run without a shipment record. Both paths reply in the same thread +with **Done**, **Next**, and **Blocked**. + +## Build from the checkout + +Use Node 22.18 or later, Bun, npm, and Rust. From the repository root: + +```sh +(cd packages/surface && bun install --frozen-lockfile --ignore-scripts && bun run build) +npm ci --prefix packages/sdk --ignore-scripts +npm install ./packages/surface --prefix packages/sdk --no-save --ignore-scripts +npm run build --prefix packages/sdk +mkdir -p node_modules/@relayflows +ln -sfn ../../packages/sdk/node_modules/@relayflows/surface node_modules/@relayflows/surface +(cd kernel && cargo build --locked -p relayflowd) +export RELAYFLOWD_BIN="$PWD/kernel/target/debug/relayflowd" +``` + +If the daemon was built under a separate Cargo target directory, set +`RELAYFLOWD_BIN` to that binary instead. + +## Reproduce the recorded run + +```sh +RELAYFLOWS_SLACK_MOCK=1 node packages/sdk/dist/cli.js check --json examples/nabis-uc1/uc1.flow.ts +npm run typecheck:examples --prefix packages/surface +node examples/nabis-uc1/verify.mjs +node examples/nabis-uc1/verify.mjs --real-agent +node --test examples/nabis-uc1/*.test.mjs +``` + +The first verification uses mock Codex and mock Slack. It checks approval, +decline, duplicate delivery, competing decisions, wrong workspace or channel, +wrong approver or thread, stale approval, and bot replies. The second runs +signed-in Codex with `gpt-5.6-sol` and keeps Slack mocked. Both modes start +the real local daemon and exercise `flows run`, `flows answer`, and +`flows resume` with Cloud reporting and Observer disabled. They check the +journal before and after approval and print redacted JSON receipts for the +six threaded replies and the approval. The shim runs Codex in a separate, +read-only working directory with shell, delegated agents, apps, plugins, hooks, +and web search disabled. See the recorded +[mock-agent run](verification/mock-agent-mock-slack.json) and +[real-agent run](verification/real-agent-mock-slack.json) for the original +two-reply demonstration. + +The real-agent verifier passed on Node 26.8.1 with `gpt-5.6-sol`. To send the +two mock Slack callbacks individually, use the team and channel from the +fixture, approver `UAPPROVER1`, and a fresh state directory. + +```sh +export UC1_SLACK_MODE=mock +export UC1_SLACK_TEAM=TUC1DEMO UC1_SLACK_CHANNEL=CUC1DEMO UC1_SLACK_APPROVER=UAPPROVER1 +export UC1_STATE_DIR="$(mktemp -d)" +node examples/nabis-uc1/slack-event.mjs examples/nabis-uc1/fixtures/mention.json +cp examples/nabis-uc1/fixtures/approve.json "$UC1_STATE_DIR/approve.json" +node examples/nabis-uc1/slack-event.mjs "$UC1_STATE_DIR/approve.json" +``` + +The mock-agent verification passed on Node 22.23.3. It also resumed approval +successfully after stopping the local daemon while the run was parked. +The [SDK regression receipt](verification/helper-resume-regression.txt) +shows the failure without the helper replay fix and the pass with it restored. + +## Hosted Slack recording + +This path uses the Cloud workspace's existing Slack connection. The hosted +runner supplies the Relayfile mount for `f.slack.reply`. Connect the +`AgentWorkforce/flows` repository and Codex/OpenAI account in the same Cloud +workspace, and sign in to the Flows CLI. The Slack approver handle for this +demo is `khaliq`. + +After deployment is authorized, deploy the self-contained source: + +```sh +node packages/sdk/dist/cli.js deploy examples/nabis-uc1/uc1.flow.ts \ + --repo AgentWorkforce/flows \ + --on 'slack:channel=C0B9Z4CLG1J,mentioned=true,contains=[UC1 SYNTHETIC] nabis-uc1' \ + --approver khaliq --agents codex --name nabis-uc1 --no-connect +``` + +In **#watchdog-test** (`C0B9Z4CLG1J`), select **Agent Relay** from Slack's mention +picker, then append ` [UC1 SYNTHETIC] nabis-uc1` immediately after the +mention. Send `@Agent Relay [UC1 SYNTHETIC] nabis-uc1` as a new top-level message. +Cloud filters the channel, the mention and the command. UC1 checks the exact +message text and the sender in the mounted Slack record before starting any +agents or replies. On a cold start, UC1 waits up to 60 seconds for the +trigger's record to appear in the mirror. The first threaded reply links to +the live run in Flows Cloud, followed by the role updates. Cloud posts the +`f.human` question in the same thread. +The designated operator replies `yes` or `no` to resume. Inspect the linked +run in the Cloud dashboard. Cloud may add its own acknowledgement and +terminal receipt alongside the demo's role updates. + +The hosted test exercises the input and mounted-record checks and approval +branches using local fixtures. + +## Local recording from a real Slack mention + +### One-time setup + +1. Build the checkout, sign in to the real Codex CLI on `PATH`, and set + `RELAYFLOWD_BIN` if using a separate native build. Sign in with + `agent-relay cloud login` for the Cloud dashboard. For the Observer link, + use the approved active Agent Relay workspace or configure + `RELAYCAST_WORKSPACE_KEY` in the local environment. Keep + `FLOWS_NO_OBSERVER` unset for the recording. +2. In the approved Slack workspace, enable Socket Mode on the demo app. + Load its app-level `xapp-` token with `connections:write` into + `UC1_SLACK_APP_TOKEN` in the operator's shell. Subscribe the bot to + `app_mention` and `message.channels` with `app_mentions:read` and + `channels:history`. Install the app and invite it to **#watchdog-test** + (`C0B9Z4CLG1J`). + [Socket Mode setup](https://docs.slack.dev/apis/events-api/using-socket-mode/) +3. Use an existing approved Relayfile writeback connection with access to the + same channel and `chat:write` for its Slack bot. Point + `RELAYFILE_MOUNT_PATH` at the root containing `slack/`. Keep that mount + running with writeback enabled while recording. The listener uses the app + token for ingress and Relayfile for replies. It has no `SLACK_BOT_TOKEN` + setting. +4. Set `UC1_SLACK_TEAM` to the approved Slack workspace ID, + `UC1_SLACK_BOT_USER` to the demo app's bot user ID (the ID inside the + mention), and `UC1_SLACK_APPROVER` to the human Slack user ID who posts + both the trigger and the decision. Set `UC1_STATE_DIR` to a fresh private + directory, for example with `export UC1_STATE_DIR="$(mktemp -d)"`. Keep + that path for the whole recording. + +### Run the recording + +From the built repository root, launch the listener and leave its terminal open: + +```sh +node examples/nabis-uc1/slack-listen.mjs +``` + +The listener hands verified callbacks to `slack-event.mjs`. The bridge invokes +the Flows CLI built by this checkout: + +```text +flows run --local-agent --cloud-mirror --json --data-dir --input +flows answer --json --data-dir --by slack:@ --note +flows resume --local-agent --cloud-mirror --json --data-dir +``` + +1. Wait for the listening message. As the designated human, select the actual + app in Slack's mention picker and post `@YourSlackApp nabis-uc1` as a new + message in **#watchdog-test**. Socket Mode delivers the authenticated + callback to the listener, which filters it and passes it to + `slack-event.mjs`. The bridge starts the real Codex flow and all + writebacks go to the originating thread. +2. Leave the approval pause visible for the recording. When ready, reply + `approve UC1-…` or `decline UC1-…` as the designated human in that + thread, using the reference from the prompt. The listener forwards the + scoped `message` event to the bridge, which checks the journaled gate. +3. Inspect the lead's **Done / Next / Blocked** reply. Save the terminal's + `runId` and `humanWait.waitId` if you need the local receipts. Stop the + listener with Ctrl-C after the summary. + +The listener saves accepted callbacks under `UC1_STATE_DIR/inbox` before +acknowledging them to Slack. If a flow command fails twice, correct the issue +and start the listener again with the same state directory. It replays the +original callback, including an approval that reached the journal but whose +resume failed. + +### Follow the run + +The terminal prints `Observer: https://agentrelay.com/observer?key=ot_live_` +when the run's Observer link is ready. Open it locally to see the live step +progress and approval pause. Keep the keyed link out of Relay messages, +Slack replies, and recordings. + +The terminal also prints `Dashboard: /dashboard/workflow//runner` +after Cloud registers the run. Open the dashboard to follow the run graph, +agent handoffs, step transcripts, Slack effects, and approval outcome. The +Cloud dashboard links the parked attempt to the resumed attempt. The local +journal retains the same run ID throughout, including the approval and the +final summary. + +```sh +node packages/sdk/dist/cli.js status --json --data-dir "$UC1_STATE_DIR/journal" '' +``` + +The live procedure runs real Codex agents for a fictional routing task and +records only a simulated shipment. Delivery through the approved Slack +connection remains unverified. For a separate authenticated event source, +the one-shot bridge accepts a private verified callback file or `-` for +stdin. Set `UC1_SLACK_MODE=live` and `UC1_SLACK_CHANNEL` explicitly for that +path. The Socket Mode listener sets them for you. diff --git a/examples/nabis-uc1/agent-cli/codex b/examples/nabis-uc1/agent-cli/codex new file mode 100755 index 000000000..5806e6fd0 --- /dev/null +++ b/examples/nabis-uc1/agent-cli/codex @@ -0,0 +1,45 @@ +#!/bin/sh +# This demo needs JSON results. Give every model turn a fresh, read-only process +# with shell, delegated agents, apps, plugins, hooks and web search disabled. +# The bridge puts this directory first on PATH for the pinned Codex role. +shim_dir="${0%/*}" +case "${PATH:-}" in + "$shim_dir") + printf '%s\n' 'UC1 requires a Codex executable on PATH outside the shim.' >&2 + exit 127 + ;; + "$shim_dir:"*) + PATH="${PATH#*:}" + export PATH + ;; +esac + +refuse() { + printf '%s\n' 'UC1 accepts only fresh Codex turns and model probes.' >&2 + exit 2 +} + +if [ "${1:-}" = 'exec' ]; then + shift + case "${1:-}" in + --skip-git-repo-check) + [ "${2:-}" = '--dangerously-bypass-approvals-and-sandbox' ] || refuse + shift 2 + ;; + --ephemeral) + [ "${2:-}" = '--sandbox' ] && [ "${3:-}" = 'read-only' ] && [ "${4:-}" = '--skip-git-repo-check' ] || refuse + shift 4 + ;; + *) refuse ;; + esac + for option do + case "$option" in + --) break ;; + --dangerously-bypass-approvals-and-sandbox|--sandbox|--sandbox=*|--full-auto) refuse ;; + esac + done + exec codex -a never exec --ignore-user-config --disable shell_tool --disable unified_exec \ + --disable multi_agent --disable apps --disable plugins --disable hooks -c web_search=disabled \ + --skip-git-repo-check --sandbox read-only --ephemeral "$@" +fi +exec codex "$@" diff --git a/examples/nabis-uc1/contracts.ts b/examples/nabis-uc1/contracts.ts new file mode 100644 index 000000000..e15d59593 --- /dev/null +++ b/examples/nabis-uc1/contracts.ts @@ -0,0 +1,7 @@ +// The hosted deployment uploads only uc1.flow.ts. Keep the bridge's imports +// here while sharing the same contract with the self-contained flow source. +export { + approvalAttribution, approvalQuestion, approverIdentity, CHANNEL_ID, EVENT_ID, + MOCK_PROMPT_TS, orderedTasks, record, REQUEST_ID, routes, SLACK_TS, TEAM_ID, USER_ID, + type RunInput, +} from './uc1.flow.ts'; diff --git a/examples/nabis-uc1/fixtures/approve.json b/examples/nabis-uc1/fixtures/approve.json new file mode 100644 index 000000000..4e7ad200a --- /dev/null +++ b/examples/nabis-uc1/fixtures/approve.json @@ -0,0 +1,13 @@ +{ + "type": "event_callback", + "team_id": "TUC1DEMO", + "event_id": "EvMockApprove1", + "event": { + "type": "message", + "channel": "CUC1DEMO", + "user": "UAPPROVER1", + "thread_ts": "1780000000.000001", + "ts": "1780000001.000001", + "text": "approve UC1-3f9d57368e0adee4" + } +} diff --git a/examples/nabis-uc1/fixtures/codex b/examples/nabis-uc1/fixtures/codex new file mode 100755 index 000000000..d3e345ec8 --- /dev/null +++ b/examples/nabis-uc1/fixtures/codex @@ -0,0 +1,45 @@ +#!/usr/bin/env node +// MOCK Codex CLI. The demo still uses the real Flows agent worker and journal. +const argv = process.argv.slice(2); +if (argv[0] === '--version') { + console.log('codex-cli 0.154.0'); +} else if (argv[0] === 'login') { + console.log('Logged in using ChatGPT'); +} else { + const options = argv.slice(0, argv.indexOf('--')); + if (!options.includes('read-only') || options.includes('--dangerously-bypass-approvals-and-sandbox')) { + throw new Error('UC1 agent invocation did not enforce read-only mode.'); + } + const task = argv.at(-1); + if (task.includes('RELAYFLOWS_MODEL_READY')) { + console.log('RELAYFLOWS_MODEL_READY'); + } else { + const contract = { ready: 'pickup-queue', held: 'manual-review', canceled: 'archive' }; + let result; + if (task.startsWith('UC1 planner.')) { + result = { tasks: [ + { id: 'exceptions', statuses: ['held', 'canceled'], dependsOn: ['baseline'] }, + { id: 'baseline', statuses: ['ready'], dependsOn: [] }, + ] }; + } else if (task.startsWith('UC1 coder.')) { + const [, json] = /task (\{.*?\}) as a JSON routing table/u.exec(task); + const { statuses } = JSON.parse(json); + result = { rules: Object.fromEntries(statuses.filter(status => status !== 'held') + .map(status => [status, contract[status]])) }; + } else if (task.startsWith('UC1 first review.')) { + result = { verdict: 'reject', finding: 'missing-held-route' }; + } else if (task.startsWith('UC1 repair.')) { + result = { rules: contract }; + } else if (task.startsWith('UC1 repaired review.')) { + result = { verdict: 'approve' }; + } else { + throw new Error('Unexpected mock agent task.'); + } + console.log(JSON.stringify({ + type: 'item.completed', item: { id: 'fixture-response', type: 'agent_message', text: JSON.stringify(result) }, + })); + console.log(JSON.stringify({ + type: 'turn.completed', usage: { input_tokens: 10, cached_input_tokens: 0, output_tokens: 10 }, + })); + } +} diff --git a/examples/nabis-uc1/fixtures/mention.json b/examples/nabis-uc1/fixtures/mention.json new file mode 100644 index 000000000..cfdd41ee8 --- /dev/null +++ b/examples/nabis-uc1/fixtures/mention.json @@ -0,0 +1,12 @@ +{ + "type": "event_callback", + "team_id": "TUC1DEMO", + "event_id": "EvMockMention1", + "event": { + "type": "app_mention", + "channel": "CUC1DEMO", + "user": "UFIXTURE1", + "ts": "1780000000.000001", + "text": "<@UBOTDEMO> nabis-uc1" + } +} diff --git a/examples/nabis-uc1/flows.json b/examples/nabis-uc1/flows.json new file mode 100644 index 000000000..66f172fb3 --- /dev/null +++ b/examples/nabis-uc1/flows.json @@ -0,0 +1,4 @@ +{ + "cli": "codex", + "models": ["gpt-5.6-sol"] +} diff --git a/examples/nabis-uc1/hosted.test.mjs b/examples/nabis-uc1/hosted.test.mjs new file mode 100644 index 000000000..66147229b --- /dev/null +++ b/examples/nabis-uc1/hosted.test.mjs @@ -0,0 +1,168 @@ +import assert from 'node:assert/strict'; +import { exec } from 'node:child_process'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import test from 'node:test'; +import { setTimeout as delay } from 'node:timers/promises'; +import { promisify } from 'node:util'; +import { getFlowDefinition } from '@relayflows/surface/runtime'; +import uc1, { routes } from './uc1.flow.ts'; + +delete process.env.RELAYFLOWS_SLACK_MOCK; +const cloudRunId = 'cloud-run_test-1'; +const cloudBase = 'https://flows.example.test/cloud'; +process.env.RELAYFLOW_V2_CLOUD_RUN_ID = cloudRunId; +process.env.FLOWS_CLOUD_URL = cloudBase + '/'; + +const execCommand = promisify(exec); +const text = '<@U0B2596R7EZ> [UC1 SYNTHETIC] nabis-uc1'; +const channel = 'C0B9Z4CLG1J'; +const ts = '1780000000.000001'; +const path = '/slack/channels/C0B9Z4CLG1J__watchdog-test/messages/1780000000_000001/meta.json'; +const trigger = { + approver: 'khaliq', + issue: { source: 'slack', body: text, channelId: channel, mentioned: true }, + event: { provider: 'slack', eventType: 'message.created', deliveryId: 'fixture-delivery', paths: [path] }, +}; +const record = { channel, ts, text, user: 'U0ADJH4P83T', is_bot: false, thread_ts: null }; +const responses = { + planner: { tasks: [ + { id: 'baseline', statuses: ['ready', 'canceled'], dependsOn: [] }, + { id: 'held', statuses: ['held'], dependsOn: ['baseline'] }, + ] }, + 'coder-baseline': { rules: { ready: routes.ready, canceled: routes.canceled } }, + 'coder-held': { rules: {} }, + 'review-first': { verdict: 'reject', finding: 'missing-held-route' }, + repair: { rules: routes }, + 'review-repair': { verdict: 'approve' }, +}; + +async function rehearse(t, { input = trigger, message = record, approve = true, mountDelay = 0 } = {}) { + const fixture = await mkdtemp(join(tmpdir(), 'uc1-hosted-fixture-')); + t.after(() => rm(fixture, { recursive: true, force: true })); + const recordPath = join(fixture, path); + await mkdir(dirname(recordPath), { recursive: true }); + const writeRecord = () => writeFile(recordPath, JSON.stringify(message)); + if (!mountDelay) await writeRecord(); + const calls = { commands: [], replies: [], agents: [], gates: [], verdict: '', repliesWhenPlannerStarts: 0 }; + await getFlowDefinition(uc1).body({ + async run(command) { + calls.commands.push(command); + const child = execCommand(command, { + encoding: 'utf8', env: { PATH: process.env.PATH, RELAYFILE_MOUNT_PATH: fixture }, + }); + const mount = mountDelay && calls.commands.length === 1 ? delay(mountDelay).then(writeRecord) : undefined; + const [result] = await Promise.all([child, mount]); + return result.stdout; + }, + async agent(name, { cli }) { + assert.equal(cli, 'codex'); + assert.ok(responses[name]); + if (name === 'planner') calls.repliesWhenPlannerStarts = calls.replies.length; + calls.agents.push(name); + return { completionReason: 'success', summary: JSON.stringify(responses[name]) }; + }, + slack: { + async reply(channelId, thread, content) { + assert.equal(channelId, channel); + assert.equal(thread, ts); + calls.replies.push(content); + }, + }, + async human(question, recipient) { + calls.gates.push({ question, recipient, repliesWhenParked: calls.replies.length }); + return approve; + }, + done(verdict) { calls.verdict = verdict; }, + }, input); + return calls; +} + +test('uses the native approver gate between the role replies and simulated shipment', async t => { + const calls = await rehearse(t, { message: { provider: 'slack', payload: record } }); + assert.equal(calls.verdict, 'success'); + assert.deepEqual(calls.agents, Object.keys(responses)); + assert.deepEqual(calls.gates, [{ + question: 'Approve simulated shipment for UC1-1780000000000001? Reply yes or no in this thread.', + recipient: { to: 'khaliq' }, + repliesWhenParked: 5, + }]); + assert.equal(calls.replies.length, 6); // Cloud also delivers the approval prompt. + assert.equal(calls.repliesWhenPlannerStarts, 1); + assert.ok(calls.replies[0].endsWith( + `*UC1 started*\n<${cloudBase}/dashboard/workflow/${cloudRunId}/runner|Open this run in Flows Cloud>`, + )); + assert.match(calls.replies.at(-1), /\*Lead summary\*[\s\S]+\*Blocked\* None\./u); + assert.match(calls.commands.at(-1), /simulate-ship/u); +}); + +test('records a decline without a simulated shipment', async t => { + const calls = await rehearse(t, { approve: false }); + assert.equal(calls.verdict, 'declined'); + assert.equal(calls.commands.length, 1); + assert.match(calls.replies.at(-1), /designated approver declined/u); +}); + +test('drops empty query and fragment separators from the Cloud run link', async t => { + t.after(() => { process.env.FLOWS_CLOUD_URL = cloudBase + '/'; }); + for (const separator of ['?', '#']) { + process.env.FLOWS_CLOUD_URL = `${cloudBase}/${separator}`; + const calls = await rehearse(t); + assert.equal(calls.verdict, 'success'); + assert.ok(calls.replies[0].includes(`<${cloudBase}/dashboard/workflow/${cloudRunId}/runner|`)); + } +}); + +test('refuses Cloud bases the SDK rejects before it posts a link or runs an agent', async t => { + t.after(() => { process.env.FLOWS_CLOUD_URL = cloudBase + '/'; }); + for (const base of ['http://flows.example.test/cloud', `${cloudBase}?foo=1`, `${cloudBase}#notes`, `${cloudBase}/%7C`]) { + process.env.FLOWS_CLOUD_URL = base; + const calls = await rehearse(t); + assert.equal(calls.verdict, 'step_failed', base); + assert.deepEqual([...calls.replies, ...calls.agents], []); + } +}); + +test('waits for the exact canonical Slack record when the mirror starts late', async t => { + const alias = `/slack/channels/${channel}/messages/${ts}.json`; + const input = { ...trigger, event: { ...trigger.event, paths: [alias] } }; + const calls = await rehearse(t, { + input, + mountDelay: 300, + message: { ...record, raw_event: { ...record, type: 'message' } }, + }); + assert.equal(calls.verdict, 'success'); + assert.ok(calls.commands[0].includes(path)); + assert.deepEqual(calls.agents, Object.keys(responses)); +}); + +test('blocks other senders, bots, edits and thread replies before any agent or Slack step', async t => { + for (const override of [ + { user: 'UOTHER123' }, { is_bot: true }, { edited_ts: '1780000000.000002' }, + { text: '<@UOTHER123> [UC1 SYNTHETIC] nabis-uc1' }, + { thread_ts: '1780000000.000002' }, { raw_event: { ...record, type: 'message', user: 'UOTHER123' } }, + ]) { + const calls = await rehearse(t, { message: { ...record, ...override } }); + assert.equal(calls.verdict, 'step_failed'); + assert.equal(calls.commands.length, 1); + assert.deepEqual([...calls.agents, ...calls.replies, ...calls.gates], []); + } +}); + +test('refuses another channel, non-exact commands, other approvers and unrelated event paths', async t => { + for (const input of [ + { ...trigger, issue: { ...trigger.issue, channelId: 'COTHER123' } }, + { ...trigger, issue: { ...trigger.issue, body: text + ' extra' } }, + { ...trigger, issue: { ...trigger.issue, body: text.replace('U0B2596R7EZ', 'UOTHER123') } }, + { ...trigger, issue: { ...trigger.issue, body: '[UC1 SYNTHETIC] nabis-uc1' } }, + { ...trigger, issue: { ...trigger.issue, mentioned: false } }, + { ...trigger, approver: 'other' }, + { ...trigger, event: { ...trigger.event, paths: [path.replace('/messages/', '/threads/')] } }, + { ...trigger, event: { ...trigger.event, paths: [path, path.replace('000001', '000002')] } }, + ]) { + const calls = await rehearse(t, { input }); + assert.equal(calls.verdict, 'step_failed'); + assert.deepEqual([...calls.commands, ...calls.agents, ...calls.replies, ...calls.gates], []); + } +}); diff --git a/examples/nabis-uc1/slack-envelope.mjs b/examples/nabis-uc1/slack-envelope.mjs new file mode 100644 index 000000000..39ab97701 --- /dev/null +++ b/examples/nabis-uc1/slack-envelope.mjs @@ -0,0 +1,50 @@ +import { EVENT_ID, record, SLACK_TS, USER_ID } from './contracts.ts'; + +export const mention = /^<@[UW][A-Z0-9]{2,31}> nabis-uc1$/u; +export const decision = /^(approve|decline) (UC1-[a-f0-9]{16})$/u; + +export function requireMatch(value, pattern, description) { + if (typeof value !== 'string' || !pattern.test(value)) throw new Error(`Invalid ${description}.`); + return value; +} + +export function readEnvelope(value, config) { + const envelope = record(value); + const event = record(envelope.event); + if (envelope.type !== 'event_callback' || envelope.team_id !== config.team || event.channel !== config.channel) { + throw new Error('Event is outside the approved Slack workspace and test channel.'); + } + if (envelope.is_ext_shared_channel === true || event.subtype !== undefined || event.bot_id !== undefined + || event.app_id !== undefined || [event.team, event.user_team, event.source_team] + .some(team => team !== undefined && team !== config.team)) { + throw new Error('Expected an original message from a user in the approved workspace.'); + } + if (event.type !== 'app_mention' && event.type !== 'message') { + throw new Error('Expected a Slack app_mention or threaded message.'); + } + requireMatch(event.user, USER_ID, 'Slack sender ID'); + requireMatch(event.ts, SLACK_TS, 'Slack message timestamp'); + requireMatch(envelope.event_id, EVENT_ID, 'Slack event ID'); + return { event, eventId: envelope.event_id }; +} + +export function socketCallback(frame, config) { + if (frame.type !== 'events_api' || typeof frame.envelope_id !== 'string' || !frame.envelope_id) return; + let checked; + try { checked = readEnvelope(frame.payload, config); } catch { return; } + const { event, eventId } = checked; + if (event.user !== config.approver || typeof event.text !== 'string' + || (event.type === 'app_mention' + ? event.thread_ts !== undefined || event.text !== `<@${config.bot}> nabis-uc1` + : !SLACK_TS.test(event.thread_ts) || !decision.test(event.text))) return; + + // Forward only the fields the local bridge needs. Slack callbacks can include + // verification tokens, authorization details, and unrelated message metadata. + return { + type: 'event_callback', team_id: config.team, event_id: eventId, + event: { + type: event.type, channel: config.channel, user: event.user, ts: event.ts, text: event.text, + ...(event.type === 'message' ? { thread_ts: event.thread_ts } : {}), + }, + }; +} diff --git a/examples/nabis-uc1/slack-envelope.test.mjs b/examples/nabis-uc1/slack-envelope.test.mjs new file mode 100644 index 000000000..4444612dc --- /dev/null +++ b/examples/nabis-uc1/slack-envelope.test.mjs @@ -0,0 +1,48 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { socketCallback } from './slack-envelope.mjs'; + +const config = { team: 'TUC1DEMO', channel: 'C0B9Z4CLG1J', approver: 'UOPERATOR1', bot: 'UBOTDEMO' }; +const mention = { + type: 'app_mention', channel: config.channel, user: config.approver, + ts: '1780000000.000001', text: '<@UBOTDEMO> nabis-uc1', +}; +const approval = { + type: 'message', channel: config.channel, user: config.approver, channel_type: 'channel', + ts: '1780000001.000004', thread_ts: mention.ts, text: 'approve UC1-0123456789abcdef', +}; +const frame = (event, overrides = {}) => ({ + type: 'events_api', envelope_id: 'slack-envelope', + payload: { type: 'event_callback', team_id: config.team, event_id: 'EvTrigger1', event, ...overrides }, +}); + +test('forwards the exact top-level mention and strips unrelated fields', () => { + const result = socketCallback(frame({ ...mention, blocks: [] }, { token: 'fixture', authorizations: [] }), config); + assert.deepEqual(result, { type: 'event_callback', team_id: config.team, event_id: 'EvTrigger1', event: mention }); +}); + +test('only forwards a threaded decision with the demo command from the designated human', () => { + const result = socketCallback(frame(approval), config); + assert.equal(result.event.thread_ts, mention.ts); + assert.equal(result.event.text, approval.text); + assert.equal(result.event.channel_type, undefined); + assert.equal(socketCallback(frame({ ...approval, text: 'decline UC1-0123456789abcdef' }), config).event.type, 'message'); + for (const change of [ + { thread_ts: undefined }, { thread_ts: 'bad' }, { text: 'unrelated text' }, + { user: 'UOTHER1' }, { bot_id: 'BSOMEBOT' }, { subtype: 'message_changed' }, + ]) assert.equal(socketCallback(frame({ ...approval, ...change }), config), undefined); +}); + +test('ignores other workspaces, channels, users, mentions, and envelope types', () => { + for (const candidate of [ + frame(mention, { team_id: 'TOTHER1' }), + frame(mention, { is_ext_shared_channel: true }), + frame({ ...mention, channel: 'COTHER1' }), + frame({ ...mention, user: 'UOTHER1' }), + frame({ ...mention, text: '<@UOTHERBOT> nabis-uc1' }), + frame({ ...mention, text: '<@UBOTDEMO> real customer task' }), + frame({ ...mention, thread_ts: mention.ts }), + { ...frame(mention), type: 'interactive' }, + { ...frame(mention), envelope_id: undefined }, + ]) assert.equal(socketCallback(candidate, config), undefined); +}); diff --git a/examples/nabis-uc1/slack-event.mjs b/examples/nabis-uc1/slack-event.mjs new file mode 100644 index 000000000..da0dd63f1 --- /dev/null +++ b/examples/nabis-uc1/slack-event.mjs @@ -0,0 +1,199 @@ +import { spawn } from 'node:child_process'; +import { createHash, randomUUID } from 'node:crypto'; +import { once } from 'node:events'; +import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import { delimiter, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { JournalClient } from '../../packages/sdk/dist/index.js'; +import { readHumanWait } from '../../packages/sdk/dist/authored-human.js'; +import { ensureDaemon } from '../../packages/sdk/dist/daemon-lifecycle.js'; +import { slackMount } from '../../packages/sdk/dist/slack-preflight.js'; +import { + approvalAttribution, approvalQuestion, approverIdentity, CHANNEL_ID, MOCK_PROMPT_TS, + REQUEST_ID, SLACK_TS, TEAM_ID, USER_ID, +} from './contracts.ts'; +import { decision, mention, readEnvelope, requireMatch } from './slack-envelope.mjs'; + +const flow = fileURLToPath(new URL('./uc1.flow.ts', import.meta.url)); +const flows = fileURLToPath(new URL('../../packages/sdk/dist/cli.js', import.meta.url)); +const agentCli = fileURLToPath(new URL('./agent-cli', import.meta.url)); +const fixtures = fileURLToPath(new URL('./fixtures', import.meta.url)); + +function scope(env) { + const mode = requireMatch(env.UC1_SLACK_MODE, /^(mock|live)$/u, 'UC1_SLACK_MODE'); + const state = env.UC1_STATE_DIR; + if (!state) throw new Error('Set UC1_STATE_DIR to a private local directory.'); + if (mode === 'live' && (!env.RELAYFILE_MOUNT_PATH || !slackMount(env))) { + throw new Error('Live UC1 requires the existing approved Relayfile Slack mount.'); + } + return { + mode, state: resolve(state), + team: requireMatch(env.UC1_SLACK_TEAM, TEAM_ID, 'approved Slack workspace ID'), + channel: requireMatch(env.UC1_SLACK_CHANNEL, CHANNEL_ID, 'approved test channel ID'), + approver: requireMatch(env.UC1_SLACK_APPROVER, USER_ID, 'designated approver Slack ID'), + }; +} + +const journalDir = config => join(config.state, 'journal'); + +async function readText(stream) { + stream.setEncoding('utf8'); + let text = ''; + for await (const chunk of stream) text += chunk; + return text; +} + +async function invokeFlows(config, command, args, admissionKey) { + const env = { ...process.env }; + const options = ['--json', '--data-dir', journalDir(config)]; + if (command !== 'answer') { + options.push('--local-agent'); + if (config.mode === 'live') options.push('--cloud-mirror'); + } + if (config.mode === 'mock') { + // An empty explicit token blocks the signed-in CLI's Cloud-login fallback. + // Rehearsals run the same CLI without opening an Observer or Cloud session. + Object.assign(env, { FLOWS_CLOUD_TOKEN: '', FLOWS_CLOUD_MIRROR: '0', FLOWS_NO_OBSERVER: '1' }); + } + if (admissionKey) env.RELAYFLOW_AUTHORED_ADMISSION_KEY = admissionKey; + + // The CLI prints the Observer URL and dashboard receipt to the local + // terminal as soon as they are available. Never include an Observer key + // in the bridge's JSON receipt, state file, or Slack replies. + const child = spawn(process.execPath, [flows, command, ...options, ...args], { + env, stdio: ['ignore', 'pipe', 'inherit'], + }); + const [[status], stdout] = await Promise.all([once(child, 'close'), readText(child.stdout)]); + let report; + try { report = JSON.parse(stdout); } + catch { throw new Error(`flows ${command} did not return a JSON receipt (exit ${status ?? 'signal'}).`); } + if (config.mode === 'live' && command !== 'answer' && report.runId && !report.observerUrl) { + console.error('UC1 Observer link unavailable. Check the local Agent Relay workspace configuration.'); + } + delete report.observerUrl; + return { status, report }; +} + +function requestFor(config, thread) { + const digest = createHash('sha256').update([config.mode, config.team, config.channel, thread].join('/')).digest('hex'); + return `UC1-${digest.slice(0, 16)}`; +} + +async function readState(path) { + try { return JSON.parse(await readFile(path, 'utf8')); } + catch (error) { if (error.code !== 'ENOENT') throw error; } +} + +async function saveState(path, state) { + const temporary = `${path}.${randomUUID()}.tmp`; + await writeFile(temporary, JSON.stringify(state), { mode: 0o600, flag: 'wx' }); + await rename(temporary, path); +} + +async function start(config, event, eventId) { + if (event.thread_ts !== undefined || typeof event.text !== 'string' || !mention.test(event.text)) { + throw new Error('Expected a top-level Slack app mention for nabis-uc1.'); + } + const request = requestFor(config, event.ts); + const path = join(config.state, `${request}.json`); + const existing = await readState(path); + if (existing) return { status: 0, report: { duplicate: true, request, runId: existing.runId } }; + + const { mode, team, channel, approver } = config; + const input = { mode, team, channel, approver, thread: event.ts, request, triggerEvent: eventId }; + const { report, status } = await invokeFlows(config, 'run', [flow, '--input', JSON.stringify(input)], `nabis-${request}`); + if (status === 3 && report.humanWait) { + const { to, question, waitId } = report.humanWait; + const prompt = /^Approve simulated shipment for (UC1-[a-f0-9]{16}) \(Slack prompt ([\w.-]+)\)\?$/u.exec(question); + const promptTs = prompt?.[2]; + const validTs = mode === 'mock' ? MOCK_PROMPT_TS.test(promptTs) : SLACK_TS.test(promptTs) && promptTs > event.ts; + if (to !== approverIdentity(approver) || prompt?.[1] !== request || !validTs || !/^human-\d+$/u.test(waitId)) { + throw new Error('The journaled approval question does not match the Slack prompt.'); + } + const { runId, socketPath, humanWait, cloudRunId, dashboardUrl } = report; + await saveState(path, { input, runId, waitId, promptTs }); + const diagnostics = report.diagnostics.filter(diagnostic => diagnostic.severity === 'warning'); + return { status, report: { + runId, socketPath, status: 'parked', humanWait, request, transport: mode, diagnostics, cloudRunId, dashboardUrl, + } }; + } else if (report.runId && report.completionReason && status !== 3) { + await saveState(path, { input, runId: report.rootRunId ?? report.runId }); + } + return { status, report: { ...report, request, transport: mode } }; +} + +async function recordedDecision(socketPath, state) { + const client = new JournalClient(socketPath); + try { + await client.connect(); + await client.hello('nabis-uc1-slack-event'); + const { asked, answer } = await readHumanWait(client, state.runId, state.waitId); + const to = approverIdentity(state.input.approver); + const question = approvalQuestion(state.input.request, state.promptTs); + if (asked.length === 0 || asked.some(wait => wait.to !== to || wait.question !== question)) { + throw new Error('The run does not have this Slack approval question.'); + } + return answer; + } finally { + client.close(); + } +} + +async function answer(config, event, eventId) { + const match = typeof event.text === 'string' ? decision.exec(event.text) : null; + const request = requireMatch(match?.[2], REQUEST_ID, 'UC1 reply command'); + const thread = requireMatch(event.thread_ts, SLACK_TS, 'Slack approval thread timestamp'); + if (event.user !== config.approver || request !== requestFor(config, thread)) { + throw new Error('Approval does not match the run thread and designated approver.'); + } + const state = await readState(join(config.state, `${request}.json`)); + if (!state) return { status: 75, report: { status: 'retry', request, reason: 'The Slack approval prompt has no recorded park yet.' } }; + if (!state.waitId || state.input.approver !== config.approver || state.input.thread !== thread) { + throw new Error('No matching run is waiting for Slack approval.'); + } + const postedAt = config.mode === 'mock' ? thread : state.promptTs; + if (event.ts <= postedAt) throw new Error('The decision predates the Slack approval prompt.'); + + const approved = match[1] === 'approve'; + const note = `${approvalAttribution(state.input, state.promptTs)}${eventId}:${event.ts}`; + const identity = approverIdentity(event.user); + const daemon = await ensureDaemon(journalDir(config)); + if (daemon.kind !== 'attached') throw new Error(daemon.message ?? 'Could not attach to the local UC1 journal.'); + if (daemon.warning) console.error(`UC1 WARNING: ${daemon.warning}`); + // Recheck the journal after the write so concurrent deliveries cannot resume + // with a competing answer. The same Slack event can be retried after a crash. + let recorded = await recordedDecision(daemon.socketPath, state); + if (!recorded) { + await invokeFlows(config, 'answer', [state.runId, state.waitId, approved ? 'yes' : 'no', '--by', identity, '--note', note]); + recorded = await recordedDecision(daemon.socketPath, state); + } + if (recorded?.answeredBy !== identity || recorded.note !== note || recorded.answer !== approved) { + throw new Error('This run did not accept this Slack decision.'); + } + const { report, status } = await invokeFlows(config, 'resume', [state.runId]); + return { status, report: { ...report, request, transport: config.mode, decision: approved ? 'approved' : 'declined' } }; +} + +try { + const [eventPath, ...extra] = process.argv.slice(2); + if (!eventPath || extra.length) throw new Error('Usage: node slack-event.mjs '); + const config = scope(process.env); + const json = eventPath === '-' ? await readText(process.stdin) : await readFile(eventPath, 'utf8'); + const { event, eventId } = readEnvelope(JSON.parse(json), config); + const work = join(config.state, 'work'); + await mkdir(work, { recursive: true, mode: 0o700 }); + if (config.mode === 'live') process.env.RELAYFILE_MOUNT_PATH = resolve(process.env.RELAYFILE_MOUNT_PATH); + const pathEntries = (process.env.PATH ?? '').split(delimiter).filter(Boolean).map(path => resolve(path)) + .filter(path => config.mode !== 'live' || path !== fixtures); + process.env.PATH = [agentCli, ...pathEntries.filter(path => path !== agentCli)].join(delimiter); + process.chdir(work); + process.env.RELAYFLOWS_SLACK_MOCK = config.mode === 'mock' ? '1' : '0'; + const { status, report } = event.type === 'app_mention' + ? await start(config, event, eventId) + : await answer(config, event, eventId); + console.log(JSON.stringify(report)); + process.exitCode = status ?? 1; +} catch (error) { + console.error(`UC1 REFUSED: ${error.message}`); + process.exitCode = 2; +} diff --git a/examples/nabis-uc1/slack-inbox.mjs b/examples/nabis-uc1/slack-inbox.mjs new file mode 100644 index 000000000..f70f62702 --- /dev/null +++ b/examples/nabis-uc1/slack-inbox.mjs @@ -0,0 +1,72 @@ +import { randomUUID } from 'node:crypto'; +import { link, mkdir, open, readFile, readdir, rm, unlink, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import { EVENT_ID } from './contracts.ts'; + +export async function createInbox(directory, deliver, { retryMs = 2000 } = {}) { + await mkdir(directory, { recursive: true, mode: 0o700 }); + let queue = Promise.resolve(); + const scheduled = new Set(); + const accepting = new Map(); + + function schedule(path, callback) { + if (scheduled.has(path)) return; + scheduled.add(path); + queue = queue.then(async () => { + for (let attempt = 0; attempt < 2; attempt++) { + if (attempt) await delay(retryMs); + const delivered = await deliver(callback).catch(() => false); + if (delivered) { + await unlink(path); + return; + } + } + console.error(`UC1 kept ${callback.event_id} in the inbox. Restart the listener with the same UC1_STATE_DIR to replay it.`); + }).catch(() => { + console.error(`UC1 could not finish ${callback.event_id}. Its inbox record is available for replay.`); + }).finally(() => scheduled.delete(path)); + } + + async function persist(path, callback) { + const temporary = join(directory, `.${randomUUID()}.tmp`); + try { + await writeFile(temporary, JSON.stringify(callback), { flag: 'wx', mode: 0o600, flush: true }); + try { + await link(temporary, path); + } catch (error) { + if (error.code !== 'EEXIST') throw error; + callback = JSON.parse(await readFile(path, 'utf8')); + } + } finally { + await rm(temporary, { force: true }); + } + const directoryHandle = await open(directory, 'r'); + try { await directoryHandle.sync(); } + finally { await directoryHandle.close(); } + schedule(path, callback); + } + + return { + async accept(callback) { + if (!EVENT_ID.test(callback.event_id)) throw new Error('Invalid UC1 callback ID.'); + const path = join(directory, `${callback.event_id}.json`); + if (scheduled.has(path)) return; + const writing = accepting.get(path) ?? persist(path, callback).finally(() => accepting.delete(path)); + accepting.set(path, writing); + await writing; + }, + async replay(validate) { + const events = []; + for (const filename of await readdir(directory)) { + if (!filename.endsWith('.json') || !EVENT_ID.test(filename.slice(0, -5))) continue; + const path = join(directory, filename); + const callback = validate(JSON.parse(await readFile(path, 'utf8'))); + if (callback && filename === `${callback.event_id}.json`) events.push({ path, callback }); + } + events.sort((left, right) => left.callback.event.ts.localeCompare(right.callback.event.ts)); + for (const { path, callback } of events) schedule(path, callback); + }, + drain: () => queue, + }; +} diff --git a/examples/nabis-uc1/slack-inbox.test.mjs b/examples/nabis-uc1/slack-inbox.test.mjs new file mode 100644 index 000000000..1239f9b34 --- /dev/null +++ b/examples/nabis-uc1/slack-inbox.test.mjs @@ -0,0 +1,58 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, readFile, readdir, rm, stat } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { createInbox } from './slack-inbox.mjs'; + +async function directoryFor(testContext) { + const directory = await mkdtemp(join(tmpdir(), 'uc1-inbox-')); + testContext.after(() => rm(directory, { recursive: true, force: true })); + return directory; +} + +test('persists a callback privately before dispatch and coalesces concurrent redeliveries', async t => { + const directory = await directoryFor(t); + const callback = { event_id: 'EvApproval1', event: { ts: '1780000001.000001' } }; + const dispatched = []; + const { promise: release, resolve } = Promise.withResolvers(); + const inbox = await createInbox(directory, async received => { + await release; + dispatched.push(received); + return true; + }); + await Promise.all([inbox.accept(callback), inbox.accept(callback)]); + const path = join(directory, 'EvApproval1.json'); + assert.deepEqual(JSON.parse(await readFile(path, 'utf8')), callback); + assert.equal((await stat(path)).mode & 0o777, 0o600); + resolve(); + await inbox.drain(); + assert.deepEqual(dispatched, [callback]); + assert.deepEqual(await readdir(directory), []); +}); + +test('retries the original callback and replays unfinished work in Slack timestamp order after restart', async t => { + const directory = await directoryFor(t); + const mention = { event_id: 'EvMention1', event: { ts: '1780000000.000001' } }; + const approval = { event_id: 'EvApproval1', event: { ts: '1780000001.000001', text: 'approve UC1-0123456789abcdef' } }; + const attempts = []; + const firstInbox = await createInbox(directory, async received => { + attempts.push(received); + if (received === approval) throw new Error('simulated process failure'); + return false; + }, { retryMs: 1 }); + await firstInbox.accept(approval); + await firstInbox.accept(mention); + await firstInbox.drain(); + assert.deepEqual(attempts, [approval, approval, mention, mention]); + + const replayed = []; + const secondInbox = await createInbox(directory, async received => { + replayed.push(received); + return true; + }); + await secondInbox.replay(callback => callback); + await secondInbox.drain(); + assert.deepEqual(replayed, [mention, approval]); + assert.deepEqual(await readdir(directory), []); +}); diff --git a/examples/nabis-uc1/slack-listen.mjs b/examples/nabis-uc1/slack-listen.mjs new file mode 100644 index 000000000..f896994db --- /dev/null +++ b/examples/nabis-uc1/slack-listen.mjs @@ -0,0 +1,155 @@ +import { spawn, spawnSync } from 'node:child_process'; +import { once } from 'node:events'; +import { delimiter, join, resolve } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import { fileURLToPath } from 'node:url'; +import { slackMount } from '../../packages/sdk/dist/slack-preflight.js'; +import { record, TEAM_ID, USER_ID } from './contracts.ts'; +import { requireMatch, socketCallback } from './slack-envelope.mjs'; +import { createInbox } from './slack-inbox.mjs'; + +const channel = 'C0B9Z4CLG1J'; +const bridge = fileURLToPath(new URL('./slack-event.mjs', import.meta.url)); +const fixtures = fileURLToPath(new URL('./fixtures', import.meta.url)); + +async function openConnection(token, signal) { + let response; + try { + response = await fetch('https://slack.com/api/apps.connections.open', { + method: 'POST', headers: { Authorization: `Bearer ${token}` }, redirect: 'error', + signal: AbortSignal.any([signal, AbortSignal.timeout(15_000)]), + }); + } catch (error) { + if (signal.aborted) throw error; + console.error('UC1 Socket Mode connection request failed. Retrying.'); + return; + } + if (response.status === 429) { + const retry = Number(response.headers.get('retry-after')) || 5; + await delay(retry * 1000, undefined, { signal }); + return; + } + if (response.status === 408 || response.status >= 500) { + console.error(`UC1 Socket Mode connection returned HTTP ${response.status}. Retrying.`); + return; + } + if (!response.ok) throw new Error(`Slack refused apps.connections.open (HTTP ${response.status}).`); + let data; + try { data = await response.json(); } + catch (error) { + if (signal.aborted) throw error; + console.error('UC1 could not read the Socket Mode response. Retrying.'); + return; + } + if (data?.ok === false && ['internal_error', 'service_unavailable', 'request_timeout'].includes(data.error)) { + console.error('UC1 Socket Mode connection is temporarily unavailable. Retrying.'); + return; + } + if (data?.ok !== true || typeof data.url !== 'string') { + throw new Error('Slack refused apps.connections.open. Check Socket Mode and the app-level connections:write scope.'); + } + let url; + try { url = new URL(data.url); } catch { throw new Error('Slack returned an invalid Socket Mode URL.'); } + if (url.protocol !== 'wss:' || !url.hostname.endsWith('.slack.com')) { + throw new Error('Slack returned an invalid Socket Mode URL.'); + } + return url; +} + +async function listen(url, config, signal, inbox) { + const socket = new WebSocket(url); + const close = () => socket.close(); + const handshake = setTimeout(close, 15_000); + const accepting = new Set(); + signal.addEventListener('abort', close, { once: true }); + socket.addEventListener('message', ({ data }) => { + let frame; + try { frame = record(JSON.parse(data)); } catch { return; } + if (frame.type === 'hello') { + clearTimeout(handshake); + console.log('UC1 is listening in #watchdog-test. Post @YourSlackApp nabis-uc1 as a new message. The Flows CLI will print the recording links here.'); + } else if (frame.type === 'disconnect') { + close(); + } else if (typeof frame.envelope_id === 'string' && frame.envelope_id && !signal.aborted) { + const callback = socketCallback(frame, config); + const ack = () => { + if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ envelope_id: frame.envelope_id })); + }; + if (!callback) ack(); + else { + const persisted = inbox.accept(callback).then(ack).catch(() => { + console.error('UC1 could not save an accepted callback. Slack may redeliver it.'); + }).finally(() => accepting.delete(persisted)); + accepting.add(persisted); + } + } + }); + try { await new Promise(done => socket.addEventListener('close', done, { once: true })); } + finally { + clearTimeout(handshake); + signal.removeEventListener('abort', close); + await Promise.all(accepting); + } +} + +async function dispatch(callback, env) { + const child = spawn(process.execPath, [bridge, '-'], { + env, detached: true, stdio: ['pipe', 'pipe', 'inherit'], + }); + const exited = once(child, 'close'); + child.stdin.on('error', () => {}); // The child can fail preflight before reading stdin. + child.stdin.end(JSON.stringify(callback)); + let stdout = ''; + child.stdout.setEncoding('utf8'); + child.stdout.on('data', chunk => { stdout += chunk; }); + const [status] = await exited; + if (stdout) process.stdout.write(stdout); + const report = stdout ? JSON.parse(stdout) : {}; + return status === 0 || Boolean(status === 3 && report.humanWait && !report.decision) + || Boolean(report.completionReason && report.runId); +} + +async function main(signal) { + const { UC1_SLACK_APP_TOKEN: token, ...env } = process.env; + if (!token?.startsWith('xapp-')) throw new Error('Set UC1_SLACK_APP_TOKEN to an app-level Socket Mode token.'); + const config = { + team: requireMatch(env.UC1_SLACK_TEAM, TEAM_ID, 'approved Slack workspace ID'), + approver: requireMatch(env.UC1_SLACK_APPROVER, USER_ID, 'designated Slack operator ID'), + bot: requireMatch(env.UC1_SLACK_BOT_USER, USER_ID, 'Slack app bot user ID'), + channel, + }; + if (!env.UC1_STATE_DIR) throw new Error('Set UC1_STATE_DIR to a private local directory.'); + if (!env.RELAYFILE_MOUNT_PATH || !slackMount(env)) { + throw new Error('Set RELAYFILE_MOUNT_PATH to the approved Relayfile root containing slack/.'); + } + env.PATH = (env.PATH ?? '').split(delimiter).filter(entry => entry && resolve(entry) !== fixtures).join(delimiter); + if (spawnSync('codex', ['login', 'status'], { env, stdio: 'ignore', timeout: 10_000 }).status !== 0) { + throw new Error('Sign in to the real Codex CLI on PATH before starting UC1.'); + } + Object.assign(env, { + UC1_STATE_DIR: resolve(env.UC1_STATE_DIR), UC1_SLACK_MODE: 'live', + UC1_SLACK_CHANNEL: channel, RELAYFLOWS_SLACK_MOCK: '0', + }); + const inbox = await createInbox(join(env.UC1_STATE_DIR, 'inbox'), callback => dispatch(callback, env)); + await inbox.replay(payload => socketCallback({ type: 'events_api', envelope_id: 'replay', payload }, config)); + try { + while (!signal.aborted) { + const url = await openConnection(token, signal); + if (url && !signal.aborted) await listen(url, config, signal, inbox); + await delay(2000, undefined, { signal }); + } + } finally { + await inbox.drain(); + } +} + +const controller = new AbortController(); +process.once('SIGINT', () => controller.abort()); +process.once('SIGTERM', () => controller.abort()); +try { await main(controller.signal); } +catch (error) { + if (!controller.signal.aborted) { + console.error(`UC1 LISTENER: ${error.message}`); + process.exitCode = 1; + } +} diff --git a/examples/nabis-uc1/uc1.flow.ts b/examples/nabis-uc1/uc1.flow.ts new file mode 100644 index 000000000..119687758 --- /dev/null +++ b/examples/nabis-uc1/uc1.flow.ts @@ -0,0 +1,298 @@ +import { flow, type AgentResult, type Ctx } from '@relayflows/surface'; + +export const TEAM_ID = /^T[A-Z0-9]{2,31}$/u; +export const CHANNEL_ID = /^[CG][A-Z0-9]{2,31}$/u; +export const USER_ID = /^[UW][A-Z0-9]{2,31}$/u; +export const EVENT_ID = /^Ev[A-Za-z0-9]{2,32}$/u; +export const SLACK_TS = /^\d{10}\.\d{6}$/u; +export const REQUEST_ID = /^UC1-[a-f0-9]{16}$/u; +export const MOCK_PROMPT_TS = /^mock-slack-[a-zA-Z0-9-]+$/u; + +export type RunInput = { + mode: 'mock' | 'live'; + team: string; + channel: string; + thread: string; + approver: string; + request: string; + triggerEvent: string; +}; + +export function record(value: unknown): Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? value as Record + : {}; +} + +export function approvalQuestion(request: string, promptTs: string): string { + return `Approve simulated shipment for ${request} (Slack prompt ${promptTs})?`; +} + +export function approvalAttribution(input: RunInput, promptTs: string): string { + return `slack-event:${input.team}:${input.channel}:${input.thread}:${input.request}:${promptTs}:`; +} + +export function approverIdentity(approver: string): string { + return `slack:@${approver}`; +} + +export const routes = { ready: 'pickup-queue', held: 'manual-review', canceled: 'archive' } as const; +type Status = keyof typeof routes; +type Task = { id: string; statuses: Status[]; dependsOn: string[] }; +const taskId = /^[a-z][a-z0-9-]{0,29}$/u; + +function isStatus(value: unknown): value is Status { + return typeof value === 'string' && Object.hasOwn(routes, value); +} + +/** Validate the planner's partition, then order it even if dependencies appeared last. */ +export function orderedTasks(value: unknown): Task[] | undefined { + const { tasks } = record(value); + if (!Array.isArray(tasks) || tasks.length < 2 || tasks.length > 3) return; + const byId = new Map(); + const covered = new Set(); + let edgeCount = 0; + for (const raw of tasks) { + const { id, statuses, dependsOn } = record(raw); + if (typeof id !== 'string' || !taskId.test(id) || byId.has(id) + || !Array.isArray(statuses) || statuses.length === 0 || !statuses.every(isStatus) + || !Array.isArray(dependsOn) || !dependsOn.every(d => typeof d === 'string') + || new Set(dependsOn).size !== dependsOn.length) return; + for (const status of statuses) { + if (covered.has(status)) return; + covered.add(status); + } + byId.set(id, { id, statuses, dependsOn }); + edgeCount += dependsOn.length; + } + if (covered.size !== Object.keys(routes).length || edgeCount === 0) return; + const ordered: Task[] = []; + const completed = new Set(); + while (ordered.length < byId.size) { + const next = [...byId.values()].find(task => !completed.has(task.id) + && task.dependsOn.every(dependency => completed.has(dependency))); + if (!next) return; // A missing dependency or cycle cannot make progress. + ordered.push(next); + completed.add(next.id); + } + return ordered; +} + +const contract = JSON.stringify(routes); +const missingHold = 'missing-held-route'; +const jsonOnly = 'Reply with a raw JSON object without Markdown fences. Use only the fictional rules in the prompt.'; +const shellWord = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'"; +const hostedChannel = 'C0B9Z4CLG1J'; +const hostedApprover = 'khaliq'; +const hostedSender = 'U0ADJH4P83T'; +const hostedMention = '<@U0B2596R7EZ> [UC1 SYNTHETIC] nabis-uc1'; +const hostedMessagePath = /^\/slack\/channels\/C0B9Z4CLG1J(?:__watchdog-test)?\/messages\/(\d{10})[_.](\d{6})(?:\/meta\.json|\.json)$/u; +const cloudRunIdPattern = /^[A-Za-z0-9_-]{1,128}$/u; + +function localRun(value: Record): RunInput | undefined { + const { mode, team, channel, thread, approver, request, triggerEvent } = value; + if ((mode === 'mock' || mode === 'live') + && typeof team === 'string' && TEAM_ID.test(team) && typeof channel === 'string' && CHANNEL_ID.test(channel) + && typeof thread === 'string' && SLACK_TS.test(thread) && typeof approver === 'string' && USER_ID.test(approver) + && typeof request === 'string' && REQUEST_ID.test(request) && typeof triggerEvent === 'string' && EVENT_ID.test(triggerEvent)) { + return { mode, team, channel, thread, approver, request, triggerEvent }; + } +} + +function hostedRun(value: Record) { + const issue = record(value.issue); + const event = record(value.event); + if (value.approver !== hostedApprover || issue.source !== 'slack' || issue.channelId !== hostedChannel + || issue.mentioned !== true || issue.body !== hostedMention + || event.provider !== 'slack' || event.eventType !== 'message.created' + || typeof event.deliveryId !== 'string' || !event.deliveryId.trim() || !Array.isArray(event.paths)) return; + + const paths = [...new Set(event.paths)].filter((path): path is string => + typeof path === 'string' && hostedMessagePath.test(path)); + if (paths.length !== 1) return; + const [, seconds, fraction] = hostedMessagePath.exec(paths[0]!)!; + const path = `/slack/channels/${hostedChannel}__watchdog-test/messages/${seconds}_${fraction}/meta.json`; + return { path, text: hostedMention, approver: hostedApprover, channel: hostedChannel, thread: `${seconds}.${fraction}`, + request: `UC1-${seconds}${fraction}` }; +} + +// Cloud's event descriptor omits the sender. Read the verified provider +// record as a journaled step so a resume reuses the original admission +// decision. The command prints no provider data or credentials. +const checkHostedSlackMessage = ` + const { readFileSync } = require('node:fs'); + const { setTimeout: delay } = require('node:timers/promises'); + const [path, expectedJson] = process.argv.slice(1); + const expected = JSON.parse(expectedJson); + async function check() { + const root = process.env.RELAYFILE_MOUNT_PATH; + if (!root) return 'Slack mount was not configured in the runner.'; + // The first pull runs in the background. Wait only for this exact record. + const deadline = Date.now() + 60_000; + let contents; + while (contents === undefined) { + try { + contents = readFileSync(root + path, 'utf8'); + } catch (error) { + if (error.code !== 'ENOENT') return 'Slack mount could not read the trigger record.'; + if (Date.now() >= deadline) return 'Slack trigger record did not reach the mount within 60 seconds.'; + await delay(1_000); + } + } + try { + const file = JSON.parse(contents); + const message = file.provider === 'slack' && file.payload ? file.payload : file; + const matches = record => record.channel === expected.channel && record.ts === expected.ts + && record.user === expected.user && record.text === expected.text; + const humanRoot = record => !record.is_bot && record.user_is_bot !== true + && !record.bot_id && !record.app_id && !record.subtype && !record.edited && !record.edited_ts + && (record.thread_ts == null || record.thread_ts === expected.ts); + const raw = message.raw_event; + const verified = matches(message) && humanRoot(message) && !message.has_files + && (!raw || (raw.type === 'message' && matches(raw) && humanRoot(raw) && !raw.files?.length)); + return verified ? 'verified' : 'The mounted Slack record did not confirm the synthetic trigger and designated sender.'; + } catch { + return 'Slack trigger record was not valid JSON metadata.'; + } + } + check().then(detail => console.log(detail)); +`; + +function agentJson(result: AgentResult): Record { + if (result.completionReason !== 'success') return {}; + try { return record(JSON.parse(result.summary)); } catch { return {}; } +} + +function agent(f: Ctx, step: string, task: string) { + return f.agent(step, { task: `${task}\n${jsonOnly}`, cli: 'codex', model: 'gpt-5.6-sol', timeout: '2m', transportRetries: 0 }); +} + +export default flow('nabis-uc1', { tools: { slack: true } }, async (f, value) => { + const input = record(value); + const local = localRun(input); + const hosted = 'mode' in input ? undefined : hostedRun(input); + const run = local ?? hosted; + const mock = local?.mode === 'mock'; + if (!run || (process.env.RELAYFLOWS_SLACK_MOCK === '1') !== mock) { + return f.done('step_failed', { detail: 'Expected a scoped UC1 Slack trigger and the matching Slack transport mode.' }); + } + if (hosted) { + const expected = { channel: hosted.channel, ts: hosted.thread, user: hostedSender, text: hosted.text }; + const result = await f.run(`node -e ${shellWord(checkHostedSlackMessage)} ${shellWord(hosted.path)} ${shellWord(JSON.stringify(expected))}`, + { timeout: '75s' }); + const detail = result.trim(); + if (detail !== 'verified') return f.done('step_failed', { detail }); + } + + const label = mock ? '[MOCK SLACK · SIMULATION]' : '[SIMULATION]'; + const reply = (role: string, text: string) => + f.slack.reply(run.channel, run.thread, `${label} ${run.request}\n${role}\n${text}`); + if (hosted) { + const runId = process.env.RELAYFLOW_V2_CLOUD_RUN_ID; + if (!runId || !cloudRunIdPattern.test(runId)) { + return f.done('step_failed', { detail: 'The hosted runner did not provide a Cloud run ID.' }); + } + const base = process.env.FLOWS_CLOUD_URL?.trim() || 'https://agentrelay.com/cloud'; + const url = URL.parse(base); + // Match the SDK's Cloud base URL rules in this self-contained hosted flow. + if (!url || url.protocol !== 'https:' || url.username || url.password || url.search || url.hash + || !/^\/[A-Za-z0-9/_-]*$/u.test(url.pathname)) { + return f.done('step_failed', { detail: 'FLOWS_CLOUD_URL must be an HTTPS Cloud base URL with a plain path.' }); + } + const prefix = url.pathname.replace(/\/+$/u, ''); + const runUrl = `${url.origin}${prefix}/dashboard/workflow/${runId}/runner`; + await reply('*UC1 started*', `<${runUrl}|Open this run in Flows Cloud>`); + } + const summaryRole = ':clipboard: *Lead summary*'; + const blocked = async (done: string, reason: string, next: string) => { + await reply(summaryRole, `*Done* ${done}\n*Next* ${next}\n*Blocked* ${reason}`); + f.done('step_failed', { detail: reason }); + }; + + const plan = agentJson(await agent(f, 'planner', + `UC1 planner. Partition the three fictional pickup routing rules ${contract} into two or three tasks. ` + + 'Each status must appear once. Include at least one real dependency (such as assigning the held exception ' + + 'after the baseline routes). Use lowercase kebab-case IDs and return ' + + '{"tasks":[{"id":"task-name","statuses":["ready"],"dependsOn":[]}]} with your full graph.')); + const tasks = orderedTasks(plan); + if (!tasks) return blocked('Received the test trigger.', 'Planner did not return a usable task graph.', 'Start a new demo thread.'); + const assignments = tasks.map(task => { + const dependency = task.dependsOn.length ? ` (after ${task.dependsOn.join(', ')})` : ''; + return `• ${task.id} → coder for ${task.statuses.join(', ')}${dependency}`; + }); + await reply(':compass: *Lead*', `Scope: update fictional pickup routing for ready, held, and canceled pickups.\n${assignments.join('\n')}`); + + const candidate: Record = {}; + for (const task of tasks) { + const result = agentJson(await agent(f, `coder-${task.id}`, + `UC1 coder. Implement the rules for task ${JSON.stringify(task)} as a JSON routing table. ` + + `The contract is ${contract}. Implement only this task's statuses. ` + + 'For this deliberate first-pass failure, leave out held even if this task owns it. ' + + 'Return {"rules":{}} with your entries. Prior completed work: ' + JSON.stringify(candidate))); + const rules = record(result.rules); + const expected = task.statuses.filter(status => status !== 'held'); + if (rules !== result.rules || Object.keys(rules).length !== expected.length + || !expected.every(status => typeof rules[status] === 'string')) { + return blocked('Generated a task graph.', 'A coder returned a malformed first pass.', 'Inspect the coder step and start a new demo thread.'); + } + Object.assign(candidate, rules); + } + if (candidate.ready !== routes.ready || candidate.canceled !== routes.canceled) { + return blocked('Generated and executed the task graph.', 'The first pass did not match the ready and canceled rules.', 'Inspect the coder steps and start a new demo thread.'); + } + await reply(':hammer: *Coder*', `Built the first pass: ready → ${candidate.ready}, canceled → ${candidate.canceled}.`); + + const firstReview = agentJson(await agent(f, 'review-first', + `UC1 first review. Compare candidate ${JSON.stringify(candidate)} with contract ${contract}. ` + + `Return {"verdict":"reject","finding":"${missingHold}"} if only the held rule is absent; ` + + 'otherwise report a different finding or approve a complete candidate.')); + if (firstReview.verdict !== 'reject' || firstReview.finding !== missingHold || Object.hasOwn(candidate, 'held')) { + return blocked('Generated and executed the task graph.', 'The first review did not confirm the intended missing held route.', 'Inspect the first review and start a new demo thread.'); + } + await reply(':mag: *Reviewer*', 'Rejected the first pass because it omitted the held-pickup rule. Sent the routing table back to add it.'); + + const repair = agentJson(await agent(f, 'repair', + `UC1 repair. Reviewer finding: ${missingHold}. Fix the fictional routing table ${JSON.stringify(candidate)} ` + + `against ${contract} and return the complete replacement as {"rules":{}} with your entries.`)); + const repaired = record(repair.rules); + const secondReview = agentJson(await agent(f, 'review-repair', + `UC1 repaired review. Compare ${JSON.stringify(repaired)} with ${contract}. ` + + 'Return {"verdict":"approve"} only if all three mappings are correct and there are no extra rules; otherwise reject.')); + if (secondReview.verdict !== 'approve' || Object.keys(repaired).length !== Object.keys(routes).length + || !Object.entries(routes).every(([status, destination]) => repaired[status] === destination)) { + return blocked('First reviewer rejected the missing held route. A repair was attempted.', 'The repaired rules did not clear review and all routing checks.', 'Inspect the repair and start a new demo thread.'); + } + await reply(':wrench: *Repair*', `Added held → ${repaired.held}. The reviewer accepted the repaired table and all three routing checks passed.`); + + let approved: boolean; + if (local) { + const prompt = await reply(':pause_button: *Waiting for human approval*', + `<@${local.approver}>, reply in this thread with \`approve ${run.request}\` or \`decline ${run.request}\`.`); + if (prompt.channel !== run.channel || !(mock ? MOCK_PROMPT_TS : SLACK_TS).test(prompt.ts)) { + return f.done('step_failed', { detail: 'Slack did not return a confirmed prompt for the test channel.' }); + } + const to = approverIdentity(local.approver); + const source = approvalAttribution(local, prompt.ts).replaceAll('.', '\\.'); + approved = await f.human(approvalQuestion(run.request, prompt.ts), { to }).gate({ + type: 'regex_match', + pattern: `"note":"${source}Ev[A-Za-z0-9]{2,32}:\\d{10}\\.\\d{6}","answeredBy":"${to}"`, + }); + } else { + // A bare deploy approver tells Cloud to deliver the question in the + // trigger thread and accept the designated user's same-thread answer. + approved = await f.human(`Approve simulated shipment for ${run.request}? Reply yes or no in this thread.`, + { to: run.approver }); + } + if (!approved) { + await reply(summaryRole, '*Done* Repaired rules passed review.\n*Next* Start a new test thread for another decision.\n*Blocked* The designated approver declined.'); + return f.done('declined', { detail: 'The designated Slack approver declined.' }); + } + + // The receipt records the checked artifact in the journal. No shipment API is called. + await f.run(`printf '%s\\n' ${shellWord(JSON.stringify({ + action: 'simulate-ship', request: run.request, rules: repaired, + }))}`); + await reply(summaryRole, '*Done* Planned, coded, rejected once, repaired, re-reviewed, and recorded simulated shipment after approval.\n' + + '*Next* Inspect the run journal and compare the routing rules.\n*Blocked* None.'); + f.done('success', { detail: 'Simulated shipment recorded after Slack approval.' }); +}); diff --git a/examples/nabis-uc1/verification/helper-resume-regression.txt b/examples/nabis-uc1/verification/helper-resume-regression.txt new file mode 100644 index 000000000..1c277e8ef --- /dev/null +++ b/examples/nabis-uc1/verification/helper-resume-regression.txt @@ -0,0 +1,12 @@ +Run from packages/sdk with RELAYFLOWD_BIN pointing to the checkout build. +./node_modules/.bin/vitest run tests/authored-flow-slack.test.ts -t "resumes after a human answers" + +Removed only resolve() from the memoized-effect branch. Exit 1. +unsettled_derived_work: flow "notify-then-approve" completed while work derived from slack-[fixture-run]-1 (f.slack.post) was still in flight +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ + Test Files 1 failed (1) + Tests 1 failed | 7 skipped (8) + +Restored the preserved source, verified with cmp, and repeated the command. Exit 0. + Test Files 1 passed (1) + Tests 1 passed | 7 skipped (8) diff --git a/examples/nabis-uc1/verification/mock-agent-mock-slack.json b/examples/nabis-uc1/verification/mock-agent-mock-slack.json new file mode 100644 index 000000000..6dd026229 --- /dev/null +++ b/examples/nabis-uc1/verification/mock-agent-mock-slack.json @@ -0,0 +1,94 @@ +{ + "agent": "mock", + "slack": "mock", + "shipment": "simulation", + "refusals": [ + "wrong workspace", + "wrong channel", + "wrong approver", + "wrong thread", + "stale reply", + "bot reply" + ], + "resumedAfterDaemonRestart": true, + "approved": { + "runId": "01M8TSPQZBQQ3ZK6ZGE21P64H9", + "waitId": "human-8", + "request": "UC1-3f9d57368e0adee4", + "plan": { + "tasks": [ + { + "dependsOn": [ + "baseline" + ], + "id": "exceptions", + "statuses": [ + "held", + "canceled" + ] + }, + { + "dependsOn": [], + "id": "baseline", + "statuses": [ + "ready" + ] + } + ] + }, + "executionOrder": [ + "baseline", + "exceptions" + ], + "initialReview": { + "finding": "missing-held-route", + "verdict": "reject" + }, + "repair": { + "canceled": "archive", + "held": "manual-review", + "ready": "pickup-queue" + }, + "finalReview": { + "verdict": "approve" + }, + "answer": { + "answeredBy": "slack:@UAPPROVER1", + "note": "slack-event:TUC1DEMO:CUC1DEMO:1780000000.000001:UC1-3f9d57368e0adee4:mock-slack-01M8TSPQZBQQ3ZK6ZGE21P64H9-7:EvMockDecision000001:1780000001.000001", + "answer": true + }, + "result": "success", + "ship": { + "action": "simulate-ship", + "request": "UC1-3f9d57368e0adee4", + "rules": { + "canceled": "archive", + "held": "manual-review", + "ready": "pickup-queue" + } + }, + "replies": [ + { + "thread": "1780000000.000001", + "text": "[MOCK SLACK · SIMULATION] UC1-3f9d57368e0adee4\nFirst review rejected the missing held route. Repair passed all three routing checks and re-review.\n<@UAPPROVER1>, reply in this thread with `approve UC1-3f9d57368e0adee4` or `decline UC1-3f9d57368e0adee4`.", + "channel": "CUC1DEMO", + "ref": "mock-ref-slack-01M8TSPQZBQQ3ZK6ZGE21P64H9-7", + "ts": "mock-slack-01M8TSPQZBQQ3ZK6ZGE21P64H9-7" + }, + { + "thread": "1780000000.000001", + "text": "[MOCK SLACK · SIMULATION] UC1-3f9d57368e0adee4\n*Done* Planned, coded, rejected once, repaired, re-reviewed, and recorded simulated shipment after approval.\n*Next* Inspect the run journal and compare the routing rules.\n*Blocked* None.", + "channel": "CUC1DEMO", + "ref": "mock-ref-slack-01M8TSPQZBQQ3ZK6ZGE21P64H9-10", + "ts": "mock-slack-01M8TSPQZBQQ3ZK6ZGE21P64H9-10" + } + ] + }, + "declined": { + "runId": "01M8TSQ05KDVVNB2W8NBP5JHVQ", + "result": "declined", + "thread": "1780000000.000002", + "simulatedShip": false + }, + "localCloudMirrorLedger": "absent" +} diff --git a/examples/nabis-uc1/verification/real-agent-mock-slack.json b/examples/nabis-uc1/verification/real-agent-mock-slack.json new file mode 100644 index 000000000..34333f52a --- /dev/null +++ b/examples/nabis-uc1/verification/real-agent-mock-slack.json @@ -0,0 +1,79 @@ +{ + "agent": "real", + "slack": "mock", + "shipment": "simulation", + "approved": { + "runId": "01M8TV5KEFQDA9QAGASGRBA823", + "waitId": "human-8", + "request": "UC1-3f9d57368e0adee4", + "plan": { + "tasks": [ + { + "dependsOn": [], + "id": "route-baseline-pickups", + "statuses": [ + "ready", + "canceled" + ] + }, + { + "dependsOn": [ + "route-baseline-pickups" + ], + "id": "assign-held-exception", + "statuses": [ + "held" + ] + } + ] + }, + "executionOrder": [ + "route-baseline-pickups", + "assign-held-exception" + ], + "initialReview": { + "finding": "missing-held-route", + "verdict": "reject" + }, + "repair": { + "canceled": "archive", + "held": "manual-review", + "ready": "pickup-queue" + }, + "finalReview": { + "verdict": "approve" + }, + "answer": { + "answeredBy": "slack:@UAPPROVER1", + "note": "slack-event:TUC1DEMO:CUC1DEMO:1780000000.000001:UC1-3f9d57368e0adee4:mock-slack-01M8TV5KEFQDA9QAGASGRBA823-7:EvMockDecision000001:1780000001.000001", + "answer": true + }, + "result": "success", + "ship": { + "action": "simulate-ship", + "request": "UC1-3f9d57368e0adee4", + "rules": { + "canceled": "archive", + "held": "manual-review", + "ready": "pickup-queue" + } + }, + "replies": [ + { + "thread": "1780000000.000001", + "text": "[MOCK SLACK · SIMULATION] UC1-3f9d57368e0adee4\nFirst review rejected the missing held route. Repair passed all three routing checks and re-review.\n<@UAPPROVER1>, reply in this thread with `approve UC1-3f9d57368e0adee4` or `decline UC1-3f9d57368e0adee4`.", + "channel": "CUC1DEMO", + "ref": "mock-ref-slack-01M8TV5KEFQDA9QAGASGRBA823-7", + "ts": "mock-slack-01M8TV5KEFQDA9QAGASGRBA823-7" + }, + { + "thread": "1780000000.000001", + "text": "[MOCK SLACK · SIMULATION] UC1-3f9d57368e0adee4\n*Done* Planned, coded, rejected once, repaired, re-reviewed, and recorded simulated shipment after approval.\n*Next* Inspect the run journal and compare the routing rules.\n*Blocked* None.", + "channel": "CUC1DEMO", + "ref": "mock-ref-slack-01M8TV5KEFQDA9QAGASGRBA823-10", + "ts": "mock-slack-01M8TV5KEFQDA9QAGASGRBA823-10" + } + ] + }, + "localCloudMirrorLedger": "absent" +} diff --git a/examples/nabis-uc1/verify.mjs b/examples/nabis-uc1/verify.mjs new file mode 100644 index 000000000..27ba3065c --- /dev/null +++ b/examples/nabis-uc1/verify.mjs @@ -0,0 +1,266 @@ +import assert from 'node:assert/strict'; +import { spawn, spawnSync } from 'node:child_process'; +import { once } from 'node:events'; +import { access, mkdtemp, readFile, readdir, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { delimiter, join, resolve } from 'node:path'; +import { setTimeout } from 'node:timers/promises'; +import { fileURLToPath } from 'node:url'; +import { JournalClient } from '../../packages/sdk/dist/index.js'; +import { orderedTasks, routes } from './contracts.ts'; + +const root = fileURLToPath(new URL('.', import.meta.url)); +const gateway = join(root, 'slack-event.mjs'); +const daemonBinary = resolve(process.env.RELAYFLOWD_BIN ?? 'kernel/target/debug/relayflowd'); +const agentMode = process.argv.includes('--real-agent') ? 'real' : 'mock'; +const trigger = JSON.parse(await readFile(join(root, 'fixtures/mention.json'), 'utf8')); +const approver = 'UAPPROVER1'; +const fixtures = join(root, 'fixtures'); +const cleanPath = (process.env.PATH ?? '').split(delimiter).filter(path => resolve(path) !== fixtures); +const state = await mkdtemp(join(tmpdir(), 'nabis-uc1-')); +const journal = join(state, 'journal'); +const env = { + ...process.env, + RELAYFLOWD_BIN: daemonBinary, + UC1_STATE_DIR: state, + UC1_SLACK_MODE: 'mock', + UC1_SLACK_TEAM: trigger.team_id, + UC1_SLACK_CHANNEL: trigger.event.channel, + UC1_SLACK_APPROVER: approver, + PATH: (agentMode === 'mock' ? [fixtures, ...cleanPath] : cleanPath).join(delimiter), +}; + +let client; +let daemon; +let testRestartedDaemon = false; +const evidence = { agent: agentMode, slack: 'mock', shipment: 'simulation' }; + +async function send(event, expectedStatus = 0, refusal) { + const child = spawnSync(process.execPath, [gateway, '-'], { + env, encoding: 'utf8', input: JSON.stringify(event), timeout: 5 * 60_000, + }); + assert.ifError(child.error); + assert.equal(child.status, expectedStatus, child.stdout + child.stderr); + if (refusal) { + assert.match(child.stderr, refusal); + return; + } + return JSON.parse(child.stdout); +} + +function reply(mention, request, command = 'approve', overrides = {}) { + return { + type: 'event_callback', team_id: mention.team_id, event_id: 'EvMockDecision' + mention.event.ts.slice(-6), + event: { + type: 'message', user: approver, channel: mention.event.channel, + ts: '1780000001.000001', thread_ts: mention.event.ts, text: `${command} ${request}`, + ...overrides, + }, + }; +} + +async function entries(runId) { + const history = []; + let fromSeq = 1; + for (;;) { + const { entries: page } = await client.journalRead(runId, fromSeq, 500); + if (page.length === 0) return history; + history.push(...page); + fromSeq = page.at(-1).seq + 1; + } +} + +function completedSteps(history) { + const steps = new Map(); + for (const entry of history) { + if (entry.entry_type === 'stream.appended' && entry.payload.stream === 'authored-steps') { + const step = entry.payload.message; + if (step.state === 'completed') steps.set(step.step, step); + } + } + return [...steps.values()]; +} + +async function output(step) { + assert.ok(step); + const completed = (await entries(step.runId)).filter(entry => entry.entry_type === 'step.completed' + && entry.step_id === step.step && entry.payload.completionReason === 'success'); + assert.equal(completed.length, 1, step.step); + return completed[0].payload.output; +} + +function answerRecords(history) { + return history.filter(entry => entry.entry_type === 'wait.completed' && entry.payload.completionReason === 'human_responded'); +} + +async function stopOwnedDaemon() { + if (daemon?.exitCode !== null || daemon.signalCode !== null) return; + const exited = once(daemon, 'exit'); + daemon.kill(); + await exited; +} + +async function connect(socketPath) { + const connection = new JournalClient(socketPath); + await connection.connect(); + await connection.hello('nabis-uc1-proof'); + return connection; +} + +try { + if (agentMode === 'mock') { + const shim = join(root, 'agent-cli'); + const missingCli = spawnSync(join(shim, 'codex'), ['login', 'status', '--help'], { + env: { ...env, PATH: shim }, encoding: 'utf8', timeout: 2000, + }); + assert.ifError(missingCli.error); + assert.equal(missingCli.status, 127); + assert.match(missingCli.stderr, /requires a Codex executable on PATH/u); + evidence.shimOnlyPath = 'refused'; + } + + await access(daemonBinary); + daemon = spawn(daemonBinary, ['--data-dir', journal, 'serve'], { stdio: ['ignore', 'ignore', 'inherit'] }); + for (let attempt = 0; ; attempt++) { + try { await access(join(journal, 'connection.json')); break; } + catch (error) { if (attempt === 100 || daemon.exitCode !== null) throw error; } + await setTimeout(30); + } + + const parked = await send(trigger, 3); + assert.equal(parked.status, 'parked'); + assert.equal(parked.transport, 'mock'); + assert.equal(parked.humanWait.to, 'slack:@' + approver); + client = await connect(parked.socketPath); + + const before = completedSteps(await entries(parked.runId)); + const planner = before.find(step => step.label === 'planner'); + const plan = await output(planner); + const ordered = orderedTasks(plan); + assert.ok(ordered); + assert.deepEqual(before.filter(step => step.label?.startsWith('coder-')).map(step => step.label), + ordered.map(task => `coder-${task.id}`)); + const firstReview = await output(before.find(step => step.label === 'review-first')); + assert.equal(firstReview?.verdict, 'reject'); + assert.equal(firstReview.finding, 'missing-held-route'); + const repair = await output(before.find(step => step.label === 'repair')); + assert.deepEqual(repair?.rules, routes); + const review = await output(before.find(step => step.label === 'review-repair')); + assert.equal(review?.verdict, 'approve'); + assert.ok(before.every(step => !step.step.startsWith('run-'))); + const parkedReplies = await Promise.all(before.filter(step => step.step.startsWith('slack-')).map(output)); + assert.deepEqual(parkedReplies.map(effect => effect.params.text.split('\n')[1]), [ + ':compass: *Lead*', ':hammer: *Coder*', ':mag: *Reviewer*', ':wrench: *Repair*', + ':pause_button: *Waiting for human approval*', + ]); + assert.match(parkedReplies[2].params.text, /omitted the held-pickup rule/u); + assert.match(parkedReplies[3].params.text, /held → manual-review/u); + assert.equal((await readdir(join(journal, 'mock-writeback/slack'))).length, 5); + + if (agentMode === 'mock') { + await send({ ...trigger, team_id: 'TOTHER1' }, 2, /outside the approved Slack workspace/u); + await send({ ...trigger, event: { ...trigger.event, channel: 'COTHER1' } }, 2, /outside the approved Slack workspace/u); + await send(reply(trigger, parked.request, 'approve', { user: 'UOTHER1' }), 2, /designated approver/u); + await send(reply(trigger, parked.request, 'approve', { thread_ts: '1780000000.000099' }), 2, /run thread/u); + await send(reply(trigger, parked.request, 'approve', { ts: trigger.event.ts }), 2, /predates the Slack approval prompt/u); + await send(reply(trigger, parked.request, 'approve', { bot_id: 'BMOCK1' }), 2, /Expected an original message/u); + const duplicate = await send(trigger); + assert.deepEqual(duplicate, { duplicate: true, request: parked.request, runId: parked.runId }); + assert.equal(answerRecords(await entries(parked.runId)).length, 0); + evidence.refusals = ['wrong workspace', 'wrong channel', 'wrong approver', 'wrong thread', 'stale reply', 'bot reply']; + } + + if (agentMode === 'mock') { + client.close(); + await stopOwnedDaemon(); + testRestartedDaemon = true; + } + const approve = reply(trigger, parked.request); + const done = await send(approve); + if (testRestartedDaemon) { + const restarted = JSON.parse(await readFile(join(journal, 'connection.json'), 'utf8')); + assert.notEqual(restarted.pid, daemon.pid); + client = await connect(done.socketPath); + evidence.resumedAfterDaemonRestart = true; + } + assert.equal(done.runId, parked.runId); + assert.equal(done.completionReason, 'success'); + assert.equal(done.decision, 'approved'); + if (agentMode === 'mock') { + assert.equal((await send(approve)).completionReason, 'success'); + await send({ ...approve, event_id: 'EvMockCompeting1', event: { ...approve.event, text: `decline ${parked.request}` } }, + 2, /did not accept this Slack decision/u); + } + + const history = await entries(parked.runId); + const human = answerRecords(history); + assert.equal(human.length, 1); + const answer = human[0].payload.result; + assert.equal(human[0].payload.wait_id, parked.humanWait.waitId); + assert.equal(answer.answeredBy, 'slack:@' + approver); + assert.equal(answer.answer, true); + assert.ok(answer.note.includes(approve.event_id)); + const after = completedSteps(history); + const simulation = after.filter(step => step.step.startsWith('run-')); + assert.equal(simulation.length, 1); + assert.ok(simulation[0].after.includes(parked.humanWait.waitId)); + const shipReceipt = JSON.parse((await output(simulation[0])).stdout_tail); + assert.deepEqual(shipReceipt, { action: 'simulate-ship', request: parked.request, rules: routes }); + assert.deepEqual(after.filter(step => step.label), before.filter(step => step.label)); + + const replies = (await Promise.all(after.filter(step => step.step.startsWith('slack-')).map(output))); + assert.equal(replies.length, 6); + assert.deepEqual(replies.slice(0, 5), parkedReplies); + assert.equal((await readdir(join(journal, 'mock-writeback/slack'))).length, 6); + for (const effect of replies) { + assert.equal(effect.verb, 'reply'); + assert.equal(effect.params.threadTs, trigger.event.ts); + assert.equal(effect.receipt.channel, trigger.event.channel); + assert.match(effect.params.text, /^\[MOCK SLACK · SIMULATION\]/u); + } + assert.match(replies[5].params.text, /\*Lead summary\*[\s\S]+\*Done\*[\s\S]+\*Next\*[\s\S]+\*Blocked\* None\./u); + evidence.approved = { + runId: parked.runId, waitId: parked.humanWait.waitId, request: parked.request, + plan, executionOrder: ordered.map(task => task.id), initialReview: firstReview, repair: repair.rules, + finalReview: review, answer: { answeredBy: answer.answeredBy, note: answer.note, answer: answer.answer }, + result: done.completionReason, ship: shipReceipt, + replies: replies.map(effect => ({ thread: effect.params.threadTs, text: effect.params.text, ...effect.receipt })), + }; + + if (agentMode === 'mock') { + const second = { ...trigger, event_id: 'EvMockMention2', event: { ...trigger.event, ts: '1780000000.000002' } }; + const parked2 = await send(second, 3); + assert.notEqual(parked2.runId, parked.runId); + await send(reply(second, parked.request), 2, /run thread/u); + const declined = await send(reply(second, parked2.request, 'decline')); + assert.equal(declined.runId, parked2.runId); + assert.equal(declined.decision, 'declined'); + assert.ok(declined.diagnostics.some(diagnostic => diagnostic.kind === 'run_declined')); + const declinedHistory = await entries(parked2.runId); + const declinedSteps = completedSteps(declinedHistory); + assert.ok(declinedSteps.every(step => !step.step.startsWith('run-'))); + const verdict = JSON.parse((await output(declinedSteps.find(step => step.step.startsWith('complete-')))).stdout_tail); + assert.equal(verdict.completionReason, 'declined'); + assert.equal(answerRecords(declinedHistory)[0].payload.result.answer, false); + const summary = await output(declinedSteps.filter(step => step.step.startsWith('slack-')).at(-1)); + assert.equal(summary.params.threadTs, second.event.ts); + assert.match(summary.params.text, /\*Blocked\* The designated approver declined\./u); + evidence.declined = { runId: declined.runId, result: verdict.completionReason, thread: summary.params.threadTs, simulatedShip: false }; + } + + assert.ok(!(await readdir(journal)).includes('cloud-runs')); + evidence.localCloudMirrorLedger = 'absent'; + console.log(JSON.stringify(evidence, null, 2)); +} finally { + client?.close(); + await stopOwnedDaemon(); + if (testRestartedDaemon) { + try { + const { pid } = JSON.parse(await readFile(join(journal, 'connection.json'), 'utf8')); + if (pid !== daemon.pid) process.kill(pid, 'SIGTERM'); + } catch (error) { + if (error.code !== 'ENOENT' && error.code !== 'ESRCH') throw error; + } + } + await rm(state, { recursive: true, force: true }); +} diff --git a/examples/tsconfig.json b/examples/tsconfig.json index 5e6b01143..9434c62ba 100644 --- a/examples/tsconfig.json +++ b/examples/tsconfig.json @@ -25,6 +25,7 @@ "stale-issues/*.ts", "self-improvement/*.ts", "task-graph/*.ts", + "nabis-uc1/*.ts", "pr-review-pipeline/*.ts", "pr-reviewer/*.ts", "dependency-upgrade-bot/*.ts", diff --git a/packages/sdk/src/authored-helper-effect.ts b/packages/sdk/src/authored-helper-effect.ts index 1a7f00092..93c316c0d 100644 --- a/packages/sdk/src/authored-helper-effect.ts +++ b/packages/sdk/src/authored-helper-effect.ts @@ -101,7 +101,13 @@ async function driveHelperEffect( // attempt immediately, and a drive with no worker journals a crash. await releaseHelperReceiptWaits(journal, runId); const outcome = await journal.runResume(runId); - if (outcome.status === 'completed') return; + if (outcome.status === 'completed') { + // No dispatch follows a memoized effect. The authored lifecycle tracks + // the pending promise from completed.catch() as derived work even when + // this function returns without awaiting completed. + resolve(); + return; + } if (outcome.status === 'failed') { throw new AuthoredFlowExecutionError('step_failed', `Helper run ${runId} ${outcome.status}`, undefined, runId); } diff --git a/packages/sdk/src/cloud-deploy.ts b/packages/sdk/src/cloud-deploy.ts index 46df45c9d..927c204d7 100644 --- a/packages/sdk/src/cloud-deploy.ts +++ b/packages/sdk/src/cloud-deploy.ts @@ -36,7 +36,7 @@ const PROVIDER_SETTINGS: Record = { // `comments` opt a pull_request source out of its extra subscriptions. github: ['repository', 'labels', 'contains', 'events', 'reviews', 'checks', 'comments'], gitlab: ['project', 'labels', 'contains', 'events'], - slack: ['channel', 'contains'], + slack: ['channel', 'contains', 'mentioned'], // `events`: `issues` (default), `assigned` (issues assigned to the agent's // connected app user), or `all` — which Linear records wake the listener. linear: ['team', 'project', 'labels', 'contains', 'events'], @@ -186,11 +186,11 @@ export function parseTriggerSource(value: string): FlowTriggerSource { settings[key] = events; continue; } - if (provider === 'github' && (key === 'reviews' || key === 'checks' || key === 'comments')) { - // Subscription opt-outs are boolean; Cloud refuses any other value. + if ((provider === 'github' && (key === 'reviews' || key === 'checks' || key === 'comments')) + || (provider === 'slack' && key === 'mentioned')) { const toggle = setting.toLowerCase(); if (!['true', 'false'].includes(toggle)) { - throw new CloudFlowError('invalid_input', `github ${key} must be "true" or "false", got "${setting}".`); + throw new CloudFlowError('invalid_input', `${provider} ${key} must be "true" or "false", got "${setting}".`); } settings[key] = toggle; continue; diff --git a/packages/sdk/tests/authored-flow-slack.test.ts b/packages/sdk/tests/authored-flow-slack.test.ts index 5ea60f117..2b62da54a 100644 --- a/packages/sdk/tests/authored-flow-slack.test.ts +++ b/packages/sdk/tests/authored-flow-slack.test.ts @@ -9,6 +9,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { executeAuthoredFlow } from '../src/authored-flow-executor.js'; import { JournalClient } from '../src/journal-client.js'; import { socketPathFor } from '../src/daemon-connection.js'; +import { answerFlow } from '../src/cli/answer.js'; +import { runDirectFlow } from '../src/cli/direct-run.js'; import { resumeFlow } from '../src/cli/run.js'; import { runCli } from '../src/cli.js'; import { preflightHelpers } from '../src/preflight.js'; @@ -120,6 +122,37 @@ describe('authored Slack helper effects', () => { expect(network).not.toHaveBeenCalled(); }); + it('resumes after a human answers when a Slack write before the wait is already complete', async () => { + vi.stubEnv('RELAYFLOWS_SLACK_MOCK', '1'); + const dataDir = temporary(); + await start(dataDir); + const fixture = join(dataDir, 'approval.flow.mjs'); + mkdirSync(join(dataDir, 'node_modules/@relayflows'), { recursive: true }); + symlinkSync(join(root, 'packages/sdk/node_modules/@relayflows/surface'), join(dataDir, 'node_modules/@relayflows/surface')); + writeFileSync(fixture, `import { flow } from '@relayflows/surface'; +export default flow('notify-then-approve', async f => { + const prompt = await f.slack.post('C1', 'Approve this demo?'); + const approved = await f.human('Approve message ' + prompt.ts + '?', { to: 'slack:@U1' }); + if (approved) await f.slack.reply('C1', prompt.ts, 'Approved'); + f.done(approved ? 'success' : 'declined'); +});`); + const run = await runDirectFlow(fixture, '{}', dataDir); + expect(run.exitCode, JSON.stringify(run.report.diagnostics)).toBe(3); + expect(mockFiles(dataDir)).toHaveLength(1); + const { runId, humanWait } = run.report; + expect((await answerFlow(runId!, humanWait!.waitId, true, dataDir)).exitCode).toBe(0); + const resumed = await resumeFlow(runId!, dataDir); + expect(resumed.report).toMatchObject({ runId, completionReason: 'success', diagnostics: [] }); + const captures = mockFiles(dataDir).map(file => + JSON.parse(readFileSync(join(dataDir, 'mock-writeback/slack', file), 'utf8'))); + const post = captures.find(capture => capture.verb === 'post'); + expect(post).toMatchObject({ text: 'Approve this demo?' }); + expect(captures).toEqual(expect.arrayContaining([ + expect.objectContaining({ verb: 'reply', text: 'Approved', thread_ts: post.receipt.externalId }), + ])); + expect(captures).toHaveLength(2); + }); + it('refuses missing credentials before running the body while flows check warns', async () => { for (const key of ['SLACK_BOT_TOKEN', 'RELAYFLOWS_SLACK_MOCK', 'RELAYFILE_MOUNT_PATH', 'WORKSPACE_ROOT', 'WORKFORCE_SANDBOX_ROOT', 'RELAYFILE_MOUNT_ROOT', 'RELAYFILE_ROOT']) vi.stubEnv(key, ''); let executed = false; diff --git a/packages/sdk/tests/cloud-deploy.test.ts b/packages/sdk/tests/cloud-deploy.test.ts index 5782f14ad..737158111 100644 --- a/packages/sdk/tests/cloud-deploy.test.ts +++ b/packages/sdk/tests/cloud-deploy.test.ts @@ -62,6 +62,10 @@ describe('trigger source and repository parsing', () => { ['github', { provider: 'github', settings: {} }], ['github:labels=agent,contains=urgent', { provider: 'github', settings: { labels: 'agent', contains: 'urgent' } }], ['slack:channel=#eng', { provider: 'slack', settings: { channel: '#eng' } }], + ['slack:channel=C0B9Z4CLG1J,mentioned=True,contains=[UC1 SYNTHETIC] nabis-uc1', { + provider: 'slack', + settings: { channel: 'C0B9Z4CLG1J', mentioned: 'true', contains: '[UC1 SYNTHETIC] nabis-uc1' }, + }], ['linear:team=ENG', { provider: 'linear', settings: { team: 'ENG' } }], ['linear:team=Engineering,labels=agent,contains=urgent', { provider: 'linear', settings: { team: 'Engineering', labels: 'agent', contains: 'urgent' } }], ['linear:events=assigned', { provider: 'linear', settings: { events: 'assigned' } }], @@ -77,7 +81,9 @@ describe('trigger source and repository parsing', () => { expect(parseTriggerSource(value)).toEqual(expected); }); - it.each(['github:channel=x', 'github:labels=', 'github:labels=a,labels=b', 'slack:labels=x', 'github:events=releases', 'gitlab:events=pull_request', 'gitlab:repository=acme/web', 'github:reviews=maybe', 'linear:events=mentions', 'linear:events=pull_request']) + it.each(['github:channel=x', 'github:labels=', 'github:labels=a,labels=b', 'slack:labels=x', 'slack:mentioned=maybe', + 'github:events=releases', 'gitlab:events=pull_request', 'gitlab:repository=acme/web', 'github:reviews=maybe', + 'linear:events=mentions', 'linear:events=pull_request']) ('refuses %s', (value) => { expect(() => parseTriggerSource(value)).toThrow(expect.objectContaining({ code: 'invalid_input' })); });