Merge branch 'main' into fix/json-memory-transaction-snapshots-20261010

This commit is contained in:
rUv authored and GitHub committed 2026-10-11 06:31:28 -07:00
commit 342ad839bb
185 files changed
+9220 -2276

No files matched your search

+14 -2
View File
@@ -79,6 +79,15 @@ function envValue(env, name) {
return key ? env[key] : undefined;
}
/**
* Where the npx fallback resolves ruflo from: the plugin's data dir or the
* user's home, never the cwd (the opened project). `--prefix` only changes
* package resolution; the CLI still runs with the project as its cwd.
*/
function npxPrefix(env = process.env) {
return envValue(env, 'CLAUDE_PLUGIN_DATA') || envValue(env, 'PLUGIN_DATA') || require('os').homedir();
}
/**
* Locate a command on PATH using fs only.
*
@@ -98,6 +107,9 @@ function resolveCommandPath(command, env = process.env, platform = process.platf
? (envValue(env, 'PATHEXT') || '.COM;.EXE;.BAT;.CMD').split(';')
: [''];
for (const dir of dirs) {
// A relative or empty PATH entry resolves against the cwd, i.e. the
// opened project; never resolve the CLI from there.
if (!hasSeparator && !(platform === 'win32' ? path.win32 : path.posix).isAbsolute(dir)) continue;
for (const ext of extensions) {
const base = path.resolve(dir || '.', command);
const candidates = ext
@@ -289,7 +301,7 @@ function main() {
// a spurious failure even though the shim 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', 'ruflo@latest'], hookArgs, stdinData);
invokeHook('npx', ['--prefer-offline', '--yes', '--prefix', npxPrefix(), 'ruflo@latest'], hookArgs, stdinData);
}
done();
@@ -301,4 +313,4 @@ function main() {
// invokes this file directly, so main() runs unconditionally otherwise.
if (!globalThis.__RUFLO_HOOK_IMPORT_ONLY__) main();
module.exports = { invokeHook, resolveCommandPath, resolveInvocation, resolveNpmShim, escapeCmdArg };
module.exports = { invokeHook, npxPrefix, resolveCommandPath, resolveInvocation, resolveNpmShim, escapeCmdArg };
+13 -8
View File
@@ -17,11 +17,16 @@ import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Executable modules resolve only from the helper's own install root. A
// home-level helper can serve an untrusted project, so CLAUDE_PROJECT_DIR must
// never decide which JavaScript gets imported.
const MODULE_ROOT = join(__dirname, '../..');
// Home-level helpers can serve a different project. Keep the memory writer on
// the same project root as intelligence.cjs, which reads CLAUDE_PROJECT_DIR.
// PROJECT_ROOT is for data only.
const PROJECT_ROOT = process.env.CLAUDE_PROJECT_DIR
? resolve(process.env.CLAUDE_PROJECT_DIR)
: join(__dirname, '../..');
: MODULE_ROOT;
const DATA_DIR = join(PROJECT_ROOT, '.claude-flow', 'data');
const STORE_PATH = join(DATA_DIR, 'auto-memory-store.json');
@@ -41,7 +46,7 @@ const dim = (msg) => console.log(` ${DIM}${msg}${RESET}`);
// told exactly how to fix it (on both stdout, so it shows in the Claude Code hook
// transcript, and stderr, per the issue's requested channel).
function warnMemoryUnavailable() {
const line1 = `[AutoMemory] @claude-flow/memory not resolvable from ${PROJECT_ROOT} — self-learning imports are DISABLED.`;
const line1 = `[AutoMemory] @claude-flow/memory not resolvable from ${MODULE_ROOT} — self-learning imports are DISABLED.`;
const line2 = ' Fix: npm i -D @claude-flow/memory (or re-run: npx ruflo@latest init, then npx ruflo@latest doctor --fix)';
console.log(`${YELLOW}${line1}${RESET}`);
console.log(`${YELLOW}${line2}${RESET}`);
@@ -175,7 +180,7 @@ async function loadMemoryPackage() {
// project — so init resolves it from the CLI's own context and records the
// absolute path here. This is the only strategy that works on that install.
try {
const sidecar = join(PROJECT_ROOT, '.claude-flow', 'memory-package.json');
const sidecar = join(MODULE_ROOT, '.claude-flow', 'memory-package.json');
if (existsSync(sidecar)) {
const rec = JSON.parse(readFileSync(sidecar, 'utf-8'));
if (rec?.distPath && existsSync(rec.distPath)) {
@@ -185,7 +190,7 @@ async function loadMemoryPackage() {
} catch { /* fall through */ }
// Strategy 1: Local dev (built dist)
const localDist = join(PROJECT_ROOT, 'v3/@claude-flow/memory/dist/index.js');
const localDist = join(MODULE_ROOT, 'v3/@claude-flow/memory/dist/index.js');
if (existsSync(localDist)) {
try {
return await import(`file://${localDist}`);
@@ -196,7 +201,7 @@ async function loadMemoryPackage() {
// when installed as a transitive dependency via npx ruflo / npx claude-flow)
try {
const { createRequire } = await import('module');
const require = createRequire(join(PROJECT_ROOT, 'package.json'));
const require = createRequire(join(MODULE_ROOT, 'package.json'));
return require('@claude-flow/memory');
} catch { /* fall through */ }
@@ -205,8 +210,8 @@ async function loadMemoryPackage() {
return await import('@claude-flow/memory');
} catch { /* fall through */ }
// Strategy 4: Walk up from PROJECT_ROOT looking for @claude-flow/memory in any node_modules
let searchDir = PROJECT_ROOT;
// Strategy 4: Walk up from MODULE_ROOT looking for @claude-flow/memory in any node_modules
let searchDir = MODULE_ROOT;
const { parse } = await import('path');
while (searchDir !== parse(searchDir).root) {
const candidate = join(searchDir, 'node_modules', '@claude-flow', 'memory', 'dist', 'index.js');
@@ -378,7 +383,7 @@ async function doStatus() {
const memPkg = await loadMemoryPackage();
const config = readConfig();
const sidecar = join(PROJECT_ROOT, '.claude-flow', 'memory-package.json');
const sidecar = join(MODULE_ROOT, '.claude-flow', 'memory-package.json');
const hasSidecar = existsSync(sidecar);
console.log('\n=== Auto Memory Bridge Status ===\n');
+19 -14
View File
@@ -18,6 +18,10 @@ const fs = require('fs');
const os = require('os');
const helpersDir = __dirname;
// The helper's own install root: the project for a project-local helper,
// $HOME for a home-level one. CLI resolution starts here, never at the opened
// project, so a home-level helper does not run code the project supplies.
const helperRoot = path.resolve(helpersDir, '..', '..');
// Resolve an installed @claude-flow/cli (or ruflo) bin — mirrors
// statusline-generator.ts's resolveCliBin() candidate list. Used only to
@@ -38,12 +42,11 @@ const helpersDir = __dirname;
function resolveCliBinForHook() {
try {
const home = os.homedir();
const cwd = process.cwd();
const candidates = [
path.join(home, '.claude', 'plugins', 'marketplaces', 'ruflo', 'bin', 'cli.js'),
path.join(cwd, 'node_modules', '@claude-flow', 'cli', 'bin', 'cli.js'),
path.join(cwd, 'node_modules', 'ruflo', 'bin', 'cli.js'),
path.join(cwd, 'v3', '@claude-flow', 'cli', 'bin', 'cli.js'),
path.join(helperRoot, 'node_modules', '@claude-flow', 'cli', 'bin', 'cli.js'),
path.join(helperRoot, 'node_modules', 'ruflo', 'bin', 'cli.js'),
path.join(helperRoot, 'v3', '@claude-flow', 'cli', 'bin', 'cli.js'),
// helpersDir is .claude/helpers/ inside the package itself when this
// file is running from a real @claude-flow/cli install (not a project
// that merely copied the helper) — its bin/ is two levels up.
@@ -77,14 +80,19 @@ function resolveCliBinForHook() {
// render path, where local-first exists purely for per-render latency.
// `--prefer-offline` avoids a registry round trip for the tarball when
// already cached while still resolving the current `@latest` version.
//
// `--prefix helperRoot` makes npx resolve @claude-flow/cli from the helper's
// install root instead of the cwd (the opened project); the spawned CLI still
// runs with the project as its cwd.
function cliSpawnArgs(cliBin, args, platform = process.platform) {
if (cliBin) return [process.execPath, [cliBin, ...args]];
return [platform === 'win32' ? 'npx.cmd' : 'npx', ['--prefer-offline', '--prefix', helperRoot, '@claude-flow/cli', ...args]];
}
function spawnDetachedHookRefresh(subcommand) {
try {
const { spawn } = require('child_process');
const cliBin = resolveCliBinForHook();
const cmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
const spawnArgs = cliBin
? [process.execPath, [cliBin, 'hooks', subcommand, '--quiet']]
: [cmd, ['--prefer-offline', '@claude-flow/cli', 'hooks', subcommand, '--quiet']];
const spawnArgs = cliSpawnArgs(resolveCliBinForHook(), ['hooks', subcommand, '--quiet']);
const child = spawn(spawnArgs[0], spawnArgs[1], {
detached: true,
stdio: 'ignore',
@@ -151,10 +159,7 @@ function firstRunAutoEnableIfEligible() {
const cliBin = resolveCliBinForHook();
const runDetached = (args) => {
try {
const spawnArgs = cliBin
? [process.execPath, [cliBin, ...args]]
: [process.platform === 'win32' ? 'npx.cmd' : 'npx',
['--prefer-offline', '@claude-flow/cli', ...args]];
const spawnArgs = cliSpawnArgs(cliBin, args);
const child = spawn(spawnArgs[0], spawnArgs[1], {
detached: true, stdio: 'ignore', env: process.env, windowsHide: true,
});
@@ -772,4 +777,4 @@ if (require.main === module) {
// Which sibling helpers loaded (all CommonJS, shipped as .cjs — #3555).
const loadedHelpers = { router: !!router, session: !!session, memory: !!memory, intelligence: !!intelligence };
module.exports = { runWithTimeout, INTELLIGENCE_TIMEOUT_MS, loadedHelpers, ownedByMod, MOD_OWNABLE_EVENTS };
module.exports = { runWithTimeout, INTELLIGENCE_TIMEOUT_MS, loadedHelpers, ownedByMod, MOD_OWNABLE_EVENTS, resolveCliBinForHook, cliSpawnArgs, helperRoot };
+5 -2
View File
@@ -26,9 +26,12 @@ import Database from 'better-sqlite3';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Executable modules resolve only from the helper's own install root; a
// home-level helper can serve an untrusted project. PROJECT_ROOT is data only.
const MODULE_ROOT = join(__dirname, '../..');
const PROJECT_ROOT = process.env.CLAUDE_PROJECT_DIR
? resolve(process.env.CLAUDE_PROJECT_DIR)
: join(__dirname, '../..');
: MODULE_ROOT;
const DATA_DIR = join(PROJECT_ROOT, '.claude-flow/learning');
const DB_PATH = join(DATA_DIR, 'patterns.db');
const METRICS_PATH = join(DATA_DIR, 'learning-metrics.json');
@@ -463,7 +466,7 @@ class EmbeddingService {
try {
// Dynamically import agentic-flow OptimizedEmbedder
const agenticFlowPath = join(PROJECT_ROOT, 'node_modules/agentic-flow/dist/embeddings/optimized-embedder.js');
const agenticFlowPath = join(MODULE_ROOT, 'node_modules/agentic-flow/dist/embeddings/optimized-embedder.js');
if (existsSync(agenticFlowPath)) {
const { getOptimizedEmbedder } = await import(agenticFlowPath);
+56 -10
View File
@@ -6,6 +6,7 @@
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const os = require('os');
const platform = os.platform();
@@ -30,6 +31,49 @@ function getDataDir() {
const SESSION_DIR = getDataDir();
const SESSION_FILE = path.join(SESSION_DIR, 'current.json');
// Archive names are generated by start(); anything else in current.json is
// untrusted project content and must never pick a path.
const SESSION_ID = /^session-\d+$/;
// current.json lives in the opened project. A symlink there must never be read
// or written through, so only a regular file counts as an active session.
function hasSessionFile() {
try { return fs.lstatSync(SESSION_FILE).isFile(); } catch { return false; }
}
function archiveId(id) {
return SESSION_ID.test(String(id)) ? String(id) : `session-${Date.now()}`;
}
// The project session directory must resolve inside the project (no
// symlinked escape). The per-user fallback directory is not project-owned.
function assertSessionDirContained() {
if (SESSION_DIR !== path.join(process.cwd(), '.claude-flow', 'sessions')) return;
const root = fs.realpathSync(process.cwd());
// Resolve the deepest part of the path that exists (lstat: a symlink counts),
// so a symlinked .claude-flow is refused before anything is created under it.
let dir = SESSION_DIR;
for (;;) {
try { fs.lstatSync(dir); break; } catch { /* not created yet */ }
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
const rel = path.relative(root, fs.realpathSync(dir));
if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {
throw new Error('Session directory resolves outside the project');
}
}
// Exclusive temp file + rename: never writes through a planted symlink, and
// rename() replaces a symlinked target instead of following it.
function atomicWrite(file, data) {
assertSessionDirContained();
const tmp = `${file}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
fs.writeFileSync(tmp, data, { flag: 'wx' });
fs.renameSync(tmp, file);
}
function ensureDir(dir) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
@@ -38,6 +82,7 @@ function ensureDir(dir) {
const commands = {
start: () => {
assertSessionDirContained();
ensureDir(SESSION_DIR);
const sessionId = `session-${Date.now()}`;
const session = {
@@ -48,25 +93,25 @@ const commands = {
context: {},
metrics: { edits: 0, commands: 0, tasks: 0, errors: 0 }
};
fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));
atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2));
console.log(`Session started: ${sessionId}`);
return session;
},
restore: () => {
if (!fs.existsSync(SESSION_FILE)) {
if (!hasSessionFile()) {
console.log('No session to restore');
return null;
}
const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));
session.restoredAt = new Date().toISOString();
fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));
atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2));
console.log(`Session restored: ${session.id}`);
return session;
},
end: () => {
if (!fs.existsSync(SESSION_FILE)) {
if (!hasSessionFile()) {
console.log('No active session');
return null;
}
@@ -74,17 +119,18 @@ const commands = {
session.endedAt = new Date().toISOString();
session.duration = Date.now() - new Date(session.startedAt).getTime();
const archivePath = path.join(SESSION_DIR, `${session.id}.json`);
fs.writeFileSync(archivePath, JSON.stringify(session, null, 2));
// Archive under a validated name; a crafted id cannot pick the path.
const id = archiveId(session.id);
atomicWrite(path.join(SESSION_DIR, `${id}.json`), JSON.stringify(session, null, 2));
fs.unlinkSync(SESSION_FILE);
console.log(`Session ended: ${session.id}`);
console.log(`Session ended: ${id}`);
console.log(`Duration: ${Math.round(session.duration / 1000 / 60)} minutes`);
return session;
},
status: () => {
if (!fs.existsSync(SESSION_FILE)) {
if (!hasSessionFile()) {
console.log('No active session');
return null;
}
@@ -98,13 +144,13 @@ const commands = {
},
metric: (name) => {
if (!fs.existsSync(SESSION_FILE)) {
if (!hasSessionFile()) {
return null;
}
const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));
if (session.metrics[name] !== undefined) {
session.metrics[name]++;
fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));
atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2));
}
return session;
}
File diff suppressed because it is too large. Load diff
+28
View File
@@ -7,6 +7,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [3.56.5] - 2026-10-11
Patch release: one fix in `@claude-flow/cli`. No leaf package changed since 3.56.4 (`git diff v3.56.4..HEAD -- v3/@claude-flow` touches only `cli`; the `integration` change drops `publishConfig.tag` and has no runtime effect).
### Fixed
- The graph-edge-writer encryption-header sniff no longer closes the raw DB file descriptor, which dropped live SQLite POSIX locks; the header is read in a bounded child process (#4044, fixes #4040).
## [3.56.4] - 2026-10-10
Patch release: security hardening of the plugin-trust and helper paths, MCP/task fixes, and the Node 24 sqlite fix. Standalone leaves published first: `@claude-flow/memory` 3.0.4, `@claude-flow/integration` 3.0.1, `@claude-flow/plugins` 3.0.2, `@claude-flow/mcp` 3.1.1 (bundled; republished standalone), `@claude-flow/security` 3.0.4 (bundled; republished standalone). Then `@claude-flow/cli`, `claude-flow`, `ruflo` 3.56.4.
### Security
- Plugin registry trust: a placeholder (all-zero) trust anchor is a small-order Ed25519 key and no longer vouches for anything; signature verification uses strict (non-ZIP-215) rules; an unsigned registry no longer grants "official" trust (#3948).
- `plugins upgrade` no longer runs the new version's `postinstall` or registers `shell:exec` hooks without the install-time gate (#3951).
- Plugin and helper locators stop walking up at `node_modules`, so a project-local install cannot reach project `plugins/ruflo-*` code (#3986, replaces #3954).
- Helpers: session ids and session paths are validated, module roots are no longer project-chosen (#3949); the statusline no longer interpolates `HELPER_ROOT` into a shell string, and `npx` runs the helper CLI from the helper root (#3990, replaces #3953).
- User-level settings pin home helpers (#3952).
- `task_assign` rejects `__proto__` agent ids that wrote onto `Object.prototype` (#3967).
### Fixed
- Node 24: `better-sqlite3` is routed to a build that does not abort at exit (#3955).
- Importing the `agentic-flow` root entry no longer runs its CLI (#3958).
- MCP resource cache: stale writes are fenced after invalidation (#4019). `security scan` code patterns no longer report the false positives seen on a real tree (#3999).
- MCP, task and CLI fixes: #3975, #3974, #3970, #3969, #3968, #3980, #3947; graph path search ~94x faster at n=3200 (#3977).
## [3.56.3] - 2026-10-09
Patch release: AgentDB `3.0.0-alpha.20` update. `@claude-flow/memory` 3.0.3 (published standalone; the CLI pins it exactly) and `@claude-flow/cli` 3.56.3. `neural`, `shared` and `cli-core` are unchanged.
+1
View File
@@ -229,3 +229,4 @@ as a first-class, high-priority candidate, not a background note.
| 2026-09-28 | memory | `mmrRerank()`'s embedding-cosine path (`smart-retrieval.ts`) recomputed max-similarity-to-selected against the *entire* selected set on every outer-loop pass (≈O(candidates×selected²)), even after #3169/#3266 already made the Jaccard-fallback tokenization lazy — flagged grade-A by 2026-09-27's own memory scan (still-open #3476) and acted on directly tonight; replaced with a running per-candidate max-similarity cache (one new comparison per candidate per round, folded via `Math.max`, algebraically identical to recomputing the max from scratch) | #3516 | #3517 | yes | ACCEPT | byte-identical selection order across 5 scenarios (all/none/half-embedded, lambda extremes, a dedicated negative-cosine zero-floor case); wall-clock 686.5ms→<343.3ms (>2x, N=200/limit=100), stash-isolated baseline-fails/candidate-passes on this exact assertion; frozen-copy call-count comparison used instead of `vi.spyOn` after a debug test showed Vitest's ESM spy can't intercept same-module internal calls (flagged as a likely latent issue in the sibling 09-10 `tokenize()` call-count test, not fixed retroactively); 564/565 full `@claude-flow/memory` suite both ways (1 pre-existing environmental failure, unchanged), `tsc --noEmit` 0 errors both ways | 85e464a6... | 09-16 (#3339) still open/draft; 09-27 (#3476) still open/draft; 09-15..09-22 backlog mostly MERGED in a 2026-09-26 bulk review batch; no-run gap 09-23/09-25/09-26 |
| 2026-10-09 | swarm | `MessageBus.handleDeliveryError()`'s retry re-queue used the broadcast sentinel `message.to === 'broadcast'` as the queue key instead of the real subscriber `agentId` `enqueue()` had fanned the message out to — `processQueues()` skips any unsubscribed queue, so a failing broadcast subscriber's retries and eventual `message.failed` were silently dropped into an orphaned queue leaking until `shutdown()`; explicitly disclosed as a "KNOWN LIMITATION (pre-existing, not fixed here)" by the immediately-preceding #3562/#3563 rewrite, closed tonight by threading `subscription.agentId` through `deliverMessage()`→`handleDeliveryError()`→the re-queue | #3928 | #3929 | yes | ACCEPT | 2 new discriminating tests, baseline-fails/candidate-passes via stash isolation (independently reproduced byte-identical by an adversarial critic's own stash/pop cycle); full `@claude-flow/swarm` suite 274/274→276/276 (+2 new), 0 regressions, `tsc --noEmit` clean both ways; healthy co-subscriber in the same broadcast unaffected (explicit regression guard); independent adversarial critique CONFIRMED, no blocking issues | 1b7e818e... | 10-01 #3599 MERGED 2026-10-07; 10-02..10-03/10-05..10-08 open/draft or closed-not-merged (see 2026-10-09 note above); 10-04 no-run gap; also newly confirmed MERGED this session: #3339 (09-16), #3539 (09-29) |
| 2026-10-10 | performance | `fallbackLouvain()`'s `communityTotal` map was rebuilt via a full O(n) scan of every node, once per node, once per local-moving pass — O(n²) per pass — instead of maintained incrementally like networkx's `Stot`/python-louvain's `status.degrees` (O(1) per accepted move); this is the *only* community-detection path that ever runs (`loadRuVector()`'s native-acceleration checks for `hooks_graph_mincut`/`hooks_graph_cluster`/`@ruvector/wasm`'s `GraphAnalyzer`, none of which exist in any published `ruvector`/`@ruvector/wasm` version, confirmed by direct inspection of the installed `ruvector@0.2.27`'s real exports — correcting 2026-10-09's own "wire the real exports in" recommendation, which had the wrong premise) | #3976 | #3977 | yes | ACCEPT | 4 new discriminating tests (3 correctness + 1 complexity-growth) with a frozen pre-fix copy inline for CI-safe comparison; stash-isolated baseline-fails/candidate-passes on the growth assertion, independently reproduced by an adversarial critic's own stash/pop cycle; standalone `tsx` probe: baseline 10.37ms→837.29ms (~81x growth, N=200→1600), candidate 5.00ms→22.33ms (~4.5x growth), per-N speedup 2.1x→37.5x; full `@claude-flow/cli` suite failed-file set byte-identical baseline vs. candidate (200 vs. 199 — the one difference is the new test file itself), `tsc --noEmit` byte-identical (498 pre-existing errors); independent adversarial critique CONFIRMED, no blocking issues | 81e21481... | 10-01 #3599 MERGED; 10-02/10-03/10-06/10-07/10-08 open/draft, none stale; 10-04 no-run gap; 10-05 #3754 closed as duplicate of #3517 (not a fresh rejection — same fix had already shipped) |
+86
View File
@@ -0,0 +1,86 @@
# Performance SOTA Report — 2026-10-10
TL;DR: Louvain community detection has one settled 2026 practical lesson, violated tonight: its efficiency case rests on maintaining each community's total degree *incrementally*, not recomputing it from scratch. Ruflo's `graph-analyzer.ts` did the latter — made worse by a correction to 2026-10-09's own recommendation to "wire the real `ruvector` graph exports into `loadRuVector()`": that premise is false. Direct inspection of the installed `ruvector@0.2.27`'s 100+ real exports (and `@ruvector/gnn`'s real API) confirms no published `ruvector`/`@ruvector/wasm` version has ever exported the `hooks_graph_mincut`/`hooks_graph_cluster`/`GraphAnalyzer` surface `loadRuVector()` checks for. Nothing real to wire in — "native acceleration" is permanently dead in every correctly-installed environment, so the plain-JS `fallbackLouvain()`/`fallbackMinCut()` are the *only* code that ever runs. That raised the stakes on their own efficiency: `fallbackLouvain()` rebuilt a `communityTotal` map via a full O(n) node scan, once per node, once per pass — O(n²) per pass vs. the O(n·avg_degree) a correctly incrementalized pass costs. Fixed tonight.
## What's New in 2026
| Finding | Source | Confidence |
|---|---|---|
| networkx's `louvain_communities`/`_one_level` maintains per-community total degree (`Stot`) incrementally — `Stot[u_com] -= degree` on removal, `+= degree` on insertion — never rescanning all nodes | Direct read, `networkx/algorithms/community/louvain.py` (networkx.org, accessed 2026-10-10) | A |
| python-louvain (`taynaud/python-louvain`)'s `Status.degrees`/`gdegrees` use the identical subtract/add pattern inside `__one_level`'s inner loop; full modularity only recomputed once per *pass*, not per node move | Direct read, `community/community_louvain.py` (GitHub, accessed 2026-10-10) | A |
| Blondel et al. 2008 (arXiv:0803.0476) makes no formal Big-O claim — reports empirically "complexity is linear on typical and sparse data," with memory (not CPU) as the practical bottleneck at scale (12 min/39M nodes, 152 min/118M nodes) | Direct full-text read (ar5iv mirror, accessed 2026-10-10) | A |
| igraph's own docs state no complexity bound for `community_multilevel`; the commonly-repeated "O(n log n)" figure traces only to community commentary (Wikipedia), which itself notes no rigorous published analysis exists | python.igraph.org API docs + en.wikipedia.org/wiki/Louvain_method (accessed 2026-10-10) | C |
| graphology-communities-louvain's README claims runtime "bounded by the number of edges" (~O(m) per pass), qualitative only, no independent source-level confirmation of its incremental-vs-recompute mechanism | unpkg.com README (accessed 2026-10-10) | B |
No mainstream tool surveyed — including the two JS/TS dependency-graph tools checked (madge, dependency-cruiser) — applies Louvain-style community detection to a *code*-dependency graph specifically; every implementation above targets generic/social-network graphs. Closest precedent: academic Girvan-Newman clustering of Java dependency graphs, a different algorithm, single unverified source. Noted as a genuine framing gap, not padded.
## Ruflo Current Capability
`v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts` builds a code-dependency graph (import/require/dynamic-import/re-export edges) and offers MinCut-based boundary detection and Louvain-based module/community detection, reachable today via the shipped `claude-flow analyze modules <dir>` CLI command (`analyze.ts`, lazy-loaded from `commands/index.ts`) → `analyzeGraph()` → `analyzeModuleCommunities()`.
`loadRuVector()` tries to resolve "native acceleration" from `ruvector` (checking `hooks_graph_mincut`/`hooks_graph_cluster`) or `@ruvector/wasm` (checking a `GraphAnalyzer` class). Verified by direct inspection, not the code's own comments: the installed `ruvector@0.2.27` (`@claude-flow/cli`'s own normal, non-optional pin) resolves and exports 100+ real functions/classes (`VectorDB`, `FlashAttention`, `buildGraph`, `calculateModularity`, `CodeGraph`, etc.) — but not `hooks_graph_mincut`/`hooks_graph_cluster` (`typeof` → `undefined`). `@ruvector/wasm` isn't resolvable at all. `@ruvector/gnn` exists but its real API (`differentiableSearch`, `hierarchicalForward`, `RuvectorLayer`, `TensorCompress`) is GNN-embedding machinery, zero overlap with graph partitioning. **Correction to 2026-10-09's recommendation #1** ("wire the real exports in"): there's nothing real to wire in. `fallbackMinCut()`/`fallbackLouvain()` aren't a degraded-environment fallback — they're the only path that has ever run, in any correctly-installed environment.
That raised `fallbackLouvain()`'s own efficiency to this file's top priority. Its local-moving loop rebuilt `communityTotal` from a full scan of all n nodes, inside the per-node loop — O(n)×n = O(n²) per pass, ×10 passes — when the reference implementations above (and the algorithm's design intent) maintain it incrementally, O(1) per accepted move. Fixed: `communityTotal` now initializes once before the loop and is patched by ±`nodeDegree` on the two affected communities immediately after each accepted move — the existing modularity-gain arithmetic (which assumes the moving node's own degree is still counted in its current community at evaluation time) is untouched.
## Competitor Comparison
| Tool | Degree-sum tracking | Complexity evidence | Grade |
|---|---|---|---|
| networkx `louvain_communities` | Incremental (`Stot -=`/`+=` per move) | Matches near-linear-per-pass design intent | A |
| python-louvain (Aynaud) | Incremental (`status.degrees` subtract/add) | Same pattern, independently confirmed | A |
| igraph `community_multilevel` | Not disclosed in official docs | No official Big-O; community figure (~O(n log n)) disputed/unproven | C |
| graphology-communities-louvain (JS) | Unconfirmed from README alone | Qualitative "bounded by edge count" claim | B |
| madge / dependency-cruiser (JS, code-dependency-graph tools) | N/A — neither implements community detection at all | N/A | C |
**ruflo (pre-fix)**: communityTotal recomputed from scratch per node per pass — O(n²) per pass, the one practice every implementation above avoids. **ruflo (post-fix)**: incremental, matching the networkx/python-louvain pattern (Grade A precedent).
## Hypothesis (frozen before evaluation)
Given `fallbackLouvain()`'s local-moving phase, when `communityTotal` is initialized once and maintained incrementally (±`nodeDegree` per accepted move) instead of rebuilt via a full node scan per node, then (a) output partitions/modularity should be byte-identical to the pre-fix algorithm, and (b) wall-clock should scale near-linearly with node count at fixed average degree instead of quadratically — subject to: zero change to `fallbackMinCut()`, zero regression across the full suite (byte-identical failing-file set), deterministic $0 evaluation.
## Benchmarks / Evaluation
Real evaluator: Vitest 4.1.8, deterministic, $0, zero LLM calls, against a freshly `pnpm install`-ed `v3/` workspace.
New test file `graph-analyzer.louvain-complexity.test.ts` (4 tests), with a frozen verbatim copy of the pre-fix algorithm (`legacyFallbackLouvain`) inline for self-contained, CI-safe comparison:
- Byte-identical community partitions + modularity vs. the frozen pre-fix copy on two differently-shaped synthetic graphs, plus empty-graph/single-node degenerate cases.
- Growth-ratio test (fixed avg. degree, 8x node-count): legacy must show >20x growth (true O(n²) ≈64x, confirming the fixture exercises the quadratic path) and the fix's growth must stay under half that.
- Stash-isolated independently by an adversarial critic: reverting only the source file fails the growth-ratio assertion exactly as predicted; the 3 correctness assertions still pass (reverted, both algorithms are identical).
- Standalone `tsx` measurement (N=200→1600, 8x nodes, fixed avg. degree): baseline 10.37ms→837.29ms (~81x growth); candidate 5.00ms→22.33ms (~4.5x growth) — speedup itself grows, 2.1x→37.5x, the signature of a complexity-class fix.
- Full `@claude-flow/cli` suite, both ways (JSON reporter, 1295 suites): candidate 3266/3632 tests passed (199 failed files), baseline 3265/3632 (200 failed files) — the only difference in the failed-file set between the two runs is the new test file itself (fails on baseline exactly as predicted, passes on candidate); all 199 other failures are byte-identical, pre-existing, unrelated to this change. `tsc --noEmit`: 498 pre-existing errors both ways (unbuilt sibling packages), zero new.
## Darwin Results
Skipped — binary, correctness-preserving complexity fix with no continuous/categorical parameter to search over (same skip class as nearly every accepted fix since 2026-08-18). `npx ruvector harness darwin --help` was reachable during STEP 0.5 but went transiently unreachable on retry; noted, not a blocker — this candidate skips regardless.
## SOTA Proof & Witness
See issue/PR for the full reward-hack checklist, adversarial critique (independent verdict: CONFIRMED, no blocking caveats), and security review. Witness stamp at the end of this file.
## Recommended Next Steps
1. **Correct `loadRuVector()`'s "fallback" framing** (not a fallback — the only path) via a doc/comment fix, or remove the permanently-dead native-detection branch outright in a future `ruvector-integration` night, so "wire in the real exports" isn't reproposed again.
2. **`fallbackMinCut()`'s docstring claims "Stoer-Wagner MinCut"; it is not** — it's a randomized-restart maximum-adjacency heuristic with no global-minimum guarantee (real Stoer-Wagner contracts the graph per phase). Low-priority naming fix, correctness not performance, not bundled tonight.
3. **hive-mind scan (carried, not bundled):** `v3/@claude-flow/swarm/src/consensus/raft.ts:513-578`'s `handleVoteRequest()`/`handleAppendEntries()` are a second, fully unreachable Raft receiver, only exercised by unit tests, already diverged from the real transport path (`handleInboundRaftMessage()`, lines 99-147) — e.g. its commit-index clamp uses `this.node.log.length` instead of `lastLogInfo().index`. False confidence in safety-critical logic. Testable-tonight-sized for a future `swarm`/`hive-mind` night.
## Scan Findings: security
MCP tool-result injection screening (`applyContentBoundaryGuardrail`, `mcp-client.ts` ~304-351) only scans top-level string values of a tool's return object — anything nested in an array/sub-object is skipped by design. `memory_search`'s real shape (`{ results: [...] }`, each entry carrying `.content`) is exactly that skipped shape, so poisoned memory content passes unfiltered even with the opt-in flag on (off by default). A separate, independently-gated AgentDB-level retrieval guard exists but isn't wired to this path. Testable-tonight-sized (bounded recursion, capped for latency) but not bundled tonight — flagged for a future `security` night.
## Scan Findings: hive-mind
See Recommended Next Steps #3 for the primary finding. Also confirmed: `AgentPool.updateAgentHeartbeat()` (`agent-pool.ts:439`), flagged as dead code by 2026-10-09's own gist, still has zero production callers as of tonight — the open question from last night is settled (no, it has not gained a caller).
## Competitors Reviewed
networkx, python-louvain (taynaud), igraph, graphology-communities-louvain, madge, dependency-cruiser (Louvain/community-detection comparison); OWASP agentic/LLM guidance (security scan).
## Witness
```
Session commit (STEP 0): 6c046548e29506be9bfd6640186d6e85a444e849
Gist SHA-256 (pre-witness, this block's filled values stripped to PENDING): c179941b356c8a09bf9b9f2d1ea4598bd1fe65d45d809823f1cf847087a41b70
Witness stamp: 81e2148140bfe55da2e1d1ff613171d3c1d8252322c065480c7273357cf6b32e
```
Verifier: fetch this file from the branch, strip this block's filled values back to `PENDING`, SHA-256 the file, concatenate with the session commit above, SHA-256 again — must equal the witness stamp.
+4 -4
View File
@@ -1,12 +1,12 @@
{
"name": "claude-flow",
"version": "3.56.3",
"version": "3.56.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "claude-flow",
"version": "3.56.3",
"version": "3.56.5",
"bundleDependencies": [
"@claude-flow/codex",
"@claude-flow/mcp",
@@ -23,10 +23,10 @@
"dependencies": {
"@claude-flow/cli-core": "3.7.0",
"@claude-flow/codex": "3.0.3",
"@claude-flow/mcp": "3.1.0",
"@claude-flow/mcp": "3.1.1",
"@claude-flow/neural": "3.0.0",
"@claude-flow/plugin-agent-federation": "1.0.1",
"@claude-flow/security": "3.0.3",
"@claude-flow/security": "3.0.4",
"@claude-flow/shared": "3.0.2",
"@iarna/toml": "^2.2.5",
"@noble/ed25519": "2.3.0",
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "claude-flow",
"version": "3.56.3",
"version": "3.56.5",
"workspaces": [
"v3/@claude-flow/codex",
"v3/@claude-flow/mcp",
@@ -68,10 +68,10 @@
"dependencies": {
"@claude-flow/cli-core": "3.7.0",
"@claude-flow/codex": "3.0.3",
"@claude-flow/mcp": "3.1.0",
"@claude-flow/mcp": "3.1.1",
"@claude-flow/neural": "3.0.0",
"@claude-flow/plugin-agent-federation": "1.0.1",
"@claude-flow/security": "3.0.3",
"@claude-flow/security": "3.0.4",
"@claude-flow/shared": "3.0.2",
"@iarna/toml": "^2.2.5",
"@noble/ed25519": "2.3.0",
+14 -2
View File
@@ -79,6 +79,15 @@ function envValue(env, name) {
return key ? env[key] : undefined;
}
/**
* Where the npx fallback resolves ruflo from: the plugin's data dir or the
* user's home, never the cwd (the opened project). `--prefix` only changes
* package resolution; the CLI still runs with the project as its cwd.
*/
function npxPrefix(env = process.env) {
return envValue(env, 'CLAUDE_PLUGIN_DATA') || envValue(env, 'PLUGIN_DATA') || require('os').homedir();
}
/**
* Locate a command on PATH using fs only.
*
@@ -98,6 +107,9 @@ function resolveCommandPath(command, env = process.env, platform = process.platf
? (envValue(env, 'PATHEXT') || '.COM;.EXE;.BAT;.CMD').split(';')
: [''];
for (const dir of dirs) {
// A relative or empty PATH entry resolves against the cwd, i.e. the
// opened project; never resolve the CLI from there.
if (!hasSeparator && !(platform === 'win32' ? path.win32 : path.posix).isAbsolute(dir)) continue;
for (const ext of extensions) {
const base = path.resolve(dir || '.', command);
const candidates = ext
@@ -289,7 +301,7 @@ function main() {
// a spurious failure even though the shim 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', 'ruflo@latest'], hookArgs, stdinData);
invokeHook('npx', ['--prefer-offline', '--yes', '--prefix', npxPrefix(), 'ruflo@latest'], hookArgs, stdinData);
}
done();
@@ -301,4 +313,4 @@ function main() {
// invokes this file directly, so main() runs unconditionally otherwise.
if (!globalThis.__RUFLO_HOOK_IMPORT_ONLY__) main();
module.exports = { invokeHook, resolveCommandPath, resolveInvocation, resolveNpmShim, escapeCmdArg };
module.exports = { invokeHook, npxPrefix, resolveCommandPath, resolveInvocation, resolveNpmShim, escapeCmdArg };
@@ -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.42.0",
"version": "0.42.6",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
+25 -2
View File
@@ -2,6 +2,31 @@
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.42.6 — 2026-10-10
- fix: the Plugin Catalog says "mod synced here, plugin not installed" (and marks the row ◇) for a mod Claude Code loaded by sync, such as ruflo-arena@synced, instead of a flat "not installed" that contradicted the Plugins page; the install button stays (#3979)
- chore: work-in-progress and merge lines are dropped from the console and mods changelogs shown on What's new (#3979)
## 0.42.5 — 2026-10-10
- fix: every confirm route answers the card the person saw. A typed /ruflo yes answers only a card that was put in front of you (drawn in the open pane, or named in the answer to your own /ruflo run) and /ruflo yes <id> names its card; otherwise it runs nothing and says the card's id (#3983)
- fix: Enter again in the terminal, skills and automation fields answers the card that field raised, by its id, not a later card that merely reads the same; an auto-confirmed Claude call settles only the card it started, so an unrelated write that lands while a read is still running is left to the person (#3983)
## 0.42.4 — 2026-10-10
- fix: a confirm card nobody answers is cleared unrun at 30 s on the console's own clock, with one event and "expired: ask again" as the last result, so it no longer blocks every later Claude action; a Yes after the window still runs nothing, and the Room stops counting past 30 s (#3984)
- feat: Claude can withdraw its own waiting write ask (console_run ask-withdraw), never the person's card and never a spend, install, network or delete card; at most 3 a minute, with a cooldown on re-asking the same thing (#3984)
- fix: the ADR and skills entries say what to open (console_open adrs, console_open skills) instead of "not wired yet" (#3984)
## 0.42.3 — 2026-10-10
- fix: the session workspace keeps other projects' folders, working directories and git branches out of text answers (what console_state and ask-claude read): the group headings, the cwd and branch line and the unassigned titles name a session by harness and position, never by a recorded path; an adversarial test draws every view with canaries in every transcript field and a failed listing and finds none (#3981, ADR-486 section 3)
- fix: Needs you raises a failure only after the 30 s quiet period (ADR-486 2.3), not for a permission refusal, an Esc or a Codex interrupted turn, and a failure already seen stays seen when only cost or title lines are appended; a time in the future can no longer silence a session; one 12 MB read budget per pass is shared by every adapter and enforced before each read; attention.json is refreshed at least every 5 minutes and a failed write backs off; the Room's Who is here lists only agents with recent activity, keeps your main session first and counts what it leaves out (#3981)
## 0.42.2 — 2026-10-10
- fix: numbers read from CLI JSON are bounded at the reader (a count of 1e999 no longer draws Infinity on the band); an unreadable count stays visible as unknown rather than a measured 0, and a listed finding is never hidden by an under-reporting summary (#3822)
- fix: a mission resume made by Claude keeps each task's hand-out count, so resuming cannot buy more billed hand-outs after the limit paused the mission (#3823)
## 0.42.1 — 2026-10-10
- fix: Mission Control create retries only a real policy-state lock timeout (and a silent failure or a wait that ran out), reads the CLI's own Result: line rather than the Parameters object, undoes every open task of the mission when it must abort, asks the mission record to cancel, and reads the stores back so the result says what they show, not what was asked (#3945)
- fix: a run that reports for itself (mission create, the ADR page writes) now becomes the console's outcome when it ends, so console_state.lastResult carries how it ended however long it took (#3945)
## 0.42.0 — 2026-10-09
- feat: an optional, detect-only Grounding line for Stuart Kerr's third-party ruvnet-brain plugin: Overview says whether it is on, not installed, installed but disabled, or unknown (read from the plugin list and your settings; ruflo works the same without it, and nothing of it is bundled or copied) (ADR-487)
- feat: with the brain on and a mission that names the ruvnet stack (RuVector, RVF, AgentDB, ruflo ...), Claude's mission context carries one fixed line pointing at `search_ruvnet`; Settings → "RuvNet Brain nudge" turns it off (default on). The console never calls the brain and no mission text enters the line
@@ -71,7 +96,6 @@ Newest first. One `## <version> — <date>` heading per version, then `feat:`, `
## 0.37.0 — 2026-10-07
- feat: shared toast system with levels, dedupe, persistence and Settings (ADR-477)
- feat: shared toast policy and its call sites (ADR-477), work in progress
- fix: CONSOLE_VERSION follows the manifest (0.36.1)
## 0.36.1 — 2026-10-07
@@ -81,7 +105,6 @@ Newest first. One `## <version> — <date>` heading per version, then `feat:`, `
- feat: 0.36.0 integration: eventsPersist option, shared whole-batch append argv, hostile-time hardening, init ignores console/
- fix: log Claude's refused request when the person's card is waiting; mission-auto why when not wired; document the local-read allowlist
- fix: session control cap, gate on read-only entries that act, hostile text/data, mission auto-run guards (#3814 #3815 #3816 #3817 #3818)
- chore: Merge verify/events-0.36 into feat/console-0.36
## 0.35.0 — 2026-10-06
- feat: autopilot envelope editor, parallel hand-over, spend windows, band segment, and the first live run (ADR-470)
+10 -2
View File
@@ -20,14 +20,19 @@ export type ActionSpec = {
verifyLocal?: (host: Pick<Host, 'fs' | 'home'>) => Promise<boolean>
/** Reads only: runs at once, without the confirm step, and shows what the CLI printed. */
isReadOnly?: boolean
/** Not a ruflo CLI call: what runs instead once confirmed (a terminal harness), reporting for itself. */
run?: () => Promise<void>
/**
* Not a ruflo CLI call: what runs instead once confirmed (a terminal harness), reporting for itself. A run that answers a RunReport also has
* the runner keep it as the console's outcome, so what console_state shows Claude (and `/ruflo yes` prints) is how the run ended.
*/
run?: () => Promise<void | RunReport>
/** Where the ask came from in its view (`goal`, `controls`, `guide`): a view that draws its own confirm puts it under that field. */
scope?: string
/** The command line the confirm row shows when it is not `ruflo <args>`. */
shows?: string
/** Raised on Claude's behalf: set by a deferred ask (one that resolves after its screen) from the origin it had when called, so it is never attributed to the person (ADR-450 T14, #3815). */
byModel?: boolean
/** Which of Claude's console_run / console_set calls started this ask (model-tools.ts hands out the numbers): the call that settles it is that one and no other (#3983). */
byCall?: number
/** The class the entry itself declares (a Dev Tools entry's `cost`): Claude's confirm gate never reads it as less than this. */
declared?: 'write' | 'network' | 'install' | 'spend' | 'delete'
/** A MetaHarness lab entry's id: the runner keeps what it printed for the lab's result panel. */
@@ -52,6 +57,9 @@ export type ActionSpec = {
findings?: Findings
}
/** How a run that reports for itself ended, in the shape of the console's outcome. */
export type RunReport = { label: string; ok: boolean; detail: string; lines?: string[] }
export const exec = (tool: string, params: Record<string, string>) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as const
const SAFE_WORD = /^[A-Za-z0-9_.-]{1,40}$/
+21 -5
View File
@@ -19,9 +19,25 @@ const TO: Record<string, AdrStatus> = { 'adr-accept': 'accepted', 'adr-reject':
export function adrPalette(state: State): PaletteEntry[] {
const wired = adrWired(state)
const why = 'the ADRs page is not wired yet: open the console first'
const adr = adrOf(state)
// Why an entry has nothing to run, most basic first: no console in this session, the ADR folder not read yet (the page reads it when opened), then the value itself.
const blocked = wired === undefined ? 'the console is not running in this session: open it first (console_open adrs)' : !adr.isLoaded ? 'the ADR folder has not been read this session: open the ADRs page first (console_open adrs), then run it again' : null
const numbered = (keyword: string) => (value: string): string => {
// adr-supersede takes two numbers; every other entry one, written as "3", "0003" or "adr-3".
const words = keyword === 'adr-supersede' ? value.trim().split(/\s+/) : [value.trim()]
const missing = words.find(word => docFor(word) === undefined)
const usage = keyword === 'adr-supersede' ? `type two ADR numbers, the old then the new: "${keyword} 1 3"` : `type the ADR number: "${keyword} 3"`
if (blocked !== null) return blocked
if (missing === undefined || (keyword === 'adr-supersede' && words.length !== 2)) return usage
const number = NUMBER.exec(missing)?.[1]
return number === undefined ? usage : `no ADR ${Number(number)} in ${adr.dir ?? 'the ADR folder'}`
}
const local = (label: string, run: () => void, declared?: NonNullable<ActionSpec['declared']>): ActionSpec | null => (wired === undefined ? null : { label, args: [], expect: label, isReadOnly: true, ...(declared !== undefined && { declared }), run: async () => void run() })
const text = (keyword: string, make: (value: string) => ActionSpec | null) => ({ kind: 'text' as const, keyword, make: (value: string) => (wired === undefined ? null : make(value)), why: () => why })
const text = (keyword: string, make: (value: string) => ActionSpec | null) => ({ kind: 'text' as const, keyword, make: (value: string) => (wired === undefined ? null : make(value)), why: numbered(keyword) })
const docFor = (value: string) => {
const match = NUMBER.exec(value.trim())
@@ -51,7 +67,7 @@ export function adrPalette(state: State): PaletteEntry[] {
return doc === undefined ? null : local(`show ADR ${doc.number}`, () => wired?.actions.select(doc.file))
}),
},
{ id: 'adr-init', group: 'adrs', label: 'initialise ADRs here: create the folder and a first record (asks first, never overwrites)', run: { kind: 'spec', spec: wired === undefined ? null : initSpec(state, wired.host, today()), why: adrOf(state).dir === null ? why : 'this project already has an ADR folder' } },
{ id: 'adr-init', group: 'adrs', label: 'initialise ADRs here: create the folder and a first record (asks first, never overwrites)', run: { kind: 'spec', spec: wired === undefined ? null : initSpec(state, wired.host, today()), why: blocked ?? 'this project already has an ADR folder' } },
{
id: 'adr-propose',
group: 'adrs',
@@ -62,7 +78,7 @@ export function adrPalette(state: State): PaletteEntry[] {
why: (value: string) => {
const fit = titleFit(value)
return wired !== undefined && !fit.ok ? fit.message : why
return wired !== undefined && !fit.ok ? fit.message : blocked ?? (adr.dir === null ? 'this project has no ADR folder yet: adr-init first' : 'type a title: "adr-propose Use Postgres"')
},
},
},
@@ -83,7 +99,7 @@ export function adrPalette(state: State): PaletteEntry[] {
},
{ id: 'adr-attach', group: 'adrs', label: 'adr-attach <number>: attach an ADR to the active mission (Claude and the swarm are told its decision)', run: text('adr-attach', value => needDoc(value, file => wired?.actions.attach(file, true), 'attach ADR N to the active mission', 'write')) },
{ id: 'adr-detach', group: 'adrs', label: 'adr-detach <number>: detach an ADR from the active mission', run: text('adr-detach', value => needDoc(value, file => wired?.actions.attach(file, false), 'detach ADR N from the active mission', 'write')) },
{ id: 'adr-scope', group: 'adrs', label: 'compare the changed files with the paths in the active mission’s accepted ADRs (paths only)', run: { kind: 'spec', spec: local('compare changed files with the attached ADRs', () => wired?.actions.scope()), why } },
{ id: 'adr-scope', group: 'adrs', label: 'compare the changed files with the paths in the active mission’s accepted ADRs (paths only)', run: { kind: 'spec', spec: local('compare changed files with the attached ADRs', () => wired?.actions.scope()), why: blocked ?? '' } },
].map(entry => ({ ...entry, label: plain(entry.label, 200) })) as PaletteEntry[]
}
+25 -4
View File
@@ -5,7 +5,7 @@
* root: a folder or file that is a link is never read or written through, a new file never overwrites, and a status change is refused
* if the file moved since the diff was shown. The pure parts are in data/adr.ts, data/adr-write.ts and data/adr-scope.ts.
*/
import type { ActionSpec } from './actions'
import type { ActionSpec, RunReport } from './actions'
import { replaceFile } from './activity-io'
import { indexOf, lint, MAX_FILE, MAX_FILES, parseAdr, type AdrDoc, type AdrStatus, type Finding, type Registry, STATUSES } from './data/adr'
import { checkScope, digestBlock, reportLines, suggest, type ScopeReport, type Suggestion } from './data/adr-scope'
@@ -174,6 +174,20 @@ export const say = (state: State, host: Pick<Host, 'invalidate'>, label: string,
host.invalidate()
}
/**
* The page's last result as a run's report, so the runner keeps it as the outcome Claude reads too. The detail is the line that says what
* happened: the first of a success, the last of a failure (whatever was written before it stays in the lines).
*/
export function reported(state: State): RunReport | undefined {
const last = adrOf(state).last
if (last === null) return undefined
const at = last.ok ? 0 : Math.max(0, last.lines.length - 1)
return { label: last.label, ok: last.ok, detail: last.lines[at] ?? '', lines: last.lines.filter((_, index) => index !== at) }
}
/** One event on the Events page and one toast (source console, level info): the ADR said what happened, once. */
export function announce(state: State, host: Pick<Host, 'toast'>, text: string): void {
const line = plain(text, 118)
@@ -237,6 +251,8 @@ export function initSpec(state: State, host: Pick<Host, 'fs' | 'run' | 'invalida
await loadAdrs(state, host)
say(state, host, 'initialise ADRs', problem === null, problem === null ? [`created ${dir}/${first.file}`, 'your project now has an ADR folder; propose the next record from this page'] : [problem])
if (problem === null) announce(state, host, `ADRs initialised: ${dir}/${first.file}`)
return reported(state)
},
}
}
@@ -272,6 +288,8 @@ export function proposeSpec(state: State, host: Pick<Host, 'fs' | 'run' | 'inval
if (problem === null) adrOf(state).selected = name
say(state, host, `propose ADR ${number}`, problem === null, problem === null ? [`created ${dir}/${name}`, 'edit its Context and Decision, then accept it from this page'] : [problem])
if (problem === null) announce(state, host, `ADR ${number} proposed: ${title}`)
return reported(state)
},
}
}
@@ -340,21 +358,22 @@ export async function statusSpec(state: State, host: Pick<Host, 'fs' | 'run' | '
note: `Changes only the lines shown, in ${plan.changes.length} file${plan.changes.length === 1 ? '' : 's'} of your project. A file that changed since this diff was made is left alone.`,
run: async () => {
const done: string[] = []
const failed = (lines: string[]): RunReport | undefined => (say(state, host, `change ADR ${doc.number ?? doc.file}`, false, lines), reported(state))
for (const change of plan.changes) {
const path = abs(state, dir, change.file)
const safe = await checkNoLinks(host.fs, path, { cwd: root(state) }, { allowExisting: true })
if (!safe.ok) return say(state, host, `change ADR ${doc.number ?? doc.file}`, false, [...done, safe.why])
if (!safe.ok) return failed([...done, safe.why])
const now = await host.fs.read(path).catch(() => null)
if (now !== change.before) return say(state, host, `change ADR ${doc.number ?? doc.file}`, false, [...done, `${change.file} changed since the diff was shown: nothing was written to it. Ask again.`])
if (now !== change.before) return failed([...done, `${change.file} changed since the diff was shown: nothing was written to it. Ask again.`])
const result = await host.run(replaceFileArgv(path, true, await writeFlavorReady()), 10_000, change.after).catch(() => null)
const back = await host.fs.read(path).catch(() => null)
if (result === null || result.exitCode !== 0 || back !== change.after) return say(state, host, `change ADR ${doc.number ?? doc.file}`, false, [...done, `${change.file} could not be written as shown`])
if (result === null || result.exitCode !== 0 || back !== change.after) return failed([...done, `${change.file} could not be written as shown`])
done.push(`wrote ${change.file}`)
}
@@ -362,6 +381,8 @@ export async function statusSpec(state: State, host: Pick<Host, 'fs' | 'run' | '
await loadAdrs(state, host)
say(state, host, `change ADR ${doc.number ?? doc.file}`, true, done)
announce(state, host, `ADR ${doc.number ?? doc.file} ${to === 'superseded' && by !== null ? `superseded by ADR ${by.number}` : to}`)
return reported(state)
},
}
}
@@ -143,6 +143,7 @@ export function askActions(state: State, host: Host, runner: Runner, act: () =>
/** Resolves once the ask is queued (after its screen, when a typed question is screened): a model call waits on it so the ask keeps its origin and level (#3815). */
const deliver = (mode: 'visible' | 'aside', question: string | undefined, view: ViewId): void | Promise<void> => {
const byModel = state.control.viaModel
const byCall = state.control.callTag ?? undefined
const typed = plain(question ?? '', MAX_QUESTION).trim()
const fit = checkLimit(typed, LONG_TEXT_MAX, 'the question', 'sent to Claude as one prompt')
@@ -154,6 +155,7 @@ export function askActions(state: State, host: Host, runner: Runner, act: () =>
{
label: `ask Claude about ${labelOf(view)}${mode === 'aside' ? ' (/btw aside)' : ''}`,
byModel,
byCall,
scope: 'ask',
args: [],
shows: `${mode === 'aside' ? '/btw ' : ''}“${plain(typed || VIEW_ASK[view].default, 120)}” with this view’s text as data (secrets removed) — ${prompt.length} characters`,
+16 -5
View File
@@ -238,7 +238,15 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
if (best !== undefined) runner.runEntry(best, best.run.kind === 'text' ? state.palette.query.trim().slice(best.run.keyword.length).trim() : '')
},
run: (id, text = '') => runner.runById(id, text),
run: (id, text = '') => {
const before = state.pending?.id
const isRun = runner.runById(id, text)
// The card this field text raised, by id: Enter again on the same text confirms that card and no other.
state.askedAgain = state.pending !== null && state.pending.id !== before && state.pending.id !== undefined ? { entry: id, text: text.trim(), card: state.pending.id } : null
return isRun
},
costBudgetDraft: text => {
state.costBudgetDraft = text
},
@@ -308,7 +316,7 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
state.terminal.draft = ''
state.terminal.harness = pick.id
// An ask the previous harness left on screen goes with it.
if (state.terminal.asked !== null && state.pending?.label === state.terminal.asked.label) runner.cancel()
if (state.terminal.asked !== null && state.terminal.asked.card !== null && state.pending?.id === state.terminal.asked.card) runner.cancel()
state.terminal.asked = null
host.invalidate()
keepField()
@@ -332,10 +340,11 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
}
// The engine may empty the field on submit, so an empty Enter on a pending ask confirms it too.
if (asked !== null && (asked.key === key || text.trim() === '') && state.pending?.label === asked.label) {
// Enter again answers the card this field raised, by its id: a card with the same words that took its place is not it.
if (asked !== null && asked.card !== null && (asked.key === key || text.trim() === '') && state.pending?.id === asked.card) {
state.terminal.asked = null
state.terminal.draft = ''
void runner.confirm()
void runner.confirm(asked.card)
return
}
@@ -344,8 +353,10 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
// The text is in the pending ask (an empty Enter or Yes runs it): the field clears, unless it cannot be sent and stays to be fixed.
state.terminal.draft = spec !== null ? '' : text
const before = state.pending?.id
runner.ask(spec, whyNotRun(state, text) ?? 'nothing to run')
state.terminal.asked = spec !== null ? { key, label: spec.label } : null
state.terminal.asked = spec !== null ? { key, label: spec.label, card: state.pending !== null && state.pending.id !== before ? (state.pending.id ?? null) : null } : null
},
stop: () => {
for (const run of state.terminal.runs.values()) run.stop()
+6 -3
View File
@@ -16,7 +16,7 @@ export type Intent =
| { kind: 'delegate'; owner: 'ruflo-mods' | 'ruflo-swarm'; words: string }
| { kind: 'palette'; query: string }
| { kind: 'run'; paletteId: string; text: string }
| { kind: 'confirm'; isYes: boolean }
| { kind: 'confirm'; isYes: boolean; /** The card id a typed `yes <id>` names. */ card?: number }
| { kind: 'agent'; who: string }
| { kind: 'back' }
| { kind: 'select'; by: number }
@@ -66,8 +66,11 @@ export function parseRuflo(args: string): Intent {
case 'act':
return second === '' ? { kind: 'palette', query: '' } : { kind: 'run', paletteId: second, text: rest.slice(second.length).trim() }
case 'yes':
case 'y':
return { kind: 'confirm', isYes: true }
case 'y': {
const card = /^#?([0-9]{1,9})$/.exec(second)?.[1]
return card === undefined ? { kind: 'confirm', isYes: true } : { kind: 'confirm', isYes: true, card: Number(card) }
}
case 'no':
case 'n':
return { kind: 'confirm', isYes: false }
+3 -3
View File
@@ -19,7 +19,7 @@ import { markPicture } from './gfx/pictures'
import type { Host } from './host'
import { agentLogs } from './ops'
import { landingRefusal } from './model-tools'
import { createRunner, type Runner } from './runner'
import { createRunner, EXPIRY_TIMER, type Runner } from './runner'
import { advance, loadLedger, mcOf } from './mission-control'
import { hasLiveWork } from './mission-list'
import { loadAllowed } from './remember'
@@ -400,8 +400,8 @@ export function createController(state: State, host: Host): Controller {
state.pane.isShown = false
state.pane.isClosedByPerson = true
persist()
cancel('frames')
cancel('watch')
// A waiting card's expiry timer does not outlive the pane either: past its window it is cleared at the next ask or tool call instead.
for (const name of ['frames', 'watch', EXPIRY_TIMER]) cancel(name)
await host.closePane(PANE_ID).catch(() => undefined)
}
+18 -18
View File
@@ -7,7 +7,7 @@
import { closeOf } from './json-span'
import { failureReason } from './failure'
import { idOf, msOf, numberOf, plain, recordOf, stringOf, valuesOf } from './parse'
import { own } from './safe'
import { countOf, measureOf, own, ratioOf } from './safe'
import { researchProbe } from './research'
import { CLI_PREFIXES, type CliChoice, type State, type ViewId } from '../state'
@@ -118,12 +118,12 @@ export const memoryProbe: Probe<MemoryStats> = {
const entries = recordOf(value.entries)
const stats: MemoryStats = { backend: stringOf(value.backend, 60) ?? 'unknown' }
const total = numberOf(entries?.total)
const vectors = numberOf(entries?.vectors)
const total = countOf(entries?.total)
const vectors = countOf(entries?.vectors)
const storage = stringOf(recordOf(value.storage)?.total, 30)
const oldestMs = msOf(value.oldestEntry)
const newestMs = msOf(value.newestEntry)
const unread = numberOf(recordOf(value.unreadStore)?.rows)
const unread = countOf(recordOf(value.unreadStore)?.rows)
if (total !== undefined) stats.total = total
if (unread !== undefined) stats.unread = unread
@@ -162,7 +162,7 @@ export const namespacesProbe: Probe<Namespaces> = {
const record = recordOf(entry)
const name = stringOf(record?.namespace, 40) ?? '(none)'
const key = stringOf(record?.key, 128)
const size = numberOf(record?.size)
const size = countOf(record?.size)
const atMs = msOf(record?.updatedAt ?? record?.createdAt)
counts.set(name, (counts.get(name) ?? 0) + 1)
@@ -198,7 +198,7 @@ export const scoreProbe: Probe<HarnessScore> = {
}
const score: HarnessScore = { dims }
const costUsd = numberOf(value.estCostPerRunUsd)
const costUsd = measureOf(value.estCostPerRunUsd)
const archetype = stringOf(value.archetype, 40)
const constraints = stringOf(value.hardConstraints, 10)
const atMs = msOf(value.generatedAt)
@@ -232,12 +232,12 @@ export const flywheelProbe: Probe<Flywheel> = {
const flywheel: Flywheel = {
isLedgerValid: ledger.valid === true,
commits: numberOf(ledger.commits) ?? 0,
commits: countOf(ledger.commits) ?? 0,
receipts: Object.keys(recordOf(state?.receiptStates) ?? {}).length,
errors: (Array.isArray(ledger.errors) ? ledger.errors : []).slice(0, 3).map(error => plain(error, 100)),
}
const champion = stringOf(state?.activeChampionRef, 80)
const epoch = numberOf(state?.servingEpoch)
const epoch = countOf(state?.servingEpoch)
if (champion !== undefined) flywheel.champion = champion
if (epoch !== undefined) flywheel.epoch = epoch
@@ -271,7 +271,7 @@ export const auditProbe: Probe<AuditTrend> = {
const record = recordOf(entry)
const atMs = msOf(record?.finishedAt ?? record?.startedAt ?? record?.timestamp ?? record?.generatedAt ?? record?.createdAt ?? recordOf(record?.value)?.generatedAt)
const worst = stringOf(record?.worst ?? recordOf(record?.value)?.worst, 12)
const findings = numberOf(record?.findings ?? recordOf(record?.value)?.findingCount)
const findings = countOf(record?.findings ?? recordOf(record?.value)?.findingCount)
const key = idOf(record?.key) ?? undefined
return atMs === undefined ? [] : [{ atMs, ...(worst !== undefined && { worst }), ...(findings !== undefined && { findings }), ...(key !== undefined && { key }) }]
@@ -279,7 +279,7 @@ export const auditProbe: Probe<AuditTrend> = {
points.sort((a, b) => a.atMs - b.atMs)
return { total: numberOf(value.totalInNamespace) ?? points.length, points }
return { total: countOf(value.totalInNamespace) ?? points.length, points }
},
}
@@ -304,13 +304,13 @@ export const intelligenceProbe: Probe<Intelligence> = {
const sona = recordOf(value.sona)
const router = recordOf(value.modelRouter)
const neural = recordOf(value.neuralRouter)
const routerDecisions = numberOf(router?.totalDecisions)
const routerDecisions = countOf(router?.totalDecisions)
const out: Intelligence = {}
const trajectories = numberOf(sona?.trajectoriesTotal)
const patterns = numberOf(sona?.patternsLearned)
const successRate = numberOf(sona?.successRate)
const moeDecisions = numberOf(recordOf(value.moe)?.routingDecisions)
const ewc = numberOf(recordOf(value.ewc)?.consolidations)
const trajectories = countOf(sona?.trajectoriesTotal)
const patterns = countOf(sona?.patternsLearned)
const successRate = ratioOf(sona?.successRate)
const moeDecisions = countOf(recordOf(value.moe)?.routingDecisions)
const ewc = countOf(recordOf(value.ewc)?.consolidations)
if (trajectories !== undefined) out.trajectories = trajectories
if (patterns !== undefined) out.patterns = patterns
@@ -319,7 +319,7 @@ export const intelligenceProbe: Probe<Intelligence> = {
if (ewc !== undefined) out.ewcConsolidations = ewc
if (routerDecisions !== undefined) out.routerDecisions = routerDecisions
// The tool answers a default confidence before the first decision: only a measured one is kept.
if (routerDecisions !== undefined && routerDecisions > 0 && numberOf(router?.avgConfidence) !== undefined) out.routerConfidence = numberOf(router?.avgConfidence) as number
if (routerDecisions !== undefined && routerDecisions > 0 && ratioOf(router?.avgConfidence) !== undefined) out.routerConfidence = ratioOf(router?.avgConfidence) as number
if (neural !== null) out.neuralRouter = neural.enabled === true ? 'on' : `off (${plain(neural.reason, 40) || 'not enabled'})`
return out
@@ -450,7 +450,7 @@ export const registryProbe: Probe<Registry> = {
const reg = recordOf(value.registration)
const limits = recordOf(reg?.limits)
const limitText = limits === null ? undefined : Object.entries(limits).slice(0, 4).flatMap(([key, n]) => (numberOf(n) === undefined ? [] : [`${plain(key, 16)} ${numberOf(n)}`])).join(' · ')
const limitText = limits === null ? undefined : Object.entries(limits).slice(0, 4).flatMap(([key, n]) => (measureOf(n) === undefined ? [] : [`${plain(key, 16)} ${measureOf(n)}`])).join(' · ')
const out: Registry = {
join: (Array.isArray(value.join) ? value.join : []).slice(0, 6).flatMap(step => (typeof step === 'string' ? [plain(step, 200)] : [])),
channels: (Array.isArray(value.defaultChannels) ? value.defaultChannels : []).slice(0, 8).flatMap(entry => {
+10 -8
View File
@@ -18,7 +18,8 @@
*/
import { jsonAfter } from './cli'
import { readBounded, under, type ReadCache, type ReaderFs } from './files'
import { jsonObject, msOf, numberOf, plain, recordOf, stringOf } from './parse'
import { jsonObject, msOf, plain, recordOf, stringOf } from './parse'
import { countOf, measureOf } from './safe'
export const EVOLVE_FILES = {
flywheel: '.claude-flow/flywheel-v1/transaction-state.json',
@@ -111,7 +112,7 @@ export function parseFlywheel(text: string | null): FlywheelFile | null {
const baseline = refOf(commit.baselineRef)
const receipt = refOf(commit.receiptId)
const epoch = numberOf(commit.servingEpoch)
const epoch = countOf(commit.servingEpoch)
const atMs = msOf(commit.promotedAt)
const proposer = stringOf(commit.proposer, 20)
@@ -119,7 +120,7 @@ export function parseFlywheel(text: string | null): FlywheelFile | null {
})
const champion = refOf(value.activeChampionRef)
const served = refOf(value.servedChampionRef)
const epoch = numberOf(value.servingEpoch)
const epoch = countOf(value.servingEpoch)
const head = refOf(value.ledgerHead)
return { statuses, commits, ...(champion !== undefined && { champion }), ...(served !== undefined && { served }), ...(epoch !== undefined && { epoch }), ...(head !== undefined && { head }) }
@@ -137,7 +138,7 @@ export function parseReceipt(text: string | null): Receipt | null {
const candidate = refOf(payload.candidateId)
const baseline = refOf(payload.baselineRef)
const atMs = msOf(payload.issuedAt)
const lift = numberOf(recordOf(payload.statistics)?.relativeLift)
const lift = measureOf(recordOf(payload.statistics)?.relativeLift)
const signature = recordOf(value.signature)
return {
@@ -153,7 +154,7 @@ export function parseReceipt(text: string | null): Receipt | null {
export function parseGeneration(text: string | null): Generation | null {
const value = jsonObject(text)
const generation = numberOf(value?.generation)
const generation = countOf(value?.generation)
if (value === null || generation === undefined) return null
@@ -183,7 +184,7 @@ export function parseServed(text: string | null): Served | null {
if (value === null) return null
const champion = refOf(value.championHash)
const fromGeneration = numberOf(value.fromGeneration)
const fromGeneration = countOf(value.fromGeneration)
const atMs = msOf(value.servedAt)
return { ...(champion !== undefined && { champion }), ...(fromGeneration !== undefined && { fromGeneration }), ...(atMs !== undefined && { atMs }) }
@@ -215,7 +216,7 @@ export function parseManifest(text: string | null, os: Os): Manifest | null {
const issuedAtMs = msOf(manifest.issuedAt)
const gitCommit = stringOf(manifest.gitCommit, 12)
const branch = stringOf(manifest.branch, 40)
const fixes = numberOf(recordOf(manifest.summary)?.totalFixes) ?? (Array.isArray(manifest.fixes) ? manifest.fixes.length : undefined)
const fixes = countOf(recordOf(manifest.summary)?.totalFixes) ?? (Array.isArray(manifest.fixes) ? manifest.fixes.length : undefined)
return {
os,
@@ -271,7 +272,8 @@ export async function readEvolve(fs: ReaderFs, cache: ReadCache, cwd: string, no
}
}
const count = (value: unknown): number => numberOf(value) ?? 0
/** A count from the CLI's JSON: whole, non-negative and capped, else 0 (#3822). */
const count = (value: unknown): number => countOf(value) ?? 0
/** `metaharness flywheel status`: `{state, ledger: {valid, errors, commits, head}}`, its ledger as checked. */
export function parseLedger(stdout: string, atMs: number): Ledger | null {
@@ -6,7 +6,7 @@
* Declared: discovery and preview. Claude Code writes no approval request into the transcript, so `approvals` is not claimed.
*/
import { repoOf, no, yes, type Capabilities, type HarnessAdapter, type Preview, type ScanEnv, type ScanResult, type SessionRow, type SessionStatus, type Signals } from './harness'
import { isRecord, isTestCommand, scanRecords, shown, str, testLine, timeMs } from './harness-text'
import { believedAt, isRecord, isTestCommand, scanRecords, shown, str, testLine, timeMs } from './harness-text'
import { settle, type Candidate, type Memory } from './harness-track'
import { under } from './files'
@@ -37,6 +37,17 @@ const EDITS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
const FILES_MAX = 8
const ACTIVE_MS = 90_000
const FAIL_QUIET_MS = 30_000
/**
* The two whole results Claude Code writes when the person refuses a tool call at the permission prompt (both read on this machine): the
* refusal sentence alone (optionally with Claude Code's own "Note:" paragraph after it), or the refusal and the person's reply. Matched as that
* structure, never as a prefix: a genuine error that merely quotes the sentence is still a failure.
*/
const REFUSED = "The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file)."
const REFUSED_STOP = `${REFUSED} STOP what you are doing and wait for the user to tell you how to proceed.`
const REFUSED_SAID = `${REFUSED} To tell you how to proceed, the user said:\n`
const isRefusal = (body: string): boolean => body === REFUSED_STOP || body.startsWith(`${REFUSED_STOP}\n\nNote: `) || (body.startsWith(REFUSED_SAID) && body.length > REFUSED_SAID.length)
const resultText = (content: unknown): string => (typeof content === 'string' ? content : Array.isArray(content) ? content.map(part => (isRecord(part) && typeof part.text === 'string' ? part.text : '')).join('\n') : '')
export function summarizeClaude(text: string, id: string): ClaudeSummary {
const out: ClaudeSummary = { cwd: null, branch: null, title: null, idMismatch: false, lastAtMs: null, pendingTool: null, preview: { latest: '', tool: null, files: [], test: null }, signals: { question: false, approval: false, failed: false, turnEndedAtMs: null }, costUsd: null, costPartial: false }
@@ -57,6 +68,9 @@ export function summarizeClaude(text: string, id: string): ClaudeSummary {
if (str(record.gitBranch) !== undefined) out.branch = shown(record.gitBranch, 60)
if ((type === 'assistant' || type === 'user') && at !== undefined) convAtMs = Math.max(convAtMs, at)
// The person typed (a prompt, or an interrupt such as "[Request interrupted by user for tool use]"): whatever failed before is theirs to
// see in their terminal now, and the session waits on them, not on a failure.
if (type === 'user' && isRecord(record.message) && typeof record.message.content === 'string' && record.message.content !== '') afterError = false
if (type === 'ai-title') out.title = shown(record.aiTitle, 80) || out.title
else if (type === 'last-prompt') prompt = shown(record.lastPrompt, 80) || prompt
@@ -74,6 +88,8 @@ export function summarizeClaude(text: string, id: string): ClaudeSummary {
if (line !== '') out.preview.latest = line
afterError = false
} else if (block.type === 'text' && type === 'user') {
afterError = false
} else if (block.type === 'tool_use' && type === 'assistant') {
const name = shown(block.name, 40)
const input = isRecord(block.input) ? block.input : {}
@@ -91,7 +107,10 @@ export function summarizeClaude(text: string, id: string): ClaudeSummary {
afterError = false
} else if (block.type === 'tool_result' && typeof block.tool_use_id === 'string') {
const call = open.get(block.tool_use_id.slice(0, 100))
const failed = block.is_error === true
const body = resultText(block.content)
// A refusal at the permission prompt is the person's decision: is_error is set, but nothing failed. (Esc on it writes a user text
// block after the result, which clears the error below.)
const failed = block.is_error === true && !isRefusal(body)
open.delete(block.tool_use_id.slice(0, 100))
if (call?.name === 'AskUserQuestion') out.signals.question = false
@@ -99,8 +118,6 @@ export function summarizeClaude(text: string, id: string): ClaudeSummary {
lastErrorAtMs = failed ? (at ?? null) : lastErrorAtMs
if (call !== undefined && isTestCommand(call.command)) {
const body = typeof block.content === 'string' ? block.content : Array.isArray(block.content) ? block.content.map(part => (isRecord(part) && typeof part.text === 'string' ? part.text : '')).join('\n') : ''
out.preview.test = `${failed ? 'failed' : 'passed'}${testLine(body) === null ? '' : `: ${testLine(body)}`}`
}
}
@@ -109,6 +126,7 @@ export function summarizeClaude(text: string, id: string): ClaudeSummary {
})
out.signals.failed = afterError && lastErrorAtMs !== null && open.size === 0
out.signals.failedAtMs = out.signals.failed ? lastErrorAtMs : null
out.pendingTool = open.size > 0 ? [...open.values()].map(call => call.name).pop() ?? null : null
out.title = out.title ?? prompt
if (out.pendingTool === null) out.signals.question = false
@@ -149,7 +167,8 @@ export function claudeRow(cand: Candidate, held: { value: ClaudeSummary | null;
stale: held.stale,
external: true,
cost: s === null || s.costUsd === null ? { label: 'unavailable', note: 'the transcript holds no cost entry' } : { label: 'reported', usd: s.costUsd, ...(s.costPartial && { note: 'some models unpriced' }) },
signals: s?.signals ?? { question: false, approval: false, failed: false, turnEndedAtMs: null },
// Times a record claims are held to the file's mtime and the clock (believedAt), so a skewed timestamp cannot pin "seen" in the future.
signals: s === null ? { question: false, approval: false, failed: false, turnEndedAtMs: null } : { ...s.signals, turnEndedAtMs: believedAt(s.signals.turnEndedAtMs, cand.mtimeMs, nowMs), failedAtMs: believedAt(s.signals.failedAtMs, cand.mtimeMs, nowMs) },
preview: s === null ? null : s.preview,
context: [],
noPreview: held.noPreview,
@@ -234,7 +253,7 @@ export function claudeAdapter(): HarnessAdapter & { reset(): void } {
for (const [path, cand] of known) if (!names.has(cand.folder)) known.delete(path)
const tracked = [...known.values()].filter(cand => env.nowMs - cand.mtimeMs < RECENT_MS || cand.mtimeMs === 0).sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, MAX_TRACKED)
const settled = await settle(env.fs, memory, tracked, (text, _whole, cand) => summarizeClaude(text, cand.nativeId))
const settled = await settle(env.fs, memory, tracked, (text, _whole, cand) => summarizeClaude(text, cand.nativeId), env.budget)
for (const path of [...memory.keys()]) if (!known.has(path)) memory.delete(path)
@@ -6,7 +6,7 @@
*/
import { under } from './files'
import { no, yes, repoOf, type Capabilities, type HarnessAdapter, type Preview, type ScanEnv, type ScanResult, type SessionRow, type SessionStatus, type Signals } from './harness'
import { isRecord, scanRecords, shown, str, timeMs } from './harness-text'
import { believedAt, isRecord, scanRecords, shown, str, timeMs } from './harness-text'
import { settle, type Candidate, type Memory } from './harness-track'
export const CODEX_CAPS: Capabilities = {
@@ -46,17 +46,23 @@ export function summarizeCodex(text: string, whole = true): CodexSummary {
out.open = true
out.signals.turnEndedAtMs = null
out.signals.failed = false
out.signals.failedAtMs = null
} else if (type === 'event_msg' && kind === 'task_complete') {
out.open = false
out.signals.turnEndedAtMs = at ?? out.signals.turnEndedAtMs
out.signals.failed = false
out.signals.failedAtMs = null
const last = shown(payload.last_agent_message, 600)
if (last !== '') out.preview.latest = last
} else if (type === 'event_msg' && kind === 'turn_aborted') {
// "interrupted" is the person pressing Esc (every abort in the rollouts read here): their choice, so the session is idle, not failed.
const interrupted = str(payload.reason) === 'interrupted'
out.open = false
out.signals.failed = true
out.signals.failed = !interrupted
out.signals.failedAtMs = interrupted ? null : (at ?? null)
out.preview.latest = `turn aborted${str(payload.reason) === undefined ? '' : `: ${shown(payload.reason, 60)}`}`
} else if (type === 'response_item' && (kind === 'function_call' || kind === 'custom_tool_call') && typeof payload.call_id === 'string') {
calls.set(payload.call_id.slice(0, 100), shown(payload.name, 40))
@@ -71,11 +77,13 @@ export function summarizeCodex(text: string, whole = true): CodexSummary {
const idOfName = (name: string): string | undefined => /^rollout-.{1,40}?-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/.exec(name)?.[1]
const ACTIVE_MS = 90_000
/** As for Claude (ADR-486 §2.3): an abort is a failure only when nothing followed it for this long. */
const FAIL_QUIET_MS = 30_000
const DAYS = 14
const MAX_TRACKED = 60
const statusOf = (s: CodexSummary, mtimeMs: number, nowMs: number): SessionStatus => {
if (s.signals.failed) return 'failed'
if (s.signals.failed && nowMs - mtimeMs >= FAIL_QUIET_MS) return 'failed'
if (s.open && nowMs - mtimeMs < ACTIVE_MS * 4) return 'working'
return s.signals.turnEndedAtMs !== null ? 'done' : 'idle'
@@ -119,7 +127,7 @@ export function codexRow(cand: Candidate, held: { value: CodexSummary | null; no
stale: held.stale,
external: true,
cost: { label: 'unavailable', note: 'rollouts carry token counts, not dollars' },
signals: s?.signals ?? { question: false, approval: false, failed: false, turnEndedAtMs: null },
signals: s === null ? { question: false, approval: false, failed: false, turnEndedAtMs: null } : { ...s.signals, turnEndedAtMs: believedAt(s.signals.turnEndedAtMs, cand.mtimeMs, nowMs), failedAtMs: believedAt(s.signals.failedAtMs, cand.mtimeMs, nowMs) },
preview: s === null ? null : s.preview,
context: [],
noPreview: held.noPreview,
@@ -176,7 +184,7 @@ export function codexAdapter(): HarnessAdapter & { reset(): void } {
}
const tracked = [...known.values()].sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, MAX_TRACKED)
const settled = await settle(env.fs, memory, tracked, (text, whole) => summarizeCodex(text, whole))
const settled = await settle(env.fs, memory, tracked, (text, whole) => summarizeCodex(text, whole), env.budget)
for (const path of [...memory.keys()]) if (!known.has(path)) memory.delete(path)
@@ -12,19 +12,47 @@ export const TAIL_BYTES = 262_144
export const LINE_CAP = 400_000
export const MAX_LINES = 30_000
export type Window = { text: string; whole: boolean } | { text: null; reason: 'missing' | 'refused' | 'not-regular' | 'too-large' }
export type Window = { text: string; whole: boolean; bytes: number } | { text: null; reason: 'missing' | 'refused' | 'not-regular' | 'too-large' }
/** The text one session file can be summarised from, given its size from a stat that already ruled out links. Never reads what the host cannot bound. */
export async function readWindow(fs: SessionFs, path: string, size: number): Promise<Window> {
/**
* What reading this file reserves from the pass's budget, before it is read: the whole file (plus the one byte that tells a whole read from a
* grown one), the tail window, or nothing when the host cannot bound the read and it is not attempted.
*/
export const readCost = (fs: SessionFs, size: number): number => (size <= READ_MAX ? size + 1 : fs.readTail === undefined ? 0 : TAIL_BYTES)
/** The last lines of a tail: the first line starts somewhere inside a line, so it is dropped, never parsed. */
const tailText = (read: string): string => {
const tail = read.slice(-TAIL_BYTES)
const cut = tail.indexOf('\n')
return cut < 0 ? '' : tail.slice(cut + 1)
}
/**
* The text one session file can be summarised from, given its size from a stat that already ruled out links, reading at most `limit` bytes
* where the host can bound a read (`readTail`): a file that grew past its stat since is read as a tail, never pulled whole. Without `readTail`
* a whole read is bounded by the size it was stat-ed at and by the engine's 4 MiB refusal, nothing else.
*/
export async function readWindow(fs: SessionFs, path: string, size: number, limit: number = Number.POSITIVE_INFINITY): Promise<Window> {
try {
if (size <= READ_MAX) return { text: (await fs.read(path)).slice(0, READ_MAX), whole: true }
if (size <= READ_MAX) {
if (fs.readTail !== undefined && Number.isFinite(limit)) {
const want = Math.max(1, Math.min(READ_MAX + 1, limit))
const read = await fs.readTail(path, want)
// Shorter than asked for: that is the whole file. Otherwise it grew past what this pass may read, and only its tail is used.
return read.length < want ? { text: read, whole: true, bytes: read.length } : { text: tailText(read), whole: false, bytes: read.length }
}
const whole = await fs.read(path)
return { text: whole.slice(0, READ_MAX), whole: true, bytes: whole.length }
}
if (fs.readTail === undefined) return { text: null, reason: 'too-large' }
const tail = (await fs.readTail(path, TAIL_BYTES)).slice(-TAIL_BYTES * 2)
const cut = tail.indexOf('\n')
const read = await fs.readTail(path, Math.min(TAIL_BYTES, limit))
// The first line of a window starts somewhere inside a line: it is dropped, never parsed.
return { text: cut < 0 ? '' : tail.slice(cut + 1), whole: false }
return { text: tailText(read), whole: false, bytes: read.length }
} catch {
return { text: null, reason: 'refused' }
}
@@ -73,6 +101,19 @@ export const timeMs = (value: unknown): number | undefined => {
return Number.isFinite(ms) && ms > 946_684_800_000 && ms < 8.64e15 ? ms : undefined
}
/** How far ahead of the clock a recorded time may be before it is not believed (clock skew between processes, not years). */
export const FUTURE_SLACK_MS = 300_000
/**
* A time a record claims, held to what the file can vouch for: never after the file was last written, never more than FUTURE_SLACK_MS ahead
* of now. A far-future timestamp would otherwise be stored as "seen" and silence every later event of that session.
*/
export const believedAt = (ms: number | null | undefined, mtimeMs: number, nowMs: number): number | null => {
if (ms === null || ms === undefined || !Number.isFinite(ms)) return null
return Math.min(ms, nowMs + FUTURE_SLACK_MS, mtimeMs > 0 ? mtimeMs : Number.POSITIVE_INFINITY)
}
/** A test runner's summary line in a tool's output, found without a backtracking pattern. Null when none is there. */
export function testLine(output: string): string | null {
const lines = output.slice(-6000).split('\n')
+105 -38
View File
@@ -3,23 +3,53 @@
* it is read again only when its size or mtime changed. A read that fails keeps the earlier summary and says so (stale), never a blank row.
* One pass reads at most PASS_BYTES; what does not fit waits for the next pass, which is how 20 busy sessions stay inside a tick.
*/
import { readWindow } from './harness-text'
import { readCost, readWindow } from './harness-text'
import type { SessionFs } from './harness'
export type Candidate = { path: string; nativeId: string; folder: string; size: number; mtimeMs: number }
export type Held<S> = { mtimeMs: number; size: number; value: S | null; noPreview: string | null; stale: string | null; whole: boolean }
/**
* `readSeq`: when this file was last read, in reads across the process, so the least recently read changed file goes first next pass.
* `pending` and `firstSeen`: a file that has never been read (it did not fit a pass) is remembered with when it was first seen, so never-read
* files are read first come, first served, and a stream of newer files cannot keep an older one waiting.
*/
export type Held<S> = { mtimeMs: number; size: number; value: S | null; noPreview: string | null; stale: string | null; whole: boolean; readSeq?: number; pending?: boolean; firstSeen?: number }
export type Memory<S> = Map<string, Held<S>>
/**
* One workspace pass's read allowance, shared by every adapter in it (ADR-486 §2.4: a pass reads at most 12 MB, not 12 MB per harness).
* `turn` serialises reads across adapters, so a reservation and its charge are never interleaved with another adapter's; `stopped` ends the
* pass's reads once one read came back larger than it reserved (the file grew since its stat), so that overrun is never compounded.
*/
export type PassBudget = { left: number; stopped: boolean; turn: Promise<void> }
export const PASS_BYTES = 12_000_000
export const passBudget = (): PassBudget => ({ left: PASS_BYTES, stopped: false, turn: Promise.resolve() })
const CONCURRENCY = 8
let readSeq = 0
let seenSeq = 0
/** Waits for the pass's previous read (from any adapter) to finish; the returned function lets the next one go. */
async function myTurn(budget: PassBudget): Promise<() => void> {
const before = budget.turn
let release: () => void = () => undefined
budget.turn = new Promise<void>(resolve => (release = resolve))
await before
return release
}
const WHY: Record<string, string> = { 'too-large': 'transcript is larger than this host can read', refused: 'the host refused the read', missing: 'file is gone', 'not-regular': 'not a regular file' }
export async function settle<S>(fs: SessionFs, memory: Memory<S>, cands: readonly Candidate[], summarize: (text: string, whole: boolean, cand: Candidate) => S): Promise<{ cand: Candidate; held: Held<S> }[]> {
const out: { cand: Candidate; held: Held<S> }[] = []
let budget = PASS_BYTES
/**
* Stats every candidate (concurrently), then reads the changed ones one at a time against the shared budget: one at a time so a file that grew
* since its stat can overrun the pass by at most its own growth (none where the host bounds reads), and least recently read first, so files
* that change on every pass cannot starve the rest; each changed file is read within ceil(changed / per-pass) passes.
*/
export async function settle<S>(fs: SessionFs, memory: Memory<S>, cands: readonly Candidate[], summarize: (text: string, whole: boolean, cand: Candidate) => S, budget: PassBudget = passBudget()): Promise<{ cand: Candidate; held: Held<S> }[]> {
const slots: ({ cand: Candidate; held: Held<S> } | null | undefined)[] = cands.map(() => undefined)
const toRead: { i: number; cand: Candidate; before: Held<S> | undefined }[] = []
const one = async (cand: Candidate): Promise<void> => {
const look = async (cand: Candidate, i: number): Promise<void> => {
let stat: Awaited<ReturnType<SessionFs['stat']>>
try {
@@ -30,56 +60,93 @@ export async function settle<S>(fs: SessionFs, memory: Memory<S>, cands: readonl
if (stat === undefined) {
memory.delete(cand.path)
slots[i] = null
return
}
const before = memory.get(cand.path)
const size = stat.size ?? cand.size
const mtimeMs = stat.mtimeMs ?? cand.mtimeMs
const now = { ...cand, size: stat.size ?? cand.size, mtimeMs: stat.mtimeMs ?? cand.mtimeMs }
if (stat.isLink === true || (stat.kind !== undefined && stat.kind !== 'file')) {
const held: Held<S> = { mtimeMs, size, value: null, noPreview: WHY['not-regular'] as string, stale: null, whole: false }
const held: Held<S> = { mtimeMs: now.mtimeMs, size: now.size, value: null, noPreview: WHY['not-regular'] as string, stale: null, whole: false }
memory.set(cand.path, held)
out.push({ cand: { ...cand, size, mtimeMs }, held })
slots[i] = { cand: now, held }
return
}
if (before !== undefined && before.mtimeMs === mtimeMs && before.size === size && before.stale === null) {
out.push({ cand: { ...cand, size, mtimeMs }, held: before })
if (before !== undefined && before.pending !== true && before.mtimeMs === now.mtimeMs && before.size === now.size && before.stale === null) {
slots[i] = { cand: now, held: before }
return
}
// A file that fits no more of this pass keeps its earlier summary (or none) until the next pass.
const cost = Math.min(size, 300_000)
if (budget - cost < 0) {
// Not remembered, so the next pass reads it: the row says it has not been read yet instead of waiting silently.
const held: Held<S> = before === undefined ? { mtimeMs, size, value: null, noPreview: 'not read yet: the pass reached its read budget', stale: null, whole: false } : { ...before, stale: before.stale ?? 'newer than the last read' }
if (before !== undefined) memory.set(cand.path, held)
out.push({ cand: { ...cand, size, mtimeMs }, held })
return
}
budget -= cost
const window = await readWindow(fs, cand.path, size)
let held: Held<S>
if (window.text !== null) held = { mtimeMs, size, value: summarize(window.text, window.whole, { ...cand, size, mtimeMs }), noPreview: null, stale: null, whole: window.whole }
else if (before?.value !== undefined && before.value !== null) held = { ...before, mtimeMs, size, stale: `read failed: ${WHY[window.reason] ?? window.reason}` }
else held = { mtimeMs, size, value: null, noPreview: WHY[window.reason] ?? window.reason, stale: null, whole: false }
memory.set(cand.path, held)
out.push({ cand: { ...cand, size, mtimeMs }, held })
toRead.push({ i, cand: now, before })
}
for (let i = 0; i < cands.length; i += CONCURRENCY) await Promise.all(cands.slice(i, i + CONCURRENCY).map(cand => one(cand).catch(() => undefined)))
for (let i = 0; i < cands.length; i += CONCURRENCY) await Promise.all(cands.slice(i, i + CONCURRENCY).map((cand, j) => look(cand, i + j).catch(() => (slots[i + j] = null))))
return out
// A file seen for the first time gets its place in the never-read line now (newest of this batch first; every earlier batch before it).
const firstSeenOf = new Map<string, number>()
for (const job of [...toRead].filter(job => job.before === undefined).sort((a, b) => b.cand.mtimeMs - a.cand.mtimeMs)) firstSeenOf.set(job.cand.path, (seenSeq += 1))
const firstSeen = (job: (typeof toRead)[number]) => job.before?.firstSeen ?? firstSeenOf.get(job.cand.path) ?? 0
const neverRead = (job: (typeof toRead)[number]) => job.before?.readSeq === undefined
// Never-read files first, first come first served; then the rest, least recently read first.
toRead.sort((a, b) => Number(neverRead(b)) - Number(neverRead(a)) || (neverRead(a) ? firstSeen(a) - firstSeen(b) : (a.before?.readSeq ?? 0) - (b.before?.readSeq ?? 0)))
for (const job of toRead) {
const { i, cand, before } = job
const { size, mtimeMs } = cand
const cost = readCost(fs, size)
const release = await myTurn(budget)
let window: Awaited<ReturnType<typeof readWindow>> | null = null
try {
if (!budget.stopped && cost <= budget.left) {
// Reserved before the read, against the one shared budget, while no other adapter is reading.
budget.left -= cost
try {
window = await readWindow(fs, cand.path, size, budget.left + cost)
} catch {
window = { text: null, reason: 'refused' }
}
const bytes = window.text === null ? 0 : window.bytes
// Charged what was actually read: the unused reservation goes back. A read larger than its reservation (the file grew since its
// stat, on a host with no bounded read) is charged and ends this pass's reads, so one file's growth is the most a pass can overrun.
budget.left += cost - bytes
if (bytes > cost) budget.stopped = true
}
} finally {
release()
}
if (window === null) {
// Remembered with its place in line, so a later pass reads it before newer files: the row says it has not been read yet.
const held: Held<S> = before === undefined || before.pending === true ? { mtimeMs, size, value: null, noPreview: 'not read yet: the pass reached its read budget', stale: null, whole: false, pending: true, firstSeen: firstSeen(job) } : { ...before, stale: before.stale ?? 'newer than the last read' }
memory.set(cand.path, held)
slots[i] = { cand, held }
continue
}
let held: Held<S>
readSeq += 1
if (window.text !== null) held = { mtimeMs, size, value: summarize(window.text, window.whole, cand), noPreview: null, stale: null, whole: window.whole, readSeq }
else if (before?.value !== undefined && before.value !== null) held = { ...before, mtimeMs, size, stale: `read failed: ${WHY[window.reason] ?? window.reason}`, readSeq }
else held = { mtimeMs, size, value: null, noPreview: WHY[window.reason] ?? window.reason, stale: null, whole: false, readSeq }
memory.set(cand.path, held)
slots[i] = { cand, held }
}
return slots.filter((slot): slot is { cand: Candidate; held: Held<S> } => slot !== null && slot !== undefined)
}
@@ -3,6 +3,7 @@
* says, per capability, whether it can do that and why not. An action a harness has not declared stays unavailable; nothing is inferred.
* Discovery is local and read-only: it makes no model call, spawns no process and wakes no agent.
*/
import type { PassBudget } from './harness-track'
import type { ReaderFs } from './files'
export const HARNESS_IDS = ['claude', 'codex', 'ruflo'] as const
@@ -39,6 +40,8 @@ export type Signals = {
approval: boolean
/** The last tool failed and nothing followed it. */
failed: boolean
/** When the failure was recorded, from the failing record's own timestamp: a later metadata line (title, cost) does not make it new. */
failedAtMs?: number | null
/** The last turn finished at this time. */
turnEndedAtMs: number | null
}
@@ -92,6 +95,8 @@ export type ScanEnv = {
nowMs: number
/** Relist everything (slow pass); otherwise only what changed and the recently active files. */
full: boolean
/** The pass's read allowance, shared by every adapter in the pass (data/harness-track.ts); a fresh one per scan when absent. */
budget?: PassBudget
}
export interface HarnessAdapter {
@@ -0,0 +1,81 @@
/**
* One run of `ruflo mcp exec -t <tool> -p <json>`, read as Mission Control's create chain needs it. Pure: no `$`.
*
* What the CLI prints (captured from ruflo 3.56.1, commands/mcp.ts and mcp-client.ts):
* stderr `[INFO] Executing tool: <tool>`, and on a failure `[ERROR] Tool execution failed: Failed to execute MCP tool '<tool>': <cause>`
* stdout ` Parameters: {…the input…}`, then on success `[OK] Tool executed in …`, a line `Result:` and the answer as JSON
* A failure prints no `Result:` line, so the Parameters object is the only JSON on stdout: it is never read as the answer.
*/
import { closeOf } from './json-span'
import { errorLine, failureReason } from './failure'
import { plain, recordOf } from './parse'
/** The cause the policy runtime throws when it could not take `.claude-flow/policy/state.lock` in time (#3164, #3892). */
export const LOCK_TIMEOUT = 'policy-state-lock-timeout'
const ANSI = /\x1b\[[0-9;]*m/g
const RESULT_LINE = /^Result:[ \t]*$/m
/** The text after the CLI's own `Result:` line (a line of its own, so a parameter that holds "Result:" is not it), or null when there is none. */
export function afterResult(stdout: string): string | null {
const text = stdout.replace(ANSI, '')
const marker = RESULT_LINE.exec(text)
return marker === null ? null : text.slice(marker.index + marker[0].length)
}
/** The JSON object the tool answered (after `Result:`), strings and their brackets skipped, or null when it answered none. */
export function resultOf(stdout: string): Record<string, unknown> | null {
const tail = afterResult(stdout)
const start = tail === null ? -1 : tail.search(/[{[]/)
if (tail === null || start < 0) return null
const end = closeOf(tail, start)
if (end < 0) return null
try {
return recordOf(JSON.parse(tail.slice(start, end + 1)))
} catch {
return null
}
}
/** One run read: the tool's answer (null when none), whether it is the success the step needs, whether trying again may help, and why not. */
export type Attempt = { result: Record<string, unknown> | null; ok: boolean; transient: boolean; reason: string }
/** The CLI's cause, its two wrappers dropped ("Tool execution failed: Failed to execute MCP tool 'x': <cause>"). */
const causeOf = (line: string): string => line.replace(/^Tool execution failed:\s*/i, '').replace(/^Failed to execute MCP tool '[^']*':\s*/i, '').trim()
/** What one try came to: the process's output, a rejection from the host (it could not start, or was refused), or the caller's own time limit. */
export type RunRead = { exitCode: number; stdout: string; stderr: string } | { error: unknown } | { timedOutMs: number }
/**
* Reads one run of `mcp exec`. `isDone` judges the tool's parsed answer by its own keys (never a substring of the output, which quotes the
* person's text). Transient, and only then, when:
* - the CLI's cause is exactly `policy-state-lock-timeout` (thrown before the tool runs, so nothing was written),
* - the caller's own time limit ended the wait (`timedOutMs`, a structured signal, never a message), or
* - the process exited non-zero with stdout and stderr both empty.
* Any answer, any other error line (a refusal that mentions a timeout, `command not found`), and any rejection of the host (a command that
* could not start, an approval that was refused or timed out) are definite.
*/
export function readAttempt(run: RunRead, isDone: (result: Record<string, unknown>) => boolean): Attempt {
if ('timedOutMs' in run) return { result: null, ok: false, transient: true, reason: `no answer in ${Math.round(run.timedOutMs / 1000)} s; the CLI process may still finish (check \`ruflo task list\`)` }
if ('error' in run) return { result: null, ok: false, transient: false, reason: `the CLI could not be run: ${plain(run.error instanceof Error ? run.error.message : String(run.error), 140) || 'no reason given'}` }
const result = resultOf(run.stdout)
if (result !== null) {
const ok = run.exitCode === 0 && isDone(result)
const tail = afterResult(run.stdout) ?? ''
return { result, ok, transient: false, reason: ok ? '' : plain(failureReason({ stdout: tail }) || String(result.message ?? '') || 'the tool answered without the expected result', 160) }
}
const cause = plain(causeOf(errorLine(run.stderr) ?? errorLine(run.stdout) ?? ''), 160)
const silent = run.exitCode !== 0 && run.stdout.trim() === '' && run.stderr.trim() === ''
const said = cause || plain(run.stderr.split('\n').map(line => line.trim()).filter(line => line !== '').pop() ?? '', 160)
return { result: null, ok: false, transient: cause === LOCK_TIMEOUT || silent, reason: said === '' ? `no answer (exit ${run.exitCode})` : said }
}
+5 -3
View File
@@ -5,7 +5,8 @@
* validated, never from typed text. Read-only: the section stores and starts nothing.
*/
import type { Probe } from './cli'
import { jsonObject, msOf, numberOf, recordOf, stringOf } from './parse'
import { jsonObject, msOf, recordOf, stringOf } from './parse'
import { measureOf } from './safe'
import type { State } from '../state'
@@ -63,8 +64,9 @@ export function parseResearch(stdout: string): ResearchRecord[] | null {
if (record === null || question === undefined) return []
const findings = (Array.isArray(record.findings) ? record.findings : []).slice(0, MAX_FINDINGS)
const spent = numberOf(record.spentUsd)
const cap = numberOf(record.capUsd)
// Dollars are bounded where they are read: `1e300` would draw "$1e+300" (#3822).
const spent = measureOf(record.spentUsd)
const cap = measureOf(record.capUsd)
const status = typeof record.status === 'string' && STATUSES.includes(record.status) ? (record.status as ResearchRecord['status']) : 'unknown'
return [{
+3
View File
@@ -17,6 +17,9 @@ export const isoOf = (value: unknown): string => (typeof value === 'number' && N
/** A whole, non-negative count capped at MAX_COUNT, else undefined (a negative, fractional-hostile, NaN or infinite value is not a count). */
export const countOf = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.min(Math.floor(value), MAX_COUNT) : undefined)
/** A signed measurement (a score, a lift, a latency, a percentage) that is finite and within ±MAX_COUNT, else undefined: never "Infinity" or "1e+300" on screen (#3822). */
export const measureOf = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) && Math.abs(value) <= MAX_COUNT ? value : undefined)
/** A ratio clamped to 0..1, else undefined. */
export const ratioOf = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : undefined)
@@ -6,6 +6,7 @@
* An unassigned row raises nothing: its identity is in doubt.
*/
import { ATTENTION_KINDS, type AttentionKind, type SessionRow } from './harness'
import { FUTURE_SLACK_MS } from './harness-text'
export type Viewed = { baselineMs: number; seen: Record<string, number> }
export const SEEN_MAX = 500
@@ -25,10 +26,26 @@ export function viewedOf(raw: unknown, nowMs: number): Viewed {
const seen: Record<string, number> = {}
if (typeof value.seen === 'object' && value.seen !== null) {
for (const [key, stamp] of Object.entries(value.seen).slice(0, SEEN_MAX)) if (typeof stamp === 'number' && Number.isFinite(stamp)) seen[key.slice(0, 300)] = stamp
// A stamp in the future (stored from a skewed timestamp before times were held to the clock) would silence its session forever: dropped.
for (const [key, stamp] of Object.entries(value.seen).slice(0, SEEN_MAX)) if (typeof stamp === 'number' && Number.isFinite(stamp) && stamp <= nowMs + FUTURE_SLACK_MS) seen[key.slice(0, 300)] = stamp
}
return { baselineMs: typeof value.baselineMs === 'number' && Number.isFinite(value.baselineMs) ? value.baselineMs : nowMs, seen }
// A baseline in the future would make every completion until then "history": it is held to now.
return { baselineMs: typeof value.baselineMs === 'number' && Number.isFinite(value.baselineMs) ? Math.min(value.baselineMs, nowMs) : nowMs, seen }
}
/** Whether the stored value differs from what `viewedOf` made of it (not a Viewed, or a stamp dropped or held): the store needs the repaired one. */
export function needsRewrite(raw: unknown, viewed: Viewed): boolean {
if (typeof raw !== 'object' || raw === null) return true
const value = raw as { baselineMs?: unknown; seen?: unknown }
const seen = typeof value.seen === 'object' && value.seen !== null ? (value.seen as Record<string, unknown>) : null
if (value.baselineMs !== viewed.baselineMs || seen === null) return true
const keys = Object.keys(viewed.seen)
return Object.keys(seen).length !== keys.length || keys.some(key => seen[key] !== viewed.seen[key])
}
const seenKey = (rowKey: string, kind: AttentionKind) => `${rowKey}|${kind}`
@@ -45,9 +62,19 @@ export function attentionOf(rows: readonly SessionRow[], viewed: Viewed, pending
if (row.signals.approval) add('needs-approval', row.updatedMs)
if (row.signals.question) add('question', row.updatedMs)
if (row.signals.failed && Math.max(1, row.updatedMs) > (viewed.seen[seenKey(row.key, 'failed')] ?? 0)) add('failed', Math.max(1, row.updatedMs))
// A time is never believed past the row's own last write (the adapters also hold it to the clock: harness-text.ts believedAt), so nothing
// stored as seen can sit in the future and silence the session.
const held = (ms: number): number => Math.max(1, Math.min(ms, row.updatedMs > 0 ? row.updatedMs : Number.POSITIVE_INFINITY))
const ended = row.signals.turnEndedAtMs
// Failed is the adapter's verdict (status), which waits out the quiet period, not the raw signal; it is keyed on when the failure was
// recorded, so a title or cost line appended later does not bring a seen failure back.
if (row.signals.failed && row.status === 'failed') {
const at = held(row.signals.failedAtMs ?? row.updatedMs)
if (at > (viewed.seen[seenKey(row.key, 'failed')] ?? 0)) add('failed', at)
}
const ended = row.signals.turnEndedAtMs === null ? null : held(row.signals.turnEndedAtMs)
if (ended !== null && ended >= viewed.baselineMs && ended > (viewed.seen[seenKey(row.key, 'completed-unread')] ?? 0) && !row.signals.question) add('completed-unread', ended)
}
+1 -1
View File
@@ -32,7 +32,7 @@ export type SkillsState = {
createDraft: string
/** The change running now (its label), and the create the last Enter asked about: Enter on it again confirms. */
busy: string | null
asked: { key: string; label: string } | null
asked: { key: string; label: string; card: number | null } | null
/** How the last change went, kept for the view after the footer lets it go. */
last: Outcome | null
/** Where ▸ add and ▸ update all go: the scope, and the agents named to `--agent` (none: the CLI's own pick). */
@@ -67,3 +67,20 @@ export const membersText = (status: Pick<SwarmStatus, 'listed' | 'found'>): stri
/** The record's status as a run state, so Workflows says what Overview says; null for a status it does not know. */
export const swarmRunState = (status: SwarmStatus): 'failed' | 'active' | 'stalled' | 'finished' | null =>
/fail|error/i.test(status.status) ? 'failed' : /^running$|active/i.test(status.status) ? (status.isStale ? 'stalled' : 'active') : /terminat|stop|shut|complete|done|finish/i.test(status.status) ? 'finished' : null
/**
* The agents with evidence of being here now, by the same rule as a swarm's staleness: busy now, created within SWARM_STALE_MS, or seen to
* change status since `fromMs` (the console logs the first status it sees for every agent, so one entry alone is not activity). The agent store
* keeps every agent ever spawned; without this, weeks-old idle records read as present.
*/
export function presentAgents(agents: readonly AgentRecord[], log: ReadonlyMap<string, readonly { atMs: number; status: string }[]>, fromMs: number, nowMs: number): AgentRecord[] {
return uniqueAgents(agents).filter(agent => {
if (BUSY.test(agent.status) || /working/i.test(agent.status)) return true
const created = sinceOf(agent.createdAtMs, nowMs)
if (created !== undefined && nowMs - created <= SWARM_STALE_MS) return true
return (log.get(agent.id) ?? []).some((entry, i) => i > 0 && entry.atMs >= fromMs)
})
}
+5 -1
View File
@@ -130,6 +130,9 @@ export async function dispatch(control: Controller, state: State, args: string,
if (state.pending !== null) {
const pending = state.pending
// The answer puts this card in front of the person, so a bare /ruflo yes may answer it (and only it).
state.shownCard = pending.id ?? null
return { text: [`Asked: ${pending.label}. Confirm with /ruflo yes (or y in the pane), cancel with /ruflo no.`, ...(pending.shows === undefined ? [] : [`runs: ${pending.shows}`, pending.note ?? ''])].filter(Boolean).join('\n') }
}
@@ -146,7 +149,8 @@ export async function dispatch(control: Controller, state: State, args: string,
const confirmedAtMs = Date.now()
await control.runner.confirm()
// A typed yes names no card: the runner refuses it while the card is too new or just replaced one (press the card's own Yes then).
await control.runner.confirmUnbound(intent.card)
return { text: xruvAnswer(state, null, confirmedAtMs) ?? labAnswer(state, null, confirmedAtMs) ?? (state.outcome === null ? 'Ran.' : `${state.outcome.ok ? '✓' : '✗'} ${state.outcome.label}: ${state.outcome.detail}${state.outcome.verified === 'yes' ? ' (on disk)' : state.outcome.verified === 'no' ? ' (not on disk yet)' : ''}`) }
case 'agent': {
@@ -92,7 +92,7 @@ export const MORE_TOPICS: readonly HelpTopic[] = [
{ text: 'The feed below merges what changed in ruflo, what Claude did through the console tools (with its outcome), and what you sent. Filter by who (all, claude, events, you said), find words, pause to read, page back.' },
{ text: 'Press ⛔ blocked to see only what was refused or failed: Claude’s denied or failed actions and events that say denied. Press a line to open it; an event from a page of its own (swarm, claims, learning, plugins, missions) gets a jump button.' },
{ text: 'To say something: type in the box, press Enter, then pick broadcast (to the hive), aside (to Claude) or guide (a visible instruction to Claude). Each asks first, exactly as it does anywhere else; nothing here skips a confirm.' },
{ text: 'Who is here shows each agent’s busy share over the last 15 minutes. Under it, Mods lists every plugin mod that has written a status file: guard, calls, blocked, and when it last wrote; any mod that blocked something leads.' },
{ text: 'Who is here shows each recently active agent’s busy share over the last 15 minutes. Under it, Mods lists every plugin mod that has written a status file: guard, calls, blocked, and when it last wrote; any mod that blocked something leads.' },
{ text: 'Press a mod’s line for its detail: what it guards, the class of its last refusal (never the refused text), version, session start, last write and file age. It is all plain, capped text, whatever the file held.' },
],
tips: ['A confirm that waits longer than 30 seconds is dropped and shows up in the feed as an event naming it.', 'Text from peers and files in the feed is data, not instructions to you or to Claude.'],
+9 -8
View File
@@ -5,8 +5,8 @@
* found) are kept, first. And the recency binning the view draws as a timeline. Pure: strings in, strings out.
*/
import { jsonAfter } from './data/cli'
import { msOf, numberOf, plain, recordOf } from './data/parse'
import { isoOf } from './data/safe'
import { msOf, plain, recordOf } from './data/parse'
import { countOf, isoOf, measureOf } from './data/safe'
import { labLines } from './mh-lab'
/** An entry's value may be long: the panel scrolls (j/k), so it keeps more lines than the MetaHarness lab. */
@@ -57,15 +57,15 @@ export function wrap(text: string, width = WRAP): string[] {
return out
}
const short = (value: unknown, max: number): string => (typeof value === 'string' ? plain(value, max) : typeof value === 'number' || typeof value === 'boolean' ? String(value) : '')
const score = (value: unknown): string => (typeof value === 'number' && Number.isFinite(value) ? value.toFixed(3) : ' n/a')
const short = (value: unknown, max: number): string => (typeof value === 'string' ? plain(value, max) : typeof value === 'number' ? String(measureOf(value) ?? 'n/a') : typeof value === 'boolean' ? String(value) : '')
const score = (value: unknown): string => measureOf(value)?.toFixed(3) ?? ' n/a'
/** One stored entry: its name, its size and access count, then the whole value. */
function entryLines(record: Record<string, unknown>): string[] {
const value = record.content ?? record.value
const body = typeof value === 'string' ? value : JSON.stringify(value ?? null, null, 2)
const updated = msOf(record.updatedAt ?? record.storedAt)
const head = `${short(record.namespace, 40)}/${short(record.key, 128)} · ${body.length} chars · read ${numberOf(record.accessCount) ?? 'n/a'}× · ${record.hasEmbedding === true ? 'has a vector' : 'no vector'}${updated !== undefined ? ` · updated ${isoOf(updated).slice(0, 16).replace('T', ' ')}` : ''}`
const head = `${short(record.namespace, 40)}/${short(record.key, 128)} · ${body.length} chars · read ${countOf(record.accessCount) ?? 'n/a'}× · ${record.hasEmbedding === true ? 'has a vector' : 'no vector'}${updated !== undefined ? ` · updated ${isoOf(updated).slice(0, 16).replace('T', ' ')}` : ''}`
return [head, ...(Array.isArray(record.tags) && record.tags.length > 0 ? [`tags: ${record.tags.map(tag => short(tag, 24)).join(', ')}`] : []), '', ...wrap(body)]
}
@@ -101,7 +101,7 @@ function listLines(rows: unknown[]): string[] {
...entries.slice(0, 60).map(row => {
const at = msOf(row.updatedAt ?? row.createdAt ?? row.storedAt)
return `${row.hasEmbedding === true ? '◆' : '◇'} ${short(row.namespace, 24)}/${short(row.key, 80)} · ${numberOf(row.size) ?? 'n/a'} B${at !== undefined ? ` · ${isoOf(at).slice(0, 16).replace('T', ' ')}` : ''}`
return `${row.hasEmbedding === true ? '◆' : '◇'} ${short(row.namespace, 24)}/${short(row.key, 80)} · ${countOf(row.size) ?? 'n/a'} B${at !== undefined ? ` · ${isoOf(at).slice(0, 16).replace('T', ' ')}` : ''}`
}),
]
}
@@ -120,10 +120,11 @@ function vectorLines(record: Record<string, unknown>): string[] | null {
if (vector === null) return null
const numbers = vector.filter((value): value is number => typeof value === 'number' && Number.isFinite(value))
// Only measurements count as elements (#3822): an element of 1e300 would print as "1e+300" in the head and overflow the norm.
const numbers = vector.flatMap(value => measureOf(value) ?? [])
const norm = Math.sqrt(numbers.reduce((sum, value) => sum + value * value, 0))
return [`${numbers.length} dimensions · norm ${norm.toFixed(3)}${record.model !== undefined ? ` · ${short(record.model, 40)}` : ''}`, `head: ${numbers.slice(0, 8).map(value => value.toFixed(4)).join(' ')} …`]
return [`${numbers.length} dimensions · norm ${measureOf(norm)?.toFixed(3) ?? 'n/a'}${record.model !== undefined ? ` · ${short(record.model, 40)}` : ''}`, `head: ${numbers.slice(0, 8).map(value => value.toFixed(4)).join(' ')} …`]
}
/** One run's JSON as lines, by its shape; empty when nothing specific applies. */
+3 -4
View File
@@ -8,7 +8,7 @@
*/
import { activeMission, progressOf } from './mission-control'
import { alertsOf, waitingApprovalsOf } from './data/alerts'
import { secMemo } from './secure'
import { secMemo, securityBand } from './secure'
import type { State, ViewId } from './state'
import { hasUnseen } from './whatsnew'
import { money } from './views/bar'
@@ -29,8 +29,7 @@ export function badgesOf(state: State, nowMs: number): Partial<Record<ViewId, Ba
const mission = activeMission(state)
const busy = snap?.agents.filter(agent => /busy|active|working/i.test(agent.status)).length ?? 0
const claims = snap?.claims.length ?? 0
const findings = secMemo(state).findings
const serious = findings === null ? 0 : findings.counts.critical + findings.counts.high
const security = securityBand(secMemo(state).findings)
if (mission !== null && !mission.cancelled) {
const { done, total } = progressOf(mission, snap?.tasks ?? [])
@@ -42,7 +41,7 @@ export function badgesOf(state: State, nowMs: number): Partial<Record<ViewId, Ba
if (alerts > 0) out.overview = { text: `⚠ ${alerts}`, tone: 'attention' }
if (busy > 0) out.swarm = { text: `▶ ${busy}`, tone: 'plain' }
if (claims > 0) out.claims = { text: String(claims), tone: 'plain' }
if (findings !== null && serious > 0) out.secure = { text: `🔒 ${serious}`, tone: findings.counts.critical > 0 ? 'attention' : 'plain' }
if (security !== null) out.secure = { text: security.compact, tone: security.isAttention ? 'attention' : 'plain' }
if (state.usage?.costUsd !== undefined && state.usage.costUsd >= 0.01) out.cost = { text: money(state.usage.costUsd), tone: 'plain' }
if (state.terminal.runs.size > 0) out.terminal = { text: '●', tone: 'plain' }
if (hasUnseen(state)) out.whatsnew = { text: 'new', tone: 'attention' }
+23 -12
View File
@@ -10,6 +10,7 @@ import { exec, type ActionSpec } from './actions'
import { jsonAfter, type AuditTrend } from './data/cli'
import { rowsWith, type Findings } from './data/failure'
import { idOf, plain, recordOf } from './data/parse'
import { countOf, measureOf } from './data/safe'
import type { State } from './state'
/** `read`: $0, changes nothing. `writes`: $0, writes a file or memory. `local`: minutes of local compute that writes. `spends`: may call paid models. */
@@ -126,7 +127,17 @@ export const LAB_MAX_LINES = 40
const SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'] as const
const SKIP = new Set(['rawStdout', 'stdout', 'durationMs', 'generatedAt', 'schema', 'system'])
const scalar = (value: unknown): string | null => (value === null ? 'null' : typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? plain(String(value), 120) : null)
/** A number is shown only when it is a measurement (#3822): `1e999` parses as Infinity and `1e300` prints as "1e+300"; both read n/a. */
const scalar = (value: unknown): string | null => (value === null ? 'null' : typeof value === 'number' ? (measureOf(value) === undefined ? 'n/a' : String(value)) : typeof value === 'string' || typeof value === 'boolean' ? plain(String(value), 120) : null)
const tally = (value: unknown, fallback = 'n/a'): string => (value === undefined ? fallback : String(countOf(value) ?? 'n/a'))
/** A character count the CLI printed, when it is one (whole, 0..1e12): past that it is not a length, and the text's own length is used. */
const charsOf = (value: unknown): number | undefined => {
const n = measureOf(value)
return n !== undefined && n >= 0 ? Math.floor(n) : undefined
}
/** Any answer field as one cleaned cell: a number only when it is a measurement, anything else through plain() (#3822). */
const cell = (value: unknown, max: number): string => (typeof value === 'number' ? (measureOf(value) === undefined ? 'n/a' : String(value)) : plain(String(value ?? ''), max))
/** Any JSON as readable lines: scalars as `key: value`, short lists inline, objects indented, two levels deep. */
function flatten(value: unknown, out: string[], depth = 0): void {
@@ -166,14 +177,14 @@ function findingLines(record: Record<string, unknown>, findings: unknown[]): str
const rows = findings.map(recordOf).filter((row): row is Record<string, unknown> => row !== null)
const severityOf = (row: Record<string, unknown>) => String(row.severity ?? 'info').toLowerCase()
const counts = SEVERITIES.map(level => `${level} ${rows.filter(row => severityOf(row) === level).length}`).join(' · ')
const out = [`worst ${plain(String(record.worst ?? 'n/a'), 20)}${record.verdict !== undefined ? ` · verdict ${plain(String(record.verdict), 20)}` : ''} · ${rows.length} finding${rows.length === 1 ? '' : 's'}`, `by severity: ${counts}`]
const out = [`worst ${cell(record.worst ?? 'n/a', 20)}${record.verdict !== undefined ? ` · verdict ${cell(record.verdict, 20)}` : ''} · ${rows.length} finding${rows.length === 1 ? '' : 's'}`, `by severity: ${counts}`]
for (const row of rows.slice(0, 12)) out.push(`[${severityOf(row)}] ${plain(String(row.title ?? row.message ?? row.id ?? ''), 140)}`)
for (const row of rows.slice(0, 12)) out.push(`[${severityOf(row)}] ${cell(row.title ?? row.message ?? row.id, 140)}`)
const flags = ['secretsReachable', 'networkAccess', 'shellAccess', 'fileWrite', 'policyDefaultDeny', 'auditLog'].filter(flag => typeof record[flag] === 'boolean')
if (flags.length > 0) out.push(flags.map(flag => `${flag} ${record[flag] === true ? 'yes' : 'no'}`).join(' · '))
if (typeof record.allowedTools === 'number') out.push(`tools allowed ${record.allowedTools} · denied ${String(record.deniedTools ?? 'n/a')}`)
if (typeof record.allowedTools === 'number') out.push(`tools allowed ${tally(record.allowedTools)} · denied ${tally(record.deniedTools)}`)
return out
}
@@ -181,15 +192,15 @@ function findingLines(record: Record<string, unknown>, findings: unknown[]): str
/** A redblue run: tests, failures by severity, cost, the gates, then each compromised case. */
function redblueLines(record: Record<string, unknown>, summary: Record<string, unknown>): string[] {
const out = [
`tests ${String(summary.tests_run ?? 'n/a')} · failures ${String(summary.failures_found ?? 'n/a')} · critical ${String(summary.critical ?? 0)} · high ${String(summary.high ?? 0)} · med ${String(summary.med ?? 0)} · low ${String(summary.low ?? 0)}`,
`cost $${typeof summary.cost_usd === 'number' ? summary.cost_usd.toFixed(3) : 'n/a'} · gates ${record.gates_passed === true ? 'passed' : 'FAILED'} · block production ${record.should_block_production === true ? 'yes' : 'no'}`,
`tests ${tally(summary.tests_run)} · failures ${tally(summary.failures_found)} · critical ${tally(summary.critical, '0')} · high ${tally(summary.high, '0')} · med ${tally(summary.med, '0')} · low ${tally(summary.low, '0')}`,
`cost $${measureOf(summary.cost_usd)?.toFixed(3) ?? 'n/a'} · gates ${record.gates_passed === true ? 'passed' : 'FAILED'} · block production ${record.should_block_production === true ? 'yes' : 'no'}`,
]
for (const finding of (Array.isArray(record.findings) ? record.findings : []).map(recordOf)) {
if (finding?.compromised === true) out.push(`✗ ${plain(String(finding.family ?? finding.testId ?? ''), 60)} (${plain(String(finding.severity ?? ''), 12)})`)
if (finding?.compromised === true) out.push(`✗ ${cell(finding.family ?? finding.testId, 60)} (${cell(finding.severity, 12)})`)
}
for (const tip of (Array.isArray(record.recommendations) ? record.recommendations : []).slice(0, 3)) out.push(`→ ${plain(String(tip), 140)}`)
for (const tip of (Array.isArray(record.recommendations) ? record.recommendations : []).slice(0, 3)) out.push(`→ ${cell(tip, 140)}`)
return out
}
@@ -204,7 +215,7 @@ function summary(value: unknown): string[] {
return value.slice(0, 20).map(item => {
const row = recordOf(item)
return row === null ? plain(String(item), 140) : `${plain(String(row.receiptId ?? row.id ?? ''), 24)} · ${plain(String(row.decision ?? ''), 20)} · ${plain(String(row.state ?? ''), 20)}${row.signed === true ? ' · signed' : ''}`
return row === null ? cell(item, 140) : `${cell(row.receiptId ?? row.id, 24)} · ${cell(row.decision, 20)} · ${cell(row.state, 20)}${row.signed === true ? ' · signed' : ''}`
})
}
@@ -219,11 +230,11 @@ function summary(value: unknown): string[] {
if (record.subcommand === 'attack' && typeof record.stdout === 'string') {
const cases = recordOf(jsonAfter(record.stdout))?.cases
return (Array.isArray(cases) ? cases : []).map(recordOf).flatMap(row => (row === null ? [] : [`${plain(String(row.family ?? ''), 32)} · ${plain(String(row.input ?? row.objective ?? ''), 120)}`]))
return (Array.isArray(cases) ? cases : []).map(recordOf).flatMap(row => (row === null ? [] : [`${cell(row.family, 32)} · ${cell(row.input ?? row.objective, 120)}`]))
}
if (typeof record.system === 'string') {
return [`${String(record.chars ?? record.system.length)} chars from ${plain(String(record.source ?? 'the genome'), 200).split('/').pop() ?? ''}`, ...record.system.split('\n').map(line => plain(line, 160))]
return [`${charsOf(record.chars) ?? record.system.length} chars from ${cell(record.source ?? 'the genome', 200).split('/').pop() ?? ''}`, ...record.system.split('\n').map(line => plain(line, 160))]
}
const genome = recordOf(record.genome)
@@ -231,7 +242,7 @@ function summary(value: unknown): string[] {
if (genome !== null) {
const meta = recordOf(genome.meta) ?? {}
return [`valid ${record.valid === true ? 'yes' : 'NO'} · ${Array.isArray(record.errors) ? record.errors.length : 0} errors`, `genome ${String(meta.id ?? 'n/a')} (parent ${String(meta.parent ?? 'n/a')}, mutated ${String(meta.mutated ?? 'n/a')})`, `components: ${Object.keys(recordOf(genome.components) ?? {}).join(', ')}`]
return [`valid ${record.valid === true ? 'yes' : 'NO'} · ${Array.isArray(record.errors) ? record.errors.length : 0} errors`, `genome ${cell(meta.id ?? 'n/a', 40)} (parent ${cell(meta.parent ?? 'n/a', 40)}, mutated ${cell(meta.mutated ?? 'n/a', 40)})`, `components: ${Object.keys(recordOf(genome.components) ?? {}).join(', ')}`]
}
return []
@@ -230,7 +230,7 @@ export function missionActions(state: State, host: Host, runner: Runner): Missio
const tasksNow = (): readonly TaskRecord[] => state.snapshot?.tasks ?? []
/** Runs a slash command on the goal (or the active mission's objective) in the main UI: now when idle, prepared in the prompt box mid-turn. */
const launch = (slash: string, label: string, custom?: { args: string; note: string; byModel?: boolean }) => {
const launch = (slash: string, label: string, custom?: { args: string; note: string; byModel?: boolean; byCall?: number }) => {
const objective = activeMission(state)?.objective ?? mc.goal
// A research start brings its own, already screened arguments; every other launch works on the goal.
@@ -244,7 +244,7 @@ export function missionActions(state: State, host: Host, runner: Runner): Missio
runner.ask(
{
label: `run /${slash} on the goal in the main Claude UI`,
...(custom?.byModel === true && { byModel: true }),
...(custom?.byModel === true && { byModel: true, byCall: custom.byCall }),
scope: 'controls',
args: [],
shows: `/${slash} ${args}`,
@@ -273,6 +273,7 @@ export function missionActions(state: State, host: Host, runner: Runner): Missio
/** Research start: validate, screen the question (always: it reaches the web), refuse when unsafe, then ask with the confirm in words. */
const research = () => {
const byModel = state.control.viaModel
const byCall = state.control.callTag ?? undefined
const draft = { ...researchOf(state) }
const question = plain(draft.question, MAX_TEXT).trim()
@@ -291,7 +292,7 @@ export function missionActions(state: State, host: Host, runner: Runner): Missio
if (now.question !== draft.question || now.depth !== draft.depth || now.cap !== draft.cap) return
if (blocksGuidance(screen)) return say('AIDefence blocked the question', false, `${screen.detail}. Change the question.`)
launch(slashOf(skill), 'deep research', { args: researchArgs(question, draft.depth, cap), note: researchConfirm(draft.depth, cap, screen), byModel })
launch(slashOf(skill), 'deep research', { args: researchArgs(question, draft.depth, cap), note: researchConfirm(draft.depth, cap, screen), byModel, byCall })
})
}
@@ -357,7 +358,7 @@ export function missionActions(state: State, host: Host, runner: Runner): Missio
runner.ask(dispatchSpec(state, host, mission, task, text => host.submitPrompt(text)), 'nothing to hand out')
},
pause: () => setPaused(state, host, true),
resume: () => setPaused(state, host, false),
resume: by => setPaused(state, host, false, by),
cancel: () => {
const mission = activeMission(state)
@@ -411,12 +412,13 @@ export function missionActions(state: State, host: Host, runner: Runner): Missio
if (t !== '') mc.lastGuide = t
const byModel = state.control.viaModel
const byCall = state.control.callTag ?? undefined
const ask = () =>
runner.ask(
t === ''
? null
: { label: `send Claude: ${plain(t, 70)}`, byModel, scope: 'guide', args: [], shows: `to the Claude Code session, as a visible prompt: “${t}”`, expect: 'the instruction in the transcript', note: 'Starts a Claude Code turn (billed as any turn is).', run: async () => host.submitPrompt(t) },
: { label: `send Claude: ${plain(t, 70)}`, byModel, byCall, scope: 'guide', args: [], shows: `to the Claude Code session, as a visible prompt: “${t}”`, expect: 'the instruction in the transcript', note: 'Starts a Claude Code turn (billed as any turn is).', run: async () => host.submitPrompt(t) },
'type the instruction first',
)
@@ -0,0 +1,329 @@
/**
* Mission Control's create chain: `mission_create`, `mission_plan`, then one `task_create` per plan node, behind one confirm.
*
* On a busy project every `mcp exec` waits on the policy state lock and some fail with `policy-state-lock-timeout` (#3164, #3892). A step that
* failed that way (or got no answer in time, or printed nothing at all) is tried again after RETRY_WAITS_MS; any other failure is final.
* `task_create` has no request id, so after each wait, just before trying again, the task store is read: one task that is exactly this step's
* (its description and both tags, open) is a late success and is used; more than one stops the chain (it never guesses); a store that cannot
* be read stops a retry whose first try may have written; and after the last failed try the store is read once more (the last try's write
* may have landed with its answer lost). Provenance is the mission id: the step's description and tag carry the id this create was just
* given, so no older task can match; the time window (SKEW_MS) only keeps out a stale store and is wide for clock skew.
*
* Time is strict: no call, wait or read starts after its deadline, each is cut to the time left, and a call the host never answers is let go
* at that time (the CLI process may still finish: the report says so). When the create cannot finish, every open task tagged with this
* mission in the store (not only those whose create was acknowledged) is cancelled with the same retries, the mission record is asked to
* cancel, and the store and the mission observation are READ BACK: the result says what they show, not what was asked.
*/
import type { ActionSpec, RunReport } from './actions'
import { taskStatusOf } from './data/automate'
import { PROJECT, under } from './data/files'
import { readAttempt, type Attempt, type RunRead } from './data/mcp-run'
import { parseMissions } from './data/missions'
import { parseTasks, plain, recordOf, type TaskRecord } from './data/parse'
import { stageOf, toMissionPlan, type Profile } from './goap'
import { checkLimit, MISSION_OBJECTIVE_MAX } from './full-text'
import type { Host } from './host'
import { mcOf, record, saveLedger } from './mission-control'
import type { LedgerTask, MissionRecord } from './mission-types'
import { CLI_PREFIXES, type State } from './state'
export const argvOf = (state: State, tool: string, params: unknown): string[] => [...CLI_PREFIXES[state.options.cli], 'mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)]
export const taskType = (profile: Profile) => (profile === 'bugfix' ? 'bugfix' : profile === 'refactor' ? 'refactor' : profile === 'research' ? 'research' : 'feature')
/**
* Why the mission cannot be created from this goal, or null: the ruflo mission record takes an objective of at most MISSION_OBJECTIVE_MAX
* characters (mission_create's input schema), and the goal is never cut to fit (ADR-481). Checked before the ask, with the exact count.
*/
export function createWhy(state: State): string | null {
const goal = mcOf(state).goal
const fit = checkLimit(goal, MISSION_OBJECTIVE_MAX, 'the goal', 'the ruflo mission record takes at most that many; planning, guidance and the skills use the whole goal', 'No mission was created; ✎ edit the goal to fit.')
return fit.ok ? null : fit.message
}
/** The waits before a step that failed for a transient reason is tried again: up to three more tries, 1, 2 and 4 s apart. */
export const RETRY_WAITS_MS: readonly number[] = [1_000, 2_000, 4_000]
/** No create step starts after this long; what was made is then undone. */
export const CREATE_DEADLINE_MS = 180_000
/** Undoing (cancels, the mission cancel, the read-back) gets this long on top; past it, no step is retried. */
export const CLEANUP_BUDGET_MS = 120_000
/** One read of the task store or the mission observation may take this long. */
export const READ_MS = 5_000
/** One CLI call may take this long (less when the deadline is nearer). */
export const CALL_MS = 60_000
/** A store task this much older than the create can still be its late success: the mission id binds it; this only allows for clock skew. */
export const SKEW_MS = 5 * 60_000
/** The host's own process limit is set this much past the caller's, so the caller's (structured) time limit is the one that ends a wait. */
const HOST_GRACE_MS = 2_000
/** The creates running now, per console, with when each started: a second create is refused while one runs. */
const creating = new WeakMap<State, number>()
export const isCreating = (state: State): boolean => creating.has(state)
const nonce = (): string => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
const pause = (host: Host, ms: number): Promise<void> =>
new Promise(resolve => {
try {
host.after(ms, () => resolve())
} catch {
resolve()
}
})
/** `work`, or `late` once `ms` have passed without it settling (a timer of this module, so a host that never answers is let go). */
function within<T>(work: Promise<T>, ms: number, late: T): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined
return Promise.race([work, new Promise<T>(resolve => (timer = setTimeout(() => resolve(late), Math.max(0, ms))))]).finally(() => clearTimeout(timer))
}
/** A file of the project, or null when it cannot be read within `ms` (at most READ_MS; nothing is read when no time is left). */
async function readWithin(state: State, host: Host, path: string, ms: number = READ_MS): Promise<string | null> {
if (ms <= 0) return null
try {
return await within(Promise.resolve().then(() => host.fs.read(under(state.cwd, path))), Math.min(READ_MS, ms), null)
} catch {
return null
}
}
const readStore = async (state: State, host: Host, ms?: number): Promise<TaskRecord[] | null> => {
const text = await readWithin(state, host, PROJECT.tasks, ms)
return text === null ? null : parseTasks(text)
}
type Step = { id: string; description: string; tags: string[] }
/** The tasks in the store that are exactly this step's: its description and both tags (the mission id binds them), still open, made since `sinceMs`. */
export function stepTasks(tasks: readonly TaskRecord[], missionId: string, step: Step, sinceMs: number): TaskRecord[] {
const description = plain(step.description, 200)
return tasks.filter(task => {
const status = taskStatusOf(task.status)
return (status === 'pending' || status === 'in_progress') && task.description === description && (task.tags ?? []).includes(`mission:${missionId}`) && (task.tags ?? []).includes(`task:${step.id}`) && (task.createdAtMs ?? 0) >= sinceMs
})
}
type Outcome = Attempt & { tries: number }
/** Create the mission: `mission_create`, `mission_plan`, then a ruflo task per plan node. One confirm for the chain. */
export function createSpec(state: State, host: Host, onDone: () => void): ActionSpec | null {
const mc = mcOf(state)
if (mc.planned === null || mc.goal === '' || createWhy(state) !== null) return null
const planned = mc.planned
const goal = mc.goal
const body = toMissionPlan(planned)
const stamp = nonce()
return {
label: `create the mission and its ${body.tasks.length} tasks: ${plain(goal, 60)}`,
scope: 'goal',
args: [],
argv: argvOf(state, 'mission_create', { requestId: `console-create-${stamp}`, objective: goal }),
shows: `mission_create → mission_plan → task_create × ${body.tasks.length}, each \`ruflo mcp exec -t <tool>\` (${planned.profile}, ${planned.rigor}; ceiling ${body.budget.ceilingMinor / 100} ${body.budget.currency}, a record, not a charge)`,
expect: 'a planned mission and its tasks in the ruflo task store',
note: 'Writes the mission record and one task per plan node to this project’s ruflo stores. It runs no agent and spends nothing.',
run: async () => {
const since = creating.get(state)
// One create at a time: a second would race the first for the same store and the same lock.
if (since !== undefined) mc.last = { label: 'not created', ok: false, detail: `a mission is already being created (started ${Math.round((Date.now() - since) / 1000)} s ago); wait for its result` }
// The goal changed while this ask was open: the plan on screen is not the plan that was asked for.
else if (mc.goal !== goal) mc.last = { label: 'not created', ok: false, detail: 'the goal changed since you asked; ask again' }
else {
creating.set(state, Date.now())
try {
await createChain()
} catch (error) {
mc.last = { label: 'creating the mission failed', ok: false, detail: plain(error instanceof Error ? error.message : String(error), 160) }
} finally {
creating.delete(state)
host.invalidate()
}
}
host.invalidate()
// How it ended is the console's outcome too, so Claude reads it from console_state however long the chain took.
return mc.last === null ? undefined : ({ label: mc.last.label, ok: mc.last.ok, detail: mc.last.detail, ...(mc.last.lines !== undefined && { lines: mc.last.lines }) } satisfies RunReport)
},
}
async function createChain(): Promise<void> {
const startedMs = Date.now()
// The mission id in the description and the tag is what binds a store task to this create; the window only allows for clock skew.
const sinceMs = startedMs - SKEW_MS
const deadline = startedMs + CREATE_DEADLINE_MS
const cleanupEnd = deadline + CLEANUP_BUDGET_MS
const fail = (label: string, detail: string, lines?: string[]) => void (mc.last = { label, ok: false, detail: plain(detail, 200), ...(lines !== undefined && { lines }) })
const left = (until: number) => until - Date.now()
const outOfTime: Attempt = { result: null, ok: false, transient: false, reason: 'out of time: not started' }
/** One try of a tool: never started at or after `until`, and let go at the time left (the host's own limit is a little later). */
const once = async (tool: string, params: unknown, isDone: (result: Record<string, unknown>) => boolean, until: number): Promise<Attempt> => {
const ms = Math.min(CALL_MS, left(until))
if (ms <= 0) return outOfTime
const run = await within<RunRead>(host.run(argvOf(state, tool, params), ms + HOST_GRACE_MS).catch((error: unknown) => ({ error })), ms, { timedOutMs: ms })
return readAttempt(run, isDone)
}
/**
* Tries a step, and again after each wait while it fails for a transient reason and there is time before `until`. `beforeRetry` runs
* after the wait, just before the next try: it may answer the step itself (a late success found), stop it (an answer of `ok: false`),
* or let it be tried again (null).
*/
const attempt = async (tool: string, params: unknown, isDone: (result: Record<string, unknown>) => boolean, until: number, beforeRetry?: () => Promise<Attempt | null>): Promise<Outcome> => {
let last = await once(tool, params, isDone, until)
let tries = 1
for (const wait of RETRY_WAITS_MS) {
// A wait that would end at or past the deadline is not started: there would be no time left for the try after it.
if (last.ok || !last.transient || wait >= left(until)) break
await pause(host, wait)
const instead = await beforeRetry?.()
if (instead != null) return { ...instead, reason: instead.ok ? '' : `${instead.reason} (after: ${last.reason})`, tries }
if (left(until) <= 0) break
last = await once(tool, params, isDone, until)
tries += 1
}
// The last try failed for a transient reason: its write may have landed with the answer lost. One more look, if there is time for it.
if (!last.ok && last.transient && left(until) > 0) {
const found = await beforeRetry?.()
// Only a late success counts here; anything else keeps the last try's own reason (cleanup cancels every task of the mission anyway).
if (found?.ok === true) return { ...found, reason: '', tries }
}
return { ...last, tries }
}
const answered = (result: Record<string, unknown>) => result.ok === true
const created = await attempt('mission_create', { requestId: `console-create-${stamp}`, objective: goal }, result => answered(result) && typeof recordOf(result.data)?.missionId === 'string', deadline)
const data = recordOf(created.result?.data) ?? {}
if (!created.ok || typeof data.missionId !== 'string') return fail('mission_create failed', `${created.reason || 'no answer'} (${tries(created)})`)
const id = data.missionId
const createdRevision = typeof data.revision === 'number' ? data.revision : 1
// mission_create and mission_plan carry a request id, so a retry after a late success is answered from the record, never applied twice.
const placed = await attempt('mission_plan', { requestId: `console-plan-${stamp}`, missionId: id, expectedRevision: createdRevision, plan: body }, answered, deadline)
if (!placed.ok) return undo(id, createdRevision, [], `the plan was not recorded: ${placed.reason || 'no answer'} (${tries(placed)})`, 'mission not created: mission_plan failed')
const planData = recordOf(placed.result?.data) ?? {}
const planRevision = typeof planData.revision === 'number' ? planData.revision : createdRevision + 1
const tasks: LedgerTask[] = []
for (const node of planned.steps) {
if (Date.now() >= deadline) return undo(id, planRevision, tasks, `the create ran past its ${CREATE_DEADLINE_MS / 60_000} min limit before task ${node.id}`, `mission not created: out of time at task ${node.id}`)
const title = body.tasks.find(candidate => candidate.id === node.id)?.title ?? node.action.title
const step: Step = { id: node.id, description: `[${id}/${node.id}] ${title}`.slice(0, 200), tags: [`mission:${id}`, `task:${node.id}`, `phase:${node.action.phase}`] }
const made = await attempt('task_create', { type: taskType(planned.profile), description: step.description, priority: 'normal', tags: step.tags }, result => typeof result.taskId === 'string' && result.success !== false && result.error === undefined, deadline, async () => {
const store = await readStore(state, host, left(deadline))
if (store === null) return { result: null, ok: false, transient: false, reason: 'the task store could not be read to check for a late success, so the step was not tried again' }
const found = stepTasks(store, id, step, sinceMs)
if (found.length > 1) return { result: null, ok: false, transient: false, reason: `${found.length} tasks in the store match task ${node.id} (${found.map(task => task.id).join(', ')}); not guessing which one is ours` }
return found.length === 1 ? { result: { taskId: found[0]?.id }, ok: true, transient: false, reason: '' } : null
})
const rufloTaskId = made.ok && typeof made.result?.taskId === 'string' ? made.result.taskId : undefined
if (rufloTaskId === undefined) return undo(id, planRevision, tasks, `task ${node.id}: ${made.reason || 'no answer'} (${tries(made)})`, `mission not created: task ${node.id} could not be made`)
tasks.push({ id: node.id, title: node.action.title, phase: node.action.phase, stage: stageOf(node.action), agent: node.action.agent, requirement: node.action.requirement, dependsOn: node.dependsOn, rufloTaskId })
}
const record0: MissionRecord = {
id,
objective: goal,
profile: planned.profile,
rigor: planned.rigor,
planDigest: typeof planData.planDigest === 'string' ? planData.planDigest : undefined,
tasks,
acceptance: body.acceptance.map(criterion => ({ id: criterion.id, check: criterion.check })),
events: [],
paused: false,
cancelled: false,
auto: false,
createdAtMs: Date.now(),
}
record(record0, { type: 'mission.created', status: 'draft' })
record(record0, { type: 'plan.validated', status: 'planned', evidenceRef: record0.planDigest })
record(record0, { type: 'tasks.created', note: `${tasks.length} of ${tasks.length}` })
mc.missions.set(id, record0)
mc.active = id
mc.tab = 'tasks'
mc.last = { label: `mission ${id} planned`, ok: true, detail: `${tasks.length} tasks in the ruflo task store; ▶ Run next hands the first to Claude` }
saveLedger(state, host)
onDone()
/**
* The create cannot finish. Every open task of this mission is cancelled: those whose create was acknowledged, and any other the store
* holds with this mission's tag (a create whose answer was lost). Then the mission record is asked to cancel (once more at the revision a
* conflict names), and the task store and the mission observation are read back: the result says what they show. Nothing starts after
* the cleanup deadline; what was left for lack of time is named.
*/
async function undo(missionId: string, revision: number, made: LedgerTask[], why: string, label: string): Promise<void> {
const tag = `mission:${missionId}`
const before = await readStore(state, host, left(cleanupEnd))
const acknowledged = made.map(task => task.rufloTaskId as string)
const tagged = (before ?? []).filter(task => (task.tags ?? []).includes(tag)).map(task => task.id)
const ids = [...new Set([...acknowledged, ...tagged])]
const closed = new Set((before ?? []).filter(task => ['cancelled', 'completed'].includes(taskStatusOf(task.status))).map(task => task.id))
const skipped: string[] = []
for (const taskId of ids) {
if (closed.has(taskId)) continue
if (left(cleanupEnd) <= 0) skipped.push(taskId)
else await attempt('task_cancel', { taskId, reason: 'mission creation failed in the console' }, result => result.success === true, cleanupEnd)
}
const cancel = (expectedRevision: number, suffix: string) => attempt('mission_request_action', { requestId: `console-abort-${stamp}${suffix}`, missionId, expectedRevision, action: 'cancel', reason: plain(`creation failed in the console: ${why}`, 400) }, answered, cleanupEnd)
let asked = await cancel(revision, '')
const current = asked.result?.code === 'revision-conflict' && typeof asked.result.currentRevision === 'number' ? asked.result.currentRevision : null
if (!asked.ok && current !== null && current !== revision && left(cleanupEnd) > 0) asked = await cancel(current, '-r')
const after = await readStore(state, host, left(cleanupEnd))
const seen = after === null ? null : [...new Set([...ids, ...after.filter(task => (task.tags ?? []).includes(tag)).map(task => task.id)])].map(taskId => ({ taskId, status: taskStatusOf(after.find(task => task.id === taskId)?.status) || 'missing' }))
const open = seen?.filter(entry => entry.status !== 'cancelled' && entry.status !== 'completed') ?? []
const observed = parseMissions(await readWithin(state, host, PROJECT.missions, left(cleanupEnd)))?.missions.find(mission => mission.id === missionId)?.state
const total = seen?.length ?? 0
const storeLine =
seen === null
? `the task store could not be read back: ${ids.length === 0 ? 'no task of this mission is known' : `the cancels of ${ids.join(', ')} are unconfirmed`}`
: total === 0
? 'the store holds no task of this mission'
: `the store shows ${total - open.length} of the ${total} tasks of this mission cancelled${open.length > 0 ? `; ${open.length} not cancelled: ${open.map(entry => `${entry.taskId} (${entry.status})`).join(', ')}` : ''}`
const recordLine = `mission ${missionId}: ${asked.ok ? 'cancel accepted' : `cancel not accepted: ${asked.reason || 'no answer'}`}; the observation shows ${observed ?? 'nothing readable'}`
const timeLine = skipped.length > 0 ? [`out of cleanup time: not asked to cancel ${skipped.join(', ')}`] : []
const summary = seen === null ? 'Store not readable' : total === 0 ? 'No task in the store' : `Store: ${total - open.length} of ${total} cancelled${open.length > 0 ? `, ${open.length} not` : ''}`
fail(label, `${why}. ${summary}; mission ${observed ?? 'state unknown'}. Ask again.`, [why, storeLine, recordLine, ...timeLine])
}
}
}
const tries = (outcome: Outcome): string => `${outcome.tries} ${outcome.tries === 1 ? 'try' : 'tries'}`
@@ -47,7 +47,9 @@ export function missionPalette(state: State): PaletteEntry[] {
}),
},
{ id: 'mission-pause', group: 'missions', label: 'pause: no more tasks are handed out', run: spec(() => local('pause the mission', () => wired?.actions.pause(), 'write')) },
{ id: 'mission-resume', group: 'missions', label: 'resume handing out tasks', run: spec(() => local('resume the mission', () => wired?.actions.resume(), 'write')) },
// Who resumes is known when the entry is built: Claude's console_run builds the palette inside its call (state.control.viaModel). Claude's
// resume keeps the hand-out counts; only the person's gives an exhausted task more billed turns (#3823).
{ id: 'mission-resume', group: 'missions', label: 'resume handing out tasks', run: spec(() => (state.control.viaModel ? local('resume the mission (Claude: hand-out counts kept)', () => wired?.actions.resume('model'), 'write') : local('resume the mission', () => wired?.actions.resume('person'), 'write'))) },
{ id: 'mission-cancel', group: 'missions', label: 'cancel the mission and its open tasks (asks first)', run: spec(() => { const mission = activeMission(state); return wired === undefined || mission === null ? null : cancelSpec(state, wired.host, mission, tasks()) }) },
{ id: 'mission-aside', group: 'missions', label: 'mission-aside <question>: /btw beside the running task', run: text('mission-aside', value => local('ask aside', () => wired?.actions.aside(value), 'spend')) },
{ id: 'mission-guide', group: 'missions', label: 'mission-guide <instruction>: a visible instruction to Claude (screened, asks first)', run: text('mission-guide', value => local('guide Claude', () => wired?.actions.guide(value))) },
+25 -147
View File
@@ -1,152 +1,19 @@
/** The confirm-gated writes of Mission Control: create the mission and its tasks, hand a task to Claude, cancel. */
import type { ActionSpec } from './actions'
import { plain, type TaskRecord } from './data/parse'
import { resultOf } from './data/mcp-run'
import { taskStatusOf } from './data/automate'
import { stageOf, toMissionPlan, type Profile } from './goap'
import { checkLimit, MISSION_OBJECTIVE_MAX } from './full-text'
import type { Host } from './host'
import { adrBlockFor } from './adr-mission'
import { EVENT_RESUMED, stoppedByAdvisor } from './mission-advisor'
import { activeMission, instructionOf, mcOf, nextTask, record, rufloTaskOf, saveLedger } from './mission-control'
import type { LedgerTask, MissionRecord } from './mission-types'
import { CLI_PREFIXES, type State } from './state'
import type { LedgerTask, MissionRecord, ResumeBy } from './mission-types'
import { argvOf } from './mission-create'
import type { State } from './state'
const argvOf = (state: State, tool: string, params: unknown): string[] => [...CLI_PREFIXES[state.options.cli], 'mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)]
/** The JSON object after `Result:` in a tool run's output (the CLI logs around it), or null. */
export function resultOf(stdout: string): Record<string, unknown> | null {
const text = stdout.replace(/\x1b\[[0-9;]*m/g, '')
const start = text.indexOf('{', Math.max(0, text.indexOf('Result:')))
let depth = 0
for (let i = start; i >= 0 && i < text.length; i++) {
if (text[i] === '{') depth++
else if (text[i] === '}' && --depth === 0) {
try {
return JSON.parse(text.slice(start, i + 1)) as Record<string, unknown>
} catch {
return null
}
}
}
return null
}
const taskType = (profile: Profile) => (profile === 'bugfix' ? 'bugfix' : profile === 'refactor' ? 'refactor' : profile === 'research' ? 'research' : 'feature')
/**
* Why the mission cannot be created from this goal, or null: the ruflo mission record takes an objective of at most MISSION_OBJECTIVE_MAX
* characters (mission_create's input schema), and the goal is never cut to fit (ADR-481). Checked before the ask, with the exact count.
*/
export function createWhy(state: State): string | null {
const goal = mcOf(state).goal
const fit = checkLimit(goal, MISSION_OBJECTIVE_MAX, 'the goal', 'the ruflo mission record takes at most that many; planning, guidance and the skills use the whole goal', 'No mission was created; ✎ edit the goal to fit.')
return fit.ok ? null : fit.message
}
/** Create the mission: `mission_create`, `mission_plan`, then a ruflo task per plan node. One confirm for the chain. */
export function createSpec(state: State, host: Host, onDone: () => void): ActionSpec | null {
const mc = mcOf(state)
if (mc.planned === null || mc.goal === '' || createWhy(state) !== null) return null
const planned = mc.planned
const goal = mc.goal
const body = toMissionPlan(planned)
const stamp = Date.now().toString(36)
return {
label: `create the mission and its ${body.tasks.length} tasks: ${plain(goal, 60)}`,
scope: 'goal',
args: [],
argv: argvOf(state, 'mission_create', { requestId: `console-create-${stamp}`, objective: goal }),
shows: `mission_create → mission_plan → task_create × ${body.tasks.length}, each \`ruflo mcp exec -t <tool>\` (${planned.profile}, ${planned.rigor}; ceiling ${body.budget.ceilingMinor / 100} ${body.budget.currency}, a record, not a charge)`,
expect: 'a planned mission and its tasks in the ruflo task store',
note: 'Writes the mission record and one task per plan node to this project’s ruflo stores. It runs no agent and spends nothing.',
run: async () => {
// The goal changed while this ask was open: the plan on screen is not the plan that was asked for.
if (mc.goal !== goal) return void (mc.last = { label: 'not created', ok: false, detail: 'the goal changed since you asked; ask again' })
try {
await createChain()
} catch (error) {
mc.last = { label: 'creating the mission failed', ok: false, detail: plain(error instanceof Error ? error.message : String(error), 160) }
host.invalidate()
}
},
}
async function createChain(): Promise<void> {
{
const mission = mc
const fail = (label: string, detail: string) => {
mission.last = { label, ok: false, detail }
host.invalidate()
}
const call = async (tool: string, params: unknown) => resultOf((await host.run(argvOf(state, tool, params), 60_000)).stdout)
const created = await call('mission_create', { requestId: `console-create-${stamp}`, objective: goal })
const data = (created?.data ?? {}) as { missionId?: string; revision?: number }
if (created?.ok !== true || typeof data.missionId !== 'string') return fail('mission_create failed', plain(String(created?.message ?? 'no answer'), 160))
const id = data.missionId
const placed = await call('mission_plan', { requestId: `console-plan-${stamp}`, missionId: id, expectedRevision: data.revision ?? 1, plan: body })
if (placed?.ok !== true) return fail('mission_plan refused the plan', plain(String(placed?.message ?? 'no answer'), 200))
const tasks: LedgerTask[] = []
for (const step of planned.steps) {
const task = body.tasks.find(candidate => candidate.id === step.id)
const made = await call('task_create', {
type: taskType(planned.profile),
description: `[${id}/${step.id}] ${task?.title ?? step.action.title}`.slice(0, 200),
priority: 'normal',
tags: [`mission:${id}`, `task:${step.id}`, `phase:${step.action.phase}`],
})
const rufloTaskId = typeof made?.taskId === 'string' ? made.taskId : undefined
tasks.push({ id: step.id, title: step.action.title, phase: step.action.phase, stage: stageOf(step.action), agent: step.action.agent, requirement: step.action.requirement, dependsOn: step.dependsOn, ...(rufloTaskId !== undefined && { rufloTaskId }) })
}
const missing = tasks.filter(task => task.rufloTaskId === undefined).length
if (missing > 0) {
for (const task of tasks) if (task.rufloTaskId !== undefined) await host.run(argvOf(state, 'task_cancel', { taskId: task.rufloTaskId, reason: 'mission creation failed in the console' }), 60_000).catch(() => undefined)
return fail(`${missing} of ${tasks.length} tasks could not be created`, `mission ${id} exists without tasks; the tasks that were made were cancelled. Ask again.`)
}
const record0: MissionRecord = {
id,
objective: goal,
profile: planned.profile,
rigor: planned.rigor,
planDigest: typeof (placed.data as { planDigest?: string } | undefined)?.planDigest === 'string' ? (placed.data as { planDigest: string }).planDigest : undefined,
tasks,
acceptance: body.acceptance.map(criterion => ({ id: criterion.id, check: criterion.check })),
events: [],
paused: false,
cancelled: false,
auto: false,
createdAtMs: Date.now(),
}
record(record0, { type: 'mission.created', status: 'draft' })
record(record0, { type: 'plan.validated', status: 'planned', evidenceRef: record0.planDigest })
record(record0, { type: 'tasks.created', note: `${tasks.filter(task => task.rufloTaskId !== undefined).length} of ${tasks.length}` })
mc.missions.set(id, record0)
mc.active = id
mc.tab = 'tasks'
mc.last = { label: `mission ${id} planned`, ok: true, detail: `${tasks.length} tasks in the ruflo task store; ▶ Run next hands the first to Claude` }
saveLedger(state, host)
onDone()
host.invalidate()
}
}
}
/** The JSON object the tool answered after its own `Result:` line, or null (a failure prints none: the Parameters line is never read as one). */
export { resultOf } from './data/mcp-run'
export { createSpec, createWhy, RETRY_WAITS_MS } from './mission-create'
/** Mark one task in progress and hand it to the primary session as a visible prompt. One confirm: it starts a model turn. */
/** Tasks handed over in the last seconds: the task store has not refreshed yet, so they still read ready. */
@@ -221,19 +88,30 @@ export function dispatchSpec(state: State, host: Host, mission: MissionRecord, t
}
}
/** Pause or resume dispatching, kept in the ledger (a session-bound mission has no durable executor to pause). */
export function setPaused(state: State, host: Host, paused: boolean): void {
/**
* Pause or resume dispatching, kept in the ledger (a session-bound mission has no durable executor to pause). Only the person's resume re-arms
* hand-outs: Claude may resume at write:auto without a Yes, so its resume keeps every task's count (and an advisor stop-the-line stays stopped),
* and a task that used its MAX_HANDOUTS is not handed out again (no new billed turn) until the person resumes it themselves (#3823).
*/
export function setPaused(state: State, host: Host, paused: boolean, by: ResumeBy = 'person'): void {
const mission = activeMission(state)
if (mission === null || mission.cancelled) return
const isPerson = by === 'person'
const spent = mission.tasks.filter(task => (task.handouts ?? 0) >= MAX_HANDOUTS).length
mission.paused = paused
// The person resuming has seen why it stopped: each task gets its hand-outs again.
if (!paused) for (const task of mission.tasks) task.handouts = 0
record(mission, { type: paused ? 'mission.paused' : 'mission.resumed', status: paused ? 'paused' : 'running' })
// ADR-483: resuming after an advisor stop-the-line gives the failing check a fresh run of tries.
if (!paused && stoppedByAdvisor(mission)) record(mission, { type: EVENT_RESUMED })
mcOf(state).last = { label: paused ? 'paused: no more tasks are handed out' : 'resumed', ok: true, detail: paused ? 'a task already handed to Claude finishes first' : 'Run next hands out the next ready task' }
if (!paused && isPerson) for (const task of mission.tasks) task.handouts = 0
record(mission, { type: paused ? 'mission.paused' : 'mission.resumed', status: paused ? 'paused' : 'running', ...(!paused && !isPerson && { note: `resumed by Claude: hand-out counts kept${spent > 0 ? ` (${spent} task${spent === 1 ? '' : 's'} at the limit)` : ''}` }) })
// ADR-483: the person resuming after an advisor stop-the-line gives the failing check a fresh run of tries. Claude's resume does not, for the
// same reason it keeps the hand-out counts: the next checkpoint stops the line again (#3823).
if (!paused && isPerson && stoppedByAdvisor(mission)) record(mission, { type: EVENT_RESUMED })
const detail = paused ? 'a task already handed to Claude finishes first' : !isPerson && spent > 0 ? `${spent} task${spent === 1 ? '' : 's'} used every hand-out: only your own resume gives them more` : 'Run next hands out the next ready task'
mcOf(state).last = { label: paused ? 'paused: no more tasks are handed out' : isPerson ? 'resumed' : 'resumed by Claude', ok: true, detail }
saveLedger(state, host)
host.invalidate()
}
+1 -1
View File
@@ -82,5 +82,5 @@ export function missionAnswer(state: State, paletteId: string | null): string |
if (paletteId === 'mission-goal') return mc.planned === null ? 'type a goal after the id: /ruflo plan <goal>' : planText(mc.planned, mc.goal, settingsOf(state).ai)
if (paletteId === 'mission-status') return statusText(state)
return mc.last === null ? null : `${mc.last.ok ? '✓' : '✗'} ${mc.last.label}${mc.last.detail === '' ? '' : ` — ${mc.last.detail}`}`
return mc.last === null ? null : [`${mc.last.ok ? '✓' : '✗'} ${mc.last.label}${mc.last.detail === '' ? '' : ` — ${mc.last.detail}`}`, ...(mc.last.lines ?? []).map(line => ` ${line}`)].join('\n')
}
+7 -2
View File
@@ -45,9 +45,13 @@ export type McState = {
/** AIDefence's verdict on the goal (null: not screened yet or the screen is off), and whether the screen is on. */
screen: Screen | null
isScreenOn: boolean
last: { label: string; ok: boolean; detail: string; atMs?: number; next?: string } | null
/** `lines` add what one line cannot hold (which tasks are still pending after a failed create). */
last: { label: string; ok: boolean; detail: string; atMs?: number; next?: string; lines?: string[] } | null
}
/** Who resumed a mission: only the person re-arms hand-outs that ran out (#3823). */
export type ResumeBy = 'person' | 'model'
export type MissionActions = {
goal: (text: string) => void
profile: (profile: Profile) => void
@@ -58,7 +62,8 @@ export type MissionActions = {
/** Hands the next ready task to the primary session (asks first: it starts a model turn). */
next: () => void
pause: () => void
resume: () => void
/** Resume dispatching. The person's resume gives each task its hand-outs back; Claude's (`'model'`) keeps the counts (#3823). */
resume: (by?: ResumeBy) => void
cancel: () => void
/** Auto-run: when a task finishes and the session is idle, hand over the next ready one without asking. */
auto: (on: boolean) => void
@@ -0,0 +1,40 @@
/** The fields Claude's console_set may fill (ADR-444): each goes through the same action the page's own field does. Split out of model-tools.ts to keep it under 500 lines. */
import type { ModelToolDeps } from './model-tools'
import { DEV_FIELDS } from './data/devtools'
import { PROFILES, RIGORS } from './goap'
import { setResearch } from './mission-control'
import { RESEARCH_DEPTHS } from './mission-options'
export const SET_FIELDS = ['goal', 'profile', 'rigor', 'research.question', 'research.depth', 'research.cap', 'cost.budget'] as const
/** `line` is the console's one model-facing sanitiser (model-tools.ts modelLine): the field name is the model's own text. */
export function setField(deps: ModelToolDeps, field: string, value: string, line: (raw: unknown, max: number) => string): string | null {
const { state, control } = deps
const { mission } = control.actions
if (field === 'goal') mission.goal(value)
else if (field === 'profile') {
const found = PROFILES.find(profile => profile.id === value)
if (found === undefined) return `profile must be one of ${PROFILES.map(profile => profile.id).join(', ')}`
mission.profile(found.id)
} else if (field === 'rigor') {
const found = RIGORS.find(rigor => rigor === value)
if (found === undefined) return `rigor must be one of ${RIGORS.join(', ')}`
mission.rigor(found)
} else if (field === 'research.question') setResearch(state, { question: value })
else if (field === 'research.depth') {
const found = RESEARCH_DEPTHS.find(depth => depth === value)
if (found === undefined) return `research.depth must be one of ${RESEARCH_DEPTHS.join(', ')}`
setResearch(state, { depth: found })
} else if (field === 'research.cap') setResearch(state, { cap: value })
else if (field === 'cost.budget') control.actions.costBudgetDraft(value)
else if (field.startsWith('dev.') && DEV_FIELDS.includes(field.slice(4) as never)) control.actions.devtools.draft(field.slice(4) as never, value)
else return `unknown field "${line(field, 40)}". Fields: ${[...SET_FIELDS, 'dev.<field>'].join(', ')}`
control.host.invalidate()
return null
}
+36 -53
View File
@@ -11,11 +11,10 @@ import type { Register } from 'claude-code'
import type { Controller } from './controller'
import { ESCAPES, INVISIBLE, plain } from './data/parse'
import { askedBy } from './data/room'
import { DEV_FIELDS } from './data/devtools'
import { PROFILES, RIGORS } from './goap'
import { mcOf, setResearch } from './mission-control'
import { RESEARCH_DEPTHS } from './mission-options'
import { filterPalette, paletteEntries } from './palette'
import { mcOf } from './mission-control'
import { setField as setFieldOf } from './model-fields'
import { filterPalette, paletteEntries, WITHDRAW_ID, withdrawHint } from './palette'
import { isStale } from './runner'
import { hasSecret } from './screen'
import { catalogOf } from './plugin-catalog'
import { pluginNames, settingsOf } from './settings'
@@ -152,13 +151,15 @@ function within(work: Promise<void>, ms: number, host: Pick<Controller['host'],
}
/** Runs `fn` as Claude's own act: asks it raises on the way are Claude's, not the person's. Only the synchronous start counts; a deferred ask carries its origin itself (`ActionSpec.byModel`). */
function asModel<T>(state: State, fn: () => T): T {
function asModel<T>(state: State, fn: () => T, tag: number | null = null): T {
state.control.viaModel = true
state.control.callTag = tag
try {
return fn()
} finally {
state.control.viaModel = false
state.control.callTag = null
}
}
@@ -228,44 +229,11 @@ function optionChips(state: State): Map<string, string> {
return new Map(pluginNames(state, (catalogOf(state).plugins ?? []).filter(plugin => plugin.options.length > 0).map(plugin => plugin.name)).map(name => [name.replace(/^ruflo-/, ''), name]))
}
const SET_FIELDS = ['goal', 'profile', 'rigor', 'research.question', 'research.depth', 'research.cap', 'cost.budget'] as const
function setField(deps: ModelToolDeps, field: string, value: string): string | null {
const { state, control } = deps
const { mission } = control.actions
if (field === 'goal') mission.goal(value)
else if (field === 'profile') {
const found = PROFILES.find(profile => profile.id === value)
if (found === undefined) return `profile must be one of ${PROFILES.map(profile => profile.id).join(', ')}`
mission.profile(found.id)
} else if (field === 'rigor') {
const found = RIGORS.find(rigor => rigor === value)
if (found === undefined) return `rigor must be one of ${RIGORS.join(', ')}`
mission.rigor(found)
} else if (field === 'research.question') setResearch(state, { question: value })
else if (field === 'research.depth') {
const found = RESEARCH_DEPTHS.find(depth => depth === value)
if (found === undefined) return `research.depth must be one of ${RESEARCH_DEPTHS.join(', ')}`
setResearch(state, { depth: found })
} else if (field === 'research.cap') setResearch(state, { cap: value })
else if (field === 'cost.budget') control.actions.costBudgetDraft(value)
else if (field.startsWith('dev.') && DEV_FIELDS.includes(field.slice(4) as never)) control.actions.devtools.draft(field.slice(4) as never, value)
else return `unknown field "${modelLine(field, 40)}". Fields: ${[...SET_FIELDS, 'dev.<field>'].join(', ')}`
control.host.invalidate()
return null
}
/**
* An action the console queued (a palette entry, or the follow-up a field raised) is held to the same rules: above the level it is
* cancelled and nothing runs; in ask mode it waits for the person; in auto mode it confirms and reports. Null when nothing is pending.
*/
async function settlePending(deps: ModelToolDeps, tool: string, id: string, askedAt: number): Promise<{ status: 'refused' | 'waiting' | 'done'; text: string } | null> {
async function settlePending(deps: ModelToolDeps, tool: string, id: string, askedAt: number, own?: { call: number; card: number | null }): Promise<{ status: 'refused' | 'waiting' | 'done'; text: string } | null> {
const { state, control } = deps
const ai = settingsOf(state).ai
const level = levelOf(ai.modelControl)
@@ -280,6 +248,11 @@ async function settlePending(deps: ModelToolDeps, tool: string, id: string, aske
return { status: 'refused', text: `an action is waiting for the person ("${modelLine(pending.label, 80)}"), so yours was not queued. Do not run another until they answer. Nothing ran.` }
}
// Only a card this call started is settled here: the one it raised as it started (its id, taken then), or a deferred one that carries this call's
// number. A card that landed meanwhile from anything else (a screened ask of another call, a write queued earlier) is neither confirmed nor
// cancelled under this call's settlement (#3983): it waits for its own call, the person, or its window.
if (own !== undefined && pending.byCall !== own.call && !(pending.byCall === undefined && (pending.id ?? null) === own.card)) return null
const kind = classOf(pending)
// Claude's own ask: the row says who asked and what class it is (ADR-450 T14).
@@ -380,6 +353,9 @@ async function answer(name: string, input: Record<string, unknown>, deps: ModelT
if (state.control.turnCalls > MAX_CALLS_PER_TURN) return refuse(name, `more than ${MAX_CALLS_PER_TURN} console actions in one turn. Summarise for the person and stop.`)
try {
// A card past its window never blocks or reads as waiting: it is cleared first, with one event and "expired: ask again" as the last result.
if (state.pending !== null && isStale(state.pending)) control.runner.expireStale()
if (name === 'console_state') {
say(state, name, 'read the console', 'ok')
control.host.invalidate()
@@ -413,17 +389,18 @@ async function answer(name: string, input: Record<string, unknown>, deps: ModelT
if (leaksSecret(input.value, value)) return refuse(`set ${field}`, SECRET_REFUSAL)
if (state.pending !== null) return refuse(`set ${field}`, `an action is already waiting for the person ("${modelLine(state.pending.label, 80)}"). Do not change fields until they answer.`)
if (state.pending !== null) return refuse(`set ${field}`, `an action is already waiting for the person ("${modelLine(state.pending.label, 80)}"). Do not change fields until they answer${withdrawHint(state)}.`)
const askedAt = Date.now()
const problem = asModel(state, () => setField(deps, field, value))
const call = ++state.control.callSeq
const problem = asModel(state, () => setFieldOf(deps, field, value, modelLine), call)
if (problem !== null) return refuse(`set ${field}`, problem)
say(state, name, `set ${field}`, 'ok', value)
// Some fields raise a follow-up themselves (a goal is planned, then guidance is offered): it is held to the same rules.
const queued = await settlePending(deps, name, `after set ${field}`, askedAt)
const queued = await settlePending(deps, name, `after set ${field}`, askedAt, { call, card: (state as { pending: Pending | null }).pending?.id ?? null })
return `Set ${field}.${queued === null ? ' It is only filled in: run a console entry to act on it.' : ` The console then queued a follow-up. ${queued.text}`}`
}
@@ -434,26 +411,32 @@ async function answer(name: string, input: Record<string, unknown>, deps: ModelT
if (leaksSecret(input.text, text)) return refuse(`run ${id}`, SECRET_REFUSAL)
// The person's own waiting action is theirs to answer: never replaced, never cleared.
if (state.pending !== null) return refuse(`run ${id}`, `an action is already waiting for the person ("${modelLine(state.pending.label, 80)}"). Do not run another until they answer.`)
// The person's own waiting action is theirs to answer: never replaced, never cleared. Claude may take back only its own direct ask (the runner decides).
const blocked = id === WITHDRAW_ID ? asModel(state, () => control.runner.withdrawRefusal()) : state.pending === null ? null : `an action is already waiting for the person ("${modelLine(state.pending.label, 80)}"). Do not run another until they answer${withdrawHint(state)}.`
if (blocked !== null) return refuse(`run ${id}`, id === WITHDRAW_ID ? `not withdrawn: ${modelLine(blocked, 160)}. Nothing changed.` : blocked)
const askedAt = state.outcome?.atMs ?? 0
if (!asModel(state, () => control.runner.runById(id, text, { exact: true }))) return refuse(`run ${id}`, `no palette entry "${modelLine(id, 40)}" right now. Call console_state for the entries.`)
const call = ++state.control.callSeq
if (!asModel(state, () => control.runner.runById(id, text, { exact: true, direct: true }), call)) return refuse(`run ${id}`, `no palette entry "${modelLine(id, 40)}" right now. Call console_state for the entries.`)
// The card this call raised, by id, taken before anything is awaited: a read still running below may be followed by a card that landed on its own.
const raisedCard = state.pending?.id ?? null
await control.runner.settled()
if (state.pending === null) {
const done = state.outcome !== null && state.outcome.atMs > askedAt ? state.outcome : null
// Only a card this call started is settled by it (settlePending): the one it raised, or a deferred one carrying its number.
const settled = state.pending === null ? null : await settlePending(deps, name, `run ${id}`, askedAt, { call, card: raisedCard })
say(state, name, `run ${id}`, done === null || done.ok ? 'ok' : 'error', done?.detail ?? '')
if (settled !== null) return settled.status === 'refused' ? `Refused: ${settled.text}` : settled.text
return done === null ? `Ran ${id}.` : `${done.ok ? 'Done' : 'Failed'}: ${modelLine(done.label, 100)}. ${modelLine(done.detail, 200)}${(done.lines ?? []).length > 0 ? `\n${(done.lines ?? []).slice(0, 12).map(line => modelLine(line, 160)).join('\n')}` : ''}`
}
const done = state.outcome !== null && state.outcome.atMs > askedAt ? state.outcome : null
const settled = await settlePending(deps, name, `run ${id}`, askedAt)
say(state, name, `run ${id}`, done === null || done.ok ? 'ok' : 'error', done?.detail ?? '')
return settled === null ? `Ran ${id}.` : settled.status === 'refused' ? `Refused: ${settled.text}` : settled.text
return done === null ? `Ran ${id}.` : `${done.ok ? 'Done' : 'Failed'}: ${modelLine(done.label, 100)}. ${modelLine(done.detail, 200)}${(done.lines ?? []).length > 0 ? `\n${(done.lines ?? []).slice(0, 12).map(line => modelLine(line, 160)).join('\n')}` : ''}`
} catch (error) {
say(state, name, name, 'error', error instanceof Error ? error.message : 'failed')
+5 -3
View File
@@ -10,7 +10,8 @@ import type { ActionSpec } from './actions'
import { autoSpec, tool, type AutoEntry } from './automate'
import { recallEntries } from './recall'
import { EPOCHS, freeText, objectIn, parseTrain, PATTERNS, tableRows, type Pattern } from './data/automate'
import { numberOf, plain, recordOf } from './data/parse'
import { plain, recordOf } from './data/parse'
import { ratioOf } from './data/safe'
import { labLines } from './mh-lab'
import type { State } from './state'
@@ -54,11 +55,12 @@ function routeRead(stdout: string, stderr: string): string[] {
if (value === null || primary === null) return labLines('nn-route', stdout, stderr)
const confidence = numberOf(primary.confidence)
// A confidence is a 0..1 ratio: clamped where it is read, so `1e300` is not drawn as "1e+302%" (#3822).
const confidence = ratioOf(primary.confidence)
const out = [`→ ${plain(String(primary.type ?? 'n/a'), 30)}${confidence !== undefined ? ` · ${Math.round(confidence * 100)}%` : ''} · ${plain(String(recordOf(value.routing)?.method ?? 'n/a'), 30)}${value.matchedPattern !== undefined ? ` · pattern ${plain(String(value.matchedPattern), 30)}` : ''}`]
for (const alt of (Array.isArray(value.alternativeAgents) ? value.alternativeAgents : []).slice(0, 4).map(recordOf)) {
const score = numberOf(alt?.confidence ?? alt?.score)
const score = ratioOf(alt?.confidence ?? alt?.score)
if (alt !== null) out.push(` or ${plain(String(alt.type ?? alt.agent ?? ''), 30)}${score !== undefined ? ` · ${Math.round(score * 100)}%` : ''}`)
}
+13 -1
View File
@@ -28,13 +28,23 @@ import { VIEWS, type State, type ViewId } from './state'
import { XRUV } from './xruv'
import { VEC, vecSpec, vecWhy } from './vector'
import { selection } from './views/select'
import { plain } from './data/parse'
export type PaletteRun =
| { kind: 'spec'; spec: ActionSpec | null; why: string }
| { kind: 'view'; view: ViewId }
| { kind: 'drill'; agentId: string }
| { kind: 'text'; keyword: string; make: (text: string) => ActionSpec | null; why?: (text: string) => string }
| { kind: 'command'; name: 'refresh' | 'help' | 'close' }
| { kind: 'command'; name: 'refresh' | 'help' | 'close' | 'withdraw' }
/** The entry Claude uses to take back its own waiting ask; it is listed only while a card Claude raised is waiting. */
export const WITHDRAW_ID = 'ask-withdraw'
/** A card Claude raised by its own console_run, of the write class: the only kind it may withdraw (the runner also matches the card's id). */
export const canWithdraw = (state: State): boolean => state.pending?.source === 'claude' && state.pending.origin === 'console_run' && state.pending.kind === 'write'
/** How Claude can stop waiting on its own card, for a refusal's text: withdraw it. Any other card waits for the person or its window. */
export const withdrawHint = (state: State): string => (canWithdraw(state) ? `, or withdraw your own ask with console_run ${WITHDRAW_ID}` : '')
export type PaletteEntry = { id: string; label: string; group: string; run: PaletteRun }
@@ -192,6 +202,8 @@ export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {
for (const view of VIEWS) add(`view-${view.id}`, 'views', `go to ${view.label}${view.key === '' ? '' : ` (${view.key})`}`, { kind: 'view', view: view.id })
// Claude can take back its own waiting ask (never the person's): a read, it runs nothing and only clears the card.
if (canWithdraw(state) && state.pending !== null) add(WITHDRAW_ID, 'console', `withdraw Claude's waiting ask ("${plain(state.pending.label, 60)}"): nothing runs`, { kind: 'command', name: 'withdraw' })
add('refresh', 'console', 'refresh now', { kind: 'command', name: 'refresh' })
add('help', 'console', 'help: keys and commands', { kind: 'command', name: 'help' })
add('close', 'console', 'close the console', { kind: 'command', name: 'close' })
+20 -9
View File
@@ -9,6 +9,7 @@
import { exec } from './actions'
import { jsonAfter } from './data/cli'
import { plain, recordOf } from './data/parse'
import { measureOf } from './data/safe'
import { labLines } from './mh-lab'
import { mcpReader, textLines, type Reader, type SecCost } from './secure'
import type { State } from './state'
@@ -49,14 +50,21 @@ export function sparkline(values: readonly number[], width = 32): string {
/** Any value as one cleaned cell: numbers must be finite and sane (a hostile 1e300 is "n/a", not a display value), text goes through plain(). */
function show(value: unknown, max = 24): string {
if (typeof value === 'number') return Number.isFinite(value) && Math.abs(value) <= 1e12 ? String(value) : 'n/a'
if (typeof value === 'number') return measureOf(value) === undefined ? 'n/a' : String(value)
if (value === undefined || value === null) return 'n/a'
return plain(typeof value === 'string' ? value : typeof value === 'boolean' ? String(value) : '', max) || 'n/a'
}
const ms = (value: unknown, digits = 3): string => (typeof value === 'number' && Number.isFinite(value) ? `${value.toFixed(digits)}ms` : 'n/a')
const mb = (bytes: unknown): string => (typeof bytes === 'number' && Number.isFinite(bytes) ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : 'n/a')
// Every number below is bounded where it is read (#3822): `1e999` parses as Infinity and `1e300` prints as "1e+300", neither a measurement.
const as = (value: unknown, text: (n: number) => string): string => {
const n = measureOf(value)
return n === undefined ? 'n/a' : text(n)
}
const ms = (value: unknown, digits = 3): string => as(value, n => `${n.toFixed(digits)}ms`)
const mb = (bytes: unknown): string => as(bytes, n => `${(n / 1024 / 1024).toFixed(1)} MB`)
const pct = (value: unknown, digits?: number): string => as(value, n => `${digits === undefined ? String(n) : n.toFixed(digits)}%`)
/** `performance metrics --format json`: memory, CPU, load and the event-loop latency, which feeds the sparkline. */
export const metricsReader: Reader = (stdout, stderr, state) => {
@@ -68,18 +76,19 @@ export const metricsReader: Reader = (stdout, stderr, state) => {
const cpu = recordOf(record.cpu) ?? {}
const latency = recordOf(record.latency) ?? {}
const cache = recordOf(record.cache) ?? {}
const avg = typeof latency.avgMs === 'number' && Number.isFinite(latency.avgMs) ? latency.avgMs : null
const avg = measureOf(latency.avgMs) ?? null
const heap = measureOf(memory.heapUsed)
const memo = perfMemo(state)
if (avg !== null) memo.loop = [...memo.loop, avg].slice(-KEEP)
memo.heapMb = typeof memory.heapUsed === 'number' ? memory.heapUsed / 1024 / 1024 : null
memo.heapMb = heap === undefined ? null : heap / 1024 / 1024
memo.atMs = Date.now()
const load = Array.isArray(cpu.loadAverage) ? cpu.loadAverage.filter(value => typeof value === 'number').map(value => value.toFixed(2)).join(' ') : 'n/a'
const load = Array.isArray(cpu.loadAverage) ? cpu.loadAverage.flatMap(value => (measureOf(value) === undefined ? [] : [as(value, n => n.toFixed(2))])).join(' ') : 'n/a'
return [
`event-loop latency ${ms(avg)} · heap ${mb(memory.heapUsed)} of ${mb(memory.heapTotal)} · rss ${mb(memory.rss)}`,
`system memory ${typeof memory.systemPercent === 'number' ? `${memory.systemPercent}%` : 'n/a'} · load ${load}`,
`system memory ${pct(memory.systemPercent)} · load ${load}`,
`embedding cache ~${show(cache.entries)} entries · HNSW ${show(cache.hnswEntries)} entries`,
'measured in the CLI process at the moment it ran: one sample per run',
]
@@ -108,7 +117,9 @@ export const reportReader: Reader = (stdout, stderr, state) => {
const history = (Array.isArray(result.history) ? result.history : []).map(recordOf).flatMap(row => {
const avg = recordOf(row?.latency)?.avg
return typeof avg === 'number' && Number.isFinite(avg) ? [avg] : []
const sample = measureOf(avg)
return sample === undefined ? [] : [sample]
})
const memo = perfMemo(state)
const cpu = recordOf(current.cpu) ?? {}
@@ -119,7 +130,7 @@ export const reportReader: Reader = (stdout, stderr, state) => {
memo.atMs = Date.now()
return [
`cpu ${typeof cpu.usage === 'number' ? `${cpu.usage.toFixed(1)}%` : 'n/a'} of ${show(cpu.cores)} cores · memory ${show(memory.used)} of ${show(memory.total)} MB · heap ${show(memory.heap)} MB`,
`cpu ${pct(cpu.usage, 1)} of ${show(cpu.cores)} cores · memory ${show(memory.used)} of ${show(memory.total)} MB · heap ${show(memory.heap)} MB`,
`latency avg ${ms(latency.avg)} · p50 ${ms(latency.p50)} · p95 ${ms(latency.p95)} · p99 ${ms(latency.p99)}`,
`history: ${history.length} stored sample${history.length === 1 ? '' : 's'} in .claude-flow/performance/metrics.json`,
...labLines('performance_report', JSON.stringify({ trends: result.trends, recommendations: result.recommendations })).slice(0, 12),
@@ -69,6 +69,25 @@ export function installedOf(state: State): { installed: Set<string>; enabled: Se
}
}
/**
* The catalog plugins whose mod Claude Code loaded in this session without installing the plugin (mod sync: the provenance reads
* `<plugin>@synced` or `<plugin>@inline`). Installed plugins are left out: they are already shown by their install state.
*/
export function syncedOf(state: State): Set<string> {
const { installed } = installedOf(state)
const names = new Set<string>()
for (const mod of state.mods) {
if (!mod.isLoaded) continue
const bare = /^(.+)@(?:synced|inline)$/.exec(mod.provenance)?.[1]
if (bare !== undefined && !installed.has(bare)) names.add(bare)
}
return names
}
export const listOf = (state: State): CatalogPlugin[] => {
const catalog = catalogOf(state)
const { installed } = installedOf(state)
+167 -15
View File
@@ -20,6 +20,18 @@ import { prettyLines } from './result-lines'
export const PENDING_TTL_MS = 30_000
/** The state.timers key of the expiry timer, so the controller's stop and close cancel it with the rest. */
export const EXPIRY_TIMER = 'pending-expiry'
/** A typed Yes (`/ruflo yes`, bound to no card) is refused this soon after Claude raised the card, or after a card left unanswered. */
export const UNBOUND_FRESH_MS = 3_000
export const UNBOUND_REPLACED_MS = 10_000
/** Claude may withdraw at most this many asks per minute, and may not re-ask the same label this soon after withdrawing it. */
export const WITHDRAW_MAX_PER_MIN = 3
export const REASK_COOLDOWN_MS = 10_000
/** True when a waiting card has outlived its window: a Yes for it would be refused, so it only blocks the next ask. */
export const isStale = (pending: Pick<Pending, 'askedAtMs'>, nowMs = Date.now()): boolean => nowMs - pending.askedAtMs >= PENDING_TTL_MS
export type RunnerDeps = {
/** A read of the disk that starts after this call. */
freshRead: () => Promise<void>
@@ -35,9 +47,17 @@ export type Runner = {
/** `seen` is the id of the card the person said Yes to: when another card took its place meanwhile, nothing runs and the new card stays (ADR-450 T17). */
confirm: (seen?: number) => Promise<void>
cancel: () => void
/** Clears a card left past PENDING_TTL_MS, unrun, with one event and an "expired: ask again" outcome. True when it cleared one. */
expireStale: (nowMs?: number) => boolean
/** Clears the waiting card only when Claude raised it; the person's own card is never withdrawn. True when it cleared one. */
withdraw: () => boolean
/** Why Claude may not withdraw the waiting card now, or null when it may. */
withdrawRefusal: () => string | null
runEntry: (entry: PaletteEntry, text: string) => void
/** `exact` (the model path, ADR-450 T13) resolves the id as written and never falls back to fuzzy matching. */
runById: (id: string, text: string, options?: { exact?: boolean }) => boolean
runById: (id: string, text: string, options?: { exact?: boolean; direct?: boolean }) => boolean
/** A Yes typed with no card id (`/ruflo yes`): refused while the card is too new or just replaced one, else it answers the card waiting now. */
confirmUnbound: (card?: number) => Promise<void>
/** Resolves when the read started last has finished: `/ruflo run` waits on it to answer with what it printed. */
settled: () => Promise<void>
/** Resolves when the last action that brought its own `run` (and is not awaited by `confirm`) has finished: the model tools wait on it, with a limit. */
@@ -49,6 +69,12 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
let asks = 0
let inflight: Promise<void> = Promise.resolve()
let background: Promise<void> = Promise.resolve()
// The card Claude raised by its own direct console_run (its id), the only one it may withdraw; set while runById({ direct }) runs.
let directCardId: number | null = null
let isDirectRun = false
// When a card last left with no answer from the person (expired or withdrawn): a typed Yes soon after may be meant for it.
let goneUnansweredAtMs = -Infinity
const withdrawals: { label: string; atMs: number }[] = []
const say = (label: string, ok: boolean, detail: string, lines?: string[]) => {
state.outcome = { label, ok, verified: 'n/a', detail, atMs: Date.now(), ...(lines !== undefined && { lines }) }
@@ -58,9 +84,19 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
async function execute(spec: ActionSpec): Promise<void> {
// A harness run reports into the terminal and may take minutes: it does not hold the other buttons.
if (spec.run !== undefined) {
// The outcome slot as this run starts. Every writer replaces the object (never edits it), so "still this object" means no other
// action reported meanwhile: exact, where comparing millisecond stamps let a same-millisecond result be overwritten.
const outcomeAtStart = state.outcome
const running = spec.run()
background = running.then(() => undefined, () => undefined)
// A run that answers how it ended becomes the outcome when it ends, however long after the confirm that is: the page shows it on its
// own panel, and this is the one place console_state and `/ruflo yes` read (a long mission create used to leave an older result there).
// One outcome per action: when another action reported meanwhile, its outcome stays, and this one goes to the Events feed instead.
background = running.then(report => {
if (report === undefined || report === null) return
if (state.outcome === outcomeAtStart) say(report.label, report.ok, report.detail, report.lines)
else record(state.events, [{ atMs: Date.now(), kind: 'tools', text: `${report.ok ? '✓' : '✗'} ${plain(report.label, 80)}: ${plain(report.detail, 160)} (finished after a newer result)` }])
}, () => undefined)
// A read that runs its own command (a skills search) is waited on, so `/ruflo run` answers with what it found.
if (spec.isReadOnly === true) await running
@@ -155,15 +191,76 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
}
}
/** Forgets the waiting card and its expiry timer (kept in state.timers, so closing the console cancels it too). */
function clear(): void {
state.timers.get(EXPIRY_TIMER)?.cancel()
state.timers.delete(EXPIRY_TIMER)
directCardId = null
pendingSpec = null
state.pending = null
}
function expireStale(nowMs = Date.now()): boolean {
const pending = state.pending
if (pending === null || !isStale(pending, nowMs)) return false
clear()
goneUnansweredAtMs = nowMs
say(pending.label, false, `expired: ask again. Nobody answered within ${PENDING_TTL_MS / 1000} s, so it did not run`)
if (state.outcome !== null) state.outcome.expired = true
record(state.events, [{ atMs: nowMs, kind: 'tools', text: `ask for "${plain(pending.label, 60)}" expired after ${PENDING_TTL_MS / 1000} s, not run` }])
return true
}
/**
* Why Claude may not withdraw the waiting card, or null when it may. Only its own direct console_run ask, matched by id, and only of the write class:
* a spend, install, network or delete card is one the person must see, and it now leaves by itself at the window. At most a few per minute.
*/
function withdrawRefusal(nowMs = Date.now()): string | null {
const pending = state.pending
if (pending === null) return 'nothing is waiting'
if (!state.control.viaModel) return 'only Claude withdraws its own ask; the person answers a card with Yes or No'
if (pending.source !== 'claude' || pending.origin !== 'console_run' || pending.id === undefined || pending.id !== directCardId) return 'that card was not raised by your own console_run: only the person answers it'
if (pending.kind !== 'write') return `it is a ${pending.kind ?? 'unclassed'} action the person must see; it expires by itself ${PENDING_TTL_MS / 1000} s after the ask`
if (withdrawals.filter(entry => nowMs - entry.atMs < 60_000).length >= WITHDRAW_MAX_PER_MIN) return `${WITHDRAW_MAX_PER_MIN} asks were withdrawn in the last minute: leave this one to the person`
return null
}
function withdraw(): boolean {
const pending = state.pending
const nowMs = Date.now()
const refused = withdrawRefusal(nowMs)
if (pending === null || refused !== null) {
say('withdraw', false, `not withdrawn: ${refused ?? 'nothing is waiting'}`)
return false
}
clear()
goneUnansweredAtMs = nowMs
withdrawals.push({ label: pending.label, atMs: nowMs })
if (withdrawals.length > 20) withdrawals.shift()
say('withdrawn ask', true, `withdrew "${plain(pending.label, 80)}": it did not run`)
record(state.events, [{ atMs: nowMs, kind: 'tools', text: `Claude withdrew its ask "${plain(pending.label, 60)}", not run` }])
return true
}
function ask(spec: ActionSpec | null, why: string): void {
state.palette.isOpen = false
// A card left past its window blocks nothing: it is cleared (and said so) before this ask is looked at.
expireStale()
// Where this came from: the page puts the confirm and the answer right after that element. A headless run has no press, so it falls back to the top.
state.origin = state.lastPressed
state.lastPressed = null
if (spec === null) {
pendingSpec = null
state.pending = null
clear()
say('nothing to do', false, why)
return
@@ -180,6 +277,15 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
return
}
// Withdrawing and asking again is not a loop Claude can run: the same ask waits out a cooldown after its withdrawal.
const withdrawn = byModel ? withdrawals.find(entry => entry.label === spec.label && Date.now() - entry.atMs < REASK_COOLDOWN_MS) : undefined
if (withdrawn !== undefined) {
say('not queued', false, `Claude withdrew this same ask ${Math.round((Date.now() - withdrawn.atMs) / 1000)} s ago: wait ${REASK_COOLDOWN_MS / 1000} s, or leave it to the person`)
return
}
// Claude's ask never replaces what the person has waiting: their Yes would run Claude's action instead of the one they read (ADR-450 T17).
if (byModel && state.pending !== null) {
say('not queued', false, `an action is already waiting for the person ("${plain(state.pending.label, 80)}"): Claude's request was dropped`)
@@ -199,7 +305,11 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
asks += 1
const pending: Pending = { id: asks, view: state.view, ...(kind !== null && { rememberKey: kind }), ...(spec.scope !== undefined && { scope: spec.scope }), label: spec.label, args: spec.args, expect: spec.expect, askedAtMs: Date.now(), source: byModel ? 'claude' : 'you', ...(spec.shows !== undefined && { shows: spec.shows }), ...(spec.note !== undefined && { note: spec.note }), ...(spec.declared !== undefined && { declared: spec.declared }) }
// Only an ask raised inside Claude's own console_run call (not one that landed later after a screen, nor a mission follow-up) is Claude's to withdraw.
const isDirect = isDirectRun && state.control.viaModel && spec.byModel !== true
// The Claude call that started this ask: named by the spec when the ask landed later, else the call whose synchronous start is running now.
const byCall = byModel ? (spec.byCall ?? (state.control.viaModel ? (state.control.callTag ?? undefined) : undefined)) : undefined
const pending: Pending = { id: asks, view: state.view, ...(isDirect && { origin: 'console_run' as const }), ...(byCall !== undefined && { byCall }), ...(kind !== null && { rememberKey: kind }), ...(spec.scope !== undefined && { scope: spec.scope }), label: spec.label, args: spec.args, expect: spec.expect, askedAtMs: Date.now(), source: byModel ? 'claude' : 'you', ...(spec.shows !== undefined && { shows: spec.shows }), ...(spec.note !== undefined && { note: spec.note }), ...(spec.declared !== undefined && { declared: spec.declared }) }
// Claude's ask that was screened first lands after every tool call of Claude's returned, so no call is left to gate it: the level and Stop are
// checked now, not as they were when it was raised, and a refused ask is not queued (nothing waits for a Yes the settings no longer allow).
@@ -214,8 +324,13 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
}
}
// Only the person's own press replaces a card here (Claude's ask over a waiting card was dropped above): their typed Yes is for this new card.
clear()
pendingSpec = spec
state.pending = pending
if (isDirect) directCardId = asks
// At the window's end the card is cleared on the console's clock, so it never sits past it blocking every other ask.
if (typeof host.after === 'function') state.timers.set(EXPIRY_TIMER, host.after(PENDING_TTL_MS + 250, () => void expireStale()))
host.invalidate()
}
@@ -236,8 +351,7 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
if (claudes !== null && state.pending !== null) {
const label = state.pending.label
pendingSpec = null
state.pending = null
clear()
say(label, false, `not run: ${claudes}. Run it from the palette yourself if you want it`)
record(state.events, [{ atMs: Date.now(), kind: 'tools', text: `Claude's card "${plain(label, 60)}" was not run: ${claudes}` }])
@@ -249,8 +363,7 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
const waitedMs = state.pending === null ? 0 : Date.now() - state.pending.askedAtMs
pendingSpec = null
state.pending = null
clear()
if (spec === null || !isFresh || state.isActing) {
if (spec !== null && !isFresh) {
@@ -267,9 +380,41 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
await execute(spec)
}
async function confirmUnbound(card?: number): Promise<void> {
const pending = state.pending
const nowMs = Date.now()
if (pending === null) return confirm(card)
// `/ruflo yes <id>` names its card: it answers that card or nothing (confirm refuses when another card took its place).
if (card !== undefined) return confirm(card)
// A bare Yes names no card, so it answers only the card the person was shown: drawn in a pane they can see, or named in the answer to their
// own typed ask. Any other card is a stranger to them, however it got there (Claude's ask, or one that replaced the card they read).
if (state.shownCard !== pending.id) {
say(pending.label, false, `not run: card ${pending.id ?? '?'} ("${plain(pending.label, 60)}") was not put in front of you, so a bare yes may be meant for another. Read it in the console and press Yes on it, or type /ruflo yes ${pending.id ?? '<id>'}`)
record(state.events, [{ atMs: nowMs, kind: 'tools', text: `a typed yes did not run "${plain(pending.label, 60)}": the card had not been shown to the person` }])
return
}
// A card Claude has only just raised, or one that took the place of a card that left unanswered, is answered on the card itself (its button
// or y), or by its id.
const isNewClaude = pending.source === 'claude' && nowMs - pending.askedAtMs < UNBOUND_FRESH_MS
const isReplacement = nowMs - goneUnansweredAtMs < UNBOUND_REPLACED_MS
if (isNewClaude || isReplacement) {
say(pending.label, false, `not run: ${isNewClaude ? 'Claude raised this card a moment ago' : 'this card replaced one that left unanswered a moment ago'}, so a typed yes may be meant for another. Read it and press Yes on the card itself, or type /ruflo yes ${pending.id ?? '<id>'}`)
record(state.events, [{ atMs: nowMs, kind: 'tools', text: `a typed yes did not run "${plain(pending.label, 60)}": the card was new or had just replaced another` }])
return
}
return confirm(pending.id)
}
function cancel(): void {
pendingSpec = null
state.pending = null
clear()
host.invalidate()
}
@@ -304,7 +449,8 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
deps.drill(entry.run.agentId)
break
case 'command':
deps.command(entry.run.name)
if (entry.run.name === 'withdraw') withdraw()
else deps.command(entry.run.name)
break
}
@@ -312,16 +458,22 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
}
/** A palette entry by its id (`/ruflo run <id> [text]`, an approval's button): false when there is none now. */
function runById(id: string, text: string, options: { exact?: boolean } = {}): boolean {
function runById(id: string, text: string, options: { exact?: boolean; direct?: boolean } = {}): boolean {
const entries = paletteEntries(state, Date.now())
const entry = entries.find(candidate => candidate.id === id) ?? (text === '' || options.exact === true ? undefined : filterPalette(entries, `${id} ${text}`, 'all')[0])
if (entry === undefined) return false
runEntry(entry, entry.run.kind === 'text' ? textOfQuery(`${id} ${text}`, entry.run.keyword) : text)
isDirectRun = options.direct === true
try {
runEntry(entry, entry.run.kind === 'text' ? textOfQuery(`${id} ${text}`, entry.run.keyword) : text)
} finally {
isDirectRun = false
}
return true
}
return { ask, confirm, cancel, runEntry, runById, settled: () => inflight, finished: () => background }
return { ask, confirm, confirmUnbound, cancel, expireStale, withdraw, withdrawRefusal: () => withdrawRefusal(), runEntry, runById, settled: () => inflight, finished: () => background }
}
+66 -11
View File
@@ -11,6 +11,7 @@ import { exec, type ActionSpec } from './actions'
import { jsonAfter } from './data/cli'
import { countsWith, rowsWith, type Findings } from './data/failure'
import { plain, recordOf } from './data/parse'
import { countOf as wholeCount, measureOf, ratioOf } from './data/safe'
import { labLines } from './mh-lab'
import type { State } from './state'
@@ -44,7 +45,33 @@ export type SecText = { id: string; name: string; about: string; label: string;
export type Check = { status: 'pass' | 'warn' | 'fail'; name: string; message: string }
/** What the view draws beyond the result lines: the last findings by severity, the last doctor checks, the field's text. */
export type SecMemo = { findings: { source: string; counts: Record<Severity, number>; atMs: number } | null; doctor: { label: string; checks: Check[]; atMs: number } | null; draft: string }
export type SecMemo = { findings: SecFindings | null; doctor: { label: string; checks: Check[]; atMs: number } | null; draft: string }
/**
* Counts by severity. `unreadable` names the levels whose count the tool printed but no reader can trust, and `isTotalUnknown` says the same of
* the total (#3822): unknown, never a measured 0. An unknown level's `counts` entry is only a lower bound (the findings listed at that level).
*/
export type SecFindings = { source: string; counts: Record<Severity, number>; unreadable?: readonly Severity[]; isTotalUnknown?: boolean; atMs: number }
/** One level's count as text: `?` when it was unreadable, `≥n ?` when n findings of that level were listed. */
export const countText = (findings: SecFindings, level: Severity): string => {
if (!(findings.unreadable ?? []).includes(level)) return String(findings.counts[level])
return findings.counts[level] > 0 ? `≥${findings.counts[level]} ?` : '?'
}
/** What the band says about the last findings: high or critical ones, or that the counts could not be read. Null when there is nothing to warn of. */
export function securityBand(findings: SecFindings | null): { text: string; compact: string; isAttention: boolean } | null {
if (findings === null) return null
const serious = findings.counts.critical + findings.counts.high
const isUnknown = (findings.unreadable ?? []).length > 0 || findings.isTotalUnknown === true
const more = isUnknown ? '+' : ''
if (serious > 0) return { text: `🔒 ${serious}${more} high or critical`, compact: `🔒 ${serious}${more}`, isAttention: findings.counts.critical > 0 || isUnknown }
return isUnknown ? { text: '🔒 security counts unreadable', compact: '🔒 ?', isAttention: true } : null
}
const memos = new WeakMap<State, SecMemo>()
@@ -99,22 +126,50 @@ export const scanReader: Reader = (stdout, stderr, state) => {
if (record === null || summary === null) return textLines(stdout, stderr)
const counts = zero()
for (const level of SEVERITIES) counts[level] = typeof summary[level] === 'number' ? summary[level] : 0
secMemo(state).findings = { source: `scan ${plain(String(record.type ?? ''), 8)} ${plain(String(record.depth ?? ''), 10)}`.trim(), counts, atMs: Date.now() }
const findings = (Array.isArray(record.findings) ? record.findings : []).map(recordOf).filter(row => row !== null)
const total = typeof summary.total === 'number' ? summary.total : findings.length
const listed = zero()
const counts = zero()
const unreadable: Severity[] = []
for (const row of findings) listed[levelOf(row.severity) ?? 'low'] += 1
// A count is whole, non-negative and capped where it is read (#3822): `1e999` parses as Infinity. Every count, and the total, is at least what
// was listed, so a summary that under-reports cannot hide a finding or read CLEAN beside one. A count the tool printed but no reader can trust
// stays UNKNOWN (the listed findings are only its lower bound), and the result, the page and the band all say so.
for (const level of SEVERITIES) {
const raw = summary[level]
const count = wholeCount(raw)
counts[level] = Math.max(count ?? 0, listed[level])
if (count === undefined && raw !== undefined) unreadable.push(level)
}
const readTotal = wholeCount(summary.total)
const isTotalUnknown = readTotal === undefined && summary.total !== undefined
const total = Math.max(readTotal ?? 0, findings.length)
const memo: SecFindings = { source: `scan ${plain(String(record.type ?? ''), 8)} ${plain(String(record.depth ?? ''), 10)}`.trim(), counts, ...(unreadable.length > 0 && { unreadable }), ...(isTotalUnknown && { isTotalUnknown }), atMs: Date.now() }
secMemo(state).findings = memo
const isUnknown = unreadable.length > 0 || isTotalUnknown
const head = counts.critical + counts.high > 0 ? 'ATTENTION' : isUnknown ? 'COUNTS UNREADABLE' : total === 0 ? 'CLEAN' : 'REVIEW'
const totalText = isTotalUnknown ? `${total > 0 ? `≥${total} ` : ''}? findings (total unreadable)` : `${total} finding${total === 1 ? '' : 's'}`
return [
`${counts.critical + counts.high > 0 ? 'ATTENTION' : total === 0 ? 'CLEAN' : 'REVIEW'} · ${total} finding${total === 1 ? '' : 's'} · depth ${plain(String(record.depth ?? 'n/a'), 10)} · type ${plain(String(record.type ?? 'n/a'), 8)}`,
`by severity: ${SEVERITIES.map(level => `${level} ${counts[level]}`).join(' · ')}`,
`${head} · ${totalText} · depth ${plain(String(record.depth ?? 'n/a'), 10)} · type ${plain(String(record.type ?? 'n/a'), 8)}`,
`by severity: ${SEVERITIES.map(level => `${level} ${countText(memo, level)}`).join(' · ')}${unreadable.length > 0 ? ` (counts unreadable: ${unreadable.join(', ')}; a listed finding is a lower bound)` : ''}`,
...findings.slice(0, 30).map(row => `[${levelOf(row.severity) ?? 'low'}] ${plain(String(row.type ?? ''), 40)} · ${plain(String(row.location ?? ''), 60)} · ${plain(String(row.description ?? ''), 80)}`),
...(findings.length > 30 ? [`… ${findings.length - 30} more`] : []),
]
}
/** A confidence as ` 87%`, clamped to 0..100; empty when it is not a finite number (`1e999` would draw "Infinity%") (#3822). */
const percent = (value: unknown): string => {
const ratio = ratioOf(value)
return ratio === undefined ? '' : ` ${Math.round(ratio * 100)}%`
}
/** One verdict object (defend, aidefence_scan, channel-scan, scan-plan): the verdict first, so an exit 1 reads right. */
function verdictLines(record: Record<string, unknown>, source: string, state: State): string[] | null {
const threats = (Array.isArray(record.threats) ? record.threats : Array.isArray(record.findings) ? record.findings : null)?.map(recordOf).filter(row => row !== null) ?? null
@@ -138,7 +193,7 @@ function verdictLines(record: Record<string, unknown>, source: string, state: St
return [
head.join(' · '),
...(threats ?? []).slice(0, 20).map(row => `[${levelOf(row.severity) ?? 'low'}] ${plain(String(row.type ?? row.kind ?? ''), 32)}${typeof row.confidence === 'number' ? ` ${Math.round(row.confidence * 100)}%` : ''} · ${plain(String(row.description ?? row.reason ?? ''), 110)}`),
...(threats ?? []).slice(0, 20).map(row => `[${levelOf(row.severity) ?? 'low'}] ${plain(String(row.type ?? row.kind ?? ''), 32)}${percent(row.confidence)} · ${plain(String(row.description ?? row.reason ?? ''), 110)}`),
]
}
@@ -178,7 +233,7 @@ export const compositionReader: Reader = (stdout, stderr) => {
if (suspects === undefined) return textLines(stdout, stderr)
return [`${suspects.length} suspect${suspects.length === 1 ? '' : 's'} in the CLI's registered MCP tool descriptions`, ...suspects.slice(0, 25).map(row => `${plain(String(row.tool ?? ''), 32)} · ${typeof row.score === 'number' ? row.score.toFixed(2) : 'n/a'} · ${plain(String(row.reason ?? ''), 100)}`)]
return [`${suspects.length} suspect${suspects.length === 1 ? '' : 's'} in the CLI's registered MCP tool descriptions`, ...suspects.slice(0, 25).map(row => `${plain(String(row.tool ?? ''), 32)} · ${measureOf(row.score)?.toFixed(2) ?? 'n/a'} · ${plain(String(row.reason ?? ''), 100)}`)]
}
/** Doctor's `✓|⚠|✗ Name: message` rows (colours stripped), its summary, and anything after them (suggested fixes). */
+51 -15
View File
@@ -6,9 +6,10 @@
* and almost nothing while it is closed. Nothing here starts a process, makes a model call, or touches a session it lists.
*/
import { buildIndex, type Index, type Scanned } from './data/sessions-index'
import { attentionOf, countsOf, markViewed, viewedOf, type AttentionItem, type Viewed } from './data/sessions-attention'
import { attentionOf, countsOf, markViewed, needsRewrite, viewedOf, type AttentionItem, type Viewed } from './data/sessions-attention'
import { claudeAdapter } from './data/harness-claude'
import { codexAdapter } from './data/harness-codex'
import { passBudget } from './data/harness-track'
import { rufloAdapter, type LedgerFacts, type RufloInput } from './data/harness-ruflo'
import type { HarnessAdapter, SessionFs } from './data/harness'
import { mcOf } from './mission-control'
@@ -40,8 +41,13 @@ export type Workspace = {
/** A line about the last action that could not run, with its reason. */
note: string
signature: string
/** The counts last written to the summary file, so it is rewritten only when one changes. */
/** The counts last written to the summary file, so it is rewritten only when one changes or the heartbeat is due. */
summary: string
/** When the summary file was last written. */
summaryAtMs: number
/** After a failed summary write: how long the current wait is, and when the next attempt may run. */
writeBackoffMs: number
writeRetryAtMs: number
timer: { cancel: () => void } | null
}
@@ -59,7 +65,7 @@ export function workspaceOf(state: State): Workspace {
let found = spaces.get(state)
if (found === undefined) {
found = { adapters: [claudeAdapter(), codexAdapter(), rufloAdapter(() => rufloInputOf(state, Date.now()))], index: null, selected: null, cursor: 0, viewed: null, scanning: false, lastScanMs: 0, lastFullMs: 0, scanTimes: [], shown: new Map(), note: '', signature: '', summary: '', timer: null }
found = { adapters: [claudeAdapter(), codexAdapter(), rufloAdapter(() => rufloInputOf(state, Date.now()))], index: null, selected: null, cursor: 0, viewed: null, scanning: false, lastScanMs: 0, lastFullMs: 0, scanTimes: [], shown: new Map(), note: '', signature: '', summary: '', summaryAtMs: 0, writeBackoffMs: 0, writeRetryAtMs: 0, timer: null }
spaces.set(state, found)
}
@@ -82,7 +88,8 @@ export async function scanSessions(state: State, host: Pick<Host, 'fs' | 'invali
const started = performance.now()
try {
const env = { fs: host.fs as SessionFs, claudeDir: state.configDir, codexDir: codexDirOf(state), nowMs, full }
// One read budget for the whole pass, shared by every adapter (ADR-486 §2.4).
const env = { fs: host.fs as SessionFs, claudeDir: state.configDir, codexDir: codexDirOf(state), nowMs, full, budget: passBudget() }
const scans: Scanned[] = await Promise.all(
ws.adapters.map(async adapter => ({
id: adapter.id,
@@ -159,8 +166,12 @@ export function commitViewed(state: State, host: Pick<Host, 'storeSet' | 'invali
return true
}
/** Where the counts-only summary ruflo-mods can show lives: the console's own state folder, in a ruflo project, rewritten only when a count changes. */
/** Where the counts-only summary ruflo-mods can show lives: the console's own state folder, in a ruflo project, rewritten when a count changes or the heartbeat is due. */
export const ATTENTION_FILE = '.claude-flow/console/attention.json'
/** The file is rewritten at least this often while the workspace runs, so a reader can tell a quiet queue from a console that stopped (ruflo-mods hooks/attention.ts ATTENTION_STALE_MS). */
export const ATTENTION_HEARTBEAT_MS = 5 * 60_000
/** The first wait after a failed write of the summary; it doubles up to ATTENTION_HEARTBEAT_MS. */
export const WRITE_RETRY_MS = 30_000
export async function mirrorAttention(state: State, host: Pick<Host, 'fs' | 'run'>, nowMs: number = Date.now()): Promise<void> {
const ws = workspaceOf(state)
@@ -170,13 +181,25 @@ export async function mirrorAttention(state: State, host: Pick<Host, 'fs' | 'run
const counts = attentionCounts(state)
const key = `${counts['needs-approval']}/${counts.question}/${counts.failed}/${counts['completed-unread']}`
if (key === ws.summary) return
if (key === ws.summary && nowMs - ws.summaryAtMs < ATTENTION_HEARTBEAT_MS) return
if (nowMs < ws.writeRetryAtMs) return
ws.summary = key
ws.summaryAtMs = nowMs
// Counts only: no title, path or transcript text is in this file.
const text = `${JSON.stringify({ schema: 'ruflo-console.attention/1', approve: counts['needs-approval'], question: counts.question, failed: counts.failed, unread: counts['completed-unread'], atMs: nowMs })}\n`
if ((await replaceFile(host, state.cwd, `${state.cwd.replace(/\/+$/, '')}/${ATTENTION_FILE}`, text)) !== null) ws.summary = ''
if ((await replaceFile(host, state.cwd, `${state.cwd.replace(/\/+$/, '')}/${ATTENTION_FILE}`, text)) === null) {
ws.writeBackoffMs = 0
ws.writeRetryAtMs = 0
return
}
// A failed write is retried, but not every tick: 30 s, doubling to 5 minutes, until one succeeds.
ws.summary = ''
ws.writeBackoffMs = ws.writeBackoffMs === 0 ? WRITE_RETRY_MS : Math.min(ATTENTION_HEARTBEAT_MS, ws.writeBackoffMs * 2)
ws.writeRetryAtMs = nowMs + ws.writeBackoffMs
}
export type SessionActions = {
@@ -227,20 +250,33 @@ export function sessionActions(state: State, host: Pick<Host, 'fs' | 'invalidate
}
}
/**
* Loads the viewed map. The baseline is the first time this queue ever ran: older completions are history, not unread. It is stored so a
* restart keeps it. A stored value that was not a Viewed, or held a stamp or baseline in the future, is written back repaired, once.
*/
export async function loadViewed(state: State, host: Pick<Host, 'storeGet' | 'storeSet'>, nowMs: number = Date.now()): Promise<void> {
const ws = workspaceOf(state)
let raw: unknown
try {
raw = await host.storeGet(VIEWED_KEY)
} catch {
ws.viewed = viewedOf(null, nowMs)
return
}
ws.viewed = viewedOf(raw, nowMs)
if (needsRewrite(raw, ws.viewed)) await host.storeSet(VIEWED_KEY, ws.viewed).catch(() => undefined)
}
/** Starts the watcher once. A closed pane scans rarely; a shown one every second (stat-only unless something changed). */
export function startSessions(state: State, host: Host): void {
const ws = workspaceOf(state)
if (ws.timer !== null) return
// The baseline is the first time this queue ever ran: older completions are history, not unread. It is stored so a restart keeps it.
void host.storeGet(VIEWED_KEY).then(
raw => {
ws.viewed = viewedOf(raw, Date.now())
if (typeof raw !== 'object' || raw === null) void host.storeSet(VIEWED_KEY, ws.viewed).catch(() => undefined)
},
() => (ws.viewed = viewedOf(null, Date.now())),
)
void loadViewed(state, host)
ws.timer = host.every(FAST_MS, () => {
if (!state.options.sessionWorkspace) return
+1 -1
View File
@@ -320,7 +320,7 @@ export function moreSkillActions(state: State, host: Host, runner: Runner, load:
*/
export function skillPaletteEntries(state: State): PaletteEntry[] {
const wired = hosts.get(state)
const why = 'the skills view is not wired yet'
const why = 'the console is not running in this session: open it first (console_open skills)'
const spec = (make: (host: Host) => ActionSpec): { kind: 'spec'; spec: ActionSpec | null; why: string } => ({ kind: 'spec', spec: wired === undefined ? null : make(wired.host), why })
const find = (text: string): ActionSpec | null => {
const argv = findArgv(text)
+5 -3
View File
@@ -231,10 +231,10 @@ export function skillActions(state: State, host: Host, runner: Runner, load: (te
const asked = skills.asked
const name = newNameOf(text)
if (asked !== null && (asked.key === text.trim() || text.trim() === '') && state.pending?.label === asked.label) {
if (asked !== null && asked.card !== null && (asked.key === text.trim() || text.trim() === '') && state.pending?.id === asked.card) {
skills.asked = null
skills.createDraft = ''
void runner.confirm()
void runner.confirm(asked.card)
return
}
@@ -243,8 +243,10 @@ export function skillActions(state: State, host: Host, runner: Runner, load: (te
skills.createDraft = text
if (name !== null) skills.authored = name
const before = state.pending?.id
runner.ask(spec, NAME_RULE)
skills.asked = spec !== null && name !== null ? { key: name, label: spec.label } : null
skills.asked = spec !== null && name !== null ? { key: name, label: spec.label, card: state.pending !== null && state.pending.id !== before ? (state.pending.id ?? null) : null } : null
},
add: (found, scope) => runner.ask(addSpec(state, host, found, scope), 'that result is not an owner/repo@skill id'),
remove: skill => runner.ask(removeSpec(state, host, skill), nameless('remove')),
+11 -5
View File
@@ -150,7 +150,7 @@ export function optionsOf(raw: PluginOptions | undefined): Options {
}
/** A mutating action waiting for the person's second press; `shows` is the command line when it is not a ruflo one. */
export type Pending = { /** Which ask this is (runner.ts hands out ids in order): a Yes names the card it answers, so another card that took its place is never the one run. */ id?: number; label: string; args: readonly string[]; expect: string; askedAtMs: number; shows?: string; note?: string; /** The kind of action, when it may be remembered (see remember.ts). */ rememberKey?: string; /** Where in its view the ask came from. */ scope?: string; /** The page that raised it: the ask shows in full there, and as a pointer on every other page. */ view?: string; /** Who raised it: Claude's tool call or the person's own action (ADR-450 T14). */ source?: 'claude' | 'you'; /** The class the entry declares for itself; the gate takes the stricter of this and the class read from its words. */ declared?: 'write' | 'network' | 'install' | 'spend' | 'delete'; /** The class of action, set only on Claude's asks. */ kind?: 'write' | 'network' | 'install' | 'spend' | 'delete' }
export type Pending = { /** Which ask this is (runner.ts hands out ids in order): a Yes names the card it answers, so another card that took its place is never the one run. */ id?: number; label: string; args: readonly string[]; expect: string; askedAtMs: number; shows?: string; note?: string; /** The kind of action, when it may be remembered (see remember.ts). */ rememberKey?: string; /** Where in its view the ask came from. */ scope?: string; /** The page that raised it: the ask shows in full there, and as a pointer on every other page. */ view?: string; /** Who raised it: Claude's tool call or the person's own action (ADR-450 T14). */ source?: 'claude' | 'you'; /** The class the entry declares for itself; the gate takes the stricter of this and the class read from its words. */ declared?: 'write' | 'network' | 'install' | 'spend' | 'delete'; /** Set only on a card Claude raised by its own direct console_run in this session: the one kind of card it may withdraw (runner.ts also matches the id). */ origin?: 'console_run'; /** The class of action, set only on Claude's asks. */ kind?: 'write' | 'network' | 'install' | 'spend' | 'delete'; /** The number of the Claude call that started this ask (ActionSpec.byCall): only that call settles it. */ byCall?: number }
/** The MetaHarness lab's last run: what it was, how it exited, its cost note, and its output as lines to scroll. */
export type LabResult = { id: string; label: string; ok: boolean; exitCode: number | null; note?: string; lines: string[]; atMs: number }
@@ -173,7 +173,7 @@ export type TermSessions = { codex?: string; claude?: string }
export const termStoreKeyOf = (cwd: string): string => `ruflo-console/term:${cwd}`
/** What an action did: what ran, how it exited, whether the disk shows the change, and anything it printed to show. */
export type Outcome = { label: string; ok: boolean; verified: 'yes' | 'no' | 'n/a'; detail: string; atMs: number; lines?: string[] }
export type Outcome = { label: string; ok: boolean; verified: 'yes' | 'no' | 'n/a'; detail: string; atMs: number; lines?: string[]; /** A confirm card that nobody answered within PENDING_TTL_MS and was cleared unrun (the Room shows it briefly). */ expired?: boolean }
/** One module seen registering since the console loaded, as the engine's scan named it. */
export type ModSeen = { name: string; provenance: string; isLoaded: boolean; reason?: string; atMs: number }
@@ -275,6 +275,10 @@ export type State = {
drill: { agentId: string | null; logs: string[] | null; logsAtMs: number }
palette: { isOpen: boolean; query: string; index: number; context: 'all' | 'selection' }
pending: Pending | null
/** The id of the confirm card last put in front of the person (drawn in the shown pane, or named in a typed answer): the one card a bare `/ruflo yes` may answer. */
shownCard: number | null
/** The last field Enter that raised a card: which entry and text, and the card's id, so Enter again confirms that card and no other that merely reads the same. */
askedAgain: { entry: string; text: string; card: number } | null
/** The key of the element last pressed, and the one the last ask or answer came from: the page draws them right there (views/attention.ts). */
lastPressed: string | null
origin: string | null
@@ -309,7 +313,7 @@ export type State = {
scroll: number
unseen: number
/** The text the last Enter asked about: Enter on the same text again confirms it. */
asked: { key: string; label: string } | null
asked: { key: string; label: string; card: number | null } | null
}
/** The skills view: installed skills, the last search, and the change running now. */
skills: SkillsState
@@ -328,7 +332,7 @@ export type State = {
/** The Workflows page: the last read of Claude Code's run folders, the cursor, the inspector tab (wf-state.ts). */
wf: WfState
/** Claude's control of the console (ADR-444): paused by the person, the call counts, and the log the dashboard shows. */
control: { paused: boolean; calls: number; turnCalls: number; /** Model-driven actions this session, by class (ADR-450 T8 budget). */ used: Record<string, number>; log: ControlEntry[]; /** Until when Claude counts as driving (a tool call extends it): the console does not spend a second Claude turn on guidance meanwhile. */ drivingUntilMs: number; /** Claude's console_run / console_set calls running now: an ask that lands while one runs is settled (gated) by that call; one that lands with none running (console_open and console_state settle nothing) is checked by the runner. */ activeCalls: number; /** True while one of Claude's tool calls is running: a person's "always allow" answer must not let Claude's call skip the level and confirm checks (ADR-444). */ viaModel: boolean }
control: { paused: boolean; calls: number; turnCalls: number; /** Model-driven actions this session, by class (ADR-450 T8 budget). */ used: Record<string, number>; log: ControlEntry[]; /** Until when Claude counts as driving (a tool call extends it): the console does not spend a second Claude turn on guidance meanwhile. */ drivingUntilMs: number; /** Claude's console_run / console_set calls running now: an ask that lands while one runs is settled (gated) by that call; one that lands with none running (console_open and console_state settle nothing) is checked by the runner. */ activeCalls: number; /** True while one of Claude's tool calls is running: a person's "always allow" answer must not let Claude's call skip the level and confirm checks (ADR-444). */ viaModel: boolean; /** The last number handed to a console_run / console_set call, and the number of the call whose synchronous start is running now (null when none is). */ callSeq: number; callTag: number | null }
}
export function newState(raw: PluginOptions | undefined): State {
@@ -388,6 +392,8 @@ export function newState(raw: PluginOptions | undefined): State {
drill: { agentId: null, logs: null, logsAtMs: 0 },
palette: { isOpen: false, query: '', index: 0, context: 'all' },
pending: null,
shownCard: null,
askedAgain: null,
lastPressed: null,
origin: null,
outcome: null,
@@ -406,7 +412,7 @@ export function newState(raw: PluginOptions | undefined): State {
timers: new Map(),
stats: { renders: [], refreshes: [], frames: [] },
wf: emptyWf(),
control: { paused: false, calls: 0, turnCalls: 0, used: {}, log: [], drivingUntilMs: 0, activeCalls: 0, viaModel: false },
control: { paused: false, calls: 0, turnCalls: 0, used: {}, log: [], drivingUntilMs: 0, activeCalls: 0, viaModel: false, callSeq: 0, callTag: null },
}
}
+1 -1
View File
@@ -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.42.0'
export const CONSOLE_VERSION = '0.42.6'
@@ -36,16 +36,17 @@ export function strip(ctx: Ctx, key: string, items: readonly Item[]): RenderElem
/** True when Enter repeats the text the pending ask came from: the field holds the keys, so Enter again confirms. */
export function isAskedAgain(ctx: Ctx, id: string, value: string): boolean {
const pending = ctx.state.pending
const entry = [...automateEntries(ctx.state), ...neuralEntries(ctx.state)].find(candidate => candidate.id === id)
const again = ctx.state.askedAgain
return pending !== null && value.trim() !== '' && entry?.make?.(value)?.label === pending.label
// The same entry, the same text, and the very card that text raised (its id): a card with the same words that replaced it is not it.
return pending !== null && pending.id !== undefined && again !== null && value.trim() !== '' && again.entry === id && again.text === value.trim() && again.card === pending.id
}
/** A typed entry's field: Enter runs a read at once, or asks for a change; Enter again on the same text confirms it. */
export function field(ctx: Ctx, id: string, label: string, placeholder: string, submitLabel = 'ask'): RenderElement {
if (ctx.kit.Input === undefined) return text(ctx, ` ${label}: this surface has no text field; /ruflo run ${id} <text> does the same`, { dimColor: true })
return ctx.kit.Input({ key: `in-${id}`, label, placeholder, submitLabel, onSubmit: value => (isAskedAgain(ctx, id, value) ? ctx.act.confirm() : void ctx.act.run(id, value)) })
return ctx.kit.Input({ key: `in-${id}`, label, placeholder, submitLabel, onSubmit: value => (isAskedAgain(ctx, id, value) ? ctx.act.confirm(ctx.state.pending?.id) : void ctx.act.run(id, value)) })
}
/** The last run whose id has one of `prefixes`: what it was, how it exited, its cost note and a window of its lines. */
+3 -4
View File
@@ -11,7 +11,7 @@ import type { RenderElement } from 'claude-code'
import { alertsOf, waitingApprovalsOf } from '../data/alerts'
import { agentLabels } from '../data/parse'
import { swarmStatusOf } from '../data/swarm-status'
import { secMemo } from '../secure'
import { secMemo, securityBand } from '../secure'
import type { State, ViewId } from '../state'
import { sparkline } from '../memory-lines'
import { visibleNotice, type Notice } from '../notices'
@@ -173,10 +173,9 @@ export function barParts(state: State, nowMs: number = Date.now()): BarPart[] {
parts.push({ text: `ctx ${Math.round(context)}%${context >= 85 ? ' · /compact soon' : ''}`, tone: context >= 80 ? 'attention' : 'plain', go: 'cost', row: 'standing', compact: `ctx ${Math.round(context)}%` })
}
const findings = secMemo(state).findings
const serious = findings === null ? 0 : findings.counts.critical + findings.counts.high
const security = securityBand(secMemo(state).findings)
if (findings !== null && serious > 0) parts.push({ text: `🔒 ${serious} high or critical`, tone: findings.counts.critical > 0 ? 'attention' : 'plain', go: 'secure', row: 'standing', compact: `🔒 ${serious}` })
if (security !== null) parts.push({ text: security.text, tone: security.isAttention ? 'attention' : 'plain', go: 'secure', row: 'standing', compact: security.compact })
if (state.updateAvailable !== '') parts.push({ text: `⬆ ${state.updateAvailable} available`, tone: 'attention', go: 'settings', row: 'standing' })
return parts
+4 -1
View File
@@ -415,6 +415,9 @@ export function confirmRow(ctx: Ctx): RenderElement | null {
// One bordered card in the warning colour: the person says yes to everything in it, so it reads as a unit, not as loose lines. Its border and
// padding take four columns, so the text inside is clipped to the narrower width.
const inner: Ctx = { ...ctx, columns: Math.max(20, ctx.columns - 4) }
// Drawn for a person in a pane they can see: this is now the card a bare typed yes may answer. A text answer for a model shows it to no one.
if (ctx.text !== true && ctx.state.pane.isShown && pending.id !== undefined) ctx.state.shownCard = pending.id
const hasMoney = pending.note !== undefined && /money|models/i.test(pending.note)
return ctx.kit.Box({
@@ -439,7 +442,7 @@ export function confirmRow(ctx: Ctx): RenderElement | null {
// A low-risk ruflo action may be remembered: it is not asked again (Settings lists and forgets it).
...(pending.rememberKey !== undefined ? [button(ctx, 'remember', `Always allow “${pending.rememberKey}”`, () => ctx.act.remember(pending.id))] : []),
// An AI terminal turn (claude -p in plan mode, codex read-only, the budget cap) may be always accepted: Settings resets it.
...(ctx.state.terminal.asked !== null && pending.label === ctx.state.terminal.asked.label && ctx.state.terminal.harness !== 'ruflo' ? [button(ctx, 'always', 'Always accept AI turns', () => ctx.act.settings.alwaysAccept(pending.id))] : []),
...(ctx.state.terminal.asked !== null && pending.id !== undefined && pending.id === ctx.state.terminal.asked.card && ctx.state.terminal.harness !== 'ruflo' ? [button(ctx, 'always', 'Always accept AI turns', () => ctx.act.settings.alwaysAccept(pending.id))] : []),
],
}),
],
+28 -8
View File
@@ -6,7 +6,7 @@
import type { AuditTrend, HarnessScore, Intelligence } from '../data/cli'
import { recentByAgent } from '../data/events'
import { agentLabels } from '../data/parse'
import { swarmStatusOf } from '../data/swarm-status'
import { presentAgents, swarmStatusOf } from '../data/swarm-status'
import { getBootChecks } from '../boot-checks'
import { bootFacts } from '../boot-facts'
import { getBuild } from '../build'
@@ -109,22 +109,42 @@ export function healthRowsOf(state: State): HealthRow[] {
}))
}
/** The timeline's lanes over the last 15 minutes: ruflo agents' observed statuses and Claude Code's tool calls. */
/**
* The timeline's lanes over the last 15 minutes: ruflo agents' observed statuses and Claude Code's tool calls, in the order a short list must
* keep them: the person's own main session, then busy agents, then sub-agents with calls in the window (latest first), then the other present
* agents, then quiet sub-agents. A page that shows the first few never hides main or a busy agent behind earlier quiet rows, and the full
* length is what its "+N more" counts. (presentAgents already leaves the agent store's old idle records out.)
*/
export function lanesOf(state: State, nowMs: number): Lane[] {
const from = nowMs - watchOf(state).rangeMs
const labels = agentLabels(state.snapshot?.agents ?? [])
const agents = (state.snapshot?.agents ?? []).slice(0, 24).map(agent => {
// Only agents with evidence of activity (data/swarm-status.ts presentAgents): the store holds every agent ever spawned.
const agents = presentAgents(state.snapshot?.agents ?? [], state.statusLog, from, nowMs).map(agent => {
const log = state.statusLog.get(agent.id) ?? []
return {
label: labels.get(agent.id) ?? agent.type,
spans: log.map((entry, i) => ({ fromMs: Math.max(from, entry.atMs), toMs: log[i + 1]?.atMs ?? nowMs, busy: /busy|active|working/i.test(entry.status) })).filter(span => span.toMs >= from),
ticks: [],
busy: /busy|active|working|running/i.test(agent.status),
lane: {
label: labels.get(agent.id) ?? agent.type,
spans: log.map((entry, i) => ({ fromMs: Math.max(from, entry.atMs), toMs: log[i + 1]?.atMs ?? nowMs, busy: /busy|active|working/i.test(entry.status) })).filter(span => span.toMs >= from),
ticks: [],
},
}
})
const claude = [...state.toolsByAgent].slice(0, 6).map(([who, calls]) => ({ label: who === 'main' ? 'claude (main)' : `cc ${who.slice(-6)}`, spans: [], ticks: calls.map(call => call.atMs).filter(at => at >= from) }))
const claude = [...state.toolsByAgent].map(([who, calls]) => {
const ticks = calls.map(call => call.atMs).filter(at => at >= from)
return [...claude, ...agents]
return { main: who === 'main', lastMs: ticks.reduce((latest, at) => Math.max(latest, at), 0), lane: { label: who === 'main' ? 'claude (main)' : `cc ${who.slice(-6)}`, spans: [], ticks } }
})
const subs = claude.filter(entry => !entry.main).sort((a, b) => b.lastMs - a.lastMs)
return [
...claude.filter(entry => entry.main).map(entry => entry.lane),
...agents.filter(entry => entry.busy).map(entry => entry.lane),
...subs.filter(entry => entry.lastMs > 0).map(entry => entry.lane),
...agents.filter(entry => !entry.busy).map(entry => entry.lane),
...subs.filter(entry => entry.lastMs === 0).map(entry => entry.lane),
]
}
/** When the score on screen was first drawn: the radar grows from there. Module-held, reset by a new value. */
@@ -236,7 +236,7 @@ export function missionControlView(ctx: Ctx): RenderElement {
if (mission !== null) rows.push(...controlRows(ctx, mission))
if (mc.last !== null) rows.push(...fullRows(ctx, ` ${mc.last.ok ? '✓' : '✗'} `, `${mc.last.label}${mc.last.detail === '' ? '' : ` — ${mc.last.detail}`}`, { key: 'mc-last', color: mc.last.ok ? THEME.ok : THEME.bad, maxLines: 12, hint: 'your text is still in its field' }))
if (mc.last !== null) rows.push(...fullRows(ctx, ` ${mc.last.ok ? '✓' : '✗'} `, `${mc.last.label}${mc.last.detail === '' ? '' : ` — ${mc.last.detail}`}`, { key: 'mc-last', color: mc.last.ok ? THEME.ok : THEME.bad, maxLines: 12, hint: 'your text is still in its field' }), ...(mc.last.lines ?? []).slice(0, 8).map(line => text(ctx, ` ${line}`, { dimColor: true })))
rows.push(row(ctx, TABS.filter(tab => mission !== null || tab.id === 'plan' || tab.id === 'record').map(tab => chip(ctx, `mc-tab-${tab.id}`, tab.label, mc.tab === tab.id, () => ctx.act.mission.tab(tab.id))), 'mc-tabs'))
@@ -1,6 +1,6 @@
import type { RenderElement } from 'claude-code'
import { catalogOf, installedOf, listOf, MODES, PAGE, type Verb } from '../plugin-catalog'
import { catalogOf, installedOf, listOf, MODES, PAGE, syncedOf, type Verb } from '../plugin-catalog'
import type { CatalogPlugin } from '../data/plugin-catalog'
import { RUFLO_MARKET } from '../data/snapshot'
import { ago, button, clip, col, kv, row, rule, section, text, THEME, type Ctx } from './common'
@@ -21,7 +21,7 @@ function counts(plugin: CatalogPlugin): string {
/** One plugin row: the whole row selects it, the trailing button changes it. */
function pluginRow(ctx: Ctx, plugin: CatalogPlugin, lead: number): RenderElement {
const { installed, enabled } = installedOf(ctx.state)
const badge = enabled.has(plugin.name) ? '■' : installed.has(plugin.name) ? '□' : '·'
const badge = enabled.has(plugin.name) ? '■' : installed.has(plugin.name) ? '□' : syncedOf(ctx.state).has(plugin.name) ? '◇' : '·'
const act = verbOf(ctx, plugin)
const isPicked = catalogOf(ctx.state).selected === plugin.name
const press = () => ctx.act.catalog.select(isPicked ? null : plugin.name)
@@ -55,7 +55,7 @@ function itemRow(ctx: Ctx, kind: 'skill' | 'agent' | 'command', plugin: CatalogP
function detailRows(ctx: Ctx, plugin: CatalogPlugin): RenderElement[] {
const { installed, enabled, version } = installedOf(ctx.state)
const state = enabled.has(plugin.name) ? 'installed and enabled' : installed.has(plugin.name) ? 'installed, disabled' : 'not installed'
const state = enabled.has(plugin.name) ? 'installed and enabled' : installed.has(plugin.name) ? 'installed, disabled' : syncedOf(ctx.state).has(plugin.name) ? 'mod synced here, plugin not installed' : 'not installed'
const rows: RenderElement[] = [rule(ctx, plugin.name, state), text(ctx, ` ${plugin.description}`, { color: THEME.info })]
rows.push(kv(ctx, 'version', `${plugin.version ?? 'n/a'}${installed.has(plugin.name) ? ` (installed ${version.get(plugin.name) ?? '?'})` : ''}`))
@@ -119,7 +119,7 @@ export function catalogView(ctx: Ctx): RenderElement {
const lead = Math.max(24, Math.min(34, ctx.columns - 60))
rows.push(rule(ctx, 'Plugin Catalog', `${all.length} plugins · ${installed.size} installed · ${enabled.size} enabled`))
rows.push(text(ctx, ` ${total(plugin => plugin.skills.length)} skills · ${total(plugin => plugin.agents.length)} agents · ${total(plugin => plugin.commands.length)} commands · ${all.filter(plugin => plugin.hasMcp).length} MCP · ${all.filter(plugin => plugin.isMod).length} mods · ■ enabled □ installed · not installed`, { dimColor: true }))
rows.push(text(ctx, ` ${total(plugin => plugin.skills.length)} skills · ${total(plugin => plugin.agents.length)} agents · ${total(plugin => plugin.commands.length)} commands · ${all.filter(plugin => plugin.hasMcp).length} MCP · ${all.filter(plugin => plugin.isMod).length} mods · ■ enabled □ installed ◇ mod synced, plugin not installed · not installed`, { dimColor: true }))
// The marketplace these come from: how fresh the clone is, with the way back to the Plugins page (the setup's health) and the update.
const market = state.snapshot?.plugins.markets?.find(entry => entry.name === RUFLO_MARKET)
const isStale = (state.snapshot?.plugins.missingFromClone.length ?? 0) > 0
+13 -3
View File
@@ -12,6 +12,8 @@ import { statsOf } from './manage'
import { modsRows } from './mods'
import { sessionRows } from './sessions'
/** How long the Room says a card expired, after the runner cleared it. */
const EXPIRED_SHOWN_MS = 15_000
const TONE_COLOR = { ok: THEME.ok, warn: THEME.warn, bad: THEME.bad, info: THEME.info } as const
const SOURCES: readonly { id: 'all' | RoomSource; label: string }[] = [
{ id: 'all', label: 'all' },
@@ -54,12 +56,18 @@ export function roomView(ctx: Ctx): RenderElement {
const banner = pendingBanner(state.pending, nowMs, PENDING_TTL_MS)
const rows: RenderElement[] = []
rows.push(rule(ctx, 'Waiting for a yes', banner === null ? 'nothing' : `${banner.ageS}s of ${PENDING_TTL_MS / 1000}s`))
// Past the window a card is expired, never "63s of 30s": the runner clears it on its clock, and the page says so for a moment after.
const isLate = banner !== null && banner.leftS === 0
const expired = banner === null && state.outcome?.expired === true && nowMs - state.outcome.atMs < EXPIRED_SHOWN_MS ? state.outcome : null
if (banner === null) rows.push(text(ctx, ' Nothing is waiting. Anything that asks first shows up here, unmissable, with how long you have to answer.', { dimColor: true }))
rows.push(rule(ctx, 'Waiting for a yes', isLate || expired !== null ? 'expired' : banner === null ? 'nothing' : `${banner.ageS}s of ${PENDING_TTL_MS / 1000}s`))
if (expired !== null) rows.push(text(ctx, `⌛ ${clip(expired.label, 100)}: expired after ${PENDING_TTL_MS / 1000} s with no answer, so it did not run. Ask again if it is still wanted.`, { color: THEME.warn }))
else if (banner === null) rows.push(text(ctx, ' Nothing is waiting. Anything that asks first shows up here, unmissable, with how long you have to answer.', { dimColor: true }))
else if (isLate) rows.push(text(ctx, `⌛ ${banner.label}: expired after ${PENDING_TTL_MS / 1000} s with no answer. It will not run: ask again.`, { color: THEME.bad }))
else {
rows.push(text(ctx, `⚠ ${banner.label}`, { bold: true, color: TONE_COLOR[banner.tone] }))
rows.push(text(ctx, ` expects: ${banner.expect}${banner.view === null ? '' : ` · raised on ${banner.view}`} · ${banner.leftS}s left to answer${banner.leftS === 0 ? ' (too late: it will not run, ask again)' : ''}`, { color: TONE_COLOR[banner.tone] }))
rows.push(text(ctx, ` expects: ${banner.expect}${banner.view === null ? '' : ` · raised on ${banner.view}`} · ${banner.leftS}s left to answer`, { color: TONE_COLOR[banner.tone] }))
}
rows.push(...sessionRows(ctx))
@@ -126,6 +134,8 @@ export function roomView(ctx: Ctx): RenderElement {
rows.push(row(ctx, [ctx.kit.Text({ bold: true, color: THEME.head, children: ` ${clip(lane.label, 20).padEnd(20)}` }), ctx.kit.Text({ color: share === null ? THEME.info : share >= 60 ? THEME.ok : share >= 20 ? THEME.warn : THEME.info, children: ` ${share === null ? 'no status seen' : `busy ${share}%`}` }), ctx.kit.Text({ dimColor: true, children: ` · ${stats.calls} tool call${stats.calls === 1 ? '' : 's'}` })], `room-lane-${i}`))
}
if (lanes.length > 8) rows.push(text(ctx, ` +${lanes.length - 8} more`, { dimColor: true }))
rows.push(...modsRows(ctx))
return col(ctx, rows, 'room')
+3 -3
View File
@@ -1,6 +1,6 @@
import type { RenderElement } from 'claude-code'
import { DOCTOR_COMPONENTS, isSecureResult, SECURE, SECURE_TEXT, secMemo, SEVERITIES, type SecCost, type Severity } from '../secure'
import { countText, DOCTOR_COMPONENTS, isSecureResult, SECURE, SECURE_TEXT, secMemo, SEVERITIES, type SecCost, type Severity } from '../secure'
import { slot } from './attention'
import { spinAt } from '../spinner'
import { sentryRows } from './sentries'
@@ -143,7 +143,7 @@ export function meterRows(ctx: Ctx): RenderElement[] {
row(ctx, [
ctx.kit.Text({ bold: n > 0, color: n > 0 ? SEVERITY_COLOR[level]() : THEME.info, dimColor: n === 0, children: ` ${level.padEnd(9)}` }),
ctx.kit.Text({ color: SEVERITY_COLOR[level](), children: '█'.repeat(filled) }),
ctx.kit.Text({ dimColor: true, children: `${'░'.repeat(width - filled)} ${n}` }),
ctx.kit.Text({ dimColor: true, children: `${'░'.repeat(width - filled)} ${countText(findings, level)}` }),
], `meter-${level}`),
)
}
@@ -261,7 +261,7 @@ export function secureView(ctx: Ctx): RenderElement {
ctx,
'sec-findings',
'Findings',
findings === null ? 'none measured yet' : `${SEVERITIES.map(level => `${findings.counts[level]} ${level}`).join(' · ')} · ${ago(findings.atMs, nowMs)}`,
findings === null ? 'none measured yet' : `${SEVERITIES.map(level => `${countText(findings, level)} ${level}`).join(' · ')}${(findings.unreadable ?? []).length > 0 ? ' · counts unreadable' : ''} · ${ago(findings.atMs, nowMs)}`,
[...meterRows(ctx), ...anatoleMeterRows(ctx), ...(findings === null ? [] : [sendFindingsRow(ctx)])],
true,
),
+15 -3
View File
@@ -19,6 +19,17 @@ const KIND_COLOR: Record<AttentionKind, string> = { 'needs-approval': THEME.warn
const STATUS_MARK: Record<SessionRow['status'], string> = { working: '●', idle: '○', done: '✓', failed: '✗', unknown: '?' }
/** A title the harness wrote is transcript text: a text answer a model may read names the session by harness and id instead. */
const titleOf = (ctx: Ctx, harness: string, key: string | null, title: string): string => (ctx.text === true && harness !== 'ruflo' && harness !== 'console' ? `${harness} session ${(key?.split(':').pop() ?? '').slice(0, 8)}` : title)
/**
* A group heading is a path a transcript recorded (another project's directory, a worktree name): a text answer names it by harness and
* position instead. Only a group made of the console's own ruflo records keeps its label, which is the console's own working directory.
*/
const groupLabelOf = (ctx: Ctx, group: { label: string; unassigned: boolean; rows: readonly SessionRow[] }, n: number): string => {
if (ctx.text !== true || group.unassigned) return group.label
const harnesses = [...new Set(group.rows.map(found => found.harness))]
return harnesses.every(harness => harness === 'ruflo') ? group.label : `${harnesses.filter(harness => harness !== 'ruflo').join('+')} repo ${n}`
}
const SHOWN_ROWS = 30
const QUEUE_ROWS = 8
@@ -42,7 +53,8 @@ function previewRows(ctx: Ctx, found: SessionRow): RenderElement[] {
rows.push(text(ctx, ` ${titleOf(ctx, found.harness, found.key, found.title)}`, { bold: true }))
rows.push(text(ctx, ` ${found.status}${found.stale === null ? '' : ` · STALE: ${found.stale}`} · ${found.external ? 'started outside Ruflo' : 'started by Ruflo'} · updated ${found.updatedMs > 0 ? ago(found.updatedMs, nowMs) : 'n/a'} · ${costText(found.cost)}`, { dimColor: true }))
if (found.cwd !== null) rows.push(text(ctx, ` in ${clip(found.cwd, Math.max(20, ctx.columns - 10))}${found.branch === null ? '' : ` @ ${found.branch}`}`, { dimColor: true }))
// The recorded cwd and git branch are transcript text (a branch name can be any words): drawn for a person, never in a text answer.
if (found.cwd !== null && ctx.text !== true) rows.push(text(ctx, ` in ${clip(found.cwd, Math.max(20, ctx.columns - 10))}${found.branch === null ? '' : ` @ ${found.branch}`}`, { dimColor: true }))
for (const [i, line] of found.context.entries()) rows.push(text(ctx, ` ${clip(line, ctx.columns - 6)}`, { dimColor: true, ...(i === 0 && { bold: false }) }))
if (found.unassigned !== null) {
@@ -122,10 +134,10 @@ export function sessionRows(ctx: Ctx): RenderElement[] {
let left = SHOWN_ROWS
for (const group of index.groups) {
for (const [n, group] of index.groups.entries()) {
if (left <= 0) break
body.push(text(ctx, ` ${group.label}`, { bold: true, color: group.unassigned ? THEME.warn : THEME.head }))
body.push(text(ctx, ` ${groupLabelOf(ctx, group, n + 1)}`, { bold: true, color: group.unassigned ? THEME.warn : THEME.head }))
for (const found of group.rows.slice(0, left)) {
const picked = ws.selected === found.key
+2 -2
View File
@@ -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.42.0"
step "1. plugin.json declares ruflo-console 0.42.6"
grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \
&& grep -q '"version": "0.42.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
&& grep -q '"version": "0.42.6"' "$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" \
@@ -0,0 +1,244 @@
/**
* #3983: every confirm route answers the card the person saw. The card's own Yes and y were bound to its id; three other routes were not:
* a typed `/ruflo yes`, the field's "Enter again" (matched by label), and the auto-confirm of a Claude call (settled whichever card waited).
* Each is shown here to refuse the wrong card, and to still answer the right one.
* npx vitest run plugins/ruflo-console/tests/confirm-binding.spec.ts
*/
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { ActionSpec } from '../hooks/actions'
import { createController } from '../hooks/controller'
import { dispatch } from '../hooks/dispatch'
import type { Host } from '../hooks/host'
import { callTool } from '../hooks/model-tools'
import { parseRuflo } from '../hooks/commands'
import { settingsOf } from '../hooks/settings'
import { newState } from '../hooks/state'
import { confirmRow, type Ctx } from '../hooks/views/common'
import { isAskedAgain } from '../hooks/views/automate'
import { plainKit } from '../hooks/views/pane'
import { setup } from './fixtures/control-setup'
afterEach(() => vi.useRealTimers())
function console$() {
vi.useFakeTimers({ now: 5_000_000 })
const host = new Proxy({}, {
get: (_target, key) => {
if (key === 'after' || key === 'every') return (ms: number, fn: () => void) => {
const handle = key === 'after' ? setTimeout(fn, ms) : setInterval(fn, ms)
return { cancel: () => (key === 'after' ? clearTimeout(handle) : clearInterval(handle)) }
}
if (key === 'pluginRoot') return '/plugin'
if (key === 'fs') return { read: async () => Promise.reject(new Error('ENOENT')), stat: async () => Promise.reject(new Error('ENOENT')), list: async () => Promise.reject(new Error('ENOENT')) }
return () => Promise.resolve(undefined)
},
}) as unknown as Host
const state = newState({ boot: false })
Object.assign(settingsOf(state).ai, { modelControl: 'full', modelConfirm: 'ask' })
const control = createController(state, host)
const ran: string[] = []
const spec = (label: string, extra: Partial<ActionSpec> = {}) => ({ label, args: ['memory', 'store'], expect: 'x', run: async () => void ran.push(label), ...extra }) as unknown as ActionSpec
const say = (text: string) => dispatch(control, state, text, async () => undefined)
/** The card drawn for a person in a pane that is open. */
const draw = () => {
state.pane.isShown = true
confirmRow({ kit: plainKit(), state, nowMs: Date.now(), columns: 100, pictures: new Map(), act: new Proxy({}, { get: () => () => undefined }) as never } as unknown as Ctx)
}
return { state, control, ran, spec, say, draw }
}
describe('a typed /ruflo yes names its card or answers only the card the person was shown', () => {
it('parses an id', () => {
expect(parseRuflo('yes 7')).toEqual({ kind: 'confirm', isYes: true, card: 7 })
expect(parseRuflo('y #12')).toEqual({ kind: 'confirm', isYes: true, card: 12 })
expect(parseRuflo('yes')).toEqual({ kind: 'confirm', isYes: true })
expect(parseRuflo('yes now')).toEqual({ kind: 'confirm', isYes: true })
})
it('A expires, Claude raises B, a long while later a bare yes meant for A runs nothing; yes <B> runs B', async () => {
const { state, control, ran, spec, say, draw } = console$()
control.runner.ask(spec('store A'), 'x')
draw()
vi.advanceTimersByTime(30_300)
expect(state.pending).toBeNull()
control.runner.ask(spec('store B', { byModel: true }), 'x')
const b = state.pending?.id
vi.advanceTimersByTime(15_000)
expect(await say('yes')).toMatchObject({ text: expect.stringMatching(/not run.*not put in front of you/) })
expect(ran).toEqual([])
expect(state.pending?.id).toBe(b)
expect((await say(`yes ${(b ?? 0) + 1}`)).text).toMatch(/Ran|✗|✓/)
expect(ran).toEqual([])
expect(state.pending?.id).toBe(b)
await say(`yes ${b}`)
expect(ran).toEqual(['store B'])
})
it('a card drawn in the open pane is the one a bare yes answers; one drawn only for a text answer is not', async () => {
const { state, control, ran, spec, say, draw } = console$()
control.runner.ask(spec('store C'), 'x')
// A model's text answer draws the same card for no one.
state.pane.isShown = true
confirmRow({ kit: plainKit(), state, nowMs: Date.now(), columns: 100, pictures: new Map(), text: true, act: {} as never } as unknown as Ctx)
expect(state.shownCard).toBeNull()
await say('yes')
expect(ran).toEqual([])
draw()
expect(state.shownCard).toBe(state.pending?.id)
vi.advanceTimersByTime(4_000)
await say('yes')
expect(ran).toEqual(['store C'])
})
it('/ruflo run names the card in its answer, and the bare yes after it answers that card', async () => {
const { state, say } = console$()
const asked = await say('run mem-store console k1 v1')
expect(asked.text).toMatch(/^Asked: /)
expect(state.pending).not.toBeNull()
expect(state.shownCard).toBe(state.pending?.id)
vi.advanceTimersByTime(4_000)
const yes = await say('yes')
expect(yes.text).not.toMatch(/not put in front of you/)
expect(state.pending).toBeNull()
})
it('a card nobody showed the person is refused a bare yes with its id in the answer', async () => {
const { state, control, ran, spec, say } = console$()
control.runner.ask(spec('store E', { byModel: true }), 'x')
vi.advanceTimersByTime(10_000)
const refused = await say('yes')
expect(refused.text).toMatch(new RegExp(`/ruflo yes ${state.pending?.id}`))
expect(ran).toEqual([])
})
})
describe('"Enter again" answers the card its field raised, not one that reads the same', () => {
it('the automate field: a replacement card with the same label is not confirmed; the original is', () => {
const { state } = console$()
const ctx = { kit: plainKit(), state, nowMs: Date.now(), columns: 100, pictures: new Map(), act: {} as never } as unknown as Ctx
state.pending = { id: 4, label: 'train coordination', args: [], expect: 'x', askedAtMs: Date.now() }
state.askedAgain = { entry: 'neural-train', text: 'coordination 20', card: 4 }
expect(isAskedAgain(ctx, 'neural-train', 'coordination 20')).toBe(true)
// Another card with the very same words took its place (a re-ask with other arguments).
state.pending = { id: 5, label: 'train coordination', args: [], expect: 'x', askedAtMs: Date.now() }
expect(isAskedAgain(ctx, 'neural-train', 'coordination 20')).toBe(false)
state.pending = { id: 4, label: 'train coordination', args: [], expect: 'x', askedAtMs: Date.now() }
expect(isAskedAgain(ctx, 'neural-train', 'coordination 30')).toBe(false)
expect(isAskedAgain(ctx, 'other-entry', 'coordination 20')).toBe(false)
})
it('the terminal field: Enter again confirms the card it raised; a same-labelled card that replaced it is not confirmed by that Enter', async () => {
const { state, control, spec } = console$()
const submit = (text: string) => control.actions.term.submit(text)
submit('hello there')
const first = state.pending
expect(first).not.toBeNull()
expect(state.terminal.asked?.card).toBe(first?.id)
// The card the field raised is replaced by another that reads exactly the same (a re-ask from elsewhere, same label).
control.runner.ask(spec(first?.label ?? ''), 'x')
expect(state.pending?.label).toBe(first?.label)
expect(state.pending?.id).not.toBe(first?.id)
const second = state.pending?.id
submit('hello there')
// Enter again did not answer the replacement: it asked afresh (a new card), and nothing was confirmed on the replaced one.
expect(state.pending?.id).not.toBe(second)
expect(state.terminal.asked?.card).toBe(state.pending?.id)
// And now the card this field raised is the one Enter again answers.
const raised = state.pending?.id
submit('hello there')
expect(state.pending === null || state.pending.id !== raised).toBe(true)
expect(state.terminal.asked === null || state.terminal.asked.card !== raised).toBe(true)
})
})
describe('auto-confirm settles only the card the call raised', () => {
it('a read still running while an unrelated write lands: the write is not confirmed under the read call', async () => {
const { state, calls, deps } = setup('full', 'auto', { search: { label: 'search', readOnly: true } })
const control = (deps as unknown as { control: { runner: { settled: () => Promise<void> } } }).control
let release: () => void = () => undefined
control.runner.settled = () => new Promise<void>(resolve => (release = resolve))
const running = callTool('console_run', { id: 'search', text: 'x' }, deps)
// The unrelated deferred write lands while the read is still waiting.
state.pending = { id: 99, label: 'store a thing', args: [], expect: 'stored', askedAtMs: Date.now(), source: 'claude' }
release()
const answer = await running
expect(calls.confirm).toBe(0)
expect(state.pending?.id).toBe(99)
expect(answer).not.toMatch(/Waiting for the person|Done: store a thing|Failed: store a thing/)
})
it('a deferred write that carries ANOTHER call\'s number is not settled by this call; one that carries this call\'s number is', async () => {
for (const mine of [false, true]) {
const { state, calls, deps } = setup('full', 'auto', { search: { label: 'search', readOnly: true } })
const control = (deps as unknown as { control: { runner: { settled: () => Promise<void> } } }).control
let release: () => void = () => undefined
let waited = false
// Only the first wait (the read still running) is held; a later one (after a confirm) returns at once.
control.runner.settled = () => (waited ? Promise.resolve() : ((waited = true), new Promise<void>(resolve => (release = resolve))))
const running = callTool('console_run', { id: 'search', text: 'x' }, deps)
// This is the first call, so its number is 1; the stranger carries 7.
state.pending = { id: 50, label: 'store a thing', args: [], expect: 'stored', askedAtMs: Date.now(), source: 'claude', byCall: mine ? 1 : 7 }
release()
await running
expect(calls.confirm, mine ? 'own deferred card' : 'stranger').toBe(mine ? 1 : 0)
}
})
it('the card the call itself raised is still settled as before (auto: confirmed)', async () => {
const { state, calls, deps } = setup('full', 'auto')
const runner = (deps as unknown as { control: { runner: { runById: (id: string) => boolean } } }).control.runner
const original = runner.runById
runner.runById = id => {
const ok = original(id)
if (state.pending !== null) state.pending.id = 7
return ok
}
const answer = await callTool('console_run', { id: 'mission-create' }, deps)
expect(calls.confirm).toBe(1)
expect(answer).toMatch(/Done|Ran/)
})
})
@@ -61,7 +61,7 @@ describe('a Yes runs only the card it was pressed on', () => {
state.pending = { id: 41, label: 'ask Claude about the terminal', args: [], expect: 'e', askedAtMs: 1, rememberKey: 'ask' }
state.terminal.harness = 'claude'
state.terminal.asked = { key: 'k', label: 'ask Claude about the terminal' } as never
state.terminal.asked = { key: 'k', label: 'ask Claude about the terminal', card: 41 }
const card = confirmRow({ kit, state, act, columns: 100, nowMs: 1_000, pictures: new Map() } as never) as unknown as El
@@ -0,0 +1 @@
0
@@ -0,0 +1 @@
[INFO] Executing tool: mission_request_action
@@ -0,0 +1,15 @@
Parameters: {"requestId":"cap-6","missionId":"msn_694db5dfd982c67fd44f4dfc","expectedRevision":2,"action":"cancel","reason":"capture"}
[OK] Tool executed in 38.50ms
Result:
{
"ok": true,
"data": {
"missionId": "msn_694db5dfd982c67fd44f4dfc",
"revision": 4,
"state": "cancelled",
"deduplicated": false,
"sequence": 4
}
}
@@ -0,0 +1 @@
0
@@ -0,0 +1 @@
[INFO] Executing tool: mission_request_action
@@ -0,0 +1,11 @@
Parameters: {"requestId":"cap-3","missionId":"msn_694db5dfd982c67fd44f4dfc","expectedRevision":2,"action":"cancel","reason":"capture"}
[OK] Tool executed in 9.70ms
Result:
{
"ok": false,
"code": "revision-conflict",
"message": "revision-conflict: expected 2, current 1; refresh and retry",
"currentRevision": 1
}
@@ -0,0 +1 @@
0
@@ -0,0 +1 @@
[INFO] Executing tool: mission_create
@@ -0,0 +1,14 @@
Parameters: {"requestId":"cap-1","objective":"capture a transcript"}
[OK] Tool executed in 31.17ms
Result:
{
"ok": true,
"data": {
"missionId": "msn_694db5dfd982c67fd44f4dfc",
"revision": 1,
"state": "draft",
"deduplicated": false
}
}
@@ -0,0 +1 @@
0
@@ -0,0 +1 @@
[INFO] Executing tool: mission_plan
@@ -0,0 +1,16 @@
Parameters: {"requestId":"cap-5","missionId":"msn_694db5dfd982c67fd44f4dfc","expectedRevision":1,"plan":{"tasks":[{"id":"t1","title":"a","dependsOn":[],"executor":{"mode":"session-bound","requirement":"x"}}],"acceptance":[{"id":"a1","check":"x","producer":"t1"}],"budget":{"currency":"USD","ceilingMinor":100}}}
[OK] Tool executed in 33.63ms
Result:
{
"ok": true,
"data": {
"missionId": "msn_694db5dfd982c67fd44f4dfc",
"revision": 2,
"state": "planned",
"deduplicated": false,
"sequence": 2,
"planDigest": "sha256:f8bdcf5db12ba3e80b2729509fb8bf7b54e5c57fc567566f6709537de9b3e8a9"
}
}
@@ -0,0 +1 @@
0
@@ -0,0 +1 @@
[INFO] Executing tool: mission_plan
@@ -0,0 +1,10 @@
Parameters: {"requestId":"cap-2","missionId":"msn_694db5dfd982c67fd44f4dfc","expectedRevision":1,"plan":{"tasks":[{"id":"t1","title":"a","dependsOn":[],"executor":{"mode":"session-bound"}}],"acceptance":[{"id":"a1","check":"x"}],"budget":{"currency":"USD","ceilingMinor":100}}}
[OK] Tool executed in 10.48ms
Result:
{
"ok": false,
"code": "invalid-input",
"message": "invalid-input: plan.tasks.0.executor.requirement: Required; plan.acceptance.0.producer: Required"
}
@@ -0,0 +1 @@
0
@@ -0,0 +1 @@
[INFO] Executing tool: task_cancel
@@ -0,0 +1,10 @@
Parameters: {"taskId":"task-0-none","reason":"capture"}
[OK] Tool executed in 8.48ms
Result:
{
"success": false,
"taskId": "task-0-none",
"error": "Task not found"
}
@@ -0,0 +1 @@
0
@@ -0,0 +1 @@
[INFO] Executing tool: task_cancel
@@ -0,0 +1,11 @@
Parameters: {"taskId":"task-1791563600018-yl0nu9","reason":"capture"}
[OK] Tool executed in 7.44ms
Result:
{
"success": true,
"taskId": "task-1791563600018-yl0nu9",
"status": "cancelled",
"cancelledAt": "2026-10-09T16:34:02.808Z"
}
@@ -0,0 +1 @@
1
@@ -0,0 +1,2 @@
[INFO] Executing tool: task_create
[ERROR] Tool execution failed: Failed to execute MCP tool 'task_create': policy-state-lock-timeout
@@ -0,0 +1 @@
Parameters: {"type":"test","description":"x [ok}]"}
@@ -0,0 +1 @@
0
@@ -0,0 +1 @@
[INFO] Executing tool: task_create
+15
View File
@@ -0,0 +1,15 @@
Parameters: {"type":"test","description":"x"}
[OK] Tool executed in 6.83ms
Result:
{
"taskId": "task-1791563600018-yl0nu9",
"type": "test",
"description": "x",
"priority": "normal",
"status": "pending",
"createdAt": "2026-10-09T16:33:20.018Z",
"assignedTo": [],
"tags": []
}
+133
View File
@@ -0,0 +1,133 @@
/**
* The fake `ruflo mcp exec` for the mission-create specs. Its output is REAL: tests/fixtures/mcp-exec holds transcripts captured from ruflo
* 3.56.1 in a scratch project (the lock timeout induced by holding .claude-flow/policy/state.lock), and every answer here is one of them
* with its Parameters line and its Result swapped for the call's: `Parameters:` on stdout before any `Result:`, `[INFO]`/`[ERROR]` on stderr.
*/
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import type { ActionSpec } from '../../hooks/actions'
import { PROJECT } from '../../hooks/data/files'
import type { Host } from '../../hooks/host'
import { READ_MS } from '../../hooks/mission-create'
import { createSpec, mcOf, setGoal } from '../../hooks/mission-control'
import { newState, type State } from '../../hooks/state'
export type Run = { exitCode: number; stdout: string; stderr: string }
const FIXTURES = join(__dirname, 'mcp-exec')
/** A transcript exactly as the CLI printed it. */
export const real = (name: string): Run => ({ stdout: readFileSync(join(FIXTURES, `${name}.out`), 'utf8'), stderr: readFileSync(join(FIXTURES, `${name}.err`), 'utf8'), exitCode: Number(readFileSync(join(FIXTURES, `${name}.code`), 'utf8').trim()) })
/** The real success transcript of `tool`, its Parameters line and its Result swapped for this call's (the layout byte for byte). */
export function answer(params: unknown, result: unknown, tool: string, base = real('t-ok')): Run {
return {
exitCode: 0,
stdout: base.stdout.replace(/^( {2}Parameters: ).*$/m, `$1${JSON.stringify(params)}`).replace(/(\nResult:\n)[\s\S]*$/, `$1${JSON.stringify(result, null, 2)}\n`),
stderr: base.stderr.replace(/task_create/g, tool),
}
}
/** The real lock-timeout transcript for this call. */
export function locked(params: unknown, tool: string): Run {
const base = real('t-lock')
return { exitCode: base.exitCode, stdout: base.stdout.replace(/^( {2}Parameters: ).*$/m, `$1${JSON.stringify(params)}`), stderr: base.stderr.replace(/task_create/g, tool) }
}
export const ID = 'msn_0123456789abcdef01234567'
/** A try whose answer was lost: the process exited non-zero and printed nothing (transient). */
export const LOST: Run = { exitCode: 1, stdout: '', stderr: '' }
export const isOk = (result: Record<string, unknown>) => typeof result.taskId === 'string'
export type Store = Record<string, { taskId: string; type: string; description: string; status: string; tags: string[]; assignedTo: string[]; createdAt: string }>
export type World = { runs: { tool: string; params: Record<string, unknown> }[]; waits: number[]; store: Store; mission: string; onWait?: () => void; unreadable?: boolean }
export type Special = (tool: string, params: Record<string, unknown>, nth: number, world: World) => Run | Error | Promise<Run | undefined> | undefined
/** A CLI that answers in the real transcripts' layout; task_create writes the store the console reads back, the mission cancel the observation. */
export function hostOf(world: World, special: Special = () => undefined): Host {
let made = 0
const seen = new Map<string, number>()
const make = (params: Record<string, unknown>, taskId = `task-${++made}`) => {
world.store[taskId] = { taskId, type: String(params.type), description: String(params.description), status: 'pending', tags: params.tags as string[], assignedTo: [], createdAt: new Date().toISOString() }
return taskId
}
return {
run: async (argv: readonly string[]) => {
const tool = argv[argv.indexOf('-t') + 1] as string
const params = JSON.parse(argv[argv.indexOf('-p') + 1] as string) as Record<string, unknown>
const key = tool === 'task_create' ? `${tool}:${String((params.tags as string[])[1])}` : tool === 'task_cancel' ? `${tool}:${String(params.taskId)}` : tool
const nth = (seen.get(key) ?? 0) + 1
seen.set(key, nth)
world.runs.push({ tool, params })
const out = await special(tool, params, nth, world)
if (out instanceof Error) throw out
if (out !== undefined) return out
if (tool === 'mission_create') return answer(params, { ok: true, data: { missionId: ID, revision: 1, state: 'draft', deduplicated: false } }, tool, real('m-create'))
if (tool === 'mission_plan') return answer(params, { ok: true, data: { missionId: ID, revision: 2, state: 'planned', deduplicated: false, sequence: 2, planDigest: 'sha256:abc' } }, tool, real('m-plan-ok'))
if (tool === 'task_create') {
const taskId = make(params)
return answer(params, { ...world.store[taskId], priority: 'normal' }, tool)
}
if (tool === 'task_cancel') {
const task = world.store[String(params.taskId)]
if (task === undefined) return answer(params, { success: false, taskId: params.taskId, error: 'Task not found' }, tool, real('t-cancel-missing'))
task.status = 'cancelled'
return answer(params, { success: true, taskId: params.taskId, status: 'cancelled', cancelledAt: new Date().toISOString() }, tool, real('t-cancel'))
}
if (tool === 'mission_request_action') {
world.mission = 'cancelled'
return answer(params, { ok: true, data: { missionId: ID, revision: 4, state: 'cancelled', deduplicated: false, sequence: 4 } }, tool, real('m-cancel-ok'))
}
return answer(params, { ok: true }, tool)
},
fs: {
read: async (path: string) => {
if (world.unreadable === true) throw new Error('EACCES')
if (path.endsWith(PROJECT.tasks)) return JSON.stringify({ tasks: world.store, version: '3.0.0' })
if (path.endsWith(PROJECT.missions)) return JSON.stringify({ schemaVersion: 1, contract: 'ruflo.mission-observation/1', source: 'ruflo-cli/missions', observedAt: new Date().toISOString(), truncated: false, missions: [{ missionId: ID, objective: 'x', state: world.mission, revision: 4, executionMode: 'session-bound' }] })
throw new Error('ENOENT')
},
stat: async () => undefined,
list: async () => [],
},
// The backoff waits go through the host's clock: recorded, and they return at once (after the test's hook). Read time limits never fire.
after: (ms: number, fn: () => void) => {
if (ms === READ_MS) return { cancel: () => undefined }
world.waits.push(ms)
world.onWait?.()
fn()
return { cancel: () => undefined }
},
storeGet: async () => undefined,
storeSet: async () => undefined,
invalidate: () => undefined,
} as unknown as Host
}
export const fresh = (): World => ({ runs: [], waits: [], store: {}, mission: 'planned' })
export function planned(): { state: State; steps: string[] } {
const state = newState({})
state.snapshot = { tasks: [], agents: [], claims: [], swarm: null, plugins: { missingFromClone: [] }, alerts: [] } as never
setGoal(state, 'add a dark mode toggle to settings')
return { state, steps: (mcOf(state).planned?.steps ?? []).map(step => step.id) }
}
export const creates = (world: World, step?: string) => world.runs.filter(run => run.tool === 'task_create' && (step === undefined || (run.params.tags as string[]).includes(`task:${step}`)))
export const isStep = (params: Record<string, unknown>, step: string | undefined) => (params.tags as string[] | undefined)?.includes(`task:${step}`) === true
export const run = async (state: State, host: Host) => (createSpec(state, host, () => undefined) as ActionSpec).run?.()
+6 -1
View File
@@ -62,7 +62,12 @@ export function fsOn(disk: Disk, withTail = true): SessionFs {
fs.readTail = async (path, bytes) => {
disk.tails.push(path)
return (disk.files.get(path)?.content ?? '').slice(-bytes)
const file = disk.files.get(path)
// A refused read is refused whichever call makes it.
if (file === undefined || disk.failRead.has(path)) throw new Error('refused')
return file.content.slice(-bytes)
}
}
@@ -0,0 +1,277 @@
/**
* Creating a mission on a busy project: every `mcp exec` takes the policy state lock, and on a large policy state some calls time out on it
* (#3164, #3892). The CLI output here is REAL: tests/fixtures/mcp-exec holds `ruflo mcp exec` transcripts captured from ruflo 3.56.1 in a
* scratch project (the lock timeout induced by holding .claude-flow/policy/state.lock), and the fake CLI (tests/fixtures/mission-cli-real.ts) answers in exactly that
* shape: `Parameters:` on stdout before any `Result:`, `[INFO]`/`[ERROR]` on stderr.
* npx vitest run plugins/ruflo-console/tests/mission-create-retry.spec.ts
*/
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { ActionSpec } from '../hooks/actions'
import { readAttempt, resultOf } from '../hooks/data/mcp-run'
import { CREATE_DEADLINE_MS, RETRY_WAITS_MS } from '../hooks/mission-create'
import { activeMission, createSpec, mcOf } from '../hooks/mission-control'
import { answer, creates, fresh, hostOf, ID, isOk, isStep, locked, LOST, planned, real, run } from './fixtures/mission-cli-real'
afterEach(() => vi.useRealTimers())
describe('reading one real mcp exec run', () => {
it('a real lock timeout: the Parameters object before it is not read as an answer, and it is transient', () => {
const run = real('t-lock')
expect(run.stdout).toContain('Parameters: {')
expect(run.stdout).not.toContain('Result:')
expect(resultOf(run.stdout)).toBeNull()
expect(readAttempt(run, isOk)).toEqual({ result: null, ok: false, transient: true, reason: 'policy-state-lock-timeout' })
// The live case: a description with no bracket in it, so the Parameters object is valid JSON (it must still not be the answer).
const live = locked({ type: 'feature', description: `[${ID}/t5] Implement`, priority: 'normal', tags: [`mission:${ID}`, 'task:t5'] }, 'task_create')
expect(resultOf(live.stdout)).toBeNull()
expect(readAttempt(live, isOk).transient).toBe(true)
})
it('a real success is read after its own Result line; a description holding } and "Result:" does not confuse it', () => {
expect(readAttempt(real('t-ok'), isOk)).toMatchObject({ ok: true, transient: false, result: { taskId: 'task-1791563600018-yl0nu9' } })
const tricky = { type: 'test', description: 'x [ok}] Result: {"taskId":"fake"}' }
const run = answer(tricky, { taskId: 'task-9', description: tricky.description, tags: [] }, 'task_create')
expect(readAttempt(run, isOk)).toMatchObject({ ok: true, result: { taskId: 'task-9', description: tricky.description } })
})
it('definite answers are never transient: a refusal in the answer, a policy denial that mentions a timeout, a command that cannot start', () => {
expect(readAttempt(real('t-cancel-missing'), result => result.success === true)).toMatchObject({ ok: false, transient: false, reason: 'Task not found' })
expect(readAttempt(real('m-plan'), result => result.ok === true)).toMatchObject({ ok: false, transient: false })
expect(readAttempt(real('m-plan'), result => result.ok === true).reason).toContain('invalid-input')
// The denial format of mcp-client.ts (`policy-<outcome>:<reason>; receipt=<id>`) in the real failure layout; a denial was not induced live.
const denial = { ...real('t-lock'), stderr: real('t-lock').stderr.replace('policy-state-lock-timeout', 'policy-denied:task.create is limited; retry after the rate timeout window; receipt=r1') }
expect(readAttempt(denial, isOk)).toMatchObject({ ok: false, transient: false })
expect(readAttempt(denial, isOk).reason).toContain('policy-denied')
expect(readAttempt({ error: new Error('spawn ruflo ENOENT') }, isOk)).toMatchObject({ transient: false })
// A rejection of the host is never transient, whatever its words; only the caller's own (structured) time limit is.
expect(readAttempt({ error: new Error('still running after 60000 ms') }, isOk)).toMatchObject({ transient: false })
expect(readAttempt({ error: new Error('permission denied: timed out waiting for approval') }, isOk)).toMatchObject({ transient: false })
expect(readAttempt({ timedOutMs: 60_000 }, isOk)).toMatchObject({ transient: true })
expect(readAttempt({ timedOutMs: 60_000 }, isOk).reason).toContain('may still finish')
// Truly empty output with a failing exit is transient; any output (a shell's "command not found", housekeeping only) is not.
expect(readAttempt({ exitCode: 1, stdout: '', stderr: '' }, isOk)).toMatchObject({ transient: true, reason: 'no answer (exit 1)' })
expect(readAttempt({ exitCode: 127, stdout: '', stderr: 'zsh: command not found: ruflo\n' }, isOk)).toMatchObject({ transient: false, reason: 'zsh: command not found: ruflo' })
expect(readAttempt({ exitCode: 1, stdout: ' Parameters: {"a":1}\n', stderr: '[INFO] Executing tool: task_create\n' }, isOk)).toMatchObject({ transient: false })
})
})
describe('mission create on a busy project', () => {
it('a real lock timeout on one step is tried again after the first wait: the mission is created with all 15 tasks', async () => {
const { state, steps } = planned()
const world = fresh()
const host = hostOf(world, (tool, params, nth) => (tool === 'task_create' && isStep(params, steps[4]) && nth === 1 ? locked(params, tool) : undefined))
expect(steps).toHaveLength(15)
await run(state, host)
expect(mcOf(state).last).toMatchObject({ ok: true, label: `mission ${ID} planned` })
expect(activeMission(state)?.tasks).toHaveLength(15)
expect(creates(world, steps[4])).toHaveLength(2)
expect(world.waits).toEqual([RETRY_WAITS_MS[0]])
expect(Object.keys(world.store)).toHaveLength(15)
expect(world.runs.some(entry => entry.tool === 'task_cancel' || entry.tool === 'mission_request_action')).toBe(false)
})
it('a create that timed out but wrote during the backoff is found after the wait and not made twice', async () => {
const { state, steps } = planned()
const world = fresh()
let late: Record<string, unknown> | null = null
const host = hostOf(world, (tool, params, nth) => {
if (tool !== 'task_create' || !isStep(params, steps[2]) || nth !== 1) return undefined
late = params
return LOST
})
// The slow CLI finishes its write while the console waits.
world.onWait = () => {
if (late !== null && world.store['task-late'] === undefined) world.store['task-late'] = { taskId: 'task-late', type: 'feature', description: String(late.description), status: 'pending', tags: late.tags as string[], assignedTo: [], createdAt: new Date().toISOString() }
}
await run(state, host)
expect(mcOf(state).last?.ok).toBe(true)
expect(creates(world, steps[2])).toHaveLength(1)
expect(activeMission(state)?.tasks.find(task => task.id === steps[2])?.rufloTaskId).toBe('task-late')
expect(Object.keys(world.store)).toHaveLength(15)
})
it('two tasks in the store that both match the step stop the create: it reports them and does not guess', async () => {
const { state, steps } = planned()
const world = fresh()
const host = hostOf(world, (tool, params, nth, w) => {
if (tool !== 'task_create' || !isStep(params, steps[1]) || nth !== 1) return undefined
for (const taskId of ['task-a', 'task-b']) w.store[taskId] = { taskId, type: 'feature', description: String(params.description), status: 'pending', tags: params.tags as string[], assignedTo: [], createdAt: new Date().toISOString() }
return LOST
})
await run(state, host)
expect(creates(world, steps[1])).toHaveLength(1)
expect(mcOf(state).last?.ok).toBe(false)
expect(mcOf(state).last?.lines?.[0]).toContain('2 tasks in the store match')
expect(mcOf(state).last?.lines?.[0]).toContain('task-a, task-b')
expect(activeMission(state)).toBeNull()
})
it('a store that cannot be read stops a retry whose first try may have written', async () => {
const { state, steps } = planned()
const world = fresh()
const host = hostOf(world, (tool, params, nth, w) => {
if (tool !== 'task_create' || !isStep(params, steps[0]) || nth !== 1) return undefined
w.unreadable = true
return LOST
})
await run(state, host)
expect(creates(world)).toHaveLength(1)
expect(mcOf(state).last?.lines?.[0]).toContain('the task store could not be read')
})
it('a denial that mentions a timeout is not tried again', async () => {
const { state, steps } = planned()
const world = fresh()
const host = hostOf(world, (tool, params) => (tool === 'task_create' && isStep(params, steps[1]) ? { ...locked(params, tool), stderr: locked(params, tool).stderr.replace('policy-state-lock-timeout', 'policy-denied:retry after the rate timeout window; receipt=r1') } : undefined))
await run(state, host)
expect(creates(world, steps[1])).toHaveLength(1)
expect(world.waits).toEqual([])
expect(mcOf(state).last?.detail).toContain('policy-denied')
})
it('a step that keeps timing out on the lock aborts: cancels retried, the store and the mission READ BACK, the pending id named', async () => {
const { state, steps } = planned()
const world = fresh()
const host = hostOf(world, (tool, params, nth) => {
if (tool === 'task_create' && isStep(params, steps[5])) return locked(params, tool)
if (tool === 'task_cancel' && params.taskId === 'task-2' && nth === 1) return locked(params, tool)
if (tool === 'task_cancel' && params.taskId === 'task-4') return locked(params, tool)
return undefined
})
await run(state, host)
const last = mcOf(state).last
const asked = world.runs.filter(entry => entry.tool === 'mission_request_action')
expect(creates(world, steps[5])).toHaveLength(1 + RETRY_WAITS_MS.length)
expect(creates(world)).toHaveLength(5 + 1 + RETRY_WAITS_MS.length)
expect(world.runs.filter(entry => entry.tool === 'task_cancel' && entry.params.taskId === 'task-2')).toHaveLength(2)
expect(world.runs.filter(entry => entry.tool === 'task_cancel' && entry.params.taskId === 'task-4')).toHaveLength(1 + RETRY_WAITS_MS.length)
expect(asked).toHaveLength(1)
expect(asked[0]?.params).toMatchObject({ missionId: ID, action: 'cancel', expectedRevision: 2 })
expect(last?.ok).toBe(false)
expect(last?.label).toBe(`mission not created: task ${steps[5]} could not be made`)
expect(last?.lines?.[0]).toBe(`task ${steps[5]}: policy-state-lock-timeout (${1 + RETRY_WAITS_MS.length} tries)`)
expect(last?.lines?.[1]).toBe('the store shows 4 of the 5 tasks of this mission cancelled; 1 not cancelled: task-4 (pending)')
expect(last?.lines?.[2]).toBe(`mission ${ID}: cancel accepted; the observation shows cancelled`)
expect(last?.detail).toContain('Store: 4 of 5 cancelled, 1 not')
expect(world.store['task-4']?.status).toBe('pending')
})
it('an acknowledged cancel that did not land is reported as the store shows it, not as acknowledged', async () => {
const { state, steps } = planned()
const world = fresh()
const host = hostOf(world, (tool, params) => {
if (tool === 'task_create' && isStep(params, steps[2])) return answer(params, { success: false, error: 'invalid type' }, tool)
// The CLI answers success for task-1, but the store never changed (ack lost / write lost).
if (tool === 'task_cancel' && params.taskId === 'task-1') return answer(params, { success: true, taskId: 'task-1', status: 'cancelled' }, tool, real('t-cancel'))
return undefined
})
await run(state, host)
expect(mcOf(state).last?.lines?.[1]).toBe('the store shows 1 of the 2 tasks of this mission cancelled; 1 not cancelled: task-1 (pending)')
})
it('a refused plan cancels the mission that was already created, at the created revision', async () => {
const { state } = planned()
const world = fresh()
const refused = real('m-plan')
const host = hostOf(world, tool => (tool === 'mission_plan' ? refused : undefined))
await run(state, host)
const asked = world.runs.filter(entry => entry.tool === 'mission_request_action')
expect(creates(world)).toHaveLength(0)
expect(asked).toHaveLength(1)
expect(asked[0]?.params).toMatchObject({ missionId: ID, action: 'cancel', expectedRevision: 1 })
expect(mcOf(state).last?.label).toBe('mission not created: mission_plan failed')
expect(mcOf(state).last?.lines?.[0]).toContain('invalid-input')
expect(mcOf(state).last?.lines?.[2]).toBe(`mission ${ID}: cancel accepted; the observation shows cancelled`)
})
it('a revision conflict on the mission cancel is asked once more at the revision it names', async () => {
const { state } = planned()
const world = fresh()
const conflict = real('m-cancel')
const host = hostOf(world, (tool, params, nth) => (tool === 'mission_plan' ? real('m-plan') : tool === 'mission_request_action' && nth === 1 ? { ...conflict, stdout: conflict.stdout.replace('"currentRevision": 1', '"currentRevision": 3') } : undefined))
await run(state, host)
const asked = world.runs.filter(entry => entry.tool === 'mission_request_action')
expect(asked.map(entry => entry.params.expectedRevision)).toEqual([1, 3])
expect(new Set(asked.map(entry => entry.params.requestId)).size).toBe(2)
})
it('a second create while one runs is refused; request ids are unique per create', async () => {
const { state } = planned()
const world = fresh()
let release: () => void = () => undefined
const gate = new Promise<void>(resolve => (release = resolve))
const host = hostOf(world, async (tool, params, nth) => {
if (tool === 'mission_create' && nth === 1) await gate
return undefined
})
const first = createSpec(state, host, () => undefined) as ActionSpec
const second = createSpec(state, host, () => undefined) as ActionSpec
const running = first.run?.()
await Promise.resolve()
const refused = await second.run?.()
expect(refused).toMatchObject({ ok: false, label: 'not created' })
expect(refused?.detail).toContain('already being created')
release()
await running
expect(mcOf(state).last?.ok).toBe(true)
expect(world.runs.filter(entry => entry.tool === 'mission_create')).toHaveLength(1)
expect(first.argv?.join(' ')).not.toBe(second.argv?.join(' '))
})
it('the create stops at its deadline and undoes what it made', async () => {
vi.useFakeTimers({ toFake: ['Date'] })
const { state } = planned()
const world = fresh()
// Each task_create takes 40 s of the clock.
const host = hostOf(world, tool => void (tool === 'task_create' && vi.setSystemTime(Date.now() + 40_000)))
await run(state, host)
const made = Math.ceil(CREATE_DEADLINE_MS / 40_000)
expect(creates(world)).toHaveLength(made)
expect(mcOf(state).last?.label).toContain('out of time')
expect(mcOf(state).last?.lines?.[1]).toBe(`the store shows ${made} of the ${made} tasks of this mission cancelled`)
})
})
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff. Show more