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(console,adr): ADR management registry, page and mission/loop/swarm integration (ADR-480)

ruvaed428c43e48
diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.json
index 6b3c823d13..15bd5a1cdd 100644
--- a/plugins/ruflo-console/.claude-plugin/plugin.json
+++ b/plugins/ruflo-console/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-console",
"description": "ruflo's cockpit inside Claude Code and the one /ruflo command for every ruflo mod (function hooks, early access). Views: overview with health alerts, swarm topology graph, claims flow with TTL rings, federation map, plugin health matrix, learning curve and pipeline, MetaHarness radar and audit trend, memory, cost gauge, agent timeline, approvals queue, event stream, a main menu, an x.ruv.io federation board, an AI terminal (codex, claude or both in remembered sessions, streamed), Skills (npx skills), a Hive-Mind view, a MetaHarness lab, agent drill-down; a command palette for confirm-gated actions through the ruflo CLI; a band above the prompt. Reads ruflo's files and the CLI's local JSON; anything not measured reads n/a. The one network call it makes by itself is a daily read of the published plugin.json at github.com/ruvnet/ruflo to offer an update (Settings → Updates: ask, auto, or off); it installs only through Claude Code's own claude plugin update, and never a new major version without asking.",
- "version": "0.38.0",
+ "version": "0.39.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
diff --git a/plugins/ruflo-console/CHANGELOG.md b/plugins/ruflo-console/CHANGELOG.md
index 04b37867d5..5265c32143 100644
--- a/plugins/ruflo-console/CHANGELOG.md
+++ b/plugins/ruflo-console/CHANGELOG.md
@@ -2,6 +2,13 @@
Newest first. One `## <version> — <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-console`.
+## 0.39.0 — 2026-10-07
+- feat: ADRs page under TOOLS: find, propose, accept, reject, deprecate and supersede your own project's Architecture Decision Records, with the exact file and diff in the confirm (ADR-480)
+- feat: the page finds your project's ADR folder (docs/adr, docs/adrs, doc/adr, adr, docs/architecture/decisions, docs/decisions ...) or the one in Settings, follows the style of your existing ADRs (MADR, Nygard / adr-tools, ruflo style) and offers to initialise a project that has none
+- feat: attach ADRs to a mission: Claude's mission context, the task instruction and spawned swarm agents carry the accepted decisions; changed files are compared with the paths those ADRs name at verify time (a warning in the record, never a block)
+- feat: ADR lint (duplicate numbers, dangling or one-sided supersedes, no status or date, missing from the index, broken links); palette entries adr-propose, adr-accept, adr-supersede and more, at the write control level
+- feat: Settings gain ADR folder, ADR style and ADR file name pattern
+
## 0.38.0 — 2026-10-07
- feat: What’s new page under TOOLS: each installed ruflo plugin’s bundled CHANGELOG.md, newest first, with a divider at the last look, breaking changes pinned until dismissed, a new marker on the nav, and one info toast per new version (ADR-478)
- feat: CHANGELOG.md in every plugin, in a fixed format the page parses; the smoke contract checks it for console, mods, swarm and protector
diff --git a/plugins/ruflo-console/README.md b/plugins/ruflo-console/README.md
index a7eb14d17c..eb591b7df6 100644
--- a/plugins/ruflo-console/README.md
+++ b/plugins/ruflo-console/README.md
@@ -35,6 +35,16 @@ CONSOLE_DRIVE_INSTALL="$PWD:ruflo-mods@ruflo" RUFLO_E2E_LIVE=1 bash plugins/rufl
--expect 'Hide unused agent types' "$PWD/plugins/ruflo-console" read "Open view settings with chip mods, then console_state, and quote the ruflo-mods option rows."
```
+## Your project's ADRs (ADR-480)
+
+**TOOLS → ADRs** manages the Architecture Decision Records of the project you run Claude Code in (not ruflo's own).
+
+- **Finding them.** The console looks for `docs/adr`, `docs/adrs`, `doc/adr`, `adr`, `docs/architecture/decisions`, `docs/decisions` and `architecture/decisions`, or the folder in *Settings → ADR folder*. A folder that is a link is never read. With none, **initialise ADRs here** asks first, then creates the folder and `0001-record-architecture-decisions.md`; nothing is overwritten.
+- **Reading them.** MADR front matter, Nygard / adr-tools `## Status` sections (`Superseded by [5. …](0005-….md)`), ruflo-style `Status:` lines, log4brains and plain markdown with no status all parse; a file that does not parse still lists. Filter by status, words and scope; the detail shows links both ways, the decision, and the missions it is attached to; the health strip is the lint.
+- **Writing them.** *propose* takes the next number and the style your ADRs already use (override in Settings: ADR style, ADR file name pattern). Accept, reject, deprecate or supersede from a record's detail. Each shows the exact file and the diff, writes only that on your Yes, and leaves a file that changed since alone.
+- **Missions, loops, swarms.** Attach ADRs to the active mission (the page suggests some from the goal's words; you decide). Claude's mission context, each task's instruction and spawned swarm agents (ruflo-swarm 0.3.5) are told the accepted decisions, masked and capped. At *verify*, changed files are compared with the paths the attached accepted ADRs name: a warning in the mission record. **That compares paths only. It does not prove a change follows or breaks a decision, and it never blocks.** When a mission is done, *draft an ADR from this mission* prepares a proposed record from its goal and tasks; the decision is yours to write.
+- **For Claude.** `/ruflo run adr-propose <title>`, `adr-accept <n>`, `adr-supersede <old> <new>`, `adr-attach <n>` and the rest are palette entries, so Claude reaches them through `console_run` at the *write* control level (reading the page is *read*); a change still waits for your Yes on the diff.
+
## Toasts (ADR-477)
Settings → Interface and updates → **Toasts** sets what the ruflo plugins may show over the transcript: `all`, `important` (warnings and errors) or `off`, with a mute chip each for `console`, `swarm`, `protector` and `mods`. It is kept in the console's store and mirrored to `.claude-flow/console/toast-prefs.json`, which the other plugins read. Every toast, drawn or not, becomes an event on the Events page (`toast <source> <glyph> <text> [off|muted|deduped|…]`); the other plugins' digests are read from `.claude-flow/console/toasts/<source>.jsonl`, masked and capped. The console itself also toasts a mission that finishes (`ok`) or loses a task (`error`), and its update notes by level. Design and contract: [ADR-477](../../v3/docs/adr/ADR-477-mod-toasts.md).
diff --git a/plugins/ruflo-console/hooks/adr-actions.ts b/plugins/ruflo-console/hooks/adr-actions.ts
new file mode 100644
index 0000000000..12b836aa30
--- /dev/null
+++ b/plugins/ruflo-console/hooks/adr-actions.ts
@@ -0,0 +1,78 @@
+/**
+ * What the ADRs page and its palette entries call (ADR-480): filter, select, initialise, propose, change a status, attach, check scope.
+ * Each write is a spec for the runner's confirm row; this file only wires them.
+ */
+import type { ActionSpec } from './actions'
+import { adrOf, docByNumber, docOf, initSpec, loadAdrs, proposeSpec, say, statusSpec, type AdrFilter } from './adr'
+import { draftSpec, scopeCheck, setAttached } from './adr-mission'
+import { STATUSES, type AdrStatus } from './data/adr'
+import { plain } from './data/parse'
+import type { Host } from './host'
+import type { Runner } from './runner'
+import type { State } from './state'
+
+export type AdrActions = {
+ reload: () => void
+ filter: (patch: Partial<AdrFilter>) => void
+ select: (file: string | null) => void
+ page: (to: number) => void
+ init: () => void
+ propose: (title: string) => void
+ status: (file: string, to: AdrStatus) => void
+ supersede: (file: string, byNumber: string) => void
+ attach: (file: string, on: boolean) => void
+ scope: () => void
+ draft: () => void
+}
+
+export type AdrWired = { host: Host; actions: AdrActions }
+const wired = new WeakMap<State, AdrWired>()
+export const adrWired = (state: State): AdrWired | undefined => wired.get(state)
+
+const today = (): string => new Date().toISOString().slice(0, 10)
+
+export function adrActions(state: State, host: Host, runner: Runner): AdrActions {
+ const adr = adrOf(state)
+ const reason = 'open the ADRs page to read the project’s ADR folder first'
+ const ask = (spec: ActionSpec | null, why: string) => runner.ask(spec, why)
+ const actions: AdrActions = {
+ reload: () => void loadAdrs(state, host),
+ filter: patch => {
+ adr.page = 0
+ adr.filter = { ...adr.filter, ...patch, status: patch.status !== undefined && (patch.status === 'all' || STATUSES.includes(patch.status as (typeof STATUSES)[number])) ? patch.status : adr.filter.status }
+ host.invalidate()
+ },
+ page: to => {
+ adr.page = Math.max(0, Math.floor(to))
+ host.invalidate()
+ },
+ select: file => {
+ adr.selected = file
+ host.invalidate()
+ },
+ init: () => ask(initSpec(state, host, today()), adr.dir === null ? 'cannot initialise' : 'this project already has an ADR folder'),
+ propose: title => ask(proposeSpec(state, host, title, today()), adr.dir === null ? reason : 'type a title for the record'),
+ status: (file, to) => {
+ const doc = docOf(state, file)
+
+ if (doc === undefined) return say(state, host, 'change ADR', false, [`${plain(file, 60)} is not an ADR here`])
+
+ void statusSpec(state, host, doc, to).then(spec => (spec === null ? undefined : ask(spec, 'nothing to change')))
+ },
+ supersede: (file, byNumber) => {
+ const doc = docOf(state, file)
+ const by = /^\d{1,6}$/.test(byNumber.trim()) ? docByNumber(state, Number(byNumber.trim())) : undefined
+
+ if (doc === undefined || by === undefined) return say(state, host, 'supersede ADR', false, ['give the number of the record that replaces this one'])
+
+ void statusSpec(state, host, doc, 'superseded', by).then(spec => (spec === null ? undefined : ask(spec, 'nothing to change')))
+ },
+ attach: (file, on) => void setAttached(state, host, file, on),
+ scope: () => void scopeCheck(state, host).then(lines => say(state, host, 'ADR scope check', true, lines)),
+ draft: () => ask(draftSpec(state, host, today()), 'no active mission to draft from, or no ADR folder yet'),
+ }
+
+ wired.set(state, { host, actions })
+
+ return actions
+}
diff --git a/plugins/ruflo-console/hooks/adr-mission.ts b/plugins/ruflo-console/hooks/adr-mission.ts
new file mode 100644
index 0000000000..61e3ff4684
--- /dev/null
+++ b/plugins/ruflo-console/hooks/adr-mission.ts
@@ -0,0 +1,114 @@
+/**
+ * ADRs on a mission (ADR-480): attach, suggest and detach, the digest Claude and the swarm read (and the file the swarm reads it from), the
+ * comparison of changed files with the attached ADRs' paths, and a draft record from a mission. The page's logic is in adr.ts; the pure
+ * parts are in data/adr-scope.ts. Nothing here blocks anything: a scope hit is a warning in the mission record.
+ */
+import { replaceFile } from './activity-io'
+import { adrOf, announce, docOf, proposeSpec, root, say } from './adr'
+import type { ActionSpec } from './actions'
+import type { AdrDoc } from './data/adr'
+import { checkScope, digestBlock, reportLines, suggest, type Suggestion } from './data/adr-scope'
+import { draftFromMission } from './data/adr-write'
+import { plain } from './data/parse'
+import type { Host } from './host'
+import { activeMission, record, saveLedger } from './mission-control'
+import type { MissionRecord } from './mission-types'
+import type { State } from './state'
+
+
+export const MAX_ATTACH = 8
+const FILE_SAFE = /^[A-Za-z0-9][A-Za-z0-9._ -]{0,119}\.md$/
+
+/** The file names a mission has attached, validated (a saved ledger is not trusted). */
+export const attachedOf = (mission: MissionRecord): string[] => (Array.isArray(mission.adrs) ? mission.adrs.filter((file): file is string => typeof file === 'string' && FILE_SAFE.test(file)).slice(0, MAX_ATTACH) : [])
+
+/** The attached records that are in this project's folder now (an attached file that was removed simply is not listed). */
+export const attachedDocs = (state: State, mission: MissionRecord): AdrDoc[] => attachedOf(mission).flatMap(file => docOf(state, file) ?? [])
+
+/** What Claude and the swarm agents read for a mission: the digest block, or '' with no ADR attached. */
+export const adrBlockFor = (state: State, mission: MissionRecord | null): string => (mission === null ? '' : digestBlock(attachedDocs(state, mission)))
+
+export function suggestFor(state: State, mission: MissionRecord | null, goal: string): Suggestion[] {
+ return suggest(goal, adrOf(state).registry.docs, mission === null ? [] : attachedOf(mission))
+}
+
+export async function setAttached(state: State, host: Host, file: string, on: boolean): Promise<void> {
+ const mission = activeMission(state)
+
+ if (mission === null) return say(state, host, 'attach ADR', false, ['no active mission: create one in Missions first'])
+ if (!FILE_SAFE.test(file) || docOf(state, file) === undefined) return say(state, host, 'attach ADR', false, [`${plain(file, 60)} is not an ADR in this project`])
+
+ const now = attachedOf(mission)
+
+ if (on && !now.includes(file) && now.length >= MAX_ATTACH) return say(state, host, 'attach ADR', false, [`a mission carries at most ${MAX_ATTACH} ADRs`])
+
+ mission.adrs = on ? [...new Set([...now, file])] : now.filter(each => each !== file)
+ record(mission, { type: on ? 'adr.attached' : 'adr.detached', note: plain(file, 120) })
+ saveLedger(state, host)
+ await mirrorDigest(state, host)
+ say(state, host, on ? 'attach ADR' : 'detach ADR', true, [`${file} ${on ? 'attached to' : 'detached from'} the mission`])
+ announce(state, host, `ADR ${docOf(state, file)?.number ?? file} ${on ? 'attached to' : 'detached from'} the mission`)
+}
+
+/** Where the swarm plugin reads the digest: a small, masked file under the console's own folder. */
+export const DIGEST_FILE = '.claude-flow/console/adr-digest.json'
+
+/**
+ * Writes (or clears) the digest the swarm plugin appends to a spawned subagent's prompt. Only the active mission's attached ADRs; the
+ * text is the same masked, capped block Claude reads. Never throws.
+ */
+export async function mirrorDigest(state: State, host: Pick<Host, 'fs' | 'run'>): Promise<string | null> {
+ const mission = activeMission(state)
+ const docs = mission === null ? [] : attachedDocs(state, mission)
+ const body = JSON.stringify({ v: 1, atMs: Date.now(), mission: mission?.id ?? '', adrs: docs.slice(0, MAX_ATTACH).map(doc => ({ number: doc.number, file: doc.file, status: doc.status })), block: digestBlock(docs) })
+
+ return replaceFile(host, state.cwd, `${root(state)}/${DIGEST_FILE}`, body)
+}
+
+/** Files changed in the project: uncommitted work, and commits since the mission began. Read-only git. */
+export async function changedFiles(host: Pick<Host, 'run'>, cwd: string, sinceMs: number): Promise<string[]> {
+ const out = new Set<string>()
+ const status = await host.run(['git', '-C', cwd, 'status', '--porcelain'], 15_000).catch(() => null)
+
+ for (const line of (status?.stdout ?? '').split('\n')) {
+ const path = line.slice(3).split(' -> ').pop()?.trim().replace(/^"|"$/g, '')
+
+ if (path !== undefined && path !== '') out.add(path)
+ }
+
+ const log = await host.run(['git', '-C', cwd, 'log', `--since=${new Date(Math.max(0, sinceMs)).toISOString()}`, '--name-only', '--pretty=format:'], 15_000).catch(() => null)
+
+ for (const line of (log?.stdout ?? '').split('\n')) if (line.trim() !== '') out.add(line.trim())
+
+ return [...out].slice(0, 400)
+}
+
+/** The scope check for the active mission: a warning per accepted ADR whose paths a changed file falls under. Recorded as mission evidence; blocks nothing. */
+export async function scopeCheck(state: State, host: Pick<Host, 'run' | 'invalidate'>): Promise<string[]> {
+ const mission = activeMission(state)
+
+ if (mission === null) return ['no active mission']
+
+ const docs = attachedDocs(state, mission)
+ const report = checkScope(docs.length === 0 ? [] : await changedFiles(host, state.cwd, mission.createdAtMs), docs)
+ const lines = reportLines(report)
+
+ adrOf(state).scope = report
+ if (docs.length > 0) record(mission, { type: 'adr.scope', note: plain(lines.join(' | '), 400) })
+ host.invalidate()
+
+ return lines
+}
+
+/** A draft record for the active mission, as a proposeSpec: only the mission's own words; a person writes the decision. */
+export function draftSpec(state: State, host: Pick<Host, 'fs' | 'run' | 'invalidate' | 'toast'>, today: string): ActionSpec | null {
+ const mission = activeMission(state)
+
+ if (mission === null) return null
+
+ const finished = mission.events.filter(event => event.type === 'task.complete' || event.status === 'done')
+ const results = new Map<string, string>(finished.flatMap(event => (event.taskId !== undefined && event.note !== undefined ? [[event.taskId, event.note] as [string, string]] : [])))
+ const draft = draftFromMission({ objective: mission.objective, tasks: mission.tasks.map(task => ({ title: task.title, ...(results.has(task.id) && { result: results.get(task.id) as string }) })) }, attachedDocs(state, mission).flatMap(doc => doc.scope.slice(0, 2)), today)
+
+ return proposeSpec(state, host, draft.title, today, { ...(draft.context !== undefined && { context: draft.context }), ...(draft.decision !== undefined && { decision: draft.decision }), scope: draft.scope ?? [] })
+}
diff --git a/plugins/ruflo-console/hooks/adr-palette.ts b/plugins/ruflo-console/hooks/adr-palette.ts
index c3708c93d8..e2f29fde3f 100644
--- a/plugins/ruflo-console/hooks/adr-palette.ts
+++ b/plugins/ruflo-console/hooks/adr-palette.ts
@@ -5,7 +5,8 @@
* entry only prepares the change, and the confirm that follows shows the diff and writes only on the person's own Yes.
*/
import type { ActionSpec } from './actions'
-import { adrOf, adrWired, docByNumber, initSpec, proposeSpec } from './adr'
+import { adrOf, docByNumber, initSpec, proposeSpec } from './adr'
+import { adrWired } from './adr-actions'
import { STATUSES, type AdrStatus } from './data/adr'
import { plain } from './data/parse'
import type { PaletteEntry } from './palette'
diff --git a/plugins/ruflo-console/hooks/adr.ts b/plugins/ruflo-console/hooks/adr.ts
index 2d0e3c8c99..e0ac007ed5 100644
--- a/plugins/ruflo-console/hooks/adr.ts
+++ b/plugins/ruflo-console/hooks/adr.ts
@@ -70,7 +70,7 @@ export function adrOf(state: State): AdrState {
return found
}
-const root = (state: State): string => state.cwd.replace(/\/+$/, '')
+export const root = (state: State): string => state.cwd.replace(/\/+$/, '')
const isDir = (kind: string | undefined): boolean => kind === 'dir' || kind === 'directory'
/** The folder the project keeps its ADRs in: the setting if there is one, else the first usual place that exists. A link is refused. */
@@ -168,20 +168,20 @@ export async function loadAdrs(state: State, host: Pick<Host, 'fs' | 'invalidate
export const docOf = (state: State, file: string): AdrDoc | undefined => adrOf(state).registry.docs.find(doc => doc.file === file)
export const docByNumber = (state: State, number: number): AdrDoc | undefined => adrOf(state).registry.byNumber.get(number)?.[0]
-const say = (state: State, host: Pick<Host, 'invalidate'>, label: string, ok: boolean, lines: string[]): void => {
+export const say = (state: State, host: Pick<Host, 'invalidate'>, label: string, ok: boolean, lines: string[]): void => {
adrOf(state).last = { label, ok, lines: lines.slice(0, MAX_RESULT_LINES).map(line => plain(line, 200)) }
host.invalidate()
}
/** One event on the Events page and one toast (source console, level info): the ADR said what happened, once. */
-function announce(state: State, host: Pick<Host, 'toast'>, text: string): void {
+export function announce(state: State, host: Pick<Host, 'toast'>, text: string): void {
const line = plain(text, 118)
recordEvents(state.events, [{ atMs: Date.now(), kind: 'notices', text: `adr: ${line}` }])
if (state.isInteractive) host.toast(line, 6000, 'info')
}
-const abs = (state: State, dir: string, name: string): string => `${root(state)}/${dir}/${name}`
+export const abs = (state: State, dir: string, name: string): string => `${root(state)}/${dir}/${name}`
async function writeNew(state: State, host: Pick<Host, 'fs' | 'run'>, dir: string, name: string, text: string): Promise<string | null> {
const path = abs(state, dir, name)
@@ -353,168 +353,3 @@ export async function statusSpec(state: State, host: Pick<Host, 'fs' | 'run' | '
},
}
}
-
-// ---------------------------------------------------------------------------------------------------------------- missions
-
-export const MAX_ATTACH = 8
-const FILE_SAFE = /^[A-Za-z0-9][A-Za-z0-9._ -]{0,119}\.md$/
-
-/** The file names a mission has attached, validated (a saved ledger is not trusted). */
-export const attachedOf = (mission: MissionRecord): string[] => (Array.isArray(mission.adrs) ? mission.adrs.filter((file): file is string => typeof file === 'string' && FILE_SAFE.test(file)).slice(0, MAX_ATTACH) : [])
-
-/** The attached records that are in this project's folder now (an attached file that was removed simply is not listed). */
-export const attachedDocs = (state: State, mission: MissionRecord): AdrDoc[] => attachedOf(mission).flatMap(file => docOf(state, file) ?? [])
-
-/** What Claude and the swarm agents read for a mission: the digest block, or '' with no ADR attached. */
-export const adrBlockFor = (state: State, mission: MissionRecord | null): string => (mission === null ? '' : digestBlock(attachedDocs(state, mission)))
-
-export function suggestFor(state: State, mission: MissionRecord | null, goal: string): Suggestion[] {
- return suggest(goal, adrOf(state).registry.docs, mission === null ? [] : attachedOf(mission))
-}
-
-export async function setAttached(state: State, host: Host, file: string, on: boolean): Promise<void> {
- const mission = activeMission(state)
-
- if (mission === null) return say(state, host, 'attach ADR', false, ['no active mission: create one in Missions first'])
- if (!FILE_SAFE.test(file) || docOf(state, file) === undefined) return say(state, host, 'attach ADR', false, [`${plain(file, 60)} is not an ADR in this project`])
-
- const now = attachedOf(mission)
-
- if (on && !now.includes(file) && now.length >= MAX_ATTACH) return say(state, host, 'attach ADR', false, [`a mission carries at most ${MAX_ATTACH} ADRs`])
-
- mission.adrs = on ? [...new Set([...now, file])] : now.filter(each => each !== file)
- record(mission, { type: on ? 'adr.attached' : 'adr.detached', note: plain(file, 120) })
- saveLedger(state, host)
- await mirrorDigest(state, host)
- say(state, host, on ? 'attach ADR' : 'detach ADR', true, [`${file} ${on ? 'attached to' : 'detached from'} the mission`])
- announce(state, host, `ADR ${docOf(state, file)?.number ?? file} ${on ? 'attached to' : 'detached from'} the mission`)
-}
-
-/** Where the swarm plugin reads the digest: a small, masked file under the console's own folder. */
-export const DIGEST_FILE = '.claude-flow/console/adr-digest.json'
-
-/**
- * Writes (or clears) the digest the swarm plugin appends to a spawned subagent's prompt. Only the active mission's attached ADRs; the
- * text is the same masked, capped block Claude reads. Never throws.
- */
-export async function mirrorDigest(state: State, host: Pick<Host, 'fs' | 'run'>): Promise<string | null> {
- const mission = activeMission(state)
- const docs = mission === null ? [] : attachedDocs(state, mission)
- const body = JSON.stringify({ v: 1, atMs: Date.now(), mission: mission?.id ?? '', adrs: docs.slice(0, MAX_ATTACH).map(doc => ({ number: doc.number, file: doc.file, status: doc.status })), block: digestBlock(docs) })
-
- return replaceFile(host, state.cwd, `${root(state)}/${DIGEST_FILE}`, body)
-}
-
-/** Files changed in the project: uncommitted work, and commits since the mission began. Read-only git. */
-export async function changedFiles(host: Pick<Host, 'run'>, cwd: string, sinceMs: number): Promise<string[]> {
- const out = new Set<string>()
- const status = await host.run(['git', '-C', cwd, 'status', '--porcelain'], 15_000).catch(() => null)
-
- for (const line of (status?.stdout ?? '').split('\n')) {
- const path = line.slice(3).split(' -> ').pop()?.trim().replace(/^"|"$/g, '')
-
- if (path !== undefined && path !== '') out.add(path)
- }
-
- const log = await host.run(['git', '-C', cwd, 'log', `--since=${new Date(Math.max(0, sinceMs)).toISOString()}`, '--name-only', '--pretty=format:'], 15_000).catch(() => null)
-
- for (const line of (log?.stdout ?? '').split('\n')) if (line.trim() !== '') out.add(line.trim())
-
- return [...out].slice(0, 400)
-}
-
-/** The scope check for the active mission: a warning per accepted ADR whose paths a changed file falls under. Recorded as mission evidence; blocks nothing. */
-export async function scopeCheck(state: State, host: Pick<Host, 'run' | 'invalidate'>): Promise<string[]> {
- const mission = activeMission(state)
-
- if (mission === null) return ['no active mission']
-
- const docs = attachedDocs(state, mission)
- const report = checkScope(docs.length === 0 ? [] : await changedFiles(host, state.cwd, mission.createdAtMs), docs)
- const lines = reportLines(report)
-
- adrOf(state).scope = report
- if (docs.length > 0) record(mission, { type: 'adr.scope', note: plain(lines.join(' | '), 400) })
- host.invalidate()
-
- return lines
-}
-
-/** A draft record for the active mission, as a proposeSpec: only the mission's own words; a person writes the decision. */
-export function draftSpec(state: State, host: Pick<Host, 'fs' | 'run' | 'invalidate' | 'toast'>, today: string): ActionSpec | null {
- const mission = activeMission(state)
-
- if (mission === null) return null
-
- const finished = mission.events.filter(event => event.type === 'task.complete' || event.status === 'done')
- const results = new Map<string, string>(finished.flatMap(event => (event.taskId !== undefined && event.note !== undefined ? [[event.taskId, event.note] as [string, string]] : [])))
- const draft = draftFromMission({ objective: mission.objective, tasks: mission.tasks.map(task => ({ title: task.title, ...(results.has(task.id) && { result: results.get(task.id) as string }) })) }, attachedDocs(state, mission).flatMap(doc => doc.scope.slice(0, 2)), today)
-
- return proposeSpec(state, host, draft.title, today, { ...(draft.context !== undefined && { context: draft.context }), ...(draft.decision !== undefined && { decision: draft.decision }), scope: draft.scope ?? [] })
-}
-
-export type AdrActions = {
- reload: () => void
- filter: (patch: Partial<AdrFilter>) => void
- select: (file: string | null) => void
- page: (to: number) => void
- init: () => void
- propose: (title: string) => void
- status: (file: string, to: AdrStatus) => void
- supersede: (file: string, byNumber: string) => void
- attach: (file: string, on: boolean) => void
- scope: () => void
- draft: () => void
-}
-
-export type AdrWired = { host: Host; actions: AdrActions }
-const wired = new WeakMap<State, AdrWired>()
-export const adrWired = (state: State): AdrWired | undefined => wired.get(state)
-
-const today = (): string => new Date().toISOString().slice(0, 10)
-
-export function adrActions(state: State, host: Host, runner: Runner): AdrActions {
- const adr = adrOf(state)
- const reason = 'open the ADRs page to read the project’s ADR folder first'
- const ask = (spec: ActionSpec | null, why: string) => runner.ask(spec, why)
- const actions: AdrActions = {
- reload: () => void loadAdrs(state, host),
- filter: patch => {
- adr.page = 0
- adr.filter = { ...adr.filter, ...patch, status: patch.status !== undefined && (patch.status === 'all' || STATUSES.includes(patch.status as (typeof STATUSES)[number])) ? patch.status : adr.filter.status }
- host.invalidate()
- },
- page: to => {
- adr.page = Math.max(0, Math.floor(to))
- host.invalidate()
- },
- select: file => {
- adr.selected = file
- host.invalidate()
- },
- init: () => ask(initSpec(state, host, today()), adr.dir === null ? 'cannot initialise' : 'this project already has an ADR folder'),
- propose: title => ask(proposeSpec(state, host, title, today()), adr.dir === null ? reason : 'type a title for the record'),
- status: (file, to) => {
- const doc = docOf(state, file)
-
- if (doc === undefined) return say(state, host, 'change ADR', false, [`${plain(file, 60)} is not an ADR here`])
-
- void statusSpec(state, host, doc, to).then(spec => (spec === null ? undefined : ask(spec, 'nothing to change')))
- },
- supersede: (file, byNumber) => {
- const doc = docOf(state, file)
- const by = /^\d{1,6}$/.test(byNumber.trim()) ? docByNumber(state, Number(byNumber.trim())) : undefined
-
- if (doc === undefined || by === undefined) return say(state, host, 'supersede ADR', false, ['give the number of the record that replaces this one'])
-
- void statusSpec(state, host, doc, 'superseded', by).then(spec => (spec === null ? undefined : ask(spec, 'nothing to change')))
- },
- attach: (file, on) => void setAttached(state, host, file, on),
- scope: () => void scopeCheck(state, host).then(lines => say(state, host, 'ADR scope check', true, lines)),
- draft: () => ask(draftSpec(state, host, today()), 'no active mission to draft from, or no ADR folder yet'),
- }
-
- wired.set(state, { host, actions })
-
- return actions
-}
diff --git a/plugins/ruflo-console/hooks/bindings.ts b/plugins/ruflo-console/hooks/bindings.ts
index 86acf960f6..7d9705de87 100644
--- a/plugins/ruflo-console/hooks/bindings.ts
+++ b/plugins/ruflo-console/hooks/bindings.ts
@@ -42,7 +42,7 @@ import { claudeActions } from './mission-claude'
import { UPDATES_KEY } from './updates'
import { setToastMode, toggleToastMute } from './toasts'
import { whatsnewActions } from './whatsnew'
-import { adrActions } from './adr'
+import { adrActions } from './adr-actions'
import { vectorActions } from './vector'
import type { Actions } from './views/common'
import { openTasks, selection } from './views/select'
diff --git a/plugins/ruflo-console/hooks/data/adr-lint.ts b/plugins/ruflo-console/hooks/data/adr-lint.ts
new file mode 100644
index 0000000000..8db24b0d8f
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/adr-lint.ts
@@ -0,0 +1,132 @@
+/**
+ * The ADR lint, the link graph and the page's filter (ADR-480). Pure and bounded; the parser they work on is data/adr.ts, which re-exports
+ * this file. Errors are what a reader would be misled by, warnings are untidy, info is a note; a kind of finding is listed at most PER_CODE
+ * times so one noisy kind cannot hide the rest.
+ */
+import type { AdrDoc, AdrStatus, Finding, Registry } from './adr'
+
+const PER_CODE = 60
+
+/** Both directions of every link, from what each document says about the others (declared either way, deduplicated). */
+export function graphOf(registry: Registry, doc: AdrDoc): { supersedes: AdrDoc[]; supersededBy: AdrDoc[]; relates: AdrDoc[]; citedBy: AdrDoc[] } {
+ const find = (numbers: number[]): AdrDoc[] => numbers.flatMap(n => registry.byNumber.get(n)?.slice(0, 1) ?? [])
+ const by = (pick: (other: AdrDoc) => number[]): AdrDoc[] => (doc.number === null ? [] : registry.docs.filter(other => other !== doc && pick(other).includes(doc.number as number)))
+ const unique = (list: AdrDoc[]) => [...new Set(list)]
+
+ return {
+ supersedes: unique([...find(doc.supersedes), ...by(other => other.supersededBy)]),
+ supersededBy: unique([...find(doc.supersededBy), ...by(other => other.supersedes)]),
+ relates: unique([...find(doc.relates)]),
+ citedBy: unique(by(other => [...other.relates, ...other.supersedes, ...other.supersededBy])),
+ }
+}
+
+/**
+ * The lint. `files` is every file name in the folder (for broken links), `index` the text of an index file (README.md, index.md,
+ * INDEX*.md) when the folder has one. Errors are what a reader would be misled by; warnings are untidy; info is a note.
+ */
+export function lint(registry: Registry, files: readonly string[], index: string | null = null): Finding[] {
+ const out: Finding[] = []
+ const names = new Set(files)
+ const add = (level: Finding['level'], code: string, file: string, text: string) => void out.push({ level, code, file, text })
+
+ for (const [number, all] of registry.byNumber) {
+ for (const doc of all) {
+ const same = all.filter(other => other !== doc && other.variant === doc.variant)
+
+ if (same.length > 0) add('error', 'duplicate-number', doc.file, `number ${number} is also used by ${same.map(other => other.file).join(', ')}`)
+ }
+ }
+
+ for (const doc of registry.docs) {
+ for (const target of doc.supersedes) if (!registry.byNumber.has(target)) add('warn', 'dangling-supersedes', doc.file, `supersedes ${target}, which has no file`)
+ for (const target of doc.supersededBy) if (!registry.byNumber.has(target)) add('warn', 'dangling-superseded-by', doc.file, `superseded by ${target}, which has no file`)
+
+ for (const target of doc.supersedes) {
+ const other = registry.byNumber.get(target)?.[0]
+
+ if (other !== undefined && other.status !== 'superseded' && !other.supersededBy.includes(doc.number ?? -1)) add('warn', 'supersede-mismatch', doc.file, `says it supersedes ${target}, but ${other.file} is still ${other.status === 'unknown' ? 'without a status' : other.status}`)
+ }
+ if (doc.status === 'superseded' && doc.supersededBy.length === 0 && !registry.docs.some(other => other.supersedes.includes(doc.number ?? -1))) add('warn', 'superseded-by-nothing', doc.file, 'is superseded, but no document says by which')
+ if (doc.statusRaw === '') add('warn', 'no-status', doc.file, 'has no status')
+ else if (doc.status === 'unknown') add('warn', 'unknown-status', doc.file, `status “${doc.statusRaw}” is not one of proposed, accepted, superseded, deprecated, rejected`)
+ if (doc.statusRaw !== '' && doc.date === null) add('warn', 'status-without-date', doc.file, 'has a status but no date')
+ if (doc.number === null) add('warn', 'no-number', doc.file, 'has no number')
+ for (const link of doc.fileLinks) if (!names.has(link)) add('warn', 'broken-link', doc.file, `links to ${link}, which is not in this folder`)
+ for (const note of doc.notes) if (note.startsWith('longer than')) add('info', 'too-large', doc.file, note)
+ if (index !== null && !mentions(index, doc)) add('warn', 'not-in-index', doc.file, 'is not listed in the folder’s index')
+ }
+
+ // A cycle in supersession (A supersedes B supersedes A) cannot be read as history. Each walk is bounded by the number of records.
+ for (const doc of registry.docs) {
+ if (doc.number === null) continue
+
+ const seen = new Set<number>()
+ const todo = [...doc.supersedes]
+
+ while (todo.length > 0) {
+ const number = todo.pop() as number
+
+ if (number === doc.number) {
+ add('error', 'supersede-cycle', doc.file, `supersession loops back to number ${doc.number}`)
+ break
+ }
+ if (seen.has(number)) continue
+
+ seen.add(number)
+ todo.push(...(registry.byNumber.get(number)?.[0]?.supersedes ?? []))
+ }
+ }
+
+ if (registry.truncated) add('info', 'too-many', '', `the folder holds more records than the console reads: only the first ${registry.docs.length} are listed`)
+
+ // Bounded: at most PER_CODE findings of one kind (errors first), then a note of how many more there were, so one noisy kind cannot hide the rest.
+ const order = { error: 0, warn: 1, info: 2 }
+ const kept: Finding[] = []
+ const seen = new Map<string, number>()
+
+ for (const finding of [...out].sort((x, y) => order[x.level] - order[y.level])) {
+ const n = (seen.get(finding.code) ?? 0) + 1
+
+ seen.set(finding.code, n)
+ if (n <= PER_CODE) kept.push(finding)
+ }
+ for (const [code, n] of seen) if (n > PER_CODE) kept.push({ level: 'info', code: `more-${code}`, file: '', text: `${n - PER_CODE} more ${code} findings not listed` })
+
+ return kept.slice(0, 400)
+}
+
+function mentions(index: string, doc: AdrDoc): boolean {
+ if (index.includes(doc.file)) return true
+ if (doc.number === null) return false
+
+ const n = String(doc.number)
+ const padded = n.padStart(3, '0')
+
+ return new RegExp(`(?:ADR[-_ ]?|\\|\\s*|\\[|^\\s*[-*]\\s*|\\b)0*${n}\\b|\\b${padded}\\b`, 'm').test(index)
+}
+
+export type Counts = { total: number; byStatus: Record<AdrStatus, number>; errors: number; warns: number }
+
+export function countsOf(registry: Registry, findings: readonly Finding[]): Counts {
+ const byStatus: Record<AdrStatus, number> = { proposed: 0, accepted: 0, superseded: 0, deprecated: 0, rejected: 0, unknown: 0 }
+
+ for (const doc of registry.docs) byStatus[doc.status] += 1
+
+ return { total: registry.docs.length, byStatus, errors: findings.filter(f => f.level === 'error').length, warns: findings.filter(f => f.level === 'warn').length }
+}
+
+/** The filter the page applies: a status (or all), a text (every word in the title, file name or scope), a scope fragment. */
+export function filterDocs(docs: readonly AdrDoc[], filter: { status: AdrStatus | 'all'; text: string; scope: string }): AdrDoc[] {
+ const words = filter.text.toLowerCase().split(/\s+/).filter(word => word !== '')
+ const scope = filter.scope.trim().toLowerCase()
+
+ return docs.filter(doc => {
+ if (filter.status !== 'all' && doc.status !== filter.status) return false
+ if (scope !== '' && !doc.scope.some(entry => entry.toLowerCase().includes(scope))) return false
+
+ const hay = `${doc.title} ${doc.file} ${doc.number ?? ''} ${doc.scope.join(' ')}`.toLowerCase()
+
+ return words.every(word => hay.includes(word))
+ })
+}
diff --git a/plugins/ruflo-console/hooks/data/adr.ts b/plugins/ruflo-console/hooks/data/adr.ts
index 23c25c0b7b..3bc5fe01db 100644
--- a/plugins/ruflo-console/hooks/data/adr.ts
+++ b/plugins/ruflo-console/hooks/data/adr.ts
@@ -17,7 +17,6 @@ export const MAX_SCOPE = 24
export const MAX_REFS = 20
export const MAX_LINKS = 24
export const SECTION_MAX = 1200
-const PER_CODE = 60
export const STATUSES = ['proposed', 'accepted', 'superseded', 'deprecated', 'rejected'] as const
export type AdrStatus = (typeof STATUSES)[number] | 'unknown'
@@ -379,126 +378,4 @@ export function indexOf(docs: readonly AdrDoc[], truncated = false): Registry {
return { docs: sortDocs(docs), byNumber, truncated }
}
-/** Both directions of every link, from what each document says about the others (declared either way, deduplicated). */
-export function graphOf(registry: Registry, doc: AdrDoc): { supersedes: AdrDoc[]; supersededBy: AdrDoc[]; relates: AdrDoc[]; citedBy: AdrDoc[] } {
- const find = (numbers: number[]): AdrDoc[] => numbers.flatMap(n => registry.byNumber.get(n)?.slice(0, 1) ?? [])
- const by = (pick: (other: AdrDoc) => number[]): AdrDoc[] => (doc.number === null ? [] : registry.docs.filter(other => other !== doc && pick(other).includes(doc.number as number)))
- const unique = (list: AdrDoc[]) => [...new Set(list)]
-
- return {
- supersedes: unique([...find(doc.supersedes), ...by(other => other.supersededBy)]),
- supersededBy: unique([...find(doc.supersededBy), ...by(other => other.supersedes)]),
- relates: unique([...find(doc.relates)]),
- citedBy: unique(by(other => [...other.relates, ...other.supersedes, ...other.supersededBy])),
- }
-}
-
-/**
- * The lint. `files` is every file name in the folder (for broken links), `index` the text of an index file (README.md, index.md,
- * INDEX*.md) when the folder has one. Errors are what a reader would be misled by; warnings are untidy; info is a note.
- */
-export function lint(registry: Registry, files: readonly string[], index: string | null = null): Finding[] {
- const out: Finding[] = []
- const names = new Set(files)
- const add = (level: Finding['level'], code: string, file: string, text: string) => void out.push({ level, code, file, text })
-
- for (const [number, all] of registry.byNumber) {
- for (const doc of all) {
- const same = all.filter(other => other !== doc && other.variant === doc.variant)
-
- if (same.length > 0) add('error', 'duplicate-number', doc.file, `number ${number} is also used by ${same.map(other => other.file).join(', ')}`)
- }
- }
-
- for (const doc of registry.docs) {
- for (const target of doc.supersedes) if (!registry.byNumber.has(target)) add('warn', 'dangling-supersedes', doc.file, `supersedes ${target}, which has no file`)
- for (const target of doc.supersededBy) if (!registry.byNumber.has(target)) add('warn', 'dangling-superseded-by', doc.file, `superseded by ${target}, which has no file`)
-
- for (const target of doc.supersedes) {
- const other = registry.byNumber.get(target)?.[0]
-
- if (other !== undefined && other.status !== 'superseded' && !other.supersededBy.includes(doc.number ?? -1)) add('warn', 'supersede-mismatch', doc.file, `says it supersedes ${target}, but ${other.file} is still ${other.status === 'unknown' ? 'without a status' : other.status}`)
- }
- if (doc.status === 'superseded' && doc.supersededBy.length === 0 && !registry.docs.some(other => other.supersedes.includes(doc.number ?? -1))) add('warn', 'superseded-by-nothing', doc.file, 'is superseded, but no document says by which')
- if (doc.statusRaw === '') add('warn', 'no-status', doc.file, 'has no status')
- else if (doc.status === 'unknown') add('warn', 'unknown-status', doc.file, `status “${doc.statusRaw}” is not one of proposed, accepted, superseded, deprecated, rejected`)
- if (doc.statusRaw !== '' && doc.date === null) add('warn', 'status-without-date', doc.file, 'has a status but no date')
- if (doc.number === null) add('warn', 'no-number', doc.file, 'has no number')
- for (const link of doc.fileLinks) if (!names.has(link)) add('warn', 'broken-link', doc.file, `links to ${link}, which is not in this folder`)
- for (const note of doc.notes) if (note.startsWith('longer than')) add('info', 'too-large', doc.file, note)
- if (index !== null && !mentions(index, doc)) add('warn', 'not-in-index', doc.file, 'is not listed in the folder’s index')
- }
-
- // A cycle in supersession (A supersedes B supersedes A) cannot be read as history. Each walk is bounded by the number of records.
- for (const doc of registry.docs) {
- if (doc.number === null) continue
-
- const seen = new Set<number>()
- const todo = [...doc.supersedes]
-
- while (todo.length > 0) {
- const number = todo.pop() as number
-
- if (number === doc.number) {
- add('error', 'supersede-cycle', doc.file, `supersession loops back to number ${doc.number}`)
- break
- }
- if (seen.has(number)) continue
-
- seen.add(number)
- todo.push(...(registry.byNumber.get(number)?.[0]?.supersedes ?? []))
- }
- }
-
- if (registry.truncated) add('info', 'too-many', '', `only the first ${MAX_FILES} files are read`)
-
- // Bounded: at most PER_CODE findings of one kind (errors first), then a note of how many more there were, so one noisy kind cannot hide the rest.
- const order = { error: 0, warn: 1, info: 2 }
- const kept: Finding[] = []
- const seen = new Map<string, number>()
-
- for (const finding of [...out].sort((x, y) => order[x.level] - order[y.level])) {
- const n = (seen.get(finding.code) ?? 0) + 1
-
- seen.set(finding.code, n)
- if (n <= PER_CODE) kept.push(finding)
- }
- for (const [code, n] of seen) if (n > PER_CODE) kept.push({ level: 'info', code: `more-${code}`, file: '', text: `${n - PER_CODE} more ${code} findings not listed` })
-
- return kept.slice(0, 400)
-}
-
-function mentions(index: string, doc: AdrDoc): boolean {
- if (index.includes(doc.file)) return true
- if (doc.number === null) return false
-
- const n = String(doc.number)
- const padded = n.padStart(3, '0')
-
- return new RegExp(`(?:ADR[-_ ]?|\\|\\s*|\\[|^\\s*[-*]\\s*|\\b)0*${n}\\b|\\b${padded}\\b`, 'm').test(index)
-}
-
-export type Counts = { total: number; byStatus: Record<AdrStatus, number>; errors: number; warns: number }
-
-export function countsOf(registry: Registry, findings: readonly Finding[]): Counts {
- const byStatus: Record<AdrStatus, number> = { proposed: 0, accepted: 0, superseded: 0, deprecated: 0, rejected: 0, unknown: 0 }
-
- for (const doc of registry.docs) byStatus[doc.status] += 1
-
- return { total: registry.docs.length, byStatus, errors: findings.filter(f => f.level === 'error').length, warns: findings.filter(f => f.level === 'warn').length }
-}
-
-/** The filter the page applies: a status (or all), a text (every word in the title, file name or scope), a scope fragment. */
-export function filterDocs(docs: readonly AdrDoc[], filter: { status: AdrStatus | 'all'; text: string; scope: string }): AdrDoc[] {
- const words = filter.text.toLowerCase().split(/\s+/).filter(word => word !== '')
- const scope = filter.scope.trim().toLowerCase()
-
- return docs.filter(doc => {
- if (filter.status !== 'all' && doc.status !== filter.status) return false
- if (scope !== '' && !doc.scope.some(entry => entry.toLowerCase().includes(scope))) return false
-
- const hay = `${doc.title} ${doc.file} ${doc.number ?? ''} ${doc.scope.join(' ')}`.toLowerCase()
-
- return words.every(word => hay.includes(word))
- })
-}
+export * from './adr-lint'
diff --git a/plugins/ruflo-console/hooks/mission-claude.ts b/plugins/ruflo-console/hooks/mission-claude.ts
index f2575d0d1d..d4b1812630 100644
--- a/plugins/ruflo-console/hooks/mission-claude.ts
+++ b/plugins/ruflo-console/hooks/mission-claude.ts
@@ -9,7 +9,7 @@ import type { Host } from './host'
import { activeMission, derive, mcOf, nextTask, record, saveLedger } from './mission-control'
import { CONTEXT_SECTION_ID, contextEnabled, missionContextKey, missionContextText, turnNote, type TurnReason } from './mission-context'
import { armed, isTick, parseLoop, rearmCommand, startCommand, stop, stopRequest, tick, tickPlan, type LoopState } from './mission-loop'
-import { adrBlockFor, attachedOf, scopeCheck } from './adr'
+import { adrBlockFor, attachedOf, scopeCheck } from './adr-mission'
import { evidenceEvent, parseGates } from './mission-verify'
import { costOf, capOf } from './mission-guard'
import { plain } from './data/parse'
diff --git a/plugins/ruflo-console/hooks/mission-specs.ts b/plugins/ruflo-console/hooks/mission-specs.ts
index 073cbddb71..f2fce4d323 100644
--- a/plugins/ruflo-console/hooks/mission-specs.ts
+++ b/plugins/ruflo-console/hooks/mission-specs.ts
@@ -3,7 +3,7 @@ import type { ActionSpec } from './actions'
import { plain, type TaskRecord } from './data/parse'
import { stageOf, toMissionPlan, type Profile } from './goap'
import type { Host } from './host'
-import { adrBlockFor } from './adr'
+import { adrBlockFor } from './adr-mission'
import { activeMission, instructionOf, mcOf, nextTask, record, rufloTaskOf, saveLedger } from './mission-control'
import type { LedgerTask, MissionRecord } from './mission-types'
import { CLI_PREFIXES, type State } from './state'
diff --git a/plugins/ruflo-console/hooks/version.ts b/plugins/ruflo-console/hooks/version.ts
index d8757c9e58..e6871ead11 100644
--- a/plugins/ruflo-console/hooks/version.ts
+++ b/plugins/ruflo-console/hooks/version.ts
@@ -2,4 +2,4 @@
* The console's version, shown on the header so a person can tell which build is running. Kept equal to the plugin's manifest
* (`.claude-plugin/plugin.json`); tests/version.spec.ts fails if the two drift.
*/
-export const CONSOLE_VERSION = '0.38.0'
+export const CONSOLE_VERSION = '0.39.0'
diff --git a/plugins/ruflo-console/hooks/views/adr.ts b/plugins/ruflo-console/hooks/views/adr.ts
index e4ef61e44d..9a77fbbd5c 100644
--- a/plugins/ruflo-console/hooks/views/adr.ts
+++ b/plugins/ruflo-console/hooks/views/adr.ts
@@ -7,7 +7,8 @@
*/
import type { RenderElement } from 'claude-code'
-import { adrOf, attachedOf, docOf, suggestFor, transitionsOf } from '../adr'
+import { adrOf, docOf, transitionsOf } from '../adr'
+import { attachedOf, suggestFor } from '../adr-mission'
import { countsOf, filterDocs, graphOf, STATUSES, type AdrDoc, type AdrStatus } from '../data/adr'
import { activeMission, mcOf } from '../mission-control'
import { button, col, kv, row, rule, section, text, THEME, type Ctx } from './common'
diff --git a/plugins/ruflo-console/hooks/views/common.ts b/plugins/ruflo-console/hooks/views/common.ts
index e7467a1206..3ea4b15544 100644
--- a/plugins/ruflo-console/hooks/views/common.ts
+++ b/plugins/ruflo-console/hooks/views/common.ts
@@ -9,7 +9,7 @@ import { askedBy } from '../data/room'
import type { RoomActions } from '../room'
import type { WatchActions } from '../watch'
import type { WhatsNewActions } from '../whatsnew'
-import type { AdrActions } from '../adr'
+import type { AdrActions } from '../adr-actions'
import type { EventsActions } from '../events-ui'
import type { TimelineActions } from '../timeline-ui'
import type { Attention } from './attention'
diff --git a/plugins/ruflo-console/hooks/views/pane.ts b/plugins/ruflo-console/hooks/views/pane.ts
index 7de9689b43..30e67444d2 100644
--- a/plugins/ruflo-console/hooks/views/pane.ts
+++ b/plugins/ruflo-console/hooks/views/pane.ts
@@ -58,7 +58,6 @@ import { vectorResult, vectorView } from './vector'
import { xruvView } from './xruv'
export const NARROW = 44
-
/** The keyless views that keep a tab of their own (the rest are reached from the main menu). */
const CORE_TABS = new Set<ViewId>(['hive', 'skills', 'cost', 'timeline', 'approvals', 'events', 'room', 'xruv', 'terminal'])
@@ -98,8 +97,7 @@ const BODIES: Record<ViewId, (ctx: Ctx) => RenderElement> = {
sandbox: sandboxView,
market: catalogView,
settings: settingsView,
- whatsnew: whatsnewView,
- adrs: adrsView,
+ whatsnew: whatsnewView, adrs: adrsView,
agent: agentView,
}
diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.sh
index 570d03a649..87a066b377 100755
--- a/plugins/ruflo-console/scripts/smoke.sh
+++ b/plugins/ruflo-console/scripts/smoke.sh
@@ -11,9 +11,9 @@ step() { printf "→ %s ... " "$1"; }
ok() { printf "PASS\n"; PASS=$((PASS+1)); }
bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }
-step "1. plugin.json declares ruflo-console 0.38.0"
+step "1. plugin.json declares ruflo-console 0.39.0"
grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \
- && grep -q '"version": "0.38.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
+ && grep -q '"version": "0.39.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
step "2. hooks.json names exactly one module and no classic hook commands"
grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \
@@ -117,5 +117,8 @@ version=$(sed -n 's/^ "version": "\([0-9.]*\)".*/\1/p' "$ROOT/.claude-plugin/pl
if grep -qE "^## ${version//./\\.} [—–-] [0-9]{4}-[0-9]{2}-[0-9]{2}\s*$" "$ROOT/CHANGELOG.md" 2>/dev/null \
&& ! grep -qE "fetchText|httpSend|\\.run\(|spawn" "$HOOKS/whatsnew.ts" "$HOOKS/views/whatsnew.ts" "$HOOKS/data/changelog.ts"; then ok; else bad "CHANGELOG.md lacks ## $version, or whatsnew code reaches the network"; fi
+step "19. the ADR code reads and writes only the project's files: no network, no shell, no ruflo-repo path (ADR-480)"
+if ! grep -qE "fetchText|httpSend|spawn\(|v3/docs/adr|check-adr-links|\bsh -c|bash -c" "$HOOKS/adr.ts" "$HOOKS/adr-palette.ts" "$HOOKS/views/adr.ts" "$HOOKS/data/adr.ts" "$HOOKS/data/adr-write.ts" "$HOOKS/data/adr-scope.ts"; then ok; else bad "an ADR module reaches the network, a shell or a ruflo path"; fi
+
printf "\n%d passed, %d failed\n" "$PASS" "$FAIL"
[[ $FAIL -eq 0 ]]
diff --git a/plugins/ruflo-console/tests/adr-helpers.ts b/plugins/ruflo-console/tests/adr-helpers.ts
index 6f777167e4..412a2f5af5 100644
--- a/plugins/ruflo-console/tests/adr-helpers.ts
+++ b/plugins/ruflo-console/tests/adr-helpers.ts
@@ -1,5 +1,11 @@
/** Shared by the ADR specs (ADR-480): a project copied to a temp folder, and a host whose `fs` and `run` act on real files there. */
import { spawnSync } from 'node:child_process'
+import { afterAll } from 'vitest'
+import { dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { newState, type State } from '../hooks/state'
+import { loadAdrs } from '../hooks/adr'
+import { parseAdr, type AdrDoc } from '../hooks/data/adr'
import { cpSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -57,3 +63,41 @@ export function hostOfRoot(root: string) {
return { host, log }
}
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+
+export const FIXTURES = join(HERE, 'fixtures', 'adr-projects')
+export const RUFLO_ADRS = join(HERE, '..', '..', '..', 'v3', 'docs', 'adr')
+export const TODAY = '2026-10-07'
+
+const cleanups: string[] = []
+
+/** Registers the removal of every folder made through this module for the spec file that calls it. */
+export const cleanAfter = (): void => afterAll(() => {
+ for (const dir of cleanups) rmSync(dir, { recursive: true, force: true })
+})
+
+export const keep = (dir: string): string => (cleanups.push(dir), dir)
+
+export const project = (name: string): string => keep(tempProject(FIXTURES, name))
+
+export const stateAt = (root: string): State => {
+ const state = newState({})
+
+ state.cwd = root
+ state.isInteractive = true
+
+ return state
+}
+
+export const loaded = async (name: string) => {
+ const root = project(name)
+ const state = stateAt(root)
+ const world = hostOfRoot(root)
+
+ await loadAdrs(state, world.host as never)
+
+ return { root, state, world }
+}
+
+export const docsOf = (name: string, folder: string): AdrDoc[] => readdirSync(join(FIXTURES, name, folder)).filter(f => f.endsWith('.md') && !/^readme/i.test(f)).sort().map(f => parseAdr(f, readFileSync(join(FIXTURES, name, folder, f), 'utf8')))
diff --git a/plugins/ruflo-console/tests/adr-integration.spec.ts b/plugins/ruflo-console/tests/adr-integration.spec.ts
index 6e919f762f..ac90066a63 100644
--- a/plugins/ruflo-console/tests/adr-integration.spec.ts
+++ b/plugins/ruflo-console/tests/adr-integration.spec.ts
@@ -5,66 +5,26 @@
* npx vitest run plugins/ruflo-console/tests/adr-integration.spec.ts
*/
import { execFileSync } from 'node:child_process'
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { dirname, join } from 'node:path'
-import { fileURLToPath } from 'node:url'
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
import { afterAll, describe, expect, it } from 'vitest'
-import { adrActions, adrBlockFor, adrOf, attachedDocs, attachedOf, DIGEST_FILE, draftSpec, loadAdrs, mirrorDigest, scopeCheck, setAttached, suggestFor } from '../hooks/adr'
-import { adrPalette } from '../hooks/adr-palette'
-import { allows, classOf } from '../hooks/model-tools'
+import { adrOf, loadAdrs } from '../hooks/adr'
+import { adrBlockFor, attachedOf, DIGEST_FILE, draftSpec, mirrorDigest, scopeCheck, setAttached, suggestFor } from '../hooks/adr-mission'
import { contextSection, claudeActions } from '../hooks/mission-claude'
import { missionContextText } from '../hooks/mission-context'
import { instructionOf, loadLedger, LEDGER_KEY, mcOf } from '../hooks/mission-control'
import type { MissionRecord } from '../hooks/mission-types'
-import { paletteEntries } from '../hooks/palette'
-import { loadAiPrefs, saveAiPrefs, settingsOf } from '../hooks/settings'
-import { newState, VIEWS, type State } from '../hooks/state'
-import { NAV_GROUPS } from '../hooks/nav-state'
-import { setLook, type Actions } from '../hooks/views/common'
-import { viewText } from '../hooks/views/pane'
-import { adrsView } from '../hooks/views/adr'
+import { settingsOf } from '../hooks/settings'
+import { newState } from '../hooks/state'
+import { setLook } from '../hooks/views/common'
import { readAdrDigest } from '../../ruflo-swarm/hooks/adr-digest'
-import { hostOfRoot, tempProject } from './adr-helpers'
+import { cleanAfter } from './adr-helpers'
+import { missionOf, TASK, world } from './adr-world'
-const HERE = dirname(fileURLToPath(import.meta.url))
-const FIXTURES = join(HERE, 'fixtures', 'adr-projects')
-const cleanups: string[] = []
-
-afterAll(() => {
- setLook('plain')
- for (const dir of cleanups) rmSync(dir, { recursive: true, force: true })
-})
-
-const TASK = { id: 't1', title: 'Move sessions', phase: 'refinement', agent: 'coder', requirement: 'sessions live in the new store', dependsOn: [] }
-const missionOf = (patch: Partial<MissionRecord> = {}): MissionRecord => ({ id: 'msn_aaaaaaaaaaaaaaaaaaaaaaaa', objective: 'Move the graphql api sessions in api/public', profile: 'feature', rigor: 'standard', tasks: [TASK], acceptance: [{ id: 'a1', check: 'tests pass' }], events: [], paused: false, cancelled: false, auto: false, createdAtMs: Date.now() - 3_600_000, ...patch })
-
-async function world(name: string, mission: Partial<MissionRecord> | null = {}) {
- const root = tempProject(FIXTURES, name)
-
- cleanups.push(root)
-
- const state = newState({})
- const hosted = hostOfRoot(root)
- const stored = new Map<string, unknown>()
- const host = { ...hosted.host, storeSet: async (key: string, value: unknown) => void stored.set(key, value), storeGet: async (key: string) => stored.get(key) }
-
- state.cwd = root
- state.isInteractive = true
-
- if (mission !== null) {
- const record = missionOf(mission)
-
- mcOf(state).missions.set(record.id, record)
- mcOf(state).active = record.id
- }
-
- await loadAdrs(state, host as never)
-
- return { root, state, host, stored, log: hosted.log, mission: mission === null ? null : (mcOf(state).missions.get('msn_aaaaaaaaaaaaaaaaaaaaaaaa') as MissionRecord) }
-}
+cleanAfter()
+afterAll(() => setLook('plain'))
describe('attach, suggest and detach on a mission', () => {
it('attaches by file, saves the ledger, refuses what is not an ADR here, caps the number and detaches', async () => {
@@ -305,222 +265,3 @@ describe('the scope check against a real repository', () => {
expect(adrOf(w.state).registry.docs.find(doc => doc.number === 3)?.status).toBe('proposed')
})
})
-
-describe('the page', () => {
- const noAct = new Proxy(() => undefined, { get: (_t, key) => (key === 'then' ? undefined : noAct), apply: () => undefined }) as unknown as Actions
- const draw = (state: State, columns = 110) => viewText({ state, nowMs: Date.now(), columns, act: noAct }, 'adrs')
-
- it('is in the TOOLS group, has no hotkey, and says it is reading before the folder is read', () => {
- const state = newState({})
-
- expect(NAV_GROUPS.find(group => group.title === 'TOOLS')?.rows.flat()).toContain('adrs')
- expect(VIEWS.find(view => view.id === 'adrs')).toMatchObject({ key: '', label: 'ADRs' })
- expect(draw(state)).toContain('not read yet')
- })
-
- it('a project with no ADR folder offers to initialise it, and points at Settings', async () => {
- const w = await world('empty', null)
- const text = draw(w.state)
-
- expect(text).toContain('no ADR folder found')
- expect(text).toContain('initialise ADRs here')
- expect(text).toContain('Nothing is overwritten')
- expect(text).toContain('Settings')
- })
-
- it('lists records with status and date, the health strip, the filters and the honest limits', async () => {
- const w = await world('madr')
- const text = draw(w.state)
-
- expect(text).toContain('docs/decisions')
- expect(text).toContain('madr')
- expect(text).toContain('3 records · 2 accepted · 0 proposed · 1 superseded')
- expect(text).toContain('0003')
- expect(text).toContain('Use Cockroach for storage')
- expect(text).toContain('health: 0 errors')
- expect(text).toContain('compares file PATHS')
- expect(text).toContain('nothing here proves a change follows or breaks a decision')
- })
-
- it('a selected record shows its links both ways, its decision and the mission it is attached to', async () => {
- const w = await world('nygard')
-
- await setAttached(w.state, w.host as never, '0003-use-graphql.md', true)
- adrOf(w.state).selected = '0002-use-rest.md'
-
- const rest = draw(w.state)
-
- expect(rest).toContain('ADR 2: Use REST for the public API')
- expect(rest).toContain('superseded by')
- expect(rest).toContain('cited by ADRs')
-
- adrOf(w.state).selected = '0003-use-graphql.md'
-
- const graph = draw(w.state)
-
- expect(graph).toContain('supersedes')
- expect(graph).toContain('cited by missions msn_aaaaaaa')
- expect(graph).toContain('Decision: GraphQL')
- expect(graph).toContain('− detach from mission')
- })
-
- it('draws in both looks and at narrow and wide widths, with hostile titles, without an escape reaching the screen', async () => {
- const w = await world('plain')
-
- writeFileSync(join(w.root, 'adr/0001-evil.md'), '# 1. Evil\u001b[31m title ‮ <b>x</b>\n\nStatus: Accepted\u001b[2J\n')
- await loadAdrs(w.state, w.host as never)
-
- for (const look of ['plain', 'bbs'] as const) {
- setLook(look)
-
- for (const columns of [44, 80, 140]) {
- const text = draw(w.state, columns)
-
- expect(text, `${look} ${columns}`).toContain('ADR')
- expect(text, `${look} ${columns}`).not.toMatch(/[\u001b‮]/)
- }
- }
-
- setLook('plain')
- })
-
- it('every action is a button with a key, pressing reaches the action, and the list pages by j and k', async () => {
- const w = await world('madr')
- const calls: string[] = []
- const recorder = (path: string): unknown => new Proxy(() => undefined, { get: (_t, key) => (key === 'then' ? undefined : recorder(`${path}.${String(key)}`)), apply: (_t, _this, args) => void calls.push(`${path.slice(1)}(${args.join(',')})`) })
- type El = { props: Record<string, unknown> }
- const kit = { Box: (props: Record<string, unknown>): El => ({ props }), Text: (props: Record<string, unknown>): El => ({ props }), Button: (props: Record<string, unknown>): El => ({ props }), Input: (props: Record<string, unknown>): El => ({ props }) }
- const flat = (el: unknown): El[] => {
- const node = el as El
-
- if (typeof node !== 'object' || node === null) return []
-
- const kids = node.props?.children
-
- return [node, ...(Array.isArray(kids) ? kids.flatMap(flat) : typeof kids === 'object' ? flat(kids) : [])]
- }
-
- adrOf(w.state).selected = '0002-use-postgres.md'
-
- const tree = adrsView({ kit, state: w.state, nowMs: Date.now(), columns: 120, pictures: new Map(), act: recorder('') as never, cards: true } as never)
- const nodes = flat(tree)
- const by = (key: string) => nodes.find(node => node.props.key === key)
-
- ;(by('adr-row-0003-use-cockroach.md')?.props.onPress as () => void)()
- ;(by('adr-to-accepted') ?? by('adr-f-accepted'))?.props.onPress
- ;(by('adr-f-accepted')?.props.onPress as () => void)()
- ;(by('adr-reload')?.props.onPress as () => void)()
- ;(by('adr-filter')?.props.onSubmit as (v: string) => void)('cockroach')
- ;(by('adr-propose')?.props.onSubmit as (v: string) => void)('Cache reads')
- ;(by('adr-prev')?.props.onPress as () => void)()
-
- expect(by('adr-prev')?.props.hotkey).toBe('k')
- expect(by('adr-next')?.props.hotkey).toBe('j')
- expect(calls).toEqual(['adrs.select(0003-use-cockroach.md)', 'adrs.filter([object Object])', 'adrs.reload()', 'adrs.filter([object Object])', 'adrs.propose(Cache reads)', 'adrs.page(0)'])
- // Mouse and keyboard parity: every pressable here is a Button (focusable, Enter and click alike), and the fields are Inputs.
- expect(nodes.filter(node => typeof node.props.onPress === 'function').length).toBeGreaterThan(8)
- })
-})
-
-describe('the palette and the control level', () => {
- async function wired() {
- const w = await world('nygard')
- const asked: unknown[] = []
- const actions = adrActions(w.state, w.host as never, { ask: (spec: unknown) => void asked.push(spec) } as never)
-
- return { ...w, actions, asked }
- }
-
- it('has an entry for each action, in the palette headless runs use', async () => {
- const w = await wired()
- const ids = adrPalette(w.state).map(entry => entry.id)
-
- expect(ids).toEqual(['adr-open', 'adr-show', 'adr-init', 'adr-propose', 'adr-accept', 'adr-reject', 'adr-deprecate', 'adr-supersede', 'adr-attach', 'adr-detach', 'adr-scope'])
- expect(paletteEntries(w.state, Date.now()).filter(entry => entry.id.startsWith('adr-')).map(entry => entry.id)).toEqual(ids)
- })
-
- it('reading is read level; proposing, initialising, changing a status and attaching are write level, never network, spend or delete', async () => {
- const w = await wired()
- const entry = (id: string) => adrPalette(w.state).find(candidate => candidate.id === id)
- const specOf = (id: string, text = '') => {
- const run = entry(id)?.run
-
- return run?.kind === 'spec' ? run.spec : run?.kind === 'text' ? run.make(text) : null
- }
- const pending = (spec: NonNullable<ReturnType<typeof specOf>>) => ({ label: spec.label, args: spec.args, ...(spec.note !== undefined && { note: spec.note }), ...(spec.shows !== undefined && { shows: spec.shows }), expect: spec.expect, ...(spec.declared !== undefined && { declared: spec.declared }) })
- const classes: Record<string, string> = {}
-
- for (const [id, text] of [['adr-show', '3'], ['adr-propose', 'Cache reads'], ['adr-accept', '3'], ['adr-reject', '3'], ['adr-deprecate', '3'], ['adr-supersede', '1 3'], ['adr-attach', '3'], ['adr-detach', '3'], ['adr-scope', '']] as const) {
- const spec = specOf(id, text)
-
- expect(spec, id).not.toBeNull()
- classes[id] = classOf(pending(spec as never))
- }
-
- expect(Object.fromEntries(Object.entries(classes).filter(([id]) => id !== 'adr-show' && id !== 'adr-scope'))).toEqual({ 'adr-propose': 'write', 'adr-accept': 'write', 'adr-reject': 'write', 'adr-deprecate': 'write', 'adr-supersede': 'write', 'adr-attach': 'write', 'adr-detach': 'write' })
- // Reading goes through the same gate as any entry that declares nothing: it is a read-only spec, which runs at the read level without a pending card.
- expect(specOf('adr-show', '3')?.isReadOnly).toBe(true)
- expect(specOf('adr-show', '3')?.declared).toBeUndefined()
- expect(specOf('adr-scope')?.declared).toBeUndefined()
- expect(entry('adr-open')?.run).toEqual({ kind: 'view', view: 'adrs' })
-
- for (const id of ['adr-propose', 'adr-accept', 'adr-reject', 'adr-deprecate', 'adr-supersede', 'adr-attach', 'adr-detach']) {
- const spec = specOf(id, id === 'adr-propose' ? 'Cache reads' : id === 'adr-supersede' ? '1 3' : '3')
-
- expect(spec?.declared, id).toBe('write')
- expect(allows('read', classOf(pending(spec as never))), `${id} at read`).toBe(false)
- expect(allows('write', classOf(pending(spec as never))), `${id} at write`).toBe(true)
- }
- })
-
- it('a status entry only prepares the change: the diff is a second confirm, and a bad number is no spec', async () => {
- const w = await wired()
- const accept = adrPalette(w.state).find(entry => entry.id === 'adr-deprecate')?.run
-
- expect(accept?.kind === 'text' && accept.make('999')).toBeNull()
- expect(accept?.kind === 'text' && accept.make('ADR-0003')).not.toBeNull()
- ;(accept?.kind === 'text' ? accept.make('3') : null)?.run?.()
- await new Promise(resolve => setTimeout(resolve, 100))
-
- const second = w.asked[0] as { shows: string; label: string } | undefined
-
- expect(second?.label).toBe('mark ADR 3 deprecated')
- expect(second?.shows).toContain('-Accepted')
- expect(second?.shows).toContain('+Deprecated')
- })
-})
-
-describe('the settings', () => {
- it('keep a safe folder, a style and a pattern, and refuse an unsafe folder or pattern with a reason', async () => {
- const w = await world('nygard', null)
- const host = w.host as never
-
- saveAiPrefs(w.state, host, { adrDir: 'notes/decisions', adrStyle: 'madr', adrPattern: 'ADR-{n}-{slug}.md' })
- expect(settingsOf(w.state).ai).toMatchObject({ adrDir: 'notes/decisions', adrStyle: 'madr', adrPattern: 'ADR-{n}-{slug}.md' })
- saveAiPrefs(w.state, host, { adrDir: '../outside' })
- expect(settingsOf(w.state).ai.adrDir).toBe('notes/decisions')
- expect(w.state.outcome?.ok).toBe(false)
- expect(w.state.outcome?.detail).toContain('inside this project')
- saveAiPrefs(w.state, host, { adrPattern: '{n}.md' })
- expect(settingsOf(w.state).ai.adrPattern).toBe('ADR-{n}-{slug}.md')
- expect(w.state.outcome?.detail).toContain('{n} and {slug}')
-
- const reload = newState({})
-
- await w.host.storeSet('ai-prefs', { adrDir: '../evil', adrStyle: 'bogus', adrPattern: '../x{n}{slug}.md' })
- await loadAiPrefs(reload, host)
- expect(settingsOf(reload).ai).toMatchObject({ adrDir: '', adrStyle: 'auto', adrPattern: '' })
- })
-
- it('a named style and pattern shape what a new record is called and looks like', async () => {
- const w = await world('nygard', null)
-
- settingsOf(w.state).ai.adrStyle = 'ruflo'
- settingsOf(w.state).ai.adrPattern = 'ADR-{n}-{slug}.md'
- await loadAdrs(w.state, w.host as never)
- expect(adrOf(w.state).style).toMatchObject({ name: 'ruflo', pattern: 'ADR-{n}-{slug}.md', source: 'setting' })
- expect(attachedDocs).toBeTypeOf('function')
- })
-})
-
-void [mkdtempSync, tmpdir]
diff --git a/plugins/ruflo-console/tests/adr-mutation.spec.ts b/plugins/ruflo-console/tests/adr-mutation.spec.ts
new file mode 100644
index 0000000000..4b511d4627
--- /dev/null
+++ b/plugins/ruflo-console/tests/adr-mutation.spec.ts
@@ -0,0 +1,129 @@
+/**
+ * A mutation check on the pure ADR modules (ADR-480): each mutant is a one-line change to the parser, the lint, the scope matcher or the
+ * writer, written to a temporary copy beside the original and imported; the test passes only if a fixed battery sees the change. Run with
+ * npx vitest run plugins/ruflo-console/tests/adr-mutation.spec.ts
+ */
+import { readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+import { afterAll, describe, expect, it } from 'vitest'
+
+import { MAX_FILE } from '../hooks/data/adr'
+import type { AdrDoc } from '../hooks/data/adr'
+import type { filterDocs } from '../hooks/data/adr-lint'
+import type { checkScope, digestBlock, scopeHits, suggest } from '../hooks/data/adr-scope'
+import type { detectStyle, nextNumber, slugOf, withStatus } from '../hooks/data/adr-write'
+import type { indexOf, lint, parseAdr } from '../hooks/data/adr'
+import { FIXTURES, RUFLO_ADRS } from './adr-helpers'
+
+const HERE = dirname(fileURLToPath(import.meta.url))
+
+// ---------------------------------------------------------------------------------------------------------------- mutation check
+
+type Mod = Record<string, (...args: never[]) => unknown>
+
+/** What the pure modules say about a fixed battery: any change in a module's behaviour that the battery sees changes this string. */
+function signature(adr: Mod, scope: Mod, write: Mod, lintMod: Mod): string {
+ const parse = adr.parseAdr as unknown as (f: string, t: string) => AdrDoc
+ const index = adr.indexOf as unknown as typeof indexOf
+ const lintFn = lintMod.lint as unknown as typeof lint
+ const out: unknown[] = []
+ const real = readdirSync(RUFLO_ADRS).filter(f => /^ADR-.*\.md$/.test(f)).slice(0, 120).map(f => parse(f, readFileSync(join(RUFLO_ADRS, f), 'utf8')))
+ const fixtures: AdrDoc[] = []
+
+ for (const [name, folder] of [['madr', 'docs/decisions'], ['nygard', 'doc/adr'], ['ruflo-style', 'docs/adrs'], ['mixed', 'docs/architecture/decisions'], ['plain', 'adr'], ['log4brains', 'docs/adr']]) {
+ for (const f of readdirSync(join(FIXTURES, name as string, folder as string)).filter(file => file.endsWith('.md') && !/^readme/i.test(file))) fixtures.push(parse(f, readFileSync(join(FIXTURES, name as string, folder as string, f), 'utf8')))
+ }
+
+ out.push(real.map(d => [d.number, d.variant, d.status, d.date, d.scope.length, d.supersedes, d.supersededBy, d.relates, d.refs, d.decision.length, d.format]))
+ out.push(fixtures.map(d => [d.status, d.date, d.format, d.supersedes, d.supersededBy, d.refs, d.scope, d.title]))
+ out.push(lintFn(index([...real, ...fixtures]), real.map(d => d.file), 'ADR-001 ADR-002').map(f => `${f.code}:${f.file}`))
+ out.push(lintFn(index(fixtures.filter(d => d.file.startsWith('00'))), [], null).map(f => `${f.code}:${f.file}`))
+ out.push(parse('0001-x.md', `# 1. X\n\nStatus: Accepted\n\u001b[31m${'z'.repeat(MAX_FILE + 50)}`).notes)
+ out.push(parse('0001-x.md', '---\nstatus: accepted\ndate: 2024-12-31\n---\n\n# X\n').date)
+ out.push(parse('0001-x.md', '# X\n\nStatus: Accepted\u001b[2K bold\nDate: 2024-02-09\n').statusRaw)
+ out.push(parse('0001-x.md', '# X\n\n## Status\n\nSuperseded by [2. Y](0002-y.md)\n'))
+ out.push(parse('0001-x.md', `# X\n\n${'filler '.repeat(40_000)}\n\nStatus: Accepted\n`).status)
+ out.push(parse('ADR-376-x.md', '# ADR-376: X\n\n| Field | Value |\n|---|---|\n| Status | Proposed |\n').status)
+ out.push(lintFn(index([parse('0001-a.md', '# 1. A\n\nStatus: Accepted\nDate: 2020-01-01\nSupersedes: 2\n'), parse('0002-b.md', '# 2. B\n\nStatus: Accepted\nDate: 2020-01-01\nSupersedes: 1\n')]), []).map(f => `${f.level}:${f.code}`))
+
+ const hits = scope.checkScope as unknown as typeof checkScope
+ const hit = scope.scopeHits as unknown as typeof scopeHits
+ const block = scope.digestBlock as unknown as typeof digestBlock
+ const sug = scope.suggest as unknown as typeof suggest
+ const accepted = parse('0001-a.md', '# 1. Auth sessions\n\nStatus: Accepted\nDate: 2025-01-01\n\n## Decision\n\nUse sessions.\n')
+ const proposed = parse('0002-b.md', '# 2. Auth tokens\n\nStatus: Proposed\nDate: 2025-01-01\n')
+
+ accepted.scope = ['src/auth']
+ proposed.scope = ['src/auth']
+ out.push([hit('src/auth', 'src/auth/a.ts'), hit('src/auth', 'src/authz/a.ts'), hit('a/b.ts', 'x/a/b.ts'), hit('src/*.ts', 'src/deep/a.ts'), hit('docs', 'docs/x.md')])
+ out.push(hits(['src/auth/a.ts', 'src/other.ts'], [accepted, proposed]).hits.map(h => h.file))
+ out.push(block([accepted, proposed, ...Array.from({ length: 10 }, (_v, i) => ({ ...accepted, file: `00${i + 10}-z.md`, number: i + 10, decision: 'lorem ipsum '.repeat(40) }))]).length)
+ const history = { ...accepted, file: '0003-c.md', number: 3, status: 'superseded' as const }
+
+ out.push(sug('auth sessions src/auth/x.ts', [accepted, proposed, history]).map(s => s.doc.number))
+
+ const style = (write.detectStyle as unknown as typeof detectStyle)(fixtures.filter(d => d.file.startsWith('ADR-')))
+
+ out.push([style, (write.nextNumber as unknown as typeof nextNumber)(fixtures), (write.slugOf as unknown as typeof slugOf)('Use Postgres — for Storage!')])
+
+ const nygard = parse('0003-use-graphql.md', readFileSync(join(FIXTURES, 'nygard', 'doc/adr', '0003-use-graphql.md'), 'utf8'))
+ const edited = (write.withStatus as unknown as typeof withStatus)(readFileSync(join(FIXTURES, 'nygard', 'doc/adr', '0003-use-graphql.md'), 'utf8'), nygard, { name: 'nygard', width: 4, pattern: '{n}-{slug}.md', source: 'default' }, 'deprecated')
+
+ out.push(edited)
+
+ return JSON.stringify(out)
+}
+
+describe('mutation check: the battery notices a change in the parser, the lint, the scope matcher and the writer', () => {
+ const data = join(HERE, '..', 'hooks', 'data')
+ const made: string[] = []
+ const baseline = async () => signature((await import('../hooks/data/adr')) as never, (await import('../hooks/data/adr-scope')) as never, (await import('../hooks/data/adr-write')) as never, (await import('../hooks/data/adr-lint')) as never)
+
+ afterAll(() => {
+ for (const file of made) rmSync(file, { force: true })
+ })
+
+ const mutants: [string, string, string, string][] = [
+ ['adr', 'a superseded status read as deprecated', "if (/\\bsuperse?ded\\b|\\breplaced\\b|\\bobsolete/.test(text)) return 'superseded'", "if (/\\bsuperse?ded\\b|\\breplaced\\b|\\bobsolete/.test(text)) return 'deprecated'"],
+ ['adr', 'a one-digit month only', '(0?[1-9]|1[0-2])[-/. ](0?[1-9]|[12]\\d|3[01])', '(0?[1-9])[-/. ](0?[1-9]|[12]\\d|3[01])'],
+ ['adr-lint', 'A/B/C siblings counted as duplicates', 'other.variant === doc.variant', 'true'],
+ ['adr-lint', 'a supersedes with no file not reported', '!registry.byNumber.has(target)) add(\'warn\', \'dangling-supersedes\'', 'registry.byNumber.has(target)) add(\'warn\', \'dangling-supersedes\''],
+ ['adr', 'a Status section read as a status line', "return { raw: first ?? '', format: 'nygard', section }", "return { raw: first ?? '', format: 'inline', section }"],
+ ['adr', 'front matter never recognised', "if (!text.startsWith('---\\n')) return null", "if (!text.startsWith('--\\n')) return null"],
+ ['adr', 'escapes left in the text', ".replace(ESCAPES, '')", ''],
+ ['adr', 'no cap on a huge file', 'text = wash(source.length > MAX_FILE ? source.slice(0, MAX_FILE) : source)', 'text = wash(source)'],
+ ['adr', 'a table status not read', "const table = /^\\s*\\|\\s*\\**status\\**\\s*\\|\\s*(.+?)\\s*\\|?\\s*$/i.exec(line)", "const table = /^\\s*\\|\\s*\\**nostatus\\**\\s*\\|\\s*(.+?)\\s*\\|?\\s*$/i.exec(line)"],
+ ['adr-lint', 'a cycle not reported', "add('error', 'supersede-cycle'", "add('info', 'supersede-cycle'"],
+ ['adr-scope', 'a sibling that shares a prefix counted in scope', 'f.startsWith(`${e}/`)', 'f.startsWith(e)'],
+ ['adr-scope', 'a proposed ADR counted as in force', "attached.filter(doc => doc.status === 'accepted')", 'attached'],
+ ['adr-scope', 'no cap on the digest', 'if (used + line.length > DIGEST_TOTAL) break', ''],
+ ['adr-scope', 'a glob that crosses folders', "'[^/]*'", "'.*'"],
+ ['adr-scope', 'history offered as a suggestion', "(doc.status !== 'accepted' && doc.status !== 'proposed') || attached.includes(doc.file)", 'attached.includes(doc.file)'],
+ ['adr-write', 'the next number reuses the highest', "(high, doc) => Math.max(high, doc.number ?? 0), 0) + 1", "(high, doc) => Math.max(high, doc.number ?? 0), 0) + 0"],
+ ['adr-write', 'a status inserted instead of replaced', 'lines[first] = value', "lines.splice(first, 0, value)"],
+ ['adr-write', 'slugs keep their case', ' .toLowerCase()\n .normalize', ' .normalize'],
+ ['adr-write', 'the prefix is never detected', "/^adr[-_ ]/i.test(doc.file)", '/^zzz/i.test(doc.file)'],
+ ]
+
+ it('the unmutated battery is stable', async () => {
+ expect(await baseline()).toBe(await baseline())
+ })
+
+ it.each(mutants.map((m, i) => [i, m[1], m] as const))('mutant %i (%s) changes what the battery sees', async (index, _label, [module, , find, replace]) => {
+ const file = join(data, `${module}.ts`)
+ const source = readFileSync(file, 'utf8')
+
+ expect(source, `the mutation target must exist: ${find}`).toContain(find)
+
+ const path = join(data, `.mut-${index}-${module}.ts`)
+
+ writeFileSync(path, source.replace(find, replace))
+ made.push(path)
+
+ const mod = async (name: string) => (name === module ? await import(/* @vite-ignore */ path) : await import(`../hooks/data/${name}`)) as Mod
+
+ expect(signature(await mod('adr'), await mod('adr-scope'), await mod('adr-write'), await mod('adr-lint'))).not.toBe(await baseline())
+ })
+})
diff --git a/plugins/ruflo-console/tests/adr-page.spec.ts b/plugins/ruflo-console/tests/adr-page.spec.ts
new file mode 100644
index 0000000000..0b7ec1da92
--- /dev/null
+++ b/plugins/ruflo-console/tests/adr-page.spec.ts
@@ -0,0 +1,244 @@
+/**
+ * The ADRs page, the palette entries and the settings (ADR-480): the page in both looks and at three widths, every action a button with
+ * a key, the control level each palette entry needs, and the folder, style and pattern settings. Run with
+ * npx vitest run plugins/ruflo-console/tests/adr-page.spec.ts
+ */
+import { writeFileSync } from 'node:fs'
+
+import { afterAll, describe, expect, it } from 'vitest'
+
+import { adrOf, loadAdrs } from '../hooks/adr'
+import { adrActions } from '../hooks/adr-actions'
+import { setAttached } from '../hooks/adr-mission'
+import { adrPalette } from '../hooks/adr-palette'
+import { allows, classOf } from '../hooks/model-tools'
+import { NAV_GROUPS } from '../hooks/nav-state'
+import { paletteEntries } from '../hooks/palette'
+import { loadAiPrefs, saveAiPrefs, settingsOf } from '../hooks/settings'
+import { newState, VIEWS, type State } from '../hooks/state'
+import { adrsView } from '../hooks/views/adr'
+import { setLook, type Actions } from '../hooks/views/common'
+import { viewText } from '../hooks/views/pane'
+import { join } from 'node:path'
+import { cleanAfter } from './adr-helpers'
+import { world } from './adr-world'
+
+cleanAfter()
+afterAll(() => setLook('plain'))
+
+describe('the page', () => {
+ const noAct = new Proxy(() => undefined, { get: (_t, key) => (key === 'then' ? undefined : noAct), apply: () => undefined }) as unknown as Actions
+ const draw = (state: State, columns = 110) => viewText({ state, nowMs: Date.now(), columns, act: noAct }, 'adrs')
+
+ it('is in the TOOLS group, has no hotkey, and says it is reading before the folder is read', () => {
+ const state = newState({})
+
+ expect(NAV_GROUPS.find(group => group.title === 'TOOLS')?.rows.flat()).toContain('adrs')
+ expect(VIEWS.find(view => view.id === 'adrs')).toMatchObject({ key: '', label: 'ADRs' })
+ expect(draw(state)).toContain('not read yet')
+ })
+
+ it('a project with no ADR folder offers to initialise it, and points at Settings', async () => {
+ const w = await world('empty', null)
+ const text = draw(w.state)
+
+ expect(text).toContain('no ADR folder found')
+ expect(text).toContain('initialise ADRs here')
+ expect(text).toContain('Nothing is overwritten')
+ expect(text).toContain('Settings')
+ })
+
+ it('lists records with status and date, the health strip, the filters and the honest limits', async () => {
+ const w = await world('madr')
+ const text = draw(w.state)
+
+ expect(text).toContain('docs/decisions')
+ expect(text).toContain('madr')
+ expect(text).toContain('3 records · 2 accepted · 0 proposed · 1 superseded')
+ expect(text).toContain('0003')
+ expect(text).toContain('Use Cockroach for storage')
+ expect(text).toContain('health: 0 errors')
+ expect(text).toContain('compares file PATHS')
+ expect(text).toContain('nothing here proves a change follows or breaks a decision')
+ })
+
+ it('a selected record shows its links both ways, its decision and the mission it is attached to', async () => {
+ const w = await world('nygard')
+
+ await setAttached(w.state, w.host as never, '0003-use-graphql.md', true)
+ adrOf(w.state).selected = '0002-use-rest.md'
+
+ const rest = draw(w.state)
+
+ expect(rest).toContain('ADR 2: Use REST for the public API')
+ expect(rest).toContain('superseded by')
+ expect(rest).toContain('cited by ADRs')
+
+ adrOf(w.state).selected = '0003-use-graphql.md'
+
+ const graph = draw(w.state)
+
+ expect(graph).toContain('supersedes')
+ expect(graph).toContain('cited by missions msn_aaaaaaa')
+ expect(graph).toContain('Decision: GraphQL')
+ expect(graph).toContain('− detach from mission')
+ })
+
+ it('draws in both looks and at narrow and wide widths, with hostile titles, without an escape reaching the screen', async () => {
+ const w = await world('plain')
+
+ writeFileSync(join(w.root, 'adr/0001-evil.md'), '# 1. Evil\u001b[31m title ‮ <b>x</b>\n\nStatus: Accepted\u001b[2J\n')
+ await loadAdrs(w.state, w.host as never)
+
+ for (const look of ['plain', 'bbs'] as const) {
+ setLook(look)
+
+ for (const columns of [44, 80, 140]) {
+ const text = draw(w.state, columns)
+
+ expect(text, `${look} ${columns}`).toContain('ADR')
+ expect(text, `${look} ${columns}`).not.toMatch(/[\u001b‮]/)
+ }
+ }
+
+ setLook('plain')
+ })
+
+ it('every action is a button with a key, pressing reaches the action, and the list pages by j and k', async () => {
+ const w = await world('madr')
+ const calls: string[] = []
+ const recorder = (path: string): unknown => new Proxy(() => undefined, { get: (_t, key) => (key === 'then' ? undefined : recorder(`${path}.${String(key)}`)), apply: (_t, _this, args) => void calls.push(`${path.slice(1)}(${args.join(',')})`) })
+ type El = { props: Record<string, unknown> }
+ const kit = { Box: (props: Record<string, unknown>): El => ({ props }), Text: (props: Record<string, unknown>): El => ({ props }), Button: (props: Record<string, unknown>): El => ({ props }), Input: (props: Record<string, unknown>): El => ({ props }) }
+ const flat = (el: unknown): El[] => {
+ const node = el as El
+
+ if (typeof node !== 'object' || node === null) return []
+
+ const kids = node.props?.children
+
+ return [node, ...(Array.isArray(kids) ? kids.flatMap(flat) : typeof kids === 'object' ? flat(kids) : [])]
+ }
+
+ adrOf(w.state).selected = '0002-use-postgres.md'
+
+ const tree = adrsView({ kit, state: w.state, nowMs: Date.now(), columns: 120, pictures: new Map(), act: recorder('') as never, cards: true } as never)
+ const nodes = flat(tree)
+ const by = (key: string) => nodes.find(node => node.props.key === key)
+
+ ;(by('adr-row-0003-use-cockroach.md')?.props.onPress as () => void)()
+ ;(by('adr-to-accepted') ?? by('adr-f-accepted'))?.props.onPress
+ ;(by('adr-f-accepted')?.props.onPress as () => void)()
+ ;(by('adr-reload')?.props.onPress as () => void)()
+ ;(by('adr-filter')?.props.onSubmit as (v: string) => void)('cockroach')
+ ;(by('adr-propose')?.props.onSubmit as (v: string) => void)('Cache reads')
+ ;(by('adr-prev')?.props.onPress as () => void)()
+
+ expect(by('adr-prev')?.props.hotkey).toBe('k')
+ expect(by('adr-next')?.props.hotkey).toBe('j')
+ expect(calls).toEqual(['adrs.select(0003-use-cockroach.md)', 'adrs.filter([object Object])', 'adrs.reload()', 'adrs.filter([object Object])', 'adrs.propose(Cache reads)', 'adrs.page(0)'])
+ // Mouse and keyboard parity: every pressable here is a Button (focusable, Enter and click alike), and the fields are Inputs.
+ expect(nodes.filter(node => typeof node.props.onPress === 'function').length).toBeGreaterThan(8)
+ })
+})
+
+describe('the palette and the control level', () => {
+ async function wired() {
+ const w = await world('nygard')
+ const asked: unknown[] = []
+ const actions = adrActions(w.state, w.host as never, { ask: (spec: unknown) => void asked.push(spec) } as never)
+
+ return { ...w, actions, asked }
+ }
+
+ it('has an entry for each action, in the palette headless runs use', async () => {
+ const w = await wired()
+ const ids = adrPalette(w.state).map(entry => entry.id)
+
+ expect(ids).toEqual(['adr-open', 'adr-show', 'adr-init', 'adr-propose', 'adr-accept', 'adr-reject', 'adr-deprecate', 'adr-supersede', 'adr-attach', 'adr-detach', 'adr-scope'])
+ expect(paletteEntries(w.state, Date.now()).filter(entry => entry.id.startsWith('adr-')).map(entry => entry.id)).toEqual(ids)
+ })
+
+ it('reading is read level; proposing, initialising, changing a status and attaching are write level, never network, spend or delete', async () => {
+ const w = await wired()
+ const entry = (id: string) => adrPalette(w.state).find(candidate => candidate.id === id)
+ const specOf = (id: string, text = '') => {
+ const run = entry(id)?.run
+
+ return run?.kind === 'spec' ? run.spec : run?.kind === 'text' ? run.make(text) : null
+ }
+ const pending = (spec: NonNullable<ReturnType<typeof specOf>>) => ({ label: spec.label, args: spec.args, ...(spec.note !== undefined && { note: spec.note }), ...(spec.shows !== undefined && { shows: spec.shows }), expect: spec.expect, ...(spec.declared !== undefined && { declared: spec.declared }) })
+ const classes: Record<string, string> = {}
+
+ for (const [id, text] of [['adr-show', '3'], ['adr-propose', 'Cache reads'], ['adr-accept', '3'], ['adr-reject', '3'], ['adr-deprecate', '3'], ['adr-supersede', '1 3'], ['adr-attach', '3'], ['adr-detach', '3'], ['adr-scope', '']] as const) {
+ const spec = specOf(id, text)
+
+ expect(spec, id).not.toBeNull()
+ classes[id] = classOf(pending(spec as never))
+ }
+
+ expect(Object.fromEntries(Object.entries(classes).filter(([id]) => id !== 'adr-show' && id !== 'adr-scope'))).toEqual({ 'adr-propose': 'write', 'adr-accept': 'write', 'adr-reject': 'write', 'adr-deprecate': 'write', 'adr-supersede': 'write', 'adr-attach': 'write', 'adr-detach': 'write' })
+ // Reading goes through the same gate as any entry that declares nothing: it is a read-only spec, which runs at the read level without a pending card.
+ expect(specOf('adr-show', '3')?.isReadOnly).toBe(true)
+ expect(specOf('adr-show', '3')?.declared).toBeUndefined()
+ expect(specOf('adr-scope')?.declared).toBeUndefined()
+ expect(entry('adr-open')?.run).toEqual({ kind: 'view', view: 'adrs' })
+
+ for (const id of ['adr-propose', 'adr-accept', 'adr-reject', 'adr-deprecate', 'adr-supersede', 'adr-attach', 'adr-detach']) {
+ const spec = specOf(id, id === 'adr-propose' ? 'Cache reads' : id === 'adr-supersede' ? '1 3' : '3')
+
+ expect(spec?.declared, id).toBe('write')
+ expect(allows('read', classOf(pending(spec as never))), `${id} at read`).toBe(false)
+ expect(allows('write', classOf(pending(spec as never))), `${id} at write`).toBe(true)
+ }
+ })
+
+ it('a status entry only prepares the change: the diff is a second confirm, and a bad number is no spec', async () => {
+ const w = await wired()
+ const accept = adrPalette(w.state).find(entry => entry.id === 'adr-deprecate')?.run
+
+ expect(accept?.kind === 'text' && accept.make('999')).toBeNull()
+ expect(accept?.kind === 'text' && accept.make('ADR-0003')).not.toBeNull()
+ ;(accept?.kind === 'text' ? accept.make('3') : null)?.run?.()
+ await new Promise(resolve => setTimeout(resolve, 100))
+
+ const second = w.asked[0] as { shows: string; label: string } | undefined
+
+ expect(second?.label).toBe('mark ADR 3 deprecated')
+ expect(second?.shows).toContain('-Accepted')
+ expect(second?.shows).toContain('+Deprecated')
+ })
+})
+
+describe('the settings', () => {
+ it('keep a safe folder, a style and a pattern, and refuse an unsafe folder or pattern with a reason', async () => {
+ const w = await world('nygard', null)
+ const host = w.host as never
+
+ saveAiPrefs(w.state, host, { adrDir: 'notes/decisions', adrStyle: 'madr', adrPattern: 'ADR-{n}-{slug}.md' })
+ expect(settingsOf(w.state).ai).toMatchObject({ adrDir: 'notes/decisions', adrStyle: 'madr', adrPattern: 'ADR-{n}-{slug}.md' })
+ saveAiPrefs(w.state, host, { adrDir: '../outside' })
+ expect(settingsOf(w.state).ai.adrDir).toBe('notes/decisions')
+ expect(w.state.outcome?.ok).toBe(false)
+ expect(w.state.outcome?.detail).toContain('inside this project')
+ saveAiPrefs(w.state, host, { adrPattern: '{n}.md' })
+ expect(settingsOf(w.state).ai.adrPattern).toBe('ADR-{n}-{slug}.md')
+ expect(w.state.outcome?.detail).toContain('{n} and {slug}')
+
+ const reload = newState({})
+
+ await w.host.storeSet('ai-prefs', { adrDir: '../evil', adrStyle: 'bogus', adrPattern: '../x{n}{slug}.md' })
+ await loadAiPrefs(reload, host)
+ expect(settingsOf(reload).ai).toMatchObject({ adrDir: '', adrStyle: 'auto', adrPattern: '' })
+ })
+
+ it('a named style and pattern shape what a new record is called and looks like', async () => {
+ const w = await world('nygard', null)
+
+ settingsOf(w.state).ai.adrStyle = 'ruflo'
+ settingsOf(w.state).ai.adrPattern = 'ADR-{n}-{slug}.md'
+ await loadAdrs(w.state, w.host as never)
+ expect(adrOf(w.state).style).toMatchObject({ name: 'ruflo', pattern: 'ADR-{n}-{slug}.md', source: 'setting' })
+ })
+})
+
diff --git a/plugins/ruflo-console/tests/adr-world.ts b/plugins/ruflo-console/tests/adr-world.ts
new file mode 100644
index 0000000000..d0c63aa2ca
--- /dev/null
+++ b/plugins/ruflo-console/tests/adr-world.ts
@@ -0,0 +1,32 @@
+/** A project copy with a console state, a host over real files, and an active mission: the setup the ADR integration specs share (ADR-480). */
+import { loadAdrs } from '../hooks/adr'
+import { mcOf } from '../hooks/mission-control'
+import type { MissionRecord } from '../hooks/mission-types'
+import { newState } from '../hooks/state'
+import { hostOfRoot, project } from './adr-helpers'
+
+export const TASK = { id: 't1', title: 'Move sessions', phase: 'refinement', agent: 'coder', requirement: 'sessions live in the new store', dependsOn: [] }
+export const missionOf = (patch: Partial<MissionRecord> = {}): MissionRecord => ({ id: 'msn_aaaaaaaaaaaaaaaaaaaaaaaa', objective: 'Move the graphql api sessions in api/public', profile: 'feature', rigor: 'standard', tasks: [TASK], acceptance: [{ id: 'a1', check: 'tests pass' }], events: [], paused: false, cancelled: false, auto: false, createdAtMs: Date.now() - 3_600_000, ...patch })
+
+export async function world(name: string, mission: Partial<MissionRecord> | null = {}) {
+ const root = project(name)
+
+ const state = newState({})
+ const hosted = hostOfRoot(root)
+ const stored = new Map<string, unknown>()
+ const host = { ...hosted.host, storeSet: async (key: string, value: unknown) => void stored.set(key, value), storeGet: async (key: string) => stored.get(key) }
+
+ state.cwd = root
+ state.isInteractive = true
+
+ if (mission !== null) {
+ const record = missionOf(mission)
+
+ mcOf(state).missions.set(record.id, record)
+ mcOf(state).active = record.id
+ }
+
+ await loadAdrs(state, host as never)
+
+ return { root, state, host, stored, log: hosted.log, mission: mission === null ? null : (mcOf(state).missions.get('msn_aaaaaaaaaaaaaaaaaaaaaaaa') as MissionRecord) }
+}
diff --git a/plugins/ruflo-console/tests/adr-write.spec.ts b/plugins/ruflo-console/tests/adr-write.spec.ts
new file mode 100644
index 0000000000..d2fa318a3e
--- /dev/null
+++ b/plugins/ruflo-console/tests/adr-write.spec.ts
@@ -0,0 +1,241 @@
+/**
+ * Finding the ADR folder of the project the console runs in, and writing there (ADR-480): initialise, propose in each style, status changes
+ * and supersession with the exact diff, races, links and hostile titles, all in temp copies of the fixture projects. Run with
+ * npx vitest run plugins/ruflo-console/tests/adr-write.spec.ts
+ */
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+import { describe, expect, it } from 'vitest'
+
+import { lint, parseAdr, type AdrDoc } from '../hooks/data/adr'
+import { fsOfRoot, hostOfRoot, cleanAfter, keep, loaded, project, stateAt, TODAY } from './adr-helpers'
+import { adrOf, discover, initSpec, loadAdrs, planStatus, proposeSpec, statusSpec } from '../hooks/adr'
+
+cleanAfter()
+
+describe('finding the ADR folder of the project the console runs in', () => {
+ it.each([
+ ['madr', 'docs/decisions', 3],
+ ['nygard', 'doc/adr', 3],
+ ['ruflo-style', 'docs/adrs', 2],
+ ['log4brains', 'docs/adr', 1],
+ ['plain', 'adr', 1],
+ ['mixed', 'docs/architecture/decisions', 4],
+ ])('%s: %s', async (name, folder, count) => {
+ const { state } = await loaded(name)
+
+ expect(adrOf(state).dir).toBe(folder)
+ expect(adrOf(state).registry.docs).toHaveLength(count)
+ })
+
+ it('a project with no ADR folder says so and offers to initialise; a named folder is tried alone', async () => {
+ const { state, root } = await loaded('empty')
+
+ expect(adrOf(state).dir).toBeNull()
+ expect(adrOf(state).why).toContain('no ADR folder found')
+ expect((await discover({ fs: fsOfRoot(root) } as never, root, 'docs/nowhere')).why).toBe('no folder docs/nowhere in this project')
+ expect((await discover({ fs: fsOfRoot(root) } as never, root, '../x')).dir).toBeNull()
+ })
+
+ it('a folder that is a link out of the project is never read, nor are links inside the folder', async () => {
+ const root = project('madr')
+ const outside = mkdtempSync(join(tmpdir(), 'adr-outside-'))
+
+ keep(outside)
+ writeFileSync(join(outside, '0001-secret.md'), '# 1. Secret\n\nStatus: Accepted\n')
+ rmSync(join(root, 'docs/decisions'), { recursive: true })
+ symlinkSync(outside, join(root, 'docs/decisions'))
+
+ const state = stateAt(root)
+
+ await loadAdrs(state, hostOfRoot(root).host as never)
+ expect(adrOf(state).dir).toBeNull()
+ expect(adrOf(state).why).toContain('is a link')
+ expect(adrOf(state).registry.docs).toEqual([])
+
+ const second = project('madr')
+
+ symlinkSync(join(outside, '0001-secret.md'), join(second, 'docs/decisions/0009-link.md'))
+
+ const next = stateAt(second)
+
+ await loadAdrs(next, hostOfRoot(second).host as never)
+ expect(adrOf(next).registry.docs.map(d => d.file)).not.toContain('0009-link.md')
+ expect(adrOf(next).registry.docs).toHaveLength(3)
+ })
+
+ it('a setting names the folder; a link above the project root is not followed', async () => {
+ const root = project('empty')
+
+ mkdirSync(join(root, 'notes/decisions'), { recursive: true })
+ writeFileSync(join(root, 'notes/decisions/0001-x.md'), '# 1. X\n\nStatus: Accepted\nDate: 2020-01-01\n')
+
+ const state = stateAt(root)
+
+ state.cwd = root
+
+ const found = await discover({ fs: fsOfRoot(root) } as never, root, 'notes/decisions')
+
+ expect(found.dir).toBe('notes/decisions')
+ })
+})
+
+describe('writing, in a copy of each project', () => {
+ const today = TODAY
+
+ it('initialise creates the folder and the first record once, shows its exact path, and never overwrites', async () => {
+ const { root, state, world } = await loaded('empty')
+ const spec = initSpec(state, world.host as never, today)
+
+ expect(spec?.label).toContain('docs/adr/0001-record-architecture-decisions.md')
+ expect(spec?.shows).toContain('create docs/adr/0001-record-architecture-decisions.md')
+ expect(existsSync(join(root, 'docs'))).toBe(false)
+ await spec?.run?.()
+ expect(readFileSync(join(root, 'docs/adr/0001-record-architecture-decisions.md'), 'utf8')).toContain('## Status\n\nAccepted')
+ expect(adrOf(state).dir).toBe('docs/adr')
+ expect(initSpec(state, world.host as never, today)).toBeNull()
+ expect(world.log.toasts).toHaveLength(1)
+ expect(world.log.toasts[0]).toMatchObject({ level: 'info' })
+ expect(state.events.filter(event => event.kind === 'notices' && event.text.startsWith('adr:'))).toHaveLength(1)
+ })
+
+ it('initialise races a file that appears first: nothing is overwritten', async () => {
+ const { root, state, world } = await loaded('empty')
+ const spec = initSpec(state, world.host as never, today)
+
+ mkdirSync(join(root, 'docs/adr'), { recursive: true })
+ writeFileSync(join(root, 'docs/adr/0001-record-architecture-decisions.md'), 'MINE')
+ await spec?.run?.()
+ expect(readFileSync(join(root, 'docs/adr/0001-record-architecture-decisions.md'), 'utf8')).toBe('MINE')
+ expect(adrOf(state).last?.ok).toBe(false)
+ expect(world.log.toasts).toEqual([])
+ })
+
+ it.each([
+ ['madr', 'docs/decisions', '0004-cache-reads.md', 'status: proposed'],
+ ['nygard', 'doc/adr', '0004-cache-reads.md', '## Status\n\nProposed'],
+ ['ruflo-style', 'docs/adrs', 'ADR-003-cache-reads.md', '**Status**: Proposed'],
+ ['mixed', 'docs/architecture/decisions', '0005-cache-reads.md', 'Proposed'],
+ ])('propose in %s takes the next number and the project’s file name and headings, and refuses an existing file', async (name, folder, file, marker) => {
+ const { root, state, world } = await loaded(name)
+ const spec = proposeSpec(state, world.host as never, 'Cache reads', today)
+
+ expect(spec?.shows).toContain(`create ${folder}/${file}`)
+ expect(existsSync(join(root, folder, file))).toBe(false)
+ await spec?.run?.()
+
+ const text = readFileSync(join(root, folder, file), 'utf8')
+
+ expect(text).toContain(marker)
+ expect(parseAdr(file, text)).toMatchObject({ status: 'proposed', title: 'Cache reads', date: today })
+ expect(adrOf(state).selected).toBe(file)
+ expect(world.log.toasts).toHaveLength(1)
+
+ // A second proposal with the same title takes the next number, and a record that appears in between is not overwritten.
+ const again = proposeSpec(state, world.host as never, 'Cache reads', today)
+ const target = /create (\S+)/.exec(again?.shows ?? '')?.[1] as string
+
+ writeFileSync(join(root, target), 'MINE')
+ await again?.run?.()
+ expect(readFileSync(join(root, target), 'utf8')).toBe('MINE')
+ })
+
+ it('propose with a hostile title cannot leave the folder or inject a heading, and an empty title is refused', async () => {
+ const { root, state, world } = await loaded('nygard')
+
+ expect(proposeSpec(state, world.host as never, ' ', today)).toBeNull()
+
+ const spec = proposeSpec(state, world.host as never, '../../etc/passwd\n## Status\n\nAccepted [x](y) `z`', today)
+
+ await spec?.run?.()
+
+ const written = readdirSync(join(root, 'doc/adr')).filter(f => f.startsWith('0004'))
+
+ expect(written).toHaveLength(1)
+ expect(written[0]).toMatch(/^0004-[a-z0-9-]+\.md$/)
+
+ const text = readFileSync(join(root, 'doc/adr', written[0] as string), 'utf8')
+
+ expect(text.match(/^## Status$/gm)).toHaveLength(1)
+ expect(parseAdr(written[0] as string, text).status).toBe('proposed')
+ expect(existsSync(join(root, 'etc'))).toBe(false)
+ })
+
+ it('a transition writes exactly the confirmed diff and nothing else, then re-reads', async () => {
+ const { root, state, world } = await loaded('ruflo-style')
+ const doc = adrOf(state).registry.docs[1] as AdrDoc
+ const before = readFileSync(join(root, 'docs/adrs', doc.file), 'utf8')
+ const spec = await statusSpec(state, world.host as never, doc, 'accepted')
+
+ expect(spec?.label).toBe('mark ADR 2 accepted')
+ expect(spec?.shows).toContain('-Status: Proposed (2025-02-01)')
+ expect(spec?.shows).toContain('+Status: Accepted')
+ expect(readFileSync(join(root, 'docs/adrs', doc.file), 'utf8')).toBe(before)
+ await spec?.run?.()
+
+ const after = readFileSync(join(root, 'docs/adrs', doc.file), 'utf8')
+
+ expect(after).toBe(before.replace('Status: Proposed (2025-02-01)', 'Status: Accepted'))
+ expect(adrOf(state).registry.docs[1]?.status).toBe('accepted')
+ expect(world.log.toasts).toHaveLength(1)
+ })
+
+ it('a file that changed since the diff was shown is left alone', async () => {
+ const { root, state, world } = await loaded('ruflo-style')
+ const doc = adrOf(state).registry.docs[1] as AdrDoc
+ const spec = await statusSpec(state, world.host as never, doc, 'accepted')
+
+ writeFileSync(join(root, 'docs/adrs', doc.file), 'someone else edited this')
+ await spec?.run?.()
+ expect(readFileSync(join(root, 'docs/adrs', doc.file), 'utf8')).toBe('someone else edited this')
+ expect(adrOf(state).last).toMatchObject({ ok: false })
+ expect(adrOf(state).last?.lines.join(' ')).toContain('changed since the diff was shown')
+ expect(world.log.toasts).toEqual([])
+ })
+
+ it('supersede edits both files with their own diffs, and a refused change says why', async () => {
+ const { root, state, world } = await loaded('nygard')
+ const docs = adrOf(state).registry.docs
+ const accepted = docs[0] as AdrDoc
+ const created = proposeSpec(state, world.host as never, 'Use gRPC', today)
+
+ await created?.run?.()
+
+ const newer = adrOf(state).registry.docs.find(doc => doc.number === 4) as AdrDoc
+
+ expect(await planStatus(state, world.host as never, accepted, 'superseded', null)).toMatchObject({ ok: false })
+ expect(await planStatus(state, world.host as never, accepted, 'accepted', null)).toMatchObject({ ok: false, why: 'it is already accepted' })
+ expect(await planStatus(state, world.host as never, accepted, 'rejected', null)).toMatchObject({ ok: false })
+
+ const spec = await statusSpec(state, world.host as never, accepted, 'superseded', newer)
+
+ expect(spec?.expect).toContain(accepted.file)
+ expect(spec?.expect).toContain(newer.file)
+ await spec?.run?.()
+ expect(readFileSync(join(root, 'doc/adr', accepted.file), 'utf8')).toContain('Superseded by [4. Use gRPC](0004-use-grpc.md)')
+ expect(readFileSync(join(root, 'doc/adr', newer.file), 'utf8')).toContain('Supersedes [1. Record architecture decisions]')
+ expect(adrOf(state).registry.docs.find(doc => doc.number === 1)?.status).toBe('superseded')
+ expect(lint(adrOf(state).registry, adrOf(state).files).filter(f => f.code === 'supersede-mismatch' || f.code === 'dangling-supersedes')).toEqual([])
+ })
+
+ it('a record that is a link is never written through', async () => {
+ const { root, state, world } = await loaded('nygard')
+ const target = join(root, 'doc/adr', '0003-use-graphql.md')
+ const outside = mkdtempSync(join(tmpdir(), 'adr-outside-'))
+
+ keep(outside)
+
+ const doc = adrOf(state).registry.docs[2] as AdrDoc
+ const spec = await statusSpec(state, world.host as never, doc, 'deprecated')
+
+ writeFileSync(join(outside, 'x.md'), readFileSync(target, 'utf8'))
+ unlinkSync(target)
+ symlinkSync(join(outside, 'x.md'), target)
+ await spec?.run?.()
+ expect(readFileSync(join(outside, 'x.md'), 'utf8')).toContain('Accepted')
+ expect(readFileSync(join(outside, 'x.md'), 'utf8')).not.toContain('Deprecated')
+ expect(adrOf(state).last?.lines.join(' ')).toContain('link')
+ })
+})
diff --git a/plugins/ruflo-console/tests/adr.spec.ts b/plugins/ruflo-console/tests/adr.spec.ts
index cd962ef068..376d6dad22 100644
--- a/plugins/ruflo-console/tests/adr.spec.ts
+++ b/plugins/ruflo-console/tests/adr.spec.ts
@@ -1,63 +1,18 @@
/**
- * The ADR registry (ADR-480): the parser and lint over the conventions real projects use, the style detection and the writes, the mission
- * digest and the scope matcher, with hostile files and a mutation check on the three pure modules. The fixture projects are in
- * tests/fixtures/adr-projects (MADR, Nygard / adr-tools, ruflo style, log4brains, plain, mixed, empty); ruflo's own ADRs are one more set.
- * Run with
+ * The ADR registry (ADR-480): the parser and lint over the conventions real projects use, the style detection and the records written
+ * (pure), the digest and the scope matcher, with hostile files. The fixture projects are in tests/fixtures/adr-projects (MADR, Nygard /
+ * adr-tools, ruflo style, log4brains, plain, mixed, empty); ruflo's own ADRs are one more set. Run with
* npx vitest run plugins/ruflo-console/tests/adr.spec.ts
*/
-import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { dirname, join } from 'node:path'
-import { fileURLToPath } from 'node:url'
+import { readdirSync, readFileSync } from 'node:fs'
+import { join } from 'node:path'
-import { afterAll, describe, expect, it } from 'vitest'
+import { describe, expect, it } from 'vitest'
import { filterDocs, graphOf, indexOf, lint, MAX_FILE, parseAdr, type AdrDoc } from '../hooks/data/adr'
import { checkScope, digestBlock, reportLines, scopeHits, suggest } from '../hooks/data/adr-scope'
import { adrDirText, detectStyle, draftFromMission, fileNameFor, initialRecord, lineDiff, nextNumber, patternOf, renderNew, slugOf, withStatus, withSupersedes } from '../hooks/data/adr-write'
-import { adrOf, discover, loadAdrs, statusSpec, planStatus, initSpec, proposeSpec } from '../hooks/adr'
-import { newState, type State } from '../hooks/state'
-import { fsOfRoot, hostOfRoot, tempProject } from './adr-helpers'
-
-const HERE = dirname(fileURLToPath(import.meta.url))
-const FIXTURES = join(HERE, 'fixtures', 'adr-projects')
-const RUFLO_ADRS = join(HERE, '..', '..', '..', 'v3', 'docs', 'adr')
-const TODAY = '2026-10-07'
-
-const cleanups: string[] = []
-
-afterAll(() => {
- for (const dir of cleanups) rmSync(dir, { recursive: true, force: true })
-})
-
-const project = (name: string): string => {
- const dir = tempProject(FIXTURES, name)
-
- cleanups.push(dir)
-
- return dir
-}
-
-const stateAt = (root: string): State => {
- const state = newState({})
-
- state.cwd = root
- state.isInteractive = true
-
- return state
-}
-
-const loaded = async (name: string) => {
- const root = project(name)
- const state = stateAt(root)
- const world = hostOfRoot(root)
-
- await loadAdrs(state, world.host as never)
-
- return { root, state, world }
-}
-
-const docsOf = (name: string, folder: string): AdrDoc[] => readdirSync(join(FIXTURES, name, folder)).filter(f => f.endsWith('.md') && !/^readme/i.test(f)).sort().map(f => parseAdr(f, readFileSync(join(FIXTURES, name, folder, f), 'utf8')))
+import { docsOf, FIXTURES, RUFLO_ADRS, TODAY } from './adr-helpers'
describe('the conventions of real projects', () => {
it('reads MADR front matter: status, date, a superseded-by status and a supersedes field', () => {
@@ -405,339 +360,3 @@ describe('the digest, the suggestion and the scope check', () => {
expect(suggest('fix src/auth/login.ts bug', docs)[0]?.why).toContain('src/auth/login.ts')
})
})
-
-describe('finding the ADR folder of the project the console runs in', () => {
- it.each([
- ['madr', 'docs/decisions', 3],
- ['nygard', 'doc/adr', 3],
- ['ruflo-style', 'docs/adrs', 2],
- ['log4brains', 'docs/adr', 1],
- ['plain', 'adr', 1],
- ['mixed', 'docs/architecture/decisions', 4],
- ])('%s: %s', async (name, folder, count) => {
- const { state } = await loaded(name)
-
- expect(adrOf(state).dir).toBe(folder)
- expect(adrOf(state).registry.docs).toHaveLength(count)
- })
-
- it('a project with no ADR folder says so and offers to initialise; a named folder is tried alone', async () => {
- const { state, root } = await loaded('empty')
-
- expect(adrOf(state).dir).toBeNull()
- expect(adrOf(state).why).toContain('no ADR folder found')
- expect((await discover({ fs: fsOfRoot(root) } as never, root, 'docs/nowhere')).why).toBe('no folder docs/nowhere in this project')
- expect((await discover({ fs: fsOfRoot(root) } as never, root, '../x')).dir).toBeNull()
- })
-
- it('a folder that is a link out of the project is never read, nor are links inside the folder', async () => {
- const root = project('madr')
- const outside = mkdtempSync(join(tmpdir(), 'adr-outside-'))
-
- cleanups.push(outside)
- writeFileSync(join(outside, '0001-secret.md'), '# 1. Secret\n\nStatus: Accepted\n')
- rmSync(join(root, 'docs/decisions'), { recursive: true })
- symlinkSync(outside, join(root, 'docs/decisions'))
-
- const state = stateAt(root)
-
- await loadAdrs(state, hostOfRoot(root).host as never)
- expect(adrOf(state).dir).toBeNull()
- expect(adrOf(state).why).toContain('is a link')
- expect(adrOf(state).registry.docs).toEqual([])
-
- const second = project('madr')
-
- symlinkSync(join(outside, '0001-secret.md'), join(second, 'docs/decisions/0009-link.md'))
-
- const next = stateAt(second)
-
- await loadAdrs(next, hostOfRoot(second).host as never)
- expect(adrOf(next).registry.docs.map(d => d.file)).not.toContain('0009-link.md')
- expect(adrOf(next).registry.docs).toHaveLength(3)
- })
-
- it('a setting names the folder; a link above the project root is not followed', async () => {
- const root = project('empty')
-
- mkdirSync(join(root, 'notes/decisions'), { recursive: true })
- writeFileSync(join(root, 'notes/decisions/0001-x.md'), '# 1. X\n\nStatus: Accepted\nDate: 2020-01-01\n')
-
- const state = stateAt(root)
-
- state.cwd = root
-
- const found = await discover({ fs: fsOfRoot(root) } as never, root, 'notes/decisions')
-
- expect(found.dir).toBe('notes/decisions')
- })
-})
-
-describe('writing, in a copy of each project', () => {
- const today = TODAY
-
- it('initialise creates the folder and the first record once, shows its exact path, and never overwrites', async () => {
- const { root, state, world } = await loaded('empty')
- const spec = initSpec(state, world.host as never, today)
-
- expect(spec?.label).toContain('docs/adr/0001-record-architecture-decisions.md')
- expect(spec?.shows).toContain('create docs/adr/0001-record-architecture-decisions.md')
- expect(existsSync(join(root, 'docs'))).toBe(false)
- await spec?.run?.()
- expect(readFileSync(join(root, 'docs/adr/0001-record-architecture-decisions.md'), 'utf8')).toContain('## Status\n\nAccepted')
- expect(adrOf(state).dir).toBe('docs/adr')
- expect(initSpec(state, world.host as never, today)).toBeNull()
- expect(world.log.toasts).toHaveLength(1)
- expect(world.log.toasts[0]).toMatchObject({ level: 'info' })
- expect(state.events.filter(event => event.kind === 'notices' && event.text.startsWith('adr:'))).toHaveLength(1)
- })
-
- it('initialise races a file that appears first: nothing is overwritten', async () => {
- const { root, state, world } = await loaded('empty')
- const spec = initSpec(state, world.host as never, today)
-
- mkdirSync(join(root, 'docs/adr'), { recursive: true })
- writeFileSync(join(root, 'docs/adr/0001-record-architecture-decisions.md'), 'MINE')
- await spec?.run?.()
- expect(readFileSync(join(root, 'docs/adr/0001-record-architecture-decisions.md'), 'utf8')).toBe('MINE')
- expect(adrOf(state).last?.ok).toBe(false)
- expect(world.log.toasts).toEqual([])
- })
-
- it.each([
- ['madr', 'docs/decisions', '0004-cache-reads.md', 'status: proposed'],
- ['nygard', 'doc/adr', '0004-cache-reads.md', '## Status\n\nProposed'],
- ['ruflo-style', 'docs/adrs', 'ADR-003-cache-reads.md', '**Status**: Proposed'],
- ['mixed', 'docs/architecture/decisions', '0005-cache-reads.md', 'Proposed'],
- ])('propose in %s takes the next number and the project’s file name and headings, and refuses an existing file', async (name, folder, file, marker) => {
- const { root, state, world } = await loaded(name)
- const spec = proposeSpec(state, world.host as never, 'Cache reads', today)
-
- expect(spec?.shows).toContain(`create ${folder}/${file}`)
- expect(existsSync(join(root, folder, file))).toBe(false)
- await spec?.run?.()
-
- const text = readFileSync(join(root, folder, file), 'utf8')
-
- expect(text).toContain(marker)
- expect(parseAdr(file, text)).toMatchObject({ status: 'proposed', title: 'Cache reads', date: today })
- expect(adrOf(state).selected).toBe(file)
- expect(world.log.toasts).toHaveLength(1)
-
- // A second proposal with the same title takes the next number, and a record that appears in between is not overwritten.
- const again = proposeSpec(state, world.host as never, 'Cache reads', today)
- const target = /create (\S+)/.exec(again?.shows ?? '')?.[1] as string
-
- writeFileSync(join(root, target), 'MINE')
- await again?.run?.()
- expect(readFileSync(join(root, target), 'utf8')).toBe('MINE')
- })
-
- it('propose with a hostile title cannot leave the folder or inject a heading, and an empty title is refused', async () => {
- const { root, state, world } = await loaded('nygard')
-
- expect(proposeSpec(state, world.host as never, ' ', today)).toBeNull()
-
- const spec = proposeSpec(state, world.host as never, '../../etc/passwd\n## Status\n\nAccepted [x](y) `z`', today)
-
- await spec?.run?.()
-
- const written = readdirSync(join(root, 'doc/adr')).filter(f => f.startsWith('0004'))
-
- expect(written).toHaveLength(1)
- expect(written[0]).toMatch(/^0004-[a-z0-9-]+\.md$/)
-
- const text = readFileSync(join(root, 'doc/adr', written[0] as string), 'utf8')
-
- expect(text.match(/^## Status$/gm)).toHaveLength(1)
- expect(parseAdr(written[0] as string, text).status).toBe('proposed')
- expect(existsSync(join(root, 'etc'))).toBe(false)
- })
-
- it('a transition writes exactly the confirmed diff and nothing else, then re-reads', async () => {
- const { root, state, world } = await loaded('ruflo-style')
- const doc = adrOf(state).registry.docs[1] as AdrDoc
- const before = readFileSync(join(root, 'docs/adrs', doc.file), 'utf8')
- const spec = await statusSpec(state, world.host as never, doc, 'accepted')
-
- expect(spec?.label).toBe('mark ADR 2 accepted')
- expect(spec?.shows).toContain('-Status: Proposed (2025-02-01)')
- expect(spec?.shows).toContain('+Status: Accepted')
- expect(readFileSync(join(root, 'docs/adrs', doc.file), 'utf8')).toBe(before)
- await spec?.run?.()
-
- const after = readFileSync(join(root, 'docs/adrs', doc.file), 'utf8')
-
- expect(after).toBe(before.replace('Status: Proposed (2025-02-01)', 'Status: Accepted'))
- expect(adrOf(state).registry.docs[1]?.status).toBe('accepted')
- expect(world.log.toasts).toHaveLength(1)
- })
-
- it('a file that changed since the diff was shown is left alone', async () => {
- const { root, state, world } = await loaded('ruflo-style')
- const doc = adrOf(state).registry.docs[1] as AdrDoc
- const spec = await statusSpec(state, world.host as never, doc, 'accepted')
-
- writeFileSync(join(root, 'docs/adrs', doc.file), 'someone else edited this')
- await spec?.run?.()
- expect(readFileSync(join(root, 'docs/adrs', doc.file), 'utf8')).toBe('someone else edited this')
- expect(adrOf(state).last).toMatchObject({ ok: false })
- expect(adrOf(state).last?.lines.join(' ')).toContain('changed since the diff was shown')
- expect(world.log.toasts).toEqual([])
- })
-
- it('supersede edits both files with their own diffs, and a refused change says why', async () => {
- const { root, state, world } = await loaded('nygard')
- const docs = adrOf(state).registry.docs
- const accepted = docs[0] as AdrDoc
- const created = proposeSpec(state, world.host as never, 'Use gRPC', today)
-
- await created?.run?.()
-
- const newer = adrOf(state).registry.docs.find(doc => doc.number === 4) as AdrDoc
-
- expect(await planStatus(state, world.host as never, accepted, 'superseded', null)).toMatchObject({ ok: false })
- expect(await planStatus(state, world.host as never, accepted, 'accepted', null)).toMatchObject({ ok: false, why: 'it is already accepted' })
- expect(await planStatus(state, world.host as never, accepted, 'rejected', null)).toMatchObject({ ok: false })
-
- const spec = await statusSpec(state, world.host as never, accepted, 'superseded', newer)
-
- expect(spec?.expect).toContain(accepted.file)
- expect(spec?.expect).toContain(newer.file)
- await spec?.run?.()
- expect(readFileSync(join(root, 'doc/adr', accepted.file), 'utf8')).toContain('Superseded by [4. Use gRPC](0004-use-grpc.md)')
- expect(readFileSync(join(root, 'doc/adr', newer.file), 'utf8')).toContain('Supersedes [1. Record architecture decisions]')
- expect(adrOf(state).registry.docs.find(doc => doc.number === 1)?.status).toBe('superseded')
- expect(lint(adrOf(state).registry, adrOf(state).files).filter(f => f.code === 'supersede-mismatch' || f.code === 'dangling-supersedes')).toEqual([])
- })
-
- it('a record that is a link is never written through', async () => {
- const { root, state, world } = await loaded('nygard')
- const target = join(root, 'doc/adr', '0003-use-graphql.md')
- const outside = mkdtempSync(join(tmpdir(), 'adr-outside-'))
-
- cleanups.push(outside)
-
- const doc = adrOf(state).registry.docs[2] as AdrDoc
- const spec = await statusSpec(state, world.host as never, doc, 'deprecated')
-
- writeFileSync(join(outside, 'x.md'), readFileSync(target, 'utf8'))
- unlinkSync(target)
- symlinkSync(join(outside, 'x.md'), target)
- await spec?.run?.()
- expect(readFileSync(join(outside, 'x.md'), 'utf8')).toContain('Accepted')
- expect(readFileSync(join(outside, 'x.md'), 'utf8')).not.toContain('Deprecated')
- expect(adrOf(state).last?.lines.join(' ')).toContain('link')
- })
-})
-
-// ---------------------------------------------------------------------------------------------------------------- mutation check
-
-type Mod = Record<string, (...args: never[]) => unknown>
-
-/** What the pure modules say about a fixed battery: any change in a module's behaviour that the battery sees changes this string. */
-function signature(adr: Mod, scope: Mod, write: Mod): string {
- const parse = adr.parseAdr as unknown as (f: string, t: string) => AdrDoc
- const index = adr.indexOf as unknown as typeof indexOf
- const lintFn = adr.lint as unknown as typeof lint
- const out: unknown[] = []
- const real = readdirSync(RUFLO_ADRS).filter(f => /^ADR-.*\.md$/.test(f)).slice(0, 120).map(f => parse(f, readFileSync(join(RUFLO_ADRS, f), 'utf8')))
- const fixtures: AdrDoc[] = []
-
- for (const [name, folder] of [['madr', 'docs/decisions'], ['nygard', 'doc/adr'], ['ruflo-style', 'docs/adrs'], ['mixed', 'docs/architecture/decisions'], ['plain', 'adr'], ['log4brains', 'docs/adr']]) {
- for (const f of readdirSync(join(FIXTURES, name as string, folder as string)).filter(file => file.endsWith('.md') && !/^readme/i.test(file))) fixtures.push(parse(f, readFileSync(join(FIXTURES, name as string, folder as string, f), 'utf8')))
- }
-
- out.push(real.map(d => [d.number, d.variant, d.status, d.date, d.scope.length, d.supersedes, d.supersededBy, d.relates, d.refs, d.decision.length, d.format]))
- out.push(fixtures.map(d => [d.status, d.date, d.format, d.supersedes, d.supersededBy, d.refs, d.scope, d.title]))
- out.push(lintFn(index([...real, ...fixtures]), real.map(d => d.file), 'ADR-001 ADR-002').map(f => `${f.code}:${f.file}`))
- out.push(lintFn(index(fixtures.filter(d => d.file.startsWith('00'))), [], null).map(f => `${f.code}:${f.file}`))
- out.push(parse('0001-x.md', `# 1. X\n\nStatus: Accepted\n\u001b[31m${'z'.repeat(MAX_FILE + 50)}`).notes)
- out.push(parse('0001-x.md', '---\nstatus: accepted\ndate: 2024-12-31\n---\n\n# X\n').date)
- out.push(parse('0001-x.md', '# X\n\nStatus: Accepted\u001b[2K bold\nDate: 2024-02-09\n').statusRaw)
- out.push(parse('0001-x.md', '# X\n\n## Status\n\nSuperseded by [2. Y](0002-y.md)\n'))
- out.push(parse('0001-x.md', `# X\n\n${'filler '.repeat(40_000)}\n\nStatus: Accepted\n`).status)
- out.push(parse('ADR-376-x.md', '# ADR-376: X\n\n| Field | Value |\n|---|---|\n| Status | Proposed |\n').status)
- out.push(lintFn(index([parse('0001-a.md', '# 1. A\n\nStatus: Accepted\nDate: 2020-01-01\nSupersedes: 2\n'), parse('0002-b.md', '# 2. B\n\nStatus: Accepted\nDate: 2020-01-01\nSupersedes: 1\n')]), []).map(f => `${f.level}:${f.code}`))
-
- const hits = scope.checkScope as unknown as typeof checkScope
- const hit = scope.scopeHits as unknown as typeof scopeHits
- const block = scope.digestBlock as unknown as typeof digestBlock
- const sug = scope.suggest as unknown as typeof suggest
- const accepted = parse('0001-a.md', '# 1. Auth sessions\n\nStatus: Accepted\nDate: 2025-01-01\n\n## Decision\n\nUse sessions.\n')
- const proposed = parse('0002-b.md', '# 2. Auth tokens\n\nStatus: Proposed\nDate: 2025-01-01\n')
-
- accepted.scope = ['src/auth']
- proposed.scope = ['src/auth']
- out.push([hit('src/auth', 'src/auth/a.ts'), hit('src/auth', 'src/authz/a.ts'), hit('a/b.ts', 'x/a/b.ts'), hit('src/*.ts', 'src/deep/a.ts'), hit('docs', 'docs/x.md')])
- out.push(hits(['src/auth/a.ts', 'src/other.ts'], [accepted, proposed]).hits.map(h => h.file))
- out.push(block([accepted, proposed, ...Array.from({ length: 10 }, (_v, i) => ({ ...accepted, file: `00${i + 10}-z.md`, number: i + 10, decision: 'lorem ipsum '.repeat(40) }))]).length)
- const history = { ...accepted, file: '0003-c.md', number: 3, status: 'superseded' as const }
-
- out.push(sug('auth sessions src/auth/x.ts', [accepted, proposed, history]).map(s => s.doc.number))
-
- const style = (write.detectStyle as unknown as typeof detectStyle)(fixtures.filter(d => d.file.startsWith('ADR-')))
-
- out.push([style, (write.nextNumber as unknown as typeof nextNumber)(fixtures), (write.slugOf as unknown as typeof slugOf)('Use Postgres — for Storage!')])
-
- const nygard = parse('0003-use-graphql.md', readFileSync(join(FIXTURES, 'nygard', 'doc/adr', '0003-use-graphql.md'), 'utf8'))
- const edited = (write.withStatus as unknown as typeof withStatus)(readFileSync(join(FIXTURES, 'nygard', 'doc/adr', '0003-use-graphql.md'), 'utf8'), nygard, { name: 'nygard', width: 4, pattern: '{n}-{slug}.md', source: 'default' }, 'deprecated')
-
- out.push(edited)
-
- return JSON.stringify(out)
-}
-
-describe('mutation check: the battery notices a change in the parser, the lint, the scope matcher and the writer', () => {
- const data = join(HERE, '..', 'hooks', 'data')
- const made: string[] = []
- const baseline = async () => signature(await import('../hooks/data/adr') as never, await import('../hooks/data/adr-scope') as never, await import('../hooks/data/adr-write') as never)
-
- afterAll(() => {
- for (const file of made) rmSync(file, { force: true })
- })
-
- const mutants: [string, string, string, string][] = [
- ['adr', 'a superseded status read as deprecated', "if (/\\bsuperse?ded\\b|\\breplaced\\b|\\bobsolete/.test(text)) return 'superseded'", "if (/\\bsuperse?ded\\b|\\breplaced\\b|\\bobsolete/.test(text)) return 'deprecated'"],
- ['adr', 'a one-digit month only', '(0?[1-9]|1[0-2])[-/. ](0?[1-9]|[12]\\d|3[01])', '(0?[1-9])[-/. ](0?[1-9]|[12]\\d|3[01])'],
- ['adr', 'A/B/C siblings counted as duplicates', 'other.variant === doc.variant', 'true'],
- ['adr', 'a supersedes with no file not reported', '!registry.byNumber.has(target)) add(\'warn\', \'dangling-supersedes\'', 'registry.byNumber.has(target)) add(\'warn\', \'dangling-supersedes\''],
- ['adr', 'a Status section read as a status line', "return { raw: first ?? '', format: 'nygard', section }", "return { raw: first ?? '', format: 'inline', section }"],
- ['adr', 'front matter never recognised', "if (!text.startsWith('---\\n')) return null", "if (!text.startsWith('--\\n')) return null"],
- ['adr', 'escapes left in the text', ".replace(ESCAPES, '')", ''],
- ['adr', 'no cap on a huge file', 'text = wash(source.length > MAX_FILE ? source.slice(0, MAX_FILE) : source)', 'text = wash(source)'],
- ['adr', 'a table status not read', "const table = /^\\s*\\|\\s*\\**status\\**\\s*\\|\\s*(.+?)\\s*\\|?\\s*$/i.exec(line)", "const table = /^\\s*\\|\\s*\\**nostatus\\**\\s*\\|\\s*(.+?)\\s*\\|?\\s*$/i.exec(line)"],
- ['adr', 'a cycle not reported', "add('error', 'supersede-cycle'", "add('info', 'supersede-cycle'"],
- ['adr-scope', 'a sibling that shares a prefix counted in scope', 'f.startsWith(`${e}/`)', 'f.startsWith(e)'],
- ['adr-scope', 'a proposed ADR counted as in force', "attached.filter(doc => doc.status === 'accepted')", 'attached'],
- ['adr-scope', 'no cap on the digest', 'if (used + line.length > DIGEST_TOTAL) break', ''],
- ['adr-scope', 'a glob that crosses folders', "'[^/]*'", "'.*'"],
- ['adr-scope', 'history offered as a suggestion', "(doc.status !== 'accepted' && doc.status !== 'proposed') || attached.includes(doc.file)", 'attached.includes(doc.file)'],
- ['adr-write', 'the next number reuses the highest', "(high, doc) => Math.max(high, doc.number ?? 0), 0) + 1", "(high, doc) => Math.max(high, doc.number ?? 0), 0) + 0"],
- ['adr-write', 'a status inserted instead of replaced', 'lines[first] = value', "lines.splice(first, 0, value)"],
- ['adr-write', 'slugs keep their case', ' .toLowerCase()\n .normalize', ' .normalize'],
- ['adr-write', 'the prefix is never detected', "/^adr[-_ ]/i.test(doc.file)", '/^zzz/i.test(doc.file)'],
- ]
-
- it('the unmutated battery is stable', async () => {
- expect(await baseline()).toBe(await baseline())
- })
-
- it.each(mutants.map((m, i) => [i, m[1], m] as const))('mutant %i (%s) changes what the battery sees', async (index, _label, [module, , find, replace]) => {
- const file = join(data, `${module}.ts`)
- const source = readFileSync(file, 'utf8')
-
- expect(source, `the mutation target must exist: ${find}`).toContain(find)
-
- const path = join(data, `.mut-${index}-${module}.ts`)
-
- writeFileSync(path, source.replace(find, replace))
- made.push(path)
-
- const mod = async (name: string) => (name === module ? await import(/* @vite-ignore */ path) : await import(`../hooks/data/${name}`)) as Mod
-
- expect(signature(await mod('adr'), await mod('adr-scope'), await mod('adr-write'))).not.toBe(await baseline())
- })
-})
-
-void [cpSync, withStatus, graphOf]
diff --git a/plugins/ruflo-swarm/.claude-plugin/plugin.json b/plugins/ruflo-swarm/.claude-plugin/plugin.json
index 1f5f959f3d..dbd4b16756 100644
--- a/plugins/ruflo-swarm/.claude-plugin/plugin.json
+++ b/plugins/ruflo-swarm/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-swarm",
"description": "Agent teams, swarm coordination, Monitor streams, and worktree isolation — wraps 4 swarm_* + 8 agent_* MCP tools (12 total) plus 6 topologies (hierarchical / mesh / hierarchical-mesh / ring / star / adaptive). With Claude Code function hooks on (early access), a live swarm pane: agent tiles lit by reads and writes, topology, task and claims board, cost, router pick and hive-mind votes, with buttons that act through the ruflo CLI",
- "version": "0.3.4",
+ "version": "0.3.5",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
diff --git a/plugins/ruflo-swarm/CHANGELOG.md b/plugins/ruflo-swarm/CHANGELOG.md
index 46ac12b8b1..d259e64cf3 100644
--- a/plugins/ruflo-swarm/CHANGELOG.md
+++ b/plugins/ruflo-swarm/CHANGELOG.md
@@ -2,6 +2,9 @@
Newest first. One `## <version> — <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; this is the whole history.
+## 0.3.5 — 2026-10-07
+- feat: a spawned subagent is given the accepted ADRs attached to the active ruflo-console mission (masked, capped, as data), and its member row names them; option injectAdrs, on by default, nothing added without an attached ADR (ADR-480)
+
## 0.3.4 — 2026-10-07
- feat: shared toast system with levels, dedupe, persistence and Settings (ADR-477)
- feat: shared toast policy and its call sites (ADR-477), work in progress
diff --git a/plugins/ruflo-swarm/README.md b/plugins/ruflo-swarm/README.md
index bd32d3c4bf..193a96f36f 100644
--- a/plugins/ruflo-swarm/README.md
+++ b/plugins/ruflo-swarm/README.md
@@ -92,7 +92,7 @@ commands, skills and agents above behave as they always have.
`/ruflo-swarm-consensus` stay registered as aliases (ADR-406: no command is removed or renamed). `/ruflo-swarm:watch` also opens the pane.
- **Options** (`/config`): `panel` (command, the default since ruflo-console's cockpit is the pane that opens by
itself | auto | off: `/ruflo swarm pane` refuses and `/ruflo-swarm:watch` does not open it), `cli` (`npx-offline`, the default, never touches the
- network), `routeThreshold`, `injectSpawnContext` (off by default: appends a one-line swarm note to spawned subagents'
+ network), `routeThreshold`, `injectAdrs` (on by default: with ADRs attached to the active ruflo-console mission, appends their accepted decisions, masked and capped, to spawned subagents' prompts and names them on the member row; nothing is added without an attached ADR), `injectSpawnContext` (off by default: appends a one-line swarm note to spawned subagents'
prompts) and `audit` (off by default: event names, tool names and agent ids into ruflo memory, never content).
- The mod does not register `prompt.submit` or `tool.check` hooks, and its `tool.call` hook only observes.
- **With the ruflo-mods trust gate:** if you set `modTrust: refuse-risky`, the gate refuses this mod. The mod hooks
diff --git a/plugins/ruflo-swarm/scripts/smoke.sh b/plugins/ruflo-swarm/scripts/smoke.sh
index f542977775..f6ae9bf689 100755
--- a/plugins/ruflo-swarm/scripts/smoke.sh
+++ b/plugins/ruflo-swarm/scripts/smoke.sh
@@ -7,9 +7,9 @@ step() { printf "→ %s ... " "$1"; }
ok() { printf "PASS\n"; PASS=$((PASS+1)); }
bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }
-step "1. plugin.json declares 0.3.4 with new keywords"
+step "1. plugin.json declares 0.3.5 with new keywords"
v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
-if [[ "$v" != "0.3.4" ]]; then bad "expected 0.3.4, got '$v'"; else
+if [[ "$v" != "0.3.5" ]]; then bad "expected 0.3.5, got '$v'"; else
miss=""
for k in mcp topologies worktree-isolation monitor-stream; do
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
diff --git a/plugins/ruflo-swarm/tests/adr-digest.spec.ts b/plugins/ruflo-swarm/tests/adr-digest.spec.ts
new file mode 100644
index 0000000000..7548612203
--- /dev/null
+++ b/plugins/ruflo-swarm/tests/adr-digest.spec.ts
@@ -0,0 +1,55 @@
+/**
+ * The ADRs a console mission carries, as the swarm hands them to a spawned subagent (ADR-480 in ruflo-console): the digest file is read
+ * defensively, and the member row of the agent it guided says which ADRs those were. Run with
+ * npx vitest run plugins/ruflo-swarm/tests/adr-digest.spec.ts
+ */
+import { describe, expect, it } from 'vitest'
+
+import { readAdrDigest } from '../hooks/adr-digest'
+import { newActivity, noteSpawn } from '../hooks/model/members'
+
+const PATH = '.claude-flow/console/adr-digest.json'
+const fsOf = (text: string | undefined, size = text?.length) => ({ read: async () => text ?? Promise.reject(new Error('ENOENT')), stat: async () => (text === undefined ? undefined : { size }) })
+const digest = (patch: Record<string, unknown> = {}) => JSON.stringify({ v: 1, atMs: 5_000, adrs: [{ number: 7, status: 'accepted' }, { number: 8, status: 'superseded' }], block: 'Decisions attached to this work:\n- ADR 7 [accepted] Sessions', ...patch })
+
+describe('reading the digest', () => {
+ it('returns the block and the accepted numbers only', async () => {
+ expect(await readAdrDigest(fsOf(digest()), 6_000)).toEqual({ block: 'Decisions attached to this work:\n- ADR 7 [accepted] Sessions', numbers: [7] })
+ })
+
+ it.each([
+ ['missing', undefined],
+ ['not json', '{x'],
+ ['wrong version', digest({ v: 2 })],
+ ['no block', digest({ block: '' })],
+ ['block not text', digest({ block: 5 })],
+ ['stale', digest({ atMs: 1 })],
+ ['from the future', digest({ atMs: 9e12 })],
+ ['not an object', '[]'],
+ ])('ignores a digest that is %s', async (_name, text) => {
+ expect(await readAdrDigest(fsOf(text), 86_400_000 * 3)).toBeNull()
+ })
+
+ it('does not read an oversize file, and caps a long block and ignores escapes in it', async () => {
+ expect(await readAdrDigest(fsOf(digest(), 99_999), 6_000)).toBeNull()
+
+ const long = await readAdrDigest(fsOf(digest({ block: `${'- ADR 1 [accepted] x\u001b[31m red\n'.repeat(100)}` })), 6_000)
+
+ expect(long?.block.length).toBeLessThanOrEqual(1400)
+ expect(long?.block).not.toContain('\u001b')
+ expect(long?.block).not.toContain('[31m')
+ expect(PATH).toContain('console')
+ })
+})
+
+describe('citing the ADRs on the member row', () => {
+ it('a spawned agent carries the numbers it was told about, in its description and a field; none leaves both alone', () => {
+ const activity = newActivity()
+
+ noteSpawn(activity, 'a1', 'coder', 1, 'impl', 'build it', [7, 9])
+ noteSpawn(activity, 'a2', 'coder', 1, 'impl2', 'build that')
+ expect(activity.loops.get('a1')).toMatchObject({ adrs: [7, 9], description: 'build it [guided by ADR 7, 9]' })
+ expect(activity.loops.get('a2')?.adrs).toBeUndefined()
+ expect(activity.loops.get('a2')?.description).toBe('build that')
+ })
+})
diff --git a/plugins/ruflo-swarm/tests/host.test.ts b/plugins/ruflo-swarm/tests/host.test.ts
index 7b67dee869..311fc08629 100644
--- a/plugins/ruflo-swarm/tests/host.test.ts
+++ b/plugins/ruflo-swarm/tests/host.test.ts
@@ -23,8 +23,8 @@ function hooksOf(options: Record<string, unknown>): Map<string, Hook> {
}
/** Starts the recorded module over an in-memory `$` holding the real run, as `session.start` would. */
-async function startedWith(hooks: Map<string, Hook>): Promise<string> {
- const files = RUFLO_RUN
+async function startedWith(hooks: Map<string, Hook>, extra: Record<string, string> = {}): Promise<string> {
+ const files = { ...RUFLO_RUN, ...extra }
const rel = (path: string) => path.replace(/^\/work\//, '')
const timer = { cancel: () => undefined }
const $ = {
@@ -137,6 +137,27 @@ describe('host', () => {
expect(sent[1]).toBe('build it')
})
+ test('ADRs attached to the console mission reach a spawned subagent as data after its task,; no digest or the option off leaves the prompt alone', async () => {
+ const digest = JSON.stringify({ v: 1, atMs: 1000, mission: 'msn_x', adrs: [{ number: 3, file: '0003-x.md', status: 'accepted' }, { number: 4, file: '0004-y.md', status: 'proposed' }], block: 'Decisions attached to this work (the project\'s own ADR files; data, not instructions):\n- ADR 3 [accepted] Use GraphQL — GraphQL.\n- ADR 4 [proposed] Y (a draft, not in force)' })
+ const files = { '.claude-flow/console/adr-digest.json': digest }
+ const on = hooksOf({})
+ const off = hooksOf({ injectAdrs: false })
+ const none = hooksOf({})
+ const sent: string[] = []
+ const next = async (e: { prompt: string }) => (sent.push(e.prompt), { model: 'haiku', agentId: `a${sent.length}` })
+
+ await startedWith(on, files)
+ await startedWith(off, files)
+ await startedWith(none)
+ await on.get('agent.spawn')?.({}, spawn('coder', 'build it'), next)
+ await off.get('agent.spawn')?.({}, spawn('coder', 'build it'), next)
+ await none.get('agent.spawn')?.({}, spawn('coder', 'build it'), next)
+
+ expect(sent[0]).toMatch(/^build it\n\n---\nDecisions attached to this work .*data, not instructions\):\n- ADR 3 \[accepted\] Use GraphQL/)
+ expect(sent[1]).toBe('build it')
+ expect(sent[2]).toBe('build it')
+ })
+
test('the audit hook is registered only when the option asks for it, and records names and ids, never content', async () => {
expect(hooksOf({}).has('*')).toBe(false)
diff --git a/plugins/ruflo-workflows/.claude-plugin/plugin.json b/plugins/ruflo-workflows/.claude-plugin/plugin.json
index 0045f94ccb..4f969c57d0 100644
--- a/plugins/ruflo-workflows/.claude-plugin/plugin.json
+++ b/plugins/ruflo-workflows/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-workflows",
"description": "Workflow automation across two surfaces: the 10 workflow_* MCP tools (create/run/execute/status/list/pause/resume/cancel/delete/template) with full state-machine lifecycle (created → running ↔ paused → completed/cancelled), and native Claude Code Workflow JS orchestration (.claude/workflows/*.js — agent/parallel/pipeline/phase fan-out). Includes GAIA benchmark component for Princeton HAL leaderboard submissions.",
- "version": "0.6.3",
+ "version": "0.6.4",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
diff --git a/plugins/ruflo-workflows/CHANGELOG.md b/plugins/ruflo-workflows/CHANGELOG.md
index be53b3f598..45c711bfea 100644
--- a/plugins/ruflo-workflows/CHANGELOG.md
+++ b/plugins/ruflo-workflows/CHANGELOG.md
@@ -2,6 +2,9 @@
Newest first. One `## <version> — <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-workflows`.
+## 0.6.4 — 2026-10-07
+- feat: workflow-create documents the two ADR steps (requires ADR, records ADR) that use the project's own ADRs through ruflo-console's ADRs page (ADR-480)
+
## 0.6.3 — 2026-10-05
- fix: shared textsOf reports truncation and every guard fails closed on it
diff --git a/plugins/ruflo-workflows/scripts/smoke.sh b/plugins/ruflo-workflows/scripts/smoke.sh
index c70d255cb2..7f401f6e00 100755
--- a/plugins/ruflo-workflows/scripts/smoke.sh
+++ b/plugins/ruflo-workflows/scripts/smoke.sh
@@ -7,9 +7,9 @@ step() { printf "→ %s ... " "$1"; }
ok() { printf "PASS\n"; PASS=$((PASS+1)); }
bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }
-step "1. plugin.json declares 0.6.3 with lifecycle keywords"
+step "1. plugin.json declares 0.6.4 with lifecycle keywords"
v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
-if [[ "$v" != "0.6.3" ]]; then bad "expected 0.6.3, got '$v'"; else
+if [[ "$v" != "0.6.4" ]]; then bad "expected 0.6.4, got '$v'"; else
miss=""
for k in mcp workflow-templates pause-resume lifecycle; do
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
diff --git a/plugins/ruflo-workflows/skills/workflow-create/SKILL.md b/plugins/ruflo-workflows/skills/workflow-create/SKILL.md
index ad5af30881..06e2072a58 100644
--- a/plugins/ruflo-workflows/skills/workflow-create/SKILL.md
+++ b/plugins/ruflo-workflows/skills/workflow-create/SKILL.md
@@ -24,6 +24,15 @@ Author a workflow on whichever surface fits the job.
Features: sequential/parallel steps, conditional branching, template inheritance, pause/resume approval gates.
+## ADR steps (with ruflo-console 0.39.0 or later)
+
+Neither surface above has a step *type* for decisions, and ruflo-console owns no workflow engine (its Workflows page only reads runs), so these are two ordinary steps, not an engine feature. They use the ADRs of the project you run in, not ruflo's own.
+
+- **requires ADR** (first step): attach the ADRs that govern the area to the console mission (ADRs page, or `/ruflo run adr-attach <n>`); the console puts the accepted decisions in the prompt of every step and spawned agent. Name the ones the step touches before it edits anything.
+- **records ADR** (last step): when the workflow made a decision a person should keep, `/ruflo run adr-propose <title>` (or the page's *draft an ADR from this mission*). It writes a *proposed* record only after the person's Yes on the exact file; a person writes the decision and accepts it.
+
+The console's scope check compares changed file paths with the paths the attached accepted ADRs name and records a warning; it does not prove a step follows a decision.
+
## B — Native `.claude/workflows/*.js`
Write a `.js` file under `.claude/workflows/`. It MUST begin with a **pure-literal** `export const meta` block; the body runs inside an async wrapper (top-level `await`/`return` are legal) with these hooks injected:
diff --git a/v3/docs/adr/ADR-480-adr-management.md b/v3/docs/adr/ADR-480-adr-management.md
new file mode 100644
index 0000000000..20d2020141
--- /dev/null
+++ b/v3/docs/adr/ADR-480-adr-management.md
@@ -0,0 +1,135 @@
+# ADR 480: Console: managing your project's ADRs, and handing them to missions, loops and swarms
+
+Status: Accepted (ships in ruflo-console 0.39.0, ruflo-swarm 0.3.5, ruflo-workflows 0.6.4)
+
+Date: 2026-10-07
+
+Scope: `plugins/ruflo-console` (`hooks/adr.ts`, `hooks/adr-mission.ts`, `hooks/adr-actions.ts`, `hooks/adr-palette.ts`, `hooks/data/adr*.ts`, `hooks/views/adr.ts`, the mission, settings and nav files they plug into), `plugins/ruflo-swarm` (`hooks/adr-digest.ts`), `plugins/ruflo-workflows` (the workflow-create skill)
+
+Builds on: ADR-478 (the What's new page, the sibling pattern), ADR-477 (toasts), ADR-474 (the bounded, washed text the console keeps), ADR-444 and ADR-450 (Claude's control of the console, and its levels), ADR-443 (mission context, gates and the loop), ADR-407 (the cockpit)
+
+## 1. Context
+
+### 1.1 Who this is for
+
+A person who runs Claude Code in their own project and keeps (or should keep) Architecture Decision Records there. The console runs in that project, so the ADRs it manages are **that project's**, in whatever convention that project uses. ruflo's own `v3/docs/adr` is a test corpus here and the place this record lives; no runtime code names it, and nothing depends on `scripts/check-adr-links.mjs` (the lint is the plugin's own).
+
+### 1.2 What exists: the ruflo-adr plugin
+
+`plugins/ruflo-adr` (a separate marketplace plugin, 0.5.4) is a lifecycle tool for agents: skills `adr-create`, `adr-index`, `adr-reindex`, `adr-review`, `adr-verify`, an `adr` command and an `adr-architect` agent, and a mod with a write guard. It writes `docs/adr/ADR-NNN-slug.md` with bold-field lines (`- **Status**: proposed`, lowercase) and registers each record in AgentDB (`adr-patterns`, `adr-edges`) with causal edges (`supersedes`, `amends`, `depends-on`, `related`). Its parser accepts front matter and `**Status**:`-style lines, but not the plain `Status:` / `Date:` lines that most of ruflo's own ADRs use, so those parse as `Unknown`.
+
+It does nothing in the console: no page, no confirm, no mission link. It is also AgentDB-centred; a user without ruflo memory has no use for it. This ADR does not change it, and its record format is a subset of what the console reads. The two share status words (proposed, accepted, superseded, deprecated, rejected) and the supersede direction (the newer record names the older).
+
+### 1.3 What exists: the console
+
+Read from the code, not assumed:
+
+- **A page** is a `ViewId` in `state.ts` (`VIEWS`: hotkey, label, blurb, rows), a group in `nav-state.ts`, a body in `views/pane.ts` (`BODIES`), an opener in `view-open.ts`, and entries in the help topics, the ask table, the boot list and `self-check.ts`. What's new (ADR-478) touched 28 files; this ADR follows the same list.
+- **Confirm pattern**: an `ActionSpec` handed to `runner.ask`. The card shows `runs: <shows>` wrapped in full, and `Effect: <note>`. `run` is custom code that runs on Yes (30 s window). A spec that `isReadOnly` runs at once.
+- **Claude's control** (`model-tools.ts`): `console_state | console_open | console_set | console_run`. `console_run` runs a palette entry by id. A non-read-only entry becomes `state.pending`; its class (`classOf`: words in label, command, note, shows, plus the entry's `declared` class) must be allowed by the person's level (read, write, manage, full), and in `ask` mode waits for the person's Yes. A read-only entry that declares a class goes through the same gate. So the established way to expose an action to Claude is a palette entry.
+- **Events and toasts**: `record(state.events, …)` for Events; `host.toast(text, ms, level)` goes through the shared toast kit (source `console`), which also records a digest the Events page takes in.
+- **Missions**: a ledger of `MissionRecord`s in the plugin store (`saveLedger`), a **context section** (`mission-claude.ts: contextSection`, ≤1200 characters, keyed so Claude's prompt cache holds), the **task instruction** (`instructionOf`), the **gates** (the person's own commands, `verify`, which records each exit code as evidence), a loop manager that prepares `/loop` text in the prompt box, and the GOAP planner whose plan has a `create (ADRs, SOP)` step.
+- **Workflows**: the Workflows page *reads* Claude Code's run folders (`wf-live.ts`, `data/workflows-read.ts`). The console has no workflow engine and no step types. Steps live in ruflo's `workflow_create` (MCP) and in native `.claude/workflows/*.js` scripts.
+- **Swarms**: the console's Swarm page shows ruflo's swarm; spawning is `ruflo agent spawn`. The place a spawned subagent's prompt is built is ruflo-swarm's `agent.spawn` hook (`injectSpawnContext` appends a swarm note). There is no task prompt in the console itself.
+
+### 1.4 What ADRs look like in practice
+
+ruflo's `v3/docs/adr` (264 files; numbers 074 to 479; sampled and then parsed whole):
+
+| form | files | |
+|---|---|---|
+| `Status: Accepted` (plain line, ADR-4xx) | 79 | plus `Date: 2026 10 03` (space-separated) in 48 |
+| `**Status**: Accepted` / `**Status:**` | 94 + 28 | `**Date**: 2026-05-03` in 90+ |
+| `- **Status**: …` / `- Status: **…**` (list item) | 39 | ADR-104 style |
+| table row `\| Status \| Proposed \|` | 3 | ADR-376 |
+| `## Status` section | 0 as the primary form | |
+| YAML front matter | 0 in `v3/docs/adr`; both of `plugins/ruflo-adr/docs/adrs` | |
+| no status line | 11 | before the table-form fix |
+
+Names are `ADR-NNN-slug.md` (3 digits), with `ADR-322A/B/C` and `ADR-164.1` siblings and 8 numbers used twice. Relations are lines `Supersedes:`, `Builds on:`, `Extends:`, `Related:` (plain or bold, with parentheses and links), and `Supersedes: nothing` in 19 files. No file says `Superseded by`; the direction is on the newer record. Issues and PRs appear as `#N` in titles, status suffixes and `Tracking:` lines. Status words: accepted 131, proposed 108, implemented 10, draft 3; none superseded, deprecated or rejected. Free text follows the word (`Accepted (ships in ruflo-console 0.26.0)`).
+
+The console's parser reads all of that (`hooks/data/adr.ts`), and also the conventions of other projects, which are covered by fixture projects in `tests/fixtures/adr-projects/`:
+
+| project | folder | convention | what is read |
+|---|---|---|---|
+| `madr` | `docs/decisions` | MADR 3: front matter `status:`, `date:`, `supersedes:`; `status: "superseded by ADR-0003"` | status, date, links, Decision Outcome |
+| `nygard` | `doc/adr` | adr-tools: `# 3. Title`, `Date:`, `## Status` section, `Superseded by [3. …](0003-….md)`, `Supersedes [2. …](…)` | same |
+| `ruflo-style` | `docs/adrs` | `ADR-001-slug.md`, bold and plain Status/Date/Scope/Builds on lines | same, plus scope paths |
+| `log4brains` | `docs/adr` | date-prefixed names, `- Status: accepted` | status, date; the name is not a number |
+| `plain` | `adr` | markdown with no status | listed, flagged |
+| `mixed` | `docs/architecture/decisions` | three formats, a duplicate number, a missing supersede target, an index | the lint |
+| `empty` | none | a project with no ADRs | the initialise flow |
+
+Parsing ruflo's own 264 files gives: 160 accepted, 104 proposed, 261 dated, 248 with named scope paths, 249 with a Decision paragraph, 200 with a link to another ADR. The lint finds 12 duplicate numbers, 22 "supersedes, but the older one is still accepted", 5 supersedes with no file, 14 broken same-folder links and 60 files missing from `INDEX-mod-system.md`. Those are real facts about that corpus, not test noise.
+
+## 2. Decision
+
+### 2.1 The registry (pure, bounded, offline)
+
+`data/adr.ts` (parse), `data/adr-lint.ts` (lint, link graph, filter), `data/adr-write.ts` (style, numbering, templates, edits, diff), `data/adr-scope.ts` (digest, suggestion, scope check). No I/O, no throw.
+
+- A record becomes `{file, number, variant, title, status, statusRaw, date, format, scope[], supersedes[], supersededBy[], relates[], refs[], context, decision, consequences, notes[]}`. Status is normalised to proposed, accepted, superseded, deprecated, rejected or unknown by the first matching word; the raw text is kept.
+- Formats tried in order: front matter, a `## Status` section, a `Status:` / `**Status**:` / list / table line. A file with none is `bare`, listed, and flagged `no status`.
+- Bounds: a file is read to 200,000 characters (`notes` says so), at most 500 files, at most 24 scope entries, 20 issue references, 24 links; every regular expression that walks user text has a bounded quantifier (a quadratic one was found by a hostile test and fixed). Escapes and control characters are removed before anything is parsed, so none reaches the screen, a prompt or a file.
+- Siblings `322A`/`.1` share a number and are not duplicates. A date-prefixed name (`20200101-…`) is not a sequence number.
+- The lint: duplicate number (error), supersede cycle (error), dangling supersedes or superseded-by, supersedes whose target is not marked superseded, superseded by nothing, no status, unknown status, status without a date, no number, a same-folder link that does not resolve, a record missing from the folder's index file. At most 60 findings of a kind are listed, with a note of the rest.
+
+### 2.2 Finding the folder, and the style
+
+`discover` tries the folder in **Settings → ADR folder** alone, or else `docs/adr`, `docs/adrs`, `doc/adr`, `doc/adrs`, `adr`, `adrs`, `docs/architecture/decisions`, `docs/architecture/adr`, `docs/decisions`, `architecture/decisions`, `decisions`. Every folder on the path must be a real one (`checkNoLinks`): a link is refused with its reason and never read, and a record that is a link is skipped. Reads are regular files only, size-bounded, through the engine's `fs`.
+
+`detectStyle` samples the project's last 40 numbered records: the commonest format becomes MADR, Nygard or ruflo style; the width is the commonest digit count; an `ADR-` prefix is kept if most records have it. **Settings → ADR style** and **ADR file name pattern** (`{n}` and `{slug}`, ending `.md`) override; an unsafe folder or pattern is refused with a reason and the old value kept. With no ADRs the default is Nygard, four digits, `0001-slug.md`.
+
+### 2.3 The page (TOOLS → ADRs)
+
+A health strip and the lint; a status filter, a text filter and a scope filter; a paged list (`j`/`k`); a detail with the status as written, links **both ways** (supersedes, superseded by, related, cited by other ADRs), the Context, Decision and Consequences paragraphs, issue and PR references, and the missions the record is attached to; and a mission section. Every action is a button with a key and a field where text is needed, so keyboard and mouse reach the same things as on What's new. It draws in both looks and at 44, 80 and 140 columns. TOOLS was chosen over MIND and SAFETY because a project's ADRs are a working tool next to Plugins and What's new; there is no hotkey (every letter is taken), like What's new, so the page is reached from the menu, the nav, the palette or by name.
+
+### 2.4 Writing: always through the confirm, always the exact change
+
+- **Initialise** (no folder): creates the folder and `0001-record-architecture-decisions.md` (Nygard's own record, accepted). **Propose** (a title): the next number above the highest in the folder, the project's file name and headings, status proposed. Both are new files made with `dd conv=excl` (fails if the file exists) or `install -D`, after `checkNoLinks`; the confirm shows the path and every line of the file, marked `+`. A file that appears between the ask and the Yes is not overwritten, and the result says so.
+- **Status changes** (accept, reject, deprecate, supersede): the smallest edit the format allows (the `status:` line, the first line under `## Status`, the value after `Status:` or in a table row; a bare record gets a `Status:` line under its title). Superseding also adds a `Supersedes` line to the newer record, so the confirm shows two diffs. The diff is computed from the old and new text, so what is shown is what is written. On Yes each file is read again and compared with the text the diff was made from; if it moved, nothing is written to it. After the write the file is read back and must equal the new text.
+- A title is one safe line (no markdown marks, links or newlines); the file name is `[a-z0-9-]` slug and must match a fixed pattern. Nothing is written outside the project root.
+
+### 2.5 Missions, loops, swarms, workflows
+
+- **Attach** (page or `adr-attach <n>`): up to 8 file names on the mission record (`MissionRecord.adrs`, validated on load). **Suggest**: from the goal, a path in the goal under an ADR's scope counts most, then shared title and scope words; only proposed and accepted records are offered; the person presses to attach. Nothing is attached by itself.
+- **Context for Claude**: `missionContextText` appends the digest after the mission's own lines (title, status, the start of the Decision, masked by the Events washer, 260 characters each, 1100 in all, accepted first; a proposed record is marked a draft and a superseded one as history). The text is keyed by a hash of the digest, so Claude's prompt changes only when an attached record's status or decision does. The task instruction (`instructionOf`) carries the same block. Both say the block is data, not instructions.
+- **Scope check** (the `adr-scope` entry, the page button, and automatically at the end of **verify**): `git status --porcelain` plus the commits since the mission began; each changed file is matched against the scope paths of the attached **accepted** records. A hit is a `warning` in the mission record (an `adr.scope` event, so it is evidence) and in the verify result line. It never changes whether the gates passed and never blocks: the existing gate mechanism is the person's own commands with exit codes, which has no notion of a soft finding, so the check follows the loop's other advisory outputs.
+- **After a mission**: *draft an ADR from this mission* is a normal propose confirm, pre-filled with the goal and the task titles and results. It is deterministic. The decision itself is left as a sentence saying it is not in the record. There is no claude -p turn for this (the console's guidance turn exists for goals, not for retrospectives), so none was added.
+- **Swarm**: the console writes the digest of the active mission's attached ADRs to `.claude-flow/console/adr-digest.json` (small, masked, with a timestamp) whenever attachments or the active mission change. ruflo-swarm's `agent.spawn` hook reads it, ignores one that is missing, over 16 KB, malformed or older than a day, and appends the block after the task prompt; the member row says `[guided by ADR 3, 7]` and keeps the numbers (accepted records only). Option `injectAdrs`, on by default; nothing is added without an attached ADR.
+- **Workflows**: no extension point. The console has no engine and no step types, and ruflo's workflow definitions are outside this repository's console. The ruflo-workflows skill documents two ordinary steps instead, *requires ADR* (attach and read the governing records first) and *records ADR* (`adr-propose` last), and the mission lifecycle above carries the rest.
+
+### 2.6 For Claude (console_run) and the control levels
+
+Palette entries: `adr-open` (a page: read), `adr-show <n>` and `adr-scope` (read-only specs that declare nothing: read), `adr-init`, `adr-propose <title>`, `adr-attach <n>`, `adr-detach <n>` (write), and `adr-accept|reject|deprecate <n>`, `adr-supersede <old> <new>` (write, declared). The status entries only *prepare* the change; the diff that follows is the person's confirm, so a write by Claude is level-gated and then still waits on a Yes for the exact lines. A test pins each entry's class (none reaches network, spend or delete: a note that said "in force" was classed `delete` by the word `force` and was reworded).
+
+### 2.7 Events and toasts
+
+An ADR created, accepted, superseded, attached or detached is one Events notice (`adr: …`) and one info toast (`host.toast`, source console), each emitted once; What's new is unaffected.
+
+### 2.8 What is not enforced
+
+Nothing here proves that code complies with an ADR. `scope` is the set of backticked paths the record names (and a `Scope:` line), and the check is a path comparison (exact, under a folder, a glob of one level, or ending with a sub-folder-relative name). The suggestion is a word comparison. A warning is a reason to read the record; silence is not a clearance. The page and the README say this. An ADR whose status the project never wrote is not treated as accepted. Supersession is read from what the records say and is not verified against code.
+
+## 3. Consequences
+
+- A project gets a working ADR practice from the console alone: initialise, propose in its own style, change status with a diff, and see the health of the set. ruflo-adr remains for AgentDB-registered records and is not required.
+- Missions can carry the decisions that should constrain them, into Claude's prompt, each task and each spawned swarm agent, at a bounded and masked cost in tokens (about 1,100 characters at most, only when something is attached).
+- The settings gain three rows; the nav's TOOLS group is split in two rows (six at most a row); the boot list and the self-check have one more area (31).
+- A change of ADR text invalidates Claude's cached mission section (it must, to be correct); status changes of unattached records do not.
+- Not done, and why:
+ - A workflow step *type* (no engine here).
+ - A hard block on a scope hit (the gates have no soft/hard distinction; a hard block on a path heuristic would refuse good changes).
+ - ruflo-adr changes (separate plugin; its parser's gap with plain `Status:` lines is recorded in 1.2 and left alone).
+ - Auto-attach from the goal, and auto-writing of drafts (the person decides both).
+ - Sequence numbers for date-prefixed names (log4brains): they are listed and flagged `no number`; a new record in such a project gets `0001-`.
+ - A claude -p turn to write the draft's decision (no such turn exists for retrospectives).
+
+## 4. Verification
+
+- `tests/adr.spec.ts`: ruflo's own 264 ADRs parse with a number and a title, nearly all with status, date, scope and decision; every fixture convention; hostile files (a 12 MB file, a 2 MB line, nested noise, escapes, bidi marks, binary, unterminated front matter, 300 records in a supersede cycle with duplicate numbers); style detection; numbering; each style's new record parses back; each edit changes one line.
+- `tests/adr-write.spec.ts`: folder discovery for six projects and the empty one; a folder that is a link out of the project and a record that is a link (never read, never written through); initialise and propose in four projects in temp copies with real `dd`/`install`; refusal to overwrite on a race; a hostile title; transitions write exactly the diff, a changed file is left alone, supersede edits two files and the lint is then clean.
+- `tests/adr-integration.spec.ts`: attach, detach, suggest, caps, hostile ledgers; the digest in the mission context (cached, capped, masked), the task instruction and the swarm file; the scope check against a real git repository (flags under an accepted ADR, not a proposed one, a sibling path, or an unrelated file; sees commits since the mission began; verify adds it without changing the gates' result); the draft.
+- `tests/adr-page.spec.ts`: the page in both looks and three widths with hostile titles, every action a button with a key, palette entries and their control class, settings validation.
+- `tests/adr-mutation.spec.ts`: 19 one-line mutants of the parser, lint, scope matcher and writer; the battery must see each.
+- `plugins/ruflo-swarm/tests/adr-digest.spec.ts` and the host test: the digest is read defensively and reaches a spawned subagent after its task.
diff --git a/v3/docs/adr/INDEX-mod-system.md b/v3/docs/adr/INDEX-mod-system.md
index f564002942..71d19a0a65 100644
--- a/v3/docs/adr/INDEX-mod-system.md
+++ b/v3/docs/adr/INDEX-mod-system.md
@@ -66,6 +66,7 @@ Two files carry the number 430 (the menu's accents, and the menu-design amendmen
| 448 | The Room: a shared live feed | Accepted | 10-04 | 407, 416, 444 | — | #3704 (doc), #3705 (page) | console 0.33.0 (expiry event 0.32.2) | `room`, `nav`, `runner`, `watch` |
| 477 | Mods: one toast system, with levels, de-duplication, a record and a setting | Accepted | 10-07 | 404, 453, 474, 466 | — | #3889 | console 0.37.0, swarm 0.3.4, protector 0.1.1, mods 0.3.16 | `toast-policy.spec`, `toasts.spec`, `toasts.test`, `toast.test` |
| 478 | Console What's new page, plugin changelogs | Accepted | 10-07 | 428, 477 | — | — | [ADR-478](ADR-478-console-whats-new.md) | — |
+| 480 | Console ADRs page: your project's ADRs, and missions, loops and swarms that follow them | Accepted | 10-07 | 407, 443, 444, 450, 474, 477, 478 | — | this PR | console 0.39.0, swarm 0.3.5, workflows 0.6.4 | `adr.spec`, `adr-write.spec`, `adr-integration.spec`, `adr-page.spec`, `adr-mutation.spec`, `adr-digest.spec` |
Other ADRs outside 404-451 that the mod ADRs lean on: 150 (removable integrations), 174 (failures as a learning signal), 322 and 322A/B/C (flywheel, evaluation and promotion, receipts), 324 and 325 (policy engine, claims plane), 103 (witness). The console's Mods section (`hooks/data/mods.ts`, console 0.33.1, PR #3707) reads the status files ADR 446 defines.