TypeScript
refactor(server): trace reusable domain operations (#21996)
Julius Marminge221d8494c75f
diff --git a/apps/server/src/background/BackgroundPolicy.ts b/apps/server/src/background/BackgroundPolicy.tsindex 49e1c7c2061..9cb7d372d4d 100644--- a/apps/server/src/background/BackgroundPolicy.ts+++ b/apps/server/src/background/BackgroundPolicy.ts@@ -289,16 +289,17 @@ export const make = Effect.fn("background.policy.make")(function* () {const hasDemand: BackgroundPolicy["Service"]["hasDemand"] = (scope) =>Effect.map(snapshot, (current) => current.activeScopeKeys.includes(scopeKey(scope)));- const shouldRunScopeWork: BackgroundPolicy["Service"]["shouldRunScopeWork"] = (scope) =>- Effect.gen(function* () {- const [current, settings] = yield* Effect.all([snapshot, backgroundActivitySettings]);- if (isHostConstrained(current.hostPower, settings)) {- return false;- }- return current.leases.some((lease) =>- leaseMayRunScopedWork(lease, scope, current.updatedAt, settings),- );- });+ const shouldRunScopeWork: BackgroundPolicy["Service"]["shouldRunScopeWork"] = Effect.fn(+ "BackgroundPolicy.shouldRunScopeWork",+ )(function* (scope) {+ const [current, settings] = yield* Effect.all([snapshot, backgroundActivitySettings]);+ if (isHostConstrained(current.hostPower, settings)) {+ return false;+ }+ return current.leases.some((lease) =>+ leaseMayRunScopedWork(lease, scope, current.updatedAt, settings),+ );+ });const shouldRunOpportunisticWork = Effect.map(snapshot,diff --git a/apps/server/src/desktopUpdate/DesktopAppUpdate.ts b/apps/server/src/desktopUpdate/DesktopAppUpdate.tsindex c1c49d308ee..2d774a34ba2 100644--- a/apps/server/src/desktopUpdate/DesktopAppUpdate.ts+++ b/apps/server/src/desktopUpdate/DesktopAppUpdate.ts@@ -66,74 +66,71 @@ export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* (? new ServerSelfUpdateError({ reason }): new ServerSelfUpdateError({ reason, cause });- const consumeReports = (+ const consumeReports = Effect.fn("DesktopAppUpdate.consumeReports")(function* (requestId: string,changes: Stream.Stream<DesktopUpdateStatusReport>,reportProgress: (stage: ServerSelfUpdateProgressStage,) => Effect.Effect<void, ServerSelfUpdateError>,- ) =>- Effect.gen(function* () {- const lastStage = yield* Ref.make<ServerSelfUpdateProgressStage | null>(null);- const emitStage = (- stage: ServerSelfUpdateProgressStage | null,- ): Effect.Effect<void, ServerSelfUpdateError> =>- stage === null- ? Effect.void- : Ref.get(lastStage).pipe(- Effect.flatMap((previous) =>- previous === stage- ? Effect.void- : Ref.set(lastStage, stage).pipe(Effect.andThen(reportProgress(stage))),- ),- );+ ) {+ const lastStage = yield* Ref.make<ServerSelfUpdateProgressStage | null>(null);+ const emitStage = (+ stage: ServerSelfUpdateProgressStage | null,+ ): Effect.Effect<void, ServerSelfUpdateError> =>+ stage === null+ ? Effect.void+ : Ref.get(lastStage).pipe(+ Effect.flatMap((previous) =>+ previous === stage+ ? Effect.void+ : Ref.set(lastStage, stage).pipe(Effect.andThen(reportProgress(stage))),+ ),+ );- const terminal = yield* changes.pipe(- Stream.filter((report) => report.requestId === requestId),- Stream.mapEffect(- (- report,- ): Effect.Effect<Option.Option<DesktopUpdateStatusReport>, ServerSelfUpdateError> =>- report.outcome === undefined- ? emitStage(desktopUpdateProgressStage(report.state)).pipe(- Effect.as(Option.none<DesktopUpdateStatusReport>()),- )- : Effect.succeedSome(report),- ),- Stream.filterMap(- Option.match({- onNone: () => Result.failVoid,- onSome: Result.succeed,- }),- ),- Stream.runHead,- );- if (Option.isNone(terminal)) {- return yield* failWith("The desktop app stopped reporting its update.");- }+ const terminal = yield* changes.pipe(+ Stream.filter((report) => report.requestId === requestId),+ Stream.mapEffect(+ (report): Effect.Effect<Option.Option<DesktopUpdateStatusReport>, ServerSelfUpdateError> =>+ report.outcome === undefined+ ? emitStage(desktopUpdateProgressStage(report.state)).pipe(+ Effect.as(Option.none<DesktopUpdateStatusReport>()),+ )+ : Effect.succeedSome(report),+ ),+ Stream.filterMap(+ Option.match({+ onNone: () => Result.failVoid,+ onSome: Result.succeed,+ }),+ ),+ Stream.runHead,+ );+ if (Option.isNone(terminal)) {+ return yield* failWith("The desktop app stopped reporting its update.");+ }- const report = terminal.value;- if (report.outcome === "ready-to-install") {- yield* emitStage("installing");- const targetVersion =- report.state.downloadedVersion ??- report.state.availableVersion ??- report.state.currentVersion;- yield* Effect.logInfo("Desktop app update prepared for install.", {- targetVersion,- });- yield* Ref.set(inFlight, false);- return { targetVersion, method: "desktop-app" as const, desktopUpdateToken: requestId };- }- if (report.outcome === "up-to-date") {- return yield* failWith(- `The T3 Code desktop app on this machine is already up to date on ${report.state.currentVersion}.`,- );- }+ const report = terminal.value;+ if (report.outcome === "ready-to-install") {+ yield* emitStage("installing");+ const targetVersion =+ report.state.downloadedVersion ??+ report.state.availableVersion ??+ report.state.currentVersion;+ yield* Effect.logInfo("Desktop app update prepared for install.", {+ targetVersion,+ });+ yield* Ref.set(inFlight, false);+ return { targetVersion, method: "desktop-app" as const, desktopUpdateToken: requestId };+ }+ if (report.outcome === "up-to-date") {return yield* failWith(- report.reason ?? report.state.message ?? "The desktop app update failed.",+ `The T3 Code desktop app on this machine is already up to date on ${report.state.currentVersion}.`,);- });+ }+ return yield* failWith(+ report.reason ?? report.state.message ?? "The desktop app update failed.",+ );+ });const run: DesktopAppUpdate["Service"]["run"] = Effect.fn("desktopUpdate.desktopAppUpdate.run")(function* (reportProgress) {diff --git a/apps/server/src/device/DeviceActions.ts b/apps/server/src/device/DeviceActions.tsindex fec54eade8e..5d2ddca0f74 100644--- a/apps/server/src/device/DeviceActions.ts+++ b/apps/server/src/device/DeviceActions.ts@@ -206,20 +206,23 @@ const simctl = (run: Runner, udid: string, args: ReadonlyArray<string>, operatioEffect.flatMap(ok(operation)),);-const axSettings = (ready: DeviceHostReady, udid: string, args: ReadonlyArray<string>) =>- Effect.gen(function* () {- const helper = ready.helpers.serveSimAxSettings;- if (!helper) {- return yield* new DeviceActionUnavailableError({- operation: "accessibility",- platform: "ios",- reason: "helper_missing",- });- }- return yield* ready- .run("xcrun", ["simctl", "spawn", udid, helper, ...args])- .pipe(Effect.flatMap(ok("accessibility")));- });+const axSettings = Effect.fn("DeviceActions.axSettings")(function* (+ ready: DeviceHostReady,+ udid: string,+ args: ReadonlyArray<string>,+) {+ const helper = ready.helpers.serveSimAxSettings;+ if (!helper) {+ return yield* new DeviceActionUnavailableError({+ operation: "accessibility",+ platform: "ios",+ reason: "helper_missing",+ });+ }+ return yield* ready+ .run("xcrun", ["simctl", "spawn", udid, helper, ...args])+ .pipe(Effect.flatMap(ok("accessibility")));+});const runIos = Effect.fn("DeviceActions.runIos")(function* (ready: DeviceHostReady,@@ -318,31 +321,30 @@ const runIos = Effect.fn("DeviceActions.runIos")(function* (}});-const serveSimPermissions = (+const serveSimPermissions = Effect.fn("DeviceActions.serveSimPermissions")(function* (ready: DeviceHostReady,udid: string,input: Extract<DeviceActionInput, { type: "setPermission" }>,-) =>- Effect.gen(function* () {- const cli = ready.helpers.serveSimCli;- if (!cli)- return yield* new DeviceActionUnavailableError({- operation: "permission",- platform: "ios",- reason: "helper_missing",- });- yield* ready- .run(ready.nodePath, [- cli,- "permissions",- input.decision,- input.permission,- input.appId,- "-d",- udid,- ])- .pipe(Effect.flatMap(ok("permission")));- });+) {+ const cli = ready.helpers.serveSimCli;+ if (!cli)+ return yield* new DeviceActionUnavailableError({+ operation: "permission",+ platform: "ios",+ reason: "helper_missing",+ });+ yield* ready+ .run(ready.nodePath, [+ cli,+ "permissions",+ input.decision,+ input.permission,+ input.appId,+ "-d",+ udid,+ ])+ .pipe(Effect.flatMap(ok("permission")));+});const adb = (run: Runner, serial: string, args: ReadonlyArray<string>, operation: string) =>run("adb", ["-s", serial, ...args]).pipe(Effect.flatMap(ok(operation)));diff --git a/apps/server/src/device/DeviceHubProxy.ts b/apps/server/src/device/DeviceHubProxy.tsindex 3d4dc0eaafa..7c58e6eab07 100644--- a/apps/server/src/device/DeviceHubProxy.ts+++ b/apps/server/src/device/DeviceHubProxy.ts@@ -99,8 +99,9 @@ const proxyWebSocket = Effect.fn("DeviceHubProxy.proxyWebSocket")(function* (return HttpServerResponse.empty();});-const pumpFrames = (source: Socket.Socket, sink: Socket.Writer) =>- Effect.gen(function* () {+const pumpFrames =+ /* Frame pumping runs continuously; a span per frame stream adds no diagnostic value. */+ Effect.fnUntraced(function* (source: Socket.Socket, sink: Socket.Writer) {const { pull } = yield* source.reader;while (true) {yield* sink.writeAll(yield* pull);diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.tsindex 4dbaa49b28e..9f58dab8fbc 100644--- a/apps/server/src/device/DeviceService.ts+++ b/apps/server/src/device/DeviceService.ts@@ -236,15 +236,16 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*return PubSub.publish(statePubSub, next).pipe(Effect.as({ state: next }));}).pipe(Effect.map(({ state }) => state));- const resolveHost = (hostId: DeviceHostId | undefined) =>- Effect.gen(function* () {- const id = hostId ?? LOCAL_DEVICE_HOST_ID;- const host = hosts.get(id);- if (!host) {- return yield* new DeviceHostUnavailableError({ hostId: id, reason: "Unknown host." });- }- return host;- });+ const resolveHost = Effect.fn("DeviceService.resolveHost")(function* (+ hostId: DeviceHostId | undefined,+ ) {+ const id = hostId ?? LOCAL_DEVICE_HOST_ID;+ const host = hosts.get(id);+ if (!host) {+ return yield* new DeviceHostUnavailableError({ hostId: id, reason: "Unknown host." });+ }+ return host;+ });const setHostStatus = (hostId: DeviceHostId,@@ -991,33 +992,32 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`,reason: "Agent CLI installation is unavailable in this device service.",}),),- agentTarget: (input) =>- Effect.gen(function* () {- const host = yield* resolveHost(input.hostId);- const ready = yield* agentReadinessIfSupported(input.hostId);- if (!ready)- return yield* new DeviceHostUnavailableError({- hostId: input.hostId,- reason:- "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",- });- const configPath = yield* lifecycleLock.withPermit(- Effect.gen(function* () {- if (hosts.get(host.id) !== host)- return yield* new DeviceHostUnavailableError({- hostId: host.id,- reason: "Host configuration changed. Retry the operation.",- });- return yield* configureAgent(input.hostId, ready);- }),- );- const session = yield* agentDeviceSession(- input.threadId,- input.hostId,- input.deviceId,- ).pipe(Effect.provideService(Crypto.Crypto, crypto));- return ["--config", configPath, "--session", session];- }),+ agentTarget: Effect.fn("DeviceService.agentTarget")(function* (input) {+ const host = yield* resolveHost(input.hostId);+ const ready = yield* agentReadinessIfSupported(input.hostId);+ if (!ready)+ return yield* new DeviceHostUnavailableError({+ hostId: input.hostId,+ reason:+ "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",+ });+ const configPath = yield* lifecycleLock.withPermit(+ Effect.gen(function* () {+ if (hosts.get(host.id) !== host)+ return yield* new DeviceHostUnavailableError({+ hostId: host.id,+ reason: "Host configuration changed. Retry the operation.",+ });+ return yield* configureAgent(input.hostId, ready);+ }),+ );+ const session = yield* agentDeviceSession(+ input.threadId,+ input.hostId,+ input.deviceId,+ ).pipe(Effect.provideService(Crypto.Crypto, crypto));+ return ["--config", configPath, "--session", session];+ }),state: SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state)),subscribe: PubSub.subscribe(statePubSub),configure,@@ -1072,23 +1072,23 @@ export const make = Effect.gen(function* () {agentDeviceConfigPath(config.stateDir, hostId, path).pipe(Effect.provideService(Crypto.Crypto, crypto),);- const configureAgent = (hostId: DeviceHostId, ready: DeviceHost.DeviceHostAgentReady) =>- Effect.gen(function* () {+ const configureAgent = Effect.fn("DeviceService.configureAgent")(+ function* (hostId: DeviceHostId, ready: DeviceHost.DeviceHostAgentReady) {const file = yield* configPath(hostId);yield* writeAgentDeviceConfig(file, ready.agentDevice);return file;- }).pipe(- Effect.provideService(FileSystem.FileSystem, fs),- Effect.provideService(Path.Path, path),- Effect.mapError(- (cause) =>- new DeviceOperationError({- operation: "configure agent",- reason: "settings_failed",- cause,- }),- ),- );+ },+ Effect.provideService(FileSystem.FileSystem, fs),+ Effect.provideService(Path.Path, path),+ Effect.mapError(+ (cause) =>+ new DeviceOperationError({+ operation: "configure agent",+ reason: "settings_failed",+ cause,+ }),+ ),+ );const probeContext =yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.probe>>>();const localTargetContext =@@ -1132,78 +1132,79 @@ export const make = Effect.gen(function* () {const hostContext =yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.make>>>();const configured = new Map<string, { config: SshDeviceHostConfig; scope: Scope.Closeable }>();- const reconcile = (configuredHosts: ReadonlyArray<SshDeviceHostConfig>) =>- Effect.gen(function* () {- const next = yield* remoteSshDeviceHosts(configuredHosts).pipe(- Effect.provide(localTargetContext),- );- const removed = yield* service.withLifecycleLock(- Effect.gen(function* () {- const removed: Array<{ id: string; scope: Scope.Closeable }> = [];- for (const [id, previous] of configured) {- if (- next.some(- (host) =>- host.id === id &&- host.label === previous.config.label &&- host.target === previous.config.target &&- host.port === previous.config.port &&- host.identityFile === previous.config.identityFile,- )+ const reconcile = Effect.fn("DeviceService.reconcile")(function* (+ configuredHosts: ReadonlyArray<SshDeviceHostConfig>,+ ) {+ const next = yield* remoteSshDeviceHosts(configuredHosts).pipe(+ Effect.provide(localTargetContext),+ );+ const removed = yield* service.withLifecycleLock(+ Effect.gen(function* () {+ const removed: Array<{ id: string; scope: Scope.Closeable }> = [];+ for (const [id, previous] of configured) {+ if (+ next.some(+ (host) =>+ host.id === id &&+ host.label === previous.config.label &&+ host.target === previous.config.target &&+ host.port === previous.config.port &&+ host.identityFile === previous.config.identityFile,)- continue;- hosts.delete(id);- configured.delete(id);- removed.push({ id, scope: previous.scope });- }- if (removed.length > 0) yield* service.refreshHosts;- return removed;- }),- );- // Stop old writers before deleting config files or publishing replacements, without blocking healthy hosts.- yield* Effect.forEach(- removed,- ({ id, scope }) =>- Effect.gen(function* () {- yield* Scope.close(scope, Exit.void);- yield* fs.remove(yield* configPath(id), { force: true }).pipe(Effect.ignore);- }),- { concurrency: 4, discard: true },- );- yield* service.withLifecycleLock(+ )+ continue;+ hosts.delete(id);+ configured.delete(id);+ removed.push({ id, scope: previous.scope });+ }+ if (removed.length > 0) yield* service.refreshHosts;+ return removed;+ }),+ );+ // Stop old writers before deleting config files or publishing replacements, without blocking healthy hosts.+ yield* Effect.forEach(+ removed,+ ({ id, scope }) =>Effect.gen(function* () {- let added = false;- for (const host of next) {- if (configured.has(host.id)) continue;- added = true;- const hostScope = yield* Scope.fork(scope);- const instance = yield* SshDeviceHost.make(- host,- (ready) =>- configureAgent(host.id, ready).pipe(- Effect.asVoid,- Effect.mapError(- (error) =>- new DeviceHost.DeviceHostError({- hostId: host.id,- step: "configuring agent access",- cause: error,- }),- ),- ),- (status, detail) =>- service- .setHostStatus(host.id, { status, ...(detail ? { detail } : {}) })- .pipe(Effect.asVoid),- ).pipe(Effect.provideService(Scope.Scope, hostScope), Effect.provide(hostContext));- hosts.set(host.id, instance);- configured.set(host.id, { config: host, scope: hostScope });- }- // Refresh again after removed scopes closed so a late status write from an old host cannot linger.- if (added || removed.length > 0) yield* service.refreshHosts;+ yield* Scope.close(scope, Exit.void);+ yield* fs.remove(yield* configPath(id), { force: true }).pipe(Effect.ignore);}),- );- });+ { concurrency: 4, discard: true },+ );+ yield* service.withLifecycleLock(+ Effect.gen(function* () {+ let added = false;+ for (const host of next) {+ if (configured.has(host.id)) continue;+ added = true;+ const hostScope = yield* Scope.fork(scope);+ const instance = yield* SshDeviceHost.make(+ host,+ (ready) =>+ configureAgent(host.id, ready).pipe(+ Effect.asVoid,+ Effect.mapError(+ (error) =>+ new DeviceHost.DeviceHostError({+ hostId: host.id,+ step: "configuring agent access",+ cause: error,+ }),+ ),+ ),+ (status, detail) =>+ service+ .setHostStatus(host.id, { status, ...(detail ? { detail } : {}) })+ .pipe(Effect.asVoid),+ ).pipe(Effect.provideService(Scope.Scope, hostScope), Effect.provide(hostContext));+ hosts.set(host.id, instance);+ configured.set(host.id, { config: host, scope: hostScope });+ }+ // Refresh again after removed scopes closed so a late status write from an old host cannot linger.+ if (added || removed.length > 0) yield* service.refreshHosts;+ }),+ );+ });const changes = yield* settings.subscribeChanges;yield* reconcile((yield* settings.getSettings).deviceHosts);yield* changes.pipe(diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.tsindex 7a972b6a677..639c5cfe41a 100644--- a/apps/server/src/device/LocalDeviceHost.ts+++ b/apps/server/src/device/LocalDeviceHost.ts@@ -493,32 +493,34 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {Effect.ignoreCause,);- const superviseHub = (hub: HubProcess, hubTool: DeviceToolPaths): Effect.Effect<void> =>- Effect.gen(function* () {- yield* Effect.result(hub.child.exitCode);- const running = yield* Ref.get(runningRef);- if (running?.hub.child.pid !== hub.child.pid) return;- const uptime = (yield* Clock.currentTimeMillis) - hub.startedAtMillis;- const delay = yield* Ref.modify(restartDelayRef, (current) => {- if (uptime >= HUB_RESTART_STABLE_UPTIME_MS) return [0, 0];- const next = current === 0 ? 1_000 : Math.min(current * 2, HUB_RESTART_MAX_DELAY_MS);- return [current, next];- });- yield* Effect.logWarning("Device hub exited; restarting", {- pid: Number(hub.child.pid),- delayMs: delay,- });- yield* Effect.sleep(Duration.millis(delay));- yield* startLock.withPermits(1)(- Effect.gen(function* () {- const current = yield* Ref.get(runningRef);- if (current?.hub.child.pid !== hub.child.pid) return;- const replacement = yield* spawnHub(hubTool, hub.nodePath);- yield* Ref.set(runningRef, { ...current, hub: replacement });- yield* Effect.forkDetach(superviseHub(replacement, hubTool));- }),- );- }).pipe(+ // Waits for the hub's lifetime and re-forks on restart; a span would nest across restarts.+ const superviseHub: (hub: HubProcess, hubTool: DeviceToolPaths) => Effect.Effect<void> =+ Effect.fnUntraced(+ function* (hub: HubProcess, hubTool: DeviceToolPaths) {+ yield* Effect.result(hub.child.exitCode);+ const running = yield* Ref.get(runningRef);+ if (running?.hub.child.pid !== hub.child.pid) return;+ const uptime = (yield* Clock.currentTimeMillis) - hub.startedAtMillis;+ const delay = yield* Ref.modify(restartDelayRef, (current) => {+ if (uptime >= HUB_RESTART_STABLE_UPTIME_MS) return [0, 0];+ const next = current === 0 ? 1_000 : Math.min(current * 2, HUB_RESTART_MAX_DELAY_MS);+ return [current, next];+ });+ yield* Effect.logWarning("Device hub exited; restarting", {+ pid: Number(hub.child.pid),+ delayMs: delay,+ });+ yield* Effect.sleep(Duration.millis(delay));+ yield* startLock.withPermits(1)(+ Effect.gen(function* () {+ const current = yield* Ref.get(runningRef);+ if (current?.hub.child.pid !== hub.child.pid) return;+ const replacement = yield* spawnHub(hubTool, hub.nodePath);+ yield* Ref.set(runningRef, { ...current, hub: replacement });+ yield* Effect.forkDetach(superviseHub(replacement, hubTool));+ }),+ );+ },Effect.catchCause((cause) => Effect.logWarning("Device hub supervisor failed", { cause })),);diff --git a/apps/server/src/diagnostics/TraceDiagnostics.ts b/apps/server/src/diagnostics/TraceDiagnostics.tsindex 823148a29a4..5d2e3317186 100644--- a/apps/server/src/diagnostics/TraceDiagnostics.ts+++ b/apps/server/src/diagnostics/TraceDiagnostics.ts@@ -469,11 +469,9 @@ export const make = Effect.gen(function* () {export const layer = Layer.effect(TraceDiagnostics, make);-export function readTraceDiagnostics(+export const readTraceDiagnostics = Effect.fn("TraceDiagnostics.readTraceDiagnostics")(function* (options: TraceDiagnosticsOptions,-): Effect.Effect<ServerTraceDiagnosticsResult, never, TraceDiagnostics> {- return Effect.gen(function* () {- const diagnostics = yield* TraceDiagnostics;- return yield* diagnostics.read(options);- });-}+): Effect.fn.Return<ServerTraceDiagnosticsResult, never, TraceDiagnostics> {+ const diagnostics = yield* TraceDiagnostics;+ return yield* diagnostics.read(options);+});diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.tsindex ef4a1a23b79..7de85c26d02 100644--- a/apps/server/src/git/GitManager.ts+++ b/apps/server/src/git/GitManager.ts@@ -755,8 +755,8 @@ export const make = Effect.gen(function* () {return yield* gitCore.createWorktree(input, { worktreesDirectory, ...options, submodules });});- const readRepositoryInstructions = (cwd: string, fileName: string) =>- Effect.gen(function* () {+ const readRepositoryInstructions = Effect.fn("GitManager.readRepositoryInstructions")(+ function* (cwd: string, fileName: string) {const root = yield* fileSystem.realPath(cwd);const instructionPath = yield* fileSystem.realPath(path.join(root, fileName));const relative = path.relative(root, instructionPath);@@ -768,7 +768,9 @@ export const make = Effect.gen(function* () {return "";}return (yield* fileSystem.readFileString(instructionPath)).trim();- }).pipe(Effect.orElseSucceed(() => ""));+ },+ Effect.orElseSucceed(() => ""),+ );const readRecentCommitSubjects = (cwd: string) =>gitCore@@ -787,51 +789,53 @@ export const make = Effect.gen(function* () {Effect.orElseSucceed(() => []),);- const resolveStylePolicy = (cwd: string, settings: SourceControlTextGenerationSettings) =>- Effect.gen(function* () {- switch (settings.style.mode) {- case "conventional_commits":- return conventionalCommitsTextGenerationPolicy;- case "custom":- return customTextGenerationPolicy(- settings.style.customInstructions- ? {- commitInstructions: settings.style.customInstructions,- changeRequestInstructions: settings.style.customInstructions,- }- : {},+ const resolveStylePolicy = Effect.fn("GitManager.resolveStylePolicy")(function* (+ cwd: string,+ settings: SourceControlTextGenerationSettings,+ ) {+ switch (settings.style.mode) {+ case "conventional_commits":+ return conventionalCommitsTextGenerationPolicy;+ case "custom":+ return customTextGenerationPolicy(+ settings.style.customInstructions+ ? {+ commitInstructions: settings.style.customInstructions,+ changeRequestInstructions: settings.style.customInstructions,+ }+ : {},+ );+ case "repo_conventions": {+ const subjects = yield* readRecentCommitSubjects(cwd);+ const agentInstructions = yield* readRepositoryInstructions(cwd, "AGENTS.md");+ const isClaudeWriter =+ settings.modelSelection.instanceId === "claudeAgent" ||+ (yield* providerRegistry.getProviders).some(+ (provider) =>+ provider.instanceId === settings.modelSelection.instanceId &&+ provider.driver === "claudeAgent",);- case "repo_conventions": {- const subjects = yield* readRecentCommitSubjects(cwd);- const agentInstructions = yield* readRepositoryInstructions(cwd, "AGENTS.md");- const isClaudeWriter =- settings.modelSelection.instanceId === "claudeAgent" ||- (yield* providerRegistry.getProviders).some(- (provider) =>- provider.instanceId === settings.modelSelection.instanceId &&- provider.driver === "claudeAgent",- );- const claudeInstructions = isClaudeWriter- ? yield* readRepositoryInstructions(cwd, "CLAUDE.md")- : "";- const examples = [- ...(subjects.length > 0- ? [["Recent commit subjects from this repository:", ...subjects].join("\n")]- : []),- ...(agentInstructions ? [`Local AGENTS.md:\n${agentInstructions}`] : []),- ...(claudeInstructions ? [`Local CLAUDE.md:\n${claudeInstructions}`] : []),- ].join("\n\n");- if (!examples) {- return repositoryConventionsTextGenerationPolicy;- }- return {- ...repositoryConventionsTextGenerationPolicy,- commitInstructions: `${repositoryConventionsTextGenerationPolicy.commitInstructions}\n\n${examples}`,- changeRequestInstructions: `${repositoryConventionsTextGenerationPolicy.changeRequestInstructions}\n\n${examples}`,- };+ const claudeInstructions = isClaudeWriter+ ? yield* readRepositoryInstructions(cwd, "CLAUDE.md")+ : "";+ const examples = [+ ...(subjects.length > 0+ ? [["Recent commit subjects from this repository:", ...subjects].join("\n")]+ : []),+ ...(agentInstructions ? [`Local AGENTS.md:\n${agentInstructions}`] : []),+ ...(claudeInstructions ? [`Local CLAUDE.md:\n${claudeInstructions}`] : []),+ ].join("\n\n");+ if (!examples) {+ return repositoryConventionsTextGenerationPolicy;}+ return {+ ...repositoryConventionsTextGenerationPolicy,+ commitInstructions: `${repositoryConventionsTextGenerationPolicy.commitInstructions}\n\n${examples}`,+ changeRequestInstructions: `${repositoryConventionsTextGenerationPolicy.changeRequestInstructions}\n\n${examples}`,+ };}- });+ }+ });const randomUUIDv4 = (cwd: string) =>crypto.randomUUIDv4().pipe(Effect.mapError(@@ -2370,39 +2374,38 @@ export const make = Effect.gen(function* () {string,{ readonly readAtMs: number; readonly value: string | null }>();- const rememberPrLookupGitState = <E>(+ const rememberPrLookupGitState = Effect.fn("GitManager.rememberPrLookupGitState")(function* <E>(cwd: string,key: string,fresh: boolean,read: Effect.Effect<string | null, E>,- ) =>- Effect.gen(function* () {- const entryKey = `${cwd}\u0000${key}`;- const readAtMs = yield* Clock.currentTimeMillis;- const remembered = prLookupGitStateByKey.get(entryKey);- if (- !fresh &&- remembered !== undefined &&- readAtMs - remembered.readAtMs < Duration.toMillis(PR_LOOKUP_GIT_STATE_TTL)- ) {- return remembered.value;- }- // invalidateStatus bumps the epoch. A read that started before a T3 git- // action, or before a newer read finished, must not replace their state.- const epoch = prLookupEpoch(cwd);- const value = yield* read;- const latest = prLookupGitStateByKey.get(entryKey);- if (prLookupEpoch(cwd) !== epoch || (latest !== undefined && latest.readAtMs > readAtMs)) {- return value;- }- prLookupGitStateByKey.delete(entryKey);- if (prLookupGitStateByKey.size >= PR_LOOKUP_CACHE_CAPACITY) {- const oldestKey = prLookupGitStateByKey.keys().next().value;- if (oldestKey !== undefined) prLookupGitStateByKey.delete(oldestKey);- }- prLookupGitStateByKey.set(entryKey, { readAtMs, value });+ ) {+ const entryKey = `${cwd}\u0000${key}`;+ const readAtMs = yield* Clock.currentTimeMillis;+ const remembered = prLookupGitStateByKey.get(entryKey);+ if (+ !fresh &&+ remembered !== undefined &&+ readAtMs - remembered.readAtMs < Duration.toMillis(PR_LOOKUP_GIT_STATE_TTL)+ ) {+ return remembered.value;+ }+ // invalidateStatus bumps the epoch. A read that started before a T3 git+ // action, or before a newer read finished, must not replace their state.+ const epoch = prLookupEpoch(cwd);+ const value = yield* read;+ const latest = prLookupGitStateByKey.get(entryKey);+ if (prLookupEpoch(cwd) !== epoch || (latest !== undefined && latest.readAtMs > readAtMs)) {return value;- });+ }+ prLookupGitStateByKey.delete(entryKey);+ if (prLookupGitStateByKey.size >= PR_LOOKUP_CACHE_CAPACITY) {+ const oldestKey = prLookupGitStateByKey.keys().next().value;+ if (oldestKey !== undefined) prLookupGitStateByKey.delete(oldestKey);+ }+ prLookupGitStateByKey.set(entryKey, { readAtMs, value });+ return value;+ });const forgetPrLookupGitState = (cwd: string) =>normalizeStatusCacheKey(cwd).pipe(Effect.map((cacheCwd) => {diff --git a/apps/server/src/git/detachStackFrame.ts b/apps/server/src/git/detachStackFrame.tsindex a653eeedafd..7dc1982529b 100644--- a/apps/server/src/git/detachStackFrame.ts+++ b/apps/server/src/git/detachStackFrame.ts@@ -12,9 +12,11 @@ const snapshotStack = (/*** Wrap a `Cache.get` so its lookup fiber inherits a materialized stack. The lazy* caller frame would otherwise retain the caller's request snapshot for the TTL.+ * Stay untraced so this helper does not introduce another lazy frame to retain.*/-export const detachStackFrame = <A, E, R>(effect: Effect.Effect<A, E, R>) =>- Effect.gen(function* () {- const frame = snapshotStack(yield* References.CurrentStackFrame);- return yield* Effect.provideService(effect, References.CurrentStackFrame, frame);- });+export const detachStackFrame = Effect.fnUntraced(function* <A, E, R>(+ effect: Effect.Effect<A, E, R>,+) {+ const frame = snapshotStack(yield* References.CurrentStackFrame);+ return yield* Effect.provideService(effect, References.CurrentStackFrame, frame);+});diff --git a/apps/server/src/git/linkCreatedPullRequest.ts b/apps/server/src/git/linkCreatedPullRequest.tsindex 18c17ef6f12..2b687d0832b 100644--- a/apps/server/src/git/linkCreatedPullRequest.ts+++ b/apps/server/src/git/linkCreatedPullRequest.ts@@ -48,38 +48,45 @@ export function createdPullRequestKey(* Never fails: the git action already succeeded and its result is on its way to the client, so* a link that cannot be made is logged and dropped.*/-export const linkCreatedPullRequest = <E>(input: {+export const linkCreatedPullRequest: <E>(input: {readonly threadId: ThreadId;readonly result: Pick<GitRunStackedActionResult, "pr">;readonly commandId: Effect.Effect<CommandId, E>;-}): Effect.Effect<void, never, Orchestrator.OrchestratorV2 | ProjectService.ProjectService> =>- Effect.gen(function* () {- const engine = yield* Orchestrator.OrchestratorV2;- const projects = yield* ProjectService.ProjectService;- const thread = yield* engine- .getThreadShell(input.threadId)- .pipe(Effect.map(Option.fromNullishOr));- if (Option.isNone(thread)) return;- const project = Option.getOrUndefined(yield* projects.getShell(thread.value.projectId));- const key = createdPullRequestKey(input.result, project);- if (key === null) return;- const commandId = yield* input.commandId;- yield* engine- .dispatch({- type: "thread.pull-request.link",- commandId,- threadId: input.threadId,- ...key,- source: "created",- })- .pipe(Effect.asVoid);- }).pipe(- Effect.withSpan("linkCreatedPullRequest"),- Effect.catchCause((cause) =>- Cause.hasInterruptsOnly(cause)- ? Effect.failCause(cause as Cause.Cause<never>)- : Effect.logWarning("failed to link created pull request to thread", {- threadId: input.threadId,- }),- ),+}) => Effect.Effect<void, never, Orchestrator.OrchestratorV2 | ProjectService.ProjectService> =+ Effect.fn("linkCreatedPullRequest")(+ function* <E>(input: {+ readonly threadId: ThreadId;+ readonly result: Pick<GitRunStackedActionResult, "pr">;+ readonly commandId: Effect.Effect<CommandId, E>;+ }) {+ const engine = yield* Orchestrator.OrchestratorV2;+ const projects = yield* ProjectService.ProjectService;+ const thread = yield* engine+ .getThreadShell(input.threadId)+ .pipe(Effect.map(Option.fromNullishOr));+ if (Option.isNone(thread)) return;+ const project = Option.getOrUndefined(yield* projects.getShell(thread.value.projectId));+ const key = createdPullRequestKey(input.result, project);+ if (key === null) return;+ const commandId = yield* input.commandId;+ yield* engine+ .dispatch({+ type: "thread.pull-request.link",+ commandId,+ threadId: input.threadId,+ ...key,+ source: "created",+ })+ .pipe(Effect.asVoid);+ },+ (effect, input) =>+ effect.pipe(+ Effect.catchCause((cause) =>+ Cause.hasInterruptsOnly(cause)+ ? Effect.failCause(cause as Cause.Cause<never>)+ : Effect.logWarning("failed to link created pull request to thread", {+ threadId: input.threadId,+ }),+ ),+ ),);diff --git a/apps/server/src/htmlRender/HtmlRender.ts b/apps/server/src/htmlRender/HtmlRender.tsindex fdeebc6ae90..b6a5236a858 100644--- a/apps/server/src/htmlRender/HtmlRender.ts+++ b/apps/server/src/htmlRender/HtmlRender.ts@@ -341,8 +341,8 @@ const make = Effect.gen(function* () {),);- const measure = (html: string) =>- Effect.gen(function* () {+ const measure = Effect.fn("HtmlRender.measure")(+ function* (html: string) {const executable = yield* previewBrowser.installed;if (Option.isNone(executable)) return undefined;const heights = yield* launching(executable.value, (noSandbox) =>@@ -365,14 +365,13 @@ const make = Effect.gen(function* () {}),);return heights.toSorted(([left], [right]) => left - right);- }).pipe(- Effect.catch((cause) =>- Effect.logWarning("Could not measure an HTML render; publishing it without heights.", {- cause,- }).pipe(Effect.as(undefined)),- ),- Effect.withSpan("HtmlRender.measure"),- );+ },+ Effect.catch((cause) =>+ Effect.logWarning("Could not measure an HTML render; publishing it without heights.", {+ cause,+ }).pipe(Effect.as(undefined)),+ ),+ );// The bootstrap goes in first so its head scan never runs over inlined image data.const inline = (html: string) =>diff --git a/apps/server/src/htmlRender/headlessChrome.ts b/apps/server/src/htmlRender/headlessChrome.tsindex 7c476d392d3..4ad26a4aa68 100644--- a/apps/server/src/htmlRender/headlessChrome.ts+++ b/apps/server/src/htmlRender/headlessChrome.ts@@ -381,31 +381,30 @@ const launchBrowser = Effect.fnUntraced(function* (input: {Effect.forkScoped,);- const send = <A>(+ const send = Effect.fn("headlessChrome.send")(function* <A>(method: string,params: Record<string, unknown>,result: Schema.Decoder<A>,sessionId?: string,- ) =>- Effect.gen(function* () {- if (disconnected) return yield* disconnected;- const id = ++nextId;- const reply = yield* Deferred.make<unknown, BrowserFailure>();- pending.set(id, { method, reply });- const message = encodeCdpCommand({ id, method, params, ...(sessionId ? { sessionId } : {}) });- yield* Queue.offer(outgoing, new TextEncoder().encode(`${message}\0`));- return yield* Deferred.await(reply).pipe(- Effect.flatMap(Schema.decodeUnknownEffect(result)),- Effect.mapError((error) =>- error._tag === "HtmlRenderBrowserError"- ? error- : new HtmlRenderBrowserError({- reason: `${method} returned an unexpected result`,- cause: error,- }),- ),- );- });+ ) {+ if (disconnected) return yield* disconnected;+ const id = ++nextId;+ const reply = yield* Deferred.make<unknown, BrowserFailure>();+ pending.set(id, { method, reply });+ const message = encodeCdpCommand({ id, method, params, ...(sessionId ? { sessionId } : {}) });+ yield* Queue.offer(outgoing, new TextEncoder().encode(`${message}\0`));+ return yield* Deferred.await(reply).pipe(+ Effect.flatMap(Schema.decodeUnknownEffect(result)),+ Effect.mapError((error) =>+ error._tag === "HtmlRenderBrowserError"+ ? error+ : new HtmlRenderBrowserError({+ reason: `${method} returned an unexpected result`,+ cause: error,+ }),+ ),+ );+ });const openPage = Effect.fnUntraced(function* (width: number) {const { targetId } = yield* send(diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.tsindex 177da665223..0dea8553791 100644--- a/apps/server/src/keybindings.ts+++ b/apps/server/src/keybindings.ts@@ -66,24 +66,23 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(Effect.map((resolved) => resolved),),- encode: (resolved) =>- Effect.gen(function* () {- const key = encodeShortcut(resolved.shortcut);- if (!key) {- return yield* Effect.fail(- new SchemaIssue.InvalidValue({- message: "Resolved shortcut cannot be encoded to key string",- }),- );- }+ encode: Effect.fn("keybindings.encode")(function* (resolved) {+ const key = encodeShortcut(resolved.shortcut);+ if (!key) {+ return yield* Effect.fail(+ new SchemaIssue.InvalidValue({+ message: "Resolved shortcut cannot be encoded to key string",+ }),+ );+ }- const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined;- return {- key,- command: resolved.command,- when,- };- }),+ const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined;+ return {+ key,+ command: resolved.command,+ when,+ };+ }),}),),);diff --git a/apps/server/src/launcherWatch.ts b/apps/server/src/launcherWatch.tsindex 4e1c5a83212..d8870280247 100644--- a/apps/server/src/launcherWatch.ts+++ b/apps/server/src/launcherWatch.ts@@ -21,25 +21,24 @@ const startupParentPid = process.ppid;* lose, and Windows keeps the original parent id after the parent exits, so* neither is watched.*/-export const awaitLauncherLoss = (options?: {+export const awaitLauncherLoss = Effect.fn("launcherWatch.awaitLauncherLoss")(function* (options?: {readonly launcherPid?: number;readonly getParentPid?: () => number;readonly interval?: Duration.Input;-}): Effect.Effect<void> =>- Effect.gen(function* () {- const platform = yield* HostProcess.Platform;- const launcherPid = options?.launcherPid ?? startupParentPid;- const getParentPid = options?.getParentPid ?? (() => process.ppid);- const interval = options?.interval ?? DEFAULT_POLL_INTERVAL;- if (platform === "win32" || launcherPid <= 1) return yield* Effect.never;- const poll: Effect.Effect<void> = Effect.suspend(() => {- const parentPid = getParentPid();- return parentPid === launcherPid- ? Effect.flatMap(Effect.sleep(interval), () => poll)- : Effect.logWarning("desktop launcher is gone; shutting down the backend", {- launcherPid,- parentPid,- });- });- return yield* poll;+}): Effect.fn.Return<void> {+ const platform = yield* HostProcess.Platform;+ const launcherPid = options?.launcherPid ?? startupParentPid;+ const getParentPid = options?.getParentPid ?? (() => process.ppid);+ const interval = options?.interval ?? DEFAULT_POLL_INTERVAL;+ if (platform === "win32" || launcherPid <= 1) return yield* Effect.never;+ const poll: Effect.Effect<void> = Effect.suspend(() => {+ const parentPid = getParentPid();+ return parentPid === launcherPid+ ? Effect.flatMap(Effect.sleep(interval), () => poll)+ : Effect.logWarning("desktop launcher is gone; shutting down the backend", {+ launcherPid,+ parentPid,+ });});+ return yield* poll;+});diff --git a/apps/server/src/observability/Metrics.ts b/apps/server/src/observability/Metrics.tsindex 091ff5234d7..033157554d3 100644--- a/apps/server/src/observability/Metrics.ts+++ b/apps/server/src/observability/Metrics.ts@@ -101,12 +101,13 @@ export interface WithMetricsOptions {) => Readonly<Record<string, unknown>>;}-const recordMetrics = (- options: WithMetricsOptions,- startedAt: bigint,- exit: Exit.Exit<unknown, unknown>,-) =>- Effect.gen(function* () {+const recordMetrics =+ /* Instrumentation must not create its own span for every recorded operation. */+ Effect.fnUntraced(function* (+ options: WithMetricsOptions,+ startedAt: bigint,+ exit: Exit.Exit<unknown, unknown>,+ ) {const duration = Duration.nanos((yield* Clock.monotonicTimeNanos) - startedAt);const baseAttributes =typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {});diff --git a/apps/server/src/persistence/DatabaseMaintenance.ts b/apps/server/src/persistence/DatabaseMaintenance.tsindex 48d9b390b15..72af08b04c8 100644--- a/apps/server/src/persistence/DatabaseMaintenance.ts+++ b/apps/server/src/persistence/DatabaseMaintenance.ts@@ -126,20 +126,21 @@ const readStorage = Effect.gen(function* () {* refused while any other connection has the file open, even an idle one,* which is how a running server or desktop app is detected.*/-const lockExclusively = (databasePath: string) =>- Effect.gen(function* () {- const sql = yield* SqlClient.SqlClient;- yield* sql`PRAGMA busy_timeout = 0`;- yield* sql`PRAGMA locking_mode = EXCLUSIVE`;- yield* sql`BEGIN EXCLUSIVE`.pipe(- Effect.mapError((cause) =>- isSqlError(cause) && cause.reason._tag === "LockTimeoutError"- ? new DatabaseInUseError({ path: databasePath, cause })- : cause,- ),- );- yield* sql`COMMIT`;- });+const lockExclusively = Effect.fn("DatabaseMaintenance.lockExclusively")(function* (+ databasePath: string,+) {+ const sql = yield* SqlClient.SqlClient;+ yield* sql`PRAGMA busy_timeout = 0`;+ yield* sql`PRAGMA locking_mode = EXCLUSIVE`;+ yield* sql`BEGIN EXCLUSIVE`.pipe(+ Effect.mapError((cause) =>+ isSqlError(cause) && cause.reason._tag === "LockTimeoutError"+ ? new DatabaseInUseError({ path: databasePath, cause })+ : cause,+ ),+ );+ yield* sql`COMMIT`;+});const make = Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.tsindex be92a8957fa..32461ac69f7 100644--- a/apps/server/src/process/agentScope.ts+++ b/apps/server/src/process/agentScope.ts@@ -121,31 +121,32 @@ export const make = Effect.gen(function* () {// Old agents keep their scopes when the server is killed, and the restarted// server resumes their sessions. Stop them first, so two copies of one// session never work in the same worktree.- const stopLeftoverAgents = (systemctl: string) =>- Effect.gen(function* () {- const shown = yield* run(systemctl, [- "--user",- "show",- ownedSlice,- "--property=ActiveState,ControlGroup",- ]);- if (shown._tag === "None") return;- const values = parseKeyValues(shown.value.stdout);- if (values.get("ActiveState") !== "active") return;- const controlGroup = values.get("ControlGroup") ?? "";- const events = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";- if (parseCgroupCounter(events, "populated") === 0) return;- yield* Effect.logWarning("Stopping agents left by a previous server", { slice: ownedSlice });- const stopped = yield* runner- .run({ command: systemctl, args: ["--user", "stop", ownedSlice], timeout: "30 seconds" })- .pipe(Effect.option);- if (stopped._tag === "None" || stopped.value.code !== 0) {- yield* Effect.logWarning("Could not stop agents left by a previous server", {- slice: ownedSlice,- stderr: stopped._tag === "Some" ? stopped.value.stderr.trim() : undefined,- });- }- });+ const stopLeftoverAgents = Effect.fn("agentScope.stopLeftoverAgents")(function* (+ systemctl: string,+ ) {+ const shown = yield* run(systemctl, [+ "--user",+ "show",+ ownedSlice,+ "--property=ActiveState,ControlGroup",+ ]);+ if (shown._tag === "None") return;+ const values = parseKeyValues(shown.value.stdout);+ if (values.get("ActiveState") !== "active") return;+ const controlGroup = values.get("ControlGroup") ?? "";+ const events = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";+ if (parseCgroupCounter(events, "populated") === 0) return;+ yield* Effect.logWarning("Stopping agents left by a previous server", { slice: ownedSlice });+ const stopped = yield* runner+ .run({ command: systemctl, args: ["--user", "stop", ownedSlice], timeout: "30 seconds" })+ .pipe(Effect.option);+ if (stopped._tag === "None" || stopped.value.code !== 0) {+ yield* Effect.logWarning("Could not stop agents left by a previous server", {+ slice: ownedSlice,+ stderr: stopped._tag === "Some" ? stopped.value.stderr.trim() : undefined,+ });+ }+ });const systemd = yield* Effect.cached(Effect.gen(function* () {@@ -202,73 +203,76 @@ export const make = Effect.gen(function* () {const scopeByThread = new Map<string, { unit: string; oomKilled: boolean }>();- const readScope = (systemctl: string, unit: string) =>- Effect.gen(function* () {- const shown = yield* run(systemctl, [- "--user",- "show",- unit,- "--property=LoadState,ActiveState,Result,ControlGroup",- ]);- if (shown._tag === "None" || shown.value.code !== 0) return undefined;- const values = parseKeyValues(shown.value.stdout);- const controlGroup = values.get("ControlGroup") ?? "";- const memoryEvents = controlGroup ? yield* readCgroupFile(controlGroup, "memory.events") : "";- const cgroupEvents = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";- const populated = parseCgroupCounter(cgroupEvents, "populated");- return {- loadState: values.get("LoadState") ?? "",- activeState: values.get("ActiveState") ?? "",- result: values.get("Result") ?? "",- oomKills: parseCgroupCounter(memoryEvents, "oom_kill") ?? 0,- populated: populated === undefined ? undefined : populated === 1,- } satisfies ScopeState;- });+ const readScope = Effect.fn("agentScope.readScope")(function* (systemctl: string, unit: string) {+ const shown = yield* run(systemctl, [+ "--user",+ "show",+ unit,+ "--property=LoadState,ActiveState,Result,ControlGroup",+ ]);+ if (shown._tag === "None" || shown.value.code !== 0) return undefined;+ const values = parseKeyValues(shown.value.stdout);+ const controlGroup = values.get("ControlGroup") ?? "";+ const memoryEvents = controlGroup ? yield* readCgroupFile(controlGroup, "memory.events") : "";+ const cgroupEvents = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";+ const populated = parseCgroupCounter(cgroupEvents, "populated");+ return {+ loadState: values.get("LoadState") ?? "",+ activeState: values.get("ActiveState") ?? "",+ result: values.get("Result") ?? "",+ oomKills: parseCgroupCounter(memoryEvents, "oom_kill") ?? 0,+ populated: populated === undefined ? undefined : populated === 1,+ } satisfies ScopeState;+ });- const clearFailed = (systemctl: string, unit: string) =>- Effect.gen(function* () {- for (let attempt = 0; attempt < CLEAR_FAILED_ATTEMPTS; attempt++) {- const state = yield* readScope(systemctl, unit);- if (state === undefined) return;- if (state.activeState === "failed") {- yield* run(systemctl, ["--user", "reset-failed", unit]);- return;- }- if (state.activeState !== "deactivating") return;- yield* Effect.sleep(CLEAR_FAILED_INTERVAL);+ const clearFailed = Effect.fn("agentScope.clearFailed")(function* (+ systemctl: string,+ unit: string,+ ) {+ for (let attempt = 0; attempt < CLEAR_FAILED_ATTEMPTS; attempt++) {+ const state = yield* readScope(systemctl, unit);+ if (state === undefined) return;+ if (state.activeState === "failed") {+ yield* run(systemctl, ["--user", "reset-failed", unit]);+ return;}- });+ if (state.activeState !== "deactivating") return;+ yield* Effect.sleep(CLEAR_FAILED_INTERVAL);+ }+ });const forget = (systemctl: string, unit: string) =>clearFailed(systemctl, unit).pipe(Effect.forkIn(layerScope), Effect.asVoid);- const evictOldest = (systemctl: string) =>- Effect.gen(function* () {- const oldest = scopeByThread.entries().next();- if (oldest.done === true) return;- const [threadId, tracked] = oldest.value;- const state = yield* readScope(systemctl, tracked.unit);- if (scopeByThread.get(threadId) !== tracked) return;- scopeByThread.delete(threadId);- const status = state === undefined ? "running" : classifyScope(state);- if (status === "running" || status === "stopping") {- scopeByThread.set(threadId, tracked);- return;- }- yield* forget(systemctl, tracked.unit);- });+ const evictOldest = Effect.fn("agentScope.evictOldest")(function* (systemctl: string) {+ const oldest = scopeByThread.entries().next();+ if (oldest.done === true) return;+ const [threadId, tracked] = oldest.value;+ const state = yield* readScope(systemctl, tracked.unit);+ if (scopeByThread.get(threadId) !== tracked) return;+ scopeByThread.delete(threadId);+ const status = state === undefined ? "running" : classifyScope(state);+ if (status === "running" || status === "stopping") {+ scopeByThread.set(threadId, tracked);+ return;+ }+ yield* forget(systemctl, tracked.unit);+ });- const track = (systemctl: string, threadId: string, unit: string | undefined) =>- Effect.gen(function* () {- const previous = scopeByThread.get(threadId);- scopeByThread.delete(threadId);- if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false });- if (previous !== undefined) yield* forget(systemctl, previous.unit);- if (scopeByThread.size > MAX_TRACKED_THREADS) yield* evictOldest(systemctl);- });+ const track = Effect.fn("agentScope.track")(function* (+ systemctl: string,+ threadId: string,+ unit: string | undefined,+ ) {+ const previous = scopeByThread.get(threadId);+ scopeByThread.delete(threadId);+ if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false });+ if (previous !== undefined) yield* forget(systemctl, previous.unit);+ if (scopeByThread.size > MAX_TRACKED_THREADS) yield* evictOldest(systemctl);+ });- const oomKilled: AgentScopeShape["oomKilled"] = (threadId) =>- Effect.gen(function* () {+ const oomKilled: AgentScopeShape["oomKilled"] = Effect.fn("agentScope.oomKilled")(+ function* (threadId) {const tracked = scopeByThread.get(threadId);if (tracked === undefined) return false;if (tracked.oomKilled) return true;@@ -293,14 +297,14 @@ export const make = Effect.gen(function* () {return true;}return false;- });+ },+ );- const clear: AgentScopeShape["clear"] = (threadId) =>- Effect.gen(function* () {- if (!scopeByThread.has(threadId)) return;- const scope = yield* systemd;- if (scope !== undefined) yield* track(scope.systemctl, threadId, undefined);- });+ const clear: AgentScopeShape["clear"] = Effect.fn("agentScope.clear")(function* (threadId) {+ if (!scopeByThread.has(threadId)) return;+ const scope = yield* systemd;+ if (scope !== undefined) yield* track(scope.systemctl, threadId, undefined);+ });return {wrap: Effect.fn("AgentScope.wrap")(function* ({diff --git a/apps/server/src/project/ProjectCloneTracker.ts b/apps/server/src/project/ProjectCloneTracker.tsindex e68ddf78b3f..9d8896cea0f 100644--- a/apps/server/src/project/ProjectCloneTracker.ts+++ b/apps/server/src/project/ProjectCloneTracker.ts@@ -133,20 +133,21 @@ export const make = Effect.gen(function* () {return next;}).pipe(Effect.andThen(publish));- const scheduleRemoval = (projectId: ProjectId) =>- Effect.gen(function* () {- yield* clearRetention(projectId);- const fiber = yield* remove(projectId).pipe(- Effect.delay(DONE_RETENTION),- Effect.ensuring(- Effect.sync(() => {- if (retentionFibers.get(projectId) === fiber) retentionFibers.delete(projectId);- }),- ),- Effect.forkDetach,- );- retentionFibers.set(projectId, fiber);- });+ const scheduleRemoval = Effect.fn("ProjectCloneTracker.scheduleRemoval")(function* (+ projectId: ProjectId,+ ) {+ yield* clearRetention(projectId);+ const fiber = yield* remove(projectId).pipe(+ Effect.delay(DONE_RETENTION),+ Effect.ensuring(+ Effect.sync(() => {+ if (retentionFibers.get(projectId) === fiber) retentionFibers.delete(projectId);+ }),+ ),+ Effect.forkDetach,+ );+ retentionFibers.set(projectId, fiber);+ });const progress = (projectId: ProjectId,@@ -167,26 +168,25 @@ export const make = Effect.gen(function* () {},})).pipe(Effect.asVoid);- const finish = (+ const finish = Effect.fn("ProjectCloneTracker.finish")(function* (projectId: ProjectId,phase: "done" | "failed" | "cancelled",error: string | null,- ) =>- Effect.gen(function* () {- const endedAt = yield* nowIso;- yield* modify(projectId, (tracked) => ({- ...tracked,- fiber: null,- snapshot: {- ...tracked.snapshot,- phase,- endedAt,- percent: phase === "done" ? 100 : tracked.snapshot.percent,- error: error === null ? null : clampText(error, PROJECT_CLONE_ERROR_MAX_LENGTH),- },- }));- if (phase === "done") yield* scheduleRemoval(projectId);- });+ ) {+ const endedAt = yield* nowIso;+ yield* modify(projectId, (tracked) => ({+ ...tracked,+ fiber: null,+ snapshot: {+ ...tracked.snapshot,+ phase,+ endedAt,+ percent: phase === "done" ? 100 : tracked.snapshot.percent,+ error: error === null ? null : clampText(error, PROJECT_CLONE_ERROR_MAX_LENGTH),+ },+ }));+ if (phase === "done") yield* scheduleRemoval(projectId);+ });/*** Runs in its own fiber; the tracker records the outcome through `onExit`,@@ -217,20 +217,19 @@ export const make = Effect.gen(function* () {Effect.ignoreCause(),);- const launch = (projectId: ProjectId) =>- Effect.gen(function* () {- const current = yield* Ref.get(clones);- const tracked = current.get(projectId);- if (!tracked) return;- const fiber = yield* runClone(projectId, tracked).pipe(Effect.forkIn(cloneScope));- yield* Ref.update(clones, (map) => {- const existing = map.get(projectId);- if (!existing) return map;- const next = new Map(map);- next.set(projectId, { ...existing, fiber });- return next;- });+ const launch = Effect.fn("ProjectCloneTracker.launch")(function* (projectId: ProjectId) {+ const current = yield* Ref.get(clones);+ const tracked = current.get(projectId);+ if (!tracked) return;+ const fiber = yield* runClone(projectId, tracked).pipe(Effect.forkIn(cloneScope));+ yield* Ref.update(clones, (map) => {+ const existing = map.get(projectId);+ if (!existing) return map;+ const next = new Map(map);+ next.set(projectId, { ...existing, fiber });+ return next;});+ });const start: ProjectCloneTracker["Service"]["start"] = Effect.fn("ProjectCloneTracker.start")(function* (input, hooks) {@@ -307,8 +306,8 @@ export const make = Effect.gen(function* () {const get: ProjectCloneTracker["Service"]["get"] = (projectId) =>Ref.get(clones).pipe(Effect.map((current) => current.get(projectId)?.snapshot ?? null));- const cancel: ProjectCloneTracker["Service"]["cancel"] = (projectId) =>- Effect.gen(function* () {+ const cancel: ProjectCloneTracker["Service"]["cancel"] = Effect.fn("ProjectCloneTracker.cancel")(+ function* (projectId) {const current = yield* Ref.get(clones);const tracked = current.get(projectId);if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) return false;@@ -324,10 +323,11 @@ export const make = Effect.gen(function* () {}),);return true;- });+ },+ );- const retry: ProjectCloneTracker["Service"]["retry"] = (projectId) =>- Effect.gen(function* () {+ const retry: ProjectCloneTracker["Service"]["retry"] = Effect.fn("ProjectCloneTracker.retry")(+ function* (projectId) {const current = yield* Ref.get(clones);const tracked = current.get(projectId);if (@@ -353,23 +353,25 @@ export const make = Effect.gen(function* () {}));yield* launch(projectId);return true;- });+ },+ );- const discard: ProjectCloneTracker["Service"]["discard"] = (projectId) =>- Effect.gen(function* () {- const current = yield* Ref.get(clones);- const tracked = current.get(projectId);- if (!tracked) return;- if (tracked.fiber) yield* Fiber.interrupt(tracked.fiber);- // Git may have finished while the interrupt was landing; the project- // is going away either way, but a complete checkout is the user's.- const after = yield* get(projectId);- if (after?.phase !== "done") {- yield* repositories.discardClone(tracked.input.destinationPath).pipe(Effect.ignore);- }- yield* clearRetention(projectId);- yield* remove(projectId);- });+ const discard: ProjectCloneTracker["Service"]["discard"] = Effect.fn(+ "ProjectCloneTracker.discard",+ )(function* (projectId) {+ const current = yield* Ref.get(clones);+ const tracked = current.get(projectId);+ if (!tracked) return;+ if (tracked.fiber) yield* Fiber.interrupt(tracked.fiber);+ // Git may have finished while the interrupt was landing; the project+ // is going away either way, but a complete checkout is the user's.+ const after = yield* get(projectId);+ if (after?.phase !== "done") {+ yield* repositories.discardClone(tracked.input.destinationPath).pipe(Effect.ignore);+ }+ yield* clearRetention(projectId);+ yield* remove(projectId);+ });const stream: ProjectCloneTracker["Service"]["stream"] = Stream.callback<ReadonlyArray<ProjectCloneSnapshot>@@ -405,11 +407,15 @@ const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);* client can start a thread on an empty tree, and no attachment copies are made* for a command that is about to be refused.*/-export const rejectCommandsDuringClone = (- tracker: ProjectCloneTracker["Service"],- command: { readonly type: string; readonly projectId?: ProjectId; readonly bootstrap?: unknown },-): Effect.Effect<void, OrchestrationDispatchCommandError> =>- Effect.gen(function* () {+export const rejectCommandsDuringClone = Effect.fn("ProjectCloneTracker.rejectCommandsDuringClone")(+ function* (+ tracker: ProjectCloneTracker["Service"],+ command: {+ readonly type: string;+ readonly projectId?: ProjectId;+ readonly bootstrap?: unknown;+ },+ ): Effect.fn.Return<void, OrchestrationDispatchCommandError> {const projectId =command.type === "thread.create"? (command.projectId ?? null)@@ -425,7 +431,8 @@ export const rejectCommandsDuringClone = (? "The repository is still being cloned.": "The repository was not cloned. Retry the clone first.",});- });+ },+);function bootstrapProjectId(bootstrap: unknown): ProjectId | null {if (typeof bootstrap !== "object" || bootstrap === null) return null;diff --git a/apps/server/src/project/ProjectFaviconResolver.ts b/apps/server/src/project/ProjectFaviconResolver.tsindex 75dc4e661ef..aef40716ae8 100644--- a/apps/server/src/project/ProjectFaviconResolver.ts+++ b/apps/server/src/project/ProjectFaviconResolver.ts@@ -238,20 +238,19 @@ export const make = Effect.gen(function* () {// matters when the disk is slow. Fibers are joined in order, so a hit returns// without waiting for lower-ranked probes (the scope interrupts them), and a// failure surfaces only when no earlier probe found a file.- const firstInOrder = <A>(+ const firstInOrder = Effect.fn("ProjectFaviconResolver.firstInOrder")(function* <A>(items: ReadonlyArray<A>,probe: (item: A) => Effect.Effect<string | null, ProjectFaviconResolutionError>,- ) =>- Effect.gen(function* () {- const fibers = yield* Effect.forEach(items, (item) => Effect.forkScoped(probe(item)));- for (const fiber of fibers) {- const found = yield* Fiber.join(fiber);- if (found) {- return found;- }+ ) {+ const fibers = yield* Effect.forEach(items, (item) => Effect.forkScoped(probe(item)));+ for (const fiber of fibers) {+ const found = yield* Fiber.join(fiber);+ if (found) {+ return found;}- return null;- }).pipe(Effect.scoped);+ }+ return null;+ }, Effect.scoped);const resolvePathUncached = Effect.fn("ProjectFaviconResolver.resolvePathUncached")(function* (cwd: string,diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.tsindex 67977c5c7f2..6799be186d1 100644--- a/apps/server/src/project/ProjectSetupScriptRunner.ts+++ b/apps/server/src/project/ProjectSetupScriptRunner.ts@@ -191,16 +191,16 @@ export const make = Effect.gen(function* () {yield* HostProcess.Environment,);- const observeTerminalCompletion = (input: {- readonly threadId: string;- readonly terminalId: string;- readonly sentinel: string;- readonly sentinelPattern: RegExp;- /** The shell echoes typed input; lines ending with these are the wrapper, not output. */- readonly echoedWrapperLines: ReadonlyArray<string>;- readonly onOutputLine: ((line: string) => Effect.Effect<void>) | undefined;- }) =>- Effect.gen(function* () {+ const observeTerminalCompletion = Effect.fn("ProjectSetupScriptRunner.observeTerminalCompletion")(+ function* (input: {+ readonly threadId: string;+ readonly terminalId: string;+ readonly sentinel: string;+ readonly sentinelPattern: RegExp;+ /** The shell echoes typed input; lines ending with these are the wrapper, not output. */+ readonly echoedWrapperLines: ReadonlyArray<string>;+ readonly onOutputLine: ((line: string) => Effect.Effect<void>) | undefined;+ }) {const startedAtMs = yield* Clock.currentTimeMillis;const done = yield* Deferred.make<ProjectSetupScriptCompletion>();// The shell redraws its prompt just after the sentinel. Closing before@@ -278,7 +278,8 @@ export const make = Effect.gen(function* () {Effect.ensuring(Effect.sync(() => unsubscribe())),);return { completion, unsubscribe };- });+ },+ );const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn("ProjectSetupScriptRunner.runForThread",diff --git a/apps/server/src/project/WorktreeSetupTracker.ts b/apps/server/src/project/WorktreeSetupTracker.tsindex 43639afe451..0bdf7af4d2b 100644--- a/apps/server/src/project/WorktreeSetupTracker.ts+++ b/apps/server/src/project/WorktreeSetupTracker.ts@@ -147,8 +147,8 @@ export const make = Effect.gen(function* () {Effect.tap(() => Effect.sync(() => lastSequenceByThread.delete(threadId))),);- const begin: WorktreeSetupTracker["Service"]["begin"] = (input) =>- Effect.gen(function* () {+ const begin: WorktreeSetupTracker["Service"]["begin"] = Effect.fn("WorktreeSetupTracker.begin")(+ function* (input) {yield* clearRetention(input.threadId);const startedAt = yield* nowIso;const ordered = WORKTREE_SETUP_STAGE_ORDER.filter((id) => input.stages.includes(id));@@ -172,7 +172,8 @@ export const make = Effect.gen(function* () {return next;});yield* publish(input.threadId, snapshot);- });+ },+ );const update: WorktreeSetupTracker["Service"]["update"] = (threadId, mutate) =>modify(threadId, (tracked) => ({ ...tracked, snapshot: mutate(tracked.snapshot) })).pipe(@@ -235,44 +236,45 @@ export const make = Effect.gen(function* () {),}));- const finish: WorktreeSetupTracker["Service"]["finish"] = (threadId, phase, error) =>- Effect.gen(function* () {- const endedAt = yield* nowIso;- const snapshot = yield* modify(threadId, (tracked) => ({- fiber: null,- snapshot: {- ...tracked.snapshot,- phase,- endedAt,- error:- error === undefined || error === null- ? null- : clampText(error, WORKTREE_SETUP_ERROR_MAX_LENGTH),- stages: tracked.snapshot.stages.map((entry) =>- entry.status === "running"- ? {- ...entry,- status: phase === "done" ? "done" : phase === "cancelled" ? "skipped" : "failed",- endedAt,- }- : entry,- ),- },- }));- if (!snapshot) return null;- yield* clearRetention(threadId);- const fiber = yield* remove(threadId).pipe(- Effect.delay(FINISHED_RETENTION),- Effect.ensuring(- Effect.sync(() => {- if (retentionFibers.get(threadId) === fiber) retentionFibers.delete(threadId);- }),+ const finish: WorktreeSetupTracker["Service"]["finish"] = Effect.fn(+ "WorktreeSetupTracker.finish",+ )(function* (threadId, phase, error) {+ const endedAt = yield* nowIso;+ const snapshot = yield* modify(threadId, (tracked) => ({+ fiber: null,+ snapshot: {+ ...tracked.snapshot,+ phase,+ endedAt,+ error:+ error === undefined || error === null+ ? null+ : clampText(error, WORKTREE_SETUP_ERROR_MAX_LENGTH),+ stages: tracked.snapshot.stages.map((entry) =>+ entry.status === "running"+ ? {+ ...entry,+ status: phase === "done" ? "done" : phase === "cancelled" ? "skipped" : "failed",+ endedAt,+ }+ : entry,),- Effect.forkDetach,- );- retentionFibers.set(threadId, fiber);- return snapshot;- });+ },+ }));+ if (!snapshot) return null;+ yield* clearRetention(threadId);+ const fiber = yield* remove(threadId).pipe(+ Effect.delay(FINISHED_RETENTION),+ Effect.ensuring(+ Effect.sync(() => {+ if (retentionFibers.get(threadId) === fiber) retentionFibers.delete(threadId);+ }),+ ),+ Effect.forkDetach,+ );+ retentionFibers.set(threadId, fiber);+ return snapshot;+ });const markUncancellable: WorktreeSetupTracker["Service"]["markUncancellable"] = (threadId) =>Ref.update(setups, (current) => {@@ -283,16 +285,17 @@ export const make = Effect.gen(function* () {return next;});- const cancel: WorktreeSetupTracker["Service"]["cancel"] = (threadId) =>- Effect.gen(function* () {- const current = yield* Ref.get(setups);- const tracked = current.get(threadId);- if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) {- return false;- }- yield* Fiber.interrupt(tracked.fiber);- return true;- });+ const cancel: WorktreeSetupTracker["Service"]["cancel"] = Effect.fn(+ "WorktreeSetupTracker.cancel",+ )(function* (threadId) {+ const current = yield* Ref.get(setups);+ const tracked = current.get(threadId);+ if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) {+ return false;+ }+ yield* Fiber.interrupt(tracked.fiber);+ return true;+ });const get: WorktreeSetupTracker["Service"]["get"] = (threadId) =>Ref.get(setups).pipe(Effect.map((current) => current.get(threadId)?.snapshot ?? null));diff --git a/apps/server/src/pullRequest/PullRequestReadCache.ts b/apps/server/src/pullRequest/PullRequestReadCache.tsindex 16860c78ee9..6f2c107f7f9 100644--- a/apps/server/src/pullRequest/PullRequestReadCache.ts+++ b/apps/server/src/pullRequest/PullRequestReadCache.ts@@ -153,8 +153,8 @@ export const make = Effect.gen(function* () {lock.withPermits(1),);}),- invalidate: (scope) =>- Effect.gen(function* () {+ invalidate: Effect.fn("PullRequestReadCache.invalidate")(+ function* (scope) {const now = clock.currentTimeMillisUnsafe();const current = yield* Cache.get(revisions, undefined);const next = Object.fromEntries(@@ -164,14 +164,14 @@ export const make = Effect.gen(function* () {const encoded = yield* Schema.encodeEffect(revisionCodec)(next);yield* backing.set("revisions", encoded);yield* Cache.set(revisions, undefined, next);- }).pipe(- Effect.catch(() => {- enabled = false;- return Effect.logWarning("PR cache disabled after clearing failed");- }),- Effect.uninterruptible,- lock.withPermits(CONCURRENT_READS),- ),+ },+ Effect.catch(() => {+ enabled = false;+ return Effect.logWarning("PR cache disabled after clearing failed");+ }),+ Effect.uninterruptible,+ lock.withPermits(CONCURRENT_READS),+ ),});});diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.tsindex ff77f99ebe4..8f82dd8af1e 100644--- a/apps/server/src/pullRequest/PullRequestService.ts+++ b/apps/server/src/pullRequest/PullRequestService.ts@@ -1075,294 +1075,291 @@ export const make = Effect.gen(function* () {const searchVisibilityKey = (host: string, repository: string) =>`${host}\n${repository.trim().toLowerCase()}`;- const listUncached: PullRequestService["Service"]["list"] = (input) =>- Effect.gen(function* () {- const involvement = input.involvement ?? "all";- const continuation = yield* decodeCursors(input.cursors);- const {- supported: projects,- unimplemented,- viewerRoots,- } = yield* listWorkspaceProjects(input);- const projectCounts = new Map<string, number>();- for (const { host } of projects) {- projectCounts.set(host, (projectCounts.get(host) ?? 0) + 1);- }+ const listUncached: PullRequestService["Service"]["list"] = Effect.fn(+ "PullRequestService.listUncached",+ )(function* (input) {+ const involvement = input.involvement ?? "all";+ const continuation = yield* decodeCursors(input.cursors);+ const { supported: projects, unimplemented, viewerRoots } = yield* listWorkspaceProjects(input);+ const projectCounts = new Map<string, number>();+ for (const { host } of projects) {+ projectCounts.set(host, (projectCounts.get(host) ?? 0) + 1);+ }- const viewerResults = yield* resolveViewers(projects, viewerRoots);- const viewers: Record<string, string> = {};- for (const result of viewerResults) {- if (result.viewer !== null) viewers[result.host] = result.viewer;+ const viewerResults = yield* resolveViewers(projects, viewerRoots);+ const viewers: Record<string, string> = {};+ for (const result of viewerResults) {+ if (result.viewer !== null) viewers[result.host] = result.viewer;+ }++ const providers: ReadonlyArray<PullRequestProviderSummary> = [+ ...viewerResults.map((result) => {+ const capabilities = projects.find((project) => project.host === result.host)?.api+ .capabilities;+ return {+ host: result.host,+ kind: result.kind,+ searchesOnHost: capabilities?.search ?? false,+ actions: capabilities?.actions ?? [],+ projectCount: projectCounts.get(result.host) ?? 1,+ configured: result.viewer !== null,+ detail: result.error === null ? null : providerDetail(result.error),+ };+ }),+ ...[...unimplemented].map(([host, { kind, projectCount }]) => ({+ host,+ kind,+ searchesOnHost: false,+ actions: [],+ projectCount,+ configured: false,+ detail: "This host cannot be browsed here yet.",+ })),+ ];++ const selected =+ continuation === null+ ? projects+ : projects.filter(({ cursorKey }) => continuation.has(cursorKey));+ const readable = selected.filter(({ host }) => viewers[host] !== undefined);+ const unreadable = selected+ .filter(({ host }) => viewers[host] === undefined)+ .map(({ project, repository }) => ({+ projectId: project.id,+ projectTitle: project.title,+ message: `${repository} could not be read.`,+ }));+ if (readable.length === 0) {+ const errors = viewerResults.flatMap((result) =>+ result.error === null || !selected.some(({ host }) => host === result.host)+ ? []+ : [result.error],+ );+ const blocking = errors.find(isProviderUnusable) ?? errors[0];+ if (blocking) {+ return yield* toPullRequestError("list")(blocking);}- const providers: ReadonlyArray<PullRequestProviderSummary> = [- ...viewerResults.map((result) => {- const capabilities = projects.find((project) => project.host === result.host)?.api- .capabilities;- return {- host: result.host,- kind: result.kind,- searchesOnHost: capabilities?.search ?? false,- actions: capabilities?.actions ?? [],- projectCount: projectCounts.get(result.host) ?? 1,- configured: result.viewer !== null,- detail: result.error === null ? null : providerDetail(result.error),- };- }),- ...[...unimplemented].map(([host, { kind, projectCount }]) => ({- host,- kind,- searchesOnHost: false,- actions: [],- projectCount,- configured: false,- detail: "This host cannot be browsed here yet.",- })),- ];+ return {+ viewers: viewers as PullRequestListResult["viewers"],+ providers,+ entries: [],+ errors: [],+ truncated: false,+ nextCursors: {},+ };+ }- const selected =- continuation === null- ? projects- : projects.filter(({ cursorKey }) => continuation.has(cursorKey));- const readable = selected.filter(({ host }) => viewers[host] !== undefined);- const unreadable = selected- .filter(({ host }) => viewers[host] === undefined)- .map(({ project, repository }) => ({- projectId: project.id,- projectTitle: project.title,- message: `${repository} could not be read.`,- }));- if (readable.length === 0) {- const errors = viewerResults.flatMap((result) =>- result.error === null || !selected.some(({ host }) => host === result.host)- ? []- : [result.error],- );- const blocking = errors.find(isProviderUnusable) ?? errors[0];- if (blocking) {- return yield* toPullRequestError("list")(blocking);- }+ const limit = input.limit ?? DEFAULT_REPOSITORY_LIST_LIMIT;+ const cursorOf = (project: SupportedProject): ListCursor | undefined =>+ continuation?.get(project.cursorKey);- return {- viewers: viewers as PullRequestListResult["viewers"],- providers,- entries: [],- errors: [],- truncated: false,- nextCursors: {},- };+ const readRepository = (project: SupportedProject): Effect.Effect<RepositoryBatch> => {+ {+ const viewer = viewers[project.host]!;+ const key = project.cursorKey;+ const cursor = cursorOf(project);+ return project.api+ .listChangeRequests({+ cwd: project.project.workspaceRoot,+ repository: project.repository,+ host: project.host,+ state: input.state,+ involvement,+ viewer,+ limit,+ query: input.query,+ filters: input.filters,+ ...(cursor === undefined+ ? {}+ : {+ cursor: {+ updatedBefore: cursor.updatedBefore,+ delivered: cursor.delivered,+ seenAt: cursor.seenAt,+ },+ }),+ })+ .pipe(+ observeRead,+ Effect.map(({ value: page, observedAt }): RepositoryBatch => {+ // The boundary instant was asked for inclusively, so the rows already sent at it+ // come back with the slice. Dropping them here rather than asking for strictly+ // older is what keeps their neighbours at the same instant from being skipped.+ const items =+ cursor === undefined+ ? page.items+ : page.items.filter(+ (item) =>+ item.updatedAt !== cursor.updatedBefore ||+ !cursor.seenAt.includes(item.number),+ );+ return {+ key,+ entries: items+ .filter((item) => matchesRowFilters(item, input.filters, viewer))+ .map((item) => toEntry({ project, item, viewer, observedAt })),+ errors: [],+ truncated: page.truncated,+ nextCursor:+ page.continues && page.truncated+ ? nextListCursor(cursor, page.items, items, page.cursorAdvance)+ : null,+ };+ }),+ Effect.orElseSucceed((): RepositoryBatch => ({+ key,+ entries: [],+ errors: [+ {+ projectId: project.project.id,+ projectTitle: project.project.title,+ message: `${project.repository} could not be read.`,+ },+ ],+ truncated: false,+ nextCursor: null,+ })),+ );}+ };- const limit = input.limit ?? DEFAULT_REPOSITORY_LIST_LIMIT;- const cursorOf = (project: SupportedProject): ListCursor | undefined =>- continuation?.get(project.cursorKey);-- const readRepository = (project: SupportedProject): Effect.Effect<RepositoryBatch> => {- {- const viewer = viewers[project.host]!;- const key = project.cursorKey;- const cursor = cursorOf(project);- return project.api- .listChangeRequests({- cwd: project.project.workspaceRoot,- repository: project.repository,- host: project.host,- state: input.state,- involvement,- viewer,- limit,- query: input.query,- filters: input.filters,- ...(cursor === undefined- ? {}- : {- cursor: {- updatedBefore: cursor.updatedBefore,- delivered: cursor.delivered,- seenAt: cursor.seenAt,- },- }),- })- .pipe(- observeRead,- Effect.map(({ value: page, observedAt }): RepositoryBatch => {- // The boundary instant was asked for inclusively, so the rows already sent at it- // come back with the slice. Dropping them here rather than asking for strictly- // older is what keeps their neighbours at the same instant from being skipped.+ const readTogether = (+ chunk: ReadonlyArray<SupportedProject>,+ ): Effect.Effect<ReadonlyArray<RepositoryBatch>> => {+ const first = chunk[0]!;+ const readAcross = first.api.listChangeRequestsAcross;+ const separately = () =>+ Effect.forEach(chunk, readRepository, { concurrency: REPOSITORY_CONCURRENCY });+ if (readAcross === undefined) return separately();+ const viewer = viewers[first.host]!;+ const cursor = cursorOf(first);+ return readAcross({+ cwd: first.project.workspaceRoot,+ host: first.host,+ repositories: chunk.map((project) => project.repository),+ state: input.state,+ involvement,+ viewer,+ limit,+ query: input.query,+ filters: input.filters,+ ...(cursor === undefined+ ? {}+ : { cursor: { updatedBefore: cursor.updatedBefore, delivered: cursor.delivered } }),+ }).pipe(+ observeRead,+ Effect.flatMap(({ value: page, observedAt }) =>+ Effect.flatMap(Clock.currentTimeMillis, (now) => {+ const rows = new Map<string, Array<ProviderChangeRequest>>();+ for (const [key, visibleAt] of searchVisibleAt) {+ if (now - visibleAt > Duration.toMillis(SEARCH_VISIBILITY_TTL)) {+ searchVisibleAt.delete(key);+ }+ }+ for (const item of page.items) {+ const key = item.repository.trim().toLowerCase();+ const held = rows.get(key);+ if (held === undefined) rows.set(key, [item]);+ else held.push(item);+ searchVisibleAt.set(searchVisibilityKey(first.host, item.repository), now);+ }+ const boundary = page.items.reduce<string | null>(+ (oldest, item) =>+ oldest === null || item.updatedAt < oldest ? item.updatedAt : oldest,+ null,+ );+ return Effect.forEach(+ chunk,+ (project): Effect.Effect<RepositoryBatch> => {+ const fetched = rows.get(project.repository.trim().toLowerCase()) ?? [];+ // GitHub does not index every repository for search — a renamed one answers for+ // its old name with silence rather than with an error — so a repository the+ // search said nothing at all about is read on its own, once, before it is+ // believed. Only on its first slice: after that it has a boundary to carry on+ // from, and silence past one means the rows are older rather than absent.+ const lastVisible = searchVisibleAt.get(+ searchVisibilityKey(project.host, project.repository),+ );+ const searchIsKnownVisible =+ !page.truncated &&+ lastVisible !== undefined &&+ now - lastVisible <= Duration.toMillis(SEARCH_VISIBILITY_TTL);+ if (+ fetched.length === 0 &&+ cursorOf(project) === undefined &&+ !searchIsKnownVisible+ ) {+ return readRepository(project);+ }+ const cursorHere = cursorOf(project);const items =- cursor === undefined- ? page.items- : page.items.filter(+ cursorHere === undefined+ ? fetched+ : fetched.filter((item) =>- item.updatedAt !== cursor.updatedBefore ||- !cursor.seenAt.includes(item.number),+ item.updatedAt !== cursorHere.updatedBefore ||+ !cursorHere.seenAt.includes(item.number),);- return {- key,+ return Effect.succeed({+ key: project.cursorKey,entries: items.filter((item) => matchesRowFilters(item, input.filters, viewer)).map((item) => toEntry({ project, item, viewer, observedAt })),errors: [],truncated: page.truncated,nextCursor:- page.continues && page.truncated- ? nextListCursor(cursor, page.items, items, page.cursorAdvance)+ page.truncated && boundary !== null+ ? listCursorAt(cursorHere, boundary, fetched, items.length): null,- };- }),- Effect.orElseSucceed((): RepositoryBatch => ({- key,- entries: [],- errors: [- {- projectId: project.project.id,- projectTitle: project.project.title,- message: `${project.repository} could not be read.`,- },- ],- truncated: false,- nextCursor: null,- })),+ });+ },+ { concurrency: REPOSITORY_CONCURRENCY },);- }- };-- const readTogether = (- chunk: ReadonlyArray<SupportedProject>,- ): Effect.Effect<ReadonlyArray<RepositoryBatch>> => {- const first = chunk[0]!;- const readAcross = first.api.listChangeRequestsAcross;- const separately = () =>- Effect.forEach(chunk, readRepository, { concurrency: REPOSITORY_CONCURRENCY });- if (readAcross === undefined) return separately();- const viewer = viewers[first.host]!;- const cursor = cursorOf(first);- return readAcross({- cwd: first.project.workspaceRoot,- host: first.host,- repositories: chunk.map((project) => project.repository),- state: input.state,- involvement,- viewer,- limit,- query: input.query,- filters: input.filters,- ...(cursor === undefined- ? {}- : { cursor: { updatedBefore: cursor.updatedBefore, delivered: cursor.delivered } }),- }).pipe(- observeRead,- Effect.flatMap(({ value: page, observedAt }) =>- Effect.flatMap(Clock.currentTimeMillis, (now) => {- const rows = new Map<string, Array<ProviderChangeRequest>>();- for (const [key, visibleAt] of searchVisibleAt) {- if (now - visibleAt > Duration.toMillis(SEARCH_VISIBILITY_TTL)) {- searchVisibleAt.delete(key);- }- }- for (const item of page.items) {- const key = item.repository.trim().toLowerCase();- const held = rows.get(key);- if (held === undefined) rows.set(key, [item]);- else held.push(item);- searchVisibleAt.set(searchVisibilityKey(first.host, item.repository), now);- }- const boundary = page.items.reduce<string | null>(- (oldest, item) =>- oldest === null || item.updatedAt < oldest ? item.updatedAt : oldest,- null,- );- return Effect.forEach(- chunk,- (project): Effect.Effect<RepositoryBatch> => {- const fetched = rows.get(project.repository.trim().toLowerCase()) ?? [];- // GitHub does not index every repository for search — a renamed one answers for- // its old name with silence rather than with an error — so a repository the- // search said nothing at all about is read on its own, once, before it is- // believed. Only on its first slice: after that it has a boundary to carry on- // from, and silence past one means the rows are older rather than absent.- const lastVisible = searchVisibleAt.get(- searchVisibilityKey(project.host, project.repository),- );- const searchIsKnownVisible =- !page.truncated &&- lastVisible !== undefined &&- now - lastVisible <= Duration.toMillis(SEARCH_VISIBILITY_TTL);- if (- fetched.length === 0 &&- cursorOf(project) === undefined &&- !searchIsKnownVisible- ) {- return readRepository(project);- }- const cursorHere = cursorOf(project);- const items =- cursorHere === undefined- ? fetched- : fetched.filter(- (item) =>- item.updatedAt !== cursorHere.updatedBefore ||- !cursorHere.seenAt.includes(item.number),- );- return Effect.succeed({- key: project.cursorKey,- entries: items- .filter((item) => matchesRowFilters(item, input.filters, viewer))- .map((item) => toEntry({ project, item, viewer, observedAt })),- errors: [],- truncated: page.truncated,- nextCursor:- page.truncated && boundary !== null- ? listCursorAt(cursorHere, boundary, fetched, items.length)- : null,- });- },- { concurrency: REPOSITORY_CONCURRENCY },- );- }),- ),- Effect.catch(separately),- );- };+ }),+ ),+ Effect.catch(separately),+ );+ };- const together = new Map<string, Array<SupportedProject>>();- const separate: Array<SupportedProject> = [];- for (const project of readable) {- if (project.api.listChangeRequestsAcross === undefined) {- separate.push(project);- continue;- }- const key = `${project.host}\n${cursorOf(project)?.updatedBefore ?? ""}`;- const group = together.get(key);- if (group === undefined) together.set(key, [project]);- else group.push(project);+ const together = new Map<string, Array<SupportedProject>>();+ const separate: Array<SupportedProject> = [];+ for (const project of readable) {+ if (project.api.listChangeRequestsAcross === undefined) {+ separate.push(project);+ continue;}- const reads: Array<Effect.Effect<ReadonlyArray<RepositoryBatch>>> = separate.map((project) =>- readRepository(project).pipe(Effect.map((batch) => [batch])),- );- for (const group of together.values()) {- for (let start = 0; start < group.length; start += REPOSITORY_SEARCH_CHUNK) {- reads.push(readTogether(group.slice(start, start + REPOSITORY_SEARCH_CHUNK)));- }+ const key = `${project.host}\n${cursorOf(project)?.updatedBefore ?? ""}`;+ const group = together.get(key);+ if (group === undefined) together.set(key, [project]);+ else group.push(project);+ }+ const reads: Array<Effect.Effect<ReadonlyArray<RepositoryBatch>>> = separate.map((project) =>+ readRepository(project).pipe(Effect.map((batch) => [batch])),+ );+ for (const group of together.values()) {+ for (let start = 0; start < group.length; start += REPOSITORY_SEARCH_CHUNK) {+ reads.push(readTogether(group.slice(start, start + REPOSITORY_SEARCH_CHUNK)));}- const batches = (yield* Effect.all(reads, { concurrency: REPOSITORY_CONCURRENCY })).flat();+ }+ const batches = (yield* Effect.all(reads, { concurrency: REPOSITORY_CONCURRENCY })).flat();- const nextCursors: Record<string, string> = {};- for (const batch of batches) {- if (batch.nextCursor !== null) nextCursors[batch.key] = batch.nextCursor;- }+ const nextCursors: Record<string, string> = {};+ for (const batch of batches) {+ if (batch.nextCursor !== null) nextCursors[batch.key] = batch.nextCursor;+ }- return {- viewers: viewers as PullRequestListResult["viewers"],- providers,- entries: batches- .flatMap((batch) => batch.entries)- .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)),- errors: [...unreadable, ...batches.flatMap((batch) => batch.errors)],- truncated: batches.some((batch) => batch.truncated),- nextCursors,- };- });+ return {+ viewers: viewers as PullRequestListResult["viewers"],+ providers,+ entries: batches+ .flatMap((batch) => batch.entries)+ .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)),+ errors: [...unreadable, ...batches.flatMap((batch) => batch.errors)],+ truncated: batches.some((batch) => batch.truncated),+ nextCursors,+ };+ });const viewerOf = (project: SupportedProject): Effect.Effect<string | null> =>routingCredential.pipe(@@ -1396,36 +1393,34 @@ export const make = Effect.gen(function* () {return { ...identity, host, provider: "github" as const };});- const withRoutingCredential: PullRequestService["Service"]["withRoutingCredential"] = (- input,- operation,- ) =>- Effect.gen(function* () {- if (input.expectedAccountId === undefined) return yield* operation;- const rejected = () =>- new PullRequestOperationError({- operation: "routeIdentity",- detail: "The GitHub account could not be verified before starting the operation.",- });- const project = yield* requireProject(input).pipe(Effect.mapError(rejected));- const api = registry.get(project.api.kind);- if (- api?.withVerifiedCredential === undefined ||- input.host?.toLowerCase() !== project.host.toLowerCase()- ) {- return yield* rejected();- }- const result = yield* api- .withVerifiedCredential(- { cwd: project.project.workspaceRoot, host: project.host },- (identity) =>- identity.accountId === input.expectedAccountId- ? operation.pipe(Effect.provideService(routingCredential, identity), Effect.result)- : Effect.fail(rejected()),- )- .pipe(Effect.catchTags({ PullRequestProviderError: () => Effect.fail(rejected()) }));- return yield* Effect.fromResult(result);- });+ const withRoutingCredential: PullRequestService["Service"]["withRoutingCredential"] = Effect.fn(+ "PullRequestService.withRoutingCredential",+ )(function* (input, operation) {+ if (input.expectedAccountId === undefined) return yield* operation;+ const rejected = () =>+ new PullRequestOperationError({+ operation: "routeIdentity",+ detail: "The GitHub account could not be verified before starting the operation.",+ });+ const project = yield* requireProject(input).pipe(Effect.mapError(rejected));+ const api = registry.get(project.api.kind);+ if (+ api?.withVerifiedCredential === undefined ||+ input.host?.toLowerCase() !== project.host.toLowerCase()+ ) {+ return yield* rejected();+ }+ const result = yield* api+ .withVerifiedCredential(+ { cwd: project.project.workspaceRoot, host: project.host },+ (identity) =>+ identity.accountId === input.expectedAccountId+ ? operation.pipe(Effect.provideService(routingCredential, identity), Effect.result)+ : Effect.fail(rejected()),+ )+ .pipe(Effect.catchTags({ PullRequestProviderError: () => Effect.fail(rejected()) }));+ return yield* Effect.fromResult(result);+ });const routing = Effect.fn("PullRequestService.routing")(function* (input: PullRequestRef) {const project = yield* requireProject(input);@@ -2351,78 +2346,78 @@ export const make = Effect.gen(function* () {* The line counts for rows already on the page, which the listing left out because on GitHub* they cost more than everything else on the row put together.*/- const listStatsUncached: PullRequestService["Service"]["listStats"] = (input) =>- Effect.gen(function* () {- if (input.refs.length === 0) return { stats: [] };- const { supported } = yield* listWorkspaceProjects({});- const byProject = new Map(supported.map((project) => [project.project.id, project]));- const wanted = new Map<- string,- { readonly project: SupportedProject; readonly number: number }- >();- for (const ref of input.refs) {- const project = byProject.get(ref.projectId);- if (- project === undefined ||- project.api.listChangeRequestStats === undefined ||- project.repository.toLowerCase() !== ref.repository.trim().toLowerCase()- ) {- continue;- }- wanted.set(`${project.project.id} ${ref.number}`, { project, number: ref.number });- }- const byHost = new Map<string, Array<{ project: SupportedProject; number: number }>>();- for (const entry of wanted.values()) {- const held = byHost.get(entry.project.host);- if (held === undefined) byHost.set(entry.project.host, [entry]);- else held.push(entry);+ const listStatsUncached: PullRequestService["Service"]["listStats"] = Effect.fn(+ "PullRequestService.listStatsUncached",+ )(function* (input) {+ if (input.refs.length === 0) return { stats: [] };+ const { supported } = yield* listWorkspaceProjects({});+ const byProject = new Map(supported.map((project) => [project.project.id, project]));+ const wanted = new Map<+ string,+ { readonly project: SupportedProject; readonly number: number }+ >();+ for (const ref of input.refs) {+ const project = byProject.get(ref.projectId);+ if (+ project === undefined ||+ project.api.listChangeRequestStats === undefined ||+ project.repository.toLowerCase() !== ref.repository.trim().toLowerCase()+ ) {+ continue;}- const stats = yield* Effect.forEach(- [...byHost.values()],- (entries) => {- const first = entries[0]!;- const readStats = first.project.api.listChangeRequestStats;- if (readStats === undefined)- return Effect.succeed<ReadonlyArray<PullRequestDiffStat>>([]);- const projectsByRepository = new Map(- entries.map((entry) => [- `${entry.project.repository.toLowerCase()} ${entry.number}`,- entry.project,- ]),- );- return readStats({- cwd: first.project.project.workspaceRoot,- host: first.project.host,- changeRequests: entries.map((entry) => ({- repository: entry.project.repository,- number: entry.number,- })),- }).pipe(- Effect.map((read) =>- read.flatMap((stat): ReadonlyArray<PullRequestDiffStat> => {- const project = projectsByRepository.get(- `${stat.repository.toLowerCase()} ${stat.number}`,- );- return project === undefined- ? []- : [- {- projectId: project.project.id,- repository: project.repository,- number: stat.number,- additions: stat.additions,- deletions: stat.deletions,- },- ];- }),- ),- Effect.orElseSucceed((): ReadonlyArray<PullRequestDiffStat> => []),- );- },- { concurrency: REPOSITORY_CONCURRENCY },- );- return { stats: stats.flat() };- });+ wanted.set(`${project.project.id} ${ref.number}`, { project, number: ref.number });+ }+ const byHost = new Map<string, Array<{ project: SupportedProject; number: number }>>();+ for (const entry of wanted.values()) {+ const held = byHost.get(entry.project.host);+ if (held === undefined) byHost.set(entry.project.host, [entry]);+ else held.push(entry);+ }+ const stats = yield* Effect.forEach(+ [...byHost.values()],+ (entries) => {+ const first = entries[0]!;+ const readStats = first.project.api.listChangeRequestStats;+ if (readStats === undefined) return Effect.succeed<ReadonlyArray<PullRequestDiffStat>>([]);+ const projectsByRepository = new Map(+ entries.map((entry) => [+ `${entry.project.repository.toLowerCase()} ${entry.number}`,+ entry.project,+ ]),+ );+ return readStats({+ cwd: first.project.project.workspaceRoot,+ host: first.project.host,+ changeRequests: entries.map((entry) => ({+ repository: entry.project.repository,+ number: entry.number,+ })),+ }).pipe(+ Effect.map((read) =>+ read.flatMap((stat): ReadonlyArray<PullRequestDiffStat> => {+ const project = projectsByRepository.get(+ `${stat.repository.toLowerCase()} ${stat.number}`,+ );+ return project === undefined+ ? []+ : [+ {+ projectId: project.project.id,+ repository: project.repository,+ number: stat.number,+ additions: stat.additions,+ deletions: stat.deletions,+ },+ ];+ }),+ ),+ Effect.orElseSucceed((): ReadonlyArray<PullRequestDiffStat> => []),+ );+ },+ { concurrency: REPOSITORY_CONCURRENCY },+ );+ return { stats: stats.flat() };+ });const revalidate = <A, E>(read: Effect.Effect<A, E>) =>Effect.context<never>().pipe(@@ -3270,30 +3265,29 @@ export const make = Effect.gen(function* () {const fileKey = (oldPath: string, newPath: string) => JSON.stringify([oldPath, newPath]);const sliceKey = (input: PullRequestDiffInput) =>JSON.stringify([refCacheKey(input), input.cursor ?? null, input.commit ?? null]);- const read = (input: PullRequestDiffInput) =>- Effect.gen(function* () {- const key = sliceKey(input);- const now = yield* Clock.currentTimeMillis;- const cached = held.get(key);- if (cached !== undefined && now - cached.at <= ttlMs) return cached;- const slice = yield* diff(input);- const entry = {- at: now,- files: new Set(- parseDiffFilePaths(slice.patch).map((file) =>- fileKey(file.oldPath ?? file.newPath ?? "", file.newPath ?? file.oldPath ?? ""),- ),+ const read = Effect.fn("PullRequestService.read")(function* (input: PullRequestDiffInput) {+ const key = sliceKey(input);+ const now = yield* Clock.currentTimeMillis;+ const cached = held.get(key);+ if (cached !== undefined && now - cached.at <= ttlMs) return cached;+ const slice = yield* diff(input);+ const entry = {+ at: now,+ files: new Set(+ parseDiffFilePaths(slice.patch).map((file) =>+ fileKey(file.oldPath ?? file.newPath ?? "", file.newPath ?? file.oldPath ?? ""),),- nextCursor: slice.nextCursor,- };- held.delete(key);- if (held.size >= DIFF_CACHE_CAPACITY) {- const oldest = held.keys().next().value;- if (oldest !== undefined) held.delete(oldest);- }- held.set(key, entry);- return entry;- });+ ),+ nextCursor: slice.nextCursor,+ };+ held.delete(key);+ if (held.size >= DIFF_CACHE_CAPACITY) {+ const oldest = held.keys().next().value;+ if (oldest !== undefined) held.delete(oldest);+ }+ held.set(key, entry);+ return entry;+ });return { read: credentialCached(read), fileKey };})();/**diff --git a/apps/server/src/pullRequest/pullRequestViewedFiles.ts b/apps/server/src/pullRequest/pullRequestViewedFiles.tsindex 59402ee1d9c..f172a1fe567 100644--- a/apps/server/src/pullRequest/pullRequestViewedFiles.ts+++ b/apps/server/src/pullRequest/pullRequestViewedFiles.ts@@ -196,11 +196,11 @@ export const make = (dependencies: Dependencies) => {cause,});- const environmentFilesViewed = (- project: SupportedProject,- ref: PullRequestRef,- ): Effect.Effect<PullRequestFilesViewedResult, PullRequestError> =>- Effect.gen(function* () {+ const environmentFilesViewed = Effect.fn("pullRequestViewedFiles.environmentFilesViewed")(+ function* (+ project: SupportedProject,+ ref: PullRequestRef,+ ): Effect.fn.Return<PullRequestFilesViewedResult, PullRequestError> {const viewer = yield* requiredViewerOf(project, "filesViewed");const held = yield* filesViewedStore.list(filesViewedScope(project, ref.number, viewer))@@ -234,7 +234,8 @@ export const make = (dependencies: Dependencies) => {}),truncated: held.truncated,};- });+ },+ );/*** A tick's host round trip is slower than an untick's, so unordered presses could finish@@ -271,11 +272,11 @@ export const make = (dependencies: Dependencies) => {);});- const environmentSetFilesViewed = (- project: SupportedProject,- input: PullRequestSetFilesViewedInput,- ): Effect.Effect<void, PullRequestError> =>- Effect.gen(function* () {+ const environmentSetFilesViewed = Effect.fn("pullRequestViewedFiles.environmentSetFilesViewed")(+ function* (+ project: SupportedProject,+ input: PullRequestSetFilesViewedInput,+ ): Effect.fn.Return<void, PullRequestError> {const viewer = yield* requiredViewerOf(project, "setFilesViewed");const cleared = input.files.filter((file) => file.viewed).map((file) => file.path);const revisions =@@ -304,7 +305,8 @@ export const make = (dependencies: Dependencies) => {viewedAt,}).pipe(Effect.mapError(toFilesViewedStoreError("setFilesViewed")));- });+ },+ );const filesViewed = (input: PullRequestRef) =>requireProject(input).pipe(diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.tsindex 285f2cfe1f9..8811bd3d6d8 100644--- a/apps/server/src/relay/AgentAwarenessRelay.test.ts+++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts@@ -15,6 +15,7 @@ import {TurnItemId,} from "@t3tools/contracts";import { RelayAgentActivityState } from "@t3tools/contracts/relay";+import { RelayClientTracer } from "@t3tools/shared/relayTracing";import * as DateTime from "effect/DateTime";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";@@ -24,6 +25,7 @@ import * as Queue from "effect/Queue";import * as Ref from "effect/Ref";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";+import * as Tracer from "effect/Tracer";import * as TestClock from "effect/testing/TestClock";import * as FetchHttpClient from "effect/http/FetchHttpClient";@@ -373,6 +375,29 @@ describe("AgentAwarenessRelay", () => {}),);+ it.effect("exports the publication span through the relay tracer", () => {+ const relaySpans: string[] = [];+ const localSpans: string[] = [];+ const collectingTracer = (spans: string[]) =>+ Tracer.make({+ span: (options) => {+ spans.push(options.name);+ return new Tracer.NativeSpan(options);+ },+ });++ return Effect.gen(function* () {+ const { relay, publications } = yield* makeTestRelay();+ yield* relay.publishThread(THREAD_ID);+ assert.equal(publications.length, 1);+ assert.include(relaySpans, "relay.agent_activity.publish");+ assert.notInclude(localSpans, "relay.agent_activity.publish");+ }).pipe(+ Effect.provideService(RelayClientTracer, Option.some(collectingTracer(relaySpans))),+ Effect.withTracer(collectingTracer(localSpans)),+ );+ });+it.effect("deduplicates state and republishes title changes", () =>Effect.gen(function* () {const { relay, currentShell, publications } = yield* makeTestRelay();diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.tsindex fb21aa6e70d..87ce4afb08c 100644--- a/apps/server/src/relay/AgentAwarenessRelay.ts+++ b/apps/server/src/relay/AgentAwarenessRelay.ts@@ -462,54 +462,53 @@ export const make = Effect.gen(function* () {}const environmentId = yield* serverEnvironment.getEnvironmentId;- const publishState = (input: {+ const publishState = Effect.fn("relay.agent_activity.publish")(function* (input: {readonly projectId: string | null;readonly state: RelayAgentActivityState | null;readonly reason: string;- }) =>- Effect.gen(function* () {- if (cachedRelayClient === undefined) {- cachedRelayClient = yield* makeRelayClient(relayConfig);- }- const relayClient = cachedRelayClient;- const proof = yield* makePublishProof({- privateKey: cloudLinkKeyPair.privateKey,- relayIssuer: relayConfig.issuer,- environmentId,- threadId,- state: input.state,- jti: yield* crypto.randomUUIDv4(),- });+ }) {+ if (cachedRelayClient === undefined) {+ cachedRelayClient = yield* makeRelayClient(relayConfig);+ }+ const relayClient = cachedRelayClient;+ const proof = yield* makePublishProof({+ privateKey: cloudLinkKeyPair.privateKey,+ relayIssuer: relayConfig.issuer,+ environmentId,+ threadId,+ state: input.state,+ jti: yield* crypto.randomUUIDv4(),+ });- yield* Effect.logInfo("publishing agent activity for thread", {- environmentId,- threadId,- projectId: input.projectId,- statePhase: input.state?.phase ?? null,- hasState: input.state !== null,- reason: input.reason,- });+ yield* Effect.logInfo("publishing agent activity for thread", {+ environmentId,+ threadId,+ projectId: input.projectId,+ statePhase: input.state?.phase ?? null,+ hasState: input.state !== null,+ reason: input.reason,+ });- const response = yield* relayClient.server- .publishAgentActivity({- params: {- environmentId,- threadId,- },- payload: {- state: input.state,- proof,- },- })- .pipe(Effect.timeout("10 seconds"));-- yield* Effect.logInfo("agent activity publish completed", {- environmentId,- threadId,- ok: response.ok,- deliveries: deliveryStats(response.deliveries),- });- }).pipe(Effect.withSpan("relay.agent_activity.publish"), withRelayClientTracing);+ const response = yield* relayClient.server+ .publishAgentActivity({+ params: {+ environmentId,+ threadId,+ },+ payload: {+ state: input.state,+ proof,+ },+ })+ .pipe(Effect.timeout("10 seconds"));++ yield* Effect.logInfo("agent activity publish completed", {+ environmentId,+ threadId,+ ok: response.ok,+ deliveries: deliveryStats(response.deliveries),+ });+ });// Per-thread shell read: this publish runs for every activity-relevant// domain event, so materializing the full shell here would make the cost@@ -614,7 +613,7 @@ export const make = Effect.gen(function* () {projectId: snapshot.projectId,state: snapshot.state,reason: snapshot.reason,- });+ }).pipe(withRelayClientTracing);publishConfirmDeadlines.delete(threadId);yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {const nextPublishedStates = new Map(publishedStates);@@ -729,31 +728,33 @@ export const make = Effect.gen(function* () {// Many environments never link, so while unlinked the retry backs off from 5// s to 60 s. A linked environment keeps the 5 s retry, because `t3 connect- // publish` can turn publishing on from another process.- const publishActiveThreadsOnceWhenConfigured = (logEnabledWhenReady: boolean) =>- Effect.gen(function* () {- let unlinkedRetryDelayMs = 5_000;- while (!(yield* Ref.get(activeSnapshotPublishedRef))) {- const result = yield* publishActiveThreadsUnsafe.pipe(- Effect.orElseSucceed(() => "failed" as const),- );- if (result === "published") {- yield* Ref.set(activeSnapshotPublishedRef, true);- if (logEnabledWhenReady) {- const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));- yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {- relayUrl: relayConfig?.url,- });- }- return;- }- const retryDelayMs = result === "unlinked" ? unlinkedRetryDelayMs : 5_000;- yield* Effect.race(Effect.sleep(retryDelayMs), Queue.take(catchUpRequests));- if (result === "unlinked") {- unlinkedRetryDelayMs = Math.min(unlinkedRetryDelayMs * 2, 60_000);+ // publish` can turn publishing on from another process. Keep this untraced:+ // an unlinked environment can retry for the lifetime of the process.+ const publishActiveThreadsOnceWhenConfigured = Effect.fnUntraced(function* (+ logEnabledWhenReady: boolean,+ ) {+ let unlinkedRetryDelayMs = 5_000;+ while (!(yield* Ref.get(activeSnapshotPublishedRef))) {+ const result = yield* publishActiveThreadsUnsafe.pipe(+ Effect.orElseSucceed(() => "failed" as const),+ );+ if (result === "published") {+ yield* Ref.set(activeSnapshotPublishedRef, true);+ if (logEnabledWhenReady) {+ const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));+ yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {+ relayUrl: relayConfig?.url,+ });}+ return;}- });+ const retryDelayMs = result === "unlinked" ? unlinkedRetryDelayMs : 5_000;+ yield* Effect.race(Effect.sleep(retryDelayMs), Queue.take(catchUpRequests));+ if (result === "unlinked") {+ unlinkedRetryDelayMs = Math.min(unlinkedRetryDelayMs * 2, 60_000);+ }+ }+ });schedulePublishConfirm = (threadId) =>Effect.forkIn(diff --git a/apps/server/src/resourceTelemetry/NativeTelemetryClient.ts b/apps/server/src/resourceTelemetry/NativeTelemetryClient.tsindex 9d252fadb4f..5ec3664bf21 100644--- a/apps/server/src/resourceTelemetry/NativeTelemetryClient.ts+++ b/apps/server/src/resourceTelemetry/NativeTelemetryClient.ts@@ -279,23 +279,22 @@ export function resolveNativeSampleIntervalMs(return SAMPLE_INTERVAL_MS;}-export function commitCollectionControlUpdate<E, R>(+// Desktop power samples also commit control state; avoid a span for each sample.+export const commitCollectionControlUpdate = Effect.fnUntraced(function* <E, R>(desiredState: Ref.Ref<CollectionControl>,appliedState: Ref.Ref<CollectionControl>,update: (current: CollectionControl) => CollectionControl,apply: (previous: CollectionControl, next: CollectionControl) => Effect.Effect<void, E, R>,-): Effect.Effect<readonly [CollectionControl, CollectionControl], E, R> {- return Effect.gen(function* () {- const [previousDesired, next] = yield* Ref.modify(desiredState, (previous) => {- const next = update(previous);- return [[previous, next] as const, next];- });- const previousApplied = yield* Ref.get(appliedState);- yield* apply(previousApplied, next);- yield* Ref.set(appliedState, next);- return [previousDesired, next] as const;+): Effect.fn.Return<readonly [CollectionControl, CollectionControl], E, R> {+ const [previousDesired, next] = yield* Ref.modify(desiredState, (previous) => {+ const next = update(previous);+ return [[previous, next] as const, next];});-}+ const previousApplied = yield* Ref.get(appliedState);+ yield* apply(previousApplied, next);+ yield* Ref.set(appliedState, next);+ return [previousDesired, next] as const;+});export function synchronizeCollectionControlOnStart<E1, R1, E2, R2>(mutex: Semaphore.Semaphore,@@ -411,23 +410,22 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fuEffect.asVoid,);- const failPending = (error: NativeTelemetryClientError) =>- Effect.gen(function* () {- const samples = yield* Ref.getAndSet(pendingSamples, new Map());- const processTables = yield* Ref.getAndSet(pendingProcessTables, new Map());- const histories = yield* Ref.getAndSet(pendingHistories, new Map());- yield* Effect.forEach(samples.values(), (deferred) => Deferred.fail(deferred, error), {- discard: true,- });- yield* Effect.forEach(processTables.values(), (deferred) => Deferred.fail(deferred, error), {- discard: true,- });- yield* Effect.forEach(- histories.values(),- (request) => Deferred.fail(request.deferred, error),- { discard: true },- );+ const failPending = Effect.fn("NativeTelemetryClient.failPending")(function* (+ error: NativeTelemetryClientError,+ ) {+ const samples = yield* Ref.getAndSet(pendingSamples, new Map());+ const processTables = yield* Ref.getAndSet(pendingProcessTables, new Map());+ const histories = yield* Ref.getAndSet(pendingHistories, new Map());+ yield* Effect.forEach(samples.values(), (deferred) => Deferred.fail(deferred, error), {+ discard: true,+ });+ yield* Effect.forEach(processTables.values(), (deferred) => Deferred.fail(deferred, error), {+ discard: true,+ });+ yield* Effect.forEach(histories.values(), (request) => Deferred.fail(request.deferred, error), {+ discard: true,});+ });const writeCommand = (handle: ChildProcessSpawner.ChildProcessHandle,@@ -777,9 +775,11 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fuEffect.forkScoped,);- const applyCollectionControl = Effect.fn(- "resourceTelemetry.nativeTelemetryClient.applyCollectionControl",- )(function* (previous: CollectionControl, next: CollectionControl) {+ // Desktop power samples reach this even when the control state has not changed.+ const applyCollectionControl = Effect.fnUntraced(function* (+ previous: CollectionControl,+ next: CollectionControl,+ ) {const current = yield* Ref.get(state);if (canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {const handle = Option.getOrThrow(current.handle);@@ -842,10 +842,9 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu}),);- const setExternalProcesses: NativeTelemetryClient["Service"]["setExternalProcesses"] = (- processes,- ) =>- Effect.gen(function* () {+ // Desktop telemetry refreshes this process set on every sample.+ const setExternalProcesses: NativeTelemetryClient["Service"]["setExternalProcesses"] =+ Effect.fnUntraced(function* (processes) {yield* Ref.set(externalProcesses, [...processes]);const current = yield* Ref.get(state);if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) return;@@ -856,64 +855,65 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu});});- const readHistory: NativeTelemetryClient["Service"]["readHistory"] = (windowMs) =>- Effect.gen(function* () {- const current = yield* Ref.get(state);- if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {- return yield* new NativeTelemetryUnavailable({- reason: Option.getOrElse(current.lastError, () => "sidecar is not running"),- });- }- const requestId = yield* crypto.randomUUIDv4().pipe(- Effect.mapError(- (cause) =>- new NativeTelemetryCommandFailed({- operation: "createHistoryRequestId",- cause,- }),- ),- );- const deferred = yield* Deferred.make<- ReadonlyArray<ResourceMonitorSnapshotEvent>,- NativeTelemetryClientError- >();- yield* Ref.update(pendingHistories, (pending) => {- const next = new Map(pending);- next.set(requestId, { deferred, snapshots: [] });- return next;+ const readHistory: NativeTelemetryClient["Service"]["readHistory"] = Effect.fn(+ "NativeTelemetryClient.readHistory",+ )(function* (windowMs) {+ const current = yield* Ref.get(state);+ if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {+ return yield* new NativeTelemetryUnavailable({+ reason: Option.getOrElse(current.lastError, () => "sidecar is not running"),});- return yield* writeCommand(Option.getOrThrow(current.handle), {- version: RESOURCE_MONITOR_PROTOCOL_VERSION,- type: "readHistory",- requestId,- windowMs: Math.max(0, Math.round(windowMs)),- }).pipe(- Effect.andThen(- Deferred.await(deferred).pipe(- Effect.timeoutOption(HISTORY_REQUEST_TIMEOUT),- Effect.flatMap(- Option.match({- onNone: () =>- Effect.fail(- new NativeTelemetryRequestTimedOut({- operation: "readHistory",- timeoutMs: Duration.toMillis(HISTORY_REQUEST_TIMEOUT),- }),- ),- onSome: Effect.succeed,- }),- ),- ),- ),- Effect.ensuring(- Ref.update(pendingHistories, (pending) => {- const next = new Map(pending);- next.delete(requestId);- return next;+ }+ const requestId = yield* crypto.randomUUIDv4().pipe(+ Effect.mapError(+ (cause) =>+ new NativeTelemetryCommandFailed({+ operation: "createHistoryRequestId",+ cause,}),- ),- );+ ),+ );+ const deferred = yield* Deferred.make<+ ReadonlyArray<ResourceMonitorSnapshotEvent>,+ NativeTelemetryClientError+ >();+ yield* Ref.update(pendingHistories, (pending) => {+ const next = new Map(pending);+ next.set(requestId, { deferred, snapshots: [] });+ return next;});+ return yield* writeCommand(Option.getOrThrow(current.handle), {+ version: RESOURCE_MONITOR_PROTOCOL_VERSION,+ type: "readHistory",+ requestId,+ windowMs: Math.max(0, Math.round(windowMs)),+ }).pipe(+ Effect.andThen(+ Deferred.await(deferred).pipe(+ Effect.timeoutOption(HISTORY_REQUEST_TIMEOUT),+ Effect.flatMap(+ Option.match({+ onNone: () =>+ Effect.fail(+ new NativeTelemetryRequestTimedOut({+ operation: "readHistory",+ timeoutMs: Duration.toMillis(HISTORY_REQUEST_TIMEOUT),+ }),+ ),+ onSome: Effect.succeed,+ }),+ ),+ ),+ ),+ Effect.ensuring(+ Ref.update(pendingHistories, (pending) => {+ const next = new Map(pending);+ next.delete(requestId);+ return next;+ }),+ ),+ );+ });const sampleNow: NativeTelemetryClient["Service"]["sampleNow"] = Effect.gen(function* () {const current = yield* Ref.get(state);diff --git a/apps/server/src/resourceTelemetry/ResourceTelemetry.ts b/apps/server/src/resourceTelemetry/ResourceTelemetry.tsindex 0563ab7b107..2af6d98da0d 100644--- a/apps/server/src/resourceTelemetry/ResourceTelemetry.ts+++ b/apps/server/src/resourceTelemetry/ResourceTelemetry.ts@@ -333,8 +333,9 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functiconst ingestNative = (snapshot: NativeTelemetryClient.NativeTelemetrySnapshot) =>rebuild({ nativeSnapshot: snapshot, updatePrevious: true });- const ingestDesktop = (snapshot: DesktopHostTelemetrySnapshot) =>- Effect.gen(function* () {+ const ingestDesktop =+ /* Desktop samples arrive continuously; avoid a span per telemetry sample. */+ Effect.fnUntraced(function* (snapshot: DesktopHostTelemetrySnapshot) {const electronRoot = snapshot.electronProcesses.find((process) => process.pid === snapshot.electronPid,);@@ -412,39 +413,38 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functi);const liveChanges = Stream.unwrap(Effect.map(subscribe, ({ changes }) => changes));- const readHistory: ResourceTelemetry["Service"]["readHistory"] = (input) =>- Effect.gen(function* () {- const readAt = yield* DateTime.now;- const normalizedInput = normalizeResourceTelemetryHistoryInput(input);- const historyResult = yield* Effect.result(- nativeClient.readHistory(normalizedInput.windowMs),- );- if (Result.isFailure(historyResult)) {- yield* Effect.logWarning("Failed to read native resource telemetry history", {- cause: historyResult.failure.message,- });- }- const [nativeHealth, desktopHealth] = yield* Effect.all([- nativeClient.health,- desktopReceiver.health,- ]);- const current = yield* Ref.get(state);- return buildResourceTelemetryHistory({- readAt,- windowMs: normalizedInput.windowMs,- bucketMs: normalizedInput.bucketMs,- sampleIntervalMs: nativeHealth.sampleIntervalMs,- serverPid: process.pid,- sidecarPid: Option.map(nativeHealth.hello, (hello) => hello.sidecarPid),- desktopSnapshot: current.desktopSnapshot,- snapshots: Result.isSuccess(historyResult) ? historyResult.success : [],- health: buildHealth({- native: nativeHealth,- desktop: desktopHealth,- nativeSnapshot: current.nativeSnapshot,- }),+ const readHistory: ResourceTelemetry["Service"]["readHistory"] = Effect.fn(+ "ResourceTelemetry.readHistory",+ )(function* (input) {+ const readAt = yield* DateTime.now;+ const normalizedInput = normalizeResourceTelemetryHistoryInput(input);+ const historyResult = yield* Effect.result(nativeClient.readHistory(normalizedInput.windowMs));+ if (Result.isFailure(historyResult)) {+ yield* Effect.logWarning("Failed to read native resource telemetry history", {+ cause: historyResult.failure.message,});+ }+ const [nativeHealth, desktopHealth] = yield* Effect.all([+ nativeClient.health,+ desktopReceiver.health,+ ]);+ const current = yield* Ref.get(state);+ return buildResourceTelemetryHistory({+ readAt,+ windowMs: normalizedInput.windowMs,+ bucketMs: normalizedInput.bucketMs,+ sampleIntervalMs: nativeHealth.sampleIntervalMs,+ serverPid: process.pid,+ sidecarPid: Option.map(nativeHealth.hello, (hello) => hello.sidecarPid),+ desktopSnapshot: current.desktopSnapshot,+ snapshots: Result.isSuccess(historyResult) ? historyResult.success : [],+ health: buildHealth({+ native: nativeHealth,+ desktop: desktopHealth,+ nativeSnapshot: current.nativeSnapshot,+ }),});+ });yield* nativeHealthSubscription.changes.pipe(Stream.runForEach(() => refreshHealth),Effect.forkScoped,diff --git a/apps/server/src/scheduledTasks/RelayDeliveryProof.ts b/apps/server/src/scheduledTasks/RelayDeliveryProof.tsindex 767d2fa7bb9..abf7c148acc 100644--- a/apps/server/src/scheduledTasks/RelayDeliveryProof.ts+++ b/apps/server/src/scheduledTasks/RelayDeliveryProof.ts@@ -44,8 +44,8 @@ export class RelayDeliveryProof extends Context.Service<const make = Effect.gen(function* () {const secrets = yield* ServerSecretStore.ServerSecretStore;const environment = yield* ServerEnvironment.ServerEnvironment;- const verify: RelayDeliveryProof["Service"]["verify"] = (input) =>- Effect.gen(function* () {+ const verify: RelayDeliveryProof["Service"]["verify"] = Effect.fn("webhook.verifyRelayDelivery")(+ function* (input) {const proof = input.headers[RELAY_HOOK_DELIVERY_HEADER];const deliveryId = input.headers["x-t3-relay-delivery-id"];const receivedAt = input.headers["x-t3-relay-received-at"];@@ -80,7 +80,9 @@ const make = Effect.gen(function* () {return Option.none();}return Option.some({ deliveryId, receivedAt });- }).pipe(Effect.orElseSucceed(Option.none), Effect.withSpan("webhook.verifyRelayDelivery"));+ },+ Effect.orElseSucceed(Option.none),+ );return RelayDeliveryProof.of({ verify });});diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.tsindex d259d0b657a..99e215be7dc 100644--- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts@@ -281,8 +281,9 @@ function webhookEndpoint(};}-const decodeRow = (row: ScheduledTaskRow, origin: WebhookOrigin | null = null) =>- Effect.gen(function* () {+// Runs per task row; list and lookup operations already own the span.+const decodeRow = Effect.fnUntraced(+ function* (row: ScheduledTaskRow, origin: WebhookOrigin | null = null) {const schedule = yield* decodeScheduleJson(row.schedule_json);const webhook = schedule.type === "webhook" ? webhookEndpoint(row, origin) : undefined;const workspaceStrategy = yield* decodeWorkspaceStrategyJson(row.workspace_strategy_json);@@ -310,15 +311,18 @@ const decodeRow = (row: ScheduledTaskRow, origin: WebhookOrigin | null = null) =runCount: row.run_count,...(webhook === undefined ? {} : { webhook }),});- }).pipe(- Effect.mapError((cause) => {- const taskId = decodeTaskId(row.task_id);- return taskError("Could not decode schedule task row.", {- ...(Option.isSome(taskId) ? { taskId: taskId.value } : {}),- cause,- });- }),- );+ },+ (effect, row, _origin?) =>+ effect.pipe(+ Effect.mapError((cause) => {+ const taskId = decodeTaskId(row.task_id);+ return taskError("Could not decode schedule task row.", {+ ...(Option.isSome(taskId) ? { taskId: taskId.value } : {}),+ cause,+ });+ }),+ ),+);export const listDueTasks = Effect.fn("ScheduledTaskService.listDueTasks")(function* (now: DateTime.DateTime,@@ -639,8 +643,8 @@ export const layer = Layer.effect(// the task forever (it filters out 'running' rows) nor re-fires it// immediately: the dispatch may already have gone out, so next_run_at must// advance and run_count must count the attempt.- const releaseStuckRun = (task: ScheduledTask, message: string) =>- Effect.gen(function* () {+ const releaseStuckRun = Effect.fn("ScheduledTaskService.releaseStuckRun")(+ function* (task: ScheduledTask, message: string) {const now = yield* localNow;const reread = yield* Effect.result(findTask(task.id));if (Result.isSuccess(reread) && reread.success === null) return;@@ -655,14 +659,17 @@ export const layer = Layer.effect(WHERE task_id = ${task.id} AND last_run_status = 'running'`;yield* notifyChanged;- }).pipe(- Effect.catch((cause) =>- Effect.logWarning("Could not release stuck schedule task run", {- taskId: task.id,- cause,- }),+ },+ (effect, task, _message) =>+ effect.pipe(+ Effect.catch((cause) =>+ Effect.logWarning("Could not release stuck schedule task run", {+ taskId: task.id,+ cause,+ }),+ ),),- );+ );const runTask = Effect.fn("ScheduledTaskService.runTask")(function* (task: ScheduledTask,@@ -935,130 +942,131 @@ export const layer = Layer.effect(}),);- const upsert: ScheduledTaskService["Service"]["upsert"] = (input) =>- Effect.gen(function* () {- const now = yield* localNow;- const uuid =- input.commandId === undefined- ? yield* crypto- .randomUUIDv4()- .pipe(- Effect.mapError((cause) =>- taskError("Could not generate schedule task id.", { cause }),- ),- )- : null;- const id =- input.id ??- ScheduledTaskId.make(- input.commandId ? `scheduled-task:${input.commandId}` : `scheduled-task:${uuid}`,- );- // Look up by the *resolved* id so idempotent creates (commandId replays)- // keep their run history, and so real load failures propagate instead- // of silently resetting an existing row.- const existingTask = yield* findTask(id);- // Keep the existing next_run_at when the schedule itself is untouched:- // editing a title or prompt must not postpone (or resurrect) a due- // run — only schedule/enabled changes restart the clock.- const schedule: ScheduledTask["schedule"] =- input.schedule.type === "webhook"- ? {- type: "webhook",- signature:- input.schedule.signature == null- ? null- : {- header: input.schedule.signature.header.toLowerCase(),- encoding: input.schedule.signature.encoding,- prefix: input.schedule.signature.prefix,- },- maxDeliveryAgeMinutes: input.schedule.maxDeliveryAgeMinutes ?? null,+ const upsert: ScheduledTaskService["Service"]["upsert"] = Effect.fn(+ "ScheduledTaskService.upsert",+ )(function* (input) {+ const now = yield* localNow;+ const uuid =+ input.commandId === undefined+ ? yield* crypto+ .randomUUIDv4()+ .pipe(+ Effect.mapError((cause) =>+ taskError("Could not generate schedule task id.", { cause }),+ ),+ )+ : null;+ const id =+ input.id ??+ ScheduledTaskId.make(+ input.commandId ? `scheduled-task:${input.commandId}` : `scheduled-task:${uuid}`,+ );+ // Look up by the *resolved* id so idempotent creates (commandId replays)+ // keep their run history, and so real load failures propagate instead+ // of silently resetting an existing row.+ const existingTask = yield* findTask(id);+ // Keep the existing next_run_at when the schedule itself is untouched:+ // editing a title or prompt must not postpone (or resurrect) a due+ // run — only schedule/enabled changes restart the clock.+ const schedule: ScheduledTask["schedule"] =+ input.schedule.type === "webhook"+ ? {+ type: "webhook",+ signature:+ input.schedule.signature == null+ ? null+ : {+ header: input.schedule.signature.header.toLowerCase(),+ encoding: input.schedule.signature.encoding,+ prefix: input.schedule.signature.prefix,+ },+ maxDeliveryAgeMinutes: input.schedule.maxDeliveryAgeMinutes ?? null,+ }+ : input.schedule;+ const webhook =+ input.schedule.type === "webhook"+ ? yield* Effect.gen(function* () {+ const existing = existingTask === null ? null : yield* findWebhookCredentials(id);+ const token = existing?.token ?? (yield* newWebhookToken);+ const signature = input.schedule.type === "webhook" ? input.schedule.signature : null;+ // A secretRef is a value the user entered for an agent; this+ // save consumes it, so it cannot be used again. A replay of a+ // save that already used it keeps the secret that save stored.+ const replay = input.commandId !== undefined && existing?.secret != null;+ const fromRef =+ signature?.secretRef === undefined+ ? undefined+ : yield* secretRequests+ .consume({ ref: signature.secretRef, projectId: input.projectId })+ .pipe(+ Effect.catch((error) =>+ replay+ ? Effect.succeed(undefined)+ : Effect.fail(taskError(error.message, { taskId: id })),+ ),+ );+ // A ref, when given, is the only source: a plain secret sent+ // alongside it must not replace what a replayed save stored.+ const provided = signature?.secretRef === undefined ? signature?.secret : fromRef;+ const secret = signature == null ? null : (provided ?? existing?.secret ?? null);+ const secretChanged =+ signature == null || provided !== undefined || existing === null;+ if (signature != null && secret === null) {+ return yield* taskError("A webhook signature check needs a signing secret.", {+ taskId: id,+ });}- : input.schedule;- const webhook =- input.schedule.type === "webhook"- ? yield* Effect.gen(function* () {- const existing = existingTask === null ? null : yield* findWebhookCredentials(id);- const token = existing?.token ?? (yield* newWebhookToken);- const signature =- input.schedule.type === "webhook" ? input.schedule.signature : null;- // A secretRef is a value the user entered for an agent; this- // save consumes it, so it cannot be used again. A replay of a- // save that already used it keeps the secret that save stored.- const replay = input.commandId !== undefined && existing?.secret != null;- const fromRef =- signature?.secretRef === undefined- ? undefined- : yield* secretRequests- .consume({ ref: signature.secretRef, projectId: input.projectId })- .pipe(- Effect.catch((error) =>- replay- ? Effect.succeed(undefined)- : Effect.fail(taskError(error.message, { taskId: id })),- ),- );- // A ref, when given, is the only source: a plain secret sent- // alongside it must not replace what a replayed save stored.- const provided = signature?.secretRef === undefined ? signature?.secret : fromRef;- const secret = signature == null ? null : (provided ?? existing?.secret ?? null);- const secretChanged =- signature == null || provided !== undefined || existing === null;- if (signature != null && secret === null) {- return yield* taskError("A webhook signature check needs a signing secret.", {- taskId: id,- });- }- return { token, secret, secretChanged };- })- : { token: null, secret: null, secretChanged: true };- const workspaceStrategy: ScheduledTask["workspaceStrategy"] =- input.workspaceStrategy.type === "worktree" &&- (yield* managedFolders.isScratchProject(input.projectId))- ? { type: "root" }- : input.workspaceStrategy;- const scheduleUnchanged =- existingTask !== null &&- existingTask.enabled === input.enabled &&- isSameSchedule(existingTask.schedule, schedule);- const task: ScheduledTask = {- id,- title: input.title,- prompt: input.prompt,- enabled: input.enabled,- schedule,- projectId: input.projectId,- threadId: input.threadId ?? null,- workspaceStrategy,- modelSelection: input.modelSelection,- runtimeMode: input.runtimeMode,- interactionMode: input.interactionMode,- createdBy: existingTask?.createdBy ?? input.createdBy ?? "user",- creationSource: input.creationSource ?? "web",- createdAt: existingTask?.createdAt ?? iso(now),- updatedAt: iso(now),- nextRunAt: scheduleUnchanged- ? existingTask.nextRunAt- : nextRunAt({ enabled: input.enabled, schedule }, now),- lastRunAt: existingTask?.lastRunAt ?? null,- lastRunStatus: existingTask?.lastRunStatus ?? "never",- lastRunError: existingTask?.lastRunError ?? null,- runCount: existingTask?.runCount ?? 0,- };- yield* saveTask(task, input.requireExisting === true, webhook);- yield* notifyChanged;- return { task: (yield* findTask(id)) ?? task };- });+ return { token, secret, secretChanged };+ })+ : { token: null, secret: null, secretChanged: true };+ const workspaceStrategy: ScheduledTask["workspaceStrategy"] =+ input.workspaceStrategy.type === "worktree" &&+ (yield* managedFolders.isScratchProject(input.projectId))+ ? { type: "root" }+ : input.workspaceStrategy;+ const scheduleUnchanged =+ existingTask !== null &&+ existingTask.enabled === input.enabled &&+ isSameSchedule(existingTask.schedule, schedule);+ const task: ScheduledTask = {+ id,+ title: input.title,+ prompt: input.prompt,+ enabled: input.enabled,+ schedule,+ projectId: input.projectId,+ threadId: input.threadId ?? null,+ workspaceStrategy,+ modelSelection: input.modelSelection,+ runtimeMode: input.runtimeMode,+ interactionMode: input.interactionMode,+ createdBy: existingTask?.createdBy ?? input.createdBy ?? "user",+ creationSource: input.creationSource ?? "web",+ createdAt: existingTask?.createdAt ?? iso(now),+ updatedAt: iso(now),+ nextRunAt: scheduleUnchanged+ ? existingTask.nextRunAt+ : nextRunAt({ enabled: input.enabled, schedule }, now),+ lastRunAt: existingTask?.lastRunAt ?? null,+ lastRunStatus: existingTask?.lastRunStatus ?? "never",+ lastRunError: existingTask?.lastRunError ?? null,+ runCount: existingTask?.runCount ?? 0,+ };+ yield* saveTask(task, input.requireExisting === true, webhook);+ yield* notifyChanged;+ return { task: (yield* findTask(id)) ?? task };+ });- const setEnabled: ScheduledTaskService["Service"]["setEnabled"] = (input) =>- Effect.gen(function* () {- const existing = yield* loadTask(input.id);- if (existing.enabled === input.enabled) return { task: existing };- const now = yield* localNow;- const next = nextRunAt({ enabled: input.enabled, schedule: existing.schedule }, now);- // RETURNING so a task deleted between the load and this UPDATE is a- // visible not-found error, not a false success.- const updated = yield* sql<{ task_id: string }>`+ const setEnabled: ScheduledTaskService["Service"]["setEnabled"] = Effect.fn(+ "ScheduledTaskService.setEnabled",+ )(function* (input) {+ const existing = yield* loadTask(input.id);+ if (existing.enabled === input.enabled) return { task: existing };+ const now = yield* localNow;+ const next = nextRunAt({ enabled: input.enabled, schedule: existing.schedule }, now);+ // RETURNING so a task deleted between the load and this UPDATE is a+ // visible not-found error, not a false success.+ const updated = yield* sql<{ task_id: string }>`UPDATE scheduled_tasksSET enabled = ${input.enabled ? 1 : 0},next_run_at = ${next},@@ -1066,18 +1074,18 @@ export const layer = Layer.effect(WHERE task_id = ${input.id}RETURNING task_id`.pipe(- Effect.mapError((cause) =>- taskError("Could not update schedule task.", { taskId: input.id, cause }),- ),- );- if (updated.length === 0) {- return yield* taskError("Schedule task not found.", { taskId: input.id });- }- yield* notifyChanged;- return {- task: { ...existing, enabled: input.enabled, nextRunAt: next, updatedAt: iso(now) },- };- });+ Effect.mapError((cause) =>+ taskError("Could not update schedule task.", { taskId: input.id, cause }),+ ),+ );+ if (updated.length === 0) {+ return yield* taskError("Schedule task not found.", { taskId: input.id });+ }+ yield* notifyChanged;+ return {+ task: { ...existing, enabled: input.enabled, nextRunAt: next, updatedAt: iso(now) },+ };+ });const deleteTask: ScheduledTaskService["Service"]["delete"] = (input) =>deleteRow(input.id).pipe(@@ -1099,48 +1107,50 @@ export const layer = Layer.effect(Effect.as({ id: input.id }),);- const runNow: ScheduledTaskService["Service"]["runNow"] = (input: ScheduledTaskRunNowInput) =>- Effect.gen(function* () {- const task = yield* loadTask(input.id);- if (task.schedule.type === "webhook") {- return yield* taskError("Webhook tasks run when their URL receives a request.", {- taskId: input.id,- });- }- const next = yield* runTask(task, "manual").pipe(- Effect.mapError((cause) =>- taskError("Could not run schedule task.", { taskId: input.id, cause }),- ),- );- return { task: next };- });+ const runNow: ScheduledTaskService["Service"]["runNow"] = Effect.fn(+ "ScheduledTaskService.runNow",+ )(function* (input: ScheduledTaskRunNowInput) {+ const task = yield* loadTask(input.id);+ if (task.schedule.type === "webhook") {+ return yield* taskError("Webhook tasks run when their URL receives a request.", {+ taskId: input.id,+ });+ }+ const next = yield* runTask(task, "manual").pipe(+ Effect.mapError((cause) =>+ taskError("Could not run schedule task.", { taskId: input.id, cause }),+ ),+ );+ return { task: next };+ });- const rotateWebhookToken: ScheduledTaskService["Service"]["rotateWebhookToken"] = (input) =>- Effect.gen(function* () {- const task = yield* loadTask(input.id);- if (task.schedule.type !== "webhook") {- return yield* taskError("Only webhook tasks have a URL token.", { taskId: input.id });- }- const token = yield* newWebhookToken;- const now = yield* localNow;- // Matching created_at keeps a rotation from landing on a task deleted- // and recreated under the same id since it was loaded.- const updated = yield* sql<{ task_id: string }>`+ const rotateWebhookToken: ScheduledTaskService["Service"]["rotateWebhookToken"] = Effect.fn(+ "ScheduledTaskService.rotateWebhookToken",+ )(function* (input) {+ const task = yield* loadTask(input.id);+ if (task.schedule.type !== "webhook") {+ return yield* taskError("Only webhook tasks have a URL token.", { taskId: input.id });+ }+ const token = yield* newWebhookToken;+ const now = yield* localNow;+ // Matching created_at keeps a rotation from landing on a task deleted+ // and recreated under the same id since it was loaded.+ const updated = yield* sql<{ task_id: string }>`UPDATE scheduled_tasksSET webhook_token = ${token}, updated_at = ${iso(now)}WHERE task_id = ${input.id} AND created_at = ${task.createdAt}RETURNING task_id`.pipe(- Effect.mapError((cause) =>- taskError("Could not rotate webhook token.", { taskId: input.id, cause }),- ),- );- if (updated.length === 0) {- return yield* taskError("Schedule task was deleted or replaced.", { taskId: input.id });- }- yield* notifyChanged;- return { task: yield* loadTask(input.id) };- });+ Effect.mapError((cause) =>+ taskError("Could not rotate webhook token.", { taskId: input.id, cause }),+ ),+ );+ if (updated.length === 0) {+ return yield* taskError("Schedule task was deleted or replaced.", { taskId: input.id });+ }+ yield* notifyChanged;+ return { task: yield* loadTask(input.id) };+ });const deliveryHeaders = (row: WebhookDeliveryRow): Readonly<Record<string, string>> =>Option.getOrElse(decodeHeadersJson(row.headers_json), () => ({}));@@ -1171,31 +1181,32 @@ export const layer = Layer.effect(),);- const getWebhookDelivery: ScheduledTaskService["Service"]["getWebhookDelivery"] = (input) =>- Effect.gen(function* () {- const rows = yield* sql<WebhookDeliveryRow>`+ const getWebhookDelivery: ScheduledTaskService["Service"]["getWebhookDelivery"] = Effect.fn(+ "ScheduledTaskService.getWebhookDelivery",+ )(function* (input) {+ const rows = yield* sql<WebhookDeliveryRow>`SELECT * FROM scheduled_task_webhook_deliveriesWHERE task_id = ${input.id} AND delivery_id = ${input.deliveryId}`.pipe(- Effect.mapError((cause) =>- taskError("Could not load webhook delivery.", { taskId: input.id, cause }),- ),- );- const row = rows[0];- if (row === undefined) {- return yield* taskError("Webhook delivery not found.", { taskId: input.id });- }- return {- delivery: {- ...decodeDeliverySummary(row),- query: row.query,- headers: deliveryHeaders(row),- body: row.body,- bodyTruncated: row.body_truncated === 1,- renderedPrompt: row.rendered_prompt,- },- };- });+ Effect.mapError((cause) =>+ taskError("Could not load webhook delivery.", { taskId: input.id, cause }),+ ),+ );+ const row = rows[0];+ if (row === undefined) {+ return yield* taskError("Webhook delivery not found.", { taskId: input.id });+ }+ return {+ delivery: {+ ...decodeDeliverySummary(row),+ query: row.query,+ headers: deliveryHeaders(row),+ body: row.body,+ bodyTruncated: row.body_truncated === 1,+ renderedPrompt: row.rendered_prompt,+ },+ };+ });const recordDelivery = (input: {readonly id: string;@@ -1298,43 +1309,44 @@ export const layer = Layer.effect(},);- const webhookPermit = (id: ScheduledTaskId) =>- Effect.gen(function* () {- const existing = (yield* Ref.get(webhookPermits)).get(id);- if (existing !== undefined) return existing;- const created = yield* Semaphore.make(1);- return yield* Ref.modify(webhookPermits, (permits) => {- const raced = permits.get(id);- return raced === undefined- ? [created, new Map(permits).set(id, created)]- : [raced, permits];- });+ const webhookPermit = Effect.fn("ScheduledTaskService.webhookPermit")(function* (+ id: ScheduledTaskId,+ ) {+ const existing = (yield* Ref.get(webhookPermits)).get(id);+ if (existing !== undefined) return existing;+ const created = yield* Semaphore.make(1);+ return yield* Ref.modify(webhookPermits, (permits) => {+ const raced = permits.get(id);+ return raced === undefined+ ? [created, new Map(permits).set(id, created)]+ : [raced, permits];});+ });const serviceScope = yield* Effect.scope;- const observeDelivery = (+ // Delivery attributes belong to the enclosing triggerWebhook span.+ const observeDelivery = Effect.fnUntraced(function* (request: WebhookTriggerRequest,outcome: WebhookDeliveryOutcome,receivedAt: DateTime.DateTime | undefined,now: DateTime.DateTime | undefined,- ) =>- Effect.gen(function* () {- const source = request.relayDeliveryId === undefined ? "direct" : "relay";- yield* Effect.annotateCurrentSpan({- "scheduled_task.webhook.outcome": outcome,- "scheduled_task.webhook.source": source,- });- yield* Metrics.increment(Metrics.webhookDeliveriesTotal, { outcome, source });- if (request.receivedAt !== undefined && receivedAt !== undefined && now !== undefined) {- const heldMs = Math.max(- 0,- DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt),- );- yield* Effect.annotateCurrentSpan({ "scheduled_task.webhook.held_ms": heldMs });- yield* Metric.update(Metrics.webhookHeldDelay, Duration.millis(heldMs));- }+ ) {+ const source = request.relayDeliveryId === undefined ? "direct" : "relay";+ yield* Effect.annotateCurrentSpan({+ "scheduled_task.webhook.outcome": outcome,+ "scheduled_task.webhook.source": source,});+ yield* Metrics.increment(Metrics.webhookDeliveriesTotal, { outcome, source });+ if (request.receivedAt !== undefined && receivedAt !== undefined && now !== undefined) {+ const heldMs = Math.max(+ 0,+ DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt),+ );+ yield* Effect.annotateCurrentSpan({ "scheduled_task.webhook.held_ms": heldMs });+ yield* Metric.update(Metrics.webhookHeldDelay, Duration.millis(heldMs));+ }+ });const triggerWebhook: ScheduledTaskService["Service"]["triggerWebhook"] = (request) =>triggerWebhookUnobserved(request).pipe(@@ -1350,252 +1362,250 @@ export const layer = Layer.effect(}),);- const triggerWebhookUnobserved = (request: WebhookTriggerRequest) =>- Effect.gen(function* () {- const taskId = decodeTaskId(request.hookId);- const notFound = observeDelivery(request, "not_found", undefined, undefined).pipe(- Effect.as({ _tag: "not_found" as const }),- );- if (Option.isNone(taskId)) return yield* notFound;- const rows = yield* getRows(taskId.value).pipe(- Effect.mapError((cause) =>- taskError("Could not load schedule task.", { taskId: taskId.value, cause }),- ),- );- const row = rows[0];- // A wrong token is indistinguishable from an unknown hook, so the URL- // does not reveal which hooks exist.- if (- row === undefined ||- row.webhook_token === null ||- !constantTimeEquals(request.token, row.webhook_token)- ) {- return yield* notFound;- }- const task = yield* decodeRow(row);- yield* Effect.annotateCurrentSpan({ "scheduled_task.id": task.id });- const schedule = task.schedule;- if (schedule.type !== "webhook") return yield* notFound;+ // triggerWebhook owns the operation span and its task-id annotation.+ const triggerWebhookUnobserved = Effect.fnUntraced(function* (request: WebhookTriggerRequest) {+ const taskId = decodeTaskId(request.hookId);+ const notFound = observeDelivery(request, "not_found", undefined, undefined).pipe(+ Effect.as({ _tag: "not_found" as const }),+ );+ if (Option.isNone(taskId)) return yield* notFound;+ const rows = yield* getRows(taskId.value).pipe(+ Effect.mapError((cause) =>+ taskError("Could not load schedule task.", { taskId: taskId.value, cause }),+ ),+ );+ const row = rows[0];+ // A wrong token is indistinguishable from an unknown hook, so the URL+ // does not reveal which hooks exist.+ if (+ row === undefined ||+ row.webhook_token === null ||+ !constantTimeEquals(request.token, row.webhook_token)+ ) {+ return yield* notFound;+ }+ const task = yield* decodeRow(row);+ yield* Effect.annotateCurrentSpan({ "scheduled_task.id": task.id });+ const schedule = task.schedule;+ if (schedule.type !== "webhook") return yield* notFound;- const now = yield* localNow;- // Anyone can reach the tunnel directly and set the relay's header, so- // a receive time is never later than now: a future one would pin the- // delivery in the log and slip past the task's max age.- const receivedAt =- request.receivedAt === undefined- ? now- : DateTime.min(- Option.getOrElse(DateTime.make(request.receivedAt), () => now),- now,- );- const observe = (outcome: WebhookDeliveryOutcome) =>- observeDelivery(request, outcome, receivedAt, now);- const deliveryId = ScheduledTaskWebhookDeliveryId.make(- request.relayDeliveryId === undefined- ? `delivery:${yield* crypto- .randomUUIDv4()- .pipe(- Effect.mapError((cause) =>- taskError("Could not generate delivery id.", { cause }),- ),- )}`- : `delivery:relay:${request.relayDeliveryId}`,- );- // Claimed in its own table, kept longer than the relay holds a request,- // because the delivery log is trimmed. A rate-limited delivery stays- // held on the relay, so it must give up its claim or the next pass- // would treat it as already delivered.- let claimAcquired = false;- const releaseClaim = <A>(result: A) =>- !claimAcquired || request.relayDeliveryId === undefined- ? Effect.succeed(result)- : sql`+ const now = yield* localNow;+ // Anyone can reach the tunnel directly and set the relay's header, so+ // a receive time is never later than now: a future one would pin the+ // delivery in the log and slip past the task's max age.+ const receivedAt =+ request.receivedAt === undefined+ ? now+ : DateTime.min(+ Option.getOrElse(DateTime.make(request.receivedAt), () => now),+ now,+ );+ const observe = (outcome: WebhookDeliveryOutcome) =>+ observeDelivery(request, outcome, receivedAt, now);+ const deliveryId = ScheduledTaskWebhookDeliveryId.make(+ request.relayDeliveryId === undefined+ ? `delivery:${yield* crypto+ .randomUUIDv4()+ .pipe(+ Effect.mapError((cause) => taskError("Could not generate delivery id.", { cause })),+ )}`+ : `delivery:relay:${request.relayDeliveryId}`,+ );+ // Claimed in its own table, kept longer than the relay holds a request,+ // because the delivery log is trimmed. A rate-limited delivery stays+ // held on the relay, so it must give up its claim or the next pass+ // would treat it as already delivered.+ let claimAcquired = false;+ const releaseClaim = <A>(result: A) =>+ !claimAcquired || request.relayDeliveryId === undefined+ ? Effect.succeed(result)+ : sql`DELETE FROM scheduled_task_webhook_relay_deliveriesWHERE relay_delivery_id = ${request.relayDeliveryId}`.pipe(Effect.ignore, Effect.as(result));- // From the claim until the run is forked nothing may interrupt: a- // request dropped in between (the relay hangs up after its timeout)- // would leave a claimed delivery that never runs, or a queue slot that- // is never released.- return yield* Effect.uninterruptible(- Effect.gen(function* () {- if (request.relayDeliveryId !== undefined) {- const claimed = yield* sql<{ relay_delivery_id: string }>`+ // From the claim until the run is forked nothing may interrupt: a+ // request dropped in between (the relay hangs up after its timeout)+ // would leave a claimed delivery that never runs, or a queue slot that+ // is never released.+ return yield* Effect.uninterruptible(+ Effect.gen(function* () {+ if (request.relayDeliveryId !== undefined) {+ const claimed = yield* sql<{ relay_delivery_id: string }>`INSERT INTO scheduled_task_webhook_relay_deliveries(relay_delivery_id, task_id, seen_at)VALUES (${request.relayDeliveryId}, ${task.id}, ${iso(now)})ON CONFLICT (relay_delivery_id) DO NOTHINGRETURNING relay_delivery_id`.pipe(- Effect.mapError((cause) =>- taskError("Could not record webhook delivery.", { taskId: task.id, cause }),- ),- );- if (claimed.length === 0) {- yield* observe("duplicate");- return { _tag: "accepted" as const, deliveryId, outcome: "duplicate" as const };- }- claimAcquired = true;- yield* sql`+ Effect.mapError((cause) =>+ taskError("Could not record webhook delivery.", { taskId: task.id, cause }),+ ),+ );+ if (claimed.length === 0) {+ yield* observe("duplicate");+ return { _tag: "accepted" as const, deliveryId, outcome: "duplicate" as const };+ }+ claimAcquired = true;+ yield* sql`DELETE FROM scheduled_task_webhook_relay_deliveriesWHERE seen_at < ${iso(DateTime.subtract(now, { hours: 48 }))}`.pipe(Effect.ignore);- }- const log = (- outcome: ScheduledTaskWebhookDeliveryOutcome,- details: {- readonly signatureVerified?: boolean;- readonly missing?: ReadonlyArray<string>;- readonly renderedPrompt?: string;- readonly error?: string;- } = {},- ) =>- recordDelivery({- id: deliveryId,- taskId: task.id,- receivedAt: iso(receivedAt),- request,- outcome,- signatureVerified: details.signatureVerified ?? false,- missing: details.missing ?? [],- renderedPrompt: details.renderedPrompt ?? null,- ...(details.error === undefined ? {} : { error: details.error }),- });-- // Only the first rejected request in a window is logged, so a flood- // cannot write rows or push the real deliveries out of the log.- const slot = yield* takeRateSlot(task.id, DateTime.toEpochMillis(now));- if (slot !== "allowed") {- if (slot === "first_rejected") yield* log("rate_limited");- yield* observe("rate_limited");- return yield* releaseClaim({- _tag: "rate_limited" as const,- outcome: "rate_limited" as const,- });- }- if (!task.enabled) {- yield* log("disabled");- yield* observe("disabled");- return { _tag: "disabled" as const };- }- const signature = schedule.signature;- if (signature !== null) {- const verified =- row.webhook_secret !== null &&- verifyWebhookSignature({- signature,- secret: row.webhook_secret,- headers: request.headers,- body: request.body,- });- if (!verified) {- yield* log("rejected_signature");- yield* observe("rejected_signature");- return { _tag: "rejected_signature" as const };- }- }- const maxAgeMinutes = schedule.maxDeliveryAgeMinutes ?? null;- if (- maxAgeMinutes !== null &&- DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt) >- maxAgeMinutes * 60_000- ) {- yield* log("expired", { signatureVerified: signature !== null });- yield* observe("expired");- return { _tag: "expired" as const };- }+ }+ const log = (+ outcome: ScheduledTaskWebhookDeliveryOutcome,+ details: {+ readonly signatureVerified?: boolean;+ readonly missing?: ReadonlyArray<string>;+ readonly renderedPrompt?: string;+ readonly error?: string;+ } = {},+ ) =>+ recordDelivery({+ id: deliveryId,+ taskId: task.id,+ receivedAt: iso(receivedAt),+ request,+ outcome,+ signatureVerified: details.signatureVerified ?? false,+ missing: details.missing ?? [],+ renderedPrompt: details.renderedPrompt ?? null,+ ...(details.error === undefined ? {} : { error: details.error }),+ });- const frameId = yield* crypto.randomBytes(6).pipe(- Effect.map((bytes) => Buffer.from(bytes).toString("hex")),- Effect.mapError((cause) => taskError("Could not generate frame id.", { cause })),- );- const rendered = renderWebhookPrompt(task.prompt, request, frameId);- // Providers trim the prompt before checking, so whitespace around- // it is free.- if (rendered.prompt.trim().length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) {- yield* log("dispatch_failed", {- signatureVerified: signature !== null,- missing: rendered.missing,- renderedPrompt: rendered.prompt,- error: "The filled-in prompt is too long.",- });- yield* observe("prompt_too_long");- return { _tag: "accepted" as const, deliveryId, outcome: "prompt_too_long" as const };- }- // Bound the deliveries one task holds, so steady traffic to a stuck- // task cannot pile up parked fibers.- const queueKey = `${task.id}\u0000${task.createdAt}`;- const queued = yield* Ref.modify(webhookQueued, (counts) => {- const count = counts.get(queueKey) ?? 0;- return count >= WEBHOOK_MAX_QUEUED_PER_TASK- ? ([false, counts] as const)- : ([true, new Map(counts).set(queueKey, count + 1)] as const);+ // Only the first rejected request in a window is logged, so a flood+ // cannot write rows or push the real deliveries out of the log.+ const slot = yield* takeRateSlot(task.id, DateTime.toEpochMillis(now));+ if (slot !== "allowed") {+ if (slot === "first_rejected") yield* log("rate_limited");+ yield* observe("rate_limited");+ return yield* releaseClaim({+ _tag: "rate_limited" as const,+ outcome: "rate_limited" as const,});- if (!queued) {- yield* observe("queue_full");- return yield* releaseClaim({- _tag: "rate_limited" as const,- outcome: "queue_full" as const,+ }+ if (!task.enabled) {+ yield* log("disabled");+ yield* observe("disabled");+ return { _tag: "disabled" as const };+ }+ const signature = schedule.signature;+ if (signature !== null) {+ const verified =+ row.webhook_secret !== null &&+ verifyWebhookSignature({+ signature,+ secret: row.webhook_secret,+ headers: request.headers,+ body: request.body,});+ if (!verified) {+ yield* log("rejected_signature");+ yield* observe("rejected_signature");+ return { _tag: "rejected_signature" as const };}- const release = Ref.update(webhookQueued, (counts) => {- const next = new Map(counts);- const count = (next.get(queueKey) ?? 1) - 1;- if (count <= 0) next.delete(queueKey);- else next.set(queueKey, count);- return next;- });- yield* log("accepted", {+ }+ const maxAgeMinutes = schedule.maxDeliveryAgeMinutes ?? null;+ if (+ maxAgeMinutes !== null &&+ DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt) >+ maxAgeMinutes * 60_000+ ) {+ yield* log("expired", { signatureVerified: signature !== null });+ yield* observe("expired");+ return { _tag: "expired" as const };+ }++ const frameId = yield* crypto.randomBytes(6).pipe(+ Effect.map((bytes) => Buffer.from(bytes).toString("hex")),+ Effect.mapError((cause) => taskError("Could not generate frame id.", { cause })),+ );+ const rendered = renderWebhookPrompt(task.prompt, request, frameId);+ // Providers trim the prompt before checking, so whitespace around+ // it is free.+ if (rendered.prompt.trim().length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) {+ yield* log("dispatch_failed", {signatureVerified: signature !== null,missing: rendered.missing,renderedPrompt: rendered.prompt,- }).pipe(Effect.onError(() => release));- yield* observe("accepted");- const permit = yield* webhookPermit(task.id);- const runOutcome = (outcome: "started" | "skipped" | "failed") =>- Effect.all([- Effect.annotateCurrentSpan({ "scheduled_task.webhook.run_outcome": outcome }),- Metrics.increment(Metrics.webhookRunsTotal, { outcome }),- ]);- yield* runTask(task, "webhook", { deliveryId, prompt: rendered.prompt }).pipe(- Effect.flatMap((completed) =>- completed.lastRunStatus === "failed"- ? runOutcome("failed").pipe(- Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")),- )- : runOutcome("started"),- ),- Effect.catchTags({- WebhookDeliverySkipped: (skipped) =>- runOutcome("skipped").pipe(- Effect.andThen(markDeliveryFailed(deliveryId, skipped.reason)),- ),- }),- // The log is readable over RPC, so it gets a fixed reason; the- // cause, which can carry request data, stays in the server log.- Effect.catchCause((cause) =>- Effect.logWarning("Webhook dispatch failed", { taskId: task.id, cause }).pipe(- Effect.andThen(runOutcome("failed")),- Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")),+ error: "The filled-in prompt is too long.",+ });+ yield* observe("prompt_too_long");+ return { _tag: "accepted" as const, deliveryId, outcome: "prompt_too_long" as const };+ }+ // Bound the deliveries one task holds, so steady traffic to a stuck+ // task cannot pile up parked fibers.+ const queueKey = `${task.id}\u0000${task.createdAt}`;+ const queued = yield* Ref.modify(webhookQueued, (counts) => {+ const count = counts.get(queueKey) ?? 0;+ return count >= WEBHOOK_MAX_QUEUED_PER_TASK+ ? ([false, counts] as const)+ : ([true, new Map(counts).set(queueKey, count + 1)] as const);+ });+ if (!queued) {+ yield* observe("queue_full");+ return yield* releaseClaim({+ _tag: "rate_limited" as const,+ outcome: "queue_full" as const,+ });+ }+ const release = Ref.update(webhookQueued, (counts) => {+ const next = new Map(counts);+ const count = (next.get(queueKey) ?? 1) - 1;+ if (count <= 0) next.delete(queueKey);+ else next.set(queueKey, count);+ return next;+ });+ yield* log("accepted", {+ signatureVerified: signature !== null,+ missing: rendered.missing,+ renderedPrompt: rendered.prompt,+ }).pipe(Effect.onError(() => release));+ yield* observe("accepted");+ const permit = yield* webhookPermit(task.id);+ const runOutcome = (outcome: "started" | "skipped" | "failed") =>+ Effect.all([+ Effect.annotateCurrentSpan({ "scheduled_task.webhook.run_outcome": outcome }),+ Metrics.increment(Metrics.webhookRunsTotal, { outcome }),+ ]);+ yield* runTask(task, "webhook", { deliveryId, prompt: rendered.prompt }).pipe(+ Effect.flatMap((completed) =>+ completed.lastRunStatus === "failed"+ ? runOutcome("failed").pipe(+ Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")),+ )+ : runOutcome("started"),+ ),+ Effect.catchTags({+ WebhookDeliverySkipped: (skipped) =>+ runOutcome("skipped").pipe(+ Effect.andThen(markDeliveryFailed(deliveryId, skipped.reason)),),+ }),+ // The log is readable over RPC, so it gets a fixed reason; the+ // cause, which can carry request data, stays in the server log.+ Effect.catchCause((cause) =>+ Effect.logWarning("Webhook dispatch failed", { taskId: task.id, cause }).pipe(+ Effect.andThen(runOutcome("failed")),+ Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")),),- permit.withPermits(1),- Effect.withSpan("ScheduledTaskService.runWebhookDelivery", {- root: true,- attributes: {- "scheduled_task.id": task.id,- "scheduled_task.webhook.delivery_id": deliveryId,- },- }),- Effect.ensuring(release),- Effect.forkIn(serviceScope),- );- // Dispatch owns the accepted delivery now; retries must keep its claim.- claimAcquired = false;- return { _tag: "accepted" as const, deliveryId, outcome: "accepted" as const };- }).pipe(Effect.onError(() => releaseClaim(undefined))),- );- });+ ),+ permit.withPermits(1),+ Effect.withSpan("ScheduledTaskService.runWebhookDelivery", {+ root: true,+ attributes: {+ "scheduled_task.id": task.id,+ "scheduled_task.webhook.delivery_id": deliveryId,+ },+ }),+ Effect.ensuring(release),+ Effect.forkIn(serviceScope),+ );+ // Dispatch owns the accepted delivery now; retries must keep its claim.+ claimAcquired = false;+ return { _tag: "accepted" as const, deliveryId, outcome: "accepted" as const };+ }).pipe(Effect.onError(() => releaseClaim(undefined))),+ );+ });return ScheduledTaskService.of({list,diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.tsindex 41a2cc11935..ae8594a03f0 100644--- a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts@@ -15,6 +15,7 @@ import * as EffectScheduler from "effect/Scheduler";import * as Schema from "effect/Schema";import * as SqlClient from "effect/sql/SqlClient";import * as TestClock from "effect/testing/TestClock";+import * as Tracer from "effect/Tracer";import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";@@ -881,6 +882,33 @@ const deliveriesCounted = (outcome: string, source: "relay" | "direct") =>}),);+it.effect("keeps delivery attributes on the webhook operation span", () =>+ withService(({ service }) =>+ Effect.gen(function* () {+ const { task } = yield* service.upsert(yield* webhookTaskInput({ enabled: false }));+ const spans: Tracer.NativeSpan[] = [];+ const tracer = Tracer.make({+ span: (options) => {+ const span = new Tracer.NativeSpan(options);+ spans.push(span);+ return span;+ },+ });+ const receivedAt = DateTime.formatIso(DateTime.subtract(yield* DateTime.now, { seconds: 1 }));+ yield* service+ .triggerWebhook(requestFor(task, { receivedAt, relayDeliveryId: "traced-delivery" }))+ .pipe(Effect.withTracer(tracer));++ const span = spans.find((entry) => entry.name === "ScheduledTaskService.triggerWebhook");+ assert.isDefined(span);+ assert.equal(span?.attributes.get("scheduled_task.id"), task.id);+ assert.equal(span?.attributes.get("scheduled_task.webhook.outcome"), "disabled");+ assert.equal(span?.attributes.get("scheduled_task.webhook.source"), "relay");+ assert.equal(span?.attributes.get("scheduled_task.webhook.held_ms"), 1_000);+ }),+ ),+);+it.effect("counts each handled request by what happened to it", () =>withService(({ service, launches }) =>Effect.gen(function* () {diff --git a/apps/server/src/scheduledTasks/webhookRoute.ts b/apps/server/src/scheduledTasks/webhookRoute.tsindex aa1b25a6351..ce67fa157d3 100644--- a/apps/server/src/scheduledTasks/webhookRoute.ts+++ b/apps/server/src/scheduledTasks/webhookRoute.ts@@ -33,98 +33,98 @@ export const layer = HttpApiBuilder.group(* The endpoint is raw so the signature is checked over the exact body* bytes; the service checks the token and signature.*/- const handler = ({+ // Only verified relay deliveries join a trace; direct requests keep their existing context.+ const handler = Effect.fnUntraced(function* ({params,request,}: {readonly params: { readonly hookId: string; readonly token: string };readonly request: HttpServerRequest.HttpServerRequest;- }) =>- Effect.gen(function* () {- const contentLength = Number(request.headers["content-length"] ?? "0");- if (!Number.isFinite(contentLength) || contentLength > WEBHOOK_MAX_BODY_BYTES) {- return json(413, { error: "body_too_large" }, "body_too_large");- }- // Chunked requests carry no content-length, so the reader itself is capped.- const body = yield* request.arrayBuffer.pipe(- Effect.map((buffer) => new Uint8Array(buffer)),- Effect.provideService(- HttpIncomingMessage.MaxBodySize,- ByteSize.bytes(WEBHOOK_MAX_BODY_BYTES),- ),- Effect.option,- );- const tooLarge = (error: string) =>- Metrics.increment(Metrics.webhookDeliveriesTotal, {- outcome: "body_too_large",- source: request.headers["x-t3-relay-delivery-id"] ? "relay" : "direct",- }).pipe(Effect.as(json(413, { error }, "body_too_large")));- if (Option.isNone(body)) return yield* tooLarge("body_too_large_or_unreadable");- if (body.value.byteLength > WEBHOOK_MAX_BODY_BYTES) {- return yield* tooLarge("body_too_large");- }+ }) {+ const contentLength = Number(request.headers["content-length"] ?? "0");+ if (!Number.isFinite(contentLength) || contentLength > WEBHOOK_MAX_BODY_BYTES) {+ return json(413, { error: "body_too_large" }, "body_too_large");+ }+ // Chunked requests carry no content-length, so the reader itself is capped.+ const body = yield* request.arrayBuffer.pipe(+ Effect.map((buffer) => new Uint8Array(buffer)),+ Effect.provideService(+ HttpIncomingMessage.MaxBodySize,+ ByteSize.bytes(WEBHOOK_MAX_BODY_BYTES),+ ),+ Effect.option,+ );+ const tooLarge = (error: string) =>+ Metrics.increment(Metrics.webhookDeliveriesTotal, {+ outcome: "body_too_large",+ source: request.headers["x-t3-relay-delivery-id"] ? "relay" : "direct",+ }).pipe(Effect.as(json(413, { error }, "body_too_large")));+ if (Option.isNone(body)) return yield* tooLarge("body_too_large_or_unreadable");+ if (body.value.byteLength > WEBHOOK_MAX_BODY_BYTES) {+ return yield* tooLarge("body_too_large");+ }- const headers: Record<string, string> = {};- for (const [name, value] of Object.entries(request.headers)) {- if (typeof value === "string") headers[name.toLowerCase()] = value;- }- const queryIndex = request.url.indexOf("?");- // The relay's delivery id and receive time count only with its signed- // proof; the URL can also be called directly. The receive time matters- // for requests the relay held while we were offline.- const relay = yield* relayDeliveryProof.verify({ headers, hookId: params.hookId });- const relayDeliveryId = Option.isSome(relay) ? relay.value.deliveryId : undefined;- const relayReceivedAt = Option.isSome(relay) ? relay.value.receivedAt : undefined;+ const headers: Record<string, string> = {};+ for (const [name, value] of Object.entries(request.headers)) {+ if (typeof value === "string") headers[name.toLowerCase()] = value;+ }+ const queryIndex = request.url.indexOf("?");+ // The relay's delivery id and receive time count only with its signed+ // proof; the URL can also be called directly. The receive time matters+ // for requests the relay held while we were offline.+ const relay = yield* relayDeliveryProof.verify({ headers, hookId: params.hookId });+ const relayDeliveryId = Option.isSome(relay) ? relay.value.deliveryId : undefined;+ const relayReceivedAt = Option.isSome(relay) ? relay.value.receivedAt : undefined;- // A relay delivery joins the relay's trace, and goes to the T3 Connect- // tracer with it. Anyone else's traceparent is never trusted.- const relayParent = Option.isSome(relay)- ? HttpTraceContext.fromHeaders(request.headers)- : Option.none<Tracer.ExternalSpan>();- const result = yield* scheduledTasks- .triggerWebhook({- hookId: params.hookId,- token: params.token,- method: request.method,- path: `${ScheduledTaskService.WEBHOOK_ROUTE_PREFIX}/${encodeURIComponent(params.hookId)}`,- query: queryIndex === -1 ? "" : request.url.slice(queryIndex + 1),- headers,- body: body.value,- bodyText: new TextDecoder().decode(body.value),- ...(relayDeliveryId ? { relayDeliveryId } : {}),- ...(relayReceivedAt ? { receivedAt: relayReceivedAt } : {}),- })- .pipe(- Option.isSome(relayParent)- ? (effect) =>- effect.pipe(Effect.withParentSpan(relayParent.value), withRelayClientTracing)- : (effect) => effect,- Effect.catchCause((cause) =>- Effect.logWarning("Webhook delivery failed").pipe(- Effect.annotateLogs({ hookId: params.hookId }),- Effect.andThen(Effect.logDebug("Webhook delivery failure cause", { cause })),- Effect.as({ _tag: "error" as const }),- ),+ // A relay delivery joins the relay's trace, and goes to the T3 Connect+ // tracer with it. Anyone else's traceparent is never trusted.+ const relayParent = Option.isSome(relay)+ ? HttpTraceContext.fromHeaders(request.headers)+ : Option.none<Tracer.ExternalSpan>();+ const result = yield* scheduledTasks+ .triggerWebhook({+ hookId: params.hookId,+ token: params.token,+ method: request.method,+ path: `${ScheduledTaskService.WEBHOOK_ROUTE_PREFIX}/${encodeURIComponent(params.hookId)}`,+ query: queryIndex === -1 ? "" : request.url.slice(queryIndex + 1),+ headers,+ body: body.value,+ bodyText: new TextDecoder().decode(body.value),+ ...(relayDeliveryId ? { relayDeliveryId } : {}),+ ...(relayReceivedAt ? { receivedAt: relayReceivedAt } : {}),+ })+ .pipe(+ Option.isSome(relayParent)+ ? (effect) =>+ effect.pipe(Effect.withParentSpan(relayParent.value), withRelayClientTracing)+ : (effect) => effect,+ Effect.catchCause((cause) =>+ Effect.logWarning("Webhook delivery failed").pipe(+ Effect.annotateLogs({ hookId: params.hookId }),+ Effect.andThen(Effect.logDebug("Webhook delivery failure cause", { cause })),+ Effect.as({ _tag: "error" as const }),),- );+ ),+ );- switch (result._tag) {- case "accepted":- return json(202, { deliveryId: result.deliveryId }, result.outcome);- case "not_found":- return json(404, { error: "hook_not_found" }, "not_found");- case "rejected_signature":- return json(401, { error: "invalid_signature" }, "rejected_signature");- case "disabled":- return json(409, { error: "hook_disabled" }, "disabled");- case "rate_limited":- return json(429, { error: "rate_limited" }, result.outcome);- case "expired":- return json(410, { error: "delivery_too_old" }, "expired");- case "error":- return json(500, { error: "internal_error" }, "error");- }- });+ switch (result._tag) {+ case "accepted":+ return json(202, { deliveryId: result.deliveryId }, result.outcome);+ case "not_found":+ return json(404, { error: "hook_not_found" }, "not_found");+ case "rejected_signature":+ return json(401, { error: "invalid_signature" }, "rejected_signature");+ case "disabled":+ return json(409, { error: "hook_disabled" }, "disabled");+ case "rate_limited":+ return json(429, { error: "rate_limited" }, result.outcome);+ case "expired":+ return json(410, { error: "delivery_too_old" }, "expired");+ case "error":+ return json(500, { error: "internal_error" }, "error");+ }+ });return handlers.handleRaw("webhookPost", handler).handleRaw("webhookPut", handler)diff --git a/apps/server/src/secrets/SecretRequests.ts b/apps/server/src/secrets/SecretRequests.tsindex fadad6ea743..4470c257f67 100644--- a/apps/server/src/secrets/SecretRequests.ts+++ b/apps/server/src/secrets/SecretRequests.ts@@ -73,8 +73,8 @@ const make = Effect.gen(function* () {yield* store.getOrCreateRandom("secret-request-salt", 32).pipe(Effect.orDie),).toString("hex");- const answer: SecretRequests["Service"]["answer"] = (input) =>- Effect.gen(function* () {+ const answer: SecretRequests["Service"]["answer"] = Effect.fn("SecretRequests.answer")(+ function* (input) {yield* Effect.annotateCurrentSpan({"orchestration_v2.thread_id": input.threadId,"secret_request.answer": input.answer.type,@@ -159,14 +159,16 @@ const make = Effect.gen(function* () {yield* removeLogged(storeName(refFor(salt, input.threadId, item.id)));return yield* new SecretRequestError({ reason: "agent_stopped" });}- }).pipe(Effect.withSpan("SecretRequests.answer"));+ },+ );- const savedRef: SecretRequests["Service"]["savedRef"] = (input) =>- Effect.gen(function* () {+ const savedRef: SecretRequests["Service"]["savedRef"] = Effect.fn("SecretRequests.savedRef")(+ function* (input) {const ref = refFor(salt, input.threadId, input.turnItemId);const stored = yield* store.get(storeName(ref)).pipe(Effect.orElseSucceed(Option.none));return Option.map(stored, () => ref);- });+ },+ );const removeLogged = (name: string) =>store.remove(name).pipe(@@ -191,30 +193,32 @@ const make = Effect.gen(function* () {Effect.withSpan("SecretRequests.consume"),);- const consumeRef = (input: { readonly ref: SecretRef; readonly projectId: ProjectId }) =>- Effect.gen(function* () {- if (!REF_PATTERN.test(input.ref))- return yield* new SecretRequestError({ reason: "invalid_ref" });- const stored = yield* store- .get(storeName(input.ref))- .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "read_failed", cause })));- const decoded = Option.flatMap(stored, (bytes) =>- decodeStored(new TextDecoder().decode(bytes)),- );- if (Option.isNone(decoded) || decoded.value.projectId !== input.projectId) {- return yield* new SecretRequestError({ reason: "ref_unavailable" });- }- if ((yield* Clock.currentTimeMillis) - decoded.value.savedAt > SECRET_REF_TTL_MS) {- yield* removeLogged(storeName(input.ref));- return yield* new SecretRequestError({ reason: "ref_expired" });- }- // One use: the value moves into whatever consumed it. If it cannot be- // deleted, it is not handed out, so a ref is never used twice.- if (!(yield* removeLogged(storeName(input.ref)))) {- return yield* new SecretRequestError({ reason: "consume_failed" });- }- return decoded.value.value;- });+ const consumeRef = Effect.fn("SecretRequests.consumeRef")(function* (input: {+ readonly ref: SecretRef;+ readonly projectId: ProjectId;+ }) {+ if (!REF_PATTERN.test(input.ref))+ return yield* new SecretRequestError({ reason: "invalid_ref" });+ const stored = yield* store+ .get(storeName(input.ref))+ .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "read_failed", cause })));+ const decoded = Option.flatMap(stored, (bytes) =>+ decodeStored(new TextDecoder().decode(bytes)),+ );+ if (Option.isNone(decoded) || decoded.value.projectId !== input.projectId) {+ return yield* new SecretRequestError({ reason: "ref_unavailable" });+ }+ if ((yield* Clock.currentTimeMillis) - decoded.value.savedAt > SECRET_REF_TTL_MS) {+ yield* removeLogged(storeName(input.ref));+ return yield* new SecretRequestError({ reason: "ref_expired" });+ }+ // One use: the value moves into whatever consumed it. If it cannot be+ // deleted, it is not handed out, so a ref is never used twice.+ if (!(yield* removeLogged(storeName(input.ref)))) {+ return yield* new SecretRequestError({ reason: "consume_failed" });+ }+ return decoded.value.value;+ });const sweepExpired = Effect.gen(function* () {if (store.directory === undefined) return;diff --git a/apps/server/src/serverActivation.ts b/apps/server/src/serverActivation.tsindex c43cd259ef6..2945951d847 100644--- a/apps/server/src/serverActivation.ts+++ b/apps/server/src/serverActivation.ts@@ -9,21 +9,20 @@ export class ServerActivation extends Context.Reference<Effect.Effect<void> | un{ defaultValue: () => undefined },) {}-export const forkParkedFiber = <A, E, R>(+export const forkParkedFiber = Effect.fn("serverActivation.forkParkedFiber")(function* <A, E, R>(effect: Effect.Effect<A, E, R>,-): Effect.Effect<Fiber.Fiber<A, E>, never, Scope.Scope | R> =>- Effect.gen(function* () {- const activation = yield* ServerActivation;- if (activation === undefined) {- return yield* Effect.forkScoped(effect);- }- const parked = yield* Deferred.make<void>();- const fiber = yield* Effect.forkScoped(- Deferred.succeed(parked, undefined).pipe(Effect.andThen(activation), Effect.andThen(effect)),- );- yield* Deferred.await(parked);- return fiber;- });+): Effect.fn.Return<Fiber.Fiber<A, E>, never, Scope.Scope | R> {+ const activation = yield* ServerActivation;+ if (activation === undefined) {+ return yield* Effect.forkScoped(effect);+ }+ const parked = yield* Deferred.make<void>();+ const fiber = yield* Effect.forkScoped(+ Deferred.succeed(parked, undefined).pipe(Effect.andThen(activation), Effect.andThen(effect)),+ );+ yield* Deferred.await(parked);+ return fiber;+});export const forkParked = <A, E, R>(effect: Effect.Effect<A, E, R>,diff --git a/apps/server/src/serverRuntimeState.ts b/apps/server/src/serverRuntimeState.tsindex 140020614fd..abc16c16016 100644--- a/apps/server/src/serverRuntimeState.ts+++ b/apps/server/src/serverRuntimeState.ts@@ -85,30 +85,31 @@ export const persistServerRuntimeState = (input: {),);-export const clearPersistedServerRuntimeState = (path: string) =>- Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- yield* fs.remove(path, { force: true }).pipe(- Effect.mapError(- (cause) =>- new ServerRuntimeStateError({- operation: "clear",- statePath: path,- cause,+export const clearPersistedServerRuntimeState = Effect.fn(+ "serverRuntimeState.clearPersistedServerRuntimeState",+)(function* (path: string) {+ const fs = yield* FileSystem.FileSystem;+ yield* fs.remove(path, { force: true }).pipe(+ Effect.mapError(+ (cause) =>+ new ServerRuntimeStateError({+ operation: "clear",+ statePath: path,+ cause,+ }),+ ),+ Effect.catchTags({+ ServerRuntimeStateError: (error) =>+ Effect.logWarning(error.message).pipe(+ Effect.annotateLogs({+ operation: error.operation,+ statePath: error.statePath,+ cause: error,}),- ),- Effect.catchTags({- ServerRuntimeStateError: (error) =>- Effect.logWarning(error.message).pipe(- Effect.annotateLogs({- operation: error.operation,- statePath: error.statePath,- cause: error,- }),- ),- }),- );- });+ ),+ }),+ );+});/*** Signal 0 delivers nothing; it only reports whether the pid exists. EPERM@@ -124,8 +125,10 @@ export const isProcessAlive = (pid: number): boolean => {}};-export const readPersistedServerRuntimeState = (path: string) =>- Effect.gen(function* () {+export const readPersistedServerRuntimeState = Effect.fn(+ "serverRuntimeState.readPersistedServerRuntimeState",+)(+ function* (path: string) {const fs = yield* FileSystem.FileSystem;const raw = yield* fs.readFileString(path).pipe(Effect.matchEffect({@@ -162,16 +165,16 @@ export const readPersistedServerRuntimeState = (path: string) =>}),),);- }).pipe(- Effect.catchTags({- ServerRuntimeStateError: (error) =>- Effect.logWarning(error.message).pipe(- Effect.annotateLogs({- operation: error.operation,- statePath: error.statePath,- cause: error,- }),- Effect.as(Option.none<PersistedServerRuntimeState>()),- ),- }),- );+ },+ Effect.catchTags({+ ServerRuntimeStateError: (error) =>+ Effect.logWarning(error.message).pipe(+ Effect.annotateLogs({+ operation: error.operation,+ statePath: error.statePath,+ cause: error,+ }),+ Effect.as(Option.none<PersistedServerRuntimeState>()),+ ),+ }),+);diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.tsindex 8c4d70758c4..5289b7b4d75 100644--- a/apps/server/src/serverSettings.ts+++ b/apps/server/src/serverSettings.ts@@ -203,62 +203,59 @@ export class ServerSettingsService extends Context.Service<static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) => layerTest(overrides);}-const makeTest = (overrides: DeepPartial<ServerSettings> = {}) =>- Effect.gen(function* () {- const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =- overrides;- const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);- const initialSettings = yield* normalizeServerSettings({- ...merged,- ...(automaticGitFetchInterval !== undefined- ? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }- : {}),- ...(providerHealthRefreshInterval !== undefined- ? { providerHealthRefreshInterval: providerHealthRefreshInterval as Duration.Duration }- : {}),- });- const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);- const writeSemaphore = yield* Semaphore.make(1);- const getSettings = Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider));-- const updateTestSettings = (- update: (current: ServerSettings) => Effect.Effect<ServerSettings, ServerSettingsError>,- ): Effect.Effect<ServerSettings, ServerSettingsError> =>- writeSemaphore.withPermits(1)(- Ref.get(currentSettingsRef).pipe(- Effect.flatMap(update),- Effect.flatMap(normalizeServerSettings),- Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),- Effect.map(resolveTextGenerationProvider),- ),- );-- return {- start: Effect.void,- ready: Effect.void,- getSettings,- updateSettings: (patch) =>- updateTestSettings((currentSettings) =>- Effect.succeed(applyServerSettingsPatch(currentSettings, patch)),- ),- updateProviderInstance: (mutation, patch = {}) =>- updateTestSettings((currentSettings) =>- Effect.gen(function* () {- yield* ensureProviderInstanceMutationAllowed(- currentSettings,- mutation,- "test settings",- );- const patched = applyServerSettingsPatch(currentSettings, patch);- return applyProviderInstanceMutation(patched, mutation);- }),- ),- withSettingsSnapshot: (use) =>- writeSemaphore.withPermits(1)(getSettings.pipe(Effect.flatMap(use))),- streamChanges: Stream.empty,- subscribeChanges: Effect.succeed(Stream.empty),- } satisfies ServerSettingsService["Service"];+const makeTest = Effect.fn("serverSettings.makeTest")(function* (+ overrides: DeepPartial<ServerSettings> = {},+) {+ const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =+ overrides;+ const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);+ const initialSettings = yield* normalizeServerSettings({+ ...merged,+ ...(automaticGitFetchInterval !== undefined+ ? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }+ : {}),+ ...(providerHealthRefreshInterval !== undefined+ ? { providerHealthRefreshInterval: providerHealthRefreshInterval as Duration.Duration }+ : {}),});+ const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);+ const writeSemaphore = yield* Semaphore.make(1);+ const getSettings = Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider));++ const updateTestSettings = (+ update: (current: ServerSettings) => Effect.Effect<ServerSettings, ServerSettingsError>,+ ): Effect.Effect<ServerSettings, ServerSettingsError> =>+ writeSemaphore.withPermits(1)(+ Ref.get(currentSettingsRef).pipe(+ Effect.flatMap(update),+ Effect.flatMap(normalizeServerSettings),+ Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),+ Effect.map(resolveTextGenerationProvider),+ ),+ );++ return {+ start: Effect.void,+ ready: Effect.void,+ getSettings,+ updateSettings: (patch) =>+ updateTestSettings((currentSettings) =>+ Effect.succeed(applyServerSettingsPatch(currentSettings, patch)),+ ),+ updateProviderInstance: (mutation, patch = {}) =>+ updateTestSettings((currentSettings) =>+ Effect.gen(function* () {+ yield* ensureProviderInstanceMutationAllowed(currentSettings, mutation, "test settings");+ const patched = applyServerSettingsPatch(currentSettings, patch);+ return applyProviderInstanceMutation(patched, mutation);+ }),+ ),+ withSettingsSnapshot: (use) =>+ writeSemaphore.withPermits(1)(getSettings.pipe(Effect.flatMap(use))),+ streamChanges: Stream.empty,+ subscribeChanges: Effect.succeed(Stream.empty),+ } satisfies ServerSettingsService["Service"];+});export const layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>Layer.effect(ServerSettingsService, makeTest(overrides));@@ -625,8 +622,8 @@ const make = Effect.gen(function* () {),);- const moveInlineSettingsSecrets = (settings: ServerSettings) =>- Effect.gen(function* () {+ const moveInlineSettingsSecrets = Effect.fn("serverSettings.moveInlineSettingsSecrets")(+ function* (settings: ServerSettings) {const pending: SettingsSecret[] = [];mapSettingsSecrets(settings, (secret) => {if (secret.kind === "field" && !secret.redacted && secret.value.length > 0) {@@ -652,7 +649,8 @@ const make = Effect.gen(function* () {return mapSettingsSecrets(settings, (secret) =>moved.has(secret.secretName) ? { value: "", redacted: true } : secret,);- });+ },+ );const loadSettingsFromDisk = Effect.gen(function* () {let settings = DEFAULT_SERVER_SETTINGS;@@ -802,10 +800,8 @@ const make = Effect.gen(function* () {Effect.andThen(Cache.get(settingsCache, cacheKey)),);- const materializeSettingsSecrets = (- settings: ServerSettings,- ): Effect.Effect<ServerSettings, ServerSettingsError> =>- Effect.gen(function* () {+ const materializeSettingsSecrets = Effect.fn("serverSettings.materializeSettingsSecrets")(+ function* (settings: ServerSettings): Effect.fn.Return<ServerSettings, ServerSettingsError> {const storedSecrets = new Map<string, string>();const pending = new Map<string, SettingsSecret>();mapSettingsSecrets(settings, (secret) => {@@ -837,7 +833,8 @@ const make = Effect.gen(function* () {: secret.value,redacted: secret.sensitive && secret.kind === "environment" && secret.redacted,}));- });+ },+ );const materializeChanges = (changes: Stream.Stream<ServerSettings>) =>changes.pipe(diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.tsindex 74d24ffa211..098f53cc254 100644--- a/apps/server/src/storageCleanup.ts+++ b/apps/server/src/storageCleanup.ts@@ -247,8 +247,8 @@ const make = Effect.gen(function* () {);});- const measureWorktree = (worktreePath: string) =>- Effect.gen(function* () {+ const measureWorktree = Effect.fn("storageCleanup.measureWorktree")(+ function* (worktreePath: string) {const root = yield* fs.realPath(worktreePath);const pending = [root];let entries = 1;@@ -289,10 +289,10 @@ const make = Effect.gen(function* () {}}return bytes;- }).pipe(- Effect.timeout("30 seconds"),- Effect.orElseSucceed(() => null),- );+ },+ Effect.timeout("30 seconds"),+ Effect.orElseSucceed(() => null),+ );// The snapshot takes seconds on large databases, so it runs on the reader// worker instead of the event loop.diff --git a/apps/server/src/telemetry/DelegatedTaskAnalytics.ts b/apps/server/src/telemetry/DelegatedTaskAnalytics.tsindex e3f50aef6a8..724a74b5429 100644--- a/apps/server/src/telemetry/DelegatedTaskAnalytics.ts+++ b/apps/server/src/telemetry/DelegatedTaskAnalytics.ts@@ -40,8 +40,9 @@ const make = Effect.gen(function* () {// A task can be re-reported with the same final status; count it once per process.const reported = new Set<string>();- const onSubagent = (event: SubagentEvent) =>- Effect.gen(function* () {+ // Runs for every subagent update; most return early, so avoid a span per event.+ const onSubagent = Effect.fnUntraced(+ function* (event: SubagentEvent) {const task = event.payload;if (task.origin !== "app_owned" || !FINAL_STATUSES.has(task.status)) return;if (reported.has(task.id)) return;@@ -79,7 +80,9 @@ const make = Effect.gen(function* () {});// Only after recording: a failed lookup leaves the next final update to report it.reported.add(task.id);- }).pipe(Effect.ignoreCause);+ },+ (effect) => effect.pipe(Effect.ignoreCause),+ );yield* forkParked(Stream.runForEach(orchestrator.streamDomainEvents, (event) =>diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.tsindex 08651591f1a..858a16aa6f2 100644--- a/apps/server/src/terminal/Manager.ts+++ b/apps/server/src/terminal/Manager.ts@@ -1541,8 +1541,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(funcconst workerScope = yield* Scope.make("sequential");yield* Effect.addFinalizer(() => Scope.close(workerScope, Exit.void));- const publishEvent = (event: TerminalEvent) =>- Effect.gen(function* () {+ const publishEvent =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (event: TerminalEvent) {for (const listener of terminalEventListeners) {yield* listener(event).pipe(Effect.ignoreCause({ log: true }));}@@ -3016,84 +3017,85 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func}),);- const restartResolved = (input: TerminalRestartInput) =>- Effect.gen(function* () {- yield* increment(terminalRestartsTotal, { scope: "thread" });- const terminalId = input.terminalId;- yield* assertValidCwd(input.cwd);-- const sessionKey = toSessionKey(input.threadId, terminalId);- const existingSession = yield* getSession(input.threadId, terminalId);- let session: TerminalSessionState;- if (Option.isNone(existingSession)) {- const cols = input.cols ?? DEFAULT_OPEN_COLS;- const rows = input.rows ?? DEFAULT_OPEN_ROWS;- session = {- threadId: input.threadId,- terminalId,- cwd: input.cwd,- worktreePath: input.worktreePath ?? null,- status: "starting",- pid: null,- history: new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit),- pendingHistoryControlSequence: "",- pendingProcessEvents: [],- pendingProcessEventIndex: 0,- processEventDrainRunning: false,- exitCode: null,- exitSignal: null,- updatedAt: yield* nowIso,- eventSequence: 0,- inputCount: 0,- cols,- rows,- process: null,- unsubscribeData: null,- unsubscribeExit: null,- hasRunningSubprocess: false,- childCommandLabel: null,- runtimeEnv: normalizedRuntimeEnv(input.env),- };- const createdSession = session;- yield* modifyManagerState((state) => {- const sessions = new Map(state.sessions);- sessions.set(sessionKey, createdSession);- closedSessionKeys.delete(sessionKey);- return [undefined, { ...state, sessions }] as const;- });- yield* evictInactiveSessionsIfNeeded();- } else {- session = existingSession.value;- yield* stopProcess(session);- session.cwd = input.cwd;- session.worktreePath = input.worktreePath ?? null;- session.runtimeEnv = normalizedRuntimeEnv(input.env);- }+ const restartResolved = Effect.fn("Manager.restartResolved")(function* (+ input: TerminalRestartInput,+ ) {+ yield* increment(terminalRestartsTotal, { scope: "thread" });+ const terminalId = input.terminalId;+ yield* assertValidCwd(input.cwd);- const cols = input.cols ?? session.cols;- const rows = input.rows ?? session.rows;+ const sessionKey = toSessionKey(input.threadId, terminalId);+ const existingSession = yield* getSession(input.threadId, terminalId);+ let session: TerminalSessionState;+ if (Option.isNone(existingSession)) {+ const cols = input.cols ?? DEFAULT_OPEN_COLS;+ const rows = input.rows ?? DEFAULT_OPEN_ROWS;+ session = {+ threadId: input.threadId,+ terminalId,+ cwd: input.cwd,+ worktreePath: input.worktreePath ?? null,+ status: "starting",+ pid: null,+ history: new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit),+ pendingHistoryControlSequence: "",+ pendingProcessEvents: [],+ pendingProcessEventIndex: 0,+ processEventDrainRunning: false,+ exitCode: null,+ exitSignal: null,+ updatedAt: yield* nowIso,+ eventSequence: 0,+ inputCount: 0,+ cols,+ rows,+ process: null,+ unsubscribeData: null,+ unsubscribeExit: null,+ hasRunningSubprocess: false,+ childCommandLabel: null,+ runtimeEnv: normalizedRuntimeEnv(input.env),+ };+ const createdSession = session;+ yield* modifyManagerState((state) => {+ const sessions = new Map(state.sessions);+ sessions.set(sessionKey, createdSession);+ closedSessionKeys.delete(sessionKey);+ return [undefined, { ...state, sessions }] as const;+ });+ yield* evictInactiveSessionsIfNeeded();+ } else {+ session = existingSession.value;+ yield* stopProcess(session);+ session.cwd = input.cwd;+ session.worktreePath = input.worktreePath ?? null;+ session.runtimeEnv = normalizedRuntimeEnv(input.env);+ }- session.history.clear();- session.pendingHistoryControlSequence = "";- session.pendingProcessEvents = [];- session.pendingProcessEventIndex = 0;- session.processEventDrainRunning = false;- yield* persistHistory(input.threadId, terminalId, session.history);- yield* startSession(- session,- {- threadId: input.threadId,- terminalId,- cwd: input.cwd,- ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),- cols,- rows,- ...(input.env ? { env: input.env } : {}),- },- "restarted",- );- return snapshot(session);- });+ const cols = input.cols ?? session.cols;+ const rows = input.rows ?? session.rows;++ session.history.clear();+ session.pendingHistoryControlSequence = "";+ session.pendingProcessEvents = [];+ session.pendingProcessEventIndex = 0;+ session.processEventDrainRunning = false;+ yield* persistHistory(input.threadId, terminalId, session.history);+ yield* startSession(+ session,+ {+ threadId: input.threadId,+ terminalId,+ cwd: input.cwd,+ ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),+ cols,+ rows,+ ...(input.env ? { env: input.env } : {}),+ },+ "restarted",+ );+ return snapshot(session);+ });const restart: TerminalManager["Service"]["restart"] = (input) =>withThreadLock(diff --git a/apps/server/src/usage/UsageLimitSources.ts b/apps/server/src/usage/UsageLimitSources.tsindex d30b4445ea8..0ba4ecf49b9 100644--- a/apps/server/src/usage/UsageLimitSources.ts+++ b/apps/server/src/usage/UsageLimitSources.ts@@ -74,13 +74,14 @@ export const make = Effect.gen(function* () {return { ...base, accounts: accounts.success };});- const publish = (next: ReadonlyArray<UsageLimitSourceSnapshot>) =>- Effect.gen(function* () {- const changed = yield* Ref.modify(stateRef, (previous) =>- Equal.equals(previous, next) ? [false, previous] : [true, next],- );- if (changed) yield* PubSub.publish(changes, next);- });+ const publish = Effect.fn("UsageLimitSources.publish")(function* (+ next: ReadonlyArray<UsageLimitSourceSnapshot>,+ ) {+ const changed = yield* Ref.modify(stateRef, (previous) =>+ Equal.equals(previous, next) ? [false, previous] : [true, next],+ );+ if (changed) yield* PubSub.publish(changes, next);+ });// One refresh at a time: a slow hub read started before a settings change// must not publish after the change's own refresh and resurrect a removed@@ -102,25 +103,24 @@ export const make = Effect.gen(function* () {}).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true }));// Shares the refresh lock so a stale in-flight read cannot overwrite a redemption.- const consumeResetCredit = (input: UsageLimitSourceConsumeResetCreditInput) =>- Effect.gen(function* () {- const settings = yield* settingsService.getSettings.pipe(- Effect.mapError(- () => new UsageLimitSourceError({ detail: "Could not read hub settings." }),- ),- );- const config = settings.usageLimitSources[input.sourceId];- if (!config?.enabled || !config.managementKey) {- return yield* new UsageLimitSourceError({- detail: "The usage limit source is missing or disabled.",- });- }- const result = yield* api.consume(config, input.accountId, input.creditId);- const snapshot = yield* readSource(input.sourceId, config);- const previous = yield* Ref.get(stateRef);- yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source)));- return result;- }).pipe(refreshLock.withPermits(1));+ const consumeResetCredit = Effect.fn("UsageLimitSources.consumeResetCredit")(function* (+ input: UsageLimitSourceConsumeResetCreditInput,+ ) {+ const settings = yield* settingsService.getSettings.pipe(+ Effect.mapError(() => new UsageLimitSourceError({ detail: "Could not read hub settings." })),+ );+ const config = settings.usageLimitSources[input.sourceId];+ if (!config?.enabled || !config.managementKey) {+ return yield* new UsageLimitSourceError({+ detail: "The usage limit source is missing or disabled.",+ });+ }+ const result = yield* api.consume(config, input.accountId, input.creditId);+ const snapshot = yield* readSource(input.sourceId, config);+ const previous = yield* Ref.get(stateRef);+ yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source)));+ return result;+ }, refreshLock.withPermits(1));yield* settingsService.streamChanges.pipe(Stream.map((settings) => settings.usageLimitSources),diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.tsindex 49d8d179664..c27321b5177 100644--- a/apps/server/src/usage/UsageService.ts+++ b/apps/server/src/usage/UsageService.ts@@ -451,66 +451,63 @@ export const make = Effect.gen(function* () {* than completion order: saved records of deleted transcripts aggregate in* cache order, where the first copy of a duplicate wins.*/- const readFileRecords = (+ const readFileRecords = Effect.fn("UsageService.readFileRecords")(function* (filePath: string,size: number,mtimeMs: number,provider: UsageProviderKind,format: TranscriptUsageFormat<unknown>,- ): Effect.Effect<{+ ): Effect.fn.Return<{readonly records: readonly UsageRecord[];readonly failed?: true;readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };- }> =>- Effect.gen(function* () {- const cached = fileCache.get(filePath);- // Provider is part of the identity: if both providers were ever pointed- // at one directory, a hit parsed by the other parser must not be reused.- if (- cached &&- cached.size === size &&- cached.mtimeMs === mtimeMs &&- cached.provider === provider- ) {- return {- records:- cached.tailRecords.length === 0- ? cached.records- : [...cached.records, ...cached.tailRecords],- };- }-- // Only a strictly grown file may resume. Same size with a new mtime, or- // a shrunken file, means rewritten content; re-parse it whole.- const resumeFrom =- cached !== undefined && cached.provider === provider && size > cached.size- ? cached.position- : undefined;-- const parsed = yield* Effect.promise(() =>- readTranscriptRecords(filePath, format, resumeFrom),- );- // A read failure is not an empty transcript: caching it under this- // (size, mtime) would silently drop the file's usage until it changes.- if (parsed === null)- return {- records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],- failed: true,- };-- const base = parsed.resumed && cached !== undefined ? cached.records : [];- const seen = new Set<string>();- const records = dedupeWithinFile([...base, ...parsed.records], seen);- const tailRecords = dedupeWithinFile(parsed.tailRecords, seen);+ }> {+ const cached = fileCache.get(filePath);+ // Provider is part of the identity: if both providers were ever pointed+ // at one directory, a hit parsed by the other parser must not be reused.+ if (+ cached &&+ cached.size === size &&+ cached.mtimeMs === mtimeMs &&+ cached.provider === provider+ ) {+ return {+ records:+ cached.tailRecords.length === 0+ ? cached.records+ : [...cached.records, ...cached.tailRecords],+ };+ }+ // Only a strictly grown file may resume. Same size with a new mtime, or+ // a shrunken file, means rewritten content; re-parse it whole.+ const resumeFrom =+ cached !== undefined && cached.provider === provider && size > cached.size+ ? cached.position+ : undefined;++ const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, format, resumeFrom));+ // A read failure is not an empty transcript: caching it under this+ // (size, mtime) would silently drop the file's usage until it changes.+ if (parsed === null)return {- records: tailRecords.length === 0 ? records : [...records, ...tailRecords],- update: {- entry: { size, mtimeMs, provider, records, tailRecords, position: parsed.position },- replaces: cached,- },+ records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],+ failed: true,};- });++ const base = parsed.resumed && cached !== undefined ? cached.records : [];+ const seen = new Set<string>();+ const records = dedupeWithinFile([...base, ...parsed.records], seen);+ const tailRecords = dedupeWithinFile(parsed.tailRecords, seen);++ return {+ records: tailRecords.length === 0 ? records : [...records, ...tailRecords],+ update: {+ entry: { size, mtimeMs, provider, records, tailRecords, position: parsed.position },+ replaces: cached,+ },+ };+ });interface ScannedDir {readonly provider: UsageProviderKind;diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.tsindex 46e781a1d5b..5c7b20b34c5 100644--- a/apps/server/src/vcs/GitVcsDriver.ts+++ b/apps/server/src/vcs/GitVcsDriver.ts@@ -783,16 +783,17 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (}),);- const resolveGitCommonDir = (cwd: string) =>- Effect.gen(function* () {- const result = yield* execute({- operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",- cwd,- args: ["rev-parse", "--git-common-dir"],- });- const gitCommonDir = result.stdout.trim();- return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);+ const resolveGitCommonDir = Effect.fn("GitVcsDriver.resolveGitCommonDir")(function* (+ cwd: string,+ ) {+ const result = yield* execute({+ operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",+ cwd,+ args: ["rev-parse", "--git-common-dir"],});+ const gitCommonDir = result.stdout.trim();+ return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);+ });// Git renames loose objects and refs into place without fsync by default, so// an unclean restart can leave 0-byte files under refs/t3/** that break everydiff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.tsindex 4cefc3ee1da..f2c32a94a28 100644--- a/apps/server/src/vcs/GitVcsDriverCore.ts+++ b/apps/server/src/vcs/GitVcsDriverCore.ts@@ -600,14 +600,16 @@ const nowUnixNano = DateTime.now.pipe(Effect.map((now) => BigInt(DateTime.toEpochMillis(now)) * 1_000_000n),);-const addCurrentSpanEvent = (name: string, attributes: Record<string, unknown>) =>- Effect.gen(function* () {- const span = yield* Effect.currentSpan;- const timestamp = yield* nowUnixNano;- yield* Effect.sync(() => {- span.event(name, timestamp, compactTraceAttributes(attributes));- });- }).pipe(+const addCurrentSpanEvent =+ /* This helper annotates the existing operation span. */+ Effect.fnUntraced(+ function* (name: string, attributes: Record<string, unknown>) {+ const span = yield* Effect.currentSpan;+ const timestamp = yield* nowUnixNano;+ yield* Effect.sync(() => {+ span.event(name, timestamp, compactTraceAttributes(attributes));+ });+ },Effect.catchTags({NoSuchElementError: () => Effect.void,}),@@ -1440,15 +1442,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*}),},);- const invalidateStatusStaticCaches = (cwd: string) =>- Effect.gen(function* () {+ const invalidateStatusStaticCaches = Effect.fn("GitVcsDriverCore.invalidateStatusStaticCaches")(+ function* (cwd: string) {const repositoryPaths = yield* resolveRepositoryPaths(cwd).pipe(Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }),);const cacheKey = repositoryPaths?.gitCommonDir ?? normalizeRepositoryPathsCacheKey(cwd);yield* Cache.invalidate(defaultBranchCache, cacheKey);yield* Cache.invalidate(originExistsCache, cacheKey);- });+ },+ );const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) {const repositoryPaths = yield* resolveRepositoryPaths(cwd);@@ -3994,22 +3997,22 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function** Unlinks links under `target` without following them and removes the* directories that leaves empty. Returns false when anything else remains.*/- const removeLeftoverLinks = (+ // Recursive filesystem traversal can visit many entries; removeWorktree owns the operation span.+ const removeLeftoverLinks = Effect.fnUntraced(function* (target: string,- ): Effect.Effect<boolean, PlatformError.PlatformError | Cause.UnknownError> =>- Effect.gen(function* () {- if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) {- yield* fileSystem.remove(target);- return true;- }- if ((yield* fileSystem.stat(target)).type !== "Directory") return false;- let empty = true;- for (const name of yield* fileSystem.readDirectory(target)) {- if (!(yield* removeLeftoverLinks(path.join(target, name)))) empty = false;- }- // Only an empty directory goes, so files written since the listing stay.- return empty && (yield* removeEmptyDirectory(target));- });+ ): Effect.fn.Return<boolean, PlatformError.PlatformError | Cause.UnknownError> {+ if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) {+ yield* fileSystem.remove(target);+ return true;+ }+ if ((yield* fileSystem.stat(target)).type !== "Directory") return false;+ let empty = true;+ for (const name of yield* fileSystem.readDirectory(target)) {+ if (!(yield* removeLeftoverLinks(path.join(target, name)))) empty = false;+ }+ // Only an empty directory goes, so files written since the listing stay.+ return empty && (yield* removeEmptyDirectory(target));+ });const removeWorktree: GitVcsDriver.GitVcsDriver["Service"]["removeWorktree"] = Effect.fn("removeWorktree",diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.tsindex fec9f74b466..cfa253aafa3 100644--- a/apps/server/src/vcs/VcsStatusBroadcaster.ts+++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts@@ -555,88 +555,87 @@ export const make = Effect.gen(function* () {);});- const makeRemoteRefreshLoop = (+ // A subscription owns this loop; keep each poll's spans out of a never-ending parent span.+ const makeRemoteRefreshLoop = Effect.fnUntraced(function* (cwd: string,demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,refreshImmediately: boolean,- ) => {- return Effect.gen(function* () {- const consecutiveFailuresRef = yield* Ref.make(0);- const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);- const refreshRemoteStatusIfEnabled = Effect.gen(function* () {- const configuredInterval = yield* automaticFetchInterval;- const activeInterval = Duration.isZero(configuredInterval)- ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL- : configuredInterval;- const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);- if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {- return activeInterval;- }+ ) {+ const consecutiveFailuresRef = yield* Ref.make(0);+ const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);+ const refreshRemoteStatusIfEnabled = Effect.gen(function* () {+ const configuredInterval = yield* automaticFetchInterval;+ const activeInterval = Duration.isZero(configuredInterval)+ ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL+ : configuredInterval;+ const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);+ if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {+ return activeInterval;+ }- const demandCwds = yield* Ref.get(demandCwdsRef);- const shouldRun =- needsInitialRefresh ||- (yield* Effect.forEach(- [...demandCwds.keys()],- (demandCwd) =>- backgroundPolicy.shouldRunScopeWork({- type: "vcs-status",- cwd: demandCwd,- }),- { concurrency: "unbounded" },- )).some(Boolean);- if (!shouldRun) {- return activeInterval;- }+ const demandCwds = yield* Ref.get(demandCwdsRef);+ const shouldRun =+ needsInitialRefresh ||+ (yield* Effect.forEach(+ [...demandCwds.keys()],+ (demandCwd) =>+ backgroundPolicy.shouldRunScopeWork({+ type: "vcs-status",+ cwd: demandCwd,+ }),+ { concurrency: "unbounded" },+ )).some(Boolean);+ if (!shouldRun) {+ return activeInterval;+ }- const exit = yield* refreshRemoteStatus(cwd, {- refreshUpstream: !Duration.isZero(configuredInterval),- policyCwds: [...demandCwds.keys()],- }).pipe(Effect.exit);- if (Exit.isSuccess(exit)) {- yield* Ref.set(needsInitialRefreshRef, false);- yield* Ref.set(consecutiveFailuresRef, 0);- return activeInterval;- }+ const exit = yield* refreshRemoteStatus(cwd, {+ refreshUpstream: !Duration.isZero(configuredInterval),+ policyCwds: [...demandCwds.keys()],+ }).pipe(Effect.exit);+ if (Exit.isSuccess(exit)) {+ yield* Ref.set(needsInitialRefreshRef, false);+ yield* Ref.set(consecutiveFailuresRef, 0);+ return activeInterval;+ }- const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);- if (interruptionReasons.length > 0) {- return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));- }+ const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);+ if (interruptionReasons.length > 0) {+ return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));+ }- const consecutiveFailures = yield* Ref.updateAndGet(- consecutiveFailuresRef,- (count) => count + 1,- );- const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);- yield* Effect.logWarning("VCS remote status refresh failed", {- cwdLength: cwd.length,- ...remoteRefreshFailureDiagnostics(exit.cause),- consecutiveFailures,- nextDelayMs: Duration.toMillis(nextDelay),- });- return nextDelay;+ const consecutiveFailures = yield* Ref.updateAndGet(+ consecutiveFailuresRef,+ (count) => count + 1,+ );+ const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);+ yield* Effect.logWarning("VCS remote status refresh failed", {+ cwdLength: cwd.length,+ ...remoteRefreshFailureDiagnostics(exit.cause),+ consecutiveFailures,+ nextDelayMs: Duration.toMillis(nextDelay),});+ return nextDelay;+ });- if (!refreshImmediately) {- const configuredInterval = yield* automaticFetchInterval;- yield* Effect.sleep(- Duration.isZero(configuredInterval)- ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL- : configuredInterval,- );- }+ if (!refreshImmediately) {+ const configuredInterval = yield* automaticFetchInterval;+ yield* Effect.sleep(+ Duration.isZero(configuredInterval)+ ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL+ : configuredInterval,+ );+ }- return yield* refreshRemoteStatusIfEnabled.pipe(- Effect.repeat(- Schedule.identity<Duration.Duration>().pipe(- Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),- ),+ return yield* refreshRemoteStatusIfEnabled.pipe(+ Effect.repeat(+ Schedule.identity<Duration.Duration>().pipe(+ Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),),- Effect.asVoid,- );- });- };+ ),+ Effect.asVoid,+ );+ });const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (cwd: string,diff --git a/apps/server/src/workspace/WorkspaceEntries.ts b/apps/server/src/workspace/WorkspaceEntries.tsindex 607db665de7..e40a1a25c12 100644--- a/apps/server/src/workspace/WorkspaceEntries.ts+++ b/apps/server/src/workspace/WorkspaceEntries.ts@@ -160,20 +160,21 @@ export const make = Effect.gen(function* () {if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {continue;}- const recoverRefreshFailure = (- cause:- | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed- | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut- | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,- ) =>- Effect.gen(function* () {+ const recoverRefreshFailure = Effect.fn("WorkspaceEntries.recoverRefreshFailure")(+ function* (+ cause:+ | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed+ | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut+ | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,+ ) {yield* Effect.logWarning("Failed to refresh workspace search index", {cwd,variant,cause,});yield* workspaceSearchIndexes.invalidate(indexKey);- });+ },+ );yield* Effect.gen(function* () {const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;yield* searchIndex.refresh();