Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-5638]): stamp model and LoRA licenses onto generated assets (#5914)
atomanticagent80b644371046
diff --git a/client/src/components/media/AttributionList.jsx b/client/src/components/media/AttributionList.jsxnew file mode 100644index 0000000000..1e813262e3--- /dev/null+++ b/client/src/components/media/AttributionList.jsx@@ -0,0 +1,47 @@+import { licenseLabel, resolveAssetProvenance, rollupProvenance } from '../../lib/assetProvenance.js';++function SourceRow({ source }) {+ const label = source.name || source.id;+ const terms = licenseLabel(source.license);+ const kind = source.kind === 'lora' ? 'LoRA' : 'Model';+ return (+ <li className="flex flex-col gap-0.5">+ <span className="text-gray-200 break-all">+ <span className="text-gray-500 uppercase tracking-wide mr-1.5">{kind}</span>+ {source.sourceUrl ? (+ <a href={source.sourceUrl} target="_blank" rel="noreferrer" className="text-port-accent hover:underline">+ {label}+ </a>+ ) : label}+ </span>+ <span className="text-gray-400">License: {terms}</span>+ </li>+ );+}++/**+ * Attribution & licenses. `records` is a collection (rollup); `record` is one+ * asset. Unknown licenses render as "unknown" — never a guessed permissive term.+ */+export default function AttributionList({ record, records, className = '' }) {+ const provenance = records+ ? rollupProvenance(records.map((item) => item?.raw || item))+ : resolveAssetProvenance(record?.raw || record);+ const sources = provenance?.sources || [];+ if (!sources.length) return null;+ return (+ <section className={className} aria-label="Attribution and licenses">+ <h3 className="text-gray-500 uppercase tracking-wide text-xs mb-1.5">Attribution & licenses</h3>+ {provenance?.reconstructed && (+ <p className="text-[11px] text-gray-500 mb-1.5">+ This asset was not stamped at render time — licenses show as unknown.+ </p>+ )}+ <ul className="space-y-2 text-xs">+ {sources.map((source) => (+ <SourceRow key={`${source.kind}:${source.id}`} source={source} />+ ))}+ </ul>+ </section>+ );+}diff --git a/client/src/components/media/AttributionList.test.jsx b/client/src/components/media/AttributionList.test.jsxnew file mode 100644index 0000000000..09cf8f219e--- /dev/null+++ b/client/src/components/media/AttributionList.test.jsx@@ -0,0 +1,38 @@+import { describe, it, expect } from 'vitest';+import { render, screen } from '@testing-library/react';+import AttributionList from './AttributionList';++describe('AttributionList', () => {+ it('renders unknown when a license was not observed', () => {+ render(+ <AttributionList+ record={{+ provenance: {+ sources: [{ kind: 'model', id: 'flux2-klein-9b', name: 'Klein', license: null, sourceUrl: null }],+ },+ }}+ />,+ );+ expect(screen.getByText('License: unknown')).toBeTruthy();+ expect(screen.getByText('Klein')).toBeTruthy();+ });++ it('rolls up distinct sources across a collection', () => {+ render(+ <AttributionList+ records={[+ { provenance: { sources: [{ kind: 'model', id: 'a', license: 'mit' }] } },+ { provenance: { sources: [{ kind: 'lora', id: 'x.safetensors', license: 'openrail' }] } },+ ]}+ />,+ );+ expect(screen.getByText('License: mit')).toBeTruthy();+ expect(screen.getByText('License: openrail')).toBeTruthy();+ expect(screen.getByText('x.safetensors')).toBeTruthy();+ });++ it('renders nothing when there is nothing to attribute', () => {+ const { container } = render(<AttributionList record={{ filename: 'x.png' }} />);+ expect(container.firstChild).toBeNull();+ });+});diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsxindex 3ade673035..3ebe8f6d3d 100644--- a/client/src/components/media/MediaLightbox.jsx+++ b/client/src/components/media/MediaLightbox.jsx@@ -17,6 +17,7 @@ import useFocusTrap from '../../hooks/useFocusTrap.js';import { copyToClipboard } from '../../lib/clipboard';import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';import { formatDateTime, formatDateNumeric, formatDurationMs } from '../../utils/formatters';+import AttributionList from './AttributionList';// Intentionally NOT migrated to <ui/Modal> or <components/Drawer>. The// prev/next buttons sit as viewport-edge siblings of the card (not children@@ -719,6 +720,8 @@ function SettingsPane({</div>)}+ <AttributionList record={item} />+{meta.length > 0 && (<dl className="grid grid-cols-[auto,1fr] gap-x-3 gap-y-1">{meta.map(([k, v]) => {diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.jsindex e830c110fa..f62a4bb8b5 100644--- a/client/src/components/media/normalize.js+++ b/client/src/components/media/normalize.js@@ -99,6 +99,7 @@ export function normalizeImage(i) {// `cleanedFrom` sibling "Watermark removed" rather than "Cleaned", so it// MUST survive normalization (same contract as `regenerated` above).watermarkRemoved: i.watermarkRemoved === true,+ provenance: i.provenance || null,raw: i,};}@@ -127,6 +128,7 @@ export function normalizeVideo(v) {// Same contract as normalizeImage's renderMs above.renderMs: Number.isFinite(v.renderMs) ? v.renderMs : null,hidden: !!v.hidden,+ provenance: v.provenance || null,raw: v,};}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 6cfeedadb5..9e2ab91277 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -135,6 +135,7 @@ grep -i "what you want to do" client/src/lib/README.md| `manuscriptAnchors.js` | `locateFind` / `locateAnchors` / `buildHighlightSegments` — resolve editorial-comment `anchorQuote`s to spans in manuscript text and tile the text into plain + highlighted (severity-toned) segments for the Manuscript editor's in-context feedback. Mirrors the nearest-occurrence `locateFind` in `server/services/pipeline/manuscriptFix.js`. || `manuscriptFormat.js` | `formatManuscript(text, stageId)` / `REFLOW_STAGES` — normalize a manuscript section's text for the editor's "Format" button: undo PDF-paste artifacts (stylized drop-cap split onto its own line, hyphen-split words, trailing whitespace, runaway blank lines) for every stage, and additionally reflow soft-wrapped lines back into paragraphs for `prose` only (scripts keep their structural line breaks). Pure/DOM-free. || `mediaNavigation.js` | `getAdjacentMedia(items, item)` — prev/next computation for lightboxes. |+| `assetProvenance.js` | Mirror of `server/lib/assetProvenance.js`. Stamp-time model/LoRA license provenance + rollup for collection/export Attribution. Unknown license displays as "unknown". || `mediaCollectionList.js` | Search / sort ordering for the Media Collections grid (#3283) and the `CollectionPickerShell` dropdown (#3312): `applyCollectionView(collections, { query, sort })` filters via `mediaSearch.js`'s AND-token matcher over name+description and orders synthetic "Unsorted" → non-empty-or-user-created → auto-generated empties, then by `COLLECTION_SORTS` (`updated` / `name` / `count`, `normalizeCollectionSort` coerces an unknown/URL value); keys are derived once per record, not per comparison. "Hide empty" is deliberately NOT a parameter — the page owns that one predicate (`collectionItemCount(c) > 0`) because it also needs the pre-filter count. `isAutoCollection(c)` recognizes a machine-created collection from ANY of four independent markers (`AUTO_NAME_PREFIXES`, `Auto-created…`/`Auto-generated…` description, `uc-`/`sc-` id, universe/series link) so a record predating a given marker still classifies; `splitCollectionName(name)` lifts the shared `Creative Director: ` / `Writers Room: ` / `Universe: ` / `Series: ` prefix into a badge label so the distinguishing tail survives truncation, and name sorting uses that stripped title. **Adding a server-side auto-creator means adding its prefix here** or its collections silently rank as user-created. Pure — no React. || `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. || `morsePractice.js` | Pure deterministic adaptive Morse sampler — `selectMorsePrompt` combines bounded weak-character/confusion weighting with a non-zero exploration floor and only emits material valid for the active Koch pool; `canAdvanceMorseLevel` guards level advancement on sample count, accuracy, and effective speed. |diff --git a/client/src/lib/assetProvenance.js b/client/src/lib/assetProvenance.jsnew file mode 100644index 0000000000..98c7fa3cba--- /dev/null+++ b/client/src/lib/assetProvenance.js@@ -0,0 +1,198 @@+/**+ * Asset license provenance — stamp at finalize time, never re-read later.+ *+ * PortOS already resolves a model's license when it downloads one+ * (`licenseOf` in huggingFaceCatalog, Civitai/HF LoRA cards) and then drops+ * it on the floor. Create-suite outputs leave the machine (collections,+ * pipeline export, albums), so the terms that applied WHEN THE PIXELS WERE+ * MADE have to travel with the asset. A license re-read months later can+ * differ from the one in force at render; unknown stays unknown (`null`),+ * displayed as "unknown" — never a permissive default.+ *+ * Shape (schemaVersion 1):+ * {+ * schemaVersion: 1,+ * capturedAt: ISO-8601 | null,+ * sources: [{ kind: 'model'|'lora', id, name, license, sourceUrl }]+ * }+ *+ * Pure — no I/O. Server and client share this module byte-for-byte.+ */++export const PROVENANCE_SCHEMA_VERSION = 1;+export const PROVENANCE_SOURCE_KINDS = Object.freeze(['model', 'lora']);+export const UNKNOWN_LICENSE_LABEL = 'unknown';++export function normalizeLicense(value) {+ if (typeof value !== 'string') return null;+ const trimmed = value.trim();+ return trimmed || null;+}++export function licenseLabel(license) {+ const normalized = normalizeLicense(license);+ return normalized || UNKNOWN_LICENSE_LABEL;+}++export function huggingfaceUrl(repo) {+ if (typeof repo !== 'string') return null;+ const id = repo.trim();+ return id ? `https://huggingface.co/${id}` : null;+}++export function licenseFromHuggingFaceModel(model) {+ const card = normalizeLicense(model?.cardData?.license || model?.license);+ if (card) return card;+ const tags = Array.isArray(model?.tags) ? model.tags : [];+ const tag = tags.find((t) => typeof t === 'string' && /^license:/i.test(t));+ return tag ? normalizeLicense(tag.slice(tag.indexOf(':') + 1)) : null;+}++export function licenseFromCivitaiModel(model) {+ // Civitai's `allowCommercialUse` is a policy flag, not a license string —+ // never promote it into one. Only a real `license` field counts.+ return normalizeLicense(model?.license);+}++export function buildProvenanceSource({ kind, id, name = null, license = null, sourceUrl = null } = {}) {+ if (!PROVENANCE_SOURCE_KINDS.includes(kind)) return null;+ if (typeof id !== 'string' || !id.trim()) return null;+ const url = typeof sourceUrl === 'string' && sourceUrl.trim() ? sourceUrl.trim() : null;+ const display = typeof name === 'string' && name.trim() ? name.trim() : null;+ return {+ kind,+ id: id.trim(),+ name: display,+ license: normalizeLicense(license),+ sourceUrl: url,+ };+}++const sourceKey = (src) => `${src.kind}:${src.id}`;++export function buildProvenance({ sources = [], capturedAt = null } = {}) {+ const captured = typeof capturedAt === 'string' && capturedAt.trim() ? capturedAt.trim() : null;+ const byKey = new Map();+ for (const raw of Array.isArray(sources) ? sources : []) {+ const src = buildProvenanceSource(raw);+ if (!src) continue;+ const key = sourceKey(src);+ const existing = byKey.get(key);+ if (!existing) {+ byKey.set(key, src);+ continue;+ }+ // Prefer a known license over unknown when the same source appears twice+ // in one stamp (model + LoRA list shouldn't collide, but a rollup can).+ if (existing.license == null && src.license != null) {+ byKey.set(key, {+ ...existing,+ license: src.license,+ name: existing.name || src.name,+ sourceUrl: existing.sourceUrl || src.sourceUrl,+ });+ continue;+ }+ byKey.set(key, {+ ...existing,+ name: existing.name || src.name,+ sourceUrl: existing.sourceUrl || src.sourceUrl,+ });+ }+ return {+ schemaVersion: PROVENANCE_SCHEMA_VERSION,+ capturedAt: captured,+ sources: [...byKey.values()],+ };+}++export function readProvenance(record) {+ const raw = record?.provenance;+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const built = buildProvenance({+ sources: Array.isArray(raw.sources) ? raw.sources : [],+ capturedAt: raw.capturedAt,+ });+ return built.sources.length ? built : null;+}++function pickLoraFilenames(record) {+ if (Array.isArray(record?.loraFilenames)) return record.loraFilenames;+ if (Array.isArray(record?.lora_filenames)) return record.lora_filenames;+ return [];+}++export function resolveAssetProvenance(record) {+ const stamped = readProvenance(record);+ if (stamped) return { ...stamped, reconstructed: false };+ if (!record || typeof record !== 'object') return null;+ const modelId = record.modelId || record.model;+ const loras = pickLoraFilenames(record).filter((f) => typeof f === 'string' && f);+ if (!modelId && !loras.length) return null;+ const capturedAt = typeof record.createdAt === 'string' ? record.createdAt : null;+ return {+ ...buildProvenance({+ sources: [+ ...(modelId ? [{ kind: 'model', id: String(modelId), license: null }] : []),+ ...loras.map((id) => ({ kind: 'lora', id, license: null })),+ ],+ capturedAt,+ }),+ reconstructed: true,+ };+}++export function licenseFromRegistryModel(model) {+ // Weights terms only. `disclosure.runtimeLicense` is the inference stack+ // (often MIT) and must never be promoted into the asset's model license.+ return normalizeLicense(model?.license)+ || normalizeLicense(model?.disclosure?.weightsLicense?.name);+}++export function provenanceForRender({ model = null, loras = [], capturedAt = null } = {}) {+ const sources = [];+ if (model && (model.id || model.name)) {+ const id = String(model.id || model.name);+ const disclosureUrl = typeof model.disclosure?.modelCardUrl === 'string'+ ? model.disclosure.modelCardUrl+ : null;+ const weightsUrl = typeof model.disclosure?.weightsLicense?.url === 'string'+ ? model.disclosure.weightsLicense.url+ : null;+ sources.push({+ kind: 'model',+ id,+ name: model.name || null,+ license: licenseFromRegistryModel(model),+ sourceUrl: model.sourceUrl || huggingfaceUrl(model.repo) || disclosureUrl || weightsUrl,+ });+ }+ for (const lora of Array.isArray(loras) ? loras : []) {+ const filename = typeof lora === 'string' ? lora : lora?.filename;+ if (typeof filename !== 'string' || !filename) continue;+ sources.push({+ kind: 'lora',+ id: filename,+ name: typeof lora === 'object' ? (lora.name || null) : null,+ license: typeof lora === 'object' ? lora.license : null,+ sourceUrl: typeof lora === 'object' ? lora.sourceUrl : null,+ });+ }+ return buildProvenance({ sources, capturedAt });+}++export function rollupProvenance(records) {+ const sources = [];+ for (const record of Array.isArray(records) ? records : []) {+ const resolved = resolveAssetProvenance(record);+ if (!resolved) continue;+ sources.push(...resolved.sources);+ }+ return buildProvenance({ sources, capturedAt: null });+}++export function formatProvenanceSource(src) {+ const built = buildProvenanceSource(src);+ if (!built) return null;+ return { ...built, licenseLabel: licenseLabel(built.license) };+}diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 3df16c0322..94ea0a0e68 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -106,6 +106,7 @@ export * from './loopbackHost.js';export * from './manuscriptAnchors.js';export * from './manuscriptFormat.js';export * from './mediaCollectionList.js';+export * from './assetProvenance.js';export * from './mediaNavigation.js';export * from './mediaSearch.js';export * from './morsePractice.js';diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsxindex 66f48fb655..b05398e2e8 100644--- a/client/src/pages/MediaCollectionDetail.jsx+++ b/client/src/pages/MediaCollectionDetail.jsx@@ -5,6 +5,7 @@ import ShareToButton from '../components/sharing/ShareToButton';import PageSkeleton from '../components/ui/PageSkeleton';import toast from '../components/ui/Toast';import MediaCard from '../components/media/MediaCard';+import AttributionList from '../components/media/AttributionList';import MediaPreview from '../components/media/MediaPreview';import BulkTargetPicker from '../components/media/BulkTargetPicker';import { normalizeImage, normalizeVideo } from '../components/media/normalize';@@ -429,6 +430,8 @@ export default function MediaCollectionDetail() {)}</div>+ <AttributionList records={items} className="bg-port-card border border-port-border rounded-lg px-3 py-2" />+{selectMode && (<div className="bg-port-card border border-port-border rounded-lg px-3 py-2 flex flex-wrap items-center gap-2 sticky top-0 z-30"><span className="text-xs text-gray-300">diff --git a/client/src/pages/PipelineExport.jsx b/client/src/pages/PipelineExport.jsxindex ccf7f5e5e0..5c7699eda6 100644--- a/client/src/pages/PipelineExport.jsx+++ b/client/src/pages/PipelineExport.jsx@@ -21,8 +21,13 @@ import {proseExportManuscriptUrl,proseExportEpubUrl,proseExportPdfUrl,+ listMediaCollections,+ listImageGallery,+ listVideoHistory,} from '../services/api';import { useAsyncAction } from '../hooks/useAsyncAction';+import { normalizeImage, normalizeVideo } from '../components/media/normalize';+import AttributionList from '../components/media/AttributionList';// Kept in sync with server/lib/proseExportSettings.js (allow-lists + defaults).const TRIM_SIZE_OPTIONS = [@@ -73,6 +78,7 @@ export default function PipelineExport() {const [loading, setLoading] = useState(true);const [form, setForm] = useState(emptyForm);const [savedForm, setSavedForm] = useState(emptyForm);+ const [seriesAssets, setSeriesAssets] = useState([]);useEffect(() => {let canceled = false;@@ -94,6 +100,34 @@ export default function PipelineExport() {return () => { canceled = true; };}, [seriesId, navigate]);+ // Roll up licenses from the series media collection so a user about to+ // publish can see the terms that applied when the pixels were made (#5638).+ useEffect(() => {+ let canceled = false;+ Promise.all([+ listMediaCollections({ silent: true }),+ listImageGallery({ silent: true }),+ listVideoHistory({ silent: true }),+ ]).then(([collections, images, videos]) => {+ if (canceled) return;+ const list = Array.isArray(collections) ? collections : [];+ const collection = list.find((c) => c.seriesId === seriesId || c.id === `sc-${seriesId}`);+ if (!collection) { setSeriesAssets([]); return; }+ const imagesByName = new Map((images || []).map((i) => [i.filename, i]));+ const videosById = new Map((videos || []).map((v) => [v.id, v]));+ const out = [];+ for (const it of collection.items || []) {+ if (it.kind === 'image' && imagesByName.has(it.ref)) {+ out.push(normalizeImage(imagesByName.get(it.ref)));+ } else if (it.kind === 'video' && videosById.has(it.ref)) {+ out.push(normalizeVideo(videosById.get(it.ref)));+ }+ }+ setSeriesAssets(out);+ }).catch(() => { if (!canceled) setSeriesAssets([]); });+ return () => { canceled = true; };+ }, [seriesId]);+const dirty = useMemo(() => JSON.stringify(form) !== JSON.stringify(savedForm),[form, savedForm],@@ -269,6 +303,11 @@ export default function PipelineExport() {))}</section></div>++ <AttributionList+ records={seriesAssets}+ className="mt-6 max-w-5xl bg-port-card border border-port-border rounded-lg px-3 py-2"+ /></div>);}diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 663f996e09..524b6312ab 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -87,6 +87,8 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](**Media asset index (`media_assets`, #1000).** One row per generated image/video: `media_key` (`<kind>:<ref>`) PK, `kind`/`ref`/`created_at` mirror columns for queries, the full metadata record in `data` JSONB. It is a **derived index** — the on-disk sidecars + `video-history.json` stay authoritative — reconciled from disk at boot (upsert every asset, prune rows whose file is gone) and kept warm by a generation-`completed` hook. Local-only (rebuilt from disk), so no sync cursor/tombstone. Adapter: `server/services/mediaAssetIndex/{logic,db,index}.js`.+**Asset license provenance (#5638).** Every finished image and video stamps `data.provenance` at finalize time: the renderer/model id, every LoRA applied, and each one's license string and source URL *as known when the pixels were made*. Unknown stays `null` (displayed as "unknown") — never a permissive default. A license re-read months later can differ from the one in force at render, so the stamp is written into the authoritative sidecar / video-history row (the derived `media_assets.data` JSONB mirrors it). LoRA installs persist `license` on the `.metadata.json` sidecar so it is available at render rather than re-fetched. Collection and export surfaces roll the distinct sources up into an Attribution & licenses section.+**Standalone media-library federation (`mediaLibrary`, #1566).** For **full-sync peers**, the standalone media-library *bytes* (generated images + sidecars, videos, pipeline audio, uploaded music) mirror across the pair — not just bytes referenced by a synced creative record. The sender advertises a library-level manifest at `GET /api/peer-sync/library-manifest` (`{ schemaVersion, manifestHash, assets:[{kind,filename,sha256,sidecarSha256?}] }`); the receiver's periodic sweep (`syncMediaLibraryFromPeer`, driven from `initSharing`) diffs it against local disk, receiver-pulls missing bytes through the SAME `diffAssetManifestAgainstLocal` + `pullOneAsset` machinery as the per-record path, then rebuilds the derived `media_assets` index. Video thumbnails are regenerated locally on video pull (not byte-federated); `video-history.json` metadata already union-merges via the `videoHistory` dataSync category; the generic `data/history.jsonl` action log is machine-local and never federated. Byte replication is gated to `peer.fullSync` and honors backup `DEFAULT_EXCLUDES` (a media dir excluded from backup isn't federated). Manifest envelope versioned by `PORTOS_SCHEMA_VERSIONS.mediaLibrary` (a non-record category — see `NON_RECORD_SCHEMA_CATEGORIES`); the receiver gently skips a sender ahead of its version.**Postgres-First target (remaining).** `data/history.jsonl` (action log) and the durable portions of `data/media-jobs.json` (job history / lineage) are still file-backed — follow-up slices. Do **not** move generated image/video/audio bytes into PostgreSQL.diff --git a/server/lib/README.md b/server/lib/README.mdindex bc0a4cd5e8..829129f5f1 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -389,6 +389,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `learningVerdict.js` | The three-way success-criteria verdict a completed agent run carries on `result.validationPassed` (#4107). `true`/`false` = a declared criterion was met/missed; `null` = none declared (record the run, fall back to the exit code); `SKIP_LEARNING_VERDICT` = nothing ever evaluated the run, so task-learning must not record it at all (a programmatic-I/O output hook that bailed on `no-app`/`app-not-found`). `isSkipLearningVerdict(v)` gates the skip; `toValidationVerdict(v)` narrows anything non-boolean — including the sentinel — back to `null` for downstream telemetry. JSON-safe string (not a Symbol) because the verdict is persisted and read back by the learning backfill, and older readers already narrow on `typeof v === 'boolean'`. Pure. || `investigationTasks.js` | Investigation-task identity, approval, auto-retry, and PR-backed delivery policy — shared by the producers (`services/investigationTaskProducer.js`), the reaper (`cosTaskStore.js`, which used to hand-copy the predicate to dodge an import cycle) and the retry (`services/investigationRetry.js`). `isInvestigationTask(task)` (durable `isInvestigation` marker, falling back to the `INVESTIGATION_HEADLINE_PREFIX` headline for pre-#2615 / peer-synced tasks); `INVESTIGATION_TASK_DELIVERY` keeps unattended investigations in an isolated worktree and routes them through a PR merged on green; `buildInvestigationFingerprint(task, analysis)` / `investigationFingerprint({category, kind, scope})` → the `category:kind:scope` dedup key; `resolveInvestigationApproval({fingerprint, tasks, recentCreations})` → unattended by default (#3714), held only on a `repeat-fingerprint` or `failure-storm` loop, with `approvalReason` + `loopProse` for the queue UI; `couldReleaseBlockedTasks(investigation)` is the pure pre-read gate for `resolveInvestigationRetryTargets({investigation, tasksById})`, which returns the failure-blocked tasks a just-completed investigation releases plus every skip and its `RETRY_SKIP_REASONS` reason (an `auto-expired` completion, a non-`blocked` task, a `NON_AUTO_RETRY_BLOCK_CATEGORIES` block, or a task past `MAX_AUTO_RETRIES_PER_TASK`); `autoRetryMetadata(task, investigationId, now)` stamps the budget that survives the revive's own `failureCount` reset. Pure. || `mediaItemKey.js` | `<kind>:<ref>` key vocabulary for media items. |+| `assetProvenance.js` | Stamp-time model/LoRA license provenance (`buildProvenance` / `provenanceForRender` / `rollupProvenance`). Unknown stays `null` (displayed as "unknown") — never a permissive default. Mirrored byte-for-byte to `client/src/lib/assetProvenance.js`. || `migrationMarker.js` | Shared marker-file helpers for one-time migration/repair/reconcile scripts — `markerExists(filename)` (boolean gate), `readMarker(filename)` (parsed payload or null), `writeMarker(filename, payload)` (atomic write). All anchor `filename` under `PATHS.data` and use `tryReadFile`/`atomicWrite` so a crash can't leave a truncated marker. || `goalFeatureMap.js` | Deterministic goal `category` → PortOS feature-area map (deep-links sourced from `NAV_COMMANDS`). `getGoalFeatureAreas(goal)` honors the per-goal `featureAreas` override, else the category default. Mirrored byte-for-byte to `client/src/lib/`. || `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. |diff --git a/server/lib/assetProvenance.js b/server/lib/assetProvenance.jsnew file mode 100644index 0000000000..98c7fa3cba--- /dev/null+++ b/server/lib/assetProvenance.js@@ -0,0 +1,198 @@+/**+ * Asset license provenance — stamp at finalize time, never re-read later.+ *+ * PortOS already resolves a model's license when it downloads one+ * (`licenseOf` in huggingFaceCatalog, Civitai/HF LoRA cards) and then drops+ * it on the floor. Create-suite outputs leave the machine (collections,+ * pipeline export, albums), so the terms that applied WHEN THE PIXELS WERE+ * MADE have to travel with the asset. A license re-read months later can+ * differ from the one in force at render; unknown stays unknown (`null`),+ * displayed as "unknown" — never a permissive default.+ *+ * Shape (schemaVersion 1):+ * {+ * schemaVersion: 1,+ * capturedAt: ISO-8601 | null,+ * sources: [{ kind: 'model'|'lora', id, name, license, sourceUrl }]+ * }+ *+ * Pure — no I/O. Server and client share this module byte-for-byte.+ */++export const PROVENANCE_SCHEMA_VERSION = 1;+export const PROVENANCE_SOURCE_KINDS = Object.freeze(['model', 'lora']);+export const UNKNOWN_LICENSE_LABEL = 'unknown';++export function normalizeLicense(value) {+ if (typeof value !== 'string') return null;+ const trimmed = value.trim();+ return trimmed || null;+}++export function licenseLabel(license) {+ const normalized = normalizeLicense(license);+ return normalized || UNKNOWN_LICENSE_LABEL;+}++export function huggingfaceUrl(repo) {+ if (typeof repo !== 'string') return null;+ const id = repo.trim();+ return id ? `https://huggingface.co/${id}` : null;+}++export function licenseFromHuggingFaceModel(model) {+ const card = normalizeLicense(model?.cardData?.license || model?.license);+ if (card) return card;+ const tags = Array.isArray(model?.tags) ? model.tags : [];+ const tag = tags.find((t) => typeof t === 'string' && /^license:/i.test(t));+ return tag ? normalizeLicense(tag.slice(tag.indexOf(':') + 1)) : null;+}++export function licenseFromCivitaiModel(model) {+ // Civitai's `allowCommercialUse` is a policy flag, not a license string —+ // never promote it into one. Only a real `license` field counts.+ return normalizeLicense(model?.license);+}++export function buildProvenanceSource({ kind, id, name = null, license = null, sourceUrl = null } = {}) {+ if (!PROVENANCE_SOURCE_KINDS.includes(kind)) return null;+ if (typeof id !== 'string' || !id.trim()) return null;+ const url = typeof sourceUrl === 'string' && sourceUrl.trim() ? sourceUrl.trim() : null;+ const display = typeof name === 'string' && name.trim() ? name.trim() : null;+ return {+ kind,+ id: id.trim(),+ name: display,+ license: normalizeLicense(license),+ sourceUrl: url,+ };+}++const sourceKey = (src) => `${src.kind}:${src.id}`;++export function buildProvenance({ sources = [], capturedAt = null } = {}) {+ const captured = typeof capturedAt === 'string' && capturedAt.trim() ? capturedAt.trim() : null;+ const byKey = new Map();+ for (const raw of Array.isArray(sources) ? sources : []) {+ const src = buildProvenanceSource(raw);+ if (!src) continue;+ const key = sourceKey(src);+ const existing = byKey.get(key);+ if (!existing) {+ byKey.set(key, src);+ continue;+ }+ // Prefer a known license over unknown when the same source appears twice+ // in one stamp (model + LoRA list shouldn't collide, but a rollup can).+ if (existing.license == null && src.license != null) {+ byKey.set(key, {+ ...existing,+ license: src.license,+ name: existing.name || src.name,+ sourceUrl: existing.sourceUrl || src.sourceUrl,+ });+ continue;+ }+ byKey.set(key, {+ ...existing,+ name: existing.name || src.name,+ sourceUrl: existing.sourceUrl || src.sourceUrl,+ });+ }+ return {+ schemaVersion: PROVENANCE_SCHEMA_VERSION,+ capturedAt: captured,+ sources: [...byKey.values()],+ };+}++export function readProvenance(record) {+ const raw = record?.provenance;+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const built = buildProvenance({+ sources: Array.isArray(raw.sources) ? raw.sources : [],+ capturedAt: raw.capturedAt,+ });+ return built.sources.length ? built : null;+}++function pickLoraFilenames(record) {+ if (Array.isArray(record?.loraFilenames)) return record.loraFilenames;+ if (Array.isArray(record?.lora_filenames)) return record.lora_filenames;+ return [];+}++export function resolveAssetProvenance(record) {+ const stamped = readProvenance(record);+ if (stamped) return { ...stamped, reconstructed: false };+ if (!record || typeof record !== 'object') return null;+ const modelId = record.modelId || record.model;+ const loras = pickLoraFilenames(record).filter((f) => typeof f === 'string' && f);+ if (!modelId && !loras.length) return null;+ const capturedAt = typeof record.createdAt === 'string' ? record.createdAt : null;+ return {+ ...buildProvenance({+ sources: [+ ...(modelId ? [{ kind: 'model', id: String(modelId), license: null }] : []),+ ...loras.map((id) => ({ kind: 'lora', id, license: null })),+ ],+ capturedAt,+ }),+ reconstructed: true,+ };+}++export function licenseFromRegistryModel(model) {+ // Weights terms only. `disclosure.runtimeLicense` is the inference stack+ // (often MIT) and must never be promoted into the asset's model license.+ return normalizeLicense(model?.license)+ || normalizeLicense(model?.disclosure?.weightsLicense?.name);+}++export function provenanceForRender({ model = null, loras = [], capturedAt = null } = {}) {+ const sources = [];+ if (model && (model.id || model.name)) {+ const id = String(model.id || model.name);+ const disclosureUrl = typeof model.disclosure?.modelCardUrl === 'string'+ ? model.disclosure.modelCardUrl+ : null;+ const weightsUrl = typeof model.disclosure?.weightsLicense?.url === 'string'+ ? model.disclosure.weightsLicense.url+ : null;+ sources.push({+ kind: 'model',+ id,+ name: model.name || null,+ license: licenseFromRegistryModel(model),+ sourceUrl: model.sourceUrl || huggingfaceUrl(model.repo) || disclosureUrl || weightsUrl,+ });+ }+ for (const lora of Array.isArray(loras) ? loras : []) {+ const filename = typeof lora === 'string' ? lora : lora?.filename;+ if (typeof filename !== 'string' || !filename) continue;+ sources.push({+ kind: 'lora',+ id: filename,+ name: typeof lora === 'object' ? (lora.name || null) : null,+ license: typeof lora === 'object' ? lora.license : null,+ sourceUrl: typeof lora === 'object' ? lora.sourceUrl : null,+ });+ }+ return buildProvenance({ sources, capturedAt });+}++export function rollupProvenance(records) {+ const sources = [];+ for (const record of Array.isArray(records) ? records : []) {+ const resolved = resolveAssetProvenance(record);+ if (!resolved) continue;+ sources.push(...resolved.sources);+ }+ return buildProvenance({ sources, capturedAt: null });+}++export function formatProvenanceSource(src) {+ const built = buildProvenanceSource(src);+ if (!built) return null;+ return { ...built, licenseLabel: licenseLabel(built.license) };+}diff --git a/server/lib/assetProvenance.test.js b/server/lib/assetProvenance.test.jsnew file mode 100644index 0000000000..ac3beed894--- /dev/null+++ b/server/lib/assetProvenance.test.js@@ -0,0 +1,189 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import {+ UNKNOWN_LICENSE_LABEL,+ buildProvenance,+ buildProvenanceSource,+ huggingfaceUrl,+ licenseFromCivitaiModel,+ licenseFromHuggingFaceModel,+ licenseLabel,+ normalizeLicense,+ provenanceForRender,+ readProvenance,+ resolveAssetProvenance,+ rollupProvenance,+} from './assetProvenance.js';++describe('normalizeLicense / licenseLabel', () => {+ it('treats blank, whitespace, and non-strings as unknown (null)', () => {+ expect(normalizeLicense('')).toBeNull();+ expect(normalizeLicense(' ')).toBeNull();+ expect(normalizeLicense(null)).toBeNull();+ expect(normalizeLicense(undefined)).toBeNull();+ expect(normalizeLicense(42)).toBeNull();+ expect(licenseLabel(null)).toBe(UNKNOWN_LICENSE_LABEL);+ expect(licenseLabel(' ')).toBe(UNKNOWN_LICENSE_LABEL);+ });+ it('never infers a permissive default from absence', () => {+ expect(licenseLabel(undefined)).toBe('unknown');+ expect(licenseLabel('mit')).toBe('mit');+ });+});++describe('licenseFromHuggingFaceModel', () => {+ it('prefers cardData.license, then license, then a license: tag', () => {+ expect(licenseFromHuggingFaceModel({ cardData: { license: 'apache-2.0' } })).toBe('apache-2.0');+ expect(licenseFromHuggingFaceModel({ license: 'mit' })).toBe('mit');+ expect(licenseFromHuggingFaceModel({ tags: ['text-to-image', 'license:openrail'] })).toBe('openrail');+ });+ it('returns null when nothing is observable', () => {+ expect(licenseFromHuggingFaceModel({})).toBeNull();+ expect(licenseFromHuggingFaceModel({ tags: ['flux'] })).toBeNull();+ });+});++describe('licenseFromCivitaiModel', () => {+ it('reads the license string and ignores allowCommercialUse', () => {+ expect(licenseFromCivitaiModel({ license: 'CreativeML Open RAIL-M' })).toBe('CreativeML Open RAIL-M');+ expect(licenseFromCivitaiModel({ allowCommercialUse: 'Sell' })).toBeNull();+ expect(licenseFromCivitaiModel({ license: '', allowCommercialUse: 'Sell' })).toBeNull();+ });+});++describe('buildProvenance / provenanceForRender', () => {+ it('stamps model + LoRA sources with unknown licenses as null', () => {+ const p = provenanceForRender({+ model: { id: 'flux2-klein-9b', name: 'FLUX.2 Klein 9B', repo: 'org/flux2' },+ loras: [{ filename: 'lora-style.safetensors', license: 'openrail', sourceUrl: 'https://civitai.com/models/1' }],+ capturedAt: '2026-09-02T12:00:00.000Z',+ });+ expect(p.schemaVersion).toBe(1);+ expect(p.capturedAt).toBe('2026-09-02T12:00:00.000Z');+ expect(p.sources).toEqual([+ {+ kind: 'model',+ id: 'flux2-klein-9b',+ name: 'FLUX.2 Klein 9B',+ license: null,+ sourceUrl: 'https://huggingface.co/org/flux2',+ },+ {+ kind: 'lora',+ id: 'lora-style.safetensors',+ name: null,+ license: 'openrail',+ sourceUrl: 'https://civitai.com/models/1',+ },+ ]);+ });+ it('uses disclosure.weightsLicense and never runtimeLicense', () => {+ const p = provenanceForRender({+ model: {+ id: 'ltx-2.3',+ name: 'LTX 2.3',+ disclosure: {+ modelCardUrl: 'https://huggingface.co/Lightricks/LTX-2.3',+ weightsLicense: { name: 'Apache-2.0', url: 'https://huggingface.co/Lightricks/LTX-2.3' },+ runtimeLicense: { name: 'MIT', url: 'https://opensource.org/licenses/MIT' },+ },+ },+ });+ expect(p.sources[0].license).toBe('Apache-2.0');+ expect(p.sources[0].sourceUrl).toBe('https://huggingface.co/Lightricks/LTX-2.3');+ });++ it('drops unusable sources and dedupes by kind+id, preferring a known license', () => {+ const p = buildProvenance({+ sources: [+ { kind: 'model', id: 'm', license: null },+ { kind: 'model', id: 'm', license: 'mit', name: 'M' },+ { kind: 'weird', id: 'x' },+ { kind: 'lora', id: '' },+ ],+ });+ expect(p.sources).toEqual([+ { kind: 'model', id: 'm', name: 'M', license: 'mit', sourceUrl: null },+ ]);+ });+});++describe('readProvenance / resolveAssetProvenance', () => {+ it('returns stamped provenance as-is and does not re-derive licenses', () => {+ const record = {+ modelId: 'flux2-klein-9b',+ provenance: {+ schemaVersion: 1,+ capturedAt: '2026-01-01T00:00:00.000Z',+ sources: [{ kind: 'model', id: 'flux2-klein-9b', license: null, name: 'Klein', sourceUrl: null }],+ },+ };+ const resolved = resolveAssetProvenance(record);+ expect(resolved.reconstructed).toBe(false);+ expect(resolved.sources[0].license).toBeNull();+ });+ it('reconstructs unknown-license sources from sidecar fields when provenance is missing', () => {+ const resolved = resolveAssetProvenance({+ modelId: 'flux2-klein-9b',+ loraFilenames: ['lora-style.safetensors'],+ createdAt: '2026-01-02T00:00:00.000Z',+ });+ expect(resolved.reconstructed).toBe(true);+ expect(resolved.sources.map((s) => s.id)).toEqual(['flux2-klein-9b', 'lora-style.safetensors']);+ expect(resolved.sources.every((s) => s.license == null)).toBe(true);+ });+ it('returns null when there is nothing to attribute', () => {+ expect(resolveAssetProvenance({})).toBeNull();+ expect(readProvenance({ provenance: { sources: [] } })).toBeNull();+ });+});++describe('rollupProvenance', () => {+ it('unions distinct sources across a collection of assets', () => {+ const rollup = rollupProvenance([+ {+ provenance: {+ sources: [+ { kind: 'model', id: 'a', license: 'mit' },+ { kind: 'lora', id: 'x.safetensors', license: null },+ ],+ },+ },+ {+ provenance: {+ sources: [+ { kind: 'model', id: 'a', license: 'mit' },+ { kind: 'model', id: 'b', license: 'apache-2.0' },+ ],+ },+ },+ ]);+ expect(rollup.sources.map((s) => s.id)).toEqual(['a', 'x.safetensors', 'b']);+ });+});++describe('huggingfaceUrl', () => {+ it('builds a Hub URL from a repo id and rejects blanks', () => {+ expect(huggingfaceUrl('org/name')).toBe('https://huggingface.co/org/name');+ expect(huggingfaceUrl(' ')).toBeNull();+ expect(huggingfaceUrl(null)).toBeNull();+ });+});++describe('buildProvenanceSource', () => {+ it('rejects unknown kinds and empty ids', () => {+ expect(buildProvenanceSource({ kind: 'runtime', id: 'x' })).toBeNull();+ expect(buildProvenanceSource({ kind: 'model', id: '' })).toBeNull();+ });+});++describe('client mirror', () => {+ it('stays byte-for-byte with client/src/lib/assetProvenance.js', () => {+ const here = dirname(fileURLToPath(import.meta.url));+ const server = readFileSync(join(here, 'assetProvenance.js'), 'utf8');+ const client = readFileSync(join(here, '../../client/src/lib/assetProvenance.js'), 'utf8');+ expect(client).toBe(server);+ });+});diff --git a/server/lib/civitai.js b/server/lib/civitai.jsindex b63bbd3fb3..b70be05fed 100644--- a/server/lib/civitai.js+++ b/server/lib/civitai.js@@ -18,6 +18,7 @@import { ServerError } from './errorHandler.js';import { RUNNER_FAMILIES } from './runners.js';import { readResponseJson } from './readResponseJson.js';+import { licenseFromCivitaiModel } from './assetProvenance.js';const CIVITAI_API = 'https://civitai.com/api/v1';const CIVITAI_HOSTS = new Set(['civitai.com', 'civitai.red', 'civitai.green', 'www.civitai.com']);@@ -334,6 +335,9 @@ export const buildSidecar = ({ model, version, file, filename }) => {downloadUrl: file?.downloadUrl || null,},previewImageUrl: normalizeCivitaiImageUrl(previewImage?.url) || null,+ // License as known at install time (#5638). Unknown stays null — never+ // inferred from allowCommercialUse. Re-read at render would lie.+ license: licenseFromCivitaiModel(model),installedAt: new Date().toISOString(),};};diff --git a/server/lib/civitai.test.js b/server/lib/civitai.test.jsindex 182eba6348..c95354152d 100644--- a/server/lib/civitai.test.js+++ b/server/lib/civitai.test.js@@ -394,6 +394,23 @@ describe('buildSidecar', () => {expect(sc.previewImageUrl).toBe('p.jpg');expect(sc.file.sizeKB).toBe(102400);expect(typeof sc.installedAt).toBe('string');+ expect(sc.license).toBeNull();+ });+ it('persists a Civitai license string and never infers one from allowCommercialUse', () => {+ const licensed = buildSidecar({+ model: { id: 1, name: 'Rail', license: 'CreativeML Open RAIL-M', allowCommercialUse: 'Sell' },+ version: { id: 2, baseModel: 'Flux.1 D' },+ file: {},+ filename: 'lora-rail-v2.safetensors',+ });+ expect(licensed.license).toBe('CreativeML Open RAIL-M');+ const commercialOnly = buildSidecar({+ model: { id: 1, name: 'NoLicense', allowCommercialUse: 'Sell' },+ version: { id: 2, baseModel: 'Flux.1 D' },+ file: {},+ filename: 'lora-nolicense-v2.safetensors',+ });+ expect(commercialOnly.license).toBeNull();});it('falls back when version has no settings/preview/trainedWords', () => {const sc = buildSidecar({diff --git a/server/lib/huggingfaceLora.js b/server/lib/huggingfaceLora.jsindex 70a16dab64..b82f5163c9 100644--- a/server/lib/huggingfaceLora.js+++ b/server/lib/huggingfaceLora.js@@ -21,6 +21,7 @@import { ServerError } from './errorHandler.js';import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES } from './runners.js';import { readResponseJson } from './readResponseJson.js';+import { licenseFromHuggingFaceModel } from './assetProvenance.js';// Families the HF installer may stamp. Image runners plus video families —// the route schema and the family-override validator share this list.@@ -358,6 +359,7 @@ export const buildHfLoraSidecar = ({ repo, revision, file, model, family, filena},previewImageUrl: null,source: 'huggingface',+ license: licenseFromHuggingFaceModel(model),installedAt: new Date().toISOString(),};};diff --git a/server/lib/huggingfaceLora.test.js b/server/lib/huggingfaceLora.test.jsindex 29a52ff768..97f84ff39a 100644--- a/server/lib/huggingfaceLora.test.js+++ b/server/lib/huggingfaceLora.test.js@@ -231,8 +231,20 @@ describe('buildHfLoraSidecar', () => {expect(sidecar.recommendedScale).toBe(1.0);expect(sidecar.civitai).toBeUndefined();expect(sidecar.file.downloadUrl).toContain('/resolve/main/lora.safetensors');+ expect(sidecar.license).toBeNull();});+ it('persists a HuggingFace card license when the model reports one', () => {+ const sidecar = buildHfLoraSidecar({+ repo: 'org/weights',+ revision: null,+ file: 'lora.safetensors',+ family: VIDEO_LORA_FAMILIES.LTX_VIDEO,+ filename: 'lora-org-weights-hf.safetensors',+ model: { cardData: { license: 'apache-2.0' }, tags: ['ltxv'] },+ });+ expect(sidecar.license).toBe('apache-2.0');+ });it('labels a V2 LoRA distinctly and uses its recommended scale', () => {const sidecar = buildHfLoraSidecar({repo: 'fal/ltx2.3-audio-reactive-lora',diff --git a/server/lib/index.js b/server/lib/index.jsindex 5f8a082d46..95127d7260 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -358,6 +358,7 @@ export * from './musicDuration.js';export * from './investigationTasks.js';export * from './learningVerdict.js';export * from './mediaItemKey.js';+export * from './assetProvenance.js';export * from './migrationMarker.js';export * from './modelPricing.js';export * from './navManifest.js';diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex df6b67632a..f3e23f4cca 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -44,7 +44,8 @@ import { getImageModels, isFlux2, isErnie, isHiDream, isQwen } from '../../lib/mimport { isHardwareCompatible } from '../../lib/systemCapabilities.js';import { usesDiffusersRunner, flux2Bf16BaseRepo } from '../../lib/runners.js';import { weaveLoraTriggers } from '../../lib/loraTriggers.js';-import { readTriggerWordsByFilename } from '../loras.js';+import { provenanceForRender } from '../../lib/assetProvenance.js';+import { readTriggerWordsByFilename, readLoraLicensesByFilename } from '../loras.js';// Read the registry lazily — callers below hit getImageModels() at request// time. A prior `IMAGE_MODELS = Object.fromEntries(getImageModels()...)`@@ -330,6 +331,9 @@ export function buildSidecarMeta({// passes the map so this stays pure. Keyed rather than positional because the// valid-LoRA order is only known after the prefix-check below.loraTriggerWords = null,+ // License map keyed by LoRA basename, read from sidecars by generateImage+ // so this stays pure. Missing entries stamp license: null (unknown).+ loraLicenses = null,initImagePath = null,initImageStrength = null,referenceImagePaths = [],@@ -453,6 +457,23 @@ export function buildSidecarMeta({meta.renderPrompt = renderPrompt;meta.addedTriggerWords = addedTriggerWords;}+ // Stamp the licenses known at THIS render. A later re-read of the LoRA+ // sidecar or model card must not rewrite what was true when the pixels+ // were made (#5638). Unknown stays null.+ meta.provenance = provenanceForRender({+ model: {+ id: modelId,+ name: model?.name || modelId,+ license: model?.license,+ repo: model?.repo,+ disclosure: model?.disclosure,+ },+ loras: validLoraFilenames.map((filename) => ({+ filename,+ ...(loraLicenses?.[filename] || {}),+ })),+ capturedAt: meta.createdAt,+ });return {meta,renderPrompt,@@ -592,6 +613,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =// simply contributes nothing and the render is unchanged. A no-LoRA render// short-circuits inside the helper, so the common case does zero extra I/O.const loraTriggerWords = await readTriggerWordsByFilename([...loraFilenames, ...loraPaths]);+ const loraLicenses = await readLoraLicensesByFilename([...loraFilenames, ...loraPaths]);const {meta,renderPrompt,@@ -626,6 +648,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =visualConditioning,regenOf,loraTriggerWords,+ loraLicenses,resolveInputPath: resolveImageInputPath,loraExists: existsSync,});diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.jsindex f83ab0509b..9b05a05e9e 100644--- a/server/services/imageGen/local.test.js+++ b/server/services/imageGen/local.test.js@@ -645,6 +645,33 @@ describe('imageGen local.buildSidecarMeta', () => {expect(meta.referenceImageStrengths).toEqual([0.85, 0.5]);});+ it('stamps model+LoRA provenance at finalize and never guesses a license', () => {+ const { meta } = buildSidecarMeta({+ ...baseMetaInput,+ model: { id: 'flux2-klein-9b', name: 'FLUX.2 Klein 9B', repo: 'org/flux2', steps: 8, guidance: 0 },+ loraFilenames: ['style.safetensors'],+ loraLicenses: { 'style.safetensors': { license: 'openrail', sourceUrl: 'https://civitai.com/models/1', name: 'Style' } },+ });+ expect(meta.provenance.schemaVersion).toBe(1);+ expect(meta.provenance.capturedAt).toBe('2024-01-01T00:00:00.000Z');+ expect(meta.provenance.sources).toEqual([+ {+ kind: 'model',+ id: 'flux2-klein-9b',+ name: 'FLUX.2 Klein 9B',+ license: null,+ sourceUrl: 'https://huggingface.co/org/flux2',+ },+ {+ kind: 'lora',+ id: 'style.safetensors',+ name: 'Style',+ license: 'openrail',+ sourceUrl: 'https://civitai.com/models/1',+ },+ ]);+ });+it('persists FableLoom visual-conditioning provenance without rewriting it', () => {const visualConditioning = {version: 1, compilerVersion: '1.0.0', status: 'locked', assets: [{ role: 'character-neutral', filename: 'aria.png' }],diff --git a/server/services/imageGen/remote.js b/server/services/imageGen/remote.jsindex 24fa0fbd37..3ad9f49704 100644--- a/server/services/imageGen/remote.js+++ b/server/services/imageGen/remote.js@@ -24,6 +24,9 @@ import {import { createRemoteMediaExecutor } from '../federatedMedia/remoteExecutor.js';import { applyRemoteInputAssets, remoteInputAssetsSchema } from '../federatedMedia/inputAssets.js';import { imageGenEvents } from '../imageGenEvents.js';+import { provenanceForRender } from '../../lib/assetProvenance.js';+import { readLoraLicensesByFilename } from '../loras.js';+import { getImageModels } from '../../lib/mediaModels.js';const remoteImageMarkerSchema = z.object({wireVersion: z.literal(FEDERATED_MEDIA_WIRE_VERSION),@@ -70,11 +73,16 @@ const executor = createRemoteMediaExecutor({// never reported. `federatedPeer`/`federatedJob` are instance-level// identifiers already shared across the federation — they are the result// provenance, and carry no hostname, address, or credential.+ const createdAt = new Date().toISOString();+ const modelId = remoteJob.result.modelId ?? request.modelId;+ const model = getImageModels().find((m) => m.id === modelId);+ const loraFilenames = Array.isArray(request.loraFilenames) ? request.loraFilenames : [];+ const loraLicenses = await readLoraLicensesByFilename(loraFilenames);const meta = {id: jobId,prompt: request.prompt,negativePrompt: request.negativePrompt ?? '',- modelId: remoteJob.result.modelId ?? request.modelId,+ modelId,seed: request.seed ?? null,width: request.width,height: request.height,@@ -83,7 +91,21 @@ const executor = createRemoteMediaExecutor({filename,federatedPeerId: peerId,federatedJobId: remoteJob.id,- createdAt: new Date().toISOString(),+ createdAt,+ provenance: provenanceForRender({+ model: {+ id: modelId,+ name: model?.name || modelId,+ license: model?.license,+ repo: model?.repo,+ disclosure: model?.disclosure,+ },+ loras: loraFilenames.map((filename) => ({+ filename,+ ...(loraLicenses[filename] || {}),+ })),+ capturedAt: createdAt,+ }),...renderTimingFields(renderStartedAtMs),};await atomicWrite(join(dir, `${jobId}.metadata.json`), meta);diff --git a/server/services/loras.js b/server/services/loras.jsindex 99b2da462c..4b5298c7b3 100644--- a/server/services/loras.js+++ b/server/services/loras.js@@ -127,6 +127,25 @@ export const readTriggerWordsByFilename = async (filenames) => {);};+// License + source URL as recorded on the sidecar at install time (#5638).+// Missing/legacy sidecars contribute `{ license: null, sourceUrl: null }` so+// a render still stamps the LoRA id with unknown terms rather than skipping it.+export const readLoraLicensesByFilename = async (filenames) => {+ const names = [...new Set(+ (Array.isArray(filenames) ? filenames : [])+ .filter((f) => typeof f === 'string' && f)+ .map((f) => basename(f)),+ )];+ if (!names.length) return {};+ const sidecars = await Promise.all(names.map((n) => readSidecar(n)));+ return Object.fromEntries(names.map((n, i) => {+ const sc = sidecars[i] || {};+ const sourceUrl = sc.civitai?.url || sc.huggingface?.url || null;+ const license = typeof sc.license === 'string' && sc.license.trim() ? sc.license.trim() : null;+ return [n, { license, sourceUrl, name: sc.name || null }];+ }));+};+// Validate a basename so it can't escape PATHS.loras. Delegates to the// shared `assertSafeFilename` helper in fileUtils.js (which also handles// gallery .png assertions). Substring `..` is allowed because@@ -246,6 +265,7 @@ export const listLoras = async () => {// media list mixes clips in, and the card renders this in an <img>.previewImageUrl: normalizeCivitaiImageUrl(stillPreviewUrl(sidecar?.previewImageUrl)) || null,description: sidecar?.description || '',+ license: typeof sidecar?.license === 'string' && sidecar.license.trim() ? sidecar.license.trim() : null,// Trained-LoRA surfacing (sidecars written by services/loraTraining):// 'trained' source + the character identity block let the library UI// badge them and characterLoraResolver match them. Null for Civitaidiff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.jsindex f58386beae..3bdcdc4a37 100644--- a/server/services/videoGen/generateVideo.js+++ b/server/services/videoGen/generateVideo.js@@ -34,7 +34,8 @@ import { findFfmpeg, findFfprobe } from '../../lib/ffmpeg.js';import { inspectModelCache, findCachedRepoFile, findCachedRepoFiles } from '../../lib/hfCache.js';import { safeChildProcessOptions } from '../../lib/processEnv.js';import { describeRenderConditioning, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';-import { readTriggerWordsByFilename } from '../loras.js';+import { readTriggerWordsByFilename, readLoraLicensesByFilename } from '../loras.js';+import { provenanceForRender } from '../../lib/assetProvenance.js';import { weaveLoraTriggers } from '../../lib/loraTriggers.js';import { isLtx2FamilyRuntime } from '../../lib/runners.js';import {@@ -410,6 +411,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// orchestrator's per-chunk beats (`chunkPrompts`) get the tokens too — each// chunk re-enters through this function with its own prompt.const triggerWordsByLora = await readTriggerWordsByFilename(resolvedLoras.map((l) => l.filename));+ const loraLicenses = await readLoraLicensesByFilename(resolvedLoras.map((l) => l.filename));const { prompt: renderPrompt, added: addedTriggerWords } = weaveLoraTriggers(prompt,resolvedLoras.map((l) => triggerWordsByLora[l.filename]),@@ -712,6 +714,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mresolvedIcReferencePaths = clipPaths;}+ const createdAt = new Date().toISOString();const meta = {id: jobId,prompt,@@ -736,7 +739,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// override the user has since deselected....(resolvedTextEncoder ? { textEncoderId: resolvedTextEncoder.id } : {}),filename,- createdAt: new Date().toISOString(),+ createdAt,// History mode reflects the EFFECTIVE mode — buildLtx2Args infers fflf// from `keyframes` even when caller omitted `mode`, so without this the// history entry would say 'text' for a multi-keyframe render.@@ -808,6 +811,20 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mloraFilenames: resolvedLoras.map((l) => l.filename),loraScales: resolvedLoras.map((l) => l.strength),} : {}),+ provenance: provenanceForRender({+ model: {+ id: modelId,+ name: model?.name || modelId,+ license: model?.license,+ repo: model?.repo,+ disclosure: model?.disclosure,+ },+ loras: resolvedLoras.map((l) => ({+ filename: l.filename,+ ...(loraLicenses[l.filename] || {}),+ })),+ capturedAt: createdAt,+ }),// Provenance for the trigger weave (#4665). `prompt` above stays the user's// own text, so Remix re-derives triggers from whatever LoRAs are selected// then instead of compounding this render's clause; these two record whatdiff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex ec09e43df2..65213fcf23 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -361,6 +361,16 @@ vi.mock('../loras.js', () => ({.map((n) => [n, loraSidecarState.byFilename[n]?.triggerWords]).filter(([, words]) => Array.isArray(words)),)),+ readLoraLicensesByFilename: vi.fn(async (names) => Object.fromEntries(+ (names || []).map((n) => {+ const sc = loraSidecarState.byFilename[n] || {};+ return [n, {+ license: typeof sc.license === 'string' && sc.license.trim() ? sc.license.trim() : null,+ sourceUrl: sc.sourceUrl || sc.civitai?.url || sc.huggingface?.url || null,+ name: sc.name || null,+ }];+ }),+ )),}));// Adapter-effect gate (#4872). generateVideo opts every render into the probe,@@ -2452,6 +2462,10 @@ describe('generateVideo — LoRA history-record contract (Remix round-trip)', ()// handler consume — parallel arrays, not a `loras: [{filename,scale}]` blob.expect(startedMeta.loraFilenames).toEqual(['a.safetensors', 'b.safetensors']);expect(startedMeta.loraScales).toEqual([0.7, 1.0]);+ expect(startedMeta.provenance.sources.map((s) => s.id)).toEqual([+ 'ltx2_unified', 'a.safetensors', 'b.safetensors',+ ]);+ expect(startedMeta.provenance.sources.every((s) => s.license == null)).toBe(true);expect(startedMeta.loras).toBeUndefined();});});diff --git a/server/services/videoGen/remote.js b/server/services/videoGen/remote.jsindex 99bc56063a..5918a8b0f1 100644--- a/server/services/videoGen/remote.js+++ b/server/services/videoGen/remote.js@@ -26,6 +26,9 @@ import { applyRemoteInputAssets, remoteInputAssetsSchema } from '../federatedMedimport { videoGenEvents } from './events.js';import { mutateVideoHistory } from './history.js';import { renderTimingFields } from '../../lib/renderTiming.js';+import { provenanceForRender } from '../../lib/assetProvenance.js';+import { readLoraLicensesByFilename } from '../loras.js';+import { getVideoModels } from '../../lib/mediaModels.js';const remoteVideoMarkerSchema = z.object({wireVersion: z.literal(FEDERATED_MEDIA_WIRE_VERSION),@@ -69,12 +72,17 @@ const executor = createRemoteMediaExecutor({// missing thumbnail must not fail a render that already landed verified.await optimizeForStreaming(path);const thumbnail = await generateThumbnail(path, jobId);+ const createdAt = new Date().toISOString();+ const modelId = remoteJob.result.modelId ?? request.modelId;+ const model = getVideoModels().find((m) => m.id === modelId);+ const loraFilenames = Array.isArray(request.loraFilenames) ? request.loraFilenames : [];+ const loraLicenses = await readLoraLicensesByFilename(loraFilenames);await mutateVideoHistory((history) => {history.unshift({id: jobId,prompt: request.prompt,negativePrompt: request.negativePrompt ?? '',- modelId: remoteJob.result.modelId ?? request.modelId,+ modelId,seed: request.seed ?? null,width: request.width ?? null,height: request.height ?? null,@@ -88,7 +96,21 @@ const executor = createRemoteMediaExecutor({// the federation, never a hostname, address, or credential.federatedPeerId: peerId,federatedJobId: remoteJob.id,- createdAt: new Date().toISOString(),+ createdAt,+ provenance: provenanceForRender({+ model: {+ id: modelId,+ name: model?.name || modelId,+ license: model?.license,+ repo: model?.repo,+ disclosure: model?.disclosure,+ },+ loras: loraFilenames.map((filename) => ({+ filename,+ ...(loraLicenses[filename] || {}),+ })),+ capturedAt: createdAt,+ }),...renderTimingFields(renderStartedAtMs),});return history;