Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ export default {
'src/infrastructure/stores/': {statements: 100, branches: 100, functions: 100, lines: 100},
'src/providers/vertex/': {statements: 94.23, branches: 84.7, functions: 100, lines: 97.72},
'src/providers/mock/': {statements: 100, branches: 81.25, functions: 100, lines: 100},
'src/transport/': {statements: 97.19, branches: 93.77, functions: 96.81, lines: 97.3},
// Measured over the files no path floor above claims, which is what Jest holds `global` to.
global: {statements: 95.05, branches: 90.7, functions: 93.75, lines: 95.74},
global: {statements: 92.33, branches: 85.71, functions: 90.9, lines: 93.77},
},
};
1 change: 1 addition & 0 deletions specs/hal-engine-architecture/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@

## The Big Picture

The system has three layers: a frontend client, a Node.js backend (hal-engine), and a pluggable AI provider. They communicate over WebSocket for real-time streaming.

Check warning on line 12 in specs/hal-engine-architecture/spec.md

View workflow job for this annotation

GitHub Actions / Verify

Testable statement in a in-progress spec/ADR has no test link — add ([validated by](path/to/test.ts#Lline)) to the test that validates it, or move it under a narrative heading (Background / Rationale / Open Questions …) if it states no testable behaviour. Statement: "They communicate over WebSocket for real-time streaming."

Check warning on line 12 in specs/hal-engine-architecture/spec.md

View workflow job for this annotation

GitHub Actions / Verify

Testable statement in a in-progress spec/ADR has no test link — add ([validated by](path/to/test.ts#Lline)) to the test that validates it, or move it under a narrative heading (Background / Rationale / Open Questions …) if it states no testable behaviour. Statement: "The system has three layers: a frontend client, a Node.js ba…"

Only the middle layer is this repository. The `Client` group below, the `applyUpsert`/`applyDelta`/`applyCommit` functions in Entry Streaming Protocol, the reconnection and unmount behaviour under Connection Lifecycle, and the spinner logic in Tool Execution Loop all describe a browser client. They are here because the protocol only makes sense as a pair, not because any of it ships from here.

Check warning on line 14 in specs/hal-engine-architecture/spec.md

View workflow job for this annotation

GitHub Actions / Verify

Testable statement in a in-progress spec/ADR has no test link — add ([validated by](path/to/test.ts#Lline)) to the test that validates it, or move it under a narrative heading (Background / Rationale / Open Questions …) if it states no testable behaviour. Statement: "They are here because the protocol only makes sense as a pai…"

Check warning on line 14 in specs/hal-engine-architecture/spec.md

View workflow job for this annotation

GitHub Actions / Verify

Testable statement in a in-progress spec/ADR has no test link — add ([validated by](path/to/test.ts#Lline)) to the test that validates it, or move it under a narrative heading (Background / Rationale / Open Questions …) if it states no testable behaviour. Statement: "The `Client` group below, the `applyUpsert`/`applyDelta`/`ap…"

Check warning on line 14 in specs/hal-engine-architecture/spec.md

View workflow job for this annotation

GitHub Actions / Verify

Testable statement in a in-progress spec/ADR has no test link — add ([validated by](path/to/test.ts#Lline)) to the test that validates it, or move it under a narrative heading (Background / Rationale / Open Questions …) if it states no testable behaviour. Statement: "Only the middle layer is this repository."

```mermaid
graph LR
Expand Down Expand Up @@ -75,9 +75,9 @@

### SessionStore

Controls where session data is stored: the default `InMemorySessionStore` keeps sessions in a `Map` ([validated by: creates and retrieves a session](../../src/infrastructure/stores/inMemorySessionStore.test.ts#L13)). Implement this interface to persist sessions in Redis, a database, or any other backing store. The store is generic -- pass your own session type extending `BaseSession`.

Check warning on line 78 in specs/hal-engine-architecture/spec.md

View workflow job for this annotation

GitHub Actions / Verify

Testable statement in a in-progress spec/ADR has no test link — add ([validated by](path/to/test.ts#Lline)) to the test that validates it, or move it under a narrative heading (Background / Rationale / Open Questions …) if it states no testable behaviour. Statement: "The store is generic -- pass your own session type extending…"

Check warning on line 78 in specs/hal-engine-architecture/spec.md

View workflow job for this annotation

GitHub Actions / Verify

Testable statement in a in-progress spec/ADR has no test link — add ([validated by](path/to/test.ts#Lline)) to the test that validates it, or move it under a narrative heading (Background / Rationale / Open Questions …) if it states no testable behaviour. Statement: "Implement this interface to persist sessions in Redis, a dat…"

<!-- doc-block: src/types/sessionStore.ts#SessionStore -->

Check warning on line 80 in specs/hal-engine-architecture/spec.md

View workflow job for this annotation

GitHub Actions / Verify

Testable statement in a in-progress spec/ADR has no test link — add ([validated by](path/to/test.ts#Lline)) to the test that validates it, or move it under a narrative heading (Background / Rationale / Open Questions …) if it states no testable behaviour. Statement: "<!-- doc-block: src/types/sessionStore.ts#SessionStore -->"
```typescript
interface SessionStore<T extends BaseSession = ChatSession> {
create(sessionId: string, userId: string | number, options?: SessionCreateOptions): Awaitable<T>;
Expand Down Expand Up @@ -118,7 +118,7 @@

### WsAuthenticator

Authenticates WebSocket connections during the handshake. It receives the whole Node `IncomingMessage`, not a pre-extracted token, so it can read credentials from wherever the client put them. Return the authenticated user to accept the connection, or `null` to reject it with HTTP 401 -- a rejection is a returned `null`, not a thrown error.

Check warning on line 121 in specs/hal-engine-architecture/spec.md

View workflow job for this annotation

GitHub Actions / Verify

Testable statement in a in-progress spec/ADR has no test link — add ([validated by](path/to/test.ts#Lline)) to the test that validates it, or move it under a narrative heading (Background / Rationale / Open Questions …) if it states no testable behaviour. Statement: "It receives the whole Node `IncomingMessage`, not a pre-extr…"

Check warning on line 121 in specs/hal-engine-architecture/spec.md

View workflow job for this annotation

GitHub Actions / Verify

Testable statement in a in-progress spec/ADR has no test link — add ([validated by](path/to/test.ts#Lline)) to the test that validates it, or move it under a narrative heading (Background / Rationale / Open Questions …) if it states no testable behaviour. Statement: "Authenticates WebSocket connections during the handshake."

<!-- doc-block: src/types/auth.ts#WsAuthenticator -->
```typescript
Expand Down Expand Up @@ -491,6 +491,7 @@
- `HalEngineConfig.transport.additionalRoutes` is forwarded to `createApp`, so a route registered there mounts under `basePath` in the server the engine builds, and not at the root. ([validated by: forwards transport.additionalRoutes to createApp so the route mounts under basePath](../../src/config.test.ts#L244))
- Neither `additionalRoutes` nor `rootRoutes` is covered by `auth.http`; both receive requests before any authentication middleware the engine installs, so a consumer applies its own middleware inside the callback. ([validated by: leaves additionalRoutes and rootRoutes open while auth.http still guards the chat routes](../../src/config.test.ts#L263))
- Both callbacks inherit the CORS, JSON body-parsing, and cookie-parsing middleware that `createApp` mounts unconditionally. ([validated by: gives additionalRoutes and rootRoutes the parsed JSON body, the cookies and the CORS headers](../../src/config.test.ts#L288))
- With neither `transport.corsOrigin` nor `CORS_ORIGIN` set, that CORS middleware allows the origin `http://localhost:3000` and sends `Access-Control-Allow-Credentials: true`, a default for a front end on the developer's own machine ([validated by: allows http://localhost:3000 with credentials when neither corsOrigin nor CORS_ORIGIN is set](../../src/transport/createApp.test.ts#L165)).
- A `transport.errorHandler` receives what a route throws, whether synchronously or as a rejected promise, and the response it writes is the one the client gets, instead of Express's default HTML page. ([validated by: hands transport.errorHandler a route's synchronous throw and its rejected promise, and answers with its response](../../src/config.test.ts#L311))
- `engine.app` cannot be extended after `createHalEngine` returns: `createApp` registers a terminal `404` catch-all before returning, and Express matches routes in registration order, so a route added afterwards always returns `404`. ([validated by: answers 404 for a route added to engine.app after createHalEngine returns](../../src/config.test.ts#L332))

Expand Down
2 changes: 2 additions & 0 deletions specs/hal-engine-npm-release/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ Nothing from `src/`, `example/`, `smoke/`, `docs/`, `specs/`, `adrs/` or `script
- The floor is set at the measured baseline, not an aspiration, and exactly at it rather than rounded down: an integer floor leaves roughly a percent of slack, which was measured to let four untested lines through without failing.
- Measured at `3186f07` with those exclusions: 67.96% statements, 57.54% branches, 68% functions, 68.34% lines, across 206 tests in 17 suites. The earlier figure of 61.32% lines predates the exclusions and three of this branch's commits.
- The floor is a ratchet: a change that lowers coverage fails the job and is fixed by adding the missing test, never by lowering the number; a change that raises coverage should raise the floor with it.
- `src/transport/` gained its own floor on 2026-10-27, at what it measured that day: 97.19% statements (659/678), 93.77% branches (407/434), 96.81% functions (152/157) and 97.30% lines (578/594).
- Naming that path took its files out of `global`, which Jest measures over the files no path floor claims, so `global` was re-measured in the same commit: 458/496 statements, 228/266 branches, 120/132 functions and 392/418 lines. Its percentages fell because well-covered files left the group, not because coverage did. Measured the same day without the change, the files still in the group covered 457 statements, 228 branches, 119 functions and 391 lines, so none of the four counts went down.
- `coverage/` is gitignored already, so nothing is added for it.

### Build-chain audit
Expand Down
10 changes: 5 additions & 5 deletions specs/hal-engine-session-resume/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@

## Reading the requested id

- The id is the `sessionId` query parameter of the upgrade request, never a path segment, and only 1–128 characters of `[A-Za-z0-9_-]` count: an empty value, a longer one and a path-traversal value read as no id at all ([validated by: reads abc-123 from the query and nothing from a bare path, a path segment, an empty, a 129-character or a traversal value](../../src/transport/ws/helpers.test.ts#L6)).
- A 128-character id is the longest one read ([validated by: reads a 128-character id, the longest it accepts](../../src/transport/ws/helpers.test.ts#L24)).
- An upgrade outside `{basePath}/ws` carries no id ([validated by: reads nothing from an upgrade outside the base path](../../src/transport/ws/helpers.test.ts#L30)).
- Reading the id never throws: a target that is not a URL, such as `//`, or an empty one carries no id ([validated by: reads nothing, without throwing, from a target that is not a URL or is empty](../../src/transport/ws/helpers.test.ts#L34)).
- The id is the `sessionId` query parameter of the upgrade request, never a path segment, and only 1–128 characters of `[A-Za-z0-9_-]` count: an empty value, a longer one and a path-traversal value read as no id at all ([validated by: reads abc-123 from the query and nothing from a bare path, a path segment, an empty, a 129-character or a traversal value](../../src/transport/ws/helpers.test.ts#L7)).
- A 128-character id is the longest one read ([validated by: reads a 128-character id, the longest it accepts](../../src/transport/ws/helpers.test.ts#L25)).
- An upgrade outside `{basePath}/ws` carries no id ([validated by: reads nothing from an upgrade outside the base path](../../src/transport/ws/helpers.test.ts#L31)).
- Reading the id never throws: a target that is not a URL, such as `//`, or an empty one carries no id ([validated by: reads nothing, without throwing, from a target that is not a URL or is empty](../../src/transport/ws/helpers.test.ts#L35)).

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Reading the requested id "The id is the `sessionId` query parameter of the upgrade request, never a path segment, and only 1–128 characters of `[…"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Reading the requested id "A 128-character id is the longest one read ([validated by: reads a 128-character id, the longest it accepts](../../src/…"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Reading the requested id "An upgrade outside `{basePath}/ws` carries no id ([validated by: reads nothing from an upgrade outside the base path](.…"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Reading the requested id "Reading the id never throws: a target that is not a URL, such as `//`, or an empty one carries no id ([validated by: re…"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Continuing the latest session "`?new=1` counts only when it is exactly `1`, and only on an upgrade inside `{basePath}/ws` ([validated by: reads exactl…"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Opt-in "With resume off, a socket opened at `{basePath}/ws/undefined` still completes the handshake and gets a server-minted id…"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Rejoining a conversation "An entry still streaming when its session is resumed, because its turn is running on the socket that started it, is rep…"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Rejoining a conversation "An answer still open when suppression begins is first committed as streamed so far, then retracted and marked like any …"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › The store decides what is live "A resumed session whose socket closes before its replay is kept, never evicted: eviction erases, and it is reserved for…"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Continuing the latest session "With `latest` on, a connect that names no `?sessionId=` rejoins the user's most recently active session, which the stor…"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Continuing the latest session "It starts a new session for a user who has none, and for a connect that sends `?new=1`, which is how a client starts a …"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Continuing the latest session "A connect that names an id rejoins that session, whichever is latest ([validated by: with latest on, still rejoins the …"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Continuing the latest session "A session `latestFor` answers for another user is never rejoined, and a `latestFor` that throws or that the store does …"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Continuing the latest session "Without `latest`, a connect that names no id starts a new session, as before ([validated by: with resume on but latest …"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Telling an expired session apart "A connect naming its own session after it aged out gets `resumed: false`, `resumeFailure: 'expired'`, a new `sessionId`…"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Telling an expired session apart "Another user naming that expired id gets `resumeFailure: 'unknown'`, in a response identical to the one for an id never…"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Telling an expired session apart "A connect that names no id gets no `resumeFailure` at all, even when the latest-session default finds nothing to rejoin…"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Telling an expired session apart "Resume reads a named id with one call per attempt, the store's `lookup` when it has one and its `get` otherwise, and ei…"

Check warning on line 15 in specs/hal-engine-session-resume/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-session-resume/spec.md › Compatibility "`ConnectedMessage` gains only the optional `resumed`, `entryCount` and `resumeFailure`, so a `connected` literal carryi…"

## Opt-in

Expand Down Expand Up @@ -52,7 +52,7 @@
- A connect that names an id rejoins that session, whichever is latest ([validated by: with latest on, still rejoins the session a connect names rather than the latest one](../../src/transport/sessionResume.test.ts#L488)).
- A session `latestFor` answers for another user is never rejoined, and a `latestFor` that throws or that the store does not implement starts a new session ([validated by: starts a new session when the store's latestFor answers another user's session, throws, or is absent](../../src/transport/sessionResume.test.ts#L500)).
- Without `latest`, a connect that names no id starts a new session, as before ([validated by: with resume on but latest off, starts a new session for a connect that names none](../../src/transport/sessionResume.test.ts#L524)).
- `?new=1` counts only when it is exactly `1`, and only on an upgrade inside `{basePath}/ws` ([validated by: reads exactly ?new=1 inside the base path as a request for a new session, and nothing else](../../src/transport/ws/helpers.test.ts#L40)).
- `?new=1` counts only when it is exactly `1`, and only on an upgrade inside `{basePath}/ws` ([validated by: reads exactly ?new=1 inside the base path as a request for a new session, and nothing else](../../src/transport/ws/helpers.test.ts#L41)).
- `InMemorySessionStore.latestFor` goes by a session's newest timed entry, so the conversation the user last wrote to beats one created later, and an entry with no time, such as a thought, counts for nothing ([validated by: returns the user's session with the newest entry, not the one created last, a thought counting for nothing](../../src/infrastructure/stores/inMemoryLatestSession.test.ts#L17)).
- A session with no entries counts from its creation, and of two last active at the same moment the larger session id wins, the rule `listFor` orders by, so a resume rejoins the conversation at the head of the list ([validated by: falls back to creation time for sessions with no entries, the one created later winning](../../src/infrastructure/stores/inMemoryLatestSession.test.ts#L30), [validated by: breaks a tie between two sessions created in the same millisecond by the larger session id, zeta over alpha](../../src/infrastructure/stores/inMemoryLatestSession.test.ts#L39)).
- It never returns a session that has aged out, nor one belonging to another user ([validated by: returns nothing for a user whose only session aged out, nor another user's live one](../../src/infrastructure/stores/inMemoryLatestSession.test.ts#L47)).
Expand Down
14 changes: 10 additions & 4 deletions specs/hal-engine-websocket-protocol/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,8 @@

Constraints:

- `content` MUST NOT be empty or whitespace-only after trimming.
- `content` MUST NOT exceed 10,000 characters.
- `content` MUST NOT be empty or whitespace-only after trimming ([validated by: refuses content of three spaces as empty](../../src/transport/ws/validation.test.ts#L82)).
- `content` MUST NOT exceed 10,000 characters: 10,000 is accepted and 10,001 refused, the error naming the limit ([validated by: accepts content of exactly 10,000 characters and refuses 10,001, naming the limit](../../src/transport/ws/validation.test.ts#L72)).

Check warning on line 152 in specs/hal-engine-websocket-protocol/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-websocket-protocol/spec.md › 11.3 Reconnection "An entry still streaming when its conversation is resumed is replayed with `isStreaming: false` and `truncated: true`: …"

Check warning on line 152 in specs/hal-engine-websocket-protocol/spec.md

View workflow job for this annotation

GitHub Actions / Lore Spec Impact

Lore: coupled spec statement

specs/hal-engine-websocket-protocol/spec.md › 11.3 Reconnection "With the server's `latest` option, a client that has lost the id, after a page refresh for instance, MAY connect withou…"
- Violation of these constraints results in an `error` response with code `INVALID_MESSAGE`.

One at a time:
Expand Down Expand Up @@ -177,6 +177,8 @@
| `type` | string | Yes | `"ping"` |
| `timestamp` | number | Yes | Client timestamp in milliseconds |

A `ping` whose `timestamp` is missing or is not a number is refused, its error naming the field, and a numeric `timestamp` is passed on unchanged for the `pong` to echo ([validated by: refuses a ping with no timestamp or a text one, and passes a numeric timestamp through unchanged](../../src/transport/ws/validation.test.ts#L92)).

### 4.3 list_conversations

Asks for the connecting user's own conversations. Served only when the server enables
Expand Down Expand Up @@ -381,6 +383,8 @@
- A `list_conversations` the server does not serve is answered with `UNSUPPORTED`, whether because `transport.history` is off or because its store implements no `listFor`, and never with an empty list, which a client could not tell from a user who has no conversations ([validated by: refuses the frame when conversation history is not turned on](../../src/transport/conversationList.test.ts#L302), [validated by: refuses the frame when the store cannot list, rather than reporting no conversations](../../src/transport/conversationList.test.ts#L353)).
- A store that fails while listing is answered `SERVER_ERROR` carrying none of the store's own words, and the server logs the session id, the user id and the error's type rather than its message, since a driver's message can hold a connection string and its password; the user id in that line is personal data, as it is in every log line the engine writes ([validated by: answers a failing store with a server error, keeps the socket open, and logs no word the store said](../../src/transport/conversationList.test.ts#L388)).
- A message the server cannot parse into a known type is answered with `INVALID_MESSAGE`, and no message stream is started for it ([validated by: rejects an unparseable message and never starts a stream](../../src/transport/ws/messageHandler.test.ts#L72)).
- Each frame's bytes are parsed as JSON as they arrive, and bytes that do not parse read as no frame at all, without throwing ([validated by: reads a JSON object from text or from bytes, and an unterminated brace as null, without throwing](../../src/transport/ws/helpers.test.ts#L63)).
- A frame that is not JSON is answered with `INVALID_FORMAT` and the message `Invalid JSON`, and the connection stays open: the frame after it is handled as usual ([validated by: answers a frame that is not JSON with INVALID_FORMAT and Invalid JSON, and keeps the socket open for the next frame](../../src/transport/invalidFrame.test.ts#L16)).
- A rate limit reported by the AI provider is surfaced as `RATE_LIMITED`, which tells the client the same request is worth retrying ([validated by: tells the client to retry when the provider is rate limited](../../src/transport/ws/messageHandler.test.ts#L372)).
- Any other failure raised while processing a message that is no `AIError` is reported as `SERVER_ERROR` ([validated by: reports any other failure as a server error](../../src/transport/ws/messageHandler.test.ts#L381)).

Expand Down Expand Up @@ -779,6 +783,7 @@
- A failure while the session opens, such as a session store whose `create` throws, is answered first with an `error` frame and then the same `1011` close ([validated by: sends an error frame and closes with 1011, with no client error, through createHalEngine when the session store create throws synchronously](../../src/sessionSetupFailure.test.ts#L15)).
- The failure is logged once at `error` under `ws` as `connection failed after the handshake`, with the error's message; the upgrade request's `authorization` and `cookie` values reach no log line ([validated by: logs the failure at error under ws and keeps the authorization and cookie values out of every log line](../../src/transport/upgradeFailure.test.ts#L64)).
- Before the handshake completes, the server still answers in HTTP: a `wsAuth` that rejects gets `500 Internal Server Error` and one that resolves `null` gets `401 Unauthorized`, with no `101` and no connection opened ([validated by: answers a rejecting wsAuth with 500 and a null one with 401, with no 101 and no connection event](../../src/transport/upgradeFailure.test.ts#L85)).
- Every answer the engine itself writes before the handshake, these two and its `400`s, is a status line and an empty header block alone, such as `HTTP/1.1 401 Unauthorized\r\n\r\n`, with no header and no body, so nothing from the request is echoed into it, and the socket is destroyed once it is written. A refusal `ws` writes for an upgrade it cannot parse is its own ([validated by: writes HTTP/1.1 401 Unauthorized and an empty header block, nothing else, then destroys the socket](../../src/transport/ws/helpers.test.ts#L73)).

## 12. Security Considerations

Expand All @@ -787,8 +792,9 @@
- No offered subprotocol value is written to the engine's own log at any level. Every place a credential exists during a connection - request headers, the socket's and the session's `authHeaders`, and the tool context - is listed in [the subprotocol marker spec](../hal-engine-subprotocol-marker/spec.md#where-a-credential-exists).
- An upgrade whose `Authorization` header and subprotocol carry different credentials is refused with `400` before authentication, so the credential a `WsAuthenticator` validated is the one forwarded to the session and to every tool ([validated by: refuses Bearer attacker-token beside a victim-token subprotocol with 400 before wsAuth runs, and neither value reaches the response or a log line](../../src/transport/handshake.test.ts#L182)).
- **NIS-2 (Art. 21), supply-chain security.** Before that rule, a tool calling a downstream API could receive a bearer token no authenticator had validated: the authenticator could check one carrier while the other's value was forwarded, defeating the per-user data boundary downstream ([validated by: refuses Bearer attacker-token beside a victim-token subprotocol with 400 before wsAuth runs, and neither value reaches the response or a log line](../../src/transport/handshake.test.ts#L182)).
- Message content is validated at the server boundary. Content exceeding 10,000 characters is rejected.
- The server validates all incoming messages against known types. Unrecognized types receive an `INVALID_MESSAGE` error.
- Message content is validated at the server boundary. Content exceeding 10,000 characters is rejected ([validated by: accepts content of exactly 10,000 characters and refuses 10,001, naming the limit](../../src/transport/ws/validation.test.ts#L72)).
- The server validates all incoming messages against known types. Unrecognized types receive an `INVALID_MESSAGE` error ([validated by: refuses a frame of type nope, naming the type](../../src/transport/ws/validation.test.ts#L88), [validated by: rejects an unparseable message and never starts a stream](../../src/transport/ws/messageHandler.test.ts#L72)).
- **GDPR (Art. 5(1)(c)), data minimisation.** A turn's log lines record the length of the user's message as `contentLength`, never its text. At every level, `debug` included, no line carries the message, a tool's arguments or result, or the answer ([validated by: logs a 32-character question as contentLength 32 at debug level, and no line carries the question, a tool argument or result, or the answer](../../src/contentFreeLogs.test.ts#L59)).

## 13. Source Files

Expand Down
68 changes: 68 additions & 0 deletions src/contentFreeLogs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import {jest} from '@jest/globals';
import type {AddressInfo} from 'node:net';

// The level is read once, when the logger loads, so it is set before anything first-party is imported.
process.env.LOG_LEVEL = 'debug';
const {createHalEngine} = await import('./config.js');
const {ToolRegistry} = await import('./orchestration/tools/registry.js');
const {InMemorySessionStore} = await import('./infrastructure/stores/inMemorySessionStore.js');
const {connectClient, framesUntil} = await import('./transport/wsTestSupport.js');

const QUESTION = 'Where is parcel ZX-4471 heading?';
const TOOL_ARGUMENT = 'QK-9083';
const TOOL_RESULT = 'Held at the Aarhus depot';
const ANSWER = 'It reaches Odense on Friday.';

interface Line {
severity: string;
data?: {contentLength?: number};
}

async function oneTurnLogged(): Promise<string[]> {
const lines: string[] = [];
const keep = (raw: unknown) => void lines.push(String(raw));
jest.spyOn(console, 'log').mockImplementation(keep);
jest.spyOn(console, 'error').mockImplementation(keep);
const engine = createHalEngine({
prompt: {identity: 'Log content test.'},
session: new InMemorySessionStore(),
auth: {ws: async () => ({id: 'u1'})},
provider: {
type: 'mock',
turns: [{toolCalls: [{id: 'c1', name: 'lookup', input: {reference: TOOL_ARGUMENT}}]}, {text: ANSWER}],
},
tools: lookupTool(),
});
await engine.start(0);
const {port} = engine.server.address() as AddressInfo;
const client = connectClient(`ws://127.0.0.1:${port}/hal/ws`);
const ended = framesUntil(client, 'stream_end');
const socketClosed = new Promise<void>(resolve =>
engine.wss.once('connection', socket => socket.once('close', () => resolve()))
);
client.on('open', () => client.send(JSON.stringify({type: 'user_message', content: QUESTION})));
await ended;
await engine.stop();
await socketClosed;
return lines;
}

function lookupTool() {
const registry = new ToolRegistry();
registry.register(
{name: 'lookup', description: 'Looks a parcel up.', inputSchema: {type: 'object'}},
async () => TOOL_RESULT
);
return registry;
}

it('logs a 32-character question as contentLength 32 at debug level, and no line carries the question, a tool argument or result, or the answer', async () => {
const lines = await oneTurnLogged();

const parsed = lines.map(line => JSON.parse(line) as Line);
expect({
debugLogged: parsed.some(line => line.severity === 'DEBUG'),
contentLength: parsed.find(line => line.data?.contentLength !== undefined)?.data,
leaked: [QUESTION, TOOL_ARGUMENT, TOOL_RESULT, ANSWER].filter(text => lines.some(line => line.includes(text))),
}).toMatchObject({debugLogged: true, contentLength: {contentLength: 32}, leaked: []});
});
Loading
Loading