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

dream(security): #4312 hooks_codemod path-containment bypass (CWE-22) (evaluated, ACCEPT) (#4313)

rUvdf2dd4bfd693
diff --git a/docs/dream-cycle/LEDGER.md b/docs/dream-cycle/LEDGER.md
index 9fca8e903c..c7db7bd98e 100644
--- a/docs/dream-cycle/LEDGER.md
+++ b/docs/dream-cycle/LEDGER.md
@@ -239,3 +239,5 @@ as a first-class, high-priority candidate, not a background note.
| 2026-10-18 | memory | `ReasoningBank.consolidate()` (`v3/@claude-flow/hooks/src/reasoningbank/index.ts`) deleted pruned/deduplicated patterns from `shortTermPatterns`/AgentDB via `deleteFromStorage()` but never called `hnswIndex.removePoint(id)` β€” `storePattern()`'s unguarded `addPoint()` throws once the HNSW index's `maxElements` (orphans included) is exhausted, permanently breaking pattern learning in the `HooksLearningDaemon`'s every-60s `consolidate()` loop even though the index is full of logically-deleted ghosts; fixed with two additive `removePoint()` calls alongside the existing deletion sites | #4270 | #4271 | yes | ACCEPT | 2 new discriminating tests (prune path, dedup path) against a real built-from-source AgentDB+HNSW backend (`@claude-flow/memory`+`@claude-flow/neural` both required building in-session β€” dist was missing for both, and without it the tests would pass vacuously in in-memory fallback mode, caught via direct internals inspection); stash-isolated baseline fails both exactly as predicted (`Index is full, cannot add more elements` at the predicted `HNSWIndex.addPoint`←`storePattern` call site), candidate passes both β€” independently reproduced twice (session + a separate adversarial-critic subagent from scratch); full `@claude-flow/hooks` suite 147/147 (7/7 files), 0 regressions, `tsc --noEmit` clean; independent adversarial critique CONFIRMED, no blocking issues | b2ad8c15... | 10-09/10-10/10-11/09-28/09-29/09-30/10-15 MERGED (7/7); 10-16 #4230, 10-17 #4250 open/draft, neither stale |
**Note (2026-10-19):** verified via GitHub MCP tools (`gh` CLI unavailable this session, same fallback since 2026-09-17) before tonight's own row: 2026-10-16 (security, `DENYLISTED_ENV_NAMES` git/perl/ruby/java hijack family, #4229/#4230) ran with a real branch/issue/draft PR, not transcribed as its own row here (same "ledger rows only reach `main` via PR merge" structural gap noted since 2026-08-19); still open/draft with 1 pending reviewer comment as of tonight, 3d old, not stale. 2026-10-17 (intelligence, `agentdb-backend.ts` calling a native HNSW controller that never existed, #4249/#4250) and 2026-10-18 (memory, `ReasoningBank.consolidate()` HNSW orphan leak, #4270/#4271) both ran with real branches/issues/open draft PRs, confirmed via `search_pull_requests`; neither transcribed here either. Trailing-7-night fates before tonight (via `pull_request_read`, authoritative β€” `search_pull_requests`'s own `merged` field remains unreliable per the 2026-09-21 note): 10-09 #3929 **MERGED**; 10-10 #3977 **MERGED**; 10-11 #4053 **MERGED**; 10-12 #4081 open/draft; 10-13 #4138 open/draft; 10-14 #4174 open/draft (`mergeable_state: dirty`); 10-15 #4215 **MERGED** 2026-10-17 β€” none of 10-12..10-18 stale (<14d).
| 2026-10-19 | swarm | `TopologyManager.electLeader()`'s hierarchical/centralized branches read the cached `queenNode`/`coordinatorNode`, nulled by `removeFromRoleIndex()` on death with no replacement, and silently fell through to generic mesh-style ranking β€” electing a leader without ever promoting its `.role`, so `getQueen()`/`getCoordinator()` returned `undefined` forever after exactly one death despite `failoverEnabled: true` (default) documenting failover; added `promoteToRole()`, gated on that same flag, re-using the existing role-index cache pair | #4285 | #4286 | yes | ACCEPT | 3 new discriminating tests, baseline-fails-2-of-3/candidate-passes-3-of-3 via stash isolation (1 correct non-discriminating `failoverEnabled:false` control); full `@claude-flow/swarm` suite 335/335 (332+3 new), 0 regressions, `tsc --noEmit` clean both ways; independent adversarial critique CONFIRMED-WITH-CAVEATS β€” 1 caveat (promotion doesn't rewire connections/adjacency, self-healing under default `autoRebalance:true`) disclosed in-source as a KNOWN LIMITATION comment, 2 others (insertion-order candidate pick, no new locking) confirmed to match pre-existing class-wide convention, none blocking; confirmed zero blast-radius into raft/byzantine/gossip consensus | 7cf5c70f... | 10-09/10-10/10-11/10-15 MERGED; 10-12/10-13/10-14/10-16/10-17/10-18 open/draft, none stale |
+**Note (2026-10-20):** trailing-7-night fates verified via GitHub MCP tools (`gh` CLI's `GH_TOKEN` invalid, MCP tools work fine β€” not FALLBACK) before tonight's own row: #4230 (10-16, security) **MERGED**; #4250 (10-17, intelligence) open/draft, not stale; #4271 (10-18, memory) **MERGED**; #4286 (10-19, swarm) **MERGED**. No no-run gaps in the trailing window. **Rotation override disclosed**: tonight's `SLOT=0` rotation assigns `DEEP=performance`, but the implemented candidate below came from the `security` SCAN surface instead (precedent: 2026-09-24 #3411/#3412) β€” it scored 5.0/5 on the same candidate rubric used for the two deferred performance findings (`CacheManager.estimateSize()` redundant stringify, score 4.85; `AttentionCoordinator` embedding-cache miss, score 4.70 β€” both documented in full in issue #4312/gist for a future night), vs. their 4.85 max, and was HIGH severity/live-exploitable rather than a latent inefficiency.
+| 2026-10-20 | security (SCAN override of performance DEEP, see note above) | `hooks_codemod` MCP tool's `resolveTargets()` path-containment check used an unanchored `abs.startsWith(cwd)` string-prefix comparison β€” since `path.resolve(cwd, p)` returns an already-absolute `p` unchanged, a sibling directory merely starting with the project directory's name (e.g. `cwd`-staging) passed containment, letting this live, CLAUDE.md-recommended Tier-1 tool read **and write** (dryRun defaults false) outside the project root (CWE-22); anchored both call sites (`file`/`files[]` and `glob` branches) at a path-separator boundary, matching the already-correct `isWithinPrefix()` pattern used elsewhere in this exact codebase (`@claude-flow/security`, `@claude-flow/hooks/workers`, `@claude-flow/plugins/security`) | #4312 | #4313 | yes | ACCEPT | 4 new tests (2 discriminating, real temp-dir fs I/O; 2 non-discriminating controls); stash-isolated baseline fails both escape tests exactly as predicted (file genuinely overwritten outside root, not simulated), candidate 4/4 pass β€” independently reproduced twice (session + a separate adversarial-critic subagent from scratch, which also built its own symlink-escape repro); related suites (`mcp-tools-deep`, `validate-input-*`, `codemod-*`) 229/229 both ways (twice-reproduced); `tsc --noEmit` byte-identical 9 pre-existing errors; full `@claude-flow/cli` suite ~480/503 both ways, same ~21-22 pre-existing-failure set by name untouched by this change (second full-suite run disclosed as contaminated mid-run by this session's own revert/restore cycle, not relied on); independent adversarial critique CONFIRMED-WITH-CAVEATS β€” 1 non-blocking caveat (symlink-based containment bypass, CWE-59, distinct/broader gap) disclosed in-source as a KNOWN LIMITATION comment rather than fixed, deferred to a future realpath-hardening night | d501ab48... | 10-09/10-10/10-11/10-15/10-16/10-18/10-19 MERGED (7/7 of trailing window with a decision); 10-17 #4250 open/draft, not stale |
diff --git a/docs/dream-cycle/dream-gist-2026-10-20.md b/docs/dream-cycle/dream-gist-2026-10-20.md
new file mode 100644
index 0000000000..ad83d9f9bb
--- /dev/null
+++ b/docs/dream-cycle/dream-gist-2026-10-20.md
@@ -0,0 +1,70 @@
+# Performance/Security SOTA Report β€” 2026-10-20
+
+**TL;DR**: Tonight's DEEP slot was `performance`; SCAN was `security`+`hive-mind`. Five parallel research roles surfaced two strong fresh performance candidates (both avoiding the 3x-exhausted busy-poll and native-accel-dead-code patterns) β€” but the security scan found a HIGH-severity, **live, currently-exploitable** path-containment bypass in the `hooks_codemod` MCP tool (a Tier-1 tool CLAUDE.md tells every agent to call automatically), letting an absolute path like `/project-staging/x.ts` escape `cwd=/project` via an unanchored string-prefix check and get read+written on disk. Tonight overrides the DEEP/SCAN rotation (precedent: 2026-09-24's off-cycle #3411/#3412) to fix this instead of a performance candidate β€” it scored higher on every axis (production_value, reviewability, novelty) and the fix is a tiny, low-risk anchor-at-separator change matching a pattern already correct elsewhere in this codebase. Both deferred performance candidates, plus a hive-mind topology bug, are documented below for a future night.
+
+## What's New in 2026
+
+| Finding | Source | Confidence |
+|---|---|---|
+| EvoRoute: per-step Pareto-optimal LLM backbone selection, up to 80% cost / 70% latency reduction (GAIA/BrowseComp+) | ACL 2026, preview.aclanthology.org/2026.acl-long.1771 | B |
+| No framework (LangGraph/MS Agent Framework/CrewAI/OpenAI Agents SDK) ships a first-party swarm-level cost-aware router as of this search | Direct docs search, Oct 2026 | B |
+| CrewAI Flows/triggers = only official, current (2026) design claim for event-driven-vs-polling orchestration among 4 competitors β€” zero measured before/after numbers published by anyone | docs.crewai.com/concepts/flows, 2026 | B |
+| Ruflo's HNSW 1.9x–4.7x and quantization (int8 3.84x, RaBitQ 32x) are at industry parity (Weaviate 4x@8-bit RQ; Qdrant/Vespa headline numbers are >12mo stale) | Weaviate/Qdrant/Milvus/LanceDB/Vespa docs, cross-checked | B |
+| OWASP's 2026 cycle (LLM Top 10 + a separate Agentic/ASI Top 10, Dec 2025) ranks Excessive Agency / improper least-privilege on agent tool calls as a top category β€” directly the class of tonight's fix | CSA/Akamai secondary summaries (did not open genai.owasp.org directly) | C |
+
+## Ruflo Current Capability
+
+`hooks_codemod` (`v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts:5380`) is the real Tier-1 ($0, no-LLM) codemod path (ADR-143), explicitly surfaced by CLAUDE.md whenever `[CODEMOD_AVAILABLE]` appears. No competitor framework reviewed ships an equivalent deterministic-codemod tier at all β€” this remains a genuine Ruflo differentiator, which is exactly why its containment bug mattered: it's a tool agents are told to call automatically, not an edge-case path.
+
+## Competitor Comparison
+
+| Competitor | Cost-aware routing (last 6mo) | Event-driven vs. polling claim | Confidence |
+|---|---|---|---|
+| LangGraph | None native; third-party "close behind AutoGen" (unreplicated) | Checkpointer = resumability, not explicitly "no polling" | B/C |
+| MS Agent Framework (AutoGen successor, GA Apr 2026) | Azure "model router" is platform-level, not framework-level | Superstep/barrier model, structurally non-polling, unbenchmarked | B/C |
+| CrewAI | None found | Flows/triggers explicitly replace polling (official docs) β€” only concrete 2026 design claim of the four | B |
+| OpenAI Agents SDK | Single-model reasoning-effort knob only, not cross-model | No claim found | C |
+| Field-wide | **Open gap**: no framework ships a swarm-level cost router comparable to Ruflo's 3-tier ADR-026/143 | **Open gap**: no competitor publishes measured before/after polling-removal numbers (Ruflo has shipped 3 such fixes: #3378/#3563/#4215) | β€” |
+
+No row is a bare "None" β€” each ties to a dated source or an explicit scope/design reason.
+
+## Hypothesis (frozen before evaluation)
+
+> Given the `hooks_codemod` MCP tool's `resolveTargets()` path-containment checks (`hooks-tools.ts:5432` for `file`/`files[]`, `:5454` for `glob` matches), when a caller supplies an absolute path whose string representation shares `cwd` as a literal prefix without a path-separator boundary (e.g. cwd=`/home/user/ruflo`, target=`/home/user/ruflo-staging/notes.ts`), then the current unanchored `abs.startsWith(cwd)` check incorrectly treats the target as contained and the tool reads and (absent `dryRun`) writes that file outside the project root β€” then anchoring the check at a path-separator boundary (`abs === cwd || abs.startsWith(cwd + sep)`, matching `@claude-flow/security`'s `isWithinPrefix()` and two other already-correct sites in this codebase) should reject such targets with "path escapes project root" and perform zero I/O, while every legitimate in-root absolute/relative path continues to work identically, subject to: (1) zero change to the no-disk `code` mode; (2) zero regression to codemod-engine/corpus/routing suites; (3) deterministic, $0, zero-LLM Vitest evaluation.
+
+## Benchmarks / Evaluation
+
+Real evaluator: Vitest 4.1.8, `@claude-flow/cli` package, after building `cli-core`+`neural` (dist was missing for both). New test file `__tests__/hooks-codemod-path-containment.test.ts`, 4 tests: 2 discriminating (real temp-dir fs I/O, absolute path escaping a sibling-prefix `cwd`, via `file` and `files[]`), 2 non-discriminating controls (legitimate absolute/relative in-root paths). Stash-isolated baseline (`git stash` on just `hooks-tools.ts`): **2 of 2 escape tests fail on baseline** (`success: true`, target file actually overwritten outside root β€” the live exploit, reproduced for real, not simulated) β€” candidate: **4/4 pass**. Related suites (`mcp-tools-deep`, `validate-input-*`, `codemod-engine/routing/corpus`): **229/229 both ways, independently reproduced twice** (this session once, an adversarial-critic subagent with no authoring context a second time, including its own fresh stash/pop cycle). `tsc --noEmit`: byte-identical 9 pre-existing environmental errors both ways (unbuilt sibling packages, unrelated).
+
+Full `@claude-flow/cli` suite: ~480/503 files pass both before and after. The ~21-22 consistently-failing files (`mcp-policy-enforcer` policy-wiring, `memory-search-recall-2558`, `self-learning-2245`/`unified-stats-2245` shared-counter flakiness across parallel workers, `p1-commands`) are the same set by file/test name in both runs and touch none of: `hooks-tools.ts`, the codemod engine, or path validation β€” consistent with pre-existing environmental/shared-state flakiness, not a regression. Full disclosure: the second (baseline) full-suite run was contaminated mid-run by this session reverting the fix on disk to run a stash-isolated comparison, then promptly restoring it once a stop-hook flagged the dirty tree β€” so it is not a clean byte-identical diff and is not relied on as the authoritative check; the narrower, clean, twice-reproduced related-suite run above is.
+
+## Darwin Results
+
+Skipped β€” binary path-containment correctness fix (anchor an existing check at a separator boundary), no continuous/categorical parameter for Darwin's real interface (`npx ruvector harness darwin <config> --execute`, confirmed available in STEP 0.5) to search over. Same skip class as nearly every accepted security fix since 2026-08-18.
+
+## Reward Hack Check
+
+No standalone reward-hack CLI reachable this session (`@metaharness/weight-eft` loaded as a library dependency per STEP 0.5's doctor output, but no `npx`-callable entry point found). Manual checklist, independently re-verified by the adversarial critic from a fresh context: no test weakened, no gold/benchmark data touched, no cherry-picking (full suite disclosed, including the contaminated-run caveat above rather than hiding it), no evaluator exploitation, $0 cost (the tool's own output reports `cost: 0, tier: 1`), no seed manipulation.
+
+## Security Review
+
+This finding *is* the security fix. Independent adversarial critique (separate subagent, no authoring context): **CONFIRMED-WITH-CAVEATS, no blocking issues.** The critic independently reproduced the stash-isolated comparison, confirmed the diff was scoped to exactly 2 checks + 1 import + 1 test file, and built its own standalone repro proving the glob-branch fix (the second call site) is real defense-in-depth, not cosmetic (an absolute glob pattern bypasses the pre-existing `glob.includes('..')` guard and would have passed the old unanchored check). It also found and disclosed a **non-blocking** follow-up: the fix compares the resolved-but-not-realpath'd path, so a symlink inside the project root pointing outside it still escapes containment (CWE-59, a distinct/broader gap than the CWE-22 bug fixed tonight) β€” disclosed in-source as a KNOWN LIMITATION comment and left for a future night's realpath-based hardening, matching this repo's established non-blocking-caveat convention rather than scope-creeping tonight's patch.
+
+## SOTA Proof & Witness
+
+No `.claude-flow/flywheel/` state exists in this repo (same as every prior night). Evidence retained as: 4 new discriminating/control tests, the stash-isolated comparison (real file I/O, not simulated), an independent adversarial critique (including its own independent repro of the symlink gap), issue/PR links, and the witness below.
+
+```
+Session commit: 070349a6949aee7d5cb798a354f0712121285324
+Candidate commit: (this branch's head β€” see commit list: 71a6c07d fix, 93743766 disclosure)
+Gist SHA-256 (pre-witness, witness block stripped to PENDING): 85acdd27963f7d5598df7857acad2e609bdcfd83caee4dbe8dbda666e0ad2840
+Witness stamp: d501ab489f819875de9f3ee2028bb5b4d2ad2705a3c31092c67bbde0bb77bbe3
+```
+Verifier: fetch `docs/dream-cycle/dream-gist-2026-10-20.md` from this branch, strip the Witness block's filled-in values back to `PENDING`, SHA-256 the file, concatenate with the session commit above, SHA-256 again β€” must equal the witness stamp.
+
+## Recommended Next Steps
+
+1. **Implement `CacheManager.estimateSize()` fix** (arch-reviewer's top performance pick, score 4.85/5): every `set()`/`delete()`/`evictLRU()` in `v3/@claude-flow/memory/src/cache-manager.ts` pays a full `JSON.stringify` on every mutation for a `memoryUsage` stat that `agentdb-adapter.ts`'s real production wiring never gates eviction on (`maxMemory` is never passed). Cache the computed size once per entry instead of re-deriving it.
+2. **Fix `TopologyManager.calculateInitialConnections()`'s raw-vs-resolved role bug** (hive-mind scan): uses the caller's *requested* role instead of `determineRole()`'s *resolved* role, so a demoted-to-worker node re-requesting queen/coordinator still gets wired with leader-level connections to all existing nodes (`topology-manager.ts:77/82/365-396`). Same single-source-of-truth fix shape as the 10-19 `promoteToRole()` fix.
+3. **Decide the second-order path-containment instances found tonight**: `v3/@claude-flow/mcp/src/resource-registry.ts:513-523` and `v3/@claude-flow/shared/src/security/input-validation.ts:119-155` have the identical unanchored-prefix bug, but no confirmed attacker-reachable call site in this scan β€” verify exploitability before treating as tracked issues.
+4. Pursue `AttentionCoordinator.getOrCreateEmbedding()` memoization (deep-researcher's pick, score 4.70) on a future performance night: O(2nΒ²Β·L)β†’O(nΒ·L) in the live `hyperbolic`-mode dispatch.
diff --git a/v3/@claude-flow/cli/__tests__/hooks-codemod-path-containment.test.ts b/v3/@claude-flow/cli/__tests__/hooks-codemod-path-containment.test.ts
new file mode 100644
index 0000000000..b65fe671ab
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/hooks-codemod-path-containment.test.ts
@@ -0,0 +1,100 @@
+/**
+ * Regression test (Dream Cycle 2026-10-20): `hooks_codemod`'s path-containment
+ * check used an unanchored string-prefix comparison (`abs.startsWith(cwd)`)
+ * instead of anchoring at a path-separator boundary. A sibling directory
+ * whose name happens to start with the project directory's name (e.g.
+ * `/project` vs. `/project-staging`) passed the check and let the tool
+ * read-and-write a file outside the intended project root β€” CWE-22.
+ *
+ * Real filesystem I/O (temp dirs), no mocks β€” proves the actual read+write
+ * escape, not just the string comparison in isolation.
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { hooksCodemod } from '../src/mcp-tools/hooks-tools.js';
+
+describe('hooks_codemod path containment', () => {
+ let root: string;
+ let projectDir: string;
+ let siblingDir: string;
+ let prevCwd: string | undefined;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'dream-codemod-'));
+ // Sibling directory name shares "project" as a literal string prefix β€”
+ // the exact shape of the bypass (cwd="<root>/project", escape target
+ // lives under "<root>/project-staging", one directory up from cwd).
+ projectDir = join(root, 'project');
+ siblingDir = join(root, 'project-staging');
+ mkdirSync(projectDir, { recursive: true });
+ mkdirSync(siblingDir, { recursive: true });
+ prevCwd = process.env.CLAUDE_FLOW_CWD;
+ process.env.CLAUDE_FLOW_CWD = projectDir;
+ });
+
+ afterEach(() => {
+ if (prevCwd === undefined) delete process.env.CLAUDE_FLOW_CWD;
+ else process.env.CLAUDE_FLOW_CWD = prevCwd;
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it('rejects an absolute `file` path outside the project root that shares a string prefix with cwd', async () => {
+ const target = join(siblingDir, 'evil.ts');
+ writeFileSync(target, "console.log('leak');\n");
+
+ const result = (await hooksCodemod.handler({ intent: 'remove-console', file: target })) as Record<
+ string,
+ unknown
+ >;
+
+ expect(result.success).toBe(false);
+ expect(String(result.error)).toMatch(/escapes project root/);
+ // The file must be byte-identical β€” no write occurred outside the root.
+ expect(readFileSync(target, 'utf-8')).toBe("console.log('leak');\n");
+ });
+
+ it('rejects the same escape via the `files[]` array form', async () => {
+ const target = join(siblingDir, 'evil2.ts');
+ writeFileSync(target, "console.log('leak');\n");
+
+ const result = (await hooksCodemod.handler({ intent: 'remove-console', files: [target] })) as Record<
+ string,
+ unknown
+ >;
+
+ expect(result.success).toBe(false);
+ expect(String(result.error)).toMatch(/escapes project root/);
+ expect(readFileSync(target, 'utf-8')).toBe("console.log('leak');\n");
+ });
+
+ it('still allows a legitimate absolute path inside the project root (non-discriminating control)', async () => {
+ const target = join(projectDir, 'ok.ts');
+ writeFileSync(target, "console.log('inside');\n");
+
+ const result = (await hooksCodemod.handler({ intent: 'remove-console', file: target })) as Record<
+ string,
+ unknown
+ >;
+
+ expect(result.success).toBe(true);
+ const results = result.results as Array<Record<string, unknown>>;
+ expect(results[0].written).toBe(true);
+ expect(readFileSync(target, 'utf-8')).not.toMatch(/console\.log/);
+ });
+
+ it('still allows a relative path inside the project root (non-discriminating control)', async () => {
+ writeFileSync(join(projectDir, 'rel.ts'), "console.log('inside');\n");
+
+ const result = (await hooksCodemod.handler({ intent: 'remove-console', file: 'rel.ts' })) as Record<
+ string,
+ unknown
+ >;
+
+ expect(result.success).toBe(true);
+ const results = result.results as Array<Record<string, unknown>>;
+ expect(results[0].written).toBe(true);
+ });
+});
diff --git a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
index 822b23228c..7c7e219a5e 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
@@ -6,7 +6,7 @@ import { feedbackPatternsSchema, validateFeedbackPatterns } from '../memory/feed
import { mkdirSync, writeFileSync, existsSync, readFileSync, statSync, unlinkSync, readdirSync, rmSync } from 'fs';
import * as nodeFs from 'fs';
-import { dirname, join, resolve } from 'path';
+import { dirname, join, resolve, sep } from 'path';
import { type MCPTool, getProjectCwd } from './types.js';
import { validateIdentifier, validateText, validatePath } from './validate-input.js';
import { commandRecordingDisabled, redactCommandForStorage } from '../services/command-recording.js';
@@ -5429,7 +5429,17 @@ export const hooksCodemod: MCPTool = {
const v = validatePath(p, 'path');
if (!v.valid) return v.error;
const abs = resolve(cwd, v.sanitized);
- if (!abs.startsWith(cwd)) return `path escapes project root: ${p}`;
+ // Anchor containment at a path-separator boundary β€” an unanchored
+ // `abs.startsWith(cwd)` string-prefix check would let an absolute
+ // path like `${cwd}-staging/x.ts` pass as "inside" `cwd`. Matches
+ // the pattern already used correctly elsewhere in this codebase
+ // (@claude-flow/security's `isWithinPrefix`, hooks/workers, plugins/security).
+ // KNOWN LIMITATION (disclosed 2026-10-20, not fixed here): this
+ // compares the resolved-but-not-realpath'd path, so a symlink
+ // inside cwd pointing outside it still escapes containment
+ // (CWE-59, a distinct/broader gap than the CWE-22 prefix bug this
+ // anchors). Needs fs.realpathSync-based containment as a follow-up.
+ if (abs !== cwd && !abs.startsWith(cwd + sep)) return `path escapes project root: ${p}`;
out.add(abs);
return undefined;
};
@@ -5451,7 +5461,7 @@ export const hooksCodemod: MCPTool = {
}
for (const m of matches) {
const abs = resolve(cwd, m);
- if (abs.startsWith(cwd) && CODEMOD_EXTENSIONS.has(abs.slice(abs.lastIndexOf('.')).toLowerCase())) {
+ if ((abs === cwd || abs.startsWith(cwd + sep)) && CODEMOD_EXTENSIONS.has(abs.slice(abs.lastIndexOf('.')).toLowerCase())) {
out.add(abs);
}
}