Commit Graph
9 Commits
Author SHA1 Message Date
rUv 30e41c23f3 fix(#2679): sync statusline-generator with committed helper (read+substitute pattern) (#2680)
* fix(#2679): sync statusline-generator with committed .claude/helpers/statusline.cjs

Closes #2679. Replaces the 946-line inline template string in
generateStatuslineScript() with a read-committed-helper-and-substitute
pattern. Single source of truth = the shipped .claude/helpers/statusline.cjs.

## Root cause of the drift

The generator's inline template shipped as the pre-#2195 non-delegation
build. Meanwhile the deployed helper got continuous v3.29.0 improvements
(whole-row-clickable OSC 8, (domain) suffix, ellipsis on truncation,
bright-white bold command styling, 300s cache TTL, windowsHide on every
subprocess spawn). No mechanism kept them in sync — every `ruflo init`
regressed a user's install to the older shape.

## Fix

generateStatuslineScript() now:

1. Walks up from `__dirname_sg` looking for `@claude-flow/cli`'s
   package.json. Reads `.claude/helpers/statusline.cjs` relative to
   that. Falls back to `createRequire.resolve` for the installed-CLI
   case where walk-up misses (shipped tarball extracted outside a
   workspace).
2. Substitutes two known values:
   - `maxAgents: 15,` → `maxAgents: <options.runtime.maxAgents>,`
   - `let ver = "…";` → `let ver = <bakedVersion>;` (with non-downgrade
     guard so test environments that resolve to an older node_modules
     install can't clobber a fresh committed helper)

Function body: ~1050 lines → ~60 lines. Every future edit to the helper
now propagates to init output automatically.

## Also synced (was silently drifted)

`v3/@claude-flow/cli/.claude/helpers/statusline.cjs` was a stale
pre-v3.29.0 copy. Copied the root `.claude/helpers/statusline.cjs`
(the current v3.29.0 shape) over the top. Re-signed helpers manifest.

## Test updates

Three test assertions updated to match the current v3.29.0 helper shape:

1. `statusline-cost-display.test.ts` drift guard — restored to strict
   byte-comparison after normalizing the version line (the ONE
   legitimately environment-dependent line — vitest resolves to a
   different pnpm-installed CLI than production).
2. `funnel.test.ts` "re-sanitizes promo text" — was asserting the old
   `.slice(0, 100)` truncation; now asserts the v3.29.0 MAX_LEN + ellipsis
   path.
3. `funnel.test.ts` "styles the label as a link" — was asserting the old
   `UL_ON + safeTerminalLink(label, promo.url) + UL_OFF` label-only OSC 8
   wrap; now asserts the v3.29.0 whole-row wrap via
   `wrapWholeRowInHyperlink` + the bright-white bold command styling.

## Verified

- Local: 135/135 pass across funnel.test.ts + statusline-cost-display.test.ts.
- TypeScript build clean.
- Direct node call: generator produces exact byte-for-byte match with
  committed helper (modulo the substituted maxAgents + version).

## Follow-ups tracked

None blocking. The `wrapWholeRowInHyperlink` name assertion pins one
implementation detail — worth revisiting if we ever refactor that path.

Related: v3.30.0 release (74bc81f8e / fea1d9e95).

Co-Authored-By: RuFlo <ruv@ruv.net>

* ci: update statusline-delegation guards for #2679 read-and-substitute pattern

Two static-regression CI guards greppedthe GENERATOR source for strings that #2679 moved into the HELPER file (via the read-and-substitute refactor). Both now correctly grep the helper — with a paired invariant that the generator still reads it (so drift on either side is caught).

## Changes

### .github/workflows/v3-ci.yml — statusline generator delegation smoke (#2195)

- \`grep 'hooks statusline --json'\` → grep the HELPER, not the generator
- \`grep 'v3/docs/adr'\` → grep the HELPER
- \`grep 'v3/implementation/adrs'\` → grep the HELPER
- \`grep 'getLearningStats' | 'getV3Progress'\` (negative) → grep the HELPER
- NEW paired assertion: generator must still reference \`statusline.cjs\` AND use \`readFileSync\` for helperContent (so the read-and-substitute pattern itself can't silently regress)

### scripts/audit-fix-invariants.mjs — #2196 + #1951 invariants

- #2196 delegation invariant: moved from generator to helper file
- #2679 NEW invariant: generator must reference \`statusline.cjs\` (proves the sync pattern is intact)
- #1951 marketplaces/ruflo generator invariant: removed (candidate lives in the helper file; already covered by the two helper invariants above)

## Verified

- \`node scripts/audit-fix-invariants.mjs\` → 37/37 invariants present, no missing
- The delegation contract is now enforced by TWO checks: (1) the helper contains it, (2) the generator reads the helper — both must pass, catching drift on either side

Related: #2679 (the refactor these guards now match), v3.30.0 release.

Co-Authored-By: RuFlo <ruv@ruv.net>

* ci: update statusline delegation smoke for #2679 sync pattern

Third and final CI guard to update after #2679's read-and-substitute
refactor. The smoke script's static-source contract greps the generator
for content that now lives in the helper file.

## Change

Split the Layer 1 static-source contract across TWO files:

1. **Generator** must still reference `statusline.cjs` AND use `readFileSync`
   for helperContent — proves the sync mechanism is intact.
2. **Helper** must carry the delegation contract:
   - `hooks statusline --json` present
   - No `getLearningStats` / `getV3Progress` (old local readers)
   - Both `v3/docs/adr` and `v3/implementation/adrs` present for ADR counting

Splitting the invariant across the two files means neither can silently
regress — a future refactor that breaks the generator's read OR strips
the delegation from the helper will fail this smoke.

## Verified

`node scripts/smoke-statusline-generator-delegation.mjs` → 20/20 pass.

Includes all three layers:
- [1/3] Static source contract (updated for #2679)
- [2/3] Generated .cjs syntax check (unchanged — validates node --check on generator output)
- [3/3] Runtime JSON range validation (unchanged — runs the .cjs and checks output fields)

Related: PR #2680, issue #2679.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-07-14 16:11:18 -04:00
rUv d012042800 feat: review-driven upgrades — perf, security, SOTA capabilities (6-agent concurrent implementation) (#2547)
* chore(arch): untrack the prepublish plugin mirror — build artifact, not source

v3/@claude-flow/cli/plugins/ is regenerated by prepublishOnly from
plugins/ruflo-metaharness/ at publish time. Keeping it committed caused
silent drift between publishes (4 files diverged this week alone) and
every source edit required a manual mirror sync. npm pack still bundles
it — the files array + prepublish copy are unaffected by gitignore.

Co-Authored-By: RuFlo <ruv@ruv.net>

* feat(gaia): submission integrity checklist — fail-closed pre-submit audit (Berkeley RDI hardening)

Adds a 4-part integrity section to the gaia-validate pre-submit gate,
motivated by UC Berkeley RDI's 'Agents' Last Exam' (April 2026), which
gamed all 8 major agent benchmarks to near-100% without solving tasks.

- scripts/gaia-integrity.mjs: (A) answer-key-shaped path reads outside
  the sanctioned dataset dir — FAIL-CLOSED exit 2; (B) eval()/new
  Function()/exec-of-non-literal strings in gaia-bench runner code
  paths — FAIL-CLOSED exit 2; (C) judge-prompt-injection markers in
  produced answers/trajectories — WARN; (D) provenance stamp (results
  + git SHA + dataset content hash) written for gaia-submit to embed.
- --allow-integrity-override suppresses the exit code but records
  'overridden: true' in the stamp — never silent.
- --self-test plants a fake answer-key read, an eval-of-task runner,
  and injection markers in temp fixtures and proves fail-closed/pass/warn.
- gaia-validate.md: new check 7 documenting the checklist + flags.
- gaia-submit.md: package now embeds integrity.json under the Ed25519
  witness manifest (tamper-evident attestation); stale/failed stamps block
  packaging.
- smoke-gaia.sh: 3 new steps (script wired, self-test green, repo scan
  clean); plugin bumped to 0.5.0.

Co-Authored-By: RuFlo <ruv@ruv.net>

* perf(cli): lazy ONNX embedder init + local-first ruvector resolution

Fix 1 — lazy ONNX init (measured, biggest win):
neural-tools.ts had a module-level try/catch with TOP-LEVEL AWAIT that ran
`await import('ruvector')` + `initOnnxEmbedder()` + a probe embed at import
time. Because mcp-client statically imports neural-tools, this added the
full ONNX startup to every CLI command. The block is now a memoized
`ensureEmbeddings()` (module-level promise guard) invoked from
generateEmbedding() and from the three handlers that report the provider
without embedding (neural_compress / neural_status / neural_optimize), so
degraded/fallback semantics and provider reporting are byte-identical.
The probe embed moved inside ensureEmbeddings() — it still guards the
ADR-086 type-load-success-but-runtime-fails trap, but only on first use.

Measured (warm, darwin-arm64):
  node bin/cli.js --help   0.50s -> 0.09s
  node bin/cli.js status   0.64s -> 0.24s
  import(mcp-client.js)    438ms -> 30ms
  "Loading ONNX model" no longer appears on non-embedding commands;
  appears exactly once on first embed (neural_predict / memory search).

Fix 2 — ruvector pin + local-first resolution:
browser-session-tools.ts pinned `npx -y ruvector@0.2.25` while 0.2.27 is
what the package installs, forcing cold npx downloads of a second version
(4 per browser session). The pin is now 0.2.27 and a memoized
resolveLocalRuvectorCli() (createRequire + package.json bin walk) spawns
`node <local-cli>` directly, falling back to the npx pin only when no
local install exists.

While verifying the 0.2.27 subcommand surface (required before bumping),
found the trajectory-* flags passed here were never valid on 0.2.25 OR
0.2.27 (`--session-id/--task/--args/--verdict` vs the real
`--context/--agent`, `--action/--result`, `--success/--quality`) — every
trajectory call exited with commander "unknown option", same bug class as
the #2015 `rvf create --kind` fix documented in this file. Flags are now
mapped correctly; browser_session_record and browser_session_end verified
end-to-end (rvf create + trajectory-begin/step/end + rvf compact all pass).

Fix 3 — lazy heavy MCP tool groups: profiled and NOT converted.
Per-module timed dynamic imports of all 36 tool modules show neural-tools
was 469.6ms and every other group is 0.3-5.5ms (hooks-tools 3.5ms,
agentdb-tools 2.5ms, embeddings 0.9ms, wasm-agent 0.6ms). After fix 1 the
whole registry builds in ~30ms; converting handler dispatch to lazy
import() would add risk for <6ms of residual win, so mcp-client.ts is
intentionally untouched.

Validation:
- tsc build clean
- plugins/ruflo-metaharness/scripts/test-mcp-tools.mjs: 171/171 passed
- memory search / neural predict still work; ONNX loads lazily then

Co-Authored-By: RuFlo <ruv@ruv.net>

* security(deps): lift OTel floor-became-ceiling pins — core >=2.8.0, otlp family >=0.220.0

The exact pins @opentelemetry/{core,resources,sdk-trace-base}@1.25.1 and
the otlp exporter/transformer family@0.52.1 (root + ruflo wrapper
overrides) were added in #1997/#2112 as a 'fewer-knobs-for-arborist'
defense against the npm arborist Invalid Version crash (empty-version
placeholder from optionalDependencies/peerDependencies overlap). They
were never API-compat pins — but they became a ceiling that forces the
tree onto @opentelemetry/core <2.8.0, which npm audit flags for
GHSA-8988-4f7v-96qf (unbounded memory allocation in W3C Baggage
parsing), and they blocked every upstream fix.

Convert to floors while keeping the lockstep families coherent:
  - stable line:   core / resources / sdk-trace-base  ->  >=2.8.0
  - otlp line:     sdk-node, exporter-prometheus, the three
    exporter-trace-otlp-* packages, otlp-exporter-base,
    otlp-grpc-exporter-base, otlp-transformer  ->  >=0.220.0
(sdk-node@0.220.0 declares exactly core@2.9.0 + otlp@0.220.0, so the
floors resolve to one mutually consistent set; verified in both the
root lockfile and a fresh ruflo/ resolution: core 2.9.0 everywhere,
otlp 0.220.0 everywhere.)

The arborist defense is preserved — every package in both families is
still forced to a single resolution via overrides; the override set is
now broader (whole otlp family at root too), which gives arborist fewer
ambiguous nodes than before, not more.

Also adds the exporter family overrides to the root manifest so root
and the published ruflo wrapper stay aligned (#2112 lesson: root
overrides do not propagate to the published wrapper).

Validation:
  - root:  npm audit --omit=dev  30 moderate -> 0 vulnerabilities
  - ruflo: npm install --package-lock-only succeeds, 0 vulnerabilities
  - runtime probe: new NodeSDK({}) via @opentelemetry/sdk-node@0.220.0
    with core@2.9.0 loads and exposes start(); OTLPTraceExporter loads

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* security(deps): npm audit fix on v3 workspace lock — grpc-js, hono/node-server, brace-expansion

Plain `npm audit fix --omit=dev --package-lock-only` (no --force) on the
v3 npm workspace lockfile. Clears the three targeted advisories:

  - @grpc/grpc-js        1.14.3 -> 1.14.4   GHSA-5375-pq7m-f5r2 (+GHSA-99f4-grh7-6pcq)
  - @hono/node-server    1.19.9 -> 1.19.14  GHSA-wc8c-qw6v-h7f6 (+GHSA-92pp-h63x-v22m)
  - @isaacs/brace-expansion  5.0.0 removed/deduped  GHSA-7h2j-956f-4vf2

Audit summary: 82 vulnerabilities (2 low, 56 moderate, 24 high)
            -> 55 vulnerabilities (50 moderate, 5 high).
The remainder needs --force / dependency swaps and is out of scope for
this pass.

Note: the reify was run with the two pnpm-style `workspace:*` devDep
specs (plugin-agent-federation, plugin-iot-cognitum) temporarily
substituted with the registry pins the lockfile already records
(@claude-flow/shared@3.0.0-alpha.8, @claude-flow/security@3.0.0-alpha.10),
because npm's arborist does not support the workspace: protocol; the
manifests themselves are unchanged. The v3 workspace is otherwise
pnpm-driven (`pnpm -r build`).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* security(deps): align agentdb floor in @claude-flow/memory — ^3.0.0-alpha.17

Root overrides force agentdb >=3.0.0-alpha.17, but @claude-flow/memory
declared ^3.0.0-alpha.16, so its nested/published tree could still
resolve alpha.16 (the #2112 lesson: overrides do not propagate to
nested or published trees). The v3 pnpm lock indeed had memory pinned
to agentdb 3.0.0-alpha.16 — bumping the package's own floor makes both
branches resolve the same version regardless of the consumer's
override set.

pnpm-lock.yaml is regenerated by `pnpm install`; besides the
agentdb 3.0.0-alpha.16 -> 3.0.0-alpha.17 move under memory, it also
reconciles previously committed manifest bumps (metaharness family)
that had drifted from the stale lock.

Verified: `npm ls agentdb` from root shows a single deduped
agentdb@3.0.0-alpha.17 across direct, @claude-flow/memory,
@claude-flow/neural, and agentic-flow branches.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* security(deps): correct FEDERATION_BIND_HOST doc default — 127.0.0.1 (ADR-166 Phase 3d)

The bin.ts header JSDoc still advertised `default: 0.0.0.0`, but the
code (makeContext) has defaulted to 127.0.0.1 since the ADR-166
Phase 3d loopback-by-default hardening. Doc-only change.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* fix(memory): drop vitest-4 style vi.fn generic that breaks tsc build

The hoisted vitest 1.x types Mock as Mock<Args extends any[], Returns>,
so the single-generic vi.fn<SearchFn> form fails the package build
(pre-existing baseline failure). Annotate the variable instead — the
inferred mock signature is identical.

Co-Authored-By: RuFlo <ruv@ruv.net>

* perf(memory): batch embeddings in the migration import path

MemoryMigrator.processBatch batched entries (batchSize=100) but then
awaited this.embeddingGenerator(content) ONE ENTRY AT A TIME inside the
loop — N sequential ONNX inferences per batch on the
memory_import_claude hot path.

Now:
- New BatchEmbeddingGenerator type ((contents: string[]) =>
  Promise<Float32Array[]>) accepted as an optional 4th constructor /
  factory param — one true batch call per migration batch when the
  embedder supports it (e.g. bge-embedder's single padded forward pass).
- Fallback: bounded concurrency over the single-text generator
  (MigrationConfig.embeddingConcurrency, default 8 — never unbounded;
  set 1 to restore sequential behavior).
- If the batch call fails, falls back to per-entry embedding so one
  backend hiccup doesn't strand the batch.

Per-entry error semantics preserved: validation failures skip, store
failures fail, embedding failures warn and store the entry without a
vector — one bad entry never fails the batch.

Measured (200 synthetic entries, 5ms simulated single-embed latency):
sequential 1220ms -> concurrency-8 156ms (7.8x) -> true batch 115ms
(10.6x).

Co-Authored-By: RuFlo <ruv@ruv.net>

* feat(memory): temporal validity on hierarchical memory (Zep/Graphiti-style)

Facts in hierarchical memory can now carry validity windows and are
INVALIDATED on conflict instead of overwritten:

- New TieredMemoryStore module (@claude-flow/memory) promotes the inline
  controller-registry stub to a first-class, tested store with optional
  validFrom / validUntil (ISO) + supersededBy fields.
- store accepts supersedes=<entryId|key>: the old entry is stamped
  validUntil=now + supersededBy=<newId> and archived — never deleted.
- recall filters temporally-invalid entries (expired, superseded, or
  not-yet-valid) by default; includeExpired=true is the audit escape
  hatch.
- Backward compatible: entries without the fields behave exactly as
  before (always valid); legacy store(key,value,tier) / recall(query,
  topK) call shapes unchanged; same-key stores still overwrite; the
  bridge's real-vs-stub detection signal (getStats+promote) is
  preserved.
- CLI bridge passes the new optional fields through
  bridgeHierarchicalStore/-Recall. On the native agentdb
  HierarchicalMemory backend, validFrom/validUntil ride in metadata and
  are filtered at recall; supersedes is reported as unsupported there
  (no public update API) rather than silently dropped.
- MCP inputSchemas for agentdb_hierarchical-store (validFrom,
  validUntil, supersedes) and agentdb_hierarchical-recall
  (includeExpired) expose the fields to agents, with ISO-8601
  validation.

Tests: supersede flow (including same-key supersede preserving
history), expired + not-yet-valid filtering, includeExpired escape
hatch, legacy entries untouched, unparseable timestamps fail open.

Co-Authored-By: RuFlo <ruv@ruv.net>

* feat(routing): confidence-gated tier escalation — hooks_model-verify ($0 post-generation verifier)

ADR-026/143 classify BEFORE generation only. This adds the 2026-SOTA
post-generation gate: attempt the cheap tier, verify the output with
CHEAP structural signals (no LLM call), escalate only on failure.

- src/ruvector/output-verifier.ts — pure verifier: empty/truncated
  output, refusal patterns, degenerate repetition, unbalanced
  delimiters, and a real syntax parse for code/JSON tasks (TypeScript
  transpileModule diagnostics / JSON.parse, graceful degradation when
  typescript is absent). Returns {confident, reasons[], suggestedTier,
  suggestedModel, escalate}; ladder haiku→sonnet→opus, tier 2→3.
- hooks_model-verify MCP tool (hooks-tools.ts, surgical) — wraps the
  verifier and feeds the verdict into the SAME learning stream as
  hooks_model-outcome (ModelRouter.recordOutcome: success when
  confident, escalated when not) so the Thompson priors learn which
  task shapes the cheap tier fails on. A dedicated tool (not a verify
  mode on hooks_model-outcome) because verify is a mid-loop decision
  point returning a verdict the agent acts on, while outcome is a
  terminal write — the sequence is route → generate → verify →
  (escalate) → outcome.
- __tests__/output-verifier.test.ts — refusal/truncation/parse/
  escalation-ladder coverage + MCP handler tests (18 tests).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* feat(federation): A2A Agent Cards — spec-1.0 discovery adapter over the bespoke federation schema

Implements the Agent2Agent (A2A, Linux Foundation) Agent Card layer as an
ADAPTER over the existing federation registration/discovery shapes. Cards
only — A2A Tasks/messaging are deliberately out of scope this iteration.

Spec: A2A Protocol 1.0.0 (a2a-protocol.org; schema source of truth
specification/a2a.proto in a2aproject/A2A). Required AgentCard fields per
spec 4.4.1: name, description, supportedInterfaces, version, capabilities,
defaultInputModes, defaultOutputModes, skills. Well-known discovery path
per 8.2 + IANA registration: /.well-known/agent-card.json.

- src/a2a/agent-card.ts: toAgentCard() maps FederationManifest -> spec-
  compliant card (agent types -> AgentSkills; federation endpoint -> open-
  form RUFLO-FEDERATION AgentInterface; bespoke identity rides in a spec
  4.6 extension urn:ruflo:federation:manifest:v1 for lossless round-trip);
  validateAgentCard() enforces the 1.0 required-field shape;
  fromAgentCard() maps a remote card into a FederationNode — ALWAYS
  TrustLevel.UNTRUSTED (cards are self-asserted metadata; trust is earned
  via the normal handshake + TrustEvaluator path).
- src/a2a/well-known.ts: minimal node:http endpoint serving GET/HEAD on
  the exact well-known path with spec 8.6 Cache-Control + ETag/304.
  Binds 127.0.0.1 by default and REFUSES non-loopback binds without an
  explicit allowNonLoopback opt-in (ADR-166 posture preserved — no
  loosening of federation bind or auth).
- src/a2a/consume.ts: fetchAgentCard (injectable fetch, timeout, size cap,
  structural validation) + consumeAgentCard registering the peer into
  DiscoveryService so A2A peers appear in federation discovery.
- DiscoveryService: new 'a2a-card' discovery mechanism +
  registerExternalPeer() (refresh-not-replace preserves trust state).
- plugin.ts: opt-in wiring via config.a2aCard/a2aCardPort/a2aCardHost;
  bind failure degrades gracefully; server closed on shutdown.
- 40 new unit tests incl. golden-file card fixture
  (__tests__/fixtures/a2a-agent-card.golden.json), foreign-card mapping,
  round-trip, loopback guard, and a live serve->consume e2e over HTTP.
- plugin.test.ts: fixed pre-existing stale assertion (10 -> 11 CLI
  commands; 'federation trust elevate' was added without updating the
  count) — baseline suite failed before this change.

Build clean; 600/600 tests green.

Co-Authored-By: RuFlo <ruv@ruv.net>

* feat(intelligence): execution-state-tree retrieval prototype (MAGE-style positional recall)

Research basis: MAGE (arXiv 2606.06090) — semantic-similarity retrieval
fragments decision trajectories on long-horizon tasks; retrieving by
POSITION in a hierarchical execution-state tree (root→current path)
preserves coherence.

- src/ruvector/trajectory-tree.ts — TrajectoryTree prototype:
  trajectory-start opens a node under the session root (nesting under
  the deepest open trajectory), steps append children, end closes and
  pops the current position. recallPath({sessionId, depth}) returns
  the exact root→current path + recent siblings — no embedding search.
  Best-effort JSON snapshot at .claude-flow/intelligence/
  trajectory-tree.json, ALONGSIDE existing trajectory storage (no
  migration). Limitations documented in the module header.
- hooks-tools.ts (surgical): non-fatal tree mirrors in
  hooks_intelligence_trajectory-start/step/end (+ optional sessionId
  param on start), and an opt-in strategy:"state-tree" on
  hooks_intelligence_pattern-search (+ sessionId/depth params).
  Default strategy stays "semantic" — zero behavior change unless
  opted in.
- __tests__/trajectory-tree.test.ts — synthetic 3-level trajectory
  path assertions, nesting/pop, sibling window, persistence
  round-trip, and default-strategy-untouched checks (12 tests).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* fix(metaharness): kill third-party @latest, extract shared _invoke.mjs, derive smoke counts

Three of the four converged security/perf/arch review fixes:

1. SECURITY (HIGH) + PERF — _harness.mjs no longer shells to
   `npx -y metaharness@latest` (a compromised upstream publish would have
   executed arbitrary code on user machines, and @latest forced a registry
   check per call). Resolution is now: (a) locally installed metaharness
   satisfying the PINNED range ~0.3.0 (walk-up node_modules), then (b) a
   one-time `npm install --prefix ~/.ruflo/metaharness-cache-0.3.0`, then
   plain `node <abs-path-to-cli>` spawns — zero network per call. Both bins
   (metaharness + harness) are read from the resolved package.json bin map.
   The {stdout, stderr, exitCode, json, degraded, reason, durationMs}
   contract and ADR-150 graceful degradation are preserved; timeouts now
   report 'metaharness-timeout' (matching _darwin/_redblue) instead of being
   conflated with 'metaharness-not-available'.
   Measured: `score.mjs --path .` completes in ~0.35s via the cache.

2. ARCH — new scripts/_invoke.mjs consolidates the copy-pasted plumbing:
   DEGRADED_RX (superset incl. `npm ERR`), classifyDegraded (keeps the
   -timeout vs -not-available distinction), injectJson, parseTrailingJson
   (the LAST-{...}-block variant from _darwin — the old _harness first-block
   parse was a live bug), ensureCachedInstall (generalizes gepa/_redblue,
   cache-dir naming kept compatible so existing caches keep serving),
   importOptionalLibrary, findLocalPackageDir, makeDegradedEmitter.
   _harness/_darwin/_redblue/gepa are now thin adapters with IDENTICAL
   exported signatures; their genuinely-different parts stay (redblue's
   node-direct isMain workaround, darwin's async streaming for evolve,
   harness's dual binaries). test-graceful-degradation.mjs gains
   RUFLO_METAHARNESS_CACHE_BASE / RUFLO_METAHARNESS_SKIP_LOCAL seams so the
   ADR-150 drill still exercises the degraded path on warm-cache machines.

3. ARCH — smoke.sh derives EXPECTED_TOOLS / EXPECTED_SUBS once from
   metaharness-tools.ts / metaharness.ts and replaces the 7 independently
   hardcoded literals (15 at :750/:829/:2046, 13 at :725/:851, 16 footnote,
   15 success-pattern). Cross-surface value preserved: independent surfaces
   (CLAUDE.md catalog, test-mcp-tools' own `tools.length === 15` literal,
   footnote appends, runScript refs) are compared against the derived count,
   never a surface against itself; a >=15/>=13 floor step catches
   extraction-regex rot.

Validation: smoke.sh 122/122, test-graceful-degradation 16/16,
test-mcp-tools 171/171.

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(metaharness): add --diagnose GEPA failure diagnosis to evolve

GEPA's key trick — natural-language failure diagnosis from execution traces
feeding the next mutation, not just scalar fitness — scoped modestly into
the evolve wrapper as an opt-in flag.

`evolve.mjs --diagnose` now appends a `diagnosis` section to the emitted
JSON after the run completes: losing/failed variants' transcripts are run
through darwin's gepa `analyzeTranscript` + `classifyFailure` ops (via the
shared importGepa resolver, moved to _darwin.mjs because gepa.mjs runs
main() on import) and aggregated into failure classes + counts + dominant
class per variant.

Upstream shape findings (verified against @metaharness/darwin@0.8.0 with a
tiny mock-sandbox evolve):
- `metaharness-darwin evolve --json` emits a TEXT leaderboard — stdout
  carries no JSON and no transcripts (r.json has always been null here).
- Per-variant run records live at <repo>/.metaharness/runs/<id>.json as
  sandbox exec traces ({taskId, exitCode, stdout, stderr}) — NOT gepa
  {actionRaw, obs} transcripts.
Diagnosis therefore layers: gepa-shaped transcripts when a run record
embeds them (agent sandbox / future upstream) → champion-transcript
fallback → `diagnosis: {available: false, reason, traceSummary}` with a
mechanical per-variant tally. Never fails the run — internal errors
degrade to {available: false, reason: 'diagnosis-failed: ...'}.

Both paths exercised end-to-end: mock evolve yields the traceSummary
fallback; a seeded gepa-shaped run record yields
{available: true, scope: 'losing-variants', failureClasses:
{exploration-loop: 1, edit-mechanics: 1}, dominantClass: 'exploration-loop'}.

Documented in skills/harness-evolve/SKILL.md.

Co-Authored-By: RuFlo <ruv@ruv.net>

* Revert "feat(gaia): submission integrity checklist — fail-closed pre-submit audit (Berkeley RDI hardening)"

This reverts commit af185fcccd.

* fix(hooks): ADR-112 guidance clause on hooks_model-verify description

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(ci): retune #1921 fix-invariant to the >=2.8.0 OTel override floor

The PR deliberately raised the @opentelemetry/core override from the exact
1.25.1 pin to a >=2.8.0 floor (OTel 2.x audit fix), but the #1921 invariant
in audit-fix-invariants.mjs still asserted the old pin substring, failing
the 'Hook-command install safety (#1921)' job. Per the audit's own guidance,
the invariant is updated to point at the new location of the fix — the
override entry itself — preserving the regression guard (arborist Invalid
Version placeholder) rather than deleting it.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* fix(ci): register RUFLO_METAHARNESS_CACHE_BASE as env-var escape hatch

The metaharness _invoke.mjs consolidation introduced cacheBaseDir(), whose
RUFLO_METAHARNESS_CACHE_BASE read is a CI/test seam for relocating the
~/.ruflo pinned-cache root in smoke tests — there is no CLI-flag surface in
plugin scripts to take precedence. Register it in KNOWN_ESCAPE_HATCHES per
ADR-125/ADR-130 remediation Option B, unblocking the 'Plugin package
install-safety (#1902/#1903/#1904)' job.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* fix(ci): linear-time dash trim in A2A slugify — resolves js/polynomial-redos

CodeQL flagged /^-+|-+$/g in slugify() (agent-card.ts:281) as polynomial
ReDoS: the anchored quantifier backtracks O(n^2) on adversarial all-dash
card names, and card names are remote library input. Replace the trim regex
with an index-scan (charCodeAt) that is strictly linear. Behavior verified
equivalent against the old implementation over edge cases plus 5000-input
fuzz; package typechecks and all 600 tests pass.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* fix(ci): no-metaharness drill uses the _invoke.mjs test seams

The pinned-cache resolution defeats the drill's registry-blackhole absence
simulation (metaharness resolves locally / from the warm ~/.ruflo cache).
RUFLO_METAHARNESS_SKIP_LOCAL=1 + an empty RUFLO_METAHARNESS_CACHE_BASE make
'absent' mean absent again. Reproduced locally: exit 0 + degraded:true.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-07-03 16:52:09 -04:00
ruv f08318f2c7 fix(ci): green up the 3 audit jobs newly visible after the YAML fix
With #2267's YAML break gone and the pnpm-lock refreshed, the 25 newly-
visible failures collapsed to 3 genuinely-independent audit failures.
Fixing all three.

#2046 — Supply-chain audit (1 unaccepted critical CVE)
  Vitest <4.1.0 UI server arbitrary-file-read/exec (GHSA-5xrq-8626-4rwp,
  CVSS 9.8) was unaccepted in v3/@claude-flow/browser.
  • Bumped `vitest` spec from ^4.0.16 → ^4.1.0 in browser package.json.
  • Refreshed the workspace pnpm-lock.
  • Standalone-publish package-lock.json carries workspace:* refs that
    `npm install` can't resolve in isolation, so I added a time-boxed
    (expires 2026-09-02) accepted-findings entry citing the limited
    exposure (devDependency + UI-server-only attack vector) and pinning
    the next workspace-coordinated lockfile rebuild as the trigger to
    remove it. Tracking: ruflo#2270.

ADR-112 — Tool description discoverability (2 missing "Use when …")
  • hooks_task-completed: added "Use when native TaskUpdate is wrong
    because the runtime also needs to record the outcome as a learning
    signal and emit the standard pipeline event".
  • hooks_intelligence_unified-stats: added "Use when calling the four
    narrow aggregators one at a time is wrong because cross-store drift
    goes silent — this tool surfaces it in the `consistency` block".
  327/327 tools now pass; baseline stays at 0.

#1921 — Hook-command install safety (4 missing invariants)
  Both #1951 and #1989 fixes were silently retired by #2196's statusline
  delegation refactor. Updated scripts/audit-fix-invariants.mjs to track
  the new reality without dropping coverage:
  • #1951 (marketplaces/ruflo) — substring became `path.join(home,
    '.claude', 'plugins', 'marketplaces', 'ruflo', …)` which the literal
    substring check couldn't see. Switched to a regex form that matches
    the path.join breakup.
  • #1989 (SQLite magic-bytes + page-count clamp) — superseded entirely
    by #2196's delegation pattern: statusline-generator no longer reads
    raw memory.db bytes; it shells out to `hooks-statusline --json`
    which queries AgentDB via the typed SDK. The regression vector is
    closed by ARCHITECTURE. Replaced the two #1989 invariants with one
    #2196 invariant that locks in the delegation pattern, so a future
    refactor that reintroduces raw-bytes reading is caught BEFORE the
    SQLite magic check would be relevant. Audit-script convention says
    "do NOT delete without confirming the regression is impossible by
    another mechanism" — this is the documented confirmation.
  37 invariants, all present.

Local: all 3 audits + the 2 new regression smokes pass.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-06-02 04:26:05 -04:00
rUvandReuven 455f0b17be fix(plugin-agent-federation): #1949 — agentic-flow → optional peer dep (drops cookies@0.9.1 blocker) (#2013)
Hardened npm registries reject `@claude-flow/plugin-agent-federation@alpha`
with `403 Forbidden` on `cookies@0.9.1` because of a deep transitive
chain (agentic-flow → fastmcp → mcp-proxy → pipenet → koa → cookies).
The plugin only uses agentic-flow for one function (`loadQuicTransport`
as fallback), so it doesn't need to be a hard runtime dep.

**package.json**
- Moved `agentic-flow` from `dependencies` → `peerDependencies` with
  `peerDependenciesMeta.agentic-flow.optional = true`
- Added `midstreamer` as a second optional peer (so an operator can
  pick either or both backends — per ADR-120's Step 2 loader)
- Kept `agentic-flow` in `devDependencies` so vitest + tsc still
  resolve it in this workspace
- Bumped version 1.0.0-alpha.15 → 1.0.0-alpha.16

**midstream-aware-loader.ts**
- Replaced the static value import of `loadQuicTransport` with a
  lazy `loadAgenticFlowQuicTransport()` that uses direct dynamic
  `import()` (vitest-mockable) and falls back to `null` when the
  package isn't installed
- Type imports remain static — they're erased at compile time, so
  TypeScript users still get full IntelliSense without forcing the
  install
- `loadFederationTransport()` now throws a clear, actionable error
  when neither midstreamer nor agentic-flow is present, instead of
  silently crashing on a missing module

**Impact**
- Install size: 529 packages → 2 packages (verified via `npm pack` +
  fresh install in an empty workspace)
- No more `cookies@0.9.1`, no more `koa-router@14.0.0` deprecation
  warning, no more 403 in hardened registries
- 555/555 vitest tests pass (up from 549 — 6 loader tests now
  exercise the new lazy-import path)

**audit-fix-invariants.mjs**
- Added 4 new invariants checking the peer-dep wiring stays in
  place (package.json `peerDependencies` + `peerDependenciesMeta`,
  and the loader's type-only import + lazy loader symbol)
- 38/38 invariants pass

Closes #1949.

Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
2026-05-15 07:47:29 -04:00
rUvandReuven e0a922eef9 feat(federation-peer): wire real midstreamer-quic@0.3.0 + aimds-core@0.2.0 (ADR-120 Step 3) (#2011)
Replaces the typed `not implemented` placeholders in
`native_transport` and `native_gate` with real implementations that
delegate to the embedding traits published in ruvnet/midstream PR #82.

**Cargo.toml**
- Bumped `midstreamer-quic` 0.2.1 → 0.3.0 (now exposes `QuicTransport`)
- Bumped `aimds-core` 0.1.1 → 0.2.0 (now exposes `SafetyGate` + `SafetyVerdict`)
- Dropped optional `aimds-detection` / `-analysis` / `-response` —
  the peer composes any `aimds_core::SafetyGate` so the concrete
  3-gate pipeline is supplied by the caller (e.g. AIMDS's
  `ComposedGate` or a custom composition)
- Added optional `uuid` + `chrono` (used by the gate adapter to
  build `PromptInput` values)

**lib.rs — `native_transport::MidstreamerTransport<T: QuicTransport>`**
- Generic over any embedder-supplied transport (defaults to `QuicConnection`)
- `connect(addr)`: opens a client connection via `QuicConnection::connect`
- `send(addr, msg)`: opens a bidirectional stream, writes one NDJSON
  line per `FederationMessage`, finishes the stream
- `recv()`: accepts an inbound bidirectional stream, reads to EOF
  (16 MiB cap), parses one JSON value
- `close()`: closes the connection with reason "peer shutdown"

**lib.rs — `native_gate::AimdsGate`**
- Adapter that holds `Arc<dyn aimds_core::SafetyGate>` so it composes
  any 3-gate pipeline (AIMDS's canonical `ComposedGate`, a custom
  composition, or a test stub)
- Converts `FederationMessage` ↔ `PromptInput` (payload-as-string +
  metadata-as-context)
- Converts `aimds_core::SafetyVerdict` ↔ peer-local `SafetyVerdict`,
  preserving routing metadata on `Redact`

**bin.rs**
- Under `--features native`, boots a real tokio runtime that wires
  `MidstreamerTransport::connect()` + `AimdsGate` (with a
  pass-through default gate so the smoke boot path works without
  AIMDS rules) + an NDJSON-stdout dispatcher
- Reads `RUFLO_FEDERATION_REMOTE_ADDR` for the connect target

**Tests**
- New `aimds_gate_adapter_forwards_pass_and_block_verdicts` test
  exercises the real `aimds_core::SafetyGate` trait surface
- 4/4 tests pass under `--features native`; 3/3 pass without

**audit-fix-invariants.mjs**
- Bumped Cargo.toml pin invariants to 0.3.0 / 0.2.0
- Added two new invariants checking the lib.rs imports actually
  reference upstream `QuicTransport` and `aimds_core::SafetyGate` —
  guards against silent reversion to a typed placeholder
- 34/34 invariants pass

Closes ADR-120 Step 3.

Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
2026-05-14 23:35:32 -04:00
rUvandReuven b50d4dd7a2 feat(federation): ADR-120 Step 3 — Rust peer crate + Step 2 path update (#2009)
Lands the remaining ADR-120 work in ruflo now that upstream
ruvnet/midstream#81 shipped midstreamer@0.3.1 with real QUIC.

## Step 3 — `v3/crates/ruflo-federation-peer/`

New Rust crate that composes the QUIC transport (midstreamer-quic
or any TransportProvider impl) with the AIMDS 3-gate safety
pipeline (any SafetyGate impl) into a single Peer<T, G, D> dispatch
loop. Replaces today's Node-bridge → Node-MCP → Rust-crate path
with one process per federation peer.

Surface:
  * `TransportProvider`, `SafetyGate`, `Dispatcher` traits — async,
    Send + Sync, so the Peer can run in any tokio executor.
  * `Peer::run()` — inbound dispatch loop. `Pass` → dispatch;
    `Block` → quarantine (never reaches dispatch); `Redact` →
    dispatch the cleaned variant.
  * `Peer::send()` — outbound through the gate first; Block error
    bubbles back to the caller.
  * `--features native` — pulls in midstreamer-quic@0.2.1 +
    aimds-{core,detection,analysis,response}@0.1.1 from crates.io.
    Without it, the binary builds and the trait surface compiles
    so CI / `cargo check` work in any tree.

Verified:
  * `cargo build` and `cargo test` — 3/3 unit tests pass
    (dispatch loop with PassThroughGate, BlockEverythingGate, and
    outbound-send-blocks-when-gate-blocks).
  * `cargo check --features native` — resolves the upstream deps
    cleanly.

## Step 2 update — `midstream-aware-loader.ts`

Probes `midstreamer/quic` (the new sub-path added in
midstreamer@0.3.1) first, falls back to the root `midstreamer`
import for older versions. Accepts both ESM and CommonJS shapes
(via `.default`) since the upstream sub-path is CJS.

## CI guards

  * New workflow `.github/workflows/federation-peer-rust.yml`:
    two jobs — `stable-noop` (cargo build + cargo test without
    features) and `stable-native` (cargo check --features native).
    Triggers on changes to the crate or this workflow.
  * `scripts/audit-fix-invariants.mjs` gains 4 invariants pinning
    the crate name + the midstreamer-quic version + the two
    pluggable trait names. 31 invariants now present across 18
    files (was 27/16).

## Verification matrix

  * `node scripts/audit-fix-invariants.mjs` → 31/31 ✓
  * `npx vitest run` in plugin-agent-federation → 22 files, 555/555 ✓
  * `cargo test` in v3/crates/ruflo-federation-peer → 3/3 ✓

Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
2026-05-14 23:01:05 -04:00
rUvandReuven 8f5934dea5 feat(federation): ADR-120 Step 2 — midstream-aware transport loader (#2007)
Lands the ruflo-side of ADR-120 (cross-port agentic-flow QUIC into
midstream + Rust inflight agentics) Step 2: extend the federation
plugin's transport loading to prefer midstream's real QUIC build
when MIDSTREAMER_QUIC_NATIVE=1, with a transparent fallthrough to
the existing agentic-flow loader (which itself handles ADR-108
native QUIC and ADR-104 WebSocket fallback).

Surface:

  • New `src/transport/midstream-aware-loader.ts` —
    `loadFederationTransport(config)` probes midstreamer first,
    refuses the WASM stub via `isStub()` if reported (ADR-119),
    returns a `LoadedFederationTransport` envelope with `source`
    + optional `fallbackReason` for log/metric visibility.

  • `src/plugin.ts` now imports from the wrapper instead of
    `agentic-flow/transport/loader` directly. Logs the resolved
    source on successful load.

  • 5 unit tests covering both branches (env unset / "0" / "1"
    without package), config passthrough, envelope shape.

Behavior unchanged today: midstream's WASM build is a counter-
tracking stub per ADR-119, so `MIDSTREAMER_QUIC_NATIVE=1` falls
through to agentic-flow's loader on every install. The wrapper
activates the moment `midstreamer@0.3.0` ships real QUIC (ADR-120
Step 1, upstream work in ruvnet/midstream).

Test results in the worktree:
  • Full plugin suite: 22 files, 555/555 tests passing
  • audit-fix-invariants.mjs: 27 invariants across 16 files,
    all present (was 25/14)

Two new invariants added to the audit guard so a refactor can't
silently revert to the bare `loadQuicTransport` import and bypass
the midstream preference.

Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
2026-05-14 22:28:20 -04:00
rUvandReuven 91657b9fce chore(release): 3.7.0-alpha.36 — 10 fixes + audit guard update (#2001)
Cuts the alpha.36 release covering today's 10 PRs (#1992-#2000):

  #1989 statusline RFE1 cascade        (#1992)
  #1987 memory stats HNSW persistent    (#1993)
  #1973 Windows install README          (#1994)
  #1948 platform-aware statusLine cmd   (#1995)
  #1937 memory_import_claude excl.      (#1996)
  #1921 @opentelemetry/core override    (#1997)
  #1910 MCP stdio stdout protection     (#1998)
  #1880 verify.mjs actionable error     (#1999)
  #1872 SwarmCoordinator (2 of 5)       (#2000)
  #1990 runtime-smoke gate count

Plus 9 new invariants added to `scripts/audit-fix-invariants.mjs`
covering the source-side fixes (statusline magic-bytes, page-count
clamp, memory-stats persistent count, platform-aware statusLine,
exclusion-patterns flag, otel pin, MCP stdio mode + uncaught
handler, scaleAgents target semantics, executeTask try/catch).

Result: `node scripts/audit-fix-invariants.mjs`
  → 25 invariants across 14 file(s), all present.

Bumps all 3 packages (@claude-flow/cli, claude-flow umbrella,
ruflo umbrella) to 3.7.0-alpha.36.

Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
2026-05-14 21:38:14 -04:00
rUvandReuven 131ac346a0 ci(guards): add fix-invariants audit covering 8 recent fixes (#1972)
Companion to scripts/audit-vector-dim.mjs (#1947) and
scripts/audit-hook-handler-prompt.mjs (#1944) — those each guard one
fix's specific regression pattern. This one is a single "presence-check"
audit covering the load-bearing line(s) from 8 more fixes that shipped
without a dedicated test:

  #1939  Win32 cwd → Claude Code slug normalization
         (memory-tools.ts — Win32 candidate regex + replace pattern)

  #1941  Per-namespace vector_indexes provisioning
         (memory-bridge.ts + memory-initializer.ts — INSERT OR IGNORE)

  #1943  Helper path project-local OR $HOME probe
         (settings-generator.ts — sh `[ -f "$D/` + cmd /c IF EXIST)

  #1945  Bridge respects CLAUDE_FLOW_MEMORY_PATH
         (memory-bridge.ts — getDbPath uses getMemoryRoot)

  #1946  Doctor respects CLAUDE_FLOW_MEMORY_PATH
         (doctor.ts — checkMemoryDatabase uses getMemoryRoot)

  #1951  Statusline reads installed version from plugin package.json
         (3 files — RUFLO_VERSION probe + marketplaces/ruflo candidate)

  #1953  hooks_pretrain code-file budget + code-dir-first traversal
         (hooks-tools.ts — codeFilesScanned counter)

  #1968  daemon forwards --workers / --headless / --sandbox
         (daemon.ts — forkArgs.push for each flag)

15 invariants total. Each entry pins one substring or regex that MUST
appear in a specific file, with a `why` field explaining what runtime
behavior breaks if the line is removed. The failure output includes
that `why` so the next developer who hits the audit knows whether to
update the invariant (fix moved/refactored) or restore the line.

Verified locally:
- `node scripts/audit-fix-invariants.mjs` → clean (`exit 0`)
- Inject a regression (strip the sh probe + the getMemoryRoot call) →
  exits 1 with a per-issue diagnostic.

Wired into the existing `hook-command-audit` CI job alongside the
hook-handler-prompt audit. Combined with the other two scripts, the
recent triage cycle's 14 fixes now have:

  audit-vector-dim          → #1947 (+ siblings #1942 / #1952)
  audit-hook-handler-prompt → #1944
  audit-fix-invariants      → #1939 / #1941 / #1943 / #1945 / #1946 /
                              #1951 / #1953 / #1968

The two remaining (#1947 RC2 embeddings-index optional `-c`, #1930
cost-tracker compact resolution) are runtime-behavior surface changes
without a single load-bearing line to guard; both are exercised by
their own smokes / manual repros.

Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
2026-05-13 22:39:23 -04:00