From 6404734d054c6027eadb9de5501c112f5a18022b Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Tue, 1 Dec 2026 23:09:48 -0800 Subject: [PATCH 01/19] Add local Nabis UC1 Slack approval demo --- examples/nabis-uc1/README.md | 118 ++++++++++ examples/nabis-uc1/agent-cli/codex | 13 ++ examples/nabis-uc1/contracts.ts | 77 +++++++ examples/nabis-uc1/fixtures/codex | 41 ++++ examples/nabis-uc1/fixtures/mention.json | 12 + examples/nabis-uc1/flows.json | 4 + examples/nabis-uc1/slack-event.mjs | 177 +++++++++++++++ examples/nabis-uc1/uc1.flow.ts | 105 +++++++++ .../verification/mock-agent-mock-slack.json | 93 ++++++++ .../verification/real-agent-mock-slack.json | 81 +++++++ examples/nabis-uc1/verify.mjs | 214 ++++++++++++++++++ examples/tsconfig.json | 1 + packages/sdk/src/authored-helper-effect.ts | 7 +- .../sdk/tests/authored-flow-slack.test.ts | 26 +++ 14 files changed, 968 insertions(+), 1 deletion(-) create mode 100644 examples/nabis-uc1/README.md create mode 100755 examples/nabis-uc1/agent-cli/codex create mode 100644 examples/nabis-uc1/contracts.ts create mode 100755 examples/nabis-uc1/fixtures/codex create mode 100644 examples/nabis-uc1/fixtures/mention.json create mode 100644 examples/nabis-uc1/flows.json create mode 100644 examples/nabis-uc1/slack-event.mjs create mode 100644 examples/nabis-uc1/uc1.flow.ts create mode 100644 examples/nabis-uc1/verification/mock-agent-mock-slack.json create mode 100644 examples/nabis-uc1/verification/real-agent-mock-slack.json create mode 100644 examples/nabis-uc1/verify.mjs diff --git a/examples/nabis-uc1/README.md b/examples/nabis-uc1/README.md new file mode 100644 index 000000000..aa283d08d --- /dev/null +++ b/examples/nabis-uc1/README.md @@ -0,0 +1,118 @@ +# Nabis UC1 — pickup routing demo + +A Slack mention 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. + +Flows writes the approval prompt into the originating Slack thread and parks +on `f.human`. A verified reply from the designated user must match the +workspace, channel, thread, run reference, and open wait. 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 +``` + +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-6-astra` and keeps Slack mocked. Both modes start +the real local daemon, check the journal before and after approval, and print +redacted JSON receipts from the journal. 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). + +The real-agent receipt was captured on Node 26.8.1. The following two commands +were used with `UC1_SLACK_MODE=mock`, the team and channel from the fixture, +approver `UAPPROVER1`, and a fresh state directory. The second file held an +unmodified-style mock `message` callback from `UAPPROVER1` in the fixture +thread with the text `approve UC1-3f9d57368e0adee4`. + +```sh +node examples/nabis-uc1/slack-event.mjs examples/nabis-uc1/fixtures/mention.json +node examples/nabis-uc1/slack-event.mjs "$UC1_STATE_DIR/approve.json" +``` + +The mock-agent verification passed on Node 22.23.3. Later real-agent reruns +on Node 22 reached Codex and received provider rate limits before completing. + +The checkout's signed-in CLI can report regular `flows run` and `flows resume` +invocations to Cloud even when `FLOWS_CLOUD_MIRROR=0`. Use the event bridge +below. It calls the same local SDK lifecycle directly with no mirroring or +observer registration. + +## Use the approved test channel + +This path expects an existing Relayfile Slack writeback mount and an existing +trusted event source that has authenticated the Slack callback. The bridge +is a local event consumer. The source hands it a JSON file containing the +callback's `type`, `team_id`, `event_id`, and inner `event`, as in +[the mock mention](fixtures/mention.json). Run the bridge as the operator +account and keep the event input and state directory private to that account +and the trusted producer. Slack identities come from the verified event +fields. + +Set these for the approved workspace, channel and approver. Use a fresh state +directory for the demo, and keep its path for subsequent events. + +```sh +export UC1_SLACK_MODE=live +export UC1_SLACK_TEAM='' +export UC1_SLACK_CHANNEL='' +export UC1_SLACK_APPROVER='' +export RELAYFILE_MOUNT_PATH='' +export UC1_STATE_DIR="$(mktemp -d)" +node examples/nabis-uc1/slack-event.mjs /path/to/verified-slack-event.json +``` + +1. In the approved channel, send a top-level `@YourSlackApp nabis-uc1` mention. + The trusted source passes the `app_mention` callback to the bridge. Exit + code 3 and a `parked` receipt mean the workflow posted its approval prompt + and is waiting. Save the printed `runId` and `humanWait.waitId`. +2. The designated user replies `approve UC1-…` or `decline UC1-…` in the + original thread using the reference in the prompt. The source passes the + corresponding unedited Slack `message` callback to the same command and + state directory. Exit 75 means the source should retry the same event + because the park has yet to be recorded. +3. Inspect the thread summary and the local journal. A successful simulation + records one shipment receipt and a confirmed reply. A decline records the + decision and a blocked summary. + +```sh +node packages/sdk/dist/cli.js status --json --data-dir "$UC1_STATE_DIR/journal" '' +``` + +The bridge accepts a fixed demo command and supplies a fictional routing task +to the agents. The Slack connection supplies trigger and approval metadata. +All shipping is simulated. Live Slack delivery remains unverified pending the +approved workspace, test channel, designated approver, and trusted inbound +event source. diff --git a/examples/nabis-uc1/agent-cli/codex b/examples/nabis-uc1/agent-cli/codex new file mode 100755 index 000000000..d7f9b78c7 --- /dev/null +++ b/examples/nabis-uc1/agent-cli/codex @@ -0,0 +1,13 @@ +#!/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. +if [ "${1:-}" = 'exec' ]; then + shift + if [ "${1:-}" = '--skip-git-repo-check' ] && [ "${2:-}" = '--dangerously-bypass-approvals-and-sandbox' ]; then + shift 2 + set -- --skip-git-repo-check --sandbox read-only --ephemeral "$@" + fi + 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 "$@" +fi +exec codex "$@" diff --git a/examples/nabis-uc1/contracts.ts b/examples/nabis-uc1/contracts.ts new file mode 100644 index 000000000..5d002fd29 --- /dev/null +++ b/examples/nabis-uc1/contracts.ts @@ -0,0 +1,77 @@ +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; +} diff --git a/examples/nabis-uc1/fixtures/codex b/examples/nabis-uc1/fixtures/codex new file mode 100755 index 000000000..dc68d5623 --- /dev/null +++ b/examples/nabis-uc1/fixtures/codex @@ -0,0 +1,41 @@ +#!/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 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..199a5f681 --- /dev/null +++ b/examples/nabis-uc1/flows.json @@ -0,0 +1,4 @@ +{ + "cli": "./agent-cli/codex", + "models": ["gpt-6-astra"] +} diff --git a/examples/nabis-uc1/slack-event.mjs b/examples/nabis-uc1/slack-event.mjs new file mode 100644 index 000000000..7b79a3d12 --- /dev/null +++ b/examples/nabis-uc1/slack-event.mjs @@ -0,0 +1,177 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { JournalClient } from '../../packages/sdk/dist/index.js'; +import { answerFlow } from '../../packages/sdk/dist/cli/answer.js'; +import { runDirectFlow } from '../../packages/sdk/dist/cli/direct-run.js'; +import { resumeFlow } from '../../packages/sdk/dist/cli/run.js'; +import { + approvalAttribution, approvalQuestion, approverIdentity, CHANNEL_ID, EVENT_ID, MOCK_PROMPT_TS, + record, REQUEST_ID, SLACK_TS, TEAM_ID, USER_ID, +} from './contracts.ts'; + +const flow = fileURLToPath(new URL('./uc1.flow.ts', import.meta.url)); +const mention = /^<@[UW][A-Z0-9]{2,31}> nabis-uc1$/u; +const decision = /^(approve|decline) (UC1-[a-f0-9]{16})$/u; + +function requireMatch(value, pattern, description) { + if (typeof value !== 'string' || !pattern.test(value)) throw new Error(`Invalid ${description}.`); + return value; +} + +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) { + 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'), + }; +} + +// Use the same lifecycle as the CLI without the signed-in CLI's automatic +// dashboard reporting. Only Slack writeback uses an integration in live mode. +const localAgent = { localAgent: true }; +const journalDir = config => join(config.state, 'journal'); + +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 }; +} + +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, exitCode: status } = await runDirectFlow(flow, JSON.stringify(input), journalDir(config), { + ...localAgent, authoredAdmissionKey: `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 } = report; + await saveState(path, { input, runId, socketPath, waitId, promptTs }); + return { status, report: { runId, socketPath, status: 'parked', humanWait, request, transport: mode } }; + } 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(state) { + const client = new JournalClient(state.socketPath); + try { + await client.connect(); + await client.hello('nabis-uc1-slack-event'); + const { entries } = await client.journalRead(state.runId, 1, 500); + const asked = entries.find(entry => entry.entry_type === 'wait.human' && entry.payload.wait_id === state.waitId); + if (asked?.payload.requested_of !== approverIdentity(state.input.approver) + || asked.payload.prompt !== approvalQuestion(state.input.request, state.promptTs)) { + throw new Error('The run does not have this Slack approval question.'); + } + return entries.find(entry => entry.entry_type === 'wait.completed' + && entry.payload.wait_id === state.waitId && entry.payload.completionReason === 'human_responded')?.payload.result; + } 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); + // 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(state); + if (!recorded) { + await answerFlow(state.runId, state.waitId, approved, journalDir(config), { answeredBy: identity, note }); + recorded = await recordedDecision(state); + } + if (recorded?.answeredBy !== identity || recorded.note !== note || recorded.answer !== approved) { + throw new Error('This run did not accept this Slack decision.'); + } + const { report, exitCode: status } = await resumeFlow(state.runId, journalDir(config), localAgent); + 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 { event, eventId } = readEnvelope(JSON.parse(await readFile(eventPath, 'utf8')), config); + const work = join(config.state, 'work'); + await mkdir(work, { recursive: true, mode: 0o700 }); + 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/uc1.flow.ts b/examples/nabis-uc1/uc1.flow.ts new file mode 100644 index 000000000..7e3c5218f --- /dev/null +++ b/examples/nabis-uc1/uc1.flow.ts @@ -0,0 +1,105 @@ +import { flow, type AgentResult, type Ctx } from '@relayflows/surface'; +import { + approvalAttribution, approvalQuestion, approverIdentity, CHANNEL_ID, EVENT_ID, MOCK_PROMPT_TS, + orderedTasks, record, REQUEST_ID, routes, SLACK_TS, TEAM_ID, USER_ID, type RunInput, +} from './contracts.ts'; + +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("'", "'\\''") + "'"; + +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}`, model: 'gpt-6-astra', timeout: '2m', transportRetries: 0 }); +} + +export default flow('nabis-uc1', { tools: { slack: true } }, async (f, input) => { + if (!input || !TEAM_ID.test(input.team) || !CHANNEL_ID.test(input.channel) || !USER_ID.test(input.approver) + || !SLACK_TS.test(input.thread) || !REQUEST_ID.test(input.request) || !EVENT_ID.test(input.triggerEvent) + || !['mock', 'live'].includes(input.mode) + || (process.env.RELAYFLOWS_SLACK_MOCK === '1') !== (input.mode === 'mock')) { + return f.done('step_failed', { detail: 'Expected a scoped UC1 Slack trigger and the matching Slack transport mode.' }); + } + + const label = input.mode === 'mock' ? '[MOCK SLACK · SIMULATION]' : '[SIMULATION]'; + const reply = (text: string) => f.slack.reply(input.channel, input.thread, `${label} ${input.request}\n${text}`); + const blocked = async (done: string, reason: string, next: string) => { + await reply(`*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 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 (!Object.hasOwn(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); + } + + 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 + || candidate.ready !== routes.ready || candidate.canceled !== routes.canceled || 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.'); + } + + 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.'); + } + + const prompt = await reply( + `First review rejected the missing held route. Repair passed all three routing checks and re-review.\n` + + `<@${input.approver}>, reply in this thread with \`approve ${input.request}\` or \`decline ${input.request}\`.`); + if (prompt.channel !== input.channel || !(input.mode === '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(input.approver); + const source = approvalAttribution(input, prompt.ts).replaceAll('.', '\\.'); + const approved = await f.human(approvalQuestion(input.request, prompt.ts), { to }).gate({ + type: 'regex_match', + pattern: `"note":"${source}Ev[A-Za-z0-9]{2,32}:\\d{10}\\.\\d{6}","answeredBy":"${to}"`, + }); + if (!approved) { + await reply('*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: input.request, rules: repaired, + }))}`); + await reply('*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/mock-agent-mock-slack.json b/examples/nabis-uc1/verification/mock-agent-mock-slack.json new file mode 100644 index 000000000..1bc24df7b --- /dev/null +++ b/examples/nabis-uc1/verification/mock-agent-mock-slack.json @@ -0,0 +1,93 @@ +{ + "agent": "mock", + "slack": "mock", + "shipment": "simulation", + "refusals": [ + "wrong workspace", + "wrong channel", + "wrong approver", + "wrong thread", + "stale reply", + "bot reply" + ], + "approved": { + "runId": "01M8TS84NRFBQDF8NA4XZ26F97", + "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-01M8TS84NRFBQDF8NA4XZ26F97-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-01M8TS84NRFBQDF8NA4XZ26F97-7", + "ts": "mock-slack-01M8TS84NRFBQDF8NA4XZ26F97-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-01M8TS84NRFBQDF8NA4XZ26F97-10", + "ts": "mock-slack-01M8TS84NRFBQDF8NA4XZ26F97-10" + } + ] + }, + "declined": { + "runId": "01M8TS8CY0M14TST44W5N3Z7JA", + "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..8fce4efab --- /dev/null +++ b/examples/nabis-uc1/verification/real-agent-mock-slack.json @@ -0,0 +1,81 @@ +{ + "agent": "real", + "provider": "codex", + "model": "gpt-6-astra", + "slack": "mock", + "shipment": "simulation", + "approved": { + "runId": "01M8TS0EQ0ANQK19KSAFFGMPQX", + "waitId": "human-8", + "request": "UC1-3f9d57368e0adee4", + "plan": { + "tasks": [ + { + "dependsOn": [], + "id": "assign-baseline-routes", + "statuses": [ + "ready", + "canceled" + ] + }, + { + "dependsOn": [ + "assign-baseline-routes" + ], + "id": "assign-held-exception", + "statuses": [ + "held" + ] + } + ] + }, + "executionOrder": [ + "assign-baseline-routes", + "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-01M8TS0EQ0ANQK19KSAFFGMPQX-7:EvMockApprove1: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-01M8TS0EQ0ANQK19KSAFFGMPQX-7", + "ts": "mock-slack-01M8TS0EQ0ANQK19KSAFFGMPQX-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-01M8TS0EQ0ANQK19KSAFFGMPQX-10", + "ts": "mock-slack-01M8TS0EQ0ANQK19KSAFFGMPQX-10" + } + ] + }, + "localCloudMirrorLedger": "absent" +} diff --git a/examples/nabis-uc1/verify.mjs b/examples/nabis-uc1/verify.mjs new file mode 100644 index 000000000..6d5454b3a --- /dev/null +++ b/examples/nabis-uc1/verify.mjs @@ -0,0 +1,214 @@ +import assert from 'node:assert/strict'; +import { spawn, spawnSync } from 'node:child_process'; +import { once } from 'node:events'; +import { access, mkdtemp, readFile, readdir, rm, writeFile } 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 incoming = join(state, 'incoming.json'); +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; +const evidence = { agent: agentMode, slack: 'mock', shipment: 'simulation' }; + +async function send(event, expectedStatus = 0, refusal) { + await writeFile(incoming, JSON.stringify(event)); + const child = spawnSync(process.execPath, [gateway, incoming], { + env, encoding: 'utf8', 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) { + return (await client.journalRead(runId, 1, 500)).entries; +} + +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'); +} + +try { + 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 = new JournalClient(parked.socketPath); + await client.connect(); + await client.hello('nabis-uc1-proof'); + + 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-'))); + assert.equal((await readdir(join(journal, 'mock-writeback/slack'))).length, 1); + + 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']; + } + + const approve = reply(trigger, parked.request); + const done = await send(approve); + 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, 2); + assert.equal((await readdir(join(journal, 'mock-writeback/slack'))).length, 2); + 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[1].params.text, /\*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(); + if (daemon?.exitCode === null && daemon.signalCode === null) { + const exited = once(daemon, 'exit'); + daemon.kill(); + await exited; + } + 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..f3bd4f4a8 100644 --- a/packages/sdk/src/authored-helper-effect.ts +++ b/packages/sdk/src/authored-helper-effect.ts @@ -101,7 +101,12 @@ 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. Settle the dispatch promise + // so the authored operation has no derived work left on replay. + resolve(); + return; + } if (outcome.status === 'failed') { throw new AuthoredFlowExecutionError('step_failed', `Helper run ${runId} ${outcome.status}`, undefined, runId); } diff --git a/packages/sdk/tests/authored-flow-slack.test.ts b/packages/sdk/tests/authored-flow-slack.test.ts index 5ea60f117..d2ea2025f 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,30 @@ 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: [] }); + expect(mockFiles(dataDir)).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; From fb79d8fefbf87e638ffeb1d107b494cc8e6be674 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Tue, 1 Dec 2026 23:12:01 -0800 Subject: [PATCH 02/19] Reconnect the UC1 journal before processing Slack approval --- examples/nabis-uc1/README.md | 6 ++++-- examples/nabis-uc1/slack-event.mjs | 13 ++++++++----- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/examples/nabis-uc1/README.md b/examples/nabis-uc1/README.md index aa283d08d..430cda50a 100644 --- a/examples/nabis-uc1/README.md +++ b/examples/nabis-uc1/README.md @@ -53,8 +53,8 @@ and web search disabled. See the recorded The real-agent receipt was captured on Node 26.8.1. The following two commands were used with `UC1_SLACK_MODE=mock`, the team and channel from the fixture, -approver `UAPPROVER1`, and a fresh state directory. The second file held an -unmodified-style mock `message` callback from `UAPPROVER1` in the fixture +approver `UAPPROVER1`, and a fresh state directory. The second file held a +mock Slack `message` callback from `UAPPROVER1` in the fixture thread with the text `approve UC1-3f9d57368e0adee4`. ```sh @@ -64,6 +64,8 @@ node examples/nabis-uc1/slack-event.mjs "$UC1_STATE_DIR/approve.json" The mock-agent verification passed on Node 22.23.3. Later real-agent reruns on Node 22 reached Codex and received provider rate limits before completing. +A separate mock run also resumed approval successfully after stopping the +local daemon while the run was parked. The checkout's signed-in CLI can report regular `flows run` and `flows resume` invocations to Cloud even when `FLOWS_CLOUD_MIRROR=0`. Use the event bridge diff --git a/examples/nabis-uc1/slack-event.mjs b/examples/nabis-uc1/slack-event.mjs index 7b79a3d12..0030e7207 100644 --- a/examples/nabis-uc1/slack-event.mjs +++ b/examples/nabis-uc1/slack-event.mjs @@ -6,6 +6,7 @@ import { JournalClient } from '../../packages/sdk/dist/index.js'; import { answerFlow } from '../../packages/sdk/dist/cli/answer.js'; import { runDirectFlow } from '../../packages/sdk/dist/cli/direct-run.js'; import { resumeFlow } from '../../packages/sdk/dist/cli/run.js'; +import { ensureDaemon } from '../../packages/sdk/dist/daemon-lifecycle.js'; import { approvalAttribution, approvalQuestion, approverIdentity, CHANNEL_ID, EVENT_ID, MOCK_PROMPT_TS, record, REQUEST_ID, SLACK_TS, TEAM_ID, USER_ID, @@ -99,7 +100,7 @@ async function start(config, event, eventId) { throw new Error('The journaled approval question does not match the Slack prompt.'); } const { runId, socketPath, humanWait } = report; - await saveState(path, { input, runId, socketPath, waitId, promptTs }); + await saveState(path, { input, runId, waitId, promptTs }); return { status, report: { runId, socketPath, status: 'parked', humanWait, request, transport: mode } }; } else if (report.runId && report.completionReason && status !== 3) { await saveState(path, { input, runId: report.rootRunId ?? report.runId }); @@ -107,8 +108,8 @@ async function start(config, event, eventId) { return { status, report: { ...report, request, transport: mode } }; } -async function recordedDecision(state) { - const client = new JournalClient(state.socketPath); +async function recordedDecision(socketPath, state) { + const client = new JournalClient(socketPath); try { await client.connect(); await client.hello('nabis-uc1-slack-event'); @@ -143,12 +144,14 @@ async function answer(config, event, eventId) { 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.'); // 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(state); + let recorded = await recordedDecision(daemon.socketPath, state); if (!recorded) { await answerFlow(state.runId, state.waitId, approved, journalDir(config), { answeredBy: identity, note }); - recorded = await recordedDecision(state); + 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.'); From 0d3a3bc287042af3a390de35d4860c3afaf1a808 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Tue, 1 Dec 2026 23:15:25 -0800 Subject: [PATCH 03/19] Validate UC1 coder output and verify approval across daemon restart --- examples/nabis-uc1/slack-event.mjs | 1 + examples/nabis-uc1/uc1.flow.ts | 2 +- .../verification/mock-agent-mock-slack.json | 15 +++---- examples/nabis-uc1/verify.mjs | 42 +++++++++++++++---- 4 files changed, 45 insertions(+), 15 deletions(-) diff --git a/examples/nabis-uc1/slack-event.mjs b/examples/nabis-uc1/slack-event.mjs index 0030e7207..228f05d3d 100644 --- a/examples/nabis-uc1/slack-event.mjs +++ b/examples/nabis-uc1/slack-event.mjs @@ -167,6 +167,7 @@ try { const { event, eventId } = readEnvelope(JSON.parse(await readFile(eventPath, 'utf8')), 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); process.chdir(work); process.env.RELAYFLOWS_SLACK_MOCK = config.mode === 'mock' ? '1' : '0'; const { status, report } = event.type === 'app_mention' diff --git a/examples/nabis-uc1/uc1.flow.ts b/examples/nabis-uc1/uc1.flow.ts index 7e3c5218f..9042b1cb2 100644 --- a/examples/nabis-uc1/uc1.flow.ts +++ b/examples/nabis-uc1/uc1.flow.ts @@ -50,7 +50,7 @@ export default flow('nabis-uc1', { tools: { slack: true } }, async (f, + '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 (!Object.hasOwn(result, 'rules') || Object.keys(rules).length !== expected.length + 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.'); } diff --git a/examples/nabis-uc1/verification/mock-agent-mock-slack.json b/examples/nabis-uc1/verification/mock-agent-mock-slack.json index 1bc24df7b..6dd026229 100644 --- a/examples/nabis-uc1/verification/mock-agent-mock-slack.json +++ b/examples/nabis-uc1/verification/mock-agent-mock-slack.json @@ -10,8 +10,9 @@ "stale reply", "bot reply" ], + "resumedAfterDaemonRestart": true, "approved": { - "runId": "01M8TS84NRFBQDF8NA4XZ26F97", + "runId": "01M8TSPQZBQQ3ZK6ZGE21P64H9", "waitId": "human-8", "request": "UC1-3f9d57368e0adee4", "plan": { @@ -53,7 +54,7 @@ }, "answer": { "answeredBy": "slack:@UAPPROVER1", - "note": "slack-event:TUC1DEMO:CUC1DEMO:1780000000.000001:UC1-3f9d57368e0adee4:mock-slack-01M8TS84NRFBQDF8NA4XZ26F97-7:EvMockDecision000001:1780000001.000001", + "note": "slack-event:TUC1DEMO:CUC1DEMO:1780000000.000001:UC1-3f9d57368e0adee4:mock-slack-01M8TSPQZBQQ3ZK6ZGE21P64H9-7:EvMockDecision000001:1780000001.000001", "answer": true }, "result": "success", @@ -71,20 +72,20 @@ "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-01M8TS84NRFBQDF8NA4XZ26F97-7", - "ts": "mock-slack-01M8TS84NRFBQDF8NA4XZ26F97-7" + "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-01M8TS84NRFBQDF8NA4XZ26F97-10", - "ts": "mock-slack-01M8TS84NRFBQDF8NA4XZ26F97-10" + "ref": "mock-ref-slack-01M8TSPQZBQQ3ZK6ZGE21P64H9-10", + "ts": "mock-slack-01M8TSPQZBQQ3ZK6ZGE21P64H9-10" } ] }, "declined": { - "runId": "01M8TS8CY0M14TST44W5N3Z7JA", + "runId": "01M8TSQ05KDVVNB2W8NBP5JHVQ", "result": "declined", "thread": "1780000000.000002", "simulatedShip": false diff --git a/examples/nabis-uc1/verify.mjs b/examples/nabis-uc1/verify.mjs index 6d5454b3a..1ffae18ba 100644 --- a/examples/nabis-uc1/verify.mjs +++ b/examples/nabis-uc1/verify.mjs @@ -33,6 +33,7 @@ const env = { let client; let daemon; +let testRestartedDaemon = false; const evidence = { agent: agentMode, slack: 'mock', shipment: 'simulation' }; async function send(event, expectedStatus = 0, refusal) { @@ -87,6 +88,20 @@ 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 { await access(daemonBinary); daemon = spawn(daemonBinary, ['--data-dir', journal, 'serve'], { stdio: ['ignore', 'ignore', 'inherit'] }); @@ -100,9 +115,7 @@ try { assert.equal(parked.status, 'parked'); assert.equal(parked.transport, 'mock'); assert.equal(parked.humanWait.to, 'slack:@' + approver); - client = new JournalClient(parked.socketPath); - await client.connect(); - await client.hello('nabis-uc1-proof'); + client = await connect(parked.socketPath); const before = completedSteps(await entries(parked.runId)); const planner = before.find(step => step.label === 'planner'); @@ -134,8 +147,19 @@ try { 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'); @@ -205,10 +229,14 @@ try { console.log(JSON.stringify(evidence, null, 2)); } finally { client?.close(); - if (daemon?.exitCode === null && daemon.signalCode === null) { - const exited = once(daemon, 'exit'); - daemon.kill(); - await exited; + 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 }); } From 27c9fc51d8b93a425d4b546e2540ce42efe4baff Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Tue, 1 Dec 2026 23:18:37 -0800 Subject: [PATCH 04/19] Keep UC1 model invocation read-only and paginate journal reads --- examples/nabis-uc1/README.md | 2 +- examples/nabis-uc1/agent-cli/codex | 29 ++++++++++++++++++++++++----- examples/nabis-uc1/fixtures/codex | 4 ++++ examples/nabis-uc1/slack-event.mjs | 12 ++++++------ examples/nabis-uc1/verify.mjs | 9 ++++++++- 5 files changed, 43 insertions(+), 13 deletions(-) diff --git a/examples/nabis-uc1/README.md b/examples/nabis-uc1/README.md index 430cda50a..e17fe191d 100644 --- a/examples/nabis-uc1/README.md +++ b/examples/nabis-uc1/README.md @@ -63,7 +63,7 @@ node examples/nabis-uc1/slack-event.mjs "$UC1_STATE_DIR/approve.json" ``` The mock-agent verification passed on Node 22.23.3. Later real-agent reruns -on Node 22 reached Codex and received provider rate limits before completing. +on Node 22 and Node 26 received Codex provider rate limits before completing. A separate mock run also resumed approval successfully after stopping the local daemon while the run was parked. diff --git a/examples/nabis-uc1/agent-cli/codex b/examples/nabis-uc1/agent-cli/codex index d7f9b78c7..a9568b782 100755 --- a/examples/nabis-uc1/agent-cli/codex +++ b/examples/nabis-uc1/agent-cli/codex @@ -1,13 +1,32 @@ #!/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. +refuse() { + printf '%s\n' 'UC1 accepts only fresh Codex turns and model probes.' >&2 + exit 2 +} + if [ "${1:-}" = 'exec' ]; then shift - if [ "${1:-}" = '--skip-git-repo-check' ] && [ "${2:-}" = '--dangerously-bypass-approvals-and-sandbox' ]; then - shift 2 - set -- --skip-git-repo-check --sandbox read-only --ephemeral "$@" - fi + 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 "$@" + --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/fixtures/codex b/examples/nabis-uc1/fixtures/codex index dc68d5623..d3e345ec8 100755 --- a/examples/nabis-uc1/fixtures/codex +++ b/examples/nabis-uc1/fixtures/codex @@ -6,6 +6,10 @@ if (argv[0] === '--version') { } 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'); diff --git a/examples/nabis-uc1/slack-event.mjs b/examples/nabis-uc1/slack-event.mjs index 228f05d3d..9976f0267 100644 --- a/examples/nabis-uc1/slack-event.mjs +++ b/examples/nabis-uc1/slack-event.mjs @@ -3,6 +3,7 @@ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; import { 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 { answerFlow } from '../../packages/sdk/dist/cli/answer.js'; import { runDirectFlow } from '../../packages/sdk/dist/cli/direct-run.js'; import { resumeFlow } from '../../packages/sdk/dist/cli/run.js'; @@ -113,14 +114,13 @@ async function recordedDecision(socketPath, state) { try { await client.connect(); await client.hello('nabis-uc1-slack-event'); - const { entries } = await client.journalRead(state.runId, 1, 500); - const asked = entries.find(entry => entry.entry_type === 'wait.human' && entry.payload.wait_id === state.waitId); - if (asked?.payload.requested_of !== approverIdentity(state.input.approver) - || asked.payload.prompt !== approvalQuestion(state.input.request, state.promptTs)) { + 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 entries.find(entry => entry.entry_type === 'wait.completed' - && entry.payload.wait_id === state.waitId && entry.payload.completionReason === 'human_responded')?.payload.result; + return answer; } finally { client.close(); } diff --git a/examples/nabis-uc1/verify.mjs b/examples/nabis-uc1/verify.mjs index 1ffae18ba..b21168bf0 100644 --- a/examples/nabis-uc1/verify.mjs +++ b/examples/nabis-uc1/verify.mjs @@ -62,7 +62,14 @@ function reply(mention, request, command = 'approve', overrides = {}) { } async function entries(runId) { - return (await client.journalRead(runId, 1, 500)).entries; + 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) { From 31e0ab655c922b26e1fce76f2183947a8c045b4f Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Tue, 1 Dec 2026 23:24:16 -0800 Subject: [PATCH 05/19] Capture UC1 approval and helper replay regression receipts --- examples/nabis-uc1/README.md | 11 ++++++++--- examples/nabis-uc1/fixtures/approve.json | 13 +++++++++++++ .../verification/helper-resume-regression.txt | 12 ++++++++++++ packages/sdk/src/authored-helper-effect.ts | 5 +++-- packages/sdk/tests/authored-flow-slack.test.ts | 9 ++++++++- 5 files changed, 44 insertions(+), 6 deletions(-) create mode 100644 examples/nabis-uc1/fixtures/approve.json create mode 100644 examples/nabis-uc1/verification/helper-resume-regression.txt diff --git a/examples/nabis-uc1/README.md b/examples/nabis-uc1/README.md index e17fe191d..dbab0964b 100644 --- a/examples/nabis-uc1/README.md +++ b/examples/nabis-uc1/README.md @@ -53,12 +53,15 @@ and web search disabled. See the recorded The real-agent receipt was captured on Node 26.8.1. The following two commands were used with `UC1_SLACK_MODE=mock`, the team and channel from the fixture, -approver `UAPPROVER1`, and a fresh state directory. The second file held a -mock Slack `message` callback from `UAPPROVER1` in the fixture -thread with the text `approve UC1-3f9d57368e0adee4`. +approver `UAPPROVER1`, and a fresh state directory. The checked-in approval +fixture reproduces the mock Slack reply. ```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" ``` @@ -66,6 +69,8 @@ The mock-agent verification passed on Node 22.23.3. Later real-agent reruns on Node 22 and Node 26 received Codex provider rate limits before completing. A separate mock run 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. The checkout's signed-in CLI can report regular `flows run` and `flows resume` invocations to Cloud even when `FLOWS_CLOUD_MIRROR=0`. Use the event bridge 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/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/packages/sdk/src/authored-helper-effect.ts b/packages/sdk/src/authored-helper-effect.ts index f3bd4f4a8..93c316c0d 100644 --- a/packages/sdk/src/authored-helper-effect.ts +++ b/packages/sdk/src/authored-helper-effect.ts @@ -102,8 +102,9 @@ async function driveHelperEffect( await releaseHelperReceiptWaits(journal, runId); const outcome = await journal.runResume(runId); if (outcome.status === 'completed') { - // No dispatch follows a memoized effect. Settle the dispatch promise - // so the authored operation has no derived work left on replay. + // 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; } diff --git a/packages/sdk/tests/authored-flow-slack.test.ts b/packages/sdk/tests/authored-flow-slack.test.ts index d2ea2025f..2b62da54a 100644 --- a/packages/sdk/tests/authored-flow-slack.test.ts +++ b/packages/sdk/tests/authored-flow-slack.test.ts @@ -143,7 +143,14 @@ export default flow('notify-then-approve', async f => { 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: [] }); - expect(mockFiles(dataDir)).toHaveLength(2); + 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 () => { From 70f329dfbfcd16ce651ab676bd0b5bd17a36ef21 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Tue, 1 Dec 2026 23:27:11 -0800 Subject: [PATCH 06/19] Surface daemon attach warnings in the UC1 bridge --- examples/nabis-uc1/slack-event.mjs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/nabis-uc1/slack-event.mjs b/examples/nabis-uc1/slack-event.mjs index 9976f0267..9e06f6670 100644 --- a/examples/nabis-uc1/slack-event.mjs +++ b/examples/nabis-uc1/slack-event.mjs @@ -102,7 +102,8 @@ async function start(config, event, eventId) { } const { runId, socketPath, humanWait } = report; await saveState(path, { input, runId, waitId, promptTs }); - return { status, report: { runId, socketPath, status: 'parked', humanWait, request, transport: mode } }; + const diagnostics = report.diagnostics.filter(diagnostic => diagnostic.severity === 'warning'); + return { status, report: { runId, socketPath, status: 'parked', humanWait, request, transport: mode, diagnostics } }; } else if (report.runId && report.completionReason && status !== 3) { await saveState(path, { input, runId: report.rootRunId ?? report.runId }); } @@ -146,6 +147,7 @@ async function answer(config, event, eventId) { 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); From b93e121708d86092c83645a2439418ed9a9823f2 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Tue, 1 Dec 2026 23:42:25 -0800 Subject: [PATCH 07/19] Pin UC1 to the supported Codex model pair --- examples/nabis-uc1/README.md | 15 ++++++-------- examples/nabis-uc1/agent-cli/codex | 6 ++++++ examples/nabis-uc1/flows.json | 4 ++-- examples/nabis-uc1/slack-event.mjs | 5 ++++- examples/nabis-uc1/uc1.flow.ts | 2 +- .../verification/real-agent-mock-slack.json | 20 +++++++++---------- 6 files changed, 28 insertions(+), 24 deletions(-) diff --git a/examples/nabis-uc1/README.md b/examples/nabis-uc1/README.md index dbab0964b..778b6c7fe 100644 --- a/examples/nabis-uc1/README.md +++ b/examples/nabis-uc1/README.md @@ -43,7 +43,7 @@ node examples/nabis-uc1/verify.mjs --real-agent 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-6-astra` and keeps Slack mocked. Both modes start +signed-in Codex with `gpt-5.6-sol` and keeps Slack mocked. Both modes start the real local daemon, check the journal before and after approval, and print redacted JSON receipts from the journal. The shim runs Codex in a separate, read-only working directory with shell, delegated agents, apps, plugins, hooks, @@ -51,10 +51,9 @@ 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). -The real-agent receipt was captured on Node 26.8.1. The following two commands -were used with `UC1_SLACK_MODE=mock`, the team and channel from the fixture, -approver `UAPPROVER1`, and a fresh state directory. The checked-in approval -fixture reproduces the mock Slack reply. +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 @@ -65,10 +64,8 @@ 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. Later real-agent reruns -on Node 22 and Node 26 received Codex provider rate limits before completing. -A separate mock run also resumed approval successfully after stopping the -local daemon while the run was parked. +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. diff --git a/examples/nabis-uc1/agent-cli/codex b/examples/nabis-uc1/agent-cli/codex index a9568b782..ca837e860 100755 --- a/examples/nabis-uc1/agent-cli/codex +++ b/examples/nabis-uc1/agent-cli/codex @@ -1,6 +1,12 @@ #!/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. +if [ "${PATH%%:*}" = "${0%/*}" ]; then + PATH="${PATH#*:}" + export PATH +fi + refuse() { printf '%s\n' 'UC1 accepts only fresh Codex turns and model probes.' >&2 exit 2 diff --git a/examples/nabis-uc1/flows.json b/examples/nabis-uc1/flows.json index 199a5f681..66f172fb3 100644 --- a/examples/nabis-uc1/flows.json +++ b/examples/nabis-uc1/flows.json @@ -1,4 +1,4 @@ { - "cli": "./agent-cli/codex", - "models": ["gpt-6-astra"] + "cli": "codex", + "models": ["gpt-5.6-sol"] } diff --git a/examples/nabis-uc1/slack-event.mjs b/examples/nabis-uc1/slack-event.mjs index 9e06f6670..96277c5de 100644 --- a/examples/nabis-uc1/slack-event.mjs +++ b/examples/nabis-uc1/slack-event.mjs @@ -1,6 +1,6 @@ import { createHash, randomUUID } from 'node:crypto'; import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; -import { join, resolve } from 'node:path'; +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'; @@ -14,6 +14,7 @@ import { } from './contracts.ts'; const flow = fileURLToPath(new URL('./uc1.flow.ts', import.meta.url)); +const agentCli = fileURLToPath(new URL('./agent-cli', import.meta.url)); const mention = /^<@[UW][A-Z0-9]{2,31}> nabis-uc1$/u; const decision = /^(approve|decline) (UC1-[a-f0-9]{16})$/u; @@ -170,6 +171,8 @@ try { 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).map(path => resolve(path)); + 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' diff --git a/examples/nabis-uc1/uc1.flow.ts b/examples/nabis-uc1/uc1.flow.ts index 9042b1cb2..3e23e9984 100644 --- a/examples/nabis-uc1/uc1.flow.ts +++ b/examples/nabis-uc1/uc1.flow.ts @@ -15,7 +15,7 @@ function agentJson(result: AgentResult): Record { } function agent(f: Ctx, step: string, task: string) { - return f.agent(step, { task: `${task}\n${jsonOnly}`, model: 'gpt-6-astra', timeout: '2m', transportRetries: 0 }); + 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, input) => { diff --git a/examples/nabis-uc1/verification/real-agent-mock-slack.json b/examples/nabis-uc1/verification/real-agent-mock-slack.json index 8fce4efab..34333f52a 100644 --- a/examples/nabis-uc1/verification/real-agent-mock-slack.json +++ b/examples/nabis-uc1/verification/real-agent-mock-slack.json @@ -1,18 +1,16 @@ { "agent": "real", - "provider": "codex", - "model": "gpt-6-astra", "slack": "mock", "shipment": "simulation", "approved": { - "runId": "01M8TS0EQ0ANQK19KSAFFGMPQX", + "runId": "01M8TV5KEFQDA9QAGASGRBA823", "waitId": "human-8", "request": "UC1-3f9d57368e0adee4", "plan": { "tasks": [ { "dependsOn": [], - "id": "assign-baseline-routes", + "id": "route-baseline-pickups", "statuses": [ "ready", "canceled" @@ -20,7 +18,7 @@ }, { "dependsOn": [ - "assign-baseline-routes" + "route-baseline-pickups" ], "id": "assign-held-exception", "statuses": [ @@ -30,7 +28,7 @@ ] }, "executionOrder": [ - "assign-baseline-routes", + "route-baseline-pickups", "assign-held-exception" ], "initialReview": { @@ -47,7 +45,7 @@ }, "answer": { "answeredBy": "slack:@UAPPROVER1", - "note": "slack-event:TUC1DEMO:CUC1DEMO:1780000000.000001:UC1-3f9d57368e0adee4:mock-slack-01M8TS0EQ0ANQK19KSAFFGMPQX-7:EvMockApprove1:1780000001.000001", + "note": "slack-event:TUC1DEMO:CUC1DEMO:1780000000.000001:UC1-3f9d57368e0adee4:mock-slack-01M8TV5KEFQDA9QAGASGRBA823-7:EvMockDecision000001:1780000001.000001", "answer": true }, "result": "success", @@ -65,15 +63,15 @@ "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-01M8TS0EQ0ANQK19KSAFFGMPQX-7", - "ts": "mock-slack-01M8TS0EQ0ANQK19KSAFFGMPQX-7" + "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-01M8TS0EQ0ANQK19KSAFFGMPQX-10", - "ts": "mock-slack-01M8TS0EQ0ANQK19KSAFFGMPQX-10" + "ref": "mock-ref-slack-01M8TV5KEFQDA9QAGASGRBA823-10", + "ts": "mock-slack-01M8TV5KEFQDA9QAGASGRBA823-10" } ] }, From 5008a0758e0bcce77e931a8e7c46aaf15c8e1ada Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Wed, 2 Dec 2026 00:03:08 -0800 Subject: [PATCH 08/19] Ignore empty PATH entries in the UC1 bridge --- examples/nabis-uc1/slack-event.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/nabis-uc1/slack-event.mjs b/examples/nabis-uc1/slack-event.mjs index 96277c5de..f9d2199ae 100644 --- a/examples/nabis-uc1/slack-event.mjs +++ b/examples/nabis-uc1/slack-event.mjs @@ -171,7 +171,7 @@ try { 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).map(path => resolve(path)); + const pathEntries = (process.env.PATH ?? '').split(delimiter).filter(Boolean).map(path => resolve(path)); process.env.PATH = [agentCli, ...pathEntries.filter(path => path !== agentCli)].join(delimiter); process.chdir(work); process.env.RELAYFLOWS_SLACK_MOCK = config.mode === 'mock' ? '1' : '0'; From ee4284597117f0641fb2428438725129c865310e Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Wed, 2 Dec 2026 00:07:37 -0800 Subject: [PATCH 09/19] Refuse a shim-only PATH in the UC1 verifier --- examples/nabis-uc1/agent-cli/codex | 15 +++++++++++---- examples/nabis-uc1/verify.mjs | 11 +++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/examples/nabis-uc1/agent-cli/codex b/examples/nabis-uc1/agent-cli/codex index ca837e860..5806e6fd0 100755 --- a/examples/nabis-uc1/agent-cli/codex +++ b/examples/nabis-uc1/agent-cli/codex @@ -2,10 +2,17 @@ # 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. -if [ "${PATH%%:*}" = "${0%/*}" ]; then - PATH="${PATH#*:}" - export PATH -fi +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 diff --git a/examples/nabis-uc1/verify.mjs b/examples/nabis-uc1/verify.mjs index b21168bf0..ca4e31565 100644 --- a/examples/nabis-uc1/verify.mjs +++ b/examples/nabis-uc1/verify.mjs @@ -110,6 +110,17 @@ async function connect(socketPath) { } 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++) { From f3b5edb200e6e2bd4904cf72d385ad1e0983658f Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Fri, 4 Dec 2026 08:14:20 -0800 Subject: [PATCH 10/19] Run Nabis UC1 from a scoped Slack mention --- examples/nabis-uc1/README.md | 96 +++++++++------- examples/nabis-uc1/slack-envelope.mjs | 50 +++++++++ examples/nabis-uc1/slack-envelope.test.mjs | 48 ++++++++ examples/nabis-uc1/slack-event.mjs | 52 +++------ examples/nabis-uc1/slack-listen.mjs | 123 +++++++++++++++++++++ examples/nabis-uc1/uc1.flow.ts | 29 +++-- examples/nabis-uc1/verify.mjs | 24 ++-- 7 files changed, 329 insertions(+), 93 deletions(-) create mode 100644 examples/nabis-uc1/slack-envelope.mjs create mode 100644 examples/nabis-uc1/slack-envelope.test.mjs create mode 100644 examples/nabis-uc1/slack-listen.mjs diff --git a/examples/nabis-uc1/README.md b/examples/nabis-uc1/README.md index 778b6c7fe..66fc47511 100644 --- a/examples/nabis-uc1/README.md +++ b/examples/nabis-uc1/README.md @@ -6,8 +6,10 @@ 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. -Flows writes the approval prompt into the originating Slack thread and parks -on `f.human`. A verified reply from the designated user must match the +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, run reference, and open wait. 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 @@ -38,6 +40,7 @@ RELAYFLOWS_SLACK_MOCK=1 node packages/sdk/dist/cli.js check --json examples/nabi 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/slack-envelope.test.mjs ``` The first verification uses mock Codex and mock Slack. It checks approval, @@ -45,11 +48,12 @@ 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, check the journal before and after approval, and print -redacted JSON receipts from the journal. The shim runs Codex in a separate, +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). +[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 @@ -74,49 +78,59 @@ invocations to Cloud even when `FLOWS_CLOUD_MIRROR=0`. Use the event bridge below. It calls the same local SDK lifecycle directly with no mirroring or observer registration. -## Use the approved test channel - -This path expects an existing Relayfile Slack writeback mount and an existing -trusted event source that has authenticated the Slack callback. The bridge -is a local event consumer. The source hands it a JSON file containing the -callback's `type`, `team_id`, `event_id`, and inner `event`, as in -[the mock mention](fixtures/mention.json). Run the bridge as the operator -account and keep the event input and state directory private to that account -and the trusted producer. Slack identities come from the verified event -fields. - -Set these for the approved workspace, channel and approver. Use a fresh state -directory for the demo, and keep its path for subsequent events. +## Record 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. +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 ```sh -export UC1_SLACK_MODE=live -export UC1_SLACK_TEAM='' -export UC1_SLACK_CHANNEL='' -export UC1_SLACK_APPROVER='' -export RELAYFILE_MOUNT_PATH='' -export UC1_STATE_DIR="$(mktemp -d)" -node examples/nabis-uc1/slack-event.mjs /path/to/verified-slack-event.json +node examples/nabis-uc1/slack-listen.mjs ``` -1. In the approved channel, send a top-level `@YourSlackApp nabis-uc1` mention. - The trusted source passes the `app_mention` callback to the bridge. Exit - code 3 and a `parked` receipt mean the workflow posted its approval prompt - and is waiting. Save the printed `runId` and `humanWait.waitId`. -2. The designated user replies `approve UC1-…` or `decline UC1-…` in the - original thread using the reference in the prompt. The source passes the - corresponding unedited Slack `message` callback to the same command and - state directory. Exit 75 means the source should retry the same event - because the park has yet to be recorded. -3. Inspect the thread summary and the local journal. A successful simulation - records one shipment receipt and a confirmed reply. A decline records the - decision and a blocked summary. +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. ```sh node packages/sdk/dist/cli.js status --json --data-dir "$UC1_STATE_DIR/journal" '' ``` -The bridge accepts a fixed demo command and supplies a fictional routing task -to the agents. The Slack connection supplies trigger and approval metadata. -All shipping is simulated. Live Slack delivery remains unverified pending the -approved workspace, test channel, designated approver, and trusted inbound -event source. +Recording uses real Codex agents and live Slack transport. The routing task +is fictional and the only shipment is a local journal receipt. A live +recording with the approved Slack connection is still pending. For a separate +authenticated event source, the one-shot bridge also accepts a private +verified callback file or `-` for stdin, with `UC1_SLACK_CHANNEL` set +explicitly. The listener supplies this value automatically. 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 index f9d2199ae..5e106b9a3 100644 --- a/examples/nabis-uc1/slack-event.mjs +++ b/examples/nabis-uc1/slack-event.mjs @@ -8,26 +8,22 @@ import { answerFlow } from '../../packages/sdk/dist/cli/answer.js'; import { runDirectFlow } from '../../packages/sdk/dist/cli/direct-run.js'; import { resumeFlow } from '../../packages/sdk/dist/cli/run.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, EVENT_ID, MOCK_PROMPT_TS, - record, REQUEST_ID, SLACK_TS, TEAM_ID, USER_ID, + 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 agentCli = fileURLToPath(new URL('./agent-cli', import.meta.url)); -const mention = /^<@[UW][A-Z0-9]{2,31}> nabis-uc1$/u; -const decision = /^(approve|decline) (UC1-[a-f0-9]{16})$/u; - -function requireMatch(value, pattern, description) { - if (typeof value !== 'string' || !pattern.test(value)) throw new Error(`Invalid ${description}.`); - return value; -} +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 mode = requireMatch(env.UC1_SLACK_MODE ?? 'live', /^(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) { + if (mode === 'live' && (!env.RELAYFILE_MOUNT_PATH || !slackMount(env))) { throw new Error('Live UC1 requires the existing approved Relayfile Slack mount.'); } return { @@ -43,26 +39,6 @@ function scope(env) { const localAgent = { localAgent: true }; const journalDir = config => join(config.state, 'journal'); -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 }; -} - 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)}`; @@ -165,13 +141,21 @@ async function answer(config, event, eventId) { try { const [eventPath, ...extra] = process.argv.slice(2); - if (!eventPath || extra.length) throw new Error('Usage: node slack-event.mjs '); + if (!eventPath || extra.length) throw new Error('Usage: node slack-event.mjs '); const config = scope(process.env); - const { event, eventId } = readEnvelope(JSON.parse(await readFile(eventPath, 'utf8')), config); + let json = ''; + if (eventPath === '-') { + process.stdin.setEncoding('utf8'); + for await (const chunk of process.stdin) json += chunk; + } else { + json = 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)); + 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'; diff --git a/examples/nabis-uc1/slack-listen.mjs b/examples/nabis-uc1/slack-listen.mjs new file mode 100644 index 000000000..5dcd8d1f8 --- /dev/null +++ b/examples/nabis-uc1/slack-listen.mjs @@ -0,0 +1,123 @@ +import { spawn, spawnSync } from 'node:child_process'; +import { once } from 'node:events'; +import { delimiter, 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'; + +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) { + const 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)]), + }); + if (response.status === 429) { + const retry = Number(response.headers.get('retry-after')) || 5; + await delay(retry * 1000, undefined, { signal }); + return; + } + if (!response.ok) throw new Error(`Slack refused apps.connections.open (HTTP ${response.status}).`); + const data = await response.json(); + 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, deliver) { + const socket = new WebSocket(url); + const close = () => socket.close(); + const handshake = setTimeout(close, 15_000); + 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.'); + } else if (frame.type === 'disconnect') { + close(); + } else if (typeof frame.envelope_id === 'string' && frame.envelope_id && socket.readyState === WebSocket.OPEN) { + socket.send(JSON.stringify({ envelope_id: frame.envelope_id })); + const callback = socketCallback(frame, config); + if (callback) deliver(callback); + } + }); + try { await new Promise(done => socket.addEventListener('close', done, { once: true })); } + finally { + clearTimeout(handshake); + signal.removeEventListener('abort', close); + } +} + +async function dispatch(callback, env) { + const child = spawn(process.execPath, [bridge, '-'], { env, stdio: ['pipe', 'inherit', 'inherit'] }); + const exited = once(child, 'close'); + child.stdin.on('error', () => {}); // The child can fail preflight before reading stdin. + child.stdin.end(JSON.stringify(callback)); + const [status] = await exited; + if (status === 75) console.error('UC1 is still waiting for the local park record. Send the approval command again once parked.'); + else if (status !== 0 && status !== 3) console.error('UC1 did not complete this event. See the bridge receipt above.'); +} + +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_SLACK_MODE: 'live', UC1_SLACK_CHANNEL: channel, RELAYFLOWS_SLACK_MOCK: '0' }); + + // Serialize accepted callbacks, so an approval arriving just after Slack + // renders the prompt waits for the bridge to persist the corresponding park. + let queue = Promise.resolve(); + const pending = new Set(); + const deliver = callback => { + if (signal.aborted || pending.has(callback.event_id)) return; + pending.add(callback.event_id); + queue = queue.then(() => dispatch(callback, env)) + .catch(() => console.error('UC1 could not start the local event bridge.')) + .finally(() => pending.delete(callback.event_id)); + }; + try { + while (!signal.aborted) { + const url = await openConnection(token, signal); + if (url && !signal.aborted) await listen(url, config, signal, deliver); + await delay(2000, undefined, { signal }); + } + } finally { + await queue; + } +} + +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 index 3e23e9984..d24590582 100644 --- a/examples/nabis-uc1/uc1.flow.ts +++ b/examples/nabis-uc1/uc1.flow.ts @@ -27,9 +27,11 @@ export default flow('nabis-uc1', { tools: { slack: true } }, async (f, } const label = input.mode === 'mock' ? '[MOCK SLACK · SIMULATION]' : '[SIMULATION]'; - const reply = (text: string) => f.slack.reply(input.channel, input.thread, `${label} ${input.request}\n${text}`); + const reply = (role: string, text: string) => + f.slack.reply(input.channel, input.thread, `${label} ${input.request}\n${role}\n${text}`); + const summaryRole = ':clipboard: *Lead summary*'; const blocked = async (done: string, reason: string, next: string) => { - await reply(`*Done* ${done}\n*Next* ${next}\n*Blocked* ${reason}`); + await reply(summaryRole, `*Done* ${done}\n*Next* ${next}\n*Blocked* ${reason}`); f.done('step_failed', { detail: reason }); }; @@ -40,6 +42,11 @@ export default flow('nabis-uc1', { tools: { slack: true } }, async (f, + '{"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) { @@ -56,15 +63,19 @@ export default flow('nabis-uc1', { tools: { slack: true } }, async (f, } 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 - || candidate.ready !== routes.ready || candidate.canceled !== routes.canceled || Object.hasOwn(candidate, 'held')) { + 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)} ` @@ -77,10 +88,10 @@ export default flow('nabis-uc1', { tools: { slack: true } }, async (f, || !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.`); - const prompt = await reply( - `First review rejected the missing held route. Repair passed all three routing checks and re-review.\n` - + `<@${input.approver}>, reply in this thread with \`approve ${input.request}\` or \`decline ${input.request}\`.`); + const prompt = await reply(':pause_button: *Waiting for human approval*', + `<@${input.approver}>, reply in this thread with \`approve ${input.request}\` or \`decline ${input.request}\`.`); if (prompt.channel !== input.channel || !(input.mode === '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.' }); } @@ -91,7 +102,7 @@ export default flow('nabis-uc1', { tools: { slack: true } }, async (f, pattern: `"note":"${source}Ev[A-Za-z0-9]{2,32}:\\d{10}\\.\\d{6}","answeredBy":"${to}"`, }); if (!approved) { - await reply('*Done* Repaired rules passed review.\n*Next* Start a new test thread for another decision.\n*Blocked* The designated approver declined.'); + 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.' }); } @@ -99,7 +110,7 @@ export default flow('nabis-uc1', { tools: { slack: true } }, async (f, await f.run(`printf '%s\\n' ${shellWord(JSON.stringify({ action: 'simulate-ship', request: input.request, rules: repaired, }))}`); - await reply('*Done* Planned, coded, rejected once, repaired, re-reviewed, and recorded simulated shipment after approval.\n' + 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/verify.mjs b/examples/nabis-uc1/verify.mjs index ca4e31565..27ba3065c 100644 --- a/examples/nabis-uc1/verify.mjs +++ b/examples/nabis-uc1/verify.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import { spawn, spawnSync } from 'node:child_process'; import { once } from 'node:events'; -import { access, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'; +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'; @@ -19,7 +19,6 @@ 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 incoming = join(state, 'incoming.json'); const env = { ...process.env, RELAYFLOWD_BIN: daemonBinary, @@ -37,9 +36,8 @@ let testRestartedDaemon = false; const evidence = { agent: agentMode, slack: 'mock', shipment: 'simulation' }; async function send(event, expectedStatus = 0, refusal) { - await writeFile(incoming, JSON.stringify(event)); - const child = spawnSync(process.execPath, [gateway, incoming], { - env, encoding: 'utf8', timeout: 5 * 60_000, + 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); @@ -150,7 +148,14 @@ try { 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-'))); - assert.equal((await readdir(join(journal, 'mock-writeback/slack'))).length, 1); + 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); @@ -204,15 +209,16 @@ try { 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, 2); - assert.equal((await readdir(join(journal, 'mock-writeback/slack'))).length, 2); + 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[1].params.text, /\*Done\*[\s\S]+\*Next\*[\s\S]+\*Blocked\* None\./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, From 95abfe89815c3ee8556cf65a8886d2446a394d2d Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Fri, 4 Dec 2026 09:06:51 -0800 Subject: [PATCH 11/19] Expose Nabis UC1 runs through the Flows CLI --- examples/nabis-uc1/README.md | 42 ++++++++++++++---- examples/nabis-uc1/slack-event.mjs | 69 ++++++++++++++++++++--------- examples/nabis-uc1/slack-listen.mjs | 2 +- 3 files changed, 84 insertions(+), 29 deletions(-) diff --git a/examples/nabis-uc1/README.md b/examples/nabis-uc1/README.md index 66fc47511..664105ebd 100644 --- a/examples/nabis-uc1/README.md +++ b/examples/nabis-uc1/README.md @@ -47,8 +47,10 @@ 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, 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, +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 @@ -73,17 +75,16 @@ 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. -The checkout's signed-in CLI can report regular `flows run` and `flows resume` -invocations to Cloud even when `FLOWS_CLOUD_MIRROR=0`. Use the event bridge -below. It calls the same local SDK lifecycle directly with no mirroring or -observer registration. - ## Record 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. + `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 @@ -106,10 +107,21 @@ observer registration. ### 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 @@ -124,6 +136,20 @@ node examples/nabis-uc1/slack-listen.mjs `runId` and `humanWait.waitId` if you need the local receipts. Stop the listener with Ctrl-C after the summary. +### 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" '' ``` diff --git a/examples/nabis-uc1/slack-event.mjs b/examples/nabis-uc1/slack-event.mjs index 5e106b9a3..7216a63ad 100644 --- a/examples/nabis-uc1/slack-event.mjs +++ b/examples/nabis-uc1/slack-event.mjs @@ -1,12 +1,11 @@ +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 { answerFlow } from '../../packages/sdk/dist/cli/answer.js'; -import { runDirectFlow } from '../../packages/sdk/dist/cli/direct-run.js'; -import { resumeFlow } from '../../packages/sdk/dist/cli/run.js'; import { ensureDaemon } from '../../packages/sdk/dist/daemon-lifecycle.js'; import { slackMount } from '../../packages/sdk/dist/slack-preflight.js'; import { @@ -16,6 +15,7 @@ import { 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)); @@ -34,11 +34,46 @@ function scope(env) { }; } -// Use the same lifecycle as the CLI without the signed-in CLI's automatic -// dashboard reporting. Only Slack writeback uses an integration in live mode. -const localAgent = { localAgent: true }; 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)}`; @@ -66,9 +101,7 @@ async function start(config, event, eventId) { const { mode, team, channel, approver } = config; const input = { mode, team, channel, approver, thread: event.ts, request, triggerEvent: eventId }; - const { report, exitCode: status } = await runDirectFlow(flow, JSON.stringify(input), journalDir(config), { - ...localAgent, authoredAdmissionKey: `nabis-${request}`, - }); + 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); @@ -77,10 +110,12 @@ async function start(config, event, eventId) { 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 } = report; + 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 } }; + 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 }); } @@ -129,13 +164,13 @@ async function answer(config, event, eventId) { // with a competing answer. The same Slack event can be retried after a crash. let recorded = await recordedDecision(daemon.socketPath, state); if (!recorded) { - await answerFlow(state.runId, state.waitId, approved, journalDir(config), { answeredBy: identity, note }); + 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, exitCode: status } = await resumeFlow(state.runId, journalDir(config), localAgent); + const { report, status } = await invokeFlows(config, 'resume', [state.runId]); return { status, report: { ...report, request, transport: config.mode, decision: approved ? 'approved' : 'declined' } }; } @@ -143,13 +178,7 @@ 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); - let json = ''; - if (eventPath === '-') { - process.stdin.setEncoding('utf8'); - for await (const chunk of process.stdin) json += chunk; - } else { - json = await readFile(eventPath, 'utf8'); - } + 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 }); diff --git a/examples/nabis-uc1/slack-listen.mjs b/examples/nabis-uc1/slack-listen.mjs index 5dcd8d1f8..24ffa181d 100644 --- a/examples/nabis-uc1/slack-listen.mjs +++ b/examples/nabis-uc1/slack-listen.mjs @@ -44,7 +44,7 @@ async function listen(url, config, signal, deliver) { 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.'); + 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 && socket.readyState === WebSocket.OPEN) { From 5cc9be21df7e69960e0692ca5d91dc47a6ee877f Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Fri, 4 Dec 2026 09:15:01 -0800 Subject: [PATCH 12/19] Retain UC1 Slack callbacks for safe retry --- examples/nabis-uc1/README.md | 20 ++++--- examples/nabis-uc1/slack-event.mjs | 2 +- examples/nabis-uc1/slack-inbox.mjs | 70 ++++++++++++++++++++++ examples/nabis-uc1/slack-inbox.test.mjs | 58 ++++++++++++++++++ examples/nabis-uc1/slack-listen.mjs | 80 ++++++++++++++++--------- 5 files changed, 195 insertions(+), 35 deletions(-) create mode 100644 examples/nabis-uc1/slack-inbox.mjs create mode 100644 examples/nabis-uc1/slack-inbox.test.mjs diff --git a/examples/nabis-uc1/README.md b/examples/nabis-uc1/README.md index 664105ebd..679ec3270 100644 --- a/examples/nabis-uc1/README.md +++ b/examples/nabis-uc1/README.md @@ -40,7 +40,7 @@ RELAYFLOWS_SLACK_MOCK=1 node packages/sdk/dist/cli.js check --json examples/nabi 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/slack-envelope.test.mjs +node --test examples/nabis-uc1/slack-envelope.test.mjs examples/nabis-uc1/slack-inbox.test.mjs ``` The first verification uses mock Codex and mock Slack. It checks approval, @@ -136,6 +136,12 @@ flows resume --local-agent --cloud-mirror --json --data-dir `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_` @@ -154,9 +160,9 @@ final summary. node packages/sdk/dist/cli.js status --json --data-dir "$UC1_STATE_DIR/journal" '' ``` -Recording uses real Codex agents and live Slack transport. The routing task -is fictional and the only shipment is a local journal receipt. A live -recording with the approved Slack connection is still pending. For a separate -authenticated event source, the one-shot bridge also accepts a private -verified callback file or `-` for stdin, with `UC1_SLACK_CHANNEL` set -explicitly. The listener supplies this value automatically. +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/slack-event.mjs b/examples/nabis-uc1/slack-event.mjs index 7216a63ad..da0dd63f1 100644 --- a/examples/nabis-uc1/slack-event.mjs +++ b/examples/nabis-uc1/slack-event.mjs @@ -20,7 +20,7 @@ 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 ?? 'live', /^(mock|live)$/u, 'UC1_SLACK_MODE'); + 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))) { diff --git a/examples/nabis-uc1/slack-inbox.mjs b/examples/nabis-uc1/slack-inbox.mjs new file mode 100644 index 000000000..dd72c49c5 --- /dev/null +++ b/examples/nabis-uc1/slack-inbox.mjs @@ -0,0 +1,70 @@ +import { randomUUID } from 'node:crypto'; +import { link, mkdir, open, readFile, readdir, 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`); + 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 unlink(temporary); + } + 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 index 24ffa181d..a2bfb3137 100644 --- a/examples/nabis-uc1/slack-listen.mjs +++ b/examples/nabis-uc1/slack-listen.mjs @@ -1,28 +1,44 @@ import { spawn, spawnSync } from 'node:child_process'; import { once } from 'node:events'; -import { delimiter, resolve } from 'node:path'; +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) { - const 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)]), - }); + 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}).`); const data = await response.json(); + 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.'); } @@ -34,10 +50,11 @@ async function openConnection(token, signal) { return url; } -async function listen(url, config, signal, deliver) { +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; @@ -47,27 +64,43 @@ async function listen(url, config, signal, deliver) { 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 && socket.readyState === WebSocket.OPEN) { - socket.send(JSON.stringify({ envelope_id: frame.envelope_id })); + } else if (typeof frame.envelope_id === 'string' && frame.envelope_id && !signal.aborted) { const callback = socketCallback(frame, config); - if (callback) deliver(callback); + 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, stdio: ['pipe', 'inherit', 'inherit'] }); + 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 (status === 75) console.error('UC1 is still waiting for the local park record. Send the approval command again once parked.'); - else if (status !== 0 && status !== 3) console.error('UC1 did not complete this event. See the bridge receipt above.'); + 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) { @@ -87,27 +120,20 @@ async function main(signal) { 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_SLACK_MODE: 'live', UC1_SLACK_CHANNEL: channel, RELAYFLOWS_SLACK_MOCK: '0' }); - - // Serialize accepted callbacks, so an approval arriving just after Slack - // renders the prompt waits for the bridge to persist the corresponding park. - let queue = Promise.resolve(); - const pending = new Set(); - const deliver = callback => { - if (signal.aborted || pending.has(callback.event_id)) return; - pending.add(callback.event_id); - queue = queue.then(() => dispatch(callback, env)) - .catch(() => console.error('UC1 could not start the local event bridge.')) - .finally(() => pending.delete(callback.event_id)); - }; + 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, deliver); + if (url && !signal.aborted) await listen(url, config, signal, inbox); await delay(2000, undefined, { signal }); } } finally { - await queue; + await inbox.drain(); } } From 407f80fdab6ceda44c8423e7837525b70bbbd08a Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Fri, 4 Dec 2026 11:19:25 -0800 Subject: [PATCH 13/19] Support native hosted Slack intake for Nabis UC1 --- examples/nabis-uc1/README.md | 37 +++++- examples/nabis-uc1/contracts.ts | 84 ++----------- examples/nabis-uc1/hosted.test.mjs | 117 ++++++++++++++++++ examples/nabis-uc1/uc1.flow.ts | 191 +++++++++++++++++++++++++---- 4 files changed, 326 insertions(+), 103 deletions(-) create mode 100644 examples/nabis-uc1/hosted.test.mjs diff --git a/examples/nabis-uc1/README.md b/examples/nabis-uc1/README.md index 679ec3270..97df6219e 100644 --- a/examples/nabis-uc1/README.md +++ b/examples/nabis-uc1/README.md @@ -1,6 +1,6 @@ # Nabis UC1 — pickup routing demo -A Slack mention starts a run for a fictional pickup-routing change. A planner +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 @@ -10,7 +10,7 @@ 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, run reference, and open wait. Approval records +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**. @@ -40,7 +40,7 @@ RELAYFLOWS_SLACK_MOCK=1 node packages/sdk/dist/cli.js check --json examples/nabi 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/slack-envelope.test.mjs examples/nabis-uc1/slack-inbox.test.mjs +node --test examples/nabis-uc1/*.test.mjs ``` The first verification uses mock Codex and mock Slack. It checks approval, @@ -75,7 +75,36 @@ 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. -## Record from a real Slack mention +## 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 +flows deploy examples/nabis-uc1/uc1.flow.ts \ + --repo AgentWorkforce/flows \ + --on 'slack:channel=C0B9Z4CLG1J,contains=[UC1 SYNTHETIC] nabis-uc1' \ + --approver khaliq --agents codex --name nabis-uc1 --no-connect +``` + +The designated operator posts exactly `[UC1 SYNTHETIC] nabis-uc1` as a +top-level message in **#watchdog-test** (`C0B9Z4CLG1J`). UC1 checks the +normalized Cloud input and the mounted Slack message before starting any +agents or replies. Cloud posts the `f.human` question in the trigger 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. A deployment and Slack rehearsal in the +approved workspace are pending. + +## Local recording from a real Slack mention ### One-time setup diff --git a/examples/nabis-uc1/contracts.ts b/examples/nabis-uc1/contracts.ts index 5d002fd29..e15d59593 100644 --- a/examples/nabis-uc1/contracts.ts +++ b/examples/nabis-uc1/contracts.ts @@ -1,77 +1,7 @@ -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; -} +// 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/hosted.test.mjs b/examples/nabis-uc1/hosted.test.mjs new file mode 100644 index 000000000..7150b0b7c --- /dev/null +++ b/examples/nabis-uc1/hosted.test.mjs @@ -0,0 +1,117 @@ +import assert from 'node:assert/strict'; +import { spawnSync } 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 { getFlowDefinition } from '@relayflows/surface/runtime'; +import uc1, { routes } from './uc1.flow.ts'; + +delete process.env.RELAYFLOWS_SLACK_MOCK; + +const text = '[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 }, + 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 } = {}) { + 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 }); + await writeFile(recordPath, JSON.stringify(message)); + const calls = { commands: [], replies: [], agents: [], gates: [], verdict: '' }; + await getFlowDefinition(uc1).body({ + async run(command) { + calls.commands.push(command); + const child = spawnSync(command, { + shell: true, encoding: 'utf8', env: { PATH: process.env.PATH, RELAYFILE_MOUNT_PATH: fixture }, + }); + assert.ifError(child.error); + return { ok: child.status === 0, stdout: child.stdout }; + }, + async agent(name, { cli }) { + assert.equal(cli, 'codex'); + assert.ok(responses[name]); + 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: 4, + }]); + assert.equal(calls.replies.length, 5); // Cloud delivers the approval prompt. + 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('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' }, + { 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, 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/uc1.flow.ts b/examples/nabis-uc1/uc1.flow.ts index d24590582..a3d1e9bad 100644 --- a/examples/nabis-uc1/uc1.flow.ts +++ b/examples/nabis-uc1/uc1.flow.ts @@ -1,13 +1,144 @@ import { flow, type AgentResult, type Ctx } from '@relayflows/surface'; -import { - approvalAttribution, approvalQuestion, approverIdentity, CHANNEL_ID, EVENT_ID, MOCK_PROMPT_TS, - orderedTasks, record, REQUEST_ID, routes, SLACK_TS, TEAM_ID, USER_ID, type RunInput, -} from './contracts.ts'; + +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 hostedCommand = '[UC1 SYNTHETIC] nabis-uc1'; +const hostedMessagePath = /^\/slack\/channels\/C0B9Z4CLG1J(?:__watchdog-test)?\/messages\/(\d{10})[_.](\d{6})(?:\/meta\.json|\.json)$/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.body !== hostedCommand || 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 path = paths[0]!; + const [, seconds, fraction] = hostedMessagePath.exec(path)!; + return { path, 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 [path, expectedJson] = process.argv.slice(1); + const expected = JSON.parse(expectedJson); + const root = process.env.RELAYFILE_MOUNT_PATH; + if (!root) process.exit(1); + try { + const file = JSON.parse(readFileSync(root + path, 'utf8')); + 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)); + process.exitCode = verified ? 0 : 1; + } catch { + process.exitCode = 1; + } +`; function agentJson(result: AgentResult): Record { if (result.completionReason !== 'success') return {}; @@ -18,17 +149,25 @@ 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, input) => { - if (!input || !TEAM_ID.test(input.team) || !CHANNEL_ID.test(input.channel) || !USER_ID.test(input.approver) - || !SLACK_TS.test(input.thread) || !REQUEST_ID.test(input.request) || !EVENT_ID.test(input.triggerEvent) - || !['mock', 'live'].includes(input.mode) - || (process.env.RELAYFLOWS_SLACK_MOCK === '1') !== (input.mode === 'mock')) { +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: hostedCommand }; + const check = await f.run(`node -e ${shellWord(checkHostedSlackMessage)} ${shellWord(hosted.path)} ${shellWord(JSON.stringify(expected))}`, + { onNonZero: 'record' }); + if (!check.ok) return f.done('step_failed', { detail: 'The mounted Slack record did not confirm the synthetic trigger and designated sender.' }); + } - const label = input.mode === 'mock' ? '[MOCK SLACK · SIMULATION]' : '[SIMULATION]'; + const label = mock ? '[MOCK SLACK · SIMULATION]' : '[SIMULATION]'; const reply = (role: string, text: string) => - f.slack.reply(input.channel, input.thread, `${label} ${input.request}\n${role}\n${text}`); + f.slack.reply(run.channel, run.thread, `${label} ${run.request}\n${role}\n${text}`); 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}`); @@ -90,17 +229,25 @@ export default flow('nabis-uc1', { tools: { slack: true } }, async (f, } await reply(':wrench: *Repair*', `Added held → ${repaired.held}. The reviewer accepted the repaired table and all three routing checks passed.`); - const prompt = await reply(':pause_button: *Waiting for human approval*', - `<@${input.approver}>, reply in this thread with \`approve ${input.request}\` or \`decline ${input.request}\`.`); - if (prompt.channel !== input.channel || !(input.mode === '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.' }); + 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 }); } - const to = approverIdentity(input.approver); - const source = approvalAttribution(input, prompt.ts).replaceAll('.', '\\.'); - const approved = await f.human(approvalQuestion(input.request, prompt.ts), { to }).gate({ - type: 'regex_match', - pattern: `"note":"${source}Ev[A-Za-z0-9]{2,32}:\\d{10}\\.\\d{6}","answeredBy":"${to}"`, - }); 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.' }); @@ -108,7 +255,7 @@ export default flow('nabis-uc1', { tools: { slack: true } }, async (f, // 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: input.request, rules: repaired, + 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.'); From bd08c23542a68cbc19743508f0d183dd20551a59 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Fri, 4 Dec 2026 15:04:16 -0800 Subject: [PATCH 14/19] Trigger hosted Nabis UC1 from a Slack app mention --- docs/CLOUD.md | 2 +- examples/nabis-uc1/README.md | 14 ++++++++------ examples/nabis-uc1/hosted.test.mjs | 7 +++++-- examples/nabis-uc1/uc1.flow.ts | 9 +++++---- packages/sdk/src/cloud-deploy.ts | 8 ++++---- packages/sdk/tests/cloud-deploy.test.ts | 8 +++++++- 6 files changed, 30 insertions(+), 18 deletions(-) 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 index 97df6219e..6c247dcbe 100644 --- a/examples/nabis-uc1/README.md +++ b/examples/nabis-uc1/README.md @@ -86,16 +86,18 @@ demo is `khaliq`. After deployment is authorized, deploy the self-contained source: ```sh -flows deploy examples/nabis-uc1/uc1.flow.ts \ +node packages/sdk/dist/cli.js deploy examples/nabis-uc1/uc1.flow.ts \ --repo AgentWorkforce/flows \ - --on 'slack:channel=C0B9Z4CLG1J,contains=[UC1 SYNTHETIC] nabis-uc1' \ + --on 'slack:channel=C0B9Z4CLG1J,mentioned=true,contains=[UC1 SYNTHETIC] nabis-uc1' \ --approver khaliq --agents codex --name nabis-uc1 --no-connect ``` -The designated operator posts exactly `[UC1 SYNTHETIC] nabis-uc1` as a -top-level message in **#watchdog-test** (`C0B9Z4CLG1J`). UC1 checks the -normalized Cloud input and the mounted Slack message before starting any -agents or replies. Cloud posts the `f.human` question in the trigger thread. +The designated operator selects **File by Agent Relay** from Slack's mention +picker and posts `@File by Agent Relay [UC1 SYNTHETIC] nabis-uc1` as a +top-level message in **#watchdog-test** (`C0B9Z4CLG1J`). 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. Cloud posts the `f.human` question in the trigger 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. diff --git a/examples/nabis-uc1/hosted.test.mjs b/examples/nabis-uc1/hosted.test.mjs index 7150b0b7c..80bae311d 100644 --- a/examples/nabis-uc1/hosted.test.mjs +++ b/examples/nabis-uc1/hosted.test.mjs @@ -9,13 +9,13 @@ import uc1, { routes } from './uc1.flow.ts'; delete process.env.RELAYFLOWS_SLACK_MOCK; -const text = '[UC1 SYNTHETIC] nabis-uc1'; +const text = '<@UBOTDEMO> [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 }, + 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 }; @@ -93,6 +93,7 @@ test('records a decline without a simulated shipment', async t => { 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 } }); @@ -106,6 +107,8 @@ test('refuses another channel, non-exact commands, other approvers and unrelated for (const input of [ { ...trigger, issue: { ...trigger.issue, channelId: 'COTHER123' } }, { ...trigger, issue: { ...trigger.issue, body: text + ' extra' } }, + { ...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')] } }, diff --git a/examples/nabis-uc1/uc1.flow.ts b/examples/nabis-uc1/uc1.flow.ts index a3d1e9bad..4add9c466 100644 --- a/examples/nabis-uc1/uc1.flow.ts +++ b/examples/nabis-uc1/uc1.flow.ts @@ -85,7 +85,7 @@ const shellWord = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'"; const hostedChannel = 'C0B9Z4CLG1J'; const hostedApprover = 'khaliq'; const hostedSender = 'U0ADJH4P83T'; -const hostedCommand = '[UC1 SYNTHETIC] nabis-uc1'; +const hostedMention = /^<@[UW][A-Z0-9]{2,31}> \[UC1 SYNTHETIC\] nabis-uc1$/u; const hostedMessagePath = /^\/slack\/channels\/C0B9Z4CLG1J(?:__watchdog-test)?\/messages\/(\d{10})[_.](\d{6})(?:\/meta\.json|\.json)$/u; function localRun(value: Record): RunInput | undefined { @@ -102,7 +102,8 @@ 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.body !== hostedCommand || event.provider !== 'slack' || event.eventType !== 'message.created' + || issue.mentioned !== true || typeof issue.body !== 'string' || !hostedMention.test(issue.body) + || 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 => @@ -110,7 +111,7 @@ function hostedRun(value: Record) { if (paths.length !== 1) return; const path = paths[0]!; const [, seconds, fraction] = hostedMessagePath.exec(path)!; - return { path, approver: hostedApprover, channel: hostedChannel, thread: `${seconds}.${fraction}`, + return { path, text: issue.body, approver: hostedApprover, channel: hostedChannel, thread: `${seconds}.${fraction}`, request: `UC1-${seconds}${fraction}` }; } @@ -159,7 +160,7 @@ export default flow('nabis-uc1', { tools: { slack: true } }, async (f, value) => 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: hostedCommand }; + const expected = { channel: hosted.channel, ts: hosted.thread, user: hostedSender, text: hosted.text }; const check = await f.run(`node -e ${shellWord(checkHostedSlackMessage)} ${shellWord(hosted.path)} ${shellWord(JSON.stringify(expected))}`, { onNonZero: 'record' }); if (!check.ok) return f.done('step_failed', { detail: 'The mounted Slack record did not confirm the synthetic trigger and designated sender.' }); 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/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' })); }); From 96ce4a23b8dc9229a6f8ea4451db4dd5176b6bff Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Fri, 4 Dec 2026 15:47:21 -0800 Subject: [PATCH 15/19] Correct the UC1 Slack mention instructions --- examples/nabis-uc1/README.md | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/examples/nabis-uc1/README.md b/examples/nabis-uc1/README.md index 6c247dcbe..31cbb81cb 100644 --- a/examples/nabis-uc1/README.md +++ b/examples/nabis-uc1/README.md @@ -92,19 +92,18 @@ node packages/sdk/dist/cli.js deploy examples/nabis-uc1/uc1.flow.ts \ --approver khaliq --agents codex --name nabis-uc1 --no-connect ``` -The designated operator selects **File by Agent Relay** from Slack's mention -picker and posts `@File by Agent Relay [UC1 SYNTHETIC] nabis-uc1` as a -top-level message in **#watchdog-test** (`C0B9Z4CLG1J`). 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. Cloud posts the `f.human` question in the trigger thread. +In **#watchdog-test** (`C0B9Z4CLG1J`), select **File** from Slack's mention +picker, then append ` [UC1 SYNTHETIC] nabis-uc1` immediately after the +mention. Send `@File [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. Cloud posts the `f.human` question in the trigger 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. A deployment and Slack rehearsal in the -approved workspace are pending. +branches using local fixtures. ## Local recording from a real Slack mention From b1f03755cab4df71276d3422b7681649b1754e83 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Fri, 4 Dec 2026 16:03:16 -0800 Subject: [PATCH 16/19] Wait for the hosted UC1 Slack mirror on cold start --- examples/nabis-uc1/README.md | 8 ++-- examples/nabis-uc1/hosted.test.mjs | 34 ++++++++++++---- examples/nabis-uc1/uc1.flow.ts | 65 +++++++++++++++++++----------- 3 files changed, 72 insertions(+), 35 deletions(-) diff --git a/examples/nabis-uc1/README.md b/examples/nabis-uc1/README.md index 31cbb81cb..2fb0ff394 100644 --- a/examples/nabis-uc1/README.md +++ b/examples/nabis-uc1/README.md @@ -92,12 +92,14 @@ node packages/sdk/dist/cli.js deploy examples/nabis-uc1/uc1.flow.ts \ --approver khaliq --agents codex --name nabis-uc1 --no-connect ``` -In **#watchdog-test** (`C0B9Z4CLG1J`), select **File** from Slack's mention +In **#watchdog-test** (`C0B9Z4CLG1J`), select **Agent Relay** from Slack's mention picker, then append ` [UC1 SYNTHETIC] nabis-uc1` immediately after the -mention. Send `@File [UC1 SYNTHETIC] nabis-uc1` as a new top-level message. +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. Cloud posts the `f.human` question in the trigger thread. +agents or replies. On a cold start, UC1 waits up to 60 seconds for the +trigger's record to appear in the mirror. Cloud posts the `f.human` question +in the trigger 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. diff --git a/examples/nabis-uc1/hosted.test.mjs b/examples/nabis-uc1/hosted.test.mjs index 80bae311d..ffd964a32 100644 --- a/examples/nabis-uc1/hosted.test.mjs +++ b/examples/nabis-uc1/hosted.test.mjs @@ -1,15 +1,18 @@ import assert from 'node:assert/strict'; -import { spawnSync } from 'node:child_process'; +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 text = '<@UBOTDEMO> [UC1 SYNTHETIC] nabis-uc1'; +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'; @@ -31,21 +34,22 @@ const responses = { 'review-repair': { verdict: 'approve' }, }; -async function rehearse(t, { input = trigger, message = record, approve = true } = {}) { +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 }); - await writeFile(recordPath, JSON.stringify(message)); + const writeRecord = () => writeFile(recordPath, JSON.stringify(message)); + if (!mountDelay) await writeRecord(); const calls = { commands: [], replies: [], agents: [], gates: [], verdict: '' }; await getFlowDefinition(uc1).body({ async run(command) { calls.commands.push(command); - const child = spawnSync(command, { - shell: true, encoding: 'utf8', env: { PATH: process.env.PATH, RELAYFILE_MOUNT_PATH: fixture }, + const child = execCommand(command, { + encoding: 'utf8', env: { PATH: process.env.PATH, RELAYFILE_MOUNT_PATH: fixture }, }); - assert.ifError(child.error); - return { ok: child.status === 0, stdout: child.stdout }; + if (mountDelay && calls.commands.length === 1) await delay(mountDelay).then(writeRecord); + return (await child).stdout; }, async agent(name, { cli }) { assert.equal(cli, 'codex'); @@ -90,6 +94,19 @@ test('records a decline without a simulated shipment', async t => { assert.match(calls.replies.at(-1), /designated approver declined/u); }); +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' }, @@ -107,6 +124,7 @@ test('refuses another channel, non-exact commands, other approvers and unrelated 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' }, diff --git a/examples/nabis-uc1/uc1.flow.ts b/examples/nabis-uc1/uc1.flow.ts index 4add9c466..1ec235ae8 100644 --- a/examples/nabis-uc1/uc1.flow.ts +++ b/examples/nabis-uc1/uc1.flow.ts @@ -85,7 +85,7 @@ const shellWord = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'"; const hostedChannel = 'C0B9Z4CLG1J'; const hostedApprover = 'khaliq'; const hostedSender = 'U0ADJH4P83T'; -const hostedMention = /^<@[UW][A-Z0-9]{2,31}> \[UC1 SYNTHETIC\] nabis-uc1$/u; +const hostedMention = '<@U0B2596R7EZ> [UC1 SYNTHETIC] nabis-uc1'; const hostedMessagePath = /^\/slack\/channels\/C0B9Z4CLG1J(?:__watchdog-test)?\/messages\/(\d{10})[_.](\d{6})(?:\/meta\.json|\.json)$/u; function localRun(value: Record): RunInput | undefined { @@ -102,16 +102,16 @@ 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 || typeof issue.body !== 'string' || !hostedMention.test(issue.body) + || 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 path = paths[0]!; - const [, seconds, fraction] = hostedMessagePath.exec(path)!; - return { path, text: issue.body, approver: hostedApprover, channel: hostedChannel, thread: `${seconds}.${fraction}`, + 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}` }; } @@ -120,25 +120,41 @@ function hostedRun(value: Record) { // 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); - const root = process.env.RELAYFILE_MOUNT_PATH; - if (!root) process.exit(1); - try { - const file = JSON.parse(readFileSync(root + path, 'utf8')); - 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)); - process.exitCode = verified ? 0 : 1; - } catch { - process.exitCode = 1; + 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 { @@ -161,9 +177,10 @@ export default flow('nabis-uc1', { tools: { slack: true } }, async (f, value) => } if (hosted) { const expected = { channel: hosted.channel, ts: hosted.thread, user: hostedSender, text: hosted.text }; - const check = await f.run(`node -e ${shellWord(checkHostedSlackMessage)} ${shellWord(hosted.path)} ${shellWord(JSON.stringify(expected))}`, - { onNonZero: 'record' }); - if (!check.ok) return f.done('step_failed', { detail: 'The mounted Slack record did not confirm the synthetic trigger and designated sender.' }); + 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]'; From 7ffa8438425c9fabd223301e31eca105fae87937 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Fri, 4 Dec 2026 16:43:34 -0800 Subject: [PATCH 17/19] Post the hosted UC1 run link before the first agent step --- examples/nabis-uc1/README.md | 5 +++-- examples/nabis-uc1/hosted.test.mjs | 13 ++++++++++--- examples/nabis-uc1/uc1.flow.ts | 9 +++++++++ 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/examples/nabis-uc1/README.md b/examples/nabis-uc1/README.md index 2fb0ff394..3e361a1b7 100644 --- a/examples/nabis-uc1/README.md +++ b/examples/nabis-uc1/README.md @@ -98,8 +98,9 @@ mention. Send `@Agent Relay [UC1 SYNTHETIC] nabis-uc1` as a new top-level messag 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. Cloud posts the `f.human` question -in the trigger thread. +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. diff --git a/examples/nabis-uc1/hosted.test.mjs b/examples/nabis-uc1/hosted.test.mjs index ffd964a32..17a20c31b 100644 --- a/examples/nabis-uc1/hosted.test.mjs +++ b/examples/nabis-uc1/hosted.test.mjs @@ -10,6 +10,8 @@ import { getFlowDefinition } from '@relayflows/surface/runtime'; import uc1, { routes } from './uc1.flow.ts'; delete process.env.RELAYFLOWS_SLACK_MOCK; +const cloudRunId = '00000000-0000-4000-8000-000000000001'; +process.env.RELAYFLOW_V2_CLOUD_RUN_ID = cloudRunId; const execCommand = promisify(exec); const text = '<@U0B2596R7EZ> [UC1 SYNTHETIC] nabis-uc1'; @@ -41,7 +43,7 @@ async function rehearse(t, { input = trigger, message = record, approve = true, await mkdir(dirname(recordPath), { recursive: true }); const writeRecord = () => writeFile(recordPath, JSON.stringify(message)); if (!mountDelay) await writeRecord(); - const calls = { commands: [], replies: [], agents: [], gates: [], verdict: '' }; + const calls = { commands: [], replies: [], agents: [], gates: [], verdict: '', repliesWhenPlannerStarts: 0 }; await getFlowDefinition(uc1).body({ async run(command) { calls.commands.push(command); @@ -54,6 +56,7 @@ async function rehearse(t, { input = trigger, message = record, approve = true, 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]) }; }, @@ -80,9 +83,13 @@ test('uses the native approver gate between the role replies and simulated shipm assert.deepEqual(calls.gates, [{ question: 'Approve simulated shipment for UC1-1780000000000001? Reply yes or no in this thread.', recipient: { to: 'khaliq' }, - repliesWhenParked: 4, + repliesWhenParked: 5, }]); - assert.equal(calls.replies.length, 5); // Cloud delivers the approval prompt. + 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`, + )); assert.match(calls.replies.at(-1), /\*Lead summary\*[\s\S]+\*Blocked\* None\./u); assert.match(calls.commands.at(-1), /simulate-ship/u); }); diff --git a/examples/nabis-uc1/uc1.flow.ts b/examples/nabis-uc1/uc1.flow.ts index 1ec235ae8..dccc70d18 100644 --- a/examples/nabis-uc1/uc1.flow.ts +++ b/examples/nabis-uc1/uc1.flow.ts @@ -87,6 +87,7 @@ 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-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u; function localRun(value: Record): RunInput | undefined { const { mode, team, channel, thread, approver, request, triggerEvent } = value; @@ -186,6 +187,14 @@ export default flow('nabis-uc1', { tools: { slack: true } }, async (f, value) => 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 runUrl = `https://agentrelay.com/cloud/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}`); From 854c854063ddbb27d80beedbc26223ce686b5dee Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Sat, 5 Dec 2026 09:20:51 -0800 Subject: [PATCH 18/19] Address UC1 Slack listener and run link review --- examples/nabis-uc1/hosted.test.mjs | 11 +++++++---- examples/nabis-uc1/slack-inbox.mjs | 16 +++++++++------- examples/nabis-uc1/slack-listen.mjs | 8 +++++++- examples/nabis-uc1/uc1.flow.ts | 9 +++++++-- 4 files changed, 30 insertions(+), 14 deletions(-) diff --git a/examples/nabis-uc1/hosted.test.mjs b/examples/nabis-uc1/hosted.test.mjs index 17a20c31b..dd0e9a131 100644 --- a/examples/nabis-uc1/hosted.test.mjs +++ b/examples/nabis-uc1/hosted.test.mjs @@ -10,8 +10,10 @@ import { getFlowDefinition } from '@relayflows/surface/runtime'; import uc1, { routes } from './uc1.flow.ts'; delete process.env.RELAYFLOWS_SLACK_MOCK; -const cloudRunId = '00000000-0000-4000-8000-000000000001'; +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'; @@ -50,8 +52,9 @@ async function rehearse(t, { input = trigger, message = record, approve = true, const child = execCommand(command, { encoding: 'utf8', env: { PATH: process.env.PATH, RELAYFILE_MOUNT_PATH: fixture }, }); - if (mountDelay && calls.commands.length === 1) await delay(mountDelay).then(writeRecord); - return (await child).stdout; + 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'); @@ -88,7 +91,7 @@ test('uses the native approver gate between the role replies and simulated shipm 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`, + `*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); diff --git a/examples/nabis-uc1/slack-inbox.mjs b/examples/nabis-uc1/slack-inbox.mjs index dd72c49c5..f70f62702 100644 --- a/examples/nabis-uc1/slack-inbox.mjs +++ b/examples/nabis-uc1/slack-inbox.mjs @@ -1,5 +1,5 @@ import { randomUUID } from 'node:crypto'; -import { link, mkdir, open, readFile, readdir, unlink, writeFile } from 'node:fs/promises'; +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'; @@ -30,14 +30,16 @@ export async function createInbox(directory, deliver, { retryMs = 2000 } = {}) { async function persist(path, callback) { const temporary = join(directory, `.${randomUUID()}.tmp`); - 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')); + 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 unlink(temporary); + await rm(temporary, { force: true }); } const directoryHandle = await open(directory, 'r'); try { await directoryHandle.sync(); } diff --git a/examples/nabis-uc1/slack-listen.mjs b/examples/nabis-uc1/slack-listen.mjs index a2bfb3137..f896994db 100644 --- a/examples/nabis-uc1/slack-listen.mjs +++ b/examples/nabis-uc1/slack-listen.mjs @@ -34,7 +34,13 @@ async function openConnection(token, signal) { return; } if (!response.ok) throw new Error(`Slack refused apps.connections.open (HTTP ${response.status}).`); - const data = await response.json(); + 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; diff --git a/examples/nabis-uc1/uc1.flow.ts b/examples/nabis-uc1/uc1.flow.ts index dccc70d18..c510f3855 100644 --- a/examples/nabis-uc1/uc1.flow.ts +++ b/examples/nabis-uc1/uc1.flow.ts @@ -87,7 +87,7 @@ 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-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/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; @@ -192,7 +192,12 @@ export default flow('nabis-uc1', { tools: { slack: true } }, async (f, value) => if (!runId || !cloudRunIdPattern.test(runId)) { return f.done('step_failed', { detail: 'The hosted runner did not provide a Cloud run ID.' }); } - const runUrl = `https://agentrelay.com/cloud/dashboard/workflow/${runId}/runner`; + const base = process.env.FLOWS_CLOUD_URL?.trim() || 'https://agentrelay.com/cloud'; + const url = URL.parse(base); + if (!url || !['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) { + return f.done('step_failed', { detail: 'The hosted runner did not provide a valid Flows Cloud URL.' }); + } + const runUrl = `${url.href.replace(/\/+$/u, '')}/dashboard/workflow/${runId}/runner`; await reply('*UC1 started*', `<${runUrl}|Open this run in Flows Cloud>`); } const summaryRole = ':clipboard: *Lead summary*'; From 12cf8a4f0458357c08d39ace0863437a1ec3e63e Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Sat, 5 Dec 2026 09:44:12 -0800 Subject: [PATCH 19/19] Normalize the hosted UC1 dashboard link like the SDK --- examples/nabis-uc1/hosted.test.mjs | 20 ++++++++++++++++++++ examples/nabis-uc1/uc1.flow.ts | 9 ++++++--- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/examples/nabis-uc1/hosted.test.mjs b/examples/nabis-uc1/hosted.test.mjs index dd0e9a131..66147229b 100644 --- a/examples/nabis-uc1/hosted.test.mjs +++ b/examples/nabis-uc1/hosted.test.mjs @@ -104,6 +104,26 @@ test('records a decline without a simulated shipment', async t => { 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] } }; diff --git a/examples/nabis-uc1/uc1.flow.ts b/examples/nabis-uc1/uc1.flow.ts index c510f3855..119687758 100644 --- a/examples/nabis-uc1/uc1.flow.ts +++ b/examples/nabis-uc1/uc1.flow.ts @@ -194,10 +194,13 @@ export default flow('nabis-uc1', { tools: { slack: true } }, async (f, value) => } const base = process.env.FLOWS_CLOUD_URL?.trim() || 'https://agentrelay.com/cloud'; const url = URL.parse(base); - if (!url || !['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) { - return f.done('step_failed', { detail: 'The hosted runner did not provide a valid Flows Cloud URL.' }); + // 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 runUrl = `${url.href.replace(/\/+$/u, '')}/dashboard/workflow/${runId}/runner`; + 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*';