@claude-flow/cli 3.12.0 → 3.12.2

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.
Files changed (53) hide show
  1. package/.claude/helpers/auto-memory-hook.mjs +34 -4
  2. package/.claude/helpers/hook-handler.cjs +17 -13
  3. package/.claude/helpers/intelligence.cjs +16 -2
  4. package/README.md +7 -4
  5. package/dist/src/commands/daemon.d.ts.map +1 -1
  6. package/dist/src/commands/daemon.js +76 -7
  7. package/dist/src/commands/daemon.js.map +1 -1
  8. package/dist/src/commands/init.d.ts.map +1 -1
  9. package/dist/src/commands/init.js +24 -3
  10. package/dist/src/commands/init.js.map +1 -1
  11. package/dist/src/commands/security.d.ts.map +1 -1
  12. package/dist/src/commands/security.js +70 -12
  13. package/dist/src/commands/security.js.map +1 -1
  14. package/dist/tsconfig.tsbuildinfo +1 -1
  15. package/package.json +3 -2
  16. package/plugins/ruflo-metaharness/.claude-flow/data/pending-insights.jsonl +1 -0
  17. package/plugins/ruflo-metaharness/.claude-flow/neural/stats.json +6 -0
  18. package/plugins/ruflo-metaharness/.claude-plugin/plugin.json +32 -0
  19. package/plugins/ruflo-metaharness/README.md +64 -0
  20. package/plugins/ruflo-metaharness/agents/metaharness-architect.md +58 -0
  21. package/plugins/ruflo-metaharness/commands/ruflo-metaharness.md +46 -0
  22. package/plugins/ruflo-metaharness/scripts/_harness.mjs +261 -0
  23. package/plugins/ruflo-metaharness/scripts/_similarity.mjs +161 -0
  24. package/plugins/ruflo-metaharness/scripts/_spike-similarity.mjs +223 -0
  25. package/plugins/ruflo-metaharness/scripts/audit-list.mjs +158 -0
  26. package/plugins/ruflo-metaharness/scripts/audit-trend.mjs +272 -0
  27. package/plugins/ruflo-metaharness/scripts/bench-parse-mcp-scan.mjs +146 -0
  28. package/plugins/ruflo-metaharness/scripts/bench-recordpair-overhead.mjs +186 -0
  29. package/plugins/ruflo-metaharness/scripts/bench-similarity.mjs +177 -0
  30. package/plugins/ruflo-metaharness/scripts/drift-from-history.mjs +363 -0
  31. package/plugins/ruflo-metaharness/scripts/genome.mjs +80 -0
  32. package/plugins/ruflo-metaharness/scripts/mcp-scan.mjs +111 -0
  33. package/plugins/ruflo-metaharness/scripts/mint.mjs +119 -0
  34. package/plugins/ruflo-metaharness/scripts/oia-audit.mjs +228 -0
  35. package/plugins/ruflo-metaharness/scripts/router-parallel-analyze.mjs +250 -0
  36. package/plugins/ruflo-metaharness/scripts/score.mjs +92 -0
  37. package/plugins/ruflo-metaharness/scripts/similarity.mjs +158 -0
  38. package/plugins/ruflo-metaharness/scripts/smoke.sh +2268 -0
  39. package/plugins/ruflo-metaharness/scripts/test-graceful-degradation.mjs +141 -0
  40. package/plugins/ruflo-metaharness/scripts/test-mcp-tools.mjs +437 -0
  41. package/plugins/ruflo-metaharness/scripts/test-parallel-pipeline.mjs +204 -0
  42. package/plugins/ruflo-metaharness/scripts/test-pipeline-roundtrip.mjs +586 -0
  43. package/plugins/ruflo-metaharness/scripts/test-similarity.mjs +334 -0
  44. package/plugins/ruflo-metaharness/scripts/test-with-openrouter.mjs +229 -0
  45. package/plugins/ruflo-metaharness/scripts/threat-model.mjs +59 -0
  46. package/plugins/ruflo-metaharness/skills/harness-drift-from-history/SKILL.md +65 -0
  47. package/plugins/ruflo-metaharness/skills/harness-genome/SKILL.md +54 -0
  48. package/plugins/ruflo-metaharness/skills/harness-mcp-scan/SKILL.md +47 -0
  49. package/plugins/ruflo-metaharness/skills/harness-mint/SKILL.md +72 -0
  50. package/plugins/ruflo-metaharness/skills/harness-oia-audit/SKILL.md +79 -0
  51. package/plugins/ruflo-metaharness/skills/harness-score/SKILL.md +66 -0
  52. package/plugins/ruflo-metaharness/skills/harness-similarity/SKILL.md +67 -0
  53. package/plugins/ruflo-metaharness/skills/harness-threat-model/SKILL.md +39 -0
@@ -0,0 +1,334 @@
1
+ #!/usr/bin/env node
2
+ // test-similarity.mjs — unit tests for the iter-36 production module
3
+ // `_similarity.mjs` (ADR-152 §3.1).
4
+ //
5
+ // The spike (_spike-similarity.mjs) verifies the two architectural
6
+ // invariants on synthetic fixtures. This test exercises each public
7
+ // function in isolation: projectToVec, cosine, categoricalAgreement,
8
+ // jaccard, similarity, opts.weights override, opts.perDimension shape.
9
+ //
10
+ // CONTRACT EACH FUNCTION MUST SATISFY
11
+ // - input contract documented in _similarity.mjs holds
12
+ // - missing optional fields default safely (graceful, never throws)
13
+ // - numerical results are deterministic (no floats from Math.random)
14
+ // - return shapes match ADR-152 §"return shape"
15
+ //
16
+ // USAGE
17
+ // node scripts/test-similarity.mjs
18
+ // node scripts/test-similarity.mjs --format json
19
+ //
20
+ // EXIT
21
+ // 0 all unit tests pass
22
+ // 1 at least one test failed
23
+
24
+ import {
25
+ projectToVec, cosine, categoricalAgreement, jaccard, similarity,
26
+ } from './_similarity.mjs';
27
+ // iter 64 — also test the iter-63 shared severity primitives
28
+ import { SEVERITY_RANK, rankSeverity, parseMcpScanText } from './_harness.mjs';
29
+
30
+ const ARGS = (() => {
31
+ const a = { format: 'table' };
32
+ for (let i = 2; i < process.argv.length; i++) {
33
+ if (process.argv[i] === '--format') a.format = process.argv[++i];
34
+ }
35
+ return a;
36
+ })();
37
+
38
+ let passed = 0, failed = 0;
39
+ const failures = [];
40
+
41
+ function assert(cond, label) {
42
+ if (cond) { console.log(` ✓ ${label}`); passed++; }
43
+ else { console.log(` ✗ ${label}`); failures.push(label); failed++; }
44
+ }
45
+
46
+ function approx(a, b, eps = 0.0001) {
47
+ return Math.abs(a - b) < eps;
48
+ }
49
+
50
+ // ──────────────────────────────────────────────────────────────────
51
+ // FIXTURES — share two harness shapes across all tests
52
+ // ──────────────────────────────────────────────────────────────────
53
+
54
+ const A = {
55
+ score: {
56
+ harnessFit: 80, compileConfidence: 100, taskCoverage: 70, toolSafety: 90,
57
+ memoryUsefulness: 50, estCostPerRunUsd: 0.05, recommendedMode: 'CLI + MCP',
58
+ archetype: 'typescript-sdk-harness', template: 'vertical:coding',
59
+ },
60
+ genome: {
61
+ repo_type: 'node_mcp_ci',
62
+ agent_topology: ['maintainer', 'tester', 'security'],
63
+ risk_score: 0.3, test_confidence: 0.85, publish_readiness: 0.9,
64
+ },
65
+ };
66
+
67
+ const B = {
68
+ score: {
69
+ harnessFit: 60, compileConfidence: 80, taskCoverage: 50, toolSafety: 70,
70
+ memoryUsefulness: 30, estCostPerRunUsd: 0.02, recommendedMode: 'CLI',
71
+ archetype: 'python-agent-harness', template: 'vertical:devops',
72
+ },
73
+ genome: {
74
+ repo_type: 'python_ops',
75
+ agent_topology: ['deployer', 'rollback'],
76
+ risk_score: 0.1, test_confidence: 0.6, publish_readiness: 0.5,
77
+ },
78
+ };
79
+
80
+ // ──────────────────────────────────────────────────────────────────
81
+ console.log(`# test-similarity — _similarity.mjs unit tests (iter 39)\n`);
82
+
83
+ console.log('Phase 1 — projectToVec');
84
+ const vA = projectToVec(A);
85
+ assert(Array.isArray(vA), 'returns an array');
86
+ assert(vA.length === 9, 'returns 9-dim vector (ADR-152 §Decision Table 1)');
87
+ assert(approx(vA[0], 0.80), 'index 0 = harnessFit/100 (80 → 0.80)');
88
+ assert(approx(vA[1], 1.00), 'index 1 = compileConfidence/100 (100 → 1.00)');
89
+ assert(approx(vA[2], 0.70), 'index 2 = taskCoverage/100');
90
+ assert(approx(vA[3], 0.90), 'index 3 = toolSafety/100');
91
+ assert(approx(vA[4], 0.50), 'index 4 = memoryUsefulness/100');
92
+ assert(approx(vA[5], 0.30), 'index 5 = risk_score (already 0..1)');
93
+ assert(approx(vA[6], 0.85), 'index 6 = test_confidence');
94
+ assert(approx(vA[7], 0.90), 'index 7 = publish_readiness');
95
+ // Missing-field defaults safely (graceful degradation)
96
+ const vEmpty = projectToVec({});
97
+ assert(vEmpty.length === 9, 'empty input still returns 9-dim');
98
+ assert(vEmpty.every((x) => typeof x === 'number'), 'all elements numeric (no NaN propagation)');
99
+ const vNoGenome = projectToVec({ score: A.score });
100
+ assert(approx(vNoGenome[5], 0), 'missing genome → risk_score=0 default');
101
+ assert(approx(vNoGenome[0], 0.80), 'missing genome does not corrupt score-derived indices');
102
+
103
+ console.log('\nPhase 2 — cosine');
104
+ assert(approx(cosine(vA, vA), 1), 'cosine(x, x) === 1');
105
+ assert(approx(cosine([1, 0], [0, 1]), 0), 'orthogonal vectors → 0');
106
+ assert(approx(cosine([0, 0, 0], [1, 1, 1]), 0), 'zero vector → 0 (graceful divide-by-zero)');
107
+ assert(cosine([1, 2], [1, 2, 3]) === 0, 'length mismatch → 0 (graceful)');
108
+ assert(cosine(null, vA) === 0, 'null input → 0 (graceful)');
109
+ const cosAB = cosine(vA, projectToVec(B));
110
+ assert(cosAB >= 0 && cosAB <= 1, 'output bounded to [0, 1] for nonneg vectors');
111
+
112
+ console.log('\nPhase 3 — categoricalAgreement');
113
+ assert(approx(categoricalAgreement(A, A), 1), 'identical input → 1 (all 4 enums match)');
114
+ assert(approx(categoricalAgreement(A, B), 0), 'A vs B → 0 (all 4 enums differ)');
115
+ assert(approx(categoricalAgreement({}, {}), 0), 'both empty → 0 (no matches counted)');
116
+ // Partial match — 2 of 4 fields agree
117
+ const partial = {
118
+ score: { archetype: A.score.archetype, template: 'different', recommendedMode: A.score.recommendedMode },
119
+ genome: { repo_type: 'different' },
120
+ };
121
+ assert(approx(categoricalAgreement(A, partial), 0.5),
122
+ '2-of-4 partial match → 0.5 (archetype + recommendedMode)');
123
+
124
+ console.log('\nPhase 4 — jaccard');
125
+ assert(approx(jaccard(A, A), 1), 'identical topology → 1');
126
+ assert(approx(jaccard(A, B), 0), 'disjoint topology → 0');
127
+ assert(approx(jaccard({ genome: {} }, { genome: {} }), 1),
128
+ 'both empty topology → 1 (set-equality convention)');
129
+ const overlap = {
130
+ genome: { agent_topology: ['maintainer', 'tester', 'extra'] },
131
+ };
132
+ // A has {maintainer, tester, security}; overlap has {maintainer, tester, extra}
133
+ // |A ∩ B|=2, |A ∪ B|=4 → 2/4 = 0.5
134
+ assert(approx(jaccard(A, overlap), 0.5), 'partial topology overlap → |∩|/|∪|');
135
+
136
+ console.log('\nPhase 5 — similarity composite + return shape');
137
+ const sAA = similarity(A, A);
138
+ assert(typeof sAA === 'object' && sAA !== null, 'returns object');
139
+ assert(typeof sAA.overall === 'number', 'overall is numeric');
140
+ assert(approx(sAA.overall, 1), 'similarity(X, X).overall === 1');
141
+ assert(typeof sAA.components === 'object', 'components present');
142
+ assert(approx(sAA.components.cosine, 1), 'components.cosine === 1 on self-match');
143
+ assert(approx(sAA.components.categorical, 1), 'components.categorical === 1');
144
+ assert(approx(sAA.components.jaccard, 1), 'components.jaccard === 1');
145
+ assert(typeof sAA.weights === 'object', 'weights echoed in return');
146
+ assert(approx(sAA.weights.cosine, 0.6), 'default cosine weight = 0.6 (ADR-152)');
147
+ assert(approx(sAA.weights.categorical, 0.25), 'default categorical weight = 0.25');
148
+ assert(approx(sAA.weights.jaccard, 0.15), 'default jaccard weight = 0.15');
149
+ assert(approx(sAA.weights.cosine + sAA.weights.categorical + sAA.weights.jaccard, 1),
150
+ 'default weights sum to 1');
151
+
152
+ console.log('\nPhase 6 — similarity opts.weights override');
153
+ const reweighted = similarity(A, B, { weights: { cosine: 0, categorical: 0, jaccard: 1 } });
154
+ const jacOnly = jaccard(A, B);
155
+ assert(approx(reweighted.overall, jacOnly),
156
+ 'opts.weights cosine=0/cat=0/jac=1 → overall === jaccard');
157
+ const reweighted2 = similarity(A, A, { weights: { cosine: 0.5, categorical: 0.3, jaccard: 0.2 } });
158
+ assert(approx(reweighted2.overall, 1),
159
+ 'self-match holds under any weight scheme');
160
+
161
+ console.log('\nPhase 7 — similarity opts.perDimension shape');
162
+ const sPD = similarity(A, B, { perDimension: true });
163
+ assert(typeof sPD.perDimension === 'object', 'perDimension included when requested');
164
+ assert('numeric.harnessFit' in sPD.perDimension,
165
+ 'perDimension exposes each numeric feature by name');
166
+ assert('categorical.archetype' in sPD.perDimension,
167
+ 'perDimension exposes each categorical field by name');
168
+ assert('set.agent_topology' in sPD.perDimension,
169
+ 'perDimension exposes the set-typed feature');
170
+ const hf = sPD.perDimension['numeric.harnessFit'];
171
+ assert(hf.a === 80 && hf.b === 60, 'perDimension preserves raw a/b values');
172
+ assert(typeof hf.contribution === 'number', 'perDimension has numeric contribution');
173
+ const sNoPD = similarity(A, B);
174
+ assert(!('perDimension' in sNoPD), 'perDimension omitted by default');
175
+
176
+ console.log('\nPhase 8 — round-trip with the iter-35 spike fixtures (regression anchor)');
177
+ // Hard-coded spike numbers from `_spike-similarity.mjs` — ANY change
178
+ // here means the production module drifted from the spike's frozen
179
+ // invariants (catches future weight or normalization changes).
180
+ const LEGAL = {
181
+ score: { harnessFit: 78, compileConfidence: 92, taskCoverage: 65, toolSafety: 88, memoryUsefulness: 70, estCostPerRunUsd: 0.04, recommendedMode: 'CLI + MCP', archetype: 'compliance-harness', template: 'vertical:legal' },
182
+ genome: { repo_type: 'node_mcp_ci', agent_topology: ['contract-analyst', 'redline-reviewer', 'risk-rater', 'compliance-officer'], risk_score: 0.45, test_confidence: 0.7, publish_readiness: 0.6 },
183
+ };
184
+ const SUPPORT = {
185
+ score: { harnessFit: 75, compileConfidence: 90, taskCoverage: 70, toolSafety: 90, memoryUsefulness: 72, estCostPerRunUsd: 0.05, recommendedMode: 'CLI + MCP', archetype: 'compliance-harness', template: 'vertical:support' },
186
+ genome: { repo_type: 'node_mcp_ci', agent_topology: ['triager', 'kb-searcher', 'responder', 'risk-rater', 'compliance-officer'], risk_score: 0.40, test_confidence: 0.75, publish_readiness: 0.65 },
187
+ };
188
+ const sLS = similarity(LEGAL, SUPPORT);
189
+ assert(sLS.overall === 0.8296,
190
+ `LEGAL × SUPPORT overall must be exactly 0.8296 (got ${sLS.overall})`);
191
+ assert(sLS.components.cosine === 0.9987,
192
+ `LEGAL × SUPPORT cosine must be 0.9987 (got ${sLS.components.cosine})`);
193
+ assert(sLS.components.categorical === 0.75,
194
+ `LEGAL × SUPPORT categorical must be 0.75 (got ${sLS.components.categorical})`);
195
+ assert(sLS.components.jaccard === 0.2857,
196
+ `LEGAL × SUPPORT jaccard must be 0.2857 (got ${sLS.components.jaccard})`);
197
+
198
+ console.log('\nPhase 9 — iter-63 shared SEVERITY_RANK + rankSeverity()');
199
+ // Known severities — full vocab the iter-50 parser produces
200
+ assert(SEVERITY_RANK.clean === 0, 'rank.clean === 0');
201
+ assert(SEVERITY_RANK.info === 0, 'rank.info === 0 (informational, no harm)');
202
+ assert(SEVERITY_RANK.low === 1, 'rank.low === 1');
203
+ assert(SEVERITY_RANK.medium === 2, 'rank.medium === 2');
204
+ assert(SEVERITY_RANK.warn === 2, 'rank.warn === 2 (warn ≈ medium)');
205
+ assert(SEVERITY_RANK.high === 3, 'rank.high === 3');
206
+ assert(SEVERITY_RANK.error === 3, 'rank.error === 3 (error ≈ high)');
207
+ assert(SEVERITY_RANK.critical === 4, 'rank.critical === 4 (elevated above high)');
208
+
209
+ // Object.freeze blocks mutation — anti-tamper guard
210
+ const before = SEVERITY_RANK.high;
211
+ let mutated = false;
212
+ try { SEVERITY_RANK.high = 999; mutated = SEVERITY_RANK.high !== before; } catch { /* strict mode throws */ }
213
+ assert(!mutated, 'SEVERITY_RANK frozen — mutation does not stick');
214
+
215
+ // rankSeverity safe accessor
216
+ assert(rankSeverity('info') === 0, 'rankSeverity("info") === 0');
217
+ assert(rankSeverity('CRITICAL') === 4, 'rankSeverity case-insensitive ("CRITICAL" → 4)');
218
+ assert(rankSeverity('Warn') === 2, 'rankSeverity case-insensitive ("Warn" → 2)');
219
+ assert(rankSeverity('unknown') === 0, 'rankSeverity("unknown") === 0 (no NaN)');
220
+ assert(rankSeverity(null) === 0, 'rankSeverity(null) === 0');
221
+ assert(rankSeverity(undefined) === 0, 'rankSeverity(undefined) === 0');
222
+ assert(rankSeverity('') === 0, 'rankSeverity("") === 0');
223
+ assert(rankSeverity(' high ') === 0,
224
+ 'rankSeverity does not strip whitespace (returns 0 for non-normalized input)');
225
+
226
+ // Rollup pattern mirrors oia-audit's reduce
227
+ function rollup(findings) {
228
+ return findings.reduce((acc, f) => {
229
+ const s = String(f.severity || 'low').toLowerCase();
230
+ return rankSeverity(s) > rankSeverity(acc) ? s : acc;
231
+ }, 'clean');
232
+ }
233
+ assert(rollup([{ severity: 'info' }]) === 'clean',
234
+ 'rollup info-only stays clean');
235
+ assert(rollup([{ severity: 'warn' }]) === 'warn',
236
+ 'rollup warn-only elevates to warn (was NaN-ignored pre-iter-63)');
237
+ assert(rollup([{ severity: 'critical' }, { severity: 'info' }]) === 'critical',
238
+ 'rollup with critical elevates above info');
239
+ assert(rollup([{ severity: 'low' }, { severity: 'warn' }, { severity: 'high' }, { severity: 'critical' }]) === 'critical',
240
+ 'rollup picks max across mixed severities');
241
+ assert(rollup([{ severity: 'unknown-strange-value' }]) === 'clean',
242
+ 'rollup with unknown severity stays clean (safe default)');
243
+
244
+ console.log('\nPhase 10 — iter-50 parseMcpScanText edge cases');
245
+
246
+ // Empty input — graceful return shape
247
+ const empty = parseMcpScanText('');
248
+ assert(Array.isArray(empty.findings) && empty.findings.length === 0,
249
+ 'parseMcpScanText("") → findings:[]');
250
+ assert(empty.summary === null, 'parseMcpScanText("") → summary:null');
251
+
252
+ // null / undefined safe
253
+ const nullParsed = parseMcpScanText(null);
254
+ assert(Array.isArray(nullParsed.findings) && nullParsed.findings.length === 0,
255
+ 'parseMcpScanText(null) → findings:[]');
256
+ const undefParsed = parseMcpScanText(undefined);
257
+ assert(Array.isArray(undefParsed.findings) && undefParsed.findings.length === 0,
258
+ 'parseMcpScanText(undefined) → findings:[]');
259
+
260
+ // Single finding — happy path
261
+ const single = parseMcpScanText(`harness mcp-scan — /repo
262
+
263
+ [INFO] No MCP security issues found
264
+
265
+ Result: INFO (1 finding, 0 high)
266
+ `);
267
+ assert(single.findings.length === 1, 'single [INFO] block → 1 finding');
268
+ assert(single.findings[0].severity === 'info', 'severity lowercased');
269
+ assert(single.findings[0].message === 'No MCP security issues found',
270
+ 'message extracted');
271
+ assert(single.summary?.overallSeverity === 'info',
272
+ 'summary.overallSeverity from Result: line');
273
+ assert(single.summary?.totalCount === 1,
274
+ 'summary.totalCount === 1 from "(1 finding,"');
275
+
276
+ // Continuation line — indented text appends to previous finding
277
+ const cont = parseMcpScanText(`
278
+ [HIGH] Exposed credential path
279
+ Detected in .mcp/servers.json line 12
280
+ Recommended action: rotate immediately
281
+
282
+ Result: HIGH (1 finding, 1 high)
283
+ `);
284
+ assert(cont.findings.length === 1, 'finding with continuation = 1 entry');
285
+ assert(cont.findings[0].severity === 'high', 'HIGH lowercased to high');
286
+ assert(cont.findings[0].message.includes('Detected in') &&
287
+ cont.findings[0].message.includes('rotate immediately'),
288
+ 'continuation lines appended to message');
289
+
290
+ // Multiple findings — distinct entries
291
+ const multi = parseMcpScanText(`
292
+ [WARN] First issue
293
+ [HIGH] Second issue
294
+ [CRITICAL] Third issue
295
+
296
+ Result: HIGH (3 findings, 2 high)
297
+ `);
298
+ assert(multi.findings.length === 3, 'multiple findings = 3 entries');
299
+ assert(multi.findings.map((f) => f.severity).join(',') === 'warn,high,critical',
300
+ 'severities preserved in order');
301
+ assert(multi.summary?.totalCount === 3, 'multi summary totalCount === 3');
302
+
303
+ // No Result: line — summary stays null but findings still parsed
304
+ const noResult = parseMcpScanText(` [INFO] Lone finding\n`);
305
+ assert(noResult.findings.length === 1, 'no Result: line → still parses findings');
306
+ assert(noResult.summary === null, 'no Result: line → summary === null');
307
+
308
+ // Mixed-case severity in source — parser is intentionally strict: regex
309
+ // captures `[A-Z]+` so mixed-case 'Warn' WON'T match. This is the
310
+ // documented contract — upstream emits all-uppercase markers.
311
+ const mixed = parseMcpScanText(' [Warn] Something\n [HIGH] Other\n');
312
+ assert(mixed.findings.length === 1,
313
+ 'strict regex skips mixed-case [Warn], captures [HIGH] only');
314
+ assert(mixed.findings[0].severity === 'high',
315
+ 'strict regex captured the uppercase entry');
316
+
317
+ // ──────────────────────────────────────────────────────────────────
318
+ const summary = {
319
+ passed, failed,
320
+ failures,
321
+ total: passed + failed,
322
+ graduates: failed === 0,
323
+ };
324
+
325
+ console.log(`\n${passed} passed, ${failed} failed`);
326
+ if (ARGS.format === 'json') {
327
+ console.log(JSON.stringify(summary, null, 2));
328
+ }
329
+ if (failed > 0) {
330
+ console.log('\nFailures:');
331
+ for (const f of failures) console.log(` - ${f}`);
332
+ process.exit(1);
333
+ }
334
+ console.log('\n✓ All _similarity.mjs unit tests pass (ADR-152 §3.1 production contract).');
@@ -0,0 +1,229 @@
1
+ #!/usr/bin/env node
2
+ // test-with-openrouter.mjs — runtime test that exercises metaharness
3
+ // scaffolding + lifecycle commands using OPENROUTER_API_KEY fetched
4
+ // from GCP Secret Manager.
5
+ //
6
+ // WHAT IT DOES (end-to-end)
7
+ // 1. Fetch OPENROUTER_API_KEY from GCP Secret Manager via
8
+ // `gcloud secrets versions access latest --secret=OPENROUTER_API_KEY`
9
+ // 2. Verify the secret authenticates against OpenRouter by listing
10
+ // models (1 HTTP call, ~$0)
11
+ // 3. Scaffold a fresh harness into a temp dir via
12
+ // `metaharness new --name test-h --template vertical:coding
13
+ // --host claude-code --yes`
14
+ // 4. Run lifecycle commands against the scaffold:
15
+ // - harness doctor (smoke health check)
16
+ // - harness validate (full validation; --skip-gcp to avoid
17
+ // nested GCP fetches in this test)
18
+ // - harness score (5-dim scorecard of the scaffolded
19
+ // harness itself)
20
+ // - harness genome (7-section report)
21
+ // 5. (Optional) make one real LLM call through OpenRouter to a
22
+ // cheap model (e.g. openrouter/auto with a 1-token prompt) to
23
+ // prove the token works for actual inference
24
+ // 6. Clean up the temp dir
25
+ //
26
+ // COST: ~$0 (1 model-list call + optional <$0.0001 inference call)
27
+ //
28
+ // USAGE
29
+ // node scripts/test-with-openrouter.mjs # full e2e
30
+ // node scripts/test-with-openrouter.mjs --skip-inference # no LLM call
31
+ // node scripts/test-with-openrouter.mjs --keep-fixtures # leave scaffold for inspection
32
+ //
33
+ // EXIT CODES
34
+ // 0 all checks passed
35
+ // 1 at least one assertion failed
36
+ // 2 setup error (gcloud not authed, OPENROUTER_API_KEY missing in GCP, etc.)
37
+ // 3 cost/safety guard tripped
38
+
39
+ import { spawnSync, execSync } from 'node:child_process';
40
+ import { mkdtempSync, rmSync, mkdirSync, existsSync } from 'node:fs';
41
+ import { tmpdir } from 'node:os';
42
+ import { join } from 'node:path';
43
+
44
+ const ARGS = (() => {
45
+ const a = { skipInference: false, keep: false, format: 'table' };
46
+ for (let i = 2; i < process.argv.length; i++) {
47
+ const v = process.argv[i];
48
+ if (v === '--skip-inference') a.skipInference = true;
49
+ else if (v === '--keep-fixtures') a.keep = true;
50
+ else if (v === '--format') a.format = process.argv[++i];
51
+ }
52
+ return a;
53
+ })();
54
+
55
+ let passed = 0, failed = 0;
56
+ const failures = [];
57
+ function assert(cond, label) {
58
+ if (cond) { console.log(` ✓ ${label}`); passed++; }
59
+ else { console.log(` ✗ ${label}`); failures.push(label); failed++; }
60
+ }
61
+
62
+ function fetchSecretFromGcp(secretName) {
63
+ try {
64
+ const out = execSync(
65
+ `gcloud secrets versions access latest --secret=${secretName}`,
66
+ { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 15_000 },
67
+ );
68
+ return out.trim();
69
+ } catch (e) {
70
+ console.error(` ⚠ gcloud secret fetch failed: ${(e.message || '').slice(0, 120)}`);
71
+ return null;
72
+ }
73
+ }
74
+
75
+ async function listOpenRouterModels(apiKey) {
76
+ const resp = await fetch('https://openrouter.ai/api/v1/models', {
77
+ headers: { Authorization: `Bearer ${apiKey}` },
78
+ });
79
+ if (!resp.ok) {
80
+ return { ok: false, status: resp.status, body: (await resp.text()).slice(0, 200) };
81
+ }
82
+ const data = await resp.json();
83
+ return { ok: true, modelCount: data.data?.length ?? 0 };
84
+ }
85
+
86
+ async function cheapInferenceCall(apiKey) {
87
+ // openrouter/auto picks the cheapest viable model; 5-token prompt;
88
+ // max_tokens=1 to bound cost at ~$0.00005.
89
+ const resp = await fetch('https://openrouter.ai/api/v1/chat/completions', {
90
+ method: 'POST',
91
+ headers: {
92
+ Authorization: `Bearer ${apiKey}`,
93
+ 'Content-Type': 'application/json',
94
+ 'HTTP-Referer': 'https://github.com/ruvnet/ruflo',
95
+ 'X-Title': 'ruflo-metaharness-test',
96
+ },
97
+ body: JSON.stringify({
98
+ model: 'openrouter/auto',
99
+ messages: [{ role: 'user', content: 'OK' }],
100
+ max_tokens: 1,
101
+ }),
102
+ });
103
+ if (!resp.ok) return { ok: false, status: resp.status, body: (await resp.text()).slice(0, 200) };
104
+ const data = await resp.json();
105
+ return { ok: true, model: data.model, usage: data.usage };
106
+ }
107
+
108
+ function runHarness(args, opts = {}) {
109
+ const r = spawnSync('npx', ['-y', '-p', 'metaharness@latest', 'harness', ...args], {
110
+ stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8',
111
+ timeout: opts.timeoutMs ?? 60_000,
112
+ env: { ...process.env, ...opts.env },
113
+ });
114
+ return { exitCode: r.status ?? 1, stdout: r.stdout || '', stderr: r.stderr || '' };
115
+ }
116
+
117
+ function runMetaharness(args, opts = {}) {
118
+ const r = spawnSync('npx', ['-y', 'metaharness@latest', ...args], {
119
+ stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8',
120
+ timeout: opts.timeoutMs ?? 120_000,
121
+ cwd: opts.cwd, // metaharness new writes to cwd/<name>; --target is ignored
122
+ env: { ...process.env, ...opts.env },
123
+ });
124
+ return { exitCode: r.status ?? 1, stdout: r.stdout || '', stderr: r.stderr || '' };
125
+ }
126
+
127
+ async function main() {
128
+ console.log('# test-with-openrouter — metaharness × GCP × OpenRouter e2e\n');
129
+
130
+ // ── 0. Preflight ──────────────────────────────────────────────────
131
+ console.log('Phase 0 — preflight');
132
+ const gcloudWho = execSync('gcloud config get-value account 2>&1', { encoding: 'utf-8' }).trim();
133
+ assert(!!gcloudWho && !/None/.test(gcloudWho), `gcloud authenticated (${gcloudWho || 'none'})`);
134
+
135
+ // ── 1. Fetch OPENROUTER_API_KEY ───────────────────────────────────
136
+ console.log('\nPhase 1 — fetch OPENROUTER_API_KEY from GCP Secret Manager');
137
+ const apiKey = fetchSecretFromGcp('OPENROUTER_API_KEY');
138
+ assert(typeof apiKey === 'string' && apiKey.length > 20, 'OPENROUTER_API_KEY fetched (length OK)');
139
+ if (!apiKey) {
140
+ console.error('Setup error: cannot proceed without OPENROUTER_API_KEY. Skipping further phases.');
141
+ process.exit(2);
142
+ }
143
+ // Echo only length+prefix, never the raw key
144
+ console.log(` key length: ${apiKey.length}, prefix: ${apiKey.slice(0, 7)}…`);
145
+
146
+ // ── 2. Verify the key authenticates against OpenRouter ────────────
147
+ console.log('\nPhase 2 — verify OpenRouter authentication');
148
+ const modelsResp = await listOpenRouterModels(apiKey);
149
+ assert(modelsResp.ok, `OpenRouter /api/v1/models returns 2xx (got ${modelsResp.ok ? 'ok' : modelsResp.status})`);
150
+ if (modelsResp.ok) {
151
+ assert(modelsResp.modelCount > 10, `model list non-empty (${modelsResp.modelCount} models)`);
152
+ }
153
+
154
+ // ── 3. Scaffold a fresh harness ───────────────────────────────────
155
+ // CRITICAL: `metaharness new <name>` writes to $CWD/<name> — the
156
+ // --target flag is ignored by the CLI (verified 2026-06-16 against
157
+ // metaharness@0.1.11). Run from inside a fresh temp dir so the
158
+ // scaffold lands there, not in the ruflo project root.
159
+ console.log('\nPhase 3 — scaffold a fresh harness');
160
+ const fixture = mkdtempSync(join(tmpdir(), 'ruflo-mh-openrouter-'));
161
+ const target = join(fixture, 'test-harness');
162
+ console.log(` fixture cwd: ${fixture}`);
163
+ console.log(` expected target: ${target}`);
164
+ const scaffold = runMetaharness(
165
+ ['test-harness', '--template', 'vertical:coding', '--host', 'claude-code'],
166
+ { timeoutMs: 180_000, cwd: fixture },
167
+ );
168
+ assert(scaffold.exitCode === 0, `metaharness new exit 0 (got ${scaffold.exitCode})`);
169
+ assert(existsSync(target), `target dir created at ${target}`);
170
+
171
+ // ── 4. Run lifecycle commands against the scaffold ────────────────
172
+ console.log('\nPhase 4 — lifecycle commands on the scaffold');
173
+ // harness doctor — quick smoke
174
+ const doc = runHarness(['doctor', target]);
175
+ assert(doc.exitCode === 0, `harness doctor exit 0 (got ${doc.exitCode})`);
176
+
177
+ // harness score on the scaffold itself
178
+ const score = runHarness(['score', target, '--json']);
179
+ assert(score.exitCode === 0, `harness score exit 0 (got ${score.exitCode})`);
180
+ const scoreJson = (() => {
181
+ const m = /\{[\s\S]*\}/.exec(score.stdout);
182
+ try { return m ? JSON.parse(m[0]) : null; } catch { return null; }
183
+ })();
184
+ assert(scoreJson && typeof scoreJson.score === 'number', 'score.json has numeric score');
185
+
186
+ // harness genome — exit 0 (ready) or 1 (needs-work) both acceptable.
187
+ // Only exit 2 (blocked / scan-error) is a real failure.
188
+ const gen = runHarness(['genome', target, '--json']);
189
+ assert(gen.exitCode === 0 || gen.exitCode === 1, `harness genome exit 0 or 1 (got ${gen.exitCode})`);
190
+
191
+ // harness mcp-scan
192
+ const scan = runHarness(['mcp-scan', target]);
193
+ // mcp-scan can exit 1 on findings; either 0 or 1 is acceptable here.
194
+ assert(scan.exitCode === 0 || scan.exitCode === 1, `harness mcp-scan exit 0 or 1 (got ${scan.exitCode})`);
195
+
196
+ // ── 5. (Optional) one real OpenRouter inference call ──────────────
197
+ if (!ARGS.skipInference) {
198
+ console.log('\nPhase 5 — single OpenRouter inference call (cheapest auto-route, max_tokens=1)');
199
+ const inf = await cheapInferenceCall(apiKey);
200
+ assert(inf.ok, `OpenRouter inference 2xx (got ${inf.ok ? 'ok' : inf.status})`);
201
+ if (inf.ok) {
202
+ console.log(` model used: ${inf.model}`);
203
+ console.log(` usage: prompt=${inf.usage?.prompt_tokens} completion=${inf.usage?.completion_tokens}`);
204
+ }
205
+ } else {
206
+ console.log('\nPhase 5 — SKIPPED (--skip-inference)');
207
+ }
208
+
209
+ // ── 6. Cleanup ────────────────────────────────────────────────────
210
+ if (!ARGS.keep) {
211
+ rmSync(fixture, { recursive: true, force: true });
212
+ console.log(`\nFixture cleaned: ${fixture}`);
213
+ } else {
214
+ console.log(`\nFixture kept at: ${fixture}`);
215
+ }
216
+
217
+ console.log(`\n${passed} passed, ${failed} failed`);
218
+ if (failed > 0) {
219
+ console.log('\nFailures:');
220
+ for (const f of failures) console.log(` - ${f}`);
221
+ process.exit(1);
222
+ }
223
+ console.log('\n✓ All harness × OpenRouter integration checks passed.');
224
+ }
225
+
226
+ main().catch((e) => {
227
+ console.error('test-with-openrouter crashed:', e.message || e);
228
+ process.exit(2);
229
+ });
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+ // threat-model.mjs — wrapper around `harness threat-model <path>`.
3
+ //
4
+ // USAGE
5
+ // node scripts/threat-model.mjs --path . --fail-on high --format json
6
+
7
+ import { runHarness, emitDegradedJsonAndExit } from './_harness.mjs';
8
+
9
+ const SEVERITY_RANK = { clean: 0, low: 1, medium: 2, high: 3 };
10
+
11
+ const ARGS = (() => {
12
+ const a = { path: '.', format: 'json', failOn: 'high' };
13
+ for (let i = 2; i < process.argv.length; i++) {
14
+ const v = process.argv[i];
15
+ if (v === '--path') a.path = process.argv[++i];
16
+ else if (v === '--fail-on') a.failOn = String(process.argv[++i] || 'high').toLowerCase();
17
+ else if (v === '--format') a.format = process.argv[++i];
18
+ }
19
+ return a;
20
+ })();
21
+
22
+ function main() {
23
+ if (!SEVERITY_RANK.hasOwnProperty(ARGS.failOn)) {
24
+ console.error(`threat-model: --fail-on must be one of clean|low|medium|high`);
25
+ process.exit(2);
26
+ }
27
+ const r = runHarness(['threat-model', ARGS.path]);
28
+ if (r.degraded) { emitDegradedJsonAndExit(r.reason); return; }
29
+ if (r.exitCode !== 0 && r.exitCode !== 1) {
30
+ console.error(`threat-model: harness exited ${r.exitCode}`);
31
+ if (r.stderr) console.error(r.stderr.slice(0, 400));
32
+ process.exit(2);
33
+ }
34
+ const payload = r.json ?? { rawStdout: r.stdout.slice(0, 400) };
35
+ const worst = String(payload?.worst || 'clean').toLowerCase();
36
+ const threshold = SEVERITY_RANK[ARGS.failOn];
37
+ const triggered = SEVERITY_RANK[worst] >= threshold && threshold > 0;
38
+ const alert = {
39
+ threshold: ARGS.failOn, worst, triggered,
40
+ reason: triggered
41
+ ? `worst=${worst} at or above ${ARGS.failOn}`
42
+ : `worst=${worst} below ${ARGS.failOn} — OK`,
43
+ };
44
+
45
+ if (ARGS.format === 'json') {
46
+ console.log(JSON.stringify({ ...payload, durationMs: r.durationMs, alert }, null, 2));
47
+ } else {
48
+ console.log(`# harness threat-model — ${ARGS.path}`);
49
+ console.log('');
50
+ console.log(`Worst severity: ${worst}`);
51
+ console.log(`Findings: ${(payload?.findings || []).length}`);
52
+ console.log('');
53
+ console.log(alert.triggered ? `⚠ **ALERT**: ${alert.reason}` : `✓ ${alert.reason}`);
54
+ }
55
+
56
+ if (alert.triggered) process.exit(1);
57
+ }
58
+
59
+ main();