diff --git a/docs/experiment-packages.md b/docs/experiment-packages.md index 3abd4f6c..5ead4177 100644 --- a/docs/experiment-packages.md +++ b/docs/experiment-packages.md @@ -181,10 +181,16 @@ New local exports retain source manifests/publications and typed mappings under as an opaque nested evidence file. Nested archives are never executed or used as native runtime state. -Configure the draft's model credentials, MCP connections and unresolved -dependencies locally, acknowledge configuration, then use normal publication. -Acknowledgement checks owned dataset/Skill/server dependencies without connecting -to external services. Normal publication resolves new local sampling/input +Open the imported experiment's editable draft. Its setup panel reports **Ready to +publish** or **Setup needed**, with links to affected canvas nodes. Select saved +destination provider connections and compatible custom MCP connections there; +multiple compatible connections always require an explicit selection. Missing +credentials can be configured in Profile. Refresh readiness after setup changes. +Normal publication validates the current draft and every factor alternative; +there is no acknowledgement checkbox and no return to the upload screen. +Incomplete drafts remain editable and source evidence remains inspectable. +Readiness checks saved records only; live connection tests are explicit actions. +Normal publication resolves new local sampling/input snapshots; it does not rewrite the preserved source evidence. Resource names receive an import-specific suffix to avoid collisions. Canvas node IDs remain protocol-scoped labels because prompts may address them; new protocol ownership @@ -192,6 +198,31 @@ creates a fresh identity namespace. Only typed resource references, selections and bound factor alternatives are remapped. Opaque strings, scripts, prompts, dataset values, observation values and provenance are not searched/replaced. +Imported content receives fresh owned identities, including imported MCP +requirement identities. Runtime bindings may reference authorized destination +system services or explicitly selected owned connections. These bindings are +recorded separately from source-to-local content mappings. New packages record +stable built-in service identities derived from shipped modules; automatic +matching requires a trusted system registration, the same service identity, +all recorded required tools and exactly one compatible destination. The additive +`service_identity` and `required_tool_names` requirement fields are supported in +schema 2; required tools include the union of factor alternatives and implicit +dataset/Script grants. Older requirements without a required-tool subset use +their recorded full tool list conservatively. Display +names and source owner IDs never establish compatibility or authorization. +Older packages without service identities require explicit selection. Destination +commands, URLs, environment and credentials remain untouched. Scalar MCP identity +factor alternatives become complete configurations so each selected identity +retains its matching destination runtime name. Opaque values remain unchanged. + +Before downloading a prepared export, the dialog separates included dependencies, +destination connection requirements and missing/unresolved content. Incomplete +packages are labelled explicitly and retain actionable dependency diagnostics +(up to 100 in the summary; the full inventory remains in the package). Connection +requirements alone do not make content incomplete. The selected historical +publication remains authoritative; missing history never uses current content. +Use **Publish & prepare package** to download current draft changes instead. + ### API All routes below require the importing user's authentication: @@ -210,9 +241,15 @@ All routes below require the importing user's authentication: `GET .../{id}/source?path=publication/canvas.json` downloads one original file. Omitting `path` re-exports the original source archive byte-for-byte. `GET .../{id}/identities?offset=0&limit=50` pages durable typed provenance. -6. After configuring the editable draft, `POST .../{id}/configuration` with - `{"connections_configured":true,"dependencies_resolved":true}` acknowledges - local configuration. It does not publish or start execution. +6. `GET .../{id}/readiness` returns read-only readiness issues with `node_id`, + compatible authorized MCP candidates, and saved provider selections. + `POST .../{id}/connections` with `{"kind":"mcp","source_id":"source-uuid", + "destination_id":"destination-uuid"}` explicitly selects an existing + connection. Use `"kind":"provider"` and a provider key such as `"openai"` + as `source_id` to select that user's saved provider setting. These actions + never connect, test credentials, or invoke packaged code. Publish using the + normal protocol publication endpoint. The legacy `/configuration` endpoint + remains compatible but its timestamp does not unlock or gate publication. `GET /api/experiment-package-imports?experiment_id={id}` finds an experiment's source history; omitting the filter returns the newest 50 owned requests. @@ -283,8 +320,10 @@ connection is invoked by inspection or reconstruction. | Attributable durable output/artifact files | Exact source files with hashes and attempt attribution; re-exportable source evidence | | Missing/excluded dependencies and unavailable history | Visible diagnostics and preserved inventories; no same-name substitution | -The PostgreSQL tests cover independent owners and both dataset modes, exact CSV -and binary Skill bytes, publication after acknowledgement, source re-export, +The PostgreSQL tests cover isolated source/destination product and resource +schemas, different owners/storage paths/credentials, both dataset modes, exact +CSV/split/binary Skill bytes, publication readiness, built-in compatibility and +ambiguity, explicit custom mapping, factor alternatives, source re-export, ownership isolation and cross-database crash/retry/cancel boundaries. Archive tests cover corruption, unsafe members, limits, compatibility and non-execution. Native Motoro step/resume histories were never exported and cannot be restored. diff --git a/docs/experiment-portability-plan.md b/docs/experiment-portability-plan.md new file mode 100644 index 00000000..8db71fa8 --- /dev/null +++ b/docs/experiment-portability-plan.md @@ -0,0 +1,53 @@ +# Experiment portability implementation + +Branch: `fix/package-export-publication-join`; starting HEAD: `f27437d`. +Preserve existing ancestry and leave PR #56 (base `develop`) unmerged. + +1. Add stable built-in service identities and capability-based destination matching. + Preserve destination connection settings; retain owned imported requirement IDs + and record destination runtime bindings separately as provenance. +2. Add explicit authorized destination connection selection for custom MCP and + model providers, including factor alternatives. Never execute packaged code, + import credentials, or run live connection tests during setup validation. +3. Replace acknowledgement with read-only readiness checks in publication; + surface node/resource issues and allow incomplete drafts to remain editable. +4. Show readiness and setup actions in the imported experiment and link completed + imports directly to that draft. Preserve source inspection and existing UI work. +5. Separate export contents, destination requirements, and missing content; + preserve historical fidelity and the publish-before-download option. +6. Add focused cross-installation coverage for connection matching, fresh owned + identities, factor alternatives, exact bytes, evidence, retry and readiness. + +Verification: focused Python unit tests/lint and frontend tests/type checking. +Database integration uses only explicitly configured disposable PostgreSQL, never +application databases or application `.env` files. Obtain approval before starting +infrastructure, checks taking minutes, or browser automation. + +Identity clarification for #70: imported content always receives fresh owned IDs. +Runtime bindings may reference authorized destination system services. Source IDs +and source-to-local mappings remain immutable provenance; destination commands, +environment and credentials are never replaced by archive data. + +Implementation status: all six steps implemented. Readiness and destination +selection are available on the imported canvas; the legacy acknowledgement API +is retained only for compatibility. New schema-2 requirements carry stable +service identities and required-tool subsets. Legacy requirements require +explicit destination selection. Source provenance scopes reselection when +several requirements share one destination connection. + +Verification (2026-11-11): disposable PostgreSQL 16.2, isolated source/destination +product/resource schemas and filesystem roots; full backend suite passed +2,137 tests (3 skipped; 14 statistical-validation tests deselected). Full frontend +suite passed 664 tests with two workers; default concurrency exposed an existing +metrics-autosave timing failure, which passed alone. Backend lint and frontend +type checks passed. Full mypy has 695 existing errors versus 697 at the starting +HEAD, with no new diagnostics; the four portability service modules pass focused +typing. The first full backend attempt had a launcher-relative scripts-path +failure, fixed in the disposable launcher before the successful full rerun. +Final focused checks passed 121 backend tests and 19 frontend tests, additionally +covering later provenance/reselection changes. `git diff --check` and local +documentation links passed. Implementation is recorded in the branch commit. + +No application databases or application `.env` files were used. Browser +appearance and live provider/MCP behavior were not tested. All original commits +and the two previously unpushed commits remain; no push or merge was performed. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index b128c948..882442bf 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -9,6 +9,7 @@ "version": "0.0.0", "dependencies": { "@base-ui/react": "^1.7.0", + "@codemirror/lang-json": "^6.0.2", "@codemirror/lang-python": "^6.2.1", "@codemirror/theme-one-dark": "^6.1.3", "@fontsource-variable/geist": "^5.3.0", @@ -17,6 +18,7 @@ "@xyflow/react": "^12.11.3", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", + "jsonc-parser": "^3.3.1", "lucide-react": "^1.30.0", "react": "^19.2.8", "react-dom": "^19.2.8", @@ -572,6 +574,15 @@ "@lezer/common": "^1.1.0" } }, + "node_modules/@codemirror/lang-json": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@codemirror/lang-json/-/lang-json-6.0.2.tgz", + "integrity": "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@lezer/json": "^1.0.0" + } + }, "node_modules/@codemirror/lang-python": { "version": "6.2.1", "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.2.1.tgz", @@ -1071,6 +1082,16 @@ "@lezer/common": "^1.3.0" } }, + "node_modules/@lezer/json": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@lezer/json/-/json-1.0.3.tgz", + "integrity": "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, "node_modules/@lezer/lr": { "version": "1.4.10", "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz", @@ -4508,6 +4529,11 @@ "node": ">=6" } }, + "node_modules/jsonc-parser": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz", + "integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==" + }, "node_modules/jsonfile": { "version": "6.2.1", "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index 79dcd1a4..a89d8eeb 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -12,6 +12,7 @@ }, "dependencies": { "@base-ui/react": "^1.7.0", + "@codemirror/lang-json": "^6.0.2", "@codemirror/lang-python": "^6.2.1", "@codemirror/theme-one-dark": "^6.1.3", "@fontsource-variable/geist": "^5.3.0", @@ -20,6 +21,7 @@ "@xyflow/react": "^12.11.3", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", + "jsonc-parser": "^3.3.1", "lucide-react": "^1.30.0", "react": "^19.2.8", "react-dom": "^19.2.8", diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index 10c4065b..c52297f9 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -181,7 +181,8 @@ export const packageImportsApi = { command: (id: string, command: 'confirm' | 'cancel' | 'retry') => request(`${importBase}/${id}/${command}`, { method: 'POST' }), files: (id: string, offset = 0) => request<{ items: PackageFile[]; next_offset: number | null }>(`${importBase}/${id}/files?offset=${offset}`), source: (id: string, path?: string) => requestBlob(`${importBase}/${id}/source${path ? `?path=${encodeURIComponent(path)}` : ''}`), - configure: (id: string) => request(`${importBase}/${id}/configuration`, { method: 'POST', body: { connections_configured: true, dependencies_resolved: true } }), + readiness: (id: string) => request(`${importBase}/${id}/readiness`), + selectConnection: (id: string, kind: 'mcp' | 'provider', sourceId: string, destinationId: string) => request(`${importBase}/${id}/connections`, { method: 'POST', body: { kind, source_id: sourceId, destination_id: destinationId } }), } export const authApi = { diff --git a/frontend/src/components/protocol/ExperimentPackageDownload.test.tsx b/frontend/src/components/protocol/ExperimentPackageDownload.test.tsx index d6a8d03f..173a3c69 100644 --- a/frontend/src/components/protocol/ExperimentPackageDownload.test.tsx +++ b/frontend/src/components/protocol/ExperimentPackageDownload.test.tsx @@ -4,6 +4,7 @@ import { afterEach, expect, it, vi } from 'vitest' import { experimentsApi, protocolsApi, packageImportsApi } from '@/api/client' import type { Protocol, ProtocolRevision } from '@/types/protocols' import { ExperimentPackageDownload } from './ExperimentPackageDownload' +import { protocolForExperimentQueryKey, protocolGraphQueryKey } from '@/lib/protocolGraph' afterEach(() => vi.restoreAllMocks()) @@ -15,19 +16,82 @@ const versions: ProtocolRevision[] = [ { id: 'current', protocol_id: 'p', revision: 2, graph: { nodes: [], edges: [] }, published_at: '2026-01-02' }, ] -function show(selectedVersionId?: string) { +function show(selectedVersionId?: string, draft = protocol) { vi.spyOn(packageImportsApi, 'list').mockResolvedValue([]) const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) - render() + return client } +it('warns about unpublished changes and publishes the live canvas before packaging the returned version', async () => { + const published = { ...protocol, published_revision_id: 'new', published_revision: 3, has_unpublished_changes: false } + vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValueOnce(versions) + .mockResolvedValue([...versions, { ...versions[1], id: 'new', revision: 3 }]) + let finishSave!: (value: Protocol) => void + const save = vi.spyOn(protocolsApi, 'update').mockImplementation(() => new Promise(resolve => { finishSave = resolve })) + const publish = vi.spyOn(protocolsApi, 'publish').mockResolvedValue(published) + const prepared = { id: 'new-job', kind: 'export', status: 'completed', protocol_revision_id: 'new', progress: {}, error: null } as const + const prepare = vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue(prepared) + vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue(prepared) + const client = show('old') + const graph = { nodes: [{ id: 'unsaved', type: 'agent', position: { x: 0, y: 0 }, data: { label: 'Unsaved agent' } }], edges: [] } + client.setQueryData(protocolGraphQueryKey('p'), graph) + fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) + expect(await screen.findByText('Experiment has unpublished changes')).toBeInTheDocument() + await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(2)) + fireEvent.click(screen.getByRole('checkbox')) + fireEvent.click(screen.getByRole('button', { name: 'Publish & prepare package' })) + await waitFor(() => expect(save).toHaveBeenCalledWith('p', { graph })) + expect(publish).not.toHaveBeenCalled() + expect(prepare).not.toHaveBeenCalled() + expect(screen.getByRole('combobox')).toBeDisabled() + await act(async () => { finishSave(protocol) }) + await waitFor(() => expect(prepare).toHaveBeenCalledWith('e', + { protocol_id: 'p', protocol_revision_id: 'new' }, expect.objectContaining({ include_results: true }))) + expect(publish).toHaveBeenCalledWith('p') + expect(client.getQueryData(protocolForExperimentQueryKey('e'))).toEqual(published) + expect(screen.getByRole('combobox')).toHaveValue('new') +}) + +it('allows publication and package preparation before the first version exists', async () => { + const published = { ...protocol, has_unpublished_changes: false } + vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValueOnce([]).mockResolvedValue([versions[1]]) + vi.spyOn(protocolsApi, 'publish').mockResolvedValue(published) + const prepare = vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'failed', + protocol_revision_id: 'current', progress: {}, error: 'fixture' }) + vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'failed', + protocol_revision_id: 'current', progress: {}, error: 'fixture' }) + show(undefined, { ...protocol, published_revision_id: null, published_revision: null }) + fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) + expect(await screen.findByText('Experiment has not been published')).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Prepare package' })).toBeDisabled() + fireEvent.click(screen.getByRole('button', { name: 'Publish & prepare package' })) + await waitFor(() => expect(prepare).toHaveBeenCalledWith('e', + { protocol_id: 'p', protocol_revision_id: 'current' }, expect.anything())) +}) + +it('reports publication failure without preparing an older version', async () => { + vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValue(versions) + vi.spyOn(protocolsApi, 'publish').mockRejectedValue(new Error('Generate cells before publishing.')) + const prepare = vi.spyOn(experimentsApi, 'createResultJob') + show('old') + fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) + fireEvent.click(await screen.findByRole('button', { name: 'Publish & prepare package' })) + expect(await screen.findByRole('alert')).toHaveTextContent('Generate cells before publishing.') + expect(prepare).not.toHaveBeenCalled() + expect(screen.getByRole('combobox')).toHaveValue('old') +}) + it('starts from the viewed historical publication and explicitly opts into results', async () => { vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValue(versions) vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'pending', protocol_revision_id: 'old', progress: {}, error: null }) vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'completed', - protocol_revision_id: 'old', progress: {}, error: null, download_url: '/old-package', schema_url: '/manifest' }) + protocol_revision_id: 'old', progress: { completeness: { status: 'incomplete', unresolved_count: 1, + included_dependencies: 4, destination_connections: 2, + issues: [{ kind: 'split', id: 'historical-split', reason: 'Pinned split unavailable' }] } }, + error: null, download_url: '/old-package', schema_url: '/manifest' }) show('old') fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(2)) @@ -40,6 +104,19 @@ it('starts from the viewed historical publication and explicitly opts into resul expect.objectContaining({ kind: 'export', format: 'experiment_package', include_results: true }))) expect(await screen.findByRole('link', { name: 'Download prepared package' })).toHaveAttribute('href', '/old-package') expect(screen.getByRole('link', { name: 'Manifest' })).toHaveAttribute('href', '/manifest') + expect(screen.getByText('Incomplete package')).toBeInTheDocument() + expect(screen.getByText('4 included dependencies')).toBeInTheDocument() + expect(screen.getByText(/2 destination connection requirements/)).toBeInTheDocument() + expect(screen.getByText(/Pinned split unavailable/)).toBeInTheDocument() +}) + +it('does not offer publication for an unchanged published experiment', async () => { + vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValue(versions) + show(undefined, { ...protocol, has_unpublished_changes: false }) + fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) + await screen.findByRole('combobox') + expect(screen.queryByRole('button', { name: 'Publish & prepare package' })).not.toBeInTheDocument() + expect(screen.queryByText('Experiment has unpublished changes')).not.toBeInTheDocument() }) it('defaults to the published version and sends results excluded', async () => { diff --git a/frontend/src/components/protocol/ExperimentPackageDownload.tsx b/frontend/src/components/protocol/ExperimentPackageDownload.tsx index 6d222380..e570597d 100644 --- a/frontend/src/components/protocol/ExperimentPackageDownload.tsx +++ b/frontend/src/components/protocol/ExperimentPackageDownload.tsx @@ -1,17 +1,21 @@ import { useEffect, useRef, useState, type MouseEvent } from 'react' -import { useMutation, useQuery } from '@tanstack/react-query' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import type { Edge, Node } from '@xyflow/react' import { Download } from 'lucide-react' import { experimentsApi, protocolsApi } from '@/api/client' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { jobActive, useResultJob } from '@/lib/resultJobs' import { newRequestKey } from '@/lib/requestKey' +import { protocolForExperimentQueryKey, protocolGraphQueryKey, toPersistedGraph } from '@/lib/protocolGraph' +import { executionKeys } from '@/lib/executionQueries' import type { Protocol } from '@/types/protocols' import { ExperimentPackageImport } from './ExperimentPackageImport' export function ExperimentPackageDownload({ experimentId, protocol, selectedVersionId }: { experimentId: string; protocol: Protocol; selectedVersionId?: string }) { + const client = useQueryClient() const [open, setOpen] = useState(false) const [versionId, setVersionId] = useState('') const [includeResults, setIncludeResults] = useState(false) @@ -27,13 +31,32 @@ export function ExperimentPackageDownload({ experimentId, protocol, selectedVers if (open && !versionId && versions.data?.length) setVersionId(versions.data[0].id) }, [open, versionId, versions.data]) const create = useMutation({ - mutationFn: () => experimentsApi.createResultJob(experimentId, - { protocol_id: protocol.id, protocol_revision_id: versionId }, + mutationFn: (revisionId: string) => experimentsApi.createResultJob(experimentId, + { protocol_id: protocol.id, protocol_revision_id: revisionId }, { kind: 'export', request_key: newRequestKey(), format: 'experiment_package', include_results: includeResults }), onSuccess: result => setJobId(result.id), }) - const busy = create.isPending || jobActive(job.data) || (!!jobId && !job.data && !job.error) - const error = linkError ?? create.error?.message ?? job.error?.message ?? job.data?.error + const publish = useMutation({ + mutationFn: async () => { + const live = client.getQueryData<{ nodes: Node[]; edges: Edge[] }>(protocolGraphQueryKey(protocol.id)) + if (live) await protocolsApi.update(protocol.id, { graph: toPersistedGraph(live.nodes, live.edges) }) + const published = await protocolsApi.publish(protocol.id) + if (!published.published_revision_id) throw new Error('Publication did not return a downloadable version.') + return published + }, + onSuccess: async published => { + client.setQueryData(protocolForExperimentQueryKey(experimentId), published) + void client.invalidateQueries({ queryKey: ['experiments', experimentId] }) + void client.invalidateQueries({ queryKey: executionKeys.root(experimentId) }) + setVersionId(published.published_revision_id!) + setJobId(undefined) + await client.invalidateQueries({ queryKey: ['protocols', protocol.id, 'revisions'] }) + create.mutate(published.published_revision_id!) + }, + }) + const needsPublish = !protocol.published_revision_id || protocol.has_unpublished_changes + const busy = publish.isPending || create.isPending || jobActive(job.data) || (!!jobId && !job.data && !job.error) + const error = linkError ?? publish.error?.message ?? create.error?.message ?? job.error?.message ?? job.data?.error async function download(event: MouseEvent, metadata: boolean) { event.preventDefault() if (linkPending || !jobId) return @@ -66,6 +89,7 @@ export function ExperimentPackageDownload({ experimentId, protocol, selectedVers setJobId(undefined) setLinkError(undefined) create.reset() + publish.reset() setOpen(true) }}> Download experiment package @@ -74,7 +98,7 @@ export function ExperimentPackageDownload({ experimentId, protocol, selectedVers