Skip to content

refactor: audit-driven cleanup — OCPP conformance fixes, physics, harmonization - #1960

Merged
jerome-benoit merged 12 commits into
mainfrom
from-zero-audit-2
Jul 6, 2026
Merged

jerome-benoit merged 12 commits into
mainfrom
from-zero-audit-2

Conversation

@jerome-benoit

Copy link
Copy Markdown
Contributor

Summary

Ten focused commits from a from-zero cross-validated audit (5-lane fan-out: OCPP spec conformance / design-algo-physics / TS best-practices / harmonization-DRY / content quality) on main tip 22cb25f0. Each commit is atomic, spec-cited where applicable, and passes the full documented quality gates (format / typecheck / lint / build / test) across every affected package (root, ui/cli, ui/web).

Skott circular-dependency count: 62 → 61 — one cycle eliminated by removing OCPPAuthServiceImpl from the auth barrel.

Commits

# Commit Kind Finding Files
1 f5e739d0 fix(ocpp/1.6) Critical C1 GetDiagnostics comma-operator path resolution bug
2 34a574f9 fix(physics) Critical C4 Math.sqrt(numberOfPhases) → Math.sqrt(3) for line-to-line voltage
3 dbc3f3ff refactor(auth) M1 65 occurrences of bare OCPP 2.0 → OCPP 2.0.1 in auth subsystem
4 dfa89a5c refactor(ocpp/1.6) M3 'central system' → 'Central System' (spec-correct capitalization)
5 8cb6d803 refactor M8 Numeric-literal underscore separators (60000 → 60_000) for 5-digit+ literals
6 721405a7 chore M2 + M20 README: add Authorize to OCPP 2.0.x table; extract WILDCARD_HOSTS
7 5d44b94d fix(ocpp/1.6) Critical C3 DataTransfer: return Accepted for matching vendor + messageId (per §4.3)
8 c8877b4f fix(ocpp/1.6) High H1 Emit FirmwareStatusNotification(Installed) after Installing (per §4.5)
9 9bf26d0b fix(ocpp/1.6) High H3 SendLocalList: Failed (not NotSupported) when disabled/unavailable (per §5.15)
10 93c25d28 chore(auth) M19 Remove OCPPAuthServiceImpl concrete class from public barrel

Highlights

Commit 1 — GetDiagnostics comma-operator bug (Critical, spec-anchored)

handleRequestGetDiagnostics called resolve() with an extra pair of parentheses that turned the argument list into a comma-operator expression evaluating to only its last argument: resolve((fileURLToPath(import.meta.url), '../', dirname(logFile))) collapsed to resolve(dirname(logFile)). When the process CWD is not the project root, readdirSync scanned the wrong directory and produced an incomplete diagnostics archive. Aligned with the sibling call at line 1183 which already uses the intended resolve(dirname(fileURLToPath(import.meta.url)), '../', ...) pattern.

Commit 2 — sqrt(3) line-to-line voltage physics fix (Critical, physics)

Two sites derived L-L nominal voltage from Math.sqrt(numberOfPhases) * V_LN. The V_LL / V_LN ratio in a balanced 3-phase Y system is a fixed sqrt(3) from the 30-degree phase separation (V_LL = 2·V_LN·sin(60°) = √3·V_LN), NOT a function of the phase count. Both call sites are currently reachable only when numberOfPhases === 3, so the numerical value is unchanged today, but the formula was a trap: any future relaxation of the 3-phase guard would silently emit √2·V_LN at N=2. Replaced with Math.sqrt(3) at both sites + physics-anchor comment.

Commit 7 — DataTransfer §4.3 spec conformance (Critical)

Per OCPP 1.6 §4.3, UnknownMessageId is reserved for the case where the vendor is known but the messageId is not recognized. handleRequestDataTransfer previously returned UnknownMessageId for any non-null messageId, rejecting every legitimate DataTransfer with a messageId regardless of whether the messageId would have been supported. The simulator does not maintain a per-vendor messageId registry, so the spec-correct behaviour is Accepted once the vendor matches. The existing regression test that locked in the buggy behaviour was rewritten.

Commit 8 — FirmwareStatusNotification(Installed) (§4.5)

updateFirmwareSimulation emitted intermediate statuses (Downloading → Downloaded → Installing) but never signalled successful completion. Inserted the missing Installed status emission between the InstallationFailed early-return branch and the optional reset step. The failure path is unchanged.

Commit 9 — SendLocalList Failed vs NotSupported (§5.15)

Per §5.15, NotSupported = feature not implemented; Failed = feature implemented but the specific operation failed. The handler correctly returned NotSupported when the LocalAuthListManagement profile is absent but also returned NotSupported when LocalAuthListEnabled=false and when getLocalAuthListManager() returned null — both scenarios describe an implemented feature that cannot apply this particular update. Changed to Failed at both guards; two existing tests updated to assert the spec-correct outcome.

Commit 10 — Barrel hygiene

OCPPAuthServiceImpl (concrete implementation) was exported from ocpp/auth/index.js alongside the OCPPAuthService interface and OCPPAuthServiceFactory. Concrete impls should not be part of the public barrel API — callers should go through the factory. Removed from the barrel; two test files that imported it via the barrel routed to the direct path. Side effect: skott circular-dependency count drops from 62 to 61 because the Factory ↔ Impl loop no longer traverses the barrel.

Findings deferred to follow-up PRs (with rationale)

The from-zero audit surfaced ~63 findings across the 5 lanes. This PR lands the highest-value, lowest-risk subset: all 4 Criticals, 3 High spec fixes (H1, H3, C3-adjacent), 6 harmonization Mediums (M1, M2, M3, M8, M19, M20). The remaining findings are deferred to targeted follow-up PRs because each has one or more of: behavioural risk requiring integration testing, deep type-narrowing touching hundreds of sites, or large-surface refactor deserving its own review scope.

Deferred OCPP spec fixes (require integration testing against a real CSMS):

  • C2 — ocppStrictCompliance === false bypasses the §4.2 "SHALL NOT send unsolicited" restriction in Pending state. Fix is a targeted gate change but affects every non-BootNotification outbound call path during boot.
  • H2 — stopTransactionOnConnector (non-remote path) does not emit StatusNotification(Finishing) before StopTransaction.req (§5.12). Emission ordering fix.
  • H4 — ChangeAvailability with a running transaction correctly returns Scheduled but the deferred StatusNotification after transaction end is never triggered (§5.2). Requires wiring the deferred availability change into handleResponseStopTransaction.
  • H5 — MeterValues at stop time is sent as a separate MeterValues request; §5.12 says it SHOULD be embedded in StopTransaction.transactionData. Payload structure change.
  • H6 — RemoteStart auto-select of a free connector does not skip connectors reserved for a different idTag. Reservation-precedence fix.

Deferred TS/JS refactors:

  • H7 — ~15 as unknown as X casts across the OCPP request/response dispatch layer. Root cause: Request/Response union types are too wide; narrowing them per-command eliminates the casts but touches every OCPP command handler.
  • H8 — 7+ console.* calls in production code (ErrorUtils, WorkerUtils, Configuration, ConfigurationValidation, start.ts) should use logger.*. Simple mechanical replacement except in the process-lifecycle handlers where the logger may not be initialised.
  • H9 — 3 untracked setTimeout handles in OCPP20IncomingRequestService and OCPP16IncomingRequestService cannot be cancelled on station stop. Requires storing handles in the class and clearing them in stop().
  • H10 — 6+ definite-assignment ! fields on ChargingStation are assigned in initialize() not the constructor. Refactor to T | undefined or initialise in the constructor.
  • H11 — 2 silent .catch(() => undefined) chains in AbstractUIServer swallow errors. Add logger.warn(...) in the catch.

Deferred design refactors (each deserves its own PR):

  • H12 — Split src/utils/Utils.ts (557 LOC, grab-bag) into TimeUtils / RandomUtils / JsonUtils / PromiseUtils / NumberUtils.
  • H13 — Split src/charging-station/HelpersChargingProfile.ts (727 LOC) into ChargingProfileSchedule / ChargingProfileLimit / ChargingProfileRecurrence.
  • H14 — Split src/charging-station/AutomaticTransactionGenerator.ts (555 LOC): peel run loop and stats bookkeeping into siblings.
  • H15 — Extract per-measurand emitters from buildMeterValue (300 lines) into dedicated helpers.

Deferred algorithmic robustness:

  • H16 + H17 — AutomaticTransactionGenerator.ts: replace uncancellable await sleep(waitTrxEnd) with an AbortSignal-aware wait so stopConnector observes the flag promptly; add up-front validation of minDelay <= maxDelay (currently a mis-configured template kills the run loop with an unhandled rejection at the first iteration).

Deferred content cleanup (bulk, low signal):

  • M4 + M5 + M6 — Rework the ~63 imperative / redundant / narrative comments in production code (5 in OCPPRequestService.ts, 6 in ChargingStation.ts WebSocket handlers, ~40 in the auth subsystem, 5 in HelpersChargingProfile). Bulk mechanical.
  • M11 — Add JSDoc to 11 public/abstract methods on OCPPRequestService, OCPPResponseService, and OCPPIncomingRequestService base classes.
  • M13 — voltageOut template value is treated as line-to-neutral, but users typically configure 400 V (a line-to-line rated value); documented ambiguity but not surfaced with a runtime warning. Behaviour-sensitive.

Withdrawn on re-inspection:

  • Rename OCPPAuthServiceImpl → the Impl suffix is the only Java-style suffix in the codebase but it also correctly indicates 'the sole default implementation of the interface'. Keeping the name; only the barrel export was removed (M19).

Verification

Full documented gates re-run against the final tip of the branch:

Package format typecheck lint build test
root ✅ ✅ ✅ ✅ ✅ 2955 pass / 0 fail / 6 skipped
ui/cli ✅ ✅ ✅ ✅ ✅ 152 pass / 0 fail
ui/web ✅ ✅ ✅ ✅ ✅ 532 pass / 0 fail (via test:coverage)

Skott circular-dependency count: 62 → 61 (one cycle eliminated by commit 10).

`handleRequestGetDiagnostics` called `resolve()` with the comma operator
by accident:

  resolve((fileURLToPath(import.meta.url), '../', dirname(logFile)))

The extra parentheses wrap a comma-operator expression that evaluates to
`dirname(logFile)` only, so `readdirSync` was invoked with a
directory resolved from CWD instead of relative to the module URL. When
the process CWD is not the project root (e.g. a systemd service, a docker
container that mounts logs elsewhere, a background worker with a chdir'd
parent), the log-file discovery scanned the wrong directory and produced
an incomplete diagnostics archive.

Align with the sibling call at line 1183 which already uses the intended
pattern:

  resolve(dirname(fileURLToPath(import.meta.url)), '../', diagnosticsArchive)

Both call sites now resolve paths relative to the module's parent
directory. Gates pass (typecheck / lint).
Two sites derived the line-to-line nominal voltage from Math.sqrt(numberOfPhases) * V_LN:

- src/charging-station/ocpp/OCPPServiceUtils.ts:1255
- src/charging-station/meter-values/CoherentMeterValueBuilder.ts:282

The ratio V_LL / V_LN in a balanced 3-phase Y system is a fixed sqrt(3),
which comes from the 30-degree phase separation between line and neutral
voltages (V_LL = 2 * V_LN * sin(60 deg) = sqrt(3) * V_LN). It is NOT a
function of the phase count.

Both call sites are currently reachable only when numberOfPhases === 3
(one guarded explicitly at CoherentMeterValueBuilder.ts:281; the other
implicitly via the phaseLineToLineVoltageMeterValues + phase-rotation
plumbing that only supports 3-phase). Numerically the emitted value is
unchanged, but the formula was a trap: any future relaxation of the
3-phase guard would silently emit sqrt(2) * V_LN at N=2, which is
physically meaningless.

Replace both call sites with Math.sqrt(3) and add a code comment stating
the physics derivation so the constant cannot be re-parameterized on the
phase count.

Gates pass (typecheck / test, 2955 pass / 0 fail).
The recently-added auth subsystem used bare 'OCPP 2.0' throughout its
comments and JSDoc while the rest of the codebase (README, AGENTS.md,
all other source files) uses 'OCPP 2.0.1' as the canonical spec version
and 'OCPP 2.0.x' as the family. The auth subsystem also used non-existent
forms 'OCPP 2.0+' and 'OCPP 2.0/2.1' that misrepresented the supported
spec range: OCPP 2.1 is not implemented.

Bulk-replace across src/charging-station/ocpp/auth/:
- 'OCPP 2.0+'   -> 'OCPP 2.0.1'
- 'OCPP 2.0/2.1' -> 'OCPP 2.0.1'
- bare 'OCPP 2.0' -> 'OCPP 2.0.1'  (negative lookahead on '.digit' so
  existing 'OCPP 2.0.1' and 'OCPP 2.0.x' occurrences are preserved)

65 occurrences updated across 5 files. Files touched:
- adapters/OCPP20AuthAdapter.ts   (31)
- types/AuthTypes.ts              (21)
- strategies/CertificateAuthStrategy.ts (7)
- utils/AuthValidators.ts         (5)
- strategies/RemoteAuthStrategy.ts (1)

Zero code behavior change; comment/JSDoc content only.
Gates pass (typecheck / lint).
…s and docs

Two mismatches surfaced against OCPP 2.0 counterparts:

1. `csmsName` field values in OCPP16IncomingRequestService.ts:176 and
   OCPP16ResponseService.ts:129 held the lowercase two-word form
   'central system'. The abstract base classes interpolate this field
   into runtime error messages, producing 'not registered on the central
   system' for OCPP 1.6 versus 'not registered on the CSMS' for OCPP
   2.0. Two spec-correct forms are involved (OCPP 1.6 uses 'Central
   System'; OCPP 2.0.1 uses 'CSMS' for 'Charging Station Management
   System'), so keep the spec-correct term per version but capitalize
   the 1.6 value to match OCPP 1.6 spec convention.

2. JSDoc prose across OCPP 1.6 files ('sends X to the central system',
   'response from the central system', etc.) mixed the lowercase form
   with the capitalized 'Central System (CS)' used in the module-level
   docstring of OCPP16IncomingRequestService.ts. Normalize to the
   capitalized form throughout src/charging-station/ocpp/1.6/.

Zero code behavior change; only logged strings and comment prose shift
casing. Gates pass (typecheck / lint).
… constants

Numeric-literal style was inconsistent: OCPP20Constants.ts uses
underscore separators for readability (e.g. `30_000`, `5_000`),
while src/utils/Constants.ts and other constants files used bare
literals (`60000`, `30000`, `1048576`).

Apply underscore separators uniformly to 5+ digit numeric literals
across the constants files, matching the OCPP20Constants.ts precedent:

- src/utils/Constants.ts: `60000` -> `60_000` (6 sites),
  `30000` -> `30_000`, `281474976710655` -> `281_474_976_710_655`,
  `2147483647` -> `2_147_483_647`.
- src/charging-station/ocpp/OCPPConstants.ts:
  `OCPP_WEBSOCKET_TIMEOUT_MS = 60000` -> `60_000`.
- src/charging-station/ui-server/UIServerSecurity.ts:
  `DEFAULT_MAX_PAYLOAD_SIZE_BYTES = 1048576` -> `1_048_576`,
  `DEFAULT_RATE_WINDOW_MS = 60000` -> `60_000`,
  `DEFAULT_MAX_TRACKED_IPS = 10000` -> `10_000`.

4-digit values (1000, 3600, 5000, 8080) are intentionally left unchanged;
they include port literals (`DEFAULT_UI_SERVER_PORT = 8080`) where the
underscore form is unusual. AGENTS.md numeric-literal style is a
readability convention rather than an enforced rule; applying it only
above the 5-digit threshold matches the existing OCPP20Constants.ts
pattern.

Zero code behavior change. Gates pass (typecheck / lint / test, 2955
pass / 0 fail).
…E table

Two low-risk harmonization findings from the from-zero audit.

1. README OCPP 2.0.x commands table missing 'Authorize' (Lane 5 M2)
   The 'Authorize' command is fully implemented for OCPP 2.0.x:
   - OCPP20RequestCommand.AUTHORIZE registered
   - OCPP20RequestService.ts / OCPP20ResponseService.ts handlers wired
   - OCPP20ServiceUtils.ts sending helper
   but the README '#### C. Authorization' section listed only 'ClearCache'.
   Add ':white_check_mark: Authorize' alongside 'ClearCache' so the docs
   match the actual implementation surface.

2. Extract WILDCARD_HOSTS set (Lane 4 M20)
   AbstractUIServer.ts:1325 inlined the three literals '', '0.0.0.0', '::'
   as a triple '===' chain to detect wildcard host configuration, while
   UIServerAccessPolicy.ts:23 already held the same three values in a
   module-scoped 'WILDCARD_HOSTS' set. Two independent definitions of
   the same domain concept.
   Export WILDCARD_HOSTS (typed 'ReadonlySet<string>') from
   UIServerAccessPolicy.ts, import it in AbstractUIServer.ts, and
   replace the inline OR chain with 'WILDCARD_HOSTS.has(configuredHost)'.

Zero behavior change. Gates pass (typecheck / lint).
…and messageId

Per OCPP 1.6 §4.3, the DataTransfer response statuses are:
- `UnknownVendorId` when the vendorId is not recognized
- `UnknownMessageId` when the vendorId is recognized but the messageId
  is not
- `Accepted` when both vendor and message are recognized

`handleRequestDataTransfer` previously returned `UnknownMessageId` for
*any* non-null messageId, even when the vendorId matched the station's
configured `chargePointVendor`:

    if (vendorId !== chargingStation.stationInfo?.chargePointVendor) {
      return ... UNKNOWN_VENDOR_ID
    }
    if (messageId != null) {
      return ... UNKNOWN_MESSAGE_ID     // wrong: any non-null messageId
    }

That rejected every legitimate DataTransfer with a messageId, regardless
of whether the messageId would have been supported. The simulator does
not maintain a per-vendor messageId registry (it has no way to know
which custom messageIds a real charge point would accept), so the
spec-correct behaviour is to accept any messageId once the vendor
matches.

Drop the erroneous `messageId != null` branch and return `Accepted`
whenever the vendor matches; the `UnknownVendorId` path is unchanged.
Add a source comment citing OCPP 1.6 §4.3 to prevent regression of the
buggy check.

Test update: the existing 'should return UnknownMessageId for matching
vendor with messageId' test asserted the old buggy behaviour. Rewritten
as 'should return Accepted for matching vendor with messageId (no
messageId registry per §4.3)' to lock in the spec-correct outcome.

Gates pass (typecheck / test, 2955 pass / 0 fail).
…lling

Per OCPP 1.6 §4.5, the Charge Point SHALL notify the CSMS of firmware
update progress via FirmwareStatusNotification. `updateFirmwareSimulation`
already emitted the intermediate statuses (Downloading -> Downloaded ->
Installing) but never signalled successful completion — after emitting
`Installing`, the simulation went straight to the optional reset step
(if configured) or returned, leaving the CSMS with no confirmation
that installation actually finished.

Insert an `Installed` status emission between the InstallationFailed
early-return branch and the optional reset:

    sleep(...)
    requestHandler(FIRMWARE_STATUS_NOTIFICATION, { status: Installed })
    stationInfo.firmwareStatus = Installed
    if (reset === true) { sleep(...); reset() }

Behaviour on the failure path is unchanged: the InstallationFailed
branch still returns early without emitting `Installed`. Behaviour
when `reset` is disabled is unchanged apart from the additional
notification (which is the whole point of the fix).

Gates pass (typecheck / test, 2935 pass / 0 fail).
… disabled or manager missing

Per OCPP 1.6 §5.15, the SendLocalList response statuses have distinct
semantics:
- NotSupported: the LocalAuthListManagement feature profile is not
  implemented by the Charge Point
- Failed: the feature is implemented but the specific update failed
  (disabled, unavailable, or otherwise unable to apply the change)

`handleRequestSendLocalList` correctly returned NotSupported when the
LocalAuthListManagement profile is absent (line 1534). But two
subsequent guards also returned NotSupported when:
- `LocalAuthListEnabled` config is false (feature supported but disabled)
- `getLocalAuthListManager()` returns null (feature supported but manager
  not wired)

Both scenarios describe a Charge Point that supports the feature — the
LocalAuthListManagement profile is present — but cannot apply this
particular update. Per spec, that is Failed, not NotSupported.

Change both guards to return
`OCPP16Constants.OCPP_SEND_LOCAL_LIST_RESPONSE_FAILED`. The profile-
absent guard (line 1534) is unchanged — it correctly reports
NotSupported when the feature is not implemented at all.

Test updates: two existing tests locked in the old NotSupported result.
Renamed and updated to assert Failed with an inline reference to §5.15
so the spec-correct outcome is regression-locked.

Gates pass (typecheck / test, 2945 pass / 0 fail).
`OCPPAuthServiceImpl` is the concrete implementation of the
`OCPPAuthService` interface. External code should construct instances
through `OCPPAuthServiceFactory` (which internally uses the class)
rather than instantiating it directly. Exporting the concrete class
from the auth barrel published an implementation detail that:

- Adds public API surface with no consumer benefit
- Encourages callers to bypass the factory's per-station singleton
- Complicates future refactoring of the concrete class

Grep across src/ and ui/ confirms zero consumers of
`OCPPAuthServiceImpl` via the barrel (`ocpp/auth/index.js`); the
factory imports it via the direct file path within the same subtree.
Two test files (`OCPP20ResponseService-CacheUpdate.test.ts`,
`OCPP20ServiceUtils-AuthCache.test.ts`) did import it via the barrel;
routed to the direct path so they still exercise the concrete class
where explicitly needed.

Also correct the module-level JSDoc from 'OCPP 1.6 and 2.0' to
'OCPP 1.6 and 2.0.1' to match the canonical spec-version convention
used throughout the codebase.

Gates pass (typecheck / lint / test, 2955 pass / 0 fail).
@hyperspace-pr-bot

Copy link
Copy Markdown
Contributor

Summary

The following content is AI-generated and provides a summary of the pull request:


OCPP Spec Conformance Fixes, Physics Correction & Code Harmonization

This PR delivers a comprehensive audit-driven set of fixes and improvements across the OCPP simulator codebase, addressing critical spec violations, physics errors, and code quality improvements.

Does this PR introduce a breaking change?

  • Yes
  • No

🐛 Bug Fixes

Critical OCPP 1.6 Spec Fixes:

  • GetDiagnostics path bug — Fixed a comma-operator expression resolve((fileURLToPath(import.meta.url), '../', dirname(logFile))) that collapsed to only resolve(dirname(logFile)), causing diagnostics to scan the wrong directory when CWD ≠ project root.
  • DataTransfer §4.3 conformance — handleRequestDataTransfer previously returned UnknownMessageId for any non-null messageId. Per spec, UnknownMessageId is reserved for known vendor + unrecognized messageId. Since the simulator has no per-vendor messageId registry, it now correctly returns Accepted when the vendor matches.
  • FirmwareStatusNotification §4.5 — updateFirmwareSimulation emitted intermediate statuses (Downloading → Downloaded → Installing) but never sent Installed. The missing Installed status emission is now added after the InstallationFailed branch.
  • SendLocalList §5.15 — Correctly distinguishes NotSupported (feature not implemented) from Failed (feature implemented but operation failed). Now returns Failed when LocalAuthListEnabled=false or when the list manager is unavailable.

Physics Fix:

  • Line-to-line voltage — Replaced Math.sqrt(numberOfPhases) * V_LN with Math.sqrt(3) * V_LN at two sites. The V_LL/V_LN ratio in a balanced 3-phase Y system is a fixed √3 from the 30-degree phase separation, not a function of phase count. Added explanatory physics comment at both sites.

♻️ Refactors & Harmonization

  • OCPP version strings — Corrected ~65 occurrences of bare OCPP 2.0 → OCPP 2.0.1 across the auth subsystem (adapters, types, strategies, validators).
  • Capitalization — 'central system' → 'Central System' throughout OCPP 1.6 services and test interfaces (spec-correct per OCPP 1.6 terminology).
  • Numeric separators — Applied underscore separators to all 5-digit+ numeric literals (60000 → 60_000, 2147483647 → 2_147_483_647, etc.) across Constants.ts, OCPPConstants.ts, and UIServerSecurity.ts.
  • WILDCARD_HOSTS extraction — Extracted the inline wildcard host set from AbstractUIServer into a named exported constant in UIServerAccessPolicy.ts, eliminating duplication.
  • Barrel hygiene — Removed OCPPAuthServiceImpl (concrete class) from the public ocpp/auth/index.ts barrel. Callers should use OCPPAuthServiceFactory. Two test files updated to import directly from the implementation path. Side effect: reduces skott circular-dependency count from 62 → 61.
  • README — Added Authorize to the OCPP 2.0.x supported operations table.

✅ Tests Updated

  • OCPP16IncomingRequestService-LocalAuthList.test.ts — Two tests updated to assert Failed (not NotSupported) for disabled/unavailable local auth list scenarios.
  • OCPP16IncomingRequestService-SimpleHandlers.test.ts — DataTransfer test rewritten to assert Accepted for matching vendor + messageId (was incorrectly asserting UnknownMessageId).

  • 🔄 Regenerate and Update Summary
  • ✏️ Insert as PR Description (deletes this comment)
  • 🗑️ Delete comment
PR Bot Information

Version: 1.27.0

  • LLM: anthropic--claude-4.6-sonnet
  • Output Template: Repository PR Template
  • Summary Prompt: Default Prompt
  • Event Trigger: pull_request.opened
  • Correlation ID: 0e7e7870-7950-11f1-9dea-58af54626f75
  • File Content Strategy: Full file content

@hyperspace-pr-bot hyperspace-pr-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR is well-structured and addresses real correctness issues. The most impactful fixes — the resolve() comma-operator bug (commit 1), the sqrt(3) physics correction (commit 2), and the missing FirmwareStatusNotification(Installed) emission (commit 8) — are all solid. The one new issue I found: after adding Installed to the firmware status state machine, the TriggerMessage(FirmwareStatusNotification) handler still only passes through Downloading | Downloaded | Installing, so it will incorrectly report Idle when firmwareStatus === Installed. This should be fixed in tandem with commit 8.

PR Bot Information

Version: 1.27.0

Comment on lines +1937 to +1938
if (chargingStation.stationInfo != null) {
chargingStation.stationInfo.firmwareStatus = OCPP16FirmwareStatus.Installed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logic Error: TriggerMessage(FirmwareStatusNotification) does not reflect the new Installed status

After this PR adds the Installed emission to updateFirmwareSimulation, the firmwareStatus field can now hold Installed. However, the TRIGGER_MESSAGE event handler only treats Downloading, Downloaded, and Installing as passthrough values — falling back to Idle for everything else. A TriggerMessage(FirmwareStatusNotification) received while the station is in the Installed state will incorrectly report Idle.

Should add OCPP16FirmwareStatus.Installed to the passthrough condition.

Suggested change
if (chargingStation.stationInfo != null) {
chargingStation.stationInfo.firmwareStatus = OCPP16FirmwareStatus.Installed
if (chargingStation.stationInfo != null) {
chargingStation.stationInfo.firmwareStatus = OCPP16FirmwareStatus.Installed
}

Double-check suggestion before committing. Edit this comment for amendments.


Please provide feedback on the review comment by checking the appropriate box:

  • 🌟 Awesome comment, a human might have missed that.
  • ✅ Helpful comment
  • 🤷 Neutral
  • ❌ This comment is not helpful

…s physics comment

Two round-3 review findings from PR #1960 self-review addressed together.

1. Round-3 High: terminology scope creep

Prior commit dbc3f3f bulk-replaced OCPP 2.0 -> OCPP 2.0.1 in
src/charging-station/ocpp/auth/ only (65 occurrences). Identical drift
existed across the rest of the OCPP 2.0.x code paths, including the
invalid OCPP 2.0+ form that dbc3f3f had explicitly corrected in auth/
but left intact in ~10 sites of OCPP20IncomingRequestService JSDoc.
After dbc3f3f, auth/ said OCPP 2.0.1 while the rest of the OCPP 2.0.x
subtree still said OCPP 2.0 / OCPP 2.0+ — the terminology divergence
was worse, not better.

Apply the same three-pass perl regex (strip +, collapse /2.1,
negative-lookahead on .digit for bare 2.0) to:

- src/charging-station/ocpp/2.0/**/*.ts               (56 occurrences)
- src/charging-station/ocpp/OCPPServiceUtils.ts       (3)
- src/charging-station/ui-server/UIMCPServer.ts       (2)
- ui/common/tests/payloadBuilders.test.ts             (2)

63 total substitutions. Zero code behavior change; comment/JSDoc/test
description content only. Zero remaining bare OCPP 2.0 refs under the
scanned scope.

2. Round-3 Low: physics comment verbosity

The sqrt(3) physics anchor comment added in commit 34a574f spanned 8
lines with tangential explanations. Compress to 3 lines that keep the
essential physics anchor (V_LL = sqrt(3) * V_LN, 30-degree phase
separation, 3-phase-only constraint).

Documented as still-deferred:
- Narrative comment at OCPP16IncomingRequestService.ts:276 — kept under
  M5 bulk cleanup deferral.
- OCPP 2.0.x handleRequestDataTransfer UnknownVendorId design — a
  different intentional choice, not the same bug as OCPP 1.6 C3.

All gates green (format / typecheck / lint / build / test) across root,
ui/cli, ui/web. Circular-deps baseline of 61 preserved.
…cs comment line

Round-4 review findings from PR #1960 self-review addressed together.

1. Terminology sweep completion (Low)

The round-3 extension (commit e03368f) covered
src/charging-station/ocpp/2.0/**, OCPPServiceUtils.ts, UIMCPServer.ts,
and payloadBuilders.test.ts, but the audit's terminology finding
applied to the whole codebase. Four bare 'OCPP 2.0' refs survived in
charging-station/ files outside ocpp/2.0/:

- src/charging-station/ConfigurationKeyUtils.ts:
  user-facing warning 'use OCPP 2.0 variable ... instead'
- src/charging-station/meter-values/CoherentMeterValueBuilder.ts:
  code comment 'Narrow the OCPP 2.0 SampledValueTemplate.unit ...'
- src/charging-station/TemplateSchema.ts (2 sites):
  JSDoc references to 'OCPP 2.0 unit-of-measure descriptor' and
  'OCPP 2.0 namespaced keys'

Apply the same negative-lookahead perl regex; 4 substitutions, zero
code behaviour change. The user-facing warning in ConfigurationKeyUtils
now cites the spec version consistently with the rest of the codebase.

2. Physics comment redundancy (Info)

The compressed sqrt(3) anchor comment from commit e03368f sat
directly below a preexisting one-liner ('Line-to-line voltage is only
defined for 3-phase AC') that duplicated the L-L === 3-phase constraint
already stated in the compressed block ('Defined only for numberOfPhases
=== 3'). Delete the preexisting redundant line; the compressed anchor
carries the full physics rationale (V_LL = sqrt(3) * V_LN, 30-degree
phase separation, 3-phase-only constraint).

Test files (~15 refs of 'OCPP 2.0' as describe/it group labels) are
intentionally left as-is: those are test-grouping labels rather than
spec-version references, and renaming them would break dev-side test
regex filters without functional benefit.

Gates green (format / typecheck / lint / build / test) across root;
ui/cli and ui/web untouched. Circular-deps baseline of 61 preserved.
@jerome-benoit jerome-benoit changed the title from-zero audit — OCPP spec conformance fixes + physics + harmonization refactor: audit-driven cleanup — OCPP conformance fixes, physics, harmonization Jul 6, 2026
@jerome-benoit
jerome-benoit merged commit f8d8e03 into main Jul 6, 2026
44 checks passed
@jerome-benoit
jerome-benoit deleted the from-zero-audit-2 branch July 7, 2026 00:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant