From a0866ccf24ae0428a5c855e91c320ff77d5aa8ff Mon Sep 17 00:00:00 2001 From: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Fri, 9 Oct 2026 22:46:38 -0400 Subject: [PATCH 01/43] fix(mcp): preserve cancellation when an aborted executor resolves Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com> --- .../task-cancellation-result.test.ts | 63 +++++++++++++++++++ v3/@claude-flow/mcp/src/task-manager.ts | 10 ++- 2 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 v3/@claude-flow/mcp/__tests__/task-cancellation-result.test.ts diff --git a/v3/@claude-flow/mcp/__tests__/task-cancellation-result.test.ts b/v3/@claude-flow/mcp/__tests__/task-cancellation-result.test.ts new file mode 100644 index 0000000000..6c0552050f --- /dev/null +++ b/v3/@claude-flow/mcp/__tests__/task-cancellation-result.test.ts @@ -0,0 +1,63 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { TaskManager } from '../src/task-manager.js'; +import type { ILogger } from '../src/types.js'; +const logger: ILogger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }; +let manager: TaskManager; +beforeEach(() => { manager = new TaskManager(logger, { maxConcurrentTasks: 1, taskTimeout: 1000 }); }); +afterEach(() => { manager.destroy(); vi.useRealTimers(); }); + +it('reports cancellation rather than a result when an aborted executor resolves normally', async () => { + let finish!: (value: string) => void; + let signal!: AbortSignal; + const id = manager.createTask(async (_progress, received) => { + signal = received; + return new Promise(resolve => { finish = resolve; }); + }); + const completed = vi.fn(); + const cancelled = vi.fn(); + manager.on('task:completed', completed); + manager.on('task:cancelled', cancelled); + const waiting = manager.waitForTask(id); + expect(manager.cancelTask(id, 'operator cancelled')).toBe(true); + expect(signal.aborted).toBe(true); + finish('late success'); + expect(await waiting).toMatchObject({ state: 'cancelled' }); + expect(manager.getTask(id)?.result).toBeUndefined(); + expect(completed).not.toHaveBeenCalled(); + expect(cancelled).toHaveBeenCalledTimes(1); +}); +it('holds the concurrency slot until the aborted executor settles', async () => { + let finish!: () => void; + const id = manager.createTask(() => new Promise(resolve => { finish = () => resolve('late'); })); + manager.cancelTask(id); + const next = vi.fn(async () => 'next'); + const nextId = manager.createTask(next); + expect(next).not.toHaveBeenCalled(); + finish(); + expect(await manager.waitForTask(id)).toMatchObject({ state: 'cancelled' }); + expect(await manager.waitForTask(nextId)).toMatchObject({ state: 'completed', result: 'next' }); + expect(next).toHaveBeenCalledTimes(1); +}); +it('a task timeout cannot be replaced by a subsequently resolved success', async () => { + vi.useFakeTimers(); + let finish!: () => void; + const id = manager.createTask(() => new Promise(resolve => { finish = () => resolve('late'); })); + const waiting = manager.waitForTask(id, 2000); + await vi.advanceTimersByTimeAsync(1000); + finish(); + expect(await waiting).toMatchObject({ state: 'cancelled' }); + expect(manager.getTask(id)?.result).toBeUndefined(); +}); +it('still returns successful results when no cancellation was requested', async () => { + const id = manager.createTask(async () => 'result'); + expect(await manager.waitForTask(id)).toMatchObject({ state: 'completed', result: 'result' }); + expect(manager.cancelTask(id)).toBe(false); +}); +it('retains the abort-aware executor rejection path', async () => { + const id = manager.createTask((_progress, signal) => new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => reject(new Error('executor cancelled')), { once: true }); + })); + const waiting = manager.waitForTask(id); + manager.cancelTask(id); + expect(await waiting).toMatchObject({ state: 'cancelled' }); +}); diff --git a/v3/@claude-flow/mcp/src/task-manager.ts b/v3/@claude-flow/mcp/src/task-manager.ts index 4429e660cd..af03208f8b 100644 --- a/v3/@claude-flow/mcp/src/task-manager.ts +++ b/v3/@claude-flow/mcp/src/task-manager.ts @@ -123,7 +123,15 @@ export class TaskManager extends EventEmitter { clearTimeout(timeoutId); - if (task.state === 'running') { + // Executors may acknowledge AbortSignal by returning, or ignore it and + // settle later. Cancellation still owns the terminal outcome in either + // case; keep the slot occupied until the executor actually settles. + if (task.state === 'running' && task.abortController.signal.aborted) { + task.state = 'cancelled'; + task.updatedAt = new Date(); + this.logger.debug('Task cancelled', { taskId }); + this.emit('task:cancelled', { taskId }); + } else if (task.state === 'running') { task.state = 'completed'; task.result = result; task.updatedAt = new Date(); From 0aa99cd5aad17a333b70303c78675d631d29a2a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 10 Oct 2026 06:28:09 +0000 Subject: [PATCH 02/43] dream(performance): #3976 fallbackLouvain() communityTotal O(n^2)->O(n*deg) incremental fix fallbackLouvain()'s local-moving loop rebuilt a communityTotal map via a full scan of every node, once per node, once per pass (O(n^2) per pass), instead of maintaining it incrementally like networkx's Stot/python-louvain's status.degrees (O(1) per accepted move). loadRuVector() never resolves real native acceleration against any published ruvector/@ruvector/wasm version, so this fallback is the only community-detection path that ever runs, reachable via the shipped `claude-flow analyze modules` command. New test file proves byte-identical correctness against a frozen copy of the pre-fix algorithm plus a complexity-growth regression guard; a standalone tsx probe shows per-N speedup growing 2.1x->37.5x as N grows 8x, the signature of a complexity-class fix. Full @claude-flow/cli suite and tsc --noEmit byte-identical to baseline outside the new test file. Evaluated: ACCEPT. Independently adversarially reviewed: CONFIRMED, no blocking caveats. Darwin skipped (binary correctness-preserving fix, no tunable parameter). Co-Authored-By: RuFlo Claude-Session: https://claude.ai/code/session_01JL2GEEWf9ezZo1X1wQ2Ls6 --- docs/dream-cycle/dream-gist-2026-10-10.md | 86 +++++++ .../graph-analyzer.louvain-complexity.test.ts | 233 ++++++++++++++++++ .../cli/src/ruvector/graph-analyzer.ts | 26 +- 3 files changed, 338 insertions(+), 7 deletions(-) create mode 100644 docs/dream-cycle/dream-gist-2026-10-10.md create mode 100644 v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.louvain-complexity.test.ts diff --git a/docs/dream-cycle/dream-gist-2026-10-10.md b/docs/dream-cycle/dream-gist-2026-10-10.md new file mode 100644 index 0000000000..512e8947da --- /dev/null +++ b/docs/dream-cycle/dream-gist-2026-10-10.md @@ -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 ` 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. diff --git a/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.louvain-complexity.test.ts b/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.louvain-complexity.test.ts new file mode 100644 index 0000000000..c7744632a0 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.louvain-complexity.test.ts @@ -0,0 +1,233 @@ +/** + * fallbackLouvain() complexity-class regression test. + * + * `loadRuVector()` never successfully resolves native acceleration against + * any real published `ruvector`/`@ruvector/wasm` version (confirmed: the + * installed `ruvector` package exports no `hooks_graph_mincut`/ + * `hooks_graph_cluster`, and `@ruvector/wasm` isn't a resolvable package at + * all) — so `fallbackLouvain()` is the only community-detection path that + * ever actually runs, reached from the shipped `claude-flow analyze modules` + * CLI command via `analyzeGraph()` → `analyzeModuleCommunities()`. + * + * `fallbackLouvain()`'s local-moving loop used to rebuild a `communityTotal` + * map from a full scan of every node, once per node, once per pass — O(n) + * work repeated n times per pass, i.e. O(n^2) per pass regardless of how + * sparse the graph is. `legacyFallbackLouvain` below is a frozen, verbatim + * copy of that pre-fix logic (community/degree bookkeeping identical to the + * current `fallbackLouvain`, only the inner-loop total computation differs) + * so both the correctness-parity and performance-regression assertions below + * are self-contained and don't depend on `git stash` during CI. + */ +import { describe, it, expect } from 'vitest'; +import { fallbackLouvain } from '../../src/ruvector/graph-analyzer.js'; + +type Edge = [string, string, number]; + +function legacyFallbackLouvain( + nodes: string[], + edges: Edge[] +): { communities: Array<{ id: number; members: string[] }>; modularity: number } { + if (nodes.length === 0) return { communities: [], modularity: 0 }; + + const adj = new Map>(); + for (const node of nodes) adj.set(node, new Map()); + let totalWeight = 0; + for (const [u, v, w] of edges) { + if (adj.has(u) && adj.has(v)) { + adj.get(u)!.set(v, (adj.get(u)!.get(v) || 0) + w); + adj.get(v)!.set(u, (adj.get(v)!.get(u) || 0) + w); + totalWeight += w * 2; + } + } + if (totalWeight === 0) { + return { communities: nodes.map((n, i) => ({ id: i, members: [n] })), modularity: 0 }; + } + + const community = new Map(); + let nextCommunityId = 0; + for (const node of nodes) community.set(node, nextCommunityId++); + + const degree = new Map(); + for (const node of nodes) { + let d = 0; + for (const [, w] of Array.from(adj.get(node)!.entries())) d += w; + degree.set(node, d); + } + + let improved = true; + const maxIterations = 10; + let iteration = 0; + + while (improved && iteration < maxIterations) { + improved = false; + iteration++; + + for (const node of nodes) { + const currentCommunity = community.get(node)!; + const nodeAdj = adj.get(node)!; + const nodeDegree = degree.get(node)!; + + const communityWeights = new Map(); + for (const [neighbor, weight] of Array.from(nodeAdj.entries())) { + const neighborCommunity = community.get(neighbor)!; + communityWeights.set(neighborCommunity, (communityWeights.get(neighborCommunity) || 0) + weight); + } + + // The pre-fix defect: a full O(n) rebuild, inside the per-node loop. + const communityTotal = new Map(); + for (const [n, c] of Array.from(community.entries())) { + communityTotal.set(c, (communityTotal.get(c) || 0) + (degree.get(n) || 0)); + } + + let bestCommunity = currentCommunity; + let bestGain = 0; + + for (const [targetCommunity, edgeWeight] of Array.from(communityWeights.entries())) { + if (targetCommunity === currentCommunity) continue; + const currentTotal = communityTotal.get(currentCommunity) || 0; + const targetTotal = communityTotal.get(targetCommunity) || 0; + const currentEdges = communityWeights.get(currentCommunity) || 0; + const gain = + (edgeWeight - currentEdges) / totalWeight - + (nodeDegree * (targetTotal - currentTotal + nodeDegree)) / (totalWeight * totalWeight); + if (gain > bestGain) { + bestGain = gain; + bestCommunity = targetCommunity; + } + } + + if (bestCommunity !== currentCommunity) { + community.set(node, bestCommunity); + improved = true; + } + } + } + + const communityMembers = new Map(); + for (const [node, comm] of Array.from(community.entries())) { + if (!communityMembers.has(comm)) communityMembers.set(comm, []); + communityMembers.get(comm)!.push(node); + } + const communities: Array<{ id: number; members: string[] }> = []; + let id = 0; + for (const members of Array.from(communityMembers.values())) communities.push({ id: id++, members }); + + let modularity = 0; + for (const [u, v, w] of edges) { + const cu = community.get(u)!; + const cv = community.get(v)!; + if (cu === cv) { + const du = degree.get(u)!; + const dv = degree.get(v)!; + modularity += w - (du * dv) / totalWeight; + } + } + modularity /= totalWeight; + + return { communities, modularity }; +} + +/** Deterministic LCG PRNG — no Math.random, so fixtures are byte-identical across runs. */ +function makeRng(seed: number): () => number { + let s = seed >>> 0; + return () => { + s = (s * 1664525 + 1013904223) >>> 0; + return s / 4294967296; + }; +} + +function buildClusteredGraph( + numClusters: number, + clusterSize: number, + seed: number +): { nodes: string[]; edges: Edge[] } { + const rng = makeRng(seed); + const nodes: string[] = []; + for (let c = 0; c < numClusters; c++) { + for (let i = 0; i < clusterSize; i++) nodes.push(`c${c}n${i}`); + } + const edges: Edge[] = []; + for (let c = 0; c < numClusters; c++) { + const members = nodes.slice(c * clusterSize, (c + 1) * clusterSize); + for (let i = 0; i < members.length; i++) { + for (let j = i + 1; j < members.length; j++) { + if (rng() < 0.6) edges.push([members[i], members[j], 1]); + } + } + } + for (let c = 0; c < numClusters - 1; c++) { + const a = nodes[c * clusterSize + Math.floor(rng() * clusterSize)]; + const b = nodes[(c + 1) * clusterSize + Math.floor(rng() * clusterSize)]; + edges.push([a, b, 1]); + } + return { nodes, edges }; +} + +function normalize(result: { communities: Array<{ members: string[] }>; modularity: number }) { + const members = result.communities + .map(c => [...c.members].sort()) + .sort((a, b) => (a[0] > b[0] ? 1 : a[0] < b[0] ? -1 : 0)); + return { members, modularity: Number(result.modularity.toFixed(9)) }; +} + +describe('fallbackLouvain complexity fix', () => { + it('produces byte-identical community partitions to the pre-fix algorithm', () => { + const { nodes, edges } = buildClusteredGraph(6, 10, 42); + const current = normalize(fallbackLouvain(nodes, edges)); + const legacy = normalize(legacyFallbackLouvain(nodes, edges)); + expect(current).toEqual(legacy); + // Not a degenerate all-one-community or all-singleton result. + expect(current.members.length).toBeGreaterThan(1); + expect(current.members.length).toBeLessThan(nodes.length); + }); + + it('produces byte-identical output on a second, differently-shaped graph', () => { + const { nodes, edges } = buildClusteredGraph(4, 25, 1337); + const current = normalize(fallbackLouvain(nodes, edges)); + const legacy = normalize(legacyFallbackLouvain(nodes, edges)); + expect(current).toEqual(legacy); + }); + + it('handles the zero-edge and single-node degenerate cases identically', () => { + expect(normalize(fallbackLouvain([], []))).toEqual(normalize(legacyFallbackLouvain([], []))); + expect(normalize(fallbackLouvain(['solo'], []))).toEqual(normalize(legacyFallbackLouvain(['solo'], []))); + }); + + it('scales near-linearly with node count at fixed average degree, unlike the pre-fix O(n^2) rebuild', () => { + // Fixed cluster size (20) keeps average degree roughly constant as + // numClusters grows, isolating the complexity-class difference from + // any confound where a denser graph also has a larger `communityWeights` + // inner loop (which is correctly O(degree) in both versions). + const small = buildClusteredGraph(10, 20, 7); // n=200 + const large = buildClusteredGraph(80, 20, 7); // n=1600 (8x nodes) + + function bestOf(fn: (n: string[], e: Edge[]) => unknown, nodes: string[], edges: Edge[]): number { + fn(nodes, edges); // warmup (JIT) + let best = Infinity; + for (let t = 0; t < 3; t++) { + const start = performance.now(); + fn(nodes, edges); + const dur = performance.now() - start; + if (dur < best) best = dur; + } + return best; + } + + const currentSmall = bestOf(fallbackLouvain, small.nodes, small.edges); + const currentLarge = bestOf(fallbackLouvain, large.nodes, large.edges); + const legacySmall = bestOf(legacyFallbackLouvain, small.nodes, small.edges); + const legacyLarge = bestOf(legacyFallbackLouvain, large.nodes, large.edges); + + const currentGrowth = currentLarge / Math.max(currentSmall, 0.001); + const legacyGrowth = legacyLarge / Math.max(legacySmall, 0.001); + + // 8x nodes: true O(n) would grow ~8x, true O(n^2) would grow ~64x. + // Generous thresholds (CI-timing headroom): fixed algorithm stays well + // under half the quadratic growth the legacy algorithm exhibits, and + // the legacy algorithm itself must show clearly super-linear growth — + // otherwise this fixture isn't actually exercising the O(n^2) path. + expect(legacyGrowth).toBeGreaterThan(20); // legacy is genuinely ~quadratic + expect(currentGrowth).toBeLessThan(legacyGrowth / 2); // fixed algorithm is materially better + expect(currentLarge).toBeLessThan(legacyLarge); // and strictly faster in absolute terms at n=1600 + }); +}); diff --git a/v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts b/v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts index b6dde4ebb2..505a73f875 100644 --- a/v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts +++ b/v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts @@ -696,6 +696,18 @@ function fallbackLouvain( const maxIterations = 10; let iteration = 0; + // Community total weighted degree. Maintained incrementally (±nodeDegree on + // each accepted move) rather than rebuilt from a full scan of `community` + // inside the per-node loop below — the rebuild was O(n) per node (O(n^2) per + // pass), matching neither the reference Louvain implementations (networkx's + // `Stot`, python-louvain's `status.degrees`, both updated in O(1) per move) + // nor the algorithm's own linear-on-sparse-data design intent. + const communityTotal = new Map(); + for (const node of nodes) { + const c = community.get(node)!; + communityTotal.set(c, (communityTotal.get(c) || 0) + (degree.get(node) || 0)); + } + while (improved && iteration < maxIterations) { improved = false; iteration++; @@ -716,19 +728,17 @@ function fallbackLouvain( ); } - // Calculate community totals - const communityTotal = new Map(); - for (const [n, c] of Array.from(community.entries())) { - communityTotal.set(c, (communityTotal.get(c) || 0) + (degree.get(n) || 0)); - } - let bestCommunity = currentCommunity; let bestGain = 0; for (const [targetCommunity, edgeWeight] of Array.from(communityWeights.entries())) { if (targetCommunity === currentCommunity) continue; - // Calculate modularity gain + // Calculate modularity gain. `currentTotal` still includes this + // node's own degree (not yet removed) — the `+ nodeDegree` term + // below backs it out, so `communityTotal` must stay un-patched for + // `node` until after the move decision, matching the pre-existing + // formula this complexity fix leaves unchanged. const currentTotal = communityTotal.get(currentCommunity) || 0; const targetTotal = communityTotal.get(targetCommunity) || 0; const currentEdges = communityWeights.get(currentCommunity) || 0; @@ -745,6 +755,8 @@ function fallbackLouvain( if (bestCommunity !== currentCommunity) { community.set(node, bestCommunity); + communityTotal.set(currentCommunity, (communityTotal.get(currentCommunity) || 0) - nodeDegree); + communityTotal.set(bestCommunity, (communityTotal.get(bestCommunity) || 0) + nodeDegree); improved = true; } } From 1a5c8b834ef35385b63ddb83242d842459958caa Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 10 Oct 2026 06:32:49 +0000 Subject: [PATCH 03/43] dream(performance): #3976 update dream-cycle ledger for 2026-10-10 Co-Authored-By: RuFlo Claude-Session: https://claude.ai/code/session_01JL2GEEWf9ezZo1X1wQ2Ls6 --- docs/dream-cycle/LEDGER.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/dream-cycle/LEDGER.md b/docs/dream-cycle/LEDGER.md index 6ae831521d..90780a138f 100644 --- a/docs/dream-cycle/LEDGER.md +++ b/docs/dream-cycle/LEDGER.md @@ -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) | From 985bdcddacc294ae814ceafd3801147addd454ce Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 10 Oct 2026 06:47:01 +0000 Subject: [PATCH 04/43] dream(performance): #3976 fix CI timeout on the new complexity-growth test CI: "Test Suite (ubuntu-latest)" failed on 1a5c8b83 -- root-caused, fixed. ci-test-ratchet's summary showed an opaque `Error: STACK_TRACE_ERROR` for "scales near-linearly with node count..." Reproduced the exact CI invocation locally (CI=1 node node_modules/vitest/vitest.mjs run ... from repo root, the same command scripts/ci-test-ratchet.mjs spawns, after `npm install` at root) and got the real error: the legacy O(n^2) algorithm's warmup+3 trials at n=1600, for both algorithms at both sizes, exceeded vitest's default 5000ms per-test timeout on this invocation path -- the same failure class PR #3754 (2026-10-05) hit and fixed the same way. Fix: explicit 30000ms timeout on the test, trial count 3->2 to trim real wall-clock cost further. Re-verified against the exact CI invocation: 4/4 tests pass, ~3s total (comfortably inside the new budget). Measured growth ratios in this run are consistent with the range already disclosed in the gist/issue/PR -- no change to the reported evidence, only to the test's own timeout margin. Co-Authored-By: RuFlo Claude-Session: https://claude.ai/code/session_01JL2GEEWf9ezZo1X1wQ2Ls6 --- .../ruvector/graph-analyzer.louvain-complexity.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.louvain-complexity.test.ts b/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.louvain-complexity.test.ts index c7744632a0..e60767050a 100644 --- a/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.louvain-complexity.test.ts +++ b/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.louvain-complexity.test.ts @@ -204,7 +204,7 @@ describe('fallbackLouvain complexity fix', () => { function bestOf(fn: (n: string[], e: Edge[]) => unknown, nodes: string[], edges: Edge[]): number { fn(nodes, edges); // warmup (JIT) let best = Infinity; - for (let t = 0; t < 3; t++) { + for (let t = 0; t < 2; t++) { const start = performance.now(); fn(nodes, edges); const dur = performance.now() - start; @@ -229,5 +229,8 @@ describe('fallbackLouvain complexity fix', () => { expect(legacyGrowth).toBeGreaterThan(20); // legacy is genuinely ~quadratic expect(currentGrowth).toBeLessThan(legacyGrowth / 2); // fixed algorithm is materially better expect(currentLarge).toBeLessThan(legacyLarge); // and strictly faster in absolute terms at n=1600 - }); + }, 30000); // the legacy O(n^2) algorithm at n=1600 (warmup+2 trials, both algorithms, + // both sizes) can run well past vitest's default 5000ms per-test timeout + // on a loaded/shared CI runner — same failure mode independently hit and + // fixed by PR #3754 (2026-10-05). }); From 33d063de4839358180180f7274f4133eeae33db2 Mon Sep 17 00:00:00 2001 From: Devesh Maheshwari <31351093+Devesh-Maheshwari@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:18:15 -0500 Subject: [PATCH 05/43] fix(cli): show registered agents in status agents --- .../cli/__tests__/status-agents.test.ts | 93 +++++++++++++++++++ v3/@claude-flow/cli/src/commands/status.ts | 27 +++--- 2 files changed, 105 insertions(+), 15 deletions(-) create mode 100644 v3/@claude-flow/cli/__tests__/status-agents.test.ts diff --git a/v3/@claude-flow/cli/__tests__/status-agents.test.ts b/v3/@claude-flow/cli/__tests__/status-agents.test.ts new file mode 100644 index 0000000000..dbc4674a53 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/status-agents.test.ts @@ -0,0 +1,93 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { agentTools } from '../src/mcp-tools/agent-tools.js'; +import { callMCPTool, MCPClientError } from '../src/mcp-client.js'; +import { output } from '../src/output.js'; +import { statusCommand } from '../src/commands/status.js'; + +// Keep the real agent_list handler and file stores; bypass unrelated MCP tools. +vi.mock('../src/mcp-client.js', () => ({ + callMCPTool: vi.fn(), + MCPClientError: class MCPClientError extends Error {}, +})); + +const action = statusCommand.subcommands!.find(command => command.name === 'agents')!.action!; +const listAgents = agentTools.find(tool => tool.name === 'agent_list')!; +const agent = (agentId: string, status = 'idle') => ({ + agentId, agentType: 'coder', status, health: 0.85, taskCount: 3, + createdAt: '2026-01-01T00:00:00.000Z', config: {}, +}); + +describe('status agents with the persisted agent registry', () => { + let dir: string; + const run = (format = 'text') => action({ + args: [], flags: { _: [], format }, cwd: dir, interactive: false, + }); + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'ruflo-status-agents-')); + vi.stubEnv('CLAUDE_FLOW_CWD', dir); + mkdirSync(join(dir, '.claude-flow', 'agents'), { recursive: true }); + writeFileSync(join(dir, '.claude-flow', 'agents', 'store.json'), JSON.stringify({ + version: '3.0.0', agents: { + idle: agent('idle-coder'), busy: agent('busy-coder', 'busy'), + ended: agent('ended-coder', 'terminated'), + }, + })); + writeFileSync(join(dir, '.claude-flow', 'agents.json'), JSON.stringify({ + agents: { hive: { ...agent('hive-reviewer'), agentType: 'reviewer' } }, + })); + vi.mocked(callMCPTool).mockImplementation(async (name, input) => { + if (name !== 'agent_list') throw new Error(`Unexpected tool: ${name}`); + return listAgents.handler(input ?? {}); + }); + vi.spyOn(output, 'writeln').mockImplementation(() => {}); + vi.spyOn(output, 'printTable').mockImplementation(() => {}); + vi.spyOn(output, 'printJson').mockImplementation(() => {}); + vi.spyOn(output, 'printInfo').mockImplementation(() => {}); + vi.spyOn(output, 'printError').mockImplementation(() => {}); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.resetAllMocks(); + vi.unstubAllEnvs(); + rmSync(dir, { recursive: true, force: true }); + }); + + it('lists idle, busy and hive agents in JSON, excluding terminated agents', async () => { + const expected = await listAgents.handler({}); + expect(expected).toMatchObject({ total: 3 }); + expect(await run('json')).toEqual({ success: true, data: expected }); + expect(output.printJson).toHaveBeenCalledWith(expected); + }); + + it('renders IDs, types and recorded counts without requiring unavailable metrics', async () => { + expect(await run()).toMatchObject({ success: true }); + expect(output.printTable).toHaveBeenCalledOnce(); + const table = vi.mocked(output.printTable).mock.calls[0][0]; + expect(table.data).toEqual(expect.arrayContaining([ + expect.objectContaining({ id: 'idle-coder', type: 'coder', tasks: 3, health: 0.85 }), + expect.objectContaining({ id: 'busy-coder', type: 'coder', status: expect.stringContaining('busy') }), + expect.objectContaining({ id: 'hive-reviewer', type: 'reviewer' }), + ])); + expect(table.data).toHaveLength(3); + expect(output.printError).not.toHaveBeenCalled(); + }); + + it('reports an empty registry without a table', async () => { + rmSync(join(dir, '.claude-flow'), { recursive: true }); + expect(await run()).toMatchObject({ success: true, data: { agents: [], total: 0 } }); + expect(output.printInfo).toHaveBeenCalledWith('No agents registered'); + expect(output.printTable).not.toHaveBeenCalled(); + }); + + it('reports tool failures instead of claiming an empty registry', async () => { + vi.mocked(callMCPTool).mockRejectedValueOnce(new MCPClientError('unavailable', 'agent_list')); + expect(await run()).toEqual({ success: false, exitCode: 1 }); + expect(output.printError).toHaveBeenCalledWith('Failed to get agent status: unavailable'); + expect(output.printInfo).not.toHaveBeenCalled(); + }); +}); diff --git a/v3/@claude-flow/cli/src/commands/status.ts b/v3/@claude-flow/cli/src/commands/status.ts index 586818200d..6918d989a7 100644 --- a/v3/@claude-flow/cli/src/commands/status.ts +++ b/v3/@claude-flow/cli/src/commands/status.ts @@ -521,14 +521,13 @@ const agentsCommand: Command = { try { const result = await callMCPTool<{ agents: Array<{ - id: string; - type: string; + agentId: string; + agentType: string; status: string; - task?: string; - uptime: number; - metrics: { tasksCompleted: number; successRate: number }; + health: number; + taskCount: number; }>; - }>('agent_list', { includeMetrics: true, status: 'all' }); + }>('agent_list', {}); if (ctx.flags.format === 'json') { output.printJson(result); @@ -540,7 +539,7 @@ const agentsCommand: Command = { output.writeln(); if (result.agents.length === 0) { - output.printInfo('No agents running'); + output.printInfo('No agents registered'); return { success: true, data: result }; } @@ -549,17 +548,15 @@ const agentsCommand: Command = { { key: 'id', header: 'ID', width: 20 }, { key: 'type', header: 'Type', width: 12 }, { key: 'status', header: 'Status', width: 10 }, - { key: 'task', header: 'Current Task', width: 25 }, - { key: 'uptime', header: 'Uptime', width: 12 }, - { key: 'success', header: 'Success', width: 8 } + { key: 'tasks', header: 'Tasks', width: 8 }, + { key: 'health', header: 'Health', width: 8 } ], data: result.agents.map(a => ({ - id: a.id, - type: a.type, + id: a.agentId, + type: a.agentType, status: formatHealth(a.status), - task: a.task || '-', - uptime: formatUptime(a.uptime), - success: `${(a.metrics.successRate * 100).toFixed(0)}%` + tasks: a.taskCount, + health: a.health })) }); From b9086fc471ef831d483e0faa0b0bf0e83a61f8fe Mon Sep 17 00:00:00 2001 From: Dragan Spiridonov Date: Fri, 9 Oct 2026 18:26:03 +0200 Subject: [PATCH 06/43] fix(console): mission create retries only real lock timeouts, undoes and reads back on abort, reports run outcomes in lastResult On a project whose policy state is large, every `ruflo mcp exec` waits on the policy state lock and some calls fail with policy-state-lock-timeout (#3164, #3892). Mission create made 15 sequential task_create calls; one transient failure aborted the whole mission, cleanup cancels were fire-and-forget (orphan pending tasks while the page said they were cancelled), the CLI mission record was left planned, and the reason was never shown. The outcome of a run that reports for itself (mission create, ADR writes) never reached console_state.lastResult. resultOf also read the `Parameters:` object the CLI prints before any `Result:` line as the answer. - data/mcp-run.ts: read only after the CLI's own `Result:` line (string-aware bracket matching); the failure reason from data/failure.ts. Transient only on exactly policy-state-lock-timeout, the caller's own structured time limit, or a non-zero exit with stdout and stderr both empty. Any answer, any other error line (a denial mentioning a timeout, command not found) and any host rejection are final. - mission-create.ts: retries after 1, 2, 4 s. task_create has no request id: after each wait, and once more after the last failed try (a lost answer), the store is read for exactly this step's task (description and both tags carry the new mission id; a 5 min skew window); one is used, several stop the chain, an unreadable store stops a retry. Strict time: no call, wait or read starts after its deadline (3 min, cleanup 2 min more), each is cut to the time left, and a call the host never answers is let go then. One create at a time per console; unique request ids. On abort: cancel every open task of the mission in the store (not only acknowledged ones), cancel the mission record (again at the revision a conflict names; also when mission_plan is refused), then READ BACK the store and the mission observation and report what they show, and what was left for lack of time. - ActionSpec.run may answer a RunReport; the runner keeps it as the console outcome when the run ends, unless the outcome slot was replaced meanwhile (another action reported; then it goes to the Events feed). The verdict-exit judgement in runner.ts is unchanged. Mission create and ADR init/propose/status writes answer theirs. - tests: real `ruflo mcp exec` transcripts (ruflo 3.56.1) as fixtures. Co-Authored-By: Ruflo & AQE Claude-Session: https://claude.ai/code/session_01CGoza3gyxBjpaiMPhGHcHs --- plugins/ruflo-console/hooks/actions.ts | 10 +- plugins/ruflo-console/hooks/adr.ts | 29 +- plugins/ruflo-console/hooks/data/mcp-run.ts | 81 +++++ plugins/ruflo-console/hooks/mission-create.ts | 329 ++++++++++++++++++ plugins/ruflo-console/hooks/mission-specs.ts | 145 +------- plugins/ruflo-console/hooks/mission-text.ts | 2 +- plugins/ruflo-console/hooks/mission-types.ts | 3 +- plugins/ruflo-console/hooks/runner.ts | 12 +- .../hooks/views/mission-control.ts | 2 +- .../tests/fixtures/mcp-exec/m-cancel-ok.code | 1 + .../tests/fixtures/mcp-exec/m-cancel-ok.err | 1 + .../tests/fixtures/mcp-exec/m-cancel-ok.out | 15 + .../tests/fixtures/mcp-exec/m-cancel.code | 1 + .../tests/fixtures/mcp-exec/m-cancel.err | 1 + .../tests/fixtures/mcp-exec/m-cancel.out | 11 + .../tests/fixtures/mcp-exec/m-create.code | 1 + .../tests/fixtures/mcp-exec/m-create.err | 1 + .../tests/fixtures/mcp-exec/m-create.out | 14 + .../tests/fixtures/mcp-exec/m-plan-ok.code | 1 + .../tests/fixtures/mcp-exec/m-plan-ok.err | 1 + .../tests/fixtures/mcp-exec/m-plan-ok.out | 16 + .../tests/fixtures/mcp-exec/m-plan.code | 1 + .../tests/fixtures/mcp-exec/m-plan.err | 1 + .../tests/fixtures/mcp-exec/m-plan.out | 10 + .../fixtures/mcp-exec/t-cancel-missing.code | 1 + .../fixtures/mcp-exec/t-cancel-missing.err | 1 + .../fixtures/mcp-exec/t-cancel-missing.out | 10 + .../tests/fixtures/mcp-exec/t-cancel.code | 1 + .../tests/fixtures/mcp-exec/t-cancel.err | 1 + .../tests/fixtures/mcp-exec/t-cancel.out | 11 + .../tests/fixtures/mcp-exec/t-lock.code | 1 + .../tests/fixtures/mcp-exec/t-lock.err | 2 + .../tests/fixtures/mcp-exec/t-lock.out | 1 + .../tests/fixtures/mcp-exec/t-ok.code | 1 + .../tests/fixtures/mcp-exec/t-ok.err | 1 + .../tests/fixtures/mcp-exec/t-ok.out | 15 + .../tests/fixtures/mission-cli-real.ts | 133 +++++++ .../tests/mission-create-retry.spec.ts | 277 +++++++++++++++ .../tests/mission-create-time.spec.ts | 248 +++++++++++++ 39 files changed, 1244 insertions(+), 149 deletions(-) create mode 100644 plugins/ruflo-console/hooks/data/mcp-run.ts create mode 100644 plugins/ruflo-console/hooks/mission-create.ts create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.code create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.err create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.out create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.code create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.err create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.out create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.code create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.err create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.out create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.code create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.err create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.out create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.code create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.err create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.out create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.code create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.err create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.out create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.code create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.err create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.out create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.code create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.err create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.out create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.code create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.err create mode 100644 plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.out create mode 100644 plugins/ruflo-console/tests/fixtures/mission-cli-real.ts create mode 100644 plugins/ruflo-console/tests/mission-create-retry.spec.ts create mode 100644 plugins/ruflo-console/tests/mission-create-time.spec.ts diff --git a/plugins/ruflo-console/hooks/actions.ts b/plugins/ruflo-console/hooks/actions.ts index 3a741dde93..9e81cda6e4 100644 --- a/plugins/ruflo-console/hooks/actions.ts +++ b/plugins/ruflo-console/hooks/actions.ts @@ -20,8 +20,11 @@ export type ActionSpec = { verifyLocal?: (host: Pick) => Promise /** 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 + /** + * 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 /** 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 `. */ @@ -52,6 +55,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) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as const const SAFE_WORD = /^[A-Za-z0-9_.-]{1,40}$/ diff --git a/plugins/ruflo-console/hooks/adr.ts b/plugins/ruflo-console/hooks/adr.ts index 0fea6d84d5..8741da84a2 100644 --- a/plugins/ruflo-console/hooks/adr.ts +++ b/plugins/ruflo-console/hooks/adr.ts @@ -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, 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, text: string): void { const line = plain(text, 118) @@ -237,6 +251,8 @@ export function initSpec(state: State, host: Pick { 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 -p `, 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: `, and on a failure `[ERROR] Tool execution failed: Failed to execute MCP tool '': ` + * 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 | 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 | null; ok: boolean; transient: boolean; reason: string } + +/** The CLI's cause, its two wrappers dropped ("Tool execution failed: Failed to execute MCP tool 'x': "). */ +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) => 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 } +} diff --git a/plugins/ruflo-console/hooks/mission-create.ts b/plugins/ruflo-console/hooks/mission-create.ts new file mode 100644 index 0000000000..4aeaf6be67 --- /dev/null +++ b/plugins/ruflo-console/hooks/mission-create.ts @@ -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() + +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 => + 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(work: Promise, ms: number, late: T): Promise { + let timer: ReturnType | undefined + + return Promise.race([work, new Promise(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 { + 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 => { + 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 \` (${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 { + 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) => boolean, until: number): Promise => { + const ms = Math.min(CALL_MS, left(until)) + + if (ms <= 0) return outOfTime + + const run = await within(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) => boolean, until: number, beforeRetry?: () => Promise): Promise => { + 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) => 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 { + 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'}` diff --git a/plugins/ruflo-console/hooks/mission-specs.ts b/plugins/ruflo-console/hooks/mission-specs.ts index 62ea13a1f4..5cd0ad2cd6 100644 --- a/plugins/ruflo-console/hooks/mission-specs.ts +++ b/plugins/ruflo-console/hooks/mission-specs.ts @@ -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 { 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 | 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 - } 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 \` (${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 { - { - 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. */ diff --git a/plugins/ruflo-console/hooks/mission-text.ts b/plugins/ruflo-console/hooks/mission-text.ts index 884adb65ff..f543c0aa17 100644 --- a/plugins/ruflo-console/hooks/mission-text.ts +++ b/plugins/ruflo-console/hooks/mission-text.ts @@ -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 ' : 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') } diff --git a/plugins/ruflo-console/hooks/mission-types.ts b/plugins/ruflo-console/hooks/mission-types.ts index 458d68ca82..b12bef3c09 100644 --- a/plugins/ruflo-console/hooks/mission-types.ts +++ b/plugins/ruflo-console/hooks/mission-types.ts @@ -45,7 +45,8 @@ 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 } export type MissionActions = { diff --git a/plugins/ruflo-console/hooks/runner.ts b/plugins/ruflo-console/hooks/runner.ts index c7a4582bd0..43720c0372 100644 --- a/plugins/ruflo-console/hooks/runner.ts +++ b/plugins/ruflo-console/hooks/runner.ts @@ -58,9 +58,19 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner async function execute(spec: ActionSpec): Promise { // 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 diff --git a/plugins/ruflo-console/hooks/views/mission-control.ts b/plugins/ruflo-console/hooks/views/mission-control.ts index a1c4d82621..38f618bf10 100644 --- a/plugins/ruflo-console/hooks/views/mission-control.ts +++ b/plugins/ruflo-console/hooks/views/mission-control.ts @@ -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')) diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.code new file mode 100644 index 0000000000..573541ac97 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.code @@ -0,0 +1 @@ +0 diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.err new file mode 100644 index 0000000000..896eff45e4 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.err @@ -0,0 +1 @@ +[INFO] Executing tool: mission_request_action diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.out new file mode 100644 index 0000000000..82dce41532 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel-ok.out @@ -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 + } +} diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.code new file mode 100644 index 0000000000..573541ac97 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.code @@ -0,0 +1 @@ +0 diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.err new file mode 100644 index 0000000000..896eff45e4 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.err @@ -0,0 +1 @@ +[INFO] Executing tool: mission_request_action diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.out new file mode 100644 index 0000000000..22d05aab5d --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-cancel.out @@ -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 +} diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.code new file mode 100644 index 0000000000..573541ac97 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.code @@ -0,0 +1 @@ +0 diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.err new file mode 100644 index 0000000000..cf9fbd0d7a --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.err @@ -0,0 +1 @@ +[INFO] Executing tool: mission_create diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.out new file mode 100644 index 0000000000..98b95d76e1 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-create.out @@ -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 + } +} diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.code new file mode 100644 index 0000000000..573541ac97 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.code @@ -0,0 +1 @@ +0 diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.err new file mode 100644 index 0000000000..54d710b2c0 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.err @@ -0,0 +1 @@ +[INFO] Executing tool: mission_plan diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.out new file mode 100644 index 0000000000..459cd05213 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan-ok.out @@ -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" + } +} diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.code new file mode 100644 index 0000000000..573541ac97 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.code @@ -0,0 +1 @@ +0 diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.err new file mode 100644 index 0000000000..54d710b2c0 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.err @@ -0,0 +1 @@ +[INFO] Executing tool: mission_plan diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.out new file mode 100644 index 0000000000..4b14dbc1b5 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/m-plan.out @@ -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" +} diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.code new file mode 100644 index 0000000000..573541ac97 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.code @@ -0,0 +1 @@ +0 diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.err new file mode 100644 index 0000000000..c777688a6f --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.err @@ -0,0 +1 @@ +[INFO] Executing tool: task_cancel diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.out new file mode 100644 index 0000000000..8617cb9667 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel-missing.out @@ -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" +} diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.code new file mode 100644 index 0000000000..573541ac97 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.code @@ -0,0 +1 @@ +0 diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.err new file mode 100644 index 0000000000..c777688a6f --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.err @@ -0,0 +1 @@ +[INFO] Executing tool: task_cancel diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.out new file mode 100644 index 0000000000..fd632c0019 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-cancel.out @@ -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" +} diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.code new file mode 100644 index 0000000000..d00491fd7e --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.code @@ -0,0 +1 @@ +1 diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.err new file mode 100644 index 0000000000..537c8fa8c4 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.err @@ -0,0 +1,2 @@ +[INFO] Executing tool: task_create +[ERROR] Tool execution failed: Failed to execute MCP tool 'task_create': policy-state-lock-timeout diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.out new file mode 100644 index 0000000000..03627118d5 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-lock.out @@ -0,0 +1 @@ + Parameters: {"type":"test","description":"x [ok}]"} diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.code b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.code new file mode 100644 index 0000000000..573541ac97 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.code @@ -0,0 +1 @@ +0 diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.err b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.err new file mode 100644 index 0000000000..7053616997 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.err @@ -0,0 +1 @@ +[INFO] Executing tool: task_create diff --git a/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.out b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.out new file mode 100644 index 0000000000..650ed4758b --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mcp-exec/t-ok.out @@ -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": [] +} diff --git a/plugins/ruflo-console/tests/fixtures/mission-cli-real.ts b/plugins/ruflo-console/tests/fixtures/mission-cli-real.ts new file mode 100644 index 0000000000..23b2cf5460 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/mission-cli-real.ts @@ -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) => typeof result.taskId === 'string' + +export type Store = Record +export type World = { runs: { tool: string; params: Record }[]; waits: number[]; store: Store; mission: string; onWait?: () => void; unreadable?: boolean } +export type Special = (tool: string, params: Record, nth: number, world: World) => Run | Error | Promise | 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() + const make = (params: Record, 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 + 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, 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?.() diff --git a/plugins/ruflo-console/tests/mission-create-retry.spec.ts b/plugins/ruflo-console/tests/mission-create-retry.spec.ts new file mode 100644 index 0000000000..a3d050e041 --- /dev/null +++ b/plugins/ruflo-console/tests/mission-create-retry.spec.ts @@ -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-:; receipt=`) 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 | 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(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`) + }) +}) + diff --git a/plugins/ruflo-console/tests/mission-create-time.spec.ts b/plugins/ruflo-console/tests/mission-create-time.spec.ts new file mode 100644 index 0000000000..cbf7032ba7 --- /dev/null +++ b/plugins/ruflo-console/tests/mission-create-time.spec.ts @@ -0,0 +1,248 @@ +/** + * Mission create under lost answers and strict time, what counts as transient, and how the outcome of a long run (and of an ADR page write) + * reaches console_state's lastResult. The CLI output is the real transcripts' (tests/fixtures/mission-cli-real.ts). + * npx vitest run plugins/ruflo-console/tests/mission-create-time.spec.ts + */ +import { existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' + +import { afterEach, describe, expect, it, vi } from 'vitest' + +import type { ActionSpec } from '../hooks/actions' +import { adrOf, proposeSpec } from '../hooks/adr' +import type { Host } from '../hooks/host' +import { CALL_MS, CLEANUP_BUDGET_MS, CREATE_DEADLINE_MS, isCreating, RETRY_WAITS_MS } from '../hooks/mission-create' +import { activeMission, createSpec, mcOf } from '../hooks/mission-control' +import { callTool } from '../hooks/model-tools' +import { createRunner } from '../hooks/runner' +import type { State } from '../hooks/state' +import { cleanAfter, loaded, TODAY } from './adr-helpers' +import { setup } from './fixtures/control-setup' +import { creates, fresh, hostOf, ID, isStep, locked, LOST, planned, run } from './fixtures/mission-cli-real' +import { useNativeWriteFlavor } from './fixtures/write-flavor' + +cleanAfter() +afterEach(() => vi.useRealTimers()) + +describe('lost answers, strict time, and what counts as transient', () => { + it('the last try writes and its answer is lost: a final store read finds it, so the mission is created without a duplicate', async () => { + const { state, steps } = planned() + const world = fresh() + const host = hostOf(world, (tool, params, nth, w) => { + if (tool !== 'task_create' || !isStep(params, steps[3])) return undefined + if (nth <= RETRY_WAITS_MS.length) return locked(params, tool) + // The last try writes the task, then its answer is lost. + w.store['task-lost'] = { taskId: 'task-lost', 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[3])).toHaveLength(1 + RETRY_WAITS_MS.length) + expect(mcOf(state).last?.ok).toBe(true) + expect(activeMission(state)?.tasks.find(task => task.id === steps[3])?.rufloTaskId).toBe('task-lost') + expect(Object.keys(world.store)).toHaveLength(15) + }) + + it('cleanup cancels every open task of the mission in the store, not only the acknowledged ones', 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) + + const cancelled = world.runs.filter(entry => entry.tool === 'task_cancel').map(entry => entry.params.taskId) + + expect(cancelled).toEqual(expect.arrayContaining(['task-1', 'task-a', 'task-b'])) + expect(mcOf(state).last?.lines?.[1]).toBe('the store shows 3 of the 3 tasks of this mission cancelled') + expect(Object.values(world.store).every(task => task.status === 'cancelled')).toBe(true) + }) + + it('a store task stamped before the console started (clock skew) is still this step\'s late success: no duplicate', async () => { + const { state, steps } = planned() + const world = fresh() + const skewed = new Date(Date.now() - 2_000).toISOString() + const host = hostOf(world, (tool, params, nth, w) => { + if (tool !== 'task_create' || !isStep(params, steps[0]) || nth !== 1) return undefined + w.store['task-skew'] = { taskId: 'task-skew', type: 'feature', description: String(params.description), status: 'pending', tags: params.tags as string[], assignedTo: [], createdAt: skewed } + + return LOST + }) + + await run(state, host) + + expect(creates(world, steps[0])).toHaveLength(1) + expect(activeMission(state)?.tasks[0]?.rufloTaskId).toBe('task-skew') + expect(Object.keys(world.store)).toHaveLength(15) + }) + + it('a CLI that is not there is not retried', async () => { + const { state } = planned() + const world = fresh() + const host = hostOf(world, () => ({ exitCode: 127, stdout: '', stderr: 'zsh: command not found: ruflo\n' })) + + await run(state, host) + + expect(world.runs).toHaveLength(1) + expect(world.waits).toEqual([]) + expect(mcOf(state).last?.detail).toContain('command not found') + }) + + it('a host rejection that mentions a timeout (an approval that timed out) is not retried', async () => { + const { state } = planned() + const world = fresh() + const host = hostOf(world, () => new Error('permission denied: timed out waiting for approval')) + + await run(state, host) + + expect(world.runs).toHaveLength(1) + expect(world.waits).toEqual([]) + }) + + it('no call starts after its deadline: cleanup stops at its own and names what it left', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + + const { state } = planned() + const world = fresh() + const t0 = Date.now() + const starts: { tool: string; atMs: number }[] = [] + // Each task_create takes 40 s of the clock, each task_cancel 50 s. + const host = hostOf(world, tool => { + starts.push({ tool, atMs: Date.now() - t0 }) + if (tool === 'task_create') vi.setSystemTime(Date.now() + 40_000) + if (tool === 'task_cancel') vi.setSystemTime(Date.now() + 50_000) + + return undefined + }) + + await run(state, host) + + const cleanupEnd = CREATE_DEADLINE_MS + CLEANUP_BUDGET_MS + + expect(starts.filter(entry => entry.tool === 'task_create').every(entry => entry.atMs < CREATE_DEADLINE_MS)).toBe(true) + expect(starts.every(entry => entry.atMs < cleanupEnd)).toBe(true) + expect(starts.filter(entry => entry.tool === 'task_cancel')).toHaveLength(2) + expect(starts.some(entry => entry.tool === 'mission_request_action')).toBe(false) + expect(mcOf(state).last?.lines?.join('\n')).toContain('out of cleanup time: not asked to cancel task-3, task-4, task-5') + }) + + it('a call the host never answers is let go at the time left: the create ends, the guard is released, the report says it may still finish', async () => { + vi.useFakeTimers() + + const { state, steps } = planned() + const world = fresh() + const host = hostOf(world, (tool, params) => (tool === 'task_create' && isStep(params, steps[0]) ? new Promise(() => undefined) : undefined)) + let settled = false + const running = run(state, host).then(() => (settled = true)) + + for (let i = 0; i < 40 && !settled; i++) await vi.advanceTimersByTimeAsync(CALL_MS) + await running + + expect(settled).toBe(true) + expect(isCreating(state)).toBe(false) + expect(mcOf(state).last?.ok).toBe(false) + expect(mcOf(state).last?.lines?.[0]).toContain('the CLI process may still finish') + expect(world.runs.filter(entry => entry.tool === 'mission_request_action')).toHaveLength(1) + }) +}) + +/** Asks for `spec` through the real runner, says yes, waits for its own run, then reads lastResult as console_state hands it to Claude. */ +async function lastResultAfter(state: State, host: Host, spec: ActionSpec, meanwhile?: () => void): Promise<{ label: string; ok: boolean; detail: string; lines: string[] } | null> { + const runner = createRunner(state, host, { freshRead: async () => undefined, setView: () => undefined, drill: () => undefined, command: () => undefined }) + const { deps } = setup('read') + + // An older, unrelated result sits in the slot, as it did live. + state.outcome = { label: 'an older read', ok: true, verified: 'n/a', detail: 'unrelated', atMs: Date.now() - 1_000 } + runner.ask(spec, '') + await runner.confirm() + meanwhile?.() + await runner.finished() + // The stub snapshot is not a full one: the screen text console_state also builds reads the disk as not read yet. + state.snapshot = null + + const text = await callTool('console_state', {}, { ...deps, state }) + + if (!text.startsWith('{')) throw new Error(text) + + return (JSON.parse(text) as { lastResult: { label: string; ok: boolean; detail: string; lines: string[] } | null }).lastResult +} + +describe('the outcome of a long or page action reaches lastResult', () => { + it('mission create: an abort, with the CLI reason and the read-back', async () => { + const { state, steps } = planned() + const world = fresh() + const host = hostOf(world, (tool, params) => (tool === 'task_create' && isStep(params, steps[3]) ? locked(params, tool) : undefined)) + const result = await lastResultAfter(state, host, createSpec(state, host, () => undefined) as ActionSpec) + + expect(result?.ok).toBe(false) + expect(result?.label).toBe(`mission not created: task ${steps[3]} could not be made`) + expect(result?.lines.join('\n')).toContain('policy-state-lock-timeout') + expect(result?.lines.join('\n')).toContain('the store shows 3 of the 3 tasks of this mission cancelled') + }) + + it('mission create: a success', async () => { + const { state } = planned() + const host = hostOf(fresh()) + const result = await lastResultAfter(state, host, createSpec(state, host, () => undefined) as ActionSpec) + + expect(result).toMatchObject({ ok: true, label: `mission ${ID} planned` }) + }) + + it('another action that reports in the same millisecond the run started is not overwritten by the run\'s late result', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + + const { state } = planned() + const host = hostOf(fresh()) + const result = await lastResultAfter(state, host, createSpec(state, host, () => undefined) as ActionSpec, () => { + state.outcome = { label: 'another action', ok: true, verified: 'n/a', detail: 'same millisecond', atMs: Date.now() } + }) + + expect(result?.label).toBe('another action') + }) + + it('a late completion does not overwrite a newer outcome of another action; it goes to the Events feed', async () => { + const { state } = planned() + const host = hostOf(fresh()) + const result = await lastResultAfter(state, host, createSpec(state, host, () => undefined) as ActionSpec, () => { + state.outcome = { label: 'another action', ok: true, verified: 'n/a', detail: 'newer', atMs: Date.now() + 5 } + }) + + expect(result?.label).toBe('another action') + expect(state.events.some(event => event.text.includes(`mission ${ID} planned`) && event.text.includes('finished after a newer result'))).toBe(true) + }) + +}) + +describe('the outcome of an ADR page write reaches lastResult', () => { + // A real disk: the write argv is the one this machine's tools take, found the way the console finds it at session start. + useNativeWriteFlavor() + + it('adr-propose on a real disk: ✓, and the file exists', async () => { + const { root, state, world } = await loaded('nygard') + const spec = proposeSpec(state, world.host as never, 'Cache reads', TODAY) as ActionSpec + const target = /create (\S+)/.exec(spec.shows ?? '')?.[1] as string + const result = await lastResultAfter(state, world.host as never, spec) + + expect(result).toMatchObject({ ok: true, label: 'propose ADR 4', detail: `created ${target}` }) + expect(existsSync(join(root, target))).toBe(true) + expect(readFileSync(join(root, target), 'utf8')).toContain('Cache reads') + }) + + it('adr-propose: the write fails', async () => { + const { state, world } = await loaded('nygard') + // The write command fails, as it did live: the page said so, and console_run said "Ran: propose ADR 4". + const host = { ...world.host, run: async () => ({ exitCode: 1, stdout: '', stderr: 'install: illegal option -- D' }) } + const spec = proposeSpec(state, host as never, 'Cache reads', TODAY) as ActionSpec + const result = await lastResultAfter(state, host as never, spec) + + expect(adrOf(state).last?.ok).toBe(false) + expect(result).toMatchObject({ ok: false, label: 'propose ADR 4' }) + expect(result?.detail).toContain('the write failed (exit 1: install: illegal option -- D)') + }) +}) From b35caec0f3fe5a6931a2dceacf6a376094c26388 Mon Sep 17 00:00:00 2001 From: r Date: Sat, 10 Oct 2026 10:38:02 -0400 Subject: [PATCH 07/43] chore(console): 0.42.1 version and changelog for #3945 Co-Authored-By: RuFlo --- plugins/ruflo-console/.claude-plugin/plugin.json | 2 +- plugins/ruflo-console/CHANGELOG.md | 4 ++++ plugins/ruflo-console/hooks/version.ts | 2 +- plugins/ruflo-console/scripts/smoke.sh | 4 ++-- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.json index 11bd3c35b7..1e777af9b3 100644 --- a/plugins/ruflo-console/.claude-plugin/plugin.json +++ b/plugins/ruflo-console/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "ruflo-console", "description": "ruflo's cockpit inside Claude Code and the one /ruflo command for every ruflo mod (function hooks, early access). Views: overview with health alerts, swarm topology graph, claims flow with TTL rings, federation map, plugin health matrix, learning curve and pipeline, MetaHarness radar and audit trend, memory, cost gauge, agent timeline, approvals queue, event stream, a main menu, an x.ruv.io federation board, an AI terminal (codex, claude or both in remembered sessions, streamed), Skills (npx skills), a Hive-Mind view, a MetaHarness lab, agent drill-down; a command palette for confirm-gated actions through the ruflo CLI; a band above the prompt. Reads ruflo's files and the CLI's local JSON; anything not measured reads n/a. The one network call it makes by itself is a daily read of the published plugin.json at github.com/ruvnet/ruflo to offer an update (Settings → Updates: ask, auto, or off); it installs only through Claude Code's own claude plugin update, and never a new major version without asking.", - "version": "0.42.0", + "version": "0.42.1", "author": { "name": "ruvnet", "url": "https://github.com/ruvnet" diff --git a/plugins/ruflo-console/CHANGELOG.md b/plugins/ruflo-console/CHANGELOG.md index 8a560fb726..641bee59f3 100644 --- a/plugins/ruflo-console/CHANGELOG.md +++ b/plugins/ruflo-console/CHANGELOG.md @@ -2,6 +2,10 @@ Newest first. One `## — ` 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.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 diff --git a/plugins/ruflo-console/hooks/version.ts b/plugins/ruflo-console/hooks/version.ts index 9f04d48064..ce84185793 100644 --- a/plugins/ruflo-console/hooks/version.ts +++ b/plugins/ruflo-console/hooks/version.ts @@ -2,4 +2,4 @@ * The console's version, shown on the header so a person can tell which build is running. Kept equal to the plugin's manifest * (`.claude-plugin/plugin.json`); tests/version.spec.ts fails if the two drift. */ -export const CONSOLE_VERSION = '0.42.0' +export const CONSOLE_VERSION = '0.42.1' diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.sh index bab2ab7bfa..0856ce3382 100755 --- a/plugins/ruflo-console/scripts/smoke.sh +++ b/plugins/ruflo-console/scripts/smoke.sh @@ -11,9 +11,9 @@ step() { printf "→ %s ... " "$1"; } ok() { printf "PASS\n"; PASS=$((PASS+1)); } bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); } -step "1. plugin.json declares ruflo-console 0.42.0" +step "1. plugin.json declares ruflo-console 0.42.1" 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.1"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version" step "2. hooks.json names exactly one module and no classic hook commands" grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \ From 3c21c3ad1b52e4173f84231a6bf9d7711505ce91 Mon Sep 17 00:00:00 2001 From: r Date: Sat, 10 Oct 2026 10:42:10 -0400 Subject: [PATCH 08/43] test(cli): differential test for fallbackLouvain vs the pre-fix rebuild Adds 1800 seeded random graphs (unit, small-integer and fractional weights, disconnected, self-loops, parallel edges, unknown endpoints) asserting exact equality with the frozen pre-fix implementation. Mutation-checked: dropping the subtract-from-source update fails all three groups. Co-Authored-By: RuFlo --- .../graph-analyzer.louvain-complexity.test.ts | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.louvain-complexity.test.ts b/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.louvain-complexity.test.ts index e60767050a..1ab2dc31e2 100644 --- a/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.louvain-complexity.test.ts +++ b/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.louvain-complexity.test.ts @@ -234,3 +234,47 @@ describe('fallbackLouvain complexity fix', () => { // on a loaded/shared CI runner — same failure mode independently hit and // fixed by PR #3754 (2026-10-05). }); + +/** + * Differential test: the incremental `communityTotal` must be observationally + * identical to the frozen pre-fix rebuild on arbitrary graphs, not just the two + * clustered fixtures above. Seeded (no Math.random) so failures reproduce. + * Covers unit, small-integer (the shipped re-export weight is 2) and + * fractional weights, disconnected graphs, self-loops, parallel/duplicate + * edges, and edges naming nodes that are not in the node list (ignored). + */ +describe('fallbackLouvain differential vs the pre-fix algorithm', () => { + type Kind = 'unit' | 'int' | 'fractional'; + + function randomGraph(seed: number, kind: Kind): { nodes: string[]; edges: Edge[] } { + const r = makeRng(seed); + const n = Math.floor(r() * 60); + const nodes = Array.from({ length: n }, (_, i) => `n${i}`); + const density = [0.02, 0.08, 0.3][seed % 3]; // sparse/disconnected -> dense + const edges: Edge[] = []; + for (let i = 0; i < n; i++) { + for (let j = i; j < n; j++) { + if (i === j && r() > 0.1) continue; // occasional self-loop + if (r() >= density) continue; + const w = kind === 'unit' ? 1 : kind === 'int' ? 1 + Math.floor(r() * 3) : r() * 5 + 0.01; + edges.push([nodes[i], nodes[j], w]); + if (r() < 0.1) edges.push([nodes[j], nodes[i], w]); // parallel edge + } + } + if (n > 2) edges.push(['not-a-node', nodes[0], 1]); + return { nodes, edges }; + } + + it.each(['unit', 'int', 'fractional'] as Kind[])('matches the pre-fix output exactly on 600 random %s-weight graphs', kind => { + let nonTrivial = 0; + for (let seed = 0; seed < 600; seed++) { + const { nodes, edges } = randomGraph(seed * 7919 + kind.length, kind); + const current = fallbackLouvain(nodes, edges); + // Same communities, same member order, same ids and same modularity (not just a sorted/rounded view). + expect(current, `seed ${seed}`).toEqual(legacyFallbackLouvain(nodes, edges)); + if (current.communities.length < nodes.length) nonTrivial++; + } + // Guard against a generator that only produces all-singleton results. + expect(nonTrivial).toBeGreaterThan(300); + }); +}); From 4c95a6a1b60505dd8e8e9588a4aaa4558eeebbe4 Mon Sep 17 00:00:00 2001 From: Dragan Spiridonov Date: Fri, 9 Oct 2026 20:22:02 +0200 Subject: [PATCH 09/43] fix(cli,plugins): resolve executed optional modules from the tool's own install The CLI, two MCP tools and two plugin scripts imported or ran code found relative to the cwd, which is the opened project: - doctor (metaharness check), `metaharness` command and metaharness MCP tools: plugins/ruflo-metaharness/scripts under the cwd; - testgen MCP tools: plugins/ruflo-testgen/scripts under the cwd, reached on every published install because that plugin is not bundled; - init: /node_modules/@claude-flow/codex; - embeddings: /node_modules, /../node_modules and a fixed /workspaces/claude-flow path for agentic-flow; - ruflo-ruos ledger: the CLI's mcp-client resolved from the cwd; - cost-tracker compact.mjs: @claude-flow/integration resolved from the cwd. Each now resolves from the tool's own install (module location / createRequire(import.meta.url)), plus the user's marketplace checkout for the plugin scripts. The project remains the data/scoring target. Test: optional-module-resolution-trust.test.ts (10 cases, all fail on main). --- .../ruflo-cost-tracker/scripts/compact.mjs | 15 ++- plugins/ruflo-ruos/scripts/lib/ledger.mjs | 6 +- .../optional-module-resolution-trust.test.ts | 109 ++++++++++++++++++ v3/@claude-flow/cli/src/commands/doctor.ts | 16 +-- v3/@claude-flow/cli/src/commands/init.ts | 13 +-- .../cli/src/commands/metaharness.ts | 11 +- .../cli/src/mcp-tools/metaharness-tools.ts | 7 +- .../cli/src/mcp-tools/testgen-tools.ts | 8 +- .../embeddings/src/embedding-service.ts | 26 ++--- 9 files changed, 149 insertions(+), 62 deletions(-) create mode 100644 v3/@claude-flow/cli/__tests__/optional-module-resolution-trust.test.ts diff --git a/plugins/ruflo-cost-tracker/scripts/compact.mjs b/plugins/ruflo-cost-tracker/scripts/compact.mjs index ea9da3cef6..03a741daa4 100755 --- a/plugins/ruflo-cost-tracker/scripts/compact.mjs +++ b/plugins/ruflo-cost-tracker/scripts/compact.mjs @@ -4,11 +4,10 @@ // inlined Node one-liner. // // Resolution strategy (#1930): pnpm-workspace marketplace installs don't -// hoist `@claude-flow/integration` into `v3/node_modules/`, so resolving -// from cwd alone breaks. Try, in order: -// 1. createRequire(cwd) — works for npm-style hoisted installs -// 2. createRequire(script-dir) — works when run from inside the plugin -// 3. absolute path from this file — works on the marketplace layout +// hoist `@claude-flow/integration` into `v3/node_modules/`. The resolved +// module is imported, so it never comes from the cwd (the project). Try: +// 1. createRequire(script-dir) — works when run from inside the plugin +// 2. absolute path from this file — works on the marketplace layout // (script lives at /plugins/ruflo-cost-tracker/scripts/, the // integration package at /v3/@claude-flow/integration/) // @@ -68,9 +67,9 @@ async function main() { process.exit(2); } - // Resolution chain — cwd → script dir → absolute fallback (#1930 step 5) + // Resolution chain — script dir → absolute fallback (#1930 step 5). Not the + // cwd: the module found here is imported, and the cwd is the project. const candidates = [ - tryResolveFrom(join(process.cwd(), 'package.json')), tryResolveFrom(join(__dirname, 'package.json')), tryAbsolutePath(), ].filter(Boolean); @@ -104,7 +103,7 @@ async function main() { memoriesRetrieved: 0, tokensSaved: 0, agenticFlowAvailable: false, - hint: 'Tried cwd, script dir, and absolute path from this script — see #1930 for full troubleshooting.', + hint: 'Tried the script dir and the absolute path from this script — see #1930 for full troubleshooting.', }; if (process.env.COMPACT_QUIET === '1') return console.log(JSON.stringify(out)); console.log(`# cost-compact-context\n\nbridge unavailable: ${reason}`); diff --git a/plugins/ruflo-ruos/scripts/lib/ledger.mjs b/plugins/ruflo-ruos/scripts/lib/ledger.mjs index aa9b58e753..22437bcfa5 100644 --- a/plugins/ruflo-ruos/scripts/lib/ledger.mjs +++ b/plugins/ruflo-ruos/scripts/lib/ledger.mjs @@ -55,7 +55,9 @@ export function projectCwd(env) { /** * Locate ruflo's in-process tool dispatcher without depending on it. - * @param {string} cwd + * The dispatcher is imported, so it resolves from this plugin's own install + * (or an explicit RUFLO_CLI_MCP_CLIENT), never from the project cwd. + * @param {string} cwd kept for callers; not used for module resolution * @param {NodeJS.ProcessEnv} env * @returns {Promise} */ @@ -63,7 +65,7 @@ export async function resolveCallTool(cwd, env) { const candidates = []; if (env.RUFLO_CLI_MCP_CLIENT) candidates.push(env.RUFLO_CLI_MCP_CLIENT); try { - const req = createRequire(join(cwd, 'noop.js')); + const req = createRequire(import.meta.url); for (const pkg of ['@claude-flow/cli', 'ruflo', 'claude-flow']) { try { const pj = req.resolve(`${pkg}/package.json`); diff --git a/v3/@claude-flow/cli/__tests__/optional-module-resolution-trust.test.ts b/v3/@claude-flow/cli/__tests__/optional-module-resolution-trust.test.ts new file mode 100644 index 0000000000..98e762d447 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/optional-module-resolution-trust.test.ts @@ -0,0 +1,109 @@ +/** + * The CLI, its MCP tools and plugin scripts load optional modules and plugin + * scripts that they then execute. Those must resolve from the tool's own + * install (or the user's marketplace checkout), never from the cwd: the cwd + * is the opened project, and a project must not choose code that runs. + */ +import { afterEach, describe, expect, it } from 'vitest'; +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const here = dirname(fileURLToPath(import.meta.url)); +const REPO = resolve(here, '../../../..'); +const tempRoots: string[] = []; + +afterEach(() => { + for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +function scratch(): string { + const root = realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-optional-module-'))); + tempRoots.push(root); + return root; +} + +function write(file: string, content: string) { + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, content); +} + +/** Source of `function name(...) { ... }` up to the next top-level closing brace. */ +function fnSource(file: string, name: string): string { + const source = readFileSync(resolve(REPO, file), 'utf8'); + const start = source.search(new RegExp(`function ${name}\\(`)); + expect(start, `${name} in ${file}`).toBeGreaterThan(-1); + return source.slice(start, source.indexOf('\n}\n', start)); +} + +describe('locators of executed modules never consult the cwd', () => { + const cases: Array<[string, string]> = [ + ['v3/@claude-flow/cli/src/mcp-tools/testgen-tools.ts', 'locateTestgenScripts'], + ['v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts', 'locatePluginScripts'], + ['v3/@claude-flow/cli/src/commands/metaharness.ts', 'locatePluginScripts'], + ['v3/@claude-flow/cli/src/commands/doctor.ts', 'checkMetaharnessIntegration'], + ['v3/@claude-flow/cli/src/commands/init.ts', 'resolveCodexInitializer'], + ['plugins/ruflo-ruos/scripts/lib/ledger.mjs', 'resolveCallTool'], + ]; + for (const [file, name] of cases) { + it(`${file} ${name}()`, () => { + // Comments may still describe the old cwd lookup; only code counts. + const body = fnSource(file, name).split('\n').filter((l) => !/^\s*(\/\/|\*)/.test(l)).join('\n'); + expect(body).not.toMatch(/process\.cwd\(\)|getProjectCwd\(\)|join\(cwd,/); + }); + } + + it('embedding-service resolves agentic-flow from its own package only', () => { + const source = readFileSync(resolve(REPO, 'v3/@claude-flow/embeddings/src/embedding-service.ts'), 'utf8'); + expect(source).not.toContain("path.join(cwd, 'node_modules/agentic-flow"); + expect(source).not.toContain('/workspaces/claude-flow/node_modules'); + expect(source).toContain("require.resolve('agentic-flow/package.json')"); + }); + + it('compact.mjs does not resolve the token optimizer from the cwd', () => { + const source = readFileSync(resolve(REPO, 'plugins/ruflo-cost-tracker/scripts/compact.mjs'), 'utf8'); + expect(source).not.toContain("tryResolveFrom(join(process.cwd(), 'package.json'))"); + }); +}); + +describe('ruflo-ruos resolveCallTool at runtime', () => { + it("never imports a dispatcher planted in the project's node_modules", async () => { + const project = scratch(); + const marker = join(project, 'planted-dispatcher-ran'); + const planted = `import { writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(marker)}, '1');\nexport function callMCPTool() {}\n`; + write(join(project, 'node_modules', '@claude-flow', 'cli', 'package.json'), JSON.stringify({ name: '@claude-flow/cli', type: 'module' })); + write(join(project, 'node_modules', '@claude-flow', 'cli', 'dist', 'src', 'mcp-client.js'), planted); + + const { resolveCallTool } = await import(pathToFileURL(resolve(REPO, 'plugins/ruflo-ruos/scripts/lib/ledger.mjs')).href); + await resolveCallTool(project, {}); + + expect(existsSync(marker)).toBe(false); + }); +}); + +describe('cost-tracker compact.mjs at runtime', () => { + it("never imports a token optimizer planted in the project's node_modules", () => { + const project = scratch(); + const marker = join(project, 'planted-optimizer-ran'); + const pkg = join(project, 'node_modules', '@claude-flow', 'integration'); + write(join(pkg, 'package.json'), JSON.stringify({ + name: '@claude-flow/integration', + type: 'module', + exports: { './token-optimizer': './token-optimizer.js' }, + })); + write(join(pkg, 'token-optimizer.js'), `import { writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(marker)}, '1');\n`); + write(join(project, 'package.json'), JSON.stringify({ name: 'untrusted' })); + + const result = spawnSync(process.execPath, [resolve(REPO, 'plugins/ruflo-cost-tracker/scripts/compact.mjs'), 'query'], { + cwd: project, + env: { ...process.env, COMPACT_QUIET: '1' }, + encoding: 'utf8', + timeout: 60_000, + }); + + expect(result.error).toBeUndefined(); + expect(existsSync(marker)).toBe(false); + }); +}); diff --git a/v3/@claude-flow/cli/src/commands/doctor.ts b/v3/@claude-flow/cli/src/commands/doctor.ts index ffddd0112d..6be2781f6d 100644 --- a/v3/@claude-flow/cli/src/commands/doctor.ts +++ b/v3/@claude-flow/cli/src/commands/doctor.ts @@ -2113,7 +2113,9 @@ async function checkMetaharnessIntegration(): Promise { // (dev) until we find a directory containing `plugins/ruflo-metaharness/`. const candidates: string[] = []; - // Strategy 1: walk up from this module's own URL — covers npx + global install. + // Walk up from this module's own URL — covers npx, global and project-local + // installs and monorepo dev. The plugin found here is imported below, so it + // must come from this CLI's own install, never from the cwd (the project). try { const selfDir = dirname(fileURLToPath(import.meta.url)); let q = selfDir; @@ -2122,19 +2124,9 @@ async function checkMetaharnessIntegration(): Promise { q = dirname(q); } } catch { - // import.meta.url unavailable under some bundlers — fall through to cwd walk. + // import.meta.url unavailable under some bundlers — the plugin is reported absent. } - // Strategy 2: walk up from cwd — covers monorepo dev (running from a sub-package). - let p = process.cwd(); - for (let i = 0; i < 8; i++) { - candidates.push(join(p, 'plugins', 'ruflo-metaharness')); - p = dirname(p); - } - - // Strategy 3: explicit node_modules path relative to cwd — covers project-local install. - candidates.push(join(process.cwd(), 'node_modules', '@claude-flow', 'cli', 'plugins', 'ruflo-metaharness')); - let pluginDir: string | null = null; for (const c of candidates) { if (existsSync(join(c, 'scripts', '_harness.mjs'))) { diff --git a/v3/@claude-flow/cli/src/commands/init.ts b/v3/@claude-flow/cli/src/commands/init.ts index 1db08afa47..1956ac4fee 100644 --- a/v3/@claude-flow/cli/src/commands/init.ts +++ b/v3/@claude-flow/cli/src/commands/init.ts @@ -75,16 +75,9 @@ async function resolveCodexInitializer(cwd: string): Promise (await import(codexModuleId)).CodexInitializer, - // Strategy 2: Project node_modules (works if installed in user's project) - async () => { - const projectPath = path.join(cwd, 'node_modules', '@claude-flow', 'codex', 'dist', 'index.js'); - if (fs.existsSync(projectPath)) { - const mod = await import(`file://${projectPath}`); - return mod.CodexInitializer; - } - throw new Error('Not found in project'); - }, - // Strategy 3: Global node_modules + // (No project node_modules strategy: init must not import code the + // target project supplies.) + // Strategy 2: Global node_modules async () => { const { execSync } = await import('child_process'); const globalPath = execSync('npm root -g', { encoding: 'utf-8' }).trim(); diff --git a/v3/@claude-flow/cli/src/commands/metaharness.ts b/v3/@claude-flow/cli/src/commands/metaharness.ts index c13f83ee2b..2f4804173c 100644 --- a/v3/@claude-flow/cli/src/commands/metaharness.ts +++ b/v3/@claude-flow/cli/src/commands/metaharness.ts @@ -40,6 +40,7 @@ import { spawnSync } from 'child_process'; import { existsSync, readFileSync } from 'fs'; import { join, dirname, resolve } from 'path'; import { fileURLToPath } from 'url'; +import { homedir } from 'os'; import { runFlywheelWorker } from '../services/harness-flywheel-runtime.js'; import { listFlywheelReceipts, @@ -227,12 +228,10 @@ function locatePluginScripts(requiredScript?: string): string | null { candidates.push(join(p, '..', 'plugins', 'ruflo-metaharness', 'scripts')); p = dirname(p); } - // Also try from cwd (covers the "npx ruflo" case where the user is - // sitting in their own repo and `npx ruflo metaharness score` should - // score THAT repo using the LOCAL plugin if present). - const cwd = process.cwd(); - candidates.push(join(cwd, 'plugins', 'ruflo-metaharness', 'scripts')); - candidates.push(join(cwd, 'node_modules', '@claude-flow', 'cli', 'plugins', 'ruflo-metaharness', 'scripts')); + // The scripts are executed, so they come from this CLI's own install (or the + // user's marketplace checkout), never from the cwd: scoring a repo must not + // run plugin code that repo supplies. The repo is still the scoring target. + candidates.push(join(homedir(), '.claude', 'plugins', 'marketplaces', 'ruflo', 'plugins', 'ruflo-metaharness', 'scripts')); for (const c of candidates) { if (!existsSync(join(c, '_harness.mjs'))) continue; diff --git a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts index d3db1f0869..6551dbca66 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts @@ -53,6 +53,7 @@ import { spawn } from 'node:child_process'; import { existsSync, readFileSync } from 'node:fs'; import { join, dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { homedir } from 'node:os'; import { runFlywheelWorker } from '../services/harness-flywheel-runtime.js'; import { evaluatePolicyRequest } from '../services/policy-runtime.js'; import { @@ -83,9 +84,9 @@ function locatePluginScripts(requiredScript?: string): string | null { candidates.push(join(p, '..', 'plugins', 'ruflo-metaharness', 'scripts')); p = dirname(p); } - const cwd = getProjectCwd(); - candidates.push(join(cwd, 'plugins', 'ruflo-metaharness', 'scripts')); - candidates.push(join(cwd, 'node_modules', '@claude-flow', 'cli', 'plugins', 'ruflo-metaharness', 'scripts')); + // Scripts found here are executed, so they come from this CLI's own install + // (or the user's marketplace checkout), never from the project's cwd. + candidates.push(join(homedir(), '.claude', 'plugins', 'marketplaces', 'ruflo', 'plugins', 'ruflo-metaharness', 'scripts')); for (const c of candidates) { if (!existsSync(join(c, '_harness.mjs'))) continue; if (requiredScript && !existsSync(join(c, requiredScript))) continue; diff --git a/v3/@claude-flow/cli/src/mcp-tools/testgen-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/testgen-tools.ts index 3d10346492..e698ef79b6 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/testgen-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/testgen-tools.ts @@ -27,7 +27,7 @@ import { existsSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import type { MCPTool } from './types.js'; -import { getProjectCwd } from './types.js'; +import { homedir } from 'node:os'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); @@ -49,9 +49,9 @@ function locateTestgenScripts(): string | null { candidates.push(join(p, '..', 'plugins', 'ruflo-testgen', 'scripts')); p = dirname(p); } - const cwd = getProjectCwd(); - candidates.push(join(cwd, 'plugins', 'ruflo-testgen', 'scripts')); - candidates.push(join(cwd, 'node_modules', '@claude-flow', 'cli', 'plugins', 'ruflo-testgen', 'scripts')); + // Scripts found here are executed, so they come from this CLI's own install + // (or the user's marketplace checkout), never from the project's cwd. + candidates.push(join(homedir(), '.claude', 'plugins', 'marketplaces', 'ruflo', 'plugins', 'ruflo-testgen', 'scripts')); for (const c of candidates) { if (existsSync(join(c, 'tdd-repair', 'tdd-repair.mjs'))) return c; } diff --git a/v3/@claude-flow/embeddings/src/embedding-service.ts b/v3/@claude-flow/embeddings/src/embedding-service.ts index 2b72a61a09..790ae4ffa3 100644 --- a/v3/@claude-flow/embeddings/src/embedding-service.ts +++ b/v3/@claude-flow/embeddings/src/embedding-service.ts @@ -670,26 +670,18 @@ export class AgenticFlowEmbeddingService extends BaseEmbeddingService { // Try proper package exports first (preferred) possiblePaths.push('agentic-flow/embeddings'); - // Try node_modules resolution from different locations (for file:// imports) + // File fallback: resolve from this package's own location, never from + // the cwd or a fixed path — the module found here is imported. try { - const path = await import('path'); + const { createRequire } = await import('module'); const { existsSync } = await import('fs'); - const cwd = process.cwd(); - - // Prioritize absolute paths that exist (for file:// import fallback) - const absolutePaths = [ - path.join(cwd, 'node_modules/agentic-flow/dist/embeddings/optimized-embedder.js'), - path.join(cwd, '../node_modules/agentic-flow/dist/embeddings/optimized-embedder.js'), - '/workspaces/claude-flow/node_modules/agentic-flow/dist/embeddings/optimized-embedder.js', - ]; - - for (const p of absolutePaths) { - if (existsSync(p)) { - possiblePaths.push(p); - } - } + const path = await import('path'); + const require = createRequire(import.meta.url); + const pkgDir = path.dirname(require.resolve('agentic-flow/package.json')); + const embedder = path.join(pkgDir, 'dist/embeddings/optimized-embedder.js'); + if (existsSync(embedder)) possiblePaths.push(embedder); } catch { - // fs/path module not available + // agentic-flow not resolvable from this package } // Try each path From eadc4adfe37acb8133b623e8d4b36fe2b7a08d21 Mon Sep 17 00:00:00 2001 From: r Date: Sat, 10 Oct 2026 10:45:37 -0400 Subject: [PATCH 10/43] fix(cli,plugins): stop plugin-dir walk-ups at the node_modules boundary; drop embeddings hunk A project-local install lives at /node_modules/@claude-flow/cli, so the 8-level walk-up from import.meta.url used by the testgen/metaharness locators and doctor crossed node_modules and reached /plugins/ruflo-*, i.e. code the opened repository supplies. ownInstallAncestors()/ownPluginDirs() now stop at the first node_modules directory. Source-checkout dev layouts are unaffected. The @claude-flow/embeddings hunk is dropped from this change: that package cannot ship from main until its alpha branch is reconciled, so it needs its own change. Co-Authored-By: RuFlo --- .../optional-module-resolution-trust.test.ts | 58 ++++++++++++++++--- v3/@claude-flow/cli/src/commands/doctor.ts | 6 +- .../cli/src/commands/metaharness.ts | 12 ++-- .../cli/src/mcp-tools/metaharness-tools.ts | 10 +--- .../cli/src/mcp-tools/testgen-tools.ts | 10 +--- .../cli/src/plugins/own-install.ts | 49 ++++++++++++++++ .../embeddings/src/embedding-service.ts | 26 ++++++--- 7 files changed, 130 insertions(+), 41 deletions(-) create mode 100644 v3/@claude-flow/cli/src/plugins/own-install.ts diff --git a/v3/@claude-flow/cli/__tests__/optional-module-resolution-trust.test.ts b/v3/@claude-flow/cli/__tests__/optional-module-resolution-trust.test.ts index 98e762d447..5b0c92d23e 100644 --- a/v3/@claude-flow/cli/__tests__/optional-module-resolution-trust.test.ts +++ b/v3/@claude-flow/cli/__tests__/optional-module-resolution-trust.test.ts @@ -10,6 +10,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; +import { ownInstallAncestors, ownPluginDirs } from '../src/plugins/own-install.js'; const here = dirname(fileURLToPath(import.meta.url)); const REPO = resolve(here, '../../../..'); @@ -55,19 +56,62 @@ describe('locators of executed modules never consult the cwd', () => { }); } - it('embedding-service resolves agentic-flow from its own package only', () => { - const source = readFileSync(resolve(REPO, 'v3/@claude-flow/embeddings/src/embedding-service.ts'), 'utf8'); - expect(source).not.toContain("path.join(cwd, 'node_modules/agentic-flow"); - expect(source).not.toContain('/workspaces/claude-flow/node_modules'); - expect(source).toContain("require.resolve('agentic-flow/package.json')"); - }); - it('compact.mjs does not resolve the token optimizer from the cwd', () => { const source = readFileSync(resolve(REPO, 'plugins/ruflo-cost-tracker/scripts/compact.mjs'), 'utf8'); expect(source).not.toContain("tryResolveFrom(join(process.cwd(), 'package.json'))"); }); }); +describe('plugin locators stay inside the package own install', () => { + const sources: Array<[string, string]> = [ + ['v3/@claude-flow/cli/src/mcp-tools/testgen-tools.ts', 'locateTestgenScripts'], + ['v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts', 'locatePluginScripts'], + ['v3/@claude-flow/cli/src/commands/metaharness.ts', 'locatePluginScripts'], + ['v3/@claude-flow/cli/src/commands/doctor.ts', 'checkMetaharnessIntegration'], + ]; + for (const [file, name] of sources) { + it(`${file} ${name}() walks up through the bounded helper, not a hand-rolled loop`, () => { + const body = fnSource(file, name); + expect(body).toMatch(/ownPluginDirs\(|ownInstallAncestors\(/); + expect(body).not.toMatch(/(\w+) = dirname\(\1\)/); + }); + } + + it("a project-local install never reaches the project's own plugins/ directory", () => { + const project = scratch(); + const cliDir = join(project, 'node_modules', '@claude-flow', 'cli', 'dist', 'src', 'mcp-tools'); + for (const plugin of ['ruflo-testgen', 'ruflo-metaharness']) { + const dirs = [...ownPluginDirs(cliDir, plugin, 'scripts'), ...ownInstallAncestors(cliDir).map((d) => join(d, 'plugins', plugin))]; + expect(dirs.length).toBeGreaterThan(0); + // Every candidate is inside the package; none is the project or above it. + for (const d of dirs) expect(d.startsWith(join(project, 'node_modules', '@claude-flow', 'cli')) || d.startsWith(join(project, 'node_modules', '@claude-flow', 'plugins'))).toBe(true); + expect(dirs).not.toContain(join(project, 'plugins', plugin, 'scripts')); + } + // The package's own bundled plugin is still found. + expect(ownPluginDirs(cliDir, 'ruflo-metaharness', 'scripts')).toContain( + join(project, 'node_modules', '@claude-flow', 'cli', 'plugins', 'ruflo-metaharness', 'scripts'), + ); + }); + + it('pnpm and global layouts stop at their node_modules too', () => { + const pnpm = '/p/node_modules/.pnpm/@claude-flow+cli@1/node_modules/@claude-flow/cli/dist/src/commands'; + expect(ownInstallAncestors(pnpm)).not.toContain('/p/node_modules/.pnpm/@claude-flow+cli@1'); + expect(ownInstallAncestors('/usr/lib/node_modules/@claude-flow/cli/dist/src')).toEqual([ + '/usr/lib/node_modules/@claude-flow/cli/dist/src', + '/usr/lib/node_modules/@claude-flow/cli/dist', + '/usr/lib/node_modules/@claude-flow/cli', + '/usr/lib/node_modules/@claude-flow', + ]); + }); + + it('a source checkout still reaches the repo root (monorepo dev)', () => { + const repo = '/work/ruflo'; + expect(ownPluginDirs(`${repo}/v3/@claude-flow/cli/src/mcp-tools`, 'ruflo-testgen', 'scripts')).toContain( + `${repo}/plugins/ruflo-testgen/scripts`, + ); + }); +}); + describe('ruflo-ruos resolveCallTool at runtime', () => { it("never imports a dispatcher planted in the project's node_modules", async () => { const project = scratch(); diff --git a/v3/@claude-flow/cli/src/commands/doctor.ts b/v3/@claude-flow/cli/src/commands/doctor.ts index 6be2781f6d..97eaa30d6b 100644 --- a/v3/@claude-flow/cli/src/commands/doctor.ts +++ b/v3/@claude-flow/cli/src/commands/doctor.ts @@ -11,6 +11,7 @@ import { existsSync, readFileSync, statSync, openSync, readSync, closeSync } fro import { join, dirname } from 'path'; import { fileURLToPath, pathToFileURL } from 'url'; import { createHash } from 'crypto'; +import { ownInstallAncestors } from '../plugins/own-install.js'; import { execSync, exec, execFile } from 'child_process'; import { promisify } from 'util'; import { decodeKey, isEncryptionEnabled } from '../encryption/vault.js'; @@ -2117,11 +2118,10 @@ async function checkMetaharnessIntegration(): Promise { // installs and monorepo dev. The plugin found here is imported below, so it // must come from this CLI's own install, never from the cwd (the project). try { + // Bounded at node_modules: a project-local install must not reach the project. const selfDir = dirname(fileURLToPath(import.meta.url)); - let q = selfDir; - for (let i = 0; i < 8; i++) { + for (const q of ownInstallAncestors(selfDir)) { candidates.push(join(q, 'plugins', 'ruflo-metaharness')); - q = dirname(q); } } catch { // import.meta.url unavailable under some bundlers — the plugin is reported absent. diff --git a/v3/@claude-flow/cli/src/commands/metaharness.ts b/v3/@claude-flow/cli/src/commands/metaharness.ts index 2f4804173c..fe6e72c970 100644 --- a/v3/@claude-flow/cli/src/commands/metaharness.ts +++ b/v3/@claude-flow/cli/src/commands/metaharness.ts @@ -41,6 +41,7 @@ import { existsSync, readFileSync } from 'fs'; import { join, dirname, resolve } from 'path'; import { fileURLToPath } from 'url'; import { homedir } from 'os'; +import { ownPluginDirs } from '../plugins/own-install.js'; import { runFlywheelWorker } from '../services/harness-flywheel-runtime.js'; import { listFlywheelReceipts, @@ -220,14 +221,9 @@ async function dispatchFlywheel( * `prepublishOnly`). */ function locatePluginScripts(requiredScript?: string): string | null { - const candidates: string[] = []; - // Up from the cli dist dir - let p = resolve(__dirname); - for (let i = 0; i < 8; i++) { - candidates.push(join(p, 'plugins', 'ruflo-metaharness', 'scripts')); - candidates.push(join(p, '..', 'plugins', 'ruflo-metaharness', 'scripts')); - p = dirname(p); - } + // Up from the cli dist dir, bounded at node_modules: a project-local install + // must not reach the project. + const candidates: string[] = ownPluginDirs(__dirname, 'ruflo-metaharness', 'scripts'); // The scripts are executed, so they come from this CLI's own install (or the // user's marketplace checkout), never from the cwd: scoring a repo must not // run plugin code that repo supplies. The repo is still the scoring target. diff --git a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts index 6551dbca66..5b8e5ad981 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts @@ -54,6 +54,7 @@ import { existsSync, readFileSync } from 'node:fs'; import { join, dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { homedir } from 'node:os'; +import { ownPluginDirs } from '../plugins/own-install.js'; import { runFlywheelWorker } from '../services/harness-flywheel-runtime.js'; import { evaluatePolicyRequest } from '../services/policy-runtime.js'; import { @@ -77,13 +78,8 @@ const __dirname = dirname(fileURLToPath(import.meta.url)); * script. */ function locatePluginScripts(requiredScript?: string): string | null { - const candidates: string[] = []; - let p = resolve(__dirname); - for (let i = 0; i < 8; i++) { - candidates.push(join(p, 'plugins', 'ruflo-metaharness', 'scripts')); - candidates.push(join(p, '..', 'plugins', 'ruflo-metaharness', 'scripts')); - p = dirname(p); - } + // Bounded at node_modules: a project-local install must not reach the project. + const candidates: string[] = ownPluginDirs(__dirname, 'ruflo-metaharness', 'scripts'); // Scripts found here are executed, so they come from this CLI's own install // (or the user's marketplace checkout), never from the project's cwd. candidates.push(join(homedir(), '.claude', 'plugins', 'marketplaces', 'ruflo', 'plugins', 'ruflo-metaharness', 'scripts')); diff --git a/v3/@claude-flow/cli/src/mcp-tools/testgen-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/testgen-tools.ts index e698ef79b6..bd317d04de 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/testgen-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/testgen-tools.ts @@ -28,6 +28,7 @@ import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import type { MCPTool } from './types.js'; import { homedir } from 'node:os'; +import { ownPluginDirs } from '../plugins/own-install.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); @@ -42,13 +43,8 @@ const __dirname = dirname(__filename); * today) — when that lands at a candidate path, we've found the dir. */ function locateTestgenScripts(): string | null { - const candidates: string[] = []; - let p = resolve(__dirname); - for (let i = 0; i < 8; i++) { - candidates.push(join(p, 'plugins', 'ruflo-testgen', 'scripts')); - candidates.push(join(p, '..', 'plugins', 'ruflo-testgen', 'scripts')); - p = dirname(p); - } + // Bounded at node_modules: a project-local install must not reach the project. + const candidates: string[] = ownPluginDirs(__dirname, 'ruflo-testgen', 'scripts'); // Scripts found here are executed, so they come from this CLI's own install // (or the user's marketplace checkout), never from the project's cwd. candidates.push(join(homedir(), '.claude', 'plugins', 'marketplaces', 'ruflo', 'plugins', 'ruflo-testgen', 'scripts')); diff --git a/v3/@claude-flow/cli/src/plugins/own-install.ts b/v3/@claude-flow/cli/src/plugins/own-install.ts new file mode 100644 index 0000000000..9a1330cddb --- /dev/null +++ b/v3/@claude-flow/cli/src/plugins/own-install.ts @@ -0,0 +1,49 @@ +/** + * Where the CLI may load executable plugin code from: its OWN install only. + * + * Several callers walk up from their own module location to find a bundled + * plugin directory (`plugins/ruflo-*`) whose scripts they then import or spawn. + * A project-local install lives at `/node_modules/@claude-flow/cli/...`, + * so an unbounded walk-up leaves the package, crosses `node_modules`, and lands in + * `` itself, where `/plugins/ruflo-*` is whatever the opened + * repository ships. The walk must therefore stop at the `node_modules` boundary: + * everything above it belongs to whoever installed the package (a project, a + * global prefix, an npx cache), not to the package. + */ +import { basename, dirname, join, resolve } from 'node:path'; + +/** + * Directories from `startDir` upward that still belong to the package's own + * install: `startDir` and its ancestors, up to but excluding the first + * `node_modules` directory. In a source checkout (no `node_modules` between the + * module and the repo root) this reaches the repo root, as monorepo dev needs. + */ +export function ownInstallAncestors(startDir: string, maxDepth = 8): string[] { + const dirs: string[] = []; + let p = resolve(startDir); + for (let i = 0; i < maxDepth; i++) { + if (basename(p) === 'node_modules') break; + dirs.push(p); + const parent = dirname(p); + if (parent === p) break; + p = parent; + } + return dirs; +} + +/** + * Candidate `/plugins//<...sub>` directories inside the + * package's own install (see {@link ownInstallAncestors}). The `/../plugins` + * form (the sibling of a package root) is only produced when that sibling is itself + * still inside the own-install boundary. + */ +export function ownPluginDirs(startDir: string, plugin: string, ...sub: string[]): string[] { + const ancestors = ownInstallAncestors(startDir); + const inside = new Set(ancestors); + const out: string[] = []; + for (const p of ancestors) { + out.push(join(p, 'plugins', plugin, ...sub)); + if (inside.has(dirname(p))) out.push(join(p, '..', 'plugins', plugin, ...sub)); + } + return out; +} diff --git a/v3/@claude-flow/embeddings/src/embedding-service.ts b/v3/@claude-flow/embeddings/src/embedding-service.ts index 790ae4ffa3..2b72a61a09 100644 --- a/v3/@claude-flow/embeddings/src/embedding-service.ts +++ b/v3/@claude-flow/embeddings/src/embedding-service.ts @@ -670,18 +670,26 @@ export class AgenticFlowEmbeddingService extends BaseEmbeddingService { // Try proper package exports first (preferred) possiblePaths.push('agentic-flow/embeddings'); - // File fallback: resolve from this package's own location, never from - // the cwd or a fixed path — the module found here is imported. + // Try node_modules resolution from different locations (for file:// imports) try { - const { createRequire } = await import('module'); - const { existsSync } = await import('fs'); const path = await import('path'); - const require = createRequire(import.meta.url); - const pkgDir = path.dirname(require.resolve('agentic-flow/package.json')); - const embedder = path.join(pkgDir, 'dist/embeddings/optimized-embedder.js'); - if (existsSync(embedder)) possiblePaths.push(embedder); + const { existsSync } = await import('fs'); + const cwd = process.cwd(); + + // Prioritize absolute paths that exist (for file:// import fallback) + const absolutePaths = [ + path.join(cwd, 'node_modules/agentic-flow/dist/embeddings/optimized-embedder.js'), + path.join(cwd, '../node_modules/agentic-flow/dist/embeddings/optimized-embedder.js'), + '/workspaces/claude-flow/node_modules/agentic-flow/dist/embeddings/optimized-embedder.js', + ]; + + for (const p of absolutePaths) { + if (existsSync(p)) { + possiblePaths.push(p); + } + } } catch { - // agentic-flow not resolvable from this package + // fs/path module not available } // Try each path From c4c66b2c7b1143fa38cc2c5e9d2156a957ef818b Mon Sep 17 00:00:00 2001 From: Dragan Spiridonov Date: Fri, 9 Oct 2026 19:53:10 +0200 Subject: [PATCH 11/43] fix(plugins): fail closed when the plugin registry is not verified The live plugin registry CID is unsigned, so discovery always fell back to the built-in plugin list, whose entries all claim trustLevel "official". `plugins install` passed that claim on as registry trust, which runs npm lifecycle scripts and skips the permission gate (#3557) for any listed plugin, with nothing actually verified. - Discovery reports `verified` + `unverifiedReason`; only a registry whose signature verifies against the pinned key keeps its trust labels. The built-in fallback and a registry fetched with requireVerification off are reported with every entry as 'unverified'. - A placeholder pinned key (missing, malformed, all-zero) is never used to verify: the all-zero key is small-order and accepts a forged signature. - CLAUDE_FLOW_STRICT_PLUGINS=true (ADR-145): no fallback to the built-in list, and `plugins install` refuses unless --allow-unverified is passed. - `plugins install` passes registry trust, permissions and checksum only for a verified registry entry; `plugins list`/`info` show registry status. - PluginIntegrityVerifier (@claude-flow/security) skips placeholder anchors, such as the all-zero one in trust-anchors.json, and verifies in RFC 8032 strict mode, which rejects small-order keys. --- ...plugins-registry-trust-fail-closed.test.ts | 255 ++++++++++++++++++ v3/@claude-flow/cli/src/commands/plugins.ts | 64 ++++- .../cli/src/plugins/store/discovery.ts | 133 +++++++-- .../cli/src/plugins/store/types.ts | 5 + .../cli/src/plugins/trust-policy.ts | 22 ++ .../plugin-integrity-verifier.test.ts | 48 ++++ v3/@claude-flow/security/src/index.ts | 1 + .../src/plugins/integrity-verifier.ts | 19 +- 8 files changed, 517 insertions(+), 30 deletions(-) create mode 100644 v3/@claude-flow/cli/__tests__/plugins-registry-trust-fail-closed.test.ts diff --git a/v3/@claude-flow/cli/__tests__/plugins-registry-trust-fail-closed.test.ts b/v3/@claude-flow/cli/__tests__/plugins-registry-trust-fail-closed.test.ts new file mode 100644 index 0000000000..6c6d2382de --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/plugins-registry-trust-fail-closed.test.ts @@ -0,0 +1,255 @@ +/** + * Plugin registry trust fails closed (ADR-145). + * + * The signed registry is what vouches for a plugin: its trustLevel 'official'/'verified' lets an + * install run npm lifecycle scripts and skip the permission gate. So: + * - an unverified registry (unsigned, bad signature, placeholder pinned key, verification off) + * and the built-in fallback list carry no registry trust; + * - a placeholder (all-zero) pinned key is never used to verify — it accepts a forged signature; + * - CLAUDE_FLOW_STRICT_PLUGINS=true turns the fallback into an error and makes `plugins install` + * refuse without --allow-unverified; + * - `plugins install` never passes an unverified entry's trust, permissions or checksum on. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +const ipfs = vi.hoisted(() => ({ registry: null as Record | null })); + +vi.mock('../src/transfer/ipfs/client.js', async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + resolveIPNS: vi.fn(async () => null), + fetchFromIPFS: vi.fn(async () => ipfs.registry), + }; +}); + +const manager = vi.hoisted(() => ({ + installFromNpm: vi.fn(), +})); + +vi.mock('../src/plugins/manager.js', () => ({ + getPluginManager: () => ({ + initialize: async () => {}, + getPlugin: async () => undefined, + installFromNpm: manager.installFromNpm, + getPluginsDir: () => '/tmp/plugins', + }), +})); + +import { PluginDiscoveryService } from '../src/plugins/store/discovery.js'; +import { verifyEd25519Signature } from '../src/transfer/ipfs/client.js'; +import { isPlaceholderSigningKey, isStrictPluginMode } from '../src/plugins/trust-policy.js'; +import { pluginsCommand } from '../src/commands/plugins.js'; +import type { CommandContext } from '../src/types.js'; +import anchorsFile from '../src/plugins/trust/trust-anchors.json'; + +const ZERO_KEY = '0'.repeat(64); +// R = identity point, S = 0: verifies against any small-order key for every message (ZIP-215). +const FORGED_SIG = '01' + '0'.repeat(126); + +function entry(name: string, trustLevel = 'official') { + return { + id: name, + name, + displayName: name, + version: '1.0.0', + trustLevel, + verified: true, + checksum: 'sha256:' + 'a'.repeat(64), + permissions: ['shell:exec'], + hooks: [], + commands: [], + }; +} + +function registryWith(plugins: ReturnType[], extra: Record = {}) { + return { + version: '1.0.1', + type: 'plugins', + plugins, + totalPlugins: plugins.length, + featured: [], + official: plugins.map((p) => p.id), + ...extra, + }; +} + +function serviceFor(publicKey: string, overrides: Record = {}) { + return new PluginDiscoveryService({ + requireVerification: true, + defaultRegistry: 'test', + registries: [ + { name: 'test', description: 't', ipnsName: 'QmTestRegistry', gateway: 'https://example.invalid', publicKey, trusted: true, official: true }, + ], + ...overrides, + } as never); +} + +async function signRegistry(registry: Record) { + const ed = await import('@noble/ed25519'); + const priv = ed.utils.randomPrivateKey(); + const pub = Buffer.from(await ed.getPublicKeyAsync(priv)).toString('hex'); + const sig = await ed.signAsync(new TextEncoder().encode(JSON.stringify(registry)), priv); + return { pub, signed: { ...registry, registrySignature: Buffer.from(sig).toString('hex') } }; +} + +beforeEach(() => { + vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('offline'); })); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); + delete process.env.CLAUDE_FLOW_STRICT_PLUGINS; + ipfs.registry = null; + manager.installFromNpm.mockReset(); +}); + +afterEach(() => { + delete process.env.CLAUDE_FLOW_STRICT_PLUGINS; + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +describe('placeholder signing keys', () => { + it('the shipped trust anchor is a placeholder', () => { + expect(anchorsFile.anchors.length).toBeGreaterThan(0); + for (const a of anchorsFile.anchors) expect(isPlaceholderSigningKey(a.publicKey)).toBe(true); + }); + + it('rejects missing, malformed and all-zero keys; accepts a real-looking key', () => { + expect(isPlaceholderSigningKey(undefined)).toBe(true); + expect(isPlaceholderSigningKey('')).toBe(true); + expect(isPlaceholderSigningKey('ed25519:abc')).toBe(true); + expect(isPlaceholderSigningKey(`ed25519:${ZERO_KEY}`)).toBe(true); + expect(isPlaceholderSigningKey(`ed25519:${'ab'.repeat(32)}`)).toBe(false); + }); + + it('the all-zero key really does accept a forged signature (why it must never be verified against)', async () => { + expect(await verifyEd25519Signature('any message at all', FORGED_SIG, ZERO_KEY)).toBe(true); + }); + + it('a placeholder pinned key leaves the registry unverified even with a "valid" forged signature', async () => { + ipfs.registry = registryWith([entry('@claude-flow/evil')], { registrySignature: FORGED_SIG }); + const result = await serviceFor(`ed25519:${ZERO_KEY}`).discoverRegistry(); + + expect(result.verified).toBe(false); + expect(result.unverifiedReason).toMatch(/placeholder/); + expect(result.registry!.plugins.find((p) => p.name === '@claude-flow/evil')).toBeUndefined(); + expect(result.registry!.plugins.every((p) => p.trustLevel === 'unverified' && !p.verified)).toBe(true); + }); +}); + +describe('discovery: an unverified registry confers no trust', () => { + it('an unsigned registry falls back to the built-in list, labelled demo and unverified, with trust stripped', async () => { + ipfs.registry = registryWith([entry('@claude-flow/a')]); + const svc = serviceFor(`ed25519:${'ab'.repeat(32)}`); + + const first = await svc.discoverRegistry(); + expect(first.success).toBe(true); + expect(first.demo).toBe(true); + expect(first.verified).toBe(false); + expect(first.unverifiedReason).toMatch(/unsigned/); + expect(first.registry!.plugins.length).toBeGreaterThan(0); + expect(first.registry!.plugins.every((p) => p.trustLevel === 'unverified' && !p.verified)).toBe(true); + + const second = await svc.discoverRegistry(); + expect(second.fromCache).toBe(true); + expect(second.verified).toBe(false); + expect(second.registry!.plugins.every((p) => p.trustLevel === 'unverified')).toBe(true); + }); + + it('a signature that does not verify is not silently treated as the registry', async () => { + const { signed } = await signRegistry(registryWith([entry('@claude-flow/a')])); + ipfs.registry = signed; + // Pinned key differs from the signer. + const result = await serviceFor(`ed25519:${'ab'.repeat(32)}`).discoverRegistry(); + expect(result.verified).toBe(false); + expect(result.demo).toBe(true); + expect(result.unverifiedReason).toMatch(/does not verify/); + }); + + it('with verification disabled the fetched registry is used but every entry is unverified', async () => { + ipfs.registry = registryWith([entry('@claude-flow/a')]); + const result = await serviceFor(`ed25519:${'ab'.repeat(32)}`, { requireVerification: false }).discoverRegistry(); + expect(result.success).toBe(true); + expect(result.demo).toBeUndefined(); + expect(result.verified).toBe(false); + expect(result.registry!.plugins).toEqual([expect.objectContaining({ name: '@claude-flow/a', trustLevel: 'unverified', verified: false })]); + }); + + it('a correctly signed registry is verified and keeps its trust levels', async () => { + const { pub, signed } = await signRegistry(registryWith([entry('@claude-flow/a')])); + ipfs.registry = signed; + const result = await serviceFor(`ed25519:${pub}`).discoverRegistry(); + expect(result.verified).toBe(true); + expect(result.demo).toBeUndefined(); + expect(result.unverifiedReason).toBeUndefined(); + expect(result.registry!.plugins[0].trustLevel).toBe('official'); + }); + + it('CLAUDE_FLOW_STRICT_PLUGINS=true: no fallback, discovery fails with the reason', async () => { + process.env.CLAUDE_FLOW_STRICT_PLUGINS = 'true'; + expect(isStrictPluginMode()).toBe(true); + ipfs.registry = registryWith([entry('@claude-flow/a')]); + const result = await serviceFor(`ed25519:${'ab'.repeat(32)}`).discoverRegistry(); + expect(result.success).toBe(false); + expect(result.registry).toBeUndefined(); + expect(result.verified).toBe(false); + expect(result.error).toMatch(/unsigned.*CLAUDE_FLOW_STRICT_PLUGINS=true/); + }); +}); + +describe('plugins install: unverified registry entries get no registry trust', () => { + const install = pluginsCommand.subcommands!.find((c) => c.name === 'install')!; + const ctxFor = (flags: Record) => + ({ args: [], flags: { _: [], ...flags }, cwd: process.cwd(), interactive: false }) as unknown as CommandContext; + const installed = { success: true, plugin: { name: '@claude-flow/neural', version: '3.0.0', source: 'npm' }, warnings: [] }; + + // The real default registry is unsigned today, as the live CID is; serve it unsigned. + beforeEach(() => { + ipfs.registry = registryWith([entry('@claude-flow/neural')]); + manager.installFromNpm.mockResolvedValue(installed); + }); + + it('default mode: a built-in-list entry installs without its "official" trust, permissions or checksum', async () => { + const res = await install.action!(ctxFor({ name: '@claude-flow/neural' })); + expect(res.success).toBe(true); + expect(manager.installFromNpm).toHaveBeenCalledTimes(1); + const opts = manager.installFromNpm.mock.calls[0][2]; + expect(opts).toEqual({ verify: true, trust: false }); + }); + + it('strict mode: refuses without --allow-unverified and installs nothing', async () => { + process.env.CLAUDE_FLOW_STRICT_PLUGINS = 'true'; + const res = await install.action!(ctxFor({ name: '@claude-flow/neural' })); + expect(res.success).toBe(false); + expect(manager.installFromNpm).not.toHaveBeenCalled(); + }); + + it('strict mode + --allow-unverified: installs, still without registry trust', async () => { + process.env.CLAUDE_FLOW_STRICT_PLUGINS = 'true'; + const res = await install.action!(ctxFor({ name: '@claude-flow/neural', allowUnverified: true })); + expect(res.success).toBe(true); + expect(manager.installFromNpm.mock.calls[0][2]).toEqual({ verify: true, trust: false }); + }); + + it('a verified registry entry still passes its trust, permissions and checksum on', async () => { + const { pub, signed } = await signRegistry(registryWith([entry('@claude-flow/neural')])); + ipfs.registry = signed; + const { DEFAULT_PLUGIN_STORE_CONFIG } = await import('../src/plugins/store/discovery.js'); + const original = DEFAULT_PLUGIN_STORE_CONFIG.registries.map((r) => r.publicKey); + DEFAULT_PLUGIN_STORE_CONFIG.registries.forEach((r) => { r.publicKey = `ed25519:${pub}`; }); + try { + const res = await install.action!(ctxFor({ name: '@claude-flow/neural' })); + expect(res.success).toBe(true); + expect(manager.installFromNpm.mock.calls[0][2]).toEqual({ + verify: true, + trust: false, + expectedChecksum: 'sha256:' + 'a'.repeat(64), + registryTrustLevel: 'official', + registryPermissions: ['shell:exec'], + }); + } finally { + DEFAULT_PLUGIN_STORE_CONFIG.registries.forEach((r, i) => { r.publicKey = original[i]; }); + } + }); +}); diff --git a/v3/@claude-flow/cli/src/commands/plugins.ts b/v3/@claude-flow/cli/src/commands/plugins.ts index 60b6238edc..f7d94a7b58 100644 --- a/v3/@claude-flow/cli/src/commands/plugins.ts +++ b/v3/@claude-flow/cli/src/commands/plugins.ts @@ -20,7 +20,7 @@ import { type PluginType, } from '../plugins/store/index.js'; import { getPluginManager, type InstalledPlugin } from '../plugins/manager.js'; -import { DEFAULT_PLUGIN_PERMISSIONS } from '../plugins/trust-policy.js'; +import { DEFAULT_PLUGIN_PERMISSIONS, isStrictPluginMode } from '../plugins/trust-policy.js'; import { getBulkRatings } from '../services/registry-api.js'; // List subcommand - Now uses IPFS-based registry @@ -117,6 +117,10 @@ const listCommand: Command = { `(${result.registry.totalPlugins} plugins)`, ), ); + } else if (result.verified !== true) { + spinner.stop( + output.warning(`Registry discovered but not verified: ${result.registry.totalPlugins} plugins available`), + ); } else { spinner.succeed(`Registry discovered: ${result.registry.totalPlugins} plugins available`); } @@ -207,11 +211,19 @@ const listCommand: Command = { if (result.demo) { output.writeln( output.warning( - 'Not from the signed registry: download counts, ratings and trust labels are the ' + + 'Not from the signed registry: download counts and ratings are the ' + "CLI's built-in defaults, not verified registry data.", ), ); } + if (result.verified !== true) { + output.writeln( + output.warning( + `Registry not verified (${result.unverifiedReason ?? 'unknown reason'}): every entry is ` + + 'shown as Unverified and installs get no registry trust.', + ), + ); + } if (result.cid) { output.writeln(output.dim(`Registry CID: ${result.cid.slice(0, 30)}...`)); } @@ -245,6 +257,14 @@ const installCommand: Command = { default: true, }, { name: 'trust', type: 'boolean', description: 'Register hooks and commands even if the plugin is untrusted or declares elevated permissions', default: false }, + { + name: 'allow-unverified', + type: 'boolean', + description: + 'With CLAUDE_FLOW_STRICT_PLUGINS=true, install from npm even though the plugin registry is not verified. ' + + 'The plugin still gets no registry trust.', + default: false, + }, { name: 'registry', short: 'r', type: 'string', description: 'Registry to use' }, ], examples: [ @@ -258,6 +278,7 @@ const installCommand: Command = { const registryName = ctx.flags.registry as string; const verify = ctx.flags.verify !== false; const trust = ctx.flags.trust === true; + const allowUnverified = ctx.flags.allowUnverified === true || ctx.flags['allow-unverified'] === true; if (!name) { output.printError('Plugin name is required'); @@ -292,6 +313,7 @@ const installCommand: Command = { let result; let plugin: PluginEntry | undefined; + const registryWarnings: string[] = []; if (isLocalPath) { // Install from local path @@ -307,18 +329,43 @@ const installCommand: Command = { plugin = registryResult.registry.plugins.find(p => p.name === name || p.id === name); } + // Only a verified registry may vouch for a plugin (trust level, permissions, checksum). + // An unverified or built-in list is just a claim, so its entries install like any npm + // package: no install scripts and no permission vouching without --trust. + const registryVerified = registryResult.success && registryResult.verified === true; + if (!registryVerified) { + const reason = registryResult.unverifiedReason ?? registryResult.error ?? 'registry not verified'; + if (isStrictPluginMode() && !allowUnverified) { + spinner.fail(`Refusing to install ${name}: plugin registry is not verified (${reason})`); + output.writeln(); + output.writeln(output.dim( + 'CLAUDE_FLOW_STRICT_PLUGINS=true requires a verified registry. Pass --allow-unverified to install it ' + + 'from npm anyway, without registry trust.', + )); + return { success: false, exitCode: 1 }; + } + if (plugin) { + registryWarnings.push( + `${name} is listed only in an unverified registry (${reason}); it was installed without registry trust.`, + ); + } + } + if (plugin) { spinner.setText(`Found ${plugin.displayName} v${plugin.version}`); } - // Install from npm (since IPFS is demo mode) spinner.setText(`Installing ${name} from npm...`); result = await manager.installFromNpm(name, version !== 'latest' ? version : undefined, { verify, trust, - expectedChecksum: plugin?.checksum, - registryTrustLevel: plugin?.trustLevel, - registryPermissions: plugin?.permissions, + ...(registryVerified && plugin + ? { + expectedChecksum: plugin.checksum, + registryTrustLevel: plugin.trustLevel, + registryPermissions: plugin.permissions, + } + : {}), }); } @@ -335,7 +382,7 @@ const installCommand: Command = { if (result.decision?.verificationSkipped) { output.printWarning('Verification skipped (--no-verify): hooks and commands were registered without a trust or checksum check.'); } - for (const warning of result.warnings ?? []) { + for (const warning of [...registryWarnings, ...(result.warnings ?? [])]) { output.printWarning(warning); } @@ -535,6 +582,7 @@ const infoCommand: Command = { if (!result.success || !result.registry) { spinner.fail('Failed to discover registry'); + if (result.error) output.printError(result.error); return { success: false, exitCode: 1 }; } @@ -571,6 +619,7 @@ const infoCommand: Command = { { field: 'Author', value: plugin.author.displayName || plugin.author.id }, { field: 'Trust Level', value: plugin.trustLevel }, { field: 'Verified', value: plugin.verified ? '✓ Yes' : '✗ No' }, + { field: 'Registry', value: result.verified === true ? 'verified' : `unverified (${result.unverifiedReason ?? 'unknown reason'})` }, ], }); @@ -861,6 +910,7 @@ const searchCommand: Command = { if (!result.success || !result.registry) { spinner.fail('Failed to discover registry'); + if (result.error) output.printError(result.error); return { success: false, exitCode: 1 }; } diff --git a/v3/@claude-flow/cli/src/plugins/store/discovery.ts b/v3/@claude-flow/cli/src/plugins/store/discovery.ts index b0a8c8a122..b270172d92 100644 --- a/v3/@claude-flow/cli/src/plugins/store/discovery.ts +++ b/v3/@claude-flow/cli/src/plugins/store/discovery.ts @@ -14,6 +14,7 @@ import type { PluginEntry, } from './types.js'; import { resolveIPNS, fetchFromIPFS, verifyEd25519Signature } from '../../transfer/ipfs/client.js'; +import { isPlaceholderSigningKey, isStrictPluginMode } from '../trust-policy.js'; /** * Fetch real npm download stats for a package @@ -118,6 +119,25 @@ export interface PluginDiscoveryResult { * is NOT the verified registry, and callers must say so rather than report a discovery. */ demo?: boolean; + /** + * True only when the registry's signature verified against the pinned key. Entries of an + * unverified registry carry no registry trust: their trustLevel is reported as + * 'unverified', so nothing downstream can treat them as registry-vouched. + */ + verified?: boolean; + /** Why the registry is not verified (set whenever `verified` is not true). */ + unverifiedReason?: string; +} + +/** + * Strip registry-asserted trust from a registry that was not verified. Its trust labels are + * just claims made by whoever served (or hardcoded) the list. + */ +function withoutRegistryTrust(registry: PluginRegistry): PluginRegistry { + return { + ...registry, + plugins: registry.plugins.map((p) => ({ ...p, trustLevel: 'unverified' as const, verified: false })), + }; } /** @@ -125,12 +145,26 @@ export interface PluginDiscoveryResult { */ export class PluginDiscoveryService { private config: PluginStoreConfig; - private cache: Map = new Map(); + private cache: Map = new Map(); constructor(config: Partial = {}) { this.config = { ...DEFAULT_PLUGIN_STORE_CONFIG, ...config }; } + /** + * Whether an unverified registry may be replaced by the built-in list. Off under + * `CLAUDE_FLOW_STRICT_PLUGINS=true` (ADR-145) unless the config says otherwise. + */ + private allowsUnverifiedFallback(): boolean { + return this.config.allowUnverifiedFallback ?? !isStrictPluginMode(); + } + /** * Discover plugin registry via IPNS */ @@ -153,11 +187,13 @@ export class PluginDiscoveryService { console.log(`[PluginDiscovery] Cache hit for ${registry.name}`); return { success: true, - registry: cached.registry, + registry: cached.verified ? cached.registry : withoutRegistryTrust(cached.registry), fromCache: true, // A cached fallback is still the fallback: never relabel it as the real registry. source: cached.demo ? `${registry.name} (demo)` : registry.name, ...(cached.demo ? { demo: true } : {}), + verified: cached.verified === true, + ...(cached.verified ? {} : { unverifiedReason: cached.unverifiedReason ?? 'registry not verified' }), }; } @@ -174,8 +210,7 @@ export class PluginDiscoveryService { // Resolve IPNS to get current CID cid = await resolveIPNS(registry.ipnsName, registry.gateway); if (!cid) { - // Fallback to demo registry - return this.createDemoRegistryAsync(registry); + return this.fallbackToBuiltIn(registry, `could not resolve IPNS name ${registry.ipnsName}`); } console.log(`[PluginDiscovery] Resolved IPNS to CID: ${cid}`); } @@ -183,7 +218,7 @@ export class PluginDiscoveryService { // Fetch registry from IPFS const registryData = await fetchFromIPFS(cid, registry.gateway); if (!registryData) { - return this.createDemoRegistryAsync(registry); + return this.fallbackToBuiltIn(registry, `could not fetch registry CID ${cid}`); } // Verify registry signature when required. @@ -192,20 +227,35 @@ export class PluginDiscoveryService { // on-path attacker) swap in attacker-mapped plugin entries that the // installer would then load unsandboxed. if (this.config.requireVerification) { - const verified = await this.verifyRegistrySignature(registryData, registry.publicKey); - if (!verified) { - console.warn( - `[PluginDiscovery] Registry signature verification failed for ` + - `${registry.name} (CID ${cid}); falling back to demo registry.`, - ); - return this.createDemoRegistryAsync(registry); + const failure = await this.registrySignatureFailure(registryData, registry.publicKey); + if (failure) { + return this.fallbackToBuiltIn(registry, `${failure}, CID ${cid}`); } + } else { + // Verification disabled by config: usable, but it vouches for nothing. + const unverifiedReason = 'signature verification disabled (requireVerification: false)'; + this.cache.set(registry.ipnsName, { + registry: registryData, + timestamp: Date.now(), + verified: false, + unverifiedReason, + }); + return { + success: true, + registry: withoutRegistryTrust(registryData), + cid, + source: registry.name, + fromCache: false, + verified: false, + unverifiedReason, + }; } // Cache the result this.cache.set(registry.ipnsName, { registry: registryData, timestamp: Date.now(), + verified: true, }); return { @@ -214,14 +264,51 @@ export class PluginDiscoveryService { cid, source: registry.name, fromCache: false, + verified: true, }; } catch (error) { console.error(`[PluginDiscovery] Failed to discover registry:`, error); - // Return demo registry on error - return this.createDemoRegistryAsync(registry); + return this.fallbackToBuiltIn(registry, `discovery error: ${error instanceof Error ? error.message : String(error)}`); } } + /** + * The signed registry is unavailable or unverified. Outside strict mode, use the built-in + * list, labelled as such and stripped of registry trust; in strict mode, fail. + */ + private async fallbackToBuiltIn( + registry: KnownPluginRegistry, + reason: string, + ): Promise { + if (!this.allowsUnverifiedFallback()) { + return { + success: false, + verified: false, + unverifiedReason: reason, + error: + `Plugin registry ${registry.name} is not verified (${reason}). ` + + 'Not falling back to the built-in plugin list because CLAUDE_FLOW_STRICT_PLUGINS=true.', + }; + } + + console.warn( + `[PluginDiscovery] Registry ${registry.name} is not verified (${reason}); ` + + 'using the built-in plugin list, which is unverified and confers no registry trust.', + ); + const result = await this.createDemoRegistryAsync(registry); + const cached = this.cache.get(registry.ipnsName); + if (cached) { + cached.verified = false; + cached.unverifiedReason = reason; + } + return { + ...result, + ...(result.registry ? { registry: withoutRegistryTrust(result.registry) } : {}), + verified: false, + unverifiedReason: reason, + }; + } + /** * Create demo plugin registry with real npm stats */ @@ -1158,7 +1245,7 @@ export class PluginDiscoveryService { } /** - * Verify registry Ed25519 signature. + * Verify the registry Ed25519 signature; returns why it failed, or null when it verified. * * Mirrors the signing scheme in scripts/publish-registry.ts: the signer * removes registrySignature + registryPublicKey from the registry object @@ -1168,12 +1255,17 @@ export class PluginDiscoveryService { * whoever served the registry and can be swapped by a compromised * gateway / on-path attacker. */ - private async verifyRegistrySignature( + private async registrySignatureFailure( registry: PluginRegistry, expectedPublicKey: string, - ): Promise { - if (!registry.registrySignature || !expectedPublicKey) { - return false; + ): Promise { + // A placeholder pin (e.g. the all-zero key) can't vouch for anything, and the all-zero + // key accepts a forged signature under ZIP-215 verification. Never verify against it. + if (isPlaceholderSigningKey(expectedPublicKey)) { + return 'pinned registry signing key is missing or a placeholder'; + } + if (!registry.registrySignature) { + return 'registry is unsigned'; } // Object spread preserves insertion order; delete drops a key without // re-ordering the rest, matching the signer's view of the registry. @@ -1181,11 +1273,12 @@ export class PluginDiscoveryService { delete registryToVerify.registrySignature; delete registryToVerify.registryPublicKey; const message = JSON.stringify(registryToVerify); - return verifyEd25519Signature( + const ok = await verifyEd25519Signature( message, registry.registrySignature, expectedPublicKey, ); + return ok ? null : 'registry signature does not verify against the pinned key'; } /** diff --git a/v3/@claude-flow/cli/src/plugins/store/types.ts b/v3/@claude-flow/cli/src/plugins/store/types.ts index 22ad7cf1ed..4facb91f3a 100644 --- a/v3/@claude-flow/cli/src/plugins/store/types.ts +++ b/v3/@claude-flow/cli/src/plugins/store/types.ts @@ -319,6 +319,11 @@ export interface PluginStoreConfig { // Security requireVerification: boolean; + /** + * Fall back to the built-in (unverified) plugin list when the signed registry can't be + * verified. Defaults to true, or false under `CLAUDE_FLOW_STRICT_PLUGINS=true`. + */ + allowUnverifiedFallback?: boolean; requireSecurityAudit: boolean; minTrustLevel: TrustLevel; trustedAuthors: string[]; diff --git a/v3/@claude-flow/cli/src/plugins/trust-policy.ts b/v3/@claude-flow/cli/src/plugins/trust-policy.ts index dbbc382c14..be69f3c20f 100644 --- a/v3/@claude-flow/cli/src/plugins/trust-policy.ts +++ b/v3/@claude-flow/cli/src/plugins/trust-policy.ts @@ -119,3 +119,25 @@ export function parseSha256Checksum(checksum: unknown): string | null { export function sha256Hex(data: Buffer): string { return createHash('sha256').update(data).digest('hex'); } + +/** + * Whether `CLAUDE_FLOW_STRICT_PLUGINS=true` (ADR-145): an unverified plugin + * registry is then an error, not a warning. + */ +export function isStrictPluginMode(env: NodeJS.ProcessEnv = process.env): boolean { + return (env.CLAUDE_FLOW_STRICT_PLUGINS ?? '').trim().toLowerCase() === 'true'; +} + +/** + * A signing key that cannot vouch for anything: missing, not 32 bytes of hex, + * or all zeros (the placeholder in `trust/trust-anchors.json`). The all-zero + * key is also a small-order Ed25519 point, for which a fixed forged signature + * verifies against every message under ZIP-215 rules, so it must never be + * handed to a verifier. + */ +export function isPlaceholderSigningKey(key: unknown): boolean { + if (typeof key !== 'string') return true; + const hex = key.trim().replace(/^ed25519:/i, ''); + if (!/^[0-9a-f]{64}$/i.test(hex)) return true; + return /^0+$/.test(hex); +} diff --git a/v3/@claude-flow/security/__tests__/plugin-integrity-verifier.test.ts b/v3/@claude-flow/security/__tests__/plugin-integrity-verifier.test.ts index f2c28b29ef..a2c9602f53 100644 --- a/v3/@claude-flow/security/__tests__/plugin-integrity-verifier.test.ts +++ b/v3/@claude-flow/security/__tests__/plugin-integrity-verifier.test.ts @@ -10,15 +10,20 @@ * - verify reports `unknown-signer` when the key isn't in trust anchors * - verify reports `pass` on a valid round-trip sign → verify * - verify reports `signature-invalid` on a flipped signature byte + * - the shipped placeholder (all-zero) anchor never vouches, and small-order + * keys are rejected even when anchored (a forged R=identity, S=0 signature + * verifies against them for every message under ZIP-215) */ import { describe, it, expect, beforeAll } from 'vitest'; import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; import { PluginIntegrityVerifier, canonicalize, hashManifest, findAnchor, + isPlaceholderKey, type PluginManifest, type SignedPluginManifest, type TrustAnchor, @@ -197,3 +202,46 @@ describe('PluginIntegrityVerifier.verify', () => { expect(r.status).toBe('signature-invalid'); }); }); + +// ─── placeholder / small-order keys ──────────────────────────────────── + +describe('placeholder and small-order signing keys', () => { + const ZERO_KEY = '0'.repeat(64); + // y = -1: the order-2 point (0, -1). + const ORDER_TWO_KEY = 'ec' + 'ff'.repeat(30) + '7f'; + // R = identity, S = 0. + const FORGED_SIG = '01' + '0'.repeat(126); + + function forged(publicKey: string): SignedPluginManifest { + const manifest = { id: '@claude-flow/evil', version: '6.6.6' }; + return { manifest, manifestHash: hashManifest(manifest), signature: FORGED_SIG, publicKey }; + } + + it('isPlaceholderKey flags empty and all-zero keys only', () => { + expect(isPlaceholderKey('')).toBe(true); + expect(isPlaceholderKey(ZERO_KEY)).toBe(true); + expect(isPlaceholderKey(ORDER_TWO_KEY)).toBe(false); + }); + + it('the shipped trust-anchors.json placeholder never vouches for a forged manifest', async () => { + const shipped = JSON.parse( + readFileSync(new URL('../../cli/src/plugins/trust/trust-anchors.json', import.meta.url), 'utf-8'), + ) as TrustAnchors; + expect(shipped.anchors.some((a) => a.publicKey === ZERO_KEY)).toBe(true); + expect(findAnchor(shipped.anchors, '@claude-flow/evil', ZERO_KEY, Date.now())).toBeNull(); + + const r = await new PluginIntegrityVerifier({ trustAnchors: shipped }).verify(forged(ZERO_KEY)); + expect(r.status).not.toBe('pass'); + expect(r.status).toBe('unknown-signer'); + }); + + it('rejects a forged signature even when a small-order key is anchored', async () => { + if (!ed) { console.warn('@noble/ed25519 unavailable — skipping'); return; } + // Sanity: noble's default (ZIP-215) verify accepts the forgery against this key. + const m = forged(ORDER_TWO_KEY); + expect(await ed.verifyAsync(hexBytes(FORGED_SIG), hexBytes(m.manifestHash), hexBytes(ORDER_TWO_KEY))).toBe(true); + + const r = await new PluginIntegrityVerifier({ trustAnchors: anchorsFor(ORDER_TWO_KEY) }).verify(m); + expect(r.status).toBe('signature-invalid'); + }); +}); diff --git a/v3/@claude-flow/security/src/index.ts b/v3/@claude-flow/security/src/index.ts index 8ef2d2d3b8..15e2fbf33e 100644 --- a/v3/@claude-flow/security/src/index.ts +++ b/v3/@claude-flow/security/src/index.ts @@ -193,6 +193,7 @@ export { hashManifest, fingerprint, findAnchor, + isPlaceholderKey, type PluginManifest, type SignedPluginManifest, type TrustAnchor, diff --git a/v3/@claude-flow/security/src/plugins/integrity-verifier.ts b/v3/@claude-flow/security/src/plugins/integrity-verifier.ts index 850bf3d9db..e1cda4aad3 100644 --- a/v3/@claude-flow/security/src/plugins/integrity-verifier.ts +++ b/v3/@claude-flow/security/src/plugins/integrity-verifier.ts @@ -129,12 +129,23 @@ export function fingerprint(publicKey: string): string { return publicKey.slice(0, 16); } +/** + * A placeholder key that must never vouch for anything: empty or all zeros, as + * shipped in `trust-anchors.json` until the real key is filled in. The all-zero + * key is a small-order point: under ZIP-215 rules a fixed forged signature + * verifies against it for every message. + */ +export function isPlaceholderKey(publicKey: string): boolean { + return /^0*$/.test(publicKey.trim()); +} + /** * Find the trust anchor that vouches for a manifest. Returns the matched * anchor (with anchor.publicKey === signer.publicKey) or null. * * Scope-matching uses a minimal glob: `*` at the end of the scope string - * matches any suffix. Empty/missing scope matches every plugin id. + * matches any suffix. Empty/missing scope matches every plugin id. Placeholder + * anchors (see {@link isPlaceholderKey}) never match. */ export function findAnchor( anchors: ReadonlyArray, @@ -143,6 +154,7 @@ export function findAnchor( now: number, ): TrustAnchor | null { for (const a of anchors) { + if (isPlaceholderKey(a.publicKey)) continue; if (a.publicKey !== signerPublicKey) continue; if (a.expiresAt && new Date(a.expiresAt).getTime() <= now) continue; if (!a.scope || a.scope === '*' || a.scope === pluginId) return a; @@ -224,7 +236,8 @@ export class PluginIntegrityVerifier { const sigBytes = hexToBytes(signed.signature); const msgBytes = hexToBytes(signed.manifestHash); const pubBytes = hexToBytes(signed.publicKey); - ok = await ed.verify(sigBytes, msgBytes, pubBytes); + // RFC 8032 strict mode: rejects small-order keys, which ZIP-215 accepts. + ok = await ed.verify(sigBytes, msgBytes, pubBytes, { zip215: false }); } catch { ok = false; } @@ -251,7 +264,7 @@ function hexToBytes(hex: string): Uint8Array { } interface NobleEd25519 { - verify(sig: Uint8Array, msg: Uint8Array, pub: Uint8Array): Promise; + verify(sig: Uint8Array, msg: Uint8Array, pub: Uint8Array, opts?: { zip215?: boolean }): Promise; etc: { sha512Sync?: (...m: Uint8Array[]) => Uint8Array }; } From 5bd949dfde740e0525a2beb0a9cf091c140e95f0 Mon Sep 17 00:00:00 2001 From: Dragan Spiridonov Date: Fri, 9 Oct 2026 20:04:26 +0200 Subject: [PATCH 12/43] fix(plugins): review follow-ups for registry trust fail-closed - smoke-plugin-registry-signature.mjs: follow the verifier rename to registrySignatureFailure and require the fail-closed call site `if (failure) return this.fallbackToBuiltIn(`, keeping full #1922 coverage. - verifyEd25519Signature verifies in RFC 8032 strict mode, and isPlaceholderSigningKey rejects every small-order or off-curve key, not only the all-zero one. - An unverified registry claims no official plugins and no verified authors; MCP transfer_plugin-* results carry the registry status. - Tests no longer assume the shipped trust anchor stays a placeholder. - Document the strict-mode asymmetry for unlisted packages in --help. --- scripts/smoke-plugin-registry-signature.mjs | 30 ++--- ...plugins-registry-trust-fail-closed.test.ts | 103 +++++++++++++++--- v3/@claude-flow/cli/src/commands/plugins.ts | 7 +- .../cli/src/mcp-tools/transfer-tools.ts | 17 +-- .../cli/src/plugins/store/discovery.ts | 27 ++++- .../cli/src/plugins/store/index.ts | 1 + .../cli/src/plugins/trust-policy.ts | 14 ++- .../cli/src/transfer/ipfs/client.ts | 5 +- .../plugin-integrity-verifier.test.ts | 31 +++--- 9 files changed, 176 insertions(+), 59 deletions(-) diff --git a/scripts/smoke-plugin-registry-signature.mjs b/scripts/smoke-plugin-registry-signature.mjs index ff996f9e54..b32f1ad6c4 100755 --- a/scripts/smoke-plugin-registry-signature.mjs +++ b/scripts/smoke-plugin-registry-signature.mjs @@ -18,13 +18,16 @@ * * [1/3] STATIC CONTRACT — the source file must: * - import `verifyEd25519Signature` from `transfer/ipfs/client.ts` - * - call it from the `verifyRegistrySignature` private method + * - call it from the `registrySignatureFailure` private method + * (formerly `verifyRegistrySignature`; returns the failure + * reason, or null when the signature verified) * - strip BOTH `registrySignature` AND `registryPublicKey` from * the registry copy before stringifying (canonical form) * - pin to the caller-supplied `expectedPublicKey`, NOT to the * served `registry.registryPublicKey` field * - the call site must `await` the verifier AND fail-closed - * (return demo registry / not just `console.warn`) + * (`if (failure) return this.fallbackToBuiltIn(...)` — the + * unverified, trust-stripped fallback; not just `console.warn`) * * [2/3] CRYPTO ROUND-TRIP — using the exact same Ed25519 scheme as * `signRegistry()` in @@ -38,8 +41,9 @@ * scenario the original report calls out) * * [3/3] CALL-SITE BYTE — the call site must contain `requireVerification` - * AND `await this.verifyRegistrySignature` AND a `return` (the - * fail-closed branch). A future regression that drops `await` + * AND `await this.registrySignatureFailure` AND + * `if (failure) return this.fallbackToBuiltIn(` (the fail-closed + * branch). A future regression that drops `await` * or that reverts to plain `console.warn` will be caught here. */ @@ -103,14 +107,14 @@ function extractMethodBody(source, methodSignatureRegex) { const body = extractMethodBody( src, - /private\s+async\s+verifyRegistrySignature\s*\(/, + /private\s+async\s+registrySignatureFailure\s*\(/, ); if (body) { if (/delete\s+\w+\.registrySignature/.test(body) && /delete\s+\w+\.registryPublicKey/.test(body)) { ok('canonicalization strips BOTH registrySignature AND registryPublicKey'); } else { fail( - 'verifyRegistrySignature must delete both signature fields before stringify', + 'registrySignatureFailure must delete both signature fields before stringify', 'attacker can otherwise re-sign by spreading the served fields back in', ); } @@ -118,7 +122,7 @@ if (body) { ok('canonical message is JSON.stringify of stripped registry'); } else { fail( - 'verifyRegistrySignature must JSON.stringify the stripped registry', + 'registrySignatureFailure must JSON.stringify the stripped registry', 'the signer uses plain JSON.stringify (no whitespace, no sort) — the verifier must match', ); } @@ -135,7 +139,7 @@ if (body) { ); } } else { - fail('verifyRegistrySignature method not found in async form'); + fail('registrySignatureFailure method not found in async form'); } // Old stub pattern must be GONE. A future regression that brings back @@ -282,16 +286,16 @@ const callSiteMatch = src.match( ); if (callSiteMatch) { const block = callSiteMatch[0]; - if (/await\s+this\.verifyRegistrySignature\(/.test(block)) { - ok('call site awaits verifyRegistrySignature'); + if (/await\s+this\.registrySignatureFailure\(/.test(block)) { + ok('call site awaits registrySignatureFailure'); } else { fail( 'call site does not await the async verifier', - 'without await, the Promise is truthy and verification is bypassed', + 'without await, the Promise is truthy and the verifier result is never read', ); } - if (/return\s+this\.createDemoRegistryAsync\(/.test(block) || /return\s+\w+/.test(block)) { - ok('call site fails closed (returns rather than continuing)'); + if (/if\s*\(\s*failure\s*\)\s*\{?\s*return\s+this\.fallbackToBuiltIn\(/.test(block)) { + ok('call site fails closed (if (failure) return this.fallbackToBuiltIn(...))'); } else { fail( 'call site must return/fall-back on verification failure (not just warn)', diff --git a/v3/@claude-flow/cli/__tests__/plugins-registry-trust-fail-closed.test.ts b/v3/@claude-flow/cli/__tests__/plugins-registry-trust-fail-closed.test.ts index 6c6d2382de..0af1bf841e 100644 --- a/v3/@claude-flow/cli/__tests__/plugins-registry-trust-fail-closed.test.ts +++ b/v3/@claude-flow/cli/__tests__/plugins-registry-trust-fail-closed.test.ts @@ -5,7 +5,10 @@ * install run npm lifecycle scripts and skip the permission gate. So: * - an unverified registry (unsigned, bad signature, placeholder pinned key, verification off) * and the built-in fallback list carry no registry trust; - * - a placeholder (all-zero) pinned key is never used to verify — it accepts a forged signature; + * - a placeholder pinned key (all-zero or any small-order point) is never used to verify, and the + * Ed25519 verifier runs in RFC 8032 strict mode; + * - an unverified registry claims no official plugins and no verified authors, and the MCP + * transfer_plugin-* tools report the registry status; * - CLAUDE_FLOW_STRICT_PLUGINS=true turns the fallback into an error and makes `plugins install` * refuse without --allow-unverified; * - `plugins install` never passes an unverified entry's trust, permissions or checksum on. @@ -40,12 +43,21 @@ import { PluginDiscoveryService } from '../src/plugins/store/discovery.js'; import { verifyEd25519Signature } from '../src/transfer/ipfs/client.js'; import { isPlaceholderSigningKey, isStrictPluginMode } from '../src/plugins/trust-policy.js'; import { pluginsCommand } from '../src/commands/plugins.js'; +import transferTools from '../src/mcp-tools/transfer-tools.js'; import type { CommandContext } from '../src/types.js'; import anchorsFile from '../src/plugins/trust/trust-anchors.json'; const ZERO_KEY = '0'.repeat(64); -// R = identity point, S = 0: verifies against any small-order key for every message (ZIP-215). -const FORGED_SIG = '01' + '0'.repeat(126); +// An ordinary Ed25519 public key (not small-order) with no known signer. +const REAL_KEY = 'ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c'; +// Small-order points: identity, order 2, order 8. +const SMALL_ORDER_KEYS = [ + '01' + '0'.repeat(62), + 'ec' + 'ff'.repeat(30) + '7f', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', +]; +// Known-bad signature fixture used against small-order keys. +const BAD_SIG = '01' + '0'.repeat(126); function entry(name: string, trustLevel = 'official') { return { @@ -110,25 +122,42 @@ afterEach(() => { }); describe('placeholder signing keys', () => { - it('the shipped trust anchor is a placeholder', () => { - expect(anchorsFile.anchors.length).toBeGreaterThan(0); - for (const a of anchorsFile.anchors) expect(isPlaceholderSigningKey(a.publicKey)).toBe(true); + it('a shipped trust anchor that is a placeholder leaves a registry pinned to it unverified', async () => { + // Holds whether or not maintainers have replaced the placeholder with a real key. + for (const a of anchorsFile.anchors) { + if (!isPlaceholderSigningKey(a.publicKey)) continue; + ipfs.registry = registryWith([entry('@claude-flow/a')], { registrySignature: BAD_SIG }); + const result = await serviceFor(`ed25519:${a.publicKey}`).discoverRegistry(); + expect(result.verified).toBe(false); + expect(result.unverifiedReason).toMatch(/placeholder/); + } }); - it('rejects missing, malformed and all-zero keys; accepts a real-looking key', () => { + it('rejects missing, malformed, off-curve, all-zero and small-order keys; accepts an ordinary key', () => { expect(isPlaceholderSigningKey(undefined)).toBe(true); expect(isPlaceholderSigningKey('')).toBe(true); expect(isPlaceholderSigningKey('ed25519:abc')).toBe(true); + expect(isPlaceholderSigningKey(`ed25519:${'ab'.repeat(32)}`)).toBe(true); expect(isPlaceholderSigningKey(`ed25519:${ZERO_KEY}`)).toBe(true); - expect(isPlaceholderSigningKey(`ed25519:${'ab'.repeat(32)}`)).toBe(false); + for (const k of SMALL_ORDER_KEYS) expect(isPlaceholderSigningKey(`ed25519:${k}`)).toBe(true); + expect(isPlaceholderSigningKey(`ed25519:${REAL_KEY}`)).toBe(false); }); - it('the all-zero key really does accept a forged signature (why it must never be verified against)', async () => { - expect(await verifyEd25519Signature('any message at all', FORGED_SIG, ZERO_KEY)).toBe(true); + it('verifyEd25519Signature rejects the bad-signature fixture for every small-order key (RFC 8032 strict)', async () => { + for (const k of [ZERO_KEY, ...SMALL_ORDER_KEYS]) { + expect(await verifyEd25519Signature('any message', BAD_SIG, k)).toBe(false); + } }); - it('a placeholder pinned key leaves the registry unverified even with a "valid" forged signature', async () => { - ipfs.registry = registryWith([entry('@claude-flow/evil')], { registrySignature: FORGED_SIG }); + it('a small-order pinned key is treated as a placeholder', async () => { + ipfs.registry = registryWith([entry('@claude-flow/evil')], { registrySignature: BAD_SIG }); + const result = await serviceFor(`ed25519:${SMALL_ORDER_KEYS[0]}`).discoverRegistry(); + expect(result.verified).toBe(false); + expect(result.unverifiedReason).toMatch(/placeholder/); + }); + + it('an all-zero pinned key leaves the registry unverified and its entries unlisted', async () => { + ipfs.registry = registryWith([entry('@claude-flow/evil')], { registrySignature: BAD_SIG }); const result = await serviceFor(`ed25519:${ZERO_KEY}`).discoverRegistry(); expect(result.verified).toBe(false); @@ -141,7 +170,7 @@ describe('placeholder signing keys', () => { describe('discovery: an unverified registry confers no trust', () => { it('an unsigned registry falls back to the built-in list, labelled demo and unverified, with trust stripped', async () => { ipfs.registry = registryWith([entry('@claude-flow/a')]); - const svc = serviceFor(`ed25519:${'ab'.repeat(32)}`); + const svc = serviceFor(`ed25519:${REAL_KEY}`); const first = await svc.discoverRegistry(); expect(first.success).toBe(true); @@ -157,11 +186,20 @@ describe('discovery: an unverified registry confers no trust', () => { expect(second.registry!.plugins.every((p) => p.trustLevel === 'unverified')).toBe(true); }); + it('an unverified registry lists no official plugins and no verified authors', async () => { + ipfs.registry = registryWith([entry('@claude-flow/a')]); + const result = await serviceFor(`ed25519:${REAL_KEY}`).discoverRegistry(); + expect(result.verified).toBe(false); + expect(result.registry!.official).toEqual([]); + expect(result.registry!.authors.every((a) => !a.verified)).toBe(true); + expect(result.registry!.plugins.every((p) => !p.author?.verified)).toBe(true); + }); + it('a signature that does not verify is not silently treated as the registry', async () => { const { signed } = await signRegistry(registryWith([entry('@claude-flow/a')])); ipfs.registry = signed; // Pinned key differs from the signer. - const result = await serviceFor(`ed25519:${'ab'.repeat(32)}`).discoverRegistry(); + const result = await serviceFor(`ed25519:${REAL_KEY}`).discoverRegistry(); expect(result.verified).toBe(false); expect(result.demo).toBe(true); expect(result.unverifiedReason).toMatch(/does not verify/); @@ -169,7 +207,7 @@ describe('discovery: an unverified registry confers no trust', () => { it('with verification disabled the fetched registry is used but every entry is unverified', async () => { ipfs.registry = registryWith([entry('@claude-flow/a')]); - const result = await serviceFor(`ed25519:${'ab'.repeat(32)}`, { requireVerification: false }).discoverRegistry(); + const result = await serviceFor(`ed25519:${REAL_KEY}`, { requireVerification: false }).discoverRegistry(); expect(result.success).toBe(true); expect(result.demo).toBeUndefined(); expect(result.verified).toBe(false); @@ -190,7 +228,7 @@ describe('discovery: an unverified registry confers no trust', () => { process.env.CLAUDE_FLOW_STRICT_PLUGINS = 'true'; expect(isStrictPluginMode()).toBe(true); ipfs.registry = registryWith([entry('@claude-flow/a')]); - const result = await serviceFor(`ed25519:${'ab'.repeat(32)}`).discoverRegistry(); + const result = await serviceFor(`ed25519:${REAL_KEY}`).discoverRegistry(); expect(result.success).toBe(false); expect(result.registry).toBeUndefined(); expect(result.verified).toBe(false); @@ -253,3 +291,36 @@ describe('plugins install: unverified registry entries get no registry trust', ( } }); }); + +describe('MCP transfer_plugin-* tools report registry status', () => { + const call = async (name: string, input: Record = {}) => { + const tool = transferTools.find((t) => t.name === name)!; + const res = await tool.handler(input as never); + return JSON.parse((res.content[0] as { text: string }).text); + }; + + beforeEach(() => { + // The default registry, served unsigned as the live CID is. + ipfs.registry = registryWith([entry('@claude-flow/neural')]); + }); + + it('transfer_plugin-official claims nothing as official when the registry is unverified', async () => { + const out = await call('transfer_plugin-official'); + expect(out.plugins).toEqual([]); + expect(out.registry.verified).toBe(false); + expect(out.registry.unverifiedReason).toMatch(/unsigned/); + }); + + it('transfer_plugin-featured, -search and -info carry the status and unverified entries', async () => { + const featured = await call('transfer_plugin-featured', { limit: 3 }); + expect(featured.registry.verified).toBe(false); + expect(featured.plugins.every((p: { trustLevel: string }) => p.trustLevel === 'unverified')).toBe(true); + + const search = await call('transfer_plugin-search', { query: 'neural' }); + expect(search.registry.verified).toBe(false); + + const info = await call('transfer_plugin-info', { name: '@claude-flow/neural' }); + expect(info.trustLevel).toBe('unverified'); + expect(info.registry).toEqual(expect.objectContaining({ verified: false })); + }); +}); diff --git a/v3/@claude-flow/cli/src/commands/plugins.ts b/v3/@claude-flow/cli/src/commands/plugins.ts index f7d94a7b58..0212e55683 100644 --- a/v3/@claude-flow/cli/src/commands/plugins.ts +++ b/v3/@claude-flow/cli/src/commands/plugins.ts @@ -141,6 +141,9 @@ const listCommand: Command = { if (official) { plugins = getOfficialPlugins(result.registry); title = 'Official Plugins'; + if (result.verified !== true) { + output.writeln(output.warning('No plugin is shown as official: only a verified registry can say which are.')); + } } else if (featured) { plugins = getFeaturedPlugins(result.registry); title = 'Featured Plugins'; @@ -262,7 +265,9 @@ const installCommand: Command = { type: 'boolean', description: 'With CLAUDE_FLOW_STRICT_PLUGINS=true, install from npm even though the plugin registry is not verified. ' + - 'The plugin still gets no registry trust.', + 'The plugin still gets no registry trust. Strict mode gates on the registry, not the package: while the ' + + 'registry is unverified every npm install is refused, listed or not; once it verifies, a package it does ' + + 'not list installs without this flag, but also without registry trust.', default: false, }, { name: 'registry', short: 'r', type: 'string', description: 'Registry to use' }, diff --git a/v3/@claude-flow/cli/src/mcp-tools/transfer-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/transfer-tools.ts index 8fccf73c82..e0a56ec7a9 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/transfer-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/transfer-tools.ts @@ -302,7 +302,7 @@ export const transferTools: MCPTool[] = [ if ((input as Record).category) { const v = validateIdentifier((input as Record).category, 'category'); if (!v.valid) return createResult({ error: v.error }, true); } if ((input as Record).type) { const v = validateIdentifier((input as Record).type, 'type'); if (!v.valid) return createResult({ error: v.error }, true); } try { - const { createPluginDiscoveryService, searchPlugins } = await import( + const { createPluginDiscoveryService, searchPlugins, registryStatus } = await import( '../plugins/store/index.js' ); const discovery = createPluginDiscoveryService(); @@ -312,7 +312,7 @@ export const transferTools: MCPTool[] = [ } const opts = input as Parameters[1]; const searchResult = searchPlugins(result.registry, opts); - return createResult(searchResult); + return createResult({ ...searchResult, registry: registryStatus(result) }); } catch (error) { return createResult({ error: (error as Error).message }, true); } @@ -337,7 +337,7 @@ export const transferTools: MCPTool[] = [ handler: async (input): Promise => { { const v = validatePackageName((input as { name: string }).name, 'name'); if (!v.valid) return createResult({ error: v.error }, true); } try { - const { createPluginDiscoveryService } = await import('../plugins/store/index.js'); + const { createPluginDiscoveryService, registryStatus } = await import('../plugins/store/index.js'); const discovery = createPluginDiscoveryService(); const result = await discovery.discoverRegistry(); if (!result.success || !result.registry) { @@ -348,7 +348,7 @@ export const transferTools: MCPTool[] = [ if (!plugin) { return createResult({ error: 'Plugin not found' }, true); } - return createResult(plugin); + return createResult({ ...plugin, registry: registryStatus(result) }); } catch (error) { return createResult({ error: (error as Error).message }, true); } @@ -371,7 +371,7 @@ export const transferTools: MCPTool[] = [ }, handler: async (input): Promise => { try { - const { createPluginDiscoveryService, getFeaturedPlugins } = await import( + const { createPluginDiscoveryService, getFeaturedPlugins, registryStatus } = await import( '../plugins/store/index.js' ); const discovery = createPluginDiscoveryService(); @@ -381,7 +381,7 @@ export const transferTools: MCPTool[] = [ } const featured = getFeaturedPlugins(result.registry); const limit = (input as { limit?: number }).limit || 10; - return createResult(featured.slice(0, limit)); + return createResult({ plugins: featured.slice(0, limit), registry: registryStatus(result) }); } catch (error) { return createResult({ error: (error as Error).message }, true); } @@ -399,7 +399,7 @@ export const transferTools: MCPTool[] = [ }, handler: async (): Promise => { try { - const { createPluginDiscoveryService, getOfficialPlugins } = await import( + const { createPluginDiscoveryService, getOfficialPlugins, registryStatus } = await import( '../plugins/store/index.js' ); const discovery = createPluginDiscoveryService(); @@ -407,8 +407,9 @@ export const transferTools: MCPTool[] = [ if (!result.success || !result.registry) { return createResult({ error: result.error || 'Failed to discover registry' }, true); } + // Empty when the registry is unverified: an unsigned "official" list proves nothing. const official = getOfficialPlugins(result.registry); - return createResult(official); + return createResult({ plugins: official, registry: registryStatus(result) }); } catch (error) { return createResult({ error: (error as Error).message }, true); } diff --git a/v3/@claude-flow/cli/src/plugins/store/discovery.ts b/v3/@claude-flow/cli/src/plugins/store/discovery.ts index b270172d92..b5574f1c27 100644 --- a/v3/@claude-flow/cli/src/plugins/store/discovery.ts +++ b/v3/@claude-flow/cli/src/plugins/store/discovery.ts @@ -130,13 +130,34 @@ export interface PluginDiscoveryResult { } /** - * Strip registry-asserted trust from a registry that was not verified. Its trust labels are - * just claims made by whoever served (or hardcoded) the list. + * Strip registry-asserted trust from a registry that was not verified. Its trust labels, its + * `official` list and its author verification are just claims made by whoever served (or + * hardcoded) the list. */ function withoutRegistryTrust(registry: PluginRegistry): PluginRegistry { return { ...registry, - plugins: registry.plugins.map((p) => ({ ...p, trustLevel: 'unverified' as const, verified: false })), + plugins: registry.plugins.map((p) => ({ + ...p, + trustLevel: 'unverified' as const, + verified: false, + ...(p.author ? { author: { ...p.author, verified: false } } : {}), + })), + official: [], + authors: (registry.authors ?? []).map((a) => ({ ...a, verified: false })), + }; +} + +/** Registry-level verification status, for callers that report registry data. */ +export function registryStatus(result: PluginDiscoveryResult): { + verified: boolean; + unverifiedReason?: string; + source?: string; +} { + return { + verified: result.verified === true, + ...(result.verified === true ? {} : { unverifiedReason: result.unverifiedReason ?? 'registry not verified' }), + ...(result.source ? { source: result.source } : {}), }; } diff --git a/v3/@claude-flow/cli/src/plugins/store/index.ts b/v3/@claude-flow/cli/src/plugins/store/index.ts index 48a18123e4..839058b1b1 100644 --- a/v3/@claude-flow/cli/src/plugins/store/index.ts +++ b/v3/@claude-flow/cli/src/plugins/store/index.ts @@ -17,6 +17,7 @@ export { PluginDiscoveryService, createPluginDiscoveryService, DEFAULT_PLUGIN_STORE_CONFIG, + registryStatus, type PluginDiscoveryResult, } from './discovery.js'; diff --git a/v3/@claude-flow/cli/src/plugins/trust-policy.ts b/v3/@claude-flow/cli/src/plugins/trust-policy.ts index be69f3c20f..8da27331b0 100644 --- a/v3/@claude-flow/cli/src/plugins/trust-policy.ts +++ b/v3/@claude-flow/cli/src/plugins/trust-policy.ts @@ -7,6 +7,7 @@ */ import { createHash } from 'crypto'; +import { ExtendedPoint } from '@noble/ed25519'; /** * Permissions a plugin may declare and still have its hooks and commands @@ -130,14 +131,19 @@ export function isStrictPluginMode(env: NodeJS.ProcessEnv = process.env): boolea /** * A signing key that cannot vouch for anything: missing, not 32 bytes of hex, - * or all zeros (the placeholder in `trust/trust-anchors.json`). The all-zero - * key is also a small-order Ed25519 point, for which a fixed forged signature - * verifies against every message under ZIP-215 rules, so it must never be + * not a curve point, or a small-order point — which includes the all-zero + * placeholder in `trust/trust-anchors.json`. Signatures can be forged against + * small-order keys under ZIP-215 verification, so such a key must never be * handed to a verifier. */ export function isPlaceholderSigningKey(key: unknown): boolean { if (typeof key !== 'string') return true; const hex = key.trim().replace(/^ed25519:/i, ''); if (!/^[0-9a-f]{64}$/i.test(hex)) return true; - return /^0+$/.test(hex); + try { + // zip215=true decodes every encoding a lenient verifier would accept. + return ExtendedPoint.fromHex(hex, true).isSmallOrder(); + } catch { + return true; + } } diff --git a/v3/@claude-flow/cli/src/transfer/ipfs/client.ts b/v3/@claude-flow/cli/src/transfer/ipfs/client.ts index e7300c4ab1..ba4b8dec30 100644 --- a/v3/@claude-flow/cli/src/transfer/ipfs/client.ts +++ b/v3/@claude-flow/cli/src/transfer/ipfs/client.ts @@ -334,10 +334,13 @@ export async function verifyEd25519Signature( // Handle prefixed public key (e.g., "ed25519:abc123...") const pubKeyHex = publicKey.replace(/^ed25519:/, ''); + // RFC 8032 strict mode: rejects small-order public keys, against which + // signatures can be forged under the library's default ZIP-215 rules. const isValid = await ed.verifyAsync( Buffer.from(signature, 'hex'), new TextEncoder().encode(message), - Buffer.from(pubKeyHex, 'hex') + Buffer.from(pubKeyHex, 'hex'), + { zip215: false } ); return isValid; diff --git a/v3/@claude-flow/security/__tests__/plugin-integrity-verifier.test.ts b/v3/@claude-flow/security/__tests__/plugin-integrity-verifier.test.ts index a2c9602f53..84aa4b3c3b 100644 --- a/v3/@claude-flow/security/__tests__/plugin-integrity-verifier.test.ts +++ b/v3/@claude-flow/security/__tests__/plugin-integrity-verifier.test.ts @@ -10,9 +10,9 @@ * - verify reports `unknown-signer` when the key isn't in trust anchors * - verify reports `pass` on a valid round-trip sign → verify * - verify reports `signature-invalid` on a flipped signature byte - * - the shipped placeholder (all-zero) anchor never vouches, and small-order - * keys are rejected even when anchored (a forged R=identity, S=0 signature - * verifies against them for every message under ZIP-215) + * - a placeholder (all-zero) anchor, such as the one shipped in + * trust-anchors.json, never vouches, and small-order keys are rejected even + * when anchored (ZIP-215 verification would accept forged signatures) */ import { describe, it, expect, beforeAll } from 'vitest'; @@ -207,9 +207,9 @@ describe('PluginIntegrityVerifier.verify', () => { describe('placeholder and small-order signing keys', () => { const ZERO_KEY = '0'.repeat(64); - // y = -1: the order-2 point (0, -1). + // A small-order point. const ORDER_TWO_KEY = 'ec' + 'ff'.repeat(30) + '7f'; - // R = identity, S = 0. + // Known-bad signature fixture used against small-order keys. const FORGED_SIG = '01' + '0'.repeat(126); function forged(publicKey: string): SignedPluginManifest { @@ -223,21 +223,26 @@ describe('placeholder and small-order signing keys', () => { expect(isPlaceholderKey(ORDER_TWO_KEY)).toBe(false); }); - it('the shipped trust-anchors.json placeholder never vouches for a forged manifest', async () => { + it('a placeholder anchor never vouches for a forged manifest', async () => { + const r = await new PluginIntegrityVerifier({ trustAnchors: anchorsFor(ZERO_KEY) }).verify(forged(ZERO_KEY)); + expect(r.status).toBe('unknown-signer'); + }); + + it('no placeholder anchor shipped in trust-anchors.json vouches for anything', async () => { + // Holds whether or not maintainers have replaced the placeholder with a real key. const shipped = JSON.parse( readFileSync(new URL('../../cli/src/plugins/trust/trust-anchors.json', import.meta.url), 'utf-8'), ) as TrustAnchors; - expect(shipped.anchors.some((a) => a.publicKey === ZERO_KEY)).toBe(true); - expect(findAnchor(shipped.anchors, '@claude-flow/evil', ZERO_KEY, Date.now())).toBeNull(); - - const r = await new PluginIntegrityVerifier({ trustAnchors: shipped }).verify(forged(ZERO_KEY)); - expect(r.status).not.toBe('pass'); - expect(r.status).toBe('unknown-signer'); + for (const a of shipped.anchors.filter((x) => isPlaceholderKey(x.publicKey))) { + expect(findAnchor(shipped.anchors, '@claude-flow/evil', a.publicKey, Date.now())).toBeNull(); + const r = await new PluginIntegrityVerifier({ trustAnchors: shipped }).verify(forged(a.publicKey)); + expect(r.status).not.toBe('pass'); + } }); it('rejects a forged signature even when a small-order key is anchored', async () => { if (!ed) { console.warn('@noble/ed25519 unavailable — skipping'); return; } - // Sanity: noble's default (ZIP-215) verify accepts the forgery against this key. + // Precondition: the default (lenient) verify mode accepts this fixture for this key. const m = forged(ORDER_TWO_KEY); expect(await ed.verifyAsync(hexBytes(FORGED_SIG), hexBytes(m.manifestHash), hexBytes(ORDER_TWO_KEY))).toBe(true); From 4cc18753f9e282109e42c9737b9ecf9633d6eb42 Mon Sep 17 00:00:00 2001 From: Dragan Spiridonov Date: Fri, 9 Oct 2026 19:55:46 +0200 Subject: [PATCH 13/43] fix(helpers): resolve modules from the helper root and keep session writes in the project A home-level helper can serve whatever project Claude Code opens, so everything that project controls is untrusted input to the helper. auto-memory-hook.mjs / learning-service.mjs: since the #3286 change every module-resolution strategy (memory-package.json sidecar, local v3 dist, createRequire, node_modules walk-up, agentic-flow embedder) was rooted at CLAUDE_PROJECT_DIR, so a project could choose which JavaScript a home-level helper imports. Add MODULE_ROOT (the helper's install root) for module resolution; PROJECT_ROOT stays data-only, so #3286 still holds. session.cjs: end() archived to `${session.id}.json` with the id taken from the project's current.json, so a crafted id could write outside the session directory, and writes followed symlinks. The archive name must now match session-; current.json counts only as a regular file (lstat); writes use an exclusive temp file + rename; and the project session directory must resolve inside the project. Applied to the packaged helper, both generators (generateSessionManager / generateCrossPlatformSessionManager) and the repository copy. Tests: helper-module-root-trust and session-helper-trust (16 of 21 cases fail on main, all pass now); the #3286 test now places the mock memory package at the helper root. The helpers manifest is not re-signed here: auto-memory-hook.mjs changed, so it needs `scripts/sign-helpers.mjs` with the release key. --- .claude/helpers/auto-memory-hook.mjs | 21 +-- .claude/helpers/learning-service.mjs | 7 +- .claude/helpers/session.cjs | 56 ++++++-- .../cli/.claude/helpers/auto-memory-hook.mjs | 21 +-- .../cli/.claude/helpers/learning-service.mjs | 7 +- .../cli/.claude/helpers/session.cjs | 50 +++++-- .../auto-memory-project-root-3286.test.ts | 10 +- .../helper-module-root-trust.test.ts | 99 ++++++++++++++ .../__tests__/session-helper-trust.test.ts | 123 +++++++++++++++++ .../cli/src/init/helpers-generator.ts | 126 ++++++++++++++---- 10 files changed, 447 insertions(+), 73 deletions(-) create mode 100644 v3/@claude-flow/cli/__tests__/helper-module-root-trust.test.ts create mode 100644 v3/@claude-flow/cli/__tests__/session-helper-trust.test.ts diff --git a/.claude/helpers/auto-memory-hook.mjs b/.claude/helpers/auto-memory-hook.mjs index a83ce6cece..58ea812470 100755 --- a/.claude/helpers/auto-memory-hook.mjs +++ b/.claude/helpers/auto-memory-hook.mjs @@ -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'); diff --git a/.claude/helpers/learning-service.mjs b/.claude/helpers/learning-service.mjs index 93fdc169f2..00fba977f5 100755 --- a/.claude/helpers/learning-service.mjs +++ b/.claude/helpers/learning-service.mjs @@ -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); diff --git a/.claude/helpers/session.cjs b/.claude/helpers/session.cjs index ffe53a9b2a..3647afada0 100644 --- a/.claude/helpers/session.cjs +++ b/.claude/helpers/session.cjs @@ -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,40 @@ 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()); + const rel = path.relative(root, fs.realpathSync(SESSION_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 }); @@ -48,25 +83,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 +109,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 +134,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; } diff --git a/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs b/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs index 1fbf9b00d0..85917f9167 100755 --- a/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs +++ b/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs @@ -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/cli@latest) 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'); diff --git a/v3/@claude-flow/cli/.claude/helpers/learning-service.mjs b/v3/@claude-flow/cli/.claude/helpers/learning-service.mjs index bbe2fac8ab..ad68c0f7c7 100755 --- a/v3/@claude-flow/cli/.claude/helpers/learning-service.mjs +++ b/v3/@claude-flow/cli/.claude/helpers/learning-service.mjs @@ -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); diff --git a/v3/@claude-flow/cli/.claude/helpers/session.cjs b/v3/@claude-flow/cli/.claude/helpers/session.cjs index 2e42c8118b..3f91aa523e 100644 --- a/v3/@claude-flow/cli/.claude/helpers/session.cjs +++ b/v3/@claude-flow/cli/.claude/helpers/session.cjs @@ -6,9 +6,32 @@ const fs = require('fs'); const path = require('path'); +const crypto = require('crypto'); const SESSION_DIR = path.join(process.cwd(), '.claude-flow', 'sessions'); 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 session directory must resolve inside the project (no symlinked escape). +function assertSessionDirContained() { + const root = fs.realpathSync(process.cwd()); + const rel = path.relative(root, fs.realpathSync(SESSION_DIR)); + if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) { + throw new Error('Session directory resolves outside the project'); + } +} // #2307: Atomic write — serialize to a per-process temp file, then rename() // into place. rename() is atomic on the same filesystem, so concurrent writers @@ -18,9 +41,12 @@ const SESSION_FILE = path.join(SESSION_DIR, 'current.json'); // tail dangling past the end (valid JSON + trailing garbage = parse error). // Temp name includes process.pid so concurrent writers don't collide on it. // Same class as #1707 (metrics) / #1637 (daemon-state) — session.js was missed. +// The temp file is created exclusively (never through a planted symlink) and +// rename() replaces a symlinked target instead of writing through it. function atomicWrite(file, data) { - const tmp = `${file}.tmp.${process.pid}`; - fs.writeFileSync(tmp, data); + assertSessionDirContained(); + const tmp = `${file}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; + fs.writeFileSync(tmp, data, { flag: 'wx' }); fs.renameSync(tmp, file); } @@ -48,7 +74,7 @@ const commands = { }, restore: () => { - if (!fs.existsSync(SESSION_FILE)) { + if (!hasSessionFile()) { console.log('No session to restore'); return null; } @@ -70,7 +96,7 @@ const commands = { }, end: () => { - if (!fs.existsSync(SESSION_FILE)) { + if (!hasSessionFile()) { console.log('No active session'); return null; } @@ -79,12 +105,12 @@ const commands = { session.endedAt = new Date().toISOString(); session.duration = Date.now() - new Date(session.startedAt).getTime(); - // Archive session - const archivePath = path.join(SESSION_DIR, `${session.id}.json`); - atomicWrite(archivePath, JSON.stringify(session, null, 2)); + // Archive session 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`); console.log(`Metrics: ${JSON.stringify(session.metrics)}`); @@ -92,7 +118,7 @@ const commands = { }, status: () => { - if (!fs.existsSync(SESSION_FILE)) { + if (!hasSessionFile()) { console.log('No active session'); return null; } @@ -109,7 +135,7 @@ const commands = { }, update: (key, value) => { - if (!fs.existsSync(SESSION_FILE)) { + if (!hasSessionFile()) { console.log('No active session'); return null; } @@ -123,7 +149,7 @@ const commands = { }, get: (key) => { - if (!fs.existsSync(SESSION_FILE)) return null; + if (!hasSessionFile()) return null; try { const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); return key ? (session.context || {})[key] : session.context; @@ -131,7 +157,7 @@ const commands = { }, metric: (name) => { - if (!fs.existsSync(SESSION_FILE)) { + if (!hasSessionFile()) { return null; } diff --git a/v3/@claude-flow/cli/__tests__/auto-memory-project-root-3286.test.ts b/v3/@claude-flow/cli/__tests__/auto-memory-project-root-3286.test.ts index 8a8b6bda37..428ae55659 100644 --- a/v3/@claude-flow/cli/__tests__/auto-memory-project-root-3286.test.ts +++ b/v3/@claude-flow/cli/__tests__/auto-memory-project-root-3286.test.ts @@ -46,7 +46,9 @@ describe('#3286 auto-memory project root', () => { for (const [name, source] of [['package', packageHook], ['repository', dogfoodHook]] as const) { it(`${name} helper imports and syncs into the project when invoked from HOME`, () => { const { project, home, hook } = fixture(source); - const mockMemory = join(project, 'mock-memory.mjs'); + // The memory package resolves from the helper's install root (HOME here), + // never from the project; data still lands in the project. + const mockMemory = join(home, 'mock-memory.mjs'); writeFileSync(mockMemory, ` import { writeFileSync } from 'node:fs'; export class AutoMemoryBridge { @@ -62,14 +64,14 @@ export class AutoMemoryBridge { async curateIndex() {} } `); - mkdirSync(join(project, '.claude-flow'), { recursive: true }); - writeFileSync(join(project, '.claude-flow', 'memory-package.json'), JSON.stringify({ distPath: mockMemory })); + mkdirSync(join(home, '.claude-flow'), { recursive: true }); + writeFileSync(join(home, '.claude-flow', 'memory-package.json'), JSON.stringify({ distPath: mockMemory })); expect(run(hook, project, 'import')).toContain('Imported 1 entries'); const store = join(project, '.claude-flow', 'data', 'auto-memory-store.json'); expect(JSON.parse(readFileSync(store, 'utf8'))[0].content).toBe(project); expect(run(hook, project, 'sync')).toContain('Synced 1 entries'); - expect(readFileSync(join(project, 'sync-root.txt'), 'utf8')).toBe(project); + expect(readFileSync(join(home, 'sync-root.txt'), 'utf8')).toBe(project); expect(existsSync(join(home, '.claude-flow', 'data', 'auto-memory-store.json'))).toBe(false); }); } diff --git a/v3/@claude-flow/cli/__tests__/helper-module-root-trust.test.ts b/v3/@claude-flow/cli/__tests__/helper-module-root-trust.test.ts new file mode 100644 index 0000000000..fbd9445617 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/helper-module-root-trust.test.ts @@ -0,0 +1,99 @@ +/** + * A home-level helper can serve an untrusted project: CLAUDE_PROJECT_DIR picks + * where data goes, never which JavaScript is imported. Executable modules must + * resolve from the helper's own install root. + */ +import { afterEach, describe, expect, it } from 'vitest'; +import { spawnSync } from 'node:child_process'; +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { generateAutoMemoryHook } from '../src/init/helpers-generator.js'; + +const here = dirname(fileURLToPath(import.meta.url)); +const packageHelpers = resolve(here, '../.claude/helpers'); +const dogfoodHelpers = resolve(here, '../../../../.claude/helpers'); +const tempRoots: string[] = []; + +afterEach(() => { + for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +/** A module that leaves a marker file if it is ever imported. */ +function payload(marker: string): string { + return `import { writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(marker)}, 'executed');\n` + + 'export class AutoMemoryBridge {}\n'; +} + +/** Plant a payload in every location the memory resolver has probed from the project. */ +function plantProject(project: string, marker: string) { + const write = (file: string, content: string) => { + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, content); + }; + write(join(project, 'evil-sidecar.mjs'), payload(marker)); + write(join(project, '.claude-flow', 'memory-package.json'), JSON.stringify({ distPath: join(project, 'evil-sidecar.mjs') })); + write(join(project, 'v3', '@claude-flow', 'memory', 'dist', 'index.js'), payload(marker)); + write(join(project, 'package.json'), JSON.stringify({ name: 'untrusted', type: 'module' })); + const pkg = join(project, 'node_modules', '@claude-flow', 'memory'); + write(join(pkg, 'package.json'), JSON.stringify({ name: '@claude-flow/memory', type: 'module', main: 'dist/index.js' })); + write(join(pkg, 'dist', 'index.js'), payload(marker)); +} + +function fixture(source: string | null) { + const root = mkdtempSync(join(tmpdir(), 'ruflo-module-root-')); + tempRoots.push(root); + const project = join(root, 'project'); + const home = join(root, 'home'); + const hook = join(home, '.claude', 'helpers', 'auto-memory-hook.mjs'); + const marker = join(root, 'payload-executed'); + mkdirSync(dirname(hook), { recursive: true }); + if (source) copyFileSync(source, hook); + else writeFileSync(hook, generateAutoMemoryHook()); + plantProject(project, marker); + return { project, hook, marker }; +} + +function run(hook: string, project: string, command: string) { + const result = spawnSync(process.execPath, [hook, command], { + cwd: project, + env: { ...process.env, CLAUDE_PROJECT_DIR: project }, + encoding: 'utf8', + timeout: 10_000, + }); + expect(result.error).toBeUndefined(); + return result; +} + +describe('auto-memory-hook resolves modules from the helper root only', () => { + const sources = [ + ['package', join(packageHelpers, 'auto-memory-hook.mjs')], + ['repository', join(dogfoodHelpers, 'auto-memory-hook.mjs')], + ['generated fallback', null], + ] as const; + + for (const [name, source] of sources) { + it(`${name} helper never imports project code from a home-level install`, () => { + const { project, hook, marker } = fixture(source); + for (const command of ['import', 'sync', 'status']) { + run(hook, project, command); + expect(existsSync(marker), `${command} executed a project module`).toBe(false); + } + }); + } + // Project data placement for home-level helpers is covered by + // auto-memory-project-root-3286.test.ts. +}); + +describe('learning-service resolves modules from the helper root only', () => { + for (const [name, dir] of [['package', packageHelpers], ['repository', dogfoodHelpers]] as const) { + it(`${name} helper builds import paths from MODULE_ROOT`, () => { + const source = readFileSync(join(dir, 'learning-service.mjs'), 'utf8'); + expect(source).toContain("const MODULE_ROOT = join(__dirname, '../..');"); + expect(source).toMatch(/join\(MODULE_ROOT, 'node_modules\/agentic-flow\//); + expect(source).not.toMatch(/join\(PROJECT_ROOT, 'node_modules/); + }); + } +}); diff --git a/v3/@claude-flow/cli/__tests__/session-helper-trust.test.ts b/v3/@claude-flow/cli/__tests__/session-helper-trust.test.ts new file mode 100644 index 0000000000..d8e8f8ad81 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/session-helper-trust.test.ts @@ -0,0 +1,123 @@ +/** + * session.cjs keeps its state in /.claude-flow/sessions/current.json, + * which the opened project controls. Its contents must never steer a write + * outside that session directory. + */ +import { afterEach, describe, expect, it } from 'vitest'; +import { spawnSync } from 'node:child_process'; +import { + copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { generateCrossPlatformSessionManager, generateSessionManager } from '../src/init/helpers-generator.js'; + +const here = dirname(fileURLToPath(import.meta.url)); +const tempRoots: string[] = []; + +afterEach(() => { + for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +const sources: ReadonlyArray string | null, string | null]> = [ + ['package', () => null, resolve(here, '../.claude/helpers/session.cjs')], + ['repository', () => null, resolve(here, '../../../../.claude/helpers/session.cjs')], + ['generated', generateSessionManager, null], + ['generated cross-platform', generateCrossPlatformSessionManager, null], +]; + +function fixture(generate: () => string | null, source: string | null) { + const root = mkdtempSync(join(tmpdir(), 'ruflo-session-trust-')); + tempRoots.push(root); + const project = join(root, 'project'); + const home = join(root, 'home'); + const outside = join(root, 'outside'); + const helper = join(root, 'helpers', 'session.cjs'); + const sessions = join(project, '.claude-flow', 'sessions'); + for (const dir of [project, home, outside, dirname(helper)]) mkdirSync(dir, { recursive: true }); + if (source) copyFileSync(source, helper); + else writeFileSync(helper, generate() as string); + return { root, project, home, outside, helper, sessions }; +} + +function run(f: ReturnType, ...args: string[]) { + const result = spawnSync(process.execPath, [f.helper, ...args], { + cwd: f.project, + env: { ...process.env, HOME: f.home, USERPROFILE: f.home, APPDATA: f.home }, + encoding: 'utf8', + timeout: 10_000, + }); + expect(result.error).toBeUndefined(); + return result; +} + +function writeCurrent(sessions: string, session: Record) { + mkdirSync(sessions, { recursive: true }); + writeFileSync(join(sessions, 'current.json'), JSON.stringify(session)); +} + +describe('session helper keeps writes inside the project session dir', () => { + for (const [name, generate, source] of sources) { + describe(name, () => { + it('a crafted session id cannot choose the archive path', () => { + const f = fixture(generate, source); + const escape = join(f.outside, 'escaped'); + writeCurrent(f.sessions, { + id: `../../../outside/escaped`, + startedAt: new Date().toISOString(), + metrics: { edits: 0 }, + }); + + run(f, 'end'); + + expect(existsSync(`${escape}.json`)).toBe(false); + expect(readdirSync(f.outside)).toEqual([]); + const archived = readdirSync(f.sessions); + expect(archived).toHaveLength(1); + expect(archived[0]).toMatch(/^session-\d+\.json$/); + }); + + it('never writes through a symlinked current.json', () => { + const f = fixture(generate, source); + const target = join(f.outside, 'target.json'); + const original = JSON.stringify({ id: 'session-1', startedAt: new Date().toISOString(), metrics: { edits: 0 } }); + writeFileSync(target, original); + mkdirSync(f.sessions, { recursive: true }); + symlinkSync(target, join(f.sessions, 'current.json')); + + run(f, 'restore'); + run(f, 'end'); + + expect(readFileSync(target, 'utf8')).toBe(original); + expect(readdirSync(f.outside)).toEqual(['target.json']); + }); + + it('refuses a session directory that resolves outside the project', () => { + const f = fixture(generate, source); + mkdirSync(join(f.project, '.claude-flow'), { recursive: true }); + symlinkSync(f.outside, f.sessions, 'dir'); + + run(f, 'start'); + + expect(readdirSync(f.outside)).toEqual([]); + }); + + it('keeps the normal start / restore / end lifecycle working', () => { + const f = fixture(generate, source); + mkdirSync(join(f.project, '.claude-flow'), { recursive: true }); + + expect(run(f, 'start').stdout).toMatch(/Session started: session-\d+/); + expect(run(f, 'restore').stdout).toMatch(/Session restored: session-\d+/); + const ended = run(f, 'end').stdout; + const id = /Session ended: (session-\d+)/.exec(ended)?.[1]; + + expect(id).toBeDefined(); + expect(existsSync(join(f.sessions, `${id}.json`))).toBe(true); + expect(existsSync(join(f.sessions, 'current.json'))).toBe(false); + expect(readdirSync(f.sessions).filter((n) => n.includes('.tmp'))).toEqual([]); + }); + }); + } +}); diff --git a/v3/@claude-flow/cli/src/init/helpers-generator.ts b/v3/@claude-flow/cli/src/init/helpers-generator.ts index e7e3846864..e7ee6972f4 100644 --- a/v3/@claude-flow/cli/src/init/helpers-generator.ts +++ b/v3/@claude-flow/cli/src/init/helpers-generator.ts @@ -132,10 +132,43 @@ export function generateSessionManager(): string { const fs = require('fs'); const path = require('path'); +const crypto = require('crypto'); const SESSION_DIR = path.join(process.cwd(), '.claude-flow', 'sessions'); 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 session directory must resolve inside the project (no symlinked escape). +function assertSessionDirContained() { + const root = fs.realpathSync(process.cwd()); + const rel = path.relative(root, fs.realpathSync(SESSION_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); +} + const commands = { start: () => { const sessionId = \`session-\${Date.now()}\`; @@ -153,28 +186,28 @@ const commands = { }; fs.mkdirSync(SESSION_DIR, { recursive: true }); - 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; } @@ -183,12 +216,12 @@ const commands = { session.endedAt = new Date().toISOString(); session.duration = Date.now() - new Date(session.startedAt).getTime(); - // Archive session - const archivePath = path.join(SESSION_DIR, \`\${session.id}.json\`); - fs.writeFileSync(archivePath, JSON.stringify(session, null, 2)); + // Archive session 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\`); console.log(\`Metrics: \${JSON.stringify(session.metrics)}\`); @@ -196,7 +229,7 @@ const commands = { }, status: () => { - if (!fs.existsSync(SESSION_FILE)) { + if (!hasSessionFile()) { console.log('No active session'); return null; } @@ -213,7 +246,7 @@ const commands = { }, update: (key, value) => { - if (!fs.existsSync(SESSION_FILE)) { + if (!hasSessionFile()) { console.log('No active session'); return null; } @@ -221,20 +254,20 @@ const commands = { const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); session.context[key] = value; session.updatedAt = new Date().toISOString(); - fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2)); + atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2)); return session; }, 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; @@ -1168,9 +1201,12 @@ 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. 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', 'data'); const STORE_PATH = join(DATA_DIR, 'auto-memory-store.json'); @@ -1182,7 +1218,7 @@ const dim = (msg) => console.log(\` \${DIM}\${msg}\${RESET}\`); // #2545: fail LOUD instead of a silent dim skip when @claude-flow/memory is // unresolvable — self-learning imports are a no-op and the user must be told. function warnMemoryUnavailable() { - const l1 = \`[AutoMemory] @claude-flow/memory not resolvable from \${PROJECT_ROOT} — self-learning imports are DISABLED.\`; + const l1 = \`[AutoMemory] @claude-flow/memory not resolvable from \${MODULE_ROOT} — self-learning imports are DISABLED.\`; const l2 = ' Fix: npm i -D @claude-flow/memory (or re-run: npx ruflo@latest init, then npx ruflo@latest doctor --fix)'; console.log(\`\${YELLOW}\${l1}\${RESET}\`); console.log(\`\${YELLOW}\${l2}\${RESET}\`); @@ -1197,7 +1233,7 @@ async function loadMemoryPackage() { // path @claude-flow/memory lands in the npx cache (unreachable by walk-up), so // init records its absolute path here — the only strategy that works there. 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 && rec.distPath && existsSync(rec.distPath)) { @@ -1210,15 +1246,15 @@ 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 */ } // Strategy 2: ESM import (works when @claude-flow/memory is a direct dependency) try { return await import('@claude-flow/memory'); } catch { /* fall through */ } - // Strategy 3: Walk up from PROJECT_ROOT looking for the package in any node_modules - let searchDir = PROJECT_ROOT; + // Strategy 3: Walk up from MODULE_ROOT looking for the package 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'); @@ -1419,6 +1455,7 @@ export function generateCrossPlatformSessionManager(): string { const fs = require('fs'); const path = require('path'); +const crypto = require('crypto'); const os = require('os'); // Platform-specific paths @@ -1445,6 +1482,40 @@ 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()); + const rel = path.relative(root, fs.realpathSync(SESSION_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); +} + // Ensure directory exists function ensureDir(dir) { if (!fs.existsSync(dir)) { @@ -1464,25 +1535,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; } @@ -1490,17 +1561,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; } From d1d9df0891390f7f6766e85d00674f7fabaeb9b0 Mon Sep 17 00:00:00 2001 From: Dragan Spiridonov Date: Fri, 9 Oct 2026 20:10:39 +0200 Subject: [PATCH 14/43] fix(init): pin user-level hook and statusline commands to $HOME helpers Settings written to ~/.claude/settings.json apply to every project the user opens. The #1943 probe ran `$CLAUDE_PROJECT_DIR/.claude/helpers/