@claude-flow/cli 3.56.9 → 3.57.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/helpers/.helpers-version +1 -1
- package/.claude/helpers/helpers.manifest.json +3 -3
- package/.claude/helpers/intelligence.cjs +51 -9
- package/.claude/helpers/router.cjs +0 -0
- package/.claude/skills/verification-quality/SKILL.md +14 -11
- package/README.md +1 -1
- package/catalog-manifest.json +2 -2
- package/dist/src/autopilot-state.d.ts +2 -0
- package/dist/src/autopilot-state.js +36 -8
- package/dist/src/command-resolution.d.ts +15 -0
- package/dist/src/command-resolution.js +25 -0
- package/dist/src/commands/agent.js +17 -17
- package/dist/src/commands/claims.js +6 -8
- package/dist/src/commands/daemon.js +94 -33
- package/dist/src/commands/doctor.js +95 -18
- package/dist/src/commands/memory.js +14 -2
- package/dist/src/commands/policy.js +6 -1
- package/dist/src/commands/security-code-patterns.d.ts +2 -2
- package/dist/src/commands/security-code-patterns.js +61 -3
- package/dist/src/commands/security.d.ts +24 -0
- package/dist/src/commands/security.js +81 -35
- package/dist/src/commands/tui.d.ts +9 -0
- package/dist/src/commands/tui.js +29 -3
- package/dist/src/config/proven-config-refresh.d.ts +9 -0
- package/dist/src/config/proven-config-refresh.js +24 -3
- package/dist/src/funnel/local-signals.js +2 -1
- package/dist/src/index.js +11 -47
- package/dist/src/init/settings-generator.js +4 -58
- package/dist/src/init/types.js +1 -1
- package/dist/src/mcp-tools/agent-execute-core.d.ts +2 -0
- package/dist/src/mcp-tools/agent-execute-core.js +15 -0
- package/dist/src/mcp-tools/agent-health-metrics.d.ts +22 -0
- package/dist/src/mcp-tools/agent-health-metrics.js +33 -0
- package/dist/src/mcp-tools/agent-tools.js +45 -22
- package/dist/src/mcp-tools/agentbbs-federation.d.ts +1 -1
- package/dist/src/mcp-tools/agentbbs-federation.js +7 -2
- package/dist/src/mcp-tools/agentdb-tools.js +25 -2
- package/dist/src/mcp-tools/aidefence-known-misses.d.ts +22 -0
- package/dist/src/mcp-tools/aidefence-known-misses.js +57 -0
- package/dist/src/mcp-tools/analyze-tools.js +10 -11
- package/dist/src/mcp-tools/autopilot-tools.js +2 -2
- package/dist/src/mcp-tools/browser-intent-tools.js +6 -2
- package/dist/src/mcp-tools/embeddings-tools.js +29 -7
- package/dist/src/mcp-tools/hooks-tools.js +4 -0
- package/dist/src/mcp-tools/memory-tools.d.ts +1 -1
- package/dist/src/mcp-tools/memory-tools.js +100 -25
- package/dist/src/mcp-tools/metaharness-tools.js +1 -1
- package/dist/src/mcp-tools/neural-tools.js +48 -54
- package/dist/src/mcp-tools/policy-tools.js +5 -3
- package/dist/src/mcp-tools/ruvllm-tools.js +6 -0
- package/dist/src/mcp-tools/security-tools.js +55 -17
- package/dist/src/mcp-tools/workflow-tools.js +66 -17
- package/dist/src/memory/intelligence.d.ts +5 -1
- package/dist/src/memory/intelligence.js +158 -35
- package/dist/src/memory/memory-bridge.js +10 -3
- package/dist/src/memory/memory-initializer.js +2 -1
- package/dist/src/memory/search-defaults.d.ts +54 -0
- package/dist/src/memory/search-defaults.js +37 -0
- package/dist/src/memory/sona-optimizer.d.ts +28 -0
- package/dist/src/memory/sona-optimizer.js +59 -2
- package/dist/src/memory/stats-file-lock.d.ts +7 -0
- package/dist/src/memory/stats-file-lock.js +53 -0
- package/dist/src/mods/command-registry/schema.d.ts +24 -24
- package/dist/src/ruvector/agent-wasm.d.ts +10 -0
- package/dist/src/ruvector/agent-wasm.js +27 -1
- package/dist/src/ruvector/diff-classifier.d.ts +2 -4
- package/dist/src/ruvector/diff-classifier.js +202 -69
- package/dist/src/ruvector/ruvllm-wasm.d.ts +4 -0
- package/dist/src/ruvector/ruvllm-wasm.js +12 -1
- package/dist/src/services/distill-oracle.d.ts +1 -1
- package/dist/src/services/distill-oracle.js +2 -2
- package/dist/src/services/policy-anchor-log.d.ts +13 -0
- package/dist/src/services/policy-anchor-log.js +242 -0
- package/dist/src/services/policy-archive-scan.d.ts +7 -0
- package/dist/src/services/policy-archive-scan.js +50 -0
- package/dist/src/services/policy-ledger-anchor.d.ts +14 -8
- package/dist/src/services/policy-ledger-anchor.js +356 -40
- package/dist/src/services/policy-ledger-audit.d.ts +22 -0
- package/dist/src/services/policy-ledger-audit.js +260 -0
- package/dist/src/services/policy-ledger-record.d.ts +3 -0
- package/dist/src/services/policy-ledger-record.js +22 -0
- package/dist/src/services/policy-runtime.d.ts +2 -1
- package/dist/src/services/policy-runtime.js +267 -40
- package/dist/src/services/worker-daemon.d.ts +11 -0
- package/dist/src/services/worker-daemon.js +37 -0
- package/dist/src/transfer/store/discovery.js +16 -17
- package/dist/src/transfer/store/types.d.ts +4 -0
- package/node_modules/@claude-flow/codex/dist/cli.js +0 -0
- package/node_modules/@claude-flow/plugin-agent-federation/dist/bin.js +0 -0
- package/node_modules/@claude-flow/security/dist/policy/engine.d.ts +17 -1
- package/node_modules/@claude-flow/security/dist/policy/engine.d.ts.map +1 -1
- package/node_modules/@claude-flow/security/dist/policy/engine.js +99 -24
- package/node_modules/@claude-flow/security/dist/policy/engine.js.map +1 -1
- package/node_modules/@claude-flow/security/dist/policy/types.d.ts +14 -1
- package/node_modules/@claude-flow/security/dist/policy/types.d.ts.map +1 -1
- package/node_modules/@claude-flow/security/dist/policy/types.js +3 -1
- package/node_modules/@claude-flow/security/dist/policy/types.js.map +1 -1
- package/package.json +5 -5
- package/plugins/ruflo-console/dist/tui.mjs +162 -161
- package/plugins/ruflo-metaharness/hooks/screen.ts +7 -1
- package/plugins/ruflo-metaharness/scripts/_darwin.mjs +4 -4
|
@@ -452,8 +452,24 @@ export const neuralTools = [
|
|
|
452
452
|
patternsStored++;
|
|
453
453
|
}
|
|
454
454
|
}
|
|
455
|
+
// #4156: nothing stored means nothing was trained. Reporting success and "ready" made
|
|
456
|
+
// callers (the neural-train skill) believe the pattern store had been filled.
|
|
457
|
+
if (patternsStored === 0) {
|
|
458
|
+
model.status = 'untrained';
|
|
459
|
+
model.accuracy = 0;
|
|
460
|
+
saveNeuralStore(store);
|
|
461
|
+
return {
|
|
462
|
+
success: false,
|
|
463
|
+
status: 'empty',
|
|
464
|
+
modelId,
|
|
465
|
+
type: modelType,
|
|
466
|
+
patternsStored: 0,
|
|
467
|
+
totalPatterns: Object.keys(store.patterns).length,
|
|
468
|
+
error: 'neural_train stored nothing: pass `data` (an array of strings or {text, label} entries). It does not read trajectories, SONA or the ReasoningBank: those (hooks_intelligence_*) are a separate store that neural_predict and neural_patterns do not see.',
|
|
469
|
+
};
|
|
470
|
+
}
|
|
455
471
|
model.status = 'ready';
|
|
456
|
-
model.accuracy =
|
|
472
|
+
model.accuracy = 1.0; // accuracy = data stored, not simulated
|
|
457
473
|
model.trainedAt = new Date().toISOString();
|
|
458
474
|
saveNeuralStore(store);
|
|
459
475
|
return {
|
|
@@ -484,6 +500,7 @@ export const neuralTools = [
|
|
|
484
500
|
modelId: { type: 'string', description: 'Model ID to use' },
|
|
485
501
|
input: { type: 'string', description: 'Input text or data' },
|
|
486
502
|
topK: { type: 'number', description: 'Number of top predictions' },
|
|
503
|
+
minSimilarity: { type: 'number', description: 'Minimum cosine similarity for a stored pattern to count as a match (default 0.5). A softmax over a single candidate is always 1.0, so without a floor any input matched the only stored pattern with confidence 1' },
|
|
487
504
|
},
|
|
488
505
|
required: ['input'],
|
|
489
506
|
},
|
|
@@ -502,6 +519,7 @@ export const neuralTools = [
|
|
|
502
519
|
const modelId = input.modelId;
|
|
503
520
|
const inputText = input.input;
|
|
504
521
|
const topK = input.topK || 3;
|
|
522
|
+
const minSimilarity = typeof input.minSimilarity === 'number' ? input.minSimilarity : 0.5;
|
|
505
523
|
// Find model or use default
|
|
506
524
|
const model = modelId ? store.models[modelId] : Object.values(store.models).find(m => m.status === 'ready');
|
|
507
525
|
if (model && model.status !== 'ready') {
|
|
@@ -519,9 +537,10 @@ export const neuralTools = [
|
|
|
519
537
|
// to 1, and we surface enough metadata to trust the result.
|
|
520
538
|
const storedPatterns = Object.values(store.patterns);
|
|
521
539
|
let predictions;
|
|
540
|
+
let bestSimilarity = null;
|
|
522
541
|
if (storedPatterns.length > 0) {
|
|
523
542
|
// Step 1: k-NN with cosine
|
|
524
|
-
|
|
543
|
+
let scored = storedPatterns
|
|
525
544
|
.map(p => {
|
|
526
545
|
const sim = cosineSimilarity(embedding, p.embedding);
|
|
527
546
|
return {
|
|
@@ -530,8 +549,10 @@ export const neuralTools = [
|
|
|
530
549
|
cosineSimilarity: sim,
|
|
531
550
|
};
|
|
532
551
|
})
|
|
533
|
-
.sort((a, b) => b.cosineSimilarity - a.cosineSimilarity)
|
|
534
|
-
|
|
552
|
+
.sort((a, b) => b.cosineSimilarity - a.cosineSimilarity);
|
|
553
|
+
bestSimilarity = scored[0]?.cosineSimilarity ?? null;
|
|
554
|
+
// #4156: only patterns that reach the similarity floor are candidates.
|
|
555
|
+
scored = scored.filter((c) => c.cosineSimilarity >= minSimilarity).slice(0, topK);
|
|
535
556
|
// Step 2: temperature-softmax over the top-K so confidence sums to 1.
|
|
536
557
|
// Temperature 0.1 sharpens differences between similar candidates.
|
|
537
558
|
const tau = 0.1;
|
|
@@ -569,8 +590,11 @@ export const neuralTools = [
|
|
|
569
590
|
embedding: embedding.slice(0, 8), // Preview of embedding
|
|
570
591
|
embeddingDims: embedding.length,
|
|
571
592
|
latency,
|
|
593
|
+
...(bestSimilarity !== null ? { bestSimilarity: Number(bestSimilarity.toFixed(4)), minSimilarity } : {}),
|
|
572
594
|
...(storedPatterns.length === 0 ? {
|
|
573
595
|
_note: 'No patterns stored. Train with neural_train(modelType, trainingData) before predicting.',
|
|
596
|
+
} : predictions.length === 0 ? {
|
|
597
|
+
_note: `No stored pattern reached the similarity floor (best ${bestSimilarity === null ? 'n/a' : bestSimilarity.toFixed(3)}, floor ${minSimilarity}); pass minSimilarity to lower it.`,
|
|
574
598
|
} : {}),
|
|
575
599
|
};
|
|
576
600
|
},
|
|
@@ -884,9 +908,6 @@ export const neuralTools = [
|
|
|
884
908
|
if (!v.valid)
|
|
885
909
|
return { success: false, error: v.error };
|
|
886
910
|
}
|
|
887
|
-
// Resolve provider so embeddingProvider in the result matches the old
|
|
888
|
-
// eager-init reporting.
|
|
889
|
-
await ensureEmbeddings();
|
|
890
911
|
const store = loadNeuralStore();
|
|
891
912
|
const method = input.method || 'quantize';
|
|
892
913
|
const targetReduction = input.targetSize || 0.5;
|
|
@@ -895,38 +916,25 @@ export const neuralTools = [
|
|
|
895
916
|
return { success: false, error: 'No patterns to compress. Train patterns first with neural_train.' };
|
|
896
917
|
}
|
|
897
918
|
const beforeCount = patterns.length;
|
|
898
|
-
const beforeSize = patterns.reduce((s, p) => s + (p.embedding?.length || 0) * 4, 0); // Float32 = 4 bytes
|
|
899
919
|
if (method === 'quantize') {
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
}
|
|
916
|
-
saveNeuralStore(store);
|
|
917
|
-
return {
|
|
918
|
-
success: true, _real: true, method,
|
|
919
|
-
embeddingProvider: embeddingServiceName,
|
|
920
|
-
patternsCompressed: totalCompressed,
|
|
921
|
-
compressionRatio: '3.92x (Int8)',
|
|
922
|
-
beforeBytes: beforeSize,
|
|
923
|
-
afterBytes: Math.round(beforeSize / 3.92),
|
|
924
|
-
};
|
|
925
|
-
}
|
|
926
|
-
catch {
|
|
927
|
-
return { success: false, error: 'Quantization requires memory-initializer. Run `memory init` first.' };
|
|
928
|
-
}
|
|
920
|
+
// Neural-store readers consume `embedding` as a full-precision number[]
|
|
921
|
+
// (search, prediction, deduplication, and optimization). The former
|
|
922
|
+
// implementation discarded the Int8 vector, persisted only metadata,
|
|
923
|
+
// and reported a calculated 3.92x reduction. Refuse until the store has
|
|
924
|
+
// a persisted representation with a reader-side decode contract.
|
|
925
|
+
const storedBytes = readFileSync(getNeuralPath()).byteLength;
|
|
926
|
+
return {
|
|
927
|
+
success: false,
|
|
928
|
+
error: 'Quantized embeddings are not persisted: neural-store readers require full-precision embedding arrays.',
|
|
929
|
+
method,
|
|
930
|
+
patternsCompressed: 0,
|
|
931
|
+
beforeBytes: storedBytes,
|
|
932
|
+
afterBytes: storedBytes,
|
|
933
|
+
compressionRatio: '1.00x (unchanged JSON storage)',
|
|
934
|
+
};
|
|
929
935
|
}
|
|
936
|
+
// Resolve provider only for operations that actually use embeddings.
|
|
937
|
+
await ensureEmbeddings();
|
|
930
938
|
if (method === 'prune') {
|
|
931
939
|
// Prune patterns with low usage count below threshold (targetReduction as min usage)
|
|
932
940
|
const threshold = targetReduction;
|
|
@@ -1112,24 +1120,10 @@ export const neuralTools = [
|
|
|
1112
1120
|
if (duplicatesRemoved > 0)
|
|
1113
1121
|
actions.push(`Removed ${duplicatesRemoved} near-duplicate patterns`);
|
|
1114
1122
|
}
|
|
1115
|
-
// memory / balanced:
|
|
1123
|
+
// memory / balanced: report the unsupported persisted representation
|
|
1124
|
+
// instead of attaching metadata for a discarded Int8 vector.
|
|
1116
1125
|
if (target === 'memory' || target === 'balanced') {
|
|
1117
|
-
|
|
1118
|
-
const { quantizeInt8, getQuantizationStats } = await import('../memory/memory-initializer.js');
|
|
1119
|
-
for (const p of Object.values(store.patterns)) {
|
|
1120
|
-
if (p.embedding && p.embedding.length > 0 && !p._quantized) {
|
|
1121
|
-
const stats = getQuantizationStats(p.embedding);
|
|
1122
|
-
const q = quantizeInt8(p.embedding);
|
|
1123
|
-
p._quantized = { scale: q.scale, zeroPoint: q.zeroPoint, compressionRatio: stats.compressionRatio };
|
|
1124
|
-
patternsQuantized++;
|
|
1125
|
-
}
|
|
1126
|
-
}
|
|
1127
|
-
if (patternsQuantized > 0)
|
|
1128
|
-
actions.push(`Quantized ${patternsQuantized} pattern embeddings (Int8, ~3.92x)`);
|
|
1129
|
-
}
|
|
1130
|
-
catch {
|
|
1131
|
-
actions.push('Quantization skipped (memory-initializer not available)');
|
|
1132
|
-
}
|
|
1126
|
+
actions.push('Quantization skipped: neural-store readers require persisted full-precision embedding arrays.');
|
|
1133
1127
|
}
|
|
1134
1128
|
// accuracy / balanced: prune low-usage, zero-embedding patterns
|
|
1135
1129
|
if (target === 'accuracy' || target === 'balanced') {
|
|
@@ -24,9 +24,11 @@ export const policyTools = [
|
|
|
24
24
|
category: 'security',
|
|
25
25
|
inputSchema: {
|
|
26
26
|
type: 'object',
|
|
27
|
-
properties: {
|
|
27
|
+
properties: {
|
|
28
|
+
full: { type: 'boolean', description: 'Also replay the archived receipts to verify the complete historical ledger, not just the retained hot tail (#3164)' },
|
|
29
|
+
},
|
|
28
30
|
},
|
|
29
|
-
handler: async (
|
|
31
|
+
handler: async (input, context) => {
|
|
30
32
|
const root = typeof context?.projectRoot === 'string' ? context.projectRoot : process.cwd();
|
|
31
33
|
const state = loadPolicyState(root);
|
|
32
34
|
return {
|
|
@@ -39,7 +41,7 @@ export const policyTools = [
|
|
|
39
41
|
approvals: state.approvals.length,
|
|
40
42
|
receipts: state.receipts.length,
|
|
41
43
|
},
|
|
42
|
-
ledger: await verifyPolicyLedger(root),
|
|
44
|
+
ledger: await verifyPolicyLedger(root, { full: input.full === true }),
|
|
43
45
|
};
|
|
44
46
|
},
|
|
45
47
|
},
|
|
@@ -43,7 +43,13 @@ export const ruvllmWasmTools = [
|
|
|
43
43
|
nativeBackend = {
|
|
44
44
|
available: iStats._ruvllmBackend === 'active',
|
|
45
45
|
coordinator: iStats._ruvllmBackend || 'unavailable',
|
|
46
|
+
// `trajectories` is the in-process SonaCoordinator buffer — it is
|
|
47
|
+
// 0 in any process that did not itself record (e.g. this MCP
|
|
48
|
+
// server while the daemon / hook processes do the recording).
|
|
46
49
|
trajectories: iStats._ruvllmTrajectories || 0,
|
|
50
|
+
// Project-persisted total across all processes
|
|
51
|
+
// (.claude-flow/neural/stats.json).
|
|
52
|
+
trajectoriesRecorded: iStats.trajectoriesRecorded || 0,
|
|
47
53
|
contrastiveTrainer: sStats._contrastiveTrainer !== 'unavailable' ? 'active' : 'unavailable',
|
|
48
54
|
trainingBackend: iStats._trainingBackend || 'unknown',
|
|
49
55
|
};
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
import { validateText, validateIdentifier } from './validate-input.js';
|
|
13
13
|
import { autoInstallPackage } from './auto-install.js';
|
|
14
14
|
import { createRequire } from 'module';
|
|
15
|
+
import { findKnownMiss, recordKnownMiss } from './aidefence-known-misses.js';
|
|
15
16
|
// Create require for resolving module paths
|
|
16
17
|
const require = createRequire(import.meta.url);
|
|
17
18
|
// Lazy-loaded AIDefence instance
|
|
@@ -152,7 +153,8 @@ const aidefenceScanTool = {
|
|
|
152
153
|
piiPresent = !!defender.hasPII(input);
|
|
153
154
|
}
|
|
154
155
|
catch { /* hasPII unavailable */ }
|
|
155
|
-
const
|
|
156
|
+
const knownMiss = findKnownMiss(input);
|
|
157
|
+
const threatDetected = result.threat || piiPresent || !!knownMiss;
|
|
156
158
|
wrapperStats.quickScanCalls++;
|
|
157
159
|
if (threatDetected)
|
|
158
160
|
wrapperStats.quickScanThreats++;
|
|
@@ -164,24 +166,29 @@ const aidefenceScanTool = {
|
|
|
164
166
|
threatDetected,
|
|
165
167
|
confidence: result.confidence,
|
|
166
168
|
piiDetected: piiPresent,
|
|
167
|
-
promptInjectionDetected: result.threat,
|
|
169
|
+
promptInjectionDetected: result.threat || !!knownMiss,
|
|
170
|
+
...(knownMiss ? { knownMiss: { threatType: knownMiss.threatType, reportedAt: knownMiss.reportedAt } } : {}),
|
|
168
171
|
mode: 'quick',
|
|
169
172
|
}, null, 2),
|
|
170
173
|
}],
|
|
171
174
|
};
|
|
172
175
|
}
|
|
173
176
|
const result = await defender.detect(input);
|
|
177
|
+
const knownMiss = findKnownMiss(input);
|
|
174
178
|
return {
|
|
175
179
|
content: [{
|
|
176
180
|
type: 'text',
|
|
177
181
|
text: JSON.stringify({
|
|
178
|
-
safe: result.safe,
|
|
179
|
-
threats:
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
182
|
+
safe: result.safe && !knownMiss,
|
|
183
|
+
threats: [
|
|
184
|
+
...result.threats.map(t => ({
|
|
185
|
+
type: t.type,
|
|
186
|
+
severity: t.severity,
|
|
187
|
+
confidence: t.confidence,
|
|
188
|
+
description: t.description,
|
|
189
|
+
})),
|
|
190
|
+
...(knownMiss ? [{ type: knownMiss.threatType, severity: 'high', confidence: 1, description: 'Matches an input previously reported as a missed threat (aidefence_learn)' }] : []),
|
|
191
|
+
],
|
|
185
192
|
piiFound: result.piiFound,
|
|
186
193
|
detectionTimeMs: result.detectionTimeMs,
|
|
187
194
|
}, null, 2),
|
|
@@ -398,11 +405,33 @@ const aidefenceLearnTool = {
|
|
|
398
405
|
const defender = await getAIDefence();
|
|
399
406
|
// Re-detect to get result for learning
|
|
400
407
|
const result = await defender.detect(input);
|
|
401
|
-
//
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
408
|
+
// A false negative (wasAccurate=false, nothing detected) gives
|
|
409
|
+
// learnFromDetection() no threat to store, so record the miss itself.
|
|
410
|
+
const falseNegative = !wasAccurate && result.threats.length === 0;
|
|
411
|
+
const missType = threatType || 'prompt_injection';
|
|
412
|
+
let learned = result.threats.length;
|
|
413
|
+
let newlyRecorded = false;
|
|
414
|
+
if (falseNegative) {
|
|
415
|
+
newlyRecorded = recordKnownMiss(input, missType);
|
|
416
|
+
if (newlyRecorded) {
|
|
417
|
+
const synthetic = {
|
|
418
|
+
...result,
|
|
419
|
+
safe: false,
|
|
420
|
+
threats: [{
|
|
421
|
+
type: missType,
|
|
422
|
+
severity: 'high',
|
|
423
|
+
confidence: 1,
|
|
424
|
+
pattern: 'user-reported-miss',
|
|
425
|
+
description: verdict || 'Reported by user as a missed threat',
|
|
426
|
+
}],
|
|
427
|
+
};
|
|
428
|
+
await defender.learnFromDetection(input, synthetic, { wasAccurate, userVerdict: verdict });
|
|
429
|
+
}
|
|
430
|
+
learned = 1;
|
|
431
|
+
}
|
|
432
|
+
else {
|
|
433
|
+
await defender.learnFromDetection(input, result, { wasAccurate, userVerdict: verdict });
|
|
434
|
+
}
|
|
406
435
|
// Record mitigation if provided
|
|
407
436
|
if (threatType && mitigationStrategy && mitigationSuccess !== undefined) {
|
|
408
437
|
await defender.recordMitigation(threatType, mitigationStrategy, mitigationSuccess);
|
|
@@ -412,7 +441,14 @@ const aidefenceLearnTool = {
|
|
|
412
441
|
type: 'text',
|
|
413
442
|
text: JSON.stringify({
|
|
414
443
|
success: true,
|
|
415
|
-
message:
|
|
444
|
+
message: falseNegative
|
|
445
|
+
? (newlyRecorded
|
|
446
|
+
? 'Missed threat recorded: this exact input (normalised for case/whitespace) will now be flagged by aidefence_scan and aidefence_is_safe. Detection is pattern-based and does not generalise from it.'
|
|
447
|
+
: 'This input was already recorded as a missed threat')
|
|
448
|
+
: (learned === 0
|
|
449
|
+
? 'Feedback noted, but no threat was detected so no pattern was learned. To teach a missed threat, pass wasAccurate=false.'
|
|
450
|
+
: 'Feedback recorded for pattern learning'),
|
|
451
|
+
learned,
|
|
416
452
|
learnedFrom: {
|
|
417
453
|
input: input.slice(0, 50) + (input.length > 50 ? '...' : ''),
|
|
418
454
|
wasAccurate,
|
|
@@ -468,7 +504,8 @@ const aidefenceIsSafeTool = {
|
|
|
468
504
|
piiPresent = !!defender.hasPII(input);
|
|
469
505
|
}
|
|
470
506
|
catch { /* hasPII unavailable */ }
|
|
471
|
-
const
|
|
507
|
+
const knownMiss = findKnownMiss(input);
|
|
508
|
+
const safe = promptSafe && !piiPresent && !knownMiss;
|
|
472
509
|
wrapperStats.isSafeCalls++;
|
|
473
510
|
if (!safe)
|
|
474
511
|
wrapperStats.isSafeUnsafeVerdicts++;
|
|
@@ -477,8 +514,9 @@ const aidefenceIsSafeTool = {
|
|
|
477
514
|
type: 'text',
|
|
478
515
|
text: JSON.stringify({
|
|
479
516
|
safe,
|
|
480
|
-
promptSafe,
|
|
517
|
+
promptSafe: promptSafe && !knownMiss,
|
|
481
518
|
piiPresent,
|
|
519
|
+
...(knownMiss ? { knownMiss: { threatType: knownMiss.threatType, reportedAt: knownMiss.reportedAt } } : {}),
|
|
482
520
|
}, null, 2),
|
|
483
521
|
}],
|
|
484
522
|
};
|
|
@@ -12,6 +12,35 @@ import { executeAgentTask } from './agent-execute-core.js';
|
|
|
12
12
|
const STORAGE_DIR = '.claude-flow';
|
|
13
13
|
const WORKFLOW_DIR = 'workflows';
|
|
14
14
|
const WORKFLOW_FILE = 'store.json';
|
|
15
|
+
function parseCondition(when) {
|
|
16
|
+
if (typeof when !== 'string' || !when.trim()) {
|
|
17
|
+
return new Error('condition step requires a non-empty config.when');
|
|
18
|
+
}
|
|
19
|
+
const expression = when.trim();
|
|
20
|
+
if (expression === 'true' || expression === 'false') {
|
|
21
|
+
return { constant: expression === 'true' };
|
|
22
|
+
}
|
|
23
|
+
const match = expression.match(/^([a-zA-Z_]\w*)\s*===?\s*(?:'([^']*)'|"([^"]*)"|(-?\d+(?:\.\d+)?)|(true|false))$/);
|
|
24
|
+
if (!match) {
|
|
25
|
+
return new Error('condition config.when must compare a variable to a quoted string, number, or boolean using == or ===');
|
|
26
|
+
}
|
|
27
|
+
const expected = match[2] ?? match[3] ?? (match[4] !== undefined ? Number(match[4]) : match[5] === 'true');
|
|
28
|
+
return { variable: match[1], expected };
|
|
29
|
+
}
|
|
30
|
+
function validateExecutableStep(step) {
|
|
31
|
+
if (step.type === 'parallel' || step.type === 'loop') {
|
|
32
|
+
return `step type '${step.type}' is not implemented by the workflow runtime`;
|
|
33
|
+
}
|
|
34
|
+
if (step.type === 'condition') {
|
|
35
|
+
const parsed = parseCondition(step.config?.when);
|
|
36
|
+
if (parsed instanceof Error)
|
|
37
|
+
return parsed.message;
|
|
38
|
+
}
|
|
39
|
+
else if (step.type !== 'task' && step.type !== 'wait') {
|
|
40
|
+
return `unsupported workflow step type '${step.type}'`;
|
|
41
|
+
}
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
15
44
|
function getWorkflowDir() {
|
|
16
45
|
return join(getProjectCwd(), STORAGE_DIR, WORKFLOW_DIR);
|
|
17
46
|
}
|
|
@@ -181,8 +210,8 @@ export const workflowTools = [
|
|
|
181
210
|
type: 'object',
|
|
182
211
|
properties: {
|
|
183
212
|
name: { type: 'string' },
|
|
184
|
-
type: { type: 'string', enum: ['task', 'condition', '
|
|
185
|
-
config: { type: 'object' },
|
|
213
|
+
type: { type: 'string', enum: ['task', 'condition', 'wait'] },
|
|
214
|
+
config: { type: 'object', description: 'Condition steps require config.when; parallel and loop steps are not yet supported' },
|
|
186
215
|
},
|
|
187
216
|
},
|
|
188
217
|
},
|
|
@@ -209,6 +238,11 @@ export const workflowTools = [
|
|
|
209
238
|
config: s.config || {},
|
|
210
239
|
status: 'pending',
|
|
211
240
|
}));
|
|
241
|
+
for (const step of steps) {
|
|
242
|
+
const error = validateExecutableStep(step);
|
|
243
|
+
if (error)
|
|
244
|
+
return { success: false, error: `${step.stepId} (${step.name}): ${error}` };
|
|
245
|
+
}
|
|
212
246
|
const workflow = {
|
|
213
247
|
workflowId,
|
|
214
248
|
name: input.name,
|
|
@@ -257,6 +291,20 @@ export const workflowTools = [
|
|
|
257
291
|
if (workflow.status === 'running') {
|
|
258
292
|
return { workflowId, error: 'Workflow already running' };
|
|
259
293
|
}
|
|
294
|
+
// Older stored workflows may predate creation-time validation. Reject
|
|
295
|
+
// unsupported steps before dispatching any task with side effects.
|
|
296
|
+
for (const step of workflow.steps) {
|
|
297
|
+
const error = validateExecutableStep(step);
|
|
298
|
+
if (error) {
|
|
299
|
+
workflow.status = 'failed';
|
|
300
|
+
workflow.error = `${step.stepId} (${step.name}): ${error}`;
|
|
301
|
+
step.status = 'failed';
|
|
302
|
+
step.result = { error: workflow.error };
|
|
303
|
+
workflow.completedAt = new Date().toISOString();
|
|
304
|
+
saveWorkflowStore(store);
|
|
305
|
+
return { workflowId, status: 'failed', failedStep: step.stepId, error: workflow.error };
|
|
306
|
+
}
|
|
307
|
+
}
|
|
260
308
|
// Indices may name a step or the end boundary (used when resuming
|
|
261
309
|
// after the final step). Reject invalid control flow before any writes.
|
|
262
310
|
const validIndex = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value <= workflow.steps.length;
|
|
@@ -382,19 +430,14 @@ export const workflowTools = [
|
|
|
382
430
|
stepEntry = { stepId: step.stepId, type: 'wait', status: 'completed', durationMs: ms };
|
|
383
431
|
}
|
|
384
432
|
else if (step.type === 'condition') {
|
|
385
|
-
// Simple condition: config.when is a JS expression evaluated against workflow.variables.
|
|
386
|
-
// For safety, we only support `var === 'value'` or `var === number`.
|
|
387
433
|
const cfg = step.config;
|
|
388
|
-
const
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
}
|
|
396
|
-
else if (expr === 'true')
|
|
397
|
-
truthy = true;
|
|
434
|
+
const parsed = parseCondition(cfg.when);
|
|
435
|
+
if (parsed instanceof Error)
|
|
436
|
+
throw parsed;
|
|
437
|
+
const truthy = 'constant' in parsed
|
|
438
|
+
? parsed.constant
|
|
439
|
+
: workflow.variables[parsed.variable] === parsed.expected;
|
|
440
|
+
const expr = String(cfg.when).trim();
|
|
398
441
|
step.result = { conditionExpr: expr, truthy };
|
|
399
442
|
// condition can declare a target step index to jump to via cfg.thenStep / cfg.elseStep
|
|
400
443
|
if (typeof cfg.thenStep === 'number' && truthy)
|
|
@@ -404,9 +447,7 @@ export const workflowTools = [
|
|
|
404
447
|
stepEntry = { stepId: step.stepId, type: 'condition', status: 'completed' };
|
|
405
448
|
}
|
|
406
449
|
else {
|
|
407
|
-
|
|
408
|
-
step.result = { _note: `step type '${step.type}' not yet implemented in runtime` };
|
|
409
|
-
stepEntry = { stepId: step.stepId, type: step.type, status: 'skipped' };
|
|
450
|
+
throw new Error(`step type '${step.type}' is not implemented by the workflow runtime`);
|
|
410
451
|
}
|
|
411
452
|
step.status = stepEntry.status === 'skipped' ? 'skipped' : 'completed';
|
|
412
453
|
step.completedAt = new Date().toISOString();
|
|
@@ -906,6 +947,14 @@ export const workflowTools = [
|
|
|
906
947
|
const agentSet = new Set();
|
|
907
948
|
steps.forEach((s, i) => {
|
|
908
949
|
const step = (s ?? {});
|
|
950
|
+
if (typeof step.type === 'string') {
|
|
951
|
+
const error = validateExecutableStep({
|
|
952
|
+
type: step.type,
|
|
953
|
+
config: (step.config ?? {}),
|
|
954
|
+
});
|
|
955
|
+
if (error)
|
|
956
|
+
errors.push({ line: i + 1, message: `step ${i + 1}: ${error}`, severity: 'error' });
|
|
957
|
+
}
|
|
909
958
|
// Match workflow_execute: control steps do not dispatch agents,
|
|
910
959
|
// and task steps use config.agentId or the workflow default.
|
|
911
960
|
const config = step.config;
|
|
@@ -175,8 +175,12 @@ declare class LocalReasoningBank {
|
|
|
175
175
|
* Deduplicates by content: if a pattern with the same content already
|
|
176
176
|
* exists, the existing entry is updated (bumped usageCount, higher
|
|
177
177
|
* confidence wins, refreshed lastUsedAt) instead of adding a duplicate.
|
|
178
|
+
*
|
|
179
|
+
* Returns true only when a NEW pattern was added (#3979 item 4): callers that
|
|
180
|
+
* keep a "patterns learned" counter must not count a merge or an update of an
|
|
181
|
+
* existing pattern as a newly learned one.
|
|
178
182
|
*/
|
|
179
|
-
store(pattern: Omit<StoredPattern, 'usageCount' | 'createdAt' | 'lastUsedAt'> & Partial<StoredPattern>):
|
|
183
|
+
store(pattern: Omit<StoredPattern, 'usageCount' | 'createdAt' | 'lastUsedAt'> & Partial<StoredPattern>): boolean;
|
|
180
184
|
/**
|
|
181
185
|
* Find similar patterns by embedding.
|
|
182
186
|
*
|