@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,146 @@
1
+ #!/usr/bin/env node
2
+ // bench-parse-mcp-scan — perf characterization for iter-50's
3
+ // parseMcpScanText. Sister to iter-41's bench-similarity.mjs.
4
+ //
5
+ // THE CLAIM
6
+ // parseMcpScanText is a small regex over short text. Sub-microsecond
7
+ // per call expected. Phase-3 consumers (oia-audit + the audit-trend
8
+ // introduced/cleared diff) call it once per audit run, so the per-call
9
+ // cost compounds if the parser is on a slow path.
10
+ //
11
+ // WHAT IT MEASURES
12
+ // Per-call mean + p50 + p99 over 100k iters, across 3 categories:
13
+ // - empty: parseMcpScanText('') — fastest path
14
+ // - typical: ruflo's actual single-INFO output
15
+ // - rich: a synthetic multi-finding payload with continuation lines
16
+ //
17
+ // USAGE
18
+ // node scripts/bench-parse-mcp-scan.mjs # default 100k iters
19
+ // node scripts/bench-parse-mcp-scan.mjs --iters 1000000
20
+ // node scripts/bench-parse-mcp-scan.mjs --format json
21
+ // node scripts/bench-parse-mcp-scan.mjs --max-mean-us 5 # CI gate
22
+ //
23
+ // EXIT CODES
24
+ // 0 ok (or threshold satisfied)
25
+ // 1 --max-mean-us exceeded by any category
26
+
27
+ import { performance } from 'node:perf_hooks';
28
+ import { parseMcpScanText } from './_harness.mjs';
29
+
30
+ const ARGS = (() => {
31
+ const a = { iters: 100_000, format: 'table', maxMeanUs: null };
32
+ for (let i = 2; i < process.argv.length; i++) {
33
+ const v = process.argv[i];
34
+ if (v === '--iters') a.iters = parseInt(process.argv[++i], 10);
35
+ else if (v === '--format') a.format = process.argv[++i];
36
+ else if (v === '--max-mean-us') a.maxMeanUs = parseFloat(process.argv[++i]);
37
+ }
38
+ return a;
39
+ })();
40
+
41
+ const EMPTY = '';
42
+
43
+ const TYPICAL = `harness mcp-scan — /repo
44
+
45
+ [INFO] No MCP security issues found
46
+ Policy is default-deny with safe capability grants and an audit log.
47
+
48
+ Result: INFO (1 finding, 0 high)
49
+ `;
50
+
51
+ const RICH = `harness mcp-scan — /repo
52
+
53
+ [HIGH] First high-severity finding
54
+ Continuation line 1
55
+ Continuation line 2
56
+ [WARN] Second warning finding
57
+ Some additional context
58
+ [HIGH] Third high finding
59
+ [INFO] Fourth informational
60
+ Multi-line message body
61
+ Spanning three lines
62
+ Ending here
63
+ [CRITICAL] Fifth critical issue
64
+ With single continuation
65
+
66
+ Result: HIGH (5 findings, 2 high)
67
+ `;
68
+
69
+ function bench(label, input, iters) {
70
+ // Warm-up
71
+ for (let i = 0; i < 10_000; i++) parseMcpScanText(input);
72
+
73
+ const samples = new Float64Array(iters);
74
+ for (let i = 0; i < iters; i++) {
75
+ const t0 = performance.now();
76
+ parseMcpScanText(input);
77
+ samples[i] = performance.now() - t0;
78
+ }
79
+ let sum = 0;
80
+ for (let i = 0; i < iters; i++) sum += samples[i];
81
+ const mean = sum / iters;
82
+ const sorted = Array.from(samples).sort((x, y) => x - y);
83
+ const p50 = sorted[Math.floor(iters * 0.5)];
84
+ const p99 = sorted[Math.floor(iters * 0.99)];
85
+ return {
86
+ label, iters,
87
+ meanMs: mean, p50Ms: p50, p99Ms: p99,
88
+ meanUs: mean * 1000, p99Us: p99 * 1000,
89
+ };
90
+ }
91
+
92
+ // iter 87 — suppress markdown header in --format json so captured
93
+ // file stays valid JSON.
94
+ if (ARGS.format !== 'json') {
95
+ console.log(`# bench-parse-mcp-scan — iter-50 parser per-call cost\n`);
96
+ console.log(`iters: ${ARGS.iters.toLocaleString()}\n`);
97
+ }
98
+
99
+ const results = [
100
+ bench('empty', EMPTY, ARGS.iters),
101
+ bench('typical (1 INFO)', TYPICAL, ARGS.iters),
102
+ bench('rich (5 findings)', RICH, ARGS.iters),
103
+ ];
104
+
105
+ let gate = { triggered: false, reasons: [] };
106
+ if (ARGS.maxMeanUs != null) {
107
+ for (const r of results) {
108
+ if (r.meanUs > ARGS.maxMeanUs) {
109
+ gate.triggered = true;
110
+ gate.reasons.push(`${r.label}: mean ${r.meanUs.toFixed(3)}μs > ceiling ${ARGS.maxMeanUs}μs`);
111
+ }
112
+ }
113
+ }
114
+
115
+ const payload = {
116
+ iters: ARGS.iters,
117
+ results,
118
+ gate: ARGS.maxMeanUs != null ? {
119
+ thresholdUs: ARGS.maxMeanUs,
120
+ triggered: gate.triggered,
121
+ reasons: gate.reasons,
122
+ } : null,
123
+ generatedAt: new Date().toISOString(),
124
+ contract: 'parseMcpScanText is sub-microsecond for empty/typical; rich (5 findings, 14 lines) stays under 10μs.',
125
+ };
126
+
127
+ if (ARGS.format === 'json') {
128
+ console.log(JSON.stringify(payload, null, 2));
129
+ } else {
130
+ console.log(`| Category | mean | p50 | p99 |`);
131
+ console.log(`|---------------------|-----------:|-----------:|-----------:|`);
132
+ for (const r of results) {
133
+ console.log(`| ${r.label.padEnd(19)} | ${r.meanUs.toFixed(3).padStart(7)}μs | ${(r.p50Ms * 1000).toFixed(3).padStart(7)}μs | ${r.p99Us.toFixed(3).padStart(7)}μs |`);
134
+ }
135
+ console.log('');
136
+ if (payload.gate) {
137
+ if (payload.gate.triggered) {
138
+ console.log(`⚠ ALERT: ceiling ${ARGS.maxMeanUs}μs exceeded by:`);
139
+ for (const reason of payload.gate.reasons) console.log(` - ${reason}`);
140
+ } else {
141
+ console.log(`✓ all categories within --max-mean-us ${ARGS.maxMeanUs}μs ceiling`);
142
+ }
143
+ }
144
+ }
145
+
146
+ if (gate.triggered) process.exit(1);
@@ -0,0 +1,186 @@
1
+ #!/usr/bin/env node
2
+ // bench-recordpair-overhead.mjs — micro-benchmark proving iter-12's
3
+ // "zero default-path overhead" claim with measured numbers.
4
+ //
5
+ // THE CLAIM
6
+ // Iter 12 added one env-flag check to model-router.ts route() so
7
+ // recordPair() fires only when CLAUDE_FLOW_ROUTER_PARALLEL_LOG=1.
8
+ // When unset (default), the cost is:
9
+ //
10
+ // if (process.env.CLAUDE_FLOW_ROUTER_PARALLEL_LOG === '1') { ... }
11
+ //
12
+ // This benchmark measures that exact pattern over 1,000,000 iterations
13
+ // and reports the per-call mean + p99. For the claim to hold, the
14
+ // per-call overhead must be sub-microsecond.
15
+ //
16
+ // USAGE
17
+ // node scripts/bench-recordpair-overhead.mjs # 1M iters
18
+ // node scripts/bench-recordpair-overhead.mjs --iters 5000000
19
+ // node scripts/bench-recordpair-overhead.mjs --format json
20
+ //
21
+ // EXIT CODES
22
+ // 0 benchmark complete (always; this is informational, not pass/fail)
23
+
24
+ import { performance } from 'node:perf_hooks';
25
+
26
+ const ARGS = (() => {
27
+ const a = {
28
+ iters: 1_000_000,
29
+ format: 'table',
30
+ // iter 25 — CI regression gate. When --max-overhead-ns N is set,
31
+ // exit 1 if the measured iter-12 default-path overhead exceeds N
32
+ // nanoseconds per call. Default threshold 500ns chosen as ~3.5×
33
+ // headroom over the iter-24 measured baseline of ~147ns on Apple
34
+ // Silicon / Node 22.
35
+ maxOverheadNs: null,
36
+ };
37
+ for (let i = 2; i < process.argv.length; i++) {
38
+ const v = process.argv[i];
39
+ if (v === '--iters') a.iters = parseInt(process.argv[++i], 10);
40
+ else if (v === '--format') a.format = process.argv[++i];
41
+ else if (v === '--max-overhead-ns') a.maxOverheadNs = parseFloat(process.argv[++i]);
42
+ }
43
+ return a;
44
+ })();
45
+
46
+ function bench(label, fn, iters) {
47
+ // Warm-up
48
+ for (let i = 0; i < 10_000; i++) fn();
49
+
50
+ const samples = new Float64Array(iters);
51
+ for (let i = 0; i < iters; i++) {
52
+ const start = performance.now();
53
+ fn();
54
+ samples[i] = performance.now() - start;
55
+ }
56
+ // performance.now() resolution is ~1 microsecond on most platforms.
57
+ // For sub-microsecond ops we can't measure individual iterations
58
+ // accurately; report aggregate timing instead.
59
+
60
+ // Also measure batched timing — sum of N calls in one hot loop —
61
+ // which IS accurate for sub-μs ops.
62
+ const batchStart = performance.now();
63
+ for (let i = 0; i < iters; i++) fn();
64
+ const batchTotal = performance.now() - batchStart;
65
+ const meanNs = (batchTotal * 1e6) / iters; // ms → ns / iters
66
+
67
+ // Sort samples for percentile reporting (per-call resolution-limited)
68
+ const sortedMs = Array.from(samples).sort((a, b) => a - b);
69
+ const p99 = sortedMs[Math.floor(0.99 * sortedMs.length)];
70
+
71
+ return {
72
+ label,
73
+ iters,
74
+ batchTotalMs: Math.round(batchTotal * 1000) / 1000,
75
+ meanNsPerCall: Math.round(meanNs * 100) / 100,
76
+ p99PerCallMs: Math.round(p99 * 10000) / 10000,
77
+ };
78
+ }
79
+
80
+ function main() {
81
+ const iters = ARGS.iters;
82
+ if (!Number.isInteger(iters) || iters < 1000) {
83
+ console.error('bench-recordpair-overhead: --iters must be ≥ 1000');
84
+ process.exit(2);
85
+ }
86
+
87
+ // iter 137 — guard the markdown header behind table-format so
88
+ // --format json emits pure JSON (consumed by CI's JSON.parse).
89
+ // Same fix-class as bench-similarity's iter 87 fix.
90
+ if (ARGS.format !== 'json') {
91
+ console.log(`# bench-recordpair-overhead`);
92
+ console.log('');
93
+ console.log(`Iterations: ${iters.toLocaleString()}`);
94
+ console.log(`Platform: ${process.platform} ${process.arch}, Node ${process.version}`);
95
+ console.log('');
96
+ }
97
+
98
+ // Baseline — no-op
99
+ const baseline = bench('baseline (no-op)', () => {}, iters);
100
+
101
+ // The iter-12 env-flag check, OFF case
102
+ // Match the exact source pattern from model-router.ts
103
+ delete process.env.CLAUDE_FLOW_ROUTER_PARALLEL_LOG; // ensure OFF
104
+ const envCheckOff = bench(
105
+ 'iter-12 env check (FLAG OFF — default path)',
106
+ () => { if (process.env.CLAUDE_FLOW_ROUTER_PARALLEL_LOG === '1') { /* unreached */ } },
107
+ iters,
108
+ );
109
+
110
+ // ON case — but no actual loadParallelRecorder().then() call (that's
111
+ // a one-time microtask amortized over the process lifetime). Measure
112
+ // just the conditional.
113
+ process.env.CLAUDE_FLOW_ROUTER_PARALLEL_LOG = '1';
114
+ const envCheckOn = bench(
115
+ 'iter-12 env check (FLAG ON — branch taken, NO recordPair)',
116
+ () => { if (process.env.CLAUDE_FLOW_ROUTER_PARALLEL_LOG === '1') { /* branch taken */ } },
117
+ iters,
118
+ );
119
+ delete process.env.CLAUDE_FLOW_ROUTER_PARALLEL_LOG;
120
+
121
+ // What does the LAZY-LOADER short-circuit cost when called repeatedly?
122
+ // Once initialized, it's a single nullness check on a module-level var.
123
+ let _cached = null;
124
+ const lazyLoaderInit = () => {
125
+ if (_cached === null) _cached = { mod: { recordPair: () => {} } };
126
+ return _cached;
127
+ };
128
+ // Run once to populate the cache
129
+ lazyLoaderInit();
130
+ const lazyLoaderHot = bench(
131
+ 'lazy loader (post-init nullness check)',
132
+ () => { lazyLoaderInit(); },
133
+ iters,
134
+ );
135
+
136
+ const results = [baseline, envCheckOff, envCheckOn, lazyLoaderHot];
137
+
138
+ if (ARGS.format === 'json') {
139
+ console.log(JSON.stringify({
140
+ platform: { os: process.platform, arch: process.arch, node: process.version },
141
+ iters,
142
+ results,
143
+ generatedAt: new Date().toISOString(),
144
+ }, null, 2));
145
+ return;
146
+ }
147
+
148
+ console.log(`| Variant | Total (ms) | Mean per-call (ns) | p99 sample (ms) |`);
149
+ console.log(`|---|---:|---:|---:|`);
150
+ for (const r of results) {
151
+ console.log(`| ${r.label} | ${r.batchTotalMs} | ${r.meanNsPerCall} | ${r.p99PerCallMs} |`);
152
+ }
153
+
154
+ // Interpret
155
+ const overhead = envCheckOff.meanNsPerCall - baseline.meanNsPerCall;
156
+ console.log('');
157
+ console.log(`**Iter-12 default-path overhead**: ~${Math.round(overhead)}ns per route() call`);
158
+ console.log('');
159
+ if (overhead < 100) {
160
+ console.log(`✓ Overhead < 100ns confirms iter-12's "zero default-path overhead" claim.`);
161
+ console.log(` At 1000 routing decisions per workload, total added cost is ~${Math.round(overhead * 1000 / 1000)}μs — imperceptible.`);
162
+ } else if (overhead < 1000) {
163
+ console.log(`✓ Overhead < 1μs is well within tolerable bounds.`);
164
+ } else {
165
+ console.log(`⚠ Overhead ${Math.round(overhead)}ns is higher than expected; investigate engine optimization.`);
166
+ }
167
+
168
+ // CI regression gate (iter 25).
169
+ if (ARGS.maxOverheadNs !== null) {
170
+ if (!isFinite(ARGS.maxOverheadNs) || ARGS.maxOverheadNs <= 0) {
171
+ console.error('bench-recordpair-overhead: --max-overhead-ns must be a positive number');
172
+ process.exit(2);
173
+ }
174
+ console.log('');
175
+ if (overhead > ARGS.maxOverheadNs) {
176
+ console.log(`⚠ **REGRESSION**: measured ${Math.round(overhead)}ns > threshold ${ARGS.maxOverheadNs}ns`);
177
+ console.log(` The iter-12 dispatch wiring may have grown beyond the env-flag check.`);
178
+ console.log(` Inspect v3/@claude-flow/cli/src/ruvector/model-router.ts route() for new work in the default path.`);
179
+ process.exit(1);
180
+ } else {
181
+ console.log(`✓ Within regression threshold (${Math.round(overhead)}ns ≤ ${ARGS.maxOverheadNs}ns).`);
182
+ }
183
+ }
184
+ }
185
+
186
+ main();
@@ -0,0 +1,177 @@
1
+ #!/usr/bin/env node
2
+ // bench-similarity.mjs — micro-benchmark for ADR-152 §3.1's production
3
+ // similarity() function. Establishes the per-call cost budget that
4
+ // future Phase-3 consumers (§3.2 Recommender N×M ranking, §3.3 Drift
5
+ // fleet-wide scan, §3.4 Capability graph traversal) inherit.
6
+ //
7
+ // THE CLAIM (iter 41 baseline)
8
+ // similarity(a, b) is a pure 9-dim cosine + 4-field categorical +
9
+ // set-jaccard composite — sub-microsecond per call on Apple Silicon /
10
+ // Node 22. Phase-3 consumers can therefore safely call it 10k+ times
11
+ // per request without sweating budget.
12
+ //
13
+ // WHAT IT MEASURES
14
+ // - Per-call mean + p50 + p99 over 1M iterations
15
+ // - Three input categories (cheap / typical / rich) to surface any
16
+ // payload-size sensitivity in projectToVec
17
+ //
18
+ // USAGE
19
+ // node scripts/bench-similarity.mjs # default 1M iters
20
+ // node scripts/bench-similarity.mjs --iters 5000000
21
+ // node scripts/bench-similarity.mjs --format json
22
+ // node scripts/bench-similarity.mjs --max-mean-us 10 # CI gate (exit 1 if mean > 10μs)
23
+ //
24
+ // EXIT CODES
25
+ // 0 ok (or --max-mean-us not set / threshold satisfied)
26
+ // 1 --max-mean-us threshold exceeded (regression)
27
+
28
+ import { performance } from 'node:perf_hooks';
29
+ import { similarity } from './_similarity.mjs';
30
+
31
+ const ARGS = (() => {
32
+ const a = {
33
+ iters: 1_000_000,
34
+ format: 'table',
35
+ // CI regression gate. When --max-mean-us N is set, exit 1 if any
36
+ // measured category's mean per-call cost exceeds N microseconds.
37
+ // Default ceiling 10μs chosen as ~5× headroom over Apple-Silicon
38
+ // baseline; works on slower CI runners.
39
+ maxMeanUs: null,
40
+ };
41
+ for (let i = 2; i < process.argv.length; i++) {
42
+ const v = process.argv[i];
43
+ if (v === '--iters') a.iters = parseInt(process.argv[++i], 10);
44
+ else if (v === '--format') a.format = process.argv[++i];
45
+ else if (v === '--max-mean-us') a.maxMeanUs = parseFloat(process.argv[++i]);
46
+ }
47
+ return a;
48
+ })();
49
+
50
+ // ───────────────────────────────────────────────────────────────────
51
+ // Three fixture categories
52
+ // ───────────────────────────────────────────────────────────────────
53
+
54
+ const CHEAP = {
55
+ // Bare-bones — everything defaulted from missing fields
56
+ score: { harnessFit: 50 },
57
+ genome: { agent_topology: ['a'] },
58
+ };
59
+
60
+ const TYPICAL = {
61
+ // The shape the iter-38 oia-audit fingerprint produces
62
+ score: {
63
+ harnessFit: 78, compileConfidence: 92, taskCoverage: 65,
64
+ toolSafety: 88, memoryUsefulness: 70, estCostPerRunUsd: 0.04,
65
+ recommendedMode: 'CLI + MCP', archetype: 'compliance-harness',
66
+ template: 'vertical:legal',
67
+ },
68
+ genome: {
69
+ repo_type: 'node_mcp_ci',
70
+ agent_topology: ['contract-analyst', 'redline-reviewer', 'risk-rater', 'compliance-officer'],
71
+ risk_score: 0.45, test_confidence: 0.7, publish_readiness: 0.6,
72
+ },
73
+ };
74
+
75
+ const RICH = {
76
+ // Larger agent_topology (Jaccard's variable-cost path)
77
+ score: TYPICAL.score,
78
+ genome: {
79
+ ...TYPICAL.genome,
80
+ agent_topology: Array.from({ length: 32 }, (_, i) => `agent-${i}`),
81
+ },
82
+ };
83
+
84
+ // ───────────────────────────────────────────────────────────────────
85
+ // Benchmark harness
86
+ // ───────────────────────────────────────────────────────────────────
87
+
88
+ function bench(label, a, b, iters) {
89
+ // Warm-up
90
+ for (let i = 0; i < 10_000; i++) similarity(a, b);
91
+
92
+ const samples = new Float64Array(iters);
93
+ for (let i = 0; i < iters; i++) {
94
+ const t0 = performance.now();
95
+ similarity(a, b);
96
+ samples[i] = performance.now() - t0;
97
+ }
98
+
99
+ // Stats
100
+ let sum = 0;
101
+ for (let i = 0; i < iters; i++) sum += samples[i];
102
+ const mean = sum / iters;
103
+
104
+ const sorted = Array.from(samples).sort((x, y) => x - y);
105
+ const p50 = sorted[Math.floor(iters * 0.5)];
106
+ const p99 = sorted[Math.floor(iters * 0.99)];
107
+
108
+ return {
109
+ label,
110
+ iters,
111
+ meanMs: mean,
112
+ p50Ms: p50,
113
+ p99Ms: p99,
114
+ meanUs: mean * 1000,
115
+ p99Us: p99 * 1000,
116
+ };
117
+ }
118
+
119
+ // ───────────────────────────────────────────────────────────────────
120
+ // iter 87 — suppress markdown header when --format json so the file
121
+ // captured via `> /tmp/bench-similarity.json` is valid JSON. Iter 82's
122
+ // CI step JSON.parse'd the captured file but silently failed because
123
+ // the `# bench-similarity` header contaminated the input.
124
+ if (ARGS.format !== 'json') {
125
+ console.log(`# bench-similarity — ADR-152 §3.1 per-call cost\n`);
126
+ console.log(`iters: ${ARGS.iters.toLocaleString()}\n`);
127
+ }
128
+
129
+ const results = [
130
+ bench('cheap', CHEAP, CHEAP, ARGS.iters),
131
+ bench('typical', TYPICAL, TYPICAL, ARGS.iters),
132
+ bench('rich (32 agents)', RICH, RICH, ARGS.iters),
133
+ ];
134
+
135
+ let gate = { triggered: false, reasons: [] };
136
+ if (ARGS.maxMeanUs != null) {
137
+ for (const r of results) {
138
+ if (r.meanUs > ARGS.maxMeanUs) {
139
+ gate.triggered = true;
140
+ gate.reasons.push(`${r.label}: mean ${r.meanUs.toFixed(3)}μs > threshold ${ARGS.maxMeanUs}μs`);
141
+ }
142
+ }
143
+ }
144
+
145
+ const payload = {
146
+ iters: ARGS.iters,
147
+ results,
148
+ gate: ARGS.maxMeanUs != null ? {
149
+ thresholdUs: ARGS.maxMeanUs,
150
+ triggered: gate.triggered,
151
+ reasons: gate.reasons,
152
+ } : null,
153
+ generatedAt: new Date().toISOString(),
154
+ // The performance contract — captured for /docs/benchmarks consumers
155
+ contract: 'similarity() is sub-microsecond on Apple Silicon / Node 22+; Phase-3 consumers may freely call O(N²) on N=1000 harnesses (~1s budget).',
156
+ };
157
+
158
+ if (ARGS.format === 'json') {
159
+ console.log(JSON.stringify(payload, null, 2));
160
+ } else {
161
+ console.log(`| Category | mean | p50 | p99 |`);
162
+ console.log(`|------------------|-----------:|-----------:|-----------:|`);
163
+ for (const r of results) {
164
+ console.log(`| ${r.label.padEnd(16)} | ${r.meanUs.toFixed(3).padStart(7)}μs | ${(r.p50Ms * 1000).toFixed(3).padStart(7)}μs | ${r.p99Us.toFixed(3).padStart(7)}μs |`);
165
+ }
166
+ console.log('');
167
+ if (payload.gate) {
168
+ if (payload.gate.triggered) {
169
+ console.log(`⚠ ALERT: mean per-call exceeded ${ARGS.maxMeanUs}μs ceiling:`);
170
+ for (const reason of payload.gate.reasons) console.log(` - ${reason}`);
171
+ } else {
172
+ console.log(`✓ all categories within --max-mean-us ${ARGS.maxMeanUs}μs ceiling`);
173
+ }
174
+ }
175
+ }
176
+
177
+ if (gate.triggered) process.exit(1);