# Migrate storage from SQLite to PostgreSQL — full dashboard cutover Migrates Fusion's storage layer to the embedded PostgreSQL `AsyncDataLayer` (the default backend) and **completes the satellite-store + feature cutover** so every dashboard and Command Center surface works in PG mode. ## Status — every surface works in embedded-PG mode Verified live against a running embedded-Postgres dashboard (all **200**, zero 5xx) and gate-tested (**23 files / 99 tests** on embedded PG, plus engine-core 294 and ci-shape 63 in the blocking merge gate; core/engine/cli/dashboard typecheck clean). | Area | Surfaces | State | |---|---|---| | Satellite stores | workflows, todos, insights, research, missions, goals, mailbox | ✅ | | Views | artifacts, documents, evals | ✅ | | Command Center | activity, productivity, team, tokens, tools, **workflows**, **github**, **signals**, **plugin-activations**, **live** (all 10) | ✅ | | Run execution | insight generation, research run execution | ✅ (store-path; AI step needs a provider) | | Live updates | SSE push for mission/research/insight events | ✅ | | Workflow editing | create / update / delete / select (+ id counter) | ✅ | | Engine | mission autopilot, incident-signal ingestion, regression storm-guard, agent wake-on-message | ✅ | | Core | tasks, agents, secrets, automations, memory, chat, usage, PRs, git | ✅ | ## Approach Each satellite store gets an `Async<Store>` wrapper exposing the sync store's method names over the existing `async-*-store.ts` helpers; `get<Store>Store()` returns a `Sync | Async` union; consumers `await` (harmless on sync), and engine/CLI paths that can't convert use `instanceof Sync` graceful fallback. Analytics aggregators branch on `"ping" in dbOrLayer` to run schema-qualified raw SQL over `project.*` (snake_case) in PG. Executors/orchestrators/autopilot are await-converted to drive the union store; the async store wrappers extend `EventEmitter` so SSE live-push fires in both backends. Not-yet-ported capabilities degrade gracefully (never 500) and are individually called out in commits. ## Sync with main The branch is kept continuously merged with `main` (currently through FN-7845, 2026-07-12); the earlier "final rebase deferred" note no longer applies. Use **Create a merge commit** (or squash) to land it — GitHub's rebase-merge cannot replay a merge-maintained branch. ## Residual Review Findings Multi-agent code review of the PostgreSQL satellite-store ports (U1–U5) applied 3 safe fixes (see `fix(review): apply autofix feedback`). The following are **real but gated** — recorded here as follow-up work rather than auto-applied. All are SQLite→PostgreSQL **concurrency/atomicity regressions**: the sync stores were immune only by SQLite's single-writer, single-threaded-handler execution; the async ports open multi-await read-modify-write windows. **Reachability is low today** because the execution engines that generate concurrent same-run mutations (insight run executor, research orchestrator/dispatcher) are `instanceof`-gated to sync mode in PG. No process-crash class survived (all engine fallbacks correctly guard the sync store). - **[P1] Research `appendResearchEvent` dual-write is non-atomic** (`packages/core/src/async-research-store.ts`, corroborated: adversarial + reliability). The `research_run_events` insert (own transaction) and the `run.events` jsonb update are separate writes — a crash between them, or two concurrent appends, splits the table count from the jsonb array. **Fix:** perform the seq-insert and the jsonb update in one `layer.transactionImmediate`. - **[P1] Research run terminal-reversion via stale full-row persist** (`async-research-store.ts` `persistResearchRun`/`updateResearchStatus`). Concurrent `PATCH /runs/:id/status` + `POST /runs/:id/events` can revert a terminal run to `running` by overwriting the whole row, bypassing the transition guard. **Fix:** scoped column `UPDATE`s with a `WHERE status …` guard, or optimistic version column. - **[P2] `updateResearchRun`/`updateInsightRun` read-then-write TOCTOU** — concurrent PATCHes last-writer-wins on the lifecycle merge. **Fix:** `SELECT … FOR UPDATE` / enclosing transaction. - **[P2] `upsertRun`/`createRunOrThrowConflict` check-then-create race** (`async-insight-store.ts`) — two callers can each create an "active" run. **Fix:** partial unique index on `(projectId, trigger) WHERE status IN ('pending','running')`. - **[P3] `createResearchRetryRun` return-value divergence** — sync returns the pre-update `queued` snapshot; async returns the reloaded `retry_waiting` run (persisted state is identical). Pick one side for cross-backend parity. - **[P2/perf] Mission `getMissionWithHierarchy`/`getMissionHealth` N+1 fan-out** — O(milestones×slices) sequential round-trips hold one pool slot per request; can starve the pool for large hierarchies. **Fix:** batched/joined reads. - **Testing gaps:** no PG-mode concurrency tests (interleaved status/event mutations), no sync↔async parity assertion for the lifecycle-error codes, and no mission status/health rollup parity test vs the sync `MissionStore`. ~~Out of scope (deferred): AI run *execution* (insight/research) + mission autopilot + live SSE mission events remain sync-gated/degraded in PG mode.~~ **Since ported** — insight/research run execution, mission autopilot, and SSE live push all run on the async layer now, which also makes the concurrency findings above genuinely reachable; they remain open follow-ups. --- ## Update — 2026-07-12: production-readiness hardening & live acceptance Everything below landed on this branch since the description above was written: **Production blockers from review — fixed** - `recoverStaleTransitionPending` ported to the async layer (backend moves write + clear the crash-safe marker; startup/maintenance sweeps no longer throw). - Lost-update class fixed: `atomicWriteTaskJson`/`WithAudit` write changed columns only (full-row upserts silently resurrected stale fields across concurrent store instances — the "task stuck unplanned forever" bug). - First-boot **auto-migration**: booting the PG backend over a project with a legacy `fusion.db` migrates it automatically (loud failure, SQLite kept as backup), and the dashboard shows a one-time **"your data was migrated" banner** with the backup paths and a Need-help Discord link. - `pg_dump`/`pg_restore` discovered from common install locations for embedded-mode backups. - The PG suite is part of the blocking merge gate (`test:pg-gate`). **Multi-project isolation (PR #2007, merged into this branch)** - `project_id` partition key on tasks / archived tasks / config, `taskProjectScope` threaded through every scan/claim/count, per-project config rows, layer bound to the project at startup. - Review P1 follow-up: the shared cold-storage `archive.archived_tasks` table is also partitioned and all archived-board reads/counts/searches are scoped. - Schema drift self-heal generalized to schema-qualified columns so existing databases upgrade in place. **Other changes** - Node settings sync **removed** in PG mode (409 `settings-sync-disabled-postgres`) — nodes share state by connecting to the same database; auth sync kept (per-machine file). - Perf (review findings): `listTasks` pushes column filter + ORDER BY + LIMIT/OFFSET into SQL; `getConversation` capped to the most recent 200 messages. - Fixed a false "operator action required" pause-abort log fired on every successfully auto-merged task. **Live acceptance — PASSED (2026-07-12)** A sandboxed instance (isolated HOME, embedded PG, real Opus executor) ran a task through the complete cycle: create → triage (AI spec) → execute → in-review → AI squash-merge landed on the project's `main` → done. A write+read sweep of every data surface (settings, comments, documents, attachments + artifact bridge + artifact edit, chat with real generation, goals, missions, agent mail, secrets, workflows, memory, CC analytics) was green on embedded PG. **Known remaining work** - The per-project `config` PK re-key has no upgrade path for pre-isolation embedded-PG databases (needs a real `DROP CONSTRAINT`/re-key migration; fresh databases are fine). - `pg_dump`/`pg_restore` binaries are not yet bundled in release artifacts (PATH/common-location discovery only). - The satellite-store concurrency findings listed above. --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: Phil Larson <hello@phillarson.xyz> Co-authored-by: fusion-merge <fusion-merge@local>
462 lines
17 KiB
TypeScript
462 lines
17 KiB
TypeScript
import { exec } from "node:child_process";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { promisify } from "node:util";
|
|
import type { ApprovalRequest, ApprovalRequestActorSnapshot, ApprovalRequestStore, WorktrunkSettings } from "@fusion/core";
|
|
import type { ExternalIntegrationReleaseManifest } from "./external-integrations/manifest.js";
|
|
import { validateExternalIntegrationManifest } from "./external-integrations/manifest.js";
|
|
import { createLogger } from "./logger.js";
|
|
import type { EngineRunContext, RunAuditor } from "./run-audit.js";
|
|
import type { AgentActionGateContext } from "./agent-action-gate.js";
|
|
|
|
const execAsync = promisify(exec);
|
|
const logger = createLogger("worktrunk-installer");
|
|
|
|
export const WORKTRUNK_PROBE_TIMEOUT_MS = 10_000;
|
|
export const WORKTRUNK_DOWNLOAD_TIMEOUT_MS = 60_000;
|
|
export const WORKTRUNK_DOWNLOAD_MAX_BYTES = 50 * 1024 * 1024;
|
|
export const WORKTRUNK_CARGO_TIMEOUT_MS = 10 * 60_000;
|
|
export const WORKTRUNK_INSTALL_DIR = path.join(os.homedir(), ".fusion", "bin");
|
|
export const WORKTRUNK_BINARY_NAME = "wt";
|
|
export const WORKTRUNK_INSTALL_PATH = path.join(WORKTRUNK_INSTALL_DIR, WORKTRUNK_BINARY_NAME);
|
|
|
|
export interface WorktrunkReleaseAsset {
|
|
url: string;
|
|
sha256: string;
|
|
}
|
|
|
|
export interface WorktrunkReleaseManifest {
|
|
source: "upstream-pending-verification" | "upstream-verified";
|
|
version: string | null;
|
|
verifiedAt: string | null;
|
|
assets: Record<string, WorktrunkReleaseAsset>;
|
|
}
|
|
|
|
export const WORKTRUNK_PINNED_RELEASE: WorktrunkReleaseManifest = {
|
|
source: "upstream-pending-verification",
|
|
version: null,
|
|
verifiedAt: null,
|
|
assets: {},
|
|
};
|
|
|
|
export const WORKTRUNK_INTEGRATION_MANIFEST: ExternalIntegrationReleaseManifest = {
|
|
id: "worktrunk",
|
|
binaryName: WORKTRUNK_BINARY_NAME,
|
|
upstreamRepo: "max-sixty/worktrunk",
|
|
docsUrl: "https://worktrunk.dev/",
|
|
source: WORKTRUNK_PINNED_RELEASE.source,
|
|
version: WORKTRUNK_PINNED_RELEASE.version,
|
|
verifiedAt: WORKTRUNK_PINNED_RELEASE.verifiedAt,
|
|
assets: Object.fromEntries(
|
|
Object.entries(WORKTRUNK_PINNED_RELEASE.assets).map(([name, asset]) => [name, { url: asset.url, sha256: asset.sha256 }]),
|
|
),
|
|
};
|
|
|
|
export interface WorktrunkManifestValidationError {
|
|
ok: false;
|
|
missingFields: Array<"source" | "version" | "verifiedAt" | "assets" | `assets.${string}.url` | `assets.${string}.sha256`>;
|
|
reason: string;
|
|
}
|
|
|
|
export type WorktrunkManifestValidationResult =
|
|
| { ok: true }
|
|
| WorktrunkManifestValidationError;
|
|
|
|
const AUTO_INSTALL_DISABLED_MESSAGE =
|
|
"worktrunk auto-install path disabled; set worktrunk.binaryPath or install worktrunk on PATH";
|
|
|
|
export class WorktrunkBinaryUnavailableError extends Error {
|
|
constructor(message: string, details?: Record<string, unknown>) {
|
|
super(message);
|
|
this.name = "WorktrunkBinaryUnavailableError";
|
|
if (details) Object.assign(this, details);
|
|
}
|
|
}
|
|
|
|
export class WorktrunkInstallDeniedError extends Error {
|
|
constructor(message: string, details?: Record<string, unknown>) {
|
|
super(message);
|
|
this.name = "WorktrunkInstallDeniedError";
|
|
if (details) Object.assign(this, details);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Known `stage` values on details:
|
|
* - `auto-install-disabled`
|
|
* - `manifest-unverified`
|
|
*/
|
|
export class WorktrunkInstallFailedError extends Error {
|
|
constructor(message: string, details?: Record<string, unknown>) {
|
|
super(message);
|
|
this.name = "WorktrunkInstallFailedError";
|
|
if (details) Object.assign(this, details);
|
|
}
|
|
}
|
|
|
|
const resolveCache = new Map<string, { inputBinaryPath: string | null; path: string; resolvedAt: number }>();
|
|
|
|
function worktrunkInstallDedupeKey(): string {
|
|
return WORKTRUNK_PINNED_RELEASE.version
|
|
? `worktrunk_install:${WORKTRUNK_PINNED_RELEASE.version}`
|
|
: "worktrunk_install:pending";
|
|
}
|
|
|
|
function worktrunkVersionLabel(): string {
|
|
return WORKTRUNK_PINNED_RELEASE.version ?? "pending";
|
|
}
|
|
|
|
export function validateWorktrunkManifest(input: unknown): WorktrunkManifestValidationResult {
|
|
const record = input && typeof input === "object" && !Array.isArray(input) ? (input as Record<string, unknown>) : {};
|
|
const validation = validateExternalIntegrationManifest({
|
|
id: "worktrunk",
|
|
binaryName: WORKTRUNK_BINARY_NAME,
|
|
upstreamRepo: "max-sixty/worktrunk",
|
|
docsUrl: "https://worktrunk.dev/",
|
|
source: record.source,
|
|
version: record.version,
|
|
verifiedAt: record.verifiedAt,
|
|
assets: record.assets,
|
|
});
|
|
|
|
if (validation.ok) return { ok: true };
|
|
|
|
const narrowMissingFields: WorktrunkManifestValidationError["missingFields"] = [];
|
|
const outOfShapeFields: string[] = [];
|
|
const addNarrow = (field: WorktrunkManifestValidationError["missingFields"][number]): void => {
|
|
if (!narrowMissingFields.includes(field)) narrowMissingFields.push(field);
|
|
};
|
|
|
|
for (const field of validation.missingFields) {
|
|
if (
|
|
field === "source" ||
|
|
field === "version" ||
|
|
field === "verifiedAt" ||
|
|
field === "assets" ||
|
|
/^assets\.[^.]+\.(url|sha256)$/.test(field)
|
|
) {
|
|
addNarrow(field as WorktrunkManifestValidationError["missingFields"][number]);
|
|
} else if (field === "assets:must-be-empty-when-pending") {
|
|
addNarrow("assets");
|
|
} else {
|
|
outOfShapeFields.push(field);
|
|
}
|
|
}
|
|
|
|
if (narrowMissingFields.length === 0) {
|
|
addNarrow("assets");
|
|
}
|
|
|
|
const reasonSuffix = outOfShapeFields.length > 0
|
|
? ` (non-worktrunk fields: ${outOfShapeFields.join(", ")})`
|
|
: "";
|
|
|
|
return {
|
|
ok: false,
|
|
missingFields: narrowMissingFields,
|
|
reason: `${validation.reason}${reasonSuffix}`,
|
|
};
|
|
}
|
|
|
|
function homeKey(settings: WorktrunkSettings): string {
|
|
return `${os.homedir()}::${settings.binaryPath ?? ""}`;
|
|
}
|
|
|
|
async function emitBinaryAudit(
|
|
auditor: RunAuditor | undefined,
|
|
type: "binary:install-requested" | "binary:install-success" | "binary:install-failed" | "binary:install-denied",
|
|
metadata: Record<string, unknown>,
|
|
): Promise<void> {
|
|
if (!auditor) return;
|
|
await auditor.filesystem({ type, target: WORKTRUNK_INSTALL_PATH, metadata });
|
|
}
|
|
|
|
async function emitInstallSuccessAudit(
|
|
auditor: RunAuditor | undefined,
|
|
payload: { binaryPath: string; installSource: "release-binary" | "cargo"; durationMs: number },
|
|
runContext?: EngineRunContext,
|
|
): Promise<void> {
|
|
if (!auditor) return;
|
|
try {
|
|
await auditor.git({
|
|
type: "worktree:worktrunk-install",
|
|
target: payload.binaryPath,
|
|
metadata: {
|
|
op: "install",
|
|
binaryPath: payload.binaryPath,
|
|
installSource: payload.installSource,
|
|
durationMs: payload.durationMs,
|
|
taskId: runContext?.taskId,
|
|
runId: runContext?.runId,
|
|
},
|
|
});
|
|
} catch (err) {
|
|
logger.warn("install-audit-failed", {
|
|
err: err instanceof Error ? err.message : String(err),
|
|
});
|
|
}
|
|
}
|
|
|
|
async function lookupPath(binaryName: string): Promise<string | null> {
|
|
const command = process.platform === "win32" ? "where" : "which";
|
|
try {
|
|
const { stdout } = await execAsync(`${command} ${binaryName}`, {
|
|
timeout: WORKTRUNK_PROBE_TIMEOUT_MS,
|
|
maxBuffer: 1024 * 1024,
|
|
});
|
|
return stdout.split(/\r?\n/).map((line) => line.trim()).find(Boolean) ?? null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/*
|
|
FNXC:WindowsTerminalStartup 2026-07-03-16:10:
|
|
On Windows the worktrunk CLI (`wt`) collides by name with Windows Terminal (`wt.exe`), which ships as an App Execution Alias under %LOCALAPPDATA%\Microsoft\WindowsApps and is on PATH by default on Windows 11. `where wt` therefore resolves to Windows Terminal, and probing it with `wt --version` LAUNCHES Windows Terminal — popping its native "Windows Terminal <version>" Help/version dialog whenever worktrunk resolution runs (e.g. on dashboard load or a Settings save, field report Issue 4). Never exec a resolved `wt` that is the Windows Terminal alias: on Windows a bare `wt`/`wt.exe` command name (PATH auto-discovery OR a bare `binaryPath` override) is refused because it resolves to Windows Terminal, and an absolute path is refused when it lives under WindowsApps or a Microsoft.WindowsTerminal package dir. A genuine worktrunk must be an explicit full path or the Fusion-managed ~/.fusion/bin install. This guard sits in probeWorktrunk — the single choke point every resolution surface (cached/override/PATH/install/settings-route) funnels through — so the invariant holds everywhere.
|
|
*/
|
|
export const WORKTRUNK_WINDOWS_TERMINAL_COLLISION_MESSAGE =
|
|
"Refusing to probe `wt` on Windows: the resolved binary is Windows Terminal (wt.exe), not worktrunk. Set `worktrunk.binaryPath` to the real worktrunk executable, or let Fusion install it under ~/.fusion/bin.";
|
|
|
|
export function isWindowsTerminalBinary(binaryPath: string): boolean {
|
|
if (process.platform !== "win32") return false;
|
|
// Compute the basename from the backslash-normalized string directly rather
|
|
// than path.basename(): on a POSIX build host (tests/CI) node's default `path`
|
|
// is POSIX and would not split on "\\", so a Windows path would be misparsed.
|
|
const normalized = binaryPath.replace(/\//g, "\\").toLowerCase();
|
|
const base = (normalized.split("\\").pop() ?? "").replace(/\.exe$/, "");
|
|
if (base !== "wt") return false;
|
|
// A bare `wt` / `wt.exe` (no directory component) resolves through PATH, where on
|
|
// Windows it is Windows Terminal's App Execution Alias — so a bare override is just
|
|
// as dangerous as a PATH auto-discovery. Refuse it; worktrunk must be an explicit
|
|
// full path or the Fusion-managed install.
|
|
if (!normalized.includes("\\")) return true;
|
|
// With a directory, only treat it as Windows Terminal when it lives in one of its
|
|
// known homes: the WindowsApps alias dir, or a `Microsoft.WindowsTerminal_*` package
|
|
// dir. Match the full package prefix (not a bare "windowsterminal" substring) so a
|
|
// genuine worktrunk under an unrelated folder like `...\windowsterminal-tools\wt.exe`
|
|
// is still probed.
|
|
return normalized.includes("\\windowsapps\\") || normalized.includes("microsoft.windowsterminal");
|
|
}
|
|
|
|
export async function probeWorktrunk(binaryPath: string): Promise<{ ok: boolean; version?: string; error?: string }> {
|
|
if (isWindowsTerminalBinary(binaryPath)) {
|
|
logger.warn("probe: refusing to launch Windows Terminal wt.exe", { binaryPath });
|
|
return { ok: false, error: WORKTRUNK_WINDOWS_TERMINAL_COLLISION_MESSAGE };
|
|
}
|
|
try {
|
|
const { stdout } = await execAsync(`"${binaryPath}" --version`, {
|
|
timeout: WORKTRUNK_PROBE_TIMEOUT_MS,
|
|
maxBuffer: 1024 * 1024,
|
|
});
|
|
const version = stdout.match(/(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)/)?.[1];
|
|
return { ok: true, ...(version ? { version } : {}) };
|
|
} catch (error) {
|
|
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
}
|
|
}
|
|
|
|
export async function resolveWorktrunkBinary(opts: {
|
|
settings: WorktrunkSettings;
|
|
auditor?: RunAuditor;
|
|
runContext?: EngineRunContext;
|
|
actionGateContext?: AgentActionGateContext;
|
|
}): Promise<{
|
|
binaryPath: string;
|
|
source: "override" | "path" | "cached" | "installed-release" | "installed-cargo";
|
|
}> {
|
|
const { settings } = opts;
|
|
const key = homeKey(settings);
|
|
const cached = resolveCache.get(key);
|
|
if (cached && cached.inputBinaryPath === (settings.binaryPath ?? null)) {
|
|
const probe = await probeWorktrunk(cached.path);
|
|
if (probe.ok) return { binaryPath: cached.path, source: "cached" };
|
|
}
|
|
|
|
logger.log("resolve: checking override");
|
|
if (settings.binaryPath) {
|
|
const probe = await probeWorktrunk(settings.binaryPath);
|
|
if (probe.ok) return { binaryPath: settings.binaryPath, source: "override" };
|
|
}
|
|
|
|
logger.log("resolve: checking PATH");
|
|
const onPath = await lookupPath(WORKTRUNK_BINARY_NAME);
|
|
if (onPath) {
|
|
const probe = await probeWorktrunk(onPath);
|
|
if (probe.ok) return { binaryPath: onPath, source: "path" };
|
|
}
|
|
|
|
logger.log("resolve: checking installed cache path");
|
|
const cachedInstallPath = settings.installedBinaryPath ?? WORKTRUNK_INSTALL_PATH;
|
|
const installProbe = await probeWorktrunk(cachedInstallPath);
|
|
if (installProbe.ok) return { binaryPath: cachedInstallPath, source: "cached" };
|
|
|
|
logger.log("resolve: install path disabled; failing");
|
|
try {
|
|
const installed = await installWorktrunk(opts);
|
|
return { binaryPath: installed.binaryPath, source: installed.source };
|
|
} catch (error) {
|
|
if (error instanceof WorktrunkInstallFailedError && (error as { stage?: string }).stage === "manifest-unverified") {
|
|
throw error;
|
|
}
|
|
throw new WorktrunkInstallFailedError(AUTO_INSTALL_DISABLED_MESSAGE, { stage: "auto-install-disabled" });
|
|
}
|
|
}
|
|
|
|
export async function requestWorktrunkInstallApproval(opts: {
|
|
approvalStore: ApprovalRequestStore;
|
|
actor: ApprovalRequestActorSnapshot;
|
|
projectId?: string;
|
|
}): Promise<{ approvalRequestId: string; status: "pending" | "approved" | "denied" | "completed" }> {
|
|
const dedupeKey = worktrunkInstallDedupeKey();
|
|
const existing = await opts.approvalStore.findLatestByDedupeKey({
|
|
requesterActorId: opts.actor.actorId,
|
|
taskId: undefined,
|
|
dedupeKey,
|
|
});
|
|
if (existing) {
|
|
return { approvalRequestId: existing.id, status: existing.status };
|
|
}
|
|
|
|
const created = await opts.approvalStore.create({
|
|
requester: opts.actor,
|
|
targetAction: {
|
|
category: "network_api",
|
|
action: "worktrunk_install",
|
|
summary: `Install worktrunk ${worktrunkVersionLabel() === "pending" ? "(pending verification)" : `v${worktrunkVersionLabel()}`}`,
|
|
resourceType: "binary",
|
|
resourceId: WORKTRUNK_INSTALL_PATH,
|
|
context: {
|
|
version: WORKTRUNK_PINNED_RELEASE.version,
|
|
assets: WORKTRUNK_PINNED_RELEASE.assets,
|
|
installPath: WORKTRUNK_INSTALL_PATH,
|
|
source: "dashboard",
|
|
projectId: opts.projectId,
|
|
approvalDedupeKey: dedupeKey,
|
|
},
|
|
},
|
|
});
|
|
|
|
return { approvalRequestId: created.id, status: created.status };
|
|
}
|
|
|
|
export async function executeApprovedWorktrunkInstall(opts: {
|
|
approvalStore: ApprovalRequestStore;
|
|
settings: WorktrunkSettings;
|
|
request: ApprovalRequest;
|
|
auditor?: RunAuditor;
|
|
}): Promise<{ binaryPath: string; source: "installed-release" | "installed-cargo" }> {
|
|
if (opts.request.status !== "approved") {
|
|
throw new WorktrunkInstallDeniedError(`Approval request ${opts.request.id} is not approved`, {
|
|
requestId: opts.request.id,
|
|
status: opts.request.status,
|
|
});
|
|
}
|
|
|
|
const result = await installWorktrunk({
|
|
settings: opts.settings,
|
|
auditor: opts.auditor,
|
|
gateOverride: "pre-approved",
|
|
});
|
|
await opts.approvalStore.markCompleted(opts.request.id, {
|
|
actor: {
|
|
actorId: "system",
|
|
actorType: "system",
|
|
actorName: "System",
|
|
},
|
|
note: `Installed ${result.binaryPath}`,
|
|
});
|
|
return result;
|
|
}
|
|
|
|
async function applyInstallGate(opts: {
|
|
auditor?: RunAuditor;
|
|
runContext?: EngineRunContext;
|
|
gateOverride?: "pre-approved";
|
|
actionGateContext?: AgentActionGateContext;
|
|
}): Promise<{ satisfied: boolean }> {
|
|
if (opts.gateOverride === "pre-approved") {
|
|
await emitBinaryAudit(opts.auditor, "binary:install-requested", {
|
|
reason: "pre-approved",
|
|
taskId: opts.runContext?.taskId,
|
|
runId: opts.runContext?.runId,
|
|
});
|
|
return { satisfied: true };
|
|
}
|
|
|
|
await emitBinaryAudit(opts.auditor, "binary:install-denied", {
|
|
reason: "auto-install-disabled",
|
|
taskId: opts.runContext?.taskId,
|
|
runId: opts.runContext?.runId,
|
|
});
|
|
throw new WorktrunkInstallFailedError(AUTO_INSTALL_DISABLED_MESSAGE, { stage: "auto-install-disabled" });
|
|
}
|
|
|
|
export async function installWorktrunk(opts: {
|
|
settings: WorktrunkSettings;
|
|
auditor?: RunAuditor;
|
|
runContext?: EngineRunContext;
|
|
gateOverride?: "pre-approved";
|
|
actionGateContext?: AgentActionGateContext;
|
|
}): Promise<{ binaryPath: string; source: "installed-release" | "installed-cargo" }> {
|
|
const startedAt = Date.now();
|
|
await applyInstallGate(opts);
|
|
|
|
const manifestValidation = validateWorktrunkManifest(WORKTRUNK_PINNED_RELEASE);
|
|
if (!manifestValidation.ok) {
|
|
throw new WorktrunkInstallFailedError(manifestValidation.reason, {
|
|
stage: "manifest-unverified",
|
|
missingFields: manifestValidation.missingFields,
|
|
});
|
|
}
|
|
|
|
const assets = Object.entries(WORKTRUNK_PINNED_RELEASE.assets);
|
|
if (assets.length === 0) {
|
|
throw new WorktrunkInstallFailedError("Worktrunk release manifest is missing assets for installation.", {
|
|
stage: "manifest-unverified",
|
|
missingFields: ["assets"],
|
|
});
|
|
}
|
|
const [assetName, asset] = assets[0];
|
|
if (!asset.url.trim()) {
|
|
throw new WorktrunkInstallFailedError(`Worktrunk release manifest is missing assets.${assetName}.url.`, {
|
|
stage: "manifest-unverified",
|
|
missingFields: [`assets.${assetName}.url`],
|
|
});
|
|
}
|
|
if (!asset.sha256.trim()) {
|
|
throw new WorktrunkInstallFailedError(`Worktrunk release manifest is missing assets.${assetName}.sha256.`, {
|
|
stage: "manifest-unverified",
|
|
missingFields: [`assets.${assetName}.sha256`],
|
|
});
|
|
}
|
|
|
|
await emitBinaryAudit(opts.auditor, "binary:install-success", {
|
|
source: "installed-release",
|
|
binaryPath: WORKTRUNK_INSTALL_PATH,
|
|
taskId: opts.runContext?.taskId,
|
|
runId: opts.runContext?.runId,
|
|
});
|
|
|
|
// Emit install audit only for true installs; path/cached/override resolutions remain silent.
|
|
await emitInstallSuccessAudit(
|
|
opts.auditor,
|
|
{
|
|
binaryPath: WORKTRUNK_INSTALL_PATH,
|
|
installSource: "release-binary",
|
|
durationMs: Math.max(0, Date.now() - startedAt),
|
|
},
|
|
opts.runContext,
|
|
);
|
|
|
|
resolveCache.set(homeKey(opts.settings), {
|
|
inputBinaryPath: opts.settings.binaryPath ?? null,
|
|
path: WORKTRUNK_INSTALL_PATH,
|
|
resolvedAt: Date.now(),
|
|
});
|
|
return { binaryPath: WORKTRUNK_INSTALL_PATH, source: "installed-release" };
|
|
}
|
|
|
|
export function clearWorktrunkResolveCache(): void {
|
|
resolveCache.clear();
|
|
}
|