mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-02 16:58:52 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Operators use run logs and restricted provider traces to inspect agent work. > - Local log and trace files depend on the web server's persistent volume. > - That dependency prevents overlapping volume-backed Railway deployments. > - This PR reuses the instance S3 store for batched log and trace payloads with conditional publication. > - Existing Postgres rows retain their contracts; native export recovery reuses events already committed before Runner acknowledgement. > - S3-configured servers automatically copy and verify retained history before a later deployment cutover. ## Linked Issues or Issue Description **Subsystem affected** Server run logs, restricted provider traces, storage providers, and migration tooling. **Problem or motivation** Replacing the web server and its disk must preserve committed log output and retained traces. The current S3 mirror can repeatedly upload a growing file. Moving those payloads into Postgres would add database writes, WAL, replication, and backup work. **Proposed solution** Reuse the existing instance storage configuration, S3-compatible provider and credential chain. Store new run logs under run-logs/ and opted-in raw traces under provider-traces/, below the existing prefix. Cloud keeps its existing bucket and bucket-scoped credentials per stack. Add no new configuration switches. Store immutable payload segments and bounded binary range indexes directly in S3. Publish each batch with an ETag-conditional head. Keep existing database ownership and lifecycle records. Recover canonical native exports from their existing validated control event source, checkpointing export progress in S3. Add no new payload writes to Postgres. Preserve local defaults and migrate settled history with verified byte counts and digests. **Alternatives considered** Postgres payload chunks add control-plane load. Repeated whole-file mirrors amplify transfer work. The first index prototype left superseded index nodes; the final binary index keeps all normally published nodes reachable. **Roadmap alignment** This is a storage prerequisite for replacing the main web/API server. It does not enable deployment overlap, detach a volume, or change native Runner protocol acknowledgements. The maintainer approved this implementation scope. ROADMAP.md has no duplicate implementation item. Related PR: #16770 improves the existing in-flight mirror. This PR preserves that legacy backend and uses the existing instance S3 profile for new journals. ## What Changed - Automatically select S3 segments for new logs and opted-in traces when instance file storage uses S3. Reuse bucket, endpoint, region, prefix, path style and credentials. Remove separate backend switches. Keep local-disk instances local. - Share the existing storage configuration resolver with product files. Preserve config-file settings, environment precedence and the existing root prefix. Keep pre-existing run-log mirror settings for legacy history. - Add bounded buffering, conditional ownership fencing, immutable range reads, stable byte offsets, and completion hashing. - Dispatch all existing log consumers through the recorded backend. Coalesce output progress writes and publish live log messages after storage receipts. - Recover interrupted canonical native exports from their existing durable source. Exclude separate credential, cleanup, and reprojection records. Replay missing callback ranges and deduplicate late delivery. Repair settled archives after controller lease expiry. Bound shared repair work and stop it when all readers cancel. Serve the published prefix when best-effort repair fails. - Add encrypted optional trace channels, replacement reads, durable deletion tombstones, and deadline-driven local/external expiry cleanup independently of heartbeat scheduling. Stream historical source and remote verification. Propagate worker cancellation through trace open, conditional-write probing, upload, restore and reads. Fence deletion even before the first object head exists; abort and drain owned captures. - Retry transient storage errors, distinguish 409 from failed preconditions, and backpressure bounded log admission. Track interrupted trace imports explicitly so ordinary local deletion stays independent of S3. - Automatically migrate retained history through the existing delivery coordinator. Process one log and one trace per batch. Retry unresolved history with backoff and stop scans after completion. Keep the inventory/import command as optional diagnosis and repair. Verify source and remote bytes before switching references. Verify finalized native size and digest before setting its export cursor. Require ordered source coverage when completeness metadata is missing. Preserve original trace expiry. Block active, missing, corrupt, and unproven sources. - Preserve identity and run-secret redaction in live and recovered native logs. Register runtime log redaction secrets once through the existing encrypted registry. Keep agent private keys in their existing owner. - Add storage, migration, retention, UTF-8, and route-privacy coverage, plus operating documentation and qualification tooling. - Add no schema, payload table, per-record SQL, production dependency, or lockfile change. ## Verification - Final fixes at `b3a44c898e` passed all 116 selected startup, retention, attribution and cancellation controls. The disabled-scheduler cleanup and concurrent-repair defects reproduced red before the fixes. A timed-out repair still prevents later storage reads. - The merged source passed 124 storage and real-Postgres Cloud configuration tests. These include automatic history migration, existing environment/file vault keys, source-directory removal, five real-SDK stalled-request cancellation cases, shared capability-probe cancellation and multi-chunk trace ordering. Saved Cloud S3 settings work after the legacy config file is gone. - Workspace typecheck and full build passed at the merged parent `19f702d780`. Server typecheck and build passed again at `b3a44c898e`. - Actual app acceptance: finish a process-agent run through the normal API, stage its retained local-file input, then restart. Automatic migration reports one migrated item and zero blockers. Remove the original web home and restart at `b3a44c898e` with an empty home, the existing S3 profile and the existing vault key file. The normal log API preserves all five producer lines and exactly 788 bytes, with SHA-256 `74d9ae469da28bfe89b9b50a0e132aec24fe9e6d686496ed5e4ffa6167151036`. No log-specific storage settings are present. - Actual expiry acceptance: with heartbeat scheduling disabled, a trace remains unexpired after startup and later reaches its fixture deadline. The worker marks the row deleted and tombstones both S3 channel heads. The retained run log stays byte-identical. The process fixture emits no provider protocol frames, so nonempty encrypted payloads are qualified separately through the real SDK round trips. - Isolation tests use identical run identities in two stack buckets. Cleanup in one existing prefix leaves another prefix, another company and product files intact. Read-only Cloud source inspection confirms a bucket and bucket-scoped credentials per stack. Four existing Cloud storage environment-contract tests passed. No Cloud provisioning changed and no new live vendor permission probe was performed. - Earlier qualification passed 1,014 affected storage/native tests and 27 privacy-route tests with isolated Docker Postgres. An abrupt process test commits 1,000 records, receives receipts, dies by SIGKILL and loses its directory; another process reads every byte and continues. The real Rust Runner experiment acknowledges 32 records while the export cursor is zero, then continues the same Runner PID after controller loss. All 64 records export once with exactly 64 existing control rows. Repeated snapshot/Stop commands completed in 162/81 ms. - Emulator workload: 1,000 burst records used two batch PUTs. Eight steady streams produced 240 records with 104 conditional PUTs and 72 GETs over 6.9 seconds. These are synthetic operation counts, not fleet sizing or provider prices. - Failure evidence is retained. Compact native events over 64 KiB, missing file-key support, disabled-scheduler retention and repair failure handling all reproduced before their fixes. Fixture repairs addressed cold module setup, localhost/IPC permissions, the S3 bucket-name limit and a mode-0700 crash-test directory. Full local `pnpm test:run` was stopped after host PostgreSQL semaphore exhaustion; affected suites used isolated Docker databases instead. Native package library symlinks were restored with the package's standard hydration helper. - The `19f702d780` browser session-recovery case timed out while saving a task title. All eight browser shards passed on `b3a44c898e`, including that case, with no UI behavior or assertion change. Fresh-head CI passed at `b3a44c898e`: 55 successful checks, three skipped checks and one neutral check. The branch is conflict-free. - Map and module-boundary checks passed. Current-head Greptile is 5/5 with zero unresolved review threads. Reproduce the opt-in storage suites with `PAPERCLIP_LOG_TEST_S3_ENDPOINT` and a dedicated `PAPERCLIP_RUN_EVIDENCE_MIGRATION_DATABASE_URL` ending in `_test`. See `doc/run-evidence-storage.md` for operating limits, automatic migration, optional diagnostics and rollout qualification. ## Risks - Keep the existing per-stack bucket, prefix and vault key stable across replacements. Relocating that storage is a separate whole-instance operation. - This release automatically changes new log storage for existing S3-configured instances. Local-disk instances remain local. Canonical native source replay is qualified with a deterministic real Runner; actual remote execution and production-provider qualification remain rollout gates. Generic server-only diagnostics and optional raw trace tails without a surviving source can be incomplete after a crash. This does not establish full zero-downtime deployment. - Before deploying this release, qualify the actual S3 provider. It must enforce conditional writes and pass read, version, deletion, workload, and latency qualification. A capability probe rejects providers which ignore preconditions. Moto is emulator evidence only. - Dirty output is bounded and unconfirmed until S3 publication. Storage failure leaves persistence incomplete while task results and usage can settle. - Trace expiry is not yet represented by Cloud's external wake contract. Outstanding trace deadlines conservatively block sleep. - Automatic history copying requires the original source volume. Keep it until all retained resources pass verified import and clean-filesystem reads. Stop old binaries from creating new local-file runs. Missing or corrupt history remains blocked and visible in server logs. Rollback requires a compatible reader against the same external state. Ordinary object deletion does not erase retained historical object versions or backups. ## Model Used OpenAI Codex, `gpt-6.1-sol`, with reasoning, tool use, code execution, and browser verification. The runtime did not expose a context-window size. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
453 lines
20 KiB
TypeScript
453 lines
20 KiB
TypeScript
import { readConfigFile, resolveDeploymentMode } from "./config-file.js";
|
|
import { isCloudManagedInstance } from "./services/cloud-instance.js";
|
|
import { StartupRefusalError } from "./startup-refusals.js";
|
|
import type { PaperclipConfig } from "@paperclipai/shared";
|
|
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,
|
|
type BindMode,
|
|
type AuthBaseUrlMode,
|
|
type DeploymentExposure,
|
|
type DeploymentMode,
|
|
type SecretProvider,
|
|
inferBindModeFromHost,
|
|
resolveRuntimeBind,
|
|
validateConfiguredBindMode,
|
|
} from "@paperclipai/shared";
|
|
import {
|
|
resolveDefaultBackupDir,
|
|
resolveDefaultEmbeddedPostgresDir,
|
|
resolveDefaultSecretsKeyFilePath,
|
|
resolveHomeAwarePath,
|
|
} from "./home-paths.js";
|
|
import { loadStorageConfig, type StorageConfig } from "./storage/config.js";
|
|
|
|
if (!isCloudManagedInstance()) {
|
|
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 extends StorageConfig {
|
|
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;
|
|
isolatedSourceRehomeEnabled: boolean;
|
|
isolatedSourceRehomeDryRun: boolean;
|
|
nestedCloneMigrationEnabled: boolean;
|
|
nestedCloneMigrationDryRun: boolean;
|
|
workspaceReaperCooldownDays: number;
|
|
workspaceCompactionDelayHours: number | null;
|
|
skillVersionRetentionEnabled: boolean;
|
|
skillVersionRetentionDryRun: boolean;
|
|
skillVersionRetentionKeepNewest: number;
|
|
skillVersionRetentionGraceMinutes: number;
|
|
nativeHarnessBackupExpirationEnabled: boolean;
|
|
nativeHarnessBackupExpirationDryRun: boolean;
|
|
nativeHarnessBackupExpirationDays: number;
|
|
nativeRunnerEvidenceRetentionDays: number;
|
|
nativeWorkspaceSyncRetentionEnabled: boolean;
|
|
nativeWorkspaceSyncRetentionDryRun: boolean;
|
|
nativeWorkspaceSyncRetentionDays: number;
|
|
gitRestorePointRetentionDays: number;
|
|
gitRestorePointsEnabled: boolean;
|
|
gitRestorePointTerminalDelayDays: number;
|
|
gitRestorePointIdleDays: number;
|
|
taskDirectoryRetentionEnabled: boolean;
|
|
taskDirectoryRetentionDryRun: boolean;
|
|
taskDirectoryOrphanGraceDays: number;
|
|
serveUi: boolean;
|
|
uiDevMiddleware: boolean;
|
|
secretsProvider: SecretProvider;
|
|
secretsStrictMode: boolean;
|
|
secretsMasterKeyFilePath: string;
|
|
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(fileConfig: PaperclipConfig | null = readConfigFile()): Config {
|
|
const fileDatabaseMode =
|
|
(isCloudManagedInstance() || fileConfig?.database.mode === "postgres" ? "postgres" : "embedded-postgres") as DatabaseMode;
|
|
|
|
const fileDbUrl =
|
|
!isCloudManagedInstance() && fileDatabaseMode === "postgres"
|
|
? fileConfig?.database.connectionString
|
|
: undefined;
|
|
const fileDatabaseBackup = fileConfig?.database.backup;
|
|
const fileSecrets = fileConfig?.secrets;
|
|
|
|
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 storage = loadStorageConfig(fileConfig);
|
|
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 nativeRunnerEvidenceRetentionDays = Math.max(1, nonNegativeIntegerEnv("PAPERCLIP_NATIVE_RUNNER_EVIDENCE_RETENTION_DAYS", 7));
|
|
const nativeWorkspaceSyncRetentionDays = Math.max(1, nonNegativeIntegerEnv("PAPERCLIP_NATIVE_WORKSPACE_SYNC_RETENTION_DAYS", 7));
|
|
const gitRestorePointRetentionDays = Math.max(1, nonNegativeIntegerEnv("PAPERCLIP_GIT_RESTORE_POINT_RETENTION_DAYS", 90));
|
|
const gitRestorePointTerminalDelayDays = nonNegativeIntegerEnv("PAPERCLIP_GIT_RESTORE_POINT_TERMINAL_DELAY_DAYS", 3);
|
|
const gitRestorePointIdleDays = nonNegativeIntegerEnv("PAPERCLIP_GIT_RESTORE_POINT_IDLE_DAYS", 7);
|
|
const taskDirectoryOrphanGraceDays = Math.max(1, nonNegativeIntegerEnv("PAPERCLIP_TASK_DIRECTORY_ORPHAN_GRACE_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",
|
|
isolatedSourceRehomeEnabled: process.env.PAPERCLIP_ISOLATED_SOURCE_REHOME_ENABLED === "true",
|
|
isolatedSourceRehomeDryRun: process.env.PAPERCLIP_ISOLATED_SOURCE_REHOME_DRY_RUN === "true",
|
|
nestedCloneMigrationEnabled: process.env.PAPERCLIP_NESTED_CLONE_MIGRATION_ENABLED === "true",
|
|
nestedCloneMigrationDryRun: process.env.PAPERCLIP_NESTED_CLONE_MIGRATION_DRY_RUN === "true",
|
|
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,
|
|
nativeRunnerEvidenceRetentionDays,
|
|
nativeWorkspaceSyncRetentionEnabled: process.env.PAPERCLIP_NATIVE_WORKSPACE_SYNC_RETENTION_ENABLED !== "false",
|
|
nativeWorkspaceSyncRetentionDryRun: process.env.PAPERCLIP_NATIVE_WORKSPACE_SYNC_RETENTION_DRY_RUN === "true",
|
|
nativeWorkspaceSyncRetentionDays,
|
|
gitRestorePointRetentionDays,
|
|
gitRestorePointsEnabled: process.env.PAPERCLIP_GIT_RESTORE_POINTS_ENABLED === "true",
|
|
gitRestorePointTerminalDelayDays,
|
|
gitRestorePointIdleDays,
|
|
taskDirectoryRetentionEnabled: process.env.PAPERCLIP_TASK_DIRECTORY_RETENTION_ENABLED === "true",
|
|
taskDirectoryRetentionDryRun: process.env.PAPERCLIP_TASK_DIRECTORY_RETENTION_DRY_RUN !== "false",
|
|
taskDirectoryOrphanGraceDays,
|
|
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(),
|
|
),
|
|
...storage,
|
|
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",
|
|
};
|
|
}
|
|
|
|
export type CloudBootstrapConfig = {
|
|
databaseMode: "postgres";
|
|
databaseUrl: string;
|
|
databaseMigrationUrl: string | undefined;
|
|
};
|
|
|
|
export function loadCloudBootstrapConfig(): CloudBootstrapConfig {
|
|
if (!isCloudManagedInstance()) throw new Error("Cloud bootstrap configuration requires a managed instance");
|
|
const url = process.env.DATABASE_URL?.trim();
|
|
if (!url) throw new StartupRefusalError("database-contract-unmet", "Cloud bootstrap requires DATABASE_URL from the environment");
|
|
const migrationUrl = process.env.DATABASE_MIGRATION_URL?.trim() || undefined;
|
|
for (const [name, value] of [["DATABASE_URL", url], ["DATABASE_MIGRATION_URL", migrationUrl]]) {
|
|
if (!value) continue;
|
|
let parsed: URL;
|
|
try { parsed = new URL(value); } catch { throw new Error(`Cloud bootstrap ${name} must use PostgreSQL`); }
|
|
if (!["postgres:", "postgresql:"].includes(parsed.protocol)) throw new Error(`Cloud bootstrap ${name} must use PostgreSQL`);
|
|
}
|
|
return { databaseMode: "postgres", databaseUrl: url, databaseMigrationUrl: migrationUrl };
|
|
}
|