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 context section, stable key, settings row and turn note (ADR-443 cap 1)

ruvc0c719993601
diff --git a/plugins/ruflo-console/hooks/mission-context.ts b/plugins/ruflo-console/hooks/mission-context.ts
new file mode 100644
index 0000000000..9fe6a78154
--- /dev/null
+++ b/plugins/ruflo-console/hooks/mission-context.ts
@@ -0,0 +1,91 @@
+/**
+ * Mission context (ADR-443): the one short section Claude's system prompt carries while a mission is active, so Claude knows
+ * the mission between hand-offs. Pure text in, text out. The section only holds the mission's own fields, each capped, with
+ * control characters stripped. Its key changes only when something Claude must act on changes (mission, active task, that
+ * task's status, paused, cancelled, loop on or off): a changed system prompt makes Claude re-read the conversation at
+ * cache-write price, so event counts, timestamps and spend never reach the key.
+ */
+import { plain } from './data/parse'
+import type { Derived, LedgerTask, MissionRecord } from './mission-types'
+
+export const CONTEXT_SECTION_ID = 'ruflo-console:mission'
+export const CONTEXT_MAX = 1200
+/** The settings key the row stores under, beside the other AI preferences. */
+export const CONTEXT_PREF_KEY = 'missionContext'
+
+const EVIDENCE_RULE = 'A task is done only with evidence: record it with task_complete and put what you ran and what it printed in the result.'
+const STOP_RULE = 'Stop when every task is done or the person says stop; if blocked, mark the task failed with the reason instead of guessing.'
+const HALTED = 'Do not start new work.'
+const MAX_CHECKS = 3
+
+type LoopInfo = { interval: string; status: string } | null
+
+/** Where a task stands, from the ruflo task store (derive() in mission-control.ts needs the store, so the caller passes the result). */
+export type TaskStatus = Derived
+
+const clip = (value: unknown, max: number): string => plain(value, max)
+
+function halted(mission: MissionRecord): string | null {
+ return mission.cancelled ? 'cancelled' : mission.paused ? 'paused' : null
+}
+
+/** The section's text: deterministic, at most CONTEXT_MAX characters. `status` is the active task's derived status. */
+export function missionContextText(mission: MissionRecord, task: LedgerTask | null, loop: LoopInfo, status: TaskStatus = 'ready'): string {
+ const lines: string[] = [`Mission ${clip(mission.id, 40)}: ${clip(mission.objective, 200)}`]
+ const stop = halted(mission)
+
+ if (task !== null) {
+ lines.push(`Active task ${clip(task.id, 20)} (${status}): ${clip(task.title, 80)}. Done when: ${clip(task.requirement, 120)}`)
+
+ const checks = mission.acceptance.slice(0, MAX_CHECKS).map(item => `- ${clip(item.check, 80)}`)
+
+ if (checks.length > 0) lines.push(`Acceptance checks:\n${checks.join('\n')}`)
+ }
+
+ if (loop !== null) lines.push(`Loop: ${clip(loop.interval, 12)}, ${clip(loop.status, 12)}.`)
+
+ lines.push(EVIDENCE_RULE, STOP_RULE)
+ if (stop !== null) lines.push(`The mission is ${stop}. ${HALTED}`)
+
+ const text = lines.join('\n')
+
+ return text.length <= CONTEXT_MAX ? text : `${text.slice(0, CONTEXT_MAX - 1)}…`
+}
+
+/** What the section depends on, nothing else: the same key means Claude's prompt is byte-identical, so its cache holds. */
+export function missionContextKey(mission: MissionRecord, task: LedgerTask | null, loop: LoopInfo, status: TaskStatus = 'ready'): string {
+ return [mission.id, task === null ? '-' : `${task.id}:${status}`, mission.paused ? 'paused' : 'live', mission.cancelled ? 'cancelled' : 'open', loop === null ? 'noloop' : 'loop'].join('|')
+}
+
+/** Only the exact value 'off' (or false) turns the section off; anything else, including no value at all, leaves it on. */
+export const contextEnabled = (value: unknown): boolean => value !== 'off' && value !== false
+
+type ContextPrefs = { [CONTEXT_PREF_KEY]?: boolean }
+
+/** The Settings row, shaped like the entries of LOOP_ROWS (settings.ts); the integrator appends it to that list. */
+export const CONTEXT_ROW: { id: string; title: string; description: string; extra: string; options: readonly string[]; current: (p: ContextPrefs) => string; isChanged: (p: ContextPrefs) => boolean; patch: (value: string) => ContextPrefs } = {
+ id: 'ctx-mission',
+ title: 'Mission context in Claude’s prompt',
+ description: 'while a mission is active, Claude’s prompt carries its objective, the active task, the evidence rule and the stop rule; it changes only when the task or mission state does (default on)',
+ extra: 'mission context prompt claude system section cache',
+ options: ['on', 'off'],
+ current: p => (contextEnabled(p[CONTEXT_PREF_KEY]) ? 'on' : 'off'),
+ isChanged: p => !contextEnabled(p[CONTEXT_PREF_KEY]),
+ patch: value => ({ [CONTEXT_PREF_KEY]: value !== 'off' }),
+}
+
+export type TurnReason = 'answer' | 'aborted' | 'refusal' | 'error'
+
+const TURN_NOTE: Record<TurnReason, string> = {
+ answer: 'Claude finished a turn on this task; completion is recorded by task_complete, not by this note.',
+ aborted: 'A turn on this task was aborted before it finished.',
+ refusal: 'Claude declined a turn on this task.',
+ error: 'A turn on this task ended in an error.',
+}
+
+/** The ledger event a finished turn leaves: null with no active task; it never says the task is finished. */
+export function turnNote(reason: TurnReason, task: LedgerTask | null): { type: string; taskId?: string; note: string } | null {
+ if (task === null) return null
+
+ return { type: 'turn', taskId: clip(task.id, 20), note: TURN_NOTE[reason] ?? TURN_NOTE.error }
+}
diff --git a/plugins/ruflo-console/tests/mission-context.spec.ts b/plugins/ruflo-console/tests/mission-context.spec.ts
new file mode 100644
index 0000000000..6941e58780
--- /dev/null
+++ b/plugins/ruflo-console/tests/mission-context.spec.ts
@@ -0,0 +1,149 @@
+import { describe, expect, it } from 'vitest'
+
+import { CONTEXT_MAX, CONTEXT_PREF_KEY, CONTEXT_ROW, CONTEXT_SECTION_ID, contextEnabled, missionContextKey, missionContextText, turnNote } from '../hooks/mission-context'
+import type { LedgerTask, MissionRecord } from '../hooks/mission-types'
+
+const task: LedgerTask = { id: 't3', title: 'Write the parser', phase: 'refinement', agent: 'coder', requirement: 'parser passes its tests', dependsOn: [] }
+const mission = (patch: Partial<MissionRecord> = {}): MissionRecord => ({
+ id: 'msn_abc',
+ objective: 'Ship the parser',
+ profile: 'feature',
+ rigor: 'standard',
+ tasks: [task],
+ acceptance: [{ id: 'a1', check: 'tests pass' }, { id: 'a2', check: 'no lint errors' }],
+ events: [],
+ paused: false,
+ cancelled: false,
+ auto: false,
+ createdAtMs: 1,
+ ...patch,
+})
+const loop = { interval: '5m', status: 'armed' }
+
+describe('missionContextText', () => {
+ it('names the section id and carries objective, task, checks and both rules', () => {
+ const text = missionContextText(mission(), task, loop, 'running')
+
+ expect(CONTEXT_SECTION_ID).toBe('ruflo-console:mission')
+ expect(text).toContain('Ship the parser')
+ expect(text).toContain('Active task t3 (running): Write the parser')
+ expect(text).toContain('parser passes its tests')
+ expect(text).toContain('- tests pass')
+ expect(text).toContain('a task is done only with evidence: record it with task_complete and put what you ran and what it printed in the result'.replace(/^a/, 'A'))
+ expect(text).toContain('Stop when every task is done')
+ expect(text).toContain('Loop: 5m, armed.')
+ expect(text).not.toContain('Do not start new work')
+ })
+
+ it('is deterministic', () => {
+ expect(missionContextText(mission(), task, loop)).toBe(missionContextText(mission(), task, loop))
+ })
+
+ it('says not to start new work when paused or cancelled', () => {
+ expect(missionContextText(mission({ paused: true }), task, null)).toContain('The mission is paused. Do not start new work.')
+ expect(missionContextText(mission({ cancelled: true }), task, null)).toContain('The mission is cancelled. Do not start new work.')
+ })
+
+ it('omits the task and loop lines when there is none', () => {
+ const text = missionContextText(mission(), null, null)
+
+ expect(text).not.toContain('Active task')
+ expect(text).not.toContain('Loop:')
+ expect(text).toContain('Ship the parser')
+ })
+
+ it('strips control characters and ANSI from every field', () => {
+ const dirty = mission({ objective: 'a\u001b[31mred\u001b[0m\u0007 goal\nline', acceptance: [{ id: 'x', check: 'ok\u0000check' }] })
+ const text = missionContextText(dirty, { ...task, title: 'ti\u009ftle' }, { interval: '5m\u0001', status: 'armed' })
+
+ expect(text).not.toMatch(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/)
+ expect(text).toContain('ared goal line')
+ })
+
+ it('stays within the cap and keeps both rules at maximum field sizes', () => {
+ const big = 'x'.repeat(5000)
+ const huge = mission({ id: big, objective: big, paused: true, acceptance: Array.from({ length: 20 }, (_, index) => ({ id: `a${index}`, check: big })) })
+ const text = missionContextText(huge, { ...task, id: big, title: big, requirement: big }, { interval: big, status: big })
+
+ expect(text.length).toBeLessThanOrEqual(CONTEXT_MAX)
+ expect(text).toContain('task_complete')
+ expect(text).toContain('Stop when every task is done')
+ expect(text).toContain('Do not start new work')
+ })
+})
+
+describe('missionContextKey', () => {
+ const base = missionContextKey(mission(), task, loop, 'ready')
+
+ it('does not change with events, timestamps, spend-like fields, objective text or acceptance', () => {
+ const noisy = mission({ events: [{ seq: 1, atMs: 5, type: 'x' }, { seq: 2, atMs: 9, type: 'y', note: 'cost $4' }], createdAtMs: 999, auto: true, objective: 'reworded', acceptance: [] })
+
+ expect(missionContextKey(noisy, task, loop, 'ready')).toBe(base)
+ expect(missionContextKey(noisy, task, { interval: '30m', status: 'overdue' }, 'ready')).toBe(base)
+ })
+
+ it('changes with mission id, active task id, its status, paused, cancelled and loop on/off', () => {
+ const keys = [
+ missionContextKey(mission({ id: 'msn_other' }), task, loop, 'ready'),
+ missionContextKey(mission(), { ...task, id: 't4' }, loop, 'ready'),
+ missionContextKey(mission(), task, loop, 'running'),
+ missionContextKey(mission({ paused: true }), task, loop, 'ready'),
+ missionContextKey(mission({ cancelled: true }), task, loop, 'ready'),
+ missionContextKey(mission(), task, null, 'ready'),
+ missionContextKey(mission(), null, loop),
+ ]
+
+ expect(new Set([base, ...keys]).size).toBe(keys.length + 1)
+ })
+})
+
+describe('settings row', () => {
+ it('is on by default and only the exact off value turns it off', () => {
+ expect(contextEnabled(undefined)).toBe(true)
+ expect(contextEnabled('on')).toBe(true)
+ expect(contextEnabled('OFF')).toBe(true)
+ expect(contextEnabled(0)).toBe(true)
+ expect(contextEnabled(null)).toBe(true)
+ expect(contextEnabled('off')).toBe(false)
+ expect(contextEnabled(false)).toBe(false)
+ })
+
+ it('has the LOOP_ROWS shape and round-trips through patch/current', () => {
+ expect(CONTEXT_ROW.id).toBe('ctx-mission')
+ expect(CONTEXT_ROW.title).toBe('Mission context in Claude’s prompt')
+ expect(CONTEXT_ROW.options).toEqual(['on', 'off'])
+ expect(CONTEXT_ROW.current({})).toBe('on')
+ expect(CONTEXT_ROW.isChanged({})).toBe(false)
+
+ const off = CONTEXT_ROW.patch('off')
+
+ expect(off).toEqual({ [CONTEXT_PREF_KEY]: false })
+ expect(CONTEXT_ROW.current(off)).toBe('off')
+ expect(CONTEXT_ROW.isChanged(off)).toBe(true)
+ expect(CONTEXT_ROW.patch('on')).toEqual({ [CONTEXT_PREF_KEY]: true })
+ expect(CONTEXT_ROW.patch('garbage')).toEqual({ [CONTEXT_PREF_KEY]: true })
+ })
+})
+
+describe('turnNote', () => {
+ it('is null with no active task', () => {
+ expect(turnNote('answer', null)).toBeNull()
+ })
+
+ it('names the task and never claims it finished, for every reason', () => {
+ for (const reason of ['answer', 'aborted', 'refusal', 'error'] as const) {
+ const note = turnNote(reason, task)
+
+ expect(note?.taskId).toBe('t3')
+ expect(note?.type).toBe('turn')
+ expect(note?.note.length).toBeGreaterThan(10)
+ expect(note?.note).not.toMatch(/\b(completed|is done|was finished|succeeded)\b/i)
+ }
+ })
+
+ it('tells the reasons apart', () => {
+ const notes = (['answer', 'aborted', 'refusal', 'error'] as const).map(reason => turnNote(reason, task)?.note)
+
+ expect(new Set(notes).size).toBe(4)
+ })
+})