Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat(ruflo-console): mission verify module (gates, evidence, verdict)

ruv74aa2f9b3bd7
diff --git a/plugins/ruflo-console/hooks/mission-verify.ts b/plugins/ruflo-console/hooks/mission-verify.ts
new file mode 100644
index 0000000000..a5a85d225b
--- /dev/null
+++ b/plugins/ruflo-console/hooks/mission-verify.ts
@@ -0,0 +1,165 @@
+/**
+ * Verify (ADR-443 §2.2): a task is done with evidence. Gates are the person's own commands, kept as a fixed argv (no shell, no quoting);
+ * running one asks first, and its exit code and a short output summary are recorded as an `evidence.gate` event. The verdict is read
+ * back from those events only. Pure: data in, data out.
+ */
+import type { ActionSpec } from './actions'
+import { plain } from './data/parse'
+import type { MissionRecord } from './mission-types'
+
+export type Gate = { id: string; label: string; argv: readonly string[] }
+export type GateResult = { exitCode: number | null; stdout: string; stderr: string }
+export type GateEvent = { type: 'evidence.gate'; taskId?: string; status: 'passed' | 'failed' | 'unknown'; note: string; evidenceRef: string }
+export type Verdict = { state: 'verified' | 'failed' | 'unverified' | 'no-gates'; passed: number; failed: number; detail: string }
+
+export const MAX_GATES = 4
+export const MAX_GATE_CHARS = 200
+
+const SHELL_SYNTAX = /[;|&<>`]|\$\(/
+const CONTROL = /[\u0000-\u001f\u007f-\u009f]/
+/** A setting value is one line, so a literal backslash-n also separates lines. */
+const LINE_BREAK = /\r?\n|\\n/
+
+/** A short stable id from the argv (FNV-1a, base 36): the same command is the same gate across restarts. */
+function gateId(argv: readonly string[]): string {
+ let hash = 0x811c9dc5
+
+ for (const char of argv.join('\u0000')) {
+ hash = Math.imul(hash ^ char.codePointAt(0)!, 0x01000193) >>> 0
+ }
+
+ return `g${hash.toString(36)}`
+}
+
+/** Why a line cannot be a gate, or null when it can. */
+function refusal(line: string): string | null {
+ if (line.length > MAX_GATE_CHARS) return `longer than ${MAX_GATE_CHARS} characters`
+ if (CONTROL.test(line)) return 'contains a control character'
+ if (SHELL_SYNTAX.test(line)) return 'contains shell syntax (; | & > < ` $( ): a gate is a command and its words, run without a shell'
+ if (line.includes(' ')) return 'has two spaces in a row: words are split on single spaces'
+ if (line.startsWith('-')) return 'starts with “-”: the first word must be the program'
+
+ return null
+}
+
+/** The setting text as gates: up to 4 lines, one command each, split on single spaces. Refused lines are reported with why, never run. */
+export function parseGates(text: unknown): { gates: Gate[]; rejected: { line: string; why: string }[] } {
+ const gates: Gate[] = []
+ const rejected: { line: string; why: string }[] = []
+
+ if (typeof text !== 'string') return { gates, rejected }
+
+ for (const raw of text.split(LINE_BREAK)) {
+ const line = raw.replace(/^ +| +$/g, '')
+
+ if (line === '') continue
+
+ const shown = plain(line, 80)
+ const why = refusal(line)
+
+ if (why !== null) {
+ rejected.push({ line: shown, why })
+ continue
+ }
+
+ const argv = line.split(' ')
+ const id = gateId(argv)
+
+ if (gates.some(gate => gate.id === id)) rejected.push({ line: shown, why: 'the same command is already a gate' })
+ else if (gates.length >= MAX_GATES) rejected.push({ line: shown, why: `only the first ${MAX_GATES} gates are kept` })
+ else gates.push({ id, label: plain(line, 80), argv })
+ }
+
+ return { gates, rejected }
+}
+
+/**
+ * The confirm-gated run of one gate. `baseSpec` carries the runner plumbing (`run`, `scope`, `timeoutMs`); it can never change the
+ * argv, the label or the read-only flag: a gate is the person's own command and always asks first.
+ */
+export function gateSpec(gate: Gate, baseSpec: Partial<ActionSpec> = {}): ActionSpec {
+ return {
+ scope: 'controls',
+ note: 'Runs your own command in this project’s directory, without a shell. What it does (files, network, time) is up to the command; its exit code and a short output summary are recorded as evidence on the mission.',
+ ...baseSpec,
+ label: `run gate: ${gate.label}`,
+ args: [],
+ argv: [...gate.argv],
+ shows: gate.argv.join(' '),
+ expect: 'its exit code and output summary are recorded as evidence on the task',
+ isReadOnly: false,
+ }
+}
+
+const linesOf = (text: string): string[] => text.split(/\r?\n/).filter(line => line.trim() !== '')
+const refOf = (value: string): string => value.replace(/[^A-Za-z0-9_-]/g, '') || 'gate'
+
+/** What a finished gate run is recorded as: pass on exit 0, fail on any other exit, unknown when there was no exit code. */
+export function evidenceEvent(gate: Gate, result: GateResult, taskId?: string): GateEvent {
+ const code = typeof result.exitCode === 'number' && Number.isInteger(result.exitCode) ? result.exitCode : null
+ const lines = [...linesOf(String(result.stdout ?? '')), ...linesOf(String(result.stderr ?? ''))]
+ const first = plain(linesOf(String(result.stdout ?? ''))[0] ?? linesOf(String(result.stderr ?? ''))[0] ?? '', 120)
+ const size = lines.length === 0 ? 'no output' : `${lines.length} ${lines.length === 1 ? 'line' : 'lines'} of output`
+ const head = code === null ? 'no exit code (it did not finish)' : `exit ${code}`
+
+ return {
+ type: 'evidence.gate',
+ ...(taskId !== undefined && { taskId }),
+ status: code === null ? 'unknown' : code === 0 ? 'passed' : 'failed',
+ note: `${head}, ${size}${first === '' ? '' : `: ${first}`}`,
+ evidenceRef: `gate:${refOf(gate.id)}:${code === null ? 'none' : code}`,
+ }
+}
+
+const GATE_OF_REF = /^gate:([^:]+):/
+
+/**
+ * Read from `evidence.gate` events for the task, since its latest `task.dispatched` (a new start wipes older evidence). Order rule:
+ * each gate counts by its NEWEST result (highest seq), so a pass newer than that gate's failures clears it, and a failure newer than
+ * its pass fails it again. Verified = at least one gate and every gate's newest result is a pass. Any failed gate = failed. Anything
+ * else (unknown exit, or a configured gate that has not run) = unverified. `gates`, when given, is the configured list: with none the
+ * answer is 'no-gates', and only evidence from those gates counts. Without it, no gate evidence at all reads 'no-gates'.
+ */
+export function verdictOf(mission: MissionRecord, taskId: string, gates?: readonly Gate[]): Verdict {
+ if (gates !== undefined && gates.length === 0) return { state: 'no-gates', passed: 0, failed: 0, detail: 'no gates are set: nothing was checked' }
+
+ const mine = mission.events.filter(event => event.taskId === taskId)
+ const start = mine.reduce((latest, event) => (event.type === 'task.dispatched' && event.seq > latest ? event.seq : latest), -1)
+ const newest = new Map<string, { seq: number; status: string }>()
+
+ for (const event of mine) {
+ if (event.type !== 'evidence.gate' || event.seq <= start) continue
+
+ const key = GATE_OF_REF.exec(event.evidenceRef ?? '')?.[1] ?? '?'
+ const seen = newest.get(key)
+
+ if (seen === undefined || event.seq >= seen.seq) newest.set(key, { seq: event.seq, status: event.status ?? 'unknown' })
+ }
+
+ const counted = gates === undefined ? [...newest.entries()] : gates.map((gate): [string, { seq: number; status: string } | undefined] => [gate.id, newest.get(gate.id)])
+
+ if (counted.length === 0) return { state: 'no-gates', passed: 0, failed: 0, detail: 'no gate has run for this task' }
+
+ const passed = counted.filter(([, seen]) => seen?.status === 'passed').length
+ const failed = counted.filter(([, seen]) => seen?.status === 'failed').length
+ const open = counted.length - passed - failed
+
+ if (failed > 0) return { state: 'failed', passed, failed, detail: `${failed} of ${counted.length} gates failed on their latest run` }
+ if (open === 0) return { state: 'verified', passed, failed, detail: `${passed} of ${counted.length} gates passed on their latest run` }
+
+ return { state: 'unverified', passed, failed, detail: `${passed} of ${counted.length} gates passed; ${open} ${open === 1 ? 'has' : 'have'} not run or gave no exit code` }
+}
+
+/** The Settings row for the gates: free text (up to 4 lines), shaped like LOOP_ROWS; its value lives beside the loop preferences as `loopGates`. */
+export const GATES_ROW = {
+ id: 'loop-gates',
+ kind: 'text',
+ title: 'Mission gates',
+ description: 'your own check commands, up to 4 lines (one per line, or separated by \\n), each a program and its words, such as “npm test”; run without a shell, so no ; | & > < ` $( and no leading “-”. Each run asks first. None set: a task cannot be verified',
+ extra: 'loop gates verify test lint build check command evidence',
+ options: [] as readonly string[],
+ maxLength: MAX_GATES * (MAX_GATE_CHARS + 1),
+ current: (p: { loopGates?: string }): string => p.loopGates ?? '',
+ isChanged: (p: { loopGates?: string }): boolean => (p.loopGates ?? '') !== '',
+ patch: (value: string): { loopGates: string } => ({ loopGates: value.replace(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/g, ' ').slice(0, MAX_GATES * (MAX_GATE_CHARS + 1)).trim() }),
+} as const
diff --git a/plugins/ruflo-console/tests/mission-verify.spec.ts b/plugins/ruflo-console/tests/mission-verify.spec.ts
new file mode 100644
index 0000000000..2223132f35
--- /dev/null
+++ b/plugins/ruflo-console/tests/mission-verify.spec.ts
@@ -0,0 +1,227 @@
+import { describe, expect, it } from 'vitest'
+
+import { evidenceEvent, GATES_ROW, gateSpec, parseGates, verdictOf, type Gate } from '../hooks/mission-verify'
+import type { LedgerEvent, MissionRecord } from '../hooks/mission-types'
+
+const gate = (line: string): Gate => parseGates(line).gates[0]!
+const unit = gate('npm test')
+const lint = gate('npm run lint')
+
+const missionOf = (events: LedgerEvent[]): MissionRecord => ({ id: 'm1', objective: 'o', profile: 'feature', rigor: 'standard', tasks: [], acceptance: [], events, paused: false, cancelled: false, auto: false, createdAtMs: 0 }) as MissionRecord
+const ev = (seq: number, type: string, extra: Partial<LedgerEvent> = {}): LedgerEvent => ({ seq, atMs: seq, type, taskId: 't1', ...extra })
+const gateEv = (seq: number, g: Gate, status: 'passed' | 'failed' | 'unknown', taskId = 't1'): LedgerEvent => ev(seq, 'evidence.gate', { status, taskId, evidenceRef: `gate:${g.id}:${status === 'passed' ? 0 : 1}` })
+
+describe('parseGates', () => {
+ it('splits a line on single spaces into a fixed argv', () => {
+ const { gates, rejected } = parseGates('npm run lint')
+
+ expect(rejected).toEqual([])
+ expect(gates).toHaveLength(1)
+ expect(gates[0]!.argv).toEqual(['npm', 'run', 'lint'])
+ expect(gates[0]!.label).toBe('npm run lint')
+ expect(gates[0]!.id).toMatch(/^g[0-9a-z]+$/)
+ expect(parseGates('npm run lint').gates[0]!.id).toBe(gates[0]!.id)
+ expect(parseGates('npm test').gates[0]!.id).not.toBe(gates[0]!.id)
+ })
+
+ it.each([
+ ['semicolon', 'npm test; rm x'],
+ ['pipe', 'npm test | tee'],
+ ['ampersand', 'npm test &'],
+ ['redirect out', 'npm test > out'],
+ ['redirect in', 'npm test < in'],
+ ['backtick', 'echo `id`'],
+ ['command substitution', 'echo $(id)'],
+ ['control character', 'npm\ttest'],
+ ['leading dash', '-rf /'],
+ ['double space', 'npm test'],
+ ])('rejects %s and says why', (_name, line) => {
+ const { gates, rejected } = parseGates(line)
+
+ expect(gates).toEqual([])
+ expect(rejected).toHaveLength(1)
+ expect(rejected[0]!.why.length).toBeGreaterThan(5)
+ })
+
+ it('allows a dash after the first word', () => {
+ expect(parseGates('cargo test -p x --lib').gates[0]!.argv).toEqual(['cargo', 'test', '-p', 'x', '--lib'])
+ })
+
+ it('splits lines on newlines and on a literal backslash-n, skipping empty lines', () => {
+ expect(parseGates('a\n\n \nb\r\nc').gates.map(g => g.label)).toEqual(['a', 'b', 'c'])
+ expect(parseGates('a\\nb').gates.map(g => g.label)).toEqual(['a', 'b'])
+ })
+
+ it('keeps the first 4 gates and reports the rest', () => {
+ const { gates, rejected } = parseGates('a\nb\nc\nd\ne\nf')
+
+ expect(gates.map(g => g.label)).toEqual(['a', 'b', 'c', 'd'])
+ expect(rejected.map(r => r.line)).toEqual(['e', 'f'])
+ expect(rejected[0]!.why).toMatch(/first 4/)
+ })
+
+ it('refuses a line over 200 characters and accepts exactly 200', () => {
+ expect(parseGates('x'.repeat(201)).rejected[0]!.why).toMatch(/200/)
+ expect(parseGates('x'.repeat(200)).gates).toHaveLength(1)
+ })
+
+ it('reports a duplicate command once and gives nothing for non-text', () => {
+ expect(parseGates('npm test\nnpm test')).toMatchObject({ gates: [{ label: 'npm test' }], rejected: [{ why: expect.stringMatching(/already/) }] })
+ expect(parseGates(undefined)).toEqual({ gates: [], rejected: [] })
+ expect(parseGates(42)).toEqual({ gates: [], rejected: [] })
+ expect(parseGates('')).toEqual({ gates: [], rejected: [] })
+ })
+
+ it('does not let a rejected line use up a gate slot', () => {
+ expect(parseGates('a;b\nb\nc\nd\ne').gates).toHaveLength(4)
+ })
+})
+
+describe('gateSpec', () => {
+ it('asks first, shows the exact argv, and says what is recorded', () => {
+ const spec = gateSpec(unit)
+
+ expect(spec.label).toBe('run gate: npm test')
+ expect(spec.argv).toEqual(['npm', 'test'])
+ expect(spec.shows).toBe('npm test')
+ expect(spec.isReadOnly).toBe(false)
+ expect(spec.expect).toMatch(/exit code/)
+ expect(spec.expect).toMatch(/output summary/)
+ expect(spec.expect).toMatch(/evidence/)
+ })
+
+ it('takes plumbing from baseSpec but never the argv, label or read-only flag', () => {
+ const run = async () => {}
+ const spec = gateSpec(unit, { run, scope: 'goal', timeoutMs: 5, isReadOnly: true, argv: ['rm', '-rf', '/'], label: 'harmless', shows: 'nothing' })
+
+ expect(spec.run).toBe(run)
+ expect(spec.scope).toBe('goal')
+ expect(spec.timeoutMs).toBe(5)
+ expect(spec.isReadOnly).toBe(false)
+ expect(spec.argv).toEqual(['npm', 'test'])
+ expect(spec.label).toBe('run gate: npm test')
+ expect(spec.shows).toBe('npm test')
+ })
+
+ it('does not share the gate’s argv array', () => {
+ const spec = gateSpec(unit)
+
+ expect(spec.argv).not.toBe(unit.argv)
+ })
+})
+
+describe('evidenceEvent', () => {
+ it('summarises a pass: exit code, line count and the first line', () => {
+ const out = Array.from({ length: 12 }, (_v, i) => `line ${i}`).join('\n')
+ const event = evidenceEvent(unit, { exitCode: 0, stdout: out, stderr: '' }, 't1')
+
+ expect(event).toEqual({ type: 'evidence.gate', taskId: 't1', status: 'passed', note: 'exit 0, 12 lines of output: line 0', evidenceRef: `gate:${unit.id}:0` })
+ })
+
+ it('a non-zero exit is failed; null is unknown', () => {
+ expect(evidenceEvent(unit, { exitCode: 2, stdout: '', stderr: 'boom' }).status).toBe('failed')
+ expect(evidenceEvent(unit, { exitCode: 2, stdout: '', stderr: 'boom' }).note).toBe('exit 2, 1 line of output: boom')
+
+ const unknown = evidenceEvent(unit, { exitCode: null, stdout: '', stderr: '' })
+
+ expect(unknown.status).toBe('unknown')
+ expect(unknown.evidenceRef).toBe(`gate:${unit.id}:none`)
+ expect(unknown.note).toMatch(/no exit code/)
+ expect(unknown).not.toHaveProperty('taskId')
+ })
+
+ it('caps the first line at 120 characters and strips control characters', () => {
+ const event = evidenceEvent(unit, { exitCode: 1, stdout: `\u001b[31mred\u0007 ${'y'.repeat(300)}`, stderr: '' })
+ const shown = event.note.split(': ')[1]!
+
+ expect(shown.length).toBeLessThanOrEqual(120)
+ expect(event.note).not.toMatch(/[\u0000-\u001f]/)
+ expect(event.note).not.toContain('[31m')
+ })
+
+ it('says no output when there is none, and falls back to stderr for the first line', () => {
+ expect(evidenceEvent(unit, { exitCode: 0, stdout: '', stderr: '' }).note).toBe('exit 0, no output')
+ expect(evidenceEvent(unit, { exitCode: 1, stdout: '\n\n', stderr: 'e1\ne2' }).note).toBe('exit 1, 2 lines of output: e1')
+ })
+})
+
+describe('verdictOf', () => {
+ it('says no-gates when none are configured, even with old evidence', () => {
+ const mission = missionOf([gateEv(1, unit, 'passed')])
+
+ expect(verdictOf(mission, 't1', [])).toMatchObject({ state: 'no-gates', passed: 0, failed: 0 })
+ expect(verdictOf(missionOf([]), 't1')).toMatchObject({ state: 'no-gates' })
+ })
+
+ it('verifies when every gate’s latest result is a pass', () => {
+ const mission = missionOf([gateEv(1, unit, 'passed'), gateEv(2, lint, 'passed')])
+
+ expect(verdictOf(mission, 't1')).toMatchObject({ state: 'verified', passed: 2, failed: 0 })
+ })
+
+ it('a later pass after a fail does not count while the fail is newer than the pass, and clears it once the pass is newer', () => {
+ expect(verdictOf(missionOf([gateEv(1, unit, 'passed'), gateEv(2, unit, 'failed')]), 't1')).toMatchObject({ state: 'failed', failed: 1 })
+ expect(verdictOf(missionOf([gateEv(1, unit, 'failed'), gateEv(2, unit, 'passed')]), 't1')).toMatchObject({ state: 'verified', passed: 1, failed: 0 })
+ })
+
+ it('a pass on one gate does not hide a fail on another', () => {
+ const mission = missionOf([gateEv(1, unit, 'failed'), gateEv(2, lint, 'passed')])
+
+ expect(verdictOf(mission, 't1')).toMatchObject({ state: 'failed', passed: 1, failed: 1 })
+ })
+
+ it('orders by seq, not by array position', () => {
+ const mission = missionOf([gateEv(5, unit, 'passed'), gateEv(2, unit, 'failed')])
+
+ expect(verdictOf(mission, 't1').state).toBe('verified')
+ })
+
+ it('a new start wipes the earlier run’s evidence', () => {
+ const mission = missionOf([gateEv(1, unit, 'failed'), ev(2, 'task.dispatched'), gateEv(3, unit, 'passed')])
+ const restarted = missionOf([gateEv(1, unit, 'passed'), ev(2, 'task.dispatched')])
+
+ expect(verdictOf(mission, 't1').state).toBe('verified')
+ expect(verdictOf(restarted, 't1', [unit])).toMatchObject({ state: 'unverified', passed: 0 })
+ })
+
+ it('ignores other tasks and other event types', () => {
+ const mission = missionOf([gateEv(1, unit, 'failed', 't2'), ev(2, 'task.completed', { status: 'failed' }), gateEv(3, unit, 'passed')])
+
+ expect(verdictOf(mission, 't1').state).toBe('verified')
+ expect(verdictOf(mission, 't2').state).toBe('failed')
+ })
+
+ it('an unknown exit is unverified, never a pass', () => {
+ expect(verdictOf(missionOf([gateEv(1, unit, 'unknown')]), 't1')).toMatchObject({ state: 'unverified', passed: 0, failed: 0 })
+ })
+
+ it('with the configured gates, an unrun gate keeps the task unverified and a removed gate’s evidence does not count', () => {
+ const mission = missionOf([gateEv(1, unit, 'passed')])
+
+ expect(verdictOf(mission, 't1', [unit, lint])).toMatchObject({ state: 'unverified', passed: 1 })
+ expect(verdictOf(mission, 't1', [lint]).state).toBe('unverified')
+ expect(verdictOf(mission, 't1', [unit]).state).toBe('verified')
+ })
+
+ it('round-trips an evidenceEvent into a verdict', () => {
+ const recorded = evidenceEvent(unit, { exitCode: 0, stdout: 'ok', stderr: '' }, 't1')
+ const mission = missionOf([{ seq: 1, atMs: 1, ...recorded }])
+
+ expect(verdictOf(mission, 't1', [unit]).state).toBe('verified')
+ })
+})
+
+describe('GATES_ROW', () => {
+ it('is a text row with the loop-gates id', () => {
+ expect(GATES_ROW.id).toBe('loop-gates')
+ expect(GATES_ROW.kind).toBe('text')
+ expect(GATES_ROW.current({})).toBe('')
+ expect(GATES_ROW.isChanged({})).toBe(false)
+ expect(GATES_ROW.isChanged({ loopGates: 'npm test' })).toBe(true)
+ })
+
+ it('patches the text, keeping newlines, dropping other control characters and capping length', () => {
+ expect(GATES_ROW.patch('npm test\nnpm run lint\u0007')).toEqual({ loopGates: 'npm test\nnpm run lint ' .trim() })
+ expect(GATES_ROW.patch('x'.repeat(5000)).loopGates.length).toBeLessThanOrEqual(GATES_ROW.maxLength)
+ })
+})