@happyvertical/smrt-content 0.43.2 → 0.43.4
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 +86 -0
- package/dist/index.js +1 -1
- package/dist/manifest.json +1 -1
- package/dist/smrt-knowledge.json +5 -5
- package/dist/svelte/components/ContentList.svelte +669 -281
- package/dist/svelte/components/ContentList.svelte.d.ts +10 -1
- package/dist/svelte/components/ContentList.svelte.d.ts.map +1 -1
- package/dist/svelte/content-list-controller.d.ts +209 -0
- package/dist/svelte/content-list-controller.d.ts.map +1 -0
- package/dist/svelte/content-list-controller.js +650 -0
- package/dist/svelte/i18n.contribution.d.ts +31 -0
- package/dist/svelte/i18n.contribution.d.ts.map +1 -1
- package/dist/svelte/i18n.contribution.js +31 -0
- package/dist/svelte/index.d.ts +1 -0
- package/dist/svelte/index.d.ts.map +1 -1
- package/dist/svelte/index.js +3 -0
- package/package.json +14 -14
package/dist/manifest.json
CHANGED
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-content",
|
|
6
|
-
"packageVersion": "0.43.
|
|
6
|
+
"packageVersion": "0.43.4",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
10
|
+
"manifest": "c8b79c6fa202328f85d7e9778552df452adafe288b662e4db5d7668e1a899d0b",
|
|
11
|
+
"packageJson": "943734aa5ab93400aae0e53e9c338a436129d20962fd871add559d0e069435da",
|
|
12
|
+
"agents": "d20b5d898d2db9a906b7ff1e416a095c542423f32c87fadcc73d3e32cc563d12"
|
|
13
13
|
},
|
|
14
14
|
"exports": [
|
|
15
15
|
".",
|
|
@@ -10067,5 +10067,5 @@
|
|
|
10067
10067
|
"polymorphicAssociations": 0,
|
|
10068
10068
|
"uuidColumns": 79
|
|
10069
10069
|
},
|
|
10070
|
-
"agentDoc": "# @happyvertical/smrt-content\n\nSTI content management with governance workflows, contribution intake, AI reviews, fact-checking, corrections, versioning, transparency reports, and thumbnail generation.\n\n## Models\n\n- **Content** (STI base): `type`, `variant` (generator:domain:specific format), `status` (published/draft/review/archived/deleted), `state`, `category` (hierarchical path with `/` separator), `metadata` JSON, `tags` array, `thumbnailAssetId`\n- **Article**, **ContentDocument**, **Mirror**: STI subclasses — all share `contents` table via `_meta_type`\n- **ContentReview**: AI review result tied to a governance policy. Fields: `contentId`, `policyKey`, `kind`, `status` (accepted/flagged/rejected), `findings`, `fingerprint`, `metadata`\n- **ContentCorrection**: Post-publication change record. Fields: `contentId`, `type` (correction/retraction/update/clarification), `summary`, `note`, `status`, `metadata`\n- **ContentVersion**: Content snapshot. Fields: `contentId`, `kind` (manual/draft/review/publication/correction/auto-generated), `versionNumber`, `summary`, `metadata` (includes `transparency` for publication versions)\n- **ContentReference**: Junction model for content-to-content links (`content_references` table). Nullable `targetVersion` pins a citation to a specific `ContentVersion.version` for drift detection.\n- **ContentGovernancePolicy**: Persisted review policy (key, label, kind, instructions)\n- **ContentGovernanceProfile**: Persisted review profile (key, label, requirements array)\n- **ContentGovernanceAssignment**: Governs content type/variant → profile mapping, feature flags\n- **ContentContribution**: Held inbound submission with status lifecycle (submitted → approved/rejected/withdrawn → promoted)\n- **ContentContributor**: Contributor profile resolved by email, with trust level (standard/trusted/blocked)\n- **ContentContributionType**: Configures intake channels, rules, and promotion mapping\n- **ContentContributionRevision**: Revision history for held submissions\n- **ContentContributionAttachment**: Held file metadata; becomes an `Asset` on promotion\n\n## Contents Collection\n\n| Method | Purpose |\n|--------|---------| \n| `mirror({ url })` | Downloads URL content, extracts text, creates `type: 'mirror'`. Idempotent. |\n| `syncContentDir({ contentDir })` | Batch exports articles as markdown with YAML frontmatter |\n| `generateMissingThumbnails(options)` | Bulk thumbnail generation for content missing `thumbnailAssetId` |\n| `findWithGlobals(tenantId)` | Returns tenant-specific + global (tenantId=null) content |\n| `getOrUpsert({ slug, context })` | Upsert by slug+context combination |\n| `browseFacts()` | Browse fact catalog linked to content |\n| `getGovernanceDefinitionsAction()` | Get all governance policy/profile/assignment definitions |\n| `resolveGovernanceAction({ type, variant })` | Resolve effective governance for a content type |\n\n## Content Instance Methods\n\n| Method | Purpose |\n|--------|---------|\n| `resolveGovernance()` | Resolve effective governance config for this content |\n| `runReviewAction(options)` | Run AI review against a policy; returns `ContentReview` |\n| `listReviews()` | List all reviews for this content |\n| `listReviewProfilesAction()` | Get readiness for all profiles |\n| `evaluateReviewProfile(key)` | Evaluate one profile's requirements |\n| `issueCorrectionAction(options)` | Issue a post-publication correction |\n| `listCorrections()` | List corrections for this content |\n| `listVersions()` | List version history |\n| `mutateVersionAction(options)` | Create a version snapshot |\n| `getPublishedTransparencyAction()` | Get frozen transparency from latest publication version |\n| `previewTransparencyAction()` | Preview live transparency state |\n| `addFact(factId, relationship)` | Link a fact (supports/contradicts/referenced_in) |\n| `getFacts(options)` | Get linked facts |\n| `getFactLinks()` | Get fact-content link records |\n| `getFactsState()` / `syncFactsState(options)` | API-level facts get/sync |\n| `addAsset(asset, relationship, sortOrder)` | Add asset association |\n| `setThumbnail(image)` | Convenience: adds asset + updates `thumbnailAssetId` |\n| `addReference(content, options?)` | Link to another content; `options.targetVersion` pins citation-time `ContentVersion.version` |\n| `getReferences()` | Get content references |\n| `getReferenceDrift()` | Per-edge `{ citedVersion, currentVersion, isDrifted }` for drift detection |\n\n## Governance Workflow\n\n1. `configureContentGovernance({ policies, profiles, assignments })` — static config\n2. Or persist `ContentGovernancePolicy/Profile/Assignment` objects — DB overrides static\n3. Effective config: DB layer merges over static defaults\n4. `content.resolveGovernance()` → `ResolvedContentGovernance` with `isGoverned`, `reviewPolicies`, profile keys, feature flags\n5. `content.runReviewAction()` creates a `ContentReview` with fingerprint for staleness detection\n6. `content.evaluateReviewProfile(key)` checks all requirements\n7. `content.save()` auto-validates publish readiness when `enforcePublishReadiness` is true\n8. Publication auto-creates a `ContentVersion` with frozen transparency data\n\n## Thumbnail Generation\n\nThree strategies via ThumbnailGenerator:\n- **headline-card**: title on branded background (via `@happyvertical/images`)\n- **static-map**: requires `metadata.latitude`/`longitude` (via `@happyvertical/geo`)\n- **ai-generate**: AI image generation (dynamic import of `@happyvertical/ai`)\n\n## Svelte Components\n\n### Content Management\n`ContentList`, `ContentEditor`, `GovernedContentEditor`, `ContentAgentChat`, `ContentTitleField`, `ContentStatusFields`, `ContentMetadataFields`, `ContentReferencesPanel`, `ContentImageBrowser`, `ContentReviewStatusTray`, `ArticleCard`, `ArticleList`, `ImageThumbnail`, `Markdown`\n\n### Governance\n`ContentGovernanceManager`, `ContentGovernancePanel`, `ContentGovernancePolicyEditor`, `ContentGovernanceProfileEditor`, `ContentGovernanceAssignmentEditor`, `ContentTransparencyReport`\n\n### Contributions\n`ContentContributionForm`, `ContentContributionInbox`, `ContentContributionPortal`, `ContentContributionTypeManager`, `ContentContributorManager`\n\n## Dev Server\n\n`npm run dev` starts SvelteKit at `localhost:5173` with 4 pages:\n\n- `/` — Content catalog (CRUD, search, filters, card/list views)\n- `/governance` — Policy/profile/assignment management\n- `/contributions` — Inbox, submit form, contributor/type management\n- `/api-explorer` — Browse 69 endpoints with try-it-live for GET\n\nOn startup, `hooks.server.ts` bootstraps schemas for all 13 local classes,\nloads cross-package manifests, and seeds 3 sample content items.\n\n## Chat Integration\n\nContent `GET/POST /api/v1/contents/{id}/chat` endpoint creates\nchat sessions via `@happyvertical/smrt-chat`. Gracefully handles\nmissing chat tables (returns `session: null` with notice).\n`ContentAgentChat` Svelte component provides the UI.\n\nFor global assistant shells, `ContentEditor` and `GovernedContentEditor`\nsupport `onAssistantContextChange`. The callback receives a serializable\n`ContentEditorAssistantContext` plus local editor actions, and still fires when\n`hideChat={true}`. `ContentAgentChat` can be mounted outside the editor with an\n`assistantContext` prop. Server-side consumers can reuse the exported\n`getOrCreateContentEditorChatSession`, `createContentEditorChatThread`,\n`listContentEditorChatThreadMessages`, and\n`sendContentEditorChatThreadMessage` helpers for app-specific tenancy/auth/AI\nroute wiring.\n\nThese handlers go exclusively through the tenant-bound `ChatService` facade\n(S5 #1392) — `getAgentSession`/`findActiveAgentSessions`/`getThread`/\n`listRoomThreads`/`getThreadMessages` for reads and `startThread`/`sendMessage`/\n`sendAgentReply` (internal agent-runtime subpath) for writes. They never reach\ninto the now-`#private` chat collections, so cross-tenant chat state can no\nlonger be selected by raw id before authorization.\n\nThe content-editor session is created with a content-scoped `sessionKey`\n(`contentChatSessionKey(contentId)` → `content:<id>`, S5 #1392). Without it,\n`createAgentSession` reuses ANY active `content_editor` session for the same\nprofile/tenant, so a request about a new content id would reuse — and the\nhandler would rewrite — a session created for a different content and return the\nother content's room/threads. Keying on the content id makes each content get a\ndistinct session/room.\n\n## Relationship Models\n\n- **ContentReference**: SMRT junction model backing `content_references` for content-to-content links\n- **ContentAsset**: dedicated SMRT junction model backing `content_assets` for content-owned asset links\n\n```typescript\nawait content.addAsset(image, 'thumbnail', 0); // relationship, sortOrder\nawait content.getAssets('attachment');\nawait content.setThumbnail(image); // convenience: adds asset + updates thumbnailAssetId\nawait content.addReference(otherContent); // unpinned\nawait content.addReference(otherContent, { targetVersion: 2 }); // pinned to v2\nawait content.getReferences();\nawait content.getReferenceDrift(); // → [{ targetId, citedVersion, currentVersion, isDrifted }, ...]\n```\n\n## API Contracts\n\n`Content` implements `AssetAssociable` and `MetadataAccessor` (issue #1162). Consumers can type their parameters as `Content` (or the interfaces directly) and rely on the methods existing without `typeof === 'function'` defensive checks:\n\n```typescript\nimport type { AssetAssociable, MetadataAccessor } from '@happyvertical/smrt-content';\n\nasync function attachThumbnail(doc: AssetAssociable, asset: Asset) {\n await doc.addAsset(asset, 'thumbnail', 0); // contract guaranteed\n}\n\nfunction bumpRevision(doc: MetadataAccessor) {\n const meta = doc.getMetadata();\n doc.updateMetadata({ revision: (meta.revision ?? 0) + 1 });\n}\n```\n\n## Category Navigation\n\n`getCategorySegments()`, `getParentCategory()`, `getRootCategory()`, `getAncestorPaths()`, `isInCategory(path, includeChildren?)`\n\n## Prompt Registry\n\nContent prompts are registered with `@happyvertical/smrt-prompts` so tenants can override template/profile/model/params at runtime:\n\n```typescript\nimport {\n smrtContentReviewPrompt, // key: 'smrtContent.review'\n smrtContentApplyCorrectionPrompt, // key: 'smrtContent.applyCorrection'\n smrtContentThumbnailAIGeneratePrompt, // key: 'smrtContent.thumbnail.aiGenerate'\n} from '@happyvertical/smrt-content';\n```\n\n`smrtContent.thumbnail.aiGenerate` powers the AI image-generation prompt used by `ThumbnailGenerator` (strategy `'ai-generate'`). Variables substituted into the template: `style`, `title`, `styleHint`, `descriptionClause`. Internal foreign-key fields (`id`, `tenantId`) and the freeform `metadata` blob are intentionally excluded — `metadata` may carry tenant-private configuration or coordinates unrelated to the visual prompt.\n\n## Gotchas\n\n- **STI discriminator**: qualified names like `@happyvertical/smrt-content:Article`\n- **Optional tenancy**: `@TenantScoped({ mode: 'optional' })` — null tenantId = global content\n- **Metadata is primary extension pattern**: use JSON `metadata` field, not additional class fields\n- **Static map coordinates**: uses unary `+` for strict parsing (rejects \"45invalid\" unlike parseFloat)\n- **Review fingerprints**: reviews track content state at review time; stale reviews are detected by fingerprint mismatch\n- **Publish readiness enforcement**: `save()` throws `ValidationError` if blocking requirements aren't met when setting status to `'published'`\n- **Transparency snapshots**: published transparency is frozen into `ContentVersion.metadata.transparency` — use published for public display, preview for editors\n- **Reference pinning**: `ContentReference` is keyed on `(source_id, target_id)`; `targetVersion` is an attribute of the edge, not part of identity. Re-calling `addReference(target, { targetVersion })` updates the pin in place. Unpinned references (`targetVersion: null`) report `isDrifted: false` regardless of how stale the target is — pin them only when you want drift to be detectable.\n- **Generated API routes are not tracked**: everything the vite plugin emits under `src/routes/api/v1` is build output, listed in the bounded `.gitignore` block and regenerated on `npm run dev`. The handwritten handlers beside them (`contents/[id]/chat/**`, `images/**`) stay tracked and linted. Do not commit generated routes — they are not Biome-formatted, so tracking them turns the Lint job red (#2198)\n- **`pnpm typecheck` regenerates package-owned routes safely**: Svelte's analysis may load dependent package Vite configs, but those configs anchor their root to their own package. Content's generated API routes therefore remain under `src/routes/api/v1` and the bounded `.gitignore` block stays stable (#2199).\n- **Tests import generated routes and that is fine**: `contents-api.test.ts` imports `contents/+server.ts` and `contents/[id]/+server.ts` to exercise the generated CRUD handlers against a real SQLite database. The `test` script runs `svelte-kit sync` first, which regenerates the whole route tree, so those files exist by the time Vitest loads — no committed copy needed. Run `pnpm test`, never bare `vitest`, or the imports fail to resolve\n- **`generate:test` exists for the callers that bypass `test`**: `scripts/check-coverage.mjs` runs bare `vitest --coverage`, so without a `generate:test` hook the route imports above fail and the Coverage Gate reports `no coverage produced` rather than a real percentage. It is `cache: false` in `packages/content/turbo.json` — the root task's `outputs` describe core's manifest, so a turbo cache hit would restore nothing and silently skip `svelte-kit sync`\n- **Chat tables**: chat endpoint requires `@happyvertical/smrt-chat` tables; dev server handles missing tables gracefully\n- **Dev server bootstraps all classes**: `hooks.server.ts` generates schemas for all 13 local `@smrt()` classes plus cross-package manifests\n"
|
|
10070
|
+
"agentDoc": "# @happyvertical/smrt-content\n\nSTI content management with governance workflows, contribution intake, AI reviews, fact-checking, corrections, versioning, transparency reports, and thumbnail generation.\n\n## Models\n\n- **Content** (STI base): `type`, `variant` (generator:domain:specific format), `status` (published/draft/review/archived/deleted), `state`, `category` (hierarchical path with `/` separator), `metadata` JSON, `tags` array, `thumbnailAssetId`\n- **Article**, **ContentDocument**, **Mirror**: STI subclasses — all share `contents` table via `_meta_type`\n- **ContentReview**: AI review result tied to a governance policy. Fields: `contentId`, `policyKey`, `kind`, `status` (accepted/flagged/rejected), `findings`, `fingerprint`, `metadata`\n- **ContentCorrection**: Post-publication change record. Fields: `contentId`, `type` (correction/retraction/update/clarification), `summary`, `note`, `status`, `metadata`\n- **ContentVersion**: Content snapshot. Fields: `contentId`, `kind` (manual/draft/review/publication/correction/auto-generated), `versionNumber`, `summary`, `metadata` (includes `transparency` for publication versions)\n- **ContentReference**: Junction model for content-to-content links (`content_references` table). Nullable `targetVersion` pins a citation to a specific `ContentVersion.version` for drift detection.\n- **ContentGovernancePolicy**: Persisted review policy (key, label, kind, instructions)\n- **ContentGovernanceProfile**: Persisted review profile (key, label, requirements array)\n- **ContentGovernanceAssignment**: Governs content type/variant → profile mapping, feature flags\n- **ContentContribution**: Held inbound submission with status lifecycle (submitted → approved/rejected/withdrawn → promoted)\n- **ContentContributor**: Contributor profile resolved by email, with trust level (standard/trusted/blocked)\n- **ContentContributionType**: Configures intake channels, rules, and promotion mapping\n- **ContentContributionRevision**: Revision history for held submissions\n- **ContentContributionAttachment**: Held file metadata; becomes an `Asset` on promotion\n\n## Contents Collection\n\n| Method | Purpose |\n|--------|---------| \n| `mirror({ url })` | Downloads URL content, extracts text, creates `type: 'mirror'`. Idempotent. |\n| `syncContentDir({ contentDir })` | Batch exports articles as markdown with YAML frontmatter |\n| `generateMissingThumbnails(options)` | Bulk thumbnail generation for content missing `thumbnailAssetId` |\n| `findWithGlobals(tenantId)` | Returns tenant-specific + global (tenantId=null) content |\n| `getOrUpsert({ slug, context })` | Upsert by slug+context combination |\n| `browseFacts()` | Browse fact catalog linked to content |\n| `getGovernanceDefinitionsAction()` | Get all governance policy/profile/assignment definitions |\n| `resolveGovernanceAction({ type, variant })` | Resolve effective governance for a content type |\n\n## Content Instance Methods\n\n| Method | Purpose |\n|--------|---------|\n| `resolveGovernance()` | Resolve effective governance config for this content |\n| `runReviewAction(options)` | Run AI review against a policy; returns `ContentReview` |\n| `listReviews()` | List all reviews for this content |\n| `listReviewProfilesAction()` | Get readiness for all profiles |\n| `evaluateReviewProfile(key)` | Evaluate one profile's requirements |\n| `issueCorrectionAction(options)` | Issue a post-publication correction |\n| `listCorrections()` | List corrections for this content |\n| `listVersions()` | List version history |\n| `mutateVersionAction(options)` | Create a version snapshot |\n| `getPublishedTransparencyAction()` | Get frozen transparency from latest publication version |\n| `previewTransparencyAction()` | Preview live transparency state |\n| `addFact(factId, relationship)` | Link a fact (supports/contradicts/referenced_in) |\n| `getFacts(options)` | Get linked facts |\n| `getFactLinks()` | Get fact-content link records |\n| `getFactsState()` / `syncFactsState(options)` | API-level facts get/sync |\n| `addAsset(asset, relationship, sortOrder)` | Add asset association |\n| `setThumbnail(image)` | Convenience: adds asset + updates `thumbnailAssetId` |\n| `addReference(content, options?)` | Link to another content; `options.targetVersion` pins citation-time `ContentVersion.version` |\n| `getReferences()` | Get content references |\n| `getReferenceDrift()` | Per-edge `{ citedVersion, currentVersion, isDrifted }` for drift detection |\n\n## Governance Workflow\n\n1. `configureContentGovernance({ policies, profiles, assignments })` — static config\n2. Or persist `ContentGovernancePolicy/Profile/Assignment` objects — DB overrides static\n3. Effective config: DB layer merges over static defaults\n4. `content.resolveGovernance()` → `ResolvedContentGovernance` with `isGoverned`, `reviewPolicies`, profile keys, feature flags\n5. `content.runReviewAction()` creates a `ContentReview` with fingerprint for staleness detection\n6. `content.evaluateReviewProfile(key)` checks all requirements\n7. `content.save()` auto-validates publish readiness when `enforcePublishReadiness` is true\n8. Publication auto-creates a `ContentVersion` with frozen transparency data\n\n## Thumbnail Generation\n\nThree strategies via ThumbnailGenerator:\n- **headline-card**: title on branded background (via `@happyvertical/images`)\n- **static-map**: requires `metadata.latitude`/`longitude` (via `@happyvertical/geo`)\n- **ai-generate**: AI image generation (dynamic import of `@happyvertical/ai`)\n\n## Svelte Components\n\n### Content Management\n`ContentList`, `ContentEditor`, `GovernedContentEditor`, `ContentAgentChat`, `ContentTitleField`, `ContentStatusFields`, `ContentMetadataFields`, `ContentReferencesPanel`, `ContentImageBrowser`, `ContentReviewStatusTray`, `ArticleCard`, `ArticleList`, `ImageThumbnail`, `Markdown`\n\n### Governance\n`ContentGovernanceManager`, `ContentGovernancePanel`, `ContentGovernancePolicyEditor`, `ContentGovernanceProfileEditor`, `ContentGovernanceAssignmentEditor`, `ContentTransparencyReport`\n\n### Contributions\n`ContentContributionForm`, `ContentContributionInbox`, `ContentContributionPortal`, `ContentContributionTypeManager`, `ContentContributorManager`\n\n## ContentList migration (#2451)\n\n`ContentList` no longer holds bespoke local state. `src/svelte/content-list-controller.ts`\nis the single adapter every presentation reads from, and one shared\n`DataTableController` (from `@happyvertical/smrt-ui/data`) owns search, filters,\nsorting, page, and selection.\n\n| Before | After |\n|--------|-------|\n| local `searchTerm`/`selectedType`/`selectedStatus` runes | controller commands `setSearch` / `setFilters` (stable filter ids `type`, `status`) |\n| `filteredContents` `$derived` per view | `toContentListRows` → `selectContentListRows` → `paginateContentListRows`, computed once for all three modes |\n| bespoke `<table>` markup in compact mode | smrt-ui `DataTable` with the shared columns plus per-column cell snippets |\n| no selection | checkbox selection in every mode via `toggleRowSelection` / `setSelectedRows` |\n| `getViewHref` called inline three times | `resolveContentHref` / `contentListRowActions` (one eligibility source) |\n\nProps are unchanged and still exported as `ContentListProps`: `apiBaseUrl`,\n`contents`, `type` (still locks and hides the type filter), `defaultViewMode`\n(still seeds once), `onEdit`, `onDelete`, `onAdd`, `controls`, `getViewHref`.\nNew optional props: `loading`, `error`, `onRetry`, and `dataSurface`\n(`{ registry, descriptor? }`).\n\nAdapter exports (also re-exported from `./svelte`): `createContentListController`,\n`buildContentListColumns`, `buildContentListSurfaceDescriptor`,\n`toContentListRows`, `selectContentListRows`, `paginateContentListRows`,\n`contentListFilters`, `readContentListFilter`, `applyContentListFilter`,\n`contentListRowActions`, `resolveContentHref`, `selectableContentListRowIds`,\n`resolveSelectedContentListRows`, `resolveSelectedContents`, plus the\n`CONTENT_LIST_*` identity constants.\n\nNotes:\n\n- Controller modes are all `manual`: the adapter owns search, filters, sorting,\n and paging in **every** presentation, and the compact table receives\n `data={pageRows}` plus `totalRows={queryRows.length}`. Letting DataTable\n filter locally over already-filtered rows re-ran the transform with subtly\n different semantics (untrimmed search, its own equality rules), so the two\n presentations could disagree. The component clamps the page with\n `controller.clampPage(queryRows.length)`. #2452 replaces the local\n implementation of that transform with a server query behind the same contract.\n- A `type` prop lock is enforced against live state, not just against the prop:\n a data-surface `set-filters` or `reset` command that drops the type filter is\n re-applied by the lock effect (equality-guarded, so it settles).\n- Selection may only address durable rows. All three presentations render a\n disabled, explained checkbox for `identified: false` rows, page select-all\n skips them, and a normalization effect re-dispatches `setSelectedRows` without\n any non-durable id, which covers data-surface commands too.\n- Compact mode renders a content-owned `select` column (header + cell snippets)\n instead of passing `selectable` to DataTable. DataTable has no per-row\n selection predicate, so its header select-all addresses the synthetic id of an\n unidentified row; the normalization effect then strips it and the header stays\n indeterminate forever. Because column order is reconciled from the\n controller's known column ids, the structural `select` and `actions` ids are\n part of `CONTENT_LIST_TABLE_COLUMN_IDS` — omit them and selection renders\n behind every data column.\n- Only rendered columns are published to a data surface. `description` is a\n hidden, search-only column so search still reaches the deck; the descriptor\n additionally declares the `id` row-key column, which the surface contract\n requires but the table never renders.\n- Rows without a durable `id` (or repeating one) still render, keyed by\n position, but are marked `identified: false`;\n `resolveSelectedContentListRows` drops them so a bulk action can never act on\n an unaddressable row. `ContentData` has no expiry or site field, so the\n `site` column is derived from `url`/`source`.\n- Column ids are public identifiers and do not always match the model field, so\n the descriptor's `fieldName` comes from an explicit map\n (`publish` → `publish_date`, `updated` → `updatedAt`); the derived `site`\n column advertises no field at all rather than a nonexistent one.\n- Filter values are normalized per column (`type` via `normalizeContentType`,\n everything else via `normalizeContentToken`) through\n `normalizeContentListFilterValue`, and a blank value clears the filter — an\n `equals ''` filter would silently exclude every row.\n- The card presentations render their own page controls (smrt-ui `Pagination`\n dispatching `setPage`) and their own polite refresh status, because DataTable\n — which owns both in compact mode — is not mounted there. A page size arriving\n from a saved view or a surface command would otherwise strand the operator on\n page one, and a refresh over retained rows would be silent.\n- `dataSurface` registers the compact table only. Agent addressability for the\n grid and detailed presentations lands with #2456.\n- Compact mode stays mounted for empty and loading results — DataTable renders\n its own `empty` snippet and loading row — because it owns the mounted surface:\n swapping it for the shared empty panel unregisters the surface, and an agent\n whose own search returned nothing then gets `not_found` on the command that\n would undo it. The shared loading/empty panels are the card presentations'\n only; the `error` branch still replaces the list in every mode, since a load\n failure is host-driven rather than surface-driven.\n\n## Dev Server\n\n`npm run dev` starts SvelteKit at `localhost:5173` with 4 pages:\n\n- `/` — Content catalog (CRUD, search, filters, card/list views)\n- `/governance` — Policy/profile/assignment management\n- `/contributions` — Inbox, submit form, contributor/type management\n- `/api-explorer` — Browse 69 endpoints with try-it-live for GET\n\nOn startup, `hooks.server.ts` bootstraps schemas for all 13 local classes,\nloads cross-package manifests, and seeds 3 sample content items.\n\n## Chat Integration\n\nContent `GET/POST /api/v1/contents/{id}/chat` endpoint creates\nchat sessions via `@happyvertical/smrt-chat`. Gracefully handles\nmissing chat tables (returns `session: null` with notice).\n`ContentAgentChat` Svelte component provides the UI.\n\nFor global assistant shells, `ContentEditor` and `GovernedContentEditor`\nsupport `onAssistantContextChange`. The callback receives a serializable\n`ContentEditorAssistantContext` plus local editor actions, and still fires when\n`hideChat={true}`. `ContentAgentChat` can be mounted outside the editor with an\n`assistantContext` prop. Server-side consumers can reuse the exported\n`getOrCreateContentEditorChatSession`, `createContentEditorChatThread`,\n`listContentEditorChatThreadMessages`, and\n`sendContentEditorChatThreadMessage` helpers for app-specific tenancy/auth/AI\nroute wiring.\n\nThese handlers go exclusively through the tenant-bound `ChatService` facade\n(S5 #1392) — `getAgentSession`/`findActiveAgentSessions`/`getThread`/\n`listRoomThreads`/`getThreadMessages` for reads and `startThread`/`sendMessage`/\n`sendAgentReply` (internal agent-runtime subpath) for writes. They never reach\ninto the now-`#private` chat collections, so cross-tenant chat state can no\nlonger be selected by raw id before authorization.\n\nThe content-editor session is created with a content-scoped `sessionKey`\n(`contentChatSessionKey(contentId)` → `content:<id>`, S5 #1392). Without it,\n`createAgentSession` reuses ANY active `content_editor` session for the same\nprofile/tenant, so a request about a new content id would reuse — and the\nhandler would rewrite — a session created for a different content and return the\nother content's room/threads. Keying on the content id makes each content get a\ndistinct session/room.\n\n## Relationship Models\n\n- **ContentReference**: SMRT junction model backing `content_references` for content-to-content links\n- **ContentAsset**: dedicated SMRT junction model backing `content_assets` for content-owned asset links\n\n```typescript\nawait content.addAsset(image, 'thumbnail', 0); // relationship, sortOrder\nawait content.getAssets('attachment');\nawait content.setThumbnail(image); // convenience: adds asset + updates thumbnailAssetId\nawait content.addReference(otherContent); // unpinned\nawait content.addReference(otherContent, { targetVersion: 2 }); // pinned to v2\nawait content.getReferences();\nawait content.getReferenceDrift(); // → [{ targetId, citedVersion, currentVersion, isDrifted }, ...]\n```\n\n## API Contracts\n\n`Content` implements `AssetAssociable` and `MetadataAccessor` (issue #1162). Consumers can type their parameters as `Content` (or the interfaces directly) and rely on the methods existing without `typeof === 'function'` defensive checks:\n\n```typescript\nimport type { AssetAssociable, MetadataAccessor } from '@happyvertical/smrt-content';\n\nasync function attachThumbnail(doc: AssetAssociable, asset: Asset) {\n await doc.addAsset(asset, 'thumbnail', 0); // contract guaranteed\n}\n\nfunction bumpRevision(doc: MetadataAccessor) {\n const meta = doc.getMetadata();\n doc.updateMetadata({ revision: (meta.revision ?? 0) + 1 });\n}\n```\n\n## Category Navigation\n\n`getCategorySegments()`, `getParentCategory()`, `getRootCategory()`, `getAncestorPaths()`, `isInCategory(path, includeChildren?)`\n\n## Prompt Registry\n\nContent prompts are registered with `@happyvertical/smrt-prompts` so tenants can override template/profile/model/params at runtime:\n\n```typescript\nimport {\n smrtContentReviewPrompt, // key: 'smrtContent.review'\n smrtContentApplyCorrectionPrompt, // key: 'smrtContent.applyCorrection'\n smrtContentThumbnailAIGeneratePrompt, // key: 'smrtContent.thumbnail.aiGenerate'\n} from '@happyvertical/smrt-content';\n```\n\n`smrtContent.thumbnail.aiGenerate` powers the AI image-generation prompt used by `ThumbnailGenerator` (strategy `'ai-generate'`). Variables substituted into the template: `style`, `title`, `styleHint`, `descriptionClause`. Internal foreign-key fields (`id`, `tenantId`) and the freeform `metadata` blob are intentionally excluded — `metadata` may carry tenant-private configuration or coordinates unrelated to the visual prompt.\n\n## Gotchas\n\n- **STI discriminator**: qualified names like `@happyvertical/smrt-content:Article`\n- **Optional tenancy**: `@TenantScoped({ mode: 'optional' })` — null tenantId = global content\n- **Metadata is primary extension pattern**: use JSON `metadata` field, not additional class fields\n- **Static map coordinates**: uses unary `+` for strict parsing (rejects \"45invalid\" unlike parseFloat)\n- **Review fingerprints**: reviews track content state at review time; stale reviews are detected by fingerprint mismatch\n- **Publish readiness enforcement**: `save()` throws `ValidationError` if blocking requirements aren't met when setting status to `'published'`\n- **Transparency snapshots**: published transparency is frozen into `ContentVersion.metadata.transparency` — use published for public display, preview for editors\n- **Reference pinning**: `ContentReference` is keyed on `(source_id, target_id)`; `targetVersion` is an attribute of the edge, not part of identity. Re-calling `addReference(target, { targetVersion })` updates the pin in place. Unpinned references (`targetVersion: null`) report `isDrifted: false` regardless of how stale the target is — pin them only when you want drift to be detectable.\n- **Generated API routes are not tracked**: everything the vite plugin emits under `src/routes/api/v1` is build output, listed in the bounded `.gitignore` block and regenerated on `npm run dev`. The handwritten handlers beside them (`contents/[id]/chat/**`, `images/**`) stay tracked and linted. Do not commit generated routes — they are not Biome-formatted, so tracking them turns the Lint job red (#2198)\n- **`pnpm typecheck` regenerates package-owned routes safely**: Svelte's analysis may load dependent package Vite configs, but those configs anchor their root to their own package. Content's generated API routes therefore remain under `src/routes/api/v1` and the bounded `.gitignore` block stays stable (#2199).\n- **Tests import generated routes and that is fine**: `contents-api.test.ts` imports `contents/+server.ts` and `contents/[id]/+server.ts` to exercise the generated CRUD handlers against a real SQLite database. The `test` script runs `svelte-kit sync` first, which regenerates the whole route tree, so those files exist by the time Vitest loads — no committed copy needed. Run `pnpm test`, never bare `vitest`, or the imports fail to resolve\n- **`generate:test` exists for the callers that bypass `test`**: `scripts/check-coverage.mjs` runs bare `vitest --coverage`, so without a `generate:test` hook the route imports above fail and the Coverage Gate reports `no coverage produced` rather than a real percentage. It is `cache: false` in `packages/content/turbo.json` — the root task's `outputs` describe core's manifest, so a turbo cache hit would restore nothing and silently skip `svelte-kit sync`\n- **Chat tables**: chat endpoint requires `@happyvertical/smrt-chat` tables; dev server handles missing tables gracefully\n- **Dev server bootstraps all classes**: `hooks.server.ts` generates schemas for all 13 local `@smrt()` classes plus cross-package manifests\n"
|
|
10071
10071
|
}
|