# @tomflow/chatloop-trace

Trace is the **read-only evidence/observation domain**, not a business
authorization, receipt authority, browser driver or second job scheduler.
The existing Tools Supervisor remains the sole authoritative Trace JSONL
writer; Tools Trace Gateway provides scoped diagnosis only.

## Public npm SDK

The root exposes two data APIs and one opt-in, non-authoritative observation port:

- `subscribeTraceApiLog(listener)`: Tools attaches a best-effort collector
  to the existing Supervisor. The writer's own `record/recordControl`
  telemetry is filtered at that boundary to prevent feedback loops. A
  standalone SDK stays installable and never creates another logging service.
- `createTraceWriter({filePath})`: the Supervisor invokes
  `record(event)`, `recordControl(event,detail)` and `health()`.
- `createTraceReader({filePath,allowedProjects})`: the Gateway invokes
  `diagnose({projectRef,traceId|sessionRef,maxEvents})`, `apiUsage({windowMinutes,limit})`
  or `health()`. `apiUsage` requires a Reader explicitly scoped to
  `api_system` and returns only grouped method names, counts, success/failure
  totals and calls/minute; it never returns request content.
  No raw `query`, no CLI, service, daemon, additional storage or Browser Owner.

Trace `0.4.0` is a **source candidate**. Existing Tools versions retain
their independently pinned Trace version until separately verified and
upgraded; tests here do not prove a deployed Supervisor changed.

## Event contracts and extension

`events/<event-id>.mjs` owns the schema-v2 domain-specific validator,
error code and human purpose for a typed event family. The single
`scripts/build-events.mjs` command composes these **at build time** into
`events.generated.mjs`; `index.mjs` injects the static catalog into
the private Writer/Reader implementation. No runtime scanning, external
registration, secondary hand-maintained API catalog or duplicated validation
between writing and reading.

New typed event families must use the `typed.*` namespace. Removing a
specialized module makes that typed event **unregistered**: the Writer rejects
it, and the Reader treats old/forged matching lines as untrusted. Historical
generic event names retain their established read/write behavior.

The canonical envelope also reserves the `api` field exclusively for
`context.api`. **No newly declared typed event can claim API metadata**, even
with a permissive validator. Each validator receives a read-only copy of the
event: it cannot rewrite an event's `projectRef`, status or identifiers during
writing or diagnosis. A family may declare a `usageName(event)` projection
to join scoped API usage aggregation without modifying Reader's event dispatch.
New typed families must namespace projected names under their own family ID;
this does not add Project permissions or authorize actions.

The built-in `context.api` event is protected: it requires
`component=context`, status `BEGIN/CONFIRMED/FAILED`, and only
`api:{name,surface,mode}` with validated values. Removing or weakening
this contract blocks the build. Generic events cannot add `api` or new
arbitrary payload fields. Additional event families can constrain the
**same reviewed v2 envelope** without modifying the Writer/Reader Core.
Adding new envelope fields or granting new write authority is a separate
schema/security change, not a plugin escape hatch.

To add a typed event contract:

1. Create `events/<id>.mjs` exporting
   `capability={id,schemaVersion:2,errorCode,description,validate(v)}`
   (and optional `usageName(v)` for safe usage aggregation).
2. Run `npm run build:events`; it regenerates the only static catalog.
3. Run `npm run build:events:check`, `npm test` and workspace `npm run check`.

`test/event-composition.test.mjs` verifies that a temporary additional
event contract is accepted by **both** the Writer and the Reader and can be
removed without modifying existing Core code. Malformed or unauthorized
event-family records are rejected in both directions.

## Immutable observability boundaries

All newly written records use schema v2 with a bounded, canonical JSONL
envelope: `time`, `eventId`, `traceId`, `spanId`, optional
`parentSpanId`, `writerEpoch`, `writerSeq`, `component`, `event`,
`status`, scoped `projectRef/taskRef/sessionRef`, `generation`,
`requestId/actionId/evidenceRef`, optional `api`, `durationMs`,
and `errorCode`.

No user content, cookies, credentials, raw tool arguments or arbitrary
nested result objects can enter v2 records. Existing legacy evidence is
read-only, never migrated into a new current receipt or permission.

The SDK verifies file owner, permissions, symlink safety and bounds event
and query sizes. Diagnostics expose truncation, corrupted lines, writer
restarts, legacy records and pending receipts as **uncertainty**. They never
grant approval, Context write rights, Owner transfer or automatic retry.
A missing or interrupted Writer must be checked against the authoritative
business receipt, not inferred from a Trace event.

The npm package includes only the SDK root, generated event catalog,
event definitions, private implementation and this README. It contains no
independent API documentation or unnecessary executable.
