From d9a226913e1ca1f43f1d80e9214ac043c180db36 Mon Sep 17 00:00:00 2001 From: ruv Date: Mon, 5 Oct 2026 02:47:11 -0400 Subject: [PATCH 1/2] feat(console): Mods reader shows calls from seen/checked/calls-object and refusal class from lastReason/lastBlocked (console 0.33.10) Co-Authored-By: RuFlo --- .../ruflo-console/.claude-plugin/plugin.json | 2 +- plugins/ruflo-console/hooks/data/mods.ts | 38 +++++++++++-- plugins/ruflo-console/hooks/version.ts | 2 +- plugins/ruflo-console/scripts/smoke.sh | 4 +- .../ruflo-console/tests/mods-section.spec.ts | 55 ++++++++++++++++++- 5 files changed, 92 insertions(+), 9 deletions(-) diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.json index 3215ed3bd0..77431bb3bd 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.33.9", + "version": "0.33.10", "author": { "name": "ruvnet", "url": "https://github.com/ruvnet" diff --git a/plugins/ruflo-console/hooks/data/mods.ts b/plugins/ruflo-console/hooks/data/mods.ts index a80104120d..b92dbe5608 100644 --- a/plugins/ruflo-console/hooks/data/mods.ts +++ b/plugins/ruflo-console/hooks/data/mods.ts @@ -1,5 +1,5 @@ import { readBounded, under, type ReadCache, type ReaderFs } from './files' -import { jsonObject, plain } from './parse' +import { jsonObject, plain, recordOf } from './parse' /** The most mod folders read, and the most bytes of one status file (a larger one is refused, not trimmed). */ export const MODS_MAX_FILES = 60 @@ -15,7 +15,7 @@ export const DENY_CLASSES = ['secret', 'destructive', 'path', 'network', 'policy export type DenyClass = (typeof DENY_CLASSES)[number] /** - * One mod's status file (ADR-446): the counters every mod writes; per-plugin counters are not read here. The last four are optional and only + * One mod's status file (ADR-446): the counters every mod writes (calls also from `seen`/`checked`/a `calls` object; lastDenied also from `lastReason`/`lastBlocked`); per-plugin counters are not read here. The last four are optional and only * present when the file reported them (modVersion, a one-line summary of what it guards, the class of its last refusal, the file's age source). */ export type ModRow = { name: string; guard: boolean | null; calls: number | null; blocked: number; updatedMs: number | null; startedMs: number | null; modVersion?: string; summary?: string; lastDenied?: DenyClass; fileMs?: number } @@ -27,6 +27,34 @@ export const NO_MODS: ModsFacts = { rows: [], refused: 0, truncated: false } const whole = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : null) +/** Most keys of a `calls` object that are summed, and the ceiling of any summed or widened count (a hostile 1e300 must not become a display value). */ +const CALLS_KEYS_MAX = 64 +const COUNT_CEILING = Number.MAX_SAFE_INTEGER + +/** + * How many times a mod ran, from whichever of its three shapes the file uses: a number `calls`; a `calls` object (summed over its numeric values, + * at most 64 of them); else `seen`, else `checked`. Anything else (array, nested object, NaN, negative, a string) is not a count: null. + */ +export function callsOf(value: Record): number | null { + const direct = whole(value.calls) + + if (direct !== null) return Math.min(direct, COUNT_CEILING) + + const table = recordOf(value.calls) + + if (table !== null) { + let sum = 0 + + for (const entry of Object.values(table).slice(0, CALLS_KEYS_MAX)) sum = Math.min(sum + (whole(entry) ?? 0), COUNT_CEILING) + + return sum + } + + const seen = whole(value.seen) ?? whole(value.checked) + + return seen === null ? null : Math.min(seen, COUNT_CEILING) +} + const SUMMARY_MAX = 120 const VERSION = /^[0-9][0-9A-Za-z.+-]{0,15}$/ const CLASS_TESTS: readonly [DenyClass, RegExp][] = [ @@ -53,16 +81,18 @@ export function parseModStatus(name: string, text: string | null, fileMs: number if (value === null || value.version !== 1) return null + const denied = denyClassOf(value.lastDenied) ?? denyClassOf(value.lastReason) ?? denyClassOf(value.lastBlocked) + return { name: name.slice(0, -4), guard: typeof value.guard === 'boolean' ? value.guard : null, - calls: whole(value.calls), + calls: callsOf(value), blocked: whole(value.blocked) ?? 0, updatedMs: whole(value.updatedMs), startedMs: whole(value.startedMs), ...(modVersionOf(value.modVersion) !== null && { modVersion: modVersionOf(value.modVersion) as string }), ...(plain(value.summary, SUMMARY_MAX) !== '' && { summary: plain(value.summary, SUMMARY_MAX) }), - ...(denyClassOf(value.lastDenied) !== null && { lastDenied: denyClassOf(value.lastDenied) as DenyClass }), + ...(denied !== null && { lastDenied: denied }), ...(fileMs !== null && fileMs >= 0 && { fileMs }), } } diff --git a/plugins/ruflo-console/hooks/version.ts b/plugins/ruflo-console/hooks/version.ts index dfb91bb3a2..0c8c0d39ef 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.33.9' +export const CONSOLE_VERSION = '0.33.10' diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.sh index c51c37750a..2592c10ea3 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.33.9" +step "1. plugin.json declares ruflo-console 0.33.10" grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \ - && grep -q '"version": "0.33.9"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version" + && grep -q '"version": "0.33.10"' "$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" \ diff --git a/plugins/ruflo-console/tests/mods-section.spec.ts b/plugins/ruflo-console/tests/mods-section.spec.ts index 07463922b3..83db229823 100644 --- a/plugins/ruflo-console/tests/mods-section.spec.ts +++ b/plugins/ruflo-console/tests/mods-section.spec.ts @@ -10,7 +10,7 @@ import { readSnapshot } from '../hooks/data/snapshot' import type { Actions } from '../hooks/views/common' import { roomOf } from '../hooks/room' import { viewText } from '../hooks/views/pane' -import { denyClassOf, isStale, MODS_MAX_BYTES, MODS_MAX_FILES, MODS_STALE_MS, orderMods, parseModStatus, readMods, type ModRow } from '../hooks/data/mods' +import { callsOf, denyClassOf, isStale, MODS_MAX_BYTES, MODS_MAX_FILES, MODS_STALE_MS, orderMods, parseModStatus, readMods, type ModRow } from '../hooks/data/mods' const status = (extra: Record = {}) => JSON.stringify({ version: 1, updatedMs: 1_000, calls: 5, blocked: 0, startedMs: 500, guard: true, ...extra }) const row = (name: string, blocked: number, updatedMs: number | null): ModRow => ({ name, guard: true, calls: 1, blocked, updatedMs, startedMs: null }) @@ -104,6 +104,59 @@ describe('readMods', () => { }) }) +describe('wider status shapes (mod-status-files recommendation 1)', () => { + const calls = (extra: Record) => parseModStatus('x-mod', JSON.stringify({ version: 1, ...extra }))?.calls + + it('sums a calls object over its numeric values and ignores the rest', () => { + expect(calls({ calls: { route: 3, deny: 2, note: 'x', nested: { a: 9 }, neg: -4, nan: null } })).toBe(5) + expect(calls({ calls: {} })).toBe(0) + }) + + it('reads seen, then checked, when there is no calls; a real calls wins', () => { + expect(calls({ seen: 7, checked: 3 })).toBe(7) + expect(calls({ checked: 3 })).toBe(3) + expect(calls({ calls: 2, seen: 7 })).toBe(2) + expect(calls({ calls: 'many', seen: 4 })).toBe(4) + expect(calls({ blocked: 1 })).toBeNull() + }) + + it('is bounded and never throws on hostile shapes', () => { + expect(calls({ calls: 1e300 })).toBe(Number.MAX_SAFE_INTEGER) + expect(calls({ calls: { a: 1e300, b: 1e300 } })).toBe(Number.MAX_SAFE_INTEGER) + expect(calls({ seen: 1e300 })).toBe(Number.MAX_SAFE_INTEGER) + expect(calls({ calls: [1, 2, 3] })).toBeNull() + expect(calls({ calls: -1 })).toBeNull() + expect(calls({ seen: -1, checked: Number.NaN })).toBeNull() + expect(calls({ seen: [4], checked: { a: 1 } })).toBeNull() + expect(calls({ calls: Object.fromEntries(Array.from({ length: 500 }, (_, i) => [`k${i}`, 1])) })).toBe(64) + expect(callsOf(Object.create(null) as Record)).toBeNull() + }) + + it('maps lastReason and lastBlocked to the refusal class, lastDenied first', () => { + const denied = (extra: Record) => parseModStatus('x-mod', JSON.stringify({ version: 1, ...extra }))?.lastDenied + + expect(denied({ lastReason: 'reads a .env file' })).toBe('secret') + expect(denied({ lastBlocked: 'curl to a host' })).toBe('network') + expect(denied({ lastDenied: 'rm -rf', lastReason: 'token' })).toBe('destructive') + expect(denied({ lastReason: 42, lastBlocked: ['secret'] })).toBeUndefined() + expect(denied({ lastReason: { a: 'secret' } })).toBeUndefined() + expect(denied({ lastReason: '', lastBlocked: 'odd thing' })).toBe('other') + }) + + it('never keeps the raw reason text, and strips control and bidi characters before classing', () => { + const parsed = parseModStatus('x-mod', JSON.stringify({ version: 1, lastReason: '\u202esecret\u0007 /home/me/.ssh/id_rsa ' + 'x'.repeat(5000) })) + + expect(parsed?.lastDenied).toBe('secret') + expect(JSON.stringify(parsed)).not.toContain('id_rsa') + }) + + it('shows the three real shapes in one scan', async () => { + const mods = await readMods(fakeFs({ 'a-mod': status(), 'b-mod': JSON.stringify({ version: 1, calls: { x: 4, y: 6 }, blocked: 1, updatedMs: 5 }), 'c-mod': JSON.stringify({ version: 1, seen: 9, blocked: 2, lastReason: 'token leak', updatedMs: 6 }) }), new Map(), '/p') + + expect(Object.fromEntries(mods.rows.map(mod => [mod.name, [mod.calls, mod.lastDenied ?? null]]))).toEqual({ a: [5, null], b: [10, null], c: [9, 'secret'] }) + }) +}) + describe('the Mods section on the pages', () => { const act = new Proxy(() => undefined, { get: () => act, apply: () => undefined }) as unknown as Actions const empty: ReaderFs = { read: () => Promise.reject(new Error('ENOENT')), stat: () => Promise.reject(new Error('ENOENT')), list: () => Promise.reject(new Error('ENOENT')) } From 22e883c435143dc3e1b5a0678a753af25c259329 Mon Sep 17 00:00:00 2001 From: ruv Date: Mon, 5 Oct 2026 02:47:59 -0400 Subject: [PATCH 2/2] feat(plugin-creator): status contract in the create-mod template (0.4.1) The scaffolded mod now writes .claude-flow/-mod/status.json with the fields the console reads (version 1, summary, modVersion, guard, calls as a number, blocked, lastDenied), with a shape test and docs in the skill and README. Co-Authored-By: RuFlo --- .../.claude-plugin/plugin.json | 2 +- plugins/ruflo-plugin-creator/README.md | 1 + plugins/ruflo-plugin-creator/scripts/smoke.sh | 4 +- .../skills/create-mod/SKILL.md | 11 ++--- .../templates/mod/hooks/register.ts | 40 ++++++++++++++++--- .../templates/mod/hooks/status.ts | 40 +++++++++++++++++++ .../templates/mod/tests/register.test.ts | 9 ++++- .../templates/mod/tests/status.test.ts | 24 +++++++++++ 8 files changed, 116 insertions(+), 15 deletions(-) create mode 100644 plugins/ruflo-plugin-creator/templates/mod/hooks/status.ts create mode 100644 plugins/ruflo-plugin-creator/templates/mod/tests/status.test.ts diff --git a/plugins/ruflo-plugin-creator/.claude-plugin/plugin.json b/plugins/ruflo-plugin-creator/.claude-plugin/plugin.json index c82aed086f..385e4541b4 100644 --- a/plugins/ruflo-plugin-creator/.claude-plugin/plugin.json +++ b/plugins/ruflo-plugin-creator/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "ruflo-plugin-creator", "description": "Scaffold, validate, and publish new Claude Code plugins with the canonical plugin contract — now including governed Claude Code mods (function hooks), ADR + smoke + Compatibility + namespace coordination + MCP-tool drift warnings. As a mod (ADR-445): /creator-mod (status, reserved names, a plugin contract check) and a status file the console shows", - "version": "0.4.0", + "version": "0.4.1", "author": { "name": "ruvnet", "url": "https://github.com/ruvnet" diff --git a/plugins/ruflo-plugin-creator/README.md b/plugins/ruflo-plugin-creator/README.md index 4d41aba194..eae3156399 100644 --- a/plugins/ruflo-plugin-creator/README.md +++ b/plugins/ruflo-plugin-creator/README.md @@ -82,4 +82,5 @@ Function-hook mod (ADR-445, pattern of `ruflo-agentdb`), loaded from `hooks/hook - **Command**: `/creator-mod` answers locally with no model call, read-only. Verbs: `status`; `reserved ` lists the command and skill names a plugin already uses (a mod command must not reuse one); `check ` summarises its manifest, `hooks.json` modules and `userConfig` options. Paths with `..` are refused. - **Status file**: `.claude-flow/creator-mod/status.json` (`{version, updatedMs, checked, reserved, lastTarget}`). - **Safety**: no network, no process spawning. +- **Scaffold status contract** (0.4.1): `/create-mod` scaffolds `hooks/status.ts`, which writes `.claude-flow/-mod/status.json` with the fields the console's Mods section reads: `version: 1`, `summary`, `modVersion`, `guard`, `calls` (a number), `blocked`, `lastDenied` (only once the mod has refused something), plus `updatedMs`/`startedMs`. The scaffold's `tests/status.test.ts` asserts that shape; the steps are in `skills/create-mod/SKILL.md`. - **Test**: `claude plugin validate plugins/ruflo-plugin-creator`, `claude plugin test plugins/ruflo-plugin-creator`, `bash plugins/ruflo-plugin-creator/scripts/smoke.sh`. The runner sweeps in `templates/mod/tests` (the scaffold's own test, which only passes against the scaffold: `claude plugin test plugins/ruflo-plugin-creator/templates/mod`), so expect that one file to fail from the plugin root. diff --git a/plugins/ruflo-plugin-creator/scripts/smoke.sh b/plugins/ruflo-plugin-creator/scripts/smoke.sh index d46c6145de..6987fc8dbd 100755 --- a/plugins/ruflo-plugin-creator/scripts/smoke.sh +++ b/plugins/ruflo-plugin-creator/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.4.0 with new keywords" +step "1. plugin.json declares 0.4.1 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.4.0" ]]; then bad "expected 0.4.0, got '$v'"; else +if [[ "$v" != "0.4.1" ]]; then bad "expected 0.4.1, got '$v'"; else miss="" for k in mcp scaffolding contract-bootstrap; do grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k" diff --git a/plugins/ruflo-plugin-creator/skills/create-mod/SKILL.md b/plugins/ruflo-plugin-creator/skills/create-mod/SKILL.md index df43f548a7..a6a45b1eb0 100644 --- a/plugins/ruflo-plugin-creator/skills/create-mod/SKILL.md +++ b/plugins/ruflo-plugin-creator/skills/create-mod/SKILL.md @@ -13,20 +13,21 @@ Scaffold a mod the governed way, instead of an ad-hoc one: the template already 1. **Name it.** kebab-case ``. Commands it registers are namespaced `-`; never register a built-in's name (`/diff`, `/help`) or another plugin's (`/ruos*`, `ruflo-*`). 2. **Copy the template** `plugins/ruflo-plugin-creator/templates/mod/` to the target folder. Replace `my-mod` everywhere (plugin.json `name`, the command, `MY_MOD_ACTIVE` → `_ACTIVE` in both `hooks/register.ts` and `hooks/classic.cjs`). -3. **Write the behaviour** in pure functions taking the `Host` (see `hooks/host.ts`). In `register.ts`, build the host from literal `$.noun.method(...)` calls only — the engine reads a module's `$` uses off its source, and `claude plugin validate` refuses `$` passed around, computed (`$[noun]`), or deeper than `$.noun.method(input)`. -4. **Keep the rules:** +3. **Keep the status contract.** `hooks/status.ts` writes `.claude-flow/-mod/status.json`, the file the console's Mods section reads. The folder must be `-mod` (lowercase, digits, hyphens, at most 41 characters): replace `my-mod` in `STATUS_PATH` with `-mod`. Fields: `version: 1` (required, anything else is ignored), `summary` (one line), `modVersion`, `guard` (boolean), `calls` (a **number**, not a per-tool object), `blocked` (number), `lastDenied` (a short reason, only once the mod has refused something), plus `updatedMs`/`startedMs`. Other fields are not shown. `tests/status.test.ts` asserts the shape. +4. **Write the behaviour** in pure functions taking the `Host` (see `hooks/host.ts`). In `register.ts`, build the host from literal `$.noun.method(...)` calls only — the engine reads a module's `$` uses off its source, and `claude plugin validate` refuses `$` passed around, computed (`$[noun]`), or deeper than `$.noun.method(input)`. +5. **Keep the rules:** - Observe with `const r = await next(e); …; return r`; rewrite with `next({ ...e, … })`; answer (`{ deny }`) only when you mean to stop the chain. - On `tool.check`, only ever tighten (the stricter of `await next(e)` and yours); never answer `allow` of your own. - Wrap every `$` call so a refusal degrades instead of failing the turn (admins can withhold any `$` affordance). - No `$.process.run` / `$.http.fetch` built from event input. Nothing slow on the hot path (about 10 s per dispatch). - Anything that must survive a hot reload goes in `$.store` / `$.state`, not module variables. - Options come from `userConfig` in plugin.json, not environment variables. -5. **Keep the fallback honest.** `hooks.json` is hybrid: the classic command hook runs everywhere, the module only where function hooks are on (Claude Code >= 2.1.287; 2.1.277+ with `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1`). The module sets `_ACTIVE` at `session.start`; the classic script exits early when it sees it, so nothing fires twice. -6. **Validate and test:** +6. **Keep the fallback honest.** `hooks.json` is hybrid: the classic command hook runs everywhere, the module only where function hooks are on (Claude Code >= 2.1.287; 2.1.277+ with `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1`). The module sets `_ACTIVE` at `session.start`; the classic script exits early when it sees it, so nothing fires twice. +7. **Validate and test:** ```bash claude plugin validate # lists hooked events, $ calls, env reads/writes claude plugin test # tests/*.test.ts on the engine kit claude -p --plugin-dir "/-status" # writes .claude-plugin/types/ and proves a live load npx tsc -p # against those generated types ``` -7. **Ship it in a plugin marketplace** (`marketplace.json` entry), installed with `/plugin install @` and picked up with `/reload-plugins`. If ruflo-mods is installed with `modTrust: refuse-risky`, a mod using `process.run`, `http.fetch`, `env.set` or `fs.write`, or hooking `tool.check`/`tool.call`/`*`, is refused unless its plugin id (`@`) is in `modTrustAllow` — the template sets `env.set` (the fallback handshake), so allow-list it by id. +8. **Ship it in a plugin marketplace** (`marketplace.json` entry), installed with `/plugin install @` and picked up with `/reload-plugins`. If ruflo-mods is installed with `modTrust: refuse-risky`, a mod using `process.run`, `http.fetch`, `env.set` or `fs.write`, or hooking `tool.check`/`tool.call`/`*`, is refused unless its plugin id (`@`) is in `modTrustAllow` — the template sets `env.set` (the fallback handshake), so allow-list it by id. diff --git a/plugins/ruflo-plugin-creator/templates/mod/hooks/register.ts b/plugins/ruflo-plugin-creator/templates/mod/hooks/register.ts index b5659f0094..5b372c59a4 100644 --- a/plugins/ruflo-plugin-creator/templates/mod/hooks/register.ts +++ b/plugins/ruflo-plugin-creator/templates/mod/hooks/register.ts @@ -1,33 +1,61 @@ -import type { Register } from 'claude-code' +import type { Hook, Register } from 'claude-code' import { show, statusLine, type Host } from './host' +import { newCounters, STATUS_PATH, statusText, type Counters } from './status' + +type Dollar = Parameters>[0] + +/** What one session keeps: the counters for the status file, the project root and the start time. */ +type Session = { readonly counters: Counters; root?: string; startedMs: number } + +/** A top-level function declaration, so `import type { Hook, Register } from 'claude-code' + +import { show, statusLine, type Host } from './host' + may be passed to it; a refused write is ignored (the status file is a courtesy). */ +async function flush($: Dollar, s: Session): Promise { + if (s.root === undefined) return + try { + await $.fs.write(`${s.root}/${STATUS_PATH}`, statusText(s.counters, await $.clock.now(), s.startedMs)) + } catch { + // never fail a hook over the status file + } +} /** * A mod scaffolded by ruflo-plugin-creator (ADR-404 patterns): * - observe: `const r = await next(e); …; return r` on tool.call; * - every `$` call literal, wrapped in a host adapter, refusal-tolerant; * - namespaced command (`my-mod-status`), never a built-in's name; - * - the classic fallback handed over through MY_MOD_ACTIVE. + * - the classic fallback handed over through MY_MOD_ACTIVE; + * - a status file (status.ts) the console reads: keep `calls` a number. * Hot reload re-runs register and session.start: keep anything that must * survive a reload in `$.store` or `$.state`, not in these variables. */ export const register: Register = (on, options) => { const showLine = options.statusLine !== false - let calls = 0 + const s: Session = { counters: newCounters(), startedMs: 0 } on('session.start', async ($, e, next) => { await $.env.set('MY_MOD_ACTIVE', '1').catch(() => undefined) await $.command.register({ name: 'my-mod-status', description: 'my-mod: tool calls this session' }).catch(() => undefined) + try { + s.root = (await $.session.root()) as string | undefined + s.startedMs = await $.clock.now() + } catch { + // no project root: the mod still runs, it just writes no status file + } + await flush($, s) return next(e) }) on('tool.call', async ($, e, next) => { const result = await next(e) - calls++ + s.counters.calls++ const host: Host = { status: text => $.ui.status(text) } - if (showLine) show(host, calls) + if (showLine) show(host, s.counters.calls) + await flush($, s) return result }) - on('command.run', { command: 'my-mod-status' }, () => ({ text: statusLine(calls) })) + on('command.run', { command: 'my-mod-status' }, () => ({ text: statusLine(s.counters.calls) })) } diff --git a/plugins/ruflo-plugin-creator/templates/mod/hooks/status.ts b/plugins/ruflo-plugin-creator/templates/mod/hooks/status.ts new file mode 100644 index 0000000000..b65b7c60ee --- /dev/null +++ b/plugins/ruflo-plugin-creator/templates/mod/hooks/status.ts @@ -0,0 +1,40 @@ +/** + * The status contract (ADR-446): the file the console's Mods section reads. It scans `.claude-flow` for `-mod` folders (the folder name + * must match /^[a-z0-9][a-z0-9-]{0,40}-mod$/) and keeps a file only when `version` is 1. Anything else you write is ignored by the console. + */ +export const STATUS_PATH = '.claude-flow/my-mod/status.json' + +/** What the console reads; `calls` is a number (not a per-tool object), `lastDenied` is a short reason, left out until the mod refuses something. */ +export type ModStatus = { + version: 1 + updatedMs: number + startedMs: number + modVersion: string + summary: string + guard: boolean + calls: number + blocked: number + lastDenied?: string +} + +/** The counters the mod keeps for one session. This template guards nothing, so `blocked` stays 0 and `guard` is false. */ +export type Counters = { calls: number; blocked: number; lastDenied?: string } + +export const newCounters = (): Counters => ({ calls: 0, blocked: 0 }) + +/** Builds the document; pure, so a test can assert the shape without the engine. */ +export function modStatus(c: Counters, nowMs: number, startedMs: number): ModStatus { + return { + version: 1, + updatedMs: nowMs, + startedMs, + modVersion: '0.1.0', + summary: 'counts tool calls; guards nothing', + guard: false, + calls: c.calls, + blocked: c.blocked, + ...(c.lastDenied !== undefined && { lastDenied: c.lastDenied }), + } +} + +export const statusText = (c: Counters, nowMs: number, startedMs: number): string => `${JSON.stringify(modStatus(c, nowMs, startedMs), null, 2)}\n` diff --git a/plugins/ruflo-plugin-creator/templates/mod/tests/register.test.ts b/plugins/ruflo-plugin-creator/templates/mod/tests/register.test.ts index 98ab56ea01..8d50d181a2 100644 --- a/plugins/ruflo-plugin-creator/templates/mod/tests/register.test.ts +++ b/plugins/ruflo-plugin-creator/templates/mod/tests/register.test.ts @@ -1,15 +1,21 @@ import { describe, expect, test, tier } from 'claude-code/testing' +import { STATUS_PATH, statusText } from '../hooks/status' + tier('user') describe('register', () => { - test('counts tool calls in the status line and answers /my-mod-status', async ($, on) => { + test('counts tool calls in the status line, writes the status file and answers /my-mod-status', async ($, on) => { const env = new Map() + const files = new Map() const statuses: (string | undefined)[] = [] on('session.start', ($, e) => ({ cwd: e.cwd })) on('env.set', ($, e) => (e.value === undefined ? env.delete(e.name) : env.set(e.name, e.value), { value: undefined })) on('command.register', ($, e) => ({ value: { command: e.name } })) on('ui.status', ($, e) => (statuses.push(e.text), { value: undefined })) + on('session.root', () => ({ value: '/work' })) + on('fs.write', ($, e) => (files.set(e.path, e.text), { value: undefined })) + on('clock.now', () => ({ value: 5_000 })) on('tool.call', () => ({ result: 'ok' })) on('command.run', () => ({ text: 'core' })) @@ -19,6 +25,7 @@ describe('register', () => { await $.tool.call({ tool: 'Bash', command: 'ls' }) await $.tool.call({ tool: 'Bash', command: 'pwd' }) expect(statuses.at(-1)).toBe('my-mod · 2 tool calls') + expect(files.get(`/work/${STATUS_PATH}`)).toBe(statusText({ calls: 2, blocked: 0 }, 5_000, 5_000)) const { text } = await $.command.run({ command: 'my-mod-status', diff --git a/plugins/ruflo-plugin-creator/templates/mod/tests/status.test.ts b/plugins/ruflo-plugin-creator/templates/mod/tests/status.test.ts new file mode 100644 index 0000000000..3616a51a52 --- /dev/null +++ b/plugins/ruflo-plugin-creator/templates/mod/tests/status.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, test, tier } from 'claude-code/testing' + +import { modStatus, STATUS_PATH } from '../hooks/status' + +tier('user') + +const FOLDER = /^[a-z0-9][a-z0-9-]{0,40}-mod$/ + +describe('status contract', () => { + test('the path is .claude-flow/-mod/status.json, a folder the console scans', () => { + const [dir, folder, file] = STATUS_PATH.split('/') + expect(dir).toBe('.claude-flow') + expect(folder).toMatch(FOLDER) + expect(file).toBe('status.json') + }) + + test('carries exactly the fields the console reads, calls as a number', () => { + const doc = modStatus({ calls: 3, blocked: 0 }, 9_000, 1_000) + expect(doc).toEqual({ version: 1, updatedMs: 9000, startedMs: 1000, modVersion: '0.1.0', summary: expect.any(String), guard: false, calls: 3, blocked: 0 }) + expect(typeof doc.calls).toBe('number') + expect('lastDenied' in doc).toBe(false) + expect(modStatus({ calls: 1, blocked: 1, lastDenied: 'policy' }, 2, 1).lastDenied).toBe('policy') + }) +})