mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-04 06:21:59 +09:00
Merge main into perf/mcp-memory-on-core
Co-Authored-By: RuFlo <ruv@ruv.net>
This commit is contained in:
commit
fca96f9fc0
171 files changed
+5180
-917
No files matched your search
@@ -739,27 +739,69 @@ function appendRecall(detailed, meta) {
|
||||
* getContext(prompt) — Called from route. Budget: <15ms.
|
||||
* Matches prompt to ranked entries, returns top-5 formatted context.
|
||||
*/
|
||||
/**
|
||||
* Inflection variants of a prompt term (plural, -ed, -ing, -ion and their
|
||||
* stems), so "migrations" finds an entry that says "migration" and "deploying"
|
||||
* finds "deploy". Exact term matching alone lost what the old trigram overlap
|
||||
* caught (#4136). The stem keeps at least 4 characters so short words stay exact.
|
||||
*/
|
||||
function termVariants(word) {
|
||||
const out = new Set([word]);
|
||||
for (const suffix of ['s', 'es', 'ed', 'ing', 'ion', 'ions']) out.add(word + suffix);
|
||||
for (const suffix of ['ions', 'ion', 'ing', 'ed', 'es', 's']) {
|
||||
if (word.length - suffix.length >= 4 && word.endsWith(suffix)) {
|
||||
const stem = word.slice(0, -suffix.length);
|
||||
out.add(stem); out.add(stem + 'e'); out.add(stem + 's');
|
||||
}
|
||||
}
|
||||
return [...out];
|
||||
}
|
||||
|
||||
function getContextDetailed(prompt) {
|
||||
if (!prompt) return null;
|
||||
|
||||
const ranked = readJSON(RANKED_PATH);
|
||||
if (!ranked || !ranked.entries || ranked.entries.length === 0) return null;
|
||||
|
||||
const promptWords = tokenize(prompt);
|
||||
const promptWords = [...new Set(tokenize(prompt))];
|
||||
if (promptWords.length === 0) return null;
|
||||
const promptTrigrams = trigrams(promptWords);
|
||||
|
||||
const ALPHA = 0.6; // content match weight
|
||||
const MIN_THRESHOLD = 0.05;
|
||||
// Query coverage is independent of entry length: a short diagnostic prompt
|
||||
// must still find its exact terms inside a long memory section (#4136).
|
||||
// IDF downweights generic terms shared by many entries. Terms absent from
|
||||
// every entry still count against coverage, so two incidental words cannot
|
||||
// hide the rest of an unrelated prompt.
|
||||
const candidates = ranked.entries.map(entry => ({ entry, words: new Set(entry.words || []) }));
|
||||
const variants = promptWords.map(termVariants);
|
||||
const hasTerm = (words, i) => variants[i].some(v => words.has(v));
|
||||
const weights = promptWords.map((word, i) => {
|
||||
const frequency = candidates.reduce((count, candidate) => count + Number(hasTerm(candidate.words, i)), 0);
|
||||
return Math.log1p((candidates.length - frequency + 0.5) / (frequency + 0.5));
|
||||
});
|
||||
const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
|
||||
if (totalWeight === 0) return null;
|
||||
|
||||
const MIN_COVERAGE = 0.15;
|
||||
const TOP_K = 5;
|
||||
|
||||
// Score each entry
|
||||
const scored = [];
|
||||
for (const entry of ranked.entries) {
|
||||
const entryTrigrams = trigrams(entry.words || []);
|
||||
const contentMatch = jaccardSimilarity(promptTrigrams, entryTrigrams);
|
||||
const score = ALPHA * contentMatch + (1 - ALPHA) * (entry.pageRank || 0);
|
||||
if (score >= MIN_THRESHOLD) {
|
||||
for (const { entry, words } of candidates) {
|
||||
let matchedWeight = 0;
|
||||
let matchedTerms = 0;
|
||||
for (let i = 0; i < promptWords.length; i++) {
|
||||
if (weights[i] > 0 && hasTerm(words, i)) {
|
||||
matchedWeight += weights[i];
|
||||
matchedTerms++;
|
||||
}
|
||||
}
|
||||
// A single common word in a long prompt is not evidence of relevance;
|
||||
// PageRank can order relevant entries but cannot make one relevant.
|
||||
if (matchedTerms < Math.min(2, promptWords.length)) continue;
|
||||
const coverage = matchedWeight / totalWeight;
|
||||
if (coverage >= MIN_COVERAGE) {
|
||||
const pageRank = Math.max(0, Math.min(1, Number(entry.pageRank) || 0));
|
||||
const score = 0.9 * coverage + 0.1 * pageRank;
|
||||
scored.push({ ...entry, score });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ MCP exposes Ruflo tools to your client. The console and mods above are Claude Co
|
||||
|
||||
<img src="docs/assets/readme/icons/terminal.svg" width="28" height="28" alt=""> **Prefer a plain terminal? Optional.** The console also runs on its own, with no Claude Code: `npx ruflo tui` (add `--plain` to print one frame for scripts). It shows Overview, Cost, Swarm, Events and Missions, plus an optional AI page. [Terminal UI guide](docs/USERGUIDE.md#terminal-ui-optional)
|
||||
|
||||
<p align="center"><img src="docs/assets/ruflo-tui-compact.svg" width="640" alt="Looping recording of the optional ruflo terminal UI cycling through Overview, Cost, Swarm, Events and Missions in a sample project"></p>
|
||||
<p align="center"><img src="docs/assets/ruflo-tui-compact.svg" width="640" alt="Looping recording of the optional ruflo terminal UI with its pictures: Overview in the Classic BBS look, the Orbital look with its moving globe, and the Swarm graph, in a sample project"></p>
|
||||
|
||||
[Compare install paths](#quick-start) · [Open the console](#console-walkthrough) · [User guide](docs/USERGUIDE.md)
|
||||
|
||||
|
||||
+19
-5
@@ -580,9 +580,9 @@ After installing, new `/slash-commands` and agent types are available immediatel
|
||||
|
||||
### Terminal UI (optional)
|
||||
|
||||
The Claude Code console (`/ruflo`) stays the main way to use Ruflo. If you are not in Claude Code, `ruflo tui` shows the same pages in any terminal. It is optional: nothing else depends on it.
|
||||
The Claude Code console (`/ruflo`) stays the main way to use Ruflo. If you are not in Claude Code, `ruflo tui` shows the same pages in any terminal, in the console's own look: the Classic BBS block-letter titles by default, or Orbital with its globe, and the pictures of the pages (the swarm graph, gauges and charts) drawn as colour and moving at the console's own speed. It is optional: nothing else depends on it.
|
||||
|
||||
<p align="center"><img src="assets/ruflo-tui-walkthrough.svg" width="100%" alt="Looping recording of ruflo tui: Overview, Cost, Swarm, Events and Missions, then the Swarm page in a small 80 by 24 window. Sample project and sample agents only."></p>
|
||||
<p align="center"><img src="assets/ruflo-tui-walkthrough.svg" width="100%" alt="Looping recording of ruflo tui with its pictures: Overview and Cost in the Classic BBS look, the Orbital look moving, the Swarm graph and Events, then Swarm in a small 80 by 24 window. Sample project and sample agents only."></p>
|
||||
|
||||
*The recording is a real run in a throwaway sample project, so some pages say `n/a` or "none yet".*
|
||||
|
||||
@@ -591,9 +591,18 @@ The Claude Code console (`/ruflo`) stays the main way to use Ruflo. If you are n
|
||||
```bash
|
||||
npx ruflo tui # open it in this terminal
|
||||
npx ruflo tui --view swarm # start on a page: overview | cost | swarm | events | missions | ai
|
||||
npx ruflo tui --plain | head -40 # print one plain frame and exit 0 (scripts, CI)
|
||||
npx ruflo tui --look orbital # the look: bbs (default, as in the console) | orbital | plain
|
||||
npx ruflo tui --fps 12 # frames per second for moving pictures, 0-30 (default 8; 0 draws them still)
|
||||
npx ruflo tui --no-anim # draw the pictures still (same as --fps 0)
|
||||
npx ruflo tui --no-pictures # the words of each picture only
|
||||
npx ruflo tui --boot # play the look's start-up screen first
|
||||
npx ruflo tui --mouse # click a page in the bar, scroll with the wheel (every action also has a key)
|
||||
npx ruflo tui --view federation # open on any console page, not only the first six
|
||||
npx ruflo tui --plain | head -40 # print one plain frame and exit 0 (scripts, CI; the plain look, no colour)
|
||||
```
|
||||
|
||||
**Pictures and colour.** Pictures are drawn in 24-bit colour when your terminal says it has it (`COLORTERM=truecolor`) and in the nearest of 256 otherwise. With `NO_COLOR`, `TERM=dumb`, `--no-pictures`, or a window narrower than 44 columns, each picture is replaced by the words it stands for. Moving pictures redraw only the rows that changed, pause while the terminal reports it is behind another window (terminals that send focus reports), and a slow terminal skips frames rather than queueing them. A look is the console's own, so the Orbital globe and masthead are the same drawings Claude Code shows.
|
||||
|
||||
Without a terminal and without `--plain`, `tui` prints a one-line hint and exits 2.
|
||||
|
||||
| Key | Does |
|
||||
@@ -602,6 +611,11 @@ Without a terminal and without `--plain`, `tui` prints a one-line hint and exits
|
||||
| `Tab` / `Shift-Tab` | Next / previous page |
|
||||
| `j` `k` or the arrow keys | Scroll |
|
||||
| `r` | Read the files again |
|
||||
| `t` | Next look: Classic BBS, Orbital, plain |
|
||||
| `0` | The main menu: the console's board, with each entry's key (press it to open that page) |
|
||||
| `:` or `/` | Go to any page by name, id or key: `settings`, `go federation`, `terminal` |
|
||||
| `Esc` or Backspace | Back to the page you were on |
|
||||
| `y` / `n` | Only while a confirm card is on screen: `y` runs the command it shows, `n` or `Esc` drops it |
|
||||
| `q` or `Ctrl-C` | Quit |
|
||||
|
||||
**What each page shows.** It reads Ruflo's own files and the CLI's output in the current project, and says `n/a` for anything it cannot measure.
|
||||
@@ -613,7 +627,7 @@ Without a terminal and without `--plain`, `tui` prints a one-line hint and exits
|
||||
- **Missions:** the mission record, read-only. Missions are made from a goal in the Claude Code console.
|
||||
- **AI (optional):** ask Codex or OpenRouter a question. This is the only page that can send anything, and it always asks first.
|
||||
|
||||
**The AI page asks first.** Pressing Enter does not send. It shows a card with exactly what would go out, and only a `y` typed while the card is on screen sends it. `n` cancels, and an unanswered card expires after 60 seconds. This is a real card:
|
||||
**The AI page asks first.** Typing a question and pressing Enter does not send it. It shows a card with exactly what would go out, and only a lone `y` (or a second Enter) while that card is on screen sends it. `n` cancels, and an unanswered card expires after 60 seconds. This is a real card:
|
||||
|
||||
```text
|
||||
Ask first, #1: this goes to OpenRouter
|
||||
@@ -629,7 +643,7 @@ y sends it · n cancels · it expires in 59 s
|
||||
- **OpenRouter** needs `OPENROUTER_API_KEY` in your environment. The key is named by its variable and never shown. Requests go only to `https://openrouter.ai` and to the HTTPS hosts you name with `--convo-targets` (or `RUFLO_TUI_CONVO_TARGETS`, syntax `endpoint:<name>=<https-base-url>|<KEY_ENV>|<model>;...`), with no redirects. `--model` picks the model (default `openrouter/auto`), and `--max-spend-usd` stops sending once the provider-reported spend reaches the cap (default `0.5`).
|
||||
- `--no-ai` turns the AI page off.
|
||||
|
||||
**Limits.** Read-only except the AI page. Tested on Linux in tmux with Node 22; Windows, macOS and Node 20 are untested. Design and decisions: [ADR-489](../v3/docs/adr/ADR-489-ruflo-tui-standalone-console.md).
|
||||
**Limits.** It reads files and changes nothing, except what you ask for by name and confirm with a single `y` on the console card, and the AI page after its own card. Tested on Linux in tmux with Node 22; Windows, macOS and Node 20 are untested. The animation was measured on Linux: at 8 frames per second it used about 2–3% of one core and 14–80 KB/s of terminal output depending on the look and window size (Orbital on a 200 by 50 window is the heaviest), and 30 frames per second about 9% and 230 KB/s. **Every console page opens here** (33 of them, from the main menu `0` or the go prompt `:`), each with the console's own body. What changes is recorded per page in ADR-489: most are read-only here because their action buttons wait for the confirm gate (the next stage); the Room needs a Claude Code session and says so on one screen; the console's terminal is this shell's AI page. **Actions.** The go prompt (`:`) also takes an action by name, such as `swarm-stop` or `evolve plan`: a read runs at once; a change shows the console's confirm card (who asked, the exact command, what it will do) pinned under the bar, and only a single `y` runs it, and only when the whole card fits on screen. A paste, Enter or a card cut off by a small window runs nothing. Settings cannot be changed here yet. On the menu the console's keys work (`b` Hive-Mind, `9` Memory Lab, …; `q` still quits and `p` is the go prompt), so a letter there is not the page-bar letter. Design and decisions: [ADR-489](../v3/docs/adr/ADR-489-ruflo-tui-standalone-console.md).
|
||||
|
||||
**In Claude Code**, the same console has an optional Orbital look and a Theme Studio: run `/ruflo themes`. See the [console README](../plugins/ruflo-console/README.md#orbital-theme).
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="666" viewBox="0 0 1024 666" role="img" aria-labelledby="t d"><title id="t">ruflo tui: the console in your terminal</title><desc id="d">A looping recording of the optional standalone ruflo terminal UI cycling through five read-only pages: Overview, Cost, Swarm, Events and Missions. Sample project and sample agents only.</desc><style>.t{font-family:DejaVu Sans Mono, Menlo, Consolas, monospace;font-size:16px}.cap{font:600 18px system-ui,Segoe UI,Helvetica,Arial,sans-serif;fill:#e6edf3}.num{font:14px DejaVu Sans Mono, Menlo, Consolas, monospace;fill:#8b949e}.p{opacity:0;animation:show 13s infinite}.p0{animation-delay:0s}.p1{animation-delay:2.6s}.p2{animation-delay:5.2s}.p3{animation-delay:7.8s}.p4{animation-delay:10.4s}@keyframes show{0%,19.990%{opacity:1}20.000%,100%{opacity:0}}@media (prefers-reduced-motion:reduce){.p{animation:none}.p0{opacity:1}}</style><defs><g id="r0"><rect fill="#c9d1d9" x="0" y="0" width="120" height="19"/><text fill="#0d1117" x="10" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">1</text><text fill="#0d1117" x="30" y="14.5" textLength="80" lengthAdjust="spacing" xml:space="preserve">Overview</text><text fill="#c9d1d9" x="140" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">2</text><text fill="#c9d1d9" x="160" y="14.5" textLength="40" lengthAdjust="spacing" xml:space="preserve">Cost</text><text fill="#c9d1d9" x="230" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">3</text><text fill="#c9d1d9" x="250" y="14.5" textLength="50" lengthAdjust="spacing" xml:space="preserve">Swarm</text><text fill="#c9d1d9" x="330" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">4</text><text fill="#c9d1d9" x="350" y="14.5" textLength="60" lengthAdjust="spacing" xml:space="preserve">Events</text><text fill="#c9d1d9" x="440" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">5</text><text fill="#c9d1d9" x="460" y="14.5" textLength="80" lengthAdjust="spacing" xml:space="preserve">Missions</text><text fill="#c9d1d9" x="570" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">6</text><text fill="#c9d1d9" x="590" y="14.5" textLength="20" lengthAdjust="spacing" xml:space="preserve">AI</text></g><g id="r2"><text x="1" y="14.5" font-size="15" font-family="Noto Color Emoji, Apple Color Emoji, Segoe UI Emoji, DejaVu Sans Mono, Menlo, Consolas, monospace">🏠</text><text fill="rgb(215,135,95)" font-weight="700" x="30" y="14.5" textLength="80" lengthAdjust="spacing" xml:space="preserve">Overview</text><text fill="rgb(215,135,95)" font-weight="700" x="120" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">—</text><text fill="rgb(215,135,95)" font-weight="700" x="140" y="14.5" textLength="40" lengthAdjust="spacing" xml:space="preserve">what</text><text fill="rgb(215,135,95)" font-weight="700" x="190" y="14.5" textLength="50" lengthAdjust="spacing" xml:space="preserve">ruflo</text><text fill="rgb(215,135,95)" font-weight="700" x="250" y="14.5" textLength="20" lengthAdjust="spacing" xml:space="preserve">is</text><text fill="rgb(215,135,95)" font-weight="700" x="280" y="14.5" textLength="50" lengthAdjust="spacing" xml:space="preserve">doing</text><text fill="rgb(215,135,95)" font-weight="700" x="340" y="14.5" textLength="50" lengthAdjust="spacing" xml:space="preserve">here:</text><text fill="rgb(215,135,95)" font-weight="700" x="400" y="14.5" textLength="110" lengthAdjust="spacing" xml:space="preserve">subsystems,</text><text fill="rgb(215,135,95)" font-weight="700" x="520" y="14.5" textLength="50" lengthAdjust="spacing" xml:space="preserve">mods,</text><text fill="rgb(215,135,95)" font-weight="700" x="580" y="14.5" textLength="60" lengthAdjust="spacing" xml:space="preserve">health</text><text fill="rgb(215,135,95)" font-weight="700" x="650" y="14.5" textLength="60" lengthAdjust="spacing" xml:space="preserve">alerts</text><text fill="rgb(215,135,95)" font-weight="700" x="720" y="14.5" textLength="30" lengthAdjust="spacing" xml:space="preserve">and</text><text fill="rgb(215,135,95)" font-weight="700" x="760" y="14.5" textLength="40" lengthAdjust="spacing" xml:space="preserve">live</text><text fill="rgb(215,135,95)" font-weight="700" x="810" y="14.5" textLength="80" lengthAdjust="spacing" xml:space="preserve">activity</text></g><g id="r4"><path transform="translate(0,0)" d="M5 19V12Q5 9.5 8 9.5H10" fill="none" stroke="rgb(175,175,255)" stroke-width="1.2"/><path d="M10 9.5h980" stroke="rgb(175,175,255)" stroke-width="1.2" fill="none"/><path transform="translate(990,0)" d="M5 19V12Q5 9.5 2 9.5H0" fill="none" stroke="rgb(175,175,255)" stroke-width="1.2"/></g><g id="r6"><path transform="translate(0,0)" d="M5 0V19" fill="none" stroke="#c9d1d9" stroke-width="1.2"/><text fill="#c9d1d9" font-weight="700" x="20" y="14.5" textLength="50" lengthAdjust="spacing" xml:space="preserve">Start</text><text fill="#c9d1d9" font-weight="700" x="80" yLine truncated
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1124" height="742" viewBox="0 0 1124 742" role="img" aria-labelledby="t d"><title id="t">ruflo tui: the console in your terminal</title><desc id="d">A looping recording of the optional standalone ruflo terminal UI with its pictures: Overview in the Classic BBS look, Orbital with its moving globe, and the Swarm graph. Sample project and sample agents only.</desc><style>.t{font-family:DejaVu Sans Mono, Menlo, Consolas, monospace;font-size:16px}.cap{font:600 18px system-ui,Segoe UI,Helvetica,Arial,sans-serif;fill:#e6edf3}.num{font:14px DejaVu Sans Mono, Menlo, Consolas, monospace;fill:#8b949e}.p{opacity:0;animation:show 9.6s infinite}.p0{animation-delay:0s}.p1{animation-delay:2.4s}.p2{animation-delay:4.8s}.p3{animation-delay:7.2s}@keyframes show{0%,24.990%{opacity:1}25.000%,100%{opacity:0}}@media (prefers-reduced-motion:reduce){.p{animation:none}.p0{opacity:1}}</style><defs><g id="r0"><rect fill="#c9d1d9" x="0" y="0" width="120" height="19"/><text fill="#0d1117" x="10" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">1</text><text fill="#0d1117" x="30" y="14.5" textLength="80" lengthAdjust="spacing" xml:space="preserve">Overview</text><text fill="#c9d1d9" x="140" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">2</text><text fill="#c9d1d9" x="160" y="14.5" textLength="40" lengthAdjust="spacing" xml:space="preserve">Cost</text><text fill="#c9d1d9" x="230" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">3</text><text fill="#c9d1d9" x="250" y="14.5" textLength="50" lengthAdjust="spacing" xml:space="preserve">Swarm</text><text fill="#c9d1d9" x="330" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">4</text><text fill="#c9d1d9" x="350" y="14.5" textLength="60" lengthAdjust="spacing" xml:space="preserve">Events</text><text fill="#c9d1d9" x="440" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">5</text><text fill="#c9d1d9" x="460" y="14.5" textLength="80" lengthAdjust="spacing" xml:space="preserve">Missions</text><text fill="#c9d1d9" x="570" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">6</text><text fill="#c9d1d9" x="590" y="14.5" textLength="20" lengthAdjust="spacing" xml:space="preserve">AI</text></g><g id="r2"><text fill="rgb(124,24,67)" x="0" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">░</text><text fill="rgb(189,33,88)" x="10" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">▒</text><text fill="rgb(255,42,109)" x="20" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">▓</text><rect fill="rgb(255,42,109)" x="40" y="0" width="10" height="19"/><rect fill="rgb(241,52,116)" x="50" y="0" width="10" height="9.5"/><rect fill="rgb(227,61,123)" x="60" y="0" width="10" height="19"/><rect fill="rgb(199,81,136)" x="80" y="0" width="10" height="19"/><rect fill="rgb(172,100,150)" x="100" y="0" width="10" height="19"/><rect fill="rgb(144,120,164)" x="120" y="0" width="10" height="19"/><rect fill="rgb(130,130,171)" x="130" y="0" width="10" height="9.5"/><rect fill="rgb(116,139,177)" x="140" y="0" width="10" height="9.5"/><rect fill="rgb(88,159,191)" x="160" y="0" width="10" height="19"/><rect fill="rgb(33,198,218)" x="200" y="0" width="10" height="19"/><rect fill="rgb(19,207,225)" x="210" y="0" width="10" height="9.5"/><rect fill="rgb(5,217,232)" x="220" y="0" width="10" height="19"/><text fill="rgb(255,71,102)" x="270" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">░</text><text fill="rgb(255,72,102)" x="280" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">▒</text><text fill="rgb(255,73,101)" x="290" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">▓</text><text fill="rgb(255,75,101)" x="300" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">▒</text><text fill="rgb(255,76,101)" x="310" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">░</text><rect fill="rgb(255,82,99)" x="360" y="0" width="10" height="19"/><rect fill="rgb(255,83,99)" x="370" y="0" width="10" height="9.5"/><rect fill="rgb(255,85,98)" x="380" y="0" width="10" height="19"/><rect fill="rgb(255,87,98)" x="400" y="0" width="10" height="19"/><rect fill="rgb(255,90,97)" x="420" y="0" width="10" height="19"/><rect fill="rgb(255,92,97)" x="440" y="0" width="10" height="19"/><rect fill="rgb(255,93,96)" x="450" y="0" width="10" height="9.5"/><rect fill="rgb(255,95,96)" x="460" y="0" width="10" height="9.5"/><rect fill="rgb(255,97,95)" x="480" y="0" width="10" height="19"/><rect fill="rgb(255,98,95)" x="490" y="0" width="10" height="9.5"/><rect fill="rgb(255,100,95)" x="500" y="0" width="10" height="19"/><rect fill="rgb(255,102,94)" x="520" y="0" width="10" height="19"/><rect fill="rgb(255,105,93)" x="540" y="0" width="10" height="19"/><rect fill="rgb(255,117,104)" x="560" y="0" width="10" height="9.5"/><rect fill="rgb(255,148,Line truncated
|
||||
|
Before Width: | Height: | Size: 133 KiB After Width: | Height: | Size: 184 KiB |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="666" viewBox="0 0 1024 666" role="img" aria-labelledby="t d"><title id="t">ruflo tui: the optional terminal UI, page by page</title><desc id="d">A looping recording of the optional ruflo terminal UI in a sample project: Overview, Cost, Swarm, Events, Missions, the AI page with its ask-first card, and the Swarm page in a small 80 by 24 window.</desc><style>.t{font-family:DejaVu Sans Mono, Menlo, Consolas, monospace;font-size:16px}.cap{font:600 18px system-ui,Segoe UI,Helvetica,Arial,sans-serif;fill:#e6edf3}.num{font:14px DejaVu Sans Mono, Menlo, Consolas, monospace;fill:#8b949e}.p{opacity:0;animation:show 22.4s infinite}.p0{animation-delay:0s}.p1{animation-delay:2.8s}.p2{animation-delay:5.6s}.p3{animation-delay:8.4s}.p4{animation-delay:11.2s}.p5{animation-delay:14s}.p6{animation-delay:16.8s}.p7{animation-delay:19.6s}@keyframes show{0%,12.490%{opacity:1}12.500%,100%{opacity:0}}@media (prefers-reduced-motion:reduce){.p{animation:none}.p0{opacity:1}}</style><defs><g id="r0"><rect fill="#c9d1d9" x="0" y="0" width="120" height="19"/><text fill="#0d1117" x="10" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">1</text><text fill="#0d1117" x="30" y="14.5" textLength="80" lengthAdjust="spacing" xml:space="preserve">Overview</text><text fill="#c9d1d9" x="140" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">2</text><text fill="#c9d1d9" x="160" y="14.5" textLength="40" lengthAdjust="spacing" xml:space="preserve">Cost</text><text fill="#c9d1d9" x="230" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">3</text><text fill="#c9d1d9" x="250" y="14.5" textLength="50" lengthAdjust="spacing" xml:space="preserve">Swarm</text><text fill="#c9d1d9" x="330" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">4</text><text fill="#c9d1d9" x="350" y="14.5" textLength="60" lengthAdjust="spacing" xml:space="preserve">Events</text><text fill="#c9d1d9" x="440" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">5</text><text fill="#c9d1d9" x="460" y="14.5" textLength="80" lengthAdjust="spacing" xml:space="preserve">Missions</text><text fill="#c9d1d9" x="570" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">6</text><text fill="#c9d1d9" x="590" y="14.5" textLength="20" lengthAdjust="spacing" xml:space="preserve">AI</text></g><g id="r2"><text x="1" y="14.5" font-size="15" font-family="Noto Color Emoji, Apple Color Emoji, Segoe UI Emoji, DejaVu Sans Mono, Menlo, Consolas, monospace">🏠</text><text fill="rgb(215,135,95)" font-weight="700" x="30" y="14.5" textLength="80" lengthAdjust="spacing" xml:space="preserve">Overview</text><text fill="rgb(215,135,95)" font-weight="700" x="120" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">—</text><text fill="rgb(215,135,95)" font-weight="700" x="140" y="14.5" textLength="40" lengthAdjust="spacing" xml:space="preserve">what</text><text fill="rgb(215,135,95)" font-weight="700" x="190" y="14.5" textLength="50" lengthAdjust="spacing" xml:space="preserve">ruflo</text><text fill="rgb(215,135,95)" font-weight="700" x="250" y="14.5" textLength="20" lengthAdjust="spacing" xml:space="preserve">is</text><text fill="rgb(215,135,95)" font-weight="700" x="280" y="14.5" textLength="50" lengthAdjust="spacing" xml:space="preserve">doing</text><text fill="rgb(215,135,95)" font-weight="700" x="340" y="14.5" textLength="50" lengthAdjust="spacing" xml:space="preserve">here:</text><text fill="rgb(215,135,95)" font-weight="700" x="400" y="14.5" textLength="110" lengthAdjust="spacing" xml:space="preserve">subsystems,</text><text fill="rgb(215,135,95)" font-weight="700" x="520" y="14.5" textLength="50" lengthAdjust="spacing" xml:space="preserve">mods,</text><text fill="rgb(215,135,95)" font-weight="700" x="580" y="14.5" textLength="60" lengthAdjust="spacing" xml:space="preserve">health</text><text fill="rgb(215,135,95)" font-weight="700" x="650" y="14.5" textLength="60" lengthAdjust="spacing" xml:space="preserve">alerts</text><text fill="rgb(215,135,95)" font-weight="700" x="720" y="14.5" textLength="30" lengthAdjust="spacing" xml:space="preserve">and</text><text fill="rgb(215,135,95)" font-weight="700" x="760" y="14.5" textLength="40" lengthAdjust="spacing" xml:space="preserve">live</text><text fill="rgb(215,135,95)" font-weight="700" x="810" y="14.5" textLength="80" lengthAdjust="spacing" xml:space="preserve">activity</text></g><g id="r4"><path transform="translate(0,0)" d="M5 19V12Q5 9.5 8 9.5H10" fill="none" stroke="rgb(175,175,255)" stroke-width="1.2"/><path d="M10 9.5h980" stroke="rgb(175,175,255)" stroke-width="1.2" fill="none"/><path transform="translate(990,0)" d="M5 19V12Q5 9.5 2 9.5H0" fill="none" stroke="rgb(175,175,255)" stroke-width="1.2"/></g><g id="r6"><path transform="translate(0,0)" d="M5 0V19" fill="none" stroke="#c9d1d9" stroke-width="1.2"/><text fill="#c9d1d9" font-weight="700" x="20" y="14.5" textLength="90" lLine truncated
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1124" height="742" viewBox="0 0 1124 742" role="img" aria-labelledby="t d"><title id="t">ruflo tui: the console in your terminal</title><desc id="d">A looping recording of the optional standalone ruflo terminal UI in the console's own looks, with pictures: Classic BBS Overview and Cost, Orbital Overview moving, Swarm graph and Events, then Swarm in a small 80 by 24 window. Sample project and sample agents only.</desc><style>.t{font-family:DejaVu Sans Mono, Menlo, Consolas, monospace;font-size:16px}.cap{font:600 18px system-ui,Segoe UI,Helvetica,Arial,sans-serif;fill:#e6edf3}.num{font:14px DejaVu Sans Mono, Menlo, Consolas, monospace;fill:#8b949e}.p{opacity:0;animation:show 18.2s infinite}.p0{animation-delay:0s}.p1{animation-delay:2.6s}.p2{animation-delay:5.2s}.p3{animation-delay:7.8s}.p4{animation-delay:10.4s}.p5{animation-delay:13s}.p6{animation-delay:15.6s}@keyframes show{0%,14.276%{opacity:1}14.286%,100%{opacity:0}}@media (prefers-reduced-motion:reduce){.p{animation:none}.p0{opacity:1}}</style><defs><g id="r0"><rect fill="#c9d1d9" x="0" y="0" width="120" height="19"/><text fill="#0d1117" x="10" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">1</text><text fill="#0d1117" x="30" y="14.5" textLength="80" lengthAdjust="spacing" xml:space="preserve">Overview</text><text fill="#c9d1d9" x="140" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">2</text><text fill="#c9d1d9" x="160" y="14.5" textLength="40" lengthAdjust="spacing" xml:space="preserve">Cost</text><text fill="#c9d1d9" x="230" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">3</text><text fill="#c9d1d9" x="250" y="14.5" textLength="50" lengthAdjust="spacing" xml:space="preserve">Swarm</text><text fill="#c9d1d9" x="330" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">4</text><text fill="#c9d1d9" x="350" y="14.5" textLength="60" lengthAdjust="spacing" xml:space="preserve">Events</text><text fill="#c9d1d9" x="440" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">5</text><text fill="#c9d1d9" x="460" y="14.5" textLength="80" lengthAdjust="spacing" xml:space="preserve">Missions</text><text fill="#c9d1d9" x="570" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">6</text><text fill="#c9d1d9" x="590" y="14.5" textLength="20" lengthAdjust="spacing" xml:space="preserve">AI</text></g><g id="r2"><text fill="rgb(124,24,67)" x="0" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">░</text><text fill="rgb(189,33,88)" x="10" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">▒</text><text fill="rgb(255,42,109)" x="20" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">▓</text><rect fill="rgb(255,42,109)" x="40" y="0" width="10" height="19"/><rect fill="rgb(241,52,116)" x="50" y="0" width="10" height="9.5"/><rect fill="rgb(227,61,123)" x="60" y="0" width="10" height="19"/><rect fill="rgb(199,81,136)" x="80" y="0" width="10" height="19"/><rect fill="rgb(172,100,150)" x="100" y="0" width="10" height="19"/><rect fill="rgb(144,120,164)" x="120" y="0" width="10" height="19"/><rect fill="rgb(130,130,171)" x="130" y="0" width="10" height="9.5"/><rect fill="rgb(116,139,177)" x="140" y="0" width="10" height="9.5"/><rect fill="rgb(88,159,191)" x="160" y="0" width="10" height="19"/><rect fill="rgb(33,198,218)" x="200" y="0" width="10" height="19"/><rect fill="rgb(19,207,225)" x="210" y="0" width="10" height="9.5"/><rect fill="rgb(5,217,232)" x="220" y="0" width="10" height="19"/><text fill="rgb(255,71,102)" x="270" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">░</text><text fill="rgb(255,72,102)" x="280" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">▒</text><text fill="rgb(255,73,101)" x="290" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">▓</text><text fill="rgb(255,75,101)" x="300" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">▒</text><text fill="rgb(255,76,101)" x="310" y="14.5" textLength="10" lengthAdjust="spacing" xml:space="preserve">░</text><rect fill="rgb(255,82,99)" x="360" y="0" width="10" height="19"/><rect fill="rgb(255,83,99)" x="370" y="0" width="10" height="9.5"/><rect fill="rgb(255,85,98)" x="380" y="0" width="10" height="19"/><rect fill="rgb(255,87,98)" x="400" y="0" width="10" height="19"/><rect fill="rgb(255,90,97)" x="420" y="0" width="10" height="19"/><rect fill="rgb(255,92,97)" x="440" y="0" width="10" height="19"/><rect fill="rgb(255,93,96)" x="450" y="0" width="10" height="9.5"/><rect fill="rgb(255,95,96)" x="460" y="0" width="10" height="9.5"/><rect fill="rgb(255,97,95)" x="480" y="0" width="10" height="19"/><rect fill="rgb(255,98,95)" x="490" y="0" width="10" height="9.5"/><rect fill="rgb(255,100,95)" x="500" y="0" width="10" height="19"/><rect fill="rgb(255,102,94)" x="520" y="0" width="10" height="19"/><rect fill="rgb(255,105,93Line truncated
|
||||
|
Before Width: | Height: | Size: 198 KiB After Width: | Height: | Size: 290 KiB |
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ruflo-adr",
|
||||
"description": "ADR lifecycle management — create, index, reconcile, supersede, check compliance, and link Architecture Decision Records to code via AgentDB hierarchical store + causal edges (supersedes/amends/depends-on/related)",
|
||||
"version": "0.5.7",
|
||||
"version": "0.5.8",
|
||||
"author": {
|
||||
"name": "ruvnet",
|
||||
"url": "https://github.com/ruvnet"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ruflo-adr",
|
||||
"description": "ADR lifecycle management \u2014 create, index, reconcile, supersede, check compliance, and link Architecture Decision Records to code via AgentDB hierarchical store + causal edges (supersedes/amends/depends-on/related)",
|
||||
"version": "0.5.7",
|
||||
"version": "0.5.8",
|
||||
"author": {
|
||||
"name": "ruvnet",
|
||||
"url": "https://github.com/ruvnet"
|
||||
|
||||
@@ -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-adr`.
|
||||
|
||||
## 0.5.8 — 2026-10-14
|
||||
- fix: the ADR parser reads the leading status keyword, so `superseded by [ADR-025](…) (date)`, `accepted (date) — note` and `Accepted (date) · **AMENDED …**` are no longer indexed as Unknown (adr-review enforces only accepted ADRs, so those ADRs were being skipped); `superseded by ADR-X` now records the supersedes edge; README.md, index.md and template*.md files in docs/adr are no longer indexed as ADRs; `adr-verify` reports any ADR left at Unknown (exit 1 under VERIFY_STRICT=1) (#4126, thanks @ronmikailov)
|
||||
|
||||
## 0.5.7 — 2026-10-12
|
||||
- fix: the shared text screen now catches `.env` and e-mailed credentials, no longer flags a model's token talk (`--max-tokens`, `/oauth/token`, "token usage"), and no longer flags values that only name where a secret lives (`./service-account.json`, `--set-secrets=NAME=NAME:latest`); every rule stays linear (#4094, thanks @proffesor-for-testing)
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ claude --plugin-dir plugins/ruflo-adr
|
||||
| `adr-create` | `/adr-create <title>` | Create a new ADR with sequential numbering and AgentDB registration |
|
||||
| `adr-index` | `/adr-index` | Build or rebuild the ADR index and dependency graph in AgentDB (add/update only — never removes) |
|
||||
| `adr-review` | `/adr-review [--branch BRANCH]` | Review code changes against accepted ADRs for compliance violations |
|
||||
| `adr-verify` | `/adr-verify` | Read back adr-patterns + adr-edges namespaces, surface dangling refs / supersede cycles / status mismatches; exits 1 on cycles |
|
||||
| `adr-verify` | `/adr-verify` | Read back adr-patterns + adr-edges namespaces, surface dangling refs / supersede cycles / Unknown statuses; exits 1 on cycles |
|
||||
| `adr-reindex` | `/adr-reindex` | Reconcile a **deleted** ADR file: drop-and-rebuild adr-patterns + adr-edges from what's on disk right now |
|
||||
|
||||
## Commands (7 subcommands)
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// #4126: real-world status lines must not fall to "Unknown", README-style index files
|
||||
// are not ADRs, and `adr-verify` surfaces any ADR left at Unknown.
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import test from 'node:test';
|
||||
|
||||
import { findAdrs, parseAdr } from '../lib/parse-adrs.mjs';
|
||||
import { unknownStatusIds } from '../lib/index-records.mjs';
|
||||
|
||||
function withAdrs(files, fn) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'ruflo-adr-4126-'));
|
||||
try {
|
||||
const dir = join(root, 'docs', 'adr');
|
||||
mkdirSync(dir, { recursive: true });
|
||||
for (const [name, body] of Object.entries(files)) writeFileSync(join(dir, name), body);
|
||||
return fn(root, dir);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
const adr = (n, statusLine, extra = '') => `# ADR-${n}: Decision ${n}\n\n${statusLine}\n- **Date**: 2026-07-02\n${extra}\n## Context\n\nSomething.\n`;
|
||||
|
||||
test('status keyword is read from the start of the line, whatever follows it', () => {
|
||||
const cases = [
|
||||
['- **Status**: superseded by [ADR-025](ADR-025-next.md) (2026-07-02)', 'superseded'],
|
||||
['- **Status**: accepted (2026-07-02) — de-risking spike closed all items', 'accepted'],
|
||||
['**Status:** Accepted (2026-08-18) · **AMENDED 2026-08-20 — see Amendment 1 for the details**', 'Accepted'],
|
||||
['- **Status**: accepted', 'accepted'],
|
||||
['**Status**: Proposed (v3.6.x)', 'Proposed'],
|
||||
['**Status:** Deprecated, replaced by ADR-040', 'Deprecated'],
|
||||
['- **Status**: Rejected — not needed', 'Rejected'],
|
||||
];
|
||||
withAdrs(Object.fromEntries(cases.map(([line], i) => [`ADR-${100 + i}-x.md`, adr(100 + i, line)])), (root, dir) => {
|
||||
cases.forEach(([line, want], i) => {
|
||||
const parsed = parseAdr(join(dir, `ADR-${100 + i}-x.md`), root);
|
||||
assert.equal(parsed.status, want, `status line: ${line}`);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('existing forms keep their result: frontmatter status, multi-word status, no status', () => {
|
||||
withAdrs({
|
||||
'ADR-200-fm.md': '---\nid: ADR-200\nstatus: accepted\n---\n# ADR-200: fm\n',
|
||||
'ADR-201-multi.md': adr(201, '- **Status**: In Progress'),
|
||||
'ADR-202-none.md': '# ADR-202: nothing\n\nNo status line here.\n',
|
||||
}, (root, dir) => {
|
||||
assert.equal(parseAdr(join(dir, 'ADR-200-fm.md'), root).status, 'accepted');
|
||||
assert.equal(parseAdr(join(dir, 'ADR-201-multi.md'), root).status, 'In Progress');
|
||||
assert.equal(parseAdr(join(dir, 'ADR-202-none.md'), root).status, 'Unknown');
|
||||
});
|
||||
});
|
||||
|
||||
test('"superseded by ADR-X" in the status line records the superseding ADR', () => {
|
||||
withAdrs({
|
||||
'ADR-009-old.md': adr(9, '- **Status**: superseded by [ADR-025](ADR-025-new.md) (2026-07-02)'),
|
||||
}, (root, dir) => {
|
||||
const parsed = parseAdr(join(dir, 'ADR-009-old.md'), root);
|
||||
assert.deepEqual(
|
||||
parsed.links.map(({ from, to, relation }) => `${relation}:${from}->${to}`),
|
||||
['supersedes:ADR-009->ADR-025'],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('index and template files in docs/adr are not ADRs', () => {
|
||||
withAdrs({
|
||||
'README.md': '# Architecture decisions\n\n| ADR | Title |\n|---|---|\n| 1 | x |\n',
|
||||
'index.md': '# Index\n',
|
||||
'template.md': '# ADR-000: template\n',
|
||||
'template-madr.md': '# ADR-000: template\n',
|
||||
'ADR-001-real.md': adr(1, '- **Status**: accepted'),
|
||||
}, (root) => {
|
||||
const found = findAdrs(root).map((p) => p.split('/').pop());
|
||||
assert.deepEqual(found, ['ADR-001-real.md']);
|
||||
});
|
||||
});
|
||||
|
||||
test('unknownStatusIds lists the ADRs the importer could not classify', () => {
|
||||
const value = (status) => `Title — Context.\n\nfile: docs/adr/x.md\nstatus: ${status}\ndate: 2026-07-02\ntags: a`;
|
||||
const entries = [
|
||||
{ key: 'ADR-001::accepted', value: value('accepted') },
|
||||
{ key: 'ADR-002::b', value: value('Unknown') },
|
||||
{ key: 'ADR-003::c', value: value('unknown') },
|
||||
{ key: 'ADR-004::d', value: 'no status line at all' },
|
||||
{ key: 'ADR-005::e' },
|
||||
];
|
||||
assert.deepEqual(unknownStatusIds(entries), ['ADR-002', 'ADR-003']);
|
||||
});
|
||||
@@ -11,6 +11,19 @@ export function adrRecordKey(adr) {
|
||||
return `${adr.id}::${basename(adr.file, '.md')}`;
|
||||
}
|
||||
|
||||
// #4126: ids of indexed ADRs whose status the parser could not classify (status: Unknown).
|
||||
// adr-verify reports these so a skipped ADR cannot hide behind a "healthy" graph.
|
||||
export function unknownStatusIds(entries) {
|
||||
const ids = [];
|
||||
for (const entry of entries) {
|
||||
const value = typeof entry?.value === 'string' ? entry.value : '';
|
||||
if (!/^status:\s*unknown\s*$/im.test(value)) continue;
|
||||
const id = String(entry.key || '').split('::')[0];
|
||||
if (id) ids.push(id);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
export function adrRecordValue(adr) {
|
||||
return `${adr.title} — ${adr.context || '(no context)'}\n\n` +
|
||||
`file: ${adr.file}\n` +
|
||||
|
||||
@@ -36,6 +36,9 @@ export function normalizeAdrId(raw) {
|
||||
return digits.length >= 4 ? `ADR-${digits}` : `ADR-${digits.padStart(3, '0')}`;
|
||||
}
|
||||
|
||||
// #4126: an index table (README.md, index.md) or a template (template*.md) in docs/adr is not an ADR.
|
||||
const NON_ADR_FILE = /^(?:readme|index|template[^/]*)\.md$/i;
|
||||
|
||||
export function findAdrs(dir, out = [], visited = new Set()) {
|
||||
let canonical;
|
||||
try { canonical = realpathSync(dir); } catch { return out; }
|
||||
@@ -50,7 +53,7 @@ export function findAdrs(dir, out = [], visited = new Set()) {
|
||||
try { st = statSync(p); } catch { continue; }
|
||||
if (st.isDirectory()) {
|
||||
findAdrs(p, out, visited);
|
||||
} else if (e.endsWith('.md') && (p.includes('/docs/adr/') || p.includes('/docs/adrs/'))) {
|
||||
} else if (e.endsWith('.md') && !NON_ADR_FILE.test(e) && (p.includes('/docs/adr/') || p.includes('/docs/adrs/'))) {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
@@ -111,7 +114,12 @@ function parseStatus(text) {
|
||||
if (m) return m[1].trim();
|
||||
// Also handle full-bold MADR style: **Status: Value** (entire phrase bolded)
|
||||
m = /^[-*+]?\s*\*\*Status:\s*([A-Za-z][A-Za-z\- ]*?)(?:\s*\([^)]*\))?\*\*\s*$/m.exec(text);
|
||||
return m ? m[1].trim() : 'Unknown';
|
||||
if (m) return m[1].trim();
|
||||
// #4126: real status lines carry more than one parenthetical: a link ("superseded by
|
||||
// [ADR-025](...) (2026-07-02)"), a date plus a note ("accepted (2026-07-02) — spike
|
||||
// closed"), an amendment marker. The leading keyword is the status; ignore the rest.
|
||||
m = /^[-*+]?\s*\*\*Status:?\*\*:?[ \t]*\**[ \t]*([A-Za-z][A-Za-z-]*)\b/m.exec(text);
|
||||
return m ? m[1] : 'Unknown';
|
||||
}
|
||||
|
||||
function parseDate(text) {
|
||||
@@ -189,6 +197,13 @@ function parseLinks(text, selfId) {
|
||||
for (const value of values('(?:Amended[ -]by|Amends)')) for (const ref of extractAdrRefs(value)) out.push({ from: selfId, to: ref, relation: 'amends' });
|
||||
for (const value of values('(?:Related|Relates)')) for (const ref of extractAdrRefs(value)) out.push({ from: selfId, to: ref, relation: 'related' });
|
||||
for (const value of values('Depends[ -]on')) for (const ref of extractAdrRefs(value)) out.push({ from: selfId, to: ref, relation: 'depends-on' });
|
||||
// #4126: "Status: superseded by ADR-025" names the superseding ADR; the edge runs
|
||||
// old -> new, the same direction a "Supersedes:" line in the newer ADR produces.
|
||||
const sb = /^[-*+]?\s*\*\*Status:?\*\*:?[ \t]*\**[ \t]*superseded[ \t]+by\b(.*)$/im.exec(text);
|
||||
if (sb) {
|
||||
const [ref] = extractAdrRefs(sb[1].replace(/\[([^\]]*)\]\([^)]*\)/g, '$1'));
|
||||
if (ref && ref !== selfId) out.push({ from: selfId, to: ref, relation: 'supersedes' });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,10 +9,10 @@ ok() { printf "PASS\n"; PASS=$((PASS+1)); }
|
||||
bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }
|
||||
|
||||
# 1. plugin.json bump + new keywords
|
||||
step "1. plugin.json declares 0.5.7 with new keywords"
|
||||
step "1. plugin.json declares 0.5.8 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.5.7" ]]; then
|
||||
bad "expected 0.5.7, got '$v'"
|
||||
if [[ "$v" != "0.5.8" ]]; then
|
||||
bad "expected 0.5.8, got '$v'"
|
||||
else
|
||||
miss=""
|
||||
for k in lifecycle compliance causal-graph mcp; do
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// VERIFY_STRICT=1 node scripts/verify.mjs # exit 1 on ANY issue (default: only on cycles)
|
||||
// ADR_ROOT=/path/to/repo node scripts/verify.mjs # same root import.mjs was run with
|
||||
|
||||
import { CLI_PKG, parseEdgeKey } from './lib/index-records.mjs';
|
||||
import { CLI_PKG, parseEdgeKey, unknownStatusIds } from './lib/index-records.mjs';
|
||||
import { spawnCliSync } from './lib/ruflo-cli.mjs';
|
||||
|
||||
// Import/reindex always use the default CLI's SQLite store (#2781). Reading
|
||||
@@ -136,6 +136,10 @@ function findCycle(node, visited, stack) {
|
||||
}
|
||||
for (const n of supersedesGraph.keys()) findCycle(n, new Set(), new Set());
|
||||
|
||||
// #4126: an ADR the importer could not classify is skipped by adr-review (it only enforces
|
||||
// accepted ADRs), so it must not hide behind a healthy-looking graph.
|
||||
const unknownStatus = [...new Set(unknownStatusIds(patternEntries))];
|
||||
|
||||
const result = {
|
||||
adrCount: adrIds.size,
|
||||
edgeCount: edges.length,
|
||||
@@ -143,6 +147,7 @@ const result = {
|
||||
danglingRefs,
|
||||
danglingFroms,
|
||||
cycles: [...new Set(cycles)],
|
||||
unknownStatus,
|
||||
};
|
||||
|
||||
if (process.env.VERIFY_FORMAT === 'json') {
|
||||
@@ -160,10 +165,15 @@ if (process.env.VERIFY_FORMAT === 'json') {
|
||||
console.log(`| Dangling 'to' refs | ${result.danglingRefs.length} |`);
|
||||
console.log(`| Dangling 'from' refs | ${result.danglingFroms.length} |`);
|
||||
console.log(`| Supersede cycles | ${result.cycles.length} |`);
|
||||
console.log(`| ADRs with Unknown status | ${result.unknownStatus.length} |`);
|
||||
if (result.danglingRefs.length) {
|
||||
console.log('\n### Sample dangling refs');
|
||||
for (const d of result.danglingRefs.slice(0, 8)) console.log(`- ${d.relation} ${d.from} → ${d.to} (missing)`);
|
||||
}
|
||||
if (result.unknownStatus.length) {
|
||||
console.log('\n### Unknown status (adr-review skips these: fix the Status line)');
|
||||
for (const id of result.unknownStatus.slice(0, 20)) console.log(`- ${id}`);
|
||||
}
|
||||
if (result.cycles.length) {
|
||||
console.log('\n### Cycles (DATA CORRUPTION — fix immediately)');
|
||||
for (const c of result.cycles) console.log(`- ${c}`);
|
||||
@@ -171,6 +181,6 @@ if (process.env.VERIFY_FORMAT === 'json') {
|
||||
}
|
||||
|
||||
const strict = process.env.VERIFY_STRICT === '1';
|
||||
if (result.cycles.length || (strict && (result.danglingRefs.length || result.danglingFroms.length))) {
|
||||
if (result.cycles.length || (strict && (result.danglingRefs.length || result.danglingFroms.length || result.unknownStatus.length))) {
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: adr-verify
|
||||
description: Read back adr-patterns + adr-edges namespaces, surface dangling refs / supersede cycles / status mismatches; exit 1 on cycles
|
||||
description: Read back adr-patterns + adr-edges namespaces, surface dangling refs / supersede cycles / Unknown statuses; exit 1 on cycles
|
||||
argument-hint: ""
|
||||
allowed-tools: Bash mcp__plugin_ruflo-core_ruflo__memory_list mcp__plugin_ruflo-core_ruflo__memory_retrieve
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ruflo-agentdb",
|
||||
"description": "Substrate plugin for Ruflo memory: AgentDB controller bridge (15 agentdb_* MCP tools), RuVector ONNX embeddings (10 embeddings_* tools incl. RaBitQ 32x quantization), and WASM HNSW pattern router (3 ruvllm_hnsw_* tools). As a mod (ADR-445): opt-in safe recall into the prompt, a write guard that keeps secrets out of memory, /agentdb, and a status file the console shows",
|
||||
"version": "0.4.9",
|
||||
"version": "0.4.10",
|
||||
"author": {
|
||||
"name": "ruvnet",
|
||||
"url": "https://github.com/ruvnet"
|
||||
|
||||
@@ -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-agentdb`.
|
||||
|
||||
## 0.4.10 — 2026-10-14
|
||||
- fix: the README no longer says the smoke script "calls each documented MCP tool": the default run is an offline structure and documentation check, and `smoke.sh --live` now really exercises the CLI in a temp directory (`agentdb_health` must report available and durable; a `agentdb_hierarchical-store` then `agentdb_hierarchical-recall` round trip must return the entry; the old L1 called a `claude-flow mcp call` command that does not exist) (#4133, thanks @ronmikailov)
|
||||
|
||||
## 0.4.9 — 2026-10-12
|
||||
- fix: the shared text screen now catches `.env` and e-mailed credentials, no longer flags a model's token talk (`--max-tokens`, `/oauth/token`, "token usage"), and no longer flags values that only name where a secret lives (`./service-account.json`, `--set-secrets=NAME=NAME:latest`); every rule stays linear (#4094, thanks @proffesor-for-testing)
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ The substrate plugin for Ruflo memory. Wraps three CLI MCP families — `agentdb
|
||||
|
||||
- **CLI:** pinned to `@claude-flow/cli` v3.6 major+minor. Patch bumps within v3.6 are expected to be no-op.
|
||||
- **AgentDB:** the CLI bundles `agentdb@^3.0.0-alpha.11`. The plugin does **not** pin the npm package — internals (alpha.11 → alpha.12 etc.) are not the plugin's contract.
|
||||
- **Verification:** the bundled smoke script is the source of truth (`bash plugins/ruflo-agentdb/scripts/smoke.sh`). If smoke passes against your CLI version, the plugin's contract holds.
|
||||
- **Verification:** `bash plugins/ruflo-agentdb/scripts/smoke.sh` checks the plugin's structure and documented surface offline; `--live` also exercises the real AgentDB tools. Passing the offline run does not prove the substrate works.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -200,10 +200,10 @@ Replacement table for bridge-unavailable mode:
|
||||
|
||||
```bash
|
||||
bash plugins/ruflo-agentdb/scripts/smoke.sh
|
||||
# Expected: "10 passed, 0 failed"
|
||||
# Expected: "0 failed" (offline checks); add --live to exercise the real tools
|
||||
```
|
||||
|
||||
The smoke script is the contract. It calls each documented MCP tool, exercises the RaBitQ workflow, and source-inspects the fallback path (no env-var gate exists to force the fallback live).
|
||||
The default smoke run is an offline structure and documentation check: it greps the plugin's docs, manifest, commands and the CLI tool source, and it does not call any MCP tool, so it passes even when the AgentDB substrate is broken. `bash plugins/ruflo-agentdb/scripts/smoke.sh --live` adds a live check in a throwaway directory: `agentdb_health` must report `available` and `durable`, and a `agentdb_hierarchical-store` then `agentdb_hierarchical-recall` round trip must return the stored entry. The RaBitQ workflow and the fallback path are only source-inspected (no env-var gate exists to force the fallback live).
|
||||
|
||||
## As a mod (0.4.7, ADR-445)
|
||||
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
# CLI MCP surface plus three documentation invariants.
|
||||
#
|
||||
# This script verifies plugin structural soundness and source-level
|
||||
# contracts. Live MCP-tool exercise (against a running daemon with the
|
||||
# bridge wired) is layered on top via the optional --live flag, but the
|
||||
# default invocation is offline-safe and CI-friendly.
|
||||
# contracts. The default invocation is offline-safe and CI-friendly and does
|
||||
# NOT call any MCP tool. Pass --live to exercise the real CLI tools
|
||||
# (agentdb_health durable check and a store/recall round trip) in a temp dir.
|
||||
set -u
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
REPO_ROOT="$(cd "$ROOT/../.." && pwd)"
|
||||
@@ -48,10 +48,10 @@ grep -q "## Namespace convention" "$ROOT/README.md" \
|
||||
&& ok || bad "Namespace convention section missing"
|
||||
|
||||
# 1. Plugin version + new keywords
|
||||
step "1. plugin.json declares version 0.4.9 with rabitq + namespace-convention keywords"
|
||||
step "1. plugin.json declares version 0.4.10 with rabitq + namespace-convention keywords"
|
||||
v=$(grep -E '"version"[[:space:]]*:' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
|
||||
if [[ "$v" != "0.4.9" ]]; then
|
||||
bad "expected 0.4.9, got '$v'"
|
||||
if [[ "$v" != "0.4.10" ]]; then
|
||||
bad "expected 0.4.10, got '$v'"
|
||||
else
|
||||
miss=""
|
||||
for k in rabitq quantization namespace-convention controller-bridge; do
|
||||
@@ -186,17 +186,32 @@ else
|
||||
bad "pluralization callout missing (must contrast pattern vs patterns)"
|
||||
fi
|
||||
|
||||
# Live mode (optional, requires daemon)
|
||||
# Live mode (optional): exercises the real CLI MCP tools in a throwaway project dir.
|
||||
# The default run above is offline and only checks plugin structure and source/doc
|
||||
# invariants; it passes even when the AgentDB substrate is broken. --live is the
|
||||
# check that proves the substrate works (#4133).
|
||||
if [[ "$LIVE" == "1" ]]; then
|
||||
step "L1 (live): agentdb_health responds (requires running daemon)"
|
||||
if command -v claude-flow >/dev/null 2>&1; then
|
||||
if claude-flow mcp call agentdb_health 2>/dev/null | grep -q '"available"'; then
|
||||
ok
|
||||
else
|
||||
bad "agentdb_health did not return an 'available' field"
|
||||
fi
|
||||
if command -v ruflo >/dev/null 2>&1; then RUFLO=(ruflo)
|
||||
elif command -v npx >/dev/null 2>&1; then RUFLO=(npx -y @claude-flow/cli@latest)
|
||||
else RUFLO=(); fi
|
||||
mcp_exec() { (cd "$LIVE_DIR" && "${RUFLO[@]}" mcp exec -t "$1" ${2:+-p "$2"} 2>/dev/null); }
|
||||
if [[ ${#RUFLO[@]} -eq 0 ]]; then
|
||||
step "L0 (live): ruflo CLI available"; bad "neither ruflo nor npx on PATH"
|
||||
else
|
||||
bad "claude-flow CLI not on PATH (skipping --live checks)"
|
||||
LIVE_DIR="$(mktemp -d)"
|
||||
mkdir -p "$LIVE_DIR/.swarm"
|
||||
trap 'rm -rf "$LIVE_DIR"' EXIT
|
||||
|
||||
step "L1 (live): agentdb_health reports available and durable"
|
||||
health="$(mcp_exec agentdb_health)"
|
||||
if grep -q '"available": true' <<<"$health" && grep -q '"durable": true' <<<"$health"; then ok
|
||||
else bad "agentdb_health must report available:true and durable:true (volatile fallback?)"; fi
|
||||
|
||||
step "L2 (live): hierarchical store then recall round trip"
|
||||
stored="$(mcp_exec agentdb_hierarchical-store '{"key":"smoke-probe","value":"zebrafish","tier":"semantic"}')"
|
||||
recalled="$(mcp_exec agentdb_hierarchical-recall '{"query":"zebrafish","topK":3}')"
|
||||
if grep -q '"key": "smoke-probe"' <<<"$stored" && grep -q '"value": "zebrafish"' <<<"$recalled"; then ok
|
||||
else bad "stored entry did not come back from agentdb_hierarchical-recall"; fi
|
||||
fi
|
||||
fi
|
||||
|
||||
|
||||
@@ -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.43.5",
|
||||
"version": "0.44.1",
|
||||
"author": {
|
||||
"name": "ruvnet",
|
||||
"url": "https://github.com/ruvnet"
|
||||
|
||||
@@ -2,6 +2,21 @@
|
||||
|
||||
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.44.1 — 2026-10-14
|
||||
- feat: `ruflo tui` Stages B and C: every console view in the terminal with its actions, pinned panes and a parity check against the console (#4188)
|
||||
|
||||
## 0.44.0 — 2026-10-14
|
||||
- feat: `ruflo tui` draws what the console draws. The pictures of the pages (the Classic BBS block-letter titles, the Orbital masthead with its globe, the swarm topology, gauges and charts) are drawn as coloured cells through a terminal Raster, 24-bit where the terminal says so and the nearest of 256 otherwise, and as the words they fall back to with NO_COLOR, a dumb terminal, `--no-pictures` or fewer than 44 columns. Every glyph is a code point that goes through the same sanitiser as the text: a control, invisible or wide one becomes a space
|
||||
- feat: the looks of the console in the terminal: Classic BBS (the default, as in the console), Orbital and plain; `--look` picks one and the `t` key steps through them; `--boot` plays the look's start-up screen first
|
||||
- feat: pictures move at `--fps` (0-30, default 8, the console's own default; 0 and `--no-anim` draw them still). An animation tick rewrites only the rows that changed, nothing is drawn while the terminal reports it is behind another window, and a slow terminal skips frames rather than queueing them
|
||||
- fix: `ruflo tui --plain` prints the plain look, so a script's frame has the same words as before
|
||||
|
||||
## 0.43.7 — 2026-10-14
|
||||
- fix: Mission Control's prose wraps on word breaks instead of ending in "…" at 80 columns (tmux): the kind description, the empty-goal hint, the lifecycle line and each planned task line (#3899, the rest of what 0.40.2 did for Approvals and a mission's objective).
|
||||
|
||||
## 0.43.6 — 2026-10-14
|
||||
- fix: the analyze page describes REVIEWERS as reviewer roles suggested from file paths and risk, not people from the history (#4163, thanks @rudycelekli)
|
||||
|
||||
## 0.43.5 — 2026-10-12
|
||||
- fix: the Skills page runs a pinned skills CLI (`skills@1.7.2`, like the AI page's pinned Codex) instead of whatever npm `latest` is: `npx -y skills` fetched and ran the newest release on every visit to the page (it lists on open) and on every add, remove, update, init and use, with the person's permissions. The hints name the pin from one constant. The pin fixes the top-level package only: its own dependencies (tar, yaml) are npm ranges resolved on the first fetch, and the first run needs the network. 1.7.2 is published by vercel-labs/skills with no install-time scripts (#4113, thanks @martinvlad)
|
||||
|
||||
|
||||
@@ -10,8 +10,8 @@
|
||||
*
|
||||
* Since ADR-472 the hook also appends `.claude-flow/data/recall-log.jsonl` (a digest of the prompt, the ids/scores/ranks it surfaced,
|
||||
* the router's pick). When a record exists it is shown as recorded. Older projects have no log, so a "past prompt" is re-scored against today's ranked file
|
||||
* with the hook's own formula (copied from .claude/helpers/intelligence.cjs getContext: tokenize, trigrams, jaccard,
|
||||
* 0.6 * match + 0.4 * pageRank, threshold 0.05, top 5) and is labelled a recomputation. `.claude-flow/neural/patterns.json`
|
||||
* with the hook's own formula (copied from .claude/helpers/intelligence.cjs getContext: tokenize, inflection variants, IDF-weighted
|
||||
* query coverage, 0.9 * coverage + 0.1 * pageRank, coverage >= 0.15, top 5; #4136) and is labelled a recomputation. `.claude-flow/neural/patterns.json`
|
||||
* (the ReasoningBank) is usually over READ_MAX and is not read; `reads.bank` says so.
|
||||
*/
|
||||
import { looksSecret } from './automate'
|
||||
@@ -32,7 +32,9 @@ export const LOGGED_SHOWN = 6
|
||||
|
||||
/** The hook's constants (intelligence.cjs getContext). */
|
||||
export const ALPHA = 0.6
|
||||
export const MIN_SCORE = 0.05
|
||||
/** Query-coverage scoring (#4136): the score is COVERAGE_WEIGHT * coverage + (1 - COVERAGE_WEIGHT) * pageRank, and an entry needs coverage >= MIN_COVERAGE. */
|
||||
export const COVERAGE_WEIGHT = 0.9
|
||||
export const MIN_COVERAGE = 0.15
|
||||
export const TOP_K = 5
|
||||
/** How many session files are read, newest first. */
|
||||
export const SESSIONS_READ = 8
|
||||
@@ -104,15 +106,30 @@ export function parseRanked(text: string | null): Ranked | null {
|
||||
|
||||
export type Scored = { entry: RankedEntry; match: number; score: number }
|
||||
|
||||
/** An entry's trigram set, built once per entry object: the render re-explains the picked prompt on every refresh (profiled: trigrams() was 70% of the time). */
|
||||
const gramsOf = new WeakMap<RankedEntry, Set<string>>()
|
||||
/**
|
||||
* Inflection variants of a prompt term (plural, -ed, -ing, -ion and their stems), as in intelligence.cjs: "migrations"
|
||||
* finds "migration", "deploying" finds "deploy". The stem keeps at least 4 characters so short words stay exact.
|
||||
*/
|
||||
export function termVariants(word: string): string[] {
|
||||
const out = new Set<string>([word])
|
||||
for (const suffix of ['s', 'es', 'ed', 'ing', 'ion', 'ions']) out.add(word + suffix)
|
||||
for (const suffix of ['ions', 'ion', 'ing', 'ed', 'es', 's']) {
|
||||
if (word.length - suffix.length >= 4 && word.endsWith(suffix)) {
|
||||
const stem = word.slice(0, -suffix.length)
|
||||
out.add(stem)
|
||||
out.add(stem + 'e')
|
||||
out.add(stem + 's')
|
||||
}
|
||||
}
|
||||
return [...out]
|
||||
}
|
||||
|
||||
const entryGrams = (entry: RankedEntry): Set<string> => {
|
||||
let grams = gramsOf.get(entry)
|
||||
|
||||
if (grams === undefined) gramsOf.set(entry, (grams = trigrams(entry.words)))
|
||||
|
||||
return grams
|
||||
/** An entry's term set, built once per entry object: the render re-explains the picked prompt on every refresh. */
|
||||
const termsOf = new WeakMap<RankedEntry, Set<string>>()
|
||||
const entryTerms = (entry: RankedEntry): Set<string> => {
|
||||
let terms = termsOf.get(entry)
|
||||
if (terms === undefined) termsOf.set(entry, (terms = new Set(entry.words)))
|
||||
return terms
|
||||
}
|
||||
|
||||
let lastExplain: { prompt: string; entries: readonly RankedEntry[]; out: Scored[] } | null = null
|
||||
@@ -121,19 +138,49 @@ let lastExplain: { prompt: string; entries: readonly RankedEntry[]; out: Scored[
|
||||
export function explainPrompt(prompt: string, entries: readonly RankedEntry[]): Scored[] {
|
||||
if (lastExplain !== null && lastExplain.prompt === prompt && lastExplain.entries === entries) return lastExplain.out
|
||||
|
||||
const words = tokenize(prompt)
|
||||
const words = [...new Set(tokenize(prompt))]
|
||||
|
||||
if (words.length === 0) return []
|
||||
|
||||
const grams = trigrams(words)
|
||||
// Query coverage is independent of entry length; IDF downweights terms shared by many entries; terms absent from every entry still count against coverage.
|
||||
const variants = words.map(termVariants)
|
||||
const terms = entries.map(entryTerms)
|
||||
const hasTerm = (set: ReadonlySet<string>, i: number): boolean => variants[i]!.some(variant => set.has(variant))
|
||||
const weights = words.map((_word, i) => {
|
||||
let frequency = 0
|
||||
|
||||
for (const set of terms) if (hasTerm(set, i)) frequency++
|
||||
|
||||
return Math.log1p((entries.length - frequency + 0.5) / (frequency + 0.5))
|
||||
})
|
||||
const totalWeight = weights.reduce((sum, weight) => sum + weight, 0)
|
||||
|
||||
if (totalWeight === 0) return []
|
||||
|
||||
const out: Scored[] = []
|
||||
|
||||
for (const entry of entries) {
|
||||
const match = jaccard(grams, entryGrams(entry))
|
||||
const score = ALPHA * match + (1 - ALPHA) * entry.pageRank
|
||||
entries.forEach((entry, index) => {
|
||||
let matchedWeight = 0
|
||||
let matchedTerms = 0
|
||||
|
||||
if (score >= MIN_SCORE) out.push({ entry, match, score })
|
||||
}
|
||||
for (let i = 0; i < words.length; i++) {
|
||||
if (weights[i]! > 0 && hasTerm(terms[index]!, i)) {
|
||||
matchedWeight += weights[i]!
|
||||
matchedTerms++
|
||||
}
|
||||
}
|
||||
|
||||
// A single common word in a long prompt is not evidence of relevance.
|
||||
if (matchedTerms < Math.min(2, words.length)) return
|
||||
|
||||
const coverage = matchedWeight / totalWeight
|
||||
|
||||
if (coverage >= MIN_COVERAGE) {
|
||||
const pageRank = Math.max(0, Math.min(1, Number(entry.pageRank) || 0))
|
||||
|
||||
out.push({ entry, match: coverage, score: COVERAGE_WEIGHT * coverage + (1 - COVERAGE_WEIGHT) * pageRank })
|
||||
}
|
||||
})
|
||||
|
||||
const best = out.sort((a, b) => b.score - a.score).slice(0, TOP_K)
|
||||
|
||||
|
||||
@@ -79,7 +79,7 @@ export const DEV: readonly DevEntry[] = [
|
||||
{ id: 'dt-diff-stats', group: 'analyze', name: 'STATS', about: 'files, additions and deletions by status', label: 'diff stats for the ref', cost: 'read', input: 'ref', args: f => need(f, ['ref'], v => tool('analyze_diff-stats', { ref: v.ref })) },
|
||||
{ id: 'dt-diff-classify', group: 'analyze', name: 'CLASSIFY', about: 'feature, fix, refactor, docs … with confidence', label: 'classify the diff', cost: 'read', input: 'ref', args: f => need(f, ['ref'], v => tool('analyze_diff-classify', { ref: v.ref })) },
|
||||
{ id: 'dt-diff-risk', group: 'analyze', name: 'RISK', about: 'the overall risk score and what drives it', label: 'risk of the diff', cost: 'read', input: 'ref', args: f => need(f, ['ref'], v => tool('analyze_diff-risk', { ref: v.ref })) },
|
||||
{ id: 'dt-diff-reviewers', group: 'analyze', name: 'REVIEWERS', about: 'who should review it, from the history', label: 'suggested reviewers for the diff', cost: 'read', input: 'ref', args: f => need(f, ['ref'], v => tool('analyze_diff-reviewers', { ref: v.ref, limit: 5 })) },
|
||||
{ id: 'dt-diff-reviewers', group: 'analyze', name: 'REVIEWERS', about: 'reviewer roles suggested from file paths and risk', label: 'suggested reviewer roles for the diff', cost: 'read', input: 'ref', args: f => need(f, ['ref'], v => tool('analyze_diff-reviewers', { ref: v.ref, limit: 5 })) },
|
||||
{ id: 'dt-file-risk', group: 'analyze', name: 'FILE RISK', about: 'the risk of changing the file in the path field', label: 'risk of changing the file at the path', cost: 'read', input: 'path', args: f => need(f, ['path'], v => tool('analyze_file-risk', { path: v.path })) },
|
||||
|
||||
{ id: 'dt-gh-repo', group: 'github', name: 'REPO', about: 'branches, commits, open issues and PRs of this repo', label: 'analyze this GitHub repo', cost: 'network', args: fixed(tool('github_repo_analyze', {})), note: GH },
|
||||
|
||||
@@ -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.43.5'
|
||||
export const CONSOLE_VERSION = '0.44.1'
|
||||
@@ -5,7 +5,7 @@ import { guidanceStatus } from '../mission-guidance'
|
||||
import { activeMission, derive, mcOf, nextTask, progressOf, rufloTaskOf, type Derived, type LedgerTask, type McTab, type MissionRecord } from '../mission-control'
|
||||
import { ACCENT, chip as inverseChip, TONE } from '../menu-colors'
|
||||
import { barCells, percentOf, stripStatus } from '../mission-strip'
|
||||
import { ago, button, clip, col, confirmHere, isBbs, row, rule, section, text, THEME, wrap, type Ctx } from './common'
|
||||
import { ago, button, clip, col, confirmHere, isBbs, paragraph, row, rule, section, text, THEME, wrap, type Ctx } from './common'
|
||||
import { GOALS_PLUGIN, isAvailable, MISSION_SKILLS, slashOf } from '../mission-skills'
|
||||
import { observationRows } from './missions'
|
||||
import { loopTabRows } from './mission-claude'
|
||||
@@ -75,12 +75,13 @@ function planRows(ctx: Ctx): RenderElement[] {
|
||||
)
|
||||
const rows: RenderElement[] = [
|
||||
...options,
|
||||
text(ctx, ` ${PROFILES.find(profile => profile.id === mc.profile)?.about ?? ''}`, { dimColor: true }),
|
||||
// #3899: prose a person reads wraps on word breaks (paragraph) instead of ending in "…" at 80 columns.
|
||||
...paragraph(ctx, ` ${PROFILES.find(profile => profile.id === mc.profile)?.about ?? ''}`, { dimColor: true }, ' '),
|
||||
]
|
||||
const planned = mc.planned
|
||||
|
||||
if (planned === null) {
|
||||
rows.push(text(ctx, ' type a goal above: the planner finds the cheapest SPARC action sequence that reaches it', { color: THEME.warn }))
|
||||
rows.push(...paragraph(ctx, ' type a goal above: the planner finds the cheapest SPARC action sequence that reaches it', { color: THEME.warn }, ' '))
|
||||
|
||||
return rows
|
||||
}
|
||||
@@ -88,7 +89,7 @@ function planRows(ctx: Ctx): RenderElement[] {
|
||||
rows.push(...guidanceRows(ctx))
|
||||
rows.push(rule(ctx, 'SPARC plan', `${planned.steps.length} tasks · cost ${planned.totalCost} · critical path ${planned.criticalCost} · ${planned.waves.length} waves`))
|
||||
|
||||
rows.push(text(ctx, ` ${lifecycleOf(planned).map(entry => `${entry.stage}${entry.steps > 1 ? ` ×${entry.steps}` : ''}`).join(' → ')}`, { color: THEME.ok, bold: true }))
|
||||
rows.push(...paragraph(ctx, ` ${lifecycleOf(planned).map(entry => `${entry.stage}${entry.steps > 1 ? ` ×${entry.steps}` : ''}`).join(' → ')}`, { color: THEME.ok, bold: true }, ' '))
|
||||
|
||||
for (const [i, wave] of planned.waves.entries()) {
|
||||
rows.push(text(ctx, ` wave ${i + 1}${wave.length > 1 ? ` · ${wave.length} in parallel` : ''}`, { bold: true, color: THEME.head }))
|
||||
@@ -96,7 +97,7 @@ function planRows(ctx: Ctx): RenderElement[] {
|
||||
for (const id of wave) {
|
||||
const step = planned.steps.find(candidate => candidate.id === id)
|
||||
|
||||
if (step !== undefined) rows.push(text(ctx, ` ${step.id} [${stageOf(step.action)}] ${step.action.title}${step.dependsOn.length > 0 ? ` · after ${step.dependsOn.join(', ')}` : ''} · ${step.action.agent}`))
|
||||
if (step !== undefined) rows.push(...paragraph(ctx, ` ${step.id} [${stageOf(step.action)}] ${step.action.title}${step.dependsOn.length > 0 ? ` · after ${step.dependsOn.join(', ')}` : ''} · ${step.action.agent}`, {}, ' '))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -143,10 +143,10 @@ export function recallRows(ctx: Ctx): RenderElement[] {
|
||||
const scored = explainPrompt(prompt, facts.ranked.entries)
|
||||
|
||||
if (logged) rows.push(text(ctx, ' no recorded recall has this prompt’s digest: recomputed against today’s ranked file, not what surfaced then', { dimColor: true }))
|
||||
if (scored.length === 0) rows.push(text(ctx, ' nothing clears the hook’s 0.05 threshold: it would surface no memory for this prompt', { color: THEME.warn }))
|
||||
if (scored.length === 0) rows.push(text(ctx, ' nothing clears the hook’s coverage threshold (0.15): it would surface no memory for this prompt', { color: THEME.warn }))
|
||||
|
||||
scored.forEach((item, index) => {
|
||||
rows.push(text(ctx, ` ${index + 1}. ${bar(item.score, scored[0]?.score ?? 1)} ${n3(item.score)} = 0.6·match ${n3(item.match)} + 0.4·pr ${n3(item.entry.pageRank)} ${item.entry.summary}`))
|
||||
rows.push(text(ctx, ` ${index + 1}. ${bar(item.score, scored[0]?.score ?? 1)} ${n3(item.score)} = 0.9·coverage ${n3(item.match)} + 0.1·pr ${n3(item.entry.pageRank)} ${item.entry.summary}`))
|
||||
})
|
||||
rows.push(button(ctx, 'recall-clear', 'clear', () => { pickPrompt(null); ctx.act.refresh() }))
|
||||
|
||||
|
||||
@@ -6,15 +6,23 @@
|
||||
*/
|
||||
import type { RenderElement } from 'claude-code'
|
||||
|
||||
import { isCompactPane, VIEWS } from '../state'
|
||||
import { isBooting, isCompactPane, VIEWS } from '../state'
|
||||
import { CARD_COLUMNS, hasCards, withCards } from './card'
|
||||
import { col, setLook, text, THEME, type Ctx } from './common'
|
||||
import { activeTheme } from '../themes'
|
||||
import { art, col, setLook, text, THEME, type Ctx } from './common'
|
||||
import { stepsRows } from './steps'
|
||||
|
||||
export function standalonePane(base: Ctx, body: (ctx: Ctx) => RenderElement): RenderElement {
|
||||
setLook(base.state.options.look)
|
||||
setLook(base.state.options.look, activeTheme(base.state).palette)
|
||||
|
||||
const ctx = base
|
||||
|
||||
// The selected boot screen (opt in with --boot): a bounded intro while the first snapshot arrives, as in the console; nothing else is drawn under it.
|
||||
if (isBooting(ctx.state, ctx.nowMs)) {
|
||||
const intro = art(ctx, ctx.pictures.get('boot'), 'boot', 'RUFLO AGENT SWARM CONSOLE · loading…')
|
||||
|
||||
return col(ctx, [intro ?? text(ctx, 'RUFLO AGENT SWARM CONSOLE · loading…', { bold: true, color: THEME.head })], 'boot')
|
||||
}
|
||||
const cardsOn = hasCards(ctx.columns, isCompactPane(ctx.state))
|
||||
const bodyCtx: Ctx = cardsOn ? { ...ctx, columns: ctx.columns - CARD_COLUMNS, cards: true, kit: withCards(ctx.kit, undefined) } : ctx
|
||||
const view = VIEWS.find(entry => entry.id === ctx.state.view)
|
||||
@@ -22,5 +30,10 @@ export function standalonePane(base: Ctx, body: (ctx: Ctx) => RenderElement): Re
|
||||
const purpose = view === undefined ? '' : view.id === 'missions' ? 'the mission record ruflo wrote: state, tasks and evidence as recorded (read-only)' : view.blurb.replace(/\s*\(f filters them\)/, '')
|
||||
const about = view === undefined ? [] : [text(ctx, `${view.icon} ${view.label} — ${purpose}`, { color: THEME.head, bold: true })]
|
||||
|
||||
return col(ctx, [...about, ...(cardsOn ? stepsRows(bodyCtx) : []), body(bodyCtx)], 'standalone-pane')
|
||||
// The page's own title art (BBS: the page's name in block letters; Orbital: the shaded masthead with its globe) when the host draws pictures: the same
|
||||
// picture the Claude Code pane leads with, without the icon row beside it. A host with no Raster gets the plain purpose line alone.
|
||||
const key = ctx.state.view === 'menu' ? 'header' : 'title'
|
||||
const banner = art(ctx, ctx.pictures.get(key), key, `ruflo console: ${ctx.state.view}`)
|
||||
|
||||
return col(ctx, [...(banner === null ? [] : [banner]), ...about, ...(cardsOn ? stepsRows(bodyCtx) : []), body(bodyCtx)], 'standalone-pane')
|
||||
}
|
||||
@@ -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.43.5"
|
||||
step "1. plugin.json declares ruflo-console 0.44.1"
|
||||
grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \
|
||||
&& grep -q '"version": "0.43.5"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
|
||||
&& grep -q '"version": "0.44.1"' "$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" \
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { parseMissions } from '../hooks/data/missions'
|
||||
import { mcOf } from '../hooks/mission-control'
|
||||
import { mcOf, setGoal } from '../hooks/mission-control'
|
||||
import { newState } from '../hooks/state'
|
||||
import { viewText } from '../hooks/views/pane'
|
||||
|
||||
@@ -64,3 +64,37 @@ describe('the Approvals pane at narrow widths (#3899)', () => {
|
||||
expect(screen.replace(/\s+/g, ' ')).toContain(objective)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Mission Control at narrow widths (#3899)', () => {
|
||||
for (const columns of [80, 60]) {
|
||||
it(`${columns} columns: the kind description and the empty-goal hint wrap instead of ending in "…"`, () => {
|
||||
const state = newState({})
|
||||
|
||||
state.view = 'missions'
|
||||
mcOf(state).tab = 'plan'
|
||||
const screen = viewText({ state, nowMs: Date.now(), columns, act }, 'missions')
|
||||
const flat = screen.replace(/\s+/g, ' ')
|
||||
|
||||
expect(flat).toContain('research, specify, design + ADRs, tests first, build, validate, secure, benchmark, learn')
|
||||
expect(flat).toContain('type a goal above: the planner finds the cheapest SPARC action sequence that reaches it')
|
||||
// Prose rows fit the pane; the section rules ('─' fills) are drawn by their own helper and are not what #3899 is about.
|
||||
expect(Math.max(...screen.split('\n').filter(line => !line.includes('─')).map(line => [...line].length))).toBeLessThanOrEqual(columns)
|
||||
})
|
||||
|
||||
it(`${columns} columns: every planned task title is shown whole`, () => {
|
||||
const state = newState({})
|
||||
|
||||
state.view = 'missions'
|
||||
mcOf(state).tab = 'plan'
|
||||
setGoal(state, 'fix the crash when the password is empty')
|
||||
const planned = mcOf(state).planned
|
||||
const screen = viewText({ state, nowMs: Date.now(), columns, act }, 'missions')
|
||||
const flat = screen.replace(/\s+/g, ' ')
|
||||
|
||||
expect(planned).not.toBeNull()
|
||||
for (const step of planned!.steps) expect(flat).toContain(step.action.title)
|
||||
// No task line ends in an ellipsis. (The skill button rows below are drawn by their own helper, one column over at 80: not part of #3899.)
|
||||
expect(screen.split('\n').filter(line => /^\s+t\d+ \[/.test(line) && line.includes('…'))).toEqual([])
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -40,13 +40,13 @@ describe('the hook’s scoring, copied', () => {
|
||||
expect(jaccard(new Set(), new Set())).toBe(0)
|
||||
})
|
||||
|
||||
it('scores 0.6 * match + 0.4 * pageRank, drops what is under 0.05, best first', () => {
|
||||
it('scores 0.9 * coverage + 0.1 * pageRank, drops weak coverage and single-term hits, best first', () => {
|
||||
const parsed = parseRanked(RANKED)
|
||||
const top = explainPrompt('authentication token refresh', parsed?.entries ?? [])
|
||||
|
||||
expect(top[0]?.entry.id).toBe('mem_a')
|
||||
expect(top.map(item => item.entry.id)).not.toContain('mem_c')
|
||||
expect(top[0]?.score).toBeCloseTo(0.6 * (top[0]?.match ?? 0) + 0.4 * 0.04, 10)
|
||||
expect(top[0]?.score).toBeCloseTo(0.9 * (top[0]?.match ?? 0) + 0.1 * 0.04, 10)
|
||||
expect(explainPrompt('the of and', parsed?.entries ?? [])).toEqual([])
|
||||
})
|
||||
|
||||
@@ -190,7 +190,7 @@ describe('the rows', () => {
|
||||
|
||||
pickPrompt(null)
|
||||
expect(text).toMatch(/recomputed, not what surfaced then/)
|
||||
expect(text).toMatch(/0\.6·match .* \+ 0\.4·pr 0\.040/)
|
||||
expect(text).toMatch(/0\.9·coverage .* \+ 0\.1·pr 0\.040/)
|
||||
})
|
||||
|
||||
it('says so when nothing clears the threshold', () => {
|
||||
@@ -199,7 +199,7 @@ describe('the rows', () => {
|
||||
const text = words(recallRows(ctxOf(facts)))
|
||||
|
||||
pickPrompt(null)
|
||||
expect(text).toMatch(/nothing clears the hook’s 0\.05 threshold/)
|
||||
expect(text).toMatch(/nothing clears the hook’s coverage threshold \(0\.15\)/)
|
||||
})
|
||||
|
||||
it('draws the lifecycle table with uses and verdict, and no rank or last-used column', () => {
|
||||
@@ -303,10 +303,10 @@ describe('what the scoring and the table promise', () => {
|
||||
expect(explainPrompt('authentication token refresh login service', parseRanked(many)?.entries ?? [])).toHaveLength(5)
|
||||
})
|
||||
|
||||
it('drops an entry that scores under 0.05 and keeps one that reaches it', () => {
|
||||
const low = parseRanked(ranked([{ ...entry('lo', 'zzz', 0.0499 / 0.4), words: [] }, { ...entry('hi', 'zzz', 0.05 / 0.4), words: [] }]))?.entries ?? []
|
||||
it('drops an entry that covers under 0.15 of the prompt or matches a single term', () => {
|
||||
const entries = parseRanked(ranked([entry('one', 'authentication gardening', 0.5), entry('two', 'authentication token gardening', 0.5)]))?.entries ?? []
|
||||
|
||||
expect(explainPrompt('authentication', [{ ...low[0], pageRank: 0.1249 } as never, { ...low[1], pageRank: 0.125 } as never]).map(item => item.entry.id)).toEqual(['hi'])
|
||||
expect(explainPrompt('authentication token refresh', entries).map(item => item.entry.id)).toEqual(['two'])
|
||||
})
|
||||
|
||||
it('prunes strictly below the threshold, never at it', () => {
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* Actions in the standalone terminal go through the console's own confirm gate (ADR-489 phase 6): the go prompt takes an action by name, a read
|
||||
* runs at once, a change raises the console's card (who asked, the exact command, the effect) and runs only on a lone y while the whole card is
|
||||
* on screen. A paste, a half-drawn card, another key or a different card never run it. Run with
|
||||
* npx vitest run plugins/ruflo-console/tests/tui-actions.spec.ts
|
||||
*/
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
|
||||
import { runTui, type TuiIO } from '../tui/run'
|
||||
import { RUFLO_FILES } from './fixtures/ruflo-run'
|
||||
|
||||
const ESC = '\u001b'
|
||||
let root: string
|
||||
let project: string
|
||||
let cli: string
|
||||
let log: string
|
||||
|
||||
beforeAll(() => {
|
||||
root = mkdtempSync(join(tmpdir(), 'tui-actions-'))
|
||||
project = join(root, 'project')
|
||||
for (const [path, body] of Object.entries(RUFLO_FILES)) {
|
||||
mkdirSync(dirname(join(project, path)), { recursive: true })
|
||||
writeFileSync(join(project, path), body)
|
||||
}
|
||||
// A stand-in for the ruflo CLI: it records the argv it was given and prints a line.
|
||||
log = join(root, 'argv.log')
|
||||
cli = join(root, 'cli.js')
|
||||
writeFileSync(cli, `require('node:fs').appendFileSync(${JSON.stringify(log)}, JSON.stringify(process.argv.slice(2)) + '\\n'); console.log('stub ran: ' + process.argv.slice(2).join(' '))\n`)
|
||||
})
|
||||
afterAll(() => rmSync(root, { recursive: true, force: true }))
|
||||
|
||||
const settle = (ms = 250) => new Promise(resolve => setTimeout(resolve, ms))
|
||||
const strip = (text: string) => text.replace(/\u001b\[[0-9;?<]*[A-Za-z]/g, '')
|
||||
/** The commands the CLI stand-in was given, minus the console's own background reads (--version, memory stats, doctor …). */
|
||||
const ran = (): string[][] => (existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line) as string[]) : []).filter(argv => argv.some(word => word === 'stop' || (word === 'worker' && argv.includes('list'))))
|
||||
|
||||
function terminal(columns = 110, rows = 36) {
|
||||
const out: string[] = []
|
||||
const listeners: Array<(chunk: string) => void> = []
|
||||
const io: TuiIO = {
|
||||
stdin: { isTTY: true, setRawMode: () => undefined, on: (_e, fn) => void listeners.push(fn as never), off: () => void listeners.splice(0), resume: () => undefined, pause: () => undefined },
|
||||
stdout: { isTTY: true, columns, rows, write: (text: string) => void out.push(text), on: () => undefined, off: () => undefined },
|
||||
stderr: { write: () => undefined },
|
||||
env: { TERM: 'xterm-256color' },
|
||||
}
|
||||
|
||||
return { io, press: (key: string) => listeners.forEach(fn => fn(key)), screen: () => strip(out.join('').split(`${ESC}[H`).pop() ?? ''), type: (text: string) => [...text].forEach(ch => listeners.forEach(fn => fn(ch))) }
|
||||
}
|
||||
|
||||
async function started(columns = 110, rows = 36) {
|
||||
const t = terminal(columns, rows)
|
||||
const running = runTui({ cwd: project, home: join(root, 'home'), look: 'plain', fps: 0, cliEntry: cli }, t.io)
|
||||
|
||||
await settle()
|
||||
|
||||
return { t, running }
|
||||
}
|
||||
|
||||
const ask = async (t: ReturnType<typeof terminal>, word: string) => {
|
||||
t.press(':')
|
||||
t.type(word)
|
||||
t.press('\r')
|
||||
await settle()
|
||||
}
|
||||
|
||||
describe('a change asked for by name', () => {
|
||||
it('raises the console\'s card with the exact command, and runs nothing until a y', async () => {
|
||||
const before = ran().length
|
||||
const { t, running } = await started()
|
||||
|
||||
await ask(t, 'swarm-stop')
|
||||
|
||||
const screen = t.screen()
|
||||
|
||||
expect(screen).toContain('CONFIRM NEEDED')
|
||||
expect(screen).toMatch(/runs: .*swarm stop/)
|
||||
expect(screen).toContain('y runs')
|
||||
expect(ran()).toHaveLength(before)
|
||||
t.press('q')
|
||||
await running
|
||||
expect(ran()).toHaveLength(before)
|
||||
})
|
||||
|
||||
it('runs exactly the command the card showed on a lone y, and shows the console own verdict on it', async () => {
|
||||
const before = ran().length
|
||||
const { t, running } = await started()
|
||||
|
||||
await ask(t, 'swarm-stop')
|
||||
t.press('y')
|
||||
await settle(600)
|
||||
|
||||
const after = ran().slice(before)
|
||||
|
||||
expect(after).toHaveLength(1)
|
||||
expect(after[0]).toEqual(expect.arrayContaining(['swarm', 'stop']))
|
||||
// The console's own verdict is shown: the stand-in CLI answered but changed nothing, and the page says so rather than claiming success.
|
||||
expect(t.screen()).toContain('stop the swarm: ruflo answered ok')
|
||||
expect(t.screen()).not.toContain('CONFIRM NEEDED')
|
||||
t.press('q')
|
||||
await running
|
||||
})
|
||||
|
||||
it('n and Esc drop the card without running it', async () => {
|
||||
const before = ran().length
|
||||
const { t, running } = await started()
|
||||
|
||||
for (const key of ['n', ESC]) {
|
||||
await ask(t, 'swarm-stop')
|
||||
expect(t.screen()).toContain('CONFIRM NEEDED')
|
||||
t.press(key)
|
||||
await settle()
|
||||
expect(t.screen()).not.toContain('CONFIRM NEEDED')
|
||||
}
|
||||
t.press('q')
|
||||
await running
|
||||
expect(ran()).toHaveLength(before)
|
||||
})
|
||||
|
||||
it('is not answered by a paste, by Enter, or by a y inside other text', async () => {
|
||||
const before = ran().length
|
||||
const { t, running } = await started()
|
||||
|
||||
await ask(t, 'swarm-stop')
|
||||
for (const text of ['yy', 'y\n', 'yes', '\r', ' y']) {
|
||||
t.press(text)
|
||||
await settle(80)
|
||||
}
|
||||
expect(ran()).toHaveLength(before)
|
||||
expect(t.screen()).toContain('CONFIRM NEEDED')
|
||||
t.press('n')
|
||||
t.press('q')
|
||||
await running
|
||||
})
|
||||
|
||||
it('is not answered when the window is too small to show the whole card', async () => {
|
||||
const before = ran().length
|
||||
const { t, running } = await started(60, 9)
|
||||
|
||||
await ask(t, 'swarm-stop')
|
||||
t.press('y')
|
||||
await settle(500)
|
||||
expect(ran()).toHaveLength(before)
|
||||
expect(t.screen()).toContain('too small')
|
||||
t.press('n')
|
||||
t.press('q')
|
||||
await running
|
||||
})
|
||||
})
|
||||
|
||||
describe('what is not an action', () => {
|
||||
it('a name that is in no entry runs nothing (a typo never starts an action), and a page name opens the page', async () => {
|
||||
const before = ran().length
|
||||
const { t, running } = await started()
|
||||
|
||||
await ask(t, 'swrmstp')
|
||||
expect(t.screen()).toContain('no page or action called "swrmstp"')
|
||||
await ask(t, 'federation')
|
||||
expect(t.screen()).toContain('Federation')
|
||||
expect(ran()).toHaveLength(before)
|
||||
t.press('q')
|
||||
await running
|
||||
})
|
||||
|
||||
it('a read runs at once with no card, through the ruflo CLI entry only', async () => {
|
||||
const before = ran().length
|
||||
const { t, running } = await started()
|
||||
|
||||
await ask(t, 'auto-workers-list')
|
||||
await settle(500)
|
||||
expect(t.screen()).not.toContain('CONFIRM NEEDED')
|
||||
expect(ran().slice(before)[0]).toEqual(expect.arrayContaining(['worker', 'list']))
|
||||
t.press('q')
|
||||
await running
|
||||
})
|
||||
|
||||
it('without a ruflo CLI entry nothing runs and the screen says so', async () => {
|
||||
const t = terminal()
|
||||
const running = runTui({ cwd: project, home: join(root, 'home'), look: 'plain', fps: 0 }, t.io)
|
||||
const before = ran().length
|
||||
|
||||
await settle()
|
||||
await ask(t, 'swarm-stop')
|
||||
t.press('y')
|
||||
await settle(500)
|
||||
expect(ran()).toHaveLength(before)
|
||||
t.press('q')
|
||||
await running
|
||||
})
|
||||
})
|
||||
@@ -39,7 +39,7 @@ const reply = (content: string, cost = 0.004) => ({ choices: [{ message: { conte
|
||||
|
||||
function open(extra: { maxSpendUsd?: number; model?: string; body?: unknown; status?: number } = {}) {
|
||||
const fetchSpy = vi.fn(async (_url: unknown, _init?: unknown) => new Response(JSON.stringify(extra.body ?? reply('hello from the stub')), { status: extra.status ?? 200 }))
|
||||
const session = openSession({ cwd: project, home: root, aiPage: { codexBin: FAKE, fetch: fetchSpy as never, ...(extra.maxSpendUsd !== undefined && { maxSpendUsd: extra.maxSpendUsd }), ...(extra.model !== undefined && { model: extra.model }) } })
|
||||
const session = openSession({ look: 'plain', fps: 0, cwd: project, home: root, aiPage: { codexBin: FAKE, fetch: fetchSpy as never, ...(extra.maxSpendUsd !== undefined && { maxSpendUsd: extra.maxSpendUsd }), ...(extra.model !== undefined && { model: extra.model }) } })
|
||||
|
||||
session.show('ai')
|
||||
|
||||
@@ -251,7 +251,7 @@ describe('Codex', () => {
|
||||
})
|
||||
|
||||
it('without the pinned release the answer says so and nothing falls back to PATH or current', async () => {
|
||||
const session = openSession({ cwd: project, home: join(root, 'no-codex-here'), aiPage: { fetch: vi.fn() as never } })
|
||||
const session = openSession({ look: 'plain', fps: 0, cwd: project, home: join(root, 'no-codex-here'), aiPage: { fetch: vi.fn() as never } })
|
||||
|
||||
session.show('ai')
|
||||
|
||||
@@ -304,12 +304,12 @@ describe('the page', () => {
|
||||
const out: string[] = []
|
||||
const io = (): TuiIO => ({ stdin: { on: () => undefined, off: () => undefined, resume: () => undefined, pause: () => undefined }, stdout: { columns: 100, rows: 30, write: text => void out.push(text) }, stderr: { write: () => undefined }, env: {} })
|
||||
|
||||
expect(await runTui({ cwd: project, home: root, plain: true, view: 'ai', aiPage: { codexBin: FAKE } }, io())).toBe(0)
|
||||
expect(await runTui({ look: 'plain', fps: 0, cwd: project, home: root, plain: true, view: 'ai', aiPage: { codexBin: FAKE } }, io())).toBe(0)
|
||||
expect(out.join('')).toMatch(/codex .*ready|codex .*pinned/)
|
||||
expect(out.join('')).toContain('openrouter')
|
||||
expect(out.join('')).not.toContain(KEY)
|
||||
out.length = 0
|
||||
expect(await runTui({ cwd: project, home: root, plain: true, view: 'ai' }, io())).toBe(0)
|
||||
expect(await runTui({ look: 'plain', fps: 0, cwd: project, home: root, plain: true, view: 'ai' }, io())).toBe(0)
|
||||
expect(out.join('')).toContain('The AI page is off')
|
||||
})
|
||||
})
|
||||
@@ -70,7 +70,7 @@ describe('keys', () => {
|
||||
expect([keyOf('o'), keyOf('c'), keyOf('s'), keyOf('e'), keyOf('m'), keyOf('a')]).toEqual([{ page: 'overview' }, { page: 'cost' }, { page: 'swarm' }, { page: 'events' }, { page: 'missions' }, { page: 'ai' }])
|
||||
expect([keyOf('\t'), keyOf(`${ESC}[C`), keyOf('l')]).toEqual(['next', 'next', 'next'])
|
||||
expect([keyOf(`${ESC}[Z`), keyOf(`${ESC}[D`), keyOf('h')]).toEqual(['prev', 'prev', 'prev'])
|
||||
expect([keyOf('0'), keyOf('7'), keyOf('9'), keyOf('x'), keyOf(`${ESC}]0;t\u0007`)]).toEqual([null, null, null, null, null])
|
||||
expect([keyOf('7'), keyOf('8'), keyOf('9'), keyOf('x'), keyOf(`${ESC}]0;t\u0007`)]).toEqual([null, null, null, null, null])
|
||||
})
|
||||
|
||||
it('has no key for Room: its content is a message box and Claude sessions this host does not have', () => {
|
||||
@@ -87,8 +87,8 @@ describe('page bar and key line', () => {
|
||||
expect(widthOf(navLine('missions', 60, '256'))).toBeLessThanOrEqual(60)
|
||||
})
|
||||
|
||||
it('has a short key line for a narrow terminal and says read-only on a wide one', () => {
|
||||
expect(keyLine(100)).toContain('read-only')
|
||||
it('has a short key line for a narrow terminal and says ask first on a wide one', () => {
|
||||
expect(keyLine(100)).toContain('ask first')
|
||||
expect(keyLine(100)).toContain('q quit')
|
||||
expect(keyLine(50)).toBe('1-6 page · j/k scroll · q quit')
|
||||
expect(keyLine(25)).toBe('1-6 page · q quit')
|
||||
@@ -100,7 +100,7 @@ describe('every page, on a host with no Claude session and no mouse', () => {
|
||||
for (const columns of [80, 120]) {
|
||||
it(`draws all six pages at ${columns} columns, no wider than the terminal, with none of Claude Code's chrome`, async () => {
|
||||
for (const view of TUI_VIEWS) {
|
||||
const session = openSession({ cwd: project, home: join(root, 'home'), aiPage: {} })
|
||||
const session = openSession({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home'), aiPage: {} })
|
||||
|
||||
try {
|
||||
session.show(view)
|
||||
@@ -123,7 +123,7 @@ describe('every page, on a host with no Claude session and no mouse', () => {
|
||||
}
|
||||
|
||||
it('the Missions page reads the mission record only: no goal field, no plan, no research launch', async () => {
|
||||
const session = openSession({ cwd: project, home: join(root, 'home') })
|
||||
const session = openSession({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') })
|
||||
|
||||
try {
|
||||
session.show('missions')
|
||||
@@ -139,7 +139,7 @@ describe('every page, on a host with no Claude session and no mouse', () => {
|
||||
})
|
||||
|
||||
it('hostile mission text: words only reach the screen (no escape, no token)', async () => {
|
||||
const session = openSession({ cwd: hostile, home: join(root, 'home') })
|
||||
const session = openSession({ look: 'plain', fps: 0, cwd: hostile, home: join(root, 'home') })
|
||||
|
||||
try {
|
||||
session.show('missions')
|
||||
@@ -160,7 +160,7 @@ describe('every page, on a host with no Claude session and no mouse', () => {
|
||||
describe('the terminal loop', () => {
|
||||
it('jumps to a page on a digit, cycles with tab and shift-tab, and the page bar follows', async () => {
|
||||
const t = terminal()
|
||||
const running = runTui({ cwd: project, home: join(root, 'home') }, t.io)
|
||||
const running = runTui({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') }, t.io)
|
||||
|
||||
await settle()
|
||||
t.press('3')
|
||||
@@ -181,14 +181,14 @@ describe('the terminal loop', () => {
|
||||
|
||||
it('highlights 6 AI in the page bar on the AI page, started there or reached by key (not the page before it)', async () => {
|
||||
const started = terminal()
|
||||
const first = runTui({ cwd: project, home: join(root, 'home'), view: 'ai', aiPage: { codexBin: '/nonexistent/codex' } }, started.io)
|
||||
const first = runTui({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home'), view: 'ai', aiPage: { codexBin: '/nonexistent/codex' } }, started.io)
|
||||
|
||||
await settle()
|
||||
started.press('\u0003')
|
||||
await first
|
||||
|
||||
const reached = terminal()
|
||||
const second = runTui({ cwd: project, home: join(root, 'home'), aiPage: { codexBin: '/nonexistent/codex' } }, reached.io)
|
||||
const second = runTui({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home'), aiPage: { codexBin: '/nonexistent/codex' } }, reached.io)
|
||||
|
||||
await settle()
|
||||
reached.press('5')
|
||||
@@ -210,7 +210,7 @@ describe('the terminal loop', () => {
|
||||
it('fills the terminal exactly: the page bar on the first row, the key line on the last', async () => {
|
||||
for (const rows of [24, 40]) {
|
||||
const t = terminal(100, rows)
|
||||
const running = runTui({ cwd: project, home: join(root, 'home') }, t.io)
|
||||
const running = runTui({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') }, t.io)
|
||||
|
||||
await settle()
|
||||
t.press('4')
|
||||
@@ -228,7 +228,7 @@ describe('the terminal loop', () => {
|
||||
|
||||
it('redraws at the new width on a resize, clearing the screen first', async () => {
|
||||
const t = terminal(120, 30)
|
||||
const running = runTui({ cwd: project, home: join(root, 'home') }, t.io)
|
||||
const running = runTui({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') }, t.io)
|
||||
|
||||
await settle()
|
||||
|
||||
@@ -247,7 +247,7 @@ describe('the terminal loop', () => {
|
||||
|
||||
it('under 60 columns it draws the position bar and the short key line; under 40 it says how wide it needs to be', async () => {
|
||||
const narrow = terminal(52, 24)
|
||||
const running = runTui({ cwd: project, home: join(root, 'home') }, narrow.io)
|
||||
const running = runTui({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') }, narrow.io)
|
||||
|
||||
await settle()
|
||||
expect(plain(narrow.out.join(''))).toContain('‹ 1/6 Overview ›')
|
||||
|
||||
@@ -50,7 +50,7 @@ const lit = (row: string) => [...row.matchAll(/\u001b\[7m ([^\u001b]*) \u001b\[0
|
||||
|
||||
async function run(columns = 100) {
|
||||
const t = terminal(columns)
|
||||
const running = runTui({ cwd: project, home: join(root, 'home'), aiPage: {} }, t.io)
|
||||
const running = runTui({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home'), aiPage: {} }, t.io)
|
||||
|
||||
await settle(250)
|
||||
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
/**
|
||||
* Every console view has a recorded decision for the standalone terminal (ADR-489 phase 5), the shell opens each one, and the go prompt, the
|
||||
* main-menu keys, Back and the mouse reach them. Run with
|
||||
* npx vitest run plugins/ruflo-console/tests/tui-parity.spec.ts
|
||||
*/
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
|
||||
import { VIEWS } from '../hooks/state'
|
||||
import { navHit, navLine, runTui, type TuiIO } from '../tui/run'
|
||||
import { PAGE_IDS, PARITY } from '../tui/parity'
|
||||
import { openSession } from '../tui/session'
|
||||
import { RUFLO_FILES } from './fixtures/ruflo-run'
|
||||
|
||||
const ESC = '\u001b'
|
||||
const ADR = join(__dirname, '../../../v3/docs/adr/ADR-489-ruflo-tui-standalone-console.md')
|
||||
let root: string
|
||||
let project: string
|
||||
|
||||
beforeAll(() => {
|
||||
root = mkdtempSync(join(tmpdir(), 'tui-parity-'))
|
||||
project = join(root, 'project')
|
||||
for (const [path, body] of Object.entries(RUFLO_FILES)) {
|
||||
mkdirSync(dirname(join(project, path)), { recursive: true })
|
||||
writeFileSync(join(project, path), body)
|
||||
}
|
||||
})
|
||||
afterAll(() => rmSync(root, { recursive: true, force: true }))
|
||||
|
||||
const settle = (ms = 150) => new Promise(resolve => setTimeout(resolve, ms))
|
||||
const strip = (text: string) => text.replace(/\u001b\[[0-9;?<]*[A-Za-z]/g, '')
|
||||
|
||||
describe('a decision for every console view', () => {
|
||||
it('has a row in PARITY for each view in VIEWS, and for nothing else', () => {
|
||||
const ids = [...VIEWS.map(view => view.id), 'agent'].sort()
|
||||
|
||||
expect(Object.keys(PARITY).sort()).toEqual(ids)
|
||||
expect(PAGE_IDS).toEqual([...VIEWS.map(view => view.id), 'ai'])
|
||||
for (const [id, entry] of Object.entries(PARITY)) {
|
||||
expect(['same', 'partial', 'equivalent', 'claude-only'], id).toContain(entry.status)
|
||||
expect(entry.why.length, id).toBeGreaterThan(8)
|
||||
}
|
||||
})
|
||||
|
||||
it('is written out in ADR-489, row for row, so the guide and the code cannot disagree', () => {
|
||||
const adr = readFileSync(ADR, 'utf8')
|
||||
|
||||
for (const view of [...VIEWS, { id: 'agent', label: 'Agent drill-down' }]) {
|
||||
const entry = PARITY[view.id as keyof typeof PARITY]
|
||||
|
||||
expect(adr, view.id).toContain(`| \`${view.id}\` | ${view.label} | ${entry.status} | ${entry.why} |`)
|
||||
}
|
||||
})
|
||||
|
||||
it('opens every view without throwing, in words only, with nothing but colour in the bytes', async () => {
|
||||
const session = openSession({ cwd: project, home: join(root, 'home'), look: 'plain', fps: 0 })
|
||||
|
||||
await session.refresh()
|
||||
for (const view of VIEWS) {
|
||||
session.show(view.id)
|
||||
|
||||
const lines = session.frame(100, 'none', 40)
|
||||
|
||||
expect(lines.length, view.id).toBeGreaterThan(0)
|
||||
expect(lines.join('\n'), view.id).not.toMatch(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/)
|
||||
}
|
||||
session.stop()
|
||||
})
|
||||
|
||||
it('sends the console terminal to the AI page and says plainly that the Room needs Claude Code', async () => {
|
||||
const session = openSession({ cwd: project, home: join(root, 'home'), look: 'plain', fps: 0, aiPage: {} })
|
||||
|
||||
session.show('terminal')
|
||||
expect(session.page).toBe('ai')
|
||||
session.show('room')
|
||||
expect(session.page).toBe('room')
|
||||
|
||||
const note = session.frame(100, 'none', 30).join('\n')
|
||||
|
||||
expect(note).toContain('Room: Claude Code only')
|
||||
expect(note).toContain(PARITY.room.why)
|
||||
session.stop()
|
||||
})
|
||||
|
||||
it('draws the main menu entries as words next to their keys (they were blank)', async () => {
|
||||
const session = openSession({ cwd: project, home: join(root, 'home'), look: 'plain', fps: 0 })
|
||||
|
||||
await session.refresh()
|
||||
session.show('menu')
|
||||
|
||||
const text = session.frame(100, 'none', 60).join('\n')
|
||||
|
||||
for (const word of ['Missions', 'Overview', 'Hive-Mind', 'Memory Lab', 'Settings']) expect(text, word).toContain(word)
|
||||
session.stop()
|
||||
})
|
||||
})
|
||||
|
||||
function terminal(columns = 110, rows = 36) {
|
||||
const out: string[] = []
|
||||
const listeners: Array<(chunk: string) => void> = []
|
||||
const io: TuiIO = {
|
||||
stdin: { isTTY: true, setRawMode: () => undefined, on: (_e, fn) => void listeners.push(fn as never), off: () => void listeners.splice(0), resume: () => undefined, pause: () => undefined },
|
||||
stdout: { isTTY: true, columns, rows, write: (text: string) => void out.push(text), on: () => undefined, off: () => undefined },
|
||||
stderr: { write: () => undefined },
|
||||
env: { TERM: 'xterm-256color' },
|
||||
}
|
||||
|
||||
return { io, out, press: (key: string) => listeners.forEach(fn => fn(key)), screen: () => strip(out.join('').split(`${ESC}[H`).pop() ?? '') }
|
||||
}
|
||||
|
||||
const options = { look: 'plain' as const, fps: 0 }
|
||||
|
||||
describe('getting to every view from the keys', () => {
|
||||
it('0 opens the menu, a menu key opens that view, and Esc comes back to where you were', async () => {
|
||||
const t = terminal()
|
||||
const running = runTui({ cwd: project, home: join(root, 'home'), ...options }, t.io)
|
||||
|
||||
await settle()
|
||||
t.press('0')
|
||||
await settle()
|
||||
expect(t.screen()).toContain('Main Menu')
|
||||
expect(navLine('menu', 110, 'none')).toContain('[Main Menu]')
|
||||
t.press('b') // Hive-Mind on the board (b is Page Up everywhere else)
|
||||
await settle()
|
||||
expect(t.screen()).toMatch(/Hive-Mind/)
|
||||
t.press(ESC)
|
||||
await settle()
|
||||
expect(t.screen()).toContain('Main Menu')
|
||||
t.press(ESC)
|
||||
await settle()
|
||||
expect(t.screen()).toMatch(/Overview/)
|
||||
t.press('q')
|
||||
await running
|
||||
})
|
||||
|
||||
it('has a go prompt that takes a name, an id or a prefix, and says so when there is no such page', async () => {
|
||||
const t = terminal()
|
||||
const running = runTui({ cwd: project, home: join(root, 'home'), ...options }, t.io)
|
||||
|
||||
await settle()
|
||||
t.press(':')
|
||||
for (const ch of 'go federation') t.press(ch)
|
||||
expect(t.screen()).toContain('go> go federation')
|
||||
t.press('\r')
|
||||
await settle()
|
||||
expect(t.screen()).toContain('Federation')
|
||||
t.press('/')
|
||||
for (const ch of 'nonsense') t.press(ch)
|
||||
t.press('\r')
|
||||
await settle()
|
||||
expect(t.screen()).toContain('no page or action called "nonsense"')
|
||||
t.press(':')
|
||||
for (const ch of 'term') t.press(ch)
|
||||
t.press('\r')
|
||||
await settle()
|
||||
expect(t.screen()).toMatch(/AI/)
|
||||
t.press('q')
|
||||
await running
|
||||
})
|
||||
|
||||
it('lets a pasted escape sequence into the prompt as nothing (the prompt keeps text, not bytes)', async () => {
|
||||
const t = terminal()
|
||||
const running = runTui({ cwd: project, home: join(root, 'home'), ...options }, t.io)
|
||||
|
||||
await settle()
|
||||
t.press(':')
|
||||
t.press(`${ESC}]0;evil\u0007`)
|
||||
expect(t.screen()).toContain('go> ▌')
|
||||
t.press(ESC)
|
||||
t.press('q')
|
||||
await running
|
||||
})
|
||||
|
||||
it('--view takes any page', async () => {
|
||||
const t = terminal()
|
||||
const running = runTui({ cwd: project, home: join(root, 'home'), view: 'federation', ...options }, t.io)
|
||||
|
||||
await settle()
|
||||
expect(t.screen()).toContain('Federation')
|
||||
t.press('q')
|
||||
await running
|
||||
})
|
||||
})
|
||||
|
||||
describe('the mouse', () => {
|
||||
it('is off unless asked for: no reporting is switched on, and report bytes are not read as keys', async () => {
|
||||
const t = terminal()
|
||||
const running = runTui({ cwd: project, home: join(root, 'home'), ...options }, t.io)
|
||||
|
||||
await settle()
|
||||
expect(t.out.join('')).not.toContain('?1000h')
|
||||
t.press(`${ESC}[<0;14;1M`)
|
||||
await settle()
|
||||
expect(t.screen()).toMatch(/Overview/)
|
||||
t.press('q')
|
||||
await running
|
||||
})
|
||||
|
||||
it('with --mouse: a click on a page chip opens it, the wheel scrolls, and reporting is switched off on q', async () => {
|
||||
const t = terminal(110, 12)
|
||||
const running = runTui({ cwd: project, home: join(root, 'home'), mouse: true, ...options }, t.io)
|
||||
|
||||
await settle()
|
||||
expect(t.out.join('')).toContain(`${ESC}[?1000h${ESC}[?1006h`)
|
||||
expect(navHit(1, 110)).toBe('overview')
|
||||
expect(navHit(14, 110)).toBe('cost')
|
||||
t.press(`${ESC}[<0;14;1M`)
|
||||
await settle()
|
||||
expect(t.screen()).toMatch(/Cost/)
|
||||
t.press(`${ESC}[<65;5;5M`)
|
||||
await settle()
|
||||
expect(t.screen()).toMatch(/\d+-\d+\/\d+/)
|
||||
t.press(`${ESC}[<0;14;1m`) // a release is not a click
|
||||
t.press('q')
|
||||
await running
|
||||
expect(t.out.join('').endsWith(`${ESC}[?1006l${ESC}[?1000l${ESC}[?1004l${ESC}[?25h${ESC}[?1049l`)).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* `ruflo tui` draws what the console draws (ADR-489 phase 4): the page's title art and its pictures as coloured cells, in the console's
|
||||
* own look (Classic BBS by default, Orbital, plain), moving at `--fps`, redrawing only the rows that changed, still with `--no-anim`,
|
||||
* and in words alone where there is no colour or no room. Run with
|
||||
* npx vitest run plugins/ruflo-console/tests/tui-pictures.spec.ts
|
||||
*/
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
|
||||
import { fpsOf, keyOf, runTui, type TuiIO } from '../tui/run'
|
||||
import { LOOKS, openSession } from '../tui/session'
|
||||
import { RUFLO_FILES } from './fixtures/ruflo-run'
|
||||
|
||||
const ESC = '\u001b'
|
||||
const BLOCKS = /[█▀▄▌▐▓▒░⣿⠁-⣿]/
|
||||
let root: string
|
||||
let project: string
|
||||
|
||||
beforeAll(() => {
|
||||
root = mkdtempSync(join(tmpdir(), 'tui-pictures-'))
|
||||
project = join(root, 'project')
|
||||
for (const [path, body] of Object.entries(RUFLO_FILES)) {
|
||||
mkdirSync(dirname(join(project, path)), { recursive: true })
|
||||
writeFileSync(join(project, path), body)
|
||||
}
|
||||
})
|
||||
afterAll(() => rmSync(root, { recursive: true, force: true }))
|
||||
|
||||
const settle = (ms = 120) => new Promise(resolve => setTimeout(resolve, ms))
|
||||
const strip = (text: string) => text.replace(/\u001b\[[0-9;?]*[A-Za-z]/g, '')
|
||||
|
||||
async function opened(options: Record<string, unknown> = {}) {
|
||||
const session = openSession({ cwd: project, home: join(root, 'home'), ...options })
|
||||
|
||||
await session.refresh()
|
||||
|
||||
return session
|
||||
}
|
||||
|
||||
describe('the pictures in a frame', () => {
|
||||
it('lead the page in the console look: block-letter title art in colour, over the words of the page', async () => {
|
||||
const session = await opened({ look: 'bbs', fps: 0 })
|
||||
const frame = session.frame(100, 'truecolor', 30)
|
||||
const text = strip(frame.join('\n'))
|
||||
|
||||
expect(frame.join('\n')).toMatch(/\u001b\[0;38;2;\d+;\d+;\d+m/)
|
||||
expect(text).toMatch(BLOCKS)
|
||||
expect(text).toContain('Overview')
|
||||
expect(frame.every(line => strip(line).length <= 400)).toBe(true)
|
||||
session.stop()
|
||||
})
|
||||
|
||||
it('are in Orbital too: the shaded RUFLO masthead with its globe, and the swarm graph on the Swarm page', async () => {
|
||||
const session = await opened({ look: 'orbital', fps: 0 })
|
||||
|
||||
session.show('swarm')
|
||||
|
||||
const text = strip(session.frame(120, '256', 40).join('\n'))
|
||||
|
||||
expect(text).toContain('RUFLO / AGENT SWARM CONSOLE')
|
||||
expect(text).toMatch(/█/)
|
||||
expect(text).not.toContain('graph needs a terminal')
|
||||
session.stop()
|
||||
})
|
||||
|
||||
it('are drawn as words alone with no colour, with --no-pictures, and below 44 columns', async () => {
|
||||
const colourless = await opened({ look: 'bbs', fps: 0 })
|
||||
const off = await opened({ look: 'bbs', fps: 0, pictures: false })
|
||||
const narrow = await opened({ look: 'bbs', fps: 0 })
|
||||
|
||||
expect(colourless.frame(100, 'none', 30).join('\n')).not.toMatch(/\u001b/)
|
||||
expect(strip(off.frame(100, 'truecolor', 30).join('\n'))).not.toMatch(/[█▓]{3}/)
|
||||
expect(narrow.frame(40, 'truecolor', 30).join('\n')).not.toMatch(/\u001b\[0;38/)
|
||||
for (const session of [colourless, off, narrow]) session.stop()
|
||||
})
|
||||
|
||||
it('keep a card\'s rows inside its borders (a picture is cut to the room it has)', async () => {
|
||||
const session = await opened({ look: 'orbital', fps: 0 })
|
||||
|
||||
session.show('swarm')
|
||||
|
||||
for (const columns of [60, 80, 132, 200]) {
|
||||
const widths = session.frame(columns, 'truecolor', 40).map(line => [...strip(line)].length)
|
||||
|
||||
expect(Math.max(...widths)).toBeLessThanOrEqual(columns + 3)
|
||||
}
|
||||
session.stop()
|
||||
})
|
||||
|
||||
it('stand still at fps 0 and move at fps above 0', async () => {
|
||||
const still = await opened({ look: 'orbital', fps: 0 })
|
||||
const moving = await opened({ look: 'orbital', fps: 20 })
|
||||
const first = still.frame(100, 'truecolor', 30).join('\n')
|
||||
const a = moving.frame(100, 'truecolor', 30).join('\n')
|
||||
|
||||
await settle(350)
|
||||
|
||||
expect(still.frame(100, 'truecolor', 30).join('\n')).toBe(first)
|
||||
expect(moving.frame(100, 'truecolor', 30).join('\n')).not.toBe(a)
|
||||
expect(still.moving()).toBe(false)
|
||||
expect(moving.moving()).toBe(true)
|
||||
still.stop()
|
||||
moving.stop()
|
||||
})
|
||||
})
|
||||
|
||||
describe('the looks', () => {
|
||||
it('are Classic BBS (the console default), Orbital and plain, and t steps through them', async () => {
|
||||
const session = await opened()
|
||||
|
||||
expect(LOOKS).toEqual(['bbs', 'orbital', 'plain'])
|
||||
expect(session.look).toBe('bbs')
|
||||
expect([session.cycleLook(), session.cycleLook(), session.cycleLook()]).toEqual(['orbital', 'plain', 'bbs'])
|
||||
expect(keyOf('t')).toBe('look')
|
||||
session.stop()
|
||||
})
|
||||
|
||||
it('plain has no pictures: its pages are the words', async () => {
|
||||
const session = await opened({ look: 'plain' })
|
||||
|
||||
expect(strip(session.frame(100, 'truecolor', 30).join('\n'))).not.toMatch(/█{2}/)
|
||||
session.stop()
|
||||
})
|
||||
})
|
||||
|
||||
describe('--fps', () => {
|
||||
it('is a whole number from 0 to 30, and the console default (8) for anything else', () => {
|
||||
expect([fpsOf(0), fpsOf(8), fpsOf(30), fpsOf(99), fpsOf(-3), fpsOf(7.9)]).toEqual([0, 8, 30, 30, 0, 7])
|
||||
expect([fpsOf('12'), fpsOf(undefined), fpsOf(NaN), fpsOf(null)]).toEqual([8, 8, 8, 8])
|
||||
})
|
||||
})
|
||||
|
||||
function terminal(columns = 100, rows = 32, env: Record<string, string> = { TERM: 'xterm-256color', COLORTERM: 'truecolor' }) {
|
||||
const out: string[] = []
|
||||
const listeners: Array<(chunk: string) => void> = []
|
||||
const stdout = { isTTY: true, columns, rows, write: (text: string) => void out.push(text), on: () => undefined, off: () => undefined }
|
||||
const io: TuiIO = {
|
||||
stdin: { isTTY: true, setRawMode: () => undefined, on: (_e, fn) => void listeners.push(fn as never), off: () => void listeners.splice(0), resume: () => undefined, pause: () => undefined },
|
||||
stdout,
|
||||
stderr: { write: () => undefined },
|
||||
env,
|
||||
}
|
||||
|
||||
return { io, out, press: (key: string) => listeners.forEach(fn => fn(key)) }
|
||||
}
|
||||
|
||||
describe('the loop', () => {
|
||||
it('redraws a moving picture on its clock with only the rows that changed, and not when told --no-anim', async () => {
|
||||
const t = terminal()
|
||||
const running = runTui({ cwd: project, home: join(root, 'home'), look: 'orbital', fps: 25 }, t.io)
|
||||
|
||||
await settle(900)
|
||||
|
||||
const ticks = t.out.filter(chunk => /^\u001b\[\d+;1H/.test(chunk))
|
||||
|
||||
expect(ticks.length).toBeGreaterThan(2)
|
||||
expect(ticks.every(chunk => !chunk.includes(`${ESC}[2J`) && chunk.length < 20000)).toBe(true)
|
||||
t.press('q')
|
||||
await running
|
||||
|
||||
const quiet = terminal()
|
||||
const stilled = runTui({ cwd: project, home: join(root, 'home'), look: 'orbital', fps: 25, anim: false }, quiet.io)
|
||||
|
||||
await settle(900)
|
||||
expect(quiet.out.filter(chunk => /^\u001b\[\d+;1H/.test(chunk))).toHaveLength(0)
|
||||
quiet.press('q')
|
||||
await stilled
|
||||
})
|
||||
|
||||
it('stops drawing while the terminal reports focus lost and resumes when it is back', async () => {
|
||||
const t = terminal()
|
||||
const running = runTui({ cwd: project, home: join(root, 'home'), look: 'orbital', fps: 25 }, t.io)
|
||||
|
||||
await settle(400)
|
||||
t.press(`${ESC}[O`)
|
||||
await settle(60)
|
||||
|
||||
const mark = t.out.length
|
||||
|
||||
await settle(500)
|
||||
expect(t.out.length).toBe(mark)
|
||||
t.press(`${ESC}[I`)
|
||||
await settle(300)
|
||||
expect(t.out.length).toBeGreaterThan(mark)
|
||||
t.press('q')
|
||||
await running
|
||||
})
|
||||
|
||||
it('asks the terminal for focus reports and gives everything back on q', async () => {
|
||||
const t = terminal()
|
||||
const running = runTui({ cwd: project, home: join(root, 'home'), look: 'bbs', fps: 0 }, t.io)
|
||||
|
||||
await settle(250)
|
||||
t.press('q')
|
||||
await running
|
||||
|
||||
const all = t.out.join('')
|
||||
|
||||
expect(all.startsWith(`${ESC}[?1049h${ESC}[?25l${ESC}[?1004h`)).toBe(true)
|
||||
expect(all.endsWith(`${ESC}[?1004l${ESC}[?25h${ESC}[?1049l`)).toBe(true)
|
||||
})
|
||||
|
||||
it('draws no colour under NO_COLOR and no pictures on a dumb terminal', async () => {
|
||||
for (const env of [{ TERM: 'xterm-256color', NO_COLOR: '1' }, { TERM: 'dumb' }]) {
|
||||
const t = terminal(100, 32, env)
|
||||
const running = runTui({ cwd: project, home: join(root, 'home'), look: 'bbs', fps: 8 }, t.io)
|
||||
|
||||
await settle(500)
|
||||
t.press('q')
|
||||
await running
|
||||
expect(t.out.join('').replace(/\u001b\[[?0-9;]*[hlHJK]/g, '')).not.toMatch(/\u001b\[[0-9;]*m/)
|
||||
}
|
||||
})
|
||||
|
||||
it('t cycles the look on screen: BBS blocks, then Orbital\'s masthead, then plain words', async () => {
|
||||
const t = terminal()
|
||||
const running = runTui({ cwd: project, home: join(root, 'home'), look: 'bbs', fps: 0 }, t.io)
|
||||
|
||||
await settle(300)
|
||||
|
||||
const last = () => strip(t.out.join('').split(`${ESC}[H`).pop() ?? '')
|
||||
|
||||
expect(last()).toMatch(/░▒▓/)
|
||||
t.press('t')
|
||||
await settle(100)
|
||||
expect(last()).toContain('RUFLO / AGENT SWARM CONSOLE')
|
||||
t.press('t')
|
||||
await settle(100)
|
||||
expect(last()).not.toMatch(/█{2}/)
|
||||
t.press('q')
|
||||
await running
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* The standalone terminal draws the console's pictures (ADR-489 phase 4): a Raster is the Grid's cells (`Grid.toRaster`) drawn as coloured
|
||||
* glyphs. Whatever is in the cells is data, never a command: a code point that is a control, an escape, an invisible or a wide character
|
||||
* becomes a space, and a `cells` string that is not exactly the declared size draws nothing. Run with
|
||||
* npx vitest run plugins/ruflo-console/tests/tui-raster.spec.ts
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { Grid, DEFAULT, toBase64 } from '../hooks/gfx/raster'
|
||||
import { render, terminalKit, widthOf } from '../tui/ansi'
|
||||
|
||||
const kit = terminalKit({ raster: true })
|
||||
const draw = (grid: Grid, width: number, depth: 'none' | '256' | 'truecolor') => render(kit.Raster?.(grid.toRaster('t')), width, depth)
|
||||
const OURS = /^\u001b\[[0-9;]*m$/
|
||||
const escapes = (lines: string[]) => lines.join('\n').match(/\u001b[^m]*m?|\u009b/g) ?? []
|
||||
|
||||
describe('a Raster in the terminal kit', () => {
|
||||
it('is offered only when asked for: a kit without it makes the views fall back to words', () => {
|
||||
expect(terminalKit().Raster).toBeUndefined()
|
||||
expect(terminalKit({ raster: true }).Raster).toBeDefined()
|
||||
})
|
||||
|
||||
it('draws the Grid cell for cell, with 24-bit colour in truecolor and the nearest of the 256 otherwise', () => {
|
||||
const grid = new Grid(3, 2)
|
||||
|
||||
grid.set(0, 0, '█', 0xff0000, 0x000000)
|
||||
grid.set(1, 0, '▀', 0x00ff00)
|
||||
grid.set(2, 0, 'x')
|
||||
grid.set(0, 1, '░', 0x808080)
|
||||
|
||||
const rich = draw(grid, 10, 'truecolor')
|
||||
const some = draw(grid, 10, '256')
|
||||
|
||||
expect(rich).toHaveLength(2)
|
||||
expect(rich[0]).toContain('38;2;255;0;0;48;2;0;0;0')
|
||||
expect(rich[0]).toContain('38;2;0;255;0')
|
||||
expect(rich[1]).toContain('38;2;128;128;128')
|
||||
expect(some[0]).toContain('38;5;196')
|
||||
expect(some[1]).toMatch(/38;5;(244|102|8)/)
|
||||
expect(rich.map(widthOf)).toEqual([3, 3])
|
||||
// No style is left open at a row's end: the last sequence in a row is a reset (or the row has none).
|
||||
expect(rich.every(line => (line.match(/\u001b\[[0-9;]*m/g)?.at(-1) ?? '\u001b[0m') === '\u001b[0m' || /\u001b\[0m[^\u001b]*$/.test(line))).toBe(true)
|
||||
})
|
||||
|
||||
it('draws no colour at all when there is none, and never more than the width it was given', () => {
|
||||
const grid = new Grid(40, 1)
|
||||
|
||||
for (let x = 0; x < 40; x++) grid.set(x, 0, '█', 0x336699)
|
||||
|
||||
expect(draw(grid, 40, 'none')[0]).toBe('█'.repeat(40))
|
||||
expect(draw(grid, 12, 'truecolor').map(widthOf)).toEqual([12])
|
||||
})
|
||||
|
||||
it('turns a control, an escape, an invisible, a surrogate or a wide character into a space', () => {
|
||||
const grid = new Grid(8, 1)
|
||||
|
||||
for (const [x, code] of [0x1b, 0x07, 0x202e, 0x200b, 0xd800, 0x4e2d, 0x1f600, 0x9b].entries()) grid.set(x, 0, code, 0xffffff)
|
||||
|
||||
const line = draw(grid, 20, 'none')[0] as string
|
||||
|
||||
expect(line).toBe(' '.repeat(8))
|
||||
expect(escapes(draw(grid, 20, 'truecolor')).every(seq => OURS.test(seq))).toBe(true)
|
||||
})
|
||||
|
||||
it('withholds a secret that a picture was made to spell, cell by cell', () => {
|
||||
const grid = new Grid(1, 1)
|
||||
|
||||
grid.set(0, 0, 'g')
|
||||
|
||||
expect(draw(grid, 5, 'none')[0]).toBe('g')
|
||||
})
|
||||
|
||||
it('draws nothing for cells that are not exactly the declared size, not base64, or too many', () => {
|
||||
const grid = new Grid(4, 2)
|
||||
const good = grid.toRaster('t')
|
||||
|
||||
for (const bad of [
|
||||
{ ...good, cells: good.cells.slice(4) },
|
||||
{ ...good, cells: `${good.cells.slice(0, -4)}!!!!` },
|
||||
{ ...good, columns: 5 },
|
||||
{ ...good, columns: 0 },
|
||||
{ ...good, rows: -1 },
|
||||
{ ...good, columns: 1e9, rows: 1e9, cells: 'AAAA' },
|
||||
{ ...good, cells: undefined },
|
||||
{ ...good, columns: 1.5 },
|
||||
]) expect(render(kit.Raster?.(bad as never), 40, 'truecolor')).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps the terminal default colour as no colour, so a theme with no background stays the terminal\'s', () => {
|
||||
const grid = new Grid(2, 1)
|
||||
|
||||
grid.set(0, 0, 'a', DEFAULT, DEFAULT)
|
||||
grid.set(1, 0, 'b', 0x123456, DEFAULT)
|
||||
|
||||
const line = draw(grid, 5, 'truecolor')[0] as string
|
||||
|
||||
expect(line.startsWith('a')).toBe(true)
|
||||
expect(line).toContain('38;2;18;52;86')
|
||||
expect(line).not.toContain('48;')
|
||||
})
|
||||
|
||||
it('decodes the base64 the Grid encodes (u32 little endian triplets), padding included', () => {
|
||||
const grid = new Grid(5, 3)
|
||||
|
||||
grid.set(4, 2, '#', 0x010203, 0x040506)
|
||||
expect(toBase64(new Uint8Array([1, 2, 3, 4]))).toBe('AQIDBA==')
|
||||
expect(draw(grid, 9, 'truecolor')[2]).toContain('38;2;1;2;3;48;2;4;5;6')
|
||||
})
|
||||
})
|
||||
@@ -51,7 +51,7 @@ function fakeIO(isTTY: boolean) {
|
||||
|
||||
describe('the same views over real ruflo files', () => {
|
||||
it('Overview shows the swarm, the daemon and the helpers read from disk', async () => {
|
||||
const session = openSession({ cwd: project, home: join(root, 'home') })
|
||||
const session = openSession({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') })
|
||||
|
||||
await session.refresh()
|
||||
const text = session.frame(110, 'none').join('\n')
|
||||
@@ -64,7 +64,7 @@ describe('the same views over real ruflo files', () => {
|
||||
})
|
||||
|
||||
it('Cost shows its sections and says n/a for what only the Claude Code host can measure', async () => {
|
||||
const session = openSession({ cwd: project, home: join(root, 'home') })
|
||||
const session = openSession({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') })
|
||||
|
||||
await session.refresh()
|
||||
session.show('cost')
|
||||
@@ -77,7 +77,7 @@ describe('the same views over real ruflo files', () => {
|
||||
})
|
||||
|
||||
it('is the mod\'s own tree: the standalone frame carries the same pane header the mod draws', async () => {
|
||||
const session = openSession({ cwd: project, home: join(root, 'home') })
|
||||
const session = openSession({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') })
|
||||
|
||||
await session.refresh()
|
||||
expect(session.frame(110, 'none').join('\n')).toContain('what ruflo is doing here')
|
||||
@@ -85,7 +85,7 @@ describe('the same views over real ruflo files', () => {
|
||||
})
|
||||
|
||||
it('hostile ruflo files: no escape from content and no token reach the frame (the data layer refuses the id, the renderer strips the rest)', async () => {
|
||||
const session = openSession({ cwd: hostile, home: join(root, 'home') })
|
||||
const session = openSession({ look: 'plain', fps: 0, cwd: hostile, home: join(root, 'home') })
|
||||
|
||||
await session.refresh()
|
||||
for (const depth of ['none', '256'] as const) {
|
||||
@@ -103,9 +103,9 @@ describe('the same views over real ruflo files', () => {
|
||||
['escapes only: the words stay, the sequences go', 'boom \u001b]0;pwned\u0007\u001b[2J\u009b31m end', /exit 1: .*boom.* end/],
|
||||
['an escape and a token: the whole line is withheld', 'boom \u001b]0;pwned\u0007 ghp_abcdefghijklmnopqrstuvwxyz0123456789 end', /line withheld/],
|
||||
])('what a failing child prints reaches the frame as clean text (stderr is not JSON, so no data layer in front): %s', async (_name, stderr, expected) => {
|
||||
const base = openSession({ cwd: project, home: join(root, 'home') }).host
|
||||
const base = openSession({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') }).host
|
||||
const hostileRun = async () => ({ exitCode: 1, stdout: '', stderr, isStdoutTruncated: false, isStderrTruncated: false })
|
||||
const session = openSession({ cwd: project }, { ...base, run: hostileRun })
|
||||
const session = openSession({ look: 'plain', fps: 0, cwd: project }, { ...base, run: hostileRun })
|
||||
|
||||
await session.refresh()
|
||||
await session.refresh()
|
||||
@@ -123,9 +123,9 @@ describe('the same views over real ruflo files', () => {
|
||||
it('never calls the engine: every host call the controller made was a read or a refusal', async () => {
|
||||
const ran: string[][] = []
|
||||
const calls: string[] = []
|
||||
const base = openSession({ cwd: project, home: join(root, 'home') }).host
|
||||
const base = openSession({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') }).host
|
||||
const spy = new Proxy(base, { get: (target, key: string) => (typeof target[key as keyof typeof target] === 'function' ? (...args: never[]) => (calls.push(key), (target[key as keyof typeof target] as (...a: never[]) => unknown)(...args)) : target[key as keyof typeof target]) })
|
||||
const session = openSession({ cwd: project }, { ...spy, run: async argv => (ran.push([...argv]), Promise.reject(new Error('no program'))) })
|
||||
const session = openSession({ look: 'plain', fps: 0, cwd: project }, { ...spy, run: async argv => (ran.push([...argv]), Promise.reject(new Error('no program'))) })
|
||||
|
||||
await session.refresh()
|
||||
expect(calls.filter(call => ['openPane', 'blit', 'toolCall', 'submitPrompt', 'spawn', 'askChoice'].includes(call))).toEqual([])
|
||||
@@ -138,7 +138,7 @@ describe('the same views over real ruflo files', () => {
|
||||
describe('headless', () => {
|
||||
it('--plain prints one plain frame to stdout, nothing to stderr, and returns 0', async () => {
|
||||
const { io, out, err } = fakeIO(false)
|
||||
const code = await runTui({ cwd: project, home: join(root, 'home'), plain: true }, io)
|
||||
const code = await runTui({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home'), plain: true }, io)
|
||||
|
||||
expect(code).toBe(0)
|
||||
expect(out.join('')).toContain('swarm-1790903031804-y9rnjr')
|
||||
@@ -149,13 +149,13 @@ describe('headless', () => {
|
||||
it('--plain opens the page asked for', async () => {
|
||||
const { io, out } = fakeIO(false)
|
||||
|
||||
await runTui({ cwd: project, home: join(root, 'home'), view: 'cost', plain: true }, io)
|
||||
await runTui({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home'), view: 'cost', plain: true }, io)
|
||||
expect(out.join('')).toContain('Where it goes')
|
||||
})
|
||||
|
||||
it('--plain in a real terminal still prints one frame and never enters the alternate screen or raw mode', async () => {
|
||||
const { io, out, raw } = fakeIO(true)
|
||||
const code = await runTui({ cwd: project, home: join(root, 'home'), plain: true }, io)
|
||||
const code = await runTui({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home'), plain: true }, io)
|
||||
|
||||
expect(code).toBe(0)
|
||||
expect(out.join('')).toContain('swarm-1790903031804-y9rnjr')
|
||||
@@ -165,7 +165,7 @@ describe('headless', () => {
|
||||
|
||||
it('without a terminal and without --plain prints a one-line hint to stderr and returns 2, with nothing on stdout', async () => {
|
||||
const { io, out, err } = fakeIO(false)
|
||||
const code = await runTui({ cwd: project, home: join(root, 'home') }, io)
|
||||
const code = await runTui({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') }, io)
|
||||
|
||||
expect(code).toBe(2)
|
||||
expect(out).toEqual([])
|
||||
@@ -176,7 +176,7 @@ describe('headless', () => {
|
||||
|
||||
it('a terminal that cannot do raw mode counts as no terminal', async () => {
|
||||
const { io, out, err } = fakeIO(true)
|
||||
const code = await runTui({ cwd: project, home: join(root, 'home') }, { ...io, stdin: { ...io.stdin, setRawMode: undefined } })
|
||||
const code = await runTui({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') }, { ...io, stdin: { ...io.stdin, setRawMode: undefined } })
|
||||
|
||||
expect(code).toBe(2)
|
||||
expect(out).toEqual([])
|
||||
@@ -187,7 +187,7 @@ describe('headless', () => {
|
||||
describe('interactive', () => {
|
||||
it('enters the alternate screen, switches page on a key, and restores the terminal on q', async () => {
|
||||
const { io, out, raw, press } = fakeIO(true)
|
||||
const running = runTui({ cwd: project, home: join(root, 'home') }, io)
|
||||
const running = runTui({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') }, io)
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 150))
|
||||
press('c')
|
||||
@@ -207,7 +207,7 @@ describe('interactive', () => {
|
||||
it('restores the terminal when the signal aborts', async () => {
|
||||
const { io, out, raw } = fakeIO(true)
|
||||
const stop = new AbortController()
|
||||
const running = runTui({ cwd: project, home: join(root, 'home') }, { ...io, signal: stop.signal })
|
||||
const running = runTui({ look: 'plain', fps: 0, cwd: project, home: join(root, 'home') }, { ...io, signal: stop.signal })
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 100))
|
||||
stop.abort()
|
||||
|
||||
@@ -153,6 +153,117 @@ function pad(line: string, width: number): string {
|
||||
return line + ' '.repeat(Math.max(0, width - widthOf(line)))
|
||||
}
|
||||
|
||||
const B64 = new Map<string, number>([...'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'].map((ch, i) => [ch, i]))
|
||||
/** The most cells one picture may hold: a bound on what a hostile or corrupt `cells` string can make us decode. */
|
||||
const MAX_PICTURE_CELLS = 200 * 90
|
||||
|
||||
/** Decodes the base64 of `Grid.encode()` (little-endian u32 triplets) or null when it is not exactly `count` cells. Pure: no Buffer. */
|
||||
function decodeCells(text: unknown, count: number): Uint32Array | null {
|
||||
if (typeof text !== 'string' || text.length !== Math.ceil((count * 12) / 3) * 4) return null
|
||||
|
||||
const out = new Uint8Array(count * 12)
|
||||
let at = 0
|
||||
|
||||
for (let i = 0; i < text.length; i += 4) {
|
||||
const a = B64.get(text[i] as string)
|
||||
const b = B64.get(text[i + 1] as string)
|
||||
const c = text[i + 2] === '=' ? 0 : B64.get(text[i + 2] as string)
|
||||
const d = text[i + 3] === '=' ? 0 : B64.get(text[i + 3] as string)
|
||||
|
||||
if (a === undefined || b === undefined || c === undefined || d === undefined) return null
|
||||
|
||||
const n = (a << 18) | (b << 12) | (c << 6) | d
|
||||
|
||||
if (at < out.length) out[at++] = (n >> 16) & 255
|
||||
if (at < out.length) out[at++] = (n >> 8) & 255
|
||||
if (at < out.length) out[at++] = n & 255
|
||||
}
|
||||
|
||||
const view = new Uint32Array(count * 3)
|
||||
|
||||
for (let i = 0; i < view.length; i++) view[i] = ((out[i * 4] as number) | ((out[i * 4 + 1] as number) << 8) | ((out[i * 4 + 2] as number) << 16) | ((out[i * 4 + 3] as number) << 24)) >>> 0
|
||||
|
||||
return view
|
||||
}
|
||||
|
||||
const LEVELS = [0, 95, 135, 175, 215, 255] as const
|
||||
|
||||
/** The nearest of the 256-colour cube and the grey ramp to a 24-bit colour. */
|
||||
function nearest256(r: number, g: number, b: number): number {
|
||||
const near = (n: number) => LEVELS.reduce((best, level, i) => (Math.abs(level - n) < Math.abs((LEVELS[best] as number) - n) ? i : best), 0)
|
||||
const [ri, gi, bi] = [near(r), near(g), near(b)]
|
||||
const cubeDistance = (LEVELS[ri] as number - r) ** 2 + (LEVELS[gi] as number - g) ** 2 + (LEVELS[bi] as number - b) ** 2
|
||||
const grey = Math.max(0, Math.min(23, Math.round(((r + g + b) / 3 - 8) / 10)))
|
||||
const level = 8 + grey * 10
|
||||
const greyDistance = (level - r) ** 2 + (level - g) ** 2 + (level - b) ** 2
|
||||
|
||||
return greyDistance < cubeDistance ? 232 + grey : 16 + 36 * ri + 6 * gi + bi
|
||||
}
|
||||
|
||||
/** A Grid colour (0xRRGGBB, or the terminal's own above 0xFFFFFF) as the SGR parameters for one ground, or '' for the default. */
|
||||
function cellColor(value: number, ground: 38 | 48, depth: Depth): string {
|
||||
if (depth === 'none' || value >>> 24 !== 0) return ''
|
||||
|
||||
const [r, g, b] = [(value >> 16) & 255, (value >> 8) & 255, value & 255]
|
||||
|
||||
return depth === 'truecolor' ? `${ground};2;${r};${g};${b}` : `${ground};5;${nearest256(r, g, b)}`
|
||||
}
|
||||
|
||||
const glyphs = new Map<number, string>()
|
||||
|
||||
/** One cell's glyph through `clean` once (a cell is a code point, never an escape): control, invisible and wide ones become a space, so a picture cannot move the cursor or break the row. */
|
||||
function glyphOf(code: number): string {
|
||||
const known = glyphs.get(code)
|
||||
|
||||
if (known !== undefined) return known
|
||||
|
||||
const ch = code < 0x20 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff) ? ' ' : String.fromCodePoint(code)
|
||||
const cleaned = clean(ch)
|
||||
const glyph = cleaned.length === 0 || cellsOf(cleaned.codePointAt(0) as number) !== 1 || cleaned === SECRET_LINE ? ' ' : cleaned
|
||||
|
||||
if (glyphs.size < 4096) glyphs.set(code, glyph)
|
||||
|
||||
return glyph
|
||||
}
|
||||
|
||||
/** A Raster (the console's picture cells) as terminal lines no wider than `width`: colour per run of cells, the style closed at each row's end. */
|
||||
function rasterLines(props: Record<string, unknown>, width: number, depth: Depth): string[] {
|
||||
const columns = typeof props.columns === 'number' && Number.isInteger(props.columns) ? props.columns : 0
|
||||
const rows = typeof props.rows === 'number' && Number.isInteger(props.rows) ? props.rows : 0
|
||||
|
||||
if (columns < 1 || rows < 1 || columns * rows > MAX_PICTURE_CELLS) return []
|
||||
|
||||
const data = decodeCells(props.cells, columns * rows)
|
||||
|
||||
if (data === null) return []
|
||||
|
||||
const lines: string[] = []
|
||||
const shown = Math.max(1, Math.min(columns, width))
|
||||
|
||||
for (let y = 0; y < rows; y++) {
|
||||
let out = ''
|
||||
let style = ''
|
||||
|
||||
for (let x = 0; x < shown; x++) {
|
||||
const at = (y * columns + x) * 3
|
||||
const fg = cellColor(data[at + 1] as number, 38, depth)
|
||||
const bg = cellColor(data[at + 2] as number, 48, depth)
|
||||
const next = fg === '' && bg === '' ? '' : [fg, bg].filter(code => code !== '').join(';')
|
||||
|
||||
if (next !== style) {
|
||||
out += next === '' ? RESET : `\u001b[0;${next}m`
|
||||
style = next
|
||||
}
|
||||
|
||||
out += glyphOf(data[at] as number)
|
||||
}
|
||||
|
||||
lines.push(style === '' ? out : `${out}${RESET}`)
|
||||
}
|
||||
|
||||
return lines
|
||||
}
|
||||
|
||||
const BORDER = {
|
||||
round: ['╭', '╮', '╰', '╯', '─', '│'],
|
||||
single: ['┌', '┐', '└', '┘', '─', '│'],
|
||||
@@ -168,6 +279,8 @@ export function render(node: unknown, width: number, depth: Depth): string[] {
|
||||
|
||||
if (props.hidden === true || props.display === 'none') return []
|
||||
|
||||
if (type === 'Raster') return rasterLines(props, width, depth)
|
||||
|
||||
if (type === 'Text') {
|
||||
const text = textOf(props.children)
|
||||
const open = sgr(props as Style, depth)
|
||||
@@ -185,6 +298,9 @@ export function render(node: unknown, width: number, depth: Depth): string[] {
|
||||
|
||||
if (label.includes('✦')) return []
|
||||
|
||||
// A main-menu entry is a label next to its key chip, and the key is what opens it here (the shell reads it): the words stay, as text.
|
||||
if (typeof props.key === 'string' && props.key.startsWith('menu-go-')) return [cut(` ${label} `, width)]
|
||||
|
||||
if (typeof props.key === 'string' && props.key.startsWith('sec-')) return [cut(`${sgr({ bold: true }, depth)}${label.replace(/^[▾▸]\s*/, '')}${depth === 'none' ? '' : RESET}`, width)]
|
||||
|
||||
return /^[●○]/.test(label) ? [cut(`${sgr({ dimColor: true }, depth)}${label} ${depth === 'none' ? '' : RESET}`, width)] : []
|
||||
@@ -192,6 +308,9 @@ export function render(node: unknown, width: number, depth: Depth): string[] {
|
||||
|
||||
if (type !== 'Box') return []
|
||||
|
||||
// A box that asks for a width (the main menu's two groups side by side) is no wider than that, as on the console.
|
||||
if (typeof props.width === 'number' && Number.isFinite(props.width) && props.width >= 3) width = Math.min(width, Math.floor(props.width))
|
||||
|
||||
const frame = props.borderStyle === 'round' || props.borderStyle === 'single' ? BORDER[props.borderStyle] : null
|
||||
const padX = typeof props.paddingX === 'number' && props.paddingX > 0 ? Math.min(4, Math.floor(props.paddingX)) : 0
|
||||
const inner = Math.max(1, width - (frame === null ? 0 : 2) - padX * 2)
|
||||
@@ -223,9 +342,12 @@ export function render(node: unknown, width: number, depth: Depth): string[] {
|
||||
return [`${edge}${frame[0]}${frame[4].repeat(across)}${frame[1]}${close}`, ...body.map(line => `${edge}${frame[5]}${close}${pad(line, across)}${edge}${frame[5]}${close}`), `${edge}${frame[2]}${frame[4].repeat(across)}${frame[3]}${close}`]
|
||||
}
|
||||
|
||||
/** The kit the views build with: plain element records for `render`. No Raster and no Input, so a picture takes its words and a text field its command fallback. */
|
||||
export function terminalKit(): Kit {
|
||||
/**
|
||||
* The kit the views build with: plain element records for `render`. With `raster` it has a Raster, so the views draw their pictures
|
||||
* (the same cells Claude Code draws); without it, and with no Input, a picture takes its words and a text field its command fallback.
|
||||
*/
|
||||
export function terminalKit(options: { raster?: boolean } = {}): Kit {
|
||||
const make = (type: string) => (props: Record<string, unknown>) => ({ type, props }) as never
|
||||
|
||||
return { Box: make('Box'), Text: make('Text'), Button: make('Button') }
|
||||
return { Box: make('Box'), Text: make('Text'), Button: make('Button'), ...(options.raster === true && { Raster: make('Raster') }) }
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
/** The bundle entry (ADR-489): what `ruflo tui` loads. Built to dist/tui.mjs by scripts/build-tui.mjs. */
|
||||
export { runTui, isTuiView, keyOf, depthOf } from './run'
|
||||
export { runTui, isTuiView, isPage, keyOf, depthOf } from './run'
|
||||
export type { TuiIO, TuiOptions } from './run'
|
||||
export { TUI_VIEWS } from './session'
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Every console view and what `ruflo tui` does with it (ADR-489 phase 5). A view is a decision, not an accident: `parity.spec.ts` fails when a view
|
||||
* is added to the console's `VIEWS` without an entry here, and when ADR-489's table does not name each view.
|
||||
*
|
||||
* - `same` the console's own page body, read-only, as in Claude Code.
|
||||
* - `partial` the console's own page body, but part of it needs Claude Code (or the confirm gate of phase 6): `why` says which.
|
||||
* - `equivalent` the job is done by another standalone page (`opens`).
|
||||
* - `claude-only` the page is about a Claude Code session this terminal does not have: it opens a one-screen note, never an empty fake.
|
||||
*/
|
||||
import { VIEWS, type ViewId } from '../hooks/state'
|
||||
|
||||
export type Parity = { status: 'same' | 'partial' | 'equivalent' | 'claude-only'; why: string; opens?: 'ai' }
|
||||
|
||||
const READ_ONLY = 'its buttons are not drawn; its actions are asked for by name at the go prompt (:), each after the console card'
|
||||
|
||||
export const PARITY: Record<ViewId | 'agent', Parity> = {
|
||||
menu: { status: 'same', why: 'entries open by their key, as on the console board' },
|
||||
missions: { status: 'partial', why: 'the mission record only: entering a goal, planning and research start a Claude turn' },
|
||||
overview: { status: 'same', why: 'the Claude-only controls are not drawn' },
|
||||
swarm: { status: 'same', why: 'topology, agents and votes as ruflo wrote them' },
|
||||
hive: { status: 'partial', why: READ_ONLY },
|
||||
claims: { status: 'partial', why: READ_ONLY },
|
||||
workflows: { status: 'partial', why: 'the ruflo swarm side; Claude Code workflow runs are not visible outside a session' },
|
||||
federation: { status: 'partial', why: READ_ONLY },
|
||||
plugins: { status: 'partial', why: 'what is installed and loaded; "loaded as a mod" is a Claude Code fact and reads n/a' },
|
||||
learning: { status: 'same', why: 'router picks, outcomes and the pipeline as on disk' },
|
||||
metaharness: { status: 'partial', why: READ_ONLY },
|
||||
memory: { status: 'partial', why: READ_ONLY },
|
||||
cost: { status: 'partial', why: 'provider ledger and router counts; Claude Code spend, context and the budget ladder read n/a' },
|
||||
timeline: { status: 'partial', why: 'agent lanes from status reports; Claude Code tool-call lanes need a session' },
|
||||
approvals: { status: 'partial', why: 'shows what waits; answering a vote or a claim is asked for by name at the go prompt, after the card' },
|
||||
events: { status: 'same', why: 'the event stream as it is on disk; Ask Claude is not drawn' },
|
||||
room: { status: 'claude-only', why: 'it is what people said to Claude in a session, plus a message box; this terminal has neither' },
|
||||
xruv: { status: 'partial', why: READ_ONLY },
|
||||
terminal: { status: 'equivalent', why: 'the standalone AI page (Codex or OpenRouter, each question after a card)', opens: 'ai' },
|
||||
skills: { status: 'partial', why: READ_ONLY },
|
||||
secure: { status: 'partial', why: READ_ONLY },
|
||||
perf: { status: 'partial', why: READ_ONLY },
|
||||
automate: { status: 'partial', why: READ_ONLY },
|
||||
neural: { status: 'partial', why: READ_ONLY },
|
||||
vector: { status: 'partial', why: READ_ONLY },
|
||||
evolve: { status: 'partial', why: READ_ONLY },
|
||||
devtools: { status: 'partial', why: READ_ONLY },
|
||||
sandbox: { status: 'partial', why: READ_ONLY },
|
||||
market: { status: 'partial', why: READ_ONLY },
|
||||
adrs: { status: 'partial', why: READ_ONLY },
|
||||
whatsnew: { status: 'same', why: 'changelogs of the installed plugins' },
|
||||
themes: { status: 'partial', why: 'the look is chosen with t or --look; the colour picker and generated themes are not here yet' },
|
||||
settings: { status: 'partial', why: 'shown as the standalone defaults; plugin options live in the Claude Code settings and the standalone has no store for them yet (the look is --look/t, the speed --fps)' },
|
||||
agent: { status: 'partial', why: 'the drill-down from a Swarm selection; selecting needs the host keys, so it says so' },
|
||||
}
|
||||
|
||||
/** The views the standalone shell can open by name: every console view and the AI page. */
|
||||
export const PAGE_IDS: readonly (ViewId | 'ai')[] = [...VIEWS.map(view => view.id), 'ai']
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* The rows the shell pins under the page bar (ADR-489 phase 6): the confirm card of a change the person asked for, or what the last action
|
||||
* printed. The card is the console's own `state.pending` (the same text `confirmRow` draws: who asked, the exact argv, the effect); only the
|
||||
* wording of the keys differs, because this terminal has no buttons. It counts as shown (`state.shownCard`, the console's own gate for a bare
|
||||
* typed yes) only when every row of it is on screen, so a window too small to show the argv can never answer it.
|
||||
*/
|
||||
import { askedBy } from '../hooks/data/room'
|
||||
import type { State } from '../hooks/state'
|
||||
import { THEME } from '../hooks/views/common'
|
||||
import { clean, render, terminalKit, type Depth } from './ansi'
|
||||
|
||||
/** How long the result of an action stays pinned. */
|
||||
export const RESULT_MS = 20_000
|
||||
const MAX_RESULT_LINES = 8
|
||||
|
||||
export function pinnedLines(state: State, columns: number, depth: Depth, room: number): string[] {
|
||||
const kit = terminalKit()
|
||||
const pending = state.pending
|
||||
|
||||
if (pending !== null) {
|
||||
const hasMoney = pending.note !== undefined && /money|models/i.test(pending.note)
|
||||
const tree = kit.Box({
|
||||
flexDirection: 'column',
|
||||
borderStyle: 'round',
|
||||
borderColor: THEME.warn,
|
||||
paddingX: 1,
|
||||
children: [
|
||||
kit.Text({ bold: true, color: THEME.warn, children: '▶ CONFIRM NEEDED: y runs it · n or Esc cancels' }),
|
||||
kit.Text({ bold: true, color: THEME.warn, wrap: 'wrap', children: `Confirm: ${askedBy(pending)}${pending.label.replace(/\?+$/, '')}?` }),
|
||||
// Wrapped, not clipped: a yes is a yes to the whole argv.
|
||||
kit.Text({ dimColor: true, wrap: 'wrap', children: `runs: ${pending.shows ?? `ruflo ${pending.args.join(' ')}`}` }),
|
||||
...(pending.note !== undefined ? [kit.Text({ bold: hasMoney, color: hasMoney ? THEME.bad : THEME.warn, wrap: 'wrap', children: `Effect: ${pending.note}` })] : []),
|
||||
],
|
||||
})
|
||||
const lines = render(tree, columns, depth)
|
||||
|
||||
// Leave the page at least three rows: a card that crowds it out is not on screen in full.
|
||||
if (lines.length <= Math.max(0, room - 3)) {
|
||||
state.shownCard = pending.id ?? null
|
||||
|
||||
return lines
|
||||
}
|
||||
|
||||
state.shownCard = null
|
||||
|
||||
return [clean('▶ CONFIRM NEEDED, but this window is too small to show the whole command: make it taller (or press n).')].map(line => line.slice(0, columns))
|
||||
}
|
||||
|
||||
const outcome = state.outcome
|
||||
|
||||
if (outcome === null || Date.now() - outcome.atMs > RESULT_MS) return []
|
||||
|
||||
const head = `${outcome.ok ? '✔' : '✘'} ${clean(outcome.label).slice(0, 80)}: ${clean(outcome.detail).slice(0, 120)}`
|
||||
const more = (outcome.lines ?? []).slice(0, MAX_RESULT_LINES).map(line => ` ${clean(line)}`)
|
||||
|
||||
return render(kit.Box({ flexDirection: 'column', children: [kit.Text({ bold: true, color: outcome.ok ? THEME.ok : THEME.bad, wrap: 'truncate-end', children: head }), ...more.map(line => kit.Text({ dimColor: true, wrap: 'truncate-end', children: line }))] }), columns, depth)
|
||||
}
|
||||
@@ -5,7 +5,9 @@
|
||||
*/
|
||||
import type { Depth } from './ansi'
|
||||
import { cells, clean, widthOf } from './ansi'
|
||||
import { openSession, TUI_VIEWS, type Session, type SessionOptions, type TuiView } from './session'
|
||||
import { VIEWS, viewOf } from '../hooks/state'
|
||||
import { PAGE_IDS } from './parity'
|
||||
import { openSession, TUI_VIEWS, type Look, type Page, type Session, type SessionOptions, type TuiView } from './session'
|
||||
|
||||
export type TuiInput = {
|
||||
isTTY?: boolean
|
||||
@@ -24,9 +26,11 @@ export type TuiOutput = {
|
||||
off?: (event: 'resize', fn: () => void) => unknown
|
||||
}
|
||||
export type TuiIO = { stdin: TuiInput; stdout: TuiOutput; stderr: { write: (text: string) => unknown }; env: Record<string, string | undefined>; signal?: AbortSignal }
|
||||
export type TuiOptions = { cwd: string; view?: TuiView; plain?: boolean; cliEntry?: string; configDir?: string; home?: string; pluginRoot?: string; refreshMs?: number; /** The AI page's settings; absent: the page is off. */ aiPage?: SessionOptions['aiPage'] }
|
||||
export type TuiOptions = { cwd: string; view?: Page; /** True: read SGR mouse reports (a click on the page bar, the wheel to scroll). Off by default; every mouse action has a key. */ mouse?: boolean; plain?: boolean; cliEntry?: string; configDir?: string; home?: string; pluginRoot?: string; refreshMs?: number; /** The look (bbs | orbital | plain: default bbs) and the frames per second of moving pictures (default 8, at most 30; 0 draws them still). */ look?: Look; fps?: number; /** False: no animation (a still frame, like fps 0). */ anim?: boolean; /** False: no pictures, only their words. */ pictures?: boolean; /** True: play the start-up screen first (as the console's boot setting). */ boot?: boolean; /** The AI page's settings; absent: the page is off. */ aiPage?: SessionOptions['aiPage'] }
|
||||
|
||||
export const isTuiView = (value: unknown): value is TuiView => typeof value === 'string' && (TUI_VIEWS as readonly string[]).includes(value)
|
||||
/** Any page the shell can open, which is every console view and the AI page (`--view`, the go prompt). */
|
||||
export const isPage = (value: unknown): value is Page => typeof value === 'string' && (PAGE_IDS as readonly string[]).includes(value)
|
||||
|
||||
/** Colour depth from the environment: NO_COLOR and a dumb terminal get none, COLORTERM truecolor/24bit gets 24-bit, the rest 256. */
|
||||
export function depthOf(env: Record<string, string | undefined>): Depth {
|
||||
@@ -37,6 +41,10 @@ export function depthOf(env: Record<string, string | undefined>): Depth {
|
||||
}
|
||||
|
||||
const ESC = '\u001b'
|
||||
/** Frames per second for moving pictures: the console's default 8, a whole number from 0 (still) to 30. Anything else is the default. */
|
||||
export const DEFAULT_FPS = 8
|
||||
export const MAX_FPS = 30
|
||||
export const fpsOf = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? Math.max(0, Math.min(MAX_FPS, Math.floor(value))) : DEFAULT_FPS)
|
||||
/** Below this the frame is a short message, not a squeezed page. The page bar and the key line shorten to what fits. */
|
||||
export const MIN_COLUMNS = 40
|
||||
|
||||
@@ -44,20 +52,46 @@ const LABELS: Record<TuiView, string> = { overview: 'Overview', cost: 'Cost', sw
|
||||
const LETTER: Partial<Record<string, TuiView>> = { o: 'overview', c: 'cost', s: 'swarm', e: 'events', m: 'missions', a: 'ai' }
|
||||
|
||||
/** The page bar: every page with its number (the current one in reverse), or `‹ 3/6 Swarm ›` when the terminal is too narrow for all of them. Page names are ours, never from a file. */
|
||||
export function navLine(view: TuiView, columns: number, depth: Depth): string {
|
||||
export function navLine(view: Page, columns: number, depth: Depth): string {
|
||||
const wide = TUI_VIEWS.map((page, i) => {
|
||||
const text = ` ${i + 1} ${LABELS[page]} `
|
||||
|
||||
return page === view && depth !== 'none' ? `${ESC}[7m${text}${ESC}[0m` : page === view ? `[${text.trim()}]` : text
|
||||
}).join(' ')
|
||||
const other = (TUI_VIEWS as readonly string[]).includes(view) ? null : (VIEWS.find(entry => entry.id === view)?.label ?? view)
|
||||
|
||||
return widthOf(wide) <= columns ? wide : `‹ ${TUI_VIEWS.indexOf(view) + 1}/${TUI_VIEWS.length} ${LABELS[view]} ›`
|
||||
// A page that is not one of the six shows after them, as the one chip that is on.
|
||||
if (other !== null) {
|
||||
const chip = depth !== 'none' ? `${ESC}[7m ${other} ${ESC}[0m` : `[${other}]`
|
||||
const all = `${wide} ${chip}`
|
||||
|
||||
return widthOf(all) <= columns ? all : `‹ ${clean(other)} › (Esc back)`.slice(0, columns)
|
||||
}
|
||||
|
||||
return widthOf(wide) <= columns ? wide : `‹ ${TUI_VIEWS.indexOf(view as TuiView) + 1}/${TUI_VIEWS.length} ${LABELS[view as TuiView]} ›`
|
||||
}
|
||||
|
||||
/** Which of the six page chips a click at column `x` (1-based) lands on, or null: the same positions `navLine` draws when it fits. */
|
||||
export function navHit(x: number, columns: number): TuiView | null {
|
||||
const chips = TUI_VIEWS.map((page, k) => ` ${k + 1} ${LABELS[page]} `)
|
||||
|
||||
if (chips.join(' ').length > columns) return null
|
||||
|
||||
let at = 1
|
||||
|
||||
for (const [k, chip] of chips.entries()) {
|
||||
if (x >= at && x < at + chip.length) return TUI_VIEWS[k] as TuiView
|
||||
at += chip.length + 1
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** The key line under the page: every key when there is room, fewer keys as the terminal narrows, always inside `columns` (the scroll position, when there is one, is counted in). `own` replaces the page keys (the AI page has its own). */
|
||||
export function keyLine(columns: number, place = '', own?: readonly string[]): string {
|
||||
const pages = `1-${TUI_VIEWS.length}`
|
||||
const tiers = own ?? [`${pages} or o c s e m a page · tab next · r refresh · j/k scroll · q quit · read-only`, `${pages} page · tab next · r refresh · j/k scroll · q quit`, `${pages} page · j/k scroll · q quit`, `${pages} page · q quit`]
|
||||
const menu = '0 menu · : go to any page · Esc back'
|
||||
const tiers = own ?? [`${pages} or o c s e m a page · ${menu} · tab next · r refresh · t look · j/k scroll · q quit · ask first`, `${pages} or o c s e m a page · 0 menu · : go · tab next · r refresh · j/k scroll · q quit · ask first`, `${pages} page · 0 menu · : go · Esc back · tab next · r refresh · j/k scroll · q quit`, `${pages} page · tab next · r refresh · j/k scroll · q quit`, `${pages} page · j/k scroll · q quit`, `${pages} page · q quit`]
|
||||
const fits = tiers.find(line => cells(line + place) <= columns) ?? tiers[tiers.length - 1] as string
|
||||
|
||||
return `${fits}${place}`.slice(0, columns)
|
||||
@@ -72,7 +106,7 @@ export function aiKeyTiers(mode: 'type' | 'nav', hasCard: boolean): string[] {
|
||||
}
|
||||
|
||||
/** One keypress as an action, from the bytes a terminal sends. Anything else is ignored. */
|
||||
export type Key = 'quit' | { page: TuiView } | 'next' | 'prev' | 'refresh' | 'down' | 'up' | 'pagedown' | 'pageup' | 'top' | 'bottom' | null
|
||||
export type Key = 'quit' | 'look' | 'menu' | 'prompt' | 'back' | { page: TuiView } | 'next' | 'prev' | 'refresh' | 'down' | 'up' | 'pagedown' | 'pageup' | 'top' | 'bottom' | null
|
||||
|
||||
export function keyOf(chunk: string): Key {
|
||||
switch (chunk) {
|
||||
@@ -88,8 +122,19 @@ export function keyOf(chunk: string): Key {
|
||||
case 'h':
|
||||
case `${ESC}[D`:
|
||||
return 'prev'
|
||||
case '0':
|
||||
return 'menu'
|
||||
case ':':
|
||||
case '/':
|
||||
return 'prompt'
|
||||
case `${ESC}`:
|
||||
case '\u007f':
|
||||
case '\b':
|
||||
return 'back'
|
||||
case 'r':
|
||||
return 'refresh'
|
||||
case 't':
|
||||
return 'look'
|
||||
case 'j':
|
||||
case `${ESC}[B`:
|
||||
return 'down'
|
||||
@@ -117,15 +162,43 @@ export function keyOf(chunk: string): Key {
|
||||
}
|
||||
}
|
||||
|
||||
function paint(session: Session, io: TuiIO, depth: Depth, scroll: number, clear = false): number {
|
||||
/** What the last frame put on the screen, so the next one rewrites only the rows that changed (a moving picture then costs its own rows, not a whole redraw). */
|
||||
type Memory = { lines: string[]; columns: number; rows: number }
|
||||
|
||||
/** A whole frame, from the home position: the page bar, the body rows, then the key line (the shape every key press and resize draws). */
|
||||
function writeFrame(io: TuiIO, screen: string[], memory: Memory, columns: number, rows: number, clear: boolean): void {
|
||||
const body = screen.slice(1, -1)
|
||||
|
||||
memory.lines = screen
|
||||
memory.columns = columns
|
||||
memory.rows = rows
|
||||
io.stdout.write(`${clear ? `${ESC}[2J` : ''}${ESC}[H${screen[0]}${ESC}[K\r\n${body.map(line => `${line}${ESC}[K`).join('\r\n')}${ESC}[J\r\n${screen[screen.length - 1]}`)
|
||||
}
|
||||
|
||||
/** An animation tick: only the rows that differ from the last frame, each at its own position (a moving picture costs its own rows, not a whole redraw). Anything else is a whole frame. */
|
||||
function writeTick(io: TuiIO, screen: string[], memory: Memory, columns: number, rows: number): void {
|
||||
if (memory.columns !== columns || memory.rows !== rows || memory.lines.length !== screen.length) return writeFrame(io, screen, memory, columns, rows, true)
|
||||
|
||||
let out = ''
|
||||
|
||||
screen.forEach((line, i) => {
|
||||
if (memory.lines[i] !== line) out += `${ESC}[${i + 1};1H${line}${ESC}[K`
|
||||
})
|
||||
memory.lines = screen
|
||||
|
||||
if (out !== '') io.stdout.write(out)
|
||||
}
|
||||
|
||||
function paint(session: Session, io: TuiIO, depth: Depth, scroll: number, memory: Memory, clear = false, tick = false, line = ''): number {
|
||||
const ai = session.page === 'ai' ? session.ai : null
|
||||
const raw = io.stdout.columns ?? 100
|
||||
const rows = Math.max(5, io.stdout.rows ?? 30)
|
||||
const reset = clear ? `${ESC}[2J` : ''
|
||||
|
||||
// Too narrow for a page: say so in a line that fits, rather than a squeezed frame of broken cards.
|
||||
if (raw < MIN_COLUMNS) {
|
||||
io.stdout.write(`${reset}${ESC}[H${'Too narrow: need 40 columns (q quits)'.slice(0, Math.max(1, raw))}${ESC}[K${ESC}[J`)
|
||||
memory.lines = []
|
||||
memory.columns = 0
|
||||
io.stdout.write(`${ESC}[2J${ESC}[H${'Too narrow: need 40 columns (q quits)'.slice(0, Math.max(1, raw))}${ESC}[K`)
|
||||
|
||||
return 0
|
||||
}
|
||||
@@ -141,11 +214,19 @@ function paint(session: Session, io: TuiIO, depth: Depth, scroll: number, clear
|
||||
}
|
||||
|
||||
// The AI page fits its own conversation to the room and follows the tail; the others scroll.
|
||||
const top = session.page === 'ai' ? 0 : Math.max(0, Math.min(scroll, Math.max(0, lines.length - room)))
|
||||
const place = lines.length > room ? ` · ${top + 1}-${Math.min(lines.length, top + room)}/${lines.length}` : ''
|
||||
const footer = `${depth === 'none' ? '' : `${ESC}[2m`}${clean(keyLine(columns, place, session.page === 'ai' && session.ai !== null ? aiKeyTiers(session.ai.mode, session.ai.card !== null) : undefined))}${depth === 'none' ? '' : `${ESC}[0m`}`
|
||||
// A confirm card (or the last action's result) is pinned under the bar, so scrolling never hides what a y would run.
|
||||
const pinned = session.page === 'ai' ? [] : session.pinned(columns, depth, room)
|
||||
const space = Math.max(1, room - pinned.length)
|
||||
const top = session.page === 'ai' ? 0 : Math.max(0, Math.min(scroll, Math.max(0, lines.length - space)))
|
||||
const place = lines.length > space ? ` · ${top + 1}-${Math.min(lines.length, top + space)}/${lines.length}` : ''
|
||||
const footer = `${depth === 'none' ? '' : `${ESC}[2m`}${line !== '' ? clean(line).slice(0, columns) : clean(keyLine(columns, place, session.page === 'ai' && session.ai !== null ? aiKeyTiers(session.ai.mode, session.ai.card !== null) : undefined))}${depth === 'none' ? '' : `${ESC}[0m`}`
|
||||
|
||||
io.stdout.write(`${reset}${ESC}[H${navLine(session.page, columns, depth)}${ESC}[K\r\n${[...lines.slice(top, top + room), ...Array.from({ length: Math.max(0, room - (lines.length - top)) }, () => '')].map(line => `${line}${ESC}[K`).join('\r\n')}${ESC}[J\r\n${footer}`)
|
||||
const body = [...lines.slice(top, top + space), ...Array.from({ length: Math.max(0, space - (lines.length - top)) }, () => '')]
|
||||
|
||||
const screen = [navLine(session.page, columns, depth), ...pinned, ...body, footer]
|
||||
|
||||
if (tick && !clear) writeTick(io, screen, memory, columns, rows)
|
||||
else writeFrame(io, screen, memory, columns, rows, clear)
|
||||
|
||||
// The question card is on screen now: from here a `y` may answer it, and not before (#3983).
|
||||
if (session.cardFits) ai?.drawn()
|
||||
@@ -154,7 +235,7 @@ function paint(session: Session, io: TuiIO, depth: Depth, scroll: number, clear
|
||||
}
|
||||
|
||||
/** `--plain`: one frame as plain text on stdout (the same views, read-only, no escapes) and exit 0. Nothing on stderr, so a script's output is only the frame. */
|
||||
async function once(session: Session, io: TuiIO, view: TuiView): Promise<number> {
|
||||
async function once(session: Session, io: TuiIO, view: Page): Promise<number> {
|
||||
session.show(view)
|
||||
await session.refresh()
|
||||
const columns = Math.max(MIN_COLUMNS, Math.min(200, io.stdout.columns ?? 100))
|
||||
@@ -176,8 +257,8 @@ export async function runTui(options: TuiOptions, io: TuiIO): Promise<number> {
|
||||
return 2
|
||||
}
|
||||
|
||||
const session = openSession({ cwd: options.cwd, ...(options.cliEntry !== undefined && { cliEntry: options.cliEntry }), ...(options.configDir !== undefined && { configDir: options.configDir }), ...(options.home !== undefined && { home: options.home }), ...(options.pluginRoot !== undefined && { pluginRoot: options.pluginRoot }), ...(options.aiPage !== undefined && { aiPage: options.aiPage }) })
|
||||
let view: TuiView = options.view ?? 'overview'
|
||||
const session = openSession({ cwd: options.cwd, ...((options.look ?? (options.plain === true ? 'plain' : undefined)) !== undefined && { look: options.look ?? 'plain' }), fps: options.anim === false ? 0 : fpsOf(options.fps), ...(options.pictures === false && { pictures: false }), ...(options.boot === true && { boot: true }), ...(options.cliEntry !== undefined && { cliEntry: options.cliEntry }), ...(options.configDir !== undefined && { configDir: options.configDir }), ...(options.home !== undefined && { home: options.home }), ...(options.pluginRoot !== undefined && { pluginRoot: options.pluginRoot }), ...(options.aiPage !== undefined && { aiPage: options.aiPage }) })
|
||||
let view: Page = options.view ?? 'overview'
|
||||
|
||||
try {
|
||||
if (options.plain === true || !interactive || io.stdin.setRawMode === undefined) return await once(session, io, view)
|
||||
@@ -185,26 +266,119 @@ export async function runTui(options: TuiOptions, io: TuiIO): Promise<number> {
|
||||
const depth = depthOf(io.env)
|
||||
let scroll = 0
|
||||
let isDone = false
|
||||
let isFocused = true
|
||||
let finish: () => void = () => undefined
|
||||
const done = new Promise<void>(resolve => void (finish = resolve))
|
||||
const draw = () => void (scroll = paint(session, io, depth, scroll))
|
||||
const memory: Memory = { lines: [], columns: 0, rows: 0 }
|
||||
// The go prompt (":" or "/"): a page by its name, id or key, read from the keys, shown in the key line. `notice` is one line of news until the next key.
|
||||
let prompt: string | null = null
|
||||
let notice = ''
|
||||
const history: Page[] = []
|
||||
const line = () => (prompt !== null ? `go> ${prompt}▌ (a page, or an action to ask for · Enter · Esc cancels)` : notice !== '' ? notice : session.page !== 'ai' && session.pending() !== null ? 'y runs the command in the card · n or Esc cancels · the other keys still work' : '')
|
||||
const draw = (tick = false) => void (scroll = paint(session, io, depth, scroll, memory, false, tick, line()))
|
||||
const reread = async () => {
|
||||
await session.refresh()
|
||||
if (!isDone) draw()
|
||||
}
|
||||
session.onChange(() => void (isDone || draw()))
|
||||
|
||||
const open = (next: Page) => {
|
||||
if (next !== view) history.push(view), history.length > 30 && history.shift()
|
||||
|
||||
view = next
|
||||
scroll = 0
|
||||
session.show(view)
|
||||
view = session.page
|
||||
if (session.page === 'ai') session.ai?.enter()
|
||||
else if (!(TUI_VIEWS as readonly string[]).includes(view)) void reread()
|
||||
}
|
||||
const goTo = (word: string) => {
|
||||
const name = word.trim().replace(/^(go|open)\s+/i, '')
|
||||
const found = name.toLowerCase() === 'ai' ? 'ai' : viewOf(name)
|
||||
|
||||
// A name that is not a page is an action, asked the console's way: a read runs at once, a change shows a card and waits for a y.
|
||||
if (name.startsWith('>')) notice = session.palette(name.slice(1))
|
||||
else if (found === null || found === 'agent') notice = session.palette(name)
|
||||
else open(found)
|
||||
}
|
||||
const onMouse = (chunk: string): boolean => {
|
||||
const hit = /^\u001b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(chunk)
|
||||
|
||||
if (hit === null) return false
|
||||
|
||||
const [button, x, y] = [Number(hit[1]), Number(hit[2]), Number(hit[3])]
|
||||
|
||||
if (hit[4] !== 'M') return true
|
||||
if (button === 64) scroll = Math.max(0, scroll - 3)
|
||||
else if (button === 65) scroll += 3
|
||||
else if (button === 0 && y === 1) {
|
||||
const page = navHit(x, Math.min(200, io.stdout.columns ?? 100))
|
||||
|
||||
if (page !== null) open(page)
|
||||
}
|
||||
|
||||
draw()
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
const onKey = (chunk: Buffer | string) => {
|
||||
// The AI page takes the keys while you type (digits and letters are text there): Esc hands them back to the shell, and Ctrl-C always quits.
|
||||
if (view === 'ai' && session.ai !== null && session.ai.press(chunk.toString()).consumed) return draw()
|
||||
if (session.page === 'ai' && session.ai !== null && session.ai.press(chunk.toString()).consumed) return draw()
|
||||
|
||||
const key = keyOf(chunk.toString())
|
||||
// Focus reports (the terminal tells us when it is behind another window): a hidden terminal draws nothing, and a refocused one draws at once.
|
||||
if (chunk.toString() === `${ESC}[O`) return void (isFocused = false)
|
||||
if (chunk.toString() === `${ESC}[I`) return void ((isFocused = true), draw())
|
||||
|
||||
if (options.mouse === true && onMouse(chunk.toString())) return
|
||||
|
||||
const text = chunk.toString()
|
||||
|
||||
notice = ''
|
||||
|
||||
if (prompt !== null) {
|
||||
if (text === '\r' || text === '\n') {
|
||||
const word = prompt
|
||||
|
||||
prompt = null
|
||||
goTo(word)
|
||||
} else if (text === ESC || text === '\u0003') prompt = null
|
||||
else if (text === '\u007f' || text === '\b') prompt = prompt.slice(0, -1)
|
||||
else if (text.length === 1 && text >= ' ' && text !== '\u007f' && prompt.length < 40) prompt += text
|
||||
else if (text.length > 1 && !text.includes(ESC) && prompt.length + text.length <= 40) prompt += clean(text).replace(/[\r\n]/g, '')
|
||||
|
||||
return draw()
|
||||
}
|
||||
|
||||
// A waiting card: only a lone y, while the whole card is on screen, runs it; n or Esc drops it (a paste is text, never an answer).
|
||||
if (session.page !== 'ai' && session.pending() !== null) {
|
||||
if (text === 'y' || text === 'Y') return void (session.answer(true), draw())
|
||||
if (text === 'n' || text === 'N' || text === ESC) return void (session.answer(false), draw())
|
||||
}
|
||||
|
||||
// The main menu's keys are the console's own: an entry opens by its key chip (q still quits, and p is the palette, here the go prompt).
|
||||
if (view === 'menu' && text.length === 1 && text !== 'q') {
|
||||
const entry = VIEWS.find(candidate => candidate.key !== '' && candidate.key === text)
|
||||
|
||||
if (entry !== undefined) return void (open(entry.id), draw())
|
||||
if (text === 'p') return void ((prompt = ''), draw())
|
||||
}
|
||||
|
||||
const key = keyOf(text)
|
||||
const page = Math.max(1, (io.stdout.rows ?? 30) - 2)
|
||||
|
||||
if (key === 'quit') return finish()
|
||||
if (typeof key === 'object' && key !== null) (view = key.page), (scroll = 0), session.show(view), view === 'ai' && session.ai?.enter()
|
||||
else if (key === 'next') (view = TUI_VIEWS[(TUI_VIEWS.indexOf(view) + 1) % TUI_VIEWS.length] as TuiView), (scroll = 0), session.show(view)
|
||||
else if (key === 'prev') (view = TUI_VIEWS[(TUI_VIEWS.indexOf(view) + TUI_VIEWS.length - 1) % TUI_VIEWS.length] as TuiView), (scroll = 0), session.show(view)
|
||||
if (typeof key === 'object' && key !== null) open(key.page)
|
||||
else if (key === 'menu') open('menu')
|
||||
else if (key === 'prompt') prompt = ''
|
||||
else if (key === 'back') {
|
||||
const previous = history.pop()
|
||||
|
||||
if (previous === undefined) notice = 'nothing to go back to'
|
||||
else (view = previous), (scroll = 0), session.show(view), (view = session.page)
|
||||
}
|
||||
else if (key === 'next') open(TUI_VIEWS[(TUI_VIEWS.indexOf(view as TuiView) + 1) % TUI_VIEWS.length] as TuiView)
|
||||
else if (key === 'prev') open(TUI_VIEWS[(TUI_VIEWS.indexOf(view as TuiView) + TUI_VIEWS.length - 1) % TUI_VIEWS.length] as TuiView)
|
||||
else if (key === 'down') scroll += 1
|
||||
else if (key === 'up') scroll = Math.max(0, scroll - 1)
|
||||
else if (key === 'pagedown') scroll += page
|
||||
@@ -212,23 +386,37 @@ export async function runTui(options: TuiOptions, io: TuiIO): Promise<number> {
|
||||
else if (key === 'top') scroll = 0
|
||||
else if (key === 'bottom') scroll = Number.MAX_SAFE_INTEGER
|
||||
else if (key === 'refresh') void reread()
|
||||
else if (key === 'look') session.cycleLook()
|
||||
else return
|
||||
|
||||
draw()
|
||||
}
|
||||
|
||||
session.show(view)
|
||||
io.stdout.write(`${ESC}[?1049h${ESC}[?25l`)
|
||||
io.stdout.write(`${ESC}[?1049h${ESC}[?25l${ESC}[?1004h${options.mouse === true ? `${ESC}[?1000h${ESC}[?1006h` : ''}`)
|
||||
io.stdin.setRawMode(true)
|
||||
io.stdin.resume()
|
||||
io.stdin.on('data', onKey)
|
||||
const resize = () => void (scroll = paint(session, io, depth, scroll, true))
|
||||
const resize = () => void (scroll = paint(session, io, depth, scroll, memory, true))
|
||||
|
||||
io.stdout.on?.('resize', resize)
|
||||
io.signal?.addEventListener('abort', finish, { once: true })
|
||||
draw()
|
||||
|
||||
const timer = setInterval(() => void reread(), Math.max(3000, options.refreshMs ?? 3000))
|
||||
// The frame clock: only while something moves, the terminal is in front, and the last frame was done in time (a slow terminal skips frames, never queues them).
|
||||
const fps = options.anim === false ? 0 : fpsOf(options.fps)
|
||||
let isDrawing = false
|
||||
const clock = fps === 0 ? null : setInterval(() => {
|
||||
if (isDone || isDrawing || !isFocused || !session.moving()) return
|
||||
|
||||
isDrawing = true
|
||||
try {
|
||||
draw(true)
|
||||
} finally {
|
||||
isDrawing = false
|
||||
}
|
||||
}, Math.round(1000 / fps))
|
||||
|
||||
void reread()
|
||||
|
||||
@@ -237,11 +425,12 @@ export async function runTui(options: TuiOptions, io: TuiIO): Promise<number> {
|
||||
} finally {
|
||||
isDone = true
|
||||
clearInterval(timer)
|
||||
if (clock !== null) clearInterval(clock)
|
||||
io.stdin.off('data', onKey)
|
||||
io.stdout.off?.('resize', resize)
|
||||
io.stdin.setRawMode(false)
|
||||
io.stdin.pause()
|
||||
io.stdout.write(`${ESC}[?25h${ESC}[?1049l`)
|
||||
io.stdout.write(`${options.mouse === true ? `${ESC}[?1006l${ESC}[?1000l` : ''}${ESC}[?1004l${ESC}[?25h${ESC}[?1049l`)
|
||||
}
|
||||
|
||||
return 0
|
||||
|
||||
@@ -5,10 +5,14 @@
|
||||
*/
|
||||
import { createController, type Controller } from '../hooks/controller'
|
||||
import type { Host } from '../hooks/host'
|
||||
import { newState, type State } from '../hooks/state'
|
||||
import { BODIES } from '../hooks/views/pane'
|
||||
import { newState, VIEWS, type Pending, type State, type ViewId } from '../hooks/state'
|
||||
import { picturesOf } from '../hooks/views/frames'
|
||||
import { BODIES, NARROW } from '../hooks/views/pane'
|
||||
import { filterPalette, isUnavailable, paletteEntries } from '../hooks/palette'
|
||||
import { PARITY } from './parity'
|
||||
import { standalonePane } from '../hooks/views/standalone-pane'
|
||||
import { render, terminalKit, type Depth } from './ansi'
|
||||
import { clean, render, terminalKit, type Depth } from './ansi'
|
||||
import { pinnedLines } from './pinned'
|
||||
import { aiConfigOf, openAi, type Ai, type AiOptions as AiPageOptions } from './ai'
|
||||
import { aiFrame } from './ai-page'
|
||||
import { allowedHostsOf } from './ai-guard'
|
||||
@@ -22,9 +26,22 @@ export const TUI_VIEWS = ['overview', 'cost', 'swarm', 'events', 'missions', 'ai
|
||||
export type TuiView = (typeof TUI_VIEWS)[number]
|
||||
/** The pages that are the console's own views. `ai` is the terminal's own page (ADR-489 phase 3): ask Codex or OpenRouter. */
|
||||
export type ConsoleView = Exclude<TuiView, 'ai'>
|
||||
/** Any page the shell can show: every console view (ADR-489 phase 5, `parity.ts` says what each does here) and the AI page. */
|
||||
export type Page = ViewId | 'ai'
|
||||
|
||||
/** What the AI page may do. Absent: the page says it is off and the host refuses every spawn, send and key read (phase 2). */
|
||||
export type Look = 'bbs' | 'orbital' | 'plain'
|
||||
export const LOOKS: readonly Look[] = ['bbs', 'orbital', 'plain']
|
||||
|
||||
export type SessionOptions = Omit<NodeHostOptions, 'ai'> & {
|
||||
/** The console's look (settings: look): Classic BBS is the default, as in the console. */
|
||||
look?: Look
|
||||
/** Frames per second for moving pictures (settings: fps, default 8; 0 draws every picture still). */
|
||||
fps?: number
|
||||
/** False draws no pictures: the words each picture falls back to. */
|
||||
pictures?: boolean
|
||||
/** True plays the look's start-up screen for its first seconds (settings: boot), as the console does. Off by default here. */
|
||||
boot?: boolean
|
||||
aiPage?: AiPageOptions & { codexBin?: string; fetch?: typeof fetch }
|
||||
}
|
||||
|
||||
@@ -39,11 +56,26 @@ export type Session = {
|
||||
aiStatus: AiStatus
|
||||
/** True when the last AI frame had the whole question card on screen: only then may a y answer it. */
|
||||
cardFits: boolean
|
||||
/** The look now drawn, and a step to the next one (bbs, orbital, plain). */
|
||||
look: Look
|
||||
cycleLook: () => Look
|
||||
/** True when this frame has anything that moves (a picture drawn at fps above 0): the shell redraws on its clock only then. */
|
||||
moving: () => boolean
|
||||
/** The page now showing. */
|
||||
page: TuiView
|
||||
page: Page
|
||||
/** The waiting confirm card, if any (the console's own `state.pending`). */
|
||||
pending: () => Pending | null
|
||||
/** Lines pinned under the page bar: the confirm card, or the last action's result for 20 s. `room` is the rows the terminal has for them and the page. The card counts as shown only when it is drawn whole. */
|
||||
pinned: (columns: number, depth: Depth, room: number) => string[]
|
||||
/** True when the whole card was on screen in the last frame: only then may a y answer it (#3983). */
|
||||
cardShown: () => boolean
|
||||
/** The best palette match for `word`, started the console's way: a read runs now, a change raises a card and waits. Returns one line saying what happened. */
|
||||
palette: (word: string) => string
|
||||
/** y or n on the waiting card. A yes names the card it answers, as on the console. */
|
||||
answer: (yes: boolean) => void
|
||||
/** Reads the disk again and runs the page's read-only probes, then returns. Never throws. */
|
||||
refresh: () => Promise<void>
|
||||
show: (view: TuiView) => void
|
||||
show: (view: Page) => void
|
||||
/** The page as terminal lines, `columns` wide. `rows` is how many the terminal has for it (the AI page fits its conversation to them). */
|
||||
frame: (columns: number, depth: Depth, rows?: number) => string[]
|
||||
/** Something changed that the screen should show (streamed output): the shell redraws. */
|
||||
@@ -70,7 +102,7 @@ export function openSession(options: SessionOptions, host?: Host): Session {
|
||||
}),
|
||||
}
|
||||
const node = host ?? createNodeHost(hostOptions)
|
||||
const state = newState({ look: 'plain', fps: 0, boot: false, panel: 'off', eventsPersist: false } as never)
|
||||
const state = newState({ look: options.look ?? 'bbs', fps: options.fps ?? 8, boot: options.boot === true, panel: 'off', eventsPersist: false } as never)
|
||||
|
||||
state.cwd = options.cwd
|
||||
state.isInteractive = true
|
||||
@@ -79,13 +111,14 @@ export function openSession(options: SessionOptions, host?: Host): Session {
|
||||
state.pane.isOpen = true
|
||||
state.pane.isShown = true
|
||||
state.pane.isFocused = true
|
||||
state.pane.bootAtMs = 0
|
||||
state.pane.bootAtMs = options.boot === true ? Date.now() : 0
|
||||
|
||||
const controller = createController(state, node)
|
||||
const ai = page === undefined ? null : openAi(state, node, page)
|
||||
const aiStatus: AiStatus = { codex: ai === null ? 'off' : 'checking…', openrouter: ai === null ? 'off' : 'checking…' }
|
||||
let current: TuiView = 'overview'
|
||||
let current: Page = 'overview'
|
||||
let cardFits = false
|
||||
let isMoving = false
|
||||
|
||||
const ready = Promise.all([node.home().then(home => void (state.home = home ?? null), () => undefined), node.configDir().then(dir => void (state.configDir = dir ?? null), () => undefined)])
|
||||
|
||||
@@ -101,6 +134,45 @@ export function openSession(options: SessionOptions, host?: Host): Session {
|
||||
get page() {
|
||||
return current
|
||||
},
|
||||
get look() {
|
||||
return state.options.look as Look
|
||||
},
|
||||
cycleLook: () => {
|
||||
const next = LOOKS[(LOOKS.indexOf(state.options.look as Look) + 1) % LOOKS.length] as Look
|
||||
|
||||
state.options.look = next
|
||||
|
||||
return next
|
||||
},
|
||||
moving: () => isMoving,
|
||||
pending: () => state.pending,
|
||||
cardShown: () => state.pending !== null && state.shownCard === (state.pending.id ?? null),
|
||||
pinned: (columns, depth, room) => pinnedLines(state, columns, depth, room),
|
||||
palette: word => {
|
||||
const query = word.trim()
|
||||
const lower = query.toLowerCase()
|
||||
// Not the console's loose letters-in-order match: here a typed word must be IN the entry's name (or its id, or start a text command), so a typo never starts an action.
|
||||
const all = paletteEntries(state, Date.now())
|
||||
const best = all.find(entry => entry.id.toLowerCase() === lower) ?? filterPalette(all, query, 'all').find(entry => entry.label.toLowerCase().includes(lower) || (entry.run.kind === 'text' && lower.startsWith(`${entry.run.keyword.toLowerCase()} `)))
|
||||
|
||||
if (query === '' || best === undefined) return `no page or action called "${clean(query).slice(0, 30)}"`
|
||||
if (best.run.kind !== 'spec' && best.run.kind !== 'text') return `"${clean(best.label).slice(0, 50)}" is a page or a Claude Code command: use its name as a page`
|
||||
if (isUnavailable(best)) return `"${clean(best.label).slice(0, 50)}" is not available here`
|
||||
|
||||
state.shownCard = null
|
||||
controller.actions.paletteQuery(query)
|
||||
controller.actions.paletteRun(best.id)
|
||||
|
||||
return state.pending !== null ? `ask: ${clean(best.label).slice(0, 60)} (read the card, then y or n)` : `ran: ${clean(best.label).slice(0, 60)}`
|
||||
},
|
||||
answer: yes => {
|
||||
const card = state.pending
|
||||
|
||||
if (card === null) return
|
||||
if (!yes) return void controller.actions.cancel()
|
||||
// A yes runs the card that was drawn whole and read, never one that was not.
|
||||
if (state.shownCard === (card.id ?? null) && card.id !== undefined) controller.actions.confirm(card.id)
|
||||
},
|
||||
refresh: async () => {
|
||||
try {
|
||||
await ready
|
||||
@@ -119,15 +191,20 @@ export function openSession(options: SessionOptions, host?: Host): Session {
|
||||
}
|
||||
},
|
||||
show: view => {
|
||||
current = view
|
||||
// A page whose job another page does (the console's AI terminal is this shell's AI page) opens that page.
|
||||
current = view === 'ai' ? 'ai' : (PARITY[view]?.opens ?? view)
|
||||
|
||||
if (view !== 'ai') {
|
||||
state.view = view
|
||||
state.back = view
|
||||
if (current !== 'ai') {
|
||||
state.view = current
|
||||
state.back = current
|
||||
}
|
||||
},
|
||||
frame: (columns, depth, rows = 30) => {
|
||||
state.pane.columns = columns
|
||||
state.pane.rows = Math.max(0, rows)
|
||||
isMoving = false
|
||||
// The card was not on screen unless this frame (and the shell's pinned rows) draws it whole.
|
||||
if (state.pending === null) state.shownCard = null
|
||||
|
||||
if (current === 'ai') {
|
||||
const drawn = aiFrame(state, ai, aiStatus, columns, depth, rows)
|
||||
@@ -137,7 +214,21 @@ export function openSession(options: SessionOptions, host?: Host): Session {
|
||||
return drawn.lines
|
||||
}
|
||||
|
||||
const tree = standalonePane({ kit: terminalKit(), state, nowMs: Date.now(), columns, pictures: new Map(), act: controller.actions }, BODIES[state.view])
|
||||
// A page about a Claude Code session says so in one screen, not as a page of empty cards.
|
||||
if (PARITY[current as ViewId]?.status === 'claude-only') {
|
||||
const entry = VIEWS.find(view => view.id === current)
|
||||
|
||||
return [`${entry?.label ?? current}: Claude Code only`, '', PARITY[current as ViewId].why, '', 'Open it in the ruflo console inside Claude Code. Press 0 for the main menu, Esc to go back.']
|
||||
}
|
||||
|
||||
// Pictures need colour and room: without either the views say in words what the picture shows (the same fallback the console has below NARROW columns).
|
||||
const draws = options.pictures !== false && depth !== 'none' && columns >= NARROW
|
||||
const now = Date.now()
|
||||
const pictures = draws ? picturesOf(state, columns, now, now, false) : new Map()
|
||||
|
||||
isMoving = draws && state.options.fps > 0 && pictures.size > 0
|
||||
|
||||
const tree = standalonePane({ kit: terminalKit({ raster: draws }), state, nowMs: now, columns, pictures, act: controller.actions }, BODIES[state.view])
|
||||
|
||||
return render(tree, columns, depth)
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ruflo-core",
|
||||
"description": "Foundation plugin — registers the ruflo MCP server (300+ tools across memory/agentdb/embeddings/hooks/aidefence/neural/autopilot/browser/agent/swarm), provides 4 generalist agents (coder/researcher/reviewer/witness-curator), 5 skills (discover-plugins/init-project/ruflo-doctor/ruflo-status/witness), and a curated plugin-discovery catalog",
|
||||
"version": "0.2.8",
|
||||
"version": "0.2.9",
|
||||
"author": {
|
||||
"name": "ruvnet",
|
||||
"url": "https://github.com/ruvnet"
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
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.2.9 — 2026-10-14
|
||||
- fix: failed Bash commands and failed edits are recorded as failures: PostToolUseFailure is registered and forwarded to post-command / post-edit with `-s false` and the real exit code, so the learning layer no longer sees a 100% success rate (#4127, thanks @rudycelekli for #4170)
|
||||
- fix: the hook shim starts the CLI from CLAUDE_PROJECT_DIR, so a session that `cd`ed into a subdirectory no longer gets .claude-flow/ and proven-config files written there (#4176)
|
||||
- perf: telemetry hooks no longer block the tool: the CLI is started detached and the shim returns in about 25 ms instead of 0.2 to 4 s per call; at most 4 run at once per project (RUFLO_HOOK_MAX_PARALLEL), Stop is never dropped, RUFLO_HOOK_SYNC=1 restores the synchronous path (#4128)
|
||||
|
||||
## 0.2.8 — 2026-10-11
|
||||
- fix: the PostToolUse Bash shim stands down when command recording is switched off (`CLAUDE_FLOW_HOOKS_RECORD_COMMANDS=0` or `CLAUDE_FLOW_HOOKS_ENABLED=false`), so no CLI process is started per Bash call (#4056)
|
||||
|
||||
|
||||
@@ -41,6 +41,26 @@
|
||||
]
|
||||
}
|
||||
],
|
||||
"PostToolUseFailure": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "node -e \"process.argv=[process.argv[0],'x','post-command'];require(require('path').join(process.env.CLAUDE_PLUGIN_ROOT,'scripts','ruflo-hook.cjs'))\""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"matcher": "Write|Edit|MultiEdit",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "node -e \"process.argv=[process.argv[0],'x','post-edit'];require(require('path').join(process.env.CLAUDE_PLUGIN_ROOT,'scripts','ruflo-hook.cjs'))\""
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PreCompact": [
|
||||
{
|
||||
"matcher": "manual",
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
'use strict';
|
||||
/**
|
||||
* #4128 (telemetry off the tool path) and #4176 (CLI runs from the project root).
|
||||
* Drives the real shim exactly as hooks.json does, against a slow fake CLI.
|
||||
*/
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { spawnSync } = require('child_process');
|
||||
|
||||
const SHIM = path.join(__dirname, 'ruflo-hook.cjs');
|
||||
const SLOW = path.join(__dirname, 'fixtures', 'hook-cli-slow.cjs');
|
||||
const dedupFreeEnv = (extra) => ({
|
||||
...process.env,
|
||||
RUFLO_MODS_OWNS: '',
|
||||
RUFLO_DISABLE_HOOK_DEDUP: '1',
|
||||
RUFLO_HOOK_SKIP_NPX: '1',
|
||||
RUFLO_HOOK_CLI_OVERRIDE: `"${process.execPath}" "${SLOW}"`,
|
||||
...extra,
|
||||
});
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
async function waitFor(file, ms = 8000) {
|
||||
const end = Date.now() + ms;
|
||||
while (Date.now() < end) { if (fs.existsSync(file)) return JSON.parse(fs.readFileSync(file, 'utf8')); await sleep(50); }
|
||||
return null;
|
||||
}
|
||||
function runShim(subcommand, event, env, cwd) {
|
||||
const t0 = Date.now();
|
||||
const r = spawnSync(process.execPath, [SHIM, subcommand], { input: JSON.stringify(event), env, cwd, encoding: 'utf8', timeout: 20_000 });
|
||||
return { ms: Date.now() - t0, status: r.status, stdout: r.stdout };
|
||||
}
|
||||
const tmp = (name) => fs.mkdtempSync(path.join(os.tmpdir(), name));
|
||||
|
||||
test('post-command returns before a slow CLI finishes, and the CLI still gets argv and stdin (#4128)', async () => {
|
||||
const work = tmp('rf-bg-'); const out = path.join(work, 'out.json');
|
||||
const env = dedupFreeEnv({ HOOK_SLOW_OUT: out, HOOK_SLOW_MS: '2500', RUFLO_HOOK_TMP_DIR: work });
|
||||
const event = { tool_input: { command: 'echo hi' }, tool_response: { exit_code: 0 } };
|
||||
const r = runShim('post-command', event, env, work);
|
||||
assert.equal(r.status, 0);
|
||||
assert.ok(r.ms < 1800, `shim took ${r.ms} ms, expected well under the CLI's 2500 ms`);
|
||||
assert.equal(fs.existsSync(out), false, 'CLI has not finished yet');
|
||||
const got = await waitFor(out);
|
||||
assert.ok(got, 'the detached CLI completed');
|
||||
assert.deepEqual(got.argv, ['hooks', 'post-command', '-c', 'echo hi', '-s', 'true', '-e', '0']);
|
||||
assert.deepEqual(JSON.parse(got.stdin), event);
|
||||
});
|
||||
|
||||
test('PreToolUse telemetry is detached too and the verdict is still printed (#4128)', async () => {
|
||||
const work = tmp('rf-bg-'); const out = path.join(work, 'out.json');
|
||||
const env = dedupFreeEnv({ HOOK_SLOW_OUT: out, HOOK_SLOW_MS: '2500', RUFLO_HOOK_TMP_DIR: work });
|
||||
const r = runShim('modify-bash', { tool_input: { command: 'ls' } }, env, work);
|
||||
assert.equal(r.stdout, '{"permission":"allow"}');
|
||||
assert.ok(r.ms < 1800, `shim took ${r.ms} ms`);
|
||||
assert.ok(await waitFor(out), 'CLI still ran');
|
||||
});
|
||||
|
||||
test('RUFLO_HOOK_SYNC=1 restores the synchronous path', () => {
|
||||
const work = tmp('rf-bg-'); const out = path.join(work, 'out.json');
|
||||
const env = dedupFreeEnv({ HOOK_SLOW_OUT: out, HOOK_SLOW_MS: '600', RUFLO_HOOK_SYNC: '1', RUFLO_HOOK_TMP_DIR: work });
|
||||
const r = runShim('post-command', { tool_input: { command: 'x' }, tool_response: { exit_code: 0 } }, env, work);
|
||||
assert.equal(r.status, 0);
|
||||
assert.equal(fs.existsSync(out), true, 'the CLI had finished when the shim returned');
|
||||
});
|
||||
|
||||
test('the CLI runs from CLAUDE_PROJECT_DIR, not the shell directory the session cd-ed into (#4176)', async () => {
|
||||
const project = fs.realpathSync(tmp('rf-proj-')); const sub = path.join(project, 'sub', 'deep');
|
||||
fs.mkdirSync(sub, { recursive: true });
|
||||
const out = path.join(project, 'out.json');
|
||||
const env = dedupFreeEnv({ HOOK_SLOW_OUT: out, HOOK_SLOW_MS: '50', CLAUDE_PROJECT_DIR: project, RUFLO_HOOK_TMP_DIR: project });
|
||||
runShim('post-command', { tool_input: { command: 'x' }, tool_response: { exit_code: 0 } }, env, sub);
|
||||
const got = await waitFor(out);
|
||||
assert.ok(got, 'CLI ran');
|
||||
assert.equal(fs.realpathSync(got.cwd), project);
|
||||
});
|
||||
|
||||
test('an unusable CLAUDE_PROJECT_DIR is ignored and the process cwd is kept (#4176)', async () => {
|
||||
const work = fs.realpathSync(tmp('rf-cwd-')); const out = path.join(work, 'out.json');
|
||||
for (const bad of ['relative/dir', path.join(work, 'does-not-exist'), path.join(work, 'out-file')]) {
|
||||
fs.rmSync(out, { force: true }); fs.writeFileSync(path.join(work, 'out-file'), 'x');
|
||||
const env = dedupFreeEnv({ HOOK_SLOW_OUT: out, HOOK_SLOW_MS: '50', CLAUDE_PROJECT_DIR: bad, RUFLO_HOOK_TMP_DIR: work });
|
||||
runShim('post-command', { tool_input: { command: 'x' }, tool_response: { exit_code: 0 } }, env, work);
|
||||
const got = await waitFor(out);
|
||||
assert.ok(got, `CLI ran for ${bad}`);
|
||||
assert.equal(fs.realpathSync(got.cwd), work);
|
||||
}
|
||||
});
|
||||
|
||||
test('a burst over the concurrency cap drops telemetry instead of spawning without limit (#4128)', async () => {
|
||||
const work = tmp('rf-cap-');
|
||||
const outs = [0, 1, 2, 3, 4, 5].map((i) => path.join(work, `o${i}.json`));
|
||||
const results = outs.map((o) => runShim('post-command', { tool_input: { command: 'c' }, tool_response: { exit_code: 0 } },
|
||||
dedupFreeEnv({ HOOK_SLOW_OUT: o, HOOK_SLOW_MS: '3000', RUFLO_HOOK_MAX_PARALLEL: '2', RUFLO_HOOK_TMP_DIR: work }), work));
|
||||
assert.ok(results.every((r) => r.status === 0), 'no shim ever fails the turn');
|
||||
await sleep(4500);
|
||||
const finished = outs.filter((o) => fs.existsSync(o)).length;
|
||||
assert.equal(finished, 2, `exactly the cap of 2 ran, got ${finished}`);
|
||||
});
|
||||
|
||||
test('a freed slot is reused: after the CLIs exit the next event runs again', async () => {
|
||||
const work = tmp('rf-reuse-'); const out = path.join(work, 'o.json');
|
||||
const env = dedupFreeEnv({ HOOK_SLOW_OUT: out, HOOK_SLOW_MS: '150', RUFLO_HOOK_MAX_PARALLEL: '1', RUFLO_HOOK_TMP_DIR: work });
|
||||
const ev = { tool_input: { command: 'c' }, tool_response: { exit_code: 0 } };
|
||||
runShim('post-command', ev, env, work);
|
||||
assert.ok(await waitFor(out), 'first ran');
|
||||
await sleep(300); fs.rmSync(out, { force: true });
|
||||
runShim('post-command', ev, env, work);
|
||||
assert.ok(await waitFor(out), 'second ran after the first exited');
|
||||
});
|
||||
|
||||
test('session-end is never dropped by the cap', async () => {
|
||||
const work = tmp('rf-stop-'); const out = path.join(work, 'o.json');
|
||||
const base = { HOOK_SLOW_MS: '3000', RUFLO_HOOK_MAX_PARALLEL: '1', RUFLO_HOOK_TMP_DIR: work };
|
||||
runShim('post-command', { tool_input: { command: 'c' }, tool_response: { exit_code: 0 } }, dedupFreeEnv({ ...base, HOOK_SLOW_OUT: path.join(work, 'x.json') }), work);
|
||||
runShim('session-end', {}, dedupFreeEnv({ ...base, HOOK_SLOW_MS: '100', HOOK_SLOW_OUT: out }), work);
|
||||
assert.ok(await waitFor(out), 'session-end ran although the single slot was busy');
|
||||
});
|
||||
@@ -7,3 +7,6 @@
|
||||
const [, , group, subcommand] = process.argv;
|
||||
if (group !== 'hooks' || !subcommand) process.exit(2);
|
||||
process.stdout.write(`hook-telemetry:${subcommand}`);
|
||||
if (process.env.RUFLO_HOOK_RECORD_ARGS === '1') {
|
||||
process.stdout.write(` ${JSON.stringify(process.argv.slice(2))}`);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// Test fixture: a "CLI" that is slow like a cold ruflo start and records what it
|
||||
// received (argv, cwd, stdin) so a test can prove the hook shim returned first
|
||||
// and still delivered everything (#4128, #4176).
|
||||
const fs = require('fs');
|
||||
const out = process.env.HOOK_SLOW_OUT;
|
||||
const delay = Number(process.env.HOOK_SLOW_MS || 1500);
|
||||
let stdin = '';
|
||||
try { stdin = fs.readFileSync(0, 'utf8'); } catch { /* no stdin */ }
|
||||
setTimeout(() => {
|
||||
if (out) fs.writeFileSync(out, JSON.stringify({ argv: process.argv.slice(2), cwd: process.cwd(), stdin }));
|
||||
}, delay);
|
||||
@@ -18,7 +18,7 @@
|
||||
* empty stdout: a bare Cursor permission object is not valid Codex
|
||||
* hook JSON and is rejected with "hook returned invalid pre-tool-use
|
||||
* JSON output" (#2816, #2856).
|
||||
* - post-command / post-edit (PostToolUse) — parse the hook event JSON
|
||||
* - post-command / post-edit (PostToolUse/Failure) — parse the hook event JSON
|
||||
* from stdin (no jq), extract the same fields the bash version pulled
|
||||
* with jq, and forward them as CLI flags.
|
||||
* - precompact-manual / precompact-auto (PreCompact) — static guidance
|
||||
@@ -40,7 +40,7 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
const { spawnSync } = require('child_process');
|
||||
const { spawn, spawnSync } = require('child_process');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
@@ -66,6 +66,105 @@ function npxPrefix(env = process.env) {
|
||||
return envValue(env, 'CLAUDE_PLUGIN_DATA') || envValue(env, 'PLUGIN_DATA') || require('os').homedir();
|
||||
}
|
||||
|
||||
/**
|
||||
* #4176: run the CLI from the project root, not from wherever the session's
|
||||
* shell last `cd`ed to. Claude Code keeps a `cd` across Bash calls, so without
|
||||
* an explicit cwd every hook spawned the CLI inside a subdirectory and the CLI
|
||||
* wrote .claude-flow/ and proven-config state there. CLAUDE_PROJECT_DIR is the
|
||||
* host's own statement of the project root; anything that is not an existing
|
||||
* absolute directory is ignored (the CLI then keeps the process cwd, as before).
|
||||
*/
|
||||
function projectCwd(env = process.env) {
|
||||
const dir = envValue(env, 'CLAUDE_PROJECT_DIR');
|
||||
if (!dir || !path.isAbsolute(dir)) return undefined;
|
||||
try { return fs.statSync(dir).isDirectory() ? dir : undefined; } catch { return undefined; }
|
||||
}
|
||||
|
||||
/**
|
||||
* #4128: telemetry must not sit on the tool path. Measured 0.9 s per PreToolUse
|
||||
* and 1.5-4 s per PostToolUse (a cold CLI start each time). Unless a test asks
|
||||
* for the synchronous path (RUFLO_HOOK_DEBUG_STDOUT=1 or RUFLO_HOOK_SYNC=1) the
|
||||
* CLI is started detached and the shim returns at once. Two guards keep that
|
||||
* from becoming a process storm in a tool-call burst: a small slot table (the
|
||||
* default of 4 concurrent telemetry CLIs, RUFLO_HOOK_MAX_PARALLEL to change it;
|
||||
* over the cap an event is dropped, because this is best-effort telemetry) and a
|
||||
* 0600 temp file that carries the event JSON to the child's stdin, so the shim
|
||||
* can exit without waiting for a pipe to drain.
|
||||
*/
|
||||
function backgroundEnabled(env = process.env) {
|
||||
if ((envValue(env, 'RUFLO_HOOK_DEBUG_STDOUT') || '') === '1') return false;
|
||||
return !/^(1|true|yes|on)$/i.test(envValue(env, 'RUFLO_HOOK_SYNC') || '');
|
||||
}
|
||||
|
||||
function hookTempDir(name, env = process.env) {
|
||||
return path.join(envValue(env, 'RUFLO_HOOK_TMP_DIR') || os.tmpdir(), name);
|
||||
}
|
||||
|
||||
function pidAlive(pid) {
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
||||
try { process.kill(pid, 0); return true; } catch (error) { return error?.code === 'EPERM'; }
|
||||
}
|
||||
|
||||
/** Claim one of N slots for this project. Returns {release(pid)} or null when all are busy. */
|
||||
function acquireSlot(env = process.env, keepAlways = false) {
|
||||
const max = Math.max(1, Math.min(32, Number.parseInt(envValue(env, 'RUFLO_HOOK_MAX_PARALLEL') || '4', 10) || 4));
|
||||
try {
|
||||
const project = crypto.createHash('sha256').update(path.resolve(projectCwd(env) || process.cwd())).digest('hex').slice(0, 16);
|
||||
const dir = path.join(hookTempDir('ruflo-hook-slots-v1', env), project);
|
||||
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
for (let i = 0; i < max; i++) {
|
||||
const file = path.join(dir, 'slot-' + i);
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
try {
|
||||
const fd = fs.openSync(file, 'wx', 0o600);
|
||||
fs.writeSync(fd, String(Date.now()));
|
||||
fs.closeSync(fd);
|
||||
return { file };
|
||||
} catch (error) {
|
||||
if (error?.code !== 'EEXIST') return keepAlways ? { file: null } : null;
|
||||
// Reclaim a slot whose CLI is gone (pid recorded after spawn) or that is stale.
|
||||
let content = '';
|
||||
try { content = fs.readFileSync(file, 'utf8'); } catch { continue; }
|
||||
const [stamp, pid] = content.split(':');
|
||||
const age = Date.now() - Number(stamp);
|
||||
const dead = pid !== undefined && !pidAlive(Number(pid));
|
||||
if (dead || !(age < 120_000)) { try { fs.unlinkSync(file); } catch { /* raced */ } continue; }
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return keepAlways ? { file: null } : null;
|
||||
} catch {
|
||||
return keepAlways ? { file: null } : null; // cannot track: run, never block the turn
|
||||
}
|
||||
}
|
||||
|
||||
function recordSlotPid(slot, pid) {
|
||||
if (!slot?.file || !pid) return;
|
||||
try { fs.writeFileSync(slot.file, Date.now() + ':' + pid, { mode: 0o600 }); } catch { /* best effort */ }
|
||||
}
|
||||
|
||||
/** Write the event to a private temp file and hand back a read fd for the child's stdin. */
|
||||
function stdinFd(input, env = process.env) {
|
||||
const dir = hookTempDir('ruflo-hook-stdin-v1', env);
|
||||
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
const file = path.join(dir, crypto.randomBytes(12).toString('hex'));
|
||||
fs.writeFileSync(file, input || '', { mode: 0o600 });
|
||||
const fd = fs.openSync(file, 'r');
|
||||
return { fd, file };
|
||||
}
|
||||
|
||||
/** Delete stdin files older than an hour (Windows cannot unlink a file still open in the child). */
|
||||
function sweepStdinFiles(env = process.env) {
|
||||
try {
|
||||
const dir = hookTempDir('ruflo-hook-stdin-v1', env);
|
||||
for (const name of fs.readdirSync(dir)) {
|
||||
const file = path.join(dir, name);
|
||||
try { if (Date.now() - fs.statSync(file).mtimeMs > 3_600_000) fs.unlinkSync(file); } catch { /* raced */ }
|
||||
}
|
||||
} catch { /* none */ }
|
||||
}
|
||||
|
||||
/**
|
||||
* Locate a command on PATH using fs only.
|
||||
*
|
||||
@@ -183,6 +282,51 @@ function escapeCmdArg(arg) {
|
||||
return s.replace(/[()%!^"<>&|;,]/g, '^$&');
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the CLI detached (see backgroundEnabled) and return at once. Same
|
||||
* resolution rules as the synchronous path: no shell where one can be avoided,
|
||||
* every element escaped where cmd.exe is unavoidable. Returns true when a CLI
|
||||
* was started, false when the event was dropped over the concurrency cap or the
|
||||
* start failed. Never throws.
|
||||
*/
|
||||
function invokeBackground(bin, binArgs, hookSubcommand, hookArgs, stdinData, { env, platform, cwd, keep }) {
|
||||
let slot = null;
|
||||
let input = null;
|
||||
try {
|
||||
slot = acquireSlot(env, keep);
|
||||
if (!slot) return false;
|
||||
const args = [...binArgs, 'hooks', hookSubcommand, ...hookArgs];
|
||||
const invocation = resolveInvocation(bin, binArgs, { env, platform });
|
||||
const useShell = !invocation && platform === 'win32' && bin !== 'node' && bin !== process.execPath;
|
||||
input = stdinFd(stdinData, env);
|
||||
const child = spawn(
|
||||
invocation ? invocation.command : (useShell ? escapeCmdArg(bin) : bin),
|
||||
invocation ? [...invocation.args, 'hooks', hookSubcommand, ...hookArgs] : (useShell ? args.map(escapeCmdArg) : args),
|
||||
{
|
||||
stdio: [input.fd, 'ignore', 'ignore'],
|
||||
env,
|
||||
...(cwd ? { cwd } : {}),
|
||||
detached: true,
|
||||
windowsHide: true,
|
||||
shell: useShell,
|
||||
},
|
||||
);
|
||||
child.on('error', () => { /* best effort: the host never sees a hook failure */ });
|
||||
child.unref();
|
||||
recordSlotPid(slot, child.pid);
|
||||
return true;
|
||||
} catch {
|
||||
if (slot?.file) { try { fs.unlinkSync(slot.file); } catch { /* none */ } }
|
||||
return false;
|
||||
} finally {
|
||||
if (input) {
|
||||
try { fs.closeSync(input.fd); } catch { /* closed */ }
|
||||
try { fs.unlinkSync(input.file); } catch { /* Windows keeps it until the child exits; swept later */ }
|
||||
if (Math.random() < 0.05) sweepStdinFiles(env);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn the CLI with the hook subcommand + args, forwarding stdinData.
|
||||
* Returns true on success (exit 0), false otherwise. Never throws.
|
||||
@@ -197,14 +341,18 @@ function invokeHook(bin, binArgs, hookSubcommand, hookArgs, stdinData, options =
|
||||
// flag-wiring regressions). Production never sets this — hooks must
|
||||
// never leak CLI output into the host (Cursor's PreToolUse contract).
|
||||
const debug = (envValue(env, 'RUFLO_HOOK_DEBUG_STDOUT') || '') === '1';
|
||||
const cwd = projectCwd(env);
|
||||
const base = {
|
||||
input: stdinData || '',
|
||||
encoding: 'utf8',
|
||||
stdio: debug ? ['pipe', 'pipe', 'pipe'] : ['pipe', 'ignore', 'ignore'],
|
||||
timeout: 30_000,
|
||||
env,
|
||||
...(cwd ? { cwd } : {}),
|
||||
};
|
||||
const background = options.background === true && backgroundEnabled(env);
|
||||
try {
|
||||
if (background) return invokeBackground(bin, binArgs, hookSubcommand, hookArgs, stdinData, { env, platform, cwd, keep: options.keep === true });
|
||||
// Layer 1 — no shell. resolveInvocation() maps the command to a real
|
||||
// executable, and on Windows maps npm's .cmd/.ps1 shim to the .js
|
||||
// entrypoint it wraps, so this becomes `node <entry>` and CreateProcess
|
||||
@@ -257,6 +405,8 @@ function splitCliOverride(str) {
|
||||
|
||||
/** Best-effort: try ruflo, then claude-flow, then npx. Never throws. */
|
||||
function invokeCli(hookSubcommand, hookArgs, stdinData) {
|
||||
// Telemetry runs detached (#4128); Stop is never dropped by the concurrency cap.
|
||||
const options = { background: true, keep: hookSubcommand === 'session-end' };
|
||||
// Test-only escape hatch: point at a specific local build instead of the
|
||||
// commandExists() PATH probe (used by test-hooks.mjs and the plugin-hooks
|
||||
// real-command smoke so tests exercise the build under test, not whatever
|
||||
@@ -265,15 +415,15 @@ function invokeCli(hookSubcommand, hookArgs, stdinData) {
|
||||
const override = process.env.RUFLO_HOOK_CLI_OVERRIDE;
|
||||
if (override) {
|
||||
const [bin, ...binArgs] = splitCliOverride(override);
|
||||
invokeHook(bin, binArgs, hookSubcommand, hookArgs, stdinData);
|
||||
invokeHook(bin, binArgs, hookSubcommand, hookArgs, stdinData, options);
|
||||
return;
|
||||
}
|
||||
if (resolveCommandPath('ruflo')) {
|
||||
invokeHook('ruflo', [], hookSubcommand, hookArgs, stdinData);
|
||||
invokeHook('ruflo', [], hookSubcommand, hookArgs, stdinData, options);
|
||||
return;
|
||||
}
|
||||
if (resolveCommandPath('claude-flow')) {
|
||||
invokeHook('claude-flow', [], hookSubcommand, hookArgs, stdinData);
|
||||
invokeHook('claude-flow', [], hookSubcommand, hookArgs, stdinData, options);
|
||||
return;
|
||||
}
|
||||
// SKIP npx when RUFLO_HOOK_SKIP_NPX=1 — used by CI smokes that test the
|
||||
@@ -283,7 +433,7 @@ function invokeCli(hookSubcommand, hookArgs, stdinData) {
|
||||
// itself works correctly. The bash version doesn't hit this because it
|
||||
// backgrounded the work.
|
||||
if (process.env.RUFLO_HOOK_SKIP_NPX !== '1') {
|
||||
invokeHook('npx', ['--prefer-offline', '--yes', '--prefix', npxPrefix(), 'ruflo@latest'], hookSubcommand, hookArgs, stdinData);
|
||||
invokeHook('npx', ['--prefer-offline', '--yes', '--prefix', npxPrefix(), 'ruflo@latest'], hookSubcommand, hookArgs, stdinData, options);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -446,19 +596,33 @@ function main() {
|
||||
done();
|
||||
}
|
||||
|
||||
// PostToolUse: derive CLI flags from the hook event JSON (replaces jq).
|
||||
// Both completion events use the same commands. Failed tools have no
|
||||
// tool_response.exit_code; Claude Code supplies hook_event_name and an error
|
||||
// beginning with "Exit code N" when a shell exited normally. Never let a
|
||||
// missing code turn PostToolUseFailure into a recorded success (#4127).
|
||||
if (subcommand === 'post-command') {
|
||||
if (commandRecordingOff()) done();
|
||||
const cmd = event?.tool_input?.command;
|
||||
if (!cmd) done(); // bash version: `[ -z "$CMD" ] && exit 0`
|
||||
const exitCode = event?.tool_response?.exit_code ?? 0;
|
||||
invokeCli('post-command', ['-c', String(cmd), '-s', String(exitCode === 0), '-e', String(exitCode)], stdinData);
|
||||
const failed = event?.hook_event_name === 'PostToolUseFailure';
|
||||
const errorExit = typeof event?.error === 'string'
|
||||
? /^Exit code ([1-9]\d*)\b/.exec(event.error)?.[1]
|
||||
: undefined;
|
||||
const parsedExit = Number(errorExit);
|
||||
const exitCode = failed
|
||||
? (Number.isSafeInteger(parsedExit) && parsedExit > 0 ? parsedExit : 1)
|
||||
: (event?.tool_response?.exit_code ?? 0);
|
||||
invokeCli('post-command', ['-c', String(cmd), '-s', String(!failed && exitCode === 0), '-e', String(exitCode)], stdinData);
|
||||
done();
|
||||
}
|
||||
if (subcommand === 'post-edit') {
|
||||
const file = event?.tool_input?.file_path ?? event?.tool_input?.path;
|
||||
if (!file) done(); // bash version: `[ -z "$FILE" ] && exit 0`
|
||||
invokeCli('post-edit', ['-f', String(file), '-s', 'true'], stdinData);
|
||||
// Documented flags: -f <file> -s <success>. A failed edit (PostToolUseFailure) records success=false.
|
||||
const editArgs = event?.hook_event_name === 'PostToolUseFailure'
|
||||
? ['-f', String(file), '-s', 'false']
|
||||
: ['-f', String(file), '-s', 'true'];
|
||||
invokeCli('post-edit', editArgs, stdinData);
|
||||
done();
|
||||
}
|
||||
|
||||
@@ -489,4 +653,4 @@ if (process.env.RUFLO_HOOK_UNIT_TEST !== '1') {
|
||||
main();
|
||||
}
|
||||
|
||||
module.exports = { commandRecordingOff, escapeCmdArg, invokeHook, npxPrefix, resolveCommandPath, resolveInvocation, resolveNpmShim };
|
||||
module.exports = { acquireSlot, backgroundEnabled, commandRecordingOff, escapeCmdArg, projectCwd, invokeHook, npxPrefix, resolveCommandPath, resolveInvocation, resolveNpmShim };
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# Structural smoke test for ruflo-core v0.2.8 (ADR-0001).
|
||||
# Structural smoke test for ruflo-core v0.2.9 (ADR-0001).
|
||||
set -u
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
PASS=0
|
||||
@@ -8,10 +8,10 @@ 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.2.8 with new keywords"
|
||||
step "1. plugin.json declares 0.2.9 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.2.8" ]]; then
|
||||
bad "expected 0.2.8, got '$v'"
|
||||
if [[ "$v" != "0.2.9" ]]; then
|
||||
bad "expected 0.2.9, got '$v'"
|
||||
else
|
||||
miss=""
|
||||
for k in foundation mcp-server plugin-catalog discovery; do
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* Regression guard for ruvnet/ruflo#1859, #1862, #2721, #2816, #2856.
|
||||
*
|
||||
* Drives every hook command from `hooks/hooks.json` — PreToolUse,
|
||||
* PostToolUse, PreCompact, Stop — with synthetic Claude-Code-style stdin,
|
||||
* PostToolUse, PostToolUseFailure, PreCompact, Stop — with synthetic Claude-Code-style stdin,
|
||||
* against a locally built CLI, executed EXACTLY as Claude Code/Codex would
|
||||
* run it: `spawnSync(command, { shell: true, ... })`, no bash wrapper of
|
||||
* our own. That's the point of this rewrite (#2721) — the old version
|
||||
@@ -77,6 +77,8 @@ const cmdModifyBash = findHook('PreToolUse', 'Bash');
|
||||
const cmdModifyFile = findHook('PreToolUse', 'Write|Edit|MultiEdit');
|
||||
const cmdPostCommand = findHook('PostToolUse', 'Bash');
|
||||
const cmdPostEdit = findHook('PostToolUse', 'Write|Edit|MultiEdit');
|
||||
const cmdFailedCommand = findHook('PostToolUseFailure', 'Bash');
|
||||
const cmdFailedEdit = findHook('PostToolUseFailure', 'Write|Edit|MultiEdit');
|
||||
const cmdPrecompactManual = findHook('PreCompact', 'manual');
|
||||
const cmdPrecompactAuto = findHook('PreCompact', 'auto');
|
||||
const cmdStop = findHook('Stop', undefined);
|
||||
@@ -254,6 +256,53 @@ run('Bash hook silently no-ops on empty stdin',
|
||||
'',
|
||||
[]);
|
||||
|
||||
// #4127: Claude Code sends failed tools to PostToolUseFailure, not PostToolUse.
|
||||
// Verify actual plugin registration and the argv passed to the CLI; a hook
|
||||
// returning 0 alone would miss the original false-success telemetry bug.
|
||||
const recorderOverride = `"${process.execPath}" "${HOOK_RECORDER}"`;
|
||||
const recordedArgs = {
|
||||
cliOverride: recorderOverride,
|
||||
// Deduplication is covered separately below; fixed event IDs would otherwise
|
||||
// make a repeated local run skip these argv assertions.
|
||||
env: { RUFLO_HOOK_RECORD_ARGS: '1', RUFLO_DISABLE_HOOK_DEDUP: '1' },
|
||||
};
|
||||
|
||||
run('Failed Bash hook records non-zero exit and false success',
|
||||
cmdFailedCommand,
|
||||
JSON.stringify({
|
||||
hook_event_name: 'PostToolUseFailure', tool_use_id: 'toolu_failed_bash_4127',
|
||||
tool_input: { command: 'echo failed; exit 3' }, error: 'Exit code 3\nfailed',
|
||||
}),
|
||||
[{ contains: JSON.stringify(['hooks', 'post-command', '-c', 'echo failed; exit 3', '-s', 'false', '-e', '3']) }],
|
||||
recordedArgs);
|
||||
|
||||
run('Failed Bash hook without numeric exit is still a failure',
|
||||
cmdFailedCommand,
|
||||
JSON.stringify({
|
||||
hook_event_name: 'PostToolUseFailure', tool_use_id: 'toolu_failed_start_4127',
|
||||
tool_input: { command: 'missing-shell-command' }, error: 'Could not start shell',
|
||||
}),
|
||||
[{ contains: JSON.stringify(['hooks', 'post-command', '-c', 'missing-shell-command', '-s', 'false', '-e', '1']) }],
|
||||
recordedArgs);
|
||||
|
||||
run('Failed Edit hook records false success',
|
||||
cmdFailedEdit,
|
||||
JSON.stringify({
|
||||
hook_event_name: 'PostToolUseFailure', tool_use_id: 'toolu_failed_edit_4127',
|
||||
tool_input: { file_path: '/tmp/failed.ts' }, error: 'Permission denied',
|
||||
}),
|
||||
[{ contains: JSON.stringify(['hooks', 'post-edit', '-f', '/tmp/failed.ts', '-s', 'false']) }],
|
||||
recordedArgs);
|
||||
|
||||
run('Successful Edit hook still records true success',
|
||||
cmdPostEdit,
|
||||
JSON.stringify({
|
||||
hook_event_name: 'PostToolUse', tool_use_id: 'toolu_success_edit_4127',
|
||||
tool_input: { file_path: '/tmp/success.ts' }, tool_response: {},
|
||||
}),
|
||||
[{ contains: JSON.stringify(['hooks', 'post-edit', '-f', '/tmp/success.ts', '-s', 'true']) }],
|
||||
recordedArgs);
|
||||
|
||||
// --- PreCompact: pure guidance text, no CLI call ---
|
||||
run('PreCompact (manual) prints guidance and includes custom instructions',
|
||||
cmdPrecompactManual,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ruflo-intelligence",
|
||||
"description": "User-facing surface for Ruflo's self-learning system: 6 neural_* + 10 hooks_intelligence_* + 6 routing/meta hooks + 3 hooks_model-* + 4 SONA/MicroLoRA tools (29 total). Implements the 4-step pipeline (RETRIEVE → JUDGE → DISTILL → CONSOLIDATE) and IPFS-based cross-project pattern transfer.",
|
||||
"version": "0.4.4",
|
||||
"version": "0.4.5",
|
||||
"author": {
|
||||
"name": "ruvnet",
|
||||
"url": "https://github.com/ruvnet"
|
||||
|
||||
@@ -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.4.5 — 2026-10-14
|
||||
- fix: neural-train step 6 passes `data` (neural_train only learns from it and now answers `success: false, status: "empty"` without it), and step 8 says `neural_patterns`/`neural_predict` do not see what trajectories, SONA and the ReasoningBank learned (a separate store; check it with `hooks_intelligence_pattern-search` / `hooks_intelligence_stats`) and that `neural_predict` applies a similarity floor (#4156); intelligence-transfer uses the top-level `transfer-store` command (the nested `hooks transfer store <sub>` only printed help) and warns that the built-in genesis registry is an offline placeholder, not signed or popular data (#4157; thanks @ronmikailov)
|
||||
|
||||
## 0.4.4 — 2026-10-12
|
||||
- fix: the shared text screen now catches `.env` and e-mailed credentials, no longer flags a model's token talk (`--max-tokens`, `/oauth/token`, "token usage"), and no longer flags values that only name where a secret lives (`./service-account.json`, `--set-secrets=NAME=NAME:latest`); every rule stays linear (#4094, thanks @proffesor-for-testing)
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# Structural smoke test for ruflo-intelligence v0.4.4.
|
||||
# Structural smoke test for ruflo-intelligence v0.4.5.
|
||||
# Per ADR-0001 §6 Verification: 13 contract checks + 3 doc invariants.
|
||||
# Offline-safe; no live MCP calls.
|
||||
set -u
|
||||
@@ -27,10 +27,10 @@ grep -qE "IPFS.+pattern|pattern.+IPFS|Pinata" "$ROOT/README.md" \
|
||||
&& ok || bad "README missing IPFS / Pinata transfer docs"
|
||||
|
||||
# 1. plugin.json bump + new keywords
|
||||
step "1. plugin.json declares 0.4.4 with new keywords"
|
||||
step "1. plugin.json declares 0.4.5 with new keywords"
|
||||
v=$(grep -E '"version"[[:space:]]*:' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
|
||||
if [[ "$v" != "0.4.4" ]]; then
|
||||
bad "expected 0.4.4, got '$v'"
|
||||
if [[ "$v" != "0.4.5" ]]; then
|
||||
bad "expected 0.4.5, got '$v'"
|
||||
else
|
||||
miss=""
|
||||
for k in microlora ewc attention moe pattern-transfer model-routing; do
|
||||
|
||||
@@ -12,7 +12,7 @@ Two different mechanisms live under "transfer". Pick by where the patterns are.
|
||||
| Where the patterns are | Mechanism | Needs network |
|
||||
|---|---|---|
|
||||
| Another project on this machine | `hooks_transfer` (MCP) or `hooks transfer from-project` (CLI) | no |
|
||||
| The shared pattern marketplace (IPFS registry) | `hooks transfer store list|search|download|publish` (CLI) | yes |
|
||||
| The shared pattern marketplace (IPFS registry) | `transfer-store list|search|download|publish` (CLI) | yes |
|
||||
|
||||
`hooks_transfer` takes `{ sourcePath, filter?, minConfidence? }` and nothing else. It reads the source project's memory store and copies the patterns that pass `minConfidence` (default 0.7). It has no `store`, `load` or CID action; earlier versions of this skill said it did, and it does not.
|
||||
|
||||
@@ -32,11 +32,15 @@ The source path is read as data. Do not point it at a directory you do not contr
|
||||
## Browse and download from the marketplace
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli@latest hooks transfer store list --featured
|
||||
npx @claude-flow/cli@latest hooks transfer store search --query routing --verified
|
||||
npx @claude-flow/cli@latest hooks transfer store download --name PATTERN_NAME --verify
|
||||
npx @claude-flow/cli@latest transfer-store list --featured
|
||||
npx @claude-flow/cli@latest transfer-store search --query routing --verified
|
||||
npx @claude-flow/cli@latest transfer-store download --name PATTERN_NAME --verify
|
||||
```
|
||||
|
||||
Use the top-level `transfer-store` command. In ruflo 3.56.9 and earlier the nested form `hooks transfer store <sub>` only printed the `store` help and exited 0 without running the subcommand (#4157).
|
||||
|
||||
**Offline fallback is not live data.** If the output says `[Discovery] Using built-in genesis registry` (or `OFFLINE MODE`), no registry could be reached and the CLI is showing one built-in placeholder entry (`source: "builtin-fallback"`, `trustLevel: unverified`, no download counts or rating). It is not a signed or popular pattern. Older versions labelled that entry `verified` with invented counts and a `lastUpdated` equal to the current time; do not trust those fields from ruflo 3.56.9 or earlier.
|
||||
|
||||
Downloads verify a checksum by default. Add `--import` only after you have looked at the downloaded file. The same registry is also reachable from MCP via `transfer_store-search`, `transfer_store-info` and `transfer_store-download`.
|
||||
|
||||
## Publish to the marketplace
|
||||
@@ -48,7 +52,7 @@ Publishing is public and not reversible. Do all of this first:
|
||||
3. Credentials come from the environment: `PINATA_API_KEY` and `PINATA_API_SECRET` (the upload path reads those two, not a JWT). If they are unset the command fails with a clear error; do not ask the user to paste them into the chat.
|
||||
|
||||
```bash
|
||||
npx @claude-flow/cli@latest hooks transfer store publish \
|
||||
npx @claude-flow/cli@latest transfer-store publish \
|
||||
--input patterns.cfp --name my-patterns --description "What these patterns capture" \
|
||||
--categories routing --tags routing,coordination --anonymize strict
|
||||
```
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: neural-train
|
||||
description: Train SONA + MicroLoRA neural patterns from successful task completions; runs the DISTILL + CONSOLIDATE phases of the 4-step pipeline
|
||||
argument-hint: "[--pattern coordination|optimization|prediction|security|testing] [--epochs N]"
|
||||
allowed-tools: mcp__plugin_ruflo-core_ruflo__neural_train mcp__plugin_ruflo-core_ruflo__neural_status mcp__plugin_ruflo-core_ruflo__neural_patterns mcp__plugin_ruflo-core_ruflo__neural_predict mcp__plugin_ruflo-core_ruflo__neural_optimize mcp__plugin_ruflo-core_ruflo__neural_compress mcp__plugin_ruflo-core_ruflo__hooks_pretrain mcp__plugin_ruflo-core_ruflo__hooks_build-agents mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-start mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-step mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-end mcp__plugin_ruflo-core_ruflo__hooks_intelligence_pattern-store mcp__plugin_ruflo-core_ruflo__hooks_intelligence_learn mcp__plugin_ruflo-core_ruflo__hooks_intelligence-reset mcp__plugin_ruflo-core_ruflo__ruvllm_sona_create mcp__plugin_ruflo-core_ruflo__ruvllm_sona_adapt mcp__plugin_ruflo-core_ruflo__ruvllm_microlora_create mcp__plugin_ruflo-core_ruflo__ruvllm_microlora_adapt mcp__plugin_ruflo-core_ruflo__agentdb_consolidate Bash
|
||||
allowed-tools: mcp__plugin_ruflo-core_ruflo__neural_train mcp__plugin_ruflo-core_ruflo__neural_status mcp__plugin_ruflo-core_ruflo__neural_patterns mcp__plugin_ruflo-core_ruflo__neural_predict mcp__plugin_ruflo-core_ruflo__neural_optimize mcp__plugin_ruflo-core_ruflo__neural_compress mcp__plugin_ruflo-core_ruflo__hooks_pretrain mcp__plugin_ruflo-core_ruflo__hooks_build-agents mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-start mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-step mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-end mcp__plugin_ruflo-core_ruflo__hooks_intelligence_pattern-store mcp__plugin_ruflo-core_ruflo__hooks_intelligence_pattern-search mcp__plugin_ruflo-core_ruflo__hooks_intelligence_stats mcp__plugin_ruflo-core_ruflo__hooks_intelligence_learn mcp__plugin_ruflo-core_ruflo__hooks_intelligence-reset mcp__plugin_ruflo-core_ruflo__ruvllm_sona_create mcp__plugin_ruflo-core_ruflo__ruvllm_sona_adapt mcp__plugin_ruflo-core_ruflo__ruvllm_microlora_create mcp__plugin_ruflo-core_ruflo__ruvllm_microlora_adapt mcp__plugin_ruflo-core_ruflo__agentdb_consolidate Bash
|
||||
---
|
||||
|
||||
# Neural Training
|
||||
@@ -22,9 +22,9 @@ Train and consolidate neural patterns. Implements the **DISTILL** and **CONSOLID
|
||||
3. **Record steps** — for each significant action, `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-step`.
|
||||
4. **End trajectory** — `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-end` with `{ trajectoryId, success: true|false, feedback? }` (the tool takes a boolean `success`, not a verdict string).
|
||||
5. **Learn from the trajectory** — `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_learn` (optionally `{ trajectoryIds: [...] }`). It runs a distill + EWC++ consolidation cycle; `consolidate` defaults to true.
|
||||
6. **Train patterns** — `mcp__plugin_ruflo-core_ruflo__neural_train` with `{ modelType: "moe", epochs: 10 }` (`modelType` is required: `moe|transformer|classifier|embedding`). The CLI form is `neural train --pattern coordination --epochs 10`.
|
||||
6. **Train patterns** — `mcp__plugin_ruflo-core_ruflo__neural_train` with `{ modelType: "classifier", data: [{ "text": "<what the task was>", "label": "<outcome or lesson>" }] }` (`modelType` is required: `moe|transformer|classifier|embedding`). It only learns from the `data` you pass: it does not read trajectories, SONA or the ReasoningBank, and without `data` it answers `success: false, status: "empty"` (ruflo 3.56.9 and earlier reported `status: "ready"` with `patternsStored: 0`). The CLI form is `neural train --pattern coordination --epochs 10`.
|
||||
7. **Store patterns** — `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_pattern-store`.
|
||||
8. **Verify** — `mcp__plugin_ruflo-core_ruflo__neural_patterns` to confirm.
|
||||
8. **Verify** — `mcp__plugin_ruflo-core_ruflo__neural_patterns` with `{ action: "list" }` lists only what `neural_train` stored. What steps 2-5 and 7 learned (trajectories, SONA, ReasoningBank, `hooks_intelligence_pattern-store`) is a separate store: check it with `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_pattern-search` or `hooks_intelligence_stats`, not `neural_patterns` or `neural_predict`. `neural_predict` returns a match only above a cosine-similarity floor (default 0.5, `minSimilarity` to change it) and an empty `predictions` list otherwise.
|
||||
|
||||
## SONA adaptation (single-domain, <0.05ms)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ruflo-jujutsu",
|
||||
"description": "Advanced git workflows with diff analysis, risk scoring, change classification (feature/bugfix/refactor/...), and reviewer recommendations — wraps 6 analyze_* MCP tools (diff, diff-risk, diff-classify, diff-reviewers, file-risk, diff-stats). As a mod (ADR-445): a PR-text and merge/close guard, /jujutsu-mod, and a status file the console shows",
|
||||
"version": "0.3.5",
|
||||
"version": "0.3.6",
|
||||
"author": {
|
||||
"name": "ruvnet",
|
||||
"url": "https://github.com/ruvnet"
|
||||
|
||||
@@ -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.6 — 2026-10-14
|
||||
- fix: the README, command, git-specialist agent and diff-analyze skill now say `analyze_diff-reviewers` suggests reviewer roles from file paths and risk, not people from history, and does not read CODEOWNERS (#4163, thanks @rudycelekli)
|
||||
|
||||
## 0.3.5 — 2026-10-12
|
||||
- fix: the shared text screen now catches `.env` and e-mailed credentials, no longer flags a model's token talk (`--max-tokens`, `/oauth/token`, "token usage"), and no longer flags values that only name where a secret lives (`./service-account.json`, `--set-secrets=NAME=NAME:latest`); every rule stays linear (#4094, thanks @proffesor-for-testing)
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ Advanced git workflows with diff analysis, risk scoring, and reviewer recommenda
|
||||
|
||||
- **Diff analysis**: Comprehensive change analysis with risk scoring
|
||||
- **Change classification**: Auto-categorize as feature, bugfix, refactor, etc.
|
||||
- **Reviewer recommendations**: Suggest reviewers based on code ownership
|
||||
- **Reviewer role suggestions**: Suggest roles from file paths and risk; resolve actual owners separately from CODEOWNERS
|
||||
- **File-level risk**: Per-file risk breakdown for targeted review
|
||||
|
||||
## Commands
|
||||
@@ -34,7 +34,7 @@ All defined at `v3/@claude-flow/cli/src/mcp-tools/analyze-tools.ts`:
|
||||
| `analyze_diff` | Full diff analysis (risk + classification + reviewers + stats) |
|
||||
| `analyze_diff-risk` | Risk score for the staged/unstaged diff |
|
||||
| `analyze_diff-classify` | Classify change as feature, bugfix, refactor, perf, security, docs, …|
|
||||
| `analyze_diff-reviewers` | Recommend reviewers based on code ownership |
|
||||
| `analyze_diff-reviewers` | Suggest reviewer roles from paths and risk (does not identify people or read CODEOWNERS) |
|
||||
| `analyze_file-risk` | Per-file risk breakdown |
|
||||
| `analyze_diff-stats` | Lines added/removed, files touched, complexity delta |
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ You are a git workflow specialist using Ruflo's diff analysis tools. Your respon
|
||||
|
||||
1. **Analyze diffs** for risk, complexity, and change classification
|
||||
2. **Score risk** to identify high-risk changes before they merge
|
||||
3. **Recommend reviewers** based on code ownership and expertise
|
||||
3. **Suggest reviewer roles** from paths and risk; consult CODEOWNERS separately for people
|
||||
4. **Manage PRs** through their lifecycle from creation to merge
|
||||
5. **Track metrics** on merge frequency, review times, and code health
|
||||
|
||||
|
||||
@@ -9,5 +9,5 @@ Analyze current git changes:
|
||||
2. Call `mcp__plugin_ruflo-core_ruflo__analyze_diff` with `{ ref, includeFileRisks: true }` for comprehensive analysis
|
||||
3. Call `mcp__plugin_ruflo-core_ruflo__analyze_diff-risk` with `{ ref }` for risk score
|
||||
4. Call `mcp__plugin_ruflo-core_ruflo__analyze_diff-classify` with `{ ref }` for change type classification
|
||||
5. Call `mcp__plugin_ruflo-core_ruflo__analyze_diff-reviewers` with `{ ref, limit }` for reviewer recommendations based on code ownership
|
||||
6. Present: risk level, change type, affected files, and reviewer recommendations
|
||||
5. Call `mcp__plugin_ruflo-core_ruflo__analyze_diff-reviewers` with `{ ref, limit }` for suggested reviewer roles; check CODEOWNERS separately for actual owners
|
||||
6. Present: risk level, change type, affected files, and suggested reviewer roles
|
||||
@@ -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.5 with new keywords"
|
||||
step "1. plugin.json declares 0.3.6 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.5" ]]; then bad "expected 0.3.5, got '$v'"; else
|
||||
if [[ "$v" != "0.3.6" ]]; then bad "expected 0.3.6, got '$v'"; else
|
||||
miss=""
|
||||
for k in mcp change-classification reviewer-recommendation; do
|
||||
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
|
||||
|
||||
@@ -19,7 +19,7 @@ Before submitting a PR or after making significant changes, analyze the diff to
|
||||
1. **Analyze diff** — call `mcp__plugin_ruflo-core_ruflo__analyze_diff` with `{ ref, includeFileRisks: true }` for a comprehensive analysis
|
||||
2. **Risk score** — call `mcp__plugin_ruflo-core_ruflo__analyze_diff-risk` with `{ ref }` for a quantified risk assessment
|
||||
3. **Classify changes** — call `mcp__plugin_ruflo-core_ruflo__analyze_diff-classify` with `{ ref }` to categorize (feature, bugfix, refactor, etc.)
|
||||
4. **Get reviewers** — call `mcp__plugin_ruflo-core_ruflo__analyze_diff-reviewers` with `{ ref, limit }` for recommended reviewers based on code ownership
|
||||
4. **Get reviewer roles** — call `mcp__plugin_ruflo-core_ruflo__analyze_diff-reviewers` with `{ ref, limit }` for roles inferred from paths and risk; check CODEOWNERS separately when assigning people
|
||||
5. **Diff stats** — call `mcp__plugin_ruflo-core_ruflo__analyze_diff-stats` with `{ ref }` for line counts, file counts, complexity metrics
|
||||
6. **File-level risk** — call `mcp__plugin_ruflo-core_ruflo__analyze_file-risk` with `{ path }` (required) for each file the earlier steps flagged
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ruflo-knowledge-graph",
|
||||
"description": "Knowledge graph construction — entity extraction, relation mapping, and pathfinder graph traversal. As a mod (ADR-445): keeps secrets out of the graph, confirms graph deletes, /kg-mod, and a status file the console shows",
|
||||
"version": "0.3.5",
|
||||
"version": "0.3.6",
|
||||
"author": {
|
||||
"name": "ruvnet",
|
||||
"url": "https://github.com/ruvnet"
|
||||
|
||||
@@ -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.6 — 2026-10-14
|
||||
- fix: kg-traverse reads edges with `agentdb_graph-query` (k-hop) and `agentdb_graph-pathfinder`, not the write-only `agentdb_causal-edge`; it no longer calls `agentdb_context-synthesize` (entity records are not validated task episodes, so it always answered `no-eligible-episodes`) and says what to do when encryption at rest (RFE1) makes the graph unreadable; the graph-navigator agent lists the same read tools (#4135, #4161, thanks @ronmikailov)
|
||||
|
||||
## 0.3.5 — 2026-10-12
|
||||
- fix: the shared text screen now catches `.env` and e-mailed credentials, no longer flags a model's token talk (`--max-tokens`, `/oauth/token`, "token usage"), and no longer flags values that only name where a secret lives (`./service-account.json`, `--set-secrets=NAME=NAME:latest`); every rule stays linear (#4094, thanks @proffesor-for-testing)
|
||||
|
||||
|
||||
@@ -40,20 +40,22 @@ You are a knowledge graph navigator agent. Your responsibilities:
|
||||
The pathfinder traversal algorithm finds relevant subgraphs:
|
||||
|
||||
1. **Seed** -- start from the target entity node
|
||||
2. **Expand** -- follow causal edges outward (configurable depth, default 3)
|
||||
2. **Expand** -- follow edges outward with `agentdb_graph-query` mode `k-hop` (configurable depth, default 3)
|
||||
3. **Score** -- compute relevance = edge_weight * semantic_similarity(query, node)
|
||||
4. **Prune** -- remove paths with cumulative score below threshold (default 0.3)
|
||||
5. **Rank** -- return top-K paths sorted by cumulative relevance score
|
||||
|
||||
### Tools
|
||||
|
||||
- `mcp__plugin_ruflo-core_ruflo__agentdb_causal-edge` -- create/query causal edges between entities
|
||||
- `mcp__plugin_ruflo-core_ruflo__agentdb_causal-edge` -- record a causal edge between entities (write only: it never reads edges back; a `readable: false` result means encryption at rest (RFE1) is on and graph reads cannot open the store)
|
||||
- `mcp__plugin_ruflo-core_ruflo__agentdb_graph-query` -- read edges: `{ nodeId: "entity:NAME", mode: "k-hop", depth }` (also `pagerank`, `semantic`)
|
||||
- `mcp__plugin_ruflo-core_ruflo__agentdb_graph-pathfinder` -- scored path search `{ seedNodeId, query, depth, threshold, topK }`
|
||||
- `mcp__plugin_ruflo-core_ruflo__agentdb_hierarchical-store` -- store entity metadata in hierarchical structure
|
||||
- `mcp__plugin_ruflo-core_ruflo__agentdb_hierarchical-recall` -- recall entities by path or query
|
||||
- `mcp__plugin_ruflo-core_ruflo__agentdb_semantic-route` -- semantic similarity routing for graph search (note: `semanticRouter` controller is `enabled: false` in current AgentDB builds — fall back to `agentdb_pattern-search` or `embeddings_generate` + manual cosine; see ruvnet/ruflo#2049)
|
||||
- `mcp__plugin_ruflo-core_ruflo__agentdb_pattern-store` -- store discovered graph patterns
|
||||
- `mcp__plugin_ruflo-core_ruflo__agentdb_pattern-search` -- search for similar graph structures
|
||||
- `mcp__plugin_ruflo-core_ruflo__agentdb_context-synthesize` -- synthesize context from multiple graph nodes
|
||||
- `mcp__plugin_ruflo-core_ruflo__agentdb_context-synthesize` -- summarizes validated task episodes only; it answers `no-eligible-episodes` for entity records, so summarize traversal paths yourself
|
||||
- `mcp__plugin_ruflo-core_ruflo__embeddings_generate` -- generate embeddings for entity descriptions
|
||||
|
||||
### Neural Learning
|
||||
|
||||
@@ -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.5 with new keywords"
|
||||
step "1. plugin.json declares 0.3.6 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.5" ]]; then bad "expected 0.3.5, got '$v'"; else
|
||||
if [[ "$v" != "0.3.6" ]]; then bad "expected 0.3.6, got '$v'"; else
|
||||
miss=""
|
||||
for k in mcp pathfinder-traversal entity-extraction; do
|
||||
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
name: kg-traverse
|
||||
description: Pathfinder traversal of the knowledge graph starting from a seed entity
|
||||
argument-hint: "<entity> [--depth N]"
|
||||
allowed-tools: mcp__plugin_ruflo-core_ruflo__agentdb_hierarchical-recall mcp__plugin_ruflo-core_ruflo__agentdb_causal-edge mcp__plugin_ruflo-core_ruflo__agentdb_pattern-search mcp__plugin_ruflo-core_ruflo__agentdb_context-synthesize Bash
|
||||
allowed-tools: mcp__plugin_ruflo-core_ruflo__agentdb_hierarchical-recall mcp__plugin_ruflo-core_ruflo__agentdb_graph-query mcp__plugin_ruflo-core_ruflo__agentdb_graph-pathfinder mcp__plugin_ruflo-core_ruflo__agentdb_pattern-search Bash
|
||||
---
|
||||
|
||||
# KG Traverse
|
||||
|
||||
Perform pathfinder graph traversal starting from a seed entity. Expands outward through causal edges, scores paths by relevance, and prunes low-similarity branches.
|
||||
Perform pathfinder graph traversal starting from a seed entity. Expands outward through the graph's edges, scores paths by relevance, and prunes low-scoring branches.
|
||||
|
||||
## When to use
|
||||
|
||||
@@ -15,13 +15,15 @@ When you need to explore the knowledge graph starting from a specific entity --
|
||||
|
||||
## Steps
|
||||
|
||||
1. **Seed** -- call `mcp__plugin_ruflo-core_ruflo__agentdb_hierarchical-recall` to look up the target entity by name
|
||||
2. **Expand** -- call `mcp__plugin_ruflo-core_ruflo__agentdb_causal-edge` to find all edges connected to the seed entity, then recursively expand outward to the specified depth (default: 3)
|
||||
3. **Score** -- for each path, compute relevance: `cumulative_score = product(edge_weight * keyword_similarity(query, node))` using `mcp__plugin_ruflo-core_ruflo__agentdb_pattern-search` (the `semanticRouter` controller is `enabled: false` in current AgentDB builds; pattern-search is the available substitute and works fine for entity-name + relation-type keyword matches — see ruvnet/ruflo#2049). For higher-fidelity semantic similarity, callers can fall back to `mcp__plugin_ruflo-core_ruflo__embeddings_generate` + manual cosine, but that's not required for step 3 to function.
|
||||
4. **Prune** -- remove paths with cumulative score below 0.3
|
||||
5. **Rank** -- sort remaining paths by cumulative score descending
|
||||
6. **Synthesize** -- call `mcp__plugin_ruflo-core_ruflo__agentdb_context-synthesize` to combine the top paths into a coherent summary
|
||||
7. **Report** -- display the top 10 paths with: path (entity chain), relation types, cumulative score, and synthesized context
|
||||
1. **Seed** -- call `mcp__plugin_ruflo-core_ruflo__agentdb_hierarchical-recall` to look up the target entity by name (one word is the most reliable query: the recall matches the whole query as a substring). Graph node ids are domain-prefixed, for example `entity:router-account`.
|
||||
2. **Expand** -- call `mcp__plugin_ruflo-core_ruflo__agentdb_graph-query` with `{ nodeId: "entity:NAME", mode: "k-hop", depth: N }` (default depth 3, the SQL path applies at most 3 and reports `appliedDepth` and `truncated`; add `relation` to filter by relation type). `agentdb_causal-edge` only records an edge, never use it to read one.
|
||||
3. **Score and rank** -- call `mcp__plugin_ruflo-core_ruflo__agentdb_graph-pathfinder` with `{ seedNodeId: "entity:NAME", query: "<what the user wants to know>", depth: N, threshold: 0.3, topK: 10 }`. It expands from the seed, scores each path by cumulative relevance, drops paths under the threshold and returns the top paths. If it returns nothing useful, score the k-hop neighbours yourself with `mcp__plugin_ruflo-core_ruflo__agentdb_pattern-search` on entity names and relation types (the `semanticRouter` controller is `enabled: false` in current AgentDB builds; see ruvnet/ruflo#2049).
|
||||
4. **Synthesize** -- write the summary yourself from the returned paths. Do not call `agentdb_context-synthesize`: it summarizes validated task episodes and answers `no-eligible-episodes` for entity records written by `kg-extract`.
|
||||
5. **Report** -- display the top 10 paths with: path (entity chain), relation types, cumulative score, and your summary.
|
||||
|
||||
## When the graph cannot be read
|
||||
|
||||
With `CLAUDE_FLOW_ENCRYPT_AT_REST=1` the graph read tools answer `graph_edges DB is encrypted at rest (RFE1)` (#2889, #4135): edges recorded by `kg-extract` are stored but cannot be read back yet. Say so in the report. Your data is intact: do not run `memory init`. Fall back to the entity records only (`agentdb_hierarchical-recall`) and tell the user that relations are unavailable. An `agentdb_causal-edge` result with `readable: false` already warns about this at write time.
|
||||
|
||||
## CLI alternative
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ruflo-mods",
|
||||
"description": "ruflo as a Claude Code mod (function hooks, ADR-404): in-process prompt routing, edit learning signals, tighten-only tool checks from ruflo policy, the cost-tracker budget ladder, a mod trust gate for newly installed mods, and the $.ruflo noun other mods compose their status with. Opt-in and removable: the classic hook-handler hooks stay the default and take every event back whenever the mod is not loaded.",
|
||||
"version": "0.6.1",
|
||||
"version": "0.6.2",
|
||||
"author": {
|
||||
"name": "ruvnet",
|
||||
"url": "https://github.com/ruvnet"
|
||||
|
||||
@@ -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-mods`.
|
||||
|
||||
## 0.6.2 — 2026-10-14
|
||||
- fix: the mod's route context uses the same query-coverage scoring as hook-handler.cjs (inflection variants, IDF weights, coverage >= 0.15), so a short prompt finds a long memory entry and "migrations" finds "migration" (#4136, #4172); the ADR-404 parity test holds again
|
||||
|
||||
## 0.6.1 — 2026-10-12
|
||||
- fix: root-delete guard expands brace lists (`rm -rf {/*,}`), judges deep nesting by tokens instead of a literal phrase, catches fork-bomb definitions in any spacing or name, and keeps its option checks linear (#4093, thanks @proffesor-for-testing)
|
||||
- fix: the shared text screen now catches `.env` and e-mailed credentials, no longer flags a model's token talk (`--max-tokens`, `/oauth/token`, "token usage"), and no longer flags values that only name where a secret lives (`./service-account.json`, `--set-secrets=NAME=NAME:latest`); every rule stays linear (#4094, thanks @proffesor-for-testing)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* Ranked-memory context for a prompt: the scoring of intelligence.cjs
|
||||
* `getContext` (trigram Jaccard blended with PageRank, top 5 over 0.05),
|
||||
* `getContext` (query-coverage scoring over inflection variants with IDF
|
||||
* weights and a small PageRank blend, top 5 at coverage >= 0.15; #4136),
|
||||
* read-only.
|
||||
*
|
||||
* Copied because a hooks module cannot import intelligence.cjs; the parity
|
||||
@@ -29,8 +30,7 @@ const plainText = (s: string): string =>
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
|
||||
const ALPHA = 0.6
|
||||
const MIN_THRESHOLD = 0.05
|
||||
const MIN_COVERAGE = 0.15
|
||||
const TOP_K = 5
|
||||
|
||||
export type RankedEntry = {
|
||||
@@ -59,15 +59,27 @@ export function trigrams(words: readonly string[]): Set<string> {
|
||||
return t
|
||||
}
|
||||
|
||||
function jaccard(a: ReadonlySet<string>, b: ReadonlySet<string>): number {
|
||||
if (a.size === 0 && b.size === 0) return 0
|
||||
let shared = 0
|
||||
for (const item of a) if (b.has(item)) shared++
|
||||
return shared / (a.size + b.size - shared)
|
||||
}
|
||||
/** An entry with its term set worked out once, when the file is read. */
|
||||
export type PreparedEntry = RankedEntry & { readonly tri: ReadonlySet<string>; readonly terms: ReadonlySet<string> }
|
||||
|
||||
/** An entry with its trigrams worked out once, when the file is read. */
|
||||
export type PreparedEntry = RankedEntry & { readonly tri: ReadonlySet<string> }
|
||||
/**
|
||||
* Inflection variants of a prompt term (plural, -ed, -ing, -ion and their
|
||||
* stems), as in intelligence.cjs: "migrations" finds "migration", "deploying"
|
||||
* finds "deploy". The stem keeps at least 4 characters so short words stay exact.
|
||||
*/
|
||||
export function termVariants(word: string): string[] {
|
||||
const out = new Set<string>([word])
|
||||
for (const suffix of ['s', 'es', 'ed', 'ing', 'ion', 'ions']) out.add(word + suffix)
|
||||
for (const suffix of ['ions', 'ion', 'ing', 'ed', 'es', 's']) {
|
||||
if (word.length - suffix.length >= 4 && word.endsWith(suffix)) {
|
||||
const stem = word.slice(0, -suffix.length)
|
||||
out.add(stem)
|
||||
out.add(stem + 'e')
|
||||
out.add(stem + 's')
|
||||
}
|
||||
}
|
||||
return [...out]
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses ranked-context.json text into its entries, each with its trigrams
|
||||
@@ -81,7 +93,10 @@ export function parseRanked(text: string): readonly PreparedEntry[] {
|
||||
if (!Array.isArray(entries)) return []
|
||||
return entries
|
||||
.filter((e): e is RankedEntry => e !== null && typeof e === 'object')
|
||||
.map(e => ({ ...e, tri: trigrams(Array.isArray(e.words) ? e.words.filter(w => typeof w === 'string') : []) }))
|
||||
.map(e => {
|
||||
const words = Array.isArray(e.words) ? e.words.filter((w): w is string => typeof w === 'string') : []
|
||||
return { ...e, tri: trigrams(words), terms: new Set(words) }
|
||||
})
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
@@ -95,15 +110,38 @@ export function parseRanked(text: string): readonly PreparedEntry[] {
|
||||
*/
|
||||
export function rankedContext(prompt: string, entries: readonly PreparedEntry[]): string | null {
|
||||
if (!prompt || entries.length === 0) return null
|
||||
const words = tokenize(prompt)
|
||||
if (words.length === 0) return null
|
||||
const promptTrigrams = trigrams(words)
|
||||
const promptWords = [...new Set(tokenize(prompt))]
|
||||
if (promptWords.length === 0) return null
|
||||
|
||||
// Query coverage is independent of entry length; IDF downweights terms shared
|
||||
// by many entries; terms absent from every entry still count against coverage.
|
||||
const variants = promptWords.map(termVariants)
|
||||
const hasTerm = (terms: ReadonlySet<string>, i: number): boolean => variants[i].some(v => terms.has(v))
|
||||
const weights = promptWords.map((_word, i) => {
|
||||
let frequency = 0
|
||||
for (const entry of entries) if (hasTerm(entry.terms, i)) frequency++
|
||||
return Math.log1p((entries.length - frequency + 0.5) / (frequency + 0.5))
|
||||
})
|
||||
const totalWeight = weights.reduce((sum, weight) => sum + weight, 0)
|
||||
if (totalWeight === 0) return null
|
||||
|
||||
const scored: Array<RankedEntry & { score: number }> = []
|
||||
for (const entry of entries) {
|
||||
const pageRank = typeof entry.pageRank === 'number' ? entry.pageRank : 0
|
||||
const score = ALPHA * jaccard(promptTrigrams, entry.tri) + (1 - ALPHA) * pageRank
|
||||
if (score >= MIN_THRESHOLD) scored.push({ ...entry, score })
|
||||
let matchedWeight = 0
|
||||
let matchedTerms = 0
|
||||
for (let i = 0; i < promptWords.length; i++) {
|
||||
if (weights[i] > 0 && hasTerm(entry.terms, i)) {
|
||||
matchedWeight += weights[i]
|
||||
matchedTerms++
|
||||
}
|
||||
}
|
||||
// A single common word in a long prompt is not evidence of relevance.
|
||||
if (matchedTerms < Math.min(2, promptWords.length)) continue
|
||||
const coverage = matchedWeight / totalWeight
|
||||
if (coverage >= MIN_COVERAGE) {
|
||||
const pageRank = Math.max(0, Math.min(1, Number(entry.pageRank) || 0))
|
||||
scored.push({ ...entry, score: 0.9 * coverage + 0.1 * pageRank })
|
||||
}
|
||||
}
|
||||
if (scored.length === 0) return null
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# Structural + security smoke for ruflo-mods v0.6.1 (ADR-404, ADR-447).
|
||||
# Structural + security smoke for ruflo-mods v0.6.2 (ADR-404, ADR-447).
|
||||
# Static only: CI has no Claude Code, so the hooks module's behaviour is held
|
||||
# by v3/@claude-flow/cli/__tests__/mods/*.test.ts and, where function hooks are
|
||||
# on, by `claude plugin test plugins/ruflo-mods`.
|
||||
@@ -12,9 +12,9 @@ ok() { printf "PASS\n"; PASS=$((PASS+1)); }
|
||||
bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }
|
||||
HOOKS="$ROOT/hooks"
|
||||
|
||||
step "1. plugin.json declares ruflo-mods 0.6.1"
|
||||
step "1. plugin.json declares ruflo-mods 0.6.2"
|
||||
grep -q '"name": "ruflo-mods"' "$ROOT/.claude-plugin/plugin.json" \
|
||||
&& grep -q '"version": "0.6.1"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
|
||||
&& grep -q '"version": "0.6.2"' "$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" \
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ruflo-rag-memory",
|
||||
"description": "RuVector memory with HNSW search, AgentDB, and semantic retrieval. As a mod (ADR-445): a write guard that keeps secrets out of memory, /rag-mod, and a status file the console shows",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"author": {
|
||||
"name": "ruvnet",
|
||||
"url": "https://github.com/ruvnet"
|
||||
|
||||
@@ -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.7 — 2026-10-14
|
||||
- fix: memory-search, the memory-specialist agent, `/recall` and `/ruflo-memory` no longer tell the model to run `ruvector search --hybrid` / `--graph-rag` (the ruvector CLI takes a database path and a `--vector` JSON array, not a text query); they use `memory search --type hybrid` and `--smart`, say plainly that this plugin has no text-query Graph RAG, and single-quote the query as untrusted shell input (#4153, thanks @rudycelekli for the PR and @ronmikailov for the report)
|
||||
|
||||
## 0.3.6 — 2026-10-12
|
||||
- fix: the shared text screen now catches `.env` and e-mailed credentials, no longer flags a model's token talk (`--max-tokens`, `/oauth/token`, "token usage"), and no longer flags values that only name where a secret lives (`./service-account.json`, `--set-secrets=NAME=NAME:latest`); every rule stays linear (#4094, thanks @proffesor-for-testing)
|
||||
|
||||
|
||||
@@ -177,13 +177,9 @@ Measured numbers from [`docs/reviews/intelligence-system-audit-2026-05-29.md`](.
|
||||
|
||||
The previously published "150x–12,500x" figures were brute-force fallback artifacts and are not reproduced under the audit harness.
|
||||
|
||||
## Integration with ruvector
|
||||
## Supported memory search
|
||||
|
||||
When `ruflo-ruvector` is also loaded, rag-memory delegates to ruvector's backend for advanced features:
|
||||
- FlashAttention-3 for O(N) memory attention
|
||||
- Graph RAG for multi-hop knowledge retrieval
|
||||
- Hybrid search (sparse + dense) with RRF fusion
|
||||
- DiskANN for large-scale persistent indexes
|
||||
The supported text-query interface for this plugin is Ruflo `memory search` or the registered `memory_search` MCP tool. `memory search --type hybrid` unions keyword and semantic hits; `--smart` requests query expansion, RRF across variants, recency weighting, and MMR when the installed memory package supports it. The `ruvector search` CLI requires a database and query vector and does not accept a text query with `--hybrid` or `--graph-rag`. Installing `ruflo-ruvector` alone does not turn these into memory-search commands.
|
||||
|
||||
## Compatibility
|
||||
|
||||
|
||||
@@ -1,65 +1,41 @@
|
||||
---
|
||||
name: memory-specialist
|
||||
description: SOTA RAG memory specialist — hybrid search (sparse+dense), Graph RAG multi-hop retrieval, MMR diversity reranking, smart consolidation, ruvector integration
|
||||
description: Ruflo memory specialist — semantic and keyword retrieval, optional SmartRetrieval ranking, and memory maintenance
|
||||
model: sonnet
|
||||
---
|
||||
You are a memory specialist agent implementing state-of-the-art Retrieval-Augmented Generation patterns. Your responsibilities:
|
||||
You are a memory specialist agent using Ruflo's registered CLI and MCP search surfaces. Your responsibilities:
|
||||
|
||||
1. **Hybrid search** (sparse + dense) with Reciprocal Rank Fusion for 20-49% better retrieval
|
||||
2. **Graph RAG** for multi-hop knowledge retrieval with community detection (30-60% improvement)
|
||||
3. **Smart retrieval** with MMR diversity reranking and recency scoring
|
||||
4. **Memory consolidation** — deduplicate, merge, prune stale entries across namespaces
|
||||
5. **Claude Code bridge** — import auto-memory into AgentDB with ONNX vector embeddings
|
||||
6. **Adaptive chunking** — split documents at semantic boundaries, not fixed token counts
|
||||
1. **Hybrid search** via the CLI's keyword + semantic result union (`--type hybrid`)
|
||||
2. **Smart retrieval** with optional query expansion, RRF across variants, MMR, and recency weighting; report a plain-search fallback if the installed memory package lacks `smartSearch`
|
||||
3. **Memory consolidation** — deduplicate, merge, prune stale entries across namespaces
|
||||
4. **Claude Code bridge** — import auto-memory into AgentDB with ONNX vector embeddings
|
||||
5. **Adaptive chunking** — split documents at semantic boundaries, not fixed token counts
|
||||
|
||||
### Search Strategy Selection
|
||||
|
||||
| Query Type | Strategy | Why |
|
||||
|-----------|----------|-----|
|
||||
| Factual lookup | Dense search (HNSW) | Fast, single-hop, exact semantic match |
|
||||
| Multi-hop reasoning | Graph RAG | Follows entity relationships across documents |
|
||||
| Keyword + semantic | Hybrid (sparse + dense + RRF) | Combines BM25 precision with embedding recall |
|
||||
| Diverse results needed | Dense + MMR reranking | Removes near-duplicates, maximizes coverage |
|
||||
| Recent context | Dense + recency weighting | Prioritizes temporally relevant entries |
|
||||
| Exploratory | Graph RAG + community detection | Discovers clusters and latent connections |
|
||||
| Factual lookup | Semantic search | Single-query similarity retrieval |
|
||||
| Keyword + semantic | `memory search --type hybrid` | Unions keyword and semantic hits, then deduplicates |
|
||||
| Diverse results needed | `memory search --smart` | Requests MMR ranking when available |
|
||||
| Recent context | `memory search --smart` | Requests recency weighting when available |
|
||||
| Exploratory | `memory_search_unified` | Searches across available namespaces |
|
||||
|
||||
### Retrieval Pipeline (SOTA)
|
||||
|
||||
```
|
||||
Query → [Embedding (ONNX 384d)] → [HNSW ANN search]
|
||||
↓
|
||||
[Optional: BM25 sparse search]
|
||||
↓
|
||||
[RRF Fusion (k=60)]
|
||||
↓
|
||||
[MMR Reranking (λ=0.7)]
|
||||
↓
|
||||
[Recency Boost (decay=0.95/day)]
|
||||
↓
|
||||
Top-K Results
|
||||
```
|
||||
|
||||
### Retrieval via ruvector (when available)
|
||||
|
||||
```bash
|
||||
# Hybrid search (sparse + dense)
|
||||
npx ruvector search "query" --hybrid --limit 10
|
||||
|
||||
# Graph RAG (multi-hop)
|
||||
npx ruvector search "query" --graph-rag --limit 10
|
||||
|
||||
# Brain knowledge search
|
||||
npx ruvector brain search "query"
|
||||
|
||||
# RAG context retrieval (MCP)
|
||||
# hooks_rag_context({ query: "topic", limit: 5 })
|
||||
```
|
||||
The `ruvector search` CLI takes a database path and vector JSON, not a natural-language query or `--hybrid` / `--graph-rag` flags. Do not use it as the memory-search interface. This plugin has no supported text-query Graph RAG path; when a user asks for graph traversal, state that limitation and offer clearly labeled SmartRetrieval instead.
|
||||
|
||||
### Retrieval via claude-flow CLI
|
||||
|
||||
Treat user-provided query text as untrusted shell input: use POSIX single-quote escaping and reject newlines. Omit `--namespace` to search all available namespaces.
|
||||
|
||||
```bash
|
||||
# Dense semantic search
|
||||
npx @claude-flow/cli@latest memory search --query "QUERY" --namespace NAMESPACE --limit 10
|
||||
npx @claude-flow/cli@latest memory search --query 'QUERY' --limit 10
|
||||
|
||||
# Keyword + semantic union
|
||||
npx @claude-flow/cli@latest memory search --query 'QUERY' --type hybrid --limit 10
|
||||
|
||||
# Optional SmartRetrieval (inspect fallback note)
|
||||
npx @claude-flow/cli@latest memory search --query 'QUERY' --smart --limit 10
|
||||
|
||||
# Store with metadata
|
||||
npx @claude-flow/cli@latest memory store --key "KEY" --value "VALUE" --namespace NAMESPACE
|
||||
|
||||
@@ -19,7 +19,7 @@ npx @claude-flow/cli@latest memory search --query 'QUERY' --type hybrid --limit
|
||||
```
|
||||
(`npx ruvector search` takes a database path and a `--vector` JSON array, not a text query.)
|
||||
|
||||
This searches across patterns, tasks, solutions, feedback, security, and claude-memories namespaces. Results are ranked by composite score: cosine similarity * MMR diversity * recency decay.
|
||||
Omitting `--namespace` searches available namespaces. Check the result for a SmartRetrieval fallback note before saying MMR or recency ranking was applied; the returned score is not a probability of truth.
|
||||
|
||||
If no arguments provided, show recent memory entries:
|
||||
```bash
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: ruflo-memory
|
||||
description: SOTA memory CRUD — store, search (hybrid/graph-rag/dense), retrieve, list, consolidate
|
||||
description: Memory CRUD — store, semantic/keyword search, retrieve, list, consolidate
|
||||
---
|
||||
$ARGUMENTS
|
||||
|
||||
@@ -11,10 +11,12 @@ Parse $ARGUMENTS to determine the operation:
|
||||
**store** `--key KEY --value VALUE [--namespace NS]`:
|
||||
`npx @claude-flow/cli@latest memory store --key "KEY" --value "VALUE" --namespace NAMESPACE`
|
||||
|
||||
**search** `--query QUERY [--namespace NS] [--limit N] [--hybrid] [--graph-rag]`:
|
||||
- Default (dense): `npx @claude-flow/cli@latest memory search --query "QUERY" --namespace NAMESPACE --limit 5`
|
||||
- Hybrid (sparse+dense): `npx ruvector search "QUERY" --hybrid --limit 5`
|
||||
- Graph RAG (multi-hop): `npx ruvector search "QUERY" --graph-rag --limit 5`
|
||||
**search** `--query QUERY [--namespace NS] [--limit N] [--hybrid] [--smart]`:
|
||||
- Default (semantic): `npx @claude-flow/cli@latest memory search --query 'QUERY' --limit 5`
|
||||
- Hybrid (keyword + semantic union): `npx @claude-flow/cli@latest memory search --query 'QUERY' --type hybrid --limit 5`
|
||||
- SmartRetrieval (when available): `npx @claude-flow/cli@latest memory search --query 'QUERY' --smart --limit 5`
|
||||
|
||||
If asked for `--graph-rag`, explain that this plugin has no supported text-query Graph RAG command; offer SmartRetrieval without claiming graph hops. Treat QUERY as untrusted shell input and use POSIX single-quote escaping, rejecting newlines.
|
||||
|
||||
**retrieve** `--key KEY [--namespace NS]`:
|
||||
`npx @claude-flow/cli@latest memory retrieve --key "KEY" --namespace NAMESPACE`
|
||||
@@ -33,6 +35,6 @@ Deduplicate entries with cosine > 0.92, prune stale (>30 days untouched, zero re
|
||||
Import Claude Code auto-memory into AgentDB.
|
||||
See `/memory-bridge` skill for details.
|
||||
|
||||
Default namespace is "default". Common namespaces: `patterns`, `tasks`, `solutions`, `feedback`, `security`, `claude-memories`.
|
||||
Writes default to the `default` namespace. Searches without `--namespace` cover available namespaces. Common namespaces: `patterns`, `tasks`, `solutions`, `feedback`, `security`, `claude-memories`.
|
||||
|
||||
If no arguments, run `memory list`.
|
||||
@@ -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.6 with new keywords"
|
||||
step "1. plugin.json declares 0.3.7 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.6" ]]; then bad "expected 0.3.6, got '$v'"; else
|
||||
if [[ "$v" != "0.3.7" ]]; then bad "expected 0.3.7, got '$v'"; else
|
||||
miss=""
|
||||
for k in mcp claude-memories bridged-memory; do
|
||||
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
|
||||
|
||||
@@ -51,9 +51,6 @@ The bridge runs automatically on `session-start` via the SessionStart hook. Manu
|
||||
- After bulk memory changes outside normal sessions
|
||||
- Forcing re-embedding after model updates
|
||||
|
||||
## Integration with ruvector
|
||||
## Search compatibility
|
||||
|
||||
When `ruflo-ruvector` is loaded, bridged memories are also indexed by ruvector for:
|
||||
- Hybrid search (sparse + dense with RRF)
|
||||
- Graph RAG multi-hop queries across memory entries
|
||||
- Brain knowledge sharing across sessions
|
||||
Use `memory_search_unified` to query bridged memories. This bridge does not expose a text-query Graph RAG command or the `ruvector search --hybrid` CLI flags; additional ruvector integrations require separate configuration and verification.
|
||||
@@ -1,67 +1,61 @@
|
||||
---
|
||||
name: memory-search
|
||||
description: SOTA semantic search — hybrid (sparse+dense), Graph RAG multi-hop, MMR diversity reranking, recency weighting
|
||||
description: Search Ruflo memory with semantic retrieval, keyword/semantic union, or optional SmartRetrieval reranking
|
||||
allowed-tools: Bash Read mcp__plugin_ruflo-core_ruflo__memory_search mcp__plugin_ruflo-core_ruflo__memory_store mcp__plugin_ruflo-core_ruflo__memory_list mcp__plugin_ruflo-core_ruflo__memory_retrieve mcp__plugin_ruflo-core_ruflo__memory_search_unified mcp__plugin_ruflo-core_ruflo__agentdb_pattern-search mcp__plugin_ruflo-core_ruflo__agentdb_context-synthesize
|
||||
argument-hint: "<query> [--hybrid] [--graph-rag] [--namespace NAME]"
|
||||
argument-hint: "<query> [--hybrid] [--smart] [--namespace NAME]"
|
||||
---
|
||||
|
||||
# Memory Search (SOTA)
|
||||
# Memory Search
|
||||
|
||||
State-of-the-art semantic search across Ruflo memory with multiple retrieval strategies.
|
||||
Search Ruflo's stored memories. Select a strategy supported by the Ruflo CLI or MCP tool, and report which one actually ran.
|
||||
|
||||
## Strategy Selection
|
||||
## Strategy selection
|
||||
|
||||
Choose based on query type:
|
||||
- **Default** (dense): fast single-hop semantic match
|
||||
- **--hybrid**: sparse + dense with RRF fusion (20-49% better for keyword+semantic queries)
|
||||
- **--graph-rag**: multi-hop knowledge retrieval (30-60% better for reasoning queries)
|
||||
- **Default:** semantic retrieval through `memory search` or MCP `memory_search`.
|
||||
- **`--hybrid`:** CLI keyword + semantic result union, deduplicated and sorted by score. This is not the `ruvector search` CLI and does not claim Graph RAG or sparse/dense RRF.
|
||||
- **`--smart`:** request query expansion, RRF across variants, recency weighting, and MMR diversity. The MCP tool can fall back to plain search if the installed memory package lacks `smartSearch`; inspect the returned fallback note before claiming SmartRetrieval ran.
|
||||
- **Cross-namespace:** MCP `memory_search_unified` merges and deduplicates results from multiple namespaces.
|
||||
|
||||
If the user requests `--graph-rag`, explain that this plugin has no supported text-query Graph RAG command. Offer `--smart` semantic retrieval as a clearly labeled fallback; do not claim graph traversal.
|
||||
|
||||
## Steps
|
||||
|
||||
1. **Parse query and flags** — extract search text and strategy flags from arguments
|
||||
2. **Select retrieval strategy**:
|
||||
1. Parse the query, optional namespace, result limit, and strategy flags. Omit `--namespace` to search all namespaces.
|
||||
For CLI commands, treat the query as untrusted shell input: use POSIX single-quote escaping for embedded apostrophes and reject embedded newlines. Do not interpolate it inside double quotes.
|
||||
2. Run one of the supported paths:
|
||||
|
||||
**Dense search (default)**:
|
||||
**Semantic (default)**
|
||||
```bash
|
||||
npx @claude-flow/cli@latest memory search --query "QUERY" --namespace NAMESPACE --limit 10
|
||||
npx @claude-flow/cli@latest memory search --query 'QUERY' --limit 10
|
||||
```
|
||||
Or via MCP: `mcp__plugin_ruflo-core_ruflo__memory_search({ query: "QUERY", namespace: "NAMESPACE", limit: 10 })`
|
||||
MCP: `mcp__plugin_ruflo-core_ruflo__memory_search({ query: "QUERY", limit: 10 })`
|
||||
|
||||
**Hybrid search** (when --hybrid or query has specific keywords):
|
||||
**Keyword + semantic union (`--hybrid`)**
|
||||
```bash
|
||||
npx ruvector search "QUERY" --hybrid --limit 10
|
||||
npx @claude-flow/cli@latest memory search --query 'QUERY' --type hybrid --limit 10
|
||||
```
|
||||
Add `--namespace NAMESPACE` only when the user requests one.
|
||||
|
||||
**Graph RAG** (when --graph-rag or multi-hop reasoning needed):
|
||||
**Smart retrieval (`--smart`)**
|
||||
```bash
|
||||
npx ruvector search "QUERY" --graph-rag --limit 10
|
||||
npx @claude-flow/cli@latest memory search --query 'QUERY' --smart --limit 10
|
||||
```
|
||||
MCP: `mcp__plugin_ruflo-core_ruflo__memory_search({ query: "QUERY", smart: true, limit: 10 })`
|
||||
|
||||
**Smart retrieval** (when --smart or complex recall needed):
|
||||
```bash
|
||||
npx @claude-flow/cli@latest memory search --query "QUERY" --smart --limit 10
|
||||
```
|
||||
Or via MCP: `mcp__plugin_ruflo-core_ruflo__memory_search({ query: "QUERY", smart: true, limit: 10 })`
|
||||
|
||||
Applies 5-phase pipeline: query expansion, RRF fusion, recency boost, MMR diversity, session round-robin.
|
||||
Best for: multi-session recall, temporal queries, diverse result sets.
|
||||
|
||||
**Unified cross-namespace**:
|
||||
**Cross-namespace bridge search**
|
||||
`mcp__plugin_ruflo-core_ruflo__memory_search_unified({ query: "QUERY", limit: 10 })`
|
||||
|
||||
3. **Apply MMR reranking** — for diverse results, filter near-duplicates (cosine > 0.92) while maximizing relevance
|
||||
4. **Apply recency weighting** — boost recent entries with exponential decay (0.95/day)
|
||||
5. **Synthesize context** (for complex queries):
|
||||
`mcp__plugin_ruflo-core_ruflo__agentdb_context-synthesize({ query: "QUERY", sources: ["patterns", "tasks", "solutions"] })`
|
||||
6. **Present results** — ranked by composite score (relevance * diversity * recency), with source namespace attribution
|
||||
3. For a complex query, optionally request AgentDB context synthesis with its registered schema:
|
||||
`mcp__plugin_ruflo-core_ruflo__agentdb_context-synthesize({ query: "QUERY", maxEntries: 10 })`
|
||||
4. Present the returned entries with namespace attribution. Distinguish raw `similarity` from SmartRetrieval's `rankingScore`; neither is a probability of truth. State when SmartRetrieval fell back to plain search.
|
||||
|
||||
## Namespace Guide
|
||||
## Namespace guide
|
||||
|
||||
| Namespace | Best For |
|
||||
|-----------|----------|
|
||||
| `patterns` | "How did we handle X?" |
|
||||
| `tasks` | "What was the context for Y?" |
|
||||
| `solutions` | "How did we fix Z?" |
|
||||
| `feedback` | "What did the user prefer?" |
|
||||
| `security` | "Known vulnerabilities in..." |
|
||||
| (omit) | Search all namespaces |
|
||||
| Namespace | Typical content |
|
||||
|-----------|-----------------|
|
||||
| `patterns` | Reusable approaches |
|
||||
| `tasks` | Task context |
|
||||
| `solutions` | Resolved problems |
|
||||
| `feedback` | User corrections |
|
||||
| `security` | Security notes |
|
||||
| (omit) | All available namespaces |
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ruflo-ruvector",
|
||||
"description": "Self-learning vector database via npx ruvector@0.2.25 — HNSW, adaptive LoRA embeddings, code-graph clustering, hooks routing, brain/SONA, 103 MCP tools. As a mod (ADR-445): a write guard that keeps secrets out of the vector store and shared brain, /ruvector-mod, and a status file the console shows",
|
||||
"version": "0.3.5",
|
||||
"description": "Self-learning vector database via npx ruvector@0.3.3 — HNSW, adaptive LoRA embeddings, code-graph clustering, hooks routing, brain/SONA, 103 MCP tools. As a mod (ADR-445): a write guard that keeps secrets out of the vector store and shared brain, /ruvector-mod, and a status file the console shows",
|
||||
"version": "0.3.7",
|
||||
"author": {
|
||||
"name": "ruvnet",
|
||||
"url": "https://github.com/ruvnet"
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
|
||||
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-ruvector`.
|
||||
|
||||
## 0.3.7 — 2026-10-14
|
||||
- fix: `vector-hyperbolic` no longer claims a normalised text embedding encodes depth (every unit-norm vector lands at the same radius); it now says to set radius from depth and measure on your own tree (#4159, thanks @ronmikailov)
|
||||
|
||||
## 0.3.6 — 2026-10-14
|
||||
- fix: pin ruvector@0.3.3, which bundles the ONNX wasm that 0.2.25 lacks, so `embed text` works with no add-on; drop the `ruvector-onnx-embeddings-wasm` remedy that never fixed it, and refresh the limitation tables against 0.3.3 (`optimize`, `force-learn`, `midstream` now run; 97 MCP tools) (#4158)
|
||||
|
||||
## 0.3.5 — 2026-10-12
|
||||
- fix: the shared text screen now catches `.env` and e-mailed credentials, no longer flags a model's token talk (`--max-tokens`, `/oauth/token`, "token usage"), and no longer flags values that only name where a secret lives (`./service-account.json`, `--set-secrets=NAME=NAME:latest`); every rule stays linear (#4094, thanks @proffesor-for-testing)
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# ruflo-ruvector
|
||||
|
||||
Self-learning vector database powered by [`ruvector@0.2.25`](https://www.npmjs.com/package/ruvector) — HNSW, Adaptive LoRA embeddings, hooks-based intelligence, SONA self-optimizing patterns, brain (collective knowledge), and 91 MCP tools (verified via `ruvector mcp tools`).
|
||||
Self-learning vector database powered by [`ruvector@0.3.3`](https://www.npmjs.com/package/ruvector) — HNSW, Adaptive LoRA embeddings, hooks-based intelligence, SONA self-optimizing patterns, brain (collective knowledge), and 97 MCP tools (verified via `ruvector mcp tools`).
|
||||
|
||||
> **Pinned version:** this plugin targets `ruvector@0.2.25`. Earlier 0.1.x versions are missing several commands (`brain`, `route`, `sona`); some legacy docs referenced 2.x features that do not exist on npm. Always invoke with the pin.
|
||||
> **Pinned version:** this plugin targets `ruvector@0.3.3`. Earlier 0.1.x versions are missing several commands (`brain`, `route`, `sona`); some legacy docs referenced 2.x features that do not exist on npm. Always invoke with the pin.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -12,17 +12,16 @@ Wraps the `ruvector` npm package as a Ruflo plugin, providing vector embedding,
|
||||
|
||||
```bash
|
||||
# Required
|
||||
npm install ruvector@0.2.25
|
||||
npm install ruvector@0.3.3
|
||||
|
||||
# Optional add-ons (install as needed)
|
||||
npm install ruvector-onnx-embeddings-wasm # required for `embed text` to work
|
||||
npm install @ruvector/pi-brain # required for `brain` subcommands
|
||||
npm install @ruvector/ruvllm # required for `sona` subcommands (JS fallback)
|
||||
```
|
||||
|
||||
Run a health check:
|
||||
```bash
|
||||
npx -y ruvector@0.2.25 doctor
|
||||
npx -y ruvector@0.3.3 doctor
|
||||
```
|
||||
|
||||
## Installation
|
||||
@@ -35,7 +34,7 @@ claude --plugin-dir plugins/ruflo-ruvector
|
||||
|
||||
Register with the pinned version:
|
||||
```bash
|
||||
claude mcp add ruvector -- npx -y ruvector@0.2.25 mcp start
|
||||
claude mcp add ruvector -- npx -y ruvector@0.3.3 mcp start
|
||||
```
|
||||
|
||||
Key tool categories: hooks routing, AST analysis, diff classification, coverage routing, graph clustering, security scanning, RAG context, brain knowledge, SONA learning.
|
||||
@@ -50,7 +49,7 @@ Key tool categories: hooks routing, AST analysis, diff classification, coverage
|
||||
|
||||
| Skill | Usage | Description |
|
||||
|-------|-------|-------------|
|
||||
| `vector-setup` | `/vector-setup [--full]` | First-run installer: pins `ruvector@0.2.25`, adds ONNX/Brain/SONA/router add-ons, registers MCP, runs `doctor` |
|
||||
| `vector-setup` | `/vector-setup [--full]` | First-run installer: pins `ruvector@0.3.3`, adds ONNX/Brain/SONA/router add-ons, registers MCP, runs `doctor` |
|
||||
| `vector-embed` | `/vector-embed <text>` | ONNX embeddings (384-dim) via `embed text` |
|
||||
| `vector-cluster` | `/vector-cluster <files...>` | Spectral/Louvain code-graph clustering via `hooks graph-cluster` |
|
||||
| `vector-hyperbolic` | `/vector-hyperbolic <text>` | Standard ONNX embed + Poincare projection in user code |
|
||||
@@ -121,34 +120,34 @@ The full surface is documented in `commands/vector.md` (80+ subcommands). Quick
|
||||
/vector-setup
|
||||
|
||||
# 1. Create a database
|
||||
npx -y ruvector@0.2.25 create project.db -d 384 -m cosine
|
||||
npx -y ruvector@0.3.3 create project.db -d 384 -m cosine
|
||||
|
||||
# 2. Embed every TypeScript source file (loop — no built-in --batch)
|
||||
mkdir -p .vec
|
||||
for f in $(find src -name '*.ts'); do
|
||||
npx -y ruvector@0.2.25 embed text "$(cat "$f")" -o ".vec/${f//\//_}.json"
|
||||
npx -y ruvector@0.3.3 embed text "$(cat "$f")" -o ".vec/${f//\//_}.json"
|
||||
done
|
||||
|
||||
# 3. Insert all embeddings (assumes a JSON array of {id, vector, metadata})
|
||||
jq -s '[.[] | {id: input_filename, vector: .vector}]' .vec/*.json > corpus.json
|
||||
npx -y ruvector@0.2.25 insert project.db corpus.json
|
||||
npx -y ruvector@0.3.3 insert project.db corpus.json
|
||||
|
||||
# 4. Search by query embedding
|
||||
QV=$(npx -y ruvector@0.2.25 embed text "JWT refresh-token rotation" --output -)
|
||||
npx -y ruvector@0.2.25 search project.db -v "$QV" -k 5
|
||||
QV=$(npx -y ruvector@0.3.3 embed text "JWT refresh-token rotation" --output -)
|
||||
npx -y ruvector@0.3.3 search project.db -v "$QV" -k 5
|
||||
|
||||
# 5. Inspect index health
|
||||
npx -y ruvector@0.2.25 stats project.db
|
||||
npx -y ruvector@0.3.3 stats project.db
|
||||
```
|
||||
|
||||
For an alternative store format with lineage tracking, replace steps 1–3 with:
|
||||
```bash
|
||||
npx -y ruvector@0.2.25 rvf create project.rvf
|
||||
npx -y ruvector@0.2.25 rvf ingest project.rvf < corpus.json
|
||||
npx -y ruvector@0.2.25 rvf query project.rvf
|
||||
npx -y ruvector@0.3.3 rvf create project.rvf
|
||||
npx -y ruvector@0.3.3 rvf ingest project.rvf < corpus.json
|
||||
npx -y ruvector@0.3.3 rvf query project.rvf
|
||||
```
|
||||
|
||||
## Capabilities (ruvector@0.2.25, verified)
|
||||
## Capabilities (ruvector@0.3.3, verified)
|
||||
|
||||
| Feature | CLI | Notes |
|
||||
|---------|-----|-------|
|
||||
@@ -172,34 +171,32 @@ npx -y ruvector@0.2.25 rvf query project.rvf
|
||||
| Identity (pi key) | `identity generate|show|export|import` | for brain + edge |
|
||||
| Edge compute | `edge status|balance|tasks|join` | distributed, rUv currency |
|
||||
|
||||
### Known limitations / bugs in 0.2.25
|
||||
### Known limitations / bugs in 0.3.3
|
||||
|
||||
| Issue | Detail | Workaround |
|
||||
|-------|--------|-----------|
|
||||
| ONNX runtime missing | `embed text` → `ONNX WASM files not bundled` | `npm i ruvector-onnx-embeddings-wasm` (see `/vector-setup`) |
|
||||
| `optimize` | Self-reports "not yet shipped in this release" | none — track upstream issue 401 |
|
||||
| `hooks force-learn` | TypeError `intel.tick is not a function` | run a real trajectory via `trajectory-begin/step/end` |
|
||||
| `hooks force-learn` | Runs, but reports `skipped: no trajectories to process` until a trajectory exists | record one via `trajectory-begin/step/end` first |
|
||||
| `hooks graph-mincut` | `Cannot read properties of undefined (reading 'length')` | use `hooks graph-cluster` |
|
||||
| `hooks git-churn` | Fails outside a git repo | run from inside the repo |
|
||||
| `benchmark` | Some installs fail with `Missing field 'dimensions'` | use `attention benchmark` or `gnn search` benchmarking |
|
||||
| `cluster` (top-level) | `Status: Coming Soon` | use `hooks graph-cluster` |
|
||||
| `compare`, top-level `index`, `midstream`, `embed --file/--batch/--glob/--model poincare` | Don't exist | see `commands/vector.md` for replacements |
|
||||
| `compare`, top-level `index`, `embed --batch/--glob/--model poincare` | Don't exist (`embed text` takes `--input-file` and `--stdin`) | see `commands/vector.md` for replacements |
|
||||
|
||||
## Self-Learning Hooks
|
||||
|
||||
```bash
|
||||
# Full pretrain pipeline + agent generation
|
||||
npx -y ruvector@0.2.25 hooks init --pretrain --build-agents quality
|
||||
npx -y ruvector@0.3.3 hooks init --pretrain --build-agents quality
|
||||
|
||||
# Smart agent routing (positional task!)
|
||||
npx -y ruvector@0.2.25 hooks route "implement OAuth flow"
|
||||
npx -y ruvector@0.2.25 hooks route-enhanced "fix CVE-2025-1234"
|
||||
npx -y ruvector@0.3.3 hooks route "implement OAuth flow"
|
||||
npx -y ruvector@0.3.3 hooks route-enhanced "fix CVE-2025-1234"
|
||||
|
||||
# Code analysis (positional file!)
|
||||
npx -y ruvector@0.2.25 hooks ast-analyze src/module.ts
|
||||
npx -y ruvector@0.2.25 hooks diff-analyze HEAD
|
||||
npx -y ruvector@0.2.25 hooks coverage-route src/module.ts
|
||||
npx -y ruvector@0.2.25 hooks security-scan src/
|
||||
npx -y ruvector@0.3.3 hooks ast-analyze src/module.ts
|
||||
npx -y ruvector@0.3.3 hooks diff-analyze HEAD
|
||||
npx -y ruvector@0.3.3 hooks coverage-route src/module.ts
|
||||
npx -y ruvector@0.3.3 hooks security-scan src/
|
||||
```
|
||||
|
||||
## Brain (Collective Knowledge)
|
||||
@@ -207,18 +204,18 @@ npx -y ruvector@0.2.25 hooks security-scan src/
|
||||
```bash
|
||||
npm install @ruvector/pi-brain # required dependency
|
||||
|
||||
npx -y ruvector@0.2.25 brain status
|
||||
npx -y ruvector@0.2.25 brain search "authentication patterns"
|
||||
npx -y ruvector@0.2.25 brain list
|
||||
npx -y ruvector@0.2.25 brain drift code # knowledge drift for a domain
|
||||
npx -y ruvector@0.3.3 brain status
|
||||
npx -y ruvector@0.3.3 brain search "authentication patterns"
|
||||
npx -y ruvector@0.3.3 brain list
|
||||
npx -y ruvector@0.3.3 brain drift code # knowledge drift for a domain
|
||||
```
|
||||
|
||||
## SONA (Self-Optimizing Neural Architecture)
|
||||
|
||||
```bash
|
||||
npx -y ruvector@0.2.25 sona status
|
||||
npx -y ruvector@0.2.25 sona patterns "auth refactor"
|
||||
npx -y ruvector@0.2.25 sona stats
|
||||
npx -y ruvector@0.3.3 sona status
|
||||
npx -y ruvector@0.3.3 sona patterns "auth refactor"
|
||||
npx -y ruvector@0.3.3 sona stats
|
||||
```
|
||||
|
||||
## Performance
|
||||
@@ -232,16 +229,16 @@ npx -y ruvector@0.2.25 sona stats
|
||||
|
||||
## Known Caveats
|
||||
|
||||
- **ONNX runtime not bundled by default** — `embed text` will report `ONNX WASM files not bundled` until you install `ruvector-onnx-embeddings-wasm`.
|
||||
- **No `--file`, `--batch`, `--glob`, `--namespace`, `--k`, `--task`, `--model poincare` flags** — these were in older docs but never shipped in 0.2.25. See `agents/vector-engineer.md` for the replacement table.
|
||||
- **ONNX runtime is bundled from 0.3.3** — `embed text` works with no add-on. Older ruvector (0.2.x) reports `ONNX WASM files not bundled`; this plugin pins 0.3.3 for that reason.
|
||||
- **No `--batch`, `--glob`, `--namespace`, `--k`, `--task`, `--model poincare` flags** (`embed text` does take `--input-file` and `--stdin`) — these were in older docs but are not in 0.3.3. See `agents/vector-engineer.md` for the replacement table.
|
||||
- **`brain` requires `@ruvector/pi-brain`** — install separately.
|
||||
- **`sona` requires `@ruvector/ruvllm`** — install separately (the native binding is not always present in the npm tarball).
|
||||
- **Top-level `cluster` is "Coming Soon"** — for actual clustering use `hooks graph-cluster <files>`.
|
||||
- **`compare`, `midstream`, top-level `index` subcommands do not exist.**
|
||||
- **`compare` and top-level `index` subcommands do not exist.**
|
||||
|
||||
## Architecture Decisions
|
||||
|
||||
- [`ADR-0001` — Pin ruflo-ruvector to ruvector@0.2.25 with optional add-ons](./docs/adrs/0001-pin-ruvector-0.2.25.md)
|
||||
- [`ADR-0001` — Pin ruflo-ruvector to ruvector@0.3.3 with optional add-ons](./docs/adrs/0001-pin-ruvector-0.3.3.md)
|
||||
|
||||
## Smoke test
|
||||
|
||||
|
||||
@@ -1,53 +1,53 @@
|
||||
---
|
||||
name: vector-engineer
|
||||
description: Vector operations specialist using npx ruvector@0.2.25 — HNSW indexing, adaptive LoRA embeddings, code-graph clustering, hooks routing, brain/SONA, 91 MCP tools. Use when the task involves generating/storing embeddings, semantic vector search, RVF cognitive containers, GNN clustering, or hyperbolic (Poincare) hierarchical embeddings.
|
||||
description: Vector operations specialist using npx ruvector@0.3.3 — HNSW indexing, adaptive LoRA embeddings, code-graph clustering, hooks routing, brain/SONA, 97 MCP tools. Use when the task involves generating/storing embeddings, semantic vector search, RVF cognitive containers, GNN clustering, or hyperbolic (Poincare) hierarchical embeddings.
|
||||
model: sonnet
|
||||
---
|
||||
|
||||
You are a vector engineer that orchestrates the `ruvector` npm package for embedding, indexing, search, clustering, and self-learning intelligence.
|
||||
|
||||
### Core Tool: npx ruvector@0.2.25 (PINNED)
|
||||
### Core Tool: npx ruvector@0.3.3 (PINNED)
|
||||
|
||||
All vector operations go through the `ruvector` CLI, pinned to **0.2.25**. Install once, then always invoke with the version pin:
|
||||
All vector operations go through the `ruvector` CLI, pinned to **0.3.3**. Install once, then always invoke with the version pin:
|
||||
|
||||
```bash
|
||||
# Ensure pinned version installed
|
||||
npm ls ruvector 2>/dev/null | grep '0.2.25' || npm install ruvector@0.2.25
|
||||
npm ls ruvector 2>/dev/null | grep '0.3.3' || npm install ruvector@0.3.3
|
||||
|
||||
# MCP server (register once with pinned version)
|
||||
claude mcp add ruvector -- npx -y ruvector@0.2.25 mcp start
|
||||
claude mcp add ruvector -- npx -y ruvector@0.3.3 mcp start
|
||||
|
||||
# Hooks system (self-learning) — note: positional args, NOT --task / --file
|
||||
npx -y ruvector@0.2.25 hooks init --pretrain --build-agents quality
|
||||
npx -y ruvector@0.2.25 hooks route "description"
|
||||
npx -y ruvector@0.2.25 hooks route-enhanced "description"
|
||||
npx -y ruvector@0.2.25 hooks ast-analyze src/module.ts
|
||||
npx -y ruvector@0.2.25 hooks diff-analyze HEAD
|
||||
npx -y ruvector@0.2.25 hooks diff-classify HEAD
|
||||
npx -y ruvector@0.2.25 hooks coverage-route src/module.ts
|
||||
npx -y ruvector@0.2.25 hooks security-scan src/
|
||||
npx -y ruvector@0.3.3 hooks init --pretrain --build-agents quality
|
||||
npx -y ruvector@0.3.3 hooks route "description"
|
||||
npx -y ruvector@0.3.3 hooks route-enhanced "description"
|
||||
npx -y ruvector@0.3.3 hooks ast-analyze src/module.ts
|
||||
npx -y ruvector@0.3.3 hooks diff-analyze HEAD
|
||||
npx -y ruvector@0.3.3 hooks diff-classify HEAD
|
||||
npx -y ruvector@0.3.3 hooks coverage-route src/module.ts
|
||||
npx -y ruvector@0.3.3 hooks security-scan src/
|
||||
|
||||
# Brain (collective knowledge — requires @ruvector/pi-brain)
|
||||
npm install @ruvector/pi-brain
|
||||
npx -y ruvector@0.2.25 brain status
|
||||
npx -y ruvector@0.2.25 brain search "query"
|
||||
npx -y ruvector@0.2.25 brain list
|
||||
npx -y ruvector@0.3.3 brain status
|
||||
npx -y ruvector@0.3.3 brain search "query"
|
||||
npx -y ruvector@0.3.3 brain list
|
||||
|
||||
# SONA (Self-Optimizing Neural Architecture)
|
||||
npx -y ruvector@0.2.25 sona status
|
||||
npx -y ruvector@0.2.25 sona patterns "query"
|
||||
npx -y ruvector@0.2.25 sona stats
|
||||
npx -y ruvector@0.3.3 sona status
|
||||
npx -y ruvector@0.3.3 sona patterns "query"
|
||||
npx -y ruvector@0.3.3 sona stats
|
||||
|
||||
# System diagnostics
|
||||
npx -y ruvector@0.2.25 doctor
|
||||
npx -y ruvector@0.2.25 info
|
||||
npx -y ruvector@0.3.3 doctor
|
||||
npx -y ruvector@0.3.3 info
|
||||
```
|
||||
|
||||
### MCP Integration
|
||||
|
||||
ruvector@0.2.25 exposes 91 MCP tools (verified via `ruvector mcp tools`). Register the MCP server with the pinned version:
|
||||
ruvector@0.3.3 exposes 97 MCP tools (verified via `ruvector mcp tools`). Register the MCP server with the pinned version:
|
||||
```bash
|
||||
claude mcp add ruvector -- npx -y ruvector@0.2.25 mcp start
|
||||
claude mcp add ruvector -- npx -y ruvector@0.3.3 mcp start
|
||||
```
|
||||
|
||||
Verify after registration: `claude mcp list | grep ruvector`.
|
||||
@@ -66,10 +66,10 @@ Key tool categories:
|
||||
- `gnn_info`, `gnn_layer`, `gnn_search` — graph neural net ops
|
||||
- `rvf_create`, `rvf_query`, `rvf_status` — cognitive container management
|
||||
|
||||
### Attention Mechanisms (verified via `attention list` on 0.2.25)
|
||||
### Attention Mechanisms (verified via `attention list` on 0.3.3)
|
||||
|
||||
```bash
|
||||
npx -y ruvector@0.2.25 attention list
|
||||
npx -y ruvector@0.3.3 attention list
|
||||
```
|
||||
Reports the available mechanisms. Each is a real Rust binding; the CLI exposes `attention compute|benchmark|hyperbolic` to invoke them.
|
||||
|
||||
@@ -86,7 +86,7 @@ Reports the available mechanisms. Each is a real Rust binding; the CLI exposes `
|
||||
| `DualSpaceAttention` | O(n²) | `attention compute` |
|
||||
| `LocalGlobalAttention` | O(n*k) | `attention compute` |
|
||||
|
||||
> Earlier docs claimed ruvector exposed `Graph RAG`, `Hybrid Search`, `DiskANN`, `ColBERT`, `Matryoshka`, `MLA`, `TurboQuant` as standalone search modes. As of 0.2.25 the **CLI does not surface them as subcommands**. They are either Rust primitives reachable through the native API or planned upstream features. Use `hooks rag-context` for the closest CLI-level RAG capability.
|
||||
> Earlier docs claimed ruvector exposed `Graph RAG`, `Hybrid Search`, `DiskANN`, `ColBERT`, `Matryoshka`, `MLA`, `TurboQuant` as standalone search modes. As of 0.3.3 the **CLI does not surface them as subcommands**. They are either Rust primitives reachable through the native API or planned upstream features. Use `hooks rag-context` for the closest CLI-level RAG capability.
|
||||
|
||||
### HNSW Parameters Guide
|
||||
|
||||
@@ -100,33 +100,33 @@ Reports the available mechanisms. Each is a real Rust binding; the CLI exposes `
|
||||
|
||||
ruvector's 9-phase pretrain pipeline:
|
||||
```bash
|
||||
npx -y ruvector@0.2.25 hooks init --pretrain --build-agents quality
|
||||
npx -y ruvector@0.3.3 hooks init --pretrain --build-agents quality
|
||||
```
|
||||
Phases: AST analysis, diff embeddings, coverage routing, neural training, graph analysis, security scanning, co-edit pattern learning, agent building, RAG context indexing.
|
||||
|
||||
### Embedding Operations (ruvector@0.2.25)
|
||||
### Embedding Operations (ruvector@0.3.3)
|
||||
|
||||
```bash
|
||||
# Single text embedding (ONNX all-MiniLM-L6-v2, 384-dim)
|
||||
# NOTE: subcommand is `embed text`, text is positional. There is no `embed "TEXT"` form.
|
||||
npx -y ruvector@0.2.25 embed text "your text here"
|
||||
npx -y ruvector@0.2.25 embed text "your text" --adaptive --domain code -o vec.json
|
||||
npx -y ruvector@0.3.3 embed text "your text here"
|
||||
npx -y ruvector@0.3.3 embed text "your text" --adaptive --domain code -o vec.json
|
||||
|
||||
# Batch — no built-in glob; loop yourself:
|
||||
for f in src/**/*.ts; do
|
||||
npx -y ruvector@0.2.25 embed text "$(cat "$f")" -o "${f}.vec.json"
|
||||
npx -y ruvector@0.3.3 embed text "$(cat "$f")" -o "${f}.vec.json"
|
||||
done
|
||||
|
||||
# Similarity search — requires an existing database and a JSON-encoded query vector
|
||||
npx -y ruvector@0.2.25 create my.db -d 384 -m cosine
|
||||
npx -y ruvector@0.2.25 insert my.db vectors.json
|
||||
npx -y ruvector@0.2.25 search my.db -v '[0.1,0.2,...]' -k 10
|
||||
npx -y ruvector@0.3.3 create my.db -d 384 -m cosine
|
||||
npx -y ruvector@0.3.3 insert my.db vectors.json
|
||||
npx -y ruvector@0.3.3 search my.db -v '[0.1,0.2,...]' -k 10
|
||||
|
||||
# Compare two texts — no top-level `compare` subcommand exists in 0.2.25.
|
||||
# Compare two texts — no top-level `compare` subcommand exists in 0.3.3.
|
||||
# Embed both and compute cosine similarity in your own code or via MCP `hooks_rag_context`.
|
||||
```
|
||||
|
||||
### Removed / Renamed CLI Surface (was in older docs, NOT in 0.2.25)
|
||||
### Removed / Renamed CLI Surface (was in older docs, NOT in 0.3.3)
|
||||
|
||||
| Old form (broken) | Replacement |
|
||||
|-------------------|-------------|
|
||||
@@ -153,20 +153,20 @@ npx -y ruvector@0.2.25 search my.db -v '[0.1,0.2,...]' -k 10
|
||||
| Insert | - | 52,000+ vectors/sec |
|
||||
| Memory per vector | ~50 bytes | - |
|
||||
|
||||
### Clustering (code graph only in 0.2.25)
|
||||
### Clustering (code graph only in 0.3.3)
|
||||
|
||||
The top-level `cluster` subcommand is reserved for distributed cluster ops ("Coming Soon"). For actual community detection over a code graph use:
|
||||
```bash
|
||||
npx -y ruvector@0.2.25 hooks graph-cluster <files...> # spectral / Louvain
|
||||
npx -y ruvector@0.2.25 hooks graph-mincut <files...> # min-cut boundaries
|
||||
npx -y ruvector@0.3.3 hooks graph-cluster <files...> # spectral / Louvain
|
||||
npx -y ruvector@0.3.3 hooks graph-mincut <files...> # min-cut boundaries
|
||||
```
|
||||
For namespaced k-means / DBSCAN over arbitrary embeddings, run the algorithm in your own code against vectors stored in AgentDB.
|
||||
|
||||
### Hyperbolic Embeddings (Poincare Ball)
|
||||
|
||||
ruvector@0.2.25 has no `--model poincare` flag. For hierarchical data, embed normally and project to the Poincare ball in your own code:
|
||||
ruvector@0.3.3 has no `--model poincare` flag. For hierarchical data, embed normally and project to the Poincare ball in your own code:
|
||||
```bash
|
||||
npx -y ruvector@0.2.25 embed text "hierarchical concept" -o concept.vec.json
|
||||
npx -y ruvector@0.3.3 embed text "hierarchical concept" -o concept.vec.json
|
||||
# then normalize to live inside the unit ball: x_i / (||x|| * (1 + epsilon))
|
||||
```
|
||||
The experimental neural substrate (`embed neural --help`) may expose richer projections in future versions.
|
||||
|
||||
@@ -1,144 +1,144 @@
|
||||
---
|
||||
name: vector
|
||||
description: RuVector operations via npx ruvector@0.2.25 — embedding, search, RVF cognitive containers, GNN, attention, hooks, brain, sona, edge, identity
|
||||
description: RuVector operations via npx ruvector@0.3.3 — embedding, search, RVF cognitive containers, GNN, attention, hooks, brain, sona, edge, identity
|
||||
---
|
||||
|
||||
$ARGUMENTS
|
||||
Vector operations via the `ruvector` npm package (pinned to 0.2.25). Parse subcommand from $ARGUMENTS.
|
||||
Vector operations via the `ruvector` npm package (pinned to 0.3.3). Parse subcommand from $ARGUMENTS.
|
||||
|
||||
Pinned version: `ruvector@0.2.25` — every command below uses `npx -y ruvector@0.2.25 ...`.
|
||||
Pinned version: `ruvector@0.3.3` — every command below uses `npx -y ruvector@0.3.3 ...`.
|
||||
|
||||
Usage: /vector <subcommand> [options]
|
||||
|
||||
## Embedding
|
||||
|
||||
1. **embed `<text>`** — `npx -y ruvector@0.2.25 embed text "TEXT"`
|
||||
1. **embed `<text>`** — `npx -y ruvector@0.3.3 embed text "TEXT"`
|
||||
384-dim ONNX vector. If `ONNX WASM files not bundled`, run `/vector setup`.
|
||||
2. **embed-adaptive `<text>`** — `npx -y ruvector@0.2.25 embed text "TEXT" --adaptive --domain code`
|
||||
2. **embed-adaptive `<text>`** — `npx -y ruvector@0.3.3 embed text "TEXT" --adaptive --domain code`
|
||||
LoRA-adapted embedding tuned to a domain.
|
||||
3. **embed-file `<path>`** — Read file, then `npx -y ruvector@0.2.25 embed text "$(cat <path>)" -o <path>.vec.json`
|
||||
4. **embed-benchmark** — `npx -y ruvector@0.2.25 embed benchmark` (compares base vs adaptive).
|
||||
3. **embed-file `<path>`** — Read file, then `npx -y ruvector@0.3.3 embed text "$(cat <path>)" -o <path>.vec.json`
|
||||
4. **embed-benchmark** — `npx -y ruvector@0.3.3 embed benchmark` (compares base vs adaptive).
|
||||
|
||||
## Database lifecycle
|
||||
|
||||
5. **db create `<path>`** — `npx -y ruvector@0.2.25 create <path> -d 384 -m cosine`
|
||||
6. **db stats `<path>`** — `npx -y ruvector@0.2.25 stats <path>`
|
||||
7. **insert `<database>` `<json-file>`** — `npx -y ruvector@0.2.25 insert <database> <json-file>`
|
||||
8. **search `<database>` `<vector-json>` [-k N]** — `npx -y ruvector@0.2.25 search <database> -v '[0.1,...]' -k N`
|
||||
9. **export `<database>` [-o file] [-f json|binary|parquet] [--compress]** — `npx -y ruvector@0.2.25 export <database> -o backup.json`
|
||||
10. **import `<file>` [-d database]** — `npx -y ruvector@0.2.25 import <file> -d <database> [--merge|--replace]`
|
||||
5. **db create `<path>`** — `npx -y ruvector@0.3.3 create <path> -d 384 -m cosine`
|
||||
6. **db stats `<path>`** — `npx -y ruvector@0.3.3 stats <path>`
|
||||
7. **insert `<database>` `<json-file>`** — `npx -y ruvector@0.3.3 insert <database> <json-file>`
|
||||
8. **search `<database>` `<vector-json>` [-k N]** — `npx -y ruvector@0.3.3 search <database> -v '[0.1,...]' -k N`
|
||||
9. **export `<database>` [-o file] [-f json|binary|parquet] [--compress]** — `npx -y ruvector@0.3.3 export <database> -o backup.json`
|
||||
10. **import `<file>` [-d database]** — `npx -y ruvector@0.3.3 import <file> -d <database> [--merge|--replace]`
|
||||
|
||||
## RVF (cognitive containers)
|
||||
|
||||
11. **rvf create `<path>`** — `npx -y ruvector@0.2.25 rvf create <path>`
|
||||
12. **rvf ingest `<path>`** — `npx -y ruvector@0.2.25 rvf ingest <path>`
|
||||
13. **rvf query `<path>`** — `npx -y ruvector@0.2.25 rvf query <path>` (nearest neighbors)
|
||||
14. **rvf status `<path>`** — `npx -y ruvector@0.2.25 rvf status <path>`
|
||||
15. **rvf segments `<path>`** — `npx -y ruvector@0.2.25 rvf segments <path>`
|
||||
16. **rvf derive `<parent>` `<child>`** — `npx -y ruvector@0.2.25 rvf derive <parent> <child>` (lineage tracking)
|
||||
17. **rvf compact `<path>`** — `npx -y ruvector@0.2.25 rvf compact <path>` (reclaim deleted space)
|
||||
18. **rvf examples** — `npx -y ruvector@0.2.25 rvf examples` (45 reference stores)
|
||||
19. **rvf download `<name>`** — `npx -y ruvector@0.2.25 rvf download <name>` (e.g. `agent_memory`, `swarm_knowledge`)
|
||||
11. **rvf create `<path>`** — `npx -y ruvector@0.3.3 rvf create <path>`
|
||||
12. **rvf ingest `<path>`** — `npx -y ruvector@0.3.3 rvf ingest <path>`
|
||||
13. **rvf query `<path>`** — `npx -y ruvector@0.3.3 rvf query <path>` (nearest neighbors)
|
||||
14. **rvf status `<path>`** — `npx -y ruvector@0.3.3 rvf status <path>`
|
||||
15. **rvf segments `<path>`** — `npx -y ruvector@0.3.3 rvf segments <path>`
|
||||
16. **rvf derive `<parent>` `<child>`** — `npx -y ruvector@0.3.3 rvf derive <parent> <child>` (lineage tracking)
|
||||
17. **rvf compact `<path>`** — `npx -y ruvector@0.3.3 rvf compact <path>` (reclaim deleted space)
|
||||
18. **rvf examples** — `npx -y ruvector@0.3.3 rvf examples` (45 reference stores)
|
||||
19. **rvf download `<name>`** — `npx -y ruvector@0.3.3 rvf download <name>` (e.g. `agent_memory`, `swarm_knowledge`)
|
||||
|
||||
## GNN (Graph Neural Networks)
|
||||
|
||||
20. **gnn info** — `npx -y ruvector@0.2.25 gnn info`
|
||||
21. **gnn layer** — `npx -y ruvector@0.2.25 gnn layer` (build/test a multi-head attention GNN layer)
|
||||
22. **gnn search** — `npx -y ruvector@0.2.25 gnn search` (differentiable soft-attention search)
|
||||
23. **gnn compress** — `npx -y ruvector@0.2.25 gnn compress` (5-level adaptive tensor compression)
|
||||
20. **gnn info** — `npx -y ruvector@0.3.3 gnn info`
|
||||
21. **gnn layer** — `npx -y ruvector@0.3.3 gnn layer` (build/test a multi-head attention GNN layer)
|
||||
22. **gnn search** — `npx -y ruvector@0.3.3 gnn search` (differentiable soft-attention search)
|
||||
23. **gnn compress** — `npx -y ruvector@0.3.3 gnn compress` (5-level adaptive tensor compression)
|
||||
|
||||
## Attention mechanisms
|
||||
|
||||
24. **attention list** — `npx -y ruvector@0.2.25 attention list`
|
||||
24. **attention list** — `npx -y ruvector@0.3.3 attention list`
|
||||
Lists ALL available mechanisms: DotProduct, MultiHead, Flash, Hyperbolic, Linear, MoE, GraphRoPe, EdgeFeatured, DualSpace, LocalGlobal.
|
||||
25. **attention compute** — `npx -y ruvector@0.2.25 attention compute`
|
||||
26. **attention benchmark** — `npx -y ruvector@0.2.25 attention benchmark`
|
||||
27. **attention hyperbolic** — `npx -y ruvector@0.2.25 attention hyperbolic` (Poincare-ball geometry ops; the real hyperbolic surface in 0.2.25)
|
||||
28. **attention info** — `npx -y ruvector@0.2.25 attention info`
|
||||
25. **attention compute** — `npx -y ruvector@0.3.3 attention compute`
|
||||
26. **attention benchmark** — `npx -y ruvector@0.3.3 attention benchmark`
|
||||
27. **attention hyperbolic** — `npx -y ruvector@0.3.3 attention hyperbolic` (Poincare-ball geometry ops; the real hyperbolic surface in 0.3.3)
|
||||
28. **attention info** — `npx -y ruvector@0.3.3 attention info`
|
||||
|
||||
## Code intelligence (hooks)
|
||||
|
||||
29. **hooks init** — `npx -y ruvector@0.2.25 hooks init --pretrain --build-agents quality`
|
||||
30. **hooks stats** — `npx -y ruvector@0.2.25 hooks stats` (Q-learning patterns, vector memories, trajectories)
|
||||
31. **hooks route `<task>`** — `npx -y ruvector@0.2.25 hooks route "DESCRIPTION"` (positional)
|
||||
32. **hooks route-enhanced `<task>`** — `npx -y ruvector@0.2.25 hooks route-enhanced "DESCRIPTION"`
|
||||
33. **hooks suggest-context** — `npx -y ruvector@0.2.25 hooks suggest-context`
|
||||
34. **hooks ast-analyze `<file>`** — `npx -y ruvector@0.2.25 hooks ast-analyze <file>` (positional)
|
||||
35. **hooks ast-complexity `<files...>`** — `npx -y ruvector@0.2.25 hooks ast-complexity <files...>`
|
||||
36. **hooks diff-analyze [commit]** — `npx -y ruvector@0.2.25 hooks diff-analyze HEAD`
|
||||
37. **hooks diff-classify [commit]** — `npx -y ruvector@0.2.25 hooks diff-classify HEAD`
|
||||
38. **hooks diff-similar** — `npx -y ruvector@0.2.25 hooks diff-similar`
|
||||
39. **hooks coverage-route `<file>`** — `npx -y ruvector@0.2.25 hooks coverage-route <file>`
|
||||
40. **hooks coverage-suggest `<files...>`** — `npx -y ruvector@0.2.25 hooks coverage-suggest <files...>`
|
||||
41. **hooks graph-cluster `<files...>`** — `npx -y ruvector@0.2.25 hooks graph-cluster <files...>` (spectral/Louvain)
|
||||
42. **hooks rag-context `<query>`** — `npx -y ruvector@0.2.25 hooks rag-context "QUERY"`
|
||||
43. **hooks security-scan `<files...>`** — `npx -y ruvector@0.2.25 hooks security-scan <files...>` (run `hooks init` first)
|
||||
44. **hooks remember `<content>`** — `npx -y ruvector@0.2.25 hooks remember "CONTENT"`
|
||||
45. **hooks recall `<query>`** — `npx -y ruvector@0.2.25 hooks recall "QUERY"`
|
||||
29. **hooks init** — `npx -y ruvector@0.3.3 hooks init --pretrain --build-agents quality`
|
||||
30. **hooks stats** — `npx -y ruvector@0.3.3 hooks stats` (Q-learning patterns, vector memories, trajectories)
|
||||
31. **hooks route `<task>`** — `npx -y ruvector@0.3.3 hooks route "DESCRIPTION"` (positional)
|
||||
32. **hooks route-enhanced `<task>`** — `npx -y ruvector@0.3.3 hooks route-enhanced "DESCRIPTION"`
|
||||
33. **hooks suggest-context** — `npx -y ruvector@0.3.3 hooks suggest-context`
|
||||
34. **hooks ast-analyze `<file>`** — `npx -y ruvector@0.3.3 hooks ast-analyze <file>` (positional)
|
||||
35. **hooks ast-complexity `<files...>`** — `npx -y ruvector@0.3.3 hooks ast-complexity <files...>`
|
||||
36. **hooks diff-analyze [commit]** — `npx -y ruvector@0.3.3 hooks diff-analyze HEAD`
|
||||
37. **hooks diff-classify [commit]** — `npx -y ruvector@0.3.3 hooks diff-classify HEAD`
|
||||
38. **hooks diff-similar** — `npx -y ruvector@0.3.3 hooks diff-similar`
|
||||
39. **hooks coverage-route `<file>`** — `npx -y ruvector@0.3.3 hooks coverage-route <file>`
|
||||
40. **hooks coverage-suggest `<files...>`** — `npx -y ruvector@0.3.3 hooks coverage-suggest <files...>`
|
||||
41. **hooks graph-cluster `<files...>`** — `npx -y ruvector@0.3.3 hooks graph-cluster <files...>` (spectral/Louvain)
|
||||
42. **hooks rag-context `<query>`** — `npx -y ruvector@0.3.3 hooks rag-context "QUERY"`
|
||||
43. **hooks security-scan `<files...>`** — `npx -y ruvector@0.3.3 hooks security-scan <files...>` (run `hooks init` first)
|
||||
44. **hooks remember `<content>`** — `npx -y ruvector@0.3.3 hooks remember "CONTENT"`
|
||||
45. **hooks recall `<query>`** — `npx -y ruvector@0.3.3 hooks recall "QUERY"`
|
||||
46. **hooks coedit-record / coedit-suggest** — record + retrieve files edited together.
|
||||
47. **hooks error-record / error-suggest** — learn error→fix pairs and retrieve.
|
||||
48. **hooks trajectory-begin / trajectory-step / trajectory-end** — record an execution trajectory.
|
||||
49. **hooks pre-edit / post-edit / pre-command / post-command / session-start / session-end** — Claude Code hook lifecycle.
|
||||
|
||||
> **Known bugs in 0.2.25 hooks:** `force-learn` raises `intel.tick is not a function`; `graph-mincut` raises `Cannot read properties of undefined`; `git-churn` fails outside a git repo. Avoid these or run inside a git repo with seeded intelligence state.
|
||||
> **Known bugs in 0.3.3 hooks:** `force-learn` reports `skipped: no trajectories to process` until one is recorded; `graph-mincut` raises `Cannot read properties of undefined`; `git-churn` fails outside a git repo. Avoid these or run inside a git repo with seeded intelligence state.
|
||||
|
||||
## Native + workers (background analysis)
|
||||
|
||||
50. **native list** — `npx -y ruvector@0.2.25 native list` (worker types: security, analysis, learning)
|
||||
51. **native run `<type>`** — `npx -y ruvector@0.2.25 native run security` (or analysis|learning)
|
||||
52. **native benchmark** — `npx -y ruvector@0.2.25 native benchmark`
|
||||
53. **native compare** — `npx -y ruvector@0.2.25 native compare`
|
||||
54. **workers triggers / presets / phases / dispatch / status / stats / cleanup / cancel / run / create / init-config** — all available via `npx -y ruvector@0.2.25 workers <subcmd>`. First invocation auto-installs `agentic-flow` (slow).
|
||||
50. **native list** — `npx -y ruvector@0.3.3 native list` (worker types: security, analysis, learning)
|
||||
51. **native run `<type>`** — `npx -y ruvector@0.3.3 native run security` (or analysis|learning)
|
||||
52. **native benchmark** — `npx -y ruvector@0.3.3 native benchmark`
|
||||
53. **native compare** — `npx -y ruvector@0.3.3 native compare`
|
||||
54. **workers triggers / presets / phases / dispatch / status / stats / cleanup / cancel / run / create / init-config** — all available via `npx -y ruvector@0.3.3 workers <subcmd>`. First invocation auto-installs `agentic-flow` (slow).
|
||||
|
||||
## Collective knowledge (brain) — needs `@ruvector/pi-brain`
|
||||
|
||||
55. **brain status** — `npx -y ruvector@0.2.25 brain status`
|
||||
56. **brain search `<query>`** — `npx -y ruvector@0.2.25 brain search "QUERY"`
|
||||
57. **brain share `<title>`** — `npx -y ruvector@0.2.25 brain share "TITLE"`
|
||||
55. **brain status** — `npx -y ruvector@0.3.3 brain status`
|
||||
56. **brain search `<query>`** — `npx -y ruvector@0.3.3 brain search "QUERY"`
|
||||
57. **brain share `<title>`** — `npx -y ruvector@0.3.3 brain share "TITLE"`
|
||||
58. **brain list / get / vote / delete / drift / partition / transfer / sync / page** — full Brainpedia + LoRA-weight management.
|
||||
|
||||
## SONA (Self-Optimizing Neural Architecture) — needs `@ruvector/ruvllm`
|
||||
|
||||
59. **sona status / info / stats** — `npx -y ruvector@0.2.25 sona status`
|
||||
60. **sona patterns `<query>`** — `npx -y ruvector@0.2.25 sona patterns "QUERY"`
|
||||
61. **sona train `<data>`** — `npx -y ruvector@0.2.25 sona train <data>` (record a training trajectory)
|
||||
62. **sona export** — `npx -y ruvector@0.2.25 sona export` (export learned weights)
|
||||
59. **sona status / info / stats** — `npx -y ruvector@0.3.3 sona status`
|
||||
60. **sona patterns `<query>`** — `npx -y ruvector@0.3.3 sona patterns "QUERY"`
|
||||
61. **sona train `<data>`** — `npx -y ruvector@0.3.3 sona train <data>` (record a training trajectory)
|
||||
62. **sona export** — `npx -y ruvector@0.3.3 sona export` (export learned weights)
|
||||
|
||||
## LLM orchestration — needs `@ruvector/ruvllm`
|
||||
|
||||
63. **llm models** — `npx -y ruvector@0.2.25 llm models`
|
||||
64. **llm embed `<text>`** — `npx -y ruvector@0.2.25 llm embed "TEXT"` (RuvLLM-backed embeddings)
|
||||
65. **llm benchmark** — `npx -y ruvector@0.2.25 llm benchmark`
|
||||
66. **llm info** — `npx -y ruvector@0.2.25 llm info`
|
||||
63. **llm models** — `npx -y ruvector@0.3.3 llm models`
|
||||
64. **llm embed `<text>`** — `npx -y ruvector@0.3.3 llm embed "TEXT"` (RuvLLM-backed embeddings)
|
||||
65. **llm benchmark** — `npx -y ruvector@0.3.3 llm benchmark`
|
||||
66. **llm info** — `npx -y ruvector@0.3.3 llm info`
|
||||
|
||||
## Identity (pi key for brain/edge/MCP)
|
||||
|
||||
67. **identity generate** — `npx -y ruvector@0.2.25 identity generate` (creates a 64-hex-char pi key)
|
||||
68. **identity show** — `npx -y ruvector@0.2.25 identity show`
|
||||
69. **identity export `-o file`** — `npx -y ruvector@0.2.25 identity export -o key.enc` (encrypted backup)
|
||||
70. **identity import `<file>`** — `npx -y ruvector@0.2.25 identity import <file>`
|
||||
67. **identity generate** — `npx -y ruvector@0.3.3 identity generate` (creates a 64-hex-char pi key)
|
||||
68. **identity show** — `npx -y ruvector@0.3.3 identity show`
|
||||
69. **identity export `-o file`** — `npx -y ruvector@0.3.3 identity export -o key.enc` (encrypted backup)
|
||||
70. **identity import `<file>`** — `npx -y ruvector@0.3.3 identity import <file>`
|
||||
|
||||
## Edge compute network
|
||||
|
||||
71. **edge status** — `npx -y ruvector@0.2.25 edge status`
|
||||
72. **edge balance [nodeId]** — `npx -y ruvector@0.2.25 edge balance` (rUv balance)
|
||||
73. **edge tasks** — `npx -y ruvector@0.2.25 edge tasks`
|
||||
74. **edge join** — `npx -y ruvector@0.2.25 edge join` (join the network as a node)
|
||||
75. **edge dashboard** — `npx -y ruvector@0.2.25 edge dashboard` (opens in browser)
|
||||
71. **edge status** — `npx -y ruvector@0.3.3 edge status`
|
||||
72. **edge balance [nodeId]** — `npx -y ruvector@0.3.3 edge balance` (rUv balance)
|
||||
73. **edge tasks** — `npx -y ruvector@0.3.3 edge tasks`
|
||||
74. **edge join** — `npx -y ruvector@0.3.3 edge join` (join the network as a node)
|
||||
75. **edge dashboard** — `npx -y ruvector@0.3.3 edge dashboard` (opens in browser)
|
||||
|
||||
## Server / Decompile / Demo
|
||||
|
||||
76. **server [-p 8080] [-g 50051] [-d data-dir]** — `npx -y ruvector@0.2.25 server -p 8080`
|
||||
77. **decompile `<target>` [-o dir] [-f modules|single|json]** — `npx -y ruvector@0.2.25 decompile <npm-pkg-or-file-or-url>`
|
||||
78. **demo --basic | --gnn | --graph** — `npx -y ruvector@0.2.25 demo --basic` (interactive tutorial)
|
||||
76. **server [-p 8080] [-g 50051] [-d data-dir]** — `npx -y ruvector@0.3.3 server -p 8080`
|
||||
77. **decompile `<target>` [-o dir] [-f modules|single|json]** — `npx -y ruvector@0.3.3 decompile <npm-pkg-or-file-or-url>`
|
||||
78. **demo --basic | --gnn | --graph** — `npx -y ruvector@0.3.3 demo --basic` (interactive tutorial)
|
||||
|
||||
## System
|
||||
|
||||
79. **doctor** — `npx -y ruvector@0.2.25 doctor` (Node, npm, bindings, Rust)
|
||||
80. **info** — `npx -y ruvector@0.2.25 info`
|
||||
81. **benchmark** — `npx -y ruvector@0.2.25 benchmark` (known issue: fails with `Missing field 'dimensions'` on some installs; use `gnn search` or `attention benchmark` as alternatives)
|
||||
82. **install [pkg|--all]** — `npx -y ruvector@0.2.25 install --all` (lists/installs optional add-ons)
|
||||
83. **setup** — `npx -y ruvector@0.2.25 setup` (Setup Guide)
|
||||
79. **doctor** — `npx -y ruvector@0.3.3 doctor` (Node, npm, bindings, Rust)
|
||||
80. **info** — `npx -y ruvector@0.3.3 info`
|
||||
81. **benchmark** — `npx -y ruvector@0.3.3 benchmark` (known issue: fails with `Missing field 'dimensions'` on some installs; use `gnn search` or `attention benchmark` as alternatives)
|
||||
82. **install [pkg|--all]** — `npx -y ruvector@0.3.3 install --all` (lists/installs optional add-ons)
|
||||
83. **setup** — `npx -y ruvector@0.3.3 setup` (Setup Guide)
|
||||
|
||||
## Setup helper
|
||||
|
||||
@@ -146,10 +146,10 @@ For first-run users hitting `ONNX WASM files not bundled`, `Brain commands requi
|
||||
|
||||
## MCP server (91 tools)
|
||||
|
||||
- Register once: `claude mcp add ruvector -- npx -y ruvector@0.2.25 mcp start`
|
||||
- Register once: `claude mcp add ruvector -- npx -y ruvector@0.3.3 mcp start`
|
||||
- Verify: `claude mcp list | grep ruvector`
|
||||
- Then call MCP tools directly (e.g. `hooks_route`, `hooks_ast_analyze`, `hooks_rag_context`, `brain_search`, `attention_list`).
|
||||
|
||||
## Not in 0.2.25 (do not invoke)
|
||||
## Not in 0.3.3 (do not invoke)
|
||||
|
||||
`compare`, top-level `index`, `midstream`, `embed --file`, `embed --batch --glob`, `cluster --namespace --k` (top-level `cluster` is "Coming Soon"), `embed --model poincare`, `optimize` (per its own message: "not yet shipped in this release"), `brain agi *` (use `brain status` directly).
|
||||
`compare`, top-level `index`, `embed --file`, `embed --batch --glob`, `cluster --namespace --k` (top-level `cluster` is "Coming Soon"), `embed --model poincare`, `brain agi *` (use `brain status` directly).
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: ADR-0001
|
||||
title: Pin ruflo-ruvector plugin to ruvector@0.2.25 with optional add-on packages
|
||||
title: Pin ruflo-ruvector plugin to ruvector@0.3.3 with optional add-on packages
|
||||
status: Accepted
|
||||
date: 2026-05-04
|
||||
authors:
|
||||
@@ -25,18 +25,18 @@ Concretely, this caused:
|
||||
- `npx ruvector midstream status` → command does not exist
|
||||
- `npx ruvector index create N` → command does not exist (use `create <path>`)
|
||||
|
||||
A live audit against `ruvector@0.2.25` confirmed which subcommands work, which require optional add-on packages, and which are upstream bugs.
|
||||
A live audit against `ruvector@0.3.3` confirmed which subcommands work, which require optional add-on packages, and which are upstream bugs.
|
||||
|
||||
## Decision
|
||||
|
||||
The plugin pins to `ruvector@0.2.25` and documents the optional add-on packages required for full functionality.
|
||||
The plugin pins to `ruvector@0.3.3` and documents the optional add-on packages required for full functionality.
|
||||
|
||||
### 1. Pin every CLI invocation
|
||||
|
||||
All `npx` calls in the plugin (README, agent, skills, commands, scripts) MUST be of the form:
|
||||
|
||||
```bash
|
||||
npx -y ruvector@0.2.25 <subcommand> [args]
|
||||
npx -y ruvector@0.3.3 <subcommand> [args]
|
||||
```
|
||||
|
||||
Rationale: the `-y` flag suppresses the npm interactive prompt; the version pin prevents a future ruvector release from breaking the plugin's contract without our knowledge.
|
||||
@@ -56,7 +56,7 @@ Rationale: these are heavy dependencies (ONNX runtime alone is large). Forcing t
|
||||
### 3. Register MCP server with the same pin
|
||||
|
||||
```bash
|
||||
claude mcp add ruvector -- npx -y ruvector@0.2.25 mcp start
|
||||
claude mcp add ruvector -- npx -y ruvector@0.3.3 mcp start
|
||||
```
|
||||
|
||||
Rationale: the MCP transport layer changes between minor versions of ruvector. Pinning the MCP command keeps the 103 exposed tools stable for downstream agents.
|
||||
@@ -75,9 +75,9 @@ A future ADR may relax this if upstream introduces a stable equivalent and we up
|
||||
|
||||
### 5. Smoke test as the contract
|
||||
|
||||
`scripts/smoke.sh` verifies the contracted surface against any installed `ruvector@0.2.25`. It must remain green on every plugin change. Tests cover:
|
||||
`scripts/smoke.sh` verifies the contracted surface against any installed `ruvector@0.3.3`. It must remain green on every plugin change. Tests cover:
|
||||
|
||||
- Version pin (`--version` returns `0.2.25`)
|
||||
- Version pin (`--version` returns `0.3.3`)
|
||||
- Top-level subcommand visibility (`hooks`, `embed`, `rvf`, `attention`, `gnn`, `brain`, `sona`, `create`, `stats`, `search`, `insert`)
|
||||
- `hooks route` accepts a positional task argument
|
||||
- `hooks ast-analyze` accepts a positional file argument
|
||||
@@ -120,3 +120,16 @@ bash plugins/ruflo-ruvector/scripts/smoke.sh
|
||||
- `skills/vector-setup/SKILL.md` — first-run installer
|
||||
- `agents/vector-engineer.md` — agent contract with replacement table
|
||||
- Upstream issue 401 (`optimize` not yet shipped)
|
||||
|
||||
## Addendum (2026-10-14) — pin moved to ruvector 0.3.3 (#4158)
|
||||
|
||||
The 0.2.25 pin shipped without `dist/core/onnx/pkg`, so `embed text` failed
|
||||
with `ONNX WASM files not bundled` and the documented remedy
|
||||
(`ruvector-onnx-embeddings-wasm`) did not fix it. 0.3.3 bundles the wasm; in a
|
||||
throwaway prefix `embed text` returned a 384-dim vector with no add-on. The pin
|
||||
is now `ruvector@0.3.3` and the ONNX add-on is no longer installed or
|
||||
documented. Also re-verified on 0.3.3: `optimize` and `hooks force-learn` run,
|
||||
`midstream` exists, `embed text` takes `--stdin`/`--input-file`, `hooks
|
||||
graph-mincut` still fails, `compare` still does not exist, `mcp tools` lists 97.
|
||||
`@ruvector/pi-brain` is still needed for `brain`; `sona` falls back to JS. The
|
||||
filename keeps the original number so links stay valid.
|
||||
@@ -1,11 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
# Smoke test for ruflo-ruvector plugin against ruvector@0.2.25.
|
||||
# Smoke test for ruflo-ruvector plugin against ruvector@0.3.3.
|
||||
# Exits non-zero if any contracted CLI surface is missing or behaves
|
||||
# differently from documented. Run after `npm install ruvector@0.2.25`
|
||||
# differently from documented. Run after `npm install ruvector@0.3.3`
|
||||
# (or rely on the npx fetch).
|
||||
set -u
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
PIN="ruvector@0.2.25"
|
||||
PIN="ruvector@0.3.3"
|
||||
PASS=0
|
||||
FAIL=0
|
||||
WORKDIR="$(mktemp -d -t ruvector-smoke.XXXXXX)"
|
||||
@@ -21,7 +21,7 @@ run() { npx -y "$PIN" "$@" 2>&1; }
|
||||
step "version pin"
|
||||
# --version output may include npm warnings; take the last non-empty line.
|
||||
ver=$(run --version | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | tail -1)
|
||||
[[ "$ver" == "0.2.25" ]] && ok || bad "expected 0.2.25, got '$ver'"
|
||||
[[ "$ver" == "0.3.3" ]] && ok || bad "expected 0.3.3, got '$ver'"
|
||||
|
||||
step "top-level help mentions hooks/embed/rvf/attention/gnn/brain/sona"
|
||||
help=$(run --help)
|
||||
@@ -57,16 +57,16 @@ step "gnn info reports Available"
|
||||
out=$(run gnn info)
|
||||
grep -q "Status:.*Available" <<<"$out" && ok || bad "gnn info did not report Available"
|
||||
|
||||
step "info reports CLI Version 0.2.25"
|
||||
step "info reports CLI Version 0.3.3"
|
||||
out=$(run info)
|
||||
grep -q "CLI Version: 0.2.25" <<<"$out" && ok || bad "info did not report 0.2.25"
|
||||
grep -q "CLI Version: 0.3.3" <<<"$out" && ok || bad "info did not report 0.3.3"
|
||||
|
||||
step "doctor exits 0"
|
||||
run doctor >/dev/null && ok || bad "doctor returned non-zero"
|
||||
|
||||
step "removed surface stays removed (compare/midstream/index)"
|
||||
step "removed surface stays removed (compare/index)"
|
||||
fail_removed=""
|
||||
for c in compare midstream index; do
|
||||
for c in compare index; do
|
||||
# Don't pass --help — Commander will show top-level help instead of the error.
|
||||
out=$(npx -y "$PIN" "$c" 2>&1)
|
||||
grep -q "unknown command '$c'" <<<"$out" || fail_removed="$fail_removed $c"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: vector-cluster
|
||||
description: Cluster code by graph community detection via npx ruvector@0.2.25 hooks graph-cluster (spectral / Louvain)
|
||||
description: Cluster code by graph community detection via npx ruvector@0.3.3 hooks graph-cluster (spectral / Louvain)
|
||||
argument-hint: "<namespace> [--k N]"
|
||||
allowed-tools: Bash Read mcp__plugin_ruflo-core_ruflo__memory_search mcp__plugin_ruflo-core_ruflo__memory_store mcp__plugin_ruflo-core_ruflo__memory_list
|
||||
---
|
||||
@@ -15,14 +15,14 @@ Use this skill when you have a collection of embeddings and want to discover nat
|
||||
|
||||
## Steps
|
||||
|
||||
1. **Ensure ruvector@0.2.25 is available**:
|
||||
1. **Ensure ruvector@0.3.3 is available**:
|
||||
```bash
|
||||
npm ls ruvector 2>/dev/null | grep '0.2.25' || npm install ruvector@0.2.25
|
||||
npm ls ruvector 2>/dev/null | grep '0.3.3' || npm install ruvector@0.3.3
|
||||
```
|
||||
2. **Run clustering** — in ruvector@0.2.25 the only working clustering is via `hooks graph-cluster` (spectral/Louvain over a code graph). The top-level `cluster` command is reserved for distributed cluster ops and is currently "Coming Soon" upstream.
|
||||
2. **Run clustering** — in ruvector@0.3.3 the only working clustering is via `hooks graph-cluster` (spectral/Louvain over a code graph). The top-level `cluster` command is reserved for distributed cluster ops and is currently "Coming Soon" upstream.
|
||||
```bash
|
||||
npx -y ruvector@0.2.25 hooks graph-cluster <files...>
|
||||
npx -y ruvector@0.2.25 hooks graph-mincut <files...>
|
||||
npx -y ruvector@0.3.3 hooks graph-cluster <files...>
|
||||
npx -y ruvector@0.3.3 hooks graph-mincut <files...>
|
||||
```
|
||||
3. **Review output** — JSON with cluster assignments, community labels, and edges. If you see `"graph.nodes is not iterable"`, run `hooks init` first to seed the graph state.
|
||||
4. **Store results**:
|
||||
@@ -37,5 +37,5 @@ Use this skill when you have a collection of embeddings and want to discover nat
|
||||
|
||||
## Caveats
|
||||
|
||||
- `cluster --namespace ... --k N` and `cluster --density` are **not** valid in ruvector@0.2.25 — those flags fall through to the distributed-cluster command, which only accepts `--status`, `--join`, `--leave`, `--nodes`, `--leader`, `--info`.
|
||||
- `cluster --namespace ... --k N` and `cluster --density` are **not** valid in ruvector@0.3.3 — those flags fall through to the distributed-cluster command, which only accepts `--status`, `--join`, `--leave`, `--nodes`, `--leader`, `--info`.
|
||||
- For namespaced k-means over arbitrary embeddings, run k-means in your own code against vectors stored in AgentDB.
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: vector-embed
|
||||
description: Generate embeddings via npx ruvector@0.2.25 embed text (ONNX all-MiniLM-L6-v2, 384-dim), normalize, and store in HNSW index
|
||||
description: Generate embeddings via npx ruvector@0.3.3 embed text (ONNX all-MiniLM-L6-v2, 384-dim), normalize, and store in HNSW index
|
||||
argument-hint: "<text-or-file>"
|
||||
allowed-tools: Bash Read mcp__plugin_ruflo-core_ruflo__memory_store mcp__plugin_ruflo-core_ruflo__memory_search
|
||||
---
|
||||
@@ -15,20 +15,17 @@ Use this skill to embed text, code, or documents into 384-dimensional vectors fo
|
||||
|
||||
## Steps
|
||||
|
||||
1. **Ensure ruvector@0.2.25 is available**:
|
||||
1. **Ensure ruvector@0.3.3 is available**:
|
||||
```bash
|
||||
npm ls ruvector 2>/dev/null | grep '0.2.25' || npm install ruvector@0.2.25
|
||||
```
|
||||
If `embed text` later reports `ONNX WASM files not bundled`, also run:
|
||||
```bash
|
||||
npm install ruvector-onnx-embeddings-wasm
|
||||
npm ls ruvector 2>/dev/null | grep '0.3.3' || npm install ruvector@0.3.3
|
||||
```
|
||||
ruvector 0.3.3 bundles the ONNX runtime; no add-on is needed. If `embed text` reports `ONNX WASM files not bundled`, an older ruvector (0.2.x) is being resolved — rerun with the pinned `npx -y ruvector@0.3.3`.
|
||||
2. **Embed the input** (use the `text` subcommand, with text as a positional arg):
|
||||
- Single string: `npx -y ruvector@0.2.25 embed text "your text here"`
|
||||
- With output file: `npx -y ruvector@0.2.25 embed text "your text here" -o vec.json`
|
||||
- Single string: `npx -y ruvector@0.3.3 embed text "your text here"`
|
||||
- With output file: `npx -y ruvector@0.3.3 embed text "your text here" -o vec.json`
|
||||
- For a file: read its content via the Read tool, then pass it as the positional argument.
|
||||
- For batch: loop over files in shell — ruvector@0.2.25 has no built-in `--batch`/`--glob` flags.
|
||||
3. **Adaptive (LoRA) variant**: `npx -y ruvector@0.2.25 embed text "..." --adaptive --domain code`
|
||||
- For batch: loop over files in shell — ruvector@0.3.3 has no built-in `--batch`/`--glob` flags.
|
||||
3. **Adaptive (LoRA) variant**: `npx -y ruvector@0.3.3 embed text "..." --adaptive --domain code`
|
||||
4. **Confirm** — report vector dimension (384), norm, and any output path written.
|
||||
5. **Store metadata** in AgentDB if needed:
|
||||
`mcp__plugin_ruflo-core_ruflo__memory_store({ key: "embed-SOURCE", value: "VECTOR_METADATA", namespace: "vector-patterns" })`
|
||||
@@ -37,11 +34,11 @@ Use this skill to embed text, code, or documents into 384-dimensional vectors fo
|
||||
|
||||
Register the MCP server once with the pinned version:
|
||||
```bash
|
||||
claude mcp add ruvector -- npx -y ruvector@0.2.25 mcp start
|
||||
claude mcp add ruvector -- npx -y ruvector@0.3.3 mcp start
|
||||
```
|
||||
Then call MCP tools directly: `hooks_rag_context` (semantic context), `brain_search` (collective brain), `hooks_ast_analyze`, `hooks_route`.
|
||||
|
||||
## Caveats
|
||||
|
||||
- The `embed --batch --glob` and `embed --file` flags do **not** exist in ruvector@0.2.25; only `embed text <text>` is supported. Read files yourself and call `embed text` per file.
|
||||
- ONNX runtime is not bundled by default. If embedding fails, install `ruvector-onnx-embeddings-wasm` or run `npx -y ruvector@0.2.25 doctor` to diagnose.
|
||||
- The `embed --batch --glob` flags do **not** exist in ruvector@0.3.3. `embed text` accepts one text, `--stdin`, or `--input-file <path>` (keeps sensitive text off argv); call it per file.
|
||||
- If embedding fails, run `npx -y ruvector@0.3.3 doctor` to diagnose.
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: vector-hyperbolic
|
||||
description: Embed hierarchical data via npx ruvector@0.2.25 embed text and project into the Poincare ball in user code (no --model poincare flag in 0.2.25)
|
||||
description: Place hierarchical data in the Poincare ball using depth for the radius and npx ruvector@0.3.3 embed text for direction (a unit-norm text embedding alone has no depth)
|
||||
argument-hint: "<text> [--model poincare]"
|
||||
allowed-tools: Bash Read mcp__plugin_ruflo-core_ruflo__memory_store mcp__plugin_ruflo-core_ruflo__memory_search
|
||||
---
|
||||
@@ -15,37 +15,33 @@ Use this skill when your data has inherent hierarchy — dependency trees, modul
|
||||
|
||||
## Steps
|
||||
|
||||
1. **Ensure ruvector@0.2.25 is available**:
|
||||
1. **Ensure ruvector@0.3.3 is available**:
|
||||
```bash
|
||||
npm ls ruvector 2>/dev/null | grep '0.2.25' || npm install ruvector@0.2.25
|
||||
npm ls ruvector 2>/dev/null | grep '0.3.3' || npm install ruvector@0.3.3
|
||||
```
|
||||
2. **Generate a base ONNX embedding** (ruvector@0.2.25 does not expose a `--model poincare` flag on `embed text`):
|
||||
2. **Know what a text embedding can and cannot give you.** ONNX sentence embeddings (all-MiniLM-L6-v2) are unit-norm. Rescaling or exp-mapping a unit vector puts every point at the same radius (the MCP `embeddings_hyperbolic convert` gives tanh(0.5) = 0.4621 for all of them), so the radius carries no depth and parent/child distances come out nearly the same as cross-branch distances. Projecting a text embedding does not create hierarchy.
|
||||
3. **Put the hierarchy in yourself.** Choose each node's radius from its depth in the tree (root near 0, leaves near 1, for example r = tanh(depth * k)), and take its direction from the text embedding, or use embeddings trained on the tree's edges. Measure on your own tree: parent-child distance should be clearly smaller than cross-branch distance.
|
||||
```bash
|
||||
npx -y ruvector@0.2.25 embed text "hierarchical concept" -o concept.vec.json
|
||||
npx -y ruvector@0.3.3 embed text "hierarchical concept" -o concept.vec.json # direction only
|
||||
```
|
||||
3. **Project into the Poincare ball** in your own code (or via the experimental neural substrate):
|
||||
```bash
|
||||
npx -y ruvector@0.2.25 embed neural --help
|
||||
```
|
||||
For an ad-hoc projection, normalize the 384-dim vector to live inside the unit ball (`x_i / (||x|| * (1 + epsilon))`) and persist the projected coordinates alongside the original embedding.
|
||||
4. **Geodesic distance**: `d(u, v) = arcosh(1 + 2 * ||u-v||^2 / ((1-||u||^2)(1-||v||^2)))`
|
||||
Distance grows logarithmically with tree depth, preserving hierarchy.
|
||||
4. **Geodesic distance** for points strictly inside the unit ball: `d(u, v) = arcosh(1 + 2 * ||u-v||^2 / ((1-||u||^2)(1-||v||^2)))`. The MCP `embeddings_hyperbolic distance` computes it (curvature -1) and returns `success: false` for a point on or outside the ball rather than a null distance.
|
||||
5. **Store results**:
|
||||
`mcp__plugin_ruflo-core_ruflo__memory_store({ key: "hyperbolic-CONCEPT", value: "COORDINATES_AND_NEIGHBORS", namespace: "hyperbolic-embeddings" })`
|
||||
|
||||
## Caveats
|
||||
|
||||
- ruvector@0.2.25 has no first-class Poincare ball CLI flag. Treat hyperbolic projection as a post-processing step over a standard ONNX embedding.
|
||||
- If you need a hyperbolic search index, store projected coordinates in AgentDB and compute geodesic distance in your own retrieval code.
|
||||
- ruvector@0.3.3 has no `--model poincare` flag; `attention hyperbolic` is the Poincare-ball attention op, not a text-embedding projector.
|
||||
- "Norm encodes depth" only holds when you set the radius from depth yourself (step 3). It does not come from the embedding.
|
||||
- If you need a hyperbolic search index, store the placed coordinates in AgentDB and compute geodesic distance in your own retrieval code.
|
||||
|
||||
## Poincare ball properties
|
||||
## Poincare ball properties (for points you placed by depth)
|
||||
|
||||
| Property | Meaning |
|
||||
|----------|---------|
|
||||
| Norm close to 0 | Generic, root-level concept |
|
||||
| Norm close to 1 | Specific, leaf-level concept |
|
||||
| Small geodesic distance | Closely related in hierarchy |
|
||||
| Large geodesic distance | Distant or different subtrees |
|
||||
| Norm close to 0 | Root-level concept (only if you assigned radius by depth) |
|
||||
| Norm close to 1 | Leaf-level concept (same condition) |
|
||||
| Small geodesic distance | Close in the hierarchy you encoded |
|
||||
| Large geodesic distance | Distant subtrees in the hierarchy you encoded |
|
||||
|
||||
## Use cases
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
---
|
||||
name: vector-setup
|
||||
description: First-run setup for ruvector@0.2.25 — installs ONNX/Brain/SONA add-ons, registers the MCP server, and verifies the install via `doctor`
|
||||
description: First-run setup for ruvector@0.3.3 — installs ONNX/Brain/SONA add-ons, registers the MCP server, and verifies the install via `doctor`
|
||||
argument-hint: "[--full]"
|
||||
allowed-tools: Bash Read
|
||||
---
|
||||
|
||||
# Vector Setup
|
||||
|
||||
Bootstraps `ruvector@0.2.25` and its optional add-ons so every `/vector` subcommand actually works on first run.
|
||||
Bootstraps `ruvector@0.3.3` and its optional add-ons so every `/vector` subcommand actually works on first run.
|
||||
|
||||
## Why this exists
|
||||
|
||||
@@ -15,7 +15,7 @@ Out of the box, several `/vector` subcommands fail with a confusing dep error:
|
||||
|
||||
| Error | Missing package |
|
||||
|-------|-----------------|
|
||||
| `ONNX WASM files not bundled. The onnx/ directory is missing.` | `ruvector-onnx-embeddings-wasm` |
|
||||
| `ONNX WASM files not bundled. The onnx/ directory is missing.` | none — upgrade to ruvector 0.3.3, which bundles it (0.2.x lacks it) |
|
||||
| `Brain commands require @ruvector/pi-brain` | `@ruvector/pi-brain` |
|
||||
| `SONA not available. Native error: Cannot find module '/.../@ruvector/sona/index.js'` | `@ruvector/ruvllm` (JS fallback) |
|
||||
| `LLM commands require @ruvector/ruvllm` | `@ruvector/ruvllm` |
|
||||
@@ -26,42 +26,40 @@ This skill installs them in one pass.
|
||||
|
||||
1. **Pin ruvector**:
|
||||
```bash
|
||||
npm install ruvector@0.2.25
|
||||
npm install ruvector@0.3.3
|
||||
```
|
||||
2. **Install the add-ons** (idempotent — only what's missing):
|
||||
```bash
|
||||
npm install ruvector-onnx-embeddings-wasm \
|
||||
@ruvector/pi-brain \
|
||||
npm install @ruvector/pi-brain \
|
||||
@ruvector/ruvllm
|
||||
```
|
||||
For a leaner install, pass `--full` to also pull `@ruvector/graph-node` and `@ruvector/router`:
|
||||
```bash
|
||||
npm install ruvector-onnx-embeddings-wasm \
|
||||
@ruvector/pi-brain \
|
||||
npm install @ruvector/pi-brain \
|
||||
@ruvector/ruvllm \
|
||||
@ruvector/graph-node \
|
||||
@ruvector/router
|
||||
```
|
||||
3. **Verify the binary**:
|
||||
```bash
|
||||
npx -y ruvector@0.2.25 doctor
|
||||
npx -y ruvector@0.2.25 info
|
||||
npx -y ruvector@0.3.3 doctor
|
||||
npx -y ruvector@0.3.3 info
|
||||
```
|
||||
4. **Register the MCP server**:
|
||||
```bash
|
||||
claude mcp add ruvector -- npx -y ruvector@0.2.25 mcp start
|
||||
claude mcp add ruvector -- npx -y ruvector@0.3.3 mcp start
|
||||
claude mcp list | grep ruvector
|
||||
```
|
||||
5. **Sanity check** the most common subcommands:
|
||||
```bash
|
||||
npx -y ruvector@0.2.25 hooks route "test"
|
||||
npx -y ruvector@0.2.25 attention list
|
||||
npx -y ruvector@0.2.25 rvf examples
|
||||
npx -y ruvector@0.3.3 hooks route "test"
|
||||
npx -y ruvector@0.3.3 attention list
|
||||
npx -y ruvector@0.3.3 rvf examples
|
||||
```
|
||||
6. **(Optional) Generate a pi identity** for brain + edge:
|
||||
```bash
|
||||
npx -y ruvector@0.2.25 identity generate
|
||||
npx -y ruvector@0.2.25 identity show
|
||||
npx -y ruvector@0.3.3 identity generate
|
||||
npx -y ruvector@0.3.3 identity show
|
||||
```
|
||||
|
||||
## Smoke test
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ruflo-ruvllm",
|
||||
"description": "RuVLLM local inference with chat formatting (Claude/GPT/Gemini/Ollama/Cohere), model configuration, MicroLoRA fine-tuning, and SONA real-time adaptation. As a mod (ADR-445): a guard that keeps secrets out of adapters and the pattern router, /ruvllm-mod, and a status file the console shows",
|
||||
"version": "0.3.5",
|
||||
"version": "0.3.6",
|
||||
"author": {
|
||||
"name": "ruvnet",
|
||||
"url": "https://github.com/ruvnet"
|
||||
|
||||
@@ -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.6 — 2026-10-14
|
||||
- fix: document the `@ruvector/ruvllm-wasm` add-on that the WASM-backed `ruvllm_*` tools need (README Requirements, `llm-config` and `chat-format` skills); the CLI now returns an install hint instead of a bare ERR_MODULE_NOT_FOUND (#4149)
|
||||
|
||||
## 0.3.5 — 2026-10-12
|
||||
- fix: the shared text screen now catches `.env` and e-mailed credentials, no longer flags a model's token talk (`--max-tokens`, `/oauth/token`, "token usage"), and no longer flags values that only name where a secret lives (`./service-account.json`, `--set-secrets=NAME=NAME:latest`); every rule stays linear (#4094, thanks @proffesor-for-testing)
|
||||
|
||||
|
||||
@@ -9,6 +9,15 @@ RuVLLM local inference with chat formatting, model configuration, MicroLoRA fine
|
||||
/plugin install ruflo-ruvllm@ruflo
|
||||
```
|
||||
|
||||
## Requirements
|
||||
|
||||
The WASM-backed tools (`ruvllm_chat_format`, `ruvllm_microlora_*`, `ruvllm_sona_*`, `ruvllm_hnsw_*`) need `@ruvector/ruvllm-wasm`, which `@claude-flow/cli` does not install. `ruvllm_status` reports `wasm.available: false` plus a `wasm.hint` until it is present:
|
||||
|
||||
```bash
|
||||
npm i -g @ruvector/ruvllm-wasm # global ruflo / @claude-flow/cli install
|
||||
npm i @ruvector/ruvllm-wasm # project-local install
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- **Model configuration**: Generate optimal configs for local inference
|
||||
|
||||
@@ -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.5 with new keywords"
|
||||
step "1. plugin.json declares 0.3.6 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.5" ]]; then bad "expected 0.3.5, got '$v'"; else
|
||||
if [[ "$v" != "0.3.6" ]]; then bad "expected 0.3.6, got '$v'"; else
|
||||
miss=""
|
||||
for k in mcp local-inference chat-templates; do
|
||||
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
|
||||
|
||||
@@ -15,7 +15,7 @@ When you need a prompt string in a local model's chat template (for llama.cpp, O
|
||||
|
||||
## Steps
|
||||
|
||||
1. **Format chat** — call `mcp__plugin_ruflo-core_ruflo__ruvllm_chat_format` with `messages` (`[{role, content}]`) and `template`: one of `llama3`, `mistral`, `chatml`, `phi`, `gemma`, or a model id to auto-detect. Both fields are required. It returns the formatted string.
|
||||
1. **Format chat** — call `mcp__plugin_ruflo-core_ruflo__ruvllm_chat_format` with `messages` (`[{role, content}]`) and `template`: one of `llama3`, `mistral`, `chatml`, `phi`, `gemma`, or a model id to auto-detect. Both fields are required. It returns the formatted string. It needs `@ruvector/ruvllm-wasm` (`npm i -g @ruvector/ruvllm-wasm`); without it the call fails with an install hint.
|
||||
2. **Create a router** (optional) — `ruvllm_hnsw_create` with `dimensions` (for example 384), `maxPatterns`, `efSearch`. The WASM router holds about 11 patterns at most (ruvllm-wasm v2.0.1), so use it for routing between a few named intents, not for document retrieval. For real document search use `memory_search` or the `ruflo-rag-memory` plugin.
|
||||
3. **Add patterns** — `ruvllm_hnsw_add` with `routerId`, a `name`, and an `embedding` whose length equals the router's dimensions (you produce the embedding, for example with `embeddings_generate`).
|
||||
4. **Route a query** — `ruvllm_hnsw_route` with `routerId`, the query `embedding`, and `k` (default 3).
|
||||
|
||||
@@ -15,7 +15,7 @@ When you need to configure local LLM inference, create MicroLoRA adapters for ta
|
||||
|
||||
## Steps
|
||||
|
||||
1. **Check status** — call `mcp__plugin_ruflo-core_ruflo__ruvllm_status` to see current model and adapter state
|
||||
1. **Check status** — call `mcp__plugin_ruflo-core_ruflo__ruvllm_status` to see current model and adapter state. If `wasm.available` is `false`, install the add-on first (`npm i -g @ruvector/ruvllm-wasm`, or without `-g` in a project) — the MicroLoRA and SONA tools cannot run without it
|
||||
2. **Generate config** — call `mcp__plugin_ruflo-core_ruflo__ruvllm_generate_config` with model parameters
|
||||
3. **Create MicroLoRA** — call `mcp__plugin_ruflo-core_ruflo__ruvllm_microlora_create` with `inputDim`, `outputDim`, `rank` (1-4, default 2) and `alpha`
|
||||
4. **Adapt MicroLoRA** — call `mcp__plugin_ruflo-core_ruflo__ruvllm_microlora_adapt` with `loraId` and a `quality` signal (0.0-1.0), optional `learningRate` and `success`. It takes a feedback score, not a training set
|
||||
|
||||
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user