feat(spaces): add spatial memory and governed actions (#1650)

This commit is contained in:
rUv
2026-08-19 13:23:29 -04:00
committed by GitHub
parent d36f346bba
commit c929bbc8b3
28 changed files with 3192 additions and 94 deletions

View File

@@ -232,23 +232,26 @@ const CAPABILITIES = Object.freeze([
id: 'cognitum-spaces-oauth',
name: 'Cognitum Spaces OAuth projection',
topics: ['integrations', 'deployment', 'community'],
status: 'implemented-read-only',
evidence: 'PRODUCTION',
summary: 'RuView explicitly activates spaces:read through Cognitum Authorization Code + PKCE, and the contributor metaharness exposes the validated tenant/workspace projection through an OAuth-only CLI/MCP adapter.',
status: 'implemented-read-only-staged',
evidence: 'MIXED',
summary: 'The legacy Spaces OAuth read is live. The feature branch extends the same read-only PKCE authority across the versioned site/building/floor/space/zone/entity/event/alert collections with bounded pagination and independent metaharness validation.',
sources: [
'docs/adr/ADR-325-cognitum-spaces-activation-and-governed-spatial-exchange.md',
'v2/crates/wifi-densepose-cli/src/spaces.rs',
'harness/ruview/src/spaces.js',
'docs/adr/ADR-326-tenant-scoped-ruvector-spatial-memory.md',
'docs/adr/ADR-327-governed-action-intents-and-witness-receipts.md',
],
validation: [
'cd harness/ruview && node --test test/spaces.test.mjs test/policy.test.mjs',
'wifi-densepose login --spaces && node harness/ruview/bin/cli.js spaces',
'wifi-densepose login --spaces && node harness/ruview/bin/cli.js spaces --resource events',
],
limitations: [
'The projection is read-only and grants no write, pairing, command, policy-approval, or actuator authority.',
'MCP requires the credential-use grant; bearer tokens and API keys are never accepted as tool arguments.',
'OAuth refresh may rotate the local credential file before a read returns.',
'The deployed slice exposes spaces only; the broader hierarchy, events, alerts, persistent spatial memory, and governed actions remain follow-up work.',
'Production evidence covers the legacy flat Spaces read. Versioned collections, spatial memory, and governed actions remain staged until workflow deployment/readback.',
'Persistent memory is local tenant/workspace state and governed actions expose authorization receipts only; neither expands OAuth authority.',
],
},
{

View File

@@ -12,8 +12,16 @@ import { redact } from './redact.js';
const DEFAULT_BASE_URL = 'https://api.cognitum.one';
const MAX_CLI_JSON_BYTES = 2 * 1024 * 1024;
const MAX_JSON_DEPTH = 16;
const MAX_JSON_NODES = 10_000;
const MAX_ARRAY_ITEMS = 1000;
const MAX_OBJECT_KEYS = 128;
const MAX_STRING_BYTES = 4096;
const MAX_SPACES = 100;
const MAX_RESOURCES = 100;
const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,119}$/;
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
export const SPATIAL_RESOURCE_KINDS = Object.freeze([
'sites', 'buildings', 'floors', 'spaces', 'zones', 'entities', 'events', 'alerts',
]);
const REQUIRED_EXCLUSIONS = Object.freeze([
'raw_csi',
'cir',
@@ -23,7 +31,13 @@ const REQUIRED_EXCLUSIONS = Object.freeze([
'vital_waveforms',
'identity_observations',
]);
const FORBIDDEN_FIELDS = new Set(REQUIRED_EXCLUSIONS.map(normalizeField));
const FORBIDDEN_FIELDS = new Set([
...REQUIRED_EXCLUSIONS.map(normalizeField),
'csi', 'channelstateinformation', 'rawcir', 'channelimpulseresponse',
'rftensor', 'rftensors', 'packetcapture', 'packetcaptures', 'pcap', 'recording', 'recordings', 'audiorecording',
'videorecording', 'poseframe', 'skeleton', 'keypoints', 'vitalwaveform',
'heartratewaveform', 'identityobservation', 'biometric', 'biometrics', 'face', 'faces', 'faceembedding',
]);
const SPACES_ENV_ALLOWLIST = Object.freeze([
...DEFAULT_ENV_ALLOWLIST,
// Operators may bind an MCP server to a credential file without putting a
@@ -35,24 +49,26 @@ function normalizeField(value) {
return String(value).replace(/[^a-z0-9]/gi, '').toLowerCase();
}
function assertBoundedValue(value, depth = 0) {
function assertBoundedValue(value, depth = 0, state = { nodes: 0 }) {
state.nodes += 1;
if (state.nodes > MAX_JSON_NODES) throw new Error('JSON structure exceeds node bound');
if (depth > MAX_JSON_DEPTH) throw new Error('JSON nesting is too deep');
if (typeof value === 'string') {
if (Buffer.byteLength(value, 'utf8') > MAX_STRING_BYTES) throw new Error('string exceeds bound');
return;
}
if (Array.isArray(value)) {
if (value.length > 1000) throw new Error('array exceeds bound');
for (const item of value) assertBoundedValue(item, depth + 1);
if (value.length > MAX_ARRAY_ITEMS) throw new Error('array exceeds bound');
for (const item of value) assertBoundedValue(item, depth + 1, state);
return;
}
if (!value || typeof value !== 'object') return;
const entries = Object.entries(value);
if (entries.length > 128) throw new Error('object exceeds bound');
if (entries.length > MAX_OBJECT_KEYS) throw new Error('object exceeds bound');
for (const [key, item] of entries) {
if (Buffer.byteLength(key, 'utf8') > MAX_STRING_BYTES) throw new Error('object key exceeds bound');
if (FORBIDDEN_FIELDS.has(normalizeField(key))) throw new Error(`forbidden raw field: ${key}`);
assertBoundedValue(item, depth + 1);
assertBoundedValue(item, depth + 1, state);
}
}
@@ -61,7 +77,7 @@ function nonEmptyString(value) {
}
/** Parse and independently enforce the metaharness semantic boundary. */
export function parseSpacesOutput(stdout) {
export function parseSpacesOutput(stdout, expectedKind = undefined) {
if (Buffer.byteLength(String(stdout), 'utf8') > MAX_CLI_JSON_BYTES) {
throw new Error('CLI response exceeds bound');
}
@@ -72,29 +88,76 @@ export function parseSpacesOutput(stdout) {
throw new Error('CLI response is not JSON');
}
assertBoundedValue(response);
if (!response || response.object !== 'list' || !Array.isArray(response.data) || response.data.length > MAX_SPACES) {
if (!response || response.object !== 'list' || !Array.isArray(response.data) || response.data.length > MAX_RESOURCES) {
throw new Error('invalid list envelope');
}
const versioned = response.schemaVersion !== undefined || response.kind !== undefined;
if (versioned && (response.schemaVersion !== '1.0' || !SPATIAL_RESOURCE_KINDS.includes(response.kind)
|| (expectedKind !== undefined && response.kind !== expectedKind))) {
throw new Error('invalid spatial contract version or kind');
}
const boundary = response.boundary;
if (!boundary || boundary.authoritativeState !== 'HomeCore Edge' || !Array.isArray(boundary.excluded)) {
if (!boundary || boundary.authoritativeState !== 'HomeCore Edge' || !Array.isArray(boundary.excluded)
|| !boundary.excluded.every((item) => typeof item === 'string')) {
throw new Error('incomplete edge privacy boundary');
}
for (const required of REQUIRED_EXCLUSIONS) {
if (!boundary.excluded.includes(required)) throw new Error('incomplete edge privacy boundary');
}
for (const space of response.data) {
if (!space || !nonEmptyString(space.id) || !nonEmptyString(space.tenantId)
|| !nonEmptyString(space.siteId) || !nonEmptyString(space.name)) {
throw new Error('space identity is incomplete');
for (const item of response.data) {
if (!item || !ID_RE.test(String(item.id ?? '')) || !nonEmptyString(item.tenantId)) {
throw new Error('spatial identity is incomplete');
}
if (!['P2', 'P3'].includes(space.privacy) || space.state?.classification !== 'P2') {
if (!['P2', 'P3'].includes(item.privacy)) {
throw new Error('non-semantic privacy class');
}
const confidence = space.state?.confidence;
const confidence = versioned ? item.confidence : item.state?.confidence;
if (confidence !== null && confidence !== undefined
&& (typeof confidence !== 'number' || !Number.isFinite(confidence) || confidence < 0 || confidence > 1)) {
throw new Error('invalid confidence');
}
if (!versioned) {
if (!nonEmptyString(item.siteId) || !nonEmptyString(item.name) || item.state?.classification !== 'P2') {
throw new Error('space identity is incomplete');
}
continue;
}
if (!UUID_RE.test(String(item.workspaceId ?? '')) || item.kind !== response.kind
|| item.schemaVersion !== '1.0' || !nonEmptyString(item.messageId)
|| !Number.isSafeInteger(item.eventSequence) || item.eventSequence < 0
|| !Number.isSafeInteger(item.version) || item.version < 1
|| !nonEmptyString(item.observedAt) || !Number.isFinite(Date.parse(item.observedAt))
|| (item.expiresAt !== null && item.expiresAt !== undefined
&& (!nonEmptyString(item.expiresAt) || !Number.isFinite(Date.parse(item.expiresAt))))
|| !item.attributes || Array.isArray(item.attributes) || typeof item.attributes !== 'object'
|| !item.provenance || Array.isArray(item.provenance) || typeof item.provenance !== 'object') {
throw new Error('versioned spatial identity is incomplete');
}
if (['buildings', 'floors', 'spaces', 'zones', 'entities', 'events', 'alerts'].includes(response.kind)
&& !nonEmptyString(item.siteId)) throw new Error('spatial parent is incomplete');
if (response.kind === 'floors' && !nonEmptyString(item.buildingId)) throw new Error('spatial parent is incomplete');
if (response.kind === 'spaces' && (!nonEmptyString(item.buildingId) || !nonEmptyString(item.floorId))) {
throw new Error('spatial parent is incomplete');
}
if (['zones', 'entities', 'events', 'alerts'].includes(response.kind) && !nonEmptyString(item.spaceId)) {
throw new Error('spatial parent is incomplete');
}
if (response.kind === 'entities'
&& (!['sensor', 'person', 'object', 'track'].includes(item.entityType)
|| (['person', 'track'].includes(item.entityType) && item.identityMode !== 'anonymous'))) {
throw new Error('entity privacy contract is invalid');
}
if (response.kind === 'events' && !nonEmptyString(item.eventType)) throw new Error('event type is missing');
if (response.kind === 'alerts'
&& (!nonEmptyString(item.alertType) || !['info', 'warning', 'critical'].includes(item.severity)
|| !['open', 'acknowledged', 'resolved'].includes(item.status))) {
throw new Error('alert contract is invalid');
}
}
if (versioned && response.nextCursor !== null && response.nextCursor !== undefined
&& (!nonEmptyString(response.nextCursor) || response.nextCursor.length > 512
|| /[\u0000-\u001f\u007f]/u.test(response.nextCursor))) {
throw new Error('invalid next cursor');
}
return response;
}
@@ -125,7 +188,23 @@ export async function listCognitumSpaces(input = {}, options = {}) {
};
}
const spacesArgs = ['spaces', '--json', '--base-url', DEFAULT_BASE_URL];
const resource = input.resource || 'spaces';
if (!SPATIAL_RESOURCE_KINDS.includes(resource)) {
return { ok: false, reason: 'invalid_resource' };
}
const limit = input.limit === undefined ? 50 : input.limit;
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) {
return { ok: false, reason: 'invalid_limit' };
}
if (input.cursor !== undefined
&& (typeof input.cursor !== 'string' || input.cursor.length === 0 || input.cursor.length > 512 || /[\u0000-\u001f\u007f]/u.test(input.cursor))) {
return { ok: false, reason: 'invalid_cursor' };
}
const spacesArgs = [
'spaces', '--json', '--base-url', DEFAULT_BASE_URL,
'--resource', resource, '--limit', String(limit),
];
if (input.cursor) spacesArgs.push('--cursor', input.cursor);
if (input.credentials_path) spacesArgs.push('--credentials-path', input.credentials_path);
let command;
@@ -158,7 +237,7 @@ export async function listCognitumSpaces(input = {}, options = {}) {
let response;
try {
response = parseSpacesOutput(result.stdout);
response = parseSpacesOutput(result.stdout, resource);
} catch (error) {
return {
ok: false,
@@ -173,6 +252,9 @@ export async function listCognitumSpaces(input = {}, options = {}) {
authentication: 'oauth',
via,
count: response.data.length,
resource,
schemaVersion: response.schemaVersion,
nextCursor: response.nextCursor ?? null,
data: response.data,
boundary: response.boundary,
authority: 'Read-only tenant/workspace projection; this result grants no action, write, pairing, or actuator authority.',

View File

@@ -292,12 +292,15 @@ export const TOOLS = {
},
ruview_spaces_list: {
title: 'List Cognitum Spaces',
description: 'List the authenticated tenant/workspace Cognitum Spaces projection through the hardened wifi-densepose OAuth client. Never accepts tokens or API keys. MCP use requires the credential-use grant; an expired OAuth session may rotate its stored refresh credential.',
title: 'List Cognitum Spatial Resources',
description: 'Page sites, buildings, floors, spaces, zones, anonymous entities, semantic events, or alerts in the authenticated tenant/workspace through the hardened wifi-densepose OAuth client. Never accepts tokens, API keys, writes, approvals, or action authority.',
inputSchema: {
type: 'object',
properties: {
credentials_path: { type: 'string', minLength: 1, maxLength: 4096, description: 'CLI only: OAuth credential file. MCP operators must set RUVIEW_CREDENTIALS_PATH in the server environment.' },
resource: { type: 'string', enum: ['sites', 'buildings', 'floors', 'spaces', 'zones', 'entities', 'events', 'alerts'], description: 'Versioned spatial collection. Default: spaces.' },
limit: { type: 'number', minimum: 1, maximum: 100, description: 'Page size. Default: 50.' },
cursor: { type: 'string', minLength: 1, maxLength: 512, description: 'Opaque cursor from the prior page.' },
},
},
async handler(args = {}, context = {}) {