Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ sdk/src/asaree_client/_version.py
# Private local planning and agent guidance
docs/*
!docs/managed-storage.md
!docs/experiment-packages.md
# This shared storage decision must travel with implementation sessions.
!docs/adr/
docs/adr/*
Expand Down
91 changes: 91 additions & 0 deletions docs/experiment-packages.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# Published experiment packages

The canvas top bar offers **Download experiment package**. Select a published
version, including an older version, and optionally include its results. The
separate **Download draft definition JSON** action remains a draft definition
export without dependency files.

API clients create the same owned export job used by Results CSV downloads:

```http
POST /api/experiments/{experiment_id}/execution-results/jobs?protocol_id={protocol_id}&protocol_revision_id={publication_id}
Content-Type: application/json

{"kind":"export","format":"experiment_package","include_results":false,"request_key":"unique-client-request"}
```

The publication ID is mandatory. Partial cell, replicate, or row selections are
not supported for a package. Poll the returned job ID through the existing job
endpoint. Completed jobs provide a native `download_url`, a manifest
`schema_url`, and `progress.sha256` for the compressed archive. Links are signed
for five minutes; requesting job status renews the link. Prepared files expire
24 hours after job creation. Cancellation and failure never publish partial
archives as completed downloads.

## Schema version 1

The `.tar.gz` archive contains:

| Member | Meaning |
| --- | --- |
| `manifest.json` | Format/version, selected publication, capture window, software requirements, completeness and inventory hashes |
| `files.jsonl` | One record per payload member: relative path, source identity, byte count, SHA-256 and provenance |
| `dependencies.jsonl` | Included, missing, unresolved and intentionally excluded dependencies, with reasons |
| `publication/` | Selected canvas and experiment settings, including factors, bindings and measurements |
| `experiment-metadata.json` | Current name/description, explicitly captured at download time |
| `design/` | Referenced design declaration and generated cell/replicate identities |
| `inputs/` | Pinned dataset bindings, originals, exact split files and split provenance |
| `resources/` | Scripts, rendered stored Skills with all bundled resources, and authorized knowledge content |
| `requirements/` | Model configurations and MCP server/tool requirements without connection secrets |
| `results/` | Optional version-scoped attempts, observations, recorded evidence and retained attributable files |

The manifest hashes both inventories. `files.jsonl` hashes dependency inventory
bytes but does not hash itself or the manifest, avoiding circular references.
Dataset artifact UUIDs map to paths through the dependency inventory. Arrays in
pinned bindings preserve their recorded ordering and row projections. Resources
are deduplicated within this export by stable identity, never across owners.

`publication_pinned` identifies recorded publication/configuration and verified
input identities. `captured_at_download` identifies mutable reusable library or
knowledge content. Skill entry points are rendered from stored metadata/body;
bundled UTF-8 and base64 assets retain their stored content. `recorded_attempt`
identifies an attempt's own facts, rather than a latest-attempt projection.
`legacy.unknown` records history that cannot be established. Missing historical
settings, sources, splits or files never resolve to the current draft or split.

ASAREE records are read under one repeatable-read snapshot. Motoro resources use
a separate snapshot; filesystem captures verify opened files and detect tree
changes. Mutable external knowledge has no cross-file transaction or historical
snapshot. The manifest records this limitation rather than claiming publication
fidelity. Externally registered directories must be authorized through ownership
and isolated from platform storage; broad roots, other owners' knowledge,
symlinks and ambiguous overlaps are reported as unresolved dependencies.

Credential/connection fields, including typed fallback and sampling snapshot
fields, and recognized credential files are excluded. Dataset bytes, prompts,
scripts and opaque experimental values are preserved. Known knowledge display
paths become relative archive directories; sampling snapshot keys identify
credential-free explicit input in the archive, rather than executable runtime
resolver requests. Importers must use this schema and restore connections;
the package is not a direct runtime-resume image.

Optional results include every retained production attempt for the selected
publication and design. They exclude test runs, node previews, other versions,
queues, workspace resume/control state, regenerable row views/indexes, caches
and scratch. UUID-isolated retained outputs include Agent slots and Script
working directories. Shared legacy workspaces and experiment-level artifacts
without publication attribution are not assigned to historical versions; the
dependency inventory records unavailable or unscoped evidence.
AgentRun IDs in node evidence are source provenance; native Motoro step history
and resume/control snapshots are not bundled.

Archive generation streams file bytes and SQL evidence slices, spools inventories
to plain files, and discards tar member metadata after writing. Memory does not
grow with the number of attempts, archive members or dataset rows. Publication
configuration and one bounded Skill/resource record are processed at a time.
Copying/compression run off the event loop; cancellation stops and joins active
writer work before cleanup. No new database or SQLite inventory is introduced.

A package is a logical export, not a database backup. Importing packages,
resuming workspaces, and reproducing external model/tool outputs are outside its
scope. See [ADR 0003](adr/0003-immutable-dataset-inputs-and-managed-artifacts.md).
2 changes: 1 addition & 1 deletion frontend/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ export const experimentsApi = {
request<{ items: { id: string; sequence: number; iteration: number | null; phase: string; preview: string | null }[]; next_after: number | null }>(`/experiments/${id}/execution-results/attempts/${runId}/nodes/${encodeURIComponent(nodeId)}/trace${resultPageQuery(scope, { after })}`, { signal }),
getExecutionStep: (id: string, runId: string, nodeId: string, stepId: string, scope: ResultsScope, offset: number, signal?: AbortSignal) =>
request<{ text: string; next_offset: number | null }>(`/experiments/${id}/execution-results/attempts/${runId}/nodes/${encodeURIComponent(nodeId)}/trace/${stepId}${resultPageQuery(scope, { offset })}`, { signal }),
createResultJob: (id: string, scope: ResultsScope, command: { kind: ResultJob['kind']; request_key: string; cell_id?: string; replicate_ids?: string[]; row_indices?: number[]; rerun_slot_ids?: string[]; rerun_completed?: boolean }, signal?: AbortSignal) =>
createResultJob: (id: string, scope: ResultsScope, command: { kind: ResultJob['kind']; request_key: string; cell_id?: string; replicate_ids?: string[]; row_indices?: number[]; rerun_slot_ids?: string[]; rerun_completed?: boolean; format?: 'analysis_csv' | 'experiment_package'; include_results?: boolean }, signal?: AbortSignal) =>
request<ResultJob>(`/experiments/${id}/execution-results/jobs${scopeQuery(scope)}`, { method: 'POST', body: command, signal }),
getResultJob: (id: string, jobId: string, signal?: AbortSignal) =>
request<ResultJob>(`/experiments/${id}/execution-results/jobs/${jobId}`, { signal }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,6 @@ export function ExperimentDefinitionDownload({ experimentId, protocol }: { exper
}

return <><Button type="button" variant="outline" size="xs" onClick={downloadDefinition} disabled={downloadingDefinition}>
<Download className="size-3.5" /> {downloadingDefinition ? 'Preparing definition…' : 'Download experiment definition'}
<Download className="size-3.5" /> {downloadingDefinition ? 'Preparing draft JSON…' : 'Download draft definition JSON'}
</Button>{definitionDownloadError && <p role="alert" className="text-xs text-destructive">{definitionDownloadError}</p>}</>
}
111 changes: 111 additions & 0 deletions frontend/src/components/protocol/ExperimentPackageDownload.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import { experimentsApi, protocolsApi } from '@/api/client'
import type { Protocol, ProtocolRevision } from '@/types/protocols'
import { ExperimentPackageDownload } from './ExperimentPackageDownload'

afterEach(() => vi.restoreAllMocks())

const protocol: Protocol = { id: 'p', name: 'Protocol', description: null, experiment_id: 'e',
graph: { nodes: [], edges: [] }, published_revision_id: 'current', published_revision: 2,
has_unpublished_changes: true, created_at: '', updated_at: '' }
const versions: ProtocolRevision[] = [
{ id: 'old', protocol_id: 'p', revision: 1, graph: { nodes: [], edges: [] }, published_at: '2026-01-01', experiment_snapshot: null },
{ id: 'current', protocol_id: 'p', revision: 2, graph: { nodes: [], edges: [] }, published_at: '2026-01-02' },
]

function show(selectedVersionId?: string) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
render(<QueryClientProvider client={client}><ExperimentPackageDownload experimentId="e" protocol={protocol}
selectedVersionId={selectedVersionId} /></QueryClientProvider>)
}

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' })
show('old')
fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' }))
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(2))
expect(screen.getByRole('combobox', { name: 'Published version' })).toHaveValue('old')
expect(screen.getByRole('checkbox')).not.toBeChecked()
fireEvent.click(screen.getByRole('checkbox'))
fireEvent.click(screen.getByRole('button', { name: 'Prepare package' }))
await waitFor(() => expect(experimentsApi.createResultJob).toHaveBeenCalledWith('e',
{ protocol_id: 'p', protocol_revision_id: 'old' },
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')
})

it('defaults to the published version and sends results excluded', async () => {
vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValue(versions)
vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'failed',
protocol_revision_id: 'current', progress: {}, error: 'Package unavailable' })
vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'failed',
protocol_revision_id: 'current', progress: {}, error: 'Package unavailable' })
show()
fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' }))
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(2))
expect(screen.getByRole('combobox', { name: 'Published version' })).toHaveValue('current')
fireEvent.click(screen.getByRole('button', { name: 'Prepare package' }))
await waitFor(() => expect(experimentsApi.createResultJob).toHaveBeenCalledWith('e',
{ protocol_id: 'p', protocol_revision_id: 'current' },
expect.objectContaining({ include_results: false })))
expect(await screen.findByRole('alert')).toHaveTextContent('Package unavailable')
})

const completed = { id: 'job', kind: 'export', status: 'completed', protocol_revision_id: 'old',
progress: {}, error: null, download_url: '/package?token=expired', schema_url: '/manifest?token=expired' } as const

async function prepareCompletedPackage() {
vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValue(versions)
vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue(completed)
const status = vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue(completed)
show('old')
fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' }))
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(2))
fireEvent.click(screen.getByRole('button', { name: 'Prepare package' }))
await screen.findByRole('link', { name: 'Download prepared package' })
return status
}

it('renews stale archive and manifest URLs on activation and uses native navigation', async () => {
const status = await prepareCompletedPackage()
const navigated: string[] = []
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {
navigated.push(this.getAttribute('href') ?? '')
})
status.mockResolvedValue({ ...completed, download_url: '/package?token=fresh', schema_url: '/manifest?token=fresh' })
fireEvent.click(screen.getByRole('link', { name: 'Download prepared package' }))
await waitFor(() => expect(navigated).toEqual(['/package?token=fresh']))
fireEvent.click(screen.getByRole('link', { name: 'Manifest' }))
await waitFor(() => expect(navigated).toEqual(['/package?token=fresh', '/manifest?token=fresh']))
expect(status).toHaveBeenCalledTimes(3)
expect(status).toHaveBeenLastCalledWith('e', 'job', expect.any(AbortSignal))
})

it('reports link renewal failure without navigating to the expired URL', async () => {
const status = await prepareCompletedPackage()
const navigate = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
status.mockRejectedValue(new Error('Status unavailable'))
fireEvent.click(screen.getByRole('link', { name: 'Download prepared package' }))
expect(await screen.findByRole('alert')).toHaveTextContent('Could not refresh the download link. Try again.')
expect(navigate).not.toHaveBeenCalled()
})

it('does not navigate after the selected version changes while renewal is pending', async () => {
const status = await prepareCompletedPackage()
const navigate = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
let finish!: (value: Awaited<ReturnType<typeof experimentsApi.getResultJob>>) => void
status.mockImplementation(() => new Promise(resolve => { finish = resolve }))
fireEvent.click(screen.getByRole('link', { name: 'Download prepared package' }))
await waitFor(() => expect(status).toHaveBeenCalledTimes(2))
fireEvent.change(screen.getByRole('combobox', { name: 'Published version' }), { target: { value: 'current' } })
await act(async () => { finish({ ...completed, download_url: '/package?token=fresh' }) })
expect(navigate).not.toHaveBeenCalled()
expect(screen.queryByRole('link', { name: 'Download prepared package' })).not.toBeInTheDocument()
})
Loading
Loading