mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-24 10:13:11 +02:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Native agent sessions that run in a remote sandbox keep a host-side
failover copy of the sandbox's harness state, so a replacement sandbox
can resume the conversation
> - Each session keeps that copy forever, and one copy can reach several
gigabytes
> - On a busy instance these copies fill the volume, and no existing
cleanup touches them
> - Once a session's work is closed, its copy matters only if someone
reopens that work later
> - This pull request expires the copy after the session's issues have
been closed for a configurable window, and makes a reopened issue start
a fresh session
> - The benefit is bounded disk use without breaking active,
recoverable, or leased sessions
## Linked Issues or Issue Description
Bug report described in-PR (bug report template).
**What happened?**
After every remote turn, `checkpointRemoteRunner` writes the sandbox's
runner state and provider session home (for example `codex-home`) to
`durable-sessions/<scope>/failover-backups/current`. Only the same
session's next checkpoint replaces it. No code path deletes a session's
copy when the session ends, its issue closes, or its agent goes away, so
the instance volume fills. On one instance:
- 246 sessions held 17 GB of copies, 84 of them older than a week;
- 24 new sessions added 5 GB in a single day, one copy alone 3.2 GB.
**Expected behavior**
Disk used by failover copies stays bounded. A copy is kept while its
session can still resume (open issue, live run, pending recovery, or
live lease), and expires once the session's issues have been closed for
a while. A reopened issue then starts a fresh native session, instead of
failing with `runner_harness_backup_unavailable` on a replacement
sandbox.
**Steps to reproduce**
1. Run agents with a native runtime in a remote sandbox environment.
2. Let them complete many issues.
3. Watch
`<instance>/runtime/paperclip-runner/durable-sessions/*/failover-backups/current`
grow without bound after the issues close.
**Paperclip version or commit:** `master` at 9179d8dcc3.
**Deployment mode:** server with remote sandbox environments.
**Agent adapter(s) involved:** not adapter-specific (core bug); observed
with Codex sessions.
**Breaking changes**
- Reopening an issue that has been closed for longer than the window
(default 7 days) starts a fresh agent session instead of resuming the
old conversation.
- Disable with
`PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_ENABLED=false`, or lengthen
the window with `PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DAYS`.
## What Changed
-
**`server/src/services/native-runtime/native-harness-backup-expiration.ts`
(new):** the sweep. It checks at most 200 sessions and expires at most
50 per batch, continuing from a cursor. A copy expires only when all of
these hold:
- every issue the session ran on is `done` or `cancelled`, closed before
the window;
- the copy was written before the window;
- no run of the session is queued, running, or unfinished;
- every native run finalization of the session is settled (`committed`
or `terminal_failure`), with no recovery state or lease owner;
- no `active`, `released`, `retained`, or `pending_cleanup` environment
lease references the copy (by backup stamp, session run, or recorded
lease);
- the session is not executing, initializing, warm, or closing in this
process, and its directory has no pending cleanup activation.
- **One transaction:** the database checks share-lock the issues and
delete the agent task session that points at the session, so a reopened
issue cannot resume the expired session.
- **Atomic, non-blocking removal:** the copy is renamed to
`failover-backups/.retiring-<UUID>`, and a final check looks for a run
of the session. If one appeared, or the check throws, the rename is
undone. Only a confirmed copy becomes `.expired-<UUID>` and is deleted
with asynchronous file operations, so a multi-gigabyte removal does not
block the event loop. A later sweep restores an unconfirmed
`.retiring-*` copy when `current` is missing, drops it when a newer
`current` exists, and finishes an interrupted deletion. The rest of the
session directory is kept.
- **`native-session-executor.ts`:** exports
`nativeSessionScopeDigestIsBusy`, which checks the in-process executing,
initializing, warm, and closing session maps.
- **`native-harness-backup-stamp.ts`:** exports the state base path the
sweep scans.
- **`config.ts` and `index.ts`:** three environment controls
(`_ENABLED`, `_DRY_RUN`, `_DAYS`) and the scheduled sweep. It starts two
minutes after boot, honors shutdown, standby, and idle drain, and logs
candidates, reclaimed bytes, cleared task sessions, and skip reasons.
- **Docs:** `doc/recoverable-disk-cleanup.md` describes the sweep;
`doc/DEVELOPING.md` lists the variables.
- No code comments were added.
## Verification
- `pnpm exec vitest run
src/__tests__/native-harness-backup-expiration.test.ts
src/__tests__/native-harness-backup-expiration-config.test.ts` (in
`server/`): 30 passed, 24 of them against embedded Postgres plus 6
config tests. Cases:
- expiry for done and cancelled issues, including clearing the task
session;
- each keep condition: open issue, recently closed, live run, pending
finalization, recovery in progress, live lease, recent copy, cleanup
activation, in-process session;
- settled finalizations and expired leases do not block;
- dry run changes nothing;
- bounded batches continue across ticks;
- an interrupted deletion is finished, and an unconfirmed retiring copy
is restored or dropped;
- the configured clock controls the closed window.
- **Mutation checks:** treating `in_progress` as closed, ignoring live
leases, ignoring the configured clock, or not restoring a retiring copy
each fail the corresponding tests.
- `pnpm exec vitest run native-harness-backup config` (in `server/`): 19
files, 293 tests passed.
- `pnpm run typecheck` (in `server/`): pass.
- **Real server:** after building and bundling,
`scripts/server-boot-smoke.sh node server/dist-runtime/index.mjs`
reached healthy.
- **Manual equivalent on a live instance:** applying these checks by
hand (with a 3-day window) to 242 copies freed 7.1 GB. Most of the
remainder belonged to open issues or live leases.
## Risks
- **Reopen after the window:** the agent starts a fresh session and
loses the old conversation's provider history. Issue comments,
documents, and work products are unaffected.
- **Race with a wake:** the checks share-lock the issues, so a reopen
waits for the transaction. A run created for the session between commit
and rename is caught by the post-rename check, which restores the copy.
Such a run would find no task session and start fresh.
- **Missing owner run:** if the owning run row is gone (for example,
after an agent was deleted), the copy is kept, because the sweep cannot
prove the session is closed.
- **Untouched:** quarantined session roots and `continuity-breaks`
archives are not touched by this change.
- **Rollback:** set
`PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_ENABLED=false`, or revert.
Expired copies cannot be restored.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), 1M context, through Claude Code
with tool use (shell, file edits, local builds, tests and boots,
read-only measurements on a live instance).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
427 lines
18 KiB
TypeScript
427 lines
18 KiB
TypeScript
import { readConfigFile, resolveDeploymentMode } from "./config-file.js";
|
|
import { parseChatWebhookPublicBaseUrl } from "./chat-webhook-public-url.js";
|
|
import { execFileSync } from "node:child_process";
|
|
import { existsSync, realpathSync } from "node:fs";
|
|
import { basename, dirname, resolve } from "node:path";
|
|
import { config as loadDotenv } from "dotenv";
|
|
import { resolvePaperclipEnvPath } from "./paths.js";
|
|
import { maybeRepairLegacyWorktreeConfigAndEnvFiles } from "./worktree-config.js";
|
|
import { shouldLoadWorkingDirectoryEnv } from "./env-file-policy.js";
|
|
import { applyEmptyWorktreeSigningSecrets } from "./dev-runner-worktree.js";
|
|
import {
|
|
AUTH_BASE_URL_MODES,
|
|
BIND_MODES,
|
|
DEPLOYMENT_EXPOSURES,
|
|
SECRET_PROVIDERS,
|
|
STORAGE_PROVIDERS,
|
|
type BindMode,
|
|
type AuthBaseUrlMode,
|
|
type DeploymentExposure,
|
|
type DeploymentMode,
|
|
type SecretProvider,
|
|
type StorageProvider,
|
|
inferBindModeFromHost,
|
|
resolveRuntimeBind,
|
|
validateConfiguredBindMode,
|
|
} from "@paperclipai/shared";
|
|
import {
|
|
resolveDefaultBackupDir,
|
|
resolveDefaultEmbeddedPostgresDir,
|
|
resolveDefaultSecretsKeyFilePath,
|
|
resolveDefaultStorageDir,
|
|
resolveHomeAwarePath,
|
|
} from "./home-paths.js";
|
|
|
|
const PAPERCLIP_ENV_FILE_PATH = resolvePaperclipEnvPath();
|
|
if (existsSync(PAPERCLIP_ENV_FILE_PATH)) {
|
|
loadDotenv({ path: PAPERCLIP_ENV_FILE_PATH, override: false, quiet: true });
|
|
}
|
|
|
|
const CWD_ENV_PATH = resolve(process.cwd(), ".env");
|
|
const cwdEnvExists = existsSync(CWD_ENV_PATH);
|
|
const isSameFile = cwdEnvExists && existsSync(PAPERCLIP_ENV_FILE_PATH)
|
|
? realpathSync(CWD_ENV_PATH) === realpathSync(PAPERCLIP_ENV_FILE_PATH)
|
|
: CWD_ENV_PATH === PAPERCLIP_ENV_FILE_PATH;
|
|
if (shouldLoadWorkingDirectoryEnv({
|
|
cwdEnvExists,
|
|
isPaperclipEnvFile: isSameFile,
|
|
})) {
|
|
loadDotenv({ path: CWD_ENV_PATH, override: false, quiet: true });
|
|
}
|
|
|
|
if (basename(dirname(PAPERCLIP_ENV_FILE_PATH)) === ".paperclip") {
|
|
applyEmptyWorktreeSigningSecrets(dirname(dirname(PAPERCLIP_ENV_FILE_PATH)));
|
|
}
|
|
maybeRepairLegacyWorktreeConfigAndEnvFiles();
|
|
|
|
const TAILSCALE_DETECT_TIMEOUT_MS = 3000;
|
|
|
|
type DatabaseMode = "embedded-postgres" | "postgres";
|
|
|
|
export interface Config {
|
|
deploymentMode: DeploymentMode;
|
|
deploymentExposure: DeploymentExposure;
|
|
bind: BindMode;
|
|
customBindHost: string | undefined;
|
|
host: string;
|
|
port: number;
|
|
allowedHostnames: string[];
|
|
authBaseUrlMode: AuthBaseUrlMode;
|
|
authPublicBaseUrl: string | undefined;
|
|
chatWebhookPublicBaseUrl: string | undefined;
|
|
authDisableSignUp: boolean;
|
|
databaseMode: DatabaseMode;
|
|
databaseUrl: string | undefined;
|
|
databaseMigrationUrl: string | undefined;
|
|
embeddedPostgresDataDir: string;
|
|
embeddedPostgresPort: number;
|
|
databaseBackupEnabled: boolean;
|
|
databaseBackupIntervalMinutes: number;
|
|
databaseBackupRetentionDays: number;
|
|
databaseBackupDir: string;
|
|
gitCacheExpirationEnabled: boolean;
|
|
gitBaseExpirationEnabled: boolean;
|
|
gitCacheExpirationDryRun: boolean;
|
|
workspaceReaperCooldownDays: number;
|
|
workspaceCompactionDelayHours: number | null;
|
|
skillVersionRetentionEnabled: boolean;
|
|
skillVersionRetentionDryRun: boolean;
|
|
skillVersionRetentionKeepNewest: number;
|
|
skillVersionRetentionGraceMinutes: number;
|
|
nativeHarnessBackupExpirationEnabled: boolean;
|
|
nativeHarnessBackupExpirationDryRun: boolean;
|
|
nativeHarnessBackupExpirationDays: number;
|
|
serveUi: boolean;
|
|
uiDevMiddleware: boolean;
|
|
secretsProvider: SecretProvider;
|
|
secretsStrictMode: boolean;
|
|
secretsMasterKeyFilePath: string;
|
|
storageProvider: StorageProvider;
|
|
storageLocalDiskBaseDir: string;
|
|
storageS3Bucket: string;
|
|
storageS3Region: string;
|
|
storageS3Endpoint: string | undefined;
|
|
storageS3Prefix: string;
|
|
storageS3ForcePathStyle: boolean;
|
|
feedbackExportBackendUrl: string | undefined;
|
|
feedbackExportBackendToken: string | undefined;
|
|
heartbeatSchedulerEnabled: boolean;
|
|
heartbeatSchedulerIntervalMs: number;
|
|
companyDeletionEnabled: boolean;
|
|
telemetryEnabled: boolean;
|
|
announcementsEnabled: boolean;
|
|
announcementsFeedUrl: string;
|
|
}
|
|
|
|
function detectTailnetBindHost(): string | undefined {
|
|
const explicit = process.env.PAPERCLIP_TAILNET_BIND_HOST?.trim();
|
|
if (explicit) return explicit;
|
|
|
|
try {
|
|
const stdout = execFileSync("tailscale", ["ip", "-4"], {
|
|
encoding: "utf8",
|
|
stdio: ["ignore", "pipe", "ignore"],
|
|
timeout: TAILSCALE_DETECT_TIMEOUT_MS,
|
|
});
|
|
return stdout
|
|
.split(/\r?\n/)
|
|
.map((line) => line.trim())
|
|
.find(Boolean);
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
export function loadConfig(): Config {
|
|
const fileConfig = readConfigFile();
|
|
const fileDatabaseMode =
|
|
(fileConfig?.database.mode === "postgres" ? "postgres" : "embedded-postgres") as DatabaseMode;
|
|
|
|
const fileDbUrl =
|
|
fileDatabaseMode === "postgres"
|
|
? fileConfig?.database.connectionString
|
|
: undefined;
|
|
const fileDatabaseBackup = fileConfig?.database.backup;
|
|
const fileSecrets = fileConfig?.secrets;
|
|
const fileStorage = fileConfig?.storage;
|
|
|
|
const providerFromEnvRaw = process.env.PAPERCLIP_SECRETS_PROVIDER;
|
|
const providerFromEnv =
|
|
providerFromEnvRaw && SECRET_PROVIDERS.includes(providerFromEnvRaw as SecretProvider)
|
|
? (providerFromEnvRaw as SecretProvider)
|
|
: null;
|
|
const providerFromFile = fileSecrets?.provider;
|
|
const secretsProvider: SecretProvider = providerFromEnv ?? providerFromFile ?? "local_encrypted";
|
|
|
|
const storageProviderFromEnvRaw = process.env.PAPERCLIP_STORAGE_PROVIDER;
|
|
const storageProviderFromEnv =
|
|
storageProviderFromEnvRaw && STORAGE_PROVIDERS.includes(storageProviderFromEnvRaw as StorageProvider)
|
|
? (storageProviderFromEnvRaw as StorageProvider)
|
|
: null;
|
|
const storageProvider: StorageProvider = storageProviderFromEnv ?? fileStorage?.provider ?? "local_disk";
|
|
const storageLocalDiskBaseDir = resolveHomeAwarePath(
|
|
process.env.PAPERCLIP_STORAGE_LOCAL_DIR ??
|
|
fileStorage?.localDisk?.baseDir ??
|
|
resolveDefaultStorageDir(),
|
|
);
|
|
const storageS3Bucket = process.env.PAPERCLIP_STORAGE_S3_BUCKET ?? fileStorage?.s3?.bucket ?? "paperclip";
|
|
const storageS3Region = process.env.PAPERCLIP_STORAGE_S3_REGION ?? fileStorage?.s3?.region ?? "us-east-1";
|
|
const storageS3Endpoint = process.env.PAPERCLIP_STORAGE_S3_ENDPOINT ?? fileStorage?.s3?.endpoint ?? undefined;
|
|
const storageS3Prefix = process.env.PAPERCLIP_STORAGE_S3_PREFIX ?? fileStorage?.s3?.prefix ?? "";
|
|
const storageS3ForcePathStyle =
|
|
process.env.PAPERCLIP_STORAGE_S3_FORCE_PATH_STYLE !== undefined
|
|
? process.env.PAPERCLIP_STORAGE_S3_FORCE_PATH_STYLE === "true"
|
|
: (fileStorage?.s3?.forcePathStyle ?? false);
|
|
const feedbackExportBackendUrl =
|
|
process.env.PAPERCLIP_FEEDBACK_EXPORT_BACKEND_URL?.trim() ||
|
|
process.env.PAPERCLIP_TELEMETRY_BACKEND_URL?.trim() ||
|
|
undefined;
|
|
const feedbackExportBackendToken =
|
|
process.env.PAPERCLIP_FEEDBACK_EXPORT_BACKEND_TOKEN?.trim() ||
|
|
process.env.PAPERCLIP_TELEMETRY_BACKEND_TOKEN?.trim() ||
|
|
undefined;
|
|
|
|
const deploymentMode = resolveDeploymentMode(fileConfig);
|
|
const strictModeFromEnv = process.env.PAPERCLIP_SECRETS_STRICT_MODE;
|
|
const secretsStrictMode =
|
|
strictModeFromEnv !== undefined
|
|
? strictModeFromEnv === "true"
|
|
: (fileSecrets?.strictMode ?? deploymentMode === "authenticated");
|
|
const deploymentExposureFromEnvRaw = process.env.PAPERCLIP_DEPLOYMENT_EXPOSURE;
|
|
const deploymentExposureFromEnv =
|
|
deploymentExposureFromEnvRaw &&
|
|
DEPLOYMENT_EXPOSURES.includes(deploymentExposureFromEnvRaw as DeploymentExposure)
|
|
? (deploymentExposureFromEnvRaw as DeploymentExposure)
|
|
: null;
|
|
const deploymentExposure: DeploymentExposure =
|
|
deploymentMode === "local_trusted"
|
|
? "private"
|
|
: (deploymentExposureFromEnv ?? fileConfig?.server.exposure ?? "private");
|
|
const bindFromEnvRaw = process.env.PAPERCLIP_BIND;
|
|
const bindFromEnv =
|
|
bindFromEnvRaw && BIND_MODES.includes(bindFromEnvRaw as BindMode)
|
|
? (bindFromEnvRaw as BindMode)
|
|
: null;
|
|
const configuredHost = process.env.HOST ?? fileConfig?.server.host ?? "127.0.0.1";
|
|
const tailnetBindHost = detectTailnetBindHost();
|
|
const bind =
|
|
bindFromEnv ??
|
|
fileConfig?.server.bind ??
|
|
inferBindModeFromHost(configuredHost, { tailnetBindHost });
|
|
const customBindHost = process.env.PAPERCLIP_BIND_HOST ?? fileConfig?.server.customBindHost;
|
|
const authBaseUrlModeFromEnvRaw = process.env.PAPERCLIP_AUTH_BASE_URL_MODE;
|
|
const authBaseUrlModeFromEnv =
|
|
authBaseUrlModeFromEnvRaw &&
|
|
AUTH_BASE_URL_MODES.includes(authBaseUrlModeFromEnvRaw as AuthBaseUrlMode)
|
|
? (authBaseUrlModeFromEnvRaw as AuthBaseUrlMode)
|
|
: null;
|
|
const publicUrlFromEnv = process.env.PAPERCLIP_PUBLIC_URL;
|
|
const configuredAuthPublicBaseUrlRaw = [
|
|
process.env.PAPERCLIP_AUTH_PUBLIC_BASE_URL,
|
|
process.env.BETTER_AUTH_URL,
|
|
process.env.BETTER_AUTH_BASE_URL,
|
|
publicUrlFromEnv,
|
|
fileConfig?.auth?.publicBaseUrl,
|
|
].find((value): value is string => typeof value === "string" && value.trim().length > 0);
|
|
const managedRuntimePublicUrl = process.env.PAPERCLIP_MANAGED_RUNTIME_PUBLIC_URL?.trim() || undefined;
|
|
const authPublicBaseUrlRaw = configuredAuthPublicBaseUrlRaw ?? managedRuntimePublicUrl;
|
|
const authPublicBaseUrl = authPublicBaseUrlRaw?.trim() || undefined;
|
|
const authBaseUrlMode: AuthBaseUrlMode =
|
|
authBaseUrlModeFromEnv ??
|
|
(configuredAuthPublicBaseUrlRaw === undefined && managedRuntimePublicUrl
|
|
? "explicit"
|
|
: fileConfig?.auth?.baseUrlMode ?? (authPublicBaseUrl ? "explicit" : "auto"));
|
|
const disableSignUpFromEnv = process.env.PAPERCLIP_AUTH_DISABLE_SIGN_UP;
|
|
const authDisableSignUp: boolean =
|
|
disableSignUpFromEnv !== undefined
|
|
? disableSignUpFromEnv === "true"
|
|
: (fileConfig?.auth?.disableSignUp ?? false);
|
|
const allowedHostnamesFromEnvRaw = process.env.PAPERCLIP_ALLOWED_HOSTNAMES;
|
|
const allowedHostnamesFromEnv = allowedHostnamesFromEnvRaw
|
|
? allowedHostnamesFromEnvRaw
|
|
.split(",")
|
|
.map((value) => value.trim().toLowerCase())
|
|
.filter((value) => value.length > 0)
|
|
: null;
|
|
const publicUrlHostname = authPublicBaseUrl
|
|
? (() => {
|
|
try {
|
|
return new URL(authPublicBaseUrl).hostname.trim().toLowerCase();
|
|
} catch {
|
|
return null;
|
|
}
|
|
})()
|
|
: null;
|
|
const allowedHostnames = Array.from(
|
|
new Set(
|
|
[
|
|
...(allowedHostnamesFromEnv ?? fileConfig?.server.allowedHostnames ?? []),
|
|
...(publicUrlHostname ? [publicUrlHostname] : []),
|
|
]
|
|
.map((value) => value.trim().toLowerCase())
|
|
.filter(Boolean),
|
|
),
|
|
);
|
|
const companyDeletionEnvRaw = process.env.PAPERCLIP_ENABLE_COMPANY_DELETION;
|
|
const companyDeletionEnabled =
|
|
companyDeletionEnvRaw !== undefined
|
|
? companyDeletionEnvRaw === "true"
|
|
: deploymentMode === "local_trusted";
|
|
const databaseBackupEnabled =
|
|
process.env.PAPERCLIP_DB_BACKUP_ENABLED !== undefined
|
|
? process.env.PAPERCLIP_DB_BACKUP_ENABLED === "true"
|
|
: (fileDatabaseBackup?.enabled ?? true);
|
|
const databaseBackupIntervalMinutes = Math.max(
|
|
1,
|
|
Number(process.env.PAPERCLIP_DB_BACKUP_INTERVAL_MINUTES) ||
|
|
fileDatabaseBackup?.intervalMinutes ||
|
|
60,
|
|
);
|
|
const databaseBackupRetentionDays = Math.max(
|
|
1,
|
|
Number(process.env.PAPERCLIP_DB_BACKUP_RETENTION_DAYS) ||
|
|
fileDatabaseBackup?.retentionDays ||
|
|
7,
|
|
);
|
|
const databaseBackupDir = resolveHomeAwarePath(
|
|
process.env.PAPERCLIP_DB_BACKUP_DIR ??
|
|
fileDatabaseBackup?.dir ??
|
|
resolveDefaultBackupDir(),
|
|
);
|
|
// The terminal-workspace reaper waits this many days after an issue tree
|
|
// becomes terminal before it archives the workspace. A person can reopen the
|
|
// work inside this window. A value of 0 disables the cooldown and restores
|
|
// immediate reaping. A negative or non-numeric value falls back to the
|
|
// default. The day granularity obeys the PAPERCLIP_DB_BACKUP_RETENTION_DAYS
|
|
// precedent above. The default is 1 day: regenerable files are compacted
|
|
// after a few hours anyway, so a longer hold only keeps source checkouts of
|
|
// delivered work, and a recurring task produces one workspace per run.
|
|
const workspaceReaperCooldownDaysEnv =
|
|
process.env.PAPERCLIP_WORKSPACE_REAPER_COOLDOWN_DAYS?.trim();
|
|
const workspaceReaperCooldownDaysRaw = Number(workspaceReaperCooldownDaysEnv);
|
|
const workspaceReaperCooldownDays =
|
|
workspaceReaperCooldownDaysEnv
|
|
&& Number.isFinite(workspaceReaperCooldownDaysRaw)
|
|
&& workspaceReaperCooldownDaysRaw >= 0
|
|
? workspaceReaperCooldownDaysRaw
|
|
: 1;
|
|
// The terminal-workspace reaper removes regenerable files (installed
|
|
// dependencies, build output, tool caches) from a terminal workspace this
|
|
// many hours after its issue tree becomes terminal. The worktree and every
|
|
// source file stay; a resumed task regenerates the files when its workspace
|
|
// is provisioned again. 0 compacts on the next sweep. A negative, empty, or
|
|
// non-numeric value falls back to the default of 1 hour.
|
|
// PAPERCLIP_WORKSPACE_COMPACTION_ENABLED=false turns compaction off.
|
|
const workspaceCompactionDelayHoursEnv =
|
|
process.env.PAPERCLIP_WORKSPACE_COMPACTION_DELAY_HOURS?.trim();
|
|
const workspaceCompactionDelayHoursRaw = Number(workspaceCompactionDelayHoursEnv);
|
|
const workspaceCompactionDelayHours =
|
|
process.env.PAPERCLIP_WORKSPACE_COMPACTION_ENABLED?.trim().toLowerCase() === "false"
|
|
? null
|
|
: workspaceCompactionDelayHoursEnv
|
|
&& Number.isFinite(workspaceCompactionDelayHoursRaw)
|
|
&& workspaceCompactionDelayHoursRaw >= 0
|
|
? workspaceCompactionDelayHoursRaw
|
|
: 1;
|
|
// Skill version retention removes materialized version directories under
|
|
// `skills/<companyId>/__versions__/` that no current version, agent pin, or
|
|
// live run uses. It keeps this many newest versions per skill as a warm
|
|
// cache. A version directory used within the grace window also stays. A
|
|
// removed directory is written again from its version row on next use.
|
|
// Negative, empty, or non-numeric values fall back to the defaults.
|
|
const nonNegativeIntegerEnv = (name: string, fallback: number) => {
|
|
const raw = process.env[name]?.trim();
|
|
const value = Number(raw);
|
|
return raw && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
|
|
};
|
|
const skillVersionRetentionKeepNewest = nonNegativeIntegerEnv("PAPERCLIP_SKILL_VERSION_RETENTION_KEEP", 0);
|
|
const skillVersionRetentionGraceMinutes = nonNegativeIntegerEnv("PAPERCLIP_SKILL_VERSION_RETENTION_GRACE_MINUTES", 60);
|
|
const nativeHarnessBackupExpirationDays = Math.max(1, nonNegativeIntegerEnv("PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DAYS", 7));
|
|
const bindValidationErrors = validateConfiguredBindMode({
|
|
deploymentMode,
|
|
deploymentExposure,
|
|
bind,
|
|
host: configuredHost,
|
|
customBindHost,
|
|
});
|
|
if (bindValidationErrors.length > 0) {
|
|
throw new Error(bindValidationErrors[0]);
|
|
}
|
|
const resolvedBind = resolveRuntimeBind({
|
|
bind,
|
|
host: configuredHost,
|
|
customBindHost,
|
|
tailnetBindHost,
|
|
});
|
|
if (resolvedBind.errors.length > 0) {
|
|
throw new Error(resolvedBind.errors[0]);
|
|
}
|
|
|
|
return {
|
|
deploymentMode,
|
|
deploymentExposure,
|
|
bind: resolvedBind.bind,
|
|
customBindHost: resolvedBind.customBindHost,
|
|
host: resolvedBind.host,
|
|
port: Number(process.env.PORT) || fileConfig?.server.port || 3100,
|
|
allowedHostnames,
|
|
authBaseUrlMode,
|
|
authPublicBaseUrl,
|
|
chatWebhookPublicBaseUrl: parseChatWebhookPublicBaseUrl(
|
|
process.env.PAPERCLIP_CHAT_WEBHOOK_PUBLIC_URL,
|
|
),
|
|
authDisableSignUp,
|
|
databaseMode: fileDatabaseMode,
|
|
databaseUrl: process.env.DATABASE_URL ?? fileDbUrl,
|
|
databaseMigrationUrl: process.env.DATABASE_MIGRATION_URL,
|
|
embeddedPostgresDataDir: resolveHomeAwarePath(
|
|
fileConfig?.database.embeddedPostgresDataDir ?? resolveDefaultEmbeddedPostgresDir(),
|
|
),
|
|
embeddedPostgresPort: fileConfig?.database.embeddedPostgresPort ?? 54329,
|
|
databaseBackupEnabled,
|
|
databaseBackupIntervalMinutes,
|
|
databaseBackupRetentionDays,
|
|
databaseBackupDir,
|
|
gitCacheExpirationEnabled: process.env.PAPERCLIP_GIT_CACHE_EXPIRATION_ENABLED === "true",
|
|
gitBaseExpirationEnabled: process.env.PAPERCLIP_GIT_BASE_EXPIRATION_ENABLED === "true",
|
|
gitCacheExpirationDryRun: process.env.PAPERCLIP_GIT_CACHE_EXPIRATION_DRY_RUN !== "false",
|
|
workspaceReaperCooldownDays,
|
|
workspaceCompactionDelayHours,
|
|
skillVersionRetentionEnabled: process.env.PAPERCLIP_SKILL_VERSION_RETENTION_ENABLED !== "false",
|
|
skillVersionRetentionDryRun: process.env.PAPERCLIP_SKILL_VERSION_RETENTION_DRY_RUN === "true",
|
|
skillVersionRetentionKeepNewest,
|
|
skillVersionRetentionGraceMinutes,
|
|
nativeHarnessBackupExpirationEnabled: process.env.PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_ENABLED !== "false",
|
|
nativeHarnessBackupExpirationDryRun: process.env.PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DRY_RUN === "true",
|
|
nativeHarnessBackupExpirationDays,
|
|
serveUi:
|
|
process.env.SERVE_UI !== undefined
|
|
? process.env.SERVE_UI === "true"
|
|
: fileConfig?.server.serveUi ?? true,
|
|
uiDevMiddleware: process.env.PAPERCLIP_UI_DEV_MIDDLEWARE === "true",
|
|
secretsProvider,
|
|
secretsStrictMode,
|
|
secretsMasterKeyFilePath:
|
|
resolveHomeAwarePath(
|
|
process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE ??
|
|
fileSecrets?.localEncrypted.keyFilePath ??
|
|
resolveDefaultSecretsKeyFilePath(),
|
|
),
|
|
storageProvider,
|
|
storageLocalDiskBaseDir,
|
|
storageS3Bucket,
|
|
storageS3Region,
|
|
storageS3Endpoint,
|
|
storageS3Prefix,
|
|
storageS3ForcePathStyle,
|
|
feedbackExportBackendUrl,
|
|
feedbackExportBackendToken,
|
|
heartbeatSchedulerEnabled: process.env.HEARTBEAT_SCHEDULER_ENABLED !== "false",
|
|
heartbeatSchedulerIntervalMs: Math.max(10000, Number(process.env.HEARTBEAT_SCHEDULER_INTERVAL_MS) || 30000),
|
|
companyDeletionEnabled,
|
|
telemetryEnabled: fileConfig?.telemetry?.enabled ?? true,
|
|
announcementsEnabled: process.env.PAPERCLIP_ANNOUNCEMENTS_ENABLED !== "false",
|
|
announcementsFeedUrl: process.env.PAPERCLIP_ANNOUNCEMENTS_FEED_URL?.trim() || "https://pages.paperclip.ing/announcements/v1/current.json",
|
|
};
|
|
}
|