mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-05 06:56:22 +09:00
Merge origin/main into fix/agent-health-observed
This commit is contained in:
commit
6feebdd6a1
22 files changed
+849
-119
No files matched your search
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: "Verification & Quality Assurance"
|
||||
description: |
|
||||
Comprehensive truth scoring, code quality verification, and automatic rollback system with 0.95 accuracy threshold for ensuring high-quality agent outputs and codebase reliability.
|
||||
Check code quality and change risk with ruflo's shipped analysis commands (analyze diff, analyze complexity, analyze code), and run or extend ruflo's own CI regression guards. Use when assessing a change's risk, finding complexity hot spots, or adding a regression guard to ruflo. The truth-scoring and auto-rollback commands described later in this file are design notes, not shipped CLI commands.
|
||||
---
|
||||
|
||||
# Verification & Quality Assurance Skill
|
||||
@@ -62,31 +62,34 @@ node plugins/ruflo-core/scripts/witness/history.mjs --history verification/macos
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Ruflo installed (`npx ruflo@alpha`)
|
||||
- Ruflo installed (`npx ruflo@latest`)
|
||||
- Git repository (for rollback features)
|
||||
- Node.js 18+ (for dashboard features)
|
||||
- `@noble/ed25519` (for the witness verifier — a single runtime dep, `npm i @noble/ed25519`)
|
||||
|
||||
## Quick Start
|
||||
|
||||
These commands ship in the current CLI:
|
||||
|
||||
```bash
|
||||
# View current truth scores
|
||||
npx ruflo@alpha truth
|
||||
# Change risk since HEAD~1 (without --risk it also shows classification and reviewers)
|
||||
npx ruflo@latest analyze diff HEAD~1 --risk
|
||||
|
||||
# Run verification check
|
||||
npx ruflo@alpha verify check
|
||||
# Complexity hot spots in a directory
|
||||
npx ruflo@latest analyze complexity src/ --threshold 15
|
||||
|
||||
# Verify specific file with custom threshold
|
||||
npx ruflo@alpha verify check --file src/app.js --threshold 0.98
|
||||
|
||||
# Rollback last failed verification
|
||||
npx ruflo@alpha verify rollback --last-good
|
||||
# Size, functions and TODOs per file
|
||||
npx ruflo@latest analyze code -p ./src
|
||||
```
|
||||
|
||||
There is no truth-scoring, `verify check` or `verify rollback` command (`ruflo verify` only checks an installed ruflo package against its signed witness manifest). To verify agent output, run the project's own tests, linters and type checks, and roll back with git (`git restore <file>`, `git revert <commit>`). Inside the ruflo repo, run the guards in [Run the guards locally](#run-the-guards-locally).
|
||||
|
||||
---
|
||||
|
||||
## Complete Guide
|
||||
|
||||
> **Design notes, not shipped.** Everything below describes a planned truth-scoring, verification and rollback surface. `ruflo truth`, `ruflo verify check` and `ruflo verify rollback` are not commands in the current CLI, so do not run the examples below; use the commands in [Quick Start](#quick-start) instead.
|
||||
|
||||
### Truth Scoring System
|
||||
|
||||
#### View Truth Metrics
|
||||
|
||||
@@ -18,6 +18,9 @@ on:
|
||||
- 'plugins/**'
|
||||
- 'scripts/smoke-all-plugins.mjs'
|
||||
- 'scripts/audit-plugin-mcp-prefix.mjs'
|
||||
- 'scripts/audit-skill-mcp-tools.mjs'
|
||||
- 'verification/skill-mcp-tool-baseline.json'
|
||||
- 'v3/@claude-flow/cli/.claude/skills/**'
|
||||
- 'scripts/check-plugin-manifests.mjs'
|
||||
- 'scripts/sync-mod-screen.mjs'
|
||||
- 'scripts/check-guard-tool-names.mjs'
|
||||
@@ -32,6 +35,9 @@ on:
|
||||
- 'plugins/**'
|
||||
- 'scripts/smoke-all-plugins.mjs'
|
||||
- 'scripts/audit-plugin-mcp-prefix.mjs'
|
||||
- 'scripts/audit-skill-mcp-tools.mjs'
|
||||
- 'verification/skill-mcp-tool-baseline.json'
|
||||
- 'v3/@claude-flow/cli/.claude/skills/**'
|
||||
- 'scripts/check-plugin-manifests.mjs'
|
||||
- 'scripts/sync-mod-screen.mjs'
|
||||
- 'scripts/check-guard-tool-names.mjs'
|
||||
@@ -133,6 +139,14 @@ jobs:
|
||||
# plugin-qualified namespace. Reject standalone namespace references
|
||||
# that silently disable tools in plugin skills and agents.
|
||||
|
||||
- name: Skill MCP tool reference audit
|
||||
run: node scripts/audit-skill-mcp-tools.mjs
|
||||
# Every ruflo MCP tool a shipped SKILL.md names (init bundle and
|
||||
# marketplace plugins, prose and allowed-tools) must be registered by
|
||||
# mcp-client.ts. Known dangling references are carried in
|
||||
# verification/skill-mcp-tool-baseline.json; a new one fails. After
|
||||
# fixing some, run with --update-baseline to lower the floor.
|
||||
|
||||
- name: Upload machine-readable report
|
||||
if: always()
|
||||
run: node scripts/smoke-all-plugins.mjs --format json > /tmp/smoke-all-plugins.json
|
||||
|
||||
@@ -1285,8 +1285,69 @@
|
||||
"agentdb": 4052378,
|
||||
"agentic-flow": 2586642
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "2026-10-14T06:43:55.114Z-0818a355",
|
||||
"captured_at": "2026-10-14T06:43:55.114Z",
|
||||
"vector": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"totals": {
|
||||
"clones": 0,
|
||||
"uniques": 0
|
||||
},
|
||||
"repos": {
|
||||
"ruvnet/ruflo": {
|
||||
"count": 0,
|
||||
"uniques": 0,
|
||||
"days": [],
|
||||
"error": "fetch-failed"
|
||||
},
|
||||
"ruvnet/agentdb": {
|
||||
"count": 0,
|
||||
"uniques": 0,
|
||||
"days": [],
|
||||
"error": "fetch-failed"
|
||||
},
|
||||
"ruvnet/agentic-flow": {
|
||||
"count": 0,
|
||||
"uniques": 0,
|
||||
"days": [],
|
||||
"error": "fetch-failed"
|
||||
},
|
||||
"ruvnet/ruvector": {
|
||||
"count": 0,
|
||||
"uniques": 0,
|
||||
"days": [],
|
||||
"error": "fetch-failed"
|
||||
},
|
||||
"ruvnet/ruv-FANN": {
|
||||
"count": 0,
|
||||
"uniques": 0,
|
||||
"days": [],
|
||||
"error": "fetch-failed"
|
||||
}
|
||||
},
|
||||
"npm_headline_total": 13123477,
|
||||
"npm": {
|
||||
"claude-flow": 1050136,
|
||||
"ruflo": 1516870,
|
||||
"@claude-flow/cli": 1832979,
|
||||
"@claude-flow/memory": 1587272,
|
||||
"agentdb": 4306554,
|
||||
"agentic-flow": 2829666
|
||||
}
|
||||
}
|
||||
],
|
||||
"updated_at": "2026-10-01T06:48:38.061Z",
|
||||
"snapshot_count": 15
|
||||
"updated_at": "2026-10-14T06:43:55.114Z",
|
||||
"snapshot_count": 16
|
||||
}
|
||||
@@ -1,20 +1,20 @@
|
||||
{
|
||||
"schema": "ruflo-ecosystem-proof/v2",
|
||||
"generated_at": "2026-10-01T06:48:38.061Z",
|
||||
"generated_at": "2026-10-14T06:43:55.114Z",
|
||||
"sources": {
|
||||
"github_clones": "https://api.github.com/repos/{owner}/{repo}/traffic/clones (14-day rolling window)",
|
||||
"npm_downloads": "https://api.npmjs.org/downloads/range/last-year/{pkg}"
|
||||
},
|
||||
"latest_snapshot": {
|
||||
"id": "2026-10-01T06:48:38.061Z-cfb38bb3",
|
||||
"captured_at": "2026-10-01T06:48:38.061Z",
|
||||
"id": "2026-10-14T06:43:55.114Z-0818a355",
|
||||
"captured_at": "2026-10-14T06:43:55.114Z",
|
||||
"clones_14d": 0,
|
||||
"unique_cloners_14d": 0,
|
||||
"npm_downloads_12mo_headline": 12134365,
|
||||
"headline": "12.1M npm downloads · 0k git clones (14d)"
|
||||
"npm_downloads_12mo_headline": 13123477,
|
||||
"headline": "13.1M npm downloads · 0k git clones (14d)"
|
||||
},
|
||||
"ledger_snapshot_count": 15,
|
||||
"ledger_sha256": "805ea45e558cd9db679cf5923bc7cdb000edf562a0d3d19b5d75048123668dec",
|
||||
"ledger_snapshot_count": 16,
|
||||
"ledger_sha256": "4f4cbfa2996ad94139d4a79c2bb80c49acd7f3e7eda835f1ffef94b00b078c98",
|
||||
"ledger_path": "data/clone-data.ledger.json",
|
||||
"rvf_path": "data/clone-data.rvf"
|
||||
}
|
||||
Binary file not shown.
@@ -107,10 +107,19 @@ describe('the icon row', () => {
|
||||
expect([...glyph].length, name).toBe(1)
|
||||
expect(glyph, name).not.toBe('?')
|
||||
// None may be an emoji, or have an emoji form: a terminal can draw those two cells wide, and the lit icon (bold) would then jump.
|
||||
expect(glyph, name).not.toMatch(/\p{Extended_Pictographic}|\p{Emoji_Presentation}/u)
|
||||
// \p{Emoji} is exactly "has an emoji form" (⚙ yes, ⛭ no); \p{Extended_Pictographic} also covers reserved emoji-range
|
||||
// code points such as ⛭ that have no emoji form, which is why settings uses it.
|
||||
expect(glyph, name).not.toMatch(/\p{Emoji}|\p{Emoji_Presentation}/u)
|
||||
}
|
||||
})
|
||||
|
||||
it('the emoji-form check tells a gear with an emoji form from one without', () => {
|
||||
const emojiForm = /\p{Emoji}|\p{Emoji_Presentation}/u
|
||||
expect('⚙').toMatch(emojiForm) // U+2699 takes an emoji form with U+FE0F
|
||||
expect('☀').toMatch(emojiForm)
|
||||
for (const glyph of ['⛭', '⌂', '⌘', 'ʔ', '⟳']) expect(glyph).not.toMatch(emojiForm)
|
||||
})
|
||||
|
||||
it('each icon does its one thing', () => {
|
||||
calls.length = 0
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
evaluateAgainstBaseline,
|
||||
findDanglingRefs,
|
||||
readBaseline,
|
||||
registeredToolNames,
|
||||
shippedSkillFiles,
|
||||
skillToolRefs,
|
||||
} from '../audit-skill-mcp-tools.mjs';
|
||||
|
||||
describe('skill ↔ MCP tool reference audit', () => {
|
||||
it('extracts ruflo tool references from both the init and the plugin prefix', () => {
|
||||
const text = [
|
||||
'allowed-tools: mcp__plugin_ruflo-core_ruflo__memory_search Bash',
|
||||
'Call `mcp__claude-flow__swarm_init` first.',
|
||||
].join('\n');
|
||||
expect(skillToolRefs(text)).toEqual([
|
||||
{ tool: 'memory_search', line: 1 },
|
||||
{ tool: 'swarm_init', line: 2 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('ignores other MCP servers, wildcards and scaffold placeholders', () => {
|
||||
const text = [
|
||||
'mcp__github__create_issue',
|
||||
'mcp__plugin_ruflo-ai-team_ruflo-ai-team__team_launch',
|
||||
'allowed-tools: mcp__claude-flow__*',
|
||||
'allowed-tools: mcp__plugin_ruflo-core_ruflo__tool1 mcp__plugin_ruflo-core_ruflo__tool2',
|
||||
].join('\n');
|
||||
expect(skillToolRefs(text)).toEqual([]);
|
||||
});
|
||||
|
||||
it('passes references that are already in the baseline', () => {
|
||||
const dangling = [{ key: 'plugins/a/skills/x/SKILL.md::old_tool' }];
|
||||
const result = evaluateAgainstBaseline(dangling, ['plugins/a/skills/x/SKILL.md::old_tool']);
|
||||
expect(result.ok).toBe(true);
|
||||
expect(result.unexpected).toEqual([]);
|
||||
});
|
||||
|
||||
it('fails a new reference even when the total count is unchanged', () => {
|
||||
const dangling = [{ key: 'plugins/a/skills/x/SKILL.md::new_tool' }];
|
||||
const result = evaluateAgainstBaseline(dangling, ['plugins/a/skills/x/SKILL.md::old_tool']);
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.unexpected).toEqual(['plugins/a/skills/x/SKILL.md::new_tool']);
|
||||
expect(result.fixed).toEqual(['plugins/a/skills/x/SKILL.md::old_tool']);
|
||||
});
|
||||
|
||||
it('reads a non-empty tool registry from mcp-client.ts', () => {
|
||||
const registered = registeredToolNames();
|
||||
// Spot-check tools that skills commonly reference, including ones whose
|
||||
// descriptions use double quotes or template literals.
|
||||
for (const name of ['memory_store', 'swarm_init', 'agentdb_pattern-search', 'hooks_pre-task', 'federation_bbs_sync']) {
|
||||
expect(registered.has(name)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('scans the shipped skill trees', () => {
|
||||
const files = shippedSkillFiles();
|
||||
expect(files.some((f) => f.startsWith('v3/@claude-flow/cli/.claude/skills/'))).toBe(true);
|
||||
expect(files.some((f) => f.startsWith('plugins/'))).toBe(true);
|
||||
});
|
||||
|
||||
it('has no dangling references beyond verification/skill-mcp-tool-baseline.json', () => {
|
||||
const result = evaluateAgainstBaseline(findDanglingRefs(), readBaseline());
|
||||
expect(result.unexpected).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Skill ↔ MCP tool reference audit. Sibling of scripts/audit-cli-mcp-tools.mjs (#1916).
|
||||
*
|
||||
* Skills tell Claude which ruflo MCP tools to call, in prose and in their
|
||||
* `allowed-tools` frontmatter:
|
||||
* - `mcp__claude-flow__<tool>` (skills copied by `ruflo init`)
|
||||
* - `mcp__plugin_ruflo-core_ruflo__<tool>` (Claude Code marketplace plugins)
|
||||
* A reference to a tool the CLI never registers fails at call time
|
||||
* (`MCP tool not found`) or silently grants nothing in `allowed-tools`.
|
||||
*
|
||||
* This guard scans every SKILL.md that ships to users:
|
||||
* - v3/@claude-flow/cli/.claude/skills/** (npm package, installed by init)
|
||||
* - plugins/** (marketplace plugins)
|
||||
* and checks each referenced tool name against the registry that
|
||||
* `mcp-client.ts` assembles, resolved the same way audit-cli-mcp-tools.mjs
|
||||
* resolves it (the `registerTools([ ... ])` spreads and their imports).
|
||||
*
|
||||
* Existing dangling references are carried in
|
||||
* verification/skill-mcp-tool-baseline.json as `<skill path>::<tool>`
|
||||
* entries. Like scripts/ci-test-ratchet.mjs the baseline is identity-based:
|
||||
* a reference that is not in it fails, even if the total count is unchanged.
|
||||
* Fixed entries never fail; they print a reminder to lower the floor.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/audit-skill-mcp-tools.mjs # exit 1 on a NEW dangling reference
|
||||
* node scripts/audit-skill-mcp-tools.mjs --json # machine-readable report
|
||||
* node scripts/audit-skill-mcp-tools.mjs --update-baseline # after fixing some (never to hide new ones)
|
||||
*/
|
||||
|
||||
import { existsSync, readdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join, relative, resolve, sep } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const DEFAULT_REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
||||
/** Skill trees that ship to users, relative to the repo root. */
|
||||
export const SKILL_ROOTS = ['v3/@claude-flow/cli/.claude/skills', 'plugins'];
|
||||
|
||||
/** MCP server prefixes that resolve to the ruflo CLI tool registry. */
|
||||
const RUFLO_REF_RE = /mcp__(?:claude-flow|plugin_ruflo-core_ruflo)__([A-Za-z0-9_-]+)(\*?)/g;
|
||||
|
||||
/**
|
||||
* Names that are deliberately not real tools: the scaffold example in
|
||||
* plugins/ruflo-plugin-creator/skills/create-plugin/SKILL.md uses
|
||||
* `tool1`/`tool2` as placeholders.
|
||||
*/
|
||||
export const PLACEHOLDER_TOOLS = new Set(['tool1', 'tool2']);
|
||||
|
||||
// A tool definition is `name: '<tool>',` followed by `description:` on the next
|
||||
// line. Descriptions use all three quote styles (the federation_bbs_* tools in
|
||||
// agentbbs-tools.ts use "..." and `...`), so accept any of them; matching only
|
||||
// single quotes would report those registered tools as dangling.
|
||||
const TOOL_DEF_RE = /name:\s*'([^']+)',\s*\n\s*description:\s*['"`]/g;
|
||||
|
||||
function toPosix(path) {
|
||||
return path.split(sep).join('/');
|
||||
}
|
||||
|
||||
function cliSrc(repoRoot) {
|
||||
return join(repoRoot, 'v3', '@claude-flow', 'cli', 'src');
|
||||
}
|
||||
|
||||
/** Same resolution as audit-cli-mcp-tools.mjs: '.js' import specifiers map to '.ts' sources. */
|
||||
function resolveImportPath(repoRoot, spec) {
|
||||
const p = spec.replace(/^\.\//, '').replace(/\.js$/, '.ts');
|
||||
return join(cliSrc(repoRoot), p);
|
||||
}
|
||||
|
||||
/** Files whose tool arrays are spread into `registerTools([ ... ])` in mcp-client.ts. */
|
||||
export function registeredToolSourceFiles(repoRoot = DEFAULT_REPO_ROOT) {
|
||||
const mcpClient = join(cliSrc(repoRoot), 'mcp-client.ts');
|
||||
const src = readFileSync(mcpClient, 'utf8');
|
||||
const block = (src.match(/registerTools\(\[([\s\S]*?)\]\);/) || [, ''])[1];
|
||||
const idents = new Set();
|
||||
for (const m of block.matchAll(/\.\.\.\s*([A-Za-z_$][\w$]*)\s*\(?\s*\)?/g)) idents.add(m[1]);
|
||||
const files = new Set();
|
||||
for (const id of idents) {
|
||||
const escaped = id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const im = src.match(new RegExp(`import\\s*\\{[^}]*\\b${escaped}\\b[^}]*\\}\\s*from\\s*['"]([^'"]+)['"]`));
|
||||
if (im) {
|
||||
const file = resolveImportPath(repoRoot, im[1]);
|
||||
if (existsSync(file)) files.add(file);
|
||||
continue;
|
||||
}
|
||||
// `...getXTools()` factories: guess mcp-tools/<x>-tools.ts, as the sibling audit does.
|
||||
const guess = id.replace(/^get/, '').replace(/^([A-Z])/, (c) => c.toLowerCase()).replace(/([A-Z])/g, '-$1').toLowerCase();
|
||||
const candidate = join(cliSrc(repoRoot), 'mcp-tools', `${guess}.ts`);
|
||||
if (existsSync(candidate)) files.add(candidate);
|
||||
}
|
||||
return [...files];
|
||||
}
|
||||
|
||||
/** Every tool name the CLI registers. */
|
||||
export function registeredToolNames(repoRoot = DEFAULT_REPO_ROOT) {
|
||||
const names = new Set();
|
||||
for (const file of registeredToolSourceFiles(repoRoot)) {
|
||||
const src = readFileSync(file, 'utf8');
|
||||
for (const m of src.matchAll(TOOL_DEF_RE)) names.add(m[1]);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/** Ruflo MCP tool references in one SKILL.md body: [{ tool, line }]. */
|
||||
export function skillToolRefs(text) {
|
||||
const refs = [];
|
||||
for (const m of text.matchAll(RUFLO_REF_RE)) {
|
||||
const [, tool, star] = m;
|
||||
if (star || PLACEHOLDER_TOOLS.has(tool)) continue;
|
||||
refs.push({ tool, line: text.slice(0, m.index).split('\n').length });
|
||||
}
|
||||
return refs;
|
||||
}
|
||||
|
||||
function walkSkillFiles(dir, out) {
|
||||
if (!existsSync(dir)) return out;
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
if (entry.name === 'node_modules' || entry.name === '.git') continue;
|
||||
const full = join(dir, entry.name);
|
||||
if (entry.isDirectory()) walkSkillFiles(full, out);
|
||||
else if (entry.isFile() && entry.name === 'SKILL.md') out.push(full);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Every shipped SKILL.md, as repo-relative POSIX paths, sorted. */
|
||||
export function shippedSkillFiles(repoRoot = DEFAULT_REPO_ROOT) {
|
||||
const files = [];
|
||||
for (const root of SKILL_ROOTS) walkSkillFiles(join(repoRoot, root), files);
|
||||
return files.map((f) => toPosix(relative(repoRoot, f))).sort();
|
||||
}
|
||||
|
||||
/** Dangling references across shipped skills: [{ file, tool, line, key }]. */
|
||||
export function findDanglingRefs(repoRoot = DEFAULT_REPO_ROOT, registered = registeredToolNames(repoRoot)) {
|
||||
const dangling = [];
|
||||
for (const file of shippedSkillFiles(repoRoot)) {
|
||||
const text = readFileSync(join(repoRoot, file), 'utf8');
|
||||
for (const ref of skillToolRefs(text)) {
|
||||
if (!registered.has(ref.tool)) dangling.push({ file, tool: ref.tool, line: ref.line, key: `${file}::${ref.tool}` });
|
||||
}
|
||||
}
|
||||
return dangling;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare current dangling references with the baseline entries.
|
||||
* ok is false only when a reference is not already in the baseline.
|
||||
*/
|
||||
export function evaluateAgainstBaseline(dangling, baselineEntries) {
|
||||
const known = new Set(baselineEntries);
|
||||
const current = [...new Set(dangling.map((d) => d.key))].sort();
|
||||
const currentSet = new Set(current);
|
||||
const unexpected = current.filter((key) => !known.has(key));
|
||||
const fixed = [...known].filter((key) => !currentSet.has(key)).sort();
|
||||
return { ok: unexpected.length === 0, current, unexpected, fixed };
|
||||
}
|
||||
|
||||
export function baselinePath(repoRoot = DEFAULT_REPO_ROOT) {
|
||||
return join(repoRoot, 'verification', 'skill-mcp-tool-baseline.json');
|
||||
}
|
||||
|
||||
export function readBaseline(repoRoot = DEFAULT_REPO_ROOT) {
|
||||
const file = baselinePath(repoRoot);
|
||||
if (!existsSync(file)) return [];
|
||||
const parsed = JSON.parse(readFileSync(file, 'utf8'));
|
||||
return Array.isArray(parsed.knownDangling) ? parsed.knownDangling : [];
|
||||
}
|
||||
|
||||
function main(argv) {
|
||||
const repoRoot = DEFAULT_REPO_ROOT;
|
||||
const registered = registeredToolNames(repoRoot);
|
||||
const dangling = findDanglingRefs(repoRoot, registered);
|
||||
|
||||
if (argv.includes('--update-baseline')) {
|
||||
const knownDangling = [...new Set(dangling.map((d) => d.key))].sort();
|
||||
const next = {
|
||||
_comment: 'Monotone-decreasing baseline of shipped SKILL.md files that reference a ruflo MCP tool not registered by mcp-client.ts (entries are <skill path>::<tool>). Fix one, then re-run with --update-baseline to lower the floor. NEVER add entries to hide a new reference.',
|
||||
danglingCount: knownDangling.length,
|
||||
knownDangling,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
writeFileSync(baselinePath(repoRoot), JSON.stringify(next, null, 2) + '\n', 'utf8');
|
||||
console.log(`baseline updated → ${knownDangling.length} dangling skill reference(s)`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = evaluateAgainstBaseline(dangling, readBaseline(repoRoot));
|
||||
if (argv.includes('--json')) {
|
||||
console.log(JSON.stringify({
|
||||
registeredToolCount: registered.size,
|
||||
skillFilesScanned: shippedSkillFiles(repoRoot).length,
|
||||
danglingCount: result.current.length,
|
||||
unexpected: result.unexpected,
|
||||
fixed: result.fixed,
|
||||
dangling: dangling.map((d) => ({ tool: d.tool, where: `${d.file}:${d.line}` })),
|
||||
}, null, 2));
|
||||
return result.ok ? 0 : 1;
|
||||
}
|
||||
|
||||
console.log(`Skill ↔ MCP tool references: ${registered.size} registered tools, ${shippedSkillFiles(repoRoot).length} shipped SKILL.md files, ${result.current.length} dangling reference(s) (baseline ${result.current.length - result.unexpected.length + result.fixed.length})`);
|
||||
if (result.ok) {
|
||||
console.log(' ✓ no NEW dangling references (known ones are listed in verification/skill-mcp-tool-baseline.json)');
|
||||
} else {
|
||||
console.log(' ✗ NEW dangling reference(s). Use a tool name registered in v3/@claude-flow/cli/src/mcp-tools/*.ts:');
|
||||
for (const key of result.unexpected) {
|
||||
for (const d of dangling.filter((x) => x.key === key)) console.log(` '${d.tool}' ${d.file}:${d.line}`);
|
||||
}
|
||||
}
|
||||
if (result.fixed.length > 0) {
|
||||
console.log(` Progress: ${result.fixed.length} baseline entr${result.fixed.length === 1 ? 'y is' : 'ies are'} fixed. Run: node scripts/audit-skill-mcp-tools.mjs --update-baseline`);
|
||||
}
|
||||
return result.ok ? 0 : 1;
|
||||
}
|
||||
|
||||
// Compare real paths, as check-guard-tool-names.mjs does: Node canonicalizes the
|
||||
// module URL, while argv can keep a symlinked path (including macOS /var ->
|
||||
// /private/var). A string compare would silently skip the audit there.
|
||||
if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
process.exit(main(process.argv.slice(2)));
|
||||
}
|
||||
+5
-5
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@claude-flow/browser",
|
||||
"version": "3.0.0-alpha.4",
|
||||
"version": "3.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@claude-flow/browser",
|
||||
"version": "3.0.0-alpha.4",
|
||||
"version": "3.0.0",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -5440,9 +5440,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/agentic-flow": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/agentic-flow/-/agentic-flow-2.1.3.tgz",
|
||||
"integrity": "sha512-HlCaraWsEwndmqrYAbVYryeso5uFuCzMSN2LJoM9BneU8t+I80NE87Seu1n1+Z8NZjIsVPPpHA8jrXk+MQYGZw==",
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/agentic-flow/-/agentic-flow-2.1.4.tgz",
|
||||
"integrity": "sha512-bQF6z68C3VDTS7Pk2iruLPV0yRhCStje9V3emKfvBSrjCE4muC6ZifmSqZp7DLb8pkcZTIAIk7SIzmDA6pckyg==",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: "Verification & Quality Assurance"
|
||||
description: |
|
||||
Comprehensive truth scoring, code quality verification, and automatic rollback system with 0.95 accuracy threshold for ensuring high-quality agent outputs and codebase reliability.
|
||||
Check code quality and change risk with ruflo's shipped analysis commands (analyze diff, analyze complexity, analyze code), and run or extend ruflo's own CI regression guards. Use when assessing a change's risk, finding complexity hot spots, or adding a regression guard to ruflo. The truth-scoring and auto-rollback commands described later in this file are design notes, not shipped CLI commands.
|
||||
---
|
||||
|
||||
# Verification & Quality Assurance Skill
|
||||
@@ -62,31 +62,34 @@ node plugins/ruflo-core/scripts/witness/history.mjs --history verification/macos
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Ruflo installed (`npx ruflo@alpha`)
|
||||
- Ruflo installed (`npx ruflo@latest`)
|
||||
- Git repository (for rollback features)
|
||||
- Node.js 18+ (for dashboard features)
|
||||
- `@noble/ed25519` (for the witness verifier — a single runtime dep, `npm i @noble/ed25519`)
|
||||
|
||||
## Quick Start
|
||||
|
||||
These commands ship in the current CLI:
|
||||
|
||||
```bash
|
||||
# View current truth scores
|
||||
npx ruflo@alpha truth
|
||||
# Change risk since HEAD~1 (without --risk it also shows classification and reviewers)
|
||||
npx ruflo@latest analyze diff HEAD~1 --risk
|
||||
|
||||
# Run verification check
|
||||
npx ruflo@alpha verify check
|
||||
# Complexity hot spots in a directory
|
||||
npx ruflo@latest analyze complexity src/ --threshold 15
|
||||
|
||||
# Verify specific file with custom threshold
|
||||
npx ruflo@alpha verify check --file src/app.js --threshold 0.98
|
||||
|
||||
# Rollback last failed verification
|
||||
npx ruflo@alpha verify rollback --last-good
|
||||
# Size, functions and TODOs per file
|
||||
npx ruflo@latest analyze code -p ./src
|
||||
```
|
||||
|
||||
There is no truth-scoring, `verify check` or `verify rollback` command (`ruflo verify` only checks an installed ruflo package against its signed witness manifest). To verify agent output, run the project's own tests, linters and type checks, and roll back with git (`git restore <file>`, `git revert <commit>`). Inside the ruflo repo, run the guards in [Run the guards locally](#run-the-guards-locally).
|
||||
|
||||
---
|
||||
|
||||
## Complete Guide
|
||||
|
||||
> **Design notes, not shipped.** Everything below describes a planned truth-scoring, verification and rollback surface. `ruflo truth`, `ruflo verify check` and `ruflo verify rollback` are not commands in the current CLI, so do not run the examples below; use the commands in [Quick Start](#quick-start) instead.
|
||||
|
||||
### Truth Scoring System
|
||||
|
||||
#### View Truth Metrics
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { existsSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { DEFAULT_INIT_OPTIONS, FULL_INIT_OPTIONS, type InitOptions } from '../src/init/types.js';
|
||||
import { executeInit } from '../src/init/executor.js';
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function skillsOnly(base: InitOptions): InitOptions {
|
||||
const targetDir = mkdtempSync(join(tmpdir(), 'ruflo-init-skills-v3-'));
|
||||
tempDirs.push(targetDir);
|
||||
return {
|
||||
...base,
|
||||
targetDir,
|
||||
force: true,
|
||||
skipGlobalClaudeMd: true,
|
||||
components: {
|
||||
...base.components,
|
||||
settings: false, skills: true, commands: false, agents: false, helpers: false,
|
||||
statusline: false, mcp: false, runtime: false, claudeMd: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function installedSkills(targetDir: string): string[] {
|
||||
const dir = join(targetDir, '.claude', 'skills');
|
||||
return existsSync(dir) ? readdirSync(dir) : [];
|
||||
}
|
||||
|
||||
describe('v3 implementation skills are opt-in (ADR-128, matches agents.v3)', () => {
|
||||
it('default options do not select the v3 skill group', () => {
|
||||
expect(DEFAULT_INIT_OPTIONS.skills.v3).toBe(false);
|
||||
expect(DEFAULT_INIT_OPTIONS.agents.v3).toBe(false);
|
||||
});
|
||||
|
||||
it('--full still selects the v3 skill group', () => {
|
||||
expect(FULL_INIT_OPTIONS.skills.v3).toBe(true);
|
||||
});
|
||||
|
||||
it('default init installs no v3-* skills', async () => {
|
||||
const options = skillsOnly(DEFAULT_INIT_OPTIONS);
|
||||
const result = await executeInit(options);
|
||||
expect(result.success).toBe(true);
|
||||
const skills = installedSkills(options.targetDir!);
|
||||
expect(skills.length).toBeGreaterThan(0);
|
||||
expect(skills.filter((name) => name.startsWith('v3-'))).toEqual([]);
|
||||
});
|
||||
|
||||
it('full init still installs the v3-* skills', async () => {
|
||||
const options = skillsOnly(FULL_INIT_OPTIONS);
|
||||
const result = await executeInit(options);
|
||||
expect(result.success).toBe(true);
|
||||
expect(installedSkills(options.targetDir!).filter((name) => name.startsWith('v3-')).length).toBe(9);
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { DiffClassifier, createDiffClassifier, type DiffAnalysis, type FileDiff } from '../../src/ruvector/diff-classifier';
|
||||
import { DiffClassifier, assessFileRisk, createDiffClassifier, suggestReviewers, type DiffAnalysis, type DiffFile, type FileDiff } from '../../src/ruvector/diff-classifier';
|
||||
|
||||
// Mock the @ruvector/diff module
|
||||
vi.mock('@ruvector/diff', () => ({
|
||||
@@ -295,6 +295,36 @@ diff --git a/file2.ts b/file2.ts
|
||||
const files = classifier.parseDiff(diff);
|
||||
expect(files[0].classification.impactLevel).toBe('low');
|
||||
});
|
||||
|
||||
it('treats encryption changes as security-sensitive across diff and file-risk paths', () => {
|
||||
const path = 'packages/encryption/src/bytea.ts';
|
||||
const diff = `diff --git a/${path} b/${path}
|
||||
--- a/${path}
|
||||
+++ b/${path}
|
||||
@@ -1 +1 @@
|
||||
-old
|
||||
+new
|
||||
`;
|
||||
const classification = classifier.parseDiff(diff)[0].classification;
|
||||
expect(classification.impactLevel).toBe('critical');
|
||||
expect(classification.suggestedReviewers).toContain('security-team');
|
||||
expect(classification.testingStrategy).toContain('security-audit');
|
||||
expect(classification.riskFactors).toContain('Security-sensitive code');
|
||||
|
||||
const file: DiffFile = { path, status: 'modified', additions: 1, deletions: 1 };
|
||||
const risk = assessFileRisk(file);
|
||||
expect(risk).toMatchObject({ risk: 'high', score: 40, reasons: ['Security-sensitive file'] });
|
||||
expect(suggestReviewers([file], [risk])).toContain('security-team');
|
||||
});
|
||||
|
||||
it('does not flag unrelated path tokens as security-sensitive', () => {
|
||||
for (const path of ['src/tokenizer.ts', 'src/author.ts', 'src/cryptic.ts']) {
|
||||
const file: DiffFile = { path, status: 'modified', additions: 1, deletions: 1 };
|
||||
expect(assessFileRisk(file).reasons).not.toContain('Security-sensitive file');
|
||||
const diff = `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-old\n+new\n`;
|
||||
expect(classifier.parseDiff(diff)[0].classification.impactLevel).toBe('low');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('reviewer suggestions', () => {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* #4124: in a pnpm/yarn/bun project `npm audit --json` prints
|
||||
* {"error":{"code":"ENOLOCK",...}} and no `vulnerabilities` key. `security
|
||||
* scan` (deps phase) and `security cve` read that as a clean tree and exited
|
||||
* 0, so a release check got a false all-clear. They must report "could not
|
||||
* scan" instead, and the persisted record must not make the statusline CLEAN.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { spawnSync } from 'child_process';
|
||||
import { mkdtempSync, rmSync, writeFileSync, readFileSync, unlinkSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { tmpdir } from 'os';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { interpretNpmAudit } from '../src/commands/security.js';
|
||||
import { getSecurityStatus } from '../src/funnel/local-signals.js';
|
||||
|
||||
const CLI_BIN = fileURLToPath(new URL('../bin/cli.js', import.meta.url));
|
||||
const ENOLOCK = JSON.stringify({ error: { code: 'ENOLOCK', summary: 'This command requires an existing lockfile.' } });
|
||||
|
||||
describe('interpretNpmAudit', () => {
|
||||
it('treats an npm error object as could-not-scan, with the right package manager hint', () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'audit-4124-'));
|
||||
try {
|
||||
writeFileSync(join(dir, 'pnpm-lock.yaml'), 'lockfileVersion: 9.0\n');
|
||||
const result = interpretNpmAudit(ENOLOCK, dir);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.reason).toContain('ENOLOCK');
|
||||
expect(result.reason).toContain('pnpm audit');
|
||||
}
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
it('rejects output with no vulnerability report and non-JSON output', () => {
|
||||
expect(interpretNpmAudit('{}').ok).toBe(false);
|
||||
expect(interpretNpmAudit('{"vulnerabilities":[]}').ok).toBe(false);
|
||||
expect(interpretNpmAudit('not json').ok).toBe(false);
|
||||
});
|
||||
it('accepts a real report, including an empty one', () => {
|
||||
expect(interpretNpmAudit(JSON.stringify({ auditReportVersion: 2, vulnerabilities: {}, metadata: {} }))).toEqual({ ok: true, vulnerabilities: {} });
|
||||
});
|
||||
});
|
||||
|
||||
describe('security scan / cve on a lockfile-less (pnpm) project', () => {
|
||||
let dir: string;
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'audit-4124-cli-'));
|
||||
writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'pnpm-fixture', version: '1.0.0' }));
|
||||
writeFileSync(join(dir, 'pnpm-lock.yaml'), 'lockfileVersion: 9.0\n');
|
||||
});
|
||||
afterEach(() => rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
it('scan --type deps exits non-zero, says the scan did not run, and persists an incomplete record', () => {
|
||||
const res = spawnSync(process.execPath, [CLI_BIN, 'security', 'scan', '--target', dir, '--depth', 'quick', '--type', 'deps'], { encoding: 'utf-8', timeout: 60_000 });
|
||||
const out = `${res.stdout}${res.stderr}`;
|
||||
expect(res.status).not.toBe(0);
|
||||
expect(out).toContain('Dependency scan skipped');
|
||||
expect(out).toContain('pnpm audit');
|
||||
expect(out).not.toContain('No security issues found!');
|
||||
const record = JSON.parse(readFileSync(join(dir, '.claude', 'security-scans', 'scan-deps-quick.json'), 'utf-8'));
|
||||
expect(record.incomplete).toBe(true);
|
||||
expect(getSecurityStatus(dir).status).toBe('PENDING');
|
||||
});
|
||||
|
||||
it('an explicit dependency scan without package.json is incomplete, not CLEAN', () => {
|
||||
unlinkSync(join(dir, 'package.json'));
|
||||
const res = spawnSync(process.execPath, [CLI_BIN, 'security', 'scan', '--target', dir, '--depth', 'quick', '--type', 'deps'], { encoding: 'utf-8', timeout: 60_000 });
|
||||
expect(res.status).toBe(2);
|
||||
expect(`${res.stdout}${res.stderr}`).toContain('Dependency scan skipped');
|
||||
expect(getSecurityStatus(dir).status).toBe('PENDING');
|
||||
});
|
||||
|
||||
it('cve --list exits non-zero instead of printing "No known vulnerabilities"', () => {
|
||||
const res = spawnSync(process.execPath, [CLI_BIN, 'security', 'cve', '--list'], { cwd: dir, encoding: 'utf-8', timeout: 60_000 });
|
||||
const out = `${res.stdout}${res.stderr}`;
|
||||
expect(res.status).not.toBe(0);
|
||||
expect(out).not.toContain('No known vulnerabilities');
|
||||
expect(out).toContain('Could not check dependencies');
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,7 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { getGitDiffNumstat, getGitDiffNumstatAsync } from '../src/ruvector/diff-classifier.js';
|
||||
|
||||
// ============================================================================
|
||||
// 1. Path Traversal Prevention in Session Tools
|
||||
@@ -60,42 +61,35 @@ describe('Path Traversal Prevention', () => {
|
||||
// 2. Command Injection Prevention in Diff Classifier
|
||||
// ============================================================================
|
||||
describe('Command Injection Prevention - Git Ref Validation', () => {
|
||||
// Reproduce validateGitRef from diff-classifier.ts:367-382
|
||||
function validateGitRef(ref: string): void {
|
||||
if (!/^[a-zA-Z0-9_\-./~^@]+$/.test(ref)) {
|
||||
throw new Error('Invalid git ref: contains unsafe characters');
|
||||
}
|
||||
if (ref.includes('..') && !ref.match(/^[a-zA-Z0-9_\-]+\.\.\.?[a-zA-Z0-9_\-]+$/)) {
|
||||
if (!/^\w+\.\.[.\w]+$/.test(ref)) {
|
||||
throw new Error('Invalid git ref: suspicious pattern');
|
||||
}
|
||||
}
|
||||
if (ref.length > 256) {
|
||||
throw new Error('Invalid git ref: too long');
|
||||
}
|
||||
}
|
||||
|
||||
it('should allow valid git refs', () => {
|
||||
expect(() => validateGitRef('HEAD')).not.toThrow();
|
||||
expect(() => validateGitRef('main')).not.toThrow();
|
||||
expect(() => validateGitRef('feature/my-branch')).not.toThrow();
|
||||
expect(() => validateGitRef('v1.0.0')).not.toThrow();
|
||||
expect(() => validateGitRef('HEAD~3')).not.toThrow();
|
||||
expect(() => validateGitRef('HEAD^')).not.toThrow();
|
||||
expect(() => validateGitRef('origin/main')).not.toThrow();
|
||||
for (const ref of ['HEAD', 'HEAD~1', 'HEAD^', 'origin/main',
|
||||
'HEAD~1..', 'HEAD~1..HEAD', 'origin/main..origin/main',
|
||||
'HEAD~3...origin/main']) {
|
||||
expect(() => getGitDiffNumstat(ref), ref).not.toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it('should allow normal ranges through the async path', async () => {
|
||||
await expect(getGitDiffNumstatAsync('HEAD~1..HEAD')).resolves.toEqual(expect.any(Array));
|
||||
await expect(getGitDiffNumstatAsync('origin/main..origin/main')).resolves.toEqual(expect.any(Array));
|
||||
});
|
||||
|
||||
it('should reject command injection via shell metacharacters', () => {
|
||||
expect(() => validateGitRef('HEAD; rm -rf /')).toThrow('unsafe characters');
|
||||
expect(() => validateGitRef('HEAD && cat /etc/passwd')).toThrow('unsafe characters');
|
||||
expect(() => validateGitRef('HEAD | whoami')).toThrow('unsafe characters');
|
||||
expect(() => validateGitRef('$(whoami)')).toThrow('unsafe characters');
|
||||
expect(() => validateGitRef('`whoami`')).toThrow('unsafe characters');
|
||||
for (const ref of ['HEAD; rm -rf /', 'HEAD && cat /etc/passwd',
|
||||
'HEAD | whoami', '$(whoami)', '`whoami`', '--help']) {
|
||||
expect(() => getGitDiffNumstat(ref), ref).toThrow('unsafe characters');
|
||||
}
|
||||
});
|
||||
|
||||
it('should reject traversal and multiple range separators', () => {
|
||||
for (const ref of ['foo/../bar', 'HEAD..../feature', 'main..feature..other']) {
|
||||
expect(() => getGitDiffNumstat(ref), ref).toThrow('suspicious pattern');
|
||||
}
|
||||
});
|
||||
|
||||
it('should reject refs that are too long (DoS prevention)', () => {
|
||||
const longRef = 'a'.repeat(257);
|
||||
expect(() => validateGitRef(longRef)).toThrow('too long');
|
||||
expect(() => getGitDiffNumstat(longRef)).toThrow('too long');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -72,6 +72,16 @@ describe('security scan code patterns: false positives seen on a real tree', ()
|
||||
it('does not report a URL or a pattern inside a string as a comment boundary', async () => {
|
||||
expect(await findings({ 'u.ts': "const u = 'http://x/*'; const v = 1;\n" })).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not report shell-call examples inside strings or static command arguments', async () => {
|
||||
expect(await findings({
|
||||
'docs.js': [
|
||||
'const example = "execSync(`git log ${branch}`)";',
|
||||
"execSync('git ' + 'status');",
|
||||
'execSync(`echo \\${literal}`);',
|
||||
].join('\n'),
|
||||
})).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('security scan code patterns: real findings still reported', () => {
|
||||
@@ -85,6 +95,19 @@ describe('security scan code patterns: real findings still reported', () => {
|
||||
}))).toEqual(['Command Injection b.ts:1', 'Command Injection b.ts:2']);
|
||||
});
|
||||
|
||||
it('reports interpolated exec calls even when child_process was imported on another line', async () => {
|
||||
expect(types(await findings({
|
||||
'shell.js': [
|
||||
"const { execSync, execFileSync } = require('child_process');",
|
||||
'function run(req) { return execSync(`git log ${req.query.branch}`); }',
|
||||
'function run2(req) { return execSync("git log " + req.query.branch); }',
|
||||
'function run3(req) { return childProcess.exec(`git show ${req.query.ref}`); }',
|
||||
"execFileSync('git', ['log', branch]);",
|
||||
"execSync('git status');",
|
||||
].join('\n'),
|
||||
}))).toEqual(['Command Injection shell.js:2', 'Command Injection shell.js:3', 'Command Injection shell.js:4']);
|
||||
});
|
||||
|
||||
it('reports an interpolated value in SQL, also next to a placeholder', async () => {
|
||||
expect(types(await findings({
|
||||
'c.ts': 'const sql = `SELECT * FROM users WHERE id = ${id}`;\nsql += ` AND a = $${n} AND b = ${name}`;\n',
|
||||
@@ -272,4 +295,3 @@ describe('security scan code patterns: shapes the narrowing must not hide', () =
|
||||
expect(Date.now() - started).toBeLessThan(1_000);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -28,6 +28,13 @@ beforeEach(() => {
|
||||
join(scanTarget, 'package.json'),
|
||||
JSON.stringify({ name: 'security-scan-persist-fixture', version: '1.0.0' }),
|
||||
);
|
||||
// #4124: without a lockfile `npm audit` fails (ENOLOCK), which is now
|
||||
// reported as "could not scan" instead of clean. An empty v3 lockfile lets
|
||||
// npm audit produce a real (empty) report offline.
|
||||
writeFileSync(
|
||||
join(scanTarget, 'package-lock.json'),
|
||||
JSON.stringify({ name: 'security-scan-persist-fixture', version: '1.0.0', lockfileVersion: 3, requires: true, packages: { '': { name: 'security-scan-persist-fixture', version: '1.0.0' } } }),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
* - every rule is tested after comment text is blanked, so a comment naming `child_process.execFile` or `eval(` is
|
||||
* not a finding;
|
||||
* - eval needs a word start: "retrieval (" in prose is not a call; `eval(` and `window.eval(` still are;
|
||||
* - command injection keeps the old rule's reach (any `exec` after `child_process` on the line), and no longer skips
|
||||
* execSync as `exec[^S]` did;
|
||||
* - command injection keeps the old rule's reach (any `exec` after `child_process` on the line), and also catches
|
||||
* dynamic exec/execSync command strings when the import was on another line;
|
||||
* - a pg placeholder such as `$${paramCount + 1}` is a parameter number, not a value in the SQL text. It is exempt only
|
||||
* when its expression is a number, a loop letter, `params.length`-style, or a name containing `param` or `placeholder`, it
|
||||
* stands where SQL takes a value, and it is not inside a quoted SQL string.
|
||||
@@ -24,6 +24,44 @@ export type CodePattern = {
|
||||
/** No `g` flag, so `test` keeps no lastIndex between lines. */
|
||||
const re = (pattern: RegExp) => (line: string) => pattern.test(line)
|
||||
|
||||
/** Detect a dynamic shell command at an exec/execSync call site, independent of its import. */
|
||||
const interpolatedExec = (line: string): boolean => {
|
||||
let quote: "'" | '"' | '`' | null = null
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const ch = line[i]
|
||||
if (quote !== null) {
|
||||
if (ch === '\\') { i++; continue }
|
||||
if (ch === quote) quote = null
|
||||
continue
|
||||
}
|
||||
if (ch === "'" || ch === '"' || ch === '`') { quote = ch; continue }
|
||||
if (i > 0 && /[\w$]/.test(line[i - 1])) continue
|
||||
const name = line.startsWith('execSync', i) ? 'execSync' : line.startsWith('exec', i) ? 'exec' : ''
|
||||
if (!name) continue
|
||||
let arg = i + name.length
|
||||
while (/\s/.test(line[arg] ?? '')) arg++
|
||||
if (line[arg++] !== '(') continue
|
||||
while (/\s/.test(line[arg] ?? '')) arg++
|
||||
const delimiter = line[arg]
|
||||
if (delimiter !== '`' && delimiter !== "'" && delimiter !== '"') continue
|
||||
for (let end = arg + 1; end < line.length; end++) {
|
||||
if (line[end] === '\\') { end++; continue }
|
||||
if (delimiter === '`' && line[end] === '$' && line[end + 1] === '{') return true
|
||||
if (line[end] !== delimiter) continue
|
||||
if (delimiter !== '`') {
|
||||
let next = end + 1
|
||||
while (/\s/.test(line[next] ?? '')) next++
|
||||
if (line[next++] === '+') {
|
||||
while (/\s/.test(line[next] ?? '')) next++
|
||||
if (/[A-Za-z_$]/.test(line[next] ?? '')) return true
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// A `.length` counts only on a param-, value- or arg-named array: `req.body.length` is whatever the client sent.
|
||||
const COUNTER = /^\s*(?:\d+|[ijkn]|(?:[A-Za-z_$][\w$]*(?:Params?|Placeholders?|Values?|Args?)|params?|placeholders?|values?|args?)\.length|[A-Za-z_$]*(?:[Pp]aram|[Pp]laceholder)[\w$]*)\s*(?:[+-]\s*\d+\s*)?$/
|
||||
// Where a pg parameter stands in SQL: after a comparison, a list or call opener, or a clause keyword.
|
||||
@@ -70,7 +108,7 @@ export const CODE_PATTERNS: readonly CodePattern[] = [
|
||||
{ match: re(/(?<![\w$])eval\s*\(/), type: 'Eval Usage', severity: 'medium', desc: 'eval() can execute arbitrary code' },
|
||||
{ match: re(/innerHTML\s*=/), type: 'innerHTML', severity: 'medium', desc: 'XSS risk with innerHTML' },
|
||||
{ match: re(/dangerouslySetInnerHTML/), type: 'React XSS', severity: 'medium', desc: 'React XSS risk' },
|
||||
{ match: re(/child_process.*exec/), type: 'Command Injection', severity: 'high', desc: 'Possible command injection' },
|
||||
{ match: line => /child_process.*exec/.test(line) || interpolatedExec(line), type: 'Command Injection', severity: 'high', desc: 'Possible command injection' },
|
||||
{ match: line => sqlInterpolation(line) && sqlInterpolation(withoutPlaceholders(line)), type: 'SQL Injection', severity: 'high', desc: 'Possible SQL injection' },
|
||||
]
|
||||
|
||||
|
||||
@@ -182,6 +182,7 @@ const scanCommand: Command = {
|
||||
|
||||
const findings: ScanFinding[] = [];
|
||||
let criticalCount = 0, highCount = 0, mediumCount = 0, lowCount = 0;
|
||||
let depsSkipped: string | undefined;
|
||||
|
||||
try {
|
||||
const fs = await import('fs');
|
||||
@@ -207,30 +208,33 @@ const scanCommand: Command = {
|
||||
auditResult = (auditErr instanceof Error && 'stdout' in auditErr ? (auditErr as { stdout: string }).stdout : undefined) || '{}';
|
||||
}
|
||||
|
||||
try {
|
||||
const audit = JSON.parse(auditResult);
|
||||
if (audit.vulnerabilities) {
|
||||
for (const [pkg, vuln] of Object.entries(audit.vulnerabilities as Record<string, { severity: string; via: Array<{ title?: string; url?: string }> }>)) {
|
||||
const sev = vuln.severity || 'low';
|
||||
const title = Array.isArray(vuln.via) && vuln.via[0]?.title ? vuln.via[0].title : 'Vulnerability';
|
||||
if (sev === 'critical') criticalCount++;
|
||||
else if (sev === 'high') highCount++;
|
||||
else if (sev === 'moderate' || sev === 'medium') mediumCount++;
|
||||
else lowCount++;
|
||||
const audit = interpretNpmAudit(auditResult, path.resolve(target));
|
||||
if (!audit.ok) {
|
||||
depsSkipped = audit.reason;
|
||||
} else {
|
||||
for (const [pkg, vuln] of Object.entries(audit.vulnerabilities)) {
|
||||
const sev = vuln.severity || 'low';
|
||||
const first = Array.isArray(vuln.via) ? vuln.via[0] : undefined;
|
||||
const title = typeof first === 'object' && first?.title ? first.title : 'Vulnerability';
|
||||
if (sev === 'critical') criticalCount++;
|
||||
else if (sev === 'high') highCount++;
|
||||
else if (sev === 'moderate' || sev === 'medium') mediumCount++;
|
||||
else lowCount++;
|
||||
|
||||
findings.push({
|
||||
severity: sev === 'critical' ? 'critical' :
|
||||
sev === 'high' ? 'high' :
|
||||
sev === 'moderate' || sev === 'medium' ? 'medium' : 'low',
|
||||
type: 'Dependency CVE',
|
||||
location: `package.json:${pkg}`,
|
||||
description: title.substring(0, 35),
|
||||
});
|
||||
}
|
||||
findings.push({
|
||||
severity: sev === 'critical' ? 'critical' :
|
||||
sev === 'high' ? 'high' :
|
||||
sev === 'moderate' || sev === 'medium' ? 'medium' : 'low',
|
||||
type: 'Dependency CVE',
|
||||
location: `package.json:${pkg}`,
|
||||
description: title.substring(0, 35),
|
||||
});
|
||||
}
|
||||
} catch { /* JSON parse failed, no vulns */ }
|
||||
}
|
||||
} else {
|
||||
depsSkipped = 'No package.json found in the scan target; dependency scan could not run.';
|
||||
}
|
||||
} catch { /* npm audit failed */ }
|
||||
} catch (err) { depsSkipped = `npm audit could not run: ${err instanceof Error ? err.message : String(err)}`; }
|
||||
}
|
||||
|
||||
// Phase 2: Scan for hardcoded secrets
|
||||
@@ -359,9 +363,12 @@ const scanCommand: Command = {
|
||||
if (findings.length > 20) {
|
||||
output.writeln(output.dim(`... and ${findings.length - 20} more issues`));
|
||||
}
|
||||
} else if (depsSkipped) {
|
||||
output.writeln(output.warning('No issues found by the checks that ran, but the dependency scan did not run.'));
|
||||
} else {
|
||||
output.writeln(output.success('No security issues found!'));
|
||||
}
|
||||
if (depsSkipped) output.writeln(output.warning(`Dependency scan skipped: ${depsSkipped}`));
|
||||
|
||||
output.writeln();
|
||||
output.printBox([
|
||||
@@ -386,6 +393,7 @@ const scanCommand: Command = {
|
||||
low: lowCount,
|
||||
total: findings.length,
|
||||
},
|
||||
...(depsSkipped ? { incomplete: true, skipped: { deps: depsSkipped } } : {}),
|
||||
findings,
|
||||
};
|
||||
|
||||
@@ -422,6 +430,10 @@ const scanCommand: Command = {
|
||||
if (outputFormat === 'json') output.printJson(record);
|
||||
else if (outputFormat === 'sarif') output.printJson(scanSarif(findings));
|
||||
|
||||
if (depsSkipped) {
|
||||
if (outputFormat !== 'text') output.printError(`Dependency scan skipped: ${depsSkipped}`);
|
||||
return { success: false, exitCode: 2 };
|
||||
}
|
||||
return { success: findings.length === 0 || (criticalCount === 0 && highCount === 0) };
|
||||
} catch (error) {
|
||||
if (outputFormat === 'text') spinner.fail('Scan failed');
|
||||
@@ -431,6 +443,43 @@ const scanCommand: Command = {
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* #4124: `npm audit` can fail without exiting through the vulnerability path.
|
||||
* In a pnpm/yarn/bun project there is no package-lock.json, so it prints
|
||||
* `{"error":{"code":"ENOLOCK",...}}`. That has no `vulnerabilities` key, and
|
||||
* both `scan` and `cve` used to read it as a clean tree. Only a report with a
|
||||
* `vulnerabilities` object counts as a scan; anything else is "could not scan".
|
||||
*/
|
||||
type NpmAuditVuln = { severity: string; via: Array<{ title?: string; url?: string; source?: number; name?: string } | string> };
|
||||
export type NpmAuditResult =
|
||||
| { ok: true; vulnerabilities: Record<string, NpmAuditVuln> }
|
||||
| { ok: false; reason: string };
|
||||
export function interpretNpmAudit(raw: string, dir?: string): NpmAuditResult {
|
||||
let audit: { vulnerabilities?: unknown; error?: { code?: string; summary?: string } };
|
||||
try {
|
||||
audit = JSON.parse(raw);
|
||||
} catch {
|
||||
return { ok: false, reason: 'npm audit did not return a JSON report.' };
|
||||
}
|
||||
if (audit && typeof audit === 'object' && audit.error) {
|
||||
const code = typeof audit.error.code === 'string' ? audit.error.code : 'error';
|
||||
const summary = typeof audit.error.summary === 'string' ? audit.error.summary : 'npm audit failed.';
|
||||
return { ok: false, reason: `npm audit failed (${code}): ${summary}${code === 'ENOLOCK' ? auditHint(dir) : ''}` };
|
||||
}
|
||||
if (!audit || typeof audit !== 'object' || !audit.vulnerabilities || typeof audit.vulnerabilities !== 'object' || Array.isArray(audit.vulnerabilities)) {
|
||||
return { ok: false, reason: 'npm audit returned no vulnerability report.' };
|
||||
}
|
||||
return { ok: true, vulnerabilities: audit.vulnerabilities as Record<string, NpmAuditVuln> };
|
||||
}
|
||||
function auditHint(dir?: string): string {
|
||||
if (!dir) return '';
|
||||
const has = (f: string) => existsSync(resolvePath(dir, f));
|
||||
if (has('pnpm-lock.yaml')) return ' This is a pnpm project: run `pnpm audit` instead.';
|
||||
if (has('yarn.lock')) return ' This is a yarn project: run `yarn npm audit` (Berry) or `yarn audit` (v1) instead.';
|
||||
if (has('bun.lock') || has('bun.lockb')) return ' This is a bun project: run `bun audit` instead.';
|
||||
return ' Create one with `npm i --package-lock-only`, or use your package manager\'s audit.';
|
||||
}
|
||||
|
||||
// CVE subcommand
|
||||
const cveCommand: Command = {
|
||||
name: 'cve',
|
||||
@@ -466,23 +515,22 @@ const cveCommand: Command = {
|
||||
auditJson = (e instanceof Error && 'stdout' in e ? (e as { stdout: string }).stdout : '') || '{}';
|
||||
}
|
||||
|
||||
let audit: { vulnerabilities?: Record<string, { severity: string; via: Array<{ title?: string; url?: string; source?: number; name?: string }> }> };
|
||||
try {
|
||||
audit = JSON.parse(auditJson);
|
||||
} catch {
|
||||
output.writeln(output.warning('⚠ Could not parse `npm audit --json` output.'));
|
||||
output.writeln(output.dim('Make sure you are inside a project with a package.json.'));
|
||||
const audit = interpretNpmAudit(auditJson, process.cwd());
|
||||
if (!audit.ok) {
|
||||
output.writeln(output.warning(`⚠ Could not check dependencies: ${audit.reason}`));
|
||||
output.writeln(output.dim('No result is reported rather than a false all-clear.'));
|
||||
return { success: false, exitCode: 2 };
|
||||
}
|
||||
|
||||
const vulns = audit.vulnerabilities || {};
|
||||
const vulns = audit.vulnerabilities;
|
||||
const cveRows: Array<{ pkg: string; severity: string; cveIds: string[]; title: string; url: string | undefined }> = [];
|
||||
const CVE_RE = /CVE-\d{4}-\d{4,7}/g;
|
||||
|
||||
for (const [pkg, v] of Object.entries(vulns)) {
|
||||
const sev = v.severity || 'low';
|
||||
const titles = (v.via || []).filter((x) => typeof x === 'object' && x?.title).map((x) => x.title!);
|
||||
const urls = (v.via || []).filter((x) => typeof x === 'object' && x?.url).map((x) => x.url!);
|
||||
const via = (v.via || []).filter((x): x is Exclude<typeof x, string> => typeof x === 'object' && x !== null);
|
||||
const titles = via.filter((x) => x.title).map((x) => x.title!);
|
||||
const urls = via.filter((x) => x.url).map((x) => x.url!);
|
||||
const allText = `${titles.join(' ')} ${urls.join(' ')}`;
|
||||
const cveIds = Array.from(new Set(allText.match(CVE_RE) || []));
|
||||
cveRows.push({ pkg, severity: sev, cveIds, title: titles[0] || 'Vulnerability', url: urls[0] });
|
||||
|
||||
@@ -42,7 +42,8 @@ export function getSecurityStatus(cwd: string = process.cwd()): SecurityStatus {
|
||||
scan.summary?.total ?? scan.totalFindings ?? scan.findings?.length ?? 0;
|
||||
const findings = Math.max(0, Number.isFinite(rawFindings) ? rawFindings : 0);
|
||||
return {
|
||||
status: findings > 0 ? 'ISSUES' : 'CLEAN',
|
||||
// #4124: a scan whose dependency phase could not run is not a clean scan.
|
||||
status: findings > 0 ? 'ISSUES' : scan.incomplete === true ? 'PENDING' : 'CLEAN',
|
||||
findings,
|
||||
scannedAt: typeof scan.timestamp === 'string' ? scan.timestamp : undefined,
|
||||
cvesFixed: 0,
|
||||
|
||||
@@ -387,7 +387,7 @@ export const DEFAULT_INIT_OPTIONS: InitOptions = {
|
||||
github: true,
|
||||
flowNexus: false,
|
||||
browser: true,
|
||||
v3: true,
|
||||
v3: false, // ADR-128: opt-in like agents.v3; use --full or `init skills --v3`
|
||||
dualMode: false, // Optional: enable with --dual flag
|
||||
all: false,
|
||||
},
|
||||
|
||||
@@ -75,10 +75,25 @@ const CLASSIFICATION_PATTERNS: Record<string, RegExp[]> = {
|
||||
};
|
||||
|
||||
const IMPACT_KEYWORDS: Record<string, number> = {
|
||||
security: 3, auth: 3, payment: 3, database: 2, api: 2, core: 2,
|
||||
payment: 3, database: 2, api: 2, core: 2,
|
||||
util: 1, helper: 1, test: 0, mock: 0, fixture: 0,
|
||||
};
|
||||
|
||||
// Match path terms rather than substrings: `encryption` must trigger review,
|
||||
// while unrelated names such as `author` and `tokenizer` must not.
|
||||
const SECURITY_PATH_TERMS = new Set([
|
||||
'security', 'secure', 'auth', 'oauth', 'authenticate', 'authentication',
|
||||
'authorization', 'authorized', 'authenticator', 'crypto', 'cryptography',
|
||||
'encrypt', 'encryption', 'encrypted', 'decrypt', 'decryption', 'decrypted',
|
||||
'cipher', 'secret', 'secrets', 'password', 'passwords', 'token', 'tokens',
|
||||
'vault', 'kms',
|
||||
]);
|
||||
|
||||
function isSecuritySensitivePath(path: string): boolean {
|
||||
const terms = path.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase().split(/[^a-z0-9]+/);
|
||||
return terms.some(term => SECURITY_PATH_TERMS.has(term));
|
||||
}
|
||||
|
||||
export class DiffClassifier {
|
||||
private config: DiffClassifierConfig;
|
||||
private ruvectorEngine: unknown = null;
|
||||
@@ -232,6 +247,7 @@ export class DiffClassifier {
|
||||
let score = 0;
|
||||
const lowerPath = path.toLowerCase();
|
||||
for (const [keyword, weight] of Object.entries(IMPACT_KEYWORDS)) { if (lowerPath.includes(keyword)) score = Math.max(score, weight); }
|
||||
if (isSecuritySensitivePath(path)) score = Math.max(score, 3);
|
||||
const totalChanges = hunks.reduce((sum, h) => sum + h.changes.filter(c => c.type !== 'context').length, 0);
|
||||
if (totalChanges > 100) score = Math.max(score, 2);
|
||||
if (totalChanges > 300) score = Math.max(score, 3);
|
||||
@@ -246,7 +262,7 @@ export class DiffClassifier {
|
||||
const typeReviewers: Record<string, string[]> = { feature: ['tech-lead', 'product-owner'], bugfix: ['qa-engineer', 'developer'], refactor: ['senior-developer', 'architect'], docs: ['tech-writer', 'developer'], test: ['qa-engineer', 'developer'], config: ['devops', 'tech-lead'], style: ['developer'], unknown: ['developer'] };
|
||||
reviewers.push(...(typeReviewers[primary] || typeReviewers.unknown));
|
||||
if (impact === 'critical' || impact === 'high') reviewers.push('security-reviewer');
|
||||
if (/security|auth/.test(path)) reviewers.push('security-team');
|
||||
if (isSecuritySensitivePath(path)) reviewers.push('security-team');
|
||||
if (/database|migration/.test(path)) reviewers.push('dba');
|
||||
return [...new Set(reviewers)].slice(0, 4);
|
||||
}
|
||||
@@ -257,7 +273,7 @@ export class DiffClassifier {
|
||||
if (primary === 'feature') strategies.push('integration-tests');
|
||||
if (impact === 'high' || impact === 'critical') { strategies.push('regression-tests'); strategies.push('e2e-tests'); }
|
||||
if (/api|endpoint|route|handler/.test(path)) strategies.push('api-contract-tests');
|
||||
if (/security|auth|crypto/.test(path)) strategies.push('security-audit');
|
||||
if (isSecuritySensitivePath(path)) strategies.push('security-audit');
|
||||
return strategies.slice(0, 5);
|
||||
}
|
||||
|
||||
@@ -267,7 +283,7 @@ export class DiffClassifier {
|
||||
if (totalChanges > 200) risks.push('Large change set - increased review time needed');
|
||||
if (impact === 'critical') risks.push('Critical system component - requires careful review');
|
||||
if (impact === 'high') risks.push('High-impact area - monitor after deployment');
|
||||
if (/security|auth/.test(path)) risks.push('Security-sensitive code');
|
||||
if (isSecuritySensitivePath(path)) risks.push('Security-sensitive code');
|
||||
if (/database|migration/.test(path)) risks.push('Database changes - ensure backup strategy');
|
||||
if (/config|env/.test(path)) risks.push('Configuration changes - verify all environments');
|
||||
const allContent = hunks.flatMap(h => h.changes.map(c => c.content)).join('\n');
|
||||
@@ -368,20 +384,24 @@ const CACHE_TTL_MS = 5000; // 5 seconds - short TTL since diffs change frequentl
|
||||
* Only allows safe characters: alphanumeric, -, _, /, ., ~, ^
|
||||
*/
|
||||
function validateGitRef(ref: string): void {
|
||||
// Block shell metacharacters and dangerous patterns
|
||||
if (!/^[a-zA-Z0-9_\-./~^@]+$/.test(ref)) {
|
||||
throw new Error(`Invalid git ref: contains unsafe characters`);
|
||||
}
|
||||
// Block multiple dots (path traversal)
|
||||
if (ref.includes('..') && !ref.match(/^[a-zA-Z0-9_\-]+\.\.\.?[a-zA-Z0-9_\-]+$/)) {
|
||||
if (!/^\w+\.\.[.\w]+$/.test(ref)) {
|
||||
throw new Error(`Invalid git ref: suspicious pattern`);
|
||||
}
|
||||
}
|
||||
// Max length check
|
||||
if (ref.length > 256) {
|
||||
throw new Error(`Invalid git ref: too long`);
|
||||
}
|
||||
// A ref is passed as one argv element, but still must not be an option or
|
||||
// contain shell metacharacters. A range may omit its right endpoint (HEAD).
|
||||
if (!/^[a-zA-Z0-9_][a-zA-Z0-9_\-./~^@]*$/.test(ref)) {
|
||||
throw new Error(`Invalid git ref: contains unsafe characters`);
|
||||
}
|
||||
if (ref.includes('..')) {
|
||||
const range = ref.match(/^(.+?)(\.\.\.?)(.*)$/);
|
||||
// Only one range separator is allowed. In particular, reject traversal
|
||||
// inside either endpoint, while accepting branch paths and ancestry syntax.
|
||||
if (!range || range[1].includes('..') || range[3].includes('..') ||
|
||||
!/^[a-zA-Z0-9_][a-zA-Z0-9_\-./~^@]*$/.test(range[1]) ||
|
||||
(range[3] !== '' && !/^[a-zA-Z0-9_][a-zA-Z0-9_\-./~^@]*$/.test(range[3]))) {
|
||||
throw new Error(`Invalid git ref: suspicious pattern`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -558,7 +578,7 @@ export function assessFileRisk(file: DiffFile): FileRisk {
|
||||
|
||||
// Path-based risk
|
||||
const lowerPath = file.path.toLowerCase();
|
||||
if (/security|auth|crypto|password/.test(lowerPath)) {
|
||||
if (isSecuritySensitivePath(file.path)) {
|
||||
score += 40;
|
||||
reasons.push('Security-sensitive file');
|
||||
}
|
||||
@@ -659,7 +679,7 @@ export function suggestReviewers(files: DiffFile[], fileRisks: FileRisk[]): stri
|
||||
for (const file of files) {
|
||||
const lowerPath = file.path.toLowerCase();
|
||||
|
||||
if (/security|auth|crypto/.test(lowerPath)) reviewers.add('security-team');
|
||||
if (isSecuritySensitivePath(file.path)) reviewers.add('security-team');
|
||||
if (/database|migration/.test(lowerPath)) reviewers.add('dba');
|
||||
if (/api|endpoint|route/.test(lowerPath)) reviewers.add('api-owner');
|
||||
if (/test|spec/.test(lowerPath)) reviewers.add('qa-engineer');
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"_comment": "Monotone-decreasing baseline of shipped SKILL.md files that reference a ruflo MCP tool not registered by mcp-client.ts (entries are <skill path>::<tool>). Fix one, then re-run with --update-baseline to lower the floor. NEVER add entries to hide a new reference.",
|
||||
"danglingCount": 48,
|
||||
"knownDangling": [
|
||||
"v3/@claude-flow/cli/.claude/skills/github-multi-repo/SKILL.md::memory_usage",
|
||||
"v3/@claude-flow/cli/.claude/skills/github-multi-repo/SKILL.md::task_orchestrate",
|
||||
"v3/@claude-flow/cli/.claude/skills/github-project-management/SKILL.md::task_orchestrate",
|
||||
"v3/@claude-flow/cli/.claude/skills/github-release-management/SKILL.md::memory_usage",
|
||||
"v3/@claude-flow/cli/.claude/skills/github-release-management/SKILL.md::swarm_monitor",
|
||||
"v3/@claude-flow/cli/.claude/skills/github-release-management/SKILL.md::task_orchestrate",
|
||||
"v3/@claude-flow/cli/.claude/skills/github-workflow-automation/SKILL.md::task_orchestrate",
|
||||
"v3/@claude-flow/cli/.claude/skills/hooks-automation/SKILL.md::memory_persist",
|
||||
"v3/@claude-flow/cli/.claude/skills/hooks-automation/SKILL.md::memory_usage",
|
||||
"v3/@claude-flow/cli/.claude/skills/sparc-methodology/SKILL.md::bottleneck_analyze",
|
||||
"v3/@claude-flow/cli/.claude/skills/sparc-methodology/SKILL.md::context_restore",
|
||||
"v3/@claude-flow/cli/.claude/skills/sparc-methodology/SKILL.md::memory_persist",
|
||||
"v3/@claude-flow/cli/.claude/skills/sparc-methodology/SKILL.md::memory_usage",
|
||||
"v3/@claude-flow/cli/.claude/skills/sparc-methodology/SKILL.md::sparc_mode",
|
||||
"v3/@claude-flow/cli/.claude/skills/sparc-methodology/SKILL.md::swarm_monitor",
|
||||
"v3/@claude-flow/cli/.claude/skills/sparc-methodology/SKILL.md::task_orchestrate",
|
||||
"v3/@claude-flow/cli/.claude/skills/sparc-methodology/SKILL.md::token_usage",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::automation_setup",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::batch_process",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::benchmark_run",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::bottleneck_analyze",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::cognitive_analyze",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::context_restore",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::cost_analysis",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::daa_fault_tolerance",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::error_analysis",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::health_check",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::learning_adapt",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::load_balance",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::memory_backup",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::memory_namespace",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::memory_persist",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::memory_usage",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::metrics_collect",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::parallel_execute",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::pattern_recognize",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::pipeline_create",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::quality_assess",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::security_scan",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::state_snapshot",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::swarm_monitor",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::swarm_scale",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::task_orchestrate",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::task_results",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::topology_optimize",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::trend_analysis",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::trigger_setup",
|
||||
"v3/@claude-flow/cli/.claude/skills/swarm-advanced/SKILL.md::usage_stats"
|
||||
],
|
||||
"updatedAt": "2026-10-13T08:38:37.635Z"
|
||||
}
|
||||
Reference in new issue
Block a user