feat: resolve #314 — Add charging station template Zod validation with schema versioning (#1860)
* feat: add charging station template Zod validation with schema versioning
Add Zod v4 runtime validation for charging station templates with
schema versioning support. This replaces scattered imperative checks
with a declarative schema pipeline that validates, migrates, and
transforms templates at parse time.
New files:
- TemplateMigrations.ts: CURRENT_SCHEMA_VERSION, coerceVersion(),
migration registry with migrateV0ToV1()
- TemplateSchema.ts: Zod schemas with topology union, loose + strict
variants, MeterValues value coercion (number -> string)
- TemplateValidation.ts: validateTemplate() pipeline,
transformTemplate(), TemplateValidationError
Integration:
- getTemplateFromFile() now calls validateTemplate() instead of bare
JSON.parse(...) as ChargingStationTemplate
- Cache key updated to hash:vN format incorporating schema version
- Removed checkTemplate(), checkConnectorsConfiguration(),
checkEvsesConfiguration(), warnTemplateKeysDeprecation() from
Helpers.ts (logic absorbed into schema/pipeline)
- Exported getConfiguredMaxNumberOfConnectors and
getMaxNumberOfConnectors from Helpers.ts for connector setup
Template changes:
- Added "$schemaVersion": 1 to all 15 template JSON files
- coerceVersion(null|undefined) now returns 0 so legacy templates
without $schemaVersion go through v0->v1 migration; deprecated keys
(supervisionUrl, authorizationFile, payloadSchemaValidation,
mustAuthorizeAtRemoteStart) are renamed instead of being silently
swallowed by looseObject [HIGH]
- transformTemplate uses Math.max(numberOfConnectors[]) as the
worst-case bound for the randomConnectors auto-trigger; new
Helpers.ts pair getMaxConfiguredNumberOfConnectors (deterministic
upper bound) and pickConfiguredNumberOfConnectors (random pick)
centralize array semantics; getConfiguredMaxNumberOfConnectors now
delegates to pickConfiguredNumberOfConnectors [HIGH]
- BaseTemplateSchema.$schemaVersion is now z.literal(CURRENT_SCHEMA_VERSION)
(post-migration assertion); deprecated keys removed from the v1
schema and explicitly rejected by a superRefine block with a clear
diagnostic [MEDIUM]
- transformTemplate drops the unreachable templateMaxConnectors < 0
branch [LOW]
- validateTemplate widens to accept unknown and rejects null,
non-plain-object and array payloads with a clear BaseError instead
of crashing later in coerceVersion [LOW]
- SignedMeterValueSchema, UnitOfMeasureSchema and WsOptionsSchema
replace z.looseObject({}) with typed shapes plus .catchall(z.unknown())
for forward-compatible vendor extensions [LOW]
- TemplateValidationError now surfaces '(migrated from vX -> vY)' in
its message so post-migration validation failures are visible to
operators
Tests: update coerceVersion(null|undefined) expectation to 0; add
end-to-end legacy migration, deprecated-key rejection (Schema and
Validation layers), null/string/array payload guards, array-form
numberOfConnectors auto-trigger regression, dead-branch regression,
migratedFrom message presence, and unit tests for the two new
Helpers.ts helpers.
- normalize $schemaVersion to coerced integer in validateTemplate so the
no-migration path (when version === CURRENT) also satisfies the strict
z.literal(CURRENT_SCHEMA_VERSION) check; was failing for user-authored
templates with string "$schemaVersion": "1" [F1]
- harmonize coerceVersion error wording on "non-negative integer" across
all rejection branches; the previous "positive integer" message was
contradictory since 0 is a valid input (legacy/pre-versioning sentinel
triggering v0 migration) [F2]
- introduce SCHEMA_VERSION_STRING_PATTERN (^\\d+$) gate in coerceVersion
to reject permissive Number() coercions ('1.0', '0x1', '1e0', ' 1 ',
'', '+1', '01a'); pattern mirrors the canonical non-negative-integer
string pattern used in TemplateSchema for connector/EVSE keys [F6]
- replace for...in with Object.entries destructuring in Evses topology
validation, harmonizing with the prior-art pattern in Helpers.ts and
removing the redundant template.Evses[evseKey] re-lookup [F3]
- tighten getMaxConfiguredNumberOfConnectors cast to readonly number[]
matching the helper signature [F5/F7]
- document the cache-bound warning emission frequency in
transformTemplate's JSDoc: warnings fire once per (templateFile,
schemaVersion) cache miss rather than per station instance, which is
template-scoped on purpose [F4]
Tests: assert string "$schemaVersion": "1" is accepted and normalized
to numeric 1; battery of 8 permissive numeric strings rejected with
harmonized wording; coerceVersion rejection branches all use the same
"non-negative integer" diagnostic.
* fix(template): broaden wsOptions.headers and harden template pipeline
- templateHash uses SRI-style `${algorithm}:${schemaVersion}:${contentHash}`
computed over the validated template, restoring whitespace-insensitive
cache semantics from pre-PR main while keeping schema-version-bump
invalidation deterministic.
- Migration registry refactored to sequential n→n+1 chain so future
schema versions append one function instead of rewriting prior
migrations (no behavior change at v1).
- validateTemplate clones its input via structuredClone at the
validation boundary, honoring the repository immutability convention.
BREAKING CHANGE: external log monitors keyed on the literal string
"Failed to read charging station template file" must also match
"Invalid charging station template payload (not a JSON object)" for
JSON-shape errors; file I/O errors retain their previous wording via
handleFileException.
* test: extract mockLoggerWarnDebug helper to dedupe migration logger spies
Replaces 8 occurrences of the warn+debug t.mock.method pair across
TemplateMigrations.test.ts and TemplateValidation.test.ts with a typed
helper sibling to createLoggerMocks.
* chore(deps): deduplicate pnpm-lock entries for @rolldown/pluginutils and ws
feat: resolve #1020 — Persist minimal simulator state and reconstruct template indexes on startup (#1858)
* feat: persist minimal simulator state and reconstruct template indexes on startup
- Add persistState boolean to ConfigurationData (default: true)
- Add SimulatorState to FileType enum
- Add simulatorState to AsyncLockType enum
- Implement BootstrapStateUtils with:
- readStateFile: reads and validates state.json with schema version check
- writeStateFile: atomic write via tmp+rename with AsyncLock
- reconstructTemplateIndexes: scans per-station config files to rebuild indexes
- deleteStateFile: safe file deletion
- Integrate into Bootstrap:
- reconstructTemplateIndexes called in start() before worker spawn
- State file written on start() (started:true) and stop() (started:false)
- shouldAutoStart() reads state file to control auto-start behavior
- persistStateEnabled getter checks persistState config and SIMULATOR_COLD_START env
- Update start.ts to conditionally start based on shouldAutoStart()
- Handle edge cases: corrupt files, missing fields, incompatible schema version
- Add comprehensive tests for all state persistence and reconstruction scenarios
Closes #1020
* refactor(bootstrap): harmonize persisted state feature with codebase conventions
Address review findings on PR #1858:
- HIGH #1: Phase split start() lifecycle. Add public Bootstrap.startUIServer()
that always brings up the UI server (and reconstructs template indexes
before accepting requests). start.ts unconditionally calls startUIServer()
and only gates Bootstrap.start() on shouldAutoStart(), so a persisted
stopped state no longer turns the simulator into a zombie process.
- HIGH #2: Add canonical default. New defaultPersistState constant and
Configuration.getPersistState() accessor matching the existing
defaultUIServerConfiguration / defaultWorkerConfiguration pattern.
Bootstrap.persistStateEnabled now delegates instead of inlining ?? true.
- MEDIUM #3: Document persistState tunable and SIMULATOR_COLD_START
environment override in README.md.
- MEDIUM #4: writeStateFile and deleteStateFile now swallow filesystem
errors via handleFileException with throwError:false, mirroring
watchJsonFile and the storage layer. Persistence failures no longer
surface as misleading 'Startup error' / 'Shutdown error'.
- MEDIUM #5: reconstructTemplateIndexes runs inside startUIServer() before
uiServer.start(), closing the race where UI requests could arrive before
index reconstruction completes.
- LOW #7: Add formatLogPrefix() utility and use it in BootstrapStateUtils,
removing the leading-space artifact when logPrefixFn is undefined.
- LOW #8: On state file schema mismatch, quarantine to <path>.v<N>.bak
instead of silently deleting, allowing forensics during partial schema
rollouts. JSON parse errors still delete (true corruption, unrecoverable).
- LOW #9: Move state.json from dist/assets/configurations/ to dist/assets/.
Drops the fragile basename-based filter from reconstructTemplateIndexes
and separates control file from per-station configuration files.
Drop shouldAutoStart() from IBootstrap interface (boot-time concern, no UI
service consumer needs it). The method stays public on the concrete
Bootstrap class for start.ts.
Tests: align fixtures with new state.json location, add quarantine assertion,
add non-fatal writeStateFile assertion, drop obsolete state.json filter test.
* test(bootstrap): align BootstrapStateUtils tests with project style guide
- Rename BootstrapState.test.ts to BootstrapStateUtils.test.ts to match the
source module name (TEST_STYLE_GUIDE.md §1: 'Files: ModuleName.test.ts').
- Add mandatory standardCleanup() in afterEach (TEST_STYLE_GUIDE.md §3),
matching the convention used by Configuration.test.ts, FileUtils.test.ts,
ErrorUtils.test.ts and ConfigurationKeyUtils.test.ts.
* fix(bootstrap): address review findings on persisted simulator state
Distinguish UI-initiated stop from signal/restart via a private
StopReason enum, so SIGINT/SIGTERM/SIGQUIT and config-reload restarts
no longer flip the persisted state to stopped (HIGH-1).
Short-circuit persistStateEnabled when the UI server is disabled, since
persistence has no recovery channel without a UI; warn once on the
inconsistent configuration (HIGH-2).
Reconstruct template indexes via a shared prepareTemplateStatistics
helper called from constructor and restart, not only from startUIServer,
to prevent index collisions on config-reload of UI-added stations
(MED-3).
Move state file from dist/assets/state.json (wiped by pnpm build) to
dist/assets/configurations/.simulator-state.json; filter dot-prefixed
metadata files in reconstructTemplateIndexes so the state file co-located
with charging station configurations is silently skipped (MIN-10).
Clean up the .tmp file on atomic-rename failure in writeStateFile and
guard readStateFile against JSON null/primitive/array content with an
explicit message (MIN-7, MIN-8).
Unify path computations into readonly assetsDir/configurationsDir/
stateFilePath fields, deduplicate setChargingStationTemplates via a
syncUIServerTemplates helper, and route the SIMULATOR_COLD_START env
var name through Constants.ENV_SIMULATOR_COLD_START (MIN-5, MIN-6).
Export DEFAULT_PERSIST_STATE and add the persistState entry to
config-template.json so the tunable is discoverable (MED-4).
Update README to document the new state file path, the UI server
requirement, and the signal-shutdown semantics.
Test coverage added for tmp cleanup, JSON null/primitive/array guards,
and dot-prefixed metadata filtering; the misleading 'read-only
directory' test is renamed to reflect the actual OS-rejected-path
scenario (MIN-9).
* docs(bootstrap): clarify persisted state semantics from review feedback
- README: drop developer-internals sentence on template index reconstruction
from the persistState row
- TemplateStatistics: document the `added` (process-scoped) vs `indexes`
(process+disk-scoped) distinction exposed via SimulatorState
- IBootstrap: document the contract scope (UI-server-facing, excluding
process-lifecycle helpers and the internal StopReason)
- formatLogPrefix: document the trailing-space contract
- reconstructTemplateIndexes: refine the warn message wording for non-station
configuration files (level unchanged)
* refactor(utils): default formatLogPrefix prefix to logPrefix
Avoids silent loss of the timestamp when callers do not pass a module-specific
prefix function. Aligns with the existing convention where every module-level
logPrefix delegates to Utils.logPrefix.
Jérôme Benoit [Mon, 11 May 2026 19:20:30 +0000 (21:20 +0200)]
refactor: consolidate object-check utilities to eliminate duplication
Replace type() + isObject with a single isPlainObject helper.
Make isJsonObject and assertIsJsonObject delegate through it
instead of duplicating the check logic independently.
Jérôme Benoit [Mon, 11 May 2026 18:43:22 +0000 (20:43 +0200)]
refactor: remove unnecessary type assertions across monorepo
- Remove all @typescript-eslint/no-unnecessary-type-assertion violations
- Add assertIsJsonObject/isJsonObject utilities for runtime-safe narrowing
- Restructure OCPP16RequestService.buildRequestPayload with proper
runtime validation (assertIsJsonObject + OCPPError) replacing unsafe cast
- Use _syncResult assignment pattern in OCPPResponseService for
no-floating-promises compliance while preserving isAsyncFunction pattern
- Refine AsyncLock.runExclusive fn parameter as union of function types
for proper isAsyncFunction type guard narrowing
- Configure varsIgnorePattern: '^_' for @typescript-eslint/no-unused-vars
- Remove unused type imports in test files
renovate[bot] [Mon, 11 May 2026 13:14:03 +0000 (15:14 +0200)]
chore(deps): update pnpm to v11 (#1850)
* chore(deps): update pnpm to v11
* fix: migrate pnpm settings from package.json to pnpm-workspace.yaml
pnpm 11 no longer reads the 'pnpm' field from package.json.
Move patchedDependencies and allowBuilds to pnpm-workspace.yaml.
Remove dead pnpm field from package.json.
fix: resolve #1244 — add per-connector maximum power support (#1843)
* feat(charging-station): add per-connector maximum power support
Add maximumPower field to ConnectorStatus representing the physical
limitation of each connector cable/plug (thermal current rating).
Per OCPP Device Model, AvailablePowerMaxLimit is defined at the
Connector component level. The connector maximumPower acts as a
hardware cap in the power computation pipeline alongside the station-
level powerDivider sharing mechanism.
- Add ConnectorStatus.maximumPower?: number (in W)
- Initialize at boot via initializeConnectorsMaximumPower(): default
is stationPower / staticConnectorCount (using static count, not
dynamic powerDivider which can be 0 in shared mode at init)
- Clamp in getConnectorMaximumAvailablePower as additional min() term
- Use in getConnectorChargingProfilesLimit as primary cap (falls back
to stationPower/powerDivider for backward compat)
- Update 6 shared-mode templates with explicit maximumPower per
connector (= station power for DC shared-bus stations)
Resolves #1244
* chore(sandcastle): update validation and main scripts
* chore: sync release-please manifests and sandcastle prompt
* fix(charging-station): exclude index 0 from staticCount in getDefaultConnectorMaximumPower
The staticCount calculation included EVSE 0 and connector 0, while runtime
getPowerDivider excludes them. This caused connector hardware caps to be
more restrictive than intended (e.g., stationPower/3 instead of
stationPower/2 on a 2-EVSE station with EVSE 0 defined).
* [autofix.ci] apply automated fixes
* refactor(charging-station): add NaN guard to connectorHardwareMaximumPower in min()
Align the connectorHardwareMaximumPower entry with the same null/NaN guard
pattern used by all other entries in the min() call for consistency and
defensive robustness.
* docs: document per-connector maximumPower in template examples
Add maximumPower field to Connectors and Evses section examples.
Clarify powerSharedByConnectors behavior description.
Jérôme Benoit [Fri, 8 May 2026 18:45:44 +0000 (20:45 +0200)]
fix(ui/web): smooth icon-btn danger hover shadow and remove dead token
- Add box-shadow to .modern-icon-btn transition shorthand so the danger
variant hover glow animates instead of snapping
- Remove --skin-shadow-color (declared line 61 but never consumed)
Jérôme Benoit [Fri, 8 May 2026 18:30:30 +0000 (20:30 +0200)]
fix(ui/web): fix editable pill hover visibility in light themes
Refactor pill background to use scoped --_pill-bg and --_pill-bg-hover
custom properties (MD3 pattern). Each variant co-locates its base and
hover background values, and light-mode overrides reassign both.
The hover rule simply consumes var(--_pill-bg-hover), eliminating the
specificity battle that prevented the hover effect from appearing in
light themes.
Jérôme Benoit [Fri, 8 May 2026 18:00:49 +0000 (20:00 +0200)]
refactor(ui/web): remove redundant connector status column from classic skin
The connector status is now accessible via the Set Status dropdown in
the Actions column, making the dedicated read-only Status column
redundant. Move status/error-code selects to the top of Actions and
style them to fill the column width consistently with buttons.
Jérôme Benoit [Fri, 8 May 2026 15:08:22 +0000 (17:08 +0200)]
fix(sandcastle): patch pi thinking option and replace type indirections
Apply pnpm patch for @ai-hero/sandcastle porting PR #584 (pi --thinking
flag). Wire the thinking option through agentProvider() and replace
Awaited<ReturnType<...>> indirections with direct type imports (Sandbox,
SandboxRunResult, RunResult, PiOptions).
Jérôme Benoit [Fri, 8 May 2026 14:09:44 +0000 (16:09 +0200)]
fix(sandcastle): wire reasoning effort through to agent providers
Pass AGENT_*_EFFORT constants through agentProvider() to the opencode
provider's variant flag. LoopStrategy gains actorEffort/criticEffort
optional overrides following the same pattern as actorModel/criticModel.
- opencode: effort mapped to --variant CLI flag
- pi: no effort support (provider limitation, param silently ignored)
Jérôme Benoit [Thu, 7 May 2026 23:48:28 +0000 (01:48 +0200)]
refactor(sandcastle): remove plannerOutput from TaskSpec
Raw agent stdout will be handled by sandcastle's own debug/logging
mechanism rather than stored in-memory on TaskSpec. Structured fields
(acceptanceCriteria, rootCauseHypothesis, confidence, issueType) remain
as the sole inter-agent communication channel.
Jérôme Benoit [Thu, 7 May 2026 23:33:21 +0000 (01:33 +0200)]
refactor(sandcastle): remove redundant lastFindings from LoopResult
Derive last-round findings from roundHistory.at(-1)?.findings in
finalizer.ts instead of maintaining a separate field. The PR body
now shows all critic findings from the final round (including LOW
confidence) for full transparency.
Jérôme Benoit [Thu, 7 May 2026 23:20:58 +0000 (01:20 +0200)]
fix(sandcastle): assign opus to actor, sonnet to planner, increase planner iterations
Swap model assignments: claude-opus-4.6 (high effort) for the actor,
claude-sonnet-4.6 (medium effort) for the planner. Increase planner
maxIterations from 1 to 5 so it can actually read AGENTS.md and
project context before producing its analysis.
Jérôme Benoit [Thu, 7 May 2026 23:04:27 +0000 (01:04 +0200)]
feat(sandcastle): enrich planner with acceptance criteria and root cause hypothesis
The planner now produces structured analysis per issue: issueType,
confidence, rootCauseHypothesis, and acceptanceCriteria. These flow
into the actor prompt (confidence-gated hypothesis + criteria) and the
critic prompt (criteria as verification checklist).
- Confidence controls plan specificity: high → full context, medium/low → criteria only
- All planner-generated fields are sanitized and length-bounded
- Critic evaluates observable outcomes, never plan adherence
- Backward-compatible: missing fields result in empty template variables
Jérôme Benoit [Thu, 7 May 2026 22:36:27 +0000 (00:36 +0200)]
feat(sandcastle): add roundHistory to LoopResult and plannerOutput to TaskSpec
Replace the unused onRoundComplete callback with a structured
roundHistory array that accumulates RoundSnapshot per round
(including post-loop validation retry). Attach raw planner stdout
to TaskSpec.plannerOutput for downstream verification use.
This enables a future planner-verification step to receive the full
findings history alongside the original plan context.
fix(ui): allow changing status of individual connectors (#1834)
* feat(ui/web): allow changing status of individual connectors
Add a 'Set Status' action to the connector UI in both modern and classic
skins. Users can simulate OCPP connector statuses (e.g. Faulted, Unavailable)
directly from the dashboard.
- UIClient.setConnectorStatus sends STATUS_NOTIFICATION via existing ProcedureName
- useConnectorActions exposes setConnectorStatus with pending.setStatus guard
- Modern skin: SetConnectorStatusDialog presents a status picker in a modal
- Classic skin: inline <select> triggers status change on change event
- Test helpers and composable tests updated accordingly
* fix: correct OCPP version handling for connector status changes
- Add OCPP20ConnectorStatusEnumType enum to ui-common
- Fix UIClient.setConnectorStatus to send version-aware payload:
connectorStatus field for OCPP 2.0.x, status field for OCPP 1.6
- Update useConnectorActions to accept ocppVersion and pass it through;
widen status parameter type to union of 1.6 and 2.0.x enums;
accept optional onSuccess callback per action invocation
- Fix SetConnectorStatusDialog to close only after action resolves
(pass close as onSuccess instead of calling it immediately)
- Show version-appropriate status options in SetConnectorStatusDialog
- Forward ocppVersion and onRefresh from ConnectorRow to dialog
- Propagate need-refresh event through ConnectorRow → StationCard → ModernLayout
- Add tests for new OCPP 2.0.x paths and dialog behaviour
* [autofix.ci] apply automated fixes
* feat(ui): complete connector status change with error simulation and local state update
- Fix classic skin to show version-appropriate status options (OCPP 1.6/2.0.x)
- Pass ocppVersion to useConnectorActions in classic skin
- Replace passthrough STATUS_NOTIFICATION handler with sendAndSetConnectorStatus
to update in-memory connector state and emit connectorStatusChanged event
- Add OCPP 1.6 errorCode support (issue requests error simulation capability)
- Add OCPP16ChargePointErrorCode enum to ui-common
- Add error code selector in both skins (OCPP 1.6 only, hidden for 2.0.x)
- Remove unnecessary re-exports from useConnectorActions composable
- Update tests for new errorCode parameter and passthrough behavior change
Resolves the outstanding HIGH findings from automated review.
* fix(ui): polish connector status — reactivity consistency, JSDoc, tests, init from current status
- Wrap props in computed() in SetConnectorStatusDialog for consistency
- Fix JSDoc on mountDialog test helper to satisfy jsdoc/require-jsdoc
- Initialize selectedStatus from connector.status for OCPP 2.0.x too
- Add 5 unit tests for classic skin CSConnector status change behavior
* refactor(ui): remove redundant onRefresh from connector actions
The server already pushes a REFRESH notification via WebSocket when
connector state changes (connectorStatusChanged → buildUpdatedMessage →
workerEventUpdated → scheduleClientNotification → REFRESH broadcast).
The onRefresh callback in useConnectorActions duplicated this by manually
calling getChargingStations() after each action. Remove it along with
the need-refresh event bubbling chain in the modern skin.
The useAsyncAction onRefresh mechanism remains available for composables
where the server does NOT push updates (e.g., useStationActions).
Factor version-aware StatusNotification payload construction into
ui-common alongside existing buildAuthorize/Start/StopTransactionPayload
builders. Both CLI and Web UI now use the shared builder, eliminating
duplicated OCPP 1.6 vs 2.0.x branching logic.
Remove string fallback from status/errorCode parameters — the builder
accepts only the OCPP enum types. The CLI casts user input at the call
site, keeping the shared API type-safe.
* [autofix.ci] apply automated fixes
* fix(ui-common): remove invalid Occupied from OCPP16ChargePointStatus enum
Occupied is an OCPP 2.0.x-only connector status. It was erroneously
included in the OCPP 1.6 enum, causing the UI dropdown to offer an
invalid status option for OCPP 1.6 stations. Tests referencing it are
updated to use OCPP20ConnectorStatusEnumType.OCCUPIED or a valid 1.6
status as appropriate.
* fix(ui-common): make ChargePointStatus a union of OCPP 1.6 and 2.0.x enums
ChargePointStatus was aliased to OCPP16ChargePointStatus only, which
made ConnectorStatus.status unable to represent OCPP 2.0.x values like
Occupied. Now it is OCPP16ChargePointStatus | OCPP20ConnectorStatusEnumType,
matching the src/ canonical ConnectorStatusEnum pattern.
* refactor(ui-common): use ChargePointStatus type alias instead of inline union
Replace all occurrences of the verbose
'OCPP16ChargePointStatus | OCPP20ConnectorStatusEnumType' inline union
with the existing ChargePointStatus type alias across ui-common, web UI,
and CLI.
* [autofix.ci] apply automated fixes
* fix: add connectorId guard to handleStatusNotification for consistency
Other broadcast channel handlers (handleMeterValues, UNLOCK_CONNECTOR,
LOCK_CONNECTOR) throw BaseError when connectorId is missing. Without
this guard, a malformed request would silently succeed.
* fix(ui): address review feedback — clickable status pill, stale state sync, error-code apply
Modern skin:
- Replace 'Set Status' button with clickable status pill (edit icon on
hover, tooltip with status, aria-haspopup=dialog). More compact UX per
reviewer request (DerGenaue).
- Add .modern-pill--editable CSS with hover border, focus ring, and
fade-in edit icon.
Classic skin:
- Add watch on props.connector.status to sync selectedStatus ref when
server pushes new state (fixes stale dropdown after external changes).
- Add @change handler on error-code select so changing errorCode alone
also triggers a StatusNotification (previously only status change did).
Addresses review feedback from hyperspace-insights, copilot, and
DerGenaue.
Backend:
- Add errorCode field to ConnectorStatus (src/ and ui-common)
- Persist errorCode in sendAndSetConnectorStatus alongside status
- Move errorCode defaulting from buildStatusNotificationRequest to
OCPP16RequestService.buildRequestPayload via spread default pattern:
{ errorCode: NO_ERROR, ...commandParams }
- Remove Partial<> cast and ?? fallback from the builder — it now
simply passes through commandParams.errorCode (always defined by
the time it reaches the builder)
UI:
- Status pill tooltip shows errorCode when present and not NoError
(e.g., 'Faulted (ConnectorLockFailure)'), per DerGenaue's request
- ConnectorStatus.errorCode propagates automatically through existing
buildUpdatedMessage → spread serialization chain
Introduce AGENT_PROVIDER constant to switch between pi and opencode backends.
pi streams JSON output immediately, avoiding the opencode idle timeout bug
where git check-ignore indexing produces zero stdout.
Also removes redundant copyToWorktree since onSandboxReady pnpm install
handles node_modules via the mounted pnpm store.
Jérôme Benoit [Thu, 7 May 2026 18:26:40 +0000 (20:26 +0200)]
fix(sandcastle): revert idle timeout to 300s and remove redundant copyToWorktree
The 600s timeout was a misguided workaround for serena MCP init. The actual
root cause is an opencode bug: zero stdout during its git check-ignore
indexing phase. Removing copyToWorktree since pnpm install in onSandboxReady
already handles node_modules via the mounted pnpm store.
Jérôme Benoit [Thu, 7 May 2026 08:53:45 +0000 (10:53 +0200)]
refactor(sandcastle): add error observability and type-safe sentinels
- Add failureReason to LoopResult for post-mortem debugging
- Replace captureHeadSha sentinel '' with null (type-safe)
- discover() throws on planner failure (no hidden process.exitCode)
- Add console.debug in hashContextLines for dedup diagnostics
Jérôme Benoit [Thu, 7 May 2026 08:43:02 +0000 (10:43 +0200)]
refactor(sandcastle): improve separation of concerns and API clarity
- Extract runValidation into validation.ts
- Encapsulate nonce in loop (remove from strategy interface)
- Delete dead GRACE_TIMEOUT_MS constant
- Reorganize constants into proper domain groups
- Un-export FindingSchema and extractStderr
- Add uv via griffo.io APT (provides uvx for MCP servers in sandbox)
- Eliminate pipe patterns to prevent silent download failures
- Migrate GitHub CLI key to /etc/apt/keyrings/
- Remove gpg from base deps (no longer needed)
Jérôme Benoit [Wed, 6 May 2026 18:47:38 +0000 (20:47 +0200)]
fix(sandcastle): pre-create .local/share dirs in Dockerfile
Docker creates intermediate directories as root:root for bind mounts.
Pre-creating /home/agent/.local/share/pnpm/store and opencode with
correct ownership prevents EACCES when opencode writes to its data dir.
Jérôme Benoit [Wed, 6 May 2026 18:32:12 +0000 (20:32 +0200)]
fix(sandcastle): remove corepack prepare from Dockerfile
Align with the working Dockerfile from sap-ai-provider. The container
does not need explicit pnpm setup — corepack in node:24 handles it
on demand when pnpm is invoked.