mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-23 21:59:14 +09:00
Merge remote-tracking branch 'origin/main' into loop/adr451-probe
This commit is contained in:
commit
ff76bab144
13 files changed
+208
-24
No files matched your search
@@ -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"
|
||||
|
||||
@@ -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<string, unknown>): 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 }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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'
|
||||
@@ -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" \
|
||||
|
||||
@@ -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<string, unknown> = {}) => 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<string, unknown>) => 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<string, unknown>)).toBeNull()
|
||||
})
|
||||
|
||||
it('maps lastReason and lastBlocked to the refusal class, lastDenied first', () => {
|
||||
const denied = (extra: Record<string, unknown>) => 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')) }
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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 <plugin-dir>` lists the command and skill names a plugin already uses (a mod command must not reuse one); `check <plugin-dir>` 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/<name>-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.
|
||||
@@ -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"
|
||||
|
||||
@@ -13,20 +13,21 @@ Scaffold a mod the governed way, instead of an ad-hoc one: the template already
|
||||
|
||||
1. **Name it.** kebab-case `<name>`. Commands it registers are namespaced `<name>-<verb>`; 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` → `<NAME>_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/<name>-mod/status.json`, the file the console's Mods section reads. The folder must be `<name>-mod` (lowercase, digits, hyphens, at most 41 characters): replace `my-mod` in `STATUS_PATH` with `<name>-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 `<NAME>_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 `<NAME>_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 <dir> # lists hooked events, $ calls, env reads/writes
|
||||
claude plugin test <dir> # tests/*.test.ts on the engine kit
|
||||
claude -p --plugin-dir <dir> "/<name>-status" # writes .claude-plugin/types/ and proves a live load
|
||||
npx tsc -p <dir> # against those generated types
|
||||
```
|
||||
7. **Ship it in a plugin marketplace** (`marketplace.json` entry), installed with `/plugin install <name>@<marketplace>` 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 (`<name>@<marketplace>`) 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 <name>@<marketplace>` 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 (`<name>@<marketplace>`) is in `modTrustAllow` — the template sets `env.set` (the fallback handshake), so allow-list it by id.
|
||||
@@ -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<Hook<'session.start'>>[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<void> {
|
||||
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) }))
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* The status contract (ADR-446): the file the console's Mods section reads. It scans `.claude-flow` for `<name>-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`
|
||||
@@ -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<string, string>()
|
||||
const files = new Map<string, string>()
|
||||
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',
|
||||
|
||||
@@ -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/<name>-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')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user