@fusedashlabs/ui9000-workspace
Version:
UI9000 workspace MCP. One tool, show_workspace, draws a chart from your table. Set TYPESAFE_API_KEY to let Jev choose the chart.
247 lines (246 loc) • 9.45 kB
JavaScript
/**
* Goals perimeter object for `<ui9000-goals-perimeter>` (AM-2).
*
* Many agents (or resources) arranged around a shared goal: one row per agent
* with its id, its health state and the goal it works toward. Optional
* columns add a link target per agent (a dependency, another agent, or a
* goal), a reason, a blocker kind, and an exception count per goal.
*
* Or one row per goal and resource group, as the Agent operations board is
* drawn: each goal with its agents by state, the healthy ones included, on
* every goal, and optional code, status, progress and burn; each group with
* its kind, state, calls, held agents and detail.
*
* The reading is perimeter and population health, so the rows fit only when
* every agent has a health state the widget can draw and the goals are few
* against many agents, or when every goal counts its healthy agents. A
* free-form adjacency list (`source,target`) has no goal or state and stays
* network-graph.
*/
import { AGENT_KEYS, BLOCKER_KEYS, EXCEPTION_KEYS, GOAL_KEYS, LINK_KEYS, LINK_STATUS_KEYS, namesAgentPair, REASON_KEYS, STATE_KEYS, TITLE_KEYS, } from '../../profiler/perimeter-columns.js';
import { normalizeName } from '../../profiler/table.js';
import { readGoalGroups } from './goal-groups.js';
/** Health words → the widget's agent states. */
const STATES = {
healthy: 'healthy',
ok: 'healthy',
success: 'healthy',
active: 'healthy',
running: 'healthy',
online: 'healthy',
up: 'healthy',
working: 'healthy',
degraded: 'degraded',
warning: 'degraded',
warn: 'degraded',
slow: 'degraded',
overbudget: 'degraded',
blocked: 'blocked',
held: 'blocked',
awaiting: 'awaiting',
waiting: 'awaiting',
holding: 'awaiting',
pending: 'awaiting',
onhold: 'awaiting',
failed: 'failed',
failure: 'failed',
error: 'failed',
crashed: 'failed',
down: 'failed',
offline: 'failed',
unavailable: 'failed',
idle: 'idle',
inactive: 'idle',
paused: 'idle',
stopped: 'idle',
};
const BLOCKERS = {
rule: 'rule',
policy: 'rule',
dependency: 'dependency',
upstream: 'dependency',
human: 'human',
approval: 'human',
manual: 'human',
};
/** Fewer agents than this is a list, not a population. */
const MIN_AGENTS = 6;
/** More goals than this is a comparison of goals, not agents around one. */
const MAX_GOALS = 8;
/** Each goal needs this many agents on average to be a perimeter. */
const MIN_AGENTS_PER_GOAL = 3;
/** Share of rows whose state must be a health word. */
const STATE_COVERAGE = 0.9;
export function goalsPerimeterPayload(_fields, rows) {
const perimeter = readPerimeter(rows);
if (!perimeter)
return goalHealthPayload(rows);
const out = { chartType: 'goalsPerimeter' };
if (perimeter.title)
out.name = perimeter.title;
out.goals = perimeter.goals;
out.agents = perimeter.agents;
if (perimeter.links.length > 0)
out.links = perimeter.links;
out.exceptionCount = perimeter.exceptionCount;
return out;
}
/**
* True when the rows are agents around shared goals: an agent, a health
* state and a goal on every row, few goals against many agents. A plain
* node–link list stays network-graph.
*/
export function goalsPerimeterFits(payload) {
if (!Array.isArray(payload))
return false;
const rows = payload.filter(isRecord);
return readPerimeter(rows) !== null || readGoalHealth(rows) !== null;
}
/** The goals as the board draws them: progress is the perimeter arc, the widget's `health`. */
function goalHealthPayload(rows) {
const board = readGoalHealth(rows);
if (!board)
return null;
return {
chartType: 'goalsPerimeter',
...(board.title ? { name: board.title } : {}),
goals: board.goals.map(({ progress, ...goal }) => ({
...goal,
...(progress !== undefined ? { health: progress } : {}),
})),
};
}
/** Goals against their groups, one to a few of them, every one counting its healthy agents. */
function readGoalHealth(rows) {
// One goal is a perimeter of its own, unlike goals against groups.
const map = readGoalGroups(rows, { minGoals: 1 });
if (!map || map.goals.length > MAX_GOALS)
return null;
if (!map.goals.every((goal) => goal.agents.healthy !== undefined))
return null;
return { ...(map.title ? { title: map.title } : {}), goals: map.goals };
}
function readPerimeter(rows) {
if (rows.length < MIN_AGENTS)
return null;
const columns = readColumns(rows);
if (!columns)
return null;
const agents = new Map();
const goals = new Map();
const links = [];
let stated = 0;
for (const row of rows) {
const id = text(row[columns.agent]);
const goal = text(row[columns.goal]);
const stateWord = text(row[columns.state]);
if (!id || !goal)
return null;
const state = stateWord ? STATES[stateWord.toLowerCase().replace(/[\s_-]+/g, '')] : 'healthy';
if (state)
stated += 1;
if (!goals.has(goal.toLowerCase()))
goals.set(goal.toLowerCase(), { name: goal });
const known = goals.get(goal.toLowerCase());
if (columns.exceptions && known.exceptionCount === undefined) {
const count = num(row[columns.exceptions]);
if (count !== undefined)
known.exceptionCount = Math.max(0, Math.round(count));
}
const existing = agents.get(id);
if (existing) {
// A repeated agent is another link of the same agent; anything else is not one population.
if (!columns.link || existing.goal !== goal)
return null;
}
else {
const agent = { id, state: state ?? 'idle', goal };
const reason = columns.reason ? text(row[columns.reason]) : '';
if (reason && agent.state !== 'healthy')
agent.reason = reason;
const blocker = columns.blocker ? BLOCKERS[text(row[columns.blocker]).toLowerCase()] : undefined;
if (blocker && agent.state === 'blocked')
agent.blocker = blocker;
agents.set(id, agent);
}
if (columns.link) {
const target = text(row[columns.link]);
if (target && target !== id) {
const status = columns.linkStatus ? text(row[columns.linkStatus]).toLowerCase() : '';
links.push({ source: id, target, ...(status ? { status } : {}) });
}
}
}
if (stated / rows.length < STATE_COVERAGE)
return null;
if (agents.size < MIN_AGENTS)
return null;
if (goals.size > MAX_GOALS || agents.size / goals.size < MIN_AGENTS_PER_GOAL)
return null;
const all = [...agents.values()];
const counted = [...goals.values()].filter((goal) => goal.exceptionCount !== undefined);
const exceptionCount = counted.length === goals.size
? counted.reduce((sum, goal) => sum + goal.exceptionCount, 0)
: all.filter((agent) => agent.state !== 'healthy' && agent.state !== 'idle')
.length;
const title = columns.title ? sameText(rows, columns.title) : undefined;
return {
...(title ? { title } : {}),
goals: [...goals.values()],
agents: all,
links,
exceptionCount,
};
}
/**
* The agent, state and goal columns, plus the optional ones. A `source`
* column is the agent only when its `target` pair is there to be the link.
*/
function readColumns(rows) {
// Every row's keys: an optional column may be absent from the first rows of a JSON payload.
const keys = [...new Set(rows.flatMap((row) => Object.keys(row)))];
const find = (set, skip = []) => keys.find((key) => set.has(normalizeName(key)) && !skip.includes(key));
const goal = find(GOAL_KEYS);
const state = find(STATE_KEYS);
if (!goal || !state)
return null;
const agent = find(AGENT_KEYS) ?? (namesAgentPair(keys) ? keys.find((key) => normalizeName(key) === 'source') : undefined);
if (!agent)
return null;
const taken = [goal, state, agent];
const link = find(LINK_KEYS, taken);
return {
agent,
state,
goal,
...(link ? { link } : {}),
...optional('linkStatus', find(LINK_STATUS_KEYS, taken)),
...optional('reason', find(REASON_KEYS, taken)),
...optional('blocker', find(BLOCKER_KEYS, taken)),
...optional('exceptions', find(EXCEPTION_KEYS, taken)),
...optional('title', find(TITLE_KEYS, taken)),
};
}
function optional(name, key) {
return key ? { [name]: key } : {};
}
function sameText(rows, key) {
const first = text(rows[0][key]);
if (!first)
return undefined;
return rows.every((row) => text(row[key]) === first) ? first : undefined;
}
function text(value) {
return typeof value === 'string' || typeof value === 'number' ? String(value).trim() : '';
}
function num(value) {
if (typeof value === 'number')
return Number.isFinite(value) ? value : undefined;
if (typeof value !== 'string' || !value.trim())
return undefined;
const n = Number(value.trim().replace(/,/g, ''));
return Number.isFinite(n) ? n : undefined;
}
function isRecord(value) {
return !!value && typeof value === 'object' && !Array.isArray(value);
}