diff --git a/apps/editor/src/ui/editor/EditorCanvas.tsx b/apps/editor/src/ui/editor/EditorCanvas.tsx index a3f2ae6..3940bc0 100644 --- a/apps/editor/src/ui/editor/EditorCanvas.tsx +++ b/apps/editor/src/ui/editor/EditorCanvas.tsx @@ -1789,8 +1789,6 @@ export default function EditorCanvas({ onBack, onSaveToServer, onPlanAlignmentSt adoptionStatus: loadedFramework?.metadata?.adoptionStatus, readOnly, publicAccess: loadedFramework?.metadata?.publicAccess === true, - sourcePackageURI: mirrorStatus?.sourcePackageURI, - isModifiedFromSource: mirrorStatus?.isModifiedFromSource, }} userName={userName ?? undefined} tenantId={tenantId ?? undefined} diff --git a/apps/editor/src/ui/editor/components/CanvasHeader.test.tsx b/apps/editor/src/ui/editor/components/CanvasHeader.test.tsx index 88c0c35..6b8f0e2 100644 --- a/apps/editor/src/ui/editor/components/CanvasHeader.test.tsx +++ b/apps/editor/src/ui/editor/components/CanvasHeader.test.tsx @@ -9,14 +9,15 @@ describe('CanvasHeader', () => { , ) expect(screen.getByText('Skills-First Product Managers Skill Taxonomy')).toBeInTheDocument() expect(screen.getByText('Competency')).toBeInTheDocument() expect(screen.getByText('Derived')).toBeInTheDocument() expect(screen.getByText('Public')).toBeInTheDocument() - expect(screen.getByText('Mirrored')).toBeInTheDocument() + expect(screen.queryByText('Mirrored')).not.toBeInTheDocument() + expect(screen.queryByText('Forked')).not.toBeInTheDocument() }) it('shows no labels when none are given', () => { diff --git a/apps/editor/src/ui/home/HomeScreen.tsx b/apps/editor/src/ui/home/HomeScreen.tsx index a43b18f..3ed8c0a 100644 --- a/apps/editor/src/ui/home/HomeScreen.tsx +++ b/apps/editor/src/ui/home/HomeScreen.tsx @@ -835,8 +835,6 @@ export default function HomeScreen({ frameworkType: doc.frameworkType, adoptionStatus: doc.adoptionStatus, }} - sourcePackageURI={doc.extensions?.['ext:opencase']?.sourcePackageURI} - isModifiedFromSource={doc.extensions?.['ext:opencase']?.isModifiedFromSource} readOnly={doc.readOnly === true} publicAccess={doc.extensions?.['ext:opencase']?.publicAccess === true} rightHint={isArchiving ? 'Archiving' : hint} @@ -902,8 +900,6 @@ export default function HomeScreen({ frameworkType: doc.frameworkType, adoptionStatus: doc.adoptionStatus, }} - sourcePackageURI={doc.extensions?.['ext:opencase']?.sourcePackageURI} - isModifiedFromSource={doc.extensions?.['ext:opencase']?.isModifiedFromSource} readOnly publicAccess={doc.extensions?.['ext:opencase']?.publicAccess === true} rightHint={isArchiving ? 'Archiving' : hint} @@ -955,8 +951,6 @@ export default function HomeScreen({ frameworkType: doc.frameworkType, adoptionStatus: doc.adoptionStatus, }} - sourcePackageURI={doc.extensions?.['ext:opencase']?.sourcePackageURI} - isModifiedFromSource={doc.extensions?.['ext:opencase']?.isModifiedFromSource} readOnly={doc.readOnly === true} publicAccess={doc.extensions?.['ext:opencase']?.publicAccess === true} rightHint={isDeleting ? 'Deleting' : (isRestoring ? 'Restoring' : undefined)} diff --git a/apps/editor/src/ui/shared/components/FrameworkCard.tsx b/apps/editor/src/ui/shared/components/FrameworkCard.tsx index c1a0aa6..e201687 100644 --- a/apps/editor/src/ui/shared/components/FrameworkCard.tsx +++ b/apps/editor/src/ui/shared/components/FrameworkCard.tsx @@ -40,10 +40,6 @@ type Props = { children?: ReactNode /** ISO date string for the last change — shown in the card footer */ lastChanged?: string - /** URL the framework was imported from, if known — shown in the Mirrored/Forked badge tooltip */ - sourcePackageURI?: string - /** Set (true or false) once a framework has been imported/mirrored; true once it's been locally modified (forked) */ - isModifiedFromSource?: boolean /** Read-only cached remote framework (CGE cache) */ readOnly?: boolean /** CASE API readable without signing in */ @@ -66,8 +62,6 @@ export function FrameworkCard({ className, children, lastChanged, - sourcePackageURI, - isModifiedFromSource, readOnly, publicAccess, }: Readonly) { @@ -178,8 +172,6 @@ export function FrameworkCard({ adoptionStatus={adoptionStatus} readOnly={readOnly} publicAccess={publicAccess} - sourcePackageURI={sourcePackageURI} - isModifiedFromSource={isModifiedFromSource} /> {relDate ? ( diff --git a/apps/editor/src/ui/shared/components/FrameworkLabels.test.tsx b/apps/editor/src/ui/shared/components/FrameworkLabels.test.tsx index 6f9080f..d7c332f 100644 --- a/apps/editor/src/ui/shared/components/FrameworkLabels.test.tsx +++ b/apps/editor/src/ui/shared/components/FrameworkLabels.test.tsx @@ -46,19 +46,16 @@ describe('FrameworkLabels', () => { expect(screen.getByText('Public')).toHaveAttribute('title', 'Anyone can read this framework without signing in') }) - it('shows Mirrored for an unmodified import, with the source in the tooltip', () => { - render() - expect(screen.getByText('Mirrored')).toHaveAttribute('title', 'Mirrored from https://example.org/pkg') - }) - - it('shows Forked for a locally modified import', () => { - render() - expect(screen.getByText('Forked')).toHaveAttribute('title', 'Forked — originally mirrored, now locally modified') - }) + it.each([false, true, undefined])('does not show import status when isModifiedFromSource is %s', (isModifiedFromSource) => { + const provenance = { isModifiedFromSource, sourcePackageURI: 'https://example.org/pkg' } + const { container } = render() - it('shows no mirror badge for a framework that was never imported', () => { - render() expect(screen.queryByText('Mirrored')).not.toBeInTheDocument() expect(screen.queryByText('Forked')).not.toBeInTheDocument() + expect(screen.queryByTitle(/mirrored|forked/i)).not.toBeInTheDocument() + expect(container.querySelector('svg')).not.toBeInTheDocument() + expect(screen.getByText('Draft')).toBeInTheDocument() + expect(screen.getByText('Read-only')).toBeInTheDocument() + expect(screen.getByText('Public')).toBeInTheDocument() }) }) diff --git a/apps/editor/src/ui/shared/components/FrameworkLabels.tsx b/apps/editor/src/ui/shared/components/FrameworkLabels.tsx index c590773..3b39464 100644 --- a/apps/editor/src/ui/shared/components/FrameworkLabels.tsx +++ b/apps/editor/src/ui/shared/components/FrameworkLabels.tsx @@ -1,4 +1,3 @@ -import { CloudArrowDownIcon } from '@heroicons/react/24/solid' import { cn } from '@/lib/utils' import { normalizeAdoptionStatus } from '@/domain/framework/model/adoptionStatus' @@ -33,23 +32,17 @@ type Props = { readOnly?: boolean /** CASE API readable without signing in */ publicAccess?: boolean - /** URL the framework was imported from, if known — shown in the Mirrored/Forked badge tooltip */ - sourcePackageURI?: string - /** Set (true or false) once a framework has been imported/mirrored; true once it's been locally modified (forked) */ - isModifiedFromSource?: boolean className?: string } /** - * Framework status badges (adoption status, Read-only, Public, Mirrored/Forked), + * Framework status badges (adoption status, Read-only, Public), * shared by the home screen's framework cards and the editor header. */ export function FrameworkLabels({ adoptionStatus, readOnly, publicAccess, - sourcePackageURI, - isModifiedFromSource, className, }: Readonly) { const statusInfo = adoptionStatus ? STATUS_STYLE[normalizeAdoptionStatus(adoptionStatus) ?? adoptionStatus] : undefined @@ -77,24 +70,6 @@ export function FrameworkLabels({ Public ) : null} - {isModifiedFromSource !== undefined ? ( - - - {isModifiedFromSource ? 'Forked' : 'Mirrored'} - - ) : null} ) } diff --git a/apps/opencase/src/application/case/endpoints/CreateFramework.ts b/apps/opencase/src/application/case/endpoints/CreateFramework.ts index 558ebb0..b9a4d9a 100644 --- a/apps/opencase/src/application/case/endpoints/CreateFramework.ts +++ b/apps/opencase/src/application/case/endpoints/CreateFramework.ts @@ -175,10 +175,12 @@ export class CreateFramework { const doc = CFDocument.fromRaw(tenantId, caseVersion, docPayload, uriOptions) const dId = doc.sourcedId const dURI = doc.toJSON().uri + const items = itemsPayload.map((i: any) => CFItem.fromRaw(tenantId, caseVersion, i, dId, dURI, uriOptions)) + const localNodeIdentifiers = new Set([dId, ...items.map(i => i.sourcedId)]) return { document: doc, - items: itemsPayload.map((i: any) => CFItem.fromRaw(tenantId, caseVersion, i, dId, dURI, uriOptions)), - associations: assocPayload.map((a: any) => CFAssociation.fromRaw(tenantId, caseVersion, a, { ...uriOptions, documentIdentifiers: [dId] })), + items, + associations: assocPayload.map((a: any) => CFAssociation.fromRaw(tenantId, caseVersion, a, { ...uriOptions, documentIdentifiers: [dId], localNodeIdentifiers })), rubrics: rubricsPayload.map((r: any) => CFRubric.fromRaw(tenantId, caseVersion, r, uriOptions)) } } @@ -304,8 +306,9 @@ export class CreateFramework { const items = cfItemsPayload.map((i: any) => CFItem.fromRaw(tenantId, caseVersion, i, docId, docURI, preserveUris) ) + const localNodeIdentifiers = new Set([docId, ...items.map(i => i.sourcedId)]) const associations = cfAssociationsPayload.map((a: any) => - CFAssociation.fromRaw(tenantId, caseVersion, a, { ...preserveUris, documentIdentifiers: [docId] }) + CFAssociation.fromRaw(tenantId, caseVersion, a, { ...preserveUris, documentIdentifiers: [docId], localNodeIdentifiers }) ) const rubrics = cfRubricsPayload.map((r: any) => CFRubric.fromRaw(tenantId, caseVersion, r, preserveUris) diff --git a/apps/opencase/src/application/case/endpoints/ImportFramework.ts b/apps/opencase/src/application/case/endpoints/ImportFramework.ts index c8b7a81..b46f5e0 100644 --- a/apps/opencase/src/application/case/endpoints/ImportFramework.ts +++ b/apps/opencase/src/application/case/endpoints/ImportFramework.ts @@ -12,6 +12,7 @@ import { CFPackage } from '../../../domain/case/entities/CFPackage' import { logger } from '../../../infrastructure/logging/Logger' import { OPENCASE_EXT_KEY, stripOpenCaseExtensions } from '../services/openCaseExtensions' import { deriveSourcePackageURI } from '../services/packageUri' +import { mintForkedIdentifiers } from '../services/mirrorFork' import { coerceMistypedStrings } from '../services/coerceMistypedStrings' import type { ImportDocumentFlags } from '../types/ImportDocumentFlags' @@ -36,11 +37,8 @@ export interface ImportFrameworkResult { } /** - * Create the `ext:opencase` extension on a CFDocument payload, marking it as a - * pristine mirror of the source. The payload must already have had any incoming - * `ext:opencase` discarded (see execute) — OpenCASE's own state is never taken - * from an import source. `endpointUrl` is the import URL, or for pasted JSON - * whatever source could be derived from the document (may be unknown). + * Record source provenance after incoming OpenCASE state has been removed. + * Editable imports get local identities. Read-only caches keep source identities. */ function injectSourceProvenance ( docPayload: any, @@ -54,7 +52,7 @@ function injectSourceProvenance ( // can't be derived has none, so the field is left off entirely rather // than written as undefined. ...(endpointUrl ? { sourcePackageURI: endpointUrl } : {}), - isModifiedFromSource: false, + isModifiedFromSource: documentFlags?.readOnly !== true, importedAt: new Date().toISOString(), // An imported CFPackage carries its associations to other frameworks inline, // and there is no way to import alignment frameworks. @@ -121,7 +119,7 @@ export class ImportFramework { } // Use CFPackage format directly (matches API response format) - const payload = { + let payload = { CFDocument: sourceCFPackage.CFDocument, CFItems: sourceCFPackage.CFItems ?? [], CFAssociations: sourceCFPackage.CFAssociations ?? [], @@ -130,10 +128,7 @@ export class ImportFramework { extensions: sourceCFPackage.extensions } - // Saves are strictly validated against the CFPackage schema, so numbers the - // publisher sent where a string belongs are turned into strings now — otherwise - // the framework imports fine but can never be saved (CGE-183). This is a type - // correction of the source's own values, so the import is still a pristine mirror. + // Convert numeric values to strings where the save schema requires strings. const packageSchemaName = caseVersion === '1.1' ? 'case-v1p1-cfpackage' : 'case-v1p0-cfpackage' const coercedPaths = coerceMistypedStrings(this.validator, packageSchemaName, payload) if (coercedPaths.length > 0) { @@ -155,9 +150,13 @@ export class ImportFramework { } } - // Create domain entities from CFPackage format. Mirrored imports preserve the - // source's identifiers/URIs as-is rather than rewriting them onto this instance — - // they're only regenerated once the framework is edited and forked (a later task). + // Keep publisher identities for read-only remote references and cache refreshes. + if (documentFlags?.readOnly !== true) { + const { bundle } = mintForkedIdentifiers(payload, tenantId, caseVersion) + payload = { ...payload, ...bundle } + } + + // Local identities are already set. Cache identities must stay unchanged. const preserveUris = { preserveUris: true } const document = CFDocument.fromRaw(tenantId, caseVersion, payload.CFDocument, preserveUris) const docId = document.sourcedId diff --git a/apps/opencase/src/application/case/endpoints/UpdateCFAssociation.ts b/apps/opencase/src/application/case/endpoints/UpdateCFAssociation.ts index 0a82903..b5402cc 100644 --- a/apps/opencase/src/application/case/endpoints/UpdateCFAssociation.ts +++ b/apps/opencase/src/application/case/endpoints/UpdateCFAssociation.ts @@ -55,7 +55,8 @@ export class UpdateCFAssociation { // Update the specific association const updatedAssociation = CFAssociation.fromRaw(tenantId, caseVersion, payload, { - documentIdentifiers: [existingPkg.document.sourcedId] + documentIdentifiers: [existingPkg.document.sourcedId], + localNodeIdentifiers: new Set([existingPkg.document.sourcedId, ...existingPkg.items.map(i => i.sourcedId)]) }) // Replace the association in the associations array diff --git a/apps/opencase/src/application/case/endpoints/__tests__/ImportFramework.localCopy.test.ts b/apps/opencase/src/application/case/endpoints/__tests__/ImportFramework.localCopy.test.ts new file mode 100644 index 0000000..9d778e7 --- /dev/null +++ b/apps/opencase/src/application/case/endpoints/__tests__/ImportFramework.localCopy.test.ts @@ -0,0 +1,268 @@ +import fs from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import { ImportFramework } from '../ImportFramework' +import { CreateFramework } from '../CreateFramework' +import { UpdateCFAssociation } from '../UpdateCFAssociation' +import { GetCFPackage } from '../GetCFPackage' +import { GetCFDocument } from '../GetCFDocument' +import { FileFrameworkStore } from '../../../../infrastructure/persistence/file/FileFrameworkStore' +import { FileCFPackageRepository } from '../../../../infrastructure/persistence/file/FileCFPackageRepository' +import type { CaseApiClient } from '../../../../infrastructure/http/CaseApiClient' +import type { CaseVersion } from '../../../../domain/case/value-objects/Identifiers' + +// Imports are independent local copies from the start: new identifiers and local +// URIs for everything the framework owns, with its internal references intact. +describe.each(['1.0', '1.1'] as CaseVersion[])('ImportFramework — local copy on import (CASE %s)', (caseVersion) => { + const tenantId = 'test-tenant' + const v = caseVersion === '1.1' ? 'v1p1' : 'v1p0' + const source = `https://source.example.org/ims/case/${v}` + const sourcePackageUrl = `${source}/CFPackages/src-doc` + const externalItem = { identifier: 'other-fw-item', uri: 'https://other.example.org/ims/case/v1p1/CFItems/other-fw-item', title: 'Elsewhere' } + const sourceIds = ['src-doc', 'item-a', 'item-b', 'item-c', 'assoc-1', 'assoc-2', 'assoc-3', 'assoc-4', 'rubric-1', 'crit-1', 'level-1'] + + const sourcePackage = () => ({ + CFDocument: { + identifier: 'src-doc', + uri: `${source}/CFDocuments/src-doc`, + CFPackageURI: { identifier: 'src-doc', uri: sourcePackageUrl, title: 'Source' }, + title: 'Source Framework', + creator: 'Source Org', + lastChangeDateTime: '2024-01-01T00:00:00+00:00', + licenseURI: { identifier: 'lic-1', uri: `${source}/CFLicenses/lic-1`, title: 'License' }, + // Incoming OpenCASE state is never trusted. + extensions: { 'ext:opencase': { publicAccess: true, isModifiedFromSource: false } } + }, + CFItems: [ + { identifier: 'item-a', uri: `${source}/CFItems/item-a`, fullStatement: 'A', lastChangeDateTime: '2024-01-01T00:00:00+00:00', + CFItemTypeURI: { identifier: 'type-1', uri: `${source}/CFItemTypes/type-1`, title: 'Standard' } }, + { identifier: 'item-b', uri: `${source}/CFItems/item-b`, fullStatement: 'B', lastChangeDateTime: '2024-01-01T00:00:00+00:00' }, + { identifier: 'item-c', uri: `${source}/CFItems/item-c`, fullStatement: 'C (nested under B)', lastChangeDateTime: '2024-01-01T00:00:00+00:00' } + ], + CFAssociations: [ + { identifier: 'assoc-1', uri: `${source}/CFAssociations/assoc-1`, associationType: 'isChildOf', lastChangeDateTime: '2024-01-01T00:00:00+00:00', + originNodeURI: { identifier: 'item-a', uri: `${source}/CFItems/item-a`, title: 'A' }, + destinationNodeURI: { identifier: 'src-doc', uri: `${source}/CFDocuments/src-doc`, title: 'Source Framework' } }, + { identifier: 'assoc-2', uri: `${source}/CFAssociations/assoc-2`, associationType: 'isChildOf', lastChangeDateTime: '2024-01-01T00:00:00+00:00', + originNodeURI: { identifier: 'item-b', uri: `${source}/CFItems/item-b`, title: 'B' }, + destinationNodeURI: { identifier: 'item-a', uri: `${source}/CFItems/item-a`, title: 'A' } }, + { identifier: 'assoc-3', uri: `${source}/CFAssociations/assoc-3`, associationType: 'isChildOf', lastChangeDateTime: '2024-01-01T00:00:00+00:00', + originNodeURI: { identifier: 'item-c', uri: `${source}/CFItems/item-c`, title: 'C' }, + destinationNodeURI: { identifier: 'item-b', uri: `${source}/CFItems/item-b`, title: 'B' } }, + { identifier: 'assoc-4', uri: `${source}/CFAssociations/assoc-4`, associationType: 'exactMatchOf', lastChangeDateTime: '2024-01-01T00:00:00+00:00', + originNodeURI: { identifier: 'item-a', uri: `${source}/CFItems/item-a`, title: 'A' }, + destinationNodeURI: externalItem } + ], + CFRubrics: [{ + identifier: 'rubric-1', uri: `${source}/CFRubrics/rubric-1`, title: 'Rubric', lastChangeDateTime: '2024-01-01T00:00:00+00:00', + CFRubricCriteria: [{ + identifier: 'crit-1', uri: `${source}/CFRubricCriteria/crit-1`, rubricId: 'rubric-1', lastChangeDateTime: '2024-01-01T00:00:00+00:00', + CFItemURI: { identifier: 'item-a', uri: `${source}/CFItems/item-a`, title: 'A' }, + CFRubricCriterionLevels: [{ + identifier: 'level-1', uri: `${source}/CFRubricCriterionLevels/level-1`, rubricCriterionId: 'crit-1', lastChangeDateTime: '2024-01-01T00:00:00+00:00' + }] + }] + }], + CFDefinitions: { + CFLicenses: [{ identifier: 'lic-1', uri: `${source}/CFLicenses/lic-1`, title: 'License', licenseText: 'Text', lastChangeDateTime: '2024-01-01T00:00:00+00:00' }], + CFItemTypes: [{ identifier: 'type-1', uri: `${source}/CFItemTypes/type-1`, title: 'Standard', description: 'Standard', hierarchyCode: '1', lastChangeDateTime: '2024-01-01T00:00:00+00:00' }] + } + }) + + let baseDataDir: string + let store: FileFrameworkStore + let importFramework: ImportFramework + let createFramework: CreateFramework + let getPackage: GetCFPackage + let getDocument: GetCFDocument + let apiClient: jest.Mocked + + beforeEach(async () => { + baseDataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'case-import-local-copy-')) + store = new FileFrameworkStore({ baseDataDir }) + await store.loadAll() + const repo = new FileCFPackageRepository(store) + apiClient = { fetchCFPackage: jest.fn().mockImplementation(async () => ({ CFPackage: sourcePackage() })) } as any + importFramework = new ImportFramework(repo, apiClient) + createFramework = new CreateFramework(repo, undefined, store) + getPackage = new GetCFPackage(repo, store) + getDocument = new GetCFDocument(repo, store) + }) + + afterEach(async () => { + await fs.rm(baseDataDir, { recursive: true, force: true }) + }) + + const importByUrl = () => importFramework.execute({ tenantId, caseVersion, endpointUrl: sourcePackageUrl }) + const importJson = () => importFramework.execute({ tenantId, caseVersion, cfPackage: sourcePackage() }) + const read = async (docId: string) => { + const pkg = await getPackage.execute({ tenantId, caseVersion, docId }) + if (!pkg) throw new Error(`No package for ${docId}`) + return pkg + } + const ownedIds = (pkg: any): string[] => [ + pkg.CFDocument.identifier, + ...pkg.CFItems.map((i: any) => i.identifier), + ...pkg.CFAssociations.map((a: any) => a.identifier), + ...(pkg.CFRubrics ?? []).flatMap((r: any) => [ + r.identifier, + ...(r.CFRubricCriteria ?? []).flatMap((c: any) => [c.identifier, ...(c.CFRubricCriterionLevels ?? []).map((l: any) => l.identifier)]) + ]) + ] + const itemByStatement = (pkg: any, statement: string) => pkg.CFItems.find((i: any) => i.fullStatement === statement) + + it.each([['URL', importByUrl], ['JSON', importJson]])('gives a %s import new identifiers and local URIs with internal references intact', async (_kind, runImport) => { + const { docId } = await runImport() + const pkg = await read(docId) + + expect(pkg.CFDocument.identifier).toBe(docId) + const ids = ownedIds(pkg) + expect(ids).toHaveLength(sourceIds.length) + expect(new Set(ids).size).toBe(ids.length) + for (const id of ids) expect(sourceIds).not.toContain(id) + + const local = `/ims/case/${v}` + expect(pkg.CFDocument.uri).toBe(`${local}/CFDocuments/${docId}`) + for (const item of pkg.CFItems) expect(item.uri).toBe(`${local}/CFItems/${item.identifier}`) + for (const assoc of pkg.CFAssociations) expect(assoc.uri).toBe(`${local}/CFAssociations/${assoc.identifier}`) + const rubric = pkg.CFRubrics[0] + expect(rubric.uri).toBe(`${local}/CFRubrics/${rubric.identifier}`) + for (const owned of ['CFDocuments', 'CFItems', 'CFAssociations', 'CFRubrics', 'CFRubricCriteria', 'CFRubricCriterionLevels']) { + expect(JSON.stringify(pkg)).not.toContain(`${source}/${owned}/`) + } + + // Hierarchy and associations point at the copy's own nodes. + const [a, b, c] = ['A', 'B', 'C (nested under B)'].map(s => itemByStatement(pkg, s)) + const assoc = (originId: string, type: string) => + pkg.CFAssociations.find((x: any) => x.originNodeURI.identifier === originId && x.associationType === type) + expect(assoc(a.identifier, 'isChildOf').destinationNodeURI).toMatchObject({ identifier: docId, uri: `${local}/CFDocuments/${docId}` }) + expect(assoc(b.identifier, 'isChildOf').destinationNodeURI).toMatchObject({ identifier: a.identifier, uri: a.uri }) + expect(assoc(c.identifier, 'isChildOf').destinationNodeURI).toMatchObject({ identifier: b.identifier, uri: b.uri }) + + // Keep the full reference to the other publisher. + expect(assoc(a.identifier, 'exactMatchOf').destinationNodeURI).toEqual(externalItem) + + // Rubric children get new identities and follow the item they assess. + const criterion = rubric.CFRubricCriteria[0] + expect(criterion.CFItemURI.identifier).toBe(a.identifier) + expect(criterion.CFRubricCriterionLevels[0].identifier).not.toBe('level-1') + + // Shared definitions keep their identifiers. + expect(a.CFItemTypeURI.identifier).toBe('type-1') + expect(pkg.CFDocument.licenseURI.identifier).toBe('lic-1') + }) + + it('serves the copy through local endpoints, with a local CFPackageURI and the source kept as provenance', async () => { + const { docId } = await importByUrl() + const doc = await getDocument.execute({ tenantId, caseVersion, sourcedId: docId }) + + expect(doc?.CFPackageURI).toMatchObject({ identifier: docId, uri: `/ims/case/${v}/CFPackages/${docId}` }) + // CASE 1.0 documents carry no extensions, so there is nowhere to keep provenance. + if (caseVersion === '1.0') return + const opencase = doc?.extensions?.['ext:opencase'] + expect(opencase?.sourcePackageURI).toBe(sourcePackageUrl) + expect(opencase).not.toHaveProperty('publicAccess') + }) + + it('keeps the copy\'s identifiers when it is edited and saved', async () => { + const { docId } = await importJson() + const before = await read(docId) + + const edited = JSON.parse(JSON.stringify(before)) + itemByStatement(edited, 'B').fullStatement = 'B, edited' + const saved = await createFramework.execute({ tenantId, caseVersion, payload: edited }) + + expect(saved.status).toBe('published') + expect(saved).not.toHaveProperty('forked', true) + expect(saved.docId).toBe(docId) + const after = await read(docId) + expect(ownedIds(after).sort()).toEqual(ownedIds(before).sort()) + expect(itemByStatement(after, 'B, edited').identifier).toBe(itemByStatement(before, 'B').identifier) + expect(after.CFAssociations.find((a: any) => a.associationType === 'exactMatchOf').destinationNodeURI).toEqual(externalItem) + }) + + it('keeps external item and document links through edits and a server restart', async () => { + const pkg = sourcePackage() + const externalDocument = { identifier: 'other-doc', uri: 'https://other.example.org/ims/case/v1p1/CFDocuments/other-doc', title: 'Other document' } + pkg.CFAssociations[3].originNodeURI = externalDocument + const { docId } = await importFramework.execute({ tenantId, caseVersion, cfPackage: pkg }) + const before = await read(docId) + const checkLinks = (saved: any) => { + const association = saved.CFAssociations.find((a: any) => a.associationType === 'exactMatchOf') + expect(association.originNodeURI).toEqual(externalDocument) + expect(association.destinationNodeURI).toEqual(externalItem) + } + checkLinks(before) + itemByStatement(before, 'B').fullStatement = 'Edited' + await createFramework.execute({ tenantId, caseVersion, payload: before }) + checkLinks(await read(docId)) + + const restartedStore = new FileFrameworkStore({ baseDataDir }) + await restartedStore.loadAll() + const restartedGet = new GetCFPackage(new FileCFPackageRepository(restartedStore), restartedStore) + checkLinks(await restartedGet.execute({ tenantId, caseVersion, docId })) + }) + + it('keeps external links when an association is updated directly', async () => { + const { docId } = await importJson() + const pkg = await read(docId) + const association = pkg.CFAssociations.find((a: any) => a.associationType === 'exactMatchOf') + const update = new UpdateCFAssociation(new FileCFPackageRepository(store), store) + await update.execute({ tenantId, caseVersion, sourcedId: association.identifier, payload: { ...association, sequenceNumber: 2 } }) + + const saved = (await read(docId)).CFAssociations.find((a: any) => a.identifier === association.identifier) + expect(saved.destinationNodeURI).toEqual(externalItem) + expect(saved.originNodeURI).toEqual(association.originNodeURI) + expect(saved.sequenceNumber).toBe(2) + }) + + it('creates a separate copy each time the same source is imported', async () => { + const first = await importByUrl() + const firstPkg = await read(first.docId) + const second = await importByUrl() + const secondPkg = await read(second.docId) + + expect(second.docId).not.toBe(first.docId) + const firstIds = new Set(ownedIds(firstPkg)) + for (const id of ownedIds(secondPkg)) expect(firstIds.has(id)).toBe(false) + expect(await read(first.docId)).toEqual(firstPkg) + }) + + it.each(['URL', 'URN', 'string'])('remaps a rubric item link with only a %s', async (kind) => { + const pkg = sourcePackage() + const uri = kind === 'URN' ? 'urn:case:item:item-a' : `${source}/CFItems/item-a` + pkg.CFRubrics[0].CFRubricCriteria[0].CFItemURI = (kind === 'string' ? uri : { uri, title: 'A' }) as any + const { docId } = await importFramework.execute({ tenantId, caseVersion, cfPackage: pkg }) + + const imported = await read(docId) + const item = itemByStatement(imported, 'A') + const criterion = imported.CFRubrics[0].CFRubricCriteria[0] + expect(criterion.identifier).not.toBe('crit-1') + expect(criterion.CFItemURI).toEqual({ identifier: item.identifier, uri: item.uri, title: expect.any(String) }) + if (kind !== 'string') expect(criterion.CFItemURI.title).toBe('A') + + item.fullStatement = 'A, edited' + await createFramework.execute({ tenantId, caseVersion, payload: imported }) + expect((await read(docId)).CFRubrics[0].CFRubricCriteria[0].CFItemURI).toEqual(criterion.CFItemURI) + }) + + it('keeps an unknown rubric item URL instead of guessing from its last path segment', async () => { + const pkg = sourcePackage() + const link = { title: 'External', uri: 'https://other.example.org/ims/case/v1p1/CFItems/item-a' } + pkg.CFRubrics[0].CFRubricCriteria[0].CFItemURI = link as any + const { docId } = await importFramework.execute({ tenantId, caseVersion, cfPackage: pkg }) + + expect((await read(docId)).CFRubrics[0].CFRubricCriteria[0].CFItemURI).toEqual(link) + }) + + it('keeps publisher identities for a read-only cache', async () => { + const { docId } = await importFramework.execute({ + tenantId, caseVersion, endpointUrl: sourcePackageUrl, documentFlags: { readOnly: true, cgeFrameworkId: 'cge-1' } + }) + expect(docId).toBe('src-doc') + // CASE 1.0 documents carry no extensions, so a 1.0 cache has no stored source to point at. + if (caseVersion === '1.0') return + const doc = await getDocument.execute({ tenantId, caseVersion, sourcedId: docId }) + expect(doc?.CFPackageURI?.uri).toBe(sourcePackageUrl) + }) +}) diff --git a/apps/opencase/src/application/case/endpoints/__tests__/ImportFramework.test.ts b/apps/opencase/src/application/case/endpoints/__tests__/ImportFramework.test.ts index d65611d..0987585 100644 --- a/apps/opencase/src/application/case/endpoints/__tests__/ImportFramework.test.ts +++ b/apps/opencase/src/application/case/endpoints/__tests__/ImportFramework.test.ts @@ -54,7 +54,8 @@ describe('ImportFramework', () => { endpointUrl: 'https://example.org/ims/case/v1p1/CFPackages/doc-123' }) - expect(result.docId).toBe('doc-123') + expect(result.docId).not.toBe('doc-123') + expect(result.docId).toBe(mockRepository.saveNewVersion.mock.calls[0][2].document.sourcedId) expect(mockApiClient.fetchCFPackage).toHaveBeenCalledWith( 'https://example.org/ims/case/v1p1/CFPackages/doc-123', undefined @@ -92,7 +93,7 @@ describe('ImportFramework', () => { } }) - expect(result.docId).toBe('doc-123') + expect(result.docId).not.toBe('doc-123') expect(mockApiClient.fetchCFPackage).not.toHaveBeenCalled() expect(mockRepository.saveNewVersion).toHaveBeenCalledTimes(1) }) @@ -104,7 +105,7 @@ describe('ImportFramework', () => { cfPackage: { CFDocument: cfDocument, CFItems: [], CFAssociations: [], CFRubrics: [] } }) - expect(result.docId).toBe('doc-123') + expect(result.docId).not.toBe('doc-123') expect(mockRepository.saveNewVersion).toHaveBeenCalledTimes(1) }) @@ -120,10 +121,10 @@ describe('ImportFramework', () => { const savedPkg = mockRepository.saveNewVersion.mock.calls[0][2] const savedExtensions = savedPkg.document.toJSON().extensions expect(savedExtensions['ext:opencase'].sourcePackageURI).toBe('https://source.example.org/ims/case/v1p1/CFPackages/doc-123') - expect(savedExtensions['ext:opencase'].isModifiedFromSource).toBe(false) + expect(savedExtensions['ext:opencase'].isModifiedFromSource).toBe(true) }) - it('marks pasted JSON as a pristine mirror without a sourcePackageURI (no known source URL)', async () => { + it('creates a local copy of pasted JSON without a sourcePackageURI when the source is unknown', async () => { await importFramework.execute({ tenantId, caseVersion, @@ -133,7 +134,7 @@ describe('ImportFramework', () => { const savedPkg = mockRepository.saveNewVersion.mock.calls[0][2] const savedExtensions = savedPkg.document.toJSON().extensions expect(savedExtensions?.['ext:opencase']?.sourcePackageURI).toBeUndefined() - expect(savedExtensions?.['ext:opencase']?.isModifiedFromSource).toBe(false) + expect(savedExtensions?.['ext:opencase']?.isModifiedFromSource).toBe(true) }) it('stores associations to other frameworks inline, whatever the source file says', async () => { @@ -149,7 +150,7 @@ describe('ImportFramework', () => { expect(savedPkg.document.toJSON().extensions['ext:opencase'].alignmentStorage).toBe('inline') }) - it('preserves the source uri as-is (does not rewrite it onto this instance) when importing from a URL', async () => { + it('uses a local uri when importing from a URL', async () => { const foreignDocument = { ...cfDocument, uri: 'https://source.example.org/ims/case/v1p1/CFDocuments/doc-123' @@ -165,10 +166,10 @@ describe('ImportFramework', () => { }) const savedPkg = mockRepository.saveNewVersion.mock.calls[0][2] - expect(savedPkg.document.toJSON().uri).toBe('https://source.example.org/ims/case/v1p1/CFDocuments/doc-123') + expect(savedPkg.document.toJSON().uri).toBe(`/ims/case/v1p1/CFDocuments/${savedPkg.document.sourcedId}`) }) - it('preserves the source uri as-is when importing from pasted JSON', async () => { + it('uses a local uri when importing from pasted JSON', async () => { const foreignDocument = { ...cfDocument, uri: 'https://source.example.org/ims/case/v1p1/CFDocuments/doc-123' @@ -181,7 +182,7 @@ describe('ImportFramework', () => { }) const savedPkg = mockRepository.saveNewVersion.mock.calls[0][2] - expect(savedPkg.document.toJSON().uri).toBe('https://source.example.org/ims/case/v1p1/CFDocuments/doc-123') + expect(savedPkg.document.toJSON().uri).toBe(`/ims/case/v1p1/CFDocuments/${savedPkg.document.sourcedId}`) }) it('accepts a package with extra/unknown fields and does not save them (CGE-59)', async () => { @@ -287,7 +288,7 @@ describe('ImportFramework', () => { lastChangeDateTime: '2024-01-01T00:00:00+00:00' }) - it('saves numeric hierarchyCodes as strings and still treats the import as a pristine mirror', async () => { + it('saves numeric hierarchyCodes as strings in the local copy', async () => { importFramework = new ImportFramework(mockRepository, mockApiClient, realValidator()) await importFramework.execute({ @@ -301,7 +302,7 @@ describe('ImportFramework', () => { const savedPkg = mockRepository.saveNewVersion.mock.calls[0][2] expect(savedPkg.definitions?.CFItemTypes?.map((t: any) => t.hierarchyCode)).toEqual(['1', '2', '3']) - expect(savedPkg.document.toJSON().extensions['ext:opencase'].isModifiedFromSource).toBe(false) + expect(savedPkg.document.toJSON().extensions['ext:opencase'].isModifiedFromSource).toBe(true) }) it('no longer reports the coerced fields as validation warnings', async () => { @@ -351,7 +352,7 @@ describe('ImportFramework', () => { expect(savedPkg.document.toJSON().extensions.sourceSystem).toBe('smartschool') // Only server-injected provenance survives — nothing from the import file. - expect(docOpencase.isModifiedFromSource).toBe(false) + expect(docOpencase.isModifiedFromSource).toBe(true) expect(docOpencase).not.toHaveProperty('publicAccess') expect(docOpencase).not.toHaveProperty('readOnly') diff --git a/apps/opencase/src/application/case/services/mirrorFork.ts b/apps/opencase/src/application/case/services/mirrorFork.ts index d7378bf..e85b838 100644 --- a/apps/opencase/src/application/case/services/mirrorFork.ts +++ b/apps/opencase/src/application/case/services/mirrorFork.ts @@ -1,6 +1,6 @@ import { randomUUID } from 'node:crypto' import type { CaseVersion, TenantId } from '../../../domain/case/value-objects/Identifiers' -import { LinkDataHelper } from '../../../domain/case/value-objects/LinkData' +import { LinkDataHelper, UrnCaseUriHelper } from '../../../domain/case/value-objects/LinkData' export interface RawComparableBundle { CFDocument: any @@ -130,8 +130,15 @@ export function mintForkedIdentifiers ( // Old identifier (item or document) -> newly-minted identifier. const nodeIdMap = new Map() + const sourceItemIdentifiersByUri = new Map() - const oldDocId = (cloned.CFDocument.sourcedId ?? cloned.CFDocument.identifier) as string | undefined + const sourceIdentifier = (entity: any): string | undefined => + entity.identifier || entity.sourcedId || entity.id || + (typeof entity.uri === 'string' && UrnCaseUriHelper.isUrnCaseUri(entity.uri) + ? UrnCaseUriHelper.parseUrnCaseUri(entity.uri)?.identifier + : undefined) + + const oldDocId = sourceIdentifier(cloned.CFDocument) const newDocId = randomUUID() if (oldDocId) nodeIdMap.set(oldDocId, newDocId) @@ -149,9 +156,12 @@ export function mintForkedIdentifiers ( } for (const item of cloned.CFItems ?? []) { - const oldItemId = (item.sourcedId ?? item.identifier) as string | undefined + const oldItemId = sourceIdentifier(item) const newItemId = randomUUID() - if (oldItemId) nodeIdMap.set(oldItemId, newItemId) + if (oldItemId) { + nodeIdMap.set(oldItemId, newItemId) + if (typeof item.uri === 'string') sourceItemIdentifiersByUri.set(item.uri, oldItemId) + } item.sourcedId = newItemId item.identifier = newItemId item.uri = `${base}/CFItems/${newItemId}` @@ -203,6 +213,34 @@ export function mintForkedIdentifiers ( rubric.identifier = newRubricId rubric.sourcedId = newRubricId rubric.uri = `${base}/CFRubrics/${newRubricId}` + + // Embedded children resolve through the local rubric endpoint. + for (const criterion of rubric.CFRubricCriteria ?? rubric.criteria ?? []) { + const newCriterionId = randomUUID() + criterion.identifier = newCriterionId + criterion.uri = `${rubric.uri}#${newCriterionId}` + if ('sourcedId' in criterion) criterion.sourcedId = newCriterionId + if ('id' in criterion) criterion.id = newCriterionId + if ('rubricId' in criterion) criterion.rubricId = newRubricId + // Match URI-only links to declared source items. Do not guess from a URL suffix. + if (criterion.CFItemURI) { + const link = typeof criterion.CFItemURI === 'string' ? { uri: criterion.CFItemURI } : criterion.CFItemURI + const urn = typeof link.uri === 'string' ? UrnCaseUriHelper.parseUrnCaseUri(link.uri) : null + const oldItemId = link.identifier ?? sourceItemIdentifiersByUri.get(link.uri) ?? (urn?.type === 'item' ? urn.identifier : undefined) + if (oldItemId && nodeIdMap.has(oldItemId)) { + criterion.CFItemURI = resolveNode({ ...link, identifier: oldItemId }, 'rubric criterion CFItemURI') + } + } + + for (const level of criterion.CFRubricCriterionLevels ?? []) { + const newLevelId = randomUUID() + level.identifier = newLevelId + level.uri = `${rubric.uri}#${newLevelId}` + if ('sourcedId' in level) level.sourcedId = newLevelId + if ('id' in level) level.id = newLevelId + if ('rubricCriterionId' in level) level.rubricCriterionId = newCriterionId + } + } } return { bundle: cloned, forkedIdentifiers: Object.fromEntries(nodeIdMap) } diff --git a/apps/opencase/src/domain/case/entities/CFAssociation.ts b/apps/opencase/src/domain/case/entities/CFAssociation.ts index 3935fd3..3454d39 100644 --- a/apps/opencase/src/domain/case/entities/CFAssociation.ts +++ b/apps/opencase/src/domain/case/entities/CFAssociation.ts @@ -32,12 +32,14 @@ export class CFAssociation { * @param options.preserveUris keep the source's identifiers and URIs exactly as supplied (mirrored frameworks) * @param options.documentIdentifiers identifiers known to be CFDocuments (e.g. the package's own CFDocument); * association nodes with one of these identifiers get a /CFDocuments/{id} URI + * @param options.localNodeIdentifiers complete set of document and item IDs in this package; + * references outside this set keep their supplied URIs */ static fromRaw( tenantId: TenantId, caseVersion: CaseVersion, raw: any, - options?: { preserveUris?: boolean, documentIdentifiers?: Iterable } + options?: { preserveUris?: boolean, documentIdentifiers?: Iterable, localNodeIdentifiers?: ReadonlySet } ): CFAssociation { // Extract identifier from URN if present (priority over sourcedId/identifier) let identifier = raw.sourcedId || raw.identifier @@ -66,15 +68,10 @@ export class CFAssociation { originNodeURI = raw.originNodeURI destinationNodeURI = raw.destinationNodeURI } else { - // originNodeURI/destinationNodeURI reference a CFItem or a CFDocument, so — - // like CFItem.CFDocumentURI — their uri is always regenerated to point at the - // local host, regardless of what URI shape (URN, absolute foreign-host URL, or - // relative path) the source supplied. Only the identifier, and whether the node - // is a CFDocument or a CFItem, are trusted from the source data. Nodes with a - // non-CASE targetType are kept as supplied (see buildNodeLinkData). + // Rebase owned nodes. Keep external links when package membership is known. const documentIdentifiers = new Set(options?.documentIdentifiers ?? []) - originNodeURI = this.buildNodeLinkData(tenantId, caseVersion, raw.originNodeURI, raw.originNode, documentIdentifiers) - destinationNodeURI = this.buildNodeLinkData(tenantId, caseVersion, raw.destinationNodeURI, raw.destinationNode, documentIdentifiers) + originNodeURI = this.buildNodeLinkData(tenantId, caseVersion, raw.originNodeURI, raw.originNode, documentIdentifiers, options?.localNodeIdentifiers) + destinationNodeURI = this.buildNodeLinkData(tenantId, caseVersion, raw.destinationNodeURI, raw.destinationNode, documentIdentifiers, options?.localNodeIdentifiers) } // CFAssociationGroupingURI references a per-tenant definition entity that @@ -120,7 +117,8 @@ export class CFAssociation { } /** - * Builds the local LinkData for an association node (origin or destination). + * Rebase owned nodes and keep references outside the package. + * Without package membership, use legacy URI rebasing. * The node is treated as a CFDocument when its identifier is a known document * identifier, when the source supplied a `urn:case:document:` URN, or when the * source URI (relative or absolute, any CASE version) points at @@ -131,7 +129,8 @@ export class CFAssociation { caseVersion: CaseVersion, link: any, legacyNodeId: unknown, - documentIdentifiers: Set + documentIdentifiers: Set, + localNodeIdentifiers?: ReadonlySet ): LinkData { // CASE 1.1 lets an association point outside CASE (spec §1.9.3). A node whose // targetType is anything other than 'CASE' is not served by OpenCASE, so it is @@ -160,6 +159,10 @@ export class CFAssociation { isDocument = this.isDocumentUri(uriFromSource, String(id)) } + if (localNodeIdentifiers && !localNodeIdentifiers.has(String(id)) && typeof uriFromSource === 'string' && uriFromSource) { + return { ...link, title: link.title ?? String(id), identifier: link.identifier ?? id, uri: uriFromSource } + } + if (documentIdentifiers.has(String(id))) isDocument = true const result: LinkData = { diff --git a/apps/opencase/src/domain/case/entities/__tests__/CFAssociation.test.ts b/apps/opencase/src/domain/case/entities/__tests__/CFAssociation.test.ts index bb3577c..35e305a 100644 --- a/apps/opencase/src/domain/case/entities/__tests__/CFAssociation.test.ts +++ b/apps/opencase/src/domain/case/entities/__tests__/CFAssociation.test.ts @@ -129,6 +129,26 @@ describe('CFAssociation', () => { expect(json.destinationNodeURI.identifier).toBe('item-2'); }); + it.each([undefined, 'CASE', 'ext:external'])('keeps external links with targetType %s when package membership is known', (targetType) => { + const external = { + title: 'External', identifier: 'external', uri: 'https://other.example.org/ims/case/v1p1/CFItems/external', + ...(targetType ? { targetType } : {}) + }; + const owned = { title: 'Owned', identifier: 'item-1', uri: 'https://source.example.org/ims/case/v1p0/CFItems/item-1' }; + const options = { localNodeIdentifiers: new Set(['doc-1', 'item-1']), documentIdentifiers: ['doc-1'] }; + const forward = CFAssociation.fromRaw(tenantId, caseVersion, { + identifier: 'assoc-1', associationType: 'exactMatchOf', originNodeURI: owned, destinationNodeURI: external + }, options).toJSON(); + expect(forward.originNodeURI.uri).toBe('/ims/case/v1p1/CFItems/item-1'); + expect(forward.destinationNodeURI).toEqual(external); + + const reversed = CFAssociation.fromRaw(tenantId, caseVersion, { + identifier: 'assoc-2', associationType: 'exactMatchOf', originNodeURI: external, destinationNodeURI: owned + }, options).toJSON(); + expect(reversed.originNodeURI).toEqual(external); + expect(reversed.destinationNodeURI.uri).toBe('/ims/case/v1p1/CFItems/item-1'); + }); + describe('node URIs pointing at a CFDocument (#44)', () => { const docId = '11111111-1111-4111-8111-111111111111'; const itemId = '22222222-2222-4222-8222-222222222222'; diff --git a/apps/opencase/src/infrastructure/persistence/file/FileCFPackageRepository.ts b/apps/opencase/src/infrastructure/persistence/file/FileCFPackageRepository.ts index 94874b9..c3546a3 100644 --- a/apps/opencase/src/infrastructure/persistence/file/FileCFPackageRepository.ts +++ b/apps/opencase/src/infrastructure/persistence/file/FileCFPackageRepository.ts @@ -37,8 +37,9 @@ export class FileCFPackageRepository implements CFPackageRepository { const items = (bundle.items ?? []).map((i: unknown) => CFItem.fromRaw(tenantId, version, i, document.sourcedId, docURI, preserveUris) ) + const localNodeIdentifiers = new Set([document.sourcedId, ...items.map(i => i.sourcedId)]) const associations = (bundle.associations ?? []).map((a: unknown) => - CFAssociation.fromRaw(tenantId, version, a, { ...preserveUris, documentIdentifiers: [document.sourcedId] }) + CFAssociation.fromRaw(tenantId, version, a, { ...preserveUris, documentIdentifiers: [document.sourcedId], localNodeIdentifiers }) ) const rubrics = (bundle.rubrics ?? []).map((r: unknown) => CFRubric.fromRaw(tenantId, version, r, preserveUris) diff --git a/apps/opencase/src/interfaces/http/http-management/controllers/CgeManagementController.ts b/apps/opencase/src/interfaces/http/http-management/controllers/CgeManagementController.ts index c4ed3fc..e145df3 100644 --- a/apps/opencase/src/interfaces/http/http-management/controllers/CgeManagementController.ts +++ b/apps/opencase/src/interfaces/http/http-management/controllers/CgeManagementController.ts @@ -257,6 +257,7 @@ export class CgeManagementController { tenantId, caseVersion, cfPackage, + sourcePackageUri: endpointUrl, validateSchema: req.body?.validateSchema ?? false // No documentFlags — editable import })