Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix: EventStore missing snapshot, git identity whitespace paths, Porter step 4, rate limiter stats labels

ruvce1fcbca662b
diff --git a/v3/@claude-flow/cli/__tests__/lucene-bm25-porter-step4-3859.test.ts b/v3/@claude-flow/cli/__tests__/lucene-bm25-porter-step4-3859.test.ts
new file mode 100644
index 0000000000..96e42ccafb
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/lucene-bm25-porter-step4-3859.test.ts
@@ -0,0 +1,34 @@
+import { describe, it, expect } from 'vitest';
+import {
+ porterStem,
+ luceneTokenize,
+ buildLuceneCorpusStats,
+ luceneBM25,
+} from '../src/memory/lucene-bm25.js';
+
+describe('#3859 — Porter step 4 uses the longest matching suffix once', () => {
+ it('does not fall through to a shorter suffix when the longest fails its measure condition', () => {
+ // "ment" matches (stem "argu", m=1 -> condition fails); "ent" must NOT then be tried.
+ expect(porterStem('argument')).toBe('argument');
+ expect(porterStem('agreement')).toBe('agreement');
+ expect(porterStem('arguments')).toBe('argument');
+ });
+
+ it('still strips suffixes whose longest match satisfies the condition', () => {
+ expect(porterStem('adjustment')).toBe('adjust');
+ expect(porterStem('replacement')).toBe('replac');
+ expect(porterStem('adoption')).toBe('adopt');
+ expect(porterStem('homologous')).toBe('homolog');
+ expect(porterStem('communism')).toBe('commun');
+ });
+
+ it('does not collapse distinct words onto one BM25 token', () => {
+ const docs = ['argument', 'arguments', 'argum'].map(luceneTokenize);
+ expect(docs[0]).toEqual(docs[1]);
+ expect(docs[2]).not.toEqual(docs[0]);
+ const stats = buildLuceneCorpusStats(docs);
+ const q = luceneTokenize('argument');
+ expect(luceneBM25(q, docs[0], stats)).toBeGreaterThan(0);
+ expect(luceneBM25(q, docs[2], stats)).toBe(0);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/rate-limiter-stats-3856.test.ts b/v3/@claude-flow/cli/__tests__/rate-limiter-stats-3856.test.ts
new file mode 100644
index 0000000000..944ed5d764
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/rate-limiter-stats-3856.test.ts
@@ -0,0 +1,55 @@
+import { describe, it, expect } from 'vitest';
+import { RateLimiter } from '../src/production/rate-limiter.js';
+
+describe('#3856 — RateLimiter.getStats() operation/user labels', () => {
+ it('reports an anonymous operation by its name with zero active users', () => {
+ const rl = new RateLimiter();
+ rl.check('build');
+ const s = rl.getStats();
+ expect(s.activeUsers).toBe(0);
+ expect(s.mostLimitedOperations).toEqual([{ operation: 'build', requests: 1 }]);
+ });
+
+ it('keeps colon-containing operation names whole and does not count them as users', () => {
+ const rl = new RateLimiter();
+ rl.check('agent:spawn');
+ rl.check('agent:spawn', 'alice');
+ const s = rl.getStats();
+ expect(s.mostLimitedOperations).toEqual([{ operation: 'agent:spawn', requests: 2 }]);
+ expect(s.activeUsers).toBe(1);
+ });
+
+ it('counts distinct users and aggregates requests per operation', () => {
+ const rl = new RateLimiter();
+ rl.check('build', 'alice');
+ rl.check('build', 'alice');
+ rl.check('build', 'bob');
+ rl.check('deploy', 'alice');
+ const s = rl.getStats();
+ expect(s.totalBuckets).toBe(3);
+ expect(s.activeUsers).toBe(2);
+ expect(s.mostLimitedOperations).toEqual([
+ { operation: 'build', requests: 3 },
+ { operation: 'deploy', requests: 1 },
+ ]);
+ });
+
+ it('reports no users when per-user tracking is disabled', () => {
+ const rl = new RateLimiter({ perUserLimits: false });
+ rl.check('build', 'alice');
+ rl.check('build', 'bob');
+ const s = rl.getStats();
+ expect(s.activeUsers).toBe(0);
+ expect(s.totalBuckets).toBe(1);
+ expect(s.mostLimitedOperations).toEqual([{ operation: 'build', requests: 2 }]);
+ });
+
+ it('leaves allowance and reset behaviour unchanged', () => {
+ const rl = new RateLimiter({ maxRequests: 2, burstMultiplier: 1 });
+ expect(rl.check('x', 'u').allowed).toBe(true);
+ expect(rl.check('x', 'u').allowed).toBe(true);
+ expect(rl.check('x', 'u').allowed).toBe(false);
+ rl.reset('x', 'u');
+ expect(rl.check('x', 'u').allowed).toBe(true);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/services/git-workspace-identity.test.ts b/v3/@claude-flow/cli/__tests__/services/git-workspace-identity.test.ts
index cfa665f16f..e472ca0066 100644
--- a/v3/@claude-flow/cli/__tests__/services/git-workspace-identity.test.ts
+++ b/v3/@claude-flow/cli/__tests__/services/git-workspace-identity.test.ts
@@ -6,7 +6,7 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { execFileSync } from 'child_process';
-import { mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import {
@@ -83,6 +83,34 @@ describe('#2661 — git workspace identity', () => {
expect(after.head).not.toBe(before.head);
});
+ it('preserves valid trailing whitespace in repository and linked worktree paths (#3863)', () => {
+ const parent = mkdtempSync(join(tmpdir(), 'gwi-ws-'));
+ try {
+ const spaced = join(parent, 'owned repo ');
+ const linked = join(parent, 'linked leaf ');
+ mkdirSync(spaced);
+ git(spaced, 'init', '-q');
+ git(spaced, 'config', 'user.email', '[email protected]');
+ git(spaced, 'config', 'user.name', 'Test');
+ writeFileSync(join(spaced, 'a.txt'), 'hello');
+ git(spaced, 'add', 'a.txt');
+ git(spaced, 'commit', '-q', '-m', 'init');
+ git(spaced, 'worktree', 'add', '-q', linked, '-b', 'spaced-wt');
+
+ const a = resolveGitWorkspaceIdentity(spaced);
+ const b = resolveGitWorkspaceIdentity(linked);
+ expect(a.isGit).toBe(true);
+ expect(a.worktreeRoot).toBe(realpathSync(spaced));
+ expect(b.worktreeRoot).toBe(realpathSync(linked));
+ expect(a.head).toMatch(/^[0-9a-f]{40}$/);
+ expect(b.head).toBe(a.head);
+ expect(b.commonGitDir).toBe(a.commonGitDir);
+ expect(b.repositoryId).toBe(a.repositoryId);
+ } finally {
+ rmSync(parent, { recursive: true, force: true });
+ }
+ });
+
it('degrades gracefully for non-git directories', () => {
const plain = mkdtempSync(join(tmpdir(), 'gwi-plain-'));
try {
diff --git a/v3/@claude-flow/cli/src/memory/lucene-bm25.ts b/v3/@claude-flow/cli/src/memory/lucene-bm25.ts
index 3fbf86fa0c..04f173f737 100644
--- a/v3/@claude-flow/cli/src/memory/lucene-bm25.ts
+++ b/v3/@claude-flow/cli/src/memory/lucene-bm25.ts
@@ -145,32 +145,24 @@ function step3(w: string): string {
return w;
}
+// Longest suffixes first: Porter step 4 selects the longest matching suffix
+// ONCE and applies its condition; a failed condition must not fall through to
+// a shorter suffix (e.g. "argument": "ment" fails m>1, so "ent" is not tried).
const STEP4_SUFFIXES = [
- 'al', 'ance', 'ence', 'er', 'ic', 'able', 'ible', 'ant', 'ement', 'ment',
- 'ent', 'ou', 'ism', 'ate', 'iti', 'ous', 'ive', 'ize',
+ 'ement', 'ance', 'ence', 'able', 'ible', 'ment', 'ant', 'ent', 'ism',
+ 'ate', 'iti', 'ous', 'ive', 'ize', 'ion', 'al', 'er', 'ic', 'ou',
];
function step4(w: string): string {
for (const suf of STEP4_SUFFIXES) {
- if (w.endsWith(suf)) {
- const stem = w.slice(0, w.length - suf.length);
- if (measure(stem) > 1) {
- if (suf === 'ion') {
- const last = stem[stem.length - 1];
- if (last === 's' || last === 't') return stem;
- } else {
- return stem;
- }
- }
- }
- }
- // ION special-case
- if (w.endsWith('ion')) {
- const stem = w.slice(0, -3);
+ if (!w.endsWith(suf)) continue;
+ const stem = w.slice(0, w.length - suf.length);
if (measure(stem) > 1) {
+ if (suf !== 'ion') return stem;
const last = stem[stem.length - 1];
if (last === 's' || last === 't') return stem;
}
+ return w;
}
return w;
}
diff --git a/v3/@claude-flow/cli/src/production/rate-limiter.ts b/v3/@claude-flow/cli/src/production/rate-limiter.ts
index d96d8b5aaf..49febf1f02 100644
--- a/v3/@claude-flow/cli/src/production/rate-limiter.ts
+++ b/v3/@claude-flow/cli/src/production/rate-limiter.ts
@@ -42,6 +42,10 @@ interface TokenBucket {
tokens: number;
lastRefill: number;
requests: number[];
+ // Actual labels for statistics (bucket keys are not reliably parseable:
+ // operation names may contain ':')
+ operation?: string;
+ userId?: string;
}
// ============================================================================
@@ -85,13 +89,16 @@ export class RateLimiter {
const now = Date.now();
// Get or create bucket
- const bucketKey = userId && this.config.perUserLimits
+ const trackedUser = userId && this.config.perUserLimits ? userId : undefined;
+ const bucketKey = trackedUser
? `${operation}:${userId}`
: `global:${operation}`;
let bucket = this.buckets.get(bucketKey);
if (!bucket) {
bucket = this.createBucket();
+ bucket.operation = operation;
+ bucket.userId = trackedUser;
this.buckets.set(bucketKey, bucket);
this.cleanupBuckets();
}
@@ -204,9 +211,9 @@ export class RateLimiter {
const operationCounts = new Map<string, number>();
const users = new Set<string>();
- for (const [key, bucket] of this.buckets) {
- const [operation, userId] = key.split(':');
- if (userId) users.add(userId);
+ for (const bucket of this.buckets.values()) {
+ const operation = bucket.operation as string;
+ if (bucket.userId) users.add(bucket.userId);
const current = operationCounts.get(operation) || 0;
operationCounts.set(operation, current + bucket.requests.length);
diff --git a/v3/@claude-flow/cli/src/services/git-workspace-identity.ts b/v3/@claude-flow/cli/src/services/git-workspace-identity.ts
index fe3286fa99..4aa5e74acf 100644
--- a/v3/@claude-flow/cli/src/services/git-workspace-identity.ts
+++ b/v3/@claude-flow/cli/src/services/git-workspace-identity.ts
@@ -25,7 +25,7 @@
import { createHash } from 'crypto';
import { resolve } from 'path';
import * as fs from 'fs';
-import { safeGitTextSync } from '@claude-flow/security/safe-git';
+import { safeGitBufferSync, safeGitTextSync } from '@claude-flow/security/safe-git';
export interface GitWorkspaceIdentity {
/** Absolute root of this worktree (or the input dir when not a git repo). */
@@ -53,6 +53,23 @@ function git(cwd: string, ...args: string[]): string | null {
}
}
+/**
+ * Path-valued git output: git terminates the record with a single LF, so strip
+ * only that. A full trim() would corrupt valid paths ending in whitespace.
+ */
+function gitPath(cwd: string, ...args: string[]): string | null {
+ try {
+ const out = safeGitBufferSync(cwd, args, {
+ timeoutMs: GIT_TIMEOUT_MS,
+ stderr: 'ignore',
+ }).toString('utf8');
+ const rec = out.endsWith('\n') ? out.slice(0, -1) : out;
+ return rec.length > 0 ? rec : null;
+ } catch {
+ return null;
+ }
+}
+
function sha256(input: string): string {
return createHash('sha256').update(input).digest('hex');
}
@@ -69,7 +86,7 @@ export function resolveGitWorkspaceIdentity(dir: string): GitWorkspaceIdentity {
let stable = identityCache.get(resolved);
if (!stable) {
- const worktreeRoot = git(resolved, 'rev-parse', '--show-toplevel');
+ const worktreeRoot = gitPath(resolved, 'rev-parse', '--show-toplevel');
if (!worktreeRoot) {
stable = {
worktreeRoot: resolved,
@@ -81,7 +98,7 @@ export function resolveGitWorkspaceIdentity(dir: string): GitWorkspaceIdentity {
} else {
// --git-common-dir may be relative to the worktree root (git < 2.31
// and some invocation contexts) — resolve against it.
- const rawCommon = git(worktreeRoot, 'rev-parse', '--git-common-dir') ?? '.git';
+ const rawCommon = gitPath(worktreeRoot, 'rev-parse', '--git-common-dir') ?? '.git';
const commonGitDir = resolve(worktreeRoot, rawCommon);
stable = {
worktreeRoot,
diff --git a/v3/@claude-flow/shared/src/events/event-store.test.ts b/v3/@claude-flow/shared/src/events/event-store.test.ts
index a3a90741ff..84397e6497 100644
--- a/v3/@claude-flow/shared/src/events/event-store.test.ts
+++ b/v3/@claude-flow/shared/src/events/event-store.test.ts
@@ -7,6 +7,7 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { EventStore } from './event-store.js';
+import { StateReconstructor, TaskAggregate } from './state-reconstructor.js';
import { AgentStateProjection, TaskHistoryProjection, MemoryIndexProjection } from './projections.js';
import {
createAgentSpawnedEvent,
@@ -205,6 +206,30 @@ describe('EventStore', () => {
const retrieved = await eventStore.getSnapshot('agent-1');
expect(retrieved?.version).toBe(10);
+
+ });
+ it('should return null when no snapshot exists for the aggregate', async () => {
+ await expect(eventStore.getSnapshot('missing')).resolves.toBeNull();
+ });
+
+ it('should return null for an unknown aggregate when other snapshots exist', async () => {
+ await eventStore.saveSnapshot({
+ aggregateId: 'agent-1',
+ aggregateType: 'agent' as const,
+ version: 1,
+ state: {},
+ timestamp: Date.now(),
+ });
+ await expect(eventStore.getSnapshot('other')).resolves.toBeNull();
+ });
+
+ it('should reconstruct from the event log when no snapshot exists', async () => {
+ await eventStore.append(
+ createTaskCreatedEvent('task-1', 'impl', 'Write code', 'desc', 'normal', [])
+ );
+ const reconstructor = new StateReconstructor(eventStore);
+ const task = await reconstructor.reconstruct('task-1', (id) => new TaskAggregate(id));
+ expect(task.version).toBe(1);
});
});
diff --git a/v3/@claude-flow/shared/src/events/event-store.ts b/v3/@claude-flow/shared/src/events/event-store.ts
index d1ae257e16..6362c1dea5 100644
--- a/v3/@claude-flow/shared/src/events/event-store.ts
+++ b/v3/@claude-flow/shared/src/events/event-store.ts
@@ -422,10 +422,13 @@ export class EventStore extends EventEmitter {
'SELECT * FROM snapshots WHERE aggregate_id = ? ORDER BY version DESC LIMIT 1'
);
- const row = stmt.getAsObject([aggregateId]);
+ stmt.bind([aggregateId]);
+ // sql.js getAsObject() yields undefined-valued column keys when no row matched,
+ // so step first and treat absence explicitly.
+ const row = stmt.step() ? stmt.getAsObject() : null;
stmt.free();
- if (!row || Object.keys(row).length === 0) {
+ if (!row) {
return null;
}