@loucompanion/forge-bridge 0.1.4-dev.318bc3bd5b6a → 0.1.4-dev.494233aa2e50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/bridge/bridge.service.d.ts +12 -1
  2. package/dist/bridge/bridge.service.js +51 -5
  3. package/dist/bridge/bridge.types.d.ts +6 -0
  4. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  5. package/dist/bridge/dispatch-result-outbox.js +31 -6
  6. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  7. package/dist/runtime/host-database-capability-boundary.js +1 -0
  8. package/dist/runtime/host-facts.d.ts +35 -0
  9. package/dist/runtime/host-facts.js +95 -0
  10. package/dist/runtime/host-load-sampler.d.ts +83 -0
  11. package/dist/runtime/host-load-sampler.js +164 -0
  12. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  13. package/dist/runtime/host-pressure-stall.js +121 -0
  14. package/dist/runtime/host-runtime-contract.d.ts +1 -0
  15. package/dist/runtime/host-runtime-contract.js +2 -0
  16. package/dist/runtime/host-runtime-lease.js +5 -0
  17. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  18. package/dist/runtime/playwright-browser-cache.js +227 -0
  19. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  20. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  21. package/dist/session/phase-completion.artifacts.js +4 -0
  22. package/dist/session/pre-publication-process.d.ts +20 -0
  23. package/dist/session/pre-publication-process.js +97 -0
  24. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  25. package/dist/session/pre-publication-skipped-tests.js +109 -0
  26. package/dist/session/pre-publication-validation.js +27 -57
  27. package/dist/session/provider-cli/provider-cli.artifacts.js +2 -9
  28. package/dist/session/provider-cli/provider-cli.service.js +54 -7
  29. package/dist/session/publishable-worktree-changes.d.ts +45 -0
  30. package/dist/session/publishable-worktree-changes.js +177 -0
  31. package/dist/session/session.types.js +3 -0
  32. package/dist/version.d.ts +1 -1
  33. package/dist/version.js +1 -1
  34. package/package.json +1 -1
@@ -1,10 +1,10 @@
1
1
  import fs from "node:fs/promises";
2
- import os from "node:os";
3
2
  import path from "node:path";
4
3
  import { pathToFileURL } from "node:url";
5
4
  import { assertCanonicalDirectory, createPrivateCanonicalDirectory } from "./attempt-private-directory.js";
6
5
  import { readCanonicalSourceFile } from "./canonical-source-file.js";
7
6
  import { runAttemptPathOperation } from "./attempt-path-operation.js";
7
+ import { defaultPlaywrightBrowserCacheCandidates, findPlaywrightBrowserCache, missingPlaywrightBrowsersError, playwrightHostPlatform, } from "./playwright-browser-cache.js";
8
8
  const maximumConfigBytes = 1024 * 1024;
9
9
  /**
10
10
  * Prepares a finite Playwright test boundary for a managed-host attempt.
@@ -12,14 +12,32 @@ const maximumConfigBytes = 1024 * 1024;
12
12
  * Playwright-managed web servers, and keeps writable artifacts attempt-local.
13
13
  */
14
14
  export class PlaywrightHostRuntimeAdapter {
15
+ browserCacheCandidates;
16
+ hostPlatform;
17
+ constructor(browserCacheCandidates = defaultPlaywrightBrowserCacheCandidates, hostPlatform = playwrightHostPlatform) {
18
+ this.browserCacheCandidates = browserCacheCandidates;
19
+ this.hostPlatform = hostPlatform;
20
+ }
21
+ /**
22
+ * Fails a host that lacks the project's pinned Chromium builds before any
23
+ * database, build, launch, or promotion work, so the attempt never runs
24
+ * toward a Playwright gate whose every spec would fail at browser launch.
25
+ */
26
+ async assertBrowserCacheReady(config, worktreePath) {
27
+ const { realWorktree, realSource } = await projectConfigLocation(config, worktreePath);
28
+ await this.readyBrowserCache(worktreePath, realWorktree, path.dirname(realSource));
29
+ }
30
+ async readyBrowserCache(worktreePath, realWorktree, configDirectory) {
31
+ const installCommand = await resolvePlaywrightBrowserInstallCommand(worktreePath, configDirectory);
32
+ const resolution = await findPlaywrightBrowserCache(realWorktree, configDirectory, this.browserCacheCandidates, this.hostPlatform());
33
+ if (resolution.pinned && !resolution.cache) {
34
+ throw missingPlaywrightBrowsersError({ ...resolution, pinned: resolution.pinned }, installCommand);
35
+ }
36
+ return { cache: resolution.cache, installCommand };
37
+ }
15
38
  async prepare(config, context) {
16
- const worktreePath = path.resolve(context.worktreePath);
17
- const sourceConfig = path.resolve(worktreePath, config.config);
18
- const [realWorktree, realSource] = await Promise.all([
19
- fs.realpath(worktreePath),
20
- fs.realpath(sourceConfig),
21
- ]);
22
- assertContained(realWorktree, realSource, "project Playwright config");
39
+ const { realWorktree, realSource } = await projectConfigLocation(config, context.worktreePath);
40
+ const sourceConfig = path.resolve(path.resolve(context.worktreePath), config.config);
23
41
  const sourceBytes = await readCanonicalSourceFile(sourceConfig, maximumConfigBytes);
24
42
  if (sourceBytes.length < 1) {
25
43
  throw new Error(`playwright_runtime_adapter_invalid: project config must be a regular 1-${maximumConfigBytes} byte file.`);
@@ -45,8 +63,10 @@ export class PlaywrightHostRuntimeAdapter {
45
63
  throw new Error("playwright_runtime_adapter_invalid: ownership token must be a normalized dispatch attempt UUID.");
46
64
  }
47
65
  const overlayPath = path.join(temporaryDirectory, "forge.playwright.config.mjs");
48
- const browserCache = await resolvePlaywrightBrowserCache(attemptRoot);
49
- const browserInstallCommand = await resolvePlaywrightBrowserInstallCommand(context.worktreePath, path.dirname(realSource));
66
+ const { cache: readyCache, installCommand: browserInstallCommand } = await this.readyBrowserCache(context.worktreePath, realWorktree, path.dirname(realSource));
67
+ const browserCache = readyCache
68
+ ? { path: readyCache, ready: true }
69
+ : { path: await attemptBrowserCache(attemptRoot), ready: false };
50
70
  await writeAttemptOverlay(overlayPath, renderOverlay({
51
71
  projectConfigUrl: pathToFileURL(realSource).href,
52
72
  projectConfigDirectory: path.dirname(realSource),
@@ -76,6 +96,24 @@ export class PlaywrightHostRuntimeAdapter {
76
96
  };
77
97
  }
78
98
  }
99
+ async function projectConfigLocation(config, worktreePath) {
100
+ const resolvedWorktree = path.resolve(worktreePath);
101
+ const [realWorktree, realSource] = await Promise.all([
102
+ fs.realpath(resolvedWorktree),
103
+ fs.realpath(path.resolve(resolvedWorktree, config.config)),
104
+ ]);
105
+ assertContained(realWorktree, realSource, "project Playwright config");
106
+ return { realWorktree, realSource };
107
+ }
108
+ /**
109
+ * Without an installed Playwright the pinned build is unknown; the attempt
110
+ * gets its own empty cache and the readiness manifest names the install command.
111
+ */
112
+ async function attemptBrowserCache(attemptRoot) {
113
+ const attemptCache = path.join(attemptRoot, "cache", "ms-playwright");
114
+ await createPrivateCanonicalDirectory(attemptCache);
115
+ return attemptCache;
116
+ }
79
117
  async function ensureAttemptWritableDirectories(targets, realWorktree) {
80
118
  const resolvedTargets = targets.map(target => path.resolve(target));
81
119
  const attemptRoots = new Set(resolvedTargets.map(target => path.dirname(target)));
@@ -125,50 +163,6 @@ async function isFile(candidate) {
125
163
  function quoteCommandArgument(value) {
126
164
  return /[\s"']/u.test(value) ? JSON.stringify(value) : value;
127
165
  }
128
- async function resolvePlaywrightBrowserCache(attemptRoot) {
129
- const candidates = [
130
- process.env.PLAYWRIGHT_BROWSERS_PATH,
131
- process.env.LOCALAPPDATA ? path.join(process.env.LOCALAPPDATA, "ms-playwright") : null,
132
- path.join(os.homedir(), ".cache", "ms-playwright"),
133
- ].filter((candidate) => Boolean(candidate?.trim()));
134
- for (const candidate of [...new Set(candidates.map(candidate => path.resolve(candidate)))]) {
135
- if (await hasChromiumExecutable(candidate)) {
136
- return { path: candidate, ready: true };
137
- }
138
- }
139
- const attemptCache = path.join(attemptRoot, "cache", "ms-playwright");
140
- await createPrivateCanonicalDirectory(attemptCache);
141
- return { path: attemptCache, ready: false };
142
- }
143
- async function hasChromiumExecutable(cachePath) {
144
- let entries;
145
- try {
146
- entries = await fs.readdir(cachePath, { withFileTypes: true });
147
- }
148
- catch {
149
- return false;
150
- }
151
- const executableSuffixes = process.platform === "win32"
152
- ? [path.join("chrome-win64", "chrome.exe"), path.join("chrome-win", "chrome.exe")]
153
- : process.platform === "darwin"
154
- ? [path.join("chrome-mac", "Chromium.app", "Contents", "MacOS", "Chromium")]
155
- : [path.join("chrome-linux", "chrome"), path.join("chrome-linux64", "chrome")];
156
- for (const entry of entries) {
157
- if (!entry.isDirectory() || !entry.name.startsWith("chromium-"))
158
- continue;
159
- for (const suffix of executableSuffixes) {
160
- try {
161
- const stat = await fs.stat(path.join(cachePath, entry.name, suffix));
162
- if (stat.isFile())
163
- return true;
164
- }
165
- catch {
166
- // Continue through known Playwright layouts.
167
- }
168
- }
169
- }
170
- return false;
171
- }
172
166
  function renderOverlay(values) {
173
167
  return [
174
168
  "// Generated by forge-bridge for one fenced host attempt.",
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { redactSecrets } from "../shared/redaction/redaction.js";
5
5
  import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "./qa-sidecar-validation.js";
6
+ import { assertClaimedChangedFilesMatchPublishableDiff } from "./publishable-worktree-changes.js";
6
7
  import { artifactRootFor, artifactRootForOwner, completionArtifactJsonPath, completionArtifactReportPath, decomposeGateFileNames, draftGateFileNames, phaseFiles, qaGateFileNames } from "./phase-completion.js";
7
8
  import { artifactOwnerFields, artifactReferenceOwnerFields, artifactOwnerRelativeRoot, defaultQaChecklist, fallbackReport, isNodeError, jsonText, normalizeArtifactPayload, normalizeCompletionStatus, normalizeQaGateArtifactPayload, normalizeQaGateStatus, normalizedString, optionalString, numberOrDefault, parseJsonObject, parseOptionalJsonObject, phaseFromToolName, qaArray, qaArtifactRelativePath, qaArtifactRelativePathForOwner, qaEvidenceSource, qaObjectArray, qaPolicyWarnings, qaStringArray, readOptionalFile, reportMarkdown, requiredRecord, requiredString, qaGateFromToolName, sha256, stableStringify, validateOptionalWorkItemId, validatePayloadShape, validateQaGatePayloadShape, validateQaScopeRecord, writeFileAtomic, asRecord } from "./phase-completion.validation.js";
8
9
  export async function writeDecomposeGateCompletionArtifact(config, gate, toolName, input) {
@@ -158,6 +159,9 @@ export async function writeCompletionArtifact(config, toolName, input) {
158
159
  }
159
160
  validatePayloadShape(phase, validationPayload);
160
161
  validateOptionalWorkItemId(validationPayload, config.workItemId);
162
+ if (phase === "comment_repair" && status === "pass") {
163
+ await assertClaimedChangedFilesMatchPublishableDiff(config.worktreePath, validationPayload, toolName);
164
+ }
161
165
  const redactedPayload = redactSecrets(validationPayload, config.redactionSecrets ?? []);
162
166
  assertStructuralFieldsUnchanged(validationPayload, redactedPayload);
163
167
  validatePostRedaction(() => {
@@ -0,0 +1,20 @@
1
+ import type { PrePublicationCommandResult, PrePublicationCommandRunner } from "./pre-publication-validation.js";
2
+ export declare class ProcessPrePublicationCommandRunner implements PrePublicationCommandRunner {
3
+ run(command: string, args: readonly string[], cwd: string, signal?: AbortSignal, environment?: Readonly<Record<string, string>>): Promise<PrePublicationCommandResult>;
4
+ }
5
+ interface PackageManagerLaunchLocation {
6
+ readonly args: readonly string[];
7
+ readonly cwd: string;
8
+ }
9
+ /**
10
+ * Corepack picks the pnpm version from the nearest package.json `packageManager`
11
+ * pin at or above the process working directory; pnpm's own `--dir` is not
12
+ * consulted. The repository root carries no pin, so `pnpm --dir client ...`
13
+ * launched from the root would run Corepack's host-global default, and pnpm
14
+ * then refuses client's pin (ERR_PNPM_BAD_PM_VERSION). `pnpm --dir X cmd` is
15
+ * `pnpm cmd` run from X, so launch from X and let Corepack walk up from there
16
+ * to the nearest pin. Targets that are absolute, leave the worktree, or do not
17
+ * exist stay unchanged so pnpm reports them itself.
18
+ */
19
+ export declare function pnpmDirectoryLaunch(command: string, args: readonly string[], cwd: string): Promise<PackageManagerLaunchLocation>;
20
+ export {};
@@ -0,0 +1,97 @@
1
+ import { execFile } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, hostRuntimeTestPostgresProvisionerEnvironment, } from "../runtime/host-runtime-contract.js";
6
+ import { isSubPath } from "../shared/path/path.js";
7
+ const execFileAsync = promisify(execFile);
8
+ export class ProcessPrePublicationCommandRunner {
9
+ async run(command, args, cwd, signal, environment) {
10
+ try {
11
+ const launch = await pnpmDirectoryLaunch(command, args, cwd);
12
+ const windowsBatch = process.platform === "win32" && (command === "npm" || command === "pnpm");
13
+ const executable = windowsBatch ? (process.env.ComSpec ?? "cmd.exe") : command;
14
+ const commandArgs = windowsBatch
15
+ ? ["/d", "/s", "/c", [`${command}.cmd`, ...launch.args].map(quoteWindowsCommandArgument).join(" ")]
16
+ : [...launch.args];
17
+ const result = await execFileAsync(executable, commandArgs, {
18
+ cwd: launch.cwd,
19
+ encoding: "utf8",
20
+ maxBuffer: 4 * 1024 * 1024,
21
+ signal,
22
+ env: prePublicationChildEnvironment(environment),
23
+ });
24
+ return { exitCode: 0, stdout: result.stdout, stderr: result.stderr };
25
+ }
26
+ catch (error) {
27
+ const failure = error;
28
+ if (failure.name === "AbortError")
29
+ throw error;
30
+ if (failure.code === "ENOENT") {
31
+ return { exitCode: 127, stderr: `executable_not_found: ${command}` };
32
+ }
33
+ return {
34
+ exitCode: typeof failure.code === "number" ? failure.code : 1,
35
+ stdout: failure.stdout,
36
+ stderr: failure.stderr ?? failure.message,
37
+ };
38
+ }
39
+ }
40
+ }
41
+ function quoteWindowsCommandArgument(value) {
42
+ return /^[A-Za-z0-9_./:@=-]+$/u.test(value) ? value : `"${value.replaceAll('"', '""')}"`;
43
+ }
44
+ function prePublicationChildEnvironment(environment) {
45
+ const child = {};
46
+ const privilegedNames = new Set([
47
+ hostRuntimeTestPostgresAdminEnvironment.toLowerCase(),
48
+ hostRuntimeLegacyTestPostgresEnvironment.toLowerCase(),
49
+ hostRuntimeTestPostgresProvisionerEnvironment.toLowerCase(),
50
+ ]);
51
+ for (const [name, value] of Object.entries(process.env)) {
52
+ if (typeof value === "string" && !privilegedNames.has(name.toLowerCase())) {
53
+ child[name] = value;
54
+ }
55
+ }
56
+ return { ...child, ...environment };
57
+ }
58
+ /**
59
+ * Corepack picks the pnpm version from the nearest package.json `packageManager`
60
+ * pin at or above the process working directory; pnpm's own `--dir` is not
61
+ * consulted. The repository root carries no pin, so `pnpm --dir client ...`
62
+ * launched from the root would run Corepack's host-global default, and pnpm
63
+ * then refuses client's pin (ERR_PNPM_BAD_PM_VERSION). `pnpm --dir X cmd` is
64
+ * `pnpm cmd` run from X, so launch from X and let Corepack walk up from there
65
+ * to the nearest pin. Targets that are absolute, leave the worktree, or do not
66
+ * exist stay unchanged so pnpm reports them itself.
67
+ */
68
+ export async function pnpmDirectoryLaunch(command, args, cwd) {
69
+ const unchanged = { args, cwd };
70
+ if (command !== "pnpm")
71
+ return unchanged;
72
+ const target = pnpmDirectoryArgument(args);
73
+ if (!target || path.isAbsolute(target.directory))
74
+ return unchanged;
75
+ if (!isSubPath(cwd, path.resolve(cwd, target.directory)))
76
+ return unchanged;
77
+ // The lexical check alone would let a symlink (or junction) inside the worktree
78
+ // move the child's cwd outside it, so compare and launch from real paths.
79
+ const realCwd = await fs.realpath(cwd).catch(() => null);
80
+ const packageDirectory = await fs.realpath(path.resolve(cwd, target.directory)).catch(() => null);
81
+ if (!realCwd || !packageDirectory || !isSubPath(realCwd, packageDirectory))
82
+ return unchanged;
83
+ const stat = await fs.stat(packageDirectory).catch(() => null);
84
+ if (!stat?.isDirectory())
85
+ return unchanged;
86
+ return { args: args.slice(target.consumed), cwd: packageDirectory };
87
+ }
88
+ /** Reads a leading `--dir X`, `--dir=X`, `-C X`, `-CX` or `-C=X`. */
89
+ function pnpmDirectoryArgument(args) {
90
+ const first = args[0] ?? "";
91
+ if (first === "--dir" || first === "-C")
92
+ return args[1] ? { directory: args[1], consumed: 2 } : null;
93
+ const inline = first.startsWith("--dir=") ? first.slice("--dir=".length)
94
+ : first.startsWith("-C") ? first.slice(2).replace(/^=/u, "")
95
+ : "";
96
+ return inline ? { directory: inline, consumed: 1 } : null;
97
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Skipped .NET tests from the TRX files a validation step wrote, so a run that skipped tests reads as
3
+ * "passed with N skipped (reasons)" rather than a plain pass. Only files under the step's declared results
4
+ * directory and written since the step started count, and that directory must resolve (through symlinks) inside
5
+ * the worktree or the attempt's own test-output root; nothing here can fail a passing step.
6
+ */
7
+ export interface SkippedTestSummary {
8
+ readonly count: number;
9
+ readonly reasons: readonly {
10
+ readonly reason: string;
11
+ readonly count: number;
12
+ }[];
13
+ }
14
+ /** The attempt-owned output root a managed attempt's tests write under, outside the worktree. */
15
+ export declare const attemptTestOutputEnvironment = "FORGE_TEST_OUTPUT_DIR";
16
+ export declare function resultsDirectoryArgument(args: readonly string[]): string | undefined;
17
+ export declare function readSkippedTests(cwd: string, args: readonly string[], sinceMs: number, environment?: Readonly<Record<string, string>>): Promise<SkippedTestSummary>;
18
+ export declare function mergeSkippedTests(left: SkippedTestSummary, right: SkippedTestSummary): SkippedTestSummary;
19
+ export declare function describeSkippedTests(summary: SkippedTestSummary): string;
20
+ /** Each NotExecuted result's skip reason, from its ErrorInfo message (VSTest's TRX shape). */
21
+ export declare function skippedReasons(trx: string): string[];
@@ -0,0 +1,109 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { isSubPath } from "../shared/path/path.js";
4
+ const emptySummary = { count: 0, reasons: [] };
5
+ /** The attempt-owned output root a managed attempt's tests write under, outside the worktree. */
6
+ export const attemptTestOutputEnvironment = "FORGE_TEST_OUTPUT_DIR";
7
+ const resultsDirectoryFlags = new Set(["-resultsdirectory", "--results-directory"]);
8
+ const maxTrxBytes = 64 * 1024 * 1024;
9
+ const maxTrxFiles = 64;
10
+ const maxReasonLength = 400;
11
+ const maxReasons = 10;
12
+ export function resultsDirectoryArgument(args) {
13
+ const index = args.findIndex(arg => resultsDirectoryFlags.has(arg.toLowerCase()));
14
+ const value = index >= 0 ? args[index + 1] : undefined;
15
+ return value && !value.startsWith("-") ? value : undefined;
16
+ }
17
+ export async function readSkippedTests(cwd, args, sinceMs, environment) {
18
+ const declared = resultsDirectoryArgument(args);
19
+ if (!declared)
20
+ return emptySummary;
21
+ const root = await realDirectory(path.resolve(cwd, declared));
22
+ if (!root)
23
+ return emptySummary;
24
+ const attemptOutput = environment?.[attemptTestOutputEnvironment]?.trim();
25
+ const allowedRoots = (await Promise.all([cwd, ...(attemptOutput && path.isAbsolute(attemptOutput) ? [attemptOutput] : [])]
26
+ .map(realDirectory))).filter((allowed) => allowed !== undefined);
27
+ if (!allowedRoots.some(allowed => isSubPath(allowed, root)))
28
+ return emptySummary;
29
+ const files = await recentTrxFiles(root, sinceMs);
30
+ const counts = new Map();
31
+ let count = 0;
32
+ for (const file of files) {
33
+ for (const reason of skippedReasons(await fs.readFile(file, "utf8"))) {
34
+ count += 1;
35
+ counts.set(reason, (counts.get(reason) ?? 0) + 1);
36
+ }
37
+ }
38
+ return { count, reasons: [...counts].map(([reason, n]) => ({ reason, count: n })) };
39
+ }
40
+ export function mergeSkippedTests(left, right) {
41
+ const counts = new Map(left.reasons.map(entry => [entry.reason, entry.count]));
42
+ for (const entry of right.reasons)
43
+ counts.set(entry.reason, (counts.get(entry.reason) ?? 0) + entry.count);
44
+ return { count: left.count + right.count, reasons: [...counts].map(([reason, count]) => ({ reason, count })) };
45
+ }
46
+ export function describeSkippedTests(summary) {
47
+ const shown = [...summary.reasons].sort((a, b) => b.count - a.count).slice(0, maxReasons);
48
+ const more = summary.reasons.length - shown.length;
49
+ return `${summary.count} skipped test${summary.count === 1 ? "" : "s"} (${shown
50
+ .map(entry => `${entry.count}x ${entry.reason}`).join("; ")}${more > 0 ? `; ${more} more reasons` : ""})`;
51
+ }
52
+ /** Each NotExecuted result's skip reason, from its ErrorInfo message (VSTest's TRX shape). */
53
+ export function skippedReasons(trx) {
54
+ const reasons = [];
55
+ const result = /<UnitTestResult\b([^>]*?)(?:\/>|>([\s\S]*?)<\/UnitTestResult>)/gu;
56
+ for (const match of trx.matchAll(result)) {
57
+ if (!/\boutcome="NotExecuted"/u.test(match[1] ?? ""))
58
+ continue;
59
+ const message = /<Message>([\s\S]*?)<\/Message>/u.exec(match[2] ?? "")?.[1];
60
+ const reason = message ? decodeXml(message).replace(/\s+/gu, " ").trim() : "";
61
+ reasons.push(reason.length === 0 ? "no reason recorded"
62
+ : reason.length > maxReasonLength ? `${reason.slice(0, maxReasonLength)}...` : reason);
63
+ }
64
+ return reasons;
65
+ }
66
+ async function realDirectory(candidate) {
67
+ try {
68
+ const real = await fs.realpath(candidate);
69
+ return (await fs.stat(real)).isDirectory() ? real : undefined;
70
+ }
71
+ catch {
72
+ return undefined;
73
+ }
74
+ }
75
+ async function recentTrxFiles(root, sinceMs) {
76
+ const found = [];
77
+ const pending = [root];
78
+ while (pending.length > 0 && found.length < maxTrxFiles) {
79
+ const directory = pending.pop();
80
+ let entries;
81
+ try {
82
+ entries = await fs.readdir(directory, { withFileTypes: true });
83
+ }
84
+ catch {
85
+ continue;
86
+ }
87
+ for (const entry of entries) {
88
+ const full = path.join(directory, entry.name);
89
+ if (entry.isDirectory())
90
+ pending.push(full);
91
+ else if (entry.isFile() && entry.name.toLowerCase().endsWith(".trx")) {
92
+ const stat = await fs.stat(full).catch(() => null);
93
+ if (stat && stat.mtimeMs >= sinceMs && stat.size <= maxTrxBytes)
94
+ found.push(full);
95
+ }
96
+ }
97
+ }
98
+ return found.sort();
99
+ }
100
+ function decodeXml(value) {
101
+ return value.replace(/&(#x[0-9a-f]+|#[0-9]+|lt|gt|amp|quot|apos);/giu, (entity, name) => {
102
+ const lower = name.toLowerCase();
103
+ if (lower.startsWith("#x"))
104
+ return String.fromCodePoint(Number.parseInt(lower.slice(2), 16));
105
+ if (lower.startsWith("#"))
106
+ return String.fromCodePoint(Number.parseInt(lower.slice(1), 10));
107
+ return { lt: "<", gt: ">", amp: "&", quot: "\"", apos: "'" }[lower] ?? entity;
108
+ });
109
+ }
@@ -1,16 +1,15 @@
1
- import { execFile } from "node:child_process";
2
1
  import { createHash, randomUUID } from "node:crypto";
3
2
  import fs from "node:fs/promises";
4
3
  import path from "node:path";
5
- import { promisify } from "node:util";
6
4
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
7
5
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
8
6
  import { nativeTestPostgresFallbackEnvironment, parseNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
9
- import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, } from "../runtime/host-runtime-contract.js";
7
+ import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, hostRuntimeTestPostgresProvisionerEnvironment, } from "../runtime/host-runtime-contract.js";
10
8
  import { redactText } from "../shared/redaction/redaction.js";
9
+ import { describeSkippedTests, mergeSkippedTests, readSkippedTests, } from "./pre-publication-skipped-tests.js";
10
+ import { ProcessPrePublicationCommandRunner, pnpmDirectoryLaunch } from "./pre-publication-process.js";
11
11
  import { findUnreferencedNewExports } from "./unreferenced-exports.js";
12
12
  import { ForgeFailureError, sanitizeFailureError, } from "./session.types.js";
13
- const execFileAsync = promisify(execFile);
14
13
  const contractRelativePath = ".forge/validation/ci-parity.v1.json";
15
14
  const requiredCheckIds = new Set([
16
15
  "file-size-inventory",
@@ -81,54 +80,6 @@ export class PrePublicationInfrastructureError extends ForgeFailureError {
81
80
  this.name = "PrePublicationInfrastructureError";
82
81
  }
83
82
  }
84
- class ProcessPrePublicationCommandRunner {
85
- async run(command, args, cwd, signal, environment) {
86
- try {
87
- const windowsBatch = process.platform === "win32" && (command === "npm" || command === "pnpm");
88
- const executable = windowsBatch ? (process.env.ComSpec ?? "cmd.exe") : command;
89
- const commandArgs = windowsBatch
90
- ? ["/d", "/s", "/c", [`${command}.cmd`, ...args].map(quoteWindowsCommandArgument).join(" ")]
91
- : [...args];
92
- const result = await execFileAsync(executable, commandArgs, {
93
- cwd,
94
- encoding: "utf8",
95
- maxBuffer: 4 * 1024 * 1024,
96
- signal,
97
- env: prePublicationChildEnvironment(environment),
98
- });
99
- return { exitCode: 0, stdout: result.stdout, stderr: result.stderr };
100
- }
101
- catch (error) {
102
- const failure = error;
103
- if (failure.name === "AbortError")
104
- throw error;
105
- if (failure.code === "ENOENT") {
106
- return { exitCode: 127, stderr: `executable_not_found: ${command}` };
107
- }
108
- return {
109
- exitCode: typeof failure.code === "number" ? failure.code : 1,
110
- stdout: failure.stdout,
111
- stderr: failure.stderr ?? failure.message,
112
- };
113
- }
114
- }
115
- }
116
- function quoteWindowsCommandArgument(value) {
117
- return /^[A-Za-z0-9_./:@=-]+$/u.test(value) ? value : `"${value.replaceAll('"', '""')}"`;
118
- }
119
- function prePublicationChildEnvironment(environment) {
120
- const child = {};
121
- const privilegedNames = new Set([
122
- hostRuntimeTestPostgresAdminEnvironment.toLowerCase(),
123
- hostRuntimeLegacyTestPostgresEnvironment.toLowerCase(),
124
- ]);
125
- for (const [name, value] of Object.entries(process.env)) {
126
- if (typeof value === "string" && !privilegedNames.has(name.toLowerCase())) {
127
- child[name] = value;
128
- }
129
- }
130
- return { ...child, ...environment };
131
- }
132
83
  export class PrePublicationValidator {
133
84
  commands;
134
85
  dockerEngineProbe;
@@ -176,7 +127,9 @@ export class PrePublicationValidator {
176
127
  }
177
128
  const postgresAdminConnection = await this.ensurePrerequisite(check, scoped.execution?.environment, scoped.postgresAdminConnection, emit) ?? scoped.postgresAdminConnection;
178
129
  await emit?.(validationEvent("prepublication_validation_started", check.id, `Running pre-publication CI parity check '${check.id}'.`));
130
+ let skipped = { count: 0, reasons: [] };
179
131
  for (const step of check.steps) {
132
+ const stepStartedMs = Date.now() - 1000;
180
133
  let result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
181
134
  await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
182
135
  if (isTimeoutOnlyClientTestFailure(check.id, step, result)) {
@@ -222,9 +175,17 @@ export class PrePublicationValidator {
222
175
  await emit?.(validationEvent("prepublication_validation_failed", check.id, `Pre-publication CI parity check '${check.id}' exited ${result.exitCode}${detail ? `: ${detail}` : "."}`));
223
176
  throw new PrePublicationValidationError(check.id, result.exitCode, result.command, result.args, detail);
224
177
  }
178
+ // The invocation's own arguments: a managed attempt may direct results to its test-output root.
179
+ skipped = mergeSkippedTests(skipped, await readSkippedTests(worktreePath, result.args, stepStartedMs, scoped.execution?.environment));
225
180
  }
226
181
  completed.push(check.id);
227
- await emit?.(validationEvent("prepublication_validation_passed", check.id, `Pre-publication CI parity check '${check.id}' passed.`));
182
+ // A pass that skipped tests says so, with each reason, instead of reading as a plain pass.
183
+ const secrets = validationExactSecrets(scoped.execution?.environment);
184
+ skipped = { ...skipped, reasons: skipped.reasons.map(entry => ({ ...entry, reason: redactText(entry.reason, secrets) })) };
185
+ const skippedDetail = skipped.count > 0 ? describeSkippedTests(skipped) : undefined;
186
+ await emit?.(validationEvent("prepublication_validation_passed", check.id, skippedDetail
187
+ ? `Pre-publication CI parity check '${check.id}' passed with ${skippedDetail}.`
188
+ : `Pre-publication CI parity check '${check.id}' passed.`, skipped.count > 0 ? { skippedTests: skipped.count, skippedReasons: skipped.reasons } : undefined));
228
189
  }
229
190
  return completed;
230
191
  }
@@ -361,10 +322,11 @@ export class PrePublicationValidator {
361
322
  const exactSecrets = validationExactSecrets(execution?.environment);
362
323
  try {
363
324
  if (execution?.processRunner) {
325
+ const launch = await pnpmDirectoryLaunch(command, args, cwd);
364
326
  const result = await execution.processRunner.run({
365
327
  command,
366
- args,
367
- cwd,
328
+ args: launch.args,
329
+ cwd: launch.cwd,
368
330
  env: execution.environment,
369
331
  captureOutput: true,
370
332
  failureRedactionValues: exactSecrets,
@@ -455,6 +417,7 @@ function validationExactSecrets(environment) {
455
417
  return [
456
418
  environment?.[hostRuntimeTestPostgresAdminEnvironment]?.trim() ?? "",
457
419
  environment?.[hostRuntimeLegacyTestPostgresEnvironment]?.trim() ?? "",
420
+ environment?.[hostRuntimeTestPostgresProvisionerEnvironment]?.trim() ?? "",
458
421
  ...attemptDatabaseCapabilitySecrets(environment?.[attemptDatabaseCapabilityEnvironment]),
459
422
  ].filter((value, index, values) => value.length > 0 && values.indexOf(value) === index);
460
423
  }
@@ -587,6 +550,7 @@ function withoutPrivilegedPostgresEnvironment(environment) {
587
550
  const privilegedNames = new Set([
588
551
  hostRuntimeTestPostgresAdminEnvironment.toLowerCase(),
589
552
  hostRuntimeLegacyTestPostgresEnvironment.toLowerCase(),
553
+ hostRuntimeTestPostgresProvisionerEnvironment.toLowerCase(),
590
554
  ]);
591
555
  return Object.fromEntries(Object.entries(environment)
592
556
  .filter(([name]) => !privilegedNames.has(name.toLowerCase())));
@@ -656,6 +620,12 @@ function canonicalizeJson(value) {
656
620
  }
657
621
  return value;
658
622
  }
659
- function validationEvent(eventType, checkId, content) {
660
- return { role: "runner", kind: "checkpoint", content, eventType, data: JSON.stringify({ checkId, contractId: "forge-ci-parity-v1" }) };
623
+ function validationEvent(eventType, checkId, content, detail) {
624
+ return {
625
+ role: "runner",
626
+ kind: "checkpoint",
627
+ content,
628
+ eventType,
629
+ data: JSON.stringify({ checkId, contractId: "forge-ci-parity-v1", ...detail }),
630
+ };
661
631
  }
@@ -2,12 +2,12 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { artifactRootFor, artifactRootForOwner, debugCompletionPhaseOrder, draftCompletionGateOrder, qaCompletionGateOrder, readCompletionArtifact } from "../phase-completion.js";
4
4
  import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "../qa-sidecar-validation.js";
5
+ import { stagePublishableWorktreeChangeSet } from "../publishable-worktree-changes.js";
5
6
  import { hasLaunchTarget } from "./provider-cli.qa-sidecars.js";
6
7
  import { clip, isNodeError, messageFromError, normalizedString, parseJsonLine, stringField } from "./provider-output-state.js";
7
8
  const maxTransportedQaSidecarBytes = 8 * 1024 * 1024;
8
9
  const maxTransportedQaSidecarsTotalBytes = 16 * 1024 * 1024;
9
10
  const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
10
- const nonPublishableWorktreePaths = [".forge", ".local"];
11
11
  export async function emitDraftGateArtifacts(emit, worktreePath, workItemId) {
12
12
  const draftArtifactFiles = {
13
13
  draft_intent: "draft.intent.json",
@@ -157,14 +157,7 @@ export async function commitWorktreeChanges(git, worktreePath, workItemId, alrea
157
157
  return { commitSha, changedFiles };
158
158
  }
159
159
  export async function stagePublishableWorktreeChanges(git, worktreePath) {
160
- await git.run(worktreePath, ["add", "-A"]);
161
- for (const reservedPath of nonPublishableWorktreePaths) {
162
- await git.run(worktreePath, ["reset", "--", reservedPath]).catch(() => "");
163
- }
164
- return (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
165
- .split(/\r?\n/)
166
- .map((line) => line.trim())
167
- .filter(Boolean);
160
+ return (await stagePublishableWorktreeChangeSet(git, worktreePath)).publishable;
168
161
  }
169
162
  export function phaseCompleteEventType(phase) {
170
163
  return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;