@mastra/factory 0.29.0-alpha.6 → 0.29.0-alpha.8
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.
- package/README.md +50 -20
- package/dist/boards/board-events.d.ts +23 -0
- package/dist/boards/board-events.d.ts.map +1 -1
- package/dist/boards/board-events.js +37 -3
- package/dist/boards/board-events.js.map +1 -1
- package/dist/boards/board-writes.d.ts +6 -4
- package/dist/boards/board-writes.d.ts.map +1 -1
- package/dist/boards/board-writes.js +9 -6
- package/dist/boards/board-writes.js.map +1 -1
- package/dist/boards/intake-routing.d.ts +30 -16
- package/dist/boards/intake-routing.d.ts.map +1 -1
- package/dist/boards/intake-routing.js +41 -28
- package/dist/boards/intake-routing.js.map +1 -1
- package/dist/boards/project-boards.d.ts +15 -0
- package/dist/boards/project-boards.d.ts.map +1 -1
- package/dist/boards/project-boards.js +43 -7
- package/dist/boards/project-boards.js.map +1 -1
- package/dist/factory.d.ts +4 -14
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +22 -15
- package/dist/factory.js.map +1 -1
- package/dist/integrations/github/integration.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +101 -0
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +7 -3
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.d.ts +7 -1
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +15 -1
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/github/session-subscriptions.js +1 -1
- package/dist/integrations/github/session-subscriptions.js.map +1 -1
- package/dist/integrations/gitlab/rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/rules.js +2 -1
- package/dist/integrations/gitlab/rules.js.map +1 -1
- package/dist/integrations/gitlab/session-subscriptions.js +1 -1
- package/dist/integrations/gitlab/session-subscriptions.js.map +1 -1
- package/dist/integrations/slack/channel-reply-processor.d.ts +1 -0
- package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -1
- package/dist/integrations/slack/channel-reply-processor.js +4 -1
- package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
- package/dist/integrations/slack/run-error-card.js +6 -1
- package/dist/integrations/slack/run-error-card.js.map +1 -1
- package/dist/links.d.ts +4 -2
- package/dist/links.d.ts.map +1 -1
- package/dist/links.js +5 -3
- package/dist/links.js.map +1 -1
- package/dist/routes/boards.d.ts +1 -1
- package/dist/routes/boards.d.ts.map +1 -1
- package/dist/routes/boards.js.map +1 -1
- package/dist/routes/contracts.d.ts +32 -5
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +36 -9
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/intake-check.d.ts.map +1 -1
- package/dist/routes/intake-check.js +3 -1
- package/dist/routes/intake-check.js.map +1 -1
- package/dist/routes/intake-routes.d.ts +0 -3
- package/dist/routes/intake-routes.d.ts.map +1 -1
- package/dist/routes/intake-routes.js +1 -1
- package/dist/routes/intake-routes.js.map +1 -1
- package/dist/routes/skills.d.ts +1 -1
- package/dist/routes/skills.d.ts.map +1 -1
- package/dist/routes/skills.js +92 -28
- package/dist/routes/skills.js.map +1 -1
- package/dist/routes/surface.d.ts +0 -3
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +0 -1
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/dispatch-errors.d.ts +6 -0
- package/dist/rules/dispatch-errors.d.ts.map +1 -1
- package/dist/rules/dispatch-errors.js +10 -1
- package/dist/rules/dispatch-errors.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +74 -32
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/event-rules.d.ts +3 -2
- package/dist/rules/event-rules.d.ts.map +1 -1
- package/dist/rules/event-rules.js +5 -3
- package/dist/rules/event-rules.js.map +1 -1
- package/dist/rules/public-failure-reason.d.ts +11 -0
- package/dist/rules/public-failure-reason.d.ts.map +1 -0
- package/dist/rules/public-failure-reason.js +136 -0
- package/dist/rules/public-failure-reason.js.map +1 -0
- package/dist/rules/transition-service.d.ts +13 -0
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +5 -1
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +12 -0
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js.map +1 -1
- package/dist/rules/validation.d.ts.map +1 -1
- package/dist/rules/validation.js +11 -2
- package/dist/rules/validation.js.map +1 -1
- package/dist/run-error.d.ts +1 -1
- package/dist/run-error.d.ts.map +1 -1
- package/dist/run-error.js +21 -12
- package/dist/run-error.js.map +1 -1
- package/dist/session/environment-state-processor.d.ts.map +1 -1
- package/dist/session/environment-state-processor.js +6 -2
- package/dist/session/environment-state-processor.js.map +1 -1
- package/dist/session/session-row-view.js +1 -1
- package/dist/session/session-row-view.js.map +1 -1
- package/dist/session/source-control-tools.d.ts.map +1 -1
- package/dist/session/source-control-tools.js +5 -3
- package/dist/session/source-control-tools.js.map +1 -1
- package/dist/skills/app-skills.d.ts +3 -2
- package/dist/skills/app-skills.d.ts.map +1 -1
- package/dist/skills/app-skills.js +5 -3
- package/dist/skills/app-skills.js.map +1 -1
- package/dist/skills/catalog.d.ts +23 -4
- package/dist/skills/catalog.d.ts.map +1 -1
- package/dist/skills/catalog.js +61 -28
- package/dist/skills/catalog.js.map +1 -1
- package/dist/storage/domains/audit/actions.d.ts +1 -1
- package/dist/storage/domains/audit/actions.d.ts.map +1 -1
- package/dist/storage/domains/audit/actions.js +6 -1
- package/dist/storage/domains/audit/actions.js.map +1 -1
- package/dist/storage/domains/boards/base.d.ts +12 -0
- package/dist/storage/domains/boards/base.d.ts.map +1 -1
- package/dist/storage/domains/boards/base.js +3 -0
- package/dist/storage/domains/boards/base.js.map +1 -1
- package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
- package/dist/storage/domains/boards/schemas.js +4 -0
- package/dist/storage/domains/boards/schemas.js.map +1 -1
- package/dist/storage/domains/skill-overrides/base.d.ts +28 -4
- package/dist/storage/domains/skill-overrides/base.d.ts.map +1 -1
- package/dist/storage/domains/skill-overrides/base.js +54 -1
- package/dist/storage/domains/skill-overrides/base.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +2 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +13 -5
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/tools/audit-events-tool.d.ts +1 -1
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +0 -1
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/work-item-tools.d.ts.map +1 -1
- package/dist/tools/work-item-tools.js +0 -3
- package/dist/tools/work-item-tools.js.map +1 -1
- package/dist/work-items/create-work-item.d.ts.map +1 -1
- package/dist/work-items/create-work-item.js +2 -1
- package/dist/work-items/create-work-item.js.map +1 -1
- package/dist/workspace.d.ts +5 -1
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +69 -9
- package/dist/workspace.js.map +1 -1
- package/package.json +8 -8
|
@@ -174,6 +174,12 @@ export declare function resolveGitIdentity(identity: GitIdentity): {
|
|
|
174
174
|
};
|
|
175
175
|
/** Configure repository-local commit identity through direct Git argv calls. */
|
|
176
176
|
export declare function configureGitIdentity(sandbox: ExecutableSandbox, workdir: string, identity: GitIdentity): Promise<void>;
|
|
177
|
+
export interface PushedBranch {
|
|
178
|
+
/** The local branch tip that was pushed. */
|
|
179
|
+
commit: string;
|
|
180
|
+
/** True when the remote already had this commit, so the push sent nothing new. */
|
|
181
|
+
upToDate: boolean;
|
|
182
|
+
}
|
|
177
183
|
/** Whether the checkout has a local `refs/heads/<branch>`. */
|
|
178
184
|
export declare function hasLocalBranch(sandbox: ExecutableSandbox, workdir: string, branch: string): Promise<boolean>;
|
|
179
185
|
/**
|
|
@@ -192,7 +198,7 @@ export declare function pushBranch(sandbox: ExecutableSandbox, workdir: string,
|
|
|
192
198
|
* Push the active session branch through the provider-neutral repository
|
|
193
199
|
* access contract without persisting or exposing provider credentials.
|
|
194
200
|
*/
|
|
195
|
-
export declare function pushRepositoryBranch(sandbox: ExecutableSandbox, workdir: string, branch: string, access: RepositoryAccess, repoFullName: string): Promise<
|
|
201
|
+
export declare function pushRepositoryBranch(sandbox: ExecutableSandbox, workdir: string, branch: string, access: RepositoryAccess, repoFullName: string): Promise<PushedBranch>;
|
|
196
202
|
export interface CommitResult {
|
|
197
203
|
/** True when a commit was created; false when there was nothing to commit. */
|
|
198
204
|
committed: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../../../src/integrations/github/sandbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAE9E,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,KAAK,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AAEhG,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AAG/F,KAAK,oBAAoB,GAAG,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,EAAE,kBAAkB,CAAC,CAAC;AAE7F,UAAU,0BAA0B;IAClC,EAAE,EAAE,MAAM,CAAC;IACX,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,IAAI,GAAG,IAAI,CAAC;CAC7B;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAGhD;AAED;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,QAAc,CAAC;AACtD,4EAA4E;AAC5E,eAAO,MAAM,2BAA2B,QAAa,CAAC;AAEtD,UAAU,SAAS;IACjB,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AAK,EAAE,MAAM,CAAC;IACd,0BAA0B;IAC1B,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,uBAAuB;IACtC,oDAAoD;IACpD,GAAG,EAAE,MAAM,CAAC;CACb;AAuBD;;;;;;;;GAQG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,iBAAiB,EAC1B,OAAO,EAAE,MAAM,EACf,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,qBAAqB,GACxD,OAAO,CAAC,uBAAuB,CAAC,CAiClC"}
|
|
@@ -799,16 +799,30 @@ async function configureGitIdentity(sandbox, workdir, identity) {
|
|
|
799
799
|
if (setEmail.exitCode !== 0) throw new MaterializeError(`Failed to set git user.email: ${setEmail.stderr.trim()}`, "commit-failed");
|
|
800
800
|
}
|
|
801
801
|
async function pushAuthenticatedBranch(sandbox, workdir, branch, cloneUrl, token, username) {
|
|
802
|
+
const tip = await execute(sandbox, "git", [
|
|
803
|
+
"-C",
|
|
804
|
+
workdir,
|
|
805
|
+
"rev-parse",
|
|
806
|
+
"--verify",
|
|
807
|
+
`refs/heads/${branch}`
|
|
808
|
+
]);
|
|
809
|
+
if (tip.exitCode !== 0) throw classifyGitFailure(tip, "push-failed");
|
|
802
810
|
const env = gitAuthenticationEnvironment(cloneUrl, token, username, "push-failed");
|
|
803
811
|
const push = await execute(sandbox, "git", [
|
|
804
812
|
"-C",
|
|
805
813
|
workdir,
|
|
806
814
|
"push",
|
|
815
|
+
"--porcelain",
|
|
807
816
|
"-u",
|
|
808
817
|
"origin",
|
|
809
818
|
branch
|
|
810
819
|
], { env });
|
|
811
820
|
if (push.exitCode !== 0) throw classifyGitFailure(push, "push-failed");
|
|
821
|
+
const upToDate = push.stdout.split("\n").some((line) => line.startsWith("= ") && line.split(" ")[1]?.startsWith(`refs/heads/${branch}:`));
|
|
822
|
+
return {
|
|
823
|
+
commit: tip.stdout.trim(),
|
|
824
|
+
upToDate
|
|
825
|
+
};
|
|
812
826
|
}
|
|
813
827
|
/** Whether the checkout has a local `refs/heads/<branch>`. */
|
|
814
828
|
async function hasLocalBranch(sandbox, workdir, branch) {
|
|
@@ -933,7 +947,7 @@ async function pushRepositoryBranch(sandbox, workdir, branch, access, repoFullNa
|
|
|
933
947
|
assertRepositoryLocator(repoFullName, access.cloneUrl, "push-failed");
|
|
934
948
|
const authorization = access.authorization;
|
|
935
949
|
if (!authorization?.token) throw new MaterializeError("Repository access did not include push credentials.", "push-failed");
|
|
936
|
-
|
|
950
|
+
return pushAuthenticatedBranch(sandbox, workdir, branch, access.cloneUrl, authorization.token, authorization.username ?? "x-access-token");
|
|
937
951
|
}
|
|
938
952
|
/**
|
|
939
953
|
* Stage every change in the working tree and create a commit inside the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox.js","names":[],"sources":["../../../src/integrations/github/sandbox.ts"],"sourcesContent":["/**\n * Repo materialization for GitHub-backed repositories.\n *\n * A GitHub repo is never cloned onto the server host. The repo is cloned\n * *inside* the session's sandbox, so the agent's file tools and command tools\n * operate entirely against the remote checkout.\n *\n * - `materializeRepo(row, token)` clones the repo inside the sandbox when no\n * checkout exists yet (a base-image boot, a wiped disk), supplying the\n * short-lived token only in that Git process's environment. A checkout that\n * is already there, from a repo template image or an earlier start, is left\n * exactly as it is.\n *\n * This module owns everything git/GitHub: clone, commit/push, setup/teardown commands,\n * and `gh pr create`. Workdir layout lives in `../sandbox/workdir`.\n */\n\nimport type { RepositoryAccess } from '../../capabilities/version-control.js';\nimport { recordSandboxCommand } from '../../metrics/sandbox.js';\nimport { isValidGitRef } from '../../sandbox/git-ref.js';\nimport type { ExecutableSandbox, SandboxCommandResult } from '../../sandbox/materialization.js';\nimport { appliedSandboxEnv, maskSandboxEnvValues } from '../../sandbox/sandbox-env.js';\nimport type { SourceControlStorageHandle } from '../../storage/domains/source-control/base.js';\nimport { bootDiagnosticsEnabled, timedPhase } from '../../timing.js';\n\ntype MaterializationStore = Pick<SourceControlStorageHandle['sessions'], 'markMaterialized'>;\n\ninterface RepoMaterializationBinding {\n id: string;\n sandboxWorkdir: string;\n materializedAt: Date | null;\n}\n\n/**\n * Single-quote a string for safe POSIX shell interpolation. Wraps the value in\n * single quotes and escapes any embedded single quote using the canonical\n * close-quote / escaped-quote / reopen-quote sequence (`'\\''`). This is the\n * standard POSIX-safe construction and prevents the quoted string from being\n * terminated early.\n */\nexport function shellQuote(value: string): string {\n // Replace each ' with the four-character sequence: ' \\ ' '\n return `'` + value.split(`'`).join(`'\\\\''`) + `'`;\n}\n\n/**\n * Default hang guard for sandbox shell commands. Generous by design — large\n * clones and dependency installs legitimately take minutes; the guard exists\n * so a wedged sandbox surfaces a failure instead of hanging the request that\n * triggered materialization forever.\n */\nexport const DEFAULT_COMMAND_TIMEOUT_MS = 15 * 60_000;\n/** Branch checkout only fetches one ref — a much tighter budget applies. */\nexport const CHECKOUT_COMMAND_TIMEOUT_MS = 5 * 60_000;\n\ninterface ShOptions {\n /** Override the hang-guard budget for this command. */\n timeoutMs?: number;\n /** Human-readable phase name included in the timeout error. */\n phase?: string;\n}\n\ninterface CommandOptions extends ShOptions {\n cwd?: string;\n env?: Record<string, string | undefined>;\n}\n\n/**\n * A thrown transport-level failure that is worth retrying: remote sandbox\n\n * providers (e.g. the platform workspace proxy) surface transient 5xx errors\n * as exceptions carrying an HTTP `status` — typically while a freshly\n * provisioned VM is still coming up. Command failures are NOT exceptions\n * (they resolve with a non-zero exit code), so retrying here never re-runs a\n * command that the sandbox already executed and rejected.\n */\nfunction isTransientTransportError(error: unknown): boolean {\n const status = (error as { status?: unknown })?.status;\n return typeof status === 'number' && status >= 500;\n}\n\nconst SH_RETRIES = 2;\nconst SH_RETRY_DELAY_MS = 2000;\n\n/**\n * Run a shell script in the sandbox via `sh -c`. This is reserved for the\n * explicitly configured repository lifecycle hooks; programmatic commands use\n * {@link execute} with an argv array.\n */\nexport async function sh(\n sandbox: ExecutableSandbox,\n script: string,\n options: ShOptions & Pick<CommandOptions, 'env'> = {},\n): Promise<SandboxCommandResult> {\n return execute(sandbox, 'sh', ['-c', script], options);\n}\n\n/**\n * Execute one program with an argv array, bounded by a hang guard. Transient\n * sandbox transport failures are retried without ever interpolating arguments\n * into a shell command.\n */\nasync function execute(\n sandbox: ExecutableSandbox,\n command: string,\n args: string[],\n options: CommandOptions = {},\n): Promise<SandboxCommandResult> {\n const deadlineMs = Date.now() + (options.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS);\n for (let attempt = 0; ; attempt++) {\n const started = performance.now();\n try {\n const result = await executeOnce(sandbox, command, args, {\n ...options,\n timeoutMs: Math.max(deadlineMs - Date.now(), 1),\n });\n if (options.phase) {\n const elapsed = performance.now() - started;\n if (bootDiagnosticsEnabled) {\n process.stderr.write(\n `[factory:timing] ${options.phase} attempt=${attempt + 1} exit=${result.exitCode} ${Math.round(elapsed)}ms\\n`,\n );\n }\n recordSandboxCommand(options.phase, elapsed, result.exitCode === 0 ? 'ok' : 'exit');\n }\n return result;\n } catch (error) {\n if (options.phase) {\n const elapsed = performance.now() - started;\n process.stderr.write(\n `[factory:timing] ${options.phase} attempt=${attempt + 1} threw after ${Math.round(elapsed)}ms: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n recordSandboxCommand(options.phase, elapsed, 'threw');\n }\n if (attempt >= SH_RETRIES || !isTransientTransportError(error)) throw error;\n const delayMs = SH_RETRY_DELAY_MS * (attempt + 1);\n if (deadlineMs - Date.now() <= delayMs) throw error;\n await new Promise(resolve => setTimeout(resolve, delayMs));\n }\n }\n}\n\n/** Single structured command execution attempt, bounded by the hang guard. */\nasync function executeOnce(\n sandbox: ExecutableSandbox,\n command: string,\n args: string[],\n options: CommandOptions,\n): Promise<SandboxCommandResult> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const hangGuard = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const phase = options.phase ? ` during ${options.phase}` : '';\n reject(new Error(`Sandbox command timed out after ${Math.round(timeoutMs / 1000)}s${phase}.`));\n }, timeoutMs);\n timer.unref?.();\n });\n try {\n return await Promise.race([\n sandbox.executeCommand(command, args, {\n timeout: timeoutMs,\n ...(options.cwd !== undefined ? { cwd: options.cwd } : {}),\n ...(options.env !== undefined ? { env: options.env } : {}),\n }),\n hangGuard,\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nconst GIT_TRANSFER_RETRIES = 2;\nconst GIT_TRANSFER_RETRY_DELAY_MS = 2000;\n\n/**\n * True when a git transfer died mid-flight rather than being refused.\n *\n * `sh` already retries transport errors the sandbox provider *throws*, but a\n * git command that reaches the network and then loses it exits non-zero\n * instead — so a single HTTP/2 framing glitch or dropped connection to\n * github.com would otherwise permanently fail opening a workspace. These\n * patterns all mean \"the bytes stopped arriving\", which says nothing about\n * whether the operation would succeed if attempted again.\n *\n * Deliberately narrow: a refusal (bad credentials, missing repo, blocked\n * egress) is terminal and must surface immediately rather than be retried into\n * a slow failure.\n */\nfunction isTransientGitFailure(result: SandboxCommandResult): boolean {\n const output = `${result.stderr || ''}\\n${result.stdout || ''}`;\n return /HTTP2 framing layer|RPC failed; curl|RPC failed; HTTP 5\\d\\d|the remote end hung up unexpectedly|early EOF|unexpected disconnect|connection reset by peer|Recv failure|Send failure|GnuTLS recv error|TLS connection was non-properly terminated|502 Bad Gateway|503 Service Unavailable/i.test(\n output,\n );\n}\n\n/**\n * Run a git command that only *reads* from the remote, retrying it when the\n * transfer dies mid-flight. Restricted to read-only transfers on purpose:\n * re-running a clone or a fetch is free, whereas re-running a push could\n * duplicate work already accepted by the remote before the connection dropped.\n *\n * `beforeRetry` lets a call site clear whatever the aborted attempt left\n * behind — a half-written clone directory blocks the next `git clone` outright.\n */\nasync function gitTransfer(\n sandbox: ExecutableSandbox,\n args: string[],\n options: CommandOptions & { beforeRetry?: (attempt: number) => Promise<void> } = {},\n): Promise<SandboxCommandResult> {\n const { beforeRetry, ...commandOptions } = options;\n const deadlineMs = Date.now() + (commandOptions.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS);\n for (let attempt = 0; ; attempt++) {\n const result = await execute(sandbox, 'git', args, {\n ...commandOptions,\n timeoutMs: Math.max(deadlineMs - Date.now(), 1),\n });\n if (result.exitCode === 0 || attempt >= GIT_TRANSFER_RETRIES || !isTransientGitFailure(result)) return result;\n process.stderr.write(\n `[factory:timing] git ${commandOptions.phase ?? 'transfer'} retrying after attempt ${attempt + 1}\\n`,\n );\n const delayMs = GIT_TRANSFER_RETRY_DELAY_MS * (attempt + 1);\n if (deadlineMs - Date.now() <= delayMs) return result;\n await new Promise(resolve => setTimeout(resolve, delayMs));\n await beforeRetry?.(attempt + 1);\n }\n}\n\n/** Error raised when the sandbox cannot materialize the repo (actionable). */\nexport class MaterializeError extends Error {\n constructor(\n message: string,\n readonly code:\n | 'git-missing'\n | 'sandbox-unresponsive'\n | 'egress-blocked'\n | 'clone-failed'\n | 'pull-failed'\n | 'push-failed'\n | 'commit-failed'\n | 'gh-missing'\n | 'pr-failed',\n ) {\n super(message);\n this.name = 'MaterializeError';\n }\n}\n\nfunction cleanUrl(repoFullName: string): string {\n return `https://github.com/${repoFullName}.git`;\n}\n\n/**\n * True when a repository name or clone URL contains a `.` or `..` path segment.\n * `new URL` and git both collapse those, and `new URL` also treats `\\` as `/`,\n * so `owner/../other` names a different repository than the row. Checked on the\n * raw text, before that collapse. A backslash is refused on its own: the origin\n * strip below would otherwise treat it as part of the host.\n */\nfunction pathHasDotSegment(value: string): boolean {\n if (value.includes('\\\\')) return true;\n const withoutOrigin = value.replace(/^[a-z][a-z0-9+.-]*:\\/\\/[^/?#]*/i, '');\n const path = withoutOrigin.split(/[?#]/)[0] ?? '';\n return path.split('/').some(part => {\n let decoded = part;\n try {\n decoded = decodeURIComponent(part);\n } catch {\n return true;\n }\n return decoded === '.' || decoded === '..' || decoded.includes('\\\\');\n });\n}\n\nfunction assertRepositoryLocator(\n repoFullName: string | undefined,\n cloneUrl: string | undefined,\n code: 'clone-failed' | 'pull-failed' | 'push-failed',\n): void {\n if (\n repoFullName !== undefined &&\n (!/^[\\w.-]+(?:\\/[\\w.-]+)+$/.test(repoFullName) || pathHasDotSegment(repoFullName))\n ) {\n throw new MaterializeError(`Refusing to use an invalid repo full name '${repoFullName}'.`, code);\n }\n if (cloneUrl && pathHasDotSegment(cloneUrl)) {\n throw new MaterializeError('Refusing to use a clone URL whose path rewrites to another repository.', code);\n }\n}\n\nfunction credentialScope(\n cloneUrl: string,\n code: 'clone-failed' | 'pull-failed' | 'push-failed' = 'clone-failed',\n): string {\n let url: URL;\n try {\n url = new URL(cloneUrl);\n } catch {\n throw new MaterializeError('Refusing to configure credentials for an invalid repository clone URL.', code);\n }\n if (url.protocol !== 'https:' || !url.hostname || url.username || url.password || url.search || url.hash) {\n throw new MaterializeError('Refusing to configure credentials for an invalid repository clone URL.', code);\n }\n const repositoryPath = url.pathname.replace(/\\/+$/, '');\n if (!repositoryPath || repositoryPath === '/') {\n throw new MaterializeError('Refusing to configure credentials for an invalid repository clone URL.', code);\n }\n return url.origin + repositoryPath;\n}\n\n/**\n * Provide HTTP Basic credentials to one Git process without putting a secret\n * in argv, a remote URL, or persistent git config. Git reads the URL-scoped\n * extra header from its process environment and discards it on exit.\n */\nfunction gitAuthenticationEnvironment(\n cloneUrl: string,\n token: string,\n username: string,\n code: 'clone-failed' | 'pull-failed' | 'push-failed' = 'clone-failed',\n): Record<string, string> {\n const scope = credentialScope(cloneUrl, code);\n if (!token || !username) {\n throw new MaterializeError('Repository access did not include usable credentials.', code);\n }\n const authorization = Buffer.from(`${username}:${token}`, 'utf8').toString('base64');\n // Git applies `http.<url>.*` only when the config URL matches the remote at\n // a path boundary, and `origin` may spell the repository either way: Factory\n // clones with `.git`, a sandbox template clones from the normalized URL\n // without it. Scope the header to both so neither checkout prompts.\n const alternate = scope.endsWith('.git') ? scope.slice(0, -4) : `${scope}.git`;\n return {\n GIT_CONFIG_COUNT: '2',\n GIT_CONFIG_KEY_0: `http.${scope}.extraHeader`,\n GIT_CONFIG_VALUE_0: `Authorization: Basic ${authorization}`,\n GIT_CONFIG_KEY_1: `http.${alternate}.extraHeader`,\n GIT_CONFIG_VALUE_1: `Authorization: Basic ${authorization}`,\n GIT_TERMINAL_PROMPT: '0',\n };\n}\n\nfunction normalizedRemoteUrl(value: string): string | null {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return null;\n }\n if (url.protocol !== 'https:' || !url.hostname || url.search || url.hash) return null;\n const pathname = url.pathname.replace(/\\/+$/, '').replace(/\\.git$/i, '');\n const repositoryPath = url.hostname.toLowerCase() === 'github.com' ? pathname.toLowerCase() : pathname;\n return 'https://' + url.host.toLowerCase() + repositoryPath;\n}\n\n/** Repo metadata needed to materialize, read from the org-owned project row. */\nexport interface RepoMaterializeInfo {\n repoFullName: string;\n defaultBranch: string;\n /** Provider-supplied, credential-free HTTPS clone URL. */\n cloneUrl?: string;\n /** Username paired with the bearer token for git-over-HTTPS. */\n authUsername?: string;\n}\n\n/** Options for {@link materializeRepo}. */\nexport interface MaterializeRepoOptions {\n /** The per-(project,user) sandbox binding whose workdir this materializes into. */\n row: RepoMaterializationBinding;\n /** Repo metadata from the org-owned project row. */\n repoInfo: RepoMaterializeInfo;\n /** The live sandbox to run git inside. */\n sandbox: ExecutableSandbox;\n /** A freshly minted, short-lived installation access token. */\n token: string;\n storage: MaterializationStore;\n}\n\nasync function clearWorkdir(sandbox: ExecutableSandbox, workdir: string): Promise<void> {\n const mkdir = await execute(sandbox, 'mkdir', ['-p', workdir]);\n if (mkdir.exitCode !== 0) throw classifyGitFailure(mkdir, 'clone-failed');\n const clear = await execute(sandbox, 'find', [\n workdir,\n '-mindepth',\n '1',\n '-maxdepth',\n '1',\n '-exec',\n 'rm',\n '-rf',\n '--',\n '{}',\n '+',\n ]);\n if (clear.exitCode !== 0) throw classifyGitFailure(clear, 'clone-failed');\n}\n/**\n * Materialize the repo inside the user's sandbox: clone when no checkout of\n * this repo exists, otherwise nothing. Credentials are process-scoped and the\n * stored remote remains credential-free. Sets `materialized_at` on the\n * per-user sandbox binding row.\n */\nexport async function materializeRepo(options: MaterializeRepoOptions): Promise<void> {\n return timedPhase('workspace.materialize', () => materializeRepoImpl(options));\n}\n\nasync function materializeRepoImpl(options: MaterializeRepoOptions): Promise<void> {\n const { row: sandboxRow, repoInfo, sandbox, token, storage } = options;\n const workdir = sandboxRow.sandboxWorkdir;\n const repo = repoInfo.repoFullName;\n\n // 0. Defense in depth: never build a git command from values that aren't\n // strictly shaped, even if a malformed row reached the DB. Inputs are also\n // validated at the route boundary before storage. `..` in a repository path\n // collapses to a different repository, and a branch git can read as an option\n // is rejected by the same ref rules the checkout path uses.\n assertRepositoryLocator(repo, repoInfo.cloneUrl, 'clone-failed');\n if (!isValidGitRef(repoInfo.defaultBranch)) {\n throw new MaterializeError(\n `Refusing to materialize: invalid default branch '${repoInfo.defaultBranch}'.`,\n 'clone-failed',\n );\n }\n\n // 1. Preflight: git must be installed in the sandbox template. Exit 124 is\n // the provider's timeout code: the VM stopped answering, which says nothing\n // about git, so it must not be reported as a missing binary.\n const gitVersion = await execute(sandbox, 'git', ['--version']);\n if (gitVersion.exitCode === 124) {\n throw new MaterializeError(\n 'The sandbox stopped responding: `git --version` timed out (exit 124). Recreate the sandbox.',\n 'sandbox-unresponsive',\n );\n }\n if (gitVersion.exitCode !== 0) {\n const detail = (gitVersion.stderr || gitVersion.stdout).trim().slice(-500) || '(no output)';\n throw new MaterializeError(\n `git is not installed in the sandbox: \\`git --version\\` exited ${gitVersion.exitCode}: ${detail}. The sandbox template must include git.`,\n 'git-missing',\n );\n }\n\n // The DB's `materializedAt` can drift from disk in both directions: a fresh\n // binding row over an already-populated workdir (a repo template image,\n // local dev DB resets, repaired rows) must not fail `git clone` on the\n // non-empty directory, and a stale `materializedAt` over an empty sandbox\n // (an expired/recreated VM whose disk was wiped) must re-clone instead of\n // running `git -C <workdir>` against a directory that no longer exists.\n // Disk is the source of truth: detect the checkout instead of trusting the\n // row. An existing checkout is left as it is, whatever it is on: a template\n // image sits detached at its pinned commit, a resumed session on its\n // branch. Syncing with the remote is the session's business; the branch\n // checkout that follows fetches the base branch it needs.\n const cleanCloneUrl = repoInfo.cloneUrl ?? cleanUrl(repo);\n const existing = await existingCheckoutRemote(sandbox, workdir, cleanCloneUrl);\n if (existing !== null) {\n // A token an earlier start failed to scrub must not outlive it; the\n // remote already carries the plain URL otherwise, so this costs nothing\n // on the common path.\n if (/\\/\\/[^/]*@/.test(existing)) await scrubRemote(sandbox, workdir, repo, cleanCloneUrl);\n } else {\n // 2. First open: shallow-clone the default branch into the workdir, the\n // same clone a repo template bakes into its image. The workdir holds no\n // usable checkout of this repo, but it may not be empty: a checkpoint\n // seed or a clone that died partway (a crashed or OOM-killed server)\n // leaves a partial tree behind, and `git clone` refuses a non-empty\n // destination with a non-retryable fatal. Nothing here is recoverable,\n // the probe above already ruled out a checkout of this repo, so\n // clear its contents before cloning, exactly as the retry path does. Keep\n // the workdir itself because Factory's own commands use it as their cwd\n // (`gh pr create`, and the `cd` each lifecycle command starts with), so it\n // has to exist as a directory.\n const authEnv = gitAuthenticationEnvironment(\n cleanCloneUrl,\n token,\n repoInfo.authUsername ?? 'x-access-token',\n 'clone-failed',\n );\n await clearWorkdir(sandbox, workdir);\n const clone = await gitTransfer(\n sandbox,\n ['clone', '--depth=1', '--single-branch', '--branch', repoInfo.defaultBranch, '--', cleanCloneUrl, workdir],\n {\n env: authEnv,\n phase: 'repository clone',\n beforeRetry: async () => {\n // A clone that died partway leaves the destination non-empty, which\n // git refuses to clone into. Clear its contents so the retry starts\n // clean, leaving a directory Factory's commands still use as cwd.\n await clearWorkdir(sandbox, workdir);\n },\n },\n );\n if (clone.exitCode !== 0) throw classifyGitFailure(clone, 'clone-failed');\n }\n\n // 4. Mark materialized.\n await storage.markMaterialized({ id: sandboxRow.id });\n}\n\nexport interface SessionBranchOptions {\n /** Repository-local authorship configured before setup commands or agent access. */\n identity?: GitIdentity;\n branch: string;\n baseBranch: string;\n token: string;\n repoFullName: string;\n cloneUrl?: string;\n authUsername?: string;\n /** A pull-request card's session starts on the PR head instead of the base tip. */\n pullRequestNumber?: number;\n /** A GitLab merge-request card's session starts on the MR head instead of the base tip. */\n mergeRequestNumber?: number;\n}\n\n/**\n * Past file contents of a blob-less history load on demand; git asks gh, which\n * answers from the session's `GH_TOKEN`, so no credential is ever written.\n */\nconst GH_CREDENTIAL_HELPER = '!gh auth git-credential';\n\n/**\n * The git credential helper for a GitHub checkout whose repository is covered\n * by a numbered group token (`GH_TOKEN_2`, ...) instead of `GH_TOKEN`. It\n * falls back to `GH_TOKEN` while the group token is unset, as it is when an\n * org PAT is installed.\n */\nexport function githubCredentialHelper(tokenEnvName = 'GH_TOKEN'): string {\n if (tokenEnvName === 'GH_TOKEN') return GH_CREDENTIAL_HELPER;\n if (!/^GH_TOKEN_\\d+$/.test(tokenEnvName)) throw new Error(`Invalid GitHub token variable: ${tokenEnvName}`);\n return `!f() { GH_TOKEN=\"\\${${tokenEnvName}:-$GH_TOKEN}\" gh auth git-credential \"$@\"; }; f`;\n}\n\nasync function fetchStartPoint(\n sandbox: ExecutableSandbox,\n workdir: string,\n {\n baseBranch,\n pullRequestNumber,\n mergeRequestNumber,\n }: Pick<SessionBranchOptions, 'baseBranch' | 'pullRequestNumber' | 'mergeRequestNumber'>,\n shallowClone: boolean,\n env: Record<string, string>,\n): Promise<SandboxCommandResult> {\n const changeRequestRef =\n pullRequestNumber !== undefined\n ? `refs/pull/${pullRequestNumber}/head`\n : mergeRequestNumber !== undefined\n ? `refs/merge-requests/${mergeRequestNumber}/head`\n : undefined;\n const baseArgs = [\n '-C',\n workdir,\n 'fetch',\n ...(changeRequestRef && shallowClone ? ['--unshallow'] : []),\n ...(pullRequestNumber !== undefined ? ['--filter=blob:none'] : []),\n 'origin',\n baseBranch,\n ];\n const base = await gitTransfer(sandbox, baseArgs, {\n env,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'branch checkout fetch',\n });\n if (base.exitCode !== 0 || !changeRequestRef) return base;\n return gitTransfer(\n sandbox,\n [\n '-C',\n workdir,\n 'fetch',\n ...(pullRequestNumber !== undefined ? ['--filter=blob:none'] : []),\n 'origin',\n changeRequestRef,\n ],\n {\n env,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'change request head fetch',\n },\n );\n}\n\n/** Check out a session's branch inside its isolated repository clone. */\nexport async function checkoutSessionBranch(\n sandbox: ExecutableSandbox,\n workdir: string,\n options: SessionBranchOptions,\n): Promise<void> {\n return timedPhase('workspace.checkout', () => checkoutSessionBranchImpl(sandbox, workdir, options));\n}\n\nexport interface SyncEnvironmentRepositoryOptions {\n /** Repository-local authorship configured before setup commands or agent access. */\n identity?: GitIdentity;\n /** The session branch to resume when the remote already carries it. */\n branch: string;\n /** The repository's default branch; new session branches start at its remote tip. */\n defaultBranch: string;\n token: string;\n repoFullName: string;\n cloneUrl?: string;\n authUsername?: string;\n /**\n * The sandbox variable carrying this GitHub repository's token; the checkout\n * gets a credential helper reading it. Ignored when `authUsername` is set.\n */\n tokenEnvName?: string;\n}\n\nexport interface EnvironmentSyncResult {\n outcome: 'resumed' | 'created' | 'kept';\n /** The branch the checkout ends on; `null` when it stays detached. */\n branch: string | null;\n}\n\n/**\n * Bring a secondary environment repository onto the session branch at\n * session start. The primary repository keeps {@link checkoutSessionBranch};\n * every other repository follows a conservative rule: resume the session\n * branch when the remote or the local clone has it, otherwise create it from\n * the default branch tip (a detached HEAD, the template image pinned at its\n * build commit, is moved there first). A checkout that sits on any other\n * branch is left alone: it may carry local-only commits.\n */\nexport async function syncEnvironmentRepository(\n sandbox: ExecutableSandbox,\n workdir: string,\n options: SyncEnvironmentRepositoryOptions,\n): Promise<EnvironmentSyncResult> {\n const { branch, defaultBranch, token, repoFullName, cloneUrl, authUsername } = options;\n if (!isValidGitRef(branch) || !isValidGitRef(defaultBranch)) {\n throw new MaterializeError('Refusing to sync a repository from an invalid branch name.', 'pull-failed');\n }\n assertRepositoryLocator(repoFullName, cloneUrl, 'pull-failed');\n const cleanCloneUrl = cloneUrl ?? cleanUrl(repoFullName);\n const authEnv = gitAuthenticationEnvironment(cleanCloneUrl, token, authUsername ?? 'x-access-token', 'pull-failed');\n\n // Raw git in this checkout (push, fetch) authenticates through gh with the\n // token that covers this repository, like the session repository does.\n if (!authUsername) {\n const configured = await execute(sandbox, 'git', [\n '-C',\n workdir,\n 'config',\n 'credential.helper',\n githubCredentialHelper(options.tokenEnvName),\n ]);\n if (configured.exitCode !== 0) throw classifyGitFailure(configured, 'pull-failed');\n }\n\n await configureGitIdentity(sandbox, workdir, options.identity ?? {});\n\n const current = await execute(sandbox, 'git', ['-C', workdir, 'branch', '--show-current']);\n if (current.exitCode !== 0) throw classifyGitFailure(current, 'pull-failed');\n const currentBranch = current.stdout.trim();\n const kept = { outcome: 'kept' as const, branch: currentBranch || null };\n if (currentBranch === branch) return kept;\n\n // A local session branch may hold commits the remote never saw; switch\n // to it instead of resetting it onto the remote tip.\n const local = await execute(sandbox, 'git', [\n '-C',\n workdir,\n 'rev-parse',\n '--verify',\n '--quiet',\n `refs/heads/${branch}`,\n ]);\n if (local.exitCode === 0) {\n const checkout = await execute(sandbox, 'git', ['-C', workdir, 'checkout', branch], {\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'environment branch checkout',\n });\n if (checkout.exitCode === 0) return { outcome: 'resumed', branch };\n if (isBlockedByLocalWork(checkout)) return kept;\n throw classifyGitFailure(checkout, 'pull-failed');\n }\n\n const remoteHeads = await gitTransfer(\n sandbox,\n ['-C', workdir, 'ls-remote', '--heads', 'origin', `refs/heads/${branch}`],\n { env: authEnv, timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS, phase: 'environment branch probe' },\n );\n if (remoteHeads.exitCode !== 0) throw classifyGitFailure(remoteHeads, 'pull-failed');\n if (remoteHeads.stdout.trim()) {\n const fetch = await gitTransfer(sandbox, ['-C', workdir, 'fetch', 'origin', branch], {\n env: authEnv,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'environment branch fetch',\n });\n if (fetch.exitCode !== 0) throw classifyGitFailure(fetch, 'pull-failed');\n const checkout = await execute(sandbox, 'git', ['-C', workdir, 'checkout', '-B', branch, 'FETCH_HEAD'], {\n env: authEnv,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'environment branch checkout',\n });\n if (checkout.exitCode === 0) return { outcome: 'resumed', branch };\n if (isBlockedByLocalWork(checkout)) return kept;\n throw classifyGitFailure(checkout, 'pull-failed');\n }\n\n // A checkout on any other branch stays where it is: it may hold work the\n // remote never saw. The default branch and a detached HEAD (the template\n // image pinned at its build commit) become the session branch.\n if (currentBranch && currentBranch !== defaultBranch) return kept;\n if (currentBranch) {\n const status = await execute(sandbox, 'git', ['-C', workdir, 'status', '--porcelain']);\n if (status.exitCode !== 0) throw classifyGitFailure(status, 'pull-failed');\n if (status.stdout.trim()) return kept;\n }\n const fetch = await gitTransfer(sandbox, ['-C', workdir, 'fetch', 'origin', defaultBranch], {\n env: authEnv,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'environment default fetch',\n });\n if (fetch.exitCode !== 0) throw classifyGitFailure(fetch, 'pull-failed');\n if (currentBranch) {\n // Do not discard local-only commits on the default branch. A shallow\n // checkout whose ancestry cannot be established is also left untouched.\n const ancestor = await execute(sandbox, 'git', [\n '-C',\n workdir,\n 'merge-base',\n '--is-ancestor',\n 'HEAD',\n 'FETCH_HEAD',\n ]);\n if (ancestor.exitCode === 1) return kept;\n if (ancestor.exitCode !== 0) throw classifyGitFailure(ancestor, 'pull-failed');\n } else {\n const checkout = await execute(sandbox, 'git', ['-C', workdir, 'checkout', '-B', defaultBranch, 'FETCH_HEAD'], {\n env: authEnv,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'environment default checkout',\n });\n if (checkout.exitCode !== 0) {\n if (isBlockedByLocalWork(checkout)) return kept;\n throw classifyGitFailure(checkout, 'pull-failed');\n }\n }\n const created = await execute(sandbox, 'git', ['-C', workdir, 'checkout', '-b', branch, 'FETCH_HEAD'], {\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'environment branch create',\n });\n if (created.exitCode === 0) return { outcome: 'created', branch };\n throw classifyGitFailure(created, 'pull-failed');\n}\n\n/** Refresh an existing GitLab review checkout without exposing its credential to the agent. */\nexport async function refreshMergeRequestCheckout(\n sandbox: ExecutableSandbox,\n workdir: string,\n input: { branch: string; mergeRequestNumber: number; expectedHeadSha: string; access: RepositoryAccess },\n): Promise<{ headSha: string; changed: boolean }> {\n const { branch, mergeRequestNumber, expectedHeadSha, access } = input;\n assertRepositoryLocator(undefined, access.cloneUrl, 'pull-failed');\n if (\n !isValidGitRef(branch) ||\n !Number.isSafeInteger(mergeRequestNumber) ||\n mergeRequestNumber <= 0 ||\n !/^[0-9a-f]{40}$/i.test(expectedHeadSha)\n ) {\n throw new Error('Refusing to refresh a GitLab review with invalid session or head metadata.');\n }\n const token = access.authorization?.token;\n if (!token) throw new Error('GitLab repository access did not include a bearer token.');\n const env = gitAuthenticationEnvironment(\n access.cloneUrl,\n token,\n access.authorization?.username ?? 'oauth2',\n 'pull-failed',\n );\n const current = await execute(sandbox, 'git', ['-C', workdir, 'branch', '--show-current']);\n if (current.exitCode !== 0 || current.stdout.trim() !== branch) {\n throw new Error('The active checkout is not on its bound review branch.');\n }\n const status = await execute(sandbox, 'git', ['-C', workdir, 'status', '--porcelain', '--untracked-files=all']);\n if (status.exitCode !== 0 || status.stdout.trim()) {\n throw new Error('The review checkout has local changes; refusing to replace them.');\n }\n const before = await execute(sandbox, 'git', ['-C', workdir, 'rev-parse', 'HEAD']);\n if (before.exitCode !== 0) throw new Error('Could not read the current review checkout head.');\n const fetch = await gitTransfer(\n sandbox,\n ['-C', workdir, 'fetch', 'origin', `refs/merge-requests/${mergeRequestNumber}/head`],\n {\n env,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'GitLab review head refresh',\n },\n );\n if (fetch.exitCode !== 0) throw classifyGitFailure(fetch, 'pull-failed');\n const fetched = await execute(sandbox, 'git', ['-C', workdir, 'rev-parse', 'FETCH_HEAD']);\n if (fetched.exitCode !== 0 || fetched.stdout.trim().toLowerCase() !== expectedHeadSha.toLowerCase()) {\n throw new Error('The fetched GitLab review head differs from the provider-reported head; retry after it settles.');\n }\n if (before.stdout.trim().toLowerCase() === expectedHeadSha.toLowerCase()) {\n return { headSha: expectedHeadSha, changed: false };\n }\n const updated = await execute(sandbox, 'git', ['-C', workdir, 'checkout', '-B', branch, 'FETCH_HEAD'], { env });\n if (updated.exitCode !== 0) throw classifyGitFailure(updated, 'pull-failed');\n return { headSha: expectedHeadSha, changed: true };\n}\n\nasync function checkoutSessionBranchImpl(\n sandbox: ExecutableSandbox,\n workdir: string,\n options: SessionBranchOptions,\n): Promise<void> {\n const { branch, baseBranch, token, repoFullName, pullRequestNumber, mergeRequestNumber, cloneUrl, authUsername } =\n options;\n if (\n !isValidGitRef(branch) ||\n !isValidGitRef(baseBranch) ||\n (pullRequestNumber !== undefined && mergeRequestNumber !== undefined) ||\n (mergeRequestNumber !== undefined && (!Number.isSafeInteger(mergeRequestNumber) || mergeRequestNumber <= 0))\n ) {\n throw new MaterializeError('Refusing to create a session from an invalid branch name.', 'clone-failed');\n }\n assertRepositoryLocator(repoFullName, cloneUrl, 'clone-failed');\n\n const changeRequestSession = pullRequestNumber !== undefined || mergeRequestNumber !== undefined;\n // GitHub delegates later authenticated operations to `gh`. Other providers\n // deliberately receive no persistent credential helper. Remove the legacy\n // helper when reopening an older checkout so a stale sandbox cannot retain\n // credentials injected by an earlier implementation.\n const cleanCloneUrl = cloneUrl ?? cleanUrl(repoFullName);\n const authEnv = gitAuthenticationEnvironment(cleanCloneUrl, token, authUsername ?? 'x-access-token', 'pull-failed');\n const credentialKey = authUsername ? 'credential.' + credentialScope(cleanCloneUrl) + '.helper' : 'credential.helper';\n if (authUsername) {\n await execute(sandbox, 'git', ['-C', workdir, 'config', '--unset-all', credentialKey]);\n } else {\n const configured = await execute(sandbox, 'git', ['-C', workdir, 'config', credentialKey, GH_CREDENTIAL_HELPER]);\n if (configured.exitCode !== 0) throw classifyGitFailure(configured, 'pull-failed');\n }\n\n await configureGitIdentity(sandbox, workdir, options.identity ?? {});\n\n const current = await execute(sandbox, 'git', ['-C', workdir, 'branch', '--show-current']);\n if (current.exitCode === 0 && current.stdout.trim() === branch) return;\n\n const local = await execute(sandbox, 'git', [\n '-C',\n workdir,\n 'show-ref',\n '--verify',\n '--quiet',\n `refs/heads/${branch}`,\n ]);\n if (local.exitCode === 0) {\n const checkout = await execute(sandbox, 'git', ['-C', workdir, 'checkout', branch], { env: authEnv });\n if (checkout.exitCode !== 0) {\n if (isBlockedByLocalWork(checkout)) return;\n throw classifyGitFailure(checkout, 'clone-failed');\n }\n return;\n }\n\n const shallowClone =\n changeRequestSession &&\n (await execute(sandbox, 'git', ['-C', workdir, 'rev-parse', '--is-shallow-repository'])).stdout.trim() === 'true';\n const fetch = await fetchStartPoint(sandbox, workdir, options, shallowClone, authEnv);\n if (fetch.exitCode !== 0) throw classifyGitFailure(fetch, 'pull-failed');\n\n const create = await execute(sandbox, 'git', ['-C', workdir, 'checkout', '-b', branch, 'FETCH_HEAD'], {\n env: authEnv,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'branch checkout',\n });\n if (create.exitCode === 0 || isBlockedByLocalWork(create)) return;\n if (!isBranchCollision(create)) throw classifyGitFailure(create, 'clone-failed');\n\n // The branch exists even though the show-ref probe missed it: either another\n // materialization created it concurrently (adopt it), or the sandbox carries\n // a broken loose ref (remove it and retry).\n const adopt = await execute(sandbox, 'git', ['-C', workdir, 'checkout', branch], { env: authEnv });\n if (adopt.exitCode === 0 || isBlockedByLocalWork(adopt)) return;\n\n let drop = await execute(sandbox, 'git', ['-C', workdir, 'update-ref', '--no-deref', '-d', `refs/heads/${branch}`]);\n if (drop.exitCode !== 0) {\n const gitDir = await execute(sandbox, 'git', ['-C', workdir, 'rev-parse', '--absolute-git-dir']);\n if (gitDir.exitCode !== 0 || !gitDir.stdout.trim()) throw classifyGitFailure(create, 'clone-failed');\n drop = await execute(sandbox, 'rm', ['-f', '--', `${gitDir.stdout.trim()}/refs/heads/${branch}`]);\n }\n if (drop.exitCode !== 0) throw classifyGitFailure(create, 'clone-failed');\n\n const retry = await execute(sandbox, 'git', ['-C', workdir, 'checkout', '-b', branch, 'FETCH_HEAD'], {\n env: authEnv,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'branch checkout retry',\n });\n if (retry.exitCode !== 0) {\n if (isBlockedByLocalWork(retry)) return;\n throw classifyGitFailure(retry, 'clone-failed');\n }\n}\n\n/**\n * True when `git checkout -b` failed only because the branch ref already\n * exists — the collision Factory hits when a pooled sandbox carries a ref the\n * show-ref probe could not see (broken loose ref) or a concurrent\n * materialization created the branch after the probe ran.\n */\nfunction isBranchCollision(result: SandboxCommandResult): boolean {\n return /a branch named .* already exists/i.test(`${result.stderr || ''}\\n${result.stdout || ''}`);\n}\n\n/**\n * True when a failed `git checkout` just means uncommitted or untracked files\n * in the working tree would be clobbered by the branch switch. Those files are\n * a session's work in progress — the switch must yield to them, never the\n * other way around.\n */\nfunction isBlockedByLocalWork(result: SandboxCommandResult): boolean {\n const output = `${result.stderr || ''}\\n${result.stdout || ''}`;\n return /Your local changes to the following files would be overwritten by checkout|untracked working tree files would be overwritten by checkout/i.test(\n output,\n );\n}\n\n/**\n * Return the origin URL when the workdir contains this repository, including a\n * legacy checkout whose remote still embeds credentials.\n */\nasync function existingCheckoutRemote(\n sandbox: ExecutableSandbox,\n workdir: string,\n cloneUrl: string,\n): Promise<string | null> {\n const result = await execute(sandbox, 'git', ['-C', workdir, 'remote', 'get-url', 'origin']);\n if (result.exitCode !== 0) return null;\n const url = result.stdout.trim();\n const actual = normalizedRemoteUrl(url);\n const expected = normalizedRemoteUrl(cloneUrl);\n return actual !== null && expected !== null && actual === expected ? url : null;\n}\n\n/** Remove credentials persisted by an older implementation from origin. */\nasync function scrubRemote(\n sandbox: ExecutableSandbox,\n workdir: string,\n repoFullName: string,\n cloneUrl: string = cleanUrl(repoFullName),\n): Promise<void> {\n let failure: string;\n try {\n const result = await execute(sandbox, 'git', ['-C', workdir, 'remote', 'set-url', 'origin', cloneUrl]);\n if (result.exitCode === 0) return;\n failure = result.stderr.trim() || result.stdout.trim();\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n throw new MaterializeError(`Failed to scrub installation token from git remote: ${failure}`, 'pull-failed');\n}\n\n/**\n * Turn a failed git command into an actionable error, detecting the common\n * \"cannot reach github.com\" egress failure.\n */\nfunction classifyGitFailure(\n result: SandboxCommandResult,\n fallback: 'clone-failed' | 'pull-failed' | 'push-failed',\n): MaterializeError {\n const stderr = result.stderr || '';\n if (/could not resolve host|failed to connect|network is unreachable|Connection timed out/i.test(stderr)) {\n return new MaterializeError(\n 'The sandbox could not reach github.com. The sandbox network must allow outbound egress to github.com.',\n 'egress-blocked',\n );\n }\n const verb = fallback === 'clone-failed' ? 'clone' : fallback === 'pull-failed' ? 'pull' : 'push';\n return new MaterializeError(`git ${verb} failed: ${stderr}`, fallback);\n}\n\n// ---------------------------------------------------------------------------\n// Phase 1 — git identity + token-scoped push primitive\n//\n// These helpers let the sandbox author and push commits safely. The install\n// token is short-lived, minted per-operation server-side, and supplied only to\n// the Git process through its environment. It never enters argv or persistent\n// repository configuration.\n// ---------------------------------------------------------------------------\n\nexport { isValidGitRef };\n\n/** Identity used to author commits inside the sandbox. */\nexport interface GitIdentity {\n name?: string | null;\n email?: string | null;\n /** GitHub login, used to derive a stable noreply identity when name/email are absent. */\n login?: string | null;\n}\n\n/**\n * Resolve a concrete `{ name, email }` for git authorship from a possibly-sparse\n * identity. Falls back to a GitHub-style noreply identity so commits are never\n * authored with an empty or host-derived identity.\n */\nexport function resolveGitIdentity(identity: GitIdentity): { name: string; email: string } {\n const login = (identity.login || '').trim();\n const name = (identity.name || '').trim() || login || 'Mastra Code';\n const email =\n (identity.email || '').trim() ||\n (login ? `${login}@users.noreply.github.com` : 'mastra-code@users.noreply.github.com');\n return { name, email };\n}\n\n/** Configure repository-local commit identity through direct Git argv calls. */\nexport async function configureGitIdentity(\n sandbox: ExecutableSandbox,\n workdir: string,\n identity: GitIdentity,\n): Promise<void> {\n const { name, email } = resolveGitIdentity(identity);\n const setName = await execute(sandbox, 'git', ['-C', workdir, 'config', 'user.name', name]);\n if (setName.exitCode !== 0) {\n throw new MaterializeError(`Failed to set git user.name: ${setName.stderr.trim()}`, 'commit-failed');\n }\n const setEmail = await execute(sandbox, 'git', ['-C', workdir, 'config', 'user.email', email]);\n if (setEmail.exitCode !== 0) {\n throw new MaterializeError(`Failed to set git user.email: ${setEmail.stderr.trim()}`, 'commit-failed');\n }\n}\n\nasync function pushAuthenticatedBranch(\n sandbox: ExecutableSandbox,\n workdir: string,\n branch: string,\n cloneUrl: string,\n token: string,\n username: string,\n): Promise<void> {\n const env = gitAuthenticationEnvironment(cloneUrl, token, username, 'push-failed');\n const push = await execute(sandbox, 'git', ['-C', workdir, 'push', '-u', 'origin', branch], { env });\n if (push.exitCode !== 0) throw classifyGitFailure(push, 'push-failed');\n}\n\n/** Whether the checkout has a local `refs/heads/<branch>`. */\nexport async function hasLocalBranch(sandbox: ExecutableSandbox, workdir: string, branch: string): Promise<boolean> {\n const ref = await execute(sandbox, 'git', ['-C', workdir, 'show-ref', '--verify', '--quiet', `refs/heads/${branch}`]);\n if (ref.exitCode === 0) return true;\n if (ref.exitCode === 1) return false;\n throw classifyGitFailure(ref, 'push-failed');\n}\n\n/**\n * Advance the session branch to HEAD and switch to it, carrying over local work.\n * Leave an already-ahead branch and its checkout unchanged; never discard its commits.\n */\nexport async function ensureLocalBranch(sandbox: ExecutableSandbox, workdir: string, branch: string): Promise<void> {\n if (!isValidGitRef(branch)) {\n throw new MaterializeError(`Refusing to materialize: invalid branch name '${branch}'.`, 'push-failed');\n }\n const exists = await hasLocalBranch(sandbox, workdir, branch);\n if (exists) {\n const ref = `refs/heads/${branch}`;\n const tip = await execute(sandbox, 'git', ['-C', workdir, 'rev-parse', '--verify', ref]);\n if (tip.exitCode !== 0) throw classifyGitFailure(tip, 'push-failed');\n const head = await execute(sandbox, 'git', ['-C', workdir, 'rev-parse', '--verify', 'HEAD']);\n if (head.exitCode !== 0) throw classifyGitFailure(head, 'push-failed');\n const oldOid = tip.stdout.trim();\n const headOid = head.stdout.trim();\n const ancestor = await execute(sandbox, 'git', ['-C', workdir, 'merge-base', '--is-ancestor', oldOid, headOid]);\n if (ancestor.exitCode === 1) {\n const ahead = await execute(sandbox, 'git', ['-C', workdir, 'merge-base', '--is-ancestor', headOid, oldOid]);\n if (ahead.exitCode === 0) return;\n if (ahead.exitCode !== 1) throw classifyGitFailure(ahead, 'push-failed');\n throw new MaterializeError(\n `Refusing to move session branch '${branch}': it has diverged from the active HEAD. Check out or merge the session branch before pushing.`,\n 'push-failed',\n );\n }\n if (ancestor.exitCode !== 0) throw classifyGitFailure(ancestor, 'push-failed');\n const current = await execute(sandbox, 'git', ['-C', workdir, 'symbolic-ref', '--quiet', 'HEAD']);\n if (current.exitCode !== 0 && current.exitCode !== 1) throw classifyGitFailure(current, 'push-failed');\n if (current.stdout.trim() === ref) return;\n // update-ref does not enforce worktree ownership, unlike branch -f.\n const worktrees = await execute(sandbox, 'git', ['-C', workdir, 'worktree', 'list', '--porcelain', '-z']);\n if (worktrees.exitCode !== 0) throw classifyGitFailure(worktrees, 'push-failed');\n if (worktrees.stdout.split('\\0').includes(`branch ${ref}`)) {\n throw new MaterializeError(\n `Refusing to move session branch '${branch}': it is checked out in another worktree.`,\n 'push-failed',\n );\n }\n const advanced = await execute(sandbox, 'git', ['-C', workdir, 'update-ref', ref, headOid, oldOid]);\n if (advanced.exitCode !== 0) throw classifyGitFailure(advanced, 'push-failed');\n }\n const switched = await execute(sandbox, 'git', ['-C', workdir, 'switch', ...(exists ? [] : ['-c']), branch]);\n if (switched.exitCode !== 0) throw classifyGitFailure(switched, 'push-failed');\n}\n\n/** Whether `workdir` is a checkout of the repository at `cloneUrl`. */\nexport async function isCheckoutOf(sandbox: ExecutableSandbox, workdir: string, cloneUrl: string): Promise<boolean> {\n return (await existingCheckoutRemote(sandbox, workdir, cloneUrl)) !== null;\n}\n\n/**\n * Push a branch back to GitHub with credentials scoped to the Git process.\n * The token never enters argv, a repository URL, or persistent configuration.\n */\nexport async function pushBranch(\n sandbox: ExecutableSandbox,\n workdir: string,\n branch: string,\n token: string,\n repoFullName: string,\n): Promise<void> {\n if (!isValidGitRef(branch)) {\n throw new MaterializeError(`Refusing to push: invalid branch name '${branch}'.`, 'push-failed');\n }\n assertRepositoryLocator(repoFullName, undefined, 'push-failed');\n await pushAuthenticatedBranch(sandbox, workdir, branch, cleanUrl(repoFullName), token, 'x-access-token');\n}\n\n/**\n * Push the active session branch through the provider-neutral repository\n * access contract without persisting or exposing provider credentials.\n */\nexport async function pushRepositoryBranch(\n sandbox: ExecutableSandbox,\n workdir: string,\n branch: string,\n access: RepositoryAccess,\n repoFullName: string,\n): Promise<void> {\n if (!isValidGitRef(branch)) {\n throw new MaterializeError(`Refusing to push: invalid branch name '${branch}'.`, 'push-failed');\n }\n assertRepositoryLocator(repoFullName, access.cloneUrl, 'push-failed');\n const authorization = access.authorization;\n if (!authorization?.token) {\n throw new MaterializeError('Repository access did not include push credentials.', 'push-failed');\n }\n await pushAuthenticatedBranch(\n sandbox,\n workdir,\n branch,\n access.cloneUrl,\n authorization.token,\n authorization.username ?? 'x-access-token',\n );\n}\n\nexport interface CommitResult {\n /** True when a commit was created; false when there was nothing to commit. */\n committed: boolean;\n}\n\n/**\n * Stage every change in the working tree and create a commit inside the\n * sandbox. The git identity is configured first so authorship is correct. When\n * there is nothing to commit this is a no-op (`committed: false`) rather than an\n * error, so callers can safely commit-then-push without first diffing.\n *\n * @param sandbox the live sandbox containing the checkout\n * @param workdir the session workdir to commit in\n * @param message the commit message (passed as one argv value)\n * @param identity authorship identity for the commit\n */\nexport async function commitAll(\n sandbox: ExecutableSandbox,\n workdir: string,\n message: string,\n identity: GitIdentity,\n): Promise<CommitResult> {\n await configureGitIdentity(sandbox, workdir, identity);\n\n const add = await execute(sandbox, 'git', ['-C', workdir, 'add', '-A']);\n if (add.exitCode !== 0) {\n throw new MaterializeError(`git add failed: ${add.stderr.trim() || add.stdout.trim()}`, 'commit-failed');\n }\n\n // Nothing staged → nothing to commit. `git diff --cached --quiet` exits 1 when\n // there are staged changes, 0 when the index is clean.\n const staged = await execute(sandbox, 'git', ['-C', workdir, 'diff', '--cached', '--quiet']);\n if (staged.exitCode === 0) {\n return { committed: false };\n }\n\n const commit = await execute(sandbox, 'git', ['-C', workdir, 'commit', '-m', message]);\n if (commit.exitCode !== 0) {\n throw new MaterializeError(`git commit failed: ${commit.stderr.trim() || commit.stdout.trim()}`, 'commit-failed');\n }\n\n return { committed: true };\n}\n\n// ---------------------------------------------------------------------------\n// Phase 2 — setup / teardown lifecycle commands\n//\n// The org-configured setup and teardown shell commands run in the session's\n// materialized workdir. The workdir is always resolved server-side from the\n// live sandbox; client input never reaches a filesystem path.\n// ---------------------------------------------------------------------------\n\n/** Error raised when the org's setup or teardown command fails in the sandbox. */\nexport class SetupCommandError extends Error {\n constructor(\n message: string,\n readonly code: 'setup-failed' | 'teardown-failed',\n ) {\n super(message);\n this.name = 'SetupCommandError';\n }\n}\n\n/**\n * Run the project's setup command (e.g. `pnpm i && pnpm build`) inside the\n * freshly materialized session workdir. Called before the checkout is handed\n * to any agent run so it is ready to build/test. A non-zero exit is a hard\n * error — starting agent work in a half-set-up tree is worse than failing the\n * request.\n *\n * Security model: the command is intentionally arbitrary shell — that is the\n * feature (install deps, build, seed fixtures). It is only configurable by\n * authenticated org members (the settings route is gated by\n * `resolveOrgTenant` + org-scoped project lookup, with length and\n * control-character validation), and it executes exclusively inside the\n * project's isolated sandbox — the same environment where org members already\n * run arbitrary shell via the agent's command tool. It never runs on the web\n * server host, so it grants no privilege beyond what sandbox access already\n * provides.\n *\n * @param sandbox live sandbox containing the checkout\n * @param workdir the server-resolved session workdir the command runs in\n * @param command the org-configured setup shell command\n */\nasync function runLifecycleCommand(\n sandbox: ExecutableSandbox,\n workdir: string,\n command: string,\n options: {\n phase: 'setup' | 'teardown';\n timeoutMs?: number;\n env?: Record<string, string>;\n /** Values to mask in a failure message, beyond `env`; a function is read once the command has run. */\n mask?: Record<string, string> | (() => Record<string, string>);\n },\n): Promise<void> {\n const result = await sh(sandbox, `cd ${shellQuote(workdir)} && { ${command}\\n}`, {\n phase: `${options.phase} command`,\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n // Per-call only: build values must never enter the sandbox's runtime env.\n ...(options.env && Object.keys(options.env).length > 0 ? { env: options.env } : {}),\n });\n if (result.exitCode !== 0) {\n // The message is stored as build status and shown in the UI, so mask any\n // Factory value (Build or Runtime) the command printed.\n // Mask before trimming: a value with an edge newline or space would no longer match once trimmed.\n const output = result.stderr.trim() ? result.stderr : result.stdout;\n const mask = typeof options.mask === 'function' ? options.mask() : options.mask;\n const detail = maskSandboxEnvValues(output, { ...mask, ...options.env })\n .trim()\n .slice(-1800);\n const label = options.phase === 'setup' ? 'Setup' : 'Teardown';\n throw new SetupCommandError(\n `${label} command failed (exit ${result.exitCode}): ${detail}`,\n options.phase === 'setup' ? 'setup-failed' : 'teardown-failed',\n );\n }\n}\n\n/**\n * @param buildEnv the Factory's Build variables, passed to this command only\n * @param runtimeEnv the Factory's Runtime variables the command can also see; masked in a failure message\n */\nexport async function runSetupCommand(\n sandbox: ExecutableSandbox,\n workdir: string,\n command: string,\n buildEnv?: Record<string, string>,\n runtimeEnv?: Record<string, string>,\n): Promise<void> {\n return runLifecycleCommand(sandbox, workdir, command, {\n phase: 'setup',\n ...(buildEnv ? { env: buildEnv } : {}),\n ...(runtimeEnv ? { mask: runtimeEnv } : {}),\n });\n}\n\n/**\n * Run the repository's best-effort teardown command from the materialized\n * session workdir. Callers own lifecycle policy: this helper reports failures\n * so the retirement coordinator can log them while still continuing with\n * scrub, pooling/destruction, cache invalidation, and row deletion.\n */\nexport async function runTeardownCommand(\n sandbox: ExecutableSandbox,\n workdir: string,\n command: string,\n options: { timeoutMs?: number } = {},\n): Promise<void> {\n return runLifecycleCommand(sandbox, workdir, command, {\n phase: 'teardown',\n // The command sees the Factory runtime values applied to this sandbox, so a failure is masked with them.\n mask: () => appliedSandboxEnv(sandbox),\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n });\n}\n\nexport interface CreatePullRequestArgs {\n /** Short-lived installation token, injected only into the `gh` process env. */\n token: string;\n /** Base branch the PR merges into. Ref-validated. */\n base: string;\n /** Head branch the PR is opened from. Ref-validated. */\n head: string;\n /** PR title. */\n title: string;\n /** PR body (optional). */\n body?: string;\n}\n\nexport interface CreatePullRequestResult {\n /** The PR URL parsed from `gh pr create` stdout. */\n url: string;\n}\n\n/**\n * Preflight that `gh` is installed in the sandbox. Only called on the PR path so\n * a missing `gh` never blocks clone/open. Surfaces an actionable error naming\n * the sandbox template requirement.\n */\nasync function assertGhAvailable(sandbox: ExecutableSandbox): Promise<void> {\n const version = await execute(sandbox, 'gh', ['--version']);\n if (version.exitCode !== 0) {\n throw new MaterializeError(\n 'The GitHub CLI (gh) is not installed in the sandbox. The sandbox template must include gh to open pull requests.',\n 'gh-missing',\n );\n }\n}\n\n/** Match the first GitHub PR URL in `gh pr create` output. */\nfunction parsePullRequestUrl(stdout: string): string | undefined {\n const match = stdout.match(/https:\\/\\/github\\.com\\/[^\\s]+\\/pull\\/\\d+/);\n return match?.[0];\n}\n\n/**\n * Open a pull request from inside the sandbox via `gh pr create`. The token is\n * passed only through a per-invocation `GH_TOKEN` env scoped to the single `gh`\n * process (never persisted), all arguments are passed as structured argv, and\n * the resulting PR URL is parsed from stdout.\n *\n * @param sandbox live sandbox containing the checkout\n * @param workdir the worktree (or repo) path the PR head branch is checked out in\n */\nexport async function createPullRequest(\n sandbox: ExecutableSandbox,\n workdir: string,\n { token, base, head, title, body }: CreatePullRequestArgs,\n): Promise<CreatePullRequestResult> {\n if (!isValidGitRef(base)) {\n throw new MaterializeError(`Refusing to open PR: invalid base branch '${base}'.`, 'pr-failed');\n }\n if (!isValidGitRef(head)) {\n throw new MaterializeError(`Refusing to open PR: invalid head branch '${head}'.`, 'pr-failed');\n }\n\n await assertGhAvailable(sandbox);\n\n const result = await execute(\n sandbox,\n 'gh',\n ['pr', 'create', '--base', base, '--head', head, '--title', title, '--body', body ?? ''],\n { cwd: workdir, env: { GH_TOKEN: token } },\n );\n if (result.exitCode !== 0) {\n const classified = classifyGitFailure(result, 'push-failed');\n if (classified.code === 'egress-blocked') {\n throw classified;\n }\n throw new MaterializeError(`gh pr create failed: ${result.stderr.trim() || result.stdout.trim()}`, 'pr-failed');\n }\n\n const url = parsePullRequestUrl(result.stdout);\n if (!url) {\n throw new MaterializeError(\n `gh pr create succeeded but no PR URL was found in its output: ${result.stdout.trim()}`,\n 'pr-failed',\n );\n }\n\n return { url };\n}\n"],"mappings":";;;;;;;;;;;;AAwCA,SAAgB,WAAW,OAAuB;CAEhD,OAAO,MAAM,MAAM,MAAM,GAAG,CAAC,CAAC,KAAK,OAAO,IAAI;AAChD;;;;;;;AAQA,MAAa,6BAA6B;;AAE1C,MAAa,8BAA8B;;;;;;;;;;AAuB3C,SAAS,0BAA0B,OAAyB;CAC1D,MAAM,SAAU,OAAgC;CAChD,OAAO,OAAO,WAAW,YAAY,UAAU;AACjD;AAEA,MAAM,aAAa;AACnB,MAAM,oBAAoB;;;;;;AAO1B,eAAsB,GACpB,SACA,QACA,UAAmD,CAAC,GACrB;CAC/B,OAAO,QAAQ,SAAS,MAAM,CAAC,MAAM,MAAM,GAAG,OAAO;AACvD;;;;;;AAOA,eAAe,QACb,SACA,S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B,MAAM;EAER,MAAM,IAAI,iBAAiB,wBAAwB,OAAO,OAAO,KAAK,KAAK,OAAO,OAAO,KAAK,KAAK,WAAW;CAChH;CAEA,MAAM,MAAM,oBAAoB,OAAO,MAAM;CAC7C,IAAI,CAAC,KACH,MAAM,IAAI,iBACR,iEAAiE,OAAO,OAAO,KAAK,KACpF,WACF;CAGF,OAAO,EAAE,IAAI;AACf"}
|
|
1
|
+
{"version":3,"file":"sandbox.js","names":[],"sources":["../../../src/integrations/github/sandbox.ts"],"sourcesContent":["/**\n * Repo materialization for GitHub-backed repositories.\n *\n * A GitHub repo is never cloned onto the server host. The repo is cloned\n * *inside* the session's sandbox, so the agent's file tools and command tools\n * operate entirely against the remote checkout.\n *\n * - `materializeRepo(row, token)` clones the repo inside the sandbox when no\n * checkout exists yet (a base-image boot, a wiped disk), supplying the\n * short-lived token only in that Git process's environment. A checkout that\n * is already there, from a repo template image or an earlier start, is left\n * exactly as it is.\n *\n * This module owns everything git/GitHub: clone, commit/push, setup/teardown commands,\n * and `gh pr create`. Workdir layout lives in `../sandbox/workdir`.\n */\n\nimport type { RepositoryAccess } from '../../capabilities/version-control.js';\nimport { recordSandboxCommand } from '../../metrics/sandbox.js';\nimport { isValidGitRef } from '../../sandbox/git-ref.js';\nimport type { ExecutableSandbox, SandboxCommandResult } from '../../sandbox/materialization.js';\nimport { appliedSandboxEnv, maskSandboxEnvValues } from '../../sandbox/sandbox-env.js';\nimport type { SourceControlStorageHandle } from '../../storage/domains/source-control/base.js';\nimport { bootDiagnosticsEnabled, timedPhase } from '../../timing.js';\n\ntype MaterializationStore = Pick<SourceControlStorageHandle['sessions'], 'markMaterialized'>;\n\ninterface RepoMaterializationBinding {\n id: string;\n sandboxWorkdir: string;\n materializedAt: Date | null;\n}\n\n/**\n * Single-quote a string for safe POSIX shell interpolation. Wraps the value in\n * single quotes and escapes any embedded single quote using the canonical\n * close-quote / escaped-quote / reopen-quote sequence (`'\\''`). This is the\n * standard POSIX-safe construction and prevents the quoted string from being\n * terminated early.\n */\nexport function shellQuote(value: string): string {\n // Replace each ' with the four-character sequence: ' \\ ' '\n return `'` + value.split(`'`).join(`'\\\\''`) + `'`;\n}\n\n/**\n * Default hang guard for sandbox shell commands. Generous by design — large\n * clones and dependency installs legitimately take minutes; the guard exists\n * so a wedged sandbox surfaces a failure instead of hanging the request that\n * triggered materialization forever.\n */\nexport const DEFAULT_COMMAND_TIMEOUT_MS = 15 * 60_000;\n/** Branch checkout only fetches one ref — a much tighter budget applies. */\nexport const CHECKOUT_COMMAND_TIMEOUT_MS = 5 * 60_000;\n\ninterface ShOptions {\n /** Override the hang-guard budget for this command. */\n timeoutMs?: number;\n /** Human-readable phase name included in the timeout error. */\n phase?: string;\n}\n\ninterface CommandOptions extends ShOptions {\n cwd?: string;\n env?: Record<string, string | undefined>;\n}\n\n/**\n * A thrown transport-level failure that is worth retrying: remote sandbox\n\n * providers (e.g. the platform workspace proxy) surface transient 5xx errors\n * as exceptions carrying an HTTP `status` — typically while a freshly\n * provisioned VM is still coming up. Command failures are NOT exceptions\n * (they resolve with a non-zero exit code), so retrying here never re-runs a\n * command that the sandbox already executed and rejected.\n */\nfunction isTransientTransportError(error: unknown): boolean {\n const status = (error as { status?: unknown })?.status;\n return typeof status === 'number' && status >= 500;\n}\n\nconst SH_RETRIES = 2;\nconst SH_RETRY_DELAY_MS = 2000;\n\n/**\n * Run a shell script in the sandbox via `sh -c`. This is reserved for the\n * explicitly configured repository lifecycle hooks; programmatic commands use\n * {@link execute} with an argv array.\n */\nexport async function sh(\n sandbox: ExecutableSandbox,\n script: string,\n options: ShOptions & Pick<CommandOptions, 'env'> = {},\n): Promise<SandboxCommandResult> {\n return execute(sandbox, 'sh', ['-c', script], options);\n}\n\n/**\n * Execute one program with an argv array, bounded by a hang guard. Transient\n * sandbox transport failures are retried without ever interpolating arguments\n * into a shell command.\n */\nasync function execute(\n sandbox: ExecutableSandbox,\n command: string,\n args: string[],\n options: CommandOptions = {},\n): Promise<SandboxCommandResult> {\n const deadlineMs = Date.now() + (options.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS);\n for (let attempt = 0; ; attempt++) {\n const started = performance.now();\n try {\n const result = await executeOnce(sandbox, command, args, {\n ...options,\n timeoutMs: Math.max(deadlineMs - Date.now(), 1),\n });\n if (options.phase) {\n const elapsed = performance.now() - started;\n if (bootDiagnosticsEnabled) {\n process.stderr.write(\n `[factory:timing] ${options.phase} attempt=${attempt + 1} exit=${result.exitCode} ${Math.round(elapsed)}ms\\n`,\n );\n }\n recordSandboxCommand(options.phase, elapsed, result.exitCode === 0 ? 'ok' : 'exit');\n }\n return result;\n } catch (error) {\n if (options.phase) {\n const elapsed = performance.now() - started;\n process.stderr.write(\n `[factory:timing] ${options.phase} attempt=${attempt + 1} threw after ${Math.round(elapsed)}ms: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n recordSandboxCommand(options.phase, elapsed, 'threw');\n }\n if (attempt >= SH_RETRIES || !isTransientTransportError(error)) throw error;\n const delayMs = SH_RETRY_DELAY_MS * (attempt + 1);\n if (deadlineMs - Date.now() <= delayMs) throw error;\n await new Promise(resolve => setTimeout(resolve, delayMs));\n }\n }\n}\n\n/** Single structured command execution attempt, bounded by the hang guard. */\nasync function executeOnce(\n sandbox: ExecutableSandbox,\n command: string,\n args: string[],\n options: CommandOptions,\n): Promise<SandboxCommandResult> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const hangGuard = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const phase = options.phase ? ` during ${options.phase}` : '';\n reject(new Error(`Sandbox command timed out after ${Math.round(timeoutMs / 1000)}s${phase}.`));\n }, timeoutMs);\n timer.unref?.();\n });\n try {\n return await Promise.race([\n sandbox.executeCommand(command, args, {\n timeout: timeoutMs,\n ...(options.cwd !== undefined ? { cwd: options.cwd } : {}),\n ...(options.env !== undefined ? { env: options.env } : {}),\n }),\n hangGuard,\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nconst GIT_TRANSFER_RETRIES = 2;\nconst GIT_TRANSFER_RETRY_DELAY_MS = 2000;\n\n/**\n * True when a git transfer died mid-flight rather than being refused.\n *\n * `sh` already retries transport errors the sandbox provider *throws*, but a\n * git command that reaches the network and then loses it exits non-zero\n * instead — so a single HTTP/2 framing glitch or dropped connection to\n * github.com would otherwise permanently fail opening a workspace. These\n * patterns all mean \"the bytes stopped arriving\", which says nothing about\n * whether the operation would succeed if attempted again.\n *\n * Deliberately narrow: a refusal (bad credentials, missing repo, blocked\n * egress) is terminal and must surface immediately rather than be retried into\n * a slow failure.\n */\nfunction isTransientGitFailure(result: SandboxCommandResult): boolean {\n const output = `${result.stderr || ''}\\n${result.stdout || ''}`;\n return /HTTP2 framing layer|RPC failed; curl|RPC failed; HTTP 5\\d\\d|the remote end hung up unexpectedly|early EOF|unexpected disconnect|connection reset by peer|Recv failure|Send failure|GnuTLS recv error|TLS connection was non-properly terminated|502 Bad Gateway|503 Service Unavailable/i.test(\n output,\n );\n}\n\n/**\n * Run a git command that only *reads* from the remote, retrying it when the\n * transfer dies mid-flight. Restricted to read-only transfers on purpose:\n * re-running a clone or a fetch is free, whereas re-running a push could\n * duplicate work already accepted by the remote before the connection dropped.\n *\n * `beforeRetry` lets a call site clear whatever the aborted attempt left\n * behind — a half-written clone directory blocks the next `git clone` outright.\n */\nasync function gitTransfer(\n sandbox: ExecutableSandbox,\n args: string[],\n options: CommandOptions & { beforeRetry?: (attempt: number) => Promise<void> } = {},\n): Promise<SandboxCommandResult> {\n const { beforeRetry, ...commandOptions } = options;\n const deadlineMs = Date.now() + (commandOptions.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS);\n for (let attempt = 0; ; attempt++) {\n const result = await execute(sandbox, 'git', args, {\n ...commandOptions,\n timeoutMs: Math.max(deadlineMs - Date.now(), 1),\n });\n if (result.exitCode === 0 || attempt >= GIT_TRANSFER_RETRIES || !isTransientGitFailure(result)) return result;\n process.stderr.write(\n `[factory:timing] git ${commandOptions.phase ?? 'transfer'} retrying after attempt ${attempt + 1}\\n`,\n );\n const delayMs = GIT_TRANSFER_RETRY_DELAY_MS * (attempt + 1);\n if (deadlineMs - Date.now() <= delayMs) return result;\n await new Promise(resolve => setTimeout(resolve, delayMs));\n await beforeRetry?.(attempt + 1);\n }\n}\n\n/** Error raised when the sandbox cannot materialize the repo (actionable). */\nexport class MaterializeError extends Error {\n constructor(\n message: string,\n readonly code:\n | 'git-missing'\n | 'sandbox-unresponsive'\n | 'egress-blocked'\n | 'clone-failed'\n | 'pull-failed'\n | 'push-failed'\n | 'commit-failed'\n | 'gh-missing'\n | 'pr-failed',\n ) {\n super(message);\n this.name = 'MaterializeError';\n }\n}\n\nfunction cleanUrl(repoFullName: string): string {\n return `https://github.com/${repoFullName}.git`;\n}\n\n/**\n * True when a repository name or clone URL contains a `.` or `..` path segment.\n * `new URL` and git both collapse those, and `new URL` also treats `\\` as `/`,\n * so `owner/../other` names a different repository than the row. Checked on the\n * raw text, before that collapse. A backslash is refused on its own: the origin\n * strip below would otherwise treat it as part of the host.\n */\nfunction pathHasDotSegment(value: string): boolean {\n if (value.includes('\\\\')) return true;\n const withoutOrigin = value.replace(/^[a-z][a-z0-9+.-]*:\\/\\/[^/?#]*/i, '');\n const path = withoutOrigin.split(/[?#]/)[0] ?? '';\n return path.split('/').some(part => {\n let decoded = part;\n try {\n decoded = decodeURIComponent(part);\n } catch {\n return true;\n }\n return decoded === '.' || decoded === '..' || decoded.includes('\\\\');\n });\n}\n\nfunction assertRepositoryLocator(\n repoFullName: string | undefined,\n cloneUrl: string | undefined,\n code: 'clone-failed' | 'pull-failed' | 'push-failed',\n): void {\n if (\n repoFullName !== undefined &&\n (!/^[\\w.-]+(?:\\/[\\w.-]+)+$/.test(repoFullName) || pathHasDotSegment(repoFullName))\n ) {\n throw new MaterializeError(`Refusing to use an invalid repo full name '${repoFullName}'.`, code);\n }\n if (cloneUrl && pathHasDotSegment(cloneUrl)) {\n throw new MaterializeError('Refusing to use a clone URL whose path rewrites to another repository.', code);\n }\n}\n\nfunction credentialScope(\n cloneUrl: string,\n code: 'clone-failed' | 'pull-failed' | 'push-failed' = 'clone-failed',\n): string {\n let url: URL;\n try {\n url = new URL(cloneUrl);\n } catch {\n throw new MaterializeError('Refusing to configure credentials for an invalid repository clone URL.', code);\n }\n if (url.protocol !== 'https:' || !url.hostname || url.username || url.password || url.search || url.hash) {\n throw new MaterializeError('Refusing to configure credentials for an invalid repository clone URL.', code);\n }\n const repositoryPath = url.pathname.replace(/\\/+$/, '');\n if (!repositoryPath || repositoryPath === '/') {\n throw new MaterializeError('Refusing to configure credentials for an invalid repository clone URL.', code);\n }\n return url.origin + repositoryPath;\n}\n\n/**\n * Provide HTTP Basic credentials to one Git process without putting a secret\n * in argv, a remote URL, or persistent git config. Git reads the URL-scoped\n * extra header from its process environment and discards it on exit.\n */\nfunction gitAuthenticationEnvironment(\n cloneUrl: string,\n token: string,\n username: string,\n code: 'clone-failed' | 'pull-failed' | 'push-failed' = 'clone-failed',\n): Record<string, string> {\n const scope = credentialScope(cloneUrl, code);\n if (!token || !username) {\n throw new MaterializeError('Repository access did not include usable credentials.', code);\n }\n const authorization = Buffer.from(`${username}:${token}`, 'utf8').toString('base64');\n // Git applies `http.<url>.*` only when the config URL matches the remote at\n // a path boundary, and `origin` may spell the repository either way: Factory\n // clones with `.git`, a sandbox template clones from the normalized URL\n // without it. Scope the header to both so neither checkout prompts.\n const alternate = scope.endsWith('.git') ? scope.slice(0, -4) : `${scope}.git`;\n return {\n GIT_CONFIG_COUNT: '2',\n GIT_CONFIG_KEY_0: `http.${scope}.extraHeader`,\n GIT_CONFIG_VALUE_0: `Authorization: Basic ${authorization}`,\n GIT_CONFIG_KEY_1: `http.${alternate}.extraHeader`,\n GIT_CONFIG_VALUE_1: `Authorization: Basic ${authorization}`,\n GIT_TERMINAL_PROMPT: '0',\n };\n}\n\nfunction normalizedRemoteUrl(value: string): string | null {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return null;\n }\n if (url.protocol !== 'https:' || !url.hostname || url.search || url.hash) return null;\n const pathname = url.pathname.replace(/\\/+$/, '').replace(/\\.git$/i, '');\n const repositoryPath = url.hostname.toLowerCase() === 'github.com' ? pathname.toLowerCase() : pathname;\n return 'https://' + url.host.toLowerCase() + repositoryPath;\n}\n\n/** Repo metadata needed to materialize, read from the org-owned project row. */\nexport interface RepoMaterializeInfo {\n repoFullName: string;\n defaultBranch: string;\n /** Provider-supplied, credential-free HTTPS clone URL. */\n cloneUrl?: string;\n /** Username paired with the bearer token for git-over-HTTPS. */\n authUsername?: string;\n}\n\n/** Options for {@link materializeRepo}. */\nexport interface MaterializeRepoOptions {\n /** The per-(project,user) sandbox binding whose workdir this materializes into. */\n row: RepoMaterializationBinding;\n /** Repo metadata from the org-owned project row. */\n repoInfo: RepoMaterializeInfo;\n /** The live sandbox to run git inside. */\n sandbox: ExecutableSandbox;\n /** A freshly minted, short-lived installation access token. */\n token: string;\n storage: MaterializationStore;\n}\n\nasync function clearWorkdir(sandbox: ExecutableSandbox, workdir: string): Promise<void> {\n const mkdir = await execute(sandbox, 'mkdir', ['-p', workdir]);\n if (mkdir.exitCode !== 0) throw classifyGitFailure(mkdir, 'clone-failed');\n const clear = await execute(sandbox, 'find', [\n workdir,\n '-mindepth',\n '1',\n '-maxdepth',\n '1',\n '-exec',\n 'rm',\n '-rf',\n '--',\n '{}',\n '+',\n ]);\n if (clear.exitCode !== 0) throw classifyGitFailure(clear, 'clone-failed');\n}\n/**\n * Materialize the repo inside the user's sandbox: clone when no checkout of\n * this repo exists, otherwise nothing. Credentials are process-scoped and the\n * stored remote remains credential-free. Sets `materialized_at` on the\n * per-user sandbox binding row.\n */\nexport async function materializeRepo(options: MaterializeRepoOptions): Promise<void> {\n return timedPhase('workspace.materialize', () => materializeRepoImpl(options));\n}\n\nasync function materializeRepoImpl(options: MaterializeRepoOptions): Promise<void> {\n const { row: sandboxRow, repoInfo, sandbox, token, storage } = options;\n const workdir = sandboxRow.sandboxWorkdir;\n const repo = repoInfo.repoFullName;\n\n // 0. Defense in depth: never build a git command from values that aren't\n // strictly shaped, even if a malformed row reached the DB. Inputs are also\n // validated at the route boundary before storage. `..` in a repository path\n // collapses to a different repository, and a branch git can read as an option\n // is rejected by the same ref rules the checkout path uses.\n assertRepositoryLocator(repo, repoInfo.cloneUrl, 'clone-failed');\n if (!isValidGitRef(repoInfo.defaultBranch)) {\n throw new MaterializeError(\n `Refusing to materialize: invalid default branch '${repoInfo.defaultBranch}'.`,\n 'clone-failed',\n );\n }\n\n // 1. Preflight: git must be installed in the sandbox template. Exit 124 is\n // the provider's timeout code: the VM stopped answering, which says nothing\n // about git, so it must not be reported as a missing binary.\n const gitVersion = await execute(sandbox, 'git', ['--version']);\n if (gitVersion.exitCode === 124) {\n throw new MaterializeError(\n 'The sandbox stopped responding: `git --version` timed out (exit 124). Recreate the sandbox.',\n 'sandbox-unresponsive',\n );\n }\n if (gitVersion.exitCode !== 0) {\n const detail = (gitVersion.stderr || gitVersion.stdout).trim().slice(-500) || '(no output)';\n throw new MaterializeError(\n `git is not installed in the sandbox: \\`git --version\\` exited ${gitVersion.exitCode}: ${detail}. The sandbox template must include git.`,\n 'git-missing',\n );\n }\n\n // The DB's `materializedAt` can drift from disk in both directions: a fresh\n // binding row over an already-populated workdir (a repo template image,\n // local dev DB resets, repaired rows) must not fail `git clone` on the\n // non-empty directory, and a stale `materializedAt` over an empty sandbox\n // (an expired/recreated VM whose disk was wiped) must re-clone instead of\n // running `git -C <workdir>` against a directory that no longer exists.\n // Disk is the source of truth: detect the checkout instead of trusting the\n // row. An existing checkout is left as it is, whatever it is on: a template\n // image sits detached at its pinned commit, a resumed session on its\n // branch. Syncing with the remote is the session's business; the branch\n // checkout that follows fetches the base branch it needs.\n const cleanCloneUrl = repoInfo.cloneUrl ?? cleanUrl(repo);\n const existing = await existingCheckoutRemote(sandbox, workdir, cleanCloneUrl);\n if (existing !== null) {\n // A token an earlier start failed to scrub must not outlive it; the\n // remote already carries the plain URL otherwise, so this costs nothing\n // on the common path.\n if (/\\/\\/[^/]*@/.test(existing)) await scrubRemote(sandbox, workdir, repo, cleanCloneUrl);\n } else {\n // 2. First open: shallow-clone the default branch into the workdir, the\n // same clone a repo template bakes into its image. The workdir holds no\n // usable checkout of this repo, but it may not be empty: a checkpoint\n // seed or a clone that died partway (a crashed or OOM-killed server)\n // leaves a partial tree behind, and `git clone` refuses a non-empty\n // destination with a non-retryable fatal. Nothing here is recoverable,\n // the probe above already ruled out a checkout of this repo, so\n // clear its contents before cloning, exactly as the retry path does. Keep\n // the workdir itself because Factory's own commands use it as their cwd\n // (`gh pr create`, and the `cd` each lifecycle command starts with), so it\n // has to exist as a directory.\n const authEnv = gitAuthenticationEnvironment(\n cleanCloneUrl,\n token,\n repoInfo.authUsername ?? 'x-access-token',\n 'clone-failed',\n );\n await clearWorkdir(sandbox, workdir);\n const clone = await gitTransfer(\n sandbox,\n ['clone', '--depth=1', '--single-branch', '--branch', repoInfo.defaultBranch, '--', cleanCloneUrl, workdir],\n {\n env: authEnv,\n phase: 'repository clone',\n beforeRetry: async () => {\n // A clone that died partway leaves the destination non-empty, which\n // git refuses to clone into. Clear its contents so the retry starts\n // clean, leaving a directory Factory's commands still use as cwd.\n await clearWorkdir(sandbox, workdir);\n },\n },\n );\n if (clone.exitCode !== 0) throw classifyGitFailure(clone, 'clone-failed');\n }\n\n // 4. Mark materialized.\n await storage.markMaterialized({ id: sandboxRow.id });\n}\n\nexport interface SessionBranchOptions {\n /** Repository-local authorship configured before setup commands or agent access. */\n identity?: GitIdentity;\n branch: string;\n baseBranch: string;\n token: string;\n repoFullName: string;\n cloneUrl?: string;\n authUsername?: string;\n /** A pull-request card's session starts on the PR head instead of the base tip. */\n pullRequestNumber?: number;\n /** A GitLab merge-request card's session starts on the MR head instead of the base tip. */\n mergeRequestNumber?: number;\n}\n\n/**\n * Past file contents of a blob-less history load on demand; git asks gh, which\n * answers from the session's `GH_TOKEN`, so no credential is ever written.\n */\nconst GH_CREDENTIAL_HELPER = '!gh auth git-credential';\n\n/**\n * The git credential helper for a GitHub checkout whose repository is covered\n * by a numbered group token (`GH_TOKEN_2`, ...) instead of `GH_TOKEN`. It\n * falls back to `GH_TOKEN` while the group token is unset, as it is when an\n * org PAT is installed.\n */\nexport function githubCredentialHelper(tokenEnvName = 'GH_TOKEN'): string {\n if (tokenEnvName === 'GH_TOKEN') return GH_CREDENTIAL_HELPER;\n if (!/^GH_TOKEN_\\d+$/.test(tokenEnvName)) throw new Error(`Invalid GitHub token variable: ${tokenEnvName}`);\n return `!f() { GH_TOKEN=\"\\${${tokenEnvName}:-$GH_TOKEN}\" gh auth git-credential \"$@\"; }; f`;\n}\n\nasync function fetchStartPoint(\n sandbox: ExecutableSandbox,\n workdir: string,\n {\n baseBranch,\n pullRequestNumber,\n mergeRequestNumber,\n }: Pick<SessionBranchOptions, 'baseBranch' | 'pullRequestNumber' | 'mergeRequestNumber'>,\n shallowClone: boolean,\n env: Record<string, string>,\n): Promise<SandboxCommandResult> {\n const changeRequestRef =\n pullRequestNumber !== undefined\n ? `refs/pull/${pullRequestNumber}/head`\n : mergeRequestNumber !== undefined\n ? `refs/merge-requests/${mergeRequestNumber}/head`\n : undefined;\n const baseArgs = [\n '-C',\n workdir,\n 'fetch',\n ...(changeRequestRef && shallowClone ? ['--unshallow'] : []),\n ...(pullRequestNumber !== undefined ? ['--filter=blob:none'] : []),\n 'origin',\n baseBranch,\n ];\n const base = await gitTransfer(sandbox, baseArgs, {\n env,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'branch checkout fetch',\n });\n if (base.exitCode !== 0 || !changeRequestRef) return base;\n return gitTransfer(\n sandbox,\n [\n '-C',\n workdir,\n 'fetch',\n ...(pullRequestNumber !== undefined ? ['--filter=blob:none'] : []),\n 'origin',\n changeRequestRef,\n ],\n {\n env,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'change request head fetch',\n },\n );\n}\n\n/** Check out a session's branch inside its isolated repository clone. */\nexport async function checkoutSessionBranch(\n sandbox: ExecutableSandbox,\n workdir: string,\n options: SessionBranchOptions,\n): Promise<void> {\n return timedPhase('workspace.checkout', () => checkoutSessionBranchImpl(sandbox, workdir, options));\n}\n\nexport interface SyncEnvironmentRepositoryOptions {\n /** Repository-local authorship configured before setup commands or agent access. */\n identity?: GitIdentity;\n /** The session branch to resume when the remote already carries it. */\n branch: string;\n /** The repository's default branch; new session branches start at its remote tip. */\n defaultBranch: string;\n token: string;\n repoFullName: string;\n cloneUrl?: string;\n authUsername?: string;\n /**\n * The sandbox variable carrying this GitHub repository's token; the checkout\n * gets a credential helper reading it. Ignored when `authUsername` is set.\n */\n tokenEnvName?: string;\n}\n\nexport interface EnvironmentSyncResult {\n outcome: 'resumed' | 'created' | 'kept';\n /** The branch the checkout ends on; `null` when it stays detached. */\n branch: string | null;\n}\n\n/**\n * Bring a secondary environment repository onto the session branch at\n * session start. The primary repository keeps {@link checkoutSessionBranch};\n * every other repository follows a conservative rule: resume the session\n * branch when the remote or the local clone has it, otherwise create it from\n * the default branch tip (a detached HEAD, the template image pinned at its\n * build commit, is moved there first). A checkout that sits on any other\n * branch is left alone: it may carry local-only commits.\n */\nexport async function syncEnvironmentRepository(\n sandbox: ExecutableSandbox,\n workdir: string,\n options: SyncEnvironmentRepositoryOptions,\n): Promise<EnvironmentSyncResult> {\n const { branch, defaultBranch, token, repoFullName, cloneUrl, authUsername } = options;\n if (!isValidGitRef(branch) || !isValidGitRef(defaultBranch)) {\n throw new MaterializeError('Refusing to sync a repository from an invalid branch name.', 'pull-failed');\n }\n assertRepositoryLocator(repoFullName, cloneUrl, 'pull-failed');\n const cleanCloneUrl = cloneUrl ?? cleanUrl(repoFullName);\n const authEnv = gitAuthenticationEnvironment(cleanCloneUrl, token, authUsername ?? 'x-access-token', 'pull-failed');\n\n // Raw git in this checkout (push, fetch) authenticates through gh with the\n // token that covers this repository, like the session repository does.\n if (!authUsername) {\n const configured = await execute(sandbox, 'git', [\n '-C',\n workdir,\n 'config',\n 'credential.helper',\n githubCredentialHelper(options.tokenEnvName),\n ]);\n if (configured.exitCode !== 0) throw classifyGitFailure(configured, 'pull-failed');\n }\n\n await configureGitIdentity(sandbox, workdir, options.identity ?? {});\n\n const current = await execute(sandbox, 'git', ['-C', workdir, 'branch', '--show-current']);\n if (current.exitCode !== 0) throw classifyGitFailure(current, 'pull-failed');\n const currentBranch = current.stdout.trim();\n const kept = { outcome: 'kept' as const, branch: currentBranch || null };\n if (currentBranch === branch) return kept;\n\n // A local session branch may hold commits the remote never saw; switch\n // to it instead of resetting it onto the remote tip.\n const local = await execute(sandbox, 'git', [\n '-C',\n workdir,\n 'rev-parse',\n '--verify',\n '--quiet',\n `refs/heads/${branch}`,\n ]);\n if (local.exitCode === 0) {\n const checkout = await execute(sandbox, 'git', ['-C', workdir, 'checkout', branch], {\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'environment branch checkout',\n });\n if (checkout.exitCode === 0) return { outcome: 'resumed', branch };\n if (isBlockedByLocalWork(checkout)) return kept;\n throw classifyGitFailure(checkout, 'pull-failed');\n }\n\n const remoteHeads = await gitTransfer(\n sandbox,\n ['-C', workdir, 'ls-remote', '--heads', 'origin', `refs/heads/${branch}`],\n { env: authEnv, timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS, phase: 'environment branch probe' },\n );\n if (remoteHeads.exitCode !== 0) throw classifyGitFailure(remoteHeads, 'pull-failed');\n if (remoteHeads.stdout.trim()) {\n const fetch = await gitTransfer(sandbox, ['-C', workdir, 'fetch', 'origin', branch], {\n env: authEnv,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'environment branch fetch',\n });\n if (fetch.exitCode !== 0) throw classifyGitFailure(fetch, 'pull-failed');\n const checkout = await execute(sandbox, 'git', ['-C', workdir, 'checkout', '-B', branch, 'FETCH_HEAD'], {\n env: authEnv,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'environment branch checkout',\n });\n if (checkout.exitCode === 0) return { outcome: 'resumed', branch };\n if (isBlockedByLocalWork(checkout)) return kept;\n throw classifyGitFailure(checkout, 'pull-failed');\n }\n\n // A checkout on any other branch stays where it is: it may hold work the\n // remote never saw. The default branch and a detached HEAD (the template\n // image pinned at its build commit) become the session branch.\n if (currentBranch && currentBranch !== defaultBranch) return kept;\n if (currentBranch) {\n const status = await execute(sandbox, 'git', ['-C', workdir, 'status', '--porcelain']);\n if (status.exitCode !== 0) throw classifyGitFailure(status, 'pull-failed');\n if (status.stdout.trim()) return kept;\n }\n const fetch = await gitTransfer(sandbox, ['-C', workdir, 'fetch', 'origin', defaultBranch], {\n env: authEnv,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'environment default fetch',\n });\n if (fetch.exitCode !== 0) throw classifyGitFailure(fetch, 'pull-failed');\n if (currentBranch) {\n // Do not discard local-only commits on the default branch. A shallow\n // checkout whose ancestry cannot be established is also left untouched.\n const ancestor = await execute(sandbox, 'git', [\n '-C',\n workdir,\n 'merge-base',\n '--is-ancestor',\n 'HEAD',\n 'FETCH_HEAD',\n ]);\n if (ancestor.exitCode === 1) return kept;\n if (ancestor.exitCode !== 0) throw classifyGitFailure(ancestor, 'pull-failed');\n } else {\n const checkout = await execute(sandbox, 'git', ['-C', workdir, 'checkout', '-B', defaultBranch, 'FETCH_HEAD'], {\n env: authEnv,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'environment default checkout',\n });\n if (checkout.exitCode !== 0) {\n if (isBlockedByLocalWork(checkout)) return kept;\n throw classifyGitFailure(checkout, 'pull-failed');\n }\n }\n const created = await execute(sandbox, 'git', ['-C', workdir, 'checkout', '-b', branch, 'FETCH_HEAD'], {\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'environment branch create',\n });\n if (created.exitCode === 0) return { outcome: 'created', branch };\n throw classifyGitFailure(created, 'pull-failed');\n}\n\n/** Refresh an existing GitLab review checkout without exposing its credential to the agent. */\nexport async function refreshMergeRequestCheckout(\n sandbox: ExecutableSandbox,\n workdir: string,\n input: { branch: string; mergeRequestNumber: number; expectedHeadSha: string; access: RepositoryAccess },\n): Promise<{ headSha: string; changed: boolean }> {\n const { branch, mergeRequestNumber, expectedHeadSha, access } = input;\n assertRepositoryLocator(undefined, access.cloneUrl, 'pull-failed');\n if (\n !isValidGitRef(branch) ||\n !Number.isSafeInteger(mergeRequestNumber) ||\n mergeRequestNumber <= 0 ||\n !/^[0-9a-f]{40}$/i.test(expectedHeadSha)\n ) {\n throw new Error('Refusing to refresh a GitLab review with invalid session or head metadata.');\n }\n const token = access.authorization?.token;\n if (!token) throw new Error('GitLab repository access did not include a bearer token.');\n const env = gitAuthenticationEnvironment(\n access.cloneUrl,\n token,\n access.authorization?.username ?? 'oauth2',\n 'pull-failed',\n );\n const current = await execute(sandbox, 'git', ['-C', workdir, 'branch', '--show-current']);\n if (current.exitCode !== 0 || current.stdout.trim() !== branch) {\n throw new Error('The active checkout is not on its bound review branch.');\n }\n const status = await execute(sandbox, 'git', ['-C', workdir, 'status', '--porcelain', '--untracked-files=all']);\n if (status.exitCode !== 0 || status.stdout.trim()) {\n throw new Error('The review checkout has local changes; refusing to replace them.');\n }\n const before = await execute(sandbox, 'git', ['-C', workdir, 'rev-parse', 'HEAD']);\n if (before.exitCode !== 0) throw new Error('Could not read the current review checkout head.');\n const fetch = await gitTransfer(\n sandbox,\n ['-C', workdir, 'fetch', 'origin', `refs/merge-requests/${mergeRequestNumber}/head`],\n {\n env,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'GitLab review head refresh',\n },\n );\n if (fetch.exitCode !== 0) throw classifyGitFailure(fetch, 'pull-failed');\n const fetched = await execute(sandbox, 'git', ['-C', workdir, 'rev-parse', 'FETCH_HEAD']);\n if (fetched.exitCode !== 0 || fetched.stdout.trim().toLowerCase() !== expectedHeadSha.toLowerCase()) {\n throw new Error('The fetched GitLab review head differs from the provider-reported head; retry after it settles.');\n }\n if (before.stdout.trim().toLowerCase() === expectedHeadSha.toLowerCase()) {\n return { headSha: expectedHeadSha, changed: false };\n }\n const updated = await execute(sandbox, 'git', ['-C', workdir, 'checkout', '-B', branch, 'FETCH_HEAD'], { env });\n if (updated.exitCode !== 0) throw classifyGitFailure(updated, 'pull-failed');\n return { headSha: expectedHeadSha, changed: true };\n}\n\nasync function checkoutSessionBranchImpl(\n sandbox: ExecutableSandbox,\n workdir: string,\n options: SessionBranchOptions,\n): Promise<void> {\n const { branch, baseBranch, token, repoFullName, pullRequestNumber, mergeRequestNumber, cloneUrl, authUsername } =\n options;\n if (\n !isValidGitRef(branch) ||\n !isValidGitRef(baseBranch) ||\n (pullRequestNumber !== undefined && mergeRequestNumber !== undefined) ||\n (mergeRequestNumber !== undefined && (!Number.isSafeInteger(mergeRequestNumber) || mergeRequestNumber <= 0))\n ) {\n throw new MaterializeError('Refusing to create a session from an invalid branch name.', 'clone-failed');\n }\n assertRepositoryLocator(repoFullName, cloneUrl, 'clone-failed');\n\n const changeRequestSession = pullRequestNumber !== undefined || mergeRequestNumber !== undefined;\n // GitHub delegates later authenticated operations to `gh`. Other providers\n // deliberately receive no persistent credential helper. Remove the legacy\n // helper when reopening an older checkout so a stale sandbox cannot retain\n // credentials injected by an earlier implementation.\n const cleanCloneUrl = cloneUrl ?? cleanUrl(repoFullName);\n const authEnv = gitAuthenticationEnvironment(cleanCloneUrl, token, authUsername ?? 'x-access-token', 'pull-failed');\n const credentialKey = authUsername ? 'credential.' + credentialScope(cleanCloneUrl) + '.helper' : 'credential.helper';\n if (authUsername) {\n await execute(sandbox, 'git', ['-C', workdir, 'config', '--unset-all', credentialKey]);\n } else {\n const configured = await execute(sandbox, 'git', ['-C', workdir, 'config', credentialKey, GH_CREDENTIAL_HELPER]);\n if (configured.exitCode !== 0) throw classifyGitFailure(configured, 'pull-failed');\n }\n\n await configureGitIdentity(sandbox, workdir, options.identity ?? {});\n\n const current = await execute(sandbox, 'git', ['-C', workdir, 'branch', '--show-current']);\n if (current.exitCode === 0 && current.stdout.trim() === branch) return;\n\n const local = await execute(sandbox, 'git', [\n '-C',\n workdir,\n 'show-ref',\n '--verify',\n '--quiet',\n `refs/heads/${branch}`,\n ]);\n if (local.exitCode === 0) {\n const checkout = await execute(sandbox, 'git', ['-C', workdir, 'checkout', branch], { env: authEnv });\n if (checkout.exitCode !== 0) {\n if (isBlockedByLocalWork(checkout)) return;\n throw classifyGitFailure(checkout, 'clone-failed');\n }\n return;\n }\n\n const shallowClone =\n changeRequestSession &&\n (await execute(sandbox, 'git', ['-C', workdir, 'rev-parse', '--is-shallow-repository'])).stdout.trim() === 'true';\n const fetch = await fetchStartPoint(sandbox, workdir, options, shallowClone, authEnv);\n if (fetch.exitCode !== 0) throw classifyGitFailure(fetch, 'pull-failed');\n\n const create = await execute(sandbox, 'git', ['-C', workdir, 'checkout', '-b', branch, 'FETCH_HEAD'], {\n env: authEnv,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'branch checkout',\n });\n if (create.exitCode === 0 || isBlockedByLocalWork(create)) return;\n if (!isBranchCollision(create)) throw classifyGitFailure(create, 'clone-failed');\n\n // The branch exists even though the show-ref probe missed it: either another\n // materialization created it concurrently (adopt it), or the sandbox carries\n // a broken loose ref (remove it and retry).\n const adopt = await execute(sandbox, 'git', ['-C', workdir, 'checkout', branch], { env: authEnv });\n if (adopt.exitCode === 0 || isBlockedByLocalWork(adopt)) return;\n\n let drop = await execute(sandbox, 'git', ['-C', workdir, 'update-ref', '--no-deref', '-d', `refs/heads/${branch}`]);\n if (drop.exitCode !== 0) {\n const gitDir = await execute(sandbox, 'git', ['-C', workdir, 'rev-parse', '--absolute-git-dir']);\n if (gitDir.exitCode !== 0 || !gitDir.stdout.trim()) throw classifyGitFailure(create, 'clone-failed');\n drop = await execute(sandbox, 'rm', ['-f', '--', `${gitDir.stdout.trim()}/refs/heads/${branch}`]);\n }\n if (drop.exitCode !== 0) throw classifyGitFailure(create, 'clone-failed');\n\n const retry = await execute(sandbox, 'git', ['-C', workdir, 'checkout', '-b', branch, 'FETCH_HEAD'], {\n env: authEnv,\n timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,\n phase: 'branch checkout retry',\n });\n if (retry.exitCode !== 0) {\n if (isBlockedByLocalWork(retry)) return;\n throw classifyGitFailure(retry, 'clone-failed');\n }\n}\n\n/**\n * True when `git checkout -b` failed only because the branch ref already\n * exists — the collision Factory hits when a pooled sandbox carries a ref the\n * show-ref probe could not see (broken loose ref) or a concurrent\n * materialization created the branch after the probe ran.\n */\nfunction isBranchCollision(result: SandboxCommandResult): boolean {\n return /a branch named .* already exists/i.test(`${result.stderr || ''}\\n${result.stdout || ''}`);\n}\n\n/**\n * True when a failed `git checkout` just means uncommitted or untracked files\n * in the working tree would be clobbered by the branch switch. Those files are\n * a session's work in progress — the switch must yield to them, never the\n * other way around.\n */\nfunction isBlockedByLocalWork(result: SandboxCommandResult): boolean {\n const output = `${result.stderr || ''}\\n${result.stdout || ''}`;\n return /Your local changes to the following files would be overwritten by checkout|untracked working tree files would be overwritten by checkout/i.test(\n output,\n );\n}\n\n/**\n * Return the origin URL when the workdir contains this repository, including a\n * legacy checkout whose remote still embeds credentials.\n */\nasync function existingCheckoutRemote(\n sandbox: ExecutableSandbox,\n workdir: string,\n cloneUrl: string,\n): Promise<string | null> {\n const result = await execute(sandbox, 'git', ['-C', workdir, 'remote', 'get-url', 'origin']);\n if (result.exitCode !== 0) return null;\n const url = result.stdout.trim();\n const actual = normalizedRemoteUrl(url);\n const expected = normalizedRemoteUrl(cloneUrl);\n return actual !== null && expected !== null && actual === expected ? url : null;\n}\n\n/** Remove credentials persisted by an older implementation from origin. */\nasync function scrubRemote(\n sandbox: ExecutableSandbox,\n workdir: string,\n repoFullName: string,\n cloneUrl: string = cleanUrl(repoFullName),\n): Promise<void> {\n let failure: string;\n try {\n const result = await execute(sandbox, 'git', ['-C', workdir, 'remote', 'set-url', 'origin', cloneUrl]);\n if (result.exitCode === 0) return;\n failure = result.stderr.trim() || result.stdout.trim();\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n throw new MaterializeError(`Failed to scrub installation token from git remote: ${failure}`, 'pull-failed');\n}\n\n/**\n * Turn a failed git command into an actionable error, detecting the common\n * \"cannot reach github.com\" egress failure.\n */\nfunction classifyGitFailure(\n result: SandboxCommandResult,\n fallback: 'clone-failed' | 'pull-failed' | 'push-failed',\n): MaterializeError {\n const stderr = result.stderr || '';\n if (/could not resolve host|failed to connect|network is unreachable|Connection timed out/i.test(stderr)) {\n return new MaterializeError(\n 'The sandbox could not reach github.com. The sandbox network must allow outbound egress to github.com.',\n 'egress-blocked',\n );\n }\n const verb = fallback === 'clone-failed' ? 'clone' : fallback === 'pull-failed' ? 'pull' : 'push';\n return new MaterializeError(`git ${verb} failed: ${stderr}`, fallback);\n}\n\n// ---------------------------------------------------------------------------\n// Phase 1 — git identity + token-scoped push primitive\n//\n// These helpers let the sandbox author and push commits safely. The install\n// token is short-lived, minted per-operation server-side, and supplied only to\n// the Git process through its environment. It never enters argv or persistent\n// repository configuration.\n// ---------------------------------------------------------------------------\n\nexport { isValidGitRef };\n\n/** Identity used to author commits inside the sandbox. */\nexport interface GitIdentity {\n name?: string | null;\n email?: string | null;\n /** GitHub login, used to derive a stable noreply identity when name/email are absent. */\n login?: string | null;\n}\n\n/**\n * Resolve a concrete `{ name, email }` for git authorship from a possibly-sparse\n * identity. Falls back to a GitHub-style noreply identity so commits are never\n * authored with an empty or host-derived identity.\n */\nexport function resolveGitIdentity(identity: GitIdentity): { name: string; email: string } {\n const login = (identity.login || '').trim();\n const name = (identity.name || '').trim() || login || 'Mastra Code';\n const email =\n (identity.email || '').trim() ||\n (login ? `${login}@users.noreply.github.com` : 'mastra-code@users.noreply.github.com');\n return { name, email };\n}\n\n/** Configure repository-local commit identity through direct Git argv calls. */\nexport async function configureGitIdentity(\n sandbox: ExecutableSandbox,\n workdir: string,\n identity: GitIdentity,\n): Promise<void> {\n const { name, email } = resolveGitIdentity(identity);\n const setName = await execute(sandbox, 'git', ['-C', workdir, 'config', 'user.name', name]);\n if (setName.exitCode !== 0) {\n throw new MaterializeError(`Failed to set git user.name: ${setName.stderr.trim()}`, 'commit-failed');\n }\n const setEmail = await execute(sandbox, 'git', ['-C', workdir, 'config', 'user.email', email]);\n if (setEmail.exitCode !== 0) {\n throw new MaterializeError(`Failed to set git user.email: ${setEmail.stderr.trim()}`, 'commit-failed');\n }\n}\n\nexport interface PushedBranch {\n /** The local branch tip that was pushed. */\n commit: string;\n /** True when the remote already had this commit, so the push sent nothing new. */\n upToDate: boolean;\n}\n\nasync function pushAuthenticatedBranch(\n sandbox: ExecutableSandbox,\n workdir: string,\n branch: string,\n cloneUrl: string,\n token: string,\n username: string,\n): Promise<PushedBranch> {\n const tip = await execute(sandbox, 'git', ['-C', workdir, 'rev-parse', '--verify', `refs/heads/${branch}`]);\n if (tip.exitCode !== 0) throw classifyGitFailure(tip, 'push-failed');\n const env = gitAuthenticationEnvironment(cloneUrl, token, username, 'push-failed');\n const push = await execute(sandbox, 'git', ['-C', workdir, 'push', '--porcelain', '-u', 'origin', branch], { env });\n if (push.exitCode !== 0) throw classifyGitFailure(push, 'push-failed');\n // Porcelain lines read `<flag>\\t<src>:<dst>\\t<summary>`; `=` marks a ref the remote already had.\n const upToDate = push.stdout\n .split('\\n')\n .some(line => line.startsWith('=\\t') && line.split('\\t')[1]?.startsWith(`refs/heads/${branch}:`));\n return { commit: tip.stdout.trim(), upToDate };\n}\n\n/** Whether the checkout has a local `refs/heads/<branch>`. */\nexport async function hasLocalBranch(sandbox: ExecutableSandbox, workdir: string, branch: string): Promise<boolean> {\n const ref = await execute(sandbox, 'git', ['-C', workdir, 'show-ref', '--verify', '--quiet', `refs/heads/${branch}`]);\n if (ref.exitCode === 0) return true;\n if (ref.exitCode === 1) return false;\n throw classifyGitFailure(ref, 'push-failed');\n}\n\n/**\n * Advance the session branch to HEAD and switch to it, carrying over local work.\n * Leave an already-ahead branch and its checkout unchanged; never discard its commits.\n */\nexport async function ensureLocalBranch(sandbox: ExecutableSandbox, workdir: string, branch: string): Promise<void> {\n if (!isValidGitRef(branch)) {\n throw new MaterializeError(`Refusing to materialize: invalid branch name '${branch}'.`, 'push-failed');\n }\n const exists = await hasLocalBranch(sandbox, workdir, branch);\n if (exists) {\n const ref = `refs/heads/${branch}`;\n const tip = await execute(sandbox, 'git', ['-C', workdir, 'rev-parse', '--verify', ref]);\n if (tip.exitCode !== 0) throw classifyGitFailure(tip, 'push-failed');\n const head = await execute(sandbox, 'git', ['-C', workdir, 'rev-parse', '--verify', 'HEAD']);\n if (head.exitCode !== 0) throw classifyGitFailure(head, 'push-failed');\n const oldOid = tip.stdout.trim();\n const headOid = head.stdout.trim();\n const ancestor = await execute(sandbox, 'git', ['-C', workdir, 'merge-base', '--is-ancestor', oldOid, headOid]);\n if (ancestor.exitCode === 1) {\n const ahead = await execute(sandbox, 'git', ['-C', workdir, 'merge-base', '--is-ancestor', headOid, oldOid]);\n if (ahead.exitCode === 0) return;\n if (ahead.exitCode !== 1) throw classifyGitFailure(ahead, 'push-failed');\n throw new MaterializeError(\n `Refusing to move session branch '${branch}': it has diverged from the active HEAD. Check out or merge the session branch before pushing.`,\n 'push-failed',\n );\n }\n if (ancestor.exitCode !== 0) throw classifyGitFailure(ancestor, 'push-failed');\n const current = await execute(sandbox, 'git', ['-C', workdir, 'symbolic-ref', '--quiet', 'HEAD']);\n if (current.exitCode !== 0 && current.exitCode !== 1) throw classifyGitFailure(current, 'push-failed');\n if (current.stdout.trim() === ref) return;\n // update-ref does not enforce worktree ownership, unlike branch -f.\n const worktrees = await execute(sandbox, 'git', ['-C', workdir, 'worktree', 'list', '--porcelain', '-z']);\n if (worktrees.exitCode !== 0) throw classifyGitFailure(worktrees, 'push-failed');\n if (worktrees.stdout.split('\\0').includes(`branch ${ref}`)) {\n throw new MaterializeError(\n `Refusing to move session branch '${branch}': it is checked out in another worktree.`,\n 'push-failed',\n );\n }\n const advanced = await execute(sandbox, 'git', ['-C', workdir, 'update-ref', ref, headOid, oldOid]);\n if (advanced.exitCode !== 0) throw classifyGitFailure(advanced, 'push-failed');\n }\n const switched = await execute(sandbox, 'git', ['-C', workdir, 'switch', ...(exists ? [] : ['-c']), branch]);\n if (switched.exitCode !== 0) throw classifyGitFailure(switched, 'push-failed');\n}\n\n/** Whether `workdir` is a checkout of the repository at `cloneUrl`. */\nexport async function isCheckoutOf(sandbox: ExecutableSandbox, workdir: string, cloneUrl: string): Promise<boolean> {\n return (await existingCheckoutRemote(sandbox, workdir, cloneUrl)) !== null;\n}\n\n/**\n * Push a branch back to GitHub with credentials scoped to the Git process.\n * The token never enters argv, a repository URL, or persistent configuration.\n */\nexport async function pushBranch(\n sandbox: ExecutableSandbox,\n workdir: string,\n branch: string,\n token: string,\n repoFullName: string,\n): Promise<void> {\n if (!isValidGitRef(branch)) {\n throw new MaterializeError(`Refusing to push: invalid branch name '${branch}'.`, 'push-failed');\n }\n assertRepositoryLocator(repoFullName, undefined, 'push-failed');\n await pushAuthenticatedBranch(sandbox, workdir, branch, cleanUrl(repoFullName), token, 'x-access-token');\n}\n\n/**\n * Push the active session branch through the provider-neutral repository\n * access contract without persisting or exposing provider credentials.\n */\nexport async function pushRepositoryBranch(\n sandbox: ExecutableSandbox,\n workdir: string,\n branch: string,\n access: RepositoryAccess,\n repoFullName: string,\n): Promise<PushedBranch> {\n if (!isValidGitRef(branch)) {\n throw new MaterializeError(`Refusing to push: invalid branch name '${branch}'.`, 'push-failed');\n }\n assertRepositoryLocator(repoFullName, access.cloneUrl, 'push-failed');\n const authorization = access.authorization;\n if (!authorization?.token) {\n throw new MaterializeError('Repository access did not include push credentials.', 'push-failed');\n }\n return pushAuthenticatedBranch(\n sandbox,\n workdir,\n branch,\n access.cloneUrl,\n authorization.token,\n authorization.username ?? 'x-access-token',\n );\n}\n\nexport interface CommitResult {\n /** True when a commit was created; false when there was nothing to commit. */\n committed: boolean;\n}\n\n/**\n * Stage every change in the working tree and create a commit inside the\n * sandbox. The git identity is configured first so authorship is correct. When\n * there is nothing to commit this is a no-op (`committed: false`) rather than an\n * error, so callers can safely commit-then-push without first diffing.\n *\n * @param sandbox the live sandbox containing the checkout\n * @param workdir the session workdir to commit in\n * @param message the commit message (passed as one argv value)\n * @param identity authorship identity for the commit\n */\nexport async function commitAll(\n sandbox: ExecutableSandbox,\n workdir: string,\n message: string,\n identity: GitIdentity,\n): Promise<CommitResult> {\n await configureGitIdentity(sandbox, workdir, identity);\n\n const add = await execute(sandbox, 'git', ['-C', workdir, 'add', '-A']);\n if (add.exitCode !== 0) {\n throw new MaterializeError(`git add failed: ${add.stderr.trim() || add.stdout.trim()}`, 'commit-failed');\n }\n\n // Nothing staged → nothing to commit. `git diff --cached --quiet` exits 1 when\n // there are staged changes, 0 when the index is clean.\n const staged = await execute(sandbox, 'git', ['-C', workdir, 'diff', '--cached', '--quiet']);\n if (staged.exitCode === 0) {\n return { committed: false };\n }\n\n const commit = await execute(sandbox, 'git', ['-C', workdir, 'commit', '-m', message]);\n if (commit.exitCode !== 0) {\n throw new MaterializeError(`git commit failed: ${commit.stderr.trim() || commit.stdout.trim()}`, 'commit-failed');\n }\n\n return { committed: true };\n}\n\n// ---------------------------------------------------------------------------\n// Phase 2 — setup / teardown lifecycle commands\n//\n// The org-configured setup and teardown shell commands run in the session's\n// materialized workdir. The workdir is always resolved server-side from the\n// live sandbox; client input never reaches a filesystem path.\n// ---------------------------------------------------------------------------\n\n/** Error raised when the org's setup or teardown command fails in the sandbox. */\nexport class SetupCommandError extends Error {\n constructor(\n message: string,\n readonly code: 'setup-failed' | 'teardown-failed',\n ) {\n super(message);\n this.name = 'SetupCommandError';\n }\n}\n\n/**\n * Run the project's setup command (e.g. `pnpm i && pnpm build`) inside the\n * freshly materialized session workdir. Called before the checkout is handed\n * to any agent run so it is ready to build/test. A non-zero exit is a hard\n * error — starting agent work in a half-set-up tree is worse than failing the\n * request.\n *\n * Security model: the command is intentionally arbitrary shell — that is the\n * feature (install deps, build, seed fixtures). It is only configurable by\n * authenticated org members (the settings route is gated by\n * `resolveOrgTenant` + org-scoped project lookup, with length and\n * control-character validation), and it executes exclusively inside the\n * project's isolated sandbox — the same environment where org members already\n * run arbitrary shell via the agent's command tool. It never runs on the web\n * server host, so it grants no privilege beyond what sandbox access already\n * provides.\n *\n * @param sandbox live sandbox containing the checkout\n * @param workdir the server-resolved session workdir the command runs in\n * @param command the org-configured setup shell command\n */\nasync function runLifecycleCommand(\n sandbox: ExecutableSandbox,\n workdir: string,\n command: string,\n options: {\n phase: 'setup' | 'teardown';\n timeoutMs?: number;\n env?: Record<string, string>;\n /** Values to mask in a failure message, beyond `env`; a function is read once the command has run. */\n mask?: Record<string, string> | (() => Record<string, string>);\n },\n): Promise<void> {\n const result = await sh(sandbox, `cd ${shellQuote(workdir)} && { ${command}\\n}`, {\n phase: `${options.phase} command`,\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n // Per-call only: build values must never enter the sandbox's runtime env.\n ...(options.env && Object.keys(options.env).length > 0 ? { env: options.env } : {}),\n });\n if (result.exitCode !== 0) {\n // The message is stored as build status and shown in the UI, so mask any\n // Factory value (Build or Runtime) the command printed.\n // Mask before trimming: a value with an edge newline or space would no longer match once trimmed.\n const output = result.stderr.trim() ? result.stderr : result.stdout;\n const mask = typeof options.mask === 'function' ? options.mask() : options.mask;\n const detail = maskSandboxEnvValues(output, { ...mask, ...options.env })\n .trim()\n .slice(-1800);\n const label = options.phase === 'setup' ? 'Setup' : 'Teardown';\n throw new SetupCommandError(\n `${label} command failed (exit ${result.exitCode}): ${detail}`,\n options.phase === 'setup' ? 'setup-failed' : 'teardown-failed',\n );\n }\n}\n\n/**\n * @param buildEnv the Factory's Build variables, passed to this command only\n * @param runtimeEnv the Factory's Runtime variables the command can also see; masked in a failure message\n */\nexport async function runSetupCommand(\n sandbox: ExecutableSandbox,\n workdir: string,\n command: string,\n buildEnv?: Record<string, string>,\n runtimeEnv?: Record<string, string>,\n): Promise<void> {\n return runLifecycleCommand(sandbox, workdir, command, {\n phase: 'setup',\n ...(buildEnv ? { env: buildEnv } : {}),\n ...(runtimeEnv ? { mask: runtimeEnv } : {}),\n });\n}\n\n/**\n * Run the repository's best-effort teardown command from the materialized\n * session workdir. Callers own lifecycle policy: this helper reports failures\n * so the retirement coordinator can log them while still continuing with\n * scrub, pooling/destruction, cache invalidation, and row deletion.\n */\nexport async function runTeardownCommand(\n sandbox: ExecutableSandbox,\n workdir: string,\n command: string,\n options: { timeoutMs?: number } = {},\n): Promise<void> {\n return runLifecycleCommand(sandbox, workdir, command, {\n phase: 'teardown',\n // The command sees the Factory runtime values applied to this sandbox, so a failure is masked with them.\n mask: () => appliedSandboxEnv(sandbox),\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n });\n}\n\nexport interface CreatePullRequestArgs {\n /** Short-lived installation token, injected only into the `gh` process env. */\n token: string;\n /** Base branch the PR merges into. Ref-validated. */\n base: string;\n /** Head branch the PR is opened from. Ref-validated. */\n head: string;\n /** PR title. */\n title: string;\n /** PR body (optional). */\n body?: string;\n}\n\nexport interface CreatePullRequestResult {\n /** The PR URL parsed from `gh pr create` stdout. */\n url: string;\n}\n\n/**\n * Preflight that `gh` is installed in the sandbox. Only called on the PR path so\n * a missing `gh` never blocks clone/open. Surfaces an actionable error naming\n * the sandbox template requirement.\n */\nasync function assertGhAvailable(sandbox: ExecutableSandbox): Promise<void> {\n const version = await execute(sandbox, 'gh', ['--version']);\n if (version.exitCode !== 0) {\n throw new MaterializeError(\n 'The GitHub CLI (gh) is not installed in the sandbox. The sandbox template must include gh to open pull requests.',\n 'gh-missing',\n );\n }\n}\n\n/** Match the first GitHub PR URL in `gh pr create` output. */\nfunction parsePullRequestUrl(stdout: string): string | undefined {\n const match = stdout.match(/https:\\/\\/github\\.com\\/[^\\s]+\\/pull\\/\\d+/);\n return match?.[0];\n}\n\n/**\n * Open a pull request from inside the sandbox via `gh pr create`. The token is\n * passed only through a per-invocation `GH_TOKEN` env scoped to the single `gh`\n * process (never persisted), all arguments are passed as structured argv, and\n * the resulting PR URL is parsed from stdout.\n *\n * @param sandbox live sandbox containing the checkout\n * @param workdir the worktree (or repo) path the PR head branch is checked out in\n */\nexport async function createPullRequest(\n sandbox: ExecutableSandbox,\n workdir: string,\n { token, base, head, title, body }: CreatePullRequestArgs,\n): Promise<CreatePullRequestResult> {\n if (!isValidGitRef(base)) {\n throw new MaterializeError(`Refusing to open PR: invalid base branch '${base}'.`, 'pr-failed');\n }\n if (!isValidGitRef(head)) {\n throw new MaterializeError(`Refusing to open PR: invalid head branch '${head}'.`, 'pr-failed');\n }\n\n await assertGhAvailable(sandbox);\n\n const result = await execute(\n sandbox,\n 'gh',\n ['pr', 'create', '--base', base, '--head', head, '--title', title, '--body', body ?? ''],\n { cwd: workdir, env: { GH_TOKEN: token } },\n );\n if (result.exitCode !== 0) {\n const classified = classifyGitFailure(result, 'push-failed');\n if (classified.code === 'egress-blocked') {\n throw classified;\n }\n throw new MaterializeError(`gh pr create failed: ${result.stderr.trim() || result.stdout.trim()}`, 'pr-failed');\n }\n\n const url = parsePullRequestUrl(result.stdout);\n if (!url) {\n throw new MaterializeError(\n `gh pr create succeeded but no PR URL was found in its output: ${result.stdout.trim()}`,\n 'pr-failed',\n );\n }\n\n return { url };\n}\n"],"mappings":";;;;;;;;;;;;AAwCA,SAAgB,WAAW,OAAuB;CAEhD,OAAO,MAAM,MAAM,MAAM,GAAG,CAAC,CAAC,KAAK,OAAO,IAAI;AAChD;;;;;;;AAQA,MAAa,6BAA6B;;AAE1C,MAAa,8BAA8B;;;;;;;;;;AAuB3C,SAAS,0BAA0B,OAAyB;CAC1D,MAAM,SAAU,OAAgC;CAChD,OAAO,OAAO,WAAW,YAAY,UAAU;AACjD;AAEA,MAAM,aAAa;AACnB,MAAM,oBAAoB;;;;;;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sB,kBACpB,SACA,SACA,EAAE,OAAO,MAAM,MAAM,OAAO,QACM;CAClC,IAAI,CAAC,cAAc,IAAI,GACrB,MAAM,IAAI,iBAAiB,6CAA6C,KAAK,KAAK,WAAW;CAE/F,IAAI,CAAC,cAAc,IAAI,GACrB,MAAM,IAAI,iBAAiB,6CAA6C,KAAK,KAAK,WAAW;CAG/F,MAAM,kBAAkB,OAAO;CAE/B,MAAM,SAAS,MAAM,QACnB,SACA,MACA;EAAC;EAAM;EAAU;EAAU;EAAM;EAAU;EAAM;EAAW;EAAO;EAAU,QAAQ;CAAE,GACvF;EAAE,KAAK;EAAS,KAAK,EAAE,UAAU,MAAM;CAAE,CAC3C;CACA,IAAI,OAAO,aAAa,GAAG;EACzB,MAAM,aAAa,mBAAmB,QAAQ,aAAa;EAC3D,IAAI,WAAW,SAAS,kBACtB,MAAM;EAER,MAAM,IAAI,iBAAiB,wBAAwB,OAAO,OAAO,KAAK,KAAK,OAAO,OAAO,KAAK,KAAK,WAAW;CAChH;CAEA,MAAM,MAAM,oBAAoB,OAAO,MAAM;CAC7C,IAAI,CAAC,KACH,MAAM,IAAI,iBACR,iEAAiE,OAAO,OAAO,KAAK,KACpF,WACF;CAGF,OAAO,EAAE,IAAI;AACf"}
|
|
@@ -238,7 +238,7 @@ function createGithubSubscriptionTools(requestContext, github) {
|
|
|
238
238
|
}),
|
|
239
239
|
github_subscribe_pr: createTool({
|
|
240
240
|
id: "github_subscribe_pr",
|
|
241
|
-
description: "Subscribe this thread to GitHub pull request activity.
|
|
241
|
+
description: "Subscribe this thread to GitHub pull request activity. PRs created with gh pr create are subscribed automatically. Call this when you start working on an existing PR you did not create in this thread (reviewing it, fixing merge conflicts, addressing review comments, fixing CI, pushing to its branch), or to recover when automatic subscription did not occur. Closed or merged PRs are unsubscribed automatically. Accepts a canonical PR URL for any repository in this Factory; a bare PR number only when this session is filed under a single repository, so pass the URL when the Factory has more than one.",
|
|
242
242
|
inputSchema: pullRequestInputSchema,
|
|
243
243
|
execute: async ({ pullRequest }) => {
|
|
244
244
|
return {
|