feat(observability): add DispatchLogger seam — ADR-0174 SDK retirement Phase 1.3 (#177) (#223)

* test(#177): add DispatchEvent factory failing tests

Red tests for makeDispatchEvent shape, traceId UUID v4, uniqueness,
parentTraceId-always-undefined (P1.3), args redaction toggle, ISO 8601
timestamp, and all result variant passthrough.

* feat(#177): introduce DispatchEvent factory

makeDispatchEvent produces an immutable event record per dispatch:
- traceId: crypto.randomUUID() (UUID v4)
- parentTraceId: always undefined (P1.4 wires composer)
- command, result, timestamp (ISO 8601)
- args only included when includeArgs === true (default: omitted)

* test(#177): add arg redaction policy failing tests

Red tests for shouldIncludeArgs (GSD_AUDIT_ARGS env gating) and
redactEvent (strips args from frozen events, preserves all other
fields, returns a new object, never mutates the source).

* feat(#177): introduce arg redaction policy

shouldIncludeArgs(): only GSD_AUDIT_ARGS==='1' opts in; all other
values (unset, '', '0', 'true') default to omitting args.

redactEvent(event): returns a shallow copy of the event, dropping the
args field unless opted in. Never mutates the (frozen) source event.

* test(#177): add DispatchLogger interface failing tests

Red tests covering:
- no-op logger: silent on all events, never throws
- default logger: silent on ok, one flattened JSON line to stderr on error
- default logger: audit file creation + append-only + redaction + config gate
- GSD_AUDIT env var and config.audit.enabled config gate
- GSD_AUDIT_ARGS opt-in for args inclusion
All tests use real fs under os.tmpdir() — no mocked appendFileSync.

* feat(#177): introduce DispatchLogger with default and no-op implementations

createNoOpLogger(): silent on all events — Hub default when no logger injected.
createDefaultLogger({ cwd, config }):
  - Silent on ok result
  - Flattened JSON line to stderr on error: { kind, traceId, ...typedPayload }
  - Append-only audit at .planning/.gsd-trace.jsonl when GSD_AUDIT=1 or config.audit.enabled
  - Args redacted by default; GSD_AUDIT_ARGS=1 opts in
  - Logger errors caught internally; never break dispatch callers

* test(#177): add Hub+logger integration failing tests

Red tests verifying:
- onEvent called exactly once per dispatch (ok, error, handler-throw, unknown)
- DispatchEvent shape: traceId uniqueness, command, result.kind, parentTraceId
- Logger errors contained (dispatch still returns Result, warn line to stderr)
- Hub defaults to no-op when no logger injected
- End-to-end with createDefaultLogger: silent on success, stderr on error, audit file

* feat(#177): wire DispatchLogger into CommandRoutingHub

Add optional logger param to createHub({ ..., logger }).
Defaults to createNoOpLogger() — silent, no behaviour change for callers
that don't inject a logger.

After every dispatch (success and error):
- Normalises HubResult { ok } to DispatchEvent { kind: 'ok'|error-kind }
- Calls makeDispatchEvent({ command, args, result }) to mint the event
- Calls logger.onEvent(event) exactly once
- Wraps in try/catch: logger errors emit { level:'warn', source:'DispatchLogger' }
  to stderr but never propagate to dispatch callers

* chore(#177): gitignore .planning/.gsd-trace.jsonl audit file

The audit trail is local-only, append-only, and must never be committed.
Slotted under the existing "Local scratch + Claude-test artifacts" block.

* docs(#177): document GSD_AUDIT, GSD_AUDIT_ARGS, config.audit.enabled

New ## Observability section at end of CONFIGURATION.md covering:
- Default silent/stderr behaviour overview
- Stderr error JSON format
- Audit file opt-in (env var and config key)
- Args redaction policy and GSD_AUDIT_ARGS opt-in

Also slots GSD_AUDIT and GSD_AUDIT_ARGS into the existing
## Environment Variables table (alphabetical order).

* chore(#177): add changeset for observability seam

type: Added — new DispatchLogger seam with default silent/stderr/audit behaviour.
This commit is contained in:
Tom Boucher
2026-05-24 15:22:36 -04:00
committed by GitHub
parent 4bc3653578
commit 2d14eb8873
11 changed files with 1368 additions and 10 deletions

View File

@@ -1,7 +1,7 @@
'use strict';
/**
* Command Routing Hub — issue #3788, simplified in #175, typed in #176.
* Command Routing Hub — issue #3788, simplified in #175, typed in #176, observability in #177.
*
* A pure-result dispatch hub that centralizes CJS routing,
* the error taxonomy, and the no-throw contract that all command-family routers
@@ -47,6 +47,10 @@ const ERROR_KINDS = Object.freeze({
HandlerFailure: 'HandlerFailure',
});
// ─── Observability imports ────────────────────────────────────────────────────
const { makeDispatchEvent } = require('./observability/event.cjs');
const { createNoOpLogger } = require('./observability/logger.cjs');
// ─── Internal helpers ─────────────────────────────────────────────────────────
/**
@@ -202,17 +206,85 @@ function _validateErrResult(result) {
* Nested map of family -> subcommand -> handler.
* @property {Record<string, string[]>} [manifest] - Map of family -> known subcommands.
* Used for UnknownCommand detection.
* @property {{ onEvent(event: object): void }} [logger] -
* DispatchLogger to receive a DispatchEvent after every dispatch.
* Defaults to a no-op logger (silent). Use createDefaultLogger() for the
* reference implementation (stderr on error, opt-in file audit).
*/
/**
* Safe stringify for logger-failure warnings — avoids circular-ref crashes.
* @param {unknown} value
* @returns {string}
*/
function _safeJsonForWarn(value) {
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
/**
* Construct a CommandRoutingHub.
*
* @param {HubOptions} options
* @returns {{ dispatch: (req: object) => HubResult }}
*/
function createHub({ cjsRegistry, manifest } = {}) {
function createHub({ cjsRegistry, manifest, logger } = {}) {
const _cjsRegistry = cjsRegistry;
const _manifest = manifest;
// Default to no-op so callers that don't inject a logger get pure-silent behaviour.
// Consumers can opt into the reference impl by importing createDefaultLogger.
const _logger = (logger && typeof logger.onEvent === 'function')
? logger
: createNoOpLogger();
/**
* Normalise a HubResult into the DispatchEvent result shape.
*
* HubResult ok path: { ok: true, data } → { kind: 'ok', data }
* HubResult err paths: { ok: false, kind, ...payload } → { kind, ...payload }
*
* @param {object} hubResult
* @returns {object}
*/
function _normaliseResult(hubResult) {
if (hubResult.ok) {
return { kind: 'ok', data: hubResult.data };
}
// err variant: already has kind + typed payload
return hubResult;
}
/**
* Emit a DispatchEvent to the injected logger.
* Logger errors NEVER propagate — they are caught and emitted as a warn line to stderr.
*
* @param {string} command - The dispatched command string.
* @param {unknown} args - The raw args from the request.
* @param {object} hubResult - The HubResult.
*/
function _notifyLogger(command, args, hubResult) {
try {
const eventResult = _normaliseResult(hubResult);
const event = makeDispatchEvent({ command, args, result: eventResult });
_logger.onEvent(event);
} catch (logErr) {
// Logger must never break dispatch. Emit a degraded warn line.
try {
process.stderr.write(
_safeJsonForWarn({
level: 'warn',
source: 'DispatchLogger',
message: 'logger.onEvent failed: ' + String(logErr && logErr.message || logErr),
}) + '\n'
);
} catch {
// If even stderr.write fails, swallow silently — dispatch result is returned below.
}
}
}
/**
* Dispatch a command through the hub.
@@ -221,17 +293,25 @@ function createHub({ cjsRegistry, manifest } = {}) {
* @returns {HubResult}
*/
function dispatch(req) {
const { family, subcommand, args = [] } = req || {};
const command = subcommand ? `${family} ${subcommand}` : String(family);
let result;
try {
return _dispatch(req);
result = _dispatch(req);
} catch (err) {
if (err instanceof Error) {
return makeHandlerFailure(err.message, err);
result = makeHandlerFailure(err.message, err);
} else {
// Finding 2: preserve non-Error throwables via a wrapper Error with .thrown
const wrapper = new Error('non-Error thrown: ' + _safeJson(err));
wrapper.thrown = err;
result = makeHandlerFailure(String(err), wrapper);
}
// Finding 2: preserve non-Error throwables via a wrapper Error with .thrown
const wrapper = new Error('non-Error thrown: ' + _safeJson(err));
wrapper.thrown = err;
return makeHandlerFailure(String(err), wrapper);
}
_notifyLogger(command, args, result);
return result;
}
function _dispatch(req) {

View File

@@ -0,0 +1,47 @@
'use strict';
/**
* DispatchEvent shape factory — issue #177 (ADR-0174 P1.3).
*
* Creates a structured event record for every Hub dispatch, used by
* DispatchLogger to emit stderr errors and opt-in file audit trails.
*
* Shape:
* traceId: string — UUID v4, generated per dispatch
* parentTraceId: undefined — always undefined in P1.3; P1.4 wires the composer
* command: string — the dispatched verb
* args?: unknown — only present when includeArgs === true
* result: { kind: 'ok' | 'UnknownCommand' | 'InvalidArgs' | 'HandlerRefusal' | 'HandlerFailure', ...payload }
* timestamp: string — ISO 8601
*/
const { randomUUID } = require('crypto');
/**
* Create a DispatchEvent.
*
* @param {object} opts
* @param {string} opts.command - The dispatched command verb.
* @param {unknown} [opts.args] - Raw args passed to the hub.
* @param {object} opts.result - The HubResult returned by the hub.
* @param {boolean} [opts.includeArgs=false] - When true, include args in the event.
* @param {string} [opts.parentTraceId] - Ignored in P1.3; always yields undefined.
* @returns {object} Immutable DispatchEvent record.
*/
function makeDispatchEvent({ command, args, result, includeArgs = false, parentTraceId: _ignored }) {
const event = {
traceId: randomUUID(),
parentTraceId: undefined,
command: String(command),
result,
timestamp: new Date().toISOString(),
};
if (includeArgs && args !== undefined) {
event.args = args;
}
return Object.freeze(event);
}
module.exports = { makeDispatchEvent };

View File

@@ -0,0 +1,174 @@
'use strict';
/**
* DispatchLogger interface + default implementation — issue #177 (ADR-0174 P1.3).
*
* Interface:
* { onEvent(event: DispatchEvent): void }
*
* Default behaviour (createDefaultLogger):
* 1. Silent on success — no stdout/stderr when result.kind === 'ok'.
* 2. Structured JSON to stderr on error — one line per dispatch error.
* 3. Opt-in audit file — when GSD_AUDIT=1 OR config.audit.enabled===true,
* appends every event (success + error) as one JSON line to
* .planning/.gsd-trace.jsonl relative to `cwd`. Creates .planning/ if absent.
* 4. Args redaction — args omitted by default; included when GSD_AUDIT_ARGS=1.
*
* No-op logger (createNoOpLogger):
* Silent on all events. Used as the Hub default when no logger is injected.
*/
const fs = require('fs');
const path = require('path');
const { redactEvent, shouldIncludeArgs } = require('./redaction.cjs');
const AUDIT_FILE_NAME = '.gsd-trace.jsonl';
const PLANNING_DIR = '.planning';
// ─── helpers ─────────────────────────────────────────────────────────────────
/**
* Safely serialise a value to JSON, falling back to a placeholder on circular refs.
* @param {unknown} value
* @returns {string}
*/
function _safeStringify(value) {
try {
return JSON.stringify(value);
} catch {
return JSON.stringify({ _serializationError: true });
}
}
/**
* Determine whether the audit file should be written to.
*
* @param {{ audit?: { enabled?: boolean } } | undefined} config
* @returns {boolean}
*/
function _isAuditEnabled(config) {
if (process.env.GSD_AUDIT === '1') return true;
if (config && config.audit && config.audit.enabled === true) return true;
return false;
}
/**
* Build the redacted plain object for the audit file.
* Preserves the full DispatchEvent structure.
*
* @param {object} event - DispatchEvent
* @returns {object}
*/
function _toAuditRecord(event) {
return redactEvent(event);
}
/**
* Build the flattened stderr error line.
*
* Per ADR-0174 P1.3 contract: { "kind": "<variant>", "traceId": "<uuid>", ...typedPayload }
* The result's kind is promoted to top-level and the typed payload fields are spread in.
* The `result` wrapper is removed.
*
* @param {object} event - DispatchEvent with an error result
* @returns {object}
*/
function _toStderrRecord(event) {
const redacted = redactEvent(event);
const { result, ...eventWithoutResult } = redacted;
// Flatten: top-level gets kind + typed payload fields from result
const { kind, ...typedPayload } = result;
return Object.assign({}, eventWithoutResult, { kind }, typedPayload);
}
/**
* Append one JSON line to the audit file.
* Creates .planning/ directory if it does not exist.
*
* Uses synchronous fs API (crash-safe for v1 — dispatch is synchronous).
*
* @param {string} cwd - Project root directory.
* @param {object} event - Redacted DispatchEvent.
*/
function _appendAuditLine(cwd, event) {
const planningDir = path.join(cwd, PLANNING_DIR);
// Ensure the directory exists
if (!fs.existsSync(planningDir)) {
fs.mkdirSync(planningDir, { recursive: true });
}
const auditPath = path.join(planningDir, AUDIT_FILE_NAME);
fs.appendFileSync(auditPath, _safeStringify(event) + '\n', 'utf8');
}
// ─── Public factories ─────────────────────────────────────────────────────────
/**
* Create a no-op logger. All events are silently dropped.
* This is the Hub's default when no logger is injected by the caller.
*
* @returns {{ onEvent(event: object): void }}
*/
function createNoOpLogger() {
return {
onEvent(_event) {
// intentionally empty
},
};
}
/**
* Create the default DispatchLogger.
*
* @param {object} [opts]
* @param {string} [opts.cwd=process.cwd()] - Project root; audit file is written relative to this.
* @param {object} [opts.config] - GSD config object. config.audit.enabled triggers audit.
* @returns {{ onEvent(event: object): void }}
*/
function createDefaultLogger({ cwd = process.cwd(), config } = {}) {
return {
/**
* @param {object} event - A DispatchEvent from the Hub.
*/
onEvent(event) {
const isOk = event && event.result && event.result.kind === 'ok';
// ── Audit file (both ok and error) ────────────────────────────────────
if (_isAuditEnabled(config)) {
try {
const auditRecord = _toAuditRecord(event);
_appendAuditLine(cwd, auditRecord);
} catch (auditErr) {
// Audit errors must not surface to callers
process.stderr.write(
_safeStringify({
level: 'warn',
source: 'DispatchLogger',
message: 'audit file write failed: ' + String(auditErr && auditErr.message || auditErr),
}) + '\n'
);
}
}
// ── Stderr on error ───────────────────────────────────────────────────
if (!isOk) {
try {
const stderrRecord = _toStderrRecord(event);
process.stderr.write(_safeStringify(stderrRecord) + '\n');
} catch (stderrErr) {
// Last-resort: we cannot throw from the logger
process.stderr.write(
_safeStringify({
level: 'warn',
source: 'DispatchLogger',
message: 'stderr emit failed: ' + String(stderrErr && stderrErr.message || stderrErr),
}) + '\n'
);
}
}
// ── Silent on success (no else branch needed) ─────────────────────────
},
};
}
module.exports = { createDefaultLogger, createNoOpLogger };

View File

@@ -0,0 +1,50 @@
'use strict';
/**
* Arg redaction policy — issue #177 (ADR-0174 P1.3).
*
* Privacy default: args are OMITTED from every emitted event (both stderr
* and file audit). Opt-in: set GSD_AUDIT_ARGS=1 to include args verbatim.
*
* This module is deliberately simple and has no side effects — redaction
* decisions are stateless reads of process.env at call time so that tests
* can toggle the env var without module-level caching issues.
*/
/**
* Returns true when the caller has opted in to including args in events.
* Only GSD_AUDIT_ARGS === '1' enables inclusion; any other value (including
* empty string, 'true', 'yes') keeps the default of omitting args.
*
* @returns {boolean}
*/
function shouldIncludeArgs() {
return process.env.GSD_AUDIT_ARGS === '1';
}
/**
* Return a redacted copy of a DispatchEvent.
*
* If args should be omitted (default), strips the `args` field entirely.
* If args should be included (GSD_AUDIT_ARGS=1), passes the event through
* unchanged (args were already set by makeDispatchEvent with includeArgs:true,
* or absent — in which case they stay absent).
*
* The original event object is never mutated (it is frozen by makeDispatchEvent).
*
* @param {object} event - A DispatchEvent (frozen or plain).
* @returns {object} A new plain object with the same fields, minus args when redacted.
*/
function redactEvent(event) {
if (shouldIncludeArgs()) {
// Include path: return a shallow copy with args preserved if present
const copy = Object.assign({}, event);
return copy;
}
// Exclude path: build a copy omitting `args`
const { args: _dropped, ...rest } = event;
return rest;
}
module.exports = { shouldIncludeArgs, redactEvent };