Skip to content

Commit 6770311

Browse files
committed
fix(build): share artifact ownership across checkout subdirectories
1 parent 54e55e0 commit 6770311

5 files changed

Lines changed: 130 additions & 81 deletions

File tree

‎scripts/lib/dist-artifact-ownership.mts‎

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,16 @@ import { fileURLToPath, pathToFileURL } from "node:url";
55
import { acquireFileLock } from "@openclaw/fs-safe/file-lock";
66
import { root as openLockRoot } from "@openclaw/fs-safe/root";
77
import { isDirectRunUrl } from "./direct-run.mjs";
8+
import { findRepoRoot } from "./repo-root.mjs";
89

9-
export const DIST_ARTIFACT_LOCK_PATH = ".artifacts/dist-artifacts.lock";
10+
const DIST_ARTIFACT_LOCK_PATH = ".artifacts/dist-artifacts.lock";
1011
const LOCK_POLL_MS = 500;
11-
let inheritedOwnershipRoot: string | undefined;
12+
let inheritedOwnershipPath: string | undefined;
1213

13-
function lockPath(rootDir: string) {
14-
return path.join(rootDir, DIST_ARTIFACT_LOCK_PATH);
14+
export function resolveDistArtifactLockPath(rootDir: string) {
15+
// Compiler inputs can resolve outside cwd. Subdirectories share checkout
16+
// ownership; standalone non-checkout work owns its directory.
17+
return path.join(findRepoRoot(rootDir) ?? rootDir, DIST_ARTIFACT_LOCK_PATH);
1518
}
1619

1720
function hasUnjoinedWork(error: unknown): boolean {
@@ -27,39 +30,39 @@ function hasUnjoinedWork(error: unknown): boolean {
2730
return "cause" in error && hasUnjoinedWork(error.cause);
2831
}
2932

30-
function retainUnjoinedDistArtifactWork(rootDir: string, error: unknown) {
33+
function retainUnjoinedDistArtifactWork(directory: string, error: unknown) {
3134
if (hasUnjoinedWork(error)) {
32-
fs.writeFileSync(path.join(lockPath(rootDir), "unjoined"), "Child cleanup was not verified.\n");
35+
fs.writeFileSync(path.join(directory, "unjoined"), "Child cleanup was not verified.\n");
3336
}
3437
}
3538

3639
async function runOwnedDistArtifactEntry(script: string, args: string[]) {
37-
const directory = lockPath(process.cwd());
40+
const directory = resolveDistArtifactLockPath(process.cwd());
3841
const claim = path.join(directory, `child-${process.pid}`);
3942
// A killed nested wrapper cannot certify its detached compiler has joined.
4043
// Its surviving claim keeps the outer owner from releasing on leader exit.
4144
fs.writeFileSync(claim, "Awaiting child completion.\n", { flag: "wx" });
42-
inheritedOwnershipRoot = process.cwd();
45+
inheritedOwnershipPath = directory;
4346
process.argv = [process.execPath, fileURLToPath(script), ...args];
4447
try {
4548
await import(script);
4649
} catch (error) {
47-
retainUnjoinedDistArtifactWork(process.cwd(), error);
50+
retainUnjoinedDistArtifactWork(directory, error);
4851
throw error;
4952
} finally {
50-
inheritedOwnershipRoot = undefined;
53+
inheritedOwnershipPath = undefined;
5154
fs.unlinkSync(claim);
5255
}
5356
}
5457

5558
/** The callback must join every writer/reader before returning, including on failure. */
5659
export async function withDistArtifactOwnership<T>(rootDir: string, run: () => Promise<T>) {
60+
const directory = resolveDistArtifactLockPath(fs.realpathSync(rootDir));
5761
// Only the private child entry can inherit its parent's checkout ownership;
5862
// the same standalone CLI flow runs without reacquiring that parent's lock.
59-
if (rootDir === inheritedOwnershipRoot) {
63+
if (directory === inheritedOwnershipPath) {
6064
return await run();
6165
}
62-
const directory = lockPath(rootDir);
6366
fs.mkdirSync(directory, { recursive: true });
6467
const ownerPath = path.join(directory, "owner.json");
6568
let reportedWait = false;
@@ -108,7 +111,7 @@ export async function withDistArtifactOwnership<T>(rootDir: string, run: () => P
108111
try {
109112
return await run();
110113
} catch (error) {
111-
retainUnjoinedDistArtifactWork(rootDir, error);
114+
retainUnjoinedDistArtifactWork(directory, error);
112115
throw error;
113116
} finally {
114117
if (

‎scripts/lib/repo-root.mjs‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ import { existsSync } from "node:fs";
22
import path from "node:path";
33
import { fileURLToPath } from "node:url";
44

5-
/** Resolves the repository root by walking upward from the caller module. */
6-
export function resolveRepoRoot(importMetaUrl) {
7-
let dir = path.dirname(fileURLToPath(importMetaUrl));
5+
/** Finds the checkout containing a directory, including linked worktrees. */
6+
export function findRepoRoot(startDir) {
7+
let dir = path.resolve(startDir);
88
const { root } = path.parse(dir);
99
while (dir !== root) {
1010
if (
@@ -16,5 +16,11 @@ export function resolveRepoRoot(importMetaUrl) {
1616
}
1717
dir = path.dirname(dir);
1818
}
19-
return path.resolve(path.dirname(fileURLToPath(importMetaUrl)), "..", "..");
19+
return undefined;
20+
}
21+
22+
/** Resolves the repository root by walking upward from the caller module. */
23+
export function resolveRepoRoot(importMetaUrl) {
24+
const callerDir = path.dirname(fileURLToPath(importMetaUrl));
25+
return findRepoRoot(callerDir) ?? path.resolve(callerDir, "..", "..");
2026
}

‎scripts/tsdown-build.mts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import { decodeMountInfoPath } from "../packages/normalization-core/src/mountinf
1717
import { BUNDLED_PLUGIN_PATH_PREFIX } from "./lib/bundled-plugin-paths.mjs";
1818
import { isDirectRunUrl } from "./lib/direct-run.mjs";
1919
import {
20-
DIST_ARTIFACT_LOCK_PATH,
20+
resolveDistArtifactLockPath,
2121
withDistArtifactOwnership,
2222
} from "./lib/dist-artifact-ownership.mts";
2323
import { toErrorObject } from "./lib/error-format.mts";
@@ -190,7 +190,7 @@ function assertTsdownCleanOutputRoots(params: OutputRootParams = {}) {
190190
"Cannot clean the current working directory or one of its ancestors. Please specify a dedicated output directory.",
191191
);
192192
}
193-
if (isPathInside(rootPath, pathImpl.resolve(cwd, DIST_ARTIFACT_LOCK_PATH))) {
193+
if (isPathInside(rootPath, resolveDistArtifactLockPath(cwd))) {
194194
throw new Error("Cannot clean the checkout's dist artifact ownership location.");
195195
}
196196
// A safe final component is insufficient: recursive removal follows symlinked parents.

‎test/scripts/dist-artifact-ownership.test.ts‎

Lines changed: 86 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -319,24 +319,53 @@ describe.skipIf(process.platform === "win32")("dist artifact ownership", () => {
319319
}, signal);
320320
});
321321

322-
it("keeps declarations alive until their writer joins and keeps ownership across dist cleanup", async ({
323-
signal,
324-
}) => {
325-
await withProcesses(async ({ checkpoint, waitEvent, start }) => {
326-
const root = createCheckout();
327-
installCompiler(root, checkpoint("declarations-ready"));
328-
write(root, "pnpm.cjs", checkpoint("build-started"));
329-
const writer = start(root, path.join(sourceRoot, "scripts/run-tsgo.mts"), tsgoArgs);
330-
const writerGate = await writer.event("declarations-ready");
331-
const declaration = path.join(root, declarationPath);
332-
expect(fs.readFileSync(declaration, "utf8")).toContain("interface Channel");
322+
it.for([
323+
{ directory: ".", nested: false },
324+
{ directory: "src", nested: false },
325+
{ directory: "src", nested: true },
326+
])(
327+
"keeps declarations alive from $directory (nested=$nested) until their writer joins and keeps ownership across dist cleanup",
328+
{ timeout: 30_000 },
329+
async ({ directory, nested }, { signal }) => {
330+
await withProcesses(async ({ checkpoint, waitEvent, start }) => {
331+
const root = createCheckout();
332+
const cwd = path.join(root, directory);
333+
installCompiler(root, checkpoint("declarations-ready"));
334+
if (directory !== ".") {
335+
fs.symlinkSync(path.join(root, "node_modules"), path.join(cwd, "node_modules"));
336+
}
337+
write(root, "pnpm.cjs", checkpoint("build-started"));
338+
const writerArgs = [
339+
"-p",
340+
path.join(root, "tsconfig.plugin-sdk.dts.json"),
341+
"--declaration",
342+
"true",
343+
];
344+
const compilerScript = path.join(sourceRoot, "scripts/run-tsgo.mts");
345+
const writerScript = nested
346+
? write(
347+
root,
348+
"nested-writer.mts",
349+
`
350+
import { withDistArtifactOwnership, distArtifactEntryArgs } from ${JSON.stringify(path.join(sourceRoot, "scripts/lib/dist-artifact-ownership.mts"))};
351+
import { runManagedCommand } from ${JSON.stringify(path.join(sourceRoot, "scripts/lib/managed-child-process.mts"))};
352+
await withDistArtifactOwnership(${JSON.stringify(root)}, () => runManagedCommand({
353+
bin: process.execPath, args: distArtifactEntryArgs(${JSON.stringify(compilerScript)}, ${JSON.stringify(writerArgs)}), requireProcessTreeExit: true,
354+
}));
355+
`,
356+
)
357+
: compilerScript;
358+
const writer = start(cwd, writerScript, nested ? [] : writerArgs);
359+
const writerGate = await writer.event("declarations-ready");
360+
const declaration = path.join(root, declarationPath);
361+
expect(fs.readFileSync(declaration, "utf8")).toContain("interface Channel");
333362

334-
// Advance the contender's wall clock past the observed sixteen-minute build
335-
// without spending that time in Vitest; restore it before executing tsdown.
336-
const contender = write(
337-
root,
338-
"contender.mts",
339-
`
363+
// Advance the contender's wall clock past the observed sixteen-minute build
364+
// without spending that time in Vitest; restore it before executing tsdown.
365+
const contender = write(
366+
root,
367+
"contender.mts",
368+
`
340369
import { withDistArtifactOwnership } from ${JSON.stringify(path.join(sourceRoot, "scripts/lib/dist-artifact-ownership.mts"))};
341370
import { runTsdownBuild } from ${JSON.stringify(path.join(sourceRoot, "scripts/tsdown-build.mts"))};
342371
const now = Date.now;
@@ -347,44 +376,49 @@ describe.skipIf(process.platform === "win32")("dist artifact ownership", () => {
347376
return await runTsdownBuild(${JSON.stringify(buildArgs)});
348377
});
349378
`,
350-
);
351-
const build = start(root, contender);
352-
await Promise.race([build.waiting, waitEvent("build-started"), build.done]);
353-
// Before the repair the real tsdown cleanup deletes the emitted file here.
354-
expect(
355-
fs.existsSync(declaration),
356-
"cleanup must wait for the active declaration writer",
357-
).toBe(true);
358-
writerGate.write("continue");
359-
expect(await writer.done).toMatchObject({ code: 0 });
360-
const buildGate = await build.event("build-started");
361-
expect(fs.existsSync(declaration)).toBe(false);
379+
);
380+
const build = start(root, contender);
381+
await Promise.race([build.waiting, waitEvent("build-started"), build.done]);
382+
// Before the repair the real tsdown cleanup deletes the emitted file here.
383+
expect(
384+
fs.existsSync(declaration),
385+
"cleanup must wait for the active declaration writer",
386+
).toBe(true);
387+
writerGate.write("continue");
388+
expect(await writer.done).toMatchObject({ code: 0 });
389+
const buildGate = await build.event("build-started");
390+
expect(fs.existsSync(declaration)).toBe(false);
362391

363-
installCompiler(root, checkpoint("next-declarations-ready"));
364-
const nextWriter = start(root, path.join(sourceRoot, "scripts/run-tsgo.mts"), tsgoArgs);
365-
await Promise.race([
366-
nextWriter.waiting,
367-
waitEvent("next-declarations-ready"),
368-
nextWriter.done,
369-
]);
370-
expect(fs.existsSync(declaration), "deleting dist must not delete build ownership").toBe(
371-
false,
372-
);
392+
installCompiler(root, checkpoint("next-declarations-ready"));
393+
const nextWriter = start(root, path.join(sourceRoot, "scripts/run-tsgo.mts"), tsgoArgs);
394+
await Promise.race([
395+
nextWriter.waiting,
396+
waitEvent("next-declarations-ready"),
397+
nextWriter.done,
398+
]);
399+
expect(fs.existsSync(declaration), "deleting dist must not delete build ownership").toBe(
400+
false,
401+
);
373402

374-
const otherRoot = createCheckout();
375-
installCompiler(otherRoot, checkpoint("other-checkout-ready"));
376-
const independent = start(otherRoot, path.join(sourceRoot, "scripts/run-tsgo.mts"), tsgoArgs);
377-
(await independent.event("other-checkout-ready")).write("continue");
378-
expect(await independent.done).toMatchObject({ code: 0 });
379-
expect(fs.existsSync(declaration)).toBe(false);
403+
const otherRoot = createCheckout();
404+
installCompiler(otherRoot, checkpoint("other-checkout-ready"));
405+
const independent = start(
406+
otherRoot,
407+
path.join(sourceRoot, "scripts/run-tsgo.mts"),
408+
tsgoArgs,
409+
);
410+
(await independent.event("other-checkout-ready")).write("continue");
411+
expect(await independent.done).toMatchObject({ code: 0 });
412+
expect(fs.existsSync(declaration)).toBe(false);
380413

381-
buildGate.write("continue");
382-
expect(await build.done).toMatchObject({ code: 0 });
383-
(await nextWriter.event("next-declarations-ready")).write("continue");
384-
expect(await nextWriter.done).toMatchObject({ code: 0 });
385-
expect(fs.readFileSync(declaration, "utf8")).toContain("interface Channel");
386-
}, signal);
387-
}, 30_000);
414+
buildGate.write("continue");
415+
expect(await build.done).toMatchObject({ code: 0 });
416+
(await nextWriter.event("next-declarations-ready")).write("continue");
417+
expect(await nextWriter.done).toMatchObject({ code: 0 });
418+
expect(fs.readFileSync(declaration, "utf8")).toContain("interface Channel");
419+
}, signal);
420+
},
421+
);
388422

389423
it("retains ownership when a supervisor exits before its compiler joins", async ({ signal }) => {
390424
await withProcesses(async ({ checkpoint, waitEvent, start }) => {

‎test/scripts/tsdown-build.test.ts‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1940,16 +1940,22 @@ describe("resolveTsdownBuildInvocation", () => {
19401940
await expectPathMissing(outputDir);
19411941
});
19421942

1943-
it("refuses an output root containing checkout artifact ownership", async () => {
1944-
const rootDir = createTempDir("openclaw-tsdown-owner-clean-");
1945-
const owner = path.join(rootDir, ".artifacts/dist-artifacts.lock/owner.json");
1946-
await fsPromises.mkdir(path.dirname(owner), { recursive: true });
1947-
await fsPromises.writeFile(owner, "owned");
1948-
expect(() => cleanTsdownOutputRoots({ cwd: rootDir, roots: [".artifacts"] })).toThrow(
1949-
"Cannot clean the checkout's dist artifact ownership location",
1950-
);
1951-
expect(await fsPromises.readFile(owner, "utf8")).toBe("owned");
1952-
});
1943+
it.each([".", "src"])(
1944+
"refuses an output root containing checkout artifact ownership from %s",
1945+
async (directory) => {
1946+
const rootDir = createTempDir("openclaw-tsdown-owner-clean-");
1947+
const cwd = path.join(rootDir, directory);
1948+
const owner = path.join(rootDir, ".artifacts/dist-artifacts.lock/owner.json");
1949+
await fsPromises.mkdir(path.dirname(owner), { recursive: true });
1950+
await fsPromises.mkdir(cwd, { recursive: true });
1951+
await fsPromises.mkdir(path.join(rootDir, ".git"));
1952+
await fsPromises.writeFile(owner, "owned");
1953+
expect(() =>
1954+
cleanTsdownOutputRoots({ cwd, roots: [path.join(rootDir, ".artifacts")] }),
1955+
).toThrow("Cannot clean the checkout's dist artifact ownership location");
1956+
expect(await fsPromises.readFile(owner, "utf8")).toBe("owned");
1957+
},
1958+
);
19531959

19541960
it("refuses to clean the working directory and leaves it intact", async () => {
19551961
const rootDir = createTempDir("openclaw-tsdown-cwd-clean-");

0 commit comments

Comments
 (0)