A full-featured download manager.
fix(task): repair terminal recovery and large artifact finalization (#2080)
Dr_rOot915a6101fe52
diff --git a/packages/finalize-fs/src/platform/mod.rs b/packages/finalize-fs/src/platform/mod.rsindex 4a0396d8..d203de9c 100644--- a/packages/finalize-fs/src/platform/mod.rs+++ b/packages/finalize-fs/src/platform/mod.rs@@ -9,16 +9,16 @@ mod windows;#[cfg(unix)]pub(crate) use unix::{- ArtifactHandle, RootHandle, copy_opened, open_artifact, open_root, remove_opened,- rename_no_replace, rename_opened_no_replace, sync_root,+ ArtifactHandle, RootHandle, copy_opened, open_artifact, open_artifact_for_rename, open_root,+ remove_opened, rename_no_replace, rename_opened_no_replace, sync_root,};#[cfg(not(any(unix, windows)))]pub(crate) use unsupported::{- ArtifactHandle, RootHandle, copy_opened, open_artifact, open_root, remove_opened,- rename_no_replace, rename_opened_no_replace, sync_root,+ ArtifactHandle, RootHandle, copy_opened, open_artifact, open_artifact_for_rename, open_root,+ remove_opened, rename_no_replace, rename_opened_no_replace, sync_root,};#[cfg(windows)]pub(crate) use windows::{- ArtifactHandle, RootHandle, copy_opened, open_artifact, open_root, remove_opened,- rename_no_replace, rename_opened_no_replace, sync_root,+ ArtifactHandle, RootHandle, copy_opened, open_artifact, open_artifact_for_rename, open_root,+ remove_opened, rename_no_replace, rename_opened_no_replace, sync_root,};diff --git a/packages/finalize-fs/src/platform/unix/copy.rs b/packages/finalize-fs/src/platform/unix/copy.rsindex 26b67553..8bfa4f73 100644--- a/packages/finalize-fs/src/platform/unix/copy.rs+++ b/packages/finalize-fs/src/platform/unix/copy.rs@@ -135,6 +135,13 @@ pub(crate) fn copy_opened(target: &RootHandle,target_relative: &str,) -> io::Result<()> {+ if artifact.opened_tree.is_none() && artifact.opened_file_sha256.is_none() {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ "rename-only handle cannot copy or remove an artifact",+ ));+ }+let target_parts = validate_relative(target_relative)?;let target_parent = open_parent(target.0.as_raw_fd(), &target_parts)?;let target_name =diff --git a/packages/finalize-fs/src/platform/unix/mod.rs b/packages/finalize-fs/src/platform/unix/mod.rsindex 1119b224..6eb64adb 100644--- a/packages/finalize-fs/src/platform/unix/mod.rs+++ b/packages/finalize-fs/src/platform/unix/mod.rs@@ -135,6 +135,23 @@ fn open_parent(root: RawFd, parts: &[&str]) -> io::Result<OwnedFd> {}pub(crate) fn open_artifact(root: &RootHandle, relative: &str) -> io::Result<ArtifactHandle> {+ open_artifact_internal(root, relative, true)+}++/// Rename holds the inode and parent; content is verified by the host journal.+/// A destructive copy/remove snapshot is unnecessary for this operation.+pub(crate) fn open_artifact_for_rename(+ root: &RootHandle,+ relative: &str,+) -> io::Result<ArtifactHandle> {+ open_artifact_internal(root, relative, false)+}++fn open_artifact_internal(+ root: &RootHandle,+ relative: &str,+ snapshot: bool,+) -> io::Result<ArtifactHandle> {let parts = validate_relative(relative)?;let parent = open_parent(root.0.as_raw_fd(), &parts)?;let name = CString::new(*parts.last().expect("nonempty")).expect("validated component");@@ -159,7 +176,11 @@ pub(crate) fn open_artifact(root: &RootHandle, relative: &str) -> io::Result<Art}let opened_type = opened_stat.st_mode & libc::S_IFMT;let opened_tree = if opened_type == libc::S_IFDIR {- Some(snapshot_directory(artifact.as_raw_fd())?)+ if snapshot {+ Some(snapshot_directory(artifact.as_raw_fd())?)+ } else {+ None+ }} else if opened_type == libc::S_IFREG {None} else {@@ -168,7 +189,7 @@ pub(crate) fn open_artifact(root: &RootHandle, relative: &str) -> io::Result<Art"refusing to open a symbolic link or special artifact",));};- let opened_file_sha256 = if opened_type == libc::S_IFREG {+ let opened_file_sha256 = if snapshot && opened_type == libc::S_IFREG {Some(hash_opened_file(artifact.as_raw_fd())?)} else {Nonediff --git a/packages/finalize-fs/src/platform/unix/remove.rs b/packages/finalize-fs/src/platform/unix/remove.rsindex e9d77098..9cb17a67 100644--- a/packages/finalize-fs/src/platform/unix/remove.rs+++ b/packages/finalize-fs/src/platform/unix/remove.rs@@ -249,6 +249,13 @@ pub(crate) fn remove_opened(quarantine_relative: &str,resume_isolated: bool,) -> io::Result<()> {+ if artifact.opened_tree.is_none() && artifact.opened_file_sha256.is_none() {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ "rename-only handle cannot copy or remove an artifact",+ ));+ }+let opened_stat = ensure_same_entry(artifact.artifact.as_raw_fd(),artifact.parent.as_raw_fd(),diff --git a/packages/finalize-fs/src/platform/unix/rename.rs b/packages/finalize-fs/src/platform/unix/rename.rsindex 347b178b..af0d57ef 100644--- a/packages/finalize-fs/src/platform/unix/rename.rs+++ b/packages/finalize-fs/src/platform/unix/rename.rs@@ -15,6 +15,15 @@ pub(crate) fn rename_opened_no_replace(let target_name =CString::new(*target_parts.last().expect("nonempty")).expect("validated component");assert_opened_artifact(artifact, artifact.parent.as_raw_fd(), &artifact.name)?;+ if super::metadata::artifact_stamp(&super::metadata::stat_opened(+ artifact.artifact.as_raw_fd(),+ )?) != artifact.opened_stamp+ {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ "opened artifact changed before rename",+ ));+ }#[cfg(target_os = "macos")]let result = unsafe {diff --git a/packages/finalize-fs/src/platform/unix/tests.rs b/packages/finalize-fs/src/platform/unix/tests.rsindex d698dc0d..df1188db 100644--- a/packages/finalize-fs/src/platform/unix/tests.rs+++ b/packages/finalize-fs/src/platform/unix/tests.rs@@ -159,3 +159,27 @@ fn darwin_rename_is_no_replace_for_files_and_directories() {assert_eq!(std::fs::read(base.join("target/opened")).unwrap(), b"held");let _ = std::fs::remove_dir_all(base);}++#[cfg(any(target_os = "macos", target_os = "linux"))]+#[test]+fn rename_only_handles_do_not_read_large_payloads_or_authorize_removal() {+ let base = std::env::temp_dir().join(format!("motrix-rename-large-{}", std::process::id()));+ std::fs::create_dir_all(&base).unwrap();+ let base = base.canonicalize().unwrap();+ let file = std::fs::File::create(base.join("source")).unwrap();+ file.set_len(68 * 1024 * 1024 * 1024).unwrap();+ drop(file);+ let root = open_root(base.to_str().unwrap()).unwrap();+ let artifact = super::open_artifact_for_rename(&root, "source").unwrap();+ assert!(artifact.opened_file_sha256.is_none());+ assert!(artifact.opened_tree.is_none());+ assert!(super::copy_opened(&artifact, &root, "copy").is_err());+ assert!(remove_opened(&artifact, ".quarantine", false).is_err());+ assert!(base.join("source").exists());+ super::rename_opened_no_replace(&artifact, &root, "target").unwrap();+ assert_eq!(+ std::fs::metadata(base.join("target")).unwrap().len(),+ 68 * 1024 * 1024 * 1024+ );+ std::fs::remove_dir_all(base).unwrap();+}diff --git a/packages/finalize-fs/src/platform/unsupported.rs b/packages/finalize-fs/src/platform/unsupported.rsindex a5858f81..d241ec13 100644--- a/packages/finalize-fs/src/platform/unsupported.rs+++ b/packages/finalize-fs/src/platform/unsupported.rs@@ -77,3 +77,10 @@ pub(crate) fn sync_root(_root: &RootHandle) -> io::Result<()> {"directory durability is not implemented on this platform",))}++pub(crate) fn open_artifact_for_rename(+ root: &RootHandle,+ relative: &str,+) -> io::Result<ArtifactHandle> {+ open_artifact(root, relative)+}diff --git a/packages/finalize-fs/src/platform/windows/copy.rs b/packages/finalize-fs/src/platform/windows/copy.rsindex ad8f4324..aa2204c3 100644--- a/packages/finalize-fs/src/platform/windows/copy.rs+++ b/packages/finalize-fs/src/platform/windows/copy.rs@@ -10,18 +10,20 @@ pub(crate) fn copy_opened(target: &RootHandle,target_relative: &str,) -> io::Result<()> {- ensure_snapshot(&artifact.handle, &artifact.snapshot)?;+ let snapshot = artifact.snapshot.as_ref().ok_or_else(|| {+ io::Error::new(+ io::ErrorKind::InvalidInput,+ "rename-only handle cannot copy or remove an artifact",+ )+ })?;++ ensure_snapshot(&artifact.handle, snapshot)?;ensure_named_entry(&artifact.handle, &artifact.parent, &artifact.name)?;let target_parts = validate_relative(target_relative)?;let (target_parent, target_name) = open_parent(&target.handle, &target_parts)?;- materialize(- &artifact.handle,- &artifact.snapshot,- &target_parent,- &target_name,- )?;- ensure_snapshot(&artifact.handle, &artifact.snapshot)?;+ materialize(&artifact.handle, snapshot, &target_parent, &target_name)?;+ ensure_snapshot(&artifact.handle, snapshot)?;ensure_named_entry(&artifact.handle, &artifact.parent, &artifact.name)?;super::nt::flush(&target_parent)}diff --git a/packages/finalize-fs/src/platform/windows/mod.rs b/packages/finalize-fs/src/platform/windows/mod.rsindex 5c29b91c..350722dc 100644--- a/packages/finalize-fs/src/platform/windows/mod.rs+++ b/packages/finalize-fs/src/platform/windows/mod.rs@@ -29,7 +29,8 @@ pub(crate) struct ArtifactHandle {handle: OwnedHandle,parent: OwnedHandle,name: Vec<u16>,- snapshot: ArtifactSnapshot,+ snapshot: Option<ArtifactSnapshot>,+ stamp: metadata::FileStamp,}pub(crate) fn open_root(path: &str) -> io::Result<RootHandle> {@@ -61,16 +62,37 @@ pub(crate) fn open_root(path: &str) -> io::Result<RootHandle> {}pub(crate) fn open_artifact(root: &RootHandle, relative: &str) -> io::Result<ArtifactHandle> {+ open_artifact_internal(root, relative, true)+}++pub(crate) fn open_artifact_for_rename(+ root: &RootHandle,+ relative: &str,+) -> io::Result<ArtifactHandle> {+ open_artifact_internal(root, relative, false)+}++fn open_artifact_internal(+ root: &RootHandle,+ relative: &str,+ snapshot: bool,+) -> io::Result<ArtifactHandle> {let parts = validate_relative(relative)?;let (parent, name) = open_parent(&root.handle, &parts)?;let handle = nt::open_existing(&parent, &name)?;- let snapshot = metadata::snapshot_opened(&handle)?;+ let stamp = query_stamp(&handle)?;+ let snapshot = if snapshot {+ Some(metadata::snapshot_opened(&handle)?)+ } else {+ None+ };ensure_named_entry(&handle, &parent, &name)?;Ok(ArtifactHandle {handle,parent,name,snapshot,+ stamp,})}@@ -79,7 +101,14 @@ pub(crate) fn rename_opened_no_replace(target: &RootHandle,target_relative: &str,) -> io::Result<()> {- ensure_snapshot(&artifact.handle, &artifact.snapshot)?;+ if let Some(snapshot) = &artifact.snapshot {+ ensure_snapshot(&artifact.handle, snapshot)?;+ } else if query_stamp(&artifact.handle)? != artifact.stamp {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ "opened Windows artifact changed before rename",+ ));+ }ensure_named_entry(&artifact.handle, &artifact.parent, &artifact.name)?;let parts = validate_relative(target_relative)?;let (target_parent, target_name) = open_parent(&target.handle, &parts)?;diff --git a/packages/finalize-fs/src/platform/windows/remove.rs b/packages/finalize-fs/src/platform/windows/remove.rsindex a6877108..76d0e5bb 100644--- a/packages/finalize-fs/src/platform/windows/remove.rs+++ b/packages/finalize-fs/src/platform/windows/remove.rs@@ -12,6 +12,13 @@ pub(crate) fn remove_opened(quarantine_relative: &str,resume_isolated: bool,) -> io::Result<()> {+ let snapshot = artifact.snapshot.as_ref().ok_or_else(|| {+ io::Error::new(+ io::ErrorKind::InvalidInput,+ "rename-only handle cannot copy or remove an artifact",+ )+ })?;+let parts = validate_relative(quarantine_relative)?;if parts.len() != 1 {return Err(io::Error::new(@@ -20,7 +27,7 @@ pub(crate) fn remove_opened());}let quarantine_name = super::nt::wide_name(parts[0])?;- ensure_snapshot(&artifact.handle, &artifact.snapshot)?;+ ensure_snapshot(&artifact.handle, snapshot)?;ensure_named_entry(&artifact.handle, &artifact.parent, &artifact.name)?;if resume_isolated {@@ -43,7 +50,7 @@ pub(crate) fn remove_opened(super::nt::flush(&artifact.parent)?;}- remove_snapshot_contents(&artifact.handle, &artifact.snapshot)?;+ remove_snapshot_contents(&artifact.handle, snapshot)?;// The admitted artifact handle intentionally outlives this operation. Mark// a separately opened, identity-checked handle for POSIX deletion so that// closing it unlinks the quarantine while the admitted handle remains adiff --git a/packages/finalize-fs/src/platform/windows/tests.rs b/packages/finalize-fs/src/platform/windows/tests.rsindex 6eac57de..3ad5d1ad 100644--- a/packages/finalize-fs/src/platform/windows/tests.rs+++ b/packages/finalize-fs/src/platform/windows/tests.rs@@ -153,3 +153,16 @@ fn rejects_a_junction_in_the_root_path() {.arg(&junction).status();}++#[test]+fn rename_only_handles_use_metadata_and_do_not_authorize_removal() {+ let scratch = Scratch::new("rename-only");+ fs::write(scratch.path().join("source"), b"payload").unwrap();+ let root = open_root(scratch.path().to_str().unwrap()).unwrap();+ let artifact = super::open_artifact_for_rename(&root, "source").unwrap();+ assert!(artifact.snapshot.is_none());+ assert!(copy_opened(&artifact, &root, "copy").is_err());+ assert!(remove_opened(&artifact, ".quarantine", false).is_err());+ rename_opened_no_replace(&artifact, &root, "target").unwrap();+ assert_eq!(fs::read(scratch.path().join("target")).unwrap(), b"payload");+}diff --git a/packages/finalize-fs/src/protocol.rs b/packages/finalize-fs/src/protocol.rsindex b9422d10..4e0355d2 100644--- a/packages/finalize-fs/src/protocol.rs+++ b/packages/finalize-fs/src/protocol.rs@@ -17,6 +17,8 @@ pub(crate) enum Request {request_id: u64,root: u64,relative: String,+ #[serde(default)]+ rename_only: bool,},RenameOpenedNoReplace {request_id: u64,diff --git a/packages/finalize-fs/src/state.rs b/packages/finalize-fs/src/state.rsindex 93e69e0b..e36e737b 100644--- a/packages/finalize-fs/src/state.rs+++ b/packages/finalize-fs/src/state.rs@@ -2,8 +2,8 @@use crate::error::classify_error;use crate::platform::{- ArtifactHandle, RootHandle, copy_opened, open_artifact, open_root, remove_opened,- rename_no_replace, rename_opened_no_replace, sync_root,+ ArtifactHandle, RootHandle, copy_opened, open_artifact, open_artifact_for_rename, open_root,+ remove_opened, rename_no_replace, rename_opened_no_replace, sync_root,};use crate::protocol::{Request, Response};use std::collections::HashMap;@@ -39,11 +39,17 @@ impl State {request_id,root,relative,+ rename_only,} => {let Some(root) = self.roots.get(&root) else {return Response::error(Some(request_id), "invalid_handle", "unknown root");};- match open_artifact(root, &relative) {+ let open = if rename_only {+ open_artifact_for_rename+ } else {+ open_artifact+ };+ match open(root, &relative) {Ok(artifact) => {let handle = self.insert_artifact(artifact);let mut response = Response::ok(Some(request_id));diff --git a/src/core/plugin/finalize/artifact-identity.test.ts b/src/core/plugin/finalize/artifact-identity.test.tsindex 0f044363..dc52a927 100644--- a/src/core/plugin/finalize/artifact-identity.test.ts+++ b/src/core/plugin/finalize/artifact-identity.test.ts@@ -1,12 +1,15 @@+import { createHash } from 'node:crypto'import { mkdir, mkdtemp, symlink, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import path from 'node:path'-import { describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import {+ ArtifactIdentityCache,artifactContentEquals,artifactIdentityEquals,readArtifactIdentity,} from './artifact-identity'+import * as hashing from './hash-opened-file'describe('artifact identity', () => {it('hashes regular files with a held no-follow descriptor', async () => {@@ -63,3 +66,34 @@ describe('artifact identity', () => {).rejects.toMatchObject({ code: 'artifact_too_large' })})})++describe('artifact digest reuse', () => {+ afterEach(() => vi.restoreAllMocks())++ it('reuses unchanged file bytes but detects same-size edits inside a directory', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-cached-tree-'))+ const file = path.join(root, 'file')+ await writeFile(file, 'before')+ const hash = vi.spyOn(hashing, 'hashOpenedFile')+ const options = { cache: new ArtifactIdentityCache() }+ const first = await readArtifactIdentity(root, options)+ expect(await readArtifactIdentity(root, options)).toEqual(first)+ expect(hash).toHaveBeenCalledTimes(1)+ await writeFile(file, 'edited')+ expect(await readArtifactIdentity(root, options)).not.toEqual(first)+ expect(hash).toHaveBeenCalledTimes(2)+ })++ it('hashes large held files in the worker without changing the digest', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-worker-hash-'))+ const file = path.join(root, 'large')+ const bytes = Buffer.alloc(17 * 1024 * 1024, 0x61)+ await writeFile(file, bytes)+ const identity = await readArtifactIdentity(file)+ expect(identity).toMatchObject({+ kind: 'file',+ size: bytes.length,+ sha256: createHash('sha256').update(bytes).digest('hex'),+ })+ })+})diff --git a/src/core/plugin/finalize/artifact-identity.ts b/src/core/plugin/finalize/artifact-identity.tsindex 26a3b013..b1bf9d1c 100644--- a/src/core/plugin/finalize/artifact-identity.ts+++ b/src/core/plugin/finalize/artifact-identity.ts@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto'import { constants } from 'node:fs'import { lstat, open, readdir } from 'node:fs/promises'import path from 'node:path'+import { hashOpenedFile } from './hash-opened-file'export interface FileArtifactIdentity {kind: 'file'@@ -38,6 +39,22 @@ export class ArtifactIdentityError extends Error {export interface ArtifactIdentityOptions {maxEntries?: number+ cache?: ArtifactIdentityCache+}++/** Reuse content digests only while inode, size and both timestamps match. */+export class ArtifactIdentityCache {+ private readonly digests = new Map<string, string>()+ get(stamp: string): string | undefined {+ return this.digests.get(stamp)+ }+ set(stamp: string, digest: string): void {+ if (this.digests.size >= 2048) {+ const oldest = this.digests.keys().next().value+ if (oldest !== undefined) this.digests.delete(oldest)+ }+ this.digests.set(stamp, digest)+ }}const statKey = (value: {@@ -65,7 +82,8 @@ function appendRecord(}async function identityForFile(- filePath: string+ filePath: string,+ cache?: ArtifactIdentityCache): Promise<FileArtifactIdentity> {let handle: Awaited<ReturnType<typeof open>>try {@@ -85,9 +103,9 @@ async function identityForFile(`artifact is not a regular file: ${filePath}`)}- const hash = createHash('sha256')- const stream = handle.createReadStream({ autoClose: false })- for await (const chunk of stream) hash.update(chunk as Buffer)+ const stamp = statKey(before)+ const digest =+ cache?.get(stamp) ?? (await hashOpenedFile(handle, before.size))const after = await handle.stat({ bigint: true })if (statKey(before) !== statKey(after)) {throw new ArtifactIdentityError(@@ -101,10 +119,11 @@ async function identityForFile(`artifact size exceeds the safe identity range: ${filePath}`)}+ cache?.set(stamp, digest)return {kind: 'file',size: Number(after.size),- sha256: hash.digest('hex'),+ sha256: digest,platformFileId: fileId(after),}} finally {@@ -123,7 +142,8 @@ async function walkDirectory(root: string,current: string,records: TreeRecord[],- maxEntries: number+ maxEntries: number,+ cache?: ArtifactIdentityCache): Promise<void> {const entries = await readdir(current, { withFileTypes: true })entries.sort((left, right) =>@@ -147,7 +167,7 @@ async function walkDirectory(}if (entryStat.isDirectory()) {records.push({ type: 'directory', relativePath })- await walkDirectory(root, absolute, records, maxEntries)+ await walkDirectory(root, absolute, records, maxEntries, cache)const after = await lstat(absolute, { bigint: true })if (statKey(entryStat) !== statKey(after)) {throw new ArtifactIdentityError(@@ -163,7 +183,7 @@ async function walkDirectory(`directory artifact contains a special entry: ${relativePath}`)}- const identity = await identityForFile(absolute)+ const identity = await identityForFile(absolute, cache)if (identity.platformFileId !== fileId(entryStat)) {throw new ArtifactIdentityError('artifact_mutated',@@ -196,7 +216,7 @@ export async function readArtifactIdentity(`artifact root is a symbolic link: ${artifactPath}`)}- if (root.isFile()) return identityForFile(artifactPath)+ if (root.isFile()) return identityForFile(artifactPath, options.cache)if (!root.isDirectory()) {throw new ArtifactIdentityError('artifact_special_file',@@ -220,7 +240,8 @@ export async function readArtifactIdentity(artifactPath,artifactPath,records,- options.maxEntries ?? 1_000_000+ options.maxEntries ?? 1_000_000,+ options.cache)const after = directoryHandle? await directoryHandle.stat({ bigint: true })diff --git a/src/core/plugin/finalize/filesystem-adapter.test.ts b/src/core/plugin/finalize/filesystem-adapter.test.tsindex 8cb7e6b1..2b48732b 100644--- a/src/core/plugin/finalize/filesystem-adapter.test.ts+++ b/src/core/plugin/finalize/filesystem-adapter.test.ts@@ -1,7 +1,7 @@import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises'import os from 'node:os'import path from 'node:path'-import { afterEach, describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import { NativeFinalizeFilesystemAdapter } from './filesystem-adapter'describe.runIf(process.platform !== 'win32')(@@ -26,6 +26,93 @@ describe.runIf(process.platform !== 'win32')(return script}+ async function framedSidecar(): Promise<string> {+ const root = await mkdtemp(+ path.join(os.tmpdir(), 'motrix-framed-sidecar-')+ )+ roots.push(root)+ const script = path.join(root, 'sidecar.cjs')+ await writeFile(+ script,+ `+ let incoming = Buffer.alloc(0)+ process.stdin.on('data', chunk => {+ incoming = Buffer.concat([incoming, chunk])+ while (incoming.length >= 4) {+ const size = incoming.readUInt32LE(0)+ if (incoming.length < size + 4) return+ const request = JSON.parse(incoming.subarray(4, size + 4).toString())+ incoming = incoming.subarray(size + 4)+ if (request.relative === 'crash') process.exit(23)+ const send = () => {+ const payload = Buffer.from(JSON.stringify({+ request_id: request.request_id, status: 'ok',+ handle: request.op === 'open_root' ? 1 : 2,+ platform: 'test', rename_no_replace: true, held_roots: true,+ directory_sync: true, held_artifacts: true,+ }))+ const frame = Buffer.alloc(payload.length + 4)+ frame.writeUInt32LE(payload.length)+ payload.copy(frame, 4)+ process.stdout.write(frame)+ }+ if (request.relative === 'slow') setTimeout(send, 1200)+ else send()+ }+ })+ `+ )+ const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`+ return executable(`exec ${quote(process.execPath)} ${quote(script)}`)+ }++ it('lets filesystem work exceed the handshake deadline and excludes queue time', async () => {+ const adapter = new NativeFinalizeFilesystemAdapter(await framedSidecar())+ try {+ await adapter.capabilities()+ const root = await adapter.openRoot(os.tmpdir())+ // Startup uses real time. Advance only the host request deadlines,+ // while the child deliberately keeps its filesystem response pending.+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ const artifact = adapter.openArtifact(root, 'slow')+ const queuedHandshake = adapter.capabilities()+ const assertions = Promise.all([+ expect(artifact).resolves.toMatchObject({ id: 2 }),+ expect(queuedHandshake).resolves.toMatchObject({+ heldArtifacts: true,+ }),+ ])+ await vi.advanceTimersByTimeAsync(30_001)+ await assertions+ } finally {+ vi.useRealTimers()+ await adapter.dispose()+ }+ }, 10_000)++ it('restarts for a later operation while rejecting handles from the failed child', async () => {+ const adapter = new NativeFinalizeFilesystemAdapter(await framedSidecar())+ try {+ await adapter.capabilities()+ const oldRoot = await adapter.openRoot(os.tmpdir())+ await expect(adapter.openArtifact(oldRoot, 'crash')).rejects.toThrow(+ 'exited: 23'+ )+ await expect(adapter.capabilities()).resolves.toMatchObject({+ heldArtifacts: true,+ })+ const root = await adapter.openRoot(os.tmpdir())+ expect(root.id).toBe(oldRoot.id)+ await expect(adapter.syncRoot(oldRoot)).rejects.toMatchObject({+ code: 'invalid_handle',+ })+ await expect(adapter.syncRoot(root)).resolves.toBeUndefined()+ } finally {+ await adapter.dispose()+ }+ await expect(adapter.capabilities()).rejects.toThrow('disposed')+ })+async function rejectedError(operation: Promise<unknown>): Promise<Error> {let caught: unknowntry {diff --git a/src/core/plugin/finalize/filesystem-adapter.ts b/src/core/plugin/finalize/filesystem-adapter.tsindex 84e2bba0..df1686a0 100644--- a/src/core/plugin/finalize/filesystem-adapter.ts+++ b/src/core/plugin/finalize/filesystem-adapter.ts@@ -46,7 +46,7 @@ interface WireResponse {interface PendingRequest {resolve: (value: WireResponse) => voidreject: (error: Error) => void- timeout: NodeJS.Timeout+ timeout?: NodeJS.Timeout}export interface NativeFinalizeFilesystemAdapterOptions {@@ -66,7 +66,8 @@ export interface FinalizeFilesystemAdapter {openRoot(rootPath: string): Promise<FinalizeRootHandle>openArtifact(root: FinalizeRootHandle,- relativePath: string+ relativePath: string,+ intent?: 'rename'): Promise<FinalizeArtifactHandle>renameOpenedNoReplace(artifact: FinalizeArtifactHandle,@@ -97,7 +98,11 @@ export interface FinalizeFilesystemAdapter {export class NativeFinalizeFilesystemAdapterimplements FinalizeFilesystemAdapter{- private readonly child: ChildProcessWithoutNullStreams+ private child!: ChildProcessWithoutNullStreams+ private generation = 0+ private disposed = false+ private requestTail: Promise<unknown> = Promise.resolve()+ private readonly handleGenerations = new WeakMap<object, number>()private nextRequestId = 1private incoming = Buffer.alloc(0)private readonly pending = new Map<number, PendingRequest>()@@ -105,7 +110,7 @@ export class NativeFinalizeFilesystemAdapterprivate deadError: Error | null = nullconstructor(- binaryPath: string,+ private readonly binaryPath: string,options: NativeFinalizeFilesystemAdapterOptions = {}) {this.requestTimeoutMs = options.requestTimeoutMs ?? 30_000@@ -114,17 +119,54 @@ export class NativeFinalizeFilesystemAdapterthis.requestTimeoutMs <= 0)throw new Error('finalize sidecar request timeout must be positive')- this.child = spawn(binaryPath, [], { stdio: ['pipe', 'pipe', 'pipe'] })- this.child.stdout.on('data', (chunk: Buffer) => this.receive(chunk))- this.child.stderr.resume()- this.child.stdin.once('error', (error) => this.markDead(error))- this.child.once('error', (error) => this.markDead(error))- this.child.once('exit', (code) =>- this.markDead(new Error(`finalize filesystem sidecar exited: ${code}`))+ this.startChild()+ }++ private startChild(): void {+ this.generation += 1+ this.deadError = null+ this.incoming = Buffer.alloc(0)+ const child = spawn(this.binaryPath, [], {+ stdio: ['pipe', 'pipe', 'pipe'],+ })+ this.child = child+ const fail = (error: Error) => {+ if (this.child === child) this.markDead(error)+ }+ child.stdout.on('data', (chunk: Buffer) => {+ if (this.child === child) this.receive(chunk)+ })+ child.stderr.resume()+ child.stdin.once('error', fail)+ child.once('error', fail)+ child.once('exit', (code) =>+ fail(new Error(`finalize filesystem sidecar exited: ${code}`)))}+ private heldHandle(id: number, generation: number): FinalizeRootHandle {+ const handle = Object.freeze({ id })+ this.handleGenerations.set(handle, generation)+ return handle+ }++ private nativeId(+ handle: FinalizeRootHandle | FinalizeArtifactHandle+ ): number {+ if (this.deadError) throw this.deadError+ if (this.handleGenerations.get(handle) !== this.generation) {+ throw new FinalizeFsError(+ 'invalid_handle',+ 'finalize handle belongs to an earlier sidecar process'+ )+ }+ return handle.id+ }+async capabilities(): Promise<FinalizeFsCapabilities> {+ // A new operation may recover the transport. Old operations retain their+ // failed promises/handle generations and cannot mutate through the child.+ if (this.deadError && !this.disposed) this.startChild()const response = await this.request({ op: 'capabilities' }, false)return {platform: response.platform ?? 'unknown',@@ -137,17 +179,20 @@ export class NativeFinalizeFilesystemAdapterasync openArtifact(root: FinalizeRootHandle,- relativePath: string+ relativePath: string,+ intent?: 'rename'): Promise<FinalizeArtifactHandle> {+ const generation = this.generationconst response = await this.request({op: 'open_artifact',- root: root.id,+ rename_only: intent === 'rename',+ root: this.nativeId(root),relative: relativePath,})if (response.handle === undefined) {throw new Error('sidecar omitted artifact handle')}- return Object.freeze({ id: response.handle })+ return this.heldHandle(response.handle, generation)}async renameOpenedNoReplace(@@ -157,8 +202,8 @@ export class NativeFinalizeFilesystemAdapter): Promise<void> {await this.request({op: 'rename_opened_no_replace',- artifact: artifact.id,- target_root: targetRoot.id,+ artifact: this.nativeId(artifact),+ target_root: this.nativeId(targetRoot),target_relative: targetRelative,})}@@ -170,8 +215,8 @@ export class NativeFinalizeFilesystemAdapter): Promise<void> {await this.request({op: 'copy_opened',- artifact: artifact.id,- target_root: targetRoot.id,+ artifact: this.nativeId(artifact),+ target_root: this.nativeId(targetRoot),target_relative: targetRelative,})}@@ -180,10 +225,11 @@ export class NativeFinalizeFilesystemAdapterif (!path.isAbsolute(rootPath)) {throw new FinalizeFsError('invalid_path', 'root path must be absolute')}+ const generation = this.generationconst response = await this.request({ op: 'open_root', path: rootPath })if (response.handle === undefined)throw new Error('sidecar omitted root handle')- return Object.freeze({ id: response.handle })+ return this.heldHandle(response.handle, generation)}async renameNoReplace(@@ -194,9 +240,9 @@ export class NativeFinalizeFilesystemAdapter): Promise<void> {await this.request({op: 'rename_no_replace',- source_root: sourceRoot.id,+ source_root: this.nativeId(sourceRoot),source_relative: sourceRelative,- target_root: targetRoot.id,+ target_root: this.nativeId(targetRoot),target_relative: targetRelative,})}@@ -208,23 +254,25 @@ export class NativeFinalizeFilesystemAdapter): Promise<void> {await this.request({op: 'remove_opened',- artifact: artifact.id,+ artifact: this.nativeId(artifact),quarantine_relative: quarantineRelative,resume_isolated: resumeIsolated,})}async syncRoot(root: FinalizeRootHandle): Promise<void> {- await this.request({ op: 'sync_root', root: root.id })+ await this.request({ op: 'sync_root', root: this.nativeId(root) })}async close(root: FinalizeRootHandle | FinalizeArtifactHandle): Promise<void> {- await this.request({ op: 'close', handle: root.id })+ await this.request({ op: 'close', handle: this.nativeId(root) })+ this.handleGenerations.delete(root)}async dispose(): Promise<void> {+ this.disposed = trueif (this.deadError) {if (this.child.exitCode === null && this.child.signalCode === null)this.child.kill()@@ -236,7 +284,7 @@ export class NativeFinalizeFilesystemAdapterconst timeout = setTimeout(() => {this.child.kill()resolve()- }, this.requestTimeoutMs)+ }, 5_000)timeout.unref()this.child.once('exit', () => {clearTimeout(timeout)@@ -245,10 +293,29 @@ export class NativeFinalizeFilesystemAdapter})}- private async request(+ private request(body: Record<string, unknown>,includeRequestId = true): Promise<WireResponse> {+ const generation = this.generation+ const result = this.requestTail.then(() => {+ if (generation !== this.generation)+ throw new FinalizeFsError(+ 'invalid_handle',+ 'finalize operation lost its sidecar process'+ )+ return this.sendRequest(body, includeRequestId)+ })+ this.requestTail = result.catch(() => undefined)+ return result+ }++ private async sendRequest(+ body: Record<string, unknown>,+ includeRequestId = true+ ): Promise<WireResponse> {+ if (this.disposed)+ throw new Error('finalize filesystem adapter is disposed')if (this.deadError) throw this.deadErrorconst requestId = this.nextRequestId++const payload = Buffer.from(@@ -263,18 +330,24 @@ export class NativeFinalizeFilesystemAdapterpayload.copy(frame, 4)const response = new Promise<WireResponse>((resolve, reject) => {const key = includeRequestId ? requestId : 0- const timeout = setTimeout(() => {- const error = new Error(- `finalize filesystem sidecar request timed out after ${this.requestTimeoutMs}ms`- )- this.markDead(error)- this.child.kill()- }, this.requestTimeoutMs)- timeout.unref()+ // Content hashing, copies and filesystem syncs have no fixed deadline.+ // Only the startup handshake is bounded, after earlier I/O has finished.+ const timeout =+ body.op === 'capabilities'+ ? setTimeout(() => {+ this.markDead(+ new Error(+ `finalize filesystem sidecar request timed out after ${this.requestTimeoutMs}ms`+ )+ )+ }, this.requestTimeoutMs)+ : undefined+ timeout?.unref()this.pending.set(key, { resolve, reject, timeout })})- this.child.stdin.write(frame, (error) => {- if (error) this.markDead(error)+ const child = this.child+ child.stdin.write(frame, (error) => {+ if (error && this.child === child) this.markDead(error)})const result = await responseif (result.status === 'error') {diff --git a/src/core/plugin/finalize/hash-opened-file.ts b/src/core/plugin/finalize/hash-opened-file.tsnew file mode 100644index 00000000..66dc227e--- /dev/null+++ b/src/core/plugin/finalize/hash-opened-file.ts@@ -0,0 +1,57 @@+import { createHash } from 'node:crypto'+import type { FileHandle } from 'node:fs/promises'+import { Worker } from 'node:worker_threads'++// Builtins-only worker source is embedded so both packaged hosts can run it+// without another bundled entrypoint. The parent owns and closes the fd.+const HASH_WORKER = `+const { parentPort, workerData: fd } = require('node:worker_threads')+const { readSync } = require('node:fs')+const { createHash } = require('node:crypto')+const hash = createHash('sha256')+const buffer = Buffer.allocUnsafe(1024 * 1024)+let offset = 0+for (;;) {+ const length = readSync(fd, buffer, 0, buffer.length, offset)+ if (length === 0) break+ hash.update(buffer.subarray(0, length))+ offset += length+}+parentPort.postMessage(hash.digest('hex'))+parentPort.close()+`++export async function hashOpenedFile(+ handle: FileHandle,+ size: bigint+): Promise<string> {+ if (size < 16n * 1024n * 1024n) {+ const hash = createHash('sha256')+ for await (const chunk of handle.createReadStream({+ autoClose: false,+ start: 0,+ })) {+ hash.update(chunk as Buffer)+ }+ return hash.digest('hex')+ }+ return new Promise<string>((resolve, reject) => {+ const worker = new Worker(HASH_WORKER, {+ eval: true,+ workerData: handle.fd,+ })+ let digest: string | undefined+ worker.once('message', (value: string) => {+ digest = value+ })+ worker.once('error', reject)+ // Wait for exit before allowing the owner to close/reuse the descriptor.+ worker.once('exit', (code) => {+ if (code === 0 && digest) resolve(digest)+ else+ reject(+ new Error(`artifact hash worker exited without a digest: ${code}`)+ )+ })+ })+}diff --git a/src/core/plugin/finalize/native-artifact-operations.integration.test.ts b/src/core/plugin/finalize/native-artifact-operations.integration.test.tsindex 07083dc9..a16a5847 100644--- a/src/core/plugin/finalize/native-artifact-operations.integration.test.ts+++ b/src/core/plugin/finalize/native-artifact-operations.integration.test.ts@@ -11,13 +11,16 @@ import {} from 'node:fs/promises'import os from 'node:os'import path from 'node:path'-import { afterEach, describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import {artifactContentEquals,+ artifactIdentityEquals,readArtifactIdentity,} from './artifact-identity'+import { ArtifactMutationLeaseCoordinator } from './artifact-mutation-lease'import { NativeFinalizeFilesystemAdapter } from './filesystem-adapter'-import { removalQuarantinePath } from './finalize-committer'+import { FinalizeCommitter, removalQuarantinePath } from './finalize-committer'+import * as hashing from './hash-opened-file'import { NativeFinalizeArtifactOperations } from './native-artifact-operations'const binary = process.env.MOTRIX_FINALIZE_FS_TEST_BIN@@ -36,6 +39,7 @@ describe.runIf(existsSync(binary))(const roots: string[] = []afterEach(async () => {+ vi.restoreAllMocks()await Promise.all(roots.splice(0)@@ -54,6 +58,60 @@ describe.runIf(existsSync(binary))(return { root, adapter, operations }}+ it('finalizes a large file with at most two content reads and metadata-only native rename', async () => {+ const { root, adapter, operations } = await setup()+ const source = path.join(root, 'large.part')+ const target = path.join(root, 'large.bin')+ await writeFile(source, Buffer.alloc(17 * 1024 * 1024, 0x53))+ const hash = vi.spyOn(hashing, 'hashOpenedFile')+ const nativeOpen = vi.spyOn(adapter, 'openArtifact')+ const sourceIdentity = await operations.identity(source)+ if (!sourceIdentity) throw new Error('missing fixture')+ const commitTerminal = vi.fn()+ const committer = new FinalizeCommitter({+ fs: operations,+ leases: new ArtifactMutationLeaseCoordinator([]),+ repository: {+ prepare: vi.fn(),+ checkpoint: vi.fn(),+ advance: vi.fn(),+ commitTerminal,+ quarantine: vi.fn(),+ listRecoverable: async () => [],+ },+ privatePathFor: () => path.join(root, '.private'),+ rollbackPathFor: () => path.join(root, '.rollback'),+ exactIdentity: artifactIdentityEquals,+ sameContent: artifactContentEquals,+ })+ try {+ await committer.commit({+ planId: 'large-plan',+ taskId: 'large-task',+ saveDir: root,+ sourcePath: source,+ targetPath: target,+ sourceIdentity,+ metadataOps: [],+ contributors: [],+ })+ expect(hash).toHaveBeenCalled()+ expect(hash.mock.calls.length).toBeLessThanOrEqual(2)+ expect(nativeOpen).toHaveBeenCalledWith(+ expect.anything(),+ 'large.part',+ 'rename'+ )+ expect(commitTerminal).toHaveBeenCalledOnce()+ expect(existsSync(source)).toBe(false)+ expect(+ (await readFile(target)).equals(Buffer.alloc(17 * 1024 * 1024, 0x53))+ ).toBe(true)+ } finally {+ await adapter.dispose()+ }+ })+it('publishes a held file without replacing an existing target', async () => {const { root, adapter, operations } = await setup()const source = path.join(root, 'source.bin')diff --git a/src/core/plugin/finalize/native-artifact-operations.ts b/src/core/plugin/finalize/native-artifact-operations.tsindex 03338f85..a6c574b9 100644--- a/src/core/plugin/finalize/native-artifact-operations.ts+++ b/src/core/plugin/finalize/native-artifact-operations.ts@@ -3,6 +3,7 @@ import { lstat, mkdir, open, readdir, stat } from 'node:fs/promises'import path from 'node:path'import {type ArtifactIdentity,+ ArtifactIdentityCache,ArtifactIdentityError,artifactIdentityEquals,readArtifactIdentity,@@ -19,6 +20,8 @@ import type { FinalizeArtifactOperations } from './finalize-committer'export class NativeFinalizeArtifactOperationsimplements FinalizeArtifactOperations{+ private readonly identityCache = new ArtifactIdentityCache()+constructor(private readonly adapter: FinalizeFilesystemAdapter) {}async assertSupported(): Promise<void> {@@ -37,7 +40,9 @@ export class NativeFinalizeArtifactOperationsasync identity(artifactPath: string): Promise<ArtifactIdentity | null> {try {- return await readArtifactIdentity(artifactPath)+ return await readArtifactIdentity(artifactPath, {+ cache: this.identityCache,+ })} catch (error) {if (error instanceof ArtifactIdentityError &&@@ -60,6 +65,7 @@ export class NativeFinalizeArtifactOperationsexpected: ArtifactIdentity,privateTargetPath: string): Promise<ArtifactIdentity> {+ await this.assertSupported()await this.requireIdentity(sourcePath, expected)await this.ensureSafeDirectory(path.dirname(privateTargetPath))await this.assertSafeExistingParent(sourcePath)@@ -98,7 +104,9 @@ export class NativeFinalizeArtifactOperationsawait this.adapter.close(sourceRoot).catch(() => undefined)await this.adapter.close(targetRoot).catch(() => undefined)}- const copied = await readArtifactIdentity(privateTargetPath)+ const copied = await readArtifactIdentity(privateTargetPath, {+ cache: this.identityCache,+ })await this.requireIdentity(sourcePath, expected)await this.assertSafeExistingParent(privateTargetPath)return copied@@ -119,7 +127,8 @@ export class NativeFinalizeArtifactOperationstry {artifact = await this.adapter.openArtifact(sourceRoot,- path.basename(sourcePath)+ path.basename(sourcePath),+ 'rename')await this.requireIdentity(sourcePath, expected)await this.adapter.renameOpenedNoReplace(@@ -138,6 +147,7 @@ export class NativeFinalizeArtifactOperations}async makeDurable(artifactPath: string): Promise<void> {+ await this.assertSupported()await syncTree(artifactPath, this.adapter)const root = await this.adapter.openRoot(path.dirname(artifactPath))try {@@ -152,6 +162,7 @@ export class NativeFinalizeArtifactOperationsexpected: ArtifactIdentity,quarantinePath: string): Promise<void> {+ await this.assertSupported()if (path.dirname(quarantinePath) !== path.dirname(artifactPath) ||path.basename(quarantinePath) === path.basename(artifactPath)@@ -234,7 +245,9 @@ export class NativeFinalizeArtifactOperationsartifactPath: string,expected: ArtifactIdentity): Promise<void> {- const actual = await readArtifactIdentity(artifactPath)+ const actual = await readArtifactIdentity(artifactPath, {+ cache: this.identityCache,+ })if (!artifactIdentityEquals(actual, expected)) {throw new ArtifactIdentityError('artifact_mutated',diff --git a/src/core/session/durable-finalize-runtime.ts b/src/core/session/durable-finalize-runtime.tsindex b7759141..54ececb3 100644--- a/src/core/session/durable-finalize-runtime.ts+++ b/src/core/session/durable-finalize-runtime.ts@@ -1,9 +1,9 @@import { randomUUID } from 'node:crypto'import path from 'node:path'import {+ ArtifactIdentityError,artifactContentEquals,artifactIdentityEquals,- readArtifactIdentity,} from '@core/plugin/finalize/artifact-identity'import { ArtifactMutationLeaseCoordinator } from '@core/plugin/finalize/artifact-mutation-lease'import type { FinalizeArtifactOperations } from '@core/plugin/finalize/finalize-committer'@@ -59,11 +59,11 @@ export class DurableFinalizeRuntime {try {// H8: identity capture is inside the mutation lease, after every// engine/Host writer has successfully quiesced.- const sourceIdentity = await readArtifactIdentity(input.sourcePath)+ const sourceIdentity = await this.captureIdentity(input.sourcePath)const replacement = input.replacement? {...input.replacement,- identity: await readArtifactIdentity(input.replacement.stagedPath),+ identity: await this.captureIdentity(input.replacement.stagedPath),}: undefinedconst plan = freezeHookPlan({@@ -130,6 +130,16 @@ export class DurableFinalizeRuntime {}}+ private async captureIdentity(artifactPath: string) {+ const identity = await this.options.fs.identity(artifactPath)+ if (!identity)+ throw new ArtifactIdentityError(+ 'artifact_missing',+ `artifact is missing: ${artifactPath}`+ )+ return identity+ }+/** Recover before task restore: committed rows clean up; uncommitted targets roll back. */async recoverAll(): Promise<void> {const repository = new SqliteFinalizeJournalRepository(this.options.db, {diff --git a/src/core/session/migrations/index.ts b/src/core/session/migrations/index.tsindex f0379378..cf25da44 100644--- a/src/core/session/migrations/index.ts+++ b/src/core/session/migrations/index.ts@@ -8,6 +8,7 @@ import {import { V2_TASK_SCHEMA_OBJECTS, v2 } from './v2'import { V3_SCHEMA_OBJECTS, v3 } from './v3'import { V4_SCHEMA_OBJECTS, v4 } from './v4'+import { V5_TASK_SCHEMA_OBJECTS, v5 } from './v5'interface Migration {version: number@@ -20,8 +21,10 @@ interface Migration {// file selection — distinct from "still fetching metadata" so the// Downloads pill can say "Ready" instead of the misleading// "Fetching"). v3 adds task-owned Inspector Activity persistence. v4 adds-// durable plugin finalize journals plus post-delivery and quota state.-const MIGRATIONS: Migration[] = [v1, v2, v3, v4]+// durable plugin finalize journals plus post-delivery and quota state. v5+// persists the user-selected save directory independently of engine paths and+// repairs stale instance statuses beneath terminal tasks.+const MIGRATIONS: Migration[] = [v1, v2, v3, v4, v5]const HIGHEST_KNOWN_VERSION = MIGRATIONS.reduce((max, m) => (m.version > max ? m.version : max),@@ -234,10 +237,10 @@ function assertCanonicalTaskSchema(}}-function validateCanonicalV3(db: Database.Database): void {+function validateCanonicalTaskAndActivitySchema(db: Database.Database): void {const dbPath = (db as unknown as { name: string }).nameassertCanonicalInheritedSchema(db)- assertCanonicalTaskSchema(db, V2_TASK_SCHEMA_OBJECTS)+ assertCanonicalTaskSchema(db, V5_TASK_SCHEMA_OBJECTS)if (!hasExactSchemaObjects(db, V3_SCHEMA_OBJECTS)) {throw new StaleSchemaError('inspector_activity_schema_missing', dbPath)@@ -275,8 +278,8 @@ function validateCanonicalV3(db: Database.Database): void {}}-function validateCanonicalV4(db: Database.Database): void {- validateCanonicalV3(db)+function validateCanonicalSchema(db: Database.Database): void {+ validateCanonicalTaskAndActivitySchema(db)if (!hasExactSchemaObjects(db, V4_SCHEMA_OBJECTS)) {throw new StaleSchemaError('plugin_hook_schema_missing',@@ -398,7 +401,11 @@ export function migrate(db: Database.Database): void {}assertCanonicalTaskSchema(db,- current === 1 ? V1_TASK_SCHEMA_OBJECTS : V2_TASK_SCHEMA_OBJECTS+ current === 1+ ? V1_TASK_SCHEMA_OBJECTS+ : current >= 5+ ? V5_TASK_SCHEMA_OBJECTS+ : V2_TASK_SCHEMA_OBJECTS)assertCanonicalInheritedSchema(db)@@ -489,5 +496,5 @@ export function migrate(db: Database.Database): void {}}- validateCanonicalV4(db)+ validateCanonicalSchema(db)}diff --git a/src/core/session/migrations/v1.test.ts b/src/core/session/migrations/v1.test.tsindex b6f97bb8..7e707911 100644--- a/src/core/session/migrations/v1.test.ts+++ b/src/core/session/migrations/v1.test.ts@@ -524,7 +524,7 @@ describe('migrate() schema guard (Codex finding #7)', () => {const rows = db.prepare('SELECT version FROM schema_version ORDER BY version').all() as Array<{ version: number }>- expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4])+ expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5])db.close()})@@ -542,7 +542,7 @@ describe('migrate() schema guard (Codex finding #7)', () => {// v1 is the Plan A baseline, v2 widens task statuses, v3 adds task-owned// Inspector Activity persistence, and v4 adds durable Hook delivery and// finalize journals. All apply on a fresh DB.- expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4])+ expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5])const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table'")diff --git a/src/core/session/migrations/v3.test.ts b/src/core/session/migrations/v3.test.tsindex 5d16e105..c974adc8 100644--- a/src/core/session/migrations/v3.test.ts+++ b/src/core/session/migrations/v3.test.ts@@ -110,7 +110,7 @@ describe('migration v3 compatibility', () => {const db = openMemory()migrate(db)- expect(readVersion(db)).toBe(4)+ expect(readVersion(db)).toBe(5)const names = db.prepare(`SELECT name FROM sqlite_master@@ -166,7 +166,7 @@ describe('migration v3 compatibility', () => {const reopened = new Database(dbPath)reopened.pragma('foreign_keys = ON')- expect(readVersion(reopened)).toBe(4)+ expect(readVersion(reopened)).toBe(5)expect(reopened.prepare("SELECT motrix_id FROM tasks WHERE motrix_id = 'survivor'")@@ -207,7 +207,7 @@ describe('migration v3 compatibility', () => {})()expect(() => migrate(db)).not.toThrow()- expect(readVersion(db)).toBe(4)+ expect(readVersion(db)).toBe(5)db.close()})diff --git a/src/core/session/migrations/v4.test.ts b/src/core/session/migrations/v4.test.tsindex f74a4a9b..64e8f699 100644--- a/src/core/session/migrations/v4.test.ts+++ b/src/core/session/migrations/v4.test.ts@@ -40,7 +40,7 @@ describe('migration v4', () => {const db = openMemory()migrate(db)- expect(readVersion(db)).toBe(4)+ expect(readVersion(db)).toBe(5)const rows = db.prepare(`SELECT name FROM sqlite_master@@ -68,7 +68,7 @@ describe('migration v4', () => {migrate(db)- expect(readVersion(db)).toBe(4)+ expect(readVersion(db)).toBe(5)expect(db.prepare("SELECT name FROM tasks WHERE motrix_id = 'survivor'").get()).toEqual({ name: 'fixture' })diff --git a/src/core/session/migrations/v5.test.ts b/src/core/session/migrations/v5.test.tsnew file mode 100644index 00000000..b57b419b--- /dev/null+++ b/src/core/session/migrations/v5.test.ts@@ -0,0 +1,117 @@+import { TaskStatus, TransitionPhase } from '@shared/types/task'+import Database from 'better-sqlite3'+import { describe, expect, it } from 'vitest'+import { migrate } from '.'+import { v1 } from './v1'+import { v2 } from './v2'+import { v3 } from './v3'+import { v4 } from './v4'++function createV4(): Database.Database {+ const db = new Database(':memory:')+ db.exec(`CREATE TABLE schema_version (+ version INTEGER PRIMARY KEY,+ applied_at INTEGER NOT NULL+ )`)+ for (const migration of [v1, v2, v3, v4]) {+ migration.up(db)+ db.prepare('INSERT INTO schema_version VALUES (?, 1)').run(+ migration.version+ )+ }+ return db+}++describe('task recovery migration v5', () => {+ it('upgrades existing tasks and recovers the original root from their journal', () => {+ const db = createV4()+ db.exec(`INSERT INTO tasks (motrix_id, name, task_type, created_at, updated_at, final_path)+ VALUES ('interrupted', 'movie', 'bt', 1, 1, '/downloads/Movies/movie'),+ ('legacy', 'file', 'http', 1, 1, '/downloads/file')`)+ db.prepare(`INSERT INTO plugin_finalize_journals+ (plan_id, task_id, phase, plan_json, source_identity_json, created_at, updated_at)+ VALUES ('plan', 'interrupted', 'prepared', ?, '{}', 1, 1)`).run(+ JSON.stringify({+ saveDir: '/downloads',+ targetPath: '/downloads/Movies/movie',+ })+ )+ migrate(db)+ expect(+ db+ .prepare('SELECT save_dir FROM tasks WHERE motrix_id = ?')+ .get('interrupted')+ ).toEqual({ save_dir: '/downloads' })+ expect(+ db.prepare('SELECT save_dir FROM tasks WHERE motrix_id = ?').get('legacy')+ ).toEqual({ save_dir: null })+ expect(() => migrate(db)).not.toThrow()+ expect(db.prepare('SELECT COUNT(*) AS n FROM tasks').get()).toEqual({+ n: 2,+ })+ db.close()+ })++ it('repairs only terminal instance statuses, preserving recovery intent and event history', () => {+ const db = createV4()+ const insertTask = db.prepare(`INSERT INTO tasks+ (motrix_id, name, task_type, created_at, updated_at, final_path,+ agg_status, finished_at, error_message, diagnosis_revision)+ VALUES (?, 'output', 'http', 1000, 2000, '/downloads/category/output', ?, 3000, 'retained detail', 4)`)+ const insertInstance = db.prepare(`INSERT INTO task_instances+ (instance_id, motrix_id, gid, phase, status, progress, disk_path,+ transition_phase, payload, created_at, updated_at)+ VALUES (?, ?, ?, 'http_download', ?, 42, '/downloads/output.motrix', ?, '{"retained":true}', 1000, 2000)`)+ for (const status of Object.values(TaskStatus)) {+ insertTask.run(status, status)+ for (const [index, phase] of Object.values(TransitionPhase).entries()) {+ insertInstance.run(+ `${status}-${index}`,+ status,+ `gid-${status}-${index}`,+ [TaskStatus.Queued, TaskStatus.Downloading, status][index],+ phase+ )+ }+ }+ const tasksBefore = db+ .prepare('SELECT * FROM tasks ORDER BY motrix_id')+ .all()+ const readInstances = db.prepare(+ 'SELECT * FROM task_instances ORDER BY instance_id'+ )+ const instancesBefore = readInstances.all() as Array<{+ motrix_id: TaskStatus+ status: TaskStatus+ }>++ migrate(db)++ expect(readInstances.all()).toEqual(+ instancesBefore.map((entry) => ({+ ...entry,+ status:+ entry.motrix_id === TaskStatus.Error ||+ entry.motrix_id === TaskStatus.Completed+ ? entry.motrix_id+ : entry.status,+ }))+ )+ expect(db.prepare('SELECT * FROM tasks ORDER BY motrix_id').all()).toEqual(+ tasksBefore.map((entry) => ({ ...(entry as object), save_dir: null }))+ )+ expect(+ db.prepare('SELECT COUNT(*) AS count FROM task_occurrences').get()+ ).toEqual({ count: 0 })+ expect(+ db.prepare('SELECT COUNT(*) AS count FROM plugin_post_deliveries').get()+ ).toEqual({ count: 0 })+ const changes = db.prepare('SELECT total_changes() AS count').get()+ migrate(db)+ expect(db.prepare('SELECT total_changes() AS count').get()).toEqual(changes)+ expect(+ db.prepare('SELECT version FROM schema_version ORDER BY version').all()+ ).toEqual([1, 2, 3, 4, 5].map((version) => ({ version })))+ db.close()+ })+})diff --git a/src/core/session/migrations/v5.ts b/src/core/session/migrations/v5.tsnew file mode 100644index 00000000..22a49da0--- /dev/null+++ b/src/core/session/migrations/v5.ts@@ -0,0 +1,34 @@+import type Database from 'better-sqlite3'+import { V2_TASK_SCHEMA_OBJECTS } from './v2'++// ALTER TABLE preserves the existing DDL and inserts the new column before+// its closing parenthesis. Keep validation compatible with upgraded databases.+export const V5_TASK_SCHEMA_OBJECTS = V2_TASK_SCHEMA_OBJECTS.map((object) =>+ object.name === 'tasks'+ ? { ...object, sql: object.sql.replace(/\)\s*$/, ', save_dir TEXT)') }+ : object+)++export const v5 = {+ version: 5,+ up(db: Database.Database): void {+ db.exec('ALTER TABLE tasks ADD COLUMN save_dir TEXT')+ // Existing finalize journals retain the original root even when a plugin+ // chose a nested target. Other legacy rows are reconstructed on restore.+ db.exec(`UPDATE tasks SET save_dir = (+ SELECT json_extract(plan_json, '$.saveDir')+ FROM plugin_finalize_journals WHERE task_id = tasks.motrix_id+ AND json_type(plan_json, '$.saveDir') = 'text'+ )`)+ // Older engine polling committed terminal parents with stale instances.+ // Repair only status, before restore or write-signature caches are built;+ // recovery intent and occurrence history remain unchanged.+ db.exec(`UPDATE task_instances SET status = (+ SELECT agg_status FROM tasks WHERE motrix_id = task_instances.motrix_id+ ) WHERE EXISTS (+ SELECT 1 FROM tasks WHERE motrix_id = task_instances.motrix_id+ AND agg_status IN ('error', 'completed')+ AND agg_status <> task_instances.status+ )`)+ },+}diff --git a/src/core/session/motrix-database.test.ts b/src/core/session/motrix-database.test.tsindex 6b57638a..f2b65544 100644--- a/src/core/session/motrix-database.test.ts+++ b/src/core/session/motrix-database.test.ts@@ -33,6 +33,8 @@ describe('saveTaskWithInstances + getAllTasks (Plan A v1 schema)', () => {taskRow.aggStatus = TaskStatus.DownloadingtaskRow.totalBytes = 1000taskRow.downloadedBytes = 500+ taskRow.saveDir = '/tmp/downloads'+ taskRow.finalPath = '/tmp/downloads/Movies/video.mp4'const instance: TaskInstanceRow = {...makeInstanceRow('i-1', 'm-1', 'g-1', TaskInstancePhase.HttpDownload),@@ -52,6 +54,8 @@ describe('saveTaskWithInstances + getAllTasks (Plan A v1 schema)', () => {expect(loaded[0].task.motrixId).toBe('m-1')expect(loaded[0].task.kind).toBe(TaskKind.Direct)expect(loaded[0].task.aggStatus).toBe(TaskStatus.Downloading)+ expect(loaded[0].task.saveDir).toBe('/tmp/downloads')+ expect(loaded[0].task.finalPath).toBe('/tmp/downloads/Movies/video.mp4')expect(loaded[0].instances).toHaveLength(1)expect(loaded[0].instances[0].gid).toBe('g-1')expect(loaded[0].instances[0].phase).toBe(TaskInstancePhase.HttpDownload)@@ -62,6 +66,19 @@ describe('saveTaskWithInstances + getAllTasks (Plan A v1 schema)', () => {db.close()})+ it('retains the saved directory when an older writer updates task state', () => {+ const db = new MotrixDatabase(':memory:')+ db.init()+ const task = makeTaskRow('m-save-root', TaskKind.Direct)+ db.saveTaskWithInstances({+ task: { ...task, saveDir: '/tmp/downloads' },+ instances: [],+ })+ db.saveTaskWithInstances({ task, instances: [] })+ expect(db.getTask(task.motrixId)?.task.saveDir).toBe('/tmp/downloads')+ db.close()+ })+it('commits an initial task and beforeCreate metadata atomically', () => {const db = new MotrixDatabase(':memory:')db.init()diff --git a/src/core/session/motrix-database.ts b/src/core/session/motrix-database.tsindex 45d1436c..c5122bbc 100644--- a/src/core/session/motrix-database.ts+++ b/src/core/session/motrix-database.ts@@ -124,6 +124,8 @@ export const NOTIFICATION_LIST_LIMIT = 100* status. Does NOT carry any engine GID or per-instance progress; those* live in TaskInstanceRow. */export interface TaskRow {+ /** Missing on legacy rows until their save directory is reconstructed. */+ saveDir?: string | nullmotrixId: stringname: stringkind: TaskKind@@ -307,7 +309,7 @@ export class MotrixDatabase {const TASK_COLS = `motrix_id, name, kind, task_type, category, priority, tags,created_at, updated_at,- final_path, final_name, torrent_meta_path,+ save_dir, final_path, final_name, torrent_meta_path,info_hash, total_bytes, downloaded_bytes, size_when_done, file_count,is_private, trackers, piece_length,agg_status, finished_at, error_message, error_code,@@ -325,7 +327,7 @@ export class MotrixDatabase {INSERT INTO tasks (motrix_id, name, kind, task_type, category, priority, tags,created_at, updated_at,- final_path, final_name, torrent_meta_path,+ save_dir, final_path, final_name, torrent_meta_path,info_hash, total_bytes, downloaded_bytes, size_when_done, file_count,is_private, trackers, piece_length,agg_status, finished_at, error_message, error_code,@@ -334,7 +336,7 @@ export class MotrixDatabase {) VALUES (@motrixId, @name, @kind, @taskType, @category, @priority, @tags,@createdAt, @updatedAt,- @finalPath, @finalName, @torrentMetaPath,+ @saveDir, @finalPath, @finalName, @torrentMetaPath,@infoHash, @totalBytes, @downloadedBytes, @sizeWhenDone, @fileCount,@isPrivate, @trackers, @pieceLength,@aggStatus, @finishedAt, @errorMessage, @errorCode,@@ -349,6 +351,7 @@ export class MotrixDatabase {priority = @priority,tags = @tags,updated_at = @updatedAt,+ save_dir = COALESCE(@saveDir, tasks.save_dir),final_path = @finalPath,final_name = @finalName,torrent_meta_path = @torrentMetaPath,@@ -1286,6 +1289,7 @@ export class MotrixDatabase {tags: t.tags,createdAt: t.createdAt,updatedAt: t.updatedAt,+ saveDir: t.saveDir || null,finalPath: t.finalPath,finalName: t.finalName,torrentMetaPath: t.torrentMetaPath,@@ -1353,6 +1357,7 @@ export class MotrixDatabase {}interface RawTaskRow {+ save_dir: string | nullmotrix_id: stringname: stringkind: string@@ -1429,6 +1434,7 @@ function mapTaskRow(row: RawTaskRow): TaskRow {tags: row.tags,createdAt: row.created_at,updatedAt: row.updated_at,+ saveDir: row.save_dir,finalPath: row.final_path,finalName: row.final_name,torrentMetaPath: row.torrent_meta_path,diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex b404c5a3..674a64e8 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -19,8 +19,15 @@ import type { Aria2RpcClient } from '../engine/aria2/aria2-rpc-client'import type { Aria2RawStatus } from '../engine/aria2/types'import type { EngineAdapter } from '../engine/engine-adapter'import { DIRECT_RESOURCE_METADATA_PROFILE } from '../engine/engine-adapter'+import { assertValidHookPlan } from '../plugin/finalize/hook-plan'import { clearStoppedTasks } from '../task/actions/clear-stopped-tasks'import { stopSeedingTask } from '../task/actions/stop-seeding-task'+import {+ btStoragePayload,+ createBtStoragePlan,+ getBtPayloadPath,+ parseBtFileLayout,+} from '../task/bt-storage-layout'import { TaskManager } from '../task/task-manager'import { computeUriHash } from './content-key'import type {@@ -2770,7 +2777,7 @@ describe('SessionManager', () => {.getAll().find((t) => t.id === 'm-legacy-completed')expect(restored?.diskPath).toBe('/dl/movie-final.mkv')- expect(restored?.saveDir).toBe('/dl/movie-final.mkv')+ expect(restored?.saveDir).toBe('/dl')// Instances heal too, so the next save() rewrites the DB row and// the stale placeholder is gone for good.expect(restored?.instances[0]?.diskPath).toBe('/dl/movie-final.mkv')@@ -4187,3 +4194,123 @@ describe('restore() with task_instances (Plan A Task 7)', () => {expect(adapter.addTorrent).not.toHaveBeenCalled()})})++describe('restore save directories after interrupted finalization', () => {+ for (const enginePresent of [true, false]) {+ for (const status of [TaskStatus.Finalizing, TaskStatus.Error]) {+ it(`restores the BT root and payload with engine=${enginePresent}, status=${status}`, async () => {+ const tm = new TaskManager()+ const db = createMockDb()+ const rpc = createMockRpc()+ const sm = new SessionManager(tm, rpc, db, createMockAdapter())+ const saveDir = path.join(os.tmpdir(), 'motrix-restore-downloads')+ const finalPath = path.join(saveDir, 'Movies', 'movie.mkv')+ const { layout } = createBtStoragePlan('interrupted-bt', saveDir, {+ infoHash: 'a'.repeat(40),+ torrentRootName: 'movie.mkv',+ multiFile: false,+ isPrivate: false,+ files: [{ fileIndex: 0, pathInsideRoot: null }],+ })+ seedAsPair(db, {+ motrixId: 'interrupted-bt',+ gid: 'bt-gid',+ status,+ type: TaskType.Bt,+ diskPath: layout.workspacePath,+ finalPath,+ transitionPhase: TransitionPhase.Renaming,+ payload: btStoragePayload(layout),+ })+ if (enginePresent)+ rpc.tellActive = vi.fn(async () => [+ createRawStatus({+ gid: 'bt-gid',+ dir: layout.workspacePath,+ status: 'active',+ }),+ ])+ await sm.restore()+ const task = tm.getById('interrupted-bt')!+ expect(task.saveDir).toBe(saveDir)+ expect(getBtPayloadPath(task)).toBe(+ path.join(layout.workspacePath, 'p')+ )+ expect(() =>+ assertValidHookPlan({+ planId: 'plan',+ taskId: task.id,+ saveDir: task.saveDir,+ sourcePath: getBtPayloadPath(task)!,+ targetPath: task.finalPath,+ sourceIdentity: {+ kind: 'file',+ size: 1,+ sha256: 'a'.repeat(64),+ platformFileId: '1:1',+ },+ metadataOps: [],+ contributors: [],+ })+ ).not.toThrow()+ await sm.save()+ expect(db.getTask(task.id)?.task.saveDir).toBe(saveDir)+ })+ }+ }++ it('restores an unfinished HTTP file under its saving directory', async () => {+ const tm = new TaskManager()+ const db = createMockDb()+ const sm = new SessionManager(tm, createMockRpc(), db, createMockAdapter())+ const root = path.join(os.tmpdir(), 'http-save')+ seedAsPair(db, {+ motrixId: 'http-finalize',+ gid: null,+ type: TaskType.Http,+ status: TaskStatus.Finalizing,+ transitionPhase: TransitionPhase.Renaming,+ diskPath: path.join(root, 'file.zip.motrix'),+ finalPath: path.join(root, 'file.zip'),+ })+ await sm.restore()+ expect(tm.getById('http-finalize')?.saveDir).toBe(root)+ })+})++it('re-adds an interrupted indexed BT download with its original payload mapping', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'motrix-readd-layout-'))+ try {+ const bytes = buildSingleFileTorrent('movie.mkv')+ const metadata = path.join(root, 'source.torrent')+ fs.writeFileSync(metadata, bytes)+ const parsed = await parseBtFileLayout(bytes)+ const plan = createBtStoragePlan('readd-layout', root, parsed)+ const tm = new TaskManager()+ const db = createMockDb()+ const adapter = createMockAdapter()+ seedAsPair(db, {+ motrixId: 'readd-layout',+ gid: 'old-gid',+ type: TaskType.Bt,+ status: TaskStatus.Paused,+ infoHash: parsed.infoHash,+ torrentMetaPath: metadata,+ diskPath: plan.layout.workspacePath,+ finalPath: path.join(root, 'movie.mkv'),+ payload: btStoragePayload(plan.layout),+ })+ await new SessionManager(tm, createMockRpc(), db, adapter).restore()+ expect(adapter.addTorrent).toHaveBeenCalledWith(+ expect.objectContaining({+ saveDir: plan.layout.workspacePath,+ outputFilePaths: [{ fileIndex: 0, relativePath: 'p' }],+ pause: true,+ checkIntegrity: true,+ })+ )+ expect(tm.getById('readd-layout')?.saveDir).toBe(root)+ } finally {+ fs.rmSync(root, { recursive: true, force: true })+ }+})diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.tsindex e5feda4e..81051546 100644--- a/src/core/session/session-manager.ts+++ b/src/core/session/session-manager.ts@@ -47,7 +47,13 @@ import {applyTerminalTransition,terminalFieldsFromRow,} from '../task/apply-terminal-transition'-import { shouldPrioritizeBtPreviewPiecesFromMetadata } from '../task/bt-storage-layout'+import {+ buildFinalOutputFilePaths,+ buildStagingOutputFilePaths,+ getBtStorageLayout,+ parseBtFileLayout,+ shouldPrioritizeBtPreviewPiecesFromMetadata,+} from '../task/bt-storage-layout'import { isCompletedDirectOutput } from '../task/completed-direct-task-policy'import {canMirrorAria2MetadataHeaders,@@ -58,6 +64,7 @@ import { isTempPath } from '../task/paths'import { setTaskTransitionPhase } from '../task/task-instance'import type { TaskManager } from '../task/task-manager'import { taskRowToDownloadTask } from '../task/task-row-to-download-task'+import { restoreTaskSaveDirectory } from '../task/task-save-directory'import { isMagnetCleanupTombstoneHidden } from '../torrent/magnet-cleanup-quarantine'import { computeUriHash, deriveInfoHash } from './content-key'import { DirectRecoveryPlanner } from './direct-recovery-planner'@@ -558,6 +565,7 @@ export class SessionManager {tags: null,createdAt: task.createdAt,updatedAt: task.updatedAt,+ saveDir: task.saveDir,finalPath: task.finalPath,finalName: task.finalName,torrentMetaPath: task.torrentMetaPath,@@ -935,7 +943,6 @@ export class SessionManager {task.finalPath) {task.diskPath = task.finalPath- task.saveDir = task.finalPathfor (const inst of task.instances) {inst.diskPath = task.finalPath}@@ -1301,7 +1308,7 @@ export class SessionManager {String(downloadedBytes),aria2.downloadSpeed),- saveDir: aria2.dir,+ saveDir: restoreTaskSaveDirectory(taskPart, pair.instances, aria2.dir),createdAt: taskPart.createdAt,updatedAt: now,uris: extractUris(aria2),@@ -1388,7 +1395,7 @@ export class SessionManager {downloadSpeed: 0,uploadSpeed: 0,etaSeconds: 0,- saveDir: primary?.diskPath || taskPart.finalPath || '',+ saveDir: restoreTaskSaveDirectory(taskPart, pair.instances),createdAt: taskPart.createdAt,updatedAt: retainedIdentity ? taskPart.updatedAt : now,uris: primary?.uris ?? [],@@ -1450,11 +1457,30 @@ export class SessionManager {const bytes = fs.readFileSync(taskPart.torrentMetaPath)const prioritizePreviewPieces =await shouldPrioritizeBtPreviewPiecesFromMetadata(bytes)+ const restored = taskRowToDownloadTask(taskPart, pair.instances)+ const layout = getBtStorageLayout(restored)+ const parsed = layout ? await parseBtFileLayout(bytes) : null+ const alreadyRenamed = restored.diskPath === restored.finalPathreturn this.dispatchRecoveryCandidate(pair, (gid) =>this.adapter.addTorrent({metadata: bytes,gid,- saveDir: primary?.diskPath || taskPart.finalPath || '/',+ saveDir: layout+ ? alreadyRenamed+ ? path.dirname(restored.finalPath)+ : layout.workspacePath+ : primary?.diskPath || restored.saveDir || '/',+ ...(layout && parsed+ ? {+ outputFilePaths: alreadyRenamed+ ? buildFinalOutputFilePaths(+ parsed,+ restored.finalPath,+ layout+ )+ : buildStagingOutputFilePaths(parsed, layout),+ }+ : {}),pause: taskPart.aggStatus === TaskStatus.Paused,checkIntegrity: true,...(prioritizePreviewPiecesdiff --git a/src/core/task/lifecycle-persistence.test.ts b/src/core/task/lifecycle-persistence.test.tsindex 9f578dce..27629d78 100644--- a/src/core/task/lifecycle-persistence.test.ts+++ b/src/core/task/lifecycle-persistence.test.ts@@ -16,6 +16,7 @@ import {import { makeDownloadTask } from '@test-utils/task'import { afterEach, describe, expect, it, vi } from 'vitest'import { type FinalizeTaskDeps, finalizeTask } from './actions/finalize-task'+import { commitPolledTerminalTransition } from './actions/shared'import { TaskManager } from './task-manager'import {type RecoveryDeps,@@ -159,12 +160,10 @@ async function restoreFromDatabase(tellWaiting: vi.fn(async () => []),tellStopped: vi.fn(async () => []),} as unknown as Aria2RpcClient- const session = new SessionManager(- restoredTasks,- rpc,- db,- {} as EngineAdapter- )+ const session = new SessionManager(restoredTasks, rpc, db, {+ forceRemoveTask: vi.fn(async () => {}),+ removeDownloadResult: vi.fn(async () => {}),+ } as unknown as EngineAdapter)await session.restore()return restoredTasks}@@ -265,6 +264,137 @@ function makeFinalizeDeps(}}+describe('polled terminal instance persistence', () => {+ it.each(+ [TaskStatus.Error, TaskStatus.Completed].flatMap((status) =>+ [1, 2].flatMap((count) =>+ [false, true].map((enginePresent) => ({ status, count, enginePresent }))+ )+ )+ )(+ 'keeps $count instances in $status across restore (engine present: $enginePresent)',+ async ({ status, count, enginePresent }) => {+ const task = makeSingleInstanceTask({+ diskPath: '/downloads/output',+ instances: Array.from({ length: count }, (_, index) =>+ makeInstance('lifecycle-task', TaskInstancePhase.HttpDownload, {+ instanceId: `instance-${index}`,+ gid: index === 0 ? 'gid-old' : null,+ diskPath: '/downloads/output',+ })+ ),+ })+ const harness = makePersistenceHarness(task)+ await harness.persist(task)+ const candidate = mergeEngineTask(+ task,+ makeSingleInstanceTask({ status }),+ 1_700_000_010_000+ )+ const dispatch = vi.fn(async () => {})+ const outcome = await commitPolledTerminalTransition(+ task.status,+ candidate,+ {+ persistTaskWithOccurrence: (next, occurrence) =>+ harness.sessionManager.persistTaskWithOccurrence(next, occurrence),+ publish: (next) => {+ expect(+ harness.db+ .getTask(task.id)+ ?.instances.map((entry) => entry.status)+ ).toEqual(Array(count).fill(status))+ harness.taskManager.set(next.id, next)+ },+ occurrenceDispatcher: { dispatch },+ log: { warn: vi.fn() },+ }+ )+ expect(outcome).toBe('published')+ expect(dispatch).toHaveBeenCalledOnce()+ const saved = harness.db.getTask(task.id)+ expect(saved?.task.aggStatus).toBe(status)+ expect(saved?.instances).toEqual(+ task.instances.map((entry) => ({ ...entry, status }))+ )++ const restored = await restoreFromDatabase(+ harness.db,+ enginePresent ? [makeRawStatus('gid-old')] : []+ )+ expect(restored.getById(task.id)).toMatchObject({+ status,+ saveDir: '/downloads',+ finishedAt: candidate.finishedAt,+ })+ expect(+ restored.getById(task.id)?.instances.map((entry) => entry.status)+ ).toEqual(Array(count).fill(status))+ expect(harness.db.getTask(task.id)).toEqual(saved)+ expect(+ harness.db.database+ .prepare('SELECT COUNT(*) AS count FROM task_occurrences')+ .get()+ ).toEqual({ count: 1 })+ }+ )++ it('rolls back the whole terminal graph on an occurrence write failure and retries without mutating live instances', async () => {+ const task = makeSingleInstanceTask()+ const harness = makePersistenceHarness(task)+ await harness.persist(task)+ const before = structuredClone(task)+ const saved = harness.db.getTask(task.id)+ harness.db.database.exec(`CREATE TRIGGER fail_terminal_occurrence+ BEFORE INSERT ON task_occurrences BEGIN+ SELECT RAISE(ABORT, 'simulated occurrence write failure');+ END`)+ const publish = vi.fn((next: DownloadTask) =>+ harness.taskManager.set(next.id, next)+ )+ const dispatch = vi.fn(async () => {})+ const deps = {+ persistTaskWithOccurrence:+ harness.sessionManager.persistTaskWithOccurrence.bind(+ harness.sessionManager+ ),+ publish,+ occurrenceDispatcher: { dispatch },+ log: { warn: vi.fn() },+ }+ const observeError = () =>+ mergeEngineTask(+ task,+ makeSingleInstanceTask({ status: TaskStatus.Error }),+ 1_700_000_010_000+ )++ expect(+ await commitPolledTerminalTransition(task.status, observeError(), deps)+ ).toBe('persist-failed')+ expect(harness.taskManager.getById(task.id)).toEqual(before)+ expect(harness.db.getTask(task.id)).toEqual(saved)+ expect(publish).not.toHaveBeenCalled()+ expect(dispatch).not.toHaveBeenCalled()+ expect(+ harness.db.database+ .prepare('SELECT COUNT(*) AS count FROM task_occurrences')+ .get()+ ).toEqual({ count: 0 })++ harness.db.database.exec('DROP TRIGGER fail_terminal_occurrence')+ expect(+ await commitPolledTerminalTransition(task.status, observeError(), deps)+ ).toBe('published')+ expect(harness.db.getTask(task.id)?.instances[0].status).toBe(+ TaskStatus.Error+ )+ expect(publish).toHaveBeenCalledOnce()+ expect(dispatch).toHaveBeenCalledOnce()+ expect(task).toEqual(before)+ })+})+describe('lifecycle canonical persistence round trips', () => {it('restores the HTTP pre-rename intent persisted before a simulated crash', async () => {const task = makeSingleInstanceTask()diff --git a/src/core/task/merge-engine-task.test.ts b/src/core/task/merge-engine-task.test.tsindex 1ca674b2..940e99c5 100644--- a/src/core/task/merge-engine-task.test.ts+++ b/src/core/task/merge-engine-task.test.ts@@ -1,6 +1,10 @@import { DownloadErrorCode } from '@shared/errors'-import type { DownloadTask } from '@shared/types/task'-import { TaskStatus, TransitionPhase } from '@shared/types/task'+import type { DownloadTask, TaskInstance } from '@shared/types/task'+import {+ TaskInstancePhase,+ TaskStatus,+ TransitionPhase,+} from '@shared/types/task'import { makeDownloadTask } from '@test-utils/task'import { describe, expect, it } from 'vitest'import { mergeEngineTask } from './merge-engine-task'@@ -8,7 +12,88 @@ import { mergeEngineTask } from './merge-engine-task'const baseTask = (over: Partial<DownloadTask> = {}): DownloadTask =>makeDownloadTask({ id: 't1', engineTaskId: 'gid1', name: 'a', ...over })+function instance(status: TaskStatus, index = 0): TaskInstance {+ return {+ instanceId: `instance-${index}`,+ motrixId: 't1',+ gid: index === 0 ? 'gid1' : null,+ phase: TaskInstancePhase.HttpDownload,+ status,+ progress: 25,+ totalBytes: 100,+ downloadedBytes: 25,+ uploadedBytes: 0,+ diskPath: '/downloads/a.motrix',+ transitionPhase: TransitionPhase.Idle,+ uris: ['https://example.com/a'],+ uriHash: null,+ payload: { fileIndex: index },+ createdAt: 1000,+ updatedAt: 2000,+ }+}+describe('mergeEngineTask', () => {+ it.each(+ [TaskStatus.Queued, TaskStatus.Downloading].flatMap((from) =>+ [TaskStatus.Error, TaskStatus.Completed].flatMap((to) =>+ [1, 2].map((count) => ({ from, to, count }))+ )+ )+ )(+ 'synchronizes $count instances for $from → $to without changing the input',+ ({ from, to, count }) => {+ const existing = baseTask({+ status: from,+ instances: Array.from({ length: count }, (_, i) => instance(from, i)),+ })+ const before = structuredClone(existing)+ for (const entry of existing.instances) Object.freeze(entry)+ Object.freeze(existing.instances)+ Object.freeze(existing)++ const merged = mergeEngineTask(existing, baseTask({ status: to }), 5000)++ expect(merged.status).toBe(to)+ expect(merged.instances).toEqual(+ before.instances.map((entry) => ({ ...entry, status: to }))+ )+ expect(existing).toEqual(before)+ expect(merged.instances).not.toBe(existing.instances)+ }+ )++ it.each([TransitionPhase.Renaming, TransitionPhase.Reseeding])(+ 'keeps instance states while %s owns the terminal transition',+ (phase) => {+ const existing = baseTask({+ status: TaskStatus.Finalizing,+ transitionPhase: phase,+ instances: [+ { ...instance(TaskStatus.Finalizing), transitionPhase: phase },+ ],+ })+ const merged = mergeEngineTask(+ existing,+ baseTask({ status: TaskStatus.Completed })+ )+ expect(merged.status).toBe(TaskStatus.Finalizing)+ expect(merged.instances).toEqual(existing.instances)+ }+ )++ it.each([TaskStatus.Paused, TaskStatus.Seeding])(+ 'leaves per-instance state intact for a nonterminal %s snapshot',+ (status) => {+ const existing = baseTask({+ instances: [instance(TaskStatus.Downloading)],+ })+ expect(mergeEngineTask(existing, baseTask({ status })).instances).toEqual(+ existing.instances+ )+ }+ )+it('preserves existing totalBytes when engine reports zero', () => {const existing = baseTask({totalBytes: 1_000_000,diff --git a/src/core/task/merge-engine-task.ts b/src/core/task/merge-engine-task.tsindex 5f2849d1..4b08e721 100644--- a/src/core/task/merge-engine-task.ts+++ b/src/core/task/merge-engine-task.ts@@ -1,8 +1,9 @@import type { DownloadTask } from '@shared/types/task'-import { TransitionPhase } from '@shared/types/task'+import { TaskStatus, TransitionPhase } from '@shared/types/task'import { applyTerminalTransition } from './apply-terminal-transition'import { isCompletedDirectOutput } from './completed-direct-task-policy'import { nonZeroMerge } from './non-zero-merge'+import { syncTerminalInstanceStatus } from './task-instance'/*** Pure merge; this module never persists and never builds an occurrence.@@ -60,7 +61,7 @@ export function mergeEngineTask(},now)- return {+ const merged: DownloadTask = {...existing,...terminalFields,progress,@@ -80,6 +81,15 @@ export function mergeEngineTask(bt: protected_.bt ?? existing.bt,updatedAt: now,}+ if (+ merged.status === TaskStatus.Completed ||+ merged.status === TaskStatus.Error+ ) {+ // The candidate must not mutate live instances before persistence succeeds.+ merged.instances = existing.instances.map((instance) => ({ ...instance }))+ syncTerminalInstanceStatus(merged, merged.status)+ }+ return merged}export function hasEngineTaskDelta(diff --git a/src/core/task/task-row-to-download-task.test.ts b/src/core/task/task-row-to-download-task.test.tsindex cd2ad445..028af18f 100644--- a/src/core/task/task-row-to-download-task.test.ts+++ b/src/core/task/task-row-to-download-task.test.ts@@ -8,6 +8,7 @@ import {TransitionPhase,} from '@shared/types/task'import { describe, expect, it } from 'vitest'+import { btStoragePayload, createBtStoragePlan } from './bt-storage-layout'import { taskRowToDownloadTask } from './task-row-to-download-task'function makeTaskRow(overrides: Partial<TaskRow> = {}): TaskRow {@@ -122,3 +123,58 @@ describe('taskRowToDownloadTask', () => {})})})++describe('persisted save directory', () => {+ it('recovers the root from an older BT staging container before publication', () => {+ const task = taskRowToDownloadTask(+ makeTaskRow({ finalPath: '/Downloads/Movies/video' }),+ [makeInstance(TaskInstancePhase.BtDownload)]+ )+ expect(task.saveDir).toBe('/Downloads')+ })++ it('recovers the legacy root after a BT artifact moved into a plugin subdirectory', () => {+ const plan = createBtStoragePlan('t1', '/Downloads', {+ infoHash: 'a'.repeat(40),+ torrentRootName: 'video',+ multiFile: false,+ isPrivate: false,+ files: [{ fileIndex: 0, pathInsideRoot: null }],+ })+ const finalPath = '/Downloads/Movies/video'+ const task = taskRowToDownloadTask(+ makeTaskRow({ finalPath, aggStatus: TaskStatus.Completed }),+ [+ {+ ...makeInstance(TaskInstancePhase.BtDownload),+ diskPath: finalPath,+ payload: btStoragePayload(plan.layout),+ },+ ]+ )+ expect(task.saveDir).toBe('/Downloads')+ expect(task.diskPath).toBe(finalPath)+ })++ it('preserves the selected root independently of a plugin-selected final path', () => {+ const task = taskRowToDownloadTask(+ makeTaskRow({+ saveDir: '/Downloads',+ finalPath: '/Downloads/Movies/video',+ }),+ [makeInstance(TaskInstancePhase.BtDownload)]+ )+ expect(task.saveDir).toBe('/Downloads')+ })++ it('keeps the directory stored in a legacy metadata-only magnet task', () => {+ const task = taskRowToDownloadTask(+ makeTaskRow({+ taskType: TaskType.Magnet,+ finalPath: '/Downloads',+ }),+ [makeInstance(TaskInstancePhase.MagnetMetadataResolution)]+ )+ expect(task.saveDir).toBe('/Downloads')+ })+})diff --git a/src/core/task/task-row-to-download-task.ts b/src/core/task/task-row-to-download-task.tsindex ef789add..6c903c55 100644--- a/src/core/task/task-row-to-download-task.ts+++ b/src/core/task/task-row-to-download-task.ts@@ -6,6 +6,7 @@ import {TransitionPhase,} from '@shared/types/task'import { isTorrentLikeType } from '@shared/types/task-actions'+import { restoreTaskSaveDirectory } from './task-save-directory'/** Build a generic DownloadTask domain object from canonical TaskRow data.*@@ -48,7 +49,7 @@ export function taskRowToDownloadTask(downloadSpeed: 0,uploadSpeed: 0,etaSeconds: 0,- saveDir: primary?.diskPath || task.finalPath,+ saveDir: restoreTaskSaveDirectory(task, instances),createdAt: task.createdAt,updatedAt: task.updatedAt,finishedAt: task.finishedAt,diff --git a/src/core/task/task-save-directory.ts b/src/core/task/task-save-directory.tsnew file mode 100644index 00000000..bf808ae7--- /dev/null+++ b/src/core/task/task-save-directory.ts@@ -0,0 +1,59 @@+import path from 'node:path'+import type { TaskInstanceRow, TaskRow } from '@core/session/motrix-database'+import { TaskInstancePhase } from '@shared/types/task'+import { isTorrentLikeType } from '@shared/types/task-actions'+import { btWorkspacePath, getBtStorageLayout } from './bt-storage-layout'++/** Restore the user-selected root, independently of engine and output paths. */+export function restoreTaskSaveDirectory(+ task: TaskRow,+ instances: readonly TaskInstanceRow[],+ engineDirectory?: string+): string {+ if (task.saveDir && path.isAbsolute(task.saveDir)) return task.saveDir+ const primary = instances[0]+ if (isTorrentLikeType(task.taskType)) {+ // In-flight instances point at the workspace; completed instances retain+ // its layout even after diskPath has moved to a plugin-selected target.+ const workspaces = [primary?.diskPath, engineDirectory]+ for (const instance of instances) {+ const layout = instance.payload.btStorageLayout+ if (layout && typeof layout === 'object' && 'workspacePath' in layout) {+ const workspace = layout.workspacePath+ if (typeof workspace === 'string') workspaces.push(workspace)+ }+ }+ for (const workspace of workspaces) {+ if (!workspace || !path.isAbsolute(workspace)) continue+ const root = path.dirname(path.dirname(workspace))+ if (+ path.resolve(btWorkspacePath(task.motrixId, root)) !==+ path.resolve(workspace)+ )+ continue+ if (+ workspace === primary?.diskPath ||+ workspace === engineDirectory ||+ getBtStorageLayout({+ saveDir: root,+ diskPath: primary?.diskPath ?? '',+ finalPath: task.finalPath,+ instances: [...instances],+ })+ )+ return root+ }+ // Before metadata resolution finalPath is the selected directory itself.+ if (primary?.phase === TaskInstancePhase.MagnetMetadataResolution) {+ return task.finalPath || engineDirectory || ''+ }+ }+ if (engineDirectory && path.isAbsolute(engineDirectory))+ return engineDirectory+ const output =+ primary?.phase === TaskInstancePhase.HttpDownload ||+ primary?.phase === TaskInstancePhase.BtDownload+ ? primary.diskPath || task.finalPath+ : task.finalPath || primary?.diskPath+ return output ? path.dirname(output) : ''+}diff --git a/src/core/torrent/magnet-tracker.ts b/src/core/torrent/magnet-tracker.tsindex 7cb1695f..ace1c582 100644--- a/src/core/torrent/magnet-tracker.ts+++ b/src/core/torrent/magnet-tracker.ts@@ -505,6 +505,7 @@ export class MagnetTracker {tags: null,createdAt: now,updatedAt: now,+ saveDir,finalPath: saveDir,finalName: '',torrentMetaPath: null,diff --git a/src/core/torrent/swap-magnet-metadata-for-bt.atomicity.test.ts b/src/core/torrent/swap-magnet-metadata-for-bt.atomicity.test.tsindex b2a5fd9a..b79f4347 100644--- a/src/core/torrent/swap-magnet-metadata-for-bt.atomicity.test.ts+++ b/src/core/torrent/swap-magnet-metadata-for-bt.atomicity.test.ts@@ -303,6 +303,7 @@ describe('swapMagnetMetadataForBt atomic commit', () => {motrixId: taskId,aggStatus: TaskStatus.Error,taskType: TaskType.Magnet,+ saveDir,finalPath: saveDir,errorMessage: 'Magnet swap cleanup is quarantined',})@@ -684,6 +685,7 @@ function makeMetadataReadyTask(taskId: string, saveDir: string): TaskRow {tags: null,createdAt: 1_700_000_000_000,updatedAt: 1_700_000_000_100,+ saveDir,finalPath: saveDir,finalName: '',torrentMetaPath: null,diff --git a/src/core/torrent/swap-magnet-metadata-for-bt.test.ts b/src/core/torrent/swap-magnet-metadata-for-bt.test.tsindex d07995a6..5d03d7cc 100644--- a/src/core/torrent/swap-magnet-metadata-for-bt.test.ts+++ b/src/core/torrent/swap-magnet-metadata-for-bt.test.ts@@ -1116,15 +1116,18 @@ describe('swapMagnetMetadataForBt', () => {expect(tmTask.type).toBe(TaskType.Bt)})- it('uses indexed short staging after magnet metadata resolves', async () => {+ it('uses indexed staging and persists a changed destination after magnet metadata resolves', async () => {const torrent = buildSingleFileTorrent('very-long-original-name.iso')+ const original = db.getTask('m-mag')+ if (!original) throw new Error('missing fixture')+ original.task.saveDir = '/Downloads'await swapMagnetMetadataForBt({taskId: 'm-mag',base64: Buffer.from(torrent).toString('base64'),selectedFiles: [0],- saveDir: '/Downloads',+ saveDir: '/Selected',name: 'User friendly name.iso',},{@@ -1144,7 +1147,9 @@ describe('swapMagnetMetadataForBt', () => {)const params = adapter.addTorrent.mock.calls[0][0]- expect(params.saveDir).toMatch(/^\/Downloads\/\.motrix\/[a-f0-9]{20}$/)+ expect(params.saveDir).toMatch(/^\/Selected\/\.motrix\/[a-f0-9]{20}$/)+ expect(db.getTask('m-mag')?.task.saveDir).toBe('/Selected')+ expect(taskManager.getById('m-mag')?.saveDir).toBe('/Selected')expect(params.outputFilePaths).toEqual([{ fileIndex: 0, relativePath: 'p' },])diff --git a/src/core/torrent/swap-magnet-metadata-for-bt.ts b/src/core/torrent/swap-magnet-metadata-for-bt.tsindex 3cb57a65..c2df981b 100644--- a/src/core/torrent/swap-magnet-metadata-for-bt.ts+++ b/src/core/torrent/swap-magnet-metadata-for-bt.ts@@ -27,6 +27,7 @@ import type { FinalNamePicker } from '@core/task/final-name-picker'import { toTempPath } from '@core/task/paths'import type { TaskManager } from '@core/task/task-manager'import { taskRowToDownloadTask } from '@core/task/task-row-to-download-task'+import { restoreTaskSaveDirectory } from '@core/task/task-save-directory'import type { TorrentMetaStore } from '@core/task/torrent-meta-store'import { AppError, ErrorCode } from '@shared/errors'import type { TaskCreateSuccessResult } from '@shared/schemas/add-task'@@ -265,6 +266,7 @@ async function swapMagnetMetadataForBtUnderMutation(const previousGraph = {task: {...existing.task,+ saveDir: restoreTaskSaveDirectory(existing.task, existing.instances),torrentMetaPath,},instances: existing.instances,@@ -354,6 +356,7 @@ async function swapMagnetMetadataForBtUnderMutation(// previousGraph (including the original finalPath) when it completes.const reservationTask: TaskRow = {...previousGraph.task,+ saveDir,finalPath: saveDir,updatedAt: now,}@@ -491,6 +494,7 @@ async function swapMagnetMetadataForBtUnderMutation(...existing.task,name: finalName,taskType: TaskType.Bt,+ saveDir,finalPath,finalName,torrentMetaPath,