Files
machineGroupControl/test/basic/commands.basic.test.js

343 lines
15 KiB
JavaScript
Raw Normal View History

// Basic tests for the machineGroupControl commands registry.
// Run with: node --test test/basic/commands.basic.test.js
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const { createRegistry } = require('generalFunctions');
const commands = require('../../src/commands');
// --- helpers ---------------------------------------------------------------
function makeLogger() {
const calls = { warn: [], error: [], info: [], debug: [] };
return {
calls,
warn: (m) => calls.warn.push(String(m)),
error: (m) => calls.error.push(String(m)),
info: (m) => calls.info.push(String(m)),
debug: (m) => calls.debug.push(String(m)),
};
}
feat(mgc): rendezvous planner — same-time landing across all modes Routes every dispatch through a tick-aware planner so all pumps reach their setpoint at the same wall-clock instant t* = max(eta_i), regardless of control strategy or per-pump reaction speed. Architecture (src/movement/): - machineProfile.js – pure snapshot of a registered child (state, position, velocityPctPerS, ladder timings, flowAt / positionForFlow). Reads timings from child.state.config.time (the actual storage location — previous fallback paths silently produced 0 s, collapsing every eta to ramp-only). - moveTrajectory.js – seconds-to-target per machine; handles idle / starting / warmingup / operational / cooling. - movementScheduler.js – t* = max eta over ALL non-noop moves. Every command is delayed so its move finishes at t*. Startup execsequence fires at 0; its flowmovement is gated by max(ladderS, t* − rampS) so a fast pump waits before ramping rather than landing early. useRendezvous=false collapses to all fireAtTickN=0 (legacy fire-and-forget). - movementExecutor.js – wall-clock virtual cursor: each tick fires every command whose fireAtTickN ≤ floor(elapsed/tickS). tick() no longer awaits pending fireCommand promises — the synchronous prologue of handleInput claims the latest-wins gate, which is what race-favouring relies on. Shared dispatch path (src/specificClass.js): - _dispatchFlowDistribution(distribution) — extracted from _optimalControl. Builds profiles, calls movementScheduler.plan, replans the executor, ticks once. Reads config.planner.useRendezvous (default true). - _optimalControl computes its bestCombination and hands off. - equalFlowControl (priorityControl mode) computes its flowDistribution and hands off via ctx.mgc._dispatchFlowDistribution. Same-time landing now applies in BOTH modes. Editor toggle (mgc.html + src/nodeClass.js): - New "Same-time landing" checkbox under Control Strategy. - nodeClass.buildDomainConfig bridges uiConfig.useRendezvous → config.planner.useRendezvous. Default ON. Tests: - New: planner-convergence.integration.test.js (real-time end-to-end diagnostic — drives a 3-pump mixed-state dispatch and asserts both convergence to the demand setpoint AND same-time landing within one tick). - New: planner-rendezvous.integration.test.js (schedule-shape assertions against real pump objects). - New: movementScheduler.basic.test.js — includes a mixed-speed multi-startup case proving the fast pumps wait so all three land together (the regression that prompted this work). - New: movementExecutor.basic.test.js + moveTrajectory.basic.test.js. - Updated executor contract test: tick() must NOT await pending fires. Commands + wiki: - handlers.js: source/mode allow-list gate moved into a shared _gate() helper; every command now checks isValidActionForMode + isValidSourceForMode before dispatching. Status-level commands (set.mode, set.scaling) are allowed in every mode. - commands.basic.test.js: coverage for the new gate behaviour. - wiki regen: Home.md visual-first rewrite + Reference-{Architecture, Contracts,Examples,Limitations}.md split with _Sidebar.md index. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 19:43:55 +02:00
function makeSource({
name = 'mgc-1',
handleInputResult = undefined,
dt = { flow: { min: 0, max: 100 } },
// Initial mode for the fake. Defaults to optimalControl so gates pass for
// the historical tests; per-test override via the returned `source.mode = …`.
mode = 'optimalControl',
// Override the gate decisions. Default-true matches the no-gating world
// tests assumed before this change; negative-path tests pass functions that
// return false for specific actions / sources.
isValidActionForMode = () => true,
isValidSourceForMode = () => true,
} = {}) {
const calls = {
setMode: [],
handleInput: [],
registerChild: [],
governance + unit-self-describing demand + dashboard fixes Two governance items from the 2026-05-14 quality review: - test/_output-manifest.md enumerates every Port 0/1/2 key MGC emits, its source, type, range, and which tests cover it in populated/degraded states (per .claude/rules/output-coverage.md). - src/control/strategies.js extracts computeEqualFlowDistribution as a pure function so the equal-flow algorithm is testable without an MGC fixture. test/basic/equalFlowDistribution.basic.test.js (6 tests) covers all three demand branches and pins the legacy quirk where the default branch counts active machines but iterates priority-ordered first-N (documented in the test so the future cleanup is a deliberate change). Plus rolled-up session work that landed alongside: - set.demand is now unit-self-describing ({value, unit:'m3/h'|'l/s'|'%'|...} or bare number = %); setScaling/scaling.current removed from MGC, commands, editor (mgc.html), specificClass. - _optimalControl + equalFlowControl now compute eta = (Q*dP)/P_shaft rather than Q/P, keeping the metric in the same scale as each child's cog. - groupEfficiency.calcRelativeDistanceFromPeak returns undefined (was 1) when pumps are homogeneous (|max-min| < 1e-9). Dashboard treats undefined as '-' instead of showing a misleading 100% / 0% reading. - examples/02-Dashboard.json: auto-init inject so the dashboard populates at deploy, NCog formatter normalizes the SUM emitted by MGC by machineCountActive, Q-H fanout trims the flat-Q tail so the H axis isn't stretched to 40m by curve-envelope clamp points, num/pct treat null AND undefined as no-data (closes the +null === 0 trap). - new test/integration/dashboard-fanout.integration.test.js (17 tests), bep-distance-demand-sweep.integration.test.js (3 tests), group-bep-cascade.integration.test.js -- total suite now 108/108 green. - .gitignore: wiki/test.gif (143 MB screen recording, kept locally only). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 22:31:25 +02:00
turnOffAllMachines: 0,
feat(mgc): rendezvous planner — same-time landing across all modes Routes every dispatch through a tick-aware planner so all pumps reach their setpoint at the same wall-clock instant t* = max(eta_i), regardless of control strategy or per-pump reaction speed. Architecture (src/movement/): - machineProfile.js – pure snapshot of a registered child (state, position, velocityPctPerS, ladder timings, flowAt / positionForFlow). Reads timings from child.state.config.time (the actual storage location — previous fallback paths silently produced 0 s, collapsing every eta to ramp-only). - moveTrajectory.js – seconds-to-target per machine; handles idle / starting / warmingup / operational / cooling. - movementScheduler.js – t* = max eta over ALL non-noop moves. Every command is delayed so its move finishes at t*. Startup execsequence fires at 0; its flowmovement is gated by max(ladderS, t* − rampS) so a fast pump waits before ramping rather than landing early. useRendezvous=false collapses to all fireAtTickN=0 (legacy fire-and-forget). - movementExecutor.js – wall-clock virtual cursor: each tick fires every command whose fireAtTickN ≤ floor(elapsed/tickS). tick() no longer awaits pending fireCommand promises — the synchronous prologue of handleInput claims the latest-wins gate, which is what race-favouring relies on. Shared dispatch path (src/specificClass.js): - _dispatchFlowDistribution(distribution) — extracted from _optimalControl. Builds profiles, calls movementScheduler.plan, replans the executor, ticks once. Reads config.planner.useRendezvous (default true). - _optimalControl computes its bestCombination and hands off. - equalFlowControl (priorityControl mode) computes its flowDistribution and hands off via ctx.mgc._dispatchFlowDistribution. Same-time landing now applies in BOTH modes. Editor toggle (mgc.html + src/nodeClass.js): - New "Same-time landing" checkbox under Control Strategy. - nodeClass.buildDomainConfig bridges uiConfig.useRendezvous → config.planner.useRendezvous. Default ON. Tests: - New: planner-convergence.integration.test.js (real-time end-to-end diagnostic — drives a 3-pump mixed-state dispatch and asserts both convergence to the demand setpoint AND same-time landing within one tick). - New: planner-rendezvous.integration.test.js (schedule-shape assertions against real pump objects). - New: movementScheduler.basic.test.js — includes a mixed-speed multi-startup case proving the fast pumps wait so all three land together (the regression that prompted this work). - New: movementExecutor.basic.test.js + moveTrajectory.basic.test.js. - Updated executor contract test: tick() must NOT await pending fires. Commands + wiki: - handlers.js: source/mode allow-list gate moved into a shared _gate() helper; every command now checks isValidActionForMode + isValidSourceForMode before dispatching. Status-level commands (set.mode, set.scaling) are allowed in every mode. - commands.basic.test.js: coverage for the new gate behaviour. - wiki regen: Home.md visual-first rewrite + Reference-{Architecture, Contracts,Examples,Limitations}.md split with _Sidebar.md index. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 19:43:55 +02:00
gateAction: [],
gateSource: [],
};
const source = {
logger: makeLogger(),
config: { general: { name } },
feat(mgc): rendezvous planner — same-time landing across all modes Routes every dispatch through a tick-aware planner so all pumps reach their setpoint at the same wall-clock instant t* = max(eta_i), regardless of control strategy or per-pump reaction speed. Architecture (src/movement/): - machineProfile.js – pure snapshot of a registered child (state, position, velocityPctPerS, ladder timings, flowAt / positionForFlow). Reads timings from child.state.config.time (the actual storage location — previous fallback paths silently produced 0 s, collapsing every eta to ramp-only). - moveTrajectory.js – seconds-to-target per machine; handles idle / starting / warmingup / operational / cooling. - movementScheduler.js – t* = max eta over ALL non-noop moves. Every command is delayed so its move finishes at t*. Startup execsequence fires at 0; its flowmovement is gated by max(ladderS, t* − rampS) so a fast pump waits before ramping rather than landing early. useRendezvous=false collapses to all fireAtTickN=0 (legacy fire-and-forget). - movementExecutor.js – wall-clock virtual cursor: each tick fires every command whose fireAtTickN ≤ floor(elapsed/tickS). tick() no longer awaits pending fireCommand promises — the synchronous prologue of handleInput claims the latest-wins gate, which is what race-favouring relies on. Shared dispatch path (src/specificClass.js): - _dispatchFlowDistribution(distribution) — extracted from _optimalControl. Builds profiles, calls movementScheduler.plan, replans the executor, ticks once. Reads config.planner.useRendezvous (default true). - _optimalControl computes its bestCombination and hands off. - equalFlowControl (priorityControl mode) computes its flowDistribution and hands off via ctx.mgc._dispatchFlowDistribution. Same-time landing now applies in BOTH modes. Editor toggle (mgc.html + src/nodeClass.js): - New "Same-time landing" checkbox under Control Strategy. - nodeClass.buildDomainConfig bridges uiConfig.useRendezvous → config.planner.useRendezvous. Default ON. Tests: - New: planner-convergence.integration.test.js (real-time end-to-end diagnostic — drives a 3-pump mixed-state dispatch and asserts both convergence to the demand setpoint AND same-time landing within one tick). - New: planner-rendezvous.integration.test.js (schedule-shape assertions against real pump objects). - New: movementScheduler.basic.test.js — includes a mixed-speed multi-startup case proving the fast pumps wait so all three land together (the regression that prompted this work). - New: movementExecutor.basic.test.js + moveTrajectory.basic.test.js. - Updated executor contract test: tick() must NOT await pending fires. Commands + wiki: - handlers.js: source/mode allow-list gate moved into a shared _gate() helper; every command now checks isValidActionForMode + isValidSourceForMode before dispatching. Status-level commands (set.mode, set.scaling) are allowed in every mode. - commands.basic.test.js: coverage for the new gate behaviour. - wiki regen: Home.md visual-first rewrite + Reference-{Architecture, Contracts,Examples,Limitations}.md split with _Sidebar.md index. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 19:43:55 +02:00
mode,
setMode: (m) => { calls.setMode.push(m); /* keep fake.mode unchanged unless test does it */ },
isValidActionForMode: (action, m) => {
const ok = isValidActionForMode(action, m);
calls.gateAction.push({ action, mode: m, ok });
if (!ok) source.logger.warn(`action '${action}' not allowed in mode '${m}'`);
return ok;
},
isValidSourceForMode: (src, m) => {
const ok = isValidSourceForMode(src, m);
calls.gateSource.push({ src, mode: m, ok });
if (!ok) source.logger.warn(`source '${src}' not allowed in mode '${m}'`);
return ok;
},
handleInput: async (src, demand) => {
calls.handleInput.push({ src, demand });
if (handleInputResult instanceof Error) throw handleInputResult;
return handleInputResult;
},
governance + unit-self-describing demand + dashboard fixes Two governance items from the 2026-05-14 quality review: - test/_output-manifest.md enumerates every Port 0/1/2 key MGC emits, its source, type, range, and which tests cover it in populated/degraded states (per .claude/rules/output-coverage.md). - src/control/strategies.js extracts computeEqualFlowDistribution as a pure function so the equal-flow algorithm is testable without an MGC fixture. test/basic/equalFlowDistribution.basic.test.js (6 tests) covers all three demand branches and pins the legacy quirk where the default branch counts active machines but iterates priority-ordered first-N (documented in the test so the future cleanup is a deliberate change). Plus rolled-up session work that landed alongside: - set.demand is now unit-self-describing ({value, unit:'m3/h'|'l/s'|'%'|...} or bare number = %); setScaling/scaling.current removed from MGC, commands, editor (mgc.html), specificClass. - _optimalControl + equalFlowControl now compute eta = (Q*dP)/P_shaft rather than Q/P, keeping the metric in the same scale as each child's cog. - groupEfficiency.calcRelativeDistanceFromPeak returns undefined (was 1) when pumps are homogeneous (|max-min| < 1e-9). Dashboard treats undefined as '-' instead of showing a misleading 100% / 0% reading. - examples/02-Dashboard.json: auto-init inject so the dashboard populates at deploy, NCog formatter normalizes the SUM emitted by MGC by machineCountActive, Q-H fanout trims the flat-Q tail so the H axis isn't stretched to 40m by curve-envelope clamp points, num/pct treat null AND undefined as no-data (closes the +null === 0 trap). - new test/integration/dashboard-fanout.integration.test.js (17 tests), bep-distance-demand-sweep.integration.test.js (3 tests), group-bep-cascade.integration.test.js -- total suite now 108/108 green. - .gitignore: wiki/test.gif (143 MB screen recording, kept locally only). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 22:31:25 +02:00
// Used by set.demand handler when unit is %: needs dt.flow + interpolation.
// With min=0, max=100, the linear interpolation is identity so a bare
// numeric demand round-trips through handleInput unchanged.
calcDynamicTotals: () => dt,
interpolation: {
interpolate_lin_single_point: (x, ix, iy, ox, oy) => {
if (iy === ix) return ox;
return ox + ((x - ix) * (oy - ox)) / (iy - ix);
},
},
turnOffAllMachines: async () => { calls.turnOffAllMachines += 1; },
childRegistrationUtils: {
registerChild: (childSource, position) =>
calls.registerChild.push({ childSource, position }),
},
};
return { source, calls };
}
function makeCtx({ child = null, logger = makeLogger(), sendSpy = null } = {}) {
return {
logger,
RED: { nodes: { getNode: (id) => (child && child.id === id ? child : undefined) } },
node: {},
send: sendSpy || (() => {}),
};
}
function makeRegistry(logger) {
return createRegistry(commands, { logger });
}
// --- tests -----------------------------------------------------------------
test('canonical topics dispatch to their handlers', async () => {
const { source, calls } = makeSource();
const reg = makeRegistry(makeLogger());
await reg.dispatch({ topic: 'set.mode', payload: 'prioritycontrol' }, source, makeCtx());
assert.deepEqual(calls.setMode, ['prioritycontrol']);
governance + unit-self-describing demand + dashboard fixes Two governance items from the 2026-05-14 quality review: - test/_output-manifest.md enumerates every Port 0/1/2 key MGC emits, its source, type, range, and which tests cover it in populated/degraded states (per .claude/rules/output-coverage.md). - src/control/strategies.js extracts computeEqualFlowDistribution as a pure function so the equal-flow algorithm is testable without an MGC fixture. test/basic/equalFlowDistribution.basic.test.js (6 tests) covers all three demand branches and pins the legacy quirk where the default branch counts active machines but iterates priority-ordered first-N (documented in the test so the future cleanup is a deliberate change). Plus rolled-up session work that landed alongside: - set.demand is now unit-self-describing ({value, unit:'m3/h'|'l/s'|'%'|...} or bare number = %); setScaling/scaling.current removed from MGC, commands, editor (mgc.html), specificClass. - _optimalControl + equalFlowControl now compute eta = (Q*dP)/P_shaft rather than Q/P, keeping the metric in the same scale as each child's cog. - groupEfficiency.calcRelativeDistanceFromPeak returns undefined (was 1) when pumps are homogeneous (|max-min| < 1e-9). Dashboard treats undefined as '-' instead of showing a misleading 100% / 0% reading. - examples/02-Dashboard.json: auto-init inject so the dashboard populates at deploy, NCog formatter normalizes the SUM emitted by MGC by machineCountActive, Q-H fanout trims the flat-Q tail so the H axis isn't stretched to 40m by curve-envelope clamp points, num/pct treat null AND undefined as no-data (closes the +null === 0 trap). - new test/integration/dashboard-fanout.integration.test.js (17 tests), bep-distance-demand-sweep.integration.test.js (3 tests), group-bep-cascade.integration.test.js -- total suite now 108/108 green. - .gitignore: wiki/test.gif (143 MB screen recording, kept locally only). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 22:31:25 +02:00
// bare-number demand → interpreted as % → interpolated against dt.flow.
// Default test dt is {min:0,max:100} so % is identity.
await reg.dispatch({ topic: 'set.demand', payload: '12.5' }, source, makeCtx());
assert.equal(calls.handleInput.length, 1);
assert.deepEqual(calls.handleInput[0], { src: 'parent', demand: 12.5 });
});
governance + unit-self-describing demand + dashboard fixes Two governance items from the 2026-05-14 quality review: - test/_output-manifest.md enumerates every Port 0/1/2 key MGC emits, its source, type, range, and which tests cover it in populated/degraded states (per .claude/rules/output-coverage.md). - src/control/strategies.js extracts computeEqualFlowDistribution as a pure function so the equal-flow algorithm is testable without an MGC fixture. test/basic/equalFlowDistribution.basic.test.js (6 tests) covers all three demand branches and pins the legacy quirk where the default branch counts active machines but iterates priority-ordered first-N (documented in the test so the future cleanup is a deliberate change). Plus rolled-up session work that landed alongside: - set.demand is now unit-self-describing ({value, unit:'m3/h'|'l/s'|'%'|...} or bare number = %); setScaling/scaling.current removed from MGC, commands, editor (mgc.html), specificClass. - _optimalControl + equalFlowControl now compute eta = (Q*dP)/P_shaft rather than Q/P, keeping the metric in the same scale as each child's cog. - groupEfficiency.calcRelativeDistanceFromPeak returns undefined (was 1) when pumps are homogeneous (|max-min| < 1e-9). Dashboard treats undefined as '-' instead of showing a misleading 100% / 0% reading. - examples/02-Dashboard.json: auto-init inject so the dashboard populates at deploy, NCog formatter normalizes the SUM emitted by MGC by machineCountActive, Q-H fanout trims the flat-Q tail so the H axis isn't stretched to 40m by curve-envelope clamp points, num/pct treat null AND undefined as no-data (closes the +null === 0 trap). - new test/integration/dashboard-fanout.integration.test.js (17 tests), bep-distance-demand-sweep.integration.test.js (3 tests), group-bep-cascade.integration.test.js -- total suite now 108/108 green. - .gitignore: wiki/test.gif (143 MB screen recording, kept locally only). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 22:31:25 +02:00
test('set.demand with explicit flow unit converts to canonical m³/s', async () => {
const { source, calls } = makeSource();
const reg = makeRegistry(makeLogger());
await reg.dispatch({ topic: 'set.demand', payload: { value: 200, unit: 'm3/h' } }, source, makeCtx());
assert.equal(calls.handleInput.length, 1);
// 200 m³/h = 0.0555... m³/s
assert.ok(Math.abs(calls.handleInput[0].demand - 0.05555555555555556) < 1e-9,
`expected ~0.0556 m³/s, got ${calls.handleInput[0].demand}`);
});
test('set.demand negative value triggers turnOffAllMachines and bypasses handleInput', async () => {
const { source, calls } = makeSource();
const reg = makeRegistry(makeLogger());
await reg.dispatch({ topic: 'set.demand', payload: -1 }, source, makeCtx());
assert.equal(calls.turnOffAllMachines, 1);
assert.equal(calls.handleInput.length, 0);
});
test('child.register canonical resolves child via RED.nodes.getNode', async () => {
const { source, calls } = makeSource();
const child = { id: 'child-1', source: { tag: 'child-domain' } };
const reg = makeRegistry(makeLogger());
await reg.dispatch(
{ topic: 'child.register', payload: 'child-1', positionVsParent: 'upstream' },
source,
makeCtx({ child })
);
assert.equal(calls.registerChild.length, 1);
assert.equal(calls.registerChild[0].childSource, child.source);
assert.equal(calls.registerChild[0].position, 'upstream');
});
test('aliases dispatch to the same handler and log a one-time deprecation', async () => {
const { source, calls } = makeSource();
const ctxLogger = makeLogger();
const reg = makeRegistry(ctxLogger);
await reg.dispatch({ topic: 'setMode', payload: 'prioritycontrol' }, source, makeCtx({ logger: ctxLogger }));
await reg.dispatch({ topic: 'setMode', payload: 'optimalcontrol' }, source, makeCtx({ logger: ctxLogger }));
assert.deepEqual(calls.setMode, ['prioritycontrol', 'optimalcontrol']);
let warns = ctxLogger.calls.warn.filter((m) => m.includes("'setMode' is deprecated"));
assert.equal(warns.length, 1, 'setMode deprecation warning should log exactly once');
await reg.dispatch({ topic: 'Qd', payload: 5 }, source, makeCtx({ logger: ctxLogger }));
warns = ctxLogger.calls.warn.filter((m) => m.includes("'Qd' is deprecated"));
assert.equal(warns.length, 1);
assert.equal(calls.handleInput.length, 1);
const child = { id: 'child-x', source: { tag: 'child-domain' } };
await reg.dispatch(
{ topic: 'registerChild', payload: 'child-x', positionVsParent: 'atEquipment' },
source,
makeCtx({ child, logger: ctxLogger })
);
warns = ctxLogger.calls.warn.filter((m) => m.includes("'registerChild' is deprecated"));
assert.equal(warns.length, 1);
assert.equal(calls.registerChild.length, 1);
});
test('set.demand with non-numeric payload logs error and does not call handleInput', async () => {
const { source, calls } = makeSource();
const ctxLogger = makeLogger();
const reg = makeRegistry(makeLogger());
await reg.dispatch({ topic: 'set.demand', payload: 'oops' }, source, makeCtx({ logger: ctxLogger }));
assert.equal(calls.handleInput.length, 0);
assert.ok(
ctxLogger.calls.error.some((m) => m.includes('set.demand') && m.includes('oops')),
`expected error about invalid Qd, got: ${JSON.stringify(ctxLogger.calls.error)}`
);
});
test('set.demand on success calls ctx.send with reply { topic: config.general.name, payload: "done" }', async () => {
const { source, calls } = makeSource({ name: 'mgc-A' });
const sent = [];
const ctx = makeCtx({ sendSpy: (m) => sent.push(m) });
const reg = makeRegistry(makeLogger());
await reg.dispatch({ topic: 'set.demand', payload: 7.5 }, source, ctx);
assert.equal(calls.handleInput.length, 1);
assert.deepEqual(calls.handleInput[0], { src: 'parent', demand: 7.5 });
assert.equal(sent.length, 1);
assert.equal(sent[0].topic, 'mgc-A');
assert.equal(sent[0].payload, 'done');
});
test('child.register with unknown child id logs warn and does not throw', async () => {
const { source, calls } = makeSource();
const ctxLogger = makeLogger();
const reg = makeRegistry(makeLogger());
await assert.doesNotReject(() =>
reg.dispatch(
{ topic: 'child.register', payload: 'missing-id', positionVsParent: 'atEquipment' },
source,
makeCtx({ logger: ctxLogger })
)
);
assert.equal(calls.registerChild.length, 0);
assert.ok(
ctxLogger.calls.warn.some((m) => m.includes('registerChild') && m.includes('missing-id')),
`expected warn about missing child, got: ${JSON.stringify(ctxLogger.calls.warn)}`
);
});
feat(mgc): rendezvous planner — same-time landing across all modes Routes every dispatch through a tick-aware planner so all pumps reach their setpoint at the same wall-clock instant t* = max(eta_i), regardless of control strategy or per-pump reaction speed. Architecture (src/movement/): - machineProfile.js – pure snapshot of a registered child (state, position, velocityPctPerS, ladder timings, flowAt / positionForFlow). Reads timings from child.state.config.time (the actual storage location — previous fallback paths silently produced 0 s, collapsing every eta to ramp-only). - moveTrajectory.js – seconds-to-target per machine; handles idle / starting / warmingup / operational / cooling. - movementScheduler.js – t* = max eta over ALL non-noop moves. Every command is delayed so its move finishes at t*. Startup execsequence fires at 0; its flowmovement is gated by max(ladderS, t* − rampS) so a fast pump waits before ramping rather than landing early. useRendezvous=false collapses to all fireAtTickN=0 (legacy fire-and-forget). - movementExecutor.js – wall-clock virtual cursor: each tick fires every command whose fireAtTickN ≤ floor(elapsed/tickS). tick() no longer awaits pending fireCommand promises — the synchronous prologue of handleInput claims the latest-wins gate, which is what race-favouring relies on. Shared dispatch path (src/specificClass.js): - _dispatchFlowDistribution(distribution) — extracted from _optimalControl. Builds profiles, calls movementScheduler.plan, replans the executor, ticks once. Reads config.planner.useRendezvous (default true). - _optimalControl computes its bestCombination and hands off. - equalFlowControl (priorityControl mode) computes its flowDistribution and hands off via ctx.mgc._dispatchFlowDistribution. Same-time landing now applies in BOTH modes. Editor toggle (mgc.html + src/nodeClass.js): - New "Same-time landing" checkbox under Control Strategy. - nodeClass.buildDomainConfig bridges uiConfig.useRendezvous → config.planner.useRendezvous. Default ON. Tests: - New: planner-convergence.integration.test.js (real-time end-to-end diagnostic — drives a 3-pump mixed-state dispatch and asserts both convergence to the demand setpoint AND same-time landing within one tick). - New: planner-rendezvous.integration.test.js (schedule-shape assertions against real pump objects). - New: movementScheduler.basic.test.js — includes a mixed-speed multi-startup case proving the fast pumps wait so all three land together (the regression that prompted this work). - New: movementExecutor.basic.test.js + moveTrajectory.basic.test.js. - Updated executor contract test: tick() must NOT await pending fires. Commands + wiki: - handlers.js: source/mode allow-list gate moved into a shared _gate() helper; every command now checks isValidActionForMode + isValidSourceForMode before dispatching. Status-level commands (set.mode, set.scaling) are allowed in every mode. - commands.basic.test.js: coverage for the new gate behaviour. - wiki regen: Home.md visual-first rewrite + Reference-{Architecture, Contracts,Examples,Limitations}.md split with _Sidebar.md index. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 19:43:55 +02:00
// --- mode gate tests -------------------------------------------------------
test('gate: set.demand in maintenance mode is dropped (action not allowed)', async () => {
// Mirror schema: maintenance allows only statusCheck. The dispatch action
// for a positive demand under optimalControl/priorityControl is
// execOptimalCombination / execSequentialControl — neither in maintenance.
const { source, calls } = makeSource({
mode: 'maintenance',
isValidActionForMode: (action) => action === 'statusCheck',
});
const reg = makeRegistry(makeLogger());
await reg.dispatch({ topic: 'set.demand', payload: 50 }, source, makeCtx());
assert.equal(calls.handleInput.length, 0, 'handleInput must not be invoked');
assert.equal(calls.turnOffAllMachines, 0, 'turnOffAllMachines must not be invoked');
assert.ok(
source.logger.calls.warn.some((m) => m.includes('not allowed')),
`expected warn about action not allowed in maintenance, got: ${JSON.stringify(source.logger.calls.warn)}`
);
});
test("gate: set.demand from msg.source 'physical' in maintenance is dropped (source not allowed)", async () => {
// Maintenance accepts sources ['parent','GUI'] per schema. Physical/HMI is
// rejected by the source gate even before we ask which action to perform.
const { source, calls } = makeSource({
mode: 'maintenance',
isValidActionForMode: () => true, // pretend action is allowed; source gate must still reject
isValidSourceForMode: (src) => src === 'parent' || src === 'GUI',
});
const reg = makeRegistry(makeLogger());
await reg.dispatch({ topic: 'set.demand', payload: 50, source: 'physical' }, source, makeCtx());
assert.equal(calls.handleInput.length, 0);
assert.equal(calls.turnOffAllMachines, 0);
assert.ok(
source.logger.calls.warn.some((m) => m.includes("'physical'") && m.includes('not allowed')),
`expected warn about physical source not allowed, got: ${JSON.stringify(source.logger.calls.warn)}`
);
});
test('gate: set.demand from msg.source GUI in optimalControl reaches handleInput', async () => {
const { source, calls } = makeSource({
mode: 'optimalControl',
isValidActionForMode: (action) =>
['statusCheck', 'execOptimalCombination', 'balanceLoad', 'emergencyStop'].includes(action),
isValidSourceForMode: (src) => ['parent', 'GUI', 'physical', 'API'].includes(src),
});
const reg = makeRegistry(makeLogger());
await reg.dispatch({ topic: 'set.demand', payload: 25, source: 'GUI' }, source, makeCtx());
assert.equal(calls.handleInput.length, 1);
assert.deepEqual(calls.handleInput[0], { src: 'parent', demand: 25 });
// Sanity check on the gate plumbing: both gates were consulted with the
// expected (action, source, mode) tuple.
assert.ok(calls.gateAction.some((g) => g.action === 'execOptimalCombination' && g.mode === 'optimalControl' && g.ok));
assert.ok(calls.gateSource.some((g) => g.src === 'GUI' && g.mode === 'optimalControl' && g.ok));
});
test('gate: emergencyStop (negative demand) gated by mode → maintenance blocks the stop-all', async () => {
// A negative demand is the operator stop-all signal. The schema declares
// emergencyStop in optimalControl/priorityControl but NOT in maintenance,
// so this should be rejected too — maintenance is "monitor only", which
// includes "no dispatch decisions, even shutdowns".
const { source, calls } = makeSource({
mode: 'maintenance',
isValidActionForMode: (action) => action === 'statusCheck',
});
const reg = makeRegistry(makeLogger());
await reg.dispatch({ topic: 'set.demand', payload: -1 }, source, makeCtx());
assert.equal(calls.turnOffAllMachines, 0, 'turnOff must be gated');
assert.ok(
source.logger.calls.warn.some((m) => m.includes('emergencyStop') && m.includes('not allowed')),
`expected warn about emergencyStop not allowed, got: ${JSON.stringify(source.logger.calls.warn)}`
);
});
// --- mode-string normalisation (specificClass internals) --------------------
const { _normaliseMode, ALLOWED_MODES } = require('../../src/specificClass');
test('mode normalisation: camelCase pass-through, lowercase accepted, garbage rejected', () => {
assert.equal(_normaliseMode('optimalControl'), 'optimalControl');
assert.equal(_normaliseMode('optimalcontrol'), 'optimalControl');
assert.equal(_normaliseMode('OPTIMALCONTROL'), 'optimalControl');
assert.equal(_normaliseMode('priorityControl'), 'priorityControl');
assert.equal(_normaliseMode('prioritycontrol'), 'priorityControl');
assert.equal(_normaliseMode('maintenance'), 'maintenance');
assert.equal(_normaliseMode('MAINTENANCE'), 'maintenance');
assert.equal(_normaliseMode('wat'), null);
assert.equal(_normaliseMode(''), null);
assert.equal(_normaliseMode(null), null);
assert.equal(_normaliseMode(undefined), null);
assert.deepEqual(ALLOWED_MODES, ['optimalControl', 'priorityControl', 'maintenance']);
});
// --- schema-shape regression -----------------------------------------------
test('schema regression: allowedSources keys are camelCase for all three modes', () => {
// Read the JSON directly — generalFunctions' package.json `exports` map
// doesn't expose the configs subpath, and we don't want to add it just for
// a test. Path is repo-relative from this test file.
const fs = require('node:fs');
const path = require('node:path');
const schemaPath = path.resolve(__dirname, '../../../generalFunctions/src/configs/machineGroupControl.json');
const schema = JSON.parse(fs.readFileSync(schemaPath, 'utf8'));
const allowedSourcesSchema = schema.mode.allowedSources.rules.schema;
assert.ok(allowedSourcesSchema.optimalControl, 'optimalControl key must exist on allowedSources');
assert.ok(allowedSourcesSchema.priorityControl, 'priorityControl key must exist on allowedSources');
assert.ok(allowedSourcesSchema.maintenance, 'maintenance key must exist on allowedSources');
// Maintenance is monitor-only: parent + GUI permitted, physical/API rejected.
const mDefaults = allowedSourcesSchema.maintenance.default;
assert.ok(mDefaults.includes('parent'), `maintenance default should permit parent, got ${mDefaults}`);
assert.ok(mDefaults.includes('GUI'), `maintenance default should permit GUI, got ${mDefaults}`);
assert.ok(!mDefaults.includes('physical'), 'maintenance must NOT permit physical writes');
assert.ok(!mDefaults.includes('API'), 'maintenance must NOT permit API writes');
// Catch a regression to lowercase keys.
assert.equal(allowedSourcesSchema.optimalcontrol, undefined, 'lowercase optimalcontrol key must NOT exist');
assert.equal(allowedSourcesSchema.prioritycontrol, undefined, 'lowercase prioritycontrol key must NOT exist');
});