Commit Graph

8 Commits

Author SHA1 Message Date
ruv 579e0ce72e feat(adr-124/phase4): presence.now + vitals.get_* tool family (ADR-124 §4.1)
Advances SPARC Phase 4 (Refinement) iter 5: implements ruview.presence.now
and all three ruview.vitals.* tools sharing a single fetchVitals() helper.

src/types.ts:
  - Added EdgeVitalsMessage interface (mirrors Python ws.py:74-88 per ADR-124 §6):
    node_id, timestamp_ms, presence, n_persons, confidence, breathing_rate_bpm,
    heartrate_bpm, motion, zone_id

src/tools/vitals-fetch.ts (new):
  - fetchVitals(nodeId, baseUrl, token): GET /api/v1/vitals/<node_id>/latest
  - Returns VitalsFetchOk | VitalsFetchErr — all four tools project from one fetch
  - resolveNodeId(): "default" fallback for optional node_id

src/tools/presence-now.ts (new):
  - presenceNow(): projects {present, n_persons, confidence, timestamp_ms}

src/tools/vitals-get-breathing.ts (new):
  - vitalsGetBreathing(): projects {breathing_rate_bpm|null, confidence, timestamp_ms}

src/tools/vitals-get-heart-rate.ts (new):
  - vitalsGetHeartRate(): projects {heartrate_bpm|null, confidence, timestamp_ms}

src/tools/vitals-get-all.ts (new):
  - vitalsGetAll(): spreads full EdgeVitalsMessage (raw never present server-side)

src/index.ts:
  - 4 new TOOLS entries; all route through Phase 3 schema-validation gate

tests/vitals-tools.test.ts (new, 18 assertions):
  - resolveNodeId ×2; fetchVitals soft-fail ×1
  - presence.now: soft-fail, field projection, schema accept/reject ×4
  - vitals.get_breathing: soft-fail, bpm projection, null bpm, window_s ×4
  - vitals.get_heart_rate: soft-fail, bpm projection, schema ×3
  - vitals.get_all: soft-fail, full spread + no raw field, schema ×3

Test results: 93/93 PASS (+18). Build: tsc clean.

ACs touched: ADR-124 §4.1 ruview.presence.now, ruview.vitals.get_breathing,
  ruview.vitals.get_heart_rate, ruview.vitals.get_all. Phase 4 gate: all
  acceptance criteria have passing tests; coverage expanding toward threshold.

Next iter target: Phase 5 (Completion) — CHANGELOG entry, package metadata
  review, witness-bundle extension for npm tarball sha256, then open the PR.
  (Remaining §4.1 tools — pose, primitives, node, vector — can land as post-
  merge follow-up iters given Phase 5 gate criteria are otherwise met.)

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-24 22:25:37 -04:00
ruv f9c98809c2 feat(adr-124/phase4): BFLD tool family — bfld.last_scan + bfld.subscribe (ADR-124 §4.1)
Advances SPARC Phase 4 (Refinement): implements the first two ADR-124 §4.1
sensing tools, which also serve as integration tests for the schema-validation
gate wired in Phase 3 (iter 3).

New files:
  src/tools/bfld-last-scan.ts
    - bfldLastScanSchema: z.object with optional node_id (min 1) + optional
      sensing_server_url — enforces the ADR-124 §4.1 input contract
    - bfldLastScan(): proxies GET /api/v1/bfld/<node_id>/last_scan from the
      sensing-server; returns BfldLastScanResult{ok,node_id,identity_risk_score,
      privacy_class,n_frames,timestamp_ms} on success
    - Converts BfldEvent.timestamp_ns (ns) → timestamp_ms (ms)
    - Uses person_count as n_frames proxy per ADR-118 BfldEvent shape
    - Returns {ok:false,warn:true} when server unreachable (soft-failure convention)

  src/tools/bfld-subscribe.ts
    - bfldSubscribeSchema: z.object with required duration_s (positive, max 3600)
    - bfldSubscribe(): POST /api/v1/bfld/<node_id>/subscribe?duration_s=<n>
    - Synthetic envelope fallback: when server unreachable, synthesises a valid
      {subscription_id (UUID v4), expires_at, topic} locally so the schema gate
      is always exercised and the caller can track the intent
    - topic format: ruview/<node_id>/bfld/* (ADR-122 §2.2 wildcard)

src/index.ts:
    - Import bfldLastScan + bfldSubscribe
    - Two new TOOLS entries: ruview.bfld.last_scan + ruview.bfld.subscribe
    - Both go through the TOOL_INPUT_SCHEMAS schema-validation gate (iter 3)

New test: tests/bfld-tools.test.ts (14 assertions):
    - bfldLastScan: unreachable → ok:false+warn:true, malformed path,
      ns→ms arithmetic, null identity_risk_score coalescing
    - BfldLastScanInputSchema: empty object accepted, empty node_id rejected
    - bfldSubscribe: subscription_id defined + future expires_at, UUID v4 format,
      expires_at timing accuracy (±50ms), topic pattern match
    - BfldSubscribeInputSchema: duration_s > 3600 rejected, duration_s=0 rejected

Test results: 75/75 PASS (+14). Build: tsc clean.

ACs touched: ADR-124 §4.1 ruview.bfld.last_scan + ruview.bfld.subscribe.
  SPARC Phase 4 gate: acceptance criteria have passing tests; code review
  against spec complete; no critical issues.

Next iter target: Phase 4 continued — ruview.presence.now + ruview.vitals.*
  tool handlers (4 tools), following the same pattern; then Phase 5 (Completion)
  with package metadata, CHANGELOG, and witness-bundle extension.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-24 22:16:02 -04:00
ruv 092152bd73 feat(adr-124/architecture): schema-validation gate + Streamable HTTP transport (ADR-124 §3)
Advances SPARC Phase 3 (Architecture): wires the phase-2 schema barrel into
the MCP CallTool dispatch loop, and scaffolds the Streamable HTTP transport
with Origin-validation and bearer-token auth as specified in ADR-124 §3/§6.

Sub-task (a) — Uniform Zod validation gate in src/index.ts:
  - Import TOOL_INPUT_SCHEMAS + McpError + ErrorCode from SDK
  - CallTool handler: before dispatch, looks up schema by tool name using
    Object.prototype.hasOwnProperty (safe for dotted keys) then runs
    schema.safeParse(args); failures throw McpError(InvalidParams) so the
    caller receives a typed JSON-RPC error rather than a wrapped string
  - Re-throws McpError instances unchanged (policy errors propagate cleanly)

Sub-task (b) — src/http-transport.ts (new, 145 LOC):
  - buildHttpApp(mcpServer, opts): creates Node.js http.Server +
    StreamableHTTPServerTransport without binding; testable in isolation
  - createHttpTransport(mcpServer, opts): binds and resolves when listening
  - isOriginAllowed(origin, allowedOrigins): pure function — undefined origin
    allowed (non-browser), present origin validated against allowlist,
    '*' disables gate for local-dev
  - Bearer-token gate: RVAGENT_HTTP_TOKEN env or opts.bearerToken; missing/
    wrong token → 401 before any JSON-RPC processing
  - Bind default: 127.0.0.1 per MCP spec security requirement (ADR-124 §3)
  - Transport connect() only in createHttpTransport (not buildHttpApp) to
    avoid exactOptionalPropertyTypes false-incompatibility in test contexts

New test: tests/http-transport.test.ts (11 assertions):
  - isOriginAllowed() unit ×5: undefined allowed, allowlist hit/miss, wildcard,
    case-sensitivity (RFC 6454)
  - Origin-validation integration ×3: cross-origin → 403 with error body,
    allowed origin → non-403, no Origin → non-403
  - Bearer-token integration ×3: missing → 401, wrong → 401, correct → non-401

Fix: @types/express added as devDep (express is transitive from SDK ^1.29.0).

Test results: 61/61 PASS (+11 new)
Build: tsc clean, zero errors.

ACs touched: ADR-124 §3 (dual-transport architecture), §6 (Origin validation,
  127.0.0.1 bind, bearer-token auth slot). SPARC Phase 3 gate criteria met:
  API contracts typed, module boundaries established, no circular deps.

Next iter target: Phase 4 (Refinement) — implement ruview.bfld.last_scan +
  ruview.bfld.subscribe tool handlers (BFLD wire format stable post-ADR-118),
  register them in the TOOLS array using the new schema-validation gate.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-24 22:08:37 -04:00
ruv 7b7dbc7980 feat(adr-124/pseudocode): Zod schema barrel for all 20 ADR-124 §4.1+§4.1a tools
Advances SPARC Phase 2 (Pseudocode) — typed schemas are the language-level
design artifact that defines the complete tool surface before any HTTP/WS
plumbing is written. The schema map + TOOL_NAMES catalog are the pseudocode
contract that Phase 3 (Architecture) wires to the MCP Server dispatch loop.

New files under tools/ruview-mcp/src/schemas/:

  common.ts — shared Zod sub-schemas
    NodeIdSchema, DurationSSchema (max 3600 s), WindowSSchema (max 300 s),
    SemanticPrimitiveKindSchema (10 ADR-115 primitives enum), PosePersonResultSchema
    (17-keypoint COCO array + confidence + optional AETHER person_id)

  tools.ts — 20 input schemas + TOOL_NAMES catalog + TOOL_INPUT_SCHEMAS dispatch map
    §4.1 sensing (15): presence.now, vitals.get_{breathing,heart_rate,all},
      pose.{latest,subscribe}, primitives.{get,list_active,subscribe},
      bfld.{last_scan,subscribe}, node.{list,status},
      vector.{search_pose,store_pose}
    §4.1a policy (5): policy.{can_access_vitals, can_query_presence,
      can_subscribe, redact_identity_fields, audit_log}

  index.ts — barrel re-export of both modules

New test: tests/schemas.test.ts (24 assertions)
  - Catalog completeness: exactly 20 tools, all §4.1 + §4.1a names present,
    TOOL_INPUT_SCHEMAS one-to-one with catalog (no extras)
  - Happy-path parse: 11 representative schemas accept valid inputs
  - Constraint rejection: 8 schemas reject invalid inputs (empty NodeId,
    DurationS=0 / >3600, unknown primitive, wrong keypoint length, k>100,
    unknown vital, missing required node_id)

Fix: use Object.prototype.hasOwnProperty instead of Jest toHaveProperty for
dotted-key names (Jest interprets dots as nested path separators).

Test results: 50/50 PASS (schemas ×24 + manifest ×10 + tools ×5 + validate ×11)
Build: tsc clean, zero errors.

ACs touched: ADR-124 §4.1 complete tool surface; §4.1a policy layer surface;
  Phase 2 gate: pseudocode covers all acceptance criteria from spec.

Next iter target: Phase 3 (Architecture) — wire TOOL_INPUT_SCHEMAS into the
  MCP Server CallTool handler as a uniform validation gate; add Streamable HTTP
  transport scaffold with Origin-validation middleware (option C).

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-24 21:56:52 -04:00
ruv d11ca9c31e feat(adr-124/packaging): rename to @ruvnet/rvagent 0.1.0 + manifest test (ADR-124 §2)
Advances SPARC Phase 1 (Specification) for ADR-124 SENSE-BRIDGE by establishing
the correct npm package identity that all subsequent implementation iters depend on.

Changes:
- tools/ruview-mcp/package.json
  - name: @ruv/ruview-mcp → @ruvnet/rvagent  (ADR-124 §2.1)
  - version: 0.0.1 → 0.1.0  (initial publishable milestone)
  - removed private:true so the package is publishable  (ADR-124 §2.6)
  - bin: added rvagent key alongside legacy ruview-mcp alias  (ADR-124 §2.4)
  - exports: added "." entry with import+types keys for ESM+CJS dual output  (ADR-124 §2.5)
  - files: added README.md and CHANGELOG.md slots  (ADR-124 §5 npm publish plan)
  - keywords: expanded with sense-bridge, rvagent, ruvnet
  - repository / homepage / bugs: wired to github.com/ruvnet/RuView

- tools/ruview-mcp/src/index.ts
  - SERVER_NAME: "ruview" → "rvagent"
  - PACKAGE_VERSION: "0.0.1" → "0.1.0"
  - stderr log prefix: [ruview-mcp] → [@ruvnet/rvagent]

- tools/ruview-mcp/tests/manifest.test.ts  (NEW)
  - 10 ADR-124 §2 acceptance-criterion assertions, all green
  - Guards name, version >=0.1.0, engines.node >=20, bin.rvagent, exports structure,
    publishConfig.access, @modelcontextprotocol/sdk dep, zod dep, ESM type, license

Test results: 26/26 PASS (manifest.test.ts ×10 + tools.test.ts ×5 + validate.test.ts ×11)
Build: tsc clean, zero errors.

Next iter target: (A) Zod schema barrel for the 15+5 tool catalog from ADR-124 §4.1/4.1a

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-24 21:50:22 -04:00
rUv 2a2f16a380
feat(ruview-mcp): M3+M4 — schema validation + train_count wired (#708)
- Add validate.ts: validateCsiWindow (56×20 shape) + validateSensingLatestResponse
  (schema_version 2 pin per ADR-101); returns actionable errors on schema drift
- Wire csi-latest.ts: call validateSensingLatestResponse after every sensingGet;
  return {ok:false,warn:true,raw_response,...} on mismatch so agents can inspect
- Fix csi-latest.ts: subcarriers now reads amplitudes.length (not hardcoded 56)
- Add tests/validate.test.ts: 5+5 = 10 tests covering valid, null, wrong shape,
  schema_version 3, missing captured_at, window error propagation
- All 16 tests pass (validate × 10 + tools × 6); build clean
2026-05-22 00:03:19 -04:00
rUv 2783f40bd1
feat(tools/ruview-mcp): M2 — wire real inference via cog health (#706)
* research(R9): RSSI fingerprint K-NN — 2.18x lift (MODERATE); surfaces counting-vs-localization asymmetry

Hypothesis: if temporal proximity correlates with RSSI-feature
proximity in the existing single-session data, RSSI fingerprinting is
viable. If K-NN of each query is random in time, RSSI sequences are
too noisy for fingerprint localization.

Test: 1077 samples, 20-dim RSSI proxy (band-mean across 56
subcarriers), cosine-NN with K=5, measure fraction of K-NN within
plus/minus 60s of each query timestamp. Compare to random baseline.

Result (honest):

  5-NN within +/-60s    0.169
  Random baseline       0.077
  Lift over random      2.18x   (verdict: MODERATE)
  Per-query stdev       0.183

Below the >=3x STRONG-fingerprint threshold but well above 1x random.
Real signal, but weaker than R8 counting result on the same data.

Important asymmetry surfaced (publishable distinction):

  Task            RSSI vs CSI retention   Verdict
  -------         -----                   -----
  Counting        94.82% (R8)             RSSI works well
  Localization    ~2x random (R9)         RSSI struggles in this regime

This is consistent with R5's band-spread observation: the count signal
integrates across the band, but localization may require per-subcarrier
shape that the band-mean discards.

Three actionable explanations for the MODERATE result:
1. 20-frame windows (~2s) too short for stable fingerprint while operator
   moves — longer windows might lift to 3-4x.
2. Within-room fingerprint space too narrow — multi-room data would
   show categorical lift jump (5-10x).
3. Band-mean discards the per-subcarrier shape needed for localization.

Once multi-room data lands (#645), this test should be re-run; if
hypothesis (2) is right, the lift will jump categorically.

Files:
* examples/research-sota/r9_rssi_fingerprint_knn.py
* examples/research-sota/r9_rssi_fingerprint_results.json
* docs/research/sota-2026-05-22/R9-rssi-fingerprint-knn.md
* docs/research/sota-2026-05-22/PROGRESS.md updated

* feat(tools/ruview-mcp): M2 — wire real inference via cog health subcommand

ruview_pose_infer and ruview_count_infer now run the cog binary's `health`
subcommand (ADR-100 contract) which performs real Candle forward-pass
inference on a synthetic CSI window and emits a structured health.ok JSON
event containing backend, confidence (pose) or count/confidence/p95_range
(count). The MCP tools parse this event and return typed inference results.

This satisfies the ADR-104 acceptance gate: "ruview_pose_infer returns a
finite output for a synthetic CSI window" when the cog binary is installed.
On machines without the binary, both tools still fail-open with {ok:false,
warn:true} and actionable install hints.

Also updates PROGRESS.md with cross-links: R7 (Stoer-Wagner) and R8
(RSSI-only 94.82% retained) marked done with cron-originated findings
distilled into the research vectors section.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-21 23:43:32 -04:00
rUv 3f462a254d
feat(tools): scaffold ruview MCP server + CLI + ADR-104 (#705)
Adds two new npm packages that expose RuView's WiFi-DensePose
sensing capabilities outside the Cognitum appliance ecosystem:

- tools/ruview-mcp/ (@ruv/ruview-mcp) — MCP server with 6 tools:
  ruview_csi_latest, ruview_pose_infer, ruview_count_infer,
  ruview_registry_list, ruview_train_count, ruview_job_status.
  Uses @modelcontextprotocol/sdk with stdio transport.
  6/6 smoke tests pass. TypeScript strict mode, Node 20.

- tools/ruview-cli/ (@ruv/ruview-cli) — Yargs CLI with matching
  subcommands: csi tail, pose infer, count infer, cogs list,
  train count, job status. Same fail-open pattern as the cog
  binaries (WARN to stderr, exit 0 on unavailable sensing-server).

- docs/adr/ADR-104-ruview-mcp-cli-distribution.md — design rationale,
  6-row threat table, packaging plan, acceptance gates, failure modes.

- docs/research/sota-2026-05-22/HORIZON.md — 12-hour horizon plan
  with 7 milestones tracked (M1 complete in this commit).

Both packages are private:true pending the user's publish decision.
Inference is via subprocess to the signed cog binaries (ADR-100/101/103)
— no JS/WASM ML engine bundled.
2026-05-21 23:33:18 -04:00