@happyvertical/smrt-core 0.40.22 → 0.40.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -3,8 +3,20 @@
3
3
  ORM, code generation, AI integration, and the DispatchBus. Everything else builds on this.
4
4
 
5
5
  Key surfaces are `SmrtObject`, `SmrtCollection`, `ObjectRegistry`,
6
- `DispatchBus`, `GlobalInterceptors`, and `LearningMemory`; the sections below
7
- document their invariants and source locations.
6
+ `DispatchBus`, `GlobalInterceptors`, and `LearningMemory`; this file documents
7
+ their invariants and source locations, and the module docs below cover the
8
+ per-subsystem semantics.
9
+
10
+ ## Modules
11
+
12
+ Subsystem semantics live in sibling module docs — read the one for the
13
+ subsystem you are editing. This file keeps what holds across all of them.
14
+
15
+ | Module | Scope | Module doc |
16
+ |---|---|---|
17
+ | `src/change-feed.ts` | the adapter-agnostic change-observation spine — `_smrt_changes`, cursors, table versions, generated `_changes` routes, retention | [agents/change-feed.md](agents/change-feed.md) |
18
+ | `src/change-signals.ts` + the generated `_events` SSE route | the push companion to the change feed — the signal bus, cross-replica fan-out, the SSE route, and its documented gaps | [agents/change-signals.md](agents/change-signals.md) |
19
+ | `src/generators/` + `src/vite-plugin/web-collections.ts` | REST/CLI/MCP/web-collection generation, the `manifestHash` emission sites, and generated conditional-GET / ETag v2 semantics | [agents/generators.md](agents/generators.md) |
8
20
 
9
21
  ## SmrtObject Lifecycle
10
22
 
@@ -96,26 +108,6 @@ admin auth.
96
108
  - Tables: `_smrt_dispatch`, `_smrt_dispatch_subscriptions`
97
109
  - Status: `pending → processing → completed` (or `failed`)
98
110
 
99
- ## Change Feed (#1758)
100
-
101
- Adapter-agnostic change-observation spine (`src/change-feed.ts`) — the server half of the client/mobile sync contract (PRD #1755):
102
-
103
- - `_smrt_changes` system table: one append per framework save/delete via a GlobalInterceptors writer registered at framework init. Deletes are tombstones (`operation: 'delete'`). `_smrt_*` tables are skipped. Feed-append failures log and never fail the user's write. On PostgreSQL, `_smrt_append_change` catches the INSERT in an exception subtransaction and returns SQLSTATE as data, so swallowing/retrying a best-effort failure cannot leave a caller-managed transaction aborted with `25P02` (#2026); the feed row still commits or rolls back with the caller transaction. Raw-handle/read initialization checks for both the table and helper before issuing any DDL; a cold schema/helper install acquires the same transaction-scoped `('smrt', 'system-tables')` advisory lock as bootstrap before its first DDL and rechecks inside one server-side statement, while schema migration/bootstrap remains the authoritative replace path. No dirty-check: a field-unchanged `.save()` appends a spurious `update` entry (diff-aware paths like `getOrUpsert`/sync-apply short-circuit before `save()` and append nothing); subscribers must tolerate spurious entries — they are convergent.
104
- - Sequences: allocated as `MAX(seq)+1` inside the INSERT with conflict retry — committed rows stay contiguous, so commit order == seq order on SQLite/Postgres/DuckDB (deliberately NOT identity/serial: those allocate before commit and break the cursor guarantee under concurrent writers).
105
- - `getChangesSince(db, { since, tables?, tenantId?, limit? }) → { changes, cursor, resyncRequired?, resyncCursor? }`: strictly monotonic cursor; polling with returned cursors misses no committed change and never repeats one. A cursor that cannot be served incrementally — pruned below the retained `[floor..horizon]` run, or foreign/ahead of the horizon — gets `resyncRequired: true` with empty `changes`, an unadvanced `cursor`, and `resyncCursor` set to the current horizon so clients can full-refetch then resume incrementally; detection runs on the UNFILTERED log so `tables`/`tenantId` filters never trigger or mask it. `getTenantScopedChangesSince()` resolves tenant via the DispatchBus resolver hook (fail-closed: tenancy on + no context → global rows only; tenant `T` sees `T` + global rows, never another tenant).
106
- - `getTableVersion(db, table) → number`: the per-table change version (`MAX(seq)` for the table, replica-stable — no per-process divergence), the ETag source for zero-query conditional GETs (#1765). Advances on any framework write to the table (CRUD and sync-apply, which all `save()`/`delete()`). A table with no retained entry of its own falls back to the global horizon (never a resettable low value) so an all-pruned table cannot false-304 a stale client; only 0 when the feed is empty.
107
- - Generated `_changes` routes: REST (`GET {basePath}/_changes`, requires `authMiddleware`, otherwise 401 — per-model `api.public` does NOT apply) and SvelteKit (`{routesDir}/_changes/+server.ts`, requires an authenticated principal on `locals`; opt out via `sveltekit.changesRoute.enabled: false`). Query params: `since`, `tables` (comma-separated), `limit`. Responses stay HTTP 200 in the resync state — `resyncRequired` is protocol state, not an error, and `resyncCursor` is the resume cursor after the client completes a full refetch.
108
- - Retention: `pruneChangeFeed(db, { maxAgeMs?, maxRows? })` — schedule it. Pruning deletes oldest-first and always retains the newest entry (a non-empty feed is never emptied), which is what makes pruned-cursor detection provable and keeps caught-up consumers polling normally. Raw-SQL writes are invisible to the feed (same documented gap as the #1499 cache); `bumpChangeFeed(db, { table, rowId? })` is the manual escape hatch.
109
-
110
- ## Live Events / Change Signals (#1763, server half)
111
-
112
- The push companion to the change feed (`src/change-signals.ts` + the generated `_events` SSE route) — the server half of live cache invalidation (PRD #1755). The client subscriber (two-client/reconnect/polling-fallback ACs) is a separate later slice.
113
-
114
- - **Change-signal bus** (`src/change-signals.ts`): every framework save/delete that appends a durable feed row also publishes a coarse `ChangeSignal` `{ table, operation, rowId, tenantId, seq }` — **never a row payload** (authorization stays on the read path). Structurally mirrors the collection cache's notify/listen path. `subscribeToChangeSignals(db, listener) → unsubscribe`; `publishChangeSignal`/`broadcastChangeSignal`/the listener loop stay internal. `appendChange` now returns the allocated `seq` (was `void`); the signal carries it as a coarse resume cursor (`bumpChangeFeed` ignores the return). The publish runs only after the append SUCCEEDS (no signal without a durable feed row) and in its own log-and-swallow try/catch, so a signal problem never fails the user's write. `_smrt_*` writes never signal (the writer skips them). Delivery is synchronous per-listener with per-listener try/catch (one throwing SSE controller never blocks others); no per-subscriber queue — backpressure rides the platform `ReadableStream`.
115
- - **In-process + cross-replica**: locally-published and peer-received signals go through the SAME `deliverLocally` path. Cross-replica fan-out rides the db adapter's optional notification capability (`db.notifications`, a NEW `smrt_change_signals` channel distinct from the cache channel) with echo-avoidance by `PROCESS_ID`. No capability → in-process only, warn-once, **never an error, never blocks the write** (subscribers on other replicas fall back to cursor polling).
116
- - **Generated `_events` SSE route**: REST (`GET {basePath}/_events`, requires `authMiddleware`, otherwise 401 — fail-closed, per-model `api.public` does NOT apply; 405 non-GET; 503 no db or subscriber capacity reached) and SvelteKit (`{routesDir}/_events/+server.ts`, requires an authenticated principal on `locals`; opt out via `sveltekit.eventsRoute.enabled: false`; cap via `sveltekit.eventsRoute.maxSubscribers`, where `0` means unlimited). Tenant scope is captured ONCE at connection open (`resolveDispatchTenantScope`) and filtered server-side per signal via `signalVisibleToTenant` (same rule as `getChangesSince`'s tenant filter) before any byte hits the wire — delivery runs outside any tenant ALS context, so it must use the captured value. The stream lifecycle lives in `buildChangeEventStream(db, { cursor, tenantScope, heartbeatMs?, manifestHash? })` (exported; the SvelteKit route imports it so it stays thin): subscribe-before-catch-up (closes the gap window; overlap is deduped by the SSE `id:`/seq client-side), `retry: 3000`, optional connection-open `event: manifest` carrying `{ manifestHash }` for live contract detection, cursor catch-up via `getChangesSince` filtered by the CAPTURED scope (not re-resolved from ALS, so it matches the live-signal filter exactly and can't replay another tenant's rows) (`Last-Event-ID` header beats `?since=`; default = live-forward only; `resyncRequired` → `event: resync`), heartbeat (`DEFAULT_EVENTS_HEARTBEAT_MS` = 15s), and `cancel()` teardown (clears heartbeat + unsubscribes). SSE change frame: `id: <seq>\nevent: change\ndata: {table,operation,rowId,tenantId}\n\n` — seq is ONLY in the `id:` line, never the data JSON. Subscriber cap default is `DEFAULT_EVENTS_MAX_SUBSCRIBERS` = 1000; over-cap connections return retryable 503 + `Retry-After`, and existing subscribers are unaffected. **Cross-origin is opt-in and fail-closed (#1861)**: same-origin only by default. REST wraps `_events` in its CORS layer — set `enableCors` + an explicit `allowedOrigins` allowlist + `allowCredentials: true` and an allow-listed browser can subscribe with a credentialed `EventSource` (`withCredentials: true`); the response echoes the specific `Origin` (never `*`) plus `Access-Control-Allow-Credentials: true`. SvelteKit mirrors this via `sveltekit.eventsRoute.allowedOrigins` + `allowCredentials` (the generated route bakes the allowlist into a `Set`, echoes only a member origin, and answers a credentialed `OPTIONS` preflight). CORS never authorizes — the fail-closed auth guard and captured tenant scope are unchanged, so the read posture holds identically across origins; it only lets an allow-listed browser's cookies reach the guard. Client disconnect through the Node `createServer` bridge now cancels the response reader (was a teardown leak) so `cancel()` fires and the subscription is released.
117
- - **Known gaps** (documented in the module): raw-SQL writes don't signal (same gap as the feed); live signals for caller-managed-transaction writes are best-effort (the append + signal fire pre-commit, so a rolled-back write may emit a signal and its freed seq is later reused) — the autocommit default path is exact, and clients reconcile via full catch-up/resync (inherits the change feed's transaction caveat).
118
-
119
111
  ## Single Table Inheritance (STI)
120
112
 
121
113
  - Base: `@smrt({ tableStrategy: 'sti' })` — children inherit, share one table
@@ -124,29 +116,6 @@ The push companion to the change feed (`src/change-signals.ts` + the generated `
124
116
  - Polymorphic queries: collection loads `_meta_type`, creates correct subclass dynamically
125
117
  - Validation: fail-fast on save if `_meta_type` missing or mismatched
126
118
 
127
- ## Code Generators
128
-
129
- | Generator | Location | Output |
130
- |-----------|----------|--------|
131
- | REST API | `src/generators/rest.ts` | OpenAPI-compliant CRUD endpoints |
132
- | CLI | `src/generators/cli.ts` | `objectname:action` admin commands — writable allowlist, exhaustive-include, `--from-file`, fail-closed tenant context |
133
- | MCP Server | `src/generators/mcp.ts` | Model Context Protocol tools |
134
- | Web collections | `src/vite-plugin/web-collections.ts` (selectors) + `generateWebModule` | `@happyvertical/smrt-virt-web` — one typed collection definition per API-exposed REST collection (#1761), consumed by `@happyvertical/smrt-web` |
135
-
136
- Generated API clients share `selectApiClientEntries()` across the runtime Vite
137
- module, its ambient declaration, and physical prebuild declarations. When a
138
- collection class and its populated model share an endpoint, the model owns the
139
- canonical collection key and row payload schema; the collection class remains
140
- available under a deterministic class-derived secondary key. Selection and
141
- collision suffixes must not depend on manifest insertion order (#2027).
142
- For aggregated manifests, inheritance and item-type references resolve exact
143
- qualified names first, then package-local simple names, then a stable identity
144
- fallback so duplicate class names across packages cannot reintroduce ordering.
145
-
146
- The web module also emits a build-time **`manifestHash`** constant (#1764): `computeWebManifestHash(manifest)` is a deterministic, replica-stable digest of the emitted web-collection SHAPE (name/className/endpoint/idField/actions/fields/relationships), canonicalized (recursive key sort) before `sha256 → base64url`, truncated to 16 chars — so the same schema always hashes the same, and a field add/remove/type-change/edge-change changes it. A change means old persisted client rows may mis-hydrate, so smrt-web keys its durable persistence namespace on it and its `updateAvailable` contract signal compares against it. Three emission sites must not drift: the runtime value (`generateWebModule`), the `@happyvertical/smrt-virt-web` ambient d.ts (`vite-plugin/index.ts`), and the physical `@smrt/web` d.ts (`prebuild/index.ts`).
147
-
148
- Generated reads (`list`/`get`) on the REST and SvelteKit generators support conditional GET (helpers in `src/generators/conditional-get.ts`). ETag v2 (#1765): the validator is the table's change-feed version (`getTableVersion`) keyed by the request representation, so a **concrete** `If-None-Match` short-circuits into a 304 with an empty body **before** the collection query runs — an unchanged table revalidates with zero table scan. A wildcard `If-None-Match: *` is deferred until the payload builds (existence confirmed), so a missing item still returns 404, not a false 304. Tenant-scoped reads fold the active tenant into the representation (`resolveTenantEtagDiscriminator`) so one tenant's cached validator never satisfies another's read of the same URL. Routes whose GET renders via a **custom serializer** (which can load related tables the base-table version can't observe) keep the v1 body-hash ETag (`#1757`, query-first but correct); the default `toPublicJSON` path — all REST reads and non-serializer SvelteKit reads — uses v2. v2 is weakly consistent by design (the cost of not reading the data): a revalidation in the sub-statement window between a committed write and its feed append can return a stale 304 that self-heals on the next revalidation. The other v2 window — a deploy that changes the response shape WITHOUT a table write — is closed by the **#1764 ETag salt**: `computeTableVersionEtag(version, representation, manifestHash?)` folds the build's web-collection shape digest into the digest, so a shape-only redeploy busts every read validator (`undefined` reproduces the pre-#1764 unsalted value byte-for-byte for direct helper callers). The generated SvelteKit route bakes the digest in as a `MANIFEST_HASH` constant (via `generateConditionalGetRouteHelper`'s `manifestHash` option, sourced from `computeWebManifestHash(manifest)`) — automatic for the SvelteKit transport. The runtime `APIGenerator` auto-populates the same salt from the runtime registry with `computeRuntimeWebManifestHash()` when `APIConfig.manifestHash` is omitted; explicit `APIConfig.manifestHash` still wins for custom setups. The digest scope is get-OR-list (`selectWebEtagSaltEntries`), so **get-only** routes are salted too. Strong consistency still requires the v1 body-hash path. Cache-Control policy (unchanged from #1757): `private, no-cache` by default; public models may opt into shared caching via `@smrt({ api: { public: true | 'read', cache: { sMaxage } } })` → `public, max-age=0, s-maxage=<n>`; non-public models never emit shared-cache headers. Tenant-scoped models (any mode) never emit them either — bodies vary with session-cookie tenant context that URL-keyed shared caches cannot see; `sMaxage` is neutralized to `private, no-cache` with a one-time warning.
149
-
150
119
  ## Child Accessors (R10)
151
120
 
152
121
  `src/child-accessors.ts` installs a consistent `get<FieldName>()` instance method for every `@oneToMany` field at `@smrt()` registration time (e.g. `@oneToMany('OrderItem') items` → `order.getItems()`), delegating to `loadRelatedMany`. Two invariants:
@@ -0,0 +1,16 @@
1
+ # smrt-core/change feed
2
+
3
+ Module semantics for `src/change-feed.ts`. Package orientation, the cross-module
4
+ invariants, and the traps that apply before editing anything live in
5
+ [../AGENTS.md](../AGENTS.md) — read that first.
6
+
7
+ ## Change Feed (#1758)
8
+
9
+ Adapter-agnostic change-observation spine (`src/change-feed.ts`) — the server half of the client/mobile sync contract (PRD #1755):
10
+
11
+ - `_smrt_changes` system table: one append per framework save/delete via a GlobalInterceptors writer registered at framework init. Deletes are tombstones (`operation: 'delete'`). `_smrt_*` tables are skipped. Feed-append failures log and never fail the user's write. On PostgreSQL, `_smrt_append_change` catches the INSERT in an exception subtransaction and returns SQLSTATE as data, so swallowing/retrying a best-effort failure cannot leave a caller-managed transaction aborted with `25P02` (#2026); the feed row still commits or rolls back with the caller transaction. Raw-handle/read initialization checks for both the table and helper before issuing any DDL; a cold schema/helper install acquires the same transaction-scoped `('smrt', 'system-tables')` advisory lock as bootstrap before its first DDL and rechecks inside one server-side statement, while schema migration/bootstrap remains the authoritative replace path. No dirty-check: a field-unchanged `.save()` appends a spurious `update` entry (diff-aware paths like `getOrUpsert`/sync-apply short-circuit before `save()` and append nothing); subscribers must tolerate spurious entries — they are convergent.
12
+ - Sequences: allocated as `MAX(seq)+1` inside the INSERT with conflict retry — committed rows stay contiguous, so commit order == seq order on SQLite/Postgres/DuckDB (deliberately NOT identity/serial: those allocate before commit and break the cursor guarantee under concurrent writers).
13
+ - `getChangesSince(db, { since, tables?, tenantId?, limit? }) → { changes, cursor, resyncRequired?, resyncCursor? }`: strictly monotonic cursor; polling with returned cursors misses no committed change and never repeats one. A cursor that cannot be served incrementally — pruned below the retained `[floor..horizon]` run, or foreign/ahead of the horizon — gets `resyncRequired: true` with empty `changes`, an unadvanced `cursor`, and `resyncCursor` set to the current horizon so clients can full-refetch then resume incrementally; detection runs on the UNFILTERED log so `tables`/`tenantId` filters never trigger or mask it. `getTenantScopedChangesSince()` resolves tenant via the DispatchBus resolver hook (fail-closed: tenancy on + no context → global rows only; tenant `T` sees `T` + global rows, never another tenant).
14
+ - `getTableVersion(db, table) → number`: the per-table change version (`MAX(seq)` for the table, replica-stable — no per-process divergence), the ETag source for zero-query conditional GETs (#1765). Advances on any framework write to the table (CRUD and sync-apply, which all `save()`/`delete()`). A table with no retained entry of its own falls back to the global horizon (never a resettable low value) so an all-pruned table cannot false-304 a stale client; only 0 when the feed is empty.
15
+ - Generated `_changes` routes: REST (`GET {basePath}/_changes`, requires `authMiddleware`, otherwise 401 — per-model `api.public` does NOT apply) and SvelteKit (`{routesDir}/_changes/+server.ts`, requires an authenticated principal on `locals`; opt out via `sveltekit.changesRoute.enabled: false`). Query params: `since`, `tables` (comma-separated), `limit`. Responses stay HTTP 200 in the resync state — `resyncRequired` is protocol state, not an error, and `resyncCursor` is the resume cursor after the client completes a full refetch.
16
+ - Retention: `pruneChangeFeed(db, { maxAgeMs?, maxRows? })` — schedule it. Pruning deletes oldest-first and always retains the newest entry (a non-empty feed is never emptied), which is what makes pruned-cursor detection provable and keeps caught-up consumers polling normally. Raw-SQL writes are invisible to the feed (same documented gap as the #1499 cache); `bumpChangeFeed(db, { table, rowId? })` is the manual escape hatch.
@@ -0,0 +1,14 @@
1
+ # smrt-core/change signals / live events
2
+
3
+ Module semantics for `src/change-signals.ts` + the generated `_events` SSE route. Package orientation, the cross-module
4
+ invariants, and the traps that apply before editing anything live in
5
+ [../AGENTS.md](../AGENTS.md) — read that first.
6
+
7
+ ## Live Events / Change Signals (#1763, server half)
8
+
9
+ The push companion to the change feed (`src/change-signals.ts` + the generated `_events` SSE route) — the server half of live cache invalidation (PRD #1755). The client subscriber (two-client/reconnect/polling-fallback ACs) is a separate later slice.
10
+
11
+ - **Change-signal bus** (`src/change-signals.ts`): every framework save/delete that appends a durable feed row also publishes a coarse `ChangeSignal` `{ table, operation, rowId, tenantId, seq }` — **never a row payload** (authorization stays on the read path). Structurally mirrors the collection cache's notify/listen path. `subscribeToChangeSignals(db, listener) → unsubscribe`; `publishChangeSignal`/`broadcastChangeSignal`/the listener loop stay internal. `appendChange` now returns the allocated `seq` (was `void`); the signal carries it as a coarse resume cursor (`bumpChangeFeed` ignores the return). The publish runs only after the append SUCCEEDS (no signal without a durable feed row) and in its own log-and-swallow try/catch, so a signal problem never fails the user's write. `_smrt_*` writes never signal (the writer skips them). Delivery is synchronous per-listener with per-listener try/catch (one throwing SSE controller never blocks others); no per-subscriber queue — backpressure rides the platform `ReadableStream`.
12
+ - **In-process + cross-replica**: locally-published and peer-received signals go through the SAME `deliverLocally` path. Cross-replica fan-out rides the db adapter's optional notification capability (`db.notifications`, a NEW `smrt_change_signals` channel distinct from the cache channel) with echo-avoidance by `PROCESS_ID`. No capability → in-process only, warn-once, **never an error, never blocks the write** (subscribers on other replicas fall back to cursor polling).
13
+ - **Generated `_events` SSE route**: REST (`GET {basePath}/_events`, requires `authMiddleware`, otherwise 401 — fail-closed, per-model `api.public` does NOT apply; 405 non-GET; 503 no db or subscriber capacity reached) and SvelteKit (`{routesDir}/_events/+server.ts`, requires an authenticated principal on `locals`; opt out via `sveltekit.eventsRoute.enabled: false`; cap via `sveltekit.eventsRoute.maxSubscribers`, where `0` means unlimited). Tenant scope is captured ONCE at connection open (`resolveDispatchTenantScope`) and filtered server-side per signal via `signalVisibleToTenant` (same rule as `getChangesSince`'s tenant filter) before any byte hits the wire — delivery runs outside any tenant ALS context, so it must use the captured value. The stream lifecycle lives in `buildChangeEventStream(db, { cursor, tenantScope, heartbeatMs?, manifestHash? })` (exported; the SvelteKit route imports it so it stays thin): subscribe-before-catch-up (closes the gap window; overlap is deduped by the SSE `id:`/seq client-side), `retry: 3000`, optional connection-open `event: manifest` carrying `{ manifestHash }` for live contract detection, cursor catch-up via `getChangesSince` filtered by the CAPTURED scope (not re-resolved from ALS, so it matches the live-signal filter exactly and can't replay another tenant's rows) (`Last-Event-ID` header beats `?since=`; default = live-forward only; `resyncRequired` → `event: resync`), heartbeat (`DEFAULT_EVENTS_HEARTBEAT_MS` = 15s), and `cancel()` teardown (clears heartbeat + unsubscribes). SSE change frame: `id: <seq>\nevent: change\ndata: {table,operation,rowId,tenantId}\n\n` — seq is ONLY in the `id:` line, never the data JSON. Subscriber cap default is `DEFAULT_EVENTS_MAX_SUBSCRIBERS` = 1000; over-cap connections return retryable 503 + `Retry-After`, and existing subscribers are unaffected. **Cross-origin is opt-in and fail-closed (#1861)**: same-origin only by default. REST wraps `_events` in its CORS layer — set `enableCors` + an explicit `allowedOrigins` allowlist + `allowCredentials: true` and an allow-listed browser can subscribe with a credentialed `EventSource` (`withCredentials: true`); the response echoes the specific `Origin` (never `*`) plus `Access-Control-Allow-Credentials: true`. SvelteKit mirrors this via `sveltekit.eventsRoute.allowedOrigins` + `allowCredentials` (the generated route bakes the allowlist into a `Set`, echoes only a member origin, and answers a credentialed `OPTIONS` preflight). CORS never authorizes — the fail-closed auth guard and captured tenant scope are unchanged, so the read posture holds identically across origins; it only lets an allow-listed browser's cookies reach the guard. Client disconnect through the Node `createServer` bridge now cancels the response reader (was a teardown leak) so `cancel()` fires and the subscription is released.
14
+ - **Known gaps** (documented in the module): raw-SQL writes don't signal (same gap as the feed); live signals for caller-managed-transaction writes are best-effort (the append + signal fire pre-commit, so a rolled-back write may emit a signal and its freed seq is later reused) — the autocommit default path is exact, and clients reconcile via full catch-up/resync (inherits the change feed's transaction caveat).
@@ -0,0 +1,28 @@
1
+ # smrt-core/code generators
2
+
3
+ Module semantics for `src/generators/` + `src/vite-plugin/`. Package orientation, the cross-module
4
+ invariants, and the traps that apply before editing anything live in
5
+ [../AGENTS.md](../AGENTS.md) — read that first.
6
+
7
+ ## Code Generators
8
+
9
+ | Generator | Location | Output |
10
+ |-----------|----------|--------|
11
+ | REST API | `src/generators/rest.ts` | OpenAPI-compliant CRUD endpoints |
12
+ | CLI | `src/generators/cli.ts` | `objectname:action` admin commands — writable allowlist, exhaustive-include, `--from-file`, fail-closed tenant context |
13
+ | MCP Server | `src/generators/mcp.ts` | Model Context Protocol tools |
14
+ | Web collections | `src/vite-plugin/web-collections.ts` (selectors) + `generateWebModule` | `@happyvertical/smrt-virt-web` — one typed collection definition per API-exposed REST collection (#1761), consumed by `@happyvertical/smrt-web` |
15
+
16
+ Generated API clients share `selectApiClientEntries()` across the runtime Vite
17
+ module, its ambient declaration, and physical prebuild declarations. When a
18
+ collection class and its populated model share an endpoint, the model owns the
19
+ canonical collection key and row payload schema; the collection class remains
20
+ available under a deterministic class-derived secondary key. Selection and
21
+ collision suffixes must not depend on manifest insertion order (#2027).
22
+ For aggregated manifests, inheritance and item-type references resolve exact
23
+ qualified names first, then package-local simple names, then a stable identity
24
+ fallback so duplicate class names across packages cannot reintroduce ordering.
25
+
26
+ The web module also emits a build-time **`manifestHash`** constant (#1764): `computeWebManifestHash(manifest)` is a deterministic, replica-stable digest of the emitted web-collection SHAPE (name/className/endpoint/idField/actions/fields/relationships), canonicalized (recursive key sort) before `sha256 → base64url`, truncated to 16 chars — so the same schema always hashes the same, and a field add/remove/type-change/edge-change changes it. A change means old persisted client rows may mis-hydrate, so smrt-web keys its durable persistence namespace on it and its `updateAvailable` contract signal compares against it. Three emission sites must not drift: the runtime value (`generateWebModule`), the `@happyvertical/smrt-virt-web` ambient d.ts (`vite-plugin/index.ts`), and the physical `@smrt/web` d.ts (`prebuild/index.ts`).
27
+
28
+ Generated reads (`list`/`get`) on the REST and SvelteKit generators support conditional GET (helpers in `src/generators/conditional-get.ts`). ETag v2 (#1765): the validator is the table's change-feed version (`getTableVersion`) keyed by the request representation, so a **concrete** `If-None-Match` short-circuits into a 304 with an empty body **before** the collection query runs — an unchanged table revalidates with zero table scan. A wildcard `If-None-Match: *` is deferred until the payload builds (existence confirmed), so a missing item still returns 404, not a false 304. Tenant-scoped reads fold the active tenant into the representation (`resolveTenantEtagDiscriminator`) so one tenant's cached validator never satisfies another's read of the same URL. Routes whose GET renders via a **custom serializer** (which can load related tables the base-table version can't observe) keep the v1 body-hash ETag (`#1757`, query-first but correct); the default `toPublicJSON` path — all REST reads and non-serializer SvelteKit reads — uses v2. v2 is weakly consistent by design (the cost of not reading the data): a revalidation in the sub-statement window between a committed write and its feed append can return a stale 304 that self-heals on the next revalidation. The other v2 window — a deploy that changes the response shape WITHOUT a table write — is closed by the **#1764 ETag salt**: `computeTableVersionEtag(version, representation, manifestHash?)` folds the build's web-collection shape digest into the digest, so a shape-only redeploy busts every read validator (`undefined` reproduces the pre-#1764 unsalted value byte-for-byte for direct helper callers). The generated SvelteKit route bakes the digest in as a `MANIFEST_HASH` constant (via `generateConditionalGetRouteHelper`'s `manifestHash` option, sourced from `computeWebManifestHash(manifest)`) — automatic for the SvelteKit transport. The runtime `APIGenerator` auto-populates the same salt from the runtime registry with `computeRuntimeWebManifestHash()` when `APIConfig.manifestHash` is omitted; explicit `APIConfig.manifestHash` still wins for custom setups. The digest scope is get-OR-list (`selectWebEtagSaltEntries`), so **get-only** routes are salted too. Strong consistency still requires the v1 body-hash path. Cache-Control policy (unchanged from #1757): `private, no-cache` by default; public models may opt into shared caching via `@smrt({ api: { public: true | 'read', cache: { sMaxage } } })` → `public, max-age=0, s-maxage=<n>`; non-public models never emit shared-cache headers. Tenant-scoped models (any mode) never emit them either — bodies vary with session-cookie tenant context that URL-keyed shared caches cannot see; `sMaxage` is neutralized to `private, no-cache` with a one-time warning.
package/dist/index.js CHANGED
@@ -55,7 +55,7 @@ import { generateOpenAPISpec, setupSwaggerUI } from "./generators/swagger.js";
55
55
  import "./generators/index.js";
56
56
  import { SmrtHierarchical } from "./hierarchical.js";
57
57
  import { SmrtJunction } from "./junction.js";
58
- import { buildDomainKnowledgeManifest } from "./knowledge.js";
58
+ import { MODULE_DOC_HASH_PREFIX, buildDomainKnowledgeManifest, readAgentModuleDocs, resolveAgentModuleDocPaths } from "./knowledge.js";
59
59
  import { getClassConfigResolvers, getConfigResolver, isLazyConfigSentinel, listConfigResolvers, registerConfigResolver, resetConfigResolvers, resolveLazyConfig, unregisterConfigResolver } from "./lazy-config.js";
60
60
  import { DEFAULT_LEARNING_CONFIG, LearningMemory } from "./learning/memory.js";
61
61
  import { ManifestBuilder } from "./manifest/generator.js";
@@ -71,4 +71,4 @@ import "./system/index.js";
71
71
  import { getTestDatabase } from "./testing/database.js";
72
72
  import "./tools/index.js";
73
73
  import { smrtPlugin } from "./vite-plugin/index.js";
74
- export { AIError, APIGenerator, AiUsageCollector, AiUsagePersistenceHandler, CACHE_INVALIDATION_CHANNEL, CHANGE_FEED_INTERCEPTOR_NAME, CHANGE_FEED_TABLE, CHANGE_SIGNAL_CHANNEL, CLIGenerator, ConfigurationError, ContentHasher, CosineSimilarity, DEFAULT_AI_COST_RATES, DEFAULT_CHANGES_LIMIT, DEFAULT_EMBEDDING_CONFIG, DEFAULT_EVENTS_HEARTBEAT_MS, DEFAULT_EVENTS_MAX_SUBSCRIBERS, DEFAULT_EVENTS_RETRY_AFTER_SECONDS, DEFAULT_LEARNING_CONFIG, DatabaseError, Dispatch, DispatchBus, DispatchCollection, DispatchSubscription, DispatchSubscriptionCollection, EmbeddingProvider, EmbeddingStorage, ErrorUtils, FilesystemError, GlobalInterceptors, LearningMemory, MAX_CHANGES_LIMIT, MAX_SYNC_APPLY_BATCH_SIZE, MCPGenerator, ManifestBuilder, ManifestGenerator, ManifestManager, MetricsAdapter, NetworkError, ObjectRegistry, PRIVATE_READ_CACHE_CONTROL, PubSubAdapter, RuntimeError, SMRT_COLLECTION_BASE_NAMES, SYNC_APPLY_ROUTE_SEGMENTS, SYNC_APPLY_UUID_PATTERN, SchemaComparer, SignalBus, SignalSanitizer, SmrtClass, SmrtCollection, SmrtError, SmrtHierarchical, SmrtJunction, SmrtMCPServer, SmrtObject, SmrtPolymorphicAssociation, TenantIsolationError, ValidationError, ValidationReport, ValidationUtils, appendChange, applyOneToManyChildAccessors, applyPendingDecoratorRegistrations, applySyncWritablePolicy, assertPostgresSystemTimestampsCurrent, broadcastCacheInvalidation, buildChangeEventStream, buildDomainKnowledgeManifest, bumpChangeFeed, canonicalReadRepresentation, changeEventSubscribersAtCapacity, childAccessorName, clone, computeBodyEtag, computeRuntimeWebManifestHash, computeTableVersionEtag, conditionalJsonResponse, config, convertTypeToJsonSchema, createDispatchBus, createFilesystemAdapter, createInterceptorContext, createMCPServer, createQualifiedName, createRestServer, createSmrtClient, createSmrtServer, crossPackageRef, detectEngine, discoverManifestEntry, ensureCacheInvalidationListener, ensureChangeFeedTable, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, estimateAiUsageCost, eventStreamCapacityExceededResponse, executeToolCall, executeToolCalls, field, findManifestEntryByQualifiedName, foreignKey, formatToolResults, generateDDLForEngine, generateOpenAPISpec, generateSchemaDiff, generateToolFromMethod, generateToolManifest, getAdapterInfo, getCLIHandler, getCacheGeneration, getChangesSince, getClassConfigResolvers, getClassName, getConfigResolver, getDatabaseEngine, getManifest, getPackageFromQualifiedName, getSQLFromDiff, getTableVersion, getTenantScopedChangesSince, getTestDatabase, hasActionableChanges, ifNoneMatchHasConcreteMatch, ifNoneMatchSatisfied, importOptionalDependency, invalidateCollectionCache, isDatabaseInterface, isFromPackage, isLazyConfigSentinel, isQualifiedName, isSmrtCollectionExtendsName, isStaleWrite, isTenantScopedClassResolved, isType, isValid, listConfigResolvers, loadExternalManifest, loadExternalManifestSync, loadLocalTestManifestSync, loadManifestFromPathSync, manifest, manyToMany, meta, migratePostgresSystemTimestamps, normalizeEventsMaxSubscribers, oneToMany, parse, parseQualifiedName, parseSyncApplyBatch, payloadMatchesRow, processSyncApplyBatch, pruneChangeFeed, qualifiedNamesEqual, registerChangeFeedWriter, registerCompatibleFieldDecorator, registerConfigResolver, registerFilesystemAdapterFactory, registerOptionalDependency, resetChangeFeedWarnings, resetChangeSignals, resetCollectionCache, resetConfigResolvers, resetVerifiedTables, resolveDatabase, resolveDbCacheKey, resolveDispatchTenantId, resolveDispatchTenantScope, resolveLazyConfig, resolveReadCacheControl, resolveTenantEtagDiscriminator, runWithTenantGate, safeParse, safeStringify, setDispatchTenantResolver, setTenantEntryPointRunner, setTenantScopedClassResolver, setupCLI, setupSwaggerUI, shouldIncludeMethod, signalVisibleToTenant, smrt, smrtPlugin, smrt as smrtRegistry, startRestServer, staticManifest, stopCacheInvalidationListeners, stopChangeSignalListeners, stringify, subscribeToChangeSignals, tableExists, tryReserveChangeEventSubscriberSlot, unregisterChangeFeedWriter, unregisterConfigResolver, validateSyncApplyItem, validateToolCall, versionConditionalResponse, warnIfSharedCacheNeutralized };
74
+ export { AIError, APIGenerator, AiUsageCollector, AiUsagePersistenceHandler, CACHE_INVALIDATION_CHANNEL, CHANGE_FEED_INTERCEPTOR_NAME, CHANGE_FEED_TABLE, CHANGE_SIGNAL_CHANNEL, CLIGenerator, ConfigurationError, ContentHasher, CosineSimilarity, DEFAULT_AI_COST_RATES, DEFAULT_CHANGES_LIMIT, DEFAULT_EMBEDDING_CONFIG, DEFAULT_EVENTS_HEARTBEAT_MS, DEFAULT_EVENTS_MAX_SUBSCRIBERS, DEFAULT_EVENTS_RETRY_AFTER_SECONDS, DEFAULT_LEARNING_CONFIG, DatabaseError, Dispatch, DispatchBus, DispatchCollection, DispatchSubscription, DispatchSubscriptionCollection, EmbeddingProvider, EmbeddingStorage, ErrorUtils, FilesystemError, GlobalInterceptors, LearningMemory, MAX_CHANGES_LIMIT, MAX_SYNC_APPLY_BATCH_SIZE, MCPGenerator, MODULE_DOC_HASH_PREFIX, ManifestBuilder, ManifestGenerator, ManifestManager, MetricsAdapter, NetworkError, ObjectRegistry, PRIVATE_READ_CACHE_CONTROL, PubSubAdapter, RuntimeError, SMRT_COLLECTION_BASE_NAMES, SYNC_APPLY_ROUTE_SEGMENTS, SYNC_APPLY_UUID_PATTERN, SchemaComparer, SignalBus, SignalSanitizer, SmrtClass, SmrtCollection, SmrtError, SmrtHierarchical, SmrtJunction, SmrtMCPServer, SmrtObject, SmrtPolymorphicAssociation, TenantIsolationError, ValidationError, ValidationReport, ValidationUtils, appendChange, applyOneToManyChildAccessors, applyPendingDecoratorRegistrations, applySyncWritablePolicy, assertPostgresSystemTimestampsCurrent, broadcastCacheInvalidation, buildChangeEventStream, buildDomainKnowledgeManifest, bumpChangeFeed, canonicalReadRepresentation, changeEventSubscribersAtCapacity, childAccessorName, clone, computeBodyEtag, computeRuntimeWebManifestHash, computeTableVersionEtag, conditionalJsonResponse, config, convertTypeToJsonSchema, createDispatchBus, createFilesystemAdapter, createInterceptorContext, createMCPServer, createQualifiedName, createRestServer, createSmrtClient, createSmrtServer, crossPackageRef, detectEngine, discoverManifestEntry, ensureCacheInvalidationListener, ensureChangeFeedTable, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, estimateAiUsageCost, eventStreamCapacityExceededResponse, executeToolCall, executeToolCalls, field, findManifestEntryByQualifiedName, foreignKey, formatToolResults, generateDDLForEngine, generateOpenAPISpec, generateSchemaDiff, generateToolFromMethod, generateToolManifest, getAdapterInfo, getCLIHandler, getCacheGeneration, getChangesSince, getClassConfigResolvers, getClassName, getConfigResolver, getDatabaseEngine, getManifest, getPackageFromQualifiedName, getSQLFromDiff, getTableVersion, getTenantScopedChangesSince, getTestDatabase, hasActionableChanges, ifNoneMatchHasConcreteMatch, ifNoneMatchSatisfied, importOptionalDependency, invalidateCollectionCache, isDatabaseInterface, isFromPackage, isLazyConfigSentinel, isQualifiedName, isSmrtCollectionExtendsName, isStaleWrite, isTenantScopedClassResolved, isType, isValid, listConfigResolvers, loadExternalManifest, loadExternalManifestSync, loadLocalTestManifestSync, loadManifestFromPathSync, manifest, manyToMany, meta, migratePostgresSystemTimestamps, normalizeEventsMaxSubscribers, oneToMany, parse, parseQualifiedName, parseSyncApplyBatch, payloadMatchesRow, processSyncApplyBatch, pruneChangeFeed, qualifiedNamesEqual, readAgentModuleDocs, registerChangeFeedWriter, registerCompatibleFieldDecorator, registerConfigResolver, registerFilesystemAdapterFactory, registerOptionalDependency, resetChangeFeedWarnings, resetChangeSignals, resetCollectionCache, resetConfigResolvers, resetVerifiedTables, resolveAgentModuleDocPaths, resolveDatabase, resolveDbCacheKey, resolveDispatchTenantId, resolveDispatchTenantScope, resolveLazyConfig, resolveReadCacheControl, resolveTenantEtagDiscriminator, runWithTenantGate, safeParse, safeStringify, setDispatchTenantResolver, setTenantEntryPointRunner, setTenantScopedClassResolver, setupCLI, setupSwaggerUI, shouldIncludeMethod, signalVisibleToTenant, smrt, smrtPlugin, smrt as smrtRegistry, startRestServer, staticManifest, stopCacheInvalidationListeners, stopChangeSignalListeners, stringify, subscribeToChangeSignals, tableExists, tryReserveChangeEventSubscriberSlot, unregisterChangeFeedWriter, unregisterConfigResolver, validateSyncApplyItem, validateToolCall, versionConditionalResponse, warnIfSharedCacheNeutralized };
@@ -1,4 +1,4 @@
1
- import { DomainKnowledgeConfig, DomainKnowledgeManifest } from '@happyvertical/smrt-types';
1
+ import { DomainKnowledgeConfig, DomainKnowledgeManifest, DomainKnowledgeModuleDoc } from '@happyvertical/smrt-types';
2
2
  import { SmartObjectManifest } from './scanner/types.js';
3
3
  /**
4
4
  * Minimal package.json shape consumed by the knowledge builder.
@@ -18,5 +18,21 @@ export interface BuildDomainKnowledgeOptions {
18
18
  manifestPath?: string;
19
19
  config?: DomainKnowledgeConfig;
20
20
  }
21
+ /** `sourceHashes` key prefix for a linked module doc, e.g. `moduleDoc:agents/crm.md`. */
22
+ export declare const MODULE_DOC_HASH_PREFIX = "moduleDoc:";
23
+ /**
24
+ * Module doc paths linked from a package's `AGENTS.md`, relative to the package
25
+ * root and in document order.
26
+ *
27
+ * Instruction chains are additive (see `scripts/check-agents-chain.mjs`), so an
28
+ * oversized package doc is split into `packages/<pkg>/agents/<module>.md` siblings
29
+ * instead of nested `AGENTS.md` files. Only links resolving to an existing file
30
+ * INSIDE the package are accepted — a cross-package reference such as
31
+ * `packages/affiliates/MIGRATION.md` belongs to that package's own chain and is
32
+ * ignored here.
33
+ */
34
+ export declare function resolveAgentModuleDocPaths(rootDir: string, agentDoc: string | undefined): string[];
35
+ /** {@link resolveAgentModuleDocPaths}, with each doc's contents read. */
36
+ export declare function readAgentModuleDocs(rootDir: string, agentDoc: string | undefined): DomainKnowledgeModuleDoc[];
21
37
  export declare function buildDomainKnowledgeManifest(options: BuildDomainKnowledgeOptions): DomainKnowledgeManifest;
22
38
  //# sourceMappingURL=knowledge.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"knowledge.d.ts","sourceRoot":"","sources":["../src/knowledge.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,qBAAqB,EACrB,uBAAuB,EAGxB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAEV,mBAAmB,EACpB,MAAM,oBAAoB,CAAC;AAE5B;;;;;GAKG;AACH,MAAM,WAAW,eAAe;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,2BAA2B;IAC1C,QAAQ,EAAE,mBA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CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
- import { existsSync, readFileSync, readdirSync } from "node:fs";
3
- import { join, relative } from "node:path";
2
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
+ import { basename, join, relative, resolve, sep } from "node:path";
4
4
  //#region src/knowledge.ts
5
5
  var SDK_PACKAGE_NAMES = /* @__PURE__ */ new Set([
6
6
  "@happyvertical/ai",
@@ -37,13 +37,61 @@ var STANDARD_OPERATIONS = [
37
37
  "update",
38
38
  "delete"
39
39
  ];
40
+ /**
41
+ * Markdown inline links whose target is a `.md` file — `[label](agents/x.md)`,
42
+ * tolerating an `#anchor` and a `"title"`. This is how a package registers a
43
+ * sibling module doc (#2108): the link in `AGENTS.md` IS the registration, so
44
+ * there is no separate index to drift out of sync.
45
+ */
46
+ var MARKDOWN_MD_LINK = /\[[^\]]*\]\(\s*([^)\s#]+\.md)(?:#[^)\s]*)?(?:\s+"[^"]*")?\s*\)/g;
47
+ /** `sourceHashes` key prefix for a linked module doc, e.g. `moduleDoc:agents/crm.md`. */
48
+ var MODULE_DOC_HASH_PREFIX = "moduleDoc:";
49
+ /**
50
+ * Module doc paths linked from a package's `AGENTS.md`, relative to the package
51
+ * root and in document order.
52
+ *
53
+ * Instruction chains are additive (see `scripts/check-agents-chain.mjs`), so an
54
+ * oversized package doc is split into `packages/<pkg>/agents/<module>.md` siblings
55
+ * instead of nested `AGENTS.md` files. Only links resolving to an existing file
56
+ * INSIDE the package are accepted — a cross-package reference such as
57
+ * `packages/affiliates/MIGRATION.md` belongs to that package's own chain and is
58
+ * ignored here.
59
+ */
60
+ function resolveAgentModuleDocPaths(rootDir, agentDoc) {
61
+ if (!agentDoc) return [];
62
+ const root = resolve(rootDir);
63
+ const paths = [];
64
+ for (const match of agentDoc.matchAll(MARKDOWN_MD_LINK)) {
65
+ const target = match[1];
66
+ if (target.includes("://")) continue;
67
+ const absolute = resolve(root, target);
68
+ if (absolute !== root && !absolute.startsWith(root + sep)) continue;
69
+ const relativePath = relative(root, absolute).split(sep).join("/");
70
+ if (relativePath === "AGENTS.md" || relativePath === "CLAUDE.md") continue;
71
+ if (paths.includes(relativePath)) continue;
72
+ if (!existsSync(absolute) || !statSync(absolute).isFile()) continue;
73
+ paths.push(relativePath);
74
+ }
75
+ return paths;
76
+ }
77
+ /** {@link resolveAgentModuleDocPaths}, with each doc's contents read. */
78
+ function readAgentModuleDocs(rootDir, agentDoc) {
79
+ return resolveAgentModuleDocPaths(rootDir, agentDoc).map((path) => ({
80
+ path,
81
+ module: basename(path, ".md"),
82
+ content: readFileSync(join(rootDir, path), "utf8")
83
+ }));
84
+ }
40
85
  function buildDomainKnowledgeManifest(options) {
41
86
  const rootDir = options.rootDir;
42
87
  const packageJson = options.packageJson ?? readPackageJson(rootDir) ?? {};
43
88
  const packageName = options.manifest.packageName ?? packageJson.name;
44
89
  const packageVersion = options.manifest.packageVersion ?? packageJson.version;
45
90
  const agentDocPath = existingPath(rootDir, "AGENTS.md");
46
- const agentDoc = options.config?.includeDocs === false || !agentDocPath ? void 0 : readFileSync(agentDocPath, "utf8");
91
+ const agentDocContent = agentDocPath ? readFileSync(agentDocPath, "utf8") : void 0;
92
+ const includeDocs = options.config?.includeDocs !== false;
93
+ const agentDoc = includeDocs ? agentDocContent : void 0;
94
+ const moduleDocPaths = resolveAgentModuleDocPaths(rootDir, agentDocContent);
47
95
  const allDependencies = {
48
96
  ...record(packageJson.dependencies),
49
97
  ...record(packageJson.devDependencies),
@@ -63,7 +111,8 @@ function buildDomainKnowledgeManifest(options) {
63
111
  sourceHashes: sourceHashes({
64
112
  manifest: { content: manifestJson },
65
113
  packageJson: fileHashSource(existingPath(rootDir, "package.json")),
66
- agents: fileHashSource(agentDocPath)
114
+ agents: fileHashSource(agentDocPath),
115
+ ...Object.fromEntries(moduleDocPaths.map((path) => [`${MODULE_DOC_HASH_PREFIX}${path}`, fileHashSource(join(rootDir, path))]))
67
116
  }),
68
117
  exports: exportKeys(packageJson.exports),
69
118
  dependencies: allDependencies,
@@ -76,7 +125,8 @@ function buildDomainKnowledgeManifest(options) {
76
125
  surfaces,
77
126
  prompts: options.config?.includePrompts === false ? [] : readPrompts(rootDir),
78
127
  relationshipsV2: summarizeRelationships(objects, manifestObjects),
79
- agentDoc
128
+ agentDoc,
129
+ moduleDocs: includeDocs && moduleDocPaths.length > 0 ? readAgentModuleDocs(rootDir, agentDocContent) : void 0
80
130
  };
81
131
  }
82
132
  function buildKnowledgeObject(object) {
@@ -268,6 +318,6 @@ function sortJson(value) {
268
318
  return value;
269
319
  }
270
320
  //#endregion
271
- export { buildDomainKnowledgeManifest };
321
+ export { MODULE_DOC_HASH_PREFIX, buildDomainKnowledgeManifest, readAgentModuleDocs, resolveAgentModuleDocPaths };
272
322
 
273
323
  //# sourceMappingURL=knowledge.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"knowledge.js","names":[],"sources":["../src/knowledge.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport type {\n DomainKnowledgeConfig,\n DomainKnowledgeManifest,\n DomainKnowledgeObject,\n DomainKnowledgeSurface,\n} from '@happyvertical/smrt-types';\nimport type {\n SmartObjectDefinition,\n SmartObjectManifest,\n} from './scanner/types.js';\n\n/**\n * Minimal package.json shape consumed by the knowledge builder.\n * `name`/`version` are typed concretely because they flow into the manifest's\n * string-typed metadata fields; everything else is read via `unknown`-accepting\n * helpers (`record()`, `exportKeys()`), so an index signature is sufficient.\n */\nexport interface PackageJsonLike {\n name?: string;\n version?: string;\n [key: string]: unknown;\n}\n\nexport interface BuildDomainKnowledgeOptions {\n manifest: SmartObjectManifest;\n rootDir: string;\n packageJson?: PackageJsonLike;\n manifestPath?: string;\n config?: DomainKnowledgeConfig;\n}\n\nconst SDK_PACKAGE_NAMES = new Set([\n '@happyvertical/ai',\n '@happyvertical/cache',\n '@happyvertical/documents',\n '@happyvertical/email',\n '@happyvertical/encryption',\n '@happyvertical/files',\n '@happyvertical/geo',\n '@happyvertical/images',\n '@happyvertical/jobs',\n '@happyvertical/json',\n '@happyvertical/logger',\n '@happyvertical/messages',\n '@happyvertical/ocr',\n '@happyvertical/pdf',\n '@happyvertical/projects',\n '@happyvertical/repos',\n '@happyvertical/secrets',\n '@happyvertical/spider',\n '@happyvertical/sql',\n '@happyvertical/utils',\n]);\n\nconst RELATIONSHIP_FIELD_TYPES = new Set([\n 'foreignKey',\n 'crossPackageRef',\n 'oneToMany',\n 'manyToMany',\n]);\n\nconst STANDARD_OPERATIONS = ['list', 'get', 'create', 'update', 'delete'];\n\nexport function buildDomainKnowledgeManifest(\n options: BuildDomainKnowledgeOptions,\n): DomainKnowledgeManifest {\n const rootDir = options.rootDir;\n const packageJson = options.packageJson ?? readPackageJson(rootDir) ?? {};\n const packageName = options.manifest.packageName ?? packageJson.name;\n const packageVersion = options.manifest.packageVersion ?? packageJson.version;\n const agentDocPath = existingPath(rootDir, 'AGENTS.md');\n const agentDoc =\n options.config?.includeDocs === false || !agentDocPath\n ? undefined\n : readFileSync(agentDocPath, 'utf8');\n const allDependencies = {\n ...record(packageJson.dependencies),\n ...record(packageJson.devDependencies),\n ...record(packageJson.peerDependencies),\n };\n const manifestObjects = Object.values(options.manifest.objects).filter(\n (object) => object.decoratorConfig?.knowledge !== false,\n );\n const objects = manifestObjects.map((object) => buildKnowledgeObject(object));\n const surfaces = objects.flatMap((object) => object.surfaces);\n const manifestJson = stableJson(normalizeManifestForHash(options.manifest));\n\n return {\n schemaVersion: 1,\n generatedAt: new Date().toISOString(),\n packageName,\n packageVersion,\n sourceManifestPath: options.manifestPath\n ? relative(rootDir, options.manifestPath)\n : undefined,\n agentDocPath: agentDocPath ? relative(rootDir, agentDocPath) : undefined,\n sourceHashes: sourceHashes({\n manifest: { content: manifestJson },\n packageJson: fileHashSource(existingPath(rootDir, 'package.json')),\n agents: fileHashSource(agentDocPath),\n }),\n exports: exportKeys(packageJson.exports),\n dependencies: allDependencies,\n smrtDependencies: Object.keys(allDependencies)\n .filter((dep) => dep.startsWith('@happyvertical/smrt-'))\n .sort(),\n sdkDependencies: Object.keys(allDependencies)\n .filter((dep) => SDK_PACKAGE_NAMES.has(dep))\n .sort(),\n tags: options.config?.tags ?? [],\n summary: options.config?.summary,\n risks: options.config?.risks ?? [],\n objects,\n surfaces,\n prompts:\n options.config?.includePrompts === false ? [] : readPrompts(rootDir),\n relationshipsV2: summarizeRelationships(objects, manifestObjects),\n agentDoc,\n };\n}\n\nfunction buildKnowledgeObject(\n object: SmartObjectDefinition,\n): DomainKnowledgeObject {\n const knowledge =\n typeof object.decoratorConfig?.knowledge === 'object'\n ? object.decoratorConfig.knowledge\n : {};\n const fields = Object.entries(object.fields).map(([name, field]) => ({\n name,\n type: field.type,\n required: field.required,\n related: field.related,\n columnType: columnType(object, name),\n }));\n const relationships = fields\n .filter((field) => RELATIONSHIP_FIELD_TYPES.has(field.type))\n .map((field) => ({\n name: field.name,\n type: field.type,\n required: field.required,\n related: field.related,\n columnType: field.columnType,\n }));\n\n return {\n name: object.className,\n qualifiedName: object.qualifiedName,\n collection: object.collection,\n tableName: object.schema?.tableName,\n packageName: object.packageName,\n extends: object.extends,\n visibility: object.visibility,\n fields,\n relationships,\n methods: Object.keys(object.methods).sort(),\n surfaces: objectSurfaces(object),\n relationshipFeatures: relationshipFeatures(object),\n tags: knowledge.tags ?? [],\n summary: knowledge.summary,\n risks: knowledge.risks ?? [],\n };\n}\n\nfunction objectSurfaces(\n object: SmartObjectDefinition,\n): DomainKnowledgeSurface[] {\n return [\n ...configuredSurfaces('api', object),\n ...configuredSurfaces('cli', object),\n ...configuredSurfaces('mcp', object),\n ...aiSurfaces(object),\n ];\n}\n\nfunction configuredSurfaces(\n kind: 'api' | 'cli' | 'mcp',\n object: SmartObjectDefinition,\n): DomainKnowledgeSurface[] {\n const config = object.decoratorConfig?.[kind];\n if (!config) return [];\n const operations = configuredOperations(config);\n return operations.map((operation) => ({\n kind,\n name:\n kind === 'api'\n ? `${object.collection}.${operation}`\n : `${object.className.toLowerCase()}_${operation}`,\n operation,\n objectName: object.qualifiedName ?? object.className,\n path: kind === 'api' ? apiPath(object, operation) : undefined,\n method: kind === 'api' ? apiMethod(operation) : undefined,\n }));\n}\n\nfunction configuredOperations(config: unknown): string[] {\n if (config === true) return [...STANDARD_OPERATIONS];\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n return [];\n }\n const recordConfig = config as { include?: string[]; exclude?: string[] };\n const base = Array.isArray(recordConfig.include)\n ? recordConfig.include\n : STANDARD_OPERATIONS;\n const excluded = new Set(recordConfig.exclude ?? []);\n return [...new Set(base.filter((operation) => !excluded.has(operation)))];\n}\n\nfunction aiSurfaces(object: SmartObjectDefinition): DomainKnowledgeSurface[] {\n return (object.tools ?? []).map((tool) => ({\n kind: 'ai',\n name: tool.function.name,\n operation: tool.function.name,\n description: tool.function.description,\n objectName: object.qualifiedName ?? object.className,\n }));\n}\n\nfunction apiPath(object: SmartObjectDefinition, operation: string): string {\n const collection = object.decoratorConfig?.api;\n const configuredPath =\n typeof collection === 'object' && typeof collection.path === 'string'\n ? collection.path\n : object.collection.replaceAll('_', '-');\n if (operation === 'list' || operation === 'create') {\n return `/${configuredPath}`;\n }\n if (STANDARD_OPERATIONS.includes(operation)) {\n return `/${configuredPath}/[id]`;\n }\n return `/${configuredPath}/${operation}`;\n}\n\nfunction apiMethod(operation: string): string {\n switch (operation) {\n case 'list':\n case 'get':\n return 'GET';\n case 'create':\n return 'POST';\n case 'update':\n return 'PATCH';\n case 'delete':\n return 'DELETE';\n default:\n return 'POST';\n }\n}\n\nfunction relationshipFeatures(object: SmartObjectDefinition): string[] {\n const features = new Set<string>();\n for (const field of Object.values(object.fields)) {\n if (field.type === 'foreignKey') features.add('foreignKey');\n if (field.type === 'crossPackageRef') features.add('crossPackageRef');\n if (field.type === 'oneToMany') features.add('oneToMany');\n if (field.type === 'manyToMany') features.add('manyToMany');\n }\n if (object.extends === 'SmrtJunction') features.add('SmrtJunction');\n if (object.extends === 'SmrtHierarchical') features.add('SmrtHierarchical');\n if (\n object.extends === 'SmrtPolymorphicAssociation' ||\n object.fields.metaType ||\n object.fields.metaId\n ) {\n features.add('SmrtPolymorphicAssociation');\n }\n if (\n Object.keys(object.schema?.columns ?? {}).some(\n (name) => object.schema?.columns[name]?.type === 'UUID',\n )\n ) {\n features.add('uuidColumns');\n }\n return [...features].sort();\n}\n\nfunction summarizeRelationships(\n objects: DomainKnowledgeObject[],\n manifestObjects: SmartObjectDefinition[],\n) {\n const fields = objects.flatMap((object) => object.fields);\n return {\n foreignKeyFields: fields.filter((field) => field.type === 'foreignKey')\n .length,\n crossPackageRefFields: fields.filter(\n (field) => field.type === 'crossPackageRef',\n ).length,\n junctionCollections: objects.filter((object) =>\n object.relationshipFeatures.includes('SmrtJunction'),\n ).length,\n hierarchicalObjects: objects.filter((object) =>\n object.relationshipFeatures.includes('SmrtHierarchical'),\n ).length,\n polymorphicAssociations: objects.filter((object) =>\n object.relationshipFeatures.includes('SmrtPolymorphicAssociation'),\n ).length,\n uuidColumns: manifestObjects.reduce(\n (count, object) =>\n count +\n Object.values(object.schema?.columns ?? {}).filter(\n (column) => column.type === 'UUID',\n ).length,\n 0,\n ),\n };\n}\n\nfunction columnType(\n object: SmartObjectDefinition,\n fieldName: string,\n): string | undefined {\n const columnName = camelToSnake(fieldName);\n return object.schema?.columns[columnName]?.type;\n}\n\nfunction readPrompts(\n rootDir: string,\n): Array<{ filePath: string; key?: string }> {\n const srcDir = join(rootDir, 'src');\n if (!existsSync(srcDir)) return [];\n const prompts: Array<{ filePath: string; key?: string }> = [];\n for (const filePath of walkFiles(srcDir)) {\n if (!filePath.endsWith('.ts')) continue;\n const content = readFileSync(filePath, 'utf8');\n if (!content.includes('definePrompt')) continue;\n const keyMatch = content.match(/definePrompt\\s*\\(\\s*['\"`]([^'\"`]+)['\"`]/);\n prompts.push({\n filePath: relative(rootDir, filePath),\n key: keyMatch?.[1],\n });\n }\n return prompts;\n}\n\nfunction walkFiles(dir: string): string[] {\n const files: string[] = [];\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (\n entry.name === 'node_modules' ||\n entry.name === 'dist' ||\n entry.name === '.svelte-kit'\n ) {\n continue;\n }\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n files.push(...walkFiles(fullPath));\n } else if (entry.isFile()) {\n files.push(fullPath);\n }\n }\n return files;\n}\n\nfunction sourceHashes(sources: Record<string, HashSource | undefined>) {\n const hashes: Record<string, string> = {};\n for (const [name, source] of Object.entries(sources)) {\n if (!source) continue;\n const content =\n 'content' in source ? source.content : readFileSync(source.path, 'utf8');\n hashes[name] = createHash('sha256').update(content).digest('hex');\n }\n return hashes;\n}\n\ntype HashSource = { content: string } | { path: string };\n\nfunction fileHashSource(path: string | undefined): HashSource | undefined {\n return path ? { path } : undefined;\n}\n\nfunction existingPath(rootDir: string, path: string): string | undefined {\n const fullPath = join(rootDir, path);\n return existsSync(fullPath) ? fullPath : undefined;\n}\n\nfunction readPackageJson(rootDir: string): PackageJsonLike | null {\n const path = join(rootDir, 'package.json');\n if (!existsSync(path)) return null;\n return JSON.parse(readFileSync(path, 'utf8'));\n}\n\nfunction record(value: unknown): Record<string, string> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, string>)\n : {};\n}\n\nfunction exportKeys(exportsField: unknown): string[] {\n if (typeof exportsField === 'string') return ['.'];\n if (\n typeof exportsField !== 'object' ||\n exportsField === null ||\n Array.isArray(exportsField)\n ) {\n return [];\n }\n return Object.keys(exportsField).sort();\n}\n\nfunction camelToSnake(value: string): string {\n return value\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[-\\s]+/g, '_')\n .toLowerCase();\n}\n\nfunction normalizeManifestForHash(manifest: SmartObjectManifest): unknown {\n const normalized = JSON.parse(JSON.stringify(manifest)) as Record<\n string,\n unknown\n >;\n delete normalized.timestamp;\n return normalized;\n}\n\nfunction stableJson(value: unknown): string {\n return JSON.stringify(sortJson(value), null, 2);\n}\n\nfunction sortJson(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortJson);\n if (value && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, entry]) => [key, sortJson(entry)]),\n );\n }\n return value;\n}\n"],"mappings":";;;;AAkCA,IAAM,oCAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,IAAM,2CAA2B,IAAI,IAAI;CACvC;CACA;CACA;CACA;AACF,CAAC;AAED,IAAM,sBAAsB;CAAC;CAAQ;CAAO;CAAU;CAAU;AAAQ;AAExE,SAAgB,6BACd,SACyB;CACzB,MAAM,UAAU,QAAQ;CACxB,MAAM,cAAc,QAAQ,eAAe,gBAAgB,OAAO,KAAK,CAAC;CACxE,MAAM,cAAc,QAAQ,SAAS,eAAe,YAAY;CAChE,MAAM,iBAAiB,QAAQ,SAAS,kBAAkB,YAAY;CACtE,MAAM,eAAe,aAAa,SAAS,WAAW;CACtD,MAAM,WACJ,QAAQ,QAAQ,gBAAgB,SAAS,CAAC,eACtC,KAAA,IACA,aAAa,cAAc,MAAM;CACvC,MAAM,kBAAkB;EACtB,GAAG,OAAO,YAAY,YAAY;EAClC,GAAG,OAAO,YAAY,eAAe;EACrC,GAAG,OAAO,YAAY,gBAAgB;CACxC;CACA,MAAM,kBAAkB,OAAO,OAAO,QAAQ,SAAS,OAAO,CAAC,CAAC,QAC7D,WAAW,OAAO,iBAAiB,cAAc,KACpD;CACA,MAAM,UAAU,gBAAgB,KAAK,WAAW,qBAAqB,MAAM,CAAC;CAC5E,MAAM,WAAW,QAAQ,SAAS,WAAW,OAAO,QAAQ;CAC5D,MAAM,eAAe,WAAW,yBAAyB,QAAQ,QAAQ,CAAC;CAE1E,OAAO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K,MAAM,aAAa,MAAM,MAAM,CAAC;AAC9C;AAEA,SAAS,OAAO,OAAwC;CACtD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,IACrE,QACD,CAAC;AACP;AAEA,SAAS,WAAW,cAAiC;CACnD,IAAI,OAAO,iBAAiB,UAAU,OAAO,CAAC,GAAG;CACjD,IACE,OAAO,iBAAiB,YACxB,iBAAiB,QACjB,MAAM,QAAQ,YAAY,GAE1B,OAAO,CAAC;CAEV,OAAO,OAAO,KAAK,YAAY,CAAC,CAAC,KAAK;AACxC;AAEA,SAAS,aAAa,OAAuB;CAC3C,OAAO,MACJ,QAAQ,sBAAsB,OAAO,CAAC,CACtC,QAAQ,WAAW,GAAG,CAAC,CACvB,YAAY;AACjB;AAEA,SAAS,yBAAyB,UAAwC;CACxE,MAAM,aAAa,KAAK,MAAM,KAAK,UAAU,QAAQ,CAAC;CAItD,OAAO,WAAW;CAClB,OAAO;AACT;AAEA,SAAS,WAAW,OAAwB;CAC1C,OAAO,KAAK,UAAU,SAAS,KAAK,GAAG,MAAM,CAAC;AAChD;AAEA,SAAS,SAAS,OAAyB;CACzC,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,IAAI,QAAQ;CACnD,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAgC,CAAC,CAC7C,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,CACtC,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,SAAS,KAAK,CAAC,CAAC,CACjD;CAEF,OAAO;AACT"}
1
+ {"version":3,"file":"knowledge.js","names":[],"sources":["../src/knowledge.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { basename, join, relative, resolve, sep } from 'node:path';\nimport type {\n DomainKnowledgeConfig,\n DomainKnowledgeManifest,\n DomainKnowledgeModuleDoc,\n DomainKnowledgeObject,\n DomainKnowledgeSurface,\n} from '@happyvertical/smrt-types';\nimport type {\n SmartObjectDefinition,\n SmartObjectManifest,\n} from './scanner/types.js';\n\n/**\n * Minimal package.json shape consumed by the knowledge builder.\n * `name`/`version` are typed concretely because they flow into the manifest's\n * string-typed metadata fields; everything else is read via `unknown`-accepting\n * helpers (`record()`, `exportKeys()`), so an index signature is sufficient.\n */\nexport interface PackageJsonLike {\n name?: string;\n version?: string;\n [key: string]: unknown;\n}\n\nexport interface BuildDomainKnowledgeOptions {\n manifest: SmartObjectManifest;\n rootDir: string;\n packageJson?: PackageJsonLike;\n manifestPath?: string;\n config?: DomainKnowledgeConfig;\n}\n\nconst SDK_PACKAGE_NAMES = new Set([\n '@happyvertical/ai',\n '@happyvertical/cache',\n '@happyvertical/documents',\n '@happyvertical/email',\n '@happyvertical/encryption',\n '@happyvertical/files',\n '@happyvertical/geo',\n '@happyvertical/images',\n '@happyvertical/jobs',\n '@happyvertical/json',\n '@happyvertical/logger',\n '@happyvertical/messages',\n '@happyvertical/ocr',\n '@happyvertical/pdf',\n '@happyvertical/projects',\n '@happyvertical/repos',\n '@happyvertical/secrets',\n '@happyvertical/spider',\n '@happyvertical/sql',\n '@happyvertical/utils',\n]);\n\nconst RELATIONSHIP_FIELD_TYPES = new Set([\n 'foreignKey',\n 'crossPackageRef',\n 'oneToMany',\n 'manyToMany',\n]);\n\nconst STANDARD_OPERATIONS = ['list', 'get', 'create', 'update', 'delete'];\n\n/**\n * Markdown inline links whose target is a `.md` file — `[label](agents/x.md)`,\n * tolerating an `#anchor` and a `\"title\"`. This is how a package registers a\n * sibling module doc (#2108): the link in `AGENTS.md` IS the registration, so\n * there is no separate index to drift out of sync.\n */\nconst MARKDOWN_MD_LINK =\n /\\[[^\\]]*\\]\\(\\s*([^)\\s#]+\\.md)(?:#[^)\\s]*)?(?:\\s+\"[^\"]*\")?\\s*\\)/g;\n\n/** `sourceHashes` key prefix for a linked module doc, e.g. `moduleDoc:agents/crm.md`. */\nexport const MODULE_DOC_HASH_PREFIX = 'moduleDoc:';\n\n/**\n * Module doc paths linked from a package's `AGENTS.md`, relative to the package\n * root and in document order.\n *\n * Instruction chains are additive (see `scripts/check-agents-chain.mjs`), so an\n * oversized package doc is split into `packages/<pkg>/agents/<module>.md` siblings\n * instead of nested `AGENTS.md` files. Only links resolving to an existing file\n * INSIDE the package are accepted — a cross-package reference such as\n * `packages/affiliates/MIGRATION.md` belongs to that package's own chain and is\n * ignored here.\n */\nexport function resolveAgentModuleDocPaths(\n rootDir: string,\n agentDoc: string | undefined,\n): string[] {\n if (!agentDoc) return [];\n const root = resolve(rootDir);\n const paths: string[] = [];\n for (const match of agentDoc.matchAll(MARKDOWN_MD_LINK)) {\n const target = match[1];\n if (target.includes('://')) continue;\n const absolute = resolve(root, target);\n if (absolute !== root && !absolute.startsWith(root + sep)) continue;\n const relativePath = relative(root, absolute).split(sep).join('/');\n if (relativePath === 'AGENTS.md' || relativePath === 'CLAUDE.md') continue;\n if (paths.includes(relativePath)) continue;\n if (!existsSync(absolute) || !statSync(absolute).isFile()) continue;\n paths.push(relativePath);\n }\n return paths;\n}\n\n/** {@link resolveAgentModuleDocPaths}, with each doc's contents read. */\nexport function readAgentModuleDocs(\n rootDir: string,\n agentDoc: string | undefined,\n): DomainKnowledgeModuleDoc[] {\n return resolveAgentModuleDocPaths(rootDir, agentDoc).map((path) => ({\n path,\n module: basename(path, '.md'),\n content: readFileSync(join(rootDir, path), 'utf8'),\n }));\n}\n\nexport function buildDomainKnowledgeManifest(\n options: BuildDomainKnowledgeOptions,\n): DomainKnowledgeManifest {\n const rootDir = options.rootDir;\n const packageJson = options.packageJson ?? readPackageJson(rootDir) ?? {};\n const packageName = options.manifest.packageName ?? packageJson.name;\n const packageVersion = options.manifest.packageVersion ?? packageJson.version;\n const agentDocPath = existingPath(rootDir, 'AGENTS.md');\n const agentDocContent = agentDocPath\n ? readFileSync(agentDocPath, 'utf8')\n : undefined;\n const includeDocs = options.config?.includeDocs !== false;\n const agentDoc = includeDocs ? agentDocContent : undefined;\n // Module doc PATHS are always resolved so their hashes gate freshness even\n // when doc bodies are excluded from the artifact — same stance as `agents`.\n const moduleDocPaths = resolveAgentModuleDocPaths(rootDir, agentDocContent);\n const allDependencies = {\n ...record(packageJson.dependencies),\n ...record(packageJson.devDependencies),\n ...record(packageJson.peerDependencies),\n };\n const manifestObjects = Object.values(options.manifest.objects).filter(\n (object) => object.decoratorConfig?.knowledge !== false,\n );\n const objects = manifestObjects.map((object) => buildKnowledgeObject(object));\n const surfaces = objects.flatMap((object) => object.surfaces);\n const manifestJson = stableJson(normalizeManifestForHash(options.manifest));\n\n return {\n schemaVersion: 1,\n generatedAt: new Date().toISOString(),\n packageName,\n packageVersion,\n sourceManifestPath: options.manifestPath\n ? relative(rootDir, options.manifestPath)\n : undefined,\n agentDocPath: agentDocPath ? relative(rootDir, agentDocPath) : undefined,\n sourceHashes: sourceHashes({\n manifest: { content: manifestJson },\n packageJson: fileHashSource(existingPath(rootDir, 'package.json')),\n agents: fileHashSource(agentDocPath),\n ...Object.fromEntries(\n moduleDocPaths.map((path) => [\n `${MODULE_DOC_HASH_PREFIX}${path}`,\n fileHashSource(join(rootDir, path)),\n ]),\n ),\n }),\n exports: exportKeys(packageJson.exports),\n dependencies: allDependencies,\n smrtDependencies: Object.keys(allDependencies)\n .filter((dep) => dep.startsWith('@happyvertical/smrt-'))\n .sort(),\n sdkDependencies: Object.keys(allDependencies)\n .filter((dep) => SDK_PACKAGE_NAMES.has(dep))\n .sort(),\n tags: options.config?.tags ?? [],\n summary: options.config?.summary,\n risks: options.config?.risks ?? [],\n objects,\n surfaces,\n prompts:\n options.config?.includePrompts === false ? [] : readPrompts(rootDir),\n relationshipsV2: summarizeRelationships(objects, manifestObjects),\n agentDoc,\n moduleDocs:\n includeDocs && moduleDocPaths.length > 0\n ? readAgentModuleDocs(rootDir, agentDocContent)\n : undefined,\n };\n}\n\nfunction buildKnowledgeObject(\n object: SmartObjectDefinition,\n): DomainKnowledgeObject {\n const knowledge =\n typeof object.decoratorConfig?.knowledge === 'object'\n ? object.decoratorConfig.knowledge\n : {};\n const fields = Object.entries(object.fields).map(([name, field]) => ({\n name,\n type: field.type,\n required: field.required,\n related: field.related,\n columnType: columnType(object, name),\n }));\n const relationships = fields\n .filter((field) => RELATIONSHIP_FIELD_TYPES.has(field.type))\n .map((field) => ({\n name: field.name,\n type: field.type,\n required: field.required,\n related: field.related,\n columnType: field.columnType,\n }));\n\n return {\n name: object.className,\n qualifiedName: object.qualifiedName,\n collection: object.collection,\n tableName: object.schema?.tableName,\n packageName: object.packageName,\n extends: object.extends,\n visibility: object.visibility,\n fields,\n relationships,\n methods: Object.keys(object.methods).sort(),\n surfaces: objectSurfaces(object),\n relationshipFeatures: relationshipFeatures(object),\n tags: knowledge.tags ?? [],\n summary: knowledge.summary,\n risks: knowledge.risks ?? [],\n };\n}\n\nfunction objectSurfaces(\n object: SmartObjectDefinition,\n): DomainKnowledgeSurface[] {\n return [\n ...configuredSurfaces('api', object),\n ...configuredSurfaces('cli', object),\n ...configuredSurfaces('mcp', object),\n ...aiSurfaces(object),\n ];\n}\n\nfunction configuredSurfaces(\n kind: 'api' | 'cli' | 'mcp',\n object: SmartObjectDefinition,\n): DomainKnowledgeSurface[] {\n const config = object.decoratorConfig?.[kind];\n if (!config) return [];\n const operations = configuredOperations(config);\n return operations.map((operation) => ({\n kind,\n name:\n kind === 'api'\n ? `${object.collection}.${operation}`\n : `${object.className.toLowerCase()}_${operation}`,\n operation,\n objectName: object.qualifiedName ?? object.className,\n path: kind === 'api' ? apiPath(object, operation) : undefined,\n method: kind === 'api' ? apiMethod(operation) : undefined,\n }));\n}\n\nfunction configuredOperations(config: unknown): string[] {\n if (config === true) return [...STANDARD_OPERATIONS];\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n return [];\n }\n const recordConfig = config as { include?: string[]; exclude?: string[] };\n const base = Array.isArray(recordConfig.include)\n ? recordConfig.include\n : STANDARD_OPERATIONS;\n const excluded = new Set(recordConfig.exclude ?? []);\n return [...new Set(base.filter((operation) => !excluded.has(operation)))];\n}\n\nfunction aiSurfaces(object: SmartObjectDefinition): DomainKnowledgeSurface[] {\n return (object.tools ?? []).map((tool) => ({\n kind: 'ai',\n name: tool.function.name,\n operation: tool.function.name,\n description: tool.function.description,\n objectName: object.qualifiedName ?? object.className,\n }));\n}\n\nfunction apiPath(object: SmartObjectDefinition, operation: string): string {\n const collection = object.decoratorConfig?.api;\n const configuredPath =\n typeof collection === 'object' && typeof collection.path === 'string'\n ? collection.path\n : object.collection.replaceAll('_', '-');\n if (operation === 'list' || operation === 'create') {\n return `/${configuredPath}`;\n }\n if (STANDARD_OPERATIONS.includes(operation)) {\n return `/${configuredPath}/[id]`;\n }\n return `/${configuredPath}/${operation}`;\n}\n\nfunction apiMethod(operation: string): string {\n switch (operation) {\n case 'list':\n case 'get':\n return 'GET';\n case 'create':\n return 'POST';\n case 'update':\n return 'PATCH';\n case 'delete':\n return 'DELETE';\n default:\n return 'POST';\n }\n}\n\nfunction relationshipFeatures(object: SmartObjectDefinition): string[] {\n const features = new Set<string>();\n for (const field of Object.values(object.fields)) {\n if (field.type === 'foreignKey') features.add('foreignKey');\n if (field.type === 'crossPackageRef') features.add('crossPackageRef');\n if (field.type === 'oneToMany') features.add('oneToMany');\n if (field.type === 'manyToMany') features.add('manyToMany');\n }\n if (object.extends === 'SmrtJunction') features.add('SmrtJunction');\n if (object.extends === 'SmrtHierarchical') features.add('SmrtHierarchical');\n if (\n object.extends === 'SmrtPolymorphicAssociation' ||\n object.fields.metaType ||\n object.fields.metaId\n ) {\n features.add('SmrtPolymorphicAssociation');\n }\n if (\n Object.keys(object.schema?.columns ?? {}).some(\n (name) => object.schema?.columns[name]?.type === 'UUID',\n )\n ) {\n features.add('uuidColumns');\n }\n return [...features].sort();\n}\n\nfunction summarizeRelationships(\n objects: DomainKnowledgeObject[],\n manifestObjects: SmartObjectDefinition[],\n) {\n const fields = objects.flatMap((object) => object.fields);\n return {\n foreignKeyFields: fields.filter((field) => field.type === 'foreignKey')\n .length,\n crossPackageRefFields: fields.filter(\n (field) => field.type === 'crossPackageRef',\n ).length,\n junctionCollections: objects.filter((object) =>\n object.relationshipFeatures.includes('SmrtJunction'),\n ).length,\n hierarchicalObjects: objects.filter((object) =>\n object.relationshipFeatures.includes('SmrtHierarchical'),\n ).length,\n polymorphicAssociations: objects.filter((object) =>\n object.relationshipFeatures.includes('SmrtPolymorphicAssociation'),\n ).length,\n uuidColumns: manifestObjects.reduce(\n (count, object) =>\n count +\n Object.values(object.schema?.columns ?? {}).filter(\n (column) => column.type === 'UUID',\n ).length,\n 0,\n ),\n };\n}\n\nfunction columnType(\n object: SmartObjectDefinition,\n fieldName: string,\n): string | undefined {\n const columnName = camelToSnake(fieldName);\n return object.schema?.columns[columnName]?.type;\n}\n\nfunction readPrompts(\n rootDir: string,\n): Array<{ filePath: string; key?: string }> {\n const srcDir = join(rootDir, 'src');\n if (!existsSync(srcDir)) return [];\n const prompts: Array<{ filePath: string; key?: string }> = [];\n for (const filePath of walkFiles(srcDir)) {\n if (!filePath.endsWith('.ts')) continue;\n const content = readFileSync(filePath, 'utf8');\n if (!content.includes('definePrompt')) continue;\n const keyMatch = content.match(/definePrompt\\s*\\(\\s*['\"`]([^'\"`]+)['\"`]/);\n prompts.push({\n filePath: relative(rootDir, filePath),\n key: keyMatch?.[1],\n });\n }\n return prompts;\n}\n\nfunction walkFiles(dir: string): string[] {\n const files: string[] = [];\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (\n entry.name === 'node_modules' ||\n entry.name === 'dist' ||\n entry.name === '.svelte-kit'\n ) {\n continue;\n }\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n files.push(...walkFiles(fullPath));\n } else if (entry.isFile()) {\n files.push(fullPath);\n }\n }\n return files;\n}\n\nfunction sourceHashes(sources: Record<string, HashSource | undefined>) {\n const hashes: Record<string, string> = {};\n for (const [name, source] of Object.entries(sources)) {\n if (!source) continue;\n const content =\n 'content' in source ? source.content : readFileSync(source.path, 'utf8');\n hashes[name] = createHash('sha256').update(content).digest('hex');\n }\n return hashes;\n}\n\ntype HashSource = { content: string } | { path: string };\n\nfunction fileHashSource(path: string | undefined): HashSource | undefined {\n return path ? { path } : undefined;\n}\n\nfunction existingPath(rootDir: string, path: string): string | undefined {\n const fullPath = join(rootDir, path);\n return existsSync(fullPath) ? fullPath : undefined;\n}\n\nfunction readPackageJson(rootDir: string): PackageJsonLike | null {\n const path = join(rootDir, 'package.json');\n if (!existsSync(path)) return null;\n return JSON.parse(readFileSync(path, 'utf8'));\n}\n\nfunction record(value: unknown): Record<string, string> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, string>)\n : {};\n}\n\nfunction exportKeys(exportsField: unknown): string[] {\n if (typeof exportsField === 'string') return ['.'];\n if (\n typeof exportsField !== 'object' ||\n exportsField === null ||\n Array.isArray(exportsField)\n ) {\n return [];\n }\n return Object.keys(exportsField).sort();\n}\n\nfunction camelToSnake(value: string): string {\n return value\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[-\\s]+/g, '_')\n .toLowerCase();\n}\n\nfunction normalizeManifestForHash(manifest: SmartObjectManifest): unknown {\n const normalized = JSON.parse(JSON.stringify(manifest)) as Record<\n string,\n unknown\n >;\n delete normalized.timestamp;\n return normalized;\n}\n\nfunction stableJson(value: unknown): string {\n return JSON.stringify(sortJson(value), null, 2);\n}\n\nfunction sortJson(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortJson);\n if (value && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, entry]) => [key, sortJson(entry)]),\n );\n }\n return value;\n}\n"],"mappings":";;;;AAmCA,IAAM,oCAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;C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AsB,OAAO,CAAC,CACtC,QAAQ,WAAW,GAAG,CAAC,CACvB,YAAY;AACjB;AAEA,SAAS,yBAAyB,UAAwC;CACxE,MAAM,aAAa,KAAK,MAAM,KAAK,UAAU,QAAQ,CAAC;CAItD,OAAO,WAAW;CAClB,OAAO;AACT;AAEA,SAAS,WAAW,OAAwB;CAC1C,OAAO,KAAK,UAAU,SAAS,KAAK,GAAG,MAAM,CAAC;AAChD;AAEA,SAAS,SAAS,OAAyB;CACzC,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,IAAI,QAAQ;CACnD,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAgC,CAAC,CAC7C,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,CACtC,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,SAAS,KAAK,CAAC,CAAC,CACjD;CAEF,OAAO;AACT"}
@@ -1,9 +1,9 @@
1
1
  //#region src/manifest/static-manifest.ts
2
2
  var staticManifest = {
3
3
  "version": "1.0.0",
4
- "timestamp": 1785022559936,
4
+ "timestamp": 1785029944237,
5
5
  "packageName": "@happyvertical/smrt-core",
6
- "packageVersion": "0.40.22",
6
+ "packageVersion": "0.40.24",
7
7
  "objects": {
8
8
  "@happyvertical/smrt-core:SmrtClass": {
9
9
  "name": "smrtclass",