diff --git a/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx index 8b53d81969264..bd7a0a7ff86bc 100644 --- a/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx @@ -354,7 +354,7 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm return; const result = await refreshProviders({ environmentId, - input: { reloadSecrets: true }, + input: { refreshModels: true, reloadSecrets: true }, }); if (AsyncResult.isFailure(result)) throw squashAtomCommandFailure(result); setNotice(gt("Provider status refreshed.")); diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index 6c0766d1cf7d8..3bbd8a2732a41 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -8,9 +8,12 @@ import * as Layer from "effect/Layer"; import { ProviderInstanceId } from "@t3tools/contracts"; import { AcpRegistrySettings } from "@t3tools/provider-acp-registry/settings"; import { describe, expect, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; import * as EffectAcpErrors from "effect-acp/errors"; import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; @@ -362,6 +365,9 @@ describe("ACP Registry probe", () => { const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.die("unused refreshIndex"), + currentIndexRevision: () => Effect.succeed(0), + invalidateIndex: () => Effect.die("unused invalidateIndex"), inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), resolve: () => @@ -423,6 +429,9 @@ describe("ACP Registry probe", () => { const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.die("unused refreshIndex"), + currentIndexRevision: () => Effect.succeed(0), + invalidateIndex: () => Effect.die("unused invalidateIndex"), inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), resolve: () => @@ -492,6 +501,9 @@ await import(pathToFileURL(agentPath).href); const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.die("unused refreshIndex"), + currentIndexRevision: () => Effect.succeed(0), + invalidateIndex: () => Effect.die("unused invalidateIndex"), inspect: () => Effect.die("unused inspect"), uninstallManagedBinary: () => Effect.die("unused uninstall"), resolve: () => @@ -571,4 +583,67 @@ await import(pathToFileURL(agentPath).href); ).reason, ).toBe("probe_failed"); }); + + it.effect( + "does not count slow catalog resolution against the 60s ACP probe timeout and forwards failedTarget", + () => + Effect.gen(function* () { + const resolveStarted = yield* Deferred.make(); + const failedTarget: AcpRegistrySupport.AcpRegistryFailedTarget = { + version: "2.0.0", + launchIdentity: "v2-identity", + indexRevision: 4, + }; + const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ + search: () => Effect.die("unused search"), + prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.die("unused refreshIndex"), + currentIndexRevision: () => Effect.succeed(0), + invalidateIndex: () => Effect.die("unused invalidateIndex"), + inspect: () => Effect.die("unused inspect"), + uninstallManagedBinary: () => Effect.die("unused uninstall"), + resolve: () => + Deferred.succeed(resolveStarted, undefined).pipe( + Effect.andThen(Effect.sleep("2 minutes")), + Effect.as({ + agent: { + id: "mock-agent", + name: "Mock Agent", + version: "1.0.0", + description: "ACP probe timeout-split test agent", + distribution: { npx: { package: "mock-agent@1.0.0" } }, + }, + distribution: "npx" as const, + launchIdentity: "v1-identity", + fallback: true, + failedTarget, + spawn: { + command: "node", + args: [mockAgentPath], + env: { ...process.env, T3_ACP_AVAILABLE_COMMANDS: "status" }, + }, + }), + ), + }); + const probeFiber = yield* probeAcpRegistryConfiguration({ + instanceId, + settings: decodeSettings({ agentId: "mock-agent" }), + cwd: process.cwd(), + environment: {}, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.forkScoped({ startImmediately: true }), + ); + yield* Deferred.await(resolveStarted); + yield* TestClock.adjust("2 minutes"); + const result = yield* Fiber.join(probeFiber); + expect(result.probe.ready).toBe(true); + expect(result.resolved).toMatchObject({ + distribution: "npx", + launchIdentity: "v1-identity", + fallback: true, + failedTarget, + }); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); }); diff --git a/docs/user/providers-acp.md b/docs/user/providers-acp.md index 453c777e3c8c0..573e8302d1ed8 100644 --- a/docs/user/providers-acp.md +++ b/docs/user/providers-acp.md @@ -51,6 +51,18 @@ version published by the Registry. Their commands are available in a new server sign-in and direct use. Removing an agent's last provider instance removes T3-managed binary files but keeps package installs. To use an existing local binary, set **Executable override** explicitly. +T3 Code refreshes the Registry index in the background and automatically installs new versions of +prepared, T3-managed Registry agents alongside earlier versions, deferring background updates while +that agent is starting a session. If a newly published version of a T3-managed binary agent fails +to download, verify, or unpack, T3 Code keeps running the newest previously installed version until +the update succeeds (versions installed before T3 Code added this fallback can't be used for it). +Agents using **Executable override** keep running the configured executable—update those +overrides directly on the server—while Registry refreshes can still pick up updated Registry +metadata, arguments, and environment variables. Refreshing providers (in **Settings → Providers** on +web and desktop, or **Refresh providers** in environment settings on mobile) requests a fresh +Registry check right away for unprepared or unavailable agents, and after the agent's status check +finishes for installed agents. + ## Signing in Open the agent's account section in **Settings → Providers** on web or desktop. Choose diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts index a6662853ae028..21b82416bebbb 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts @@ -1,9 +1,11 @@ import { describe, expect, it } from "@effect/vitest"; import { ProviderInstanceId } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Option from "effect/Option"; +import * as TestClock from "effect/testing/TestClock"; import type { AcpRegistryAvailableCommands } from "./probe.ts"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; @@ -173,6 +175,106 @@ describe("AcpRegistryRuntimeCoordinator", () => { ).toBe(true); expect(yield* Fiber.join(request)).toBe(true); expect(Option.isNone(yield* coordinator.getUrlAuthAction(instanceId))).toBe(true); + + // Decouple current-time reads from TestClock sleep so the exact expiry boundary (>=) is + // tested in both getUrlAuthAction and acceptUrlAuthentication while the request is pending. + const baseClock = yield* Clock.Clock; + let clockNowMs = 0; + const decoupledClock: Clock.Clock = { + ...baseClock, + currentTimeMillisUnsafe: () => clockNowMs, + currentTimeMillis: Effect.sync(() => clockNowMs), + currentTimeNanosUnsafe: () => BigInt(clockNowMs) * 1_000_000n, + currentTimeNanos: Effect.sync(() => BigInt(clockNowMs) * 1_000_000n), + monotonicTimeNanosUnsafe: () => BigInt(clockNowMs) * 1_000_000n, + monotonicTimeNanos: Effect.sync(() => BigInt(clockNowMs) * 1_000_000n), + sleep: (duration) => baseClock.sleep(duration), + }; + const withDecoupledClock = (effect: Effect.Effect) => + effect.pipe(Effect.provideService(Clock.Clock, decoupledClock)); + + // Consent must still succeed 1 ms before expiry while the request is pending. + const beforeExpirySeen = yield* Deferred.make(); + const expiringWatcher = yield* coordinator + .watchUrlAuthAction(instanceId, (current) => + current?.elicitationId === "login-before-expiry" + ? Deferred.succeed(beforeExpirySeen, undefined).pipe(Effect.asVoid) + : Effect.void, + ) + .pipe(Effect.forkChild); + const beforeExpiryRequest = yield* withDecoupledClock( + coordinator.requestUrlAuthentication(instanceId, { + ...action, + elicitationId: "login-before-expiry", + }), + ).pipe(Effect.forkChild); + yield* Deferred.await(beforeExpirySeen); + clockNowMs = 10 * 60 * 1_000 - 1; + expect( + Option.isSome(yield* withDecoupledClock(coordinator.getUrlAuthAction(instanceId))), + ).toBe(true); + expect( + yield* withDecoupledClock( + coordinator.acceptUrlAuthentication({ + instanceId, + elicitationId: "login-before-expiry", + }), + ), + ).toBe(true); + expect(yield* Fiber.join(beforeExpiryRequest)).toBe(true); + yield* Fiber.interrupt(expiringWatcher); + + // Consent must be rejected at the exact expiry millisecond while the timeout has not fired. + clockNowMs = 0; + const exactExpirySeen = yield* Deferred.make(); + const exactExpiryWatcher = yield* coordinator + .watchUrlAuthAction(instanceId, (current) => + current?.elicitationId === "login-expiring" + ? Deferred.succeed(exactExpirySeen, undefined).pipe(Effect.asVoid) + : Effect.void, + ) + .pipe(Effect.forkChild); + const expiringRequest = yield* withDecoupledClock( + coordinator.requestUrlAuthentication(instanceId, { + ...action, + elicitationId: "login-expiring", + }), + ).pipe(Effect.forkChild); + yield* Deferred.await(exactExpirySeen); + clockNowMs = 10 * 60 * 1_000; + expect(expiringRequest.pollUnsafe()).toBeUndefined(); + expect( + Option.isNone(yield* withDecoupledClock(coordinator.getUrlAuthAction(instanceId))), + ).toBe(true); + expect(expiringRequest.pollUnsafe()).toBeUndefined(); + expect( + yield* withDecoupledClock( + coordinator.acceptUrlAuthentication({ instanceId, elicitationId: "login-expiring" }), + ), + ).toBe(false); + expect(yield* Fiber.join(expiringRequest)).toBe(false); + yield* Fiber.interrupt(exactExpiryWatcher); + + // An unaccepted request also expires cleanly when the timeout fires. + const timeoutSeen = yield* Deferred.make(); + const timeoutWatcher = yield* coordinator + .watchUrlAuthAction(instanceId, (current) => + current?.elicitationId === "login-timeout" + ? Deferred.succeed(timeoutSeen, undefined).pipe(Effect.asVoid) + : Effect.void, + ) + .pipe(Effect.forkChild); + const timeoutRequest = yield* coordinator + .requestUrlAuthentication(instanceId, { + ...action, + elicitationId: "login-timeout", + }) + .pipe(Effect.forkChild); + yield* Deferred.await(timeoutSeen); + yield* TestClock.adjust("10 minutes"); + expect(yield* Fiber.join(timeoutRequest)).toBe(false); + expect(Option.isNone(yield* coordinator.getUrlAuthAction(instanceId))).toBe(true); + yield* Fiber.interrupt(timeoutWatcher); yield* Fiber.interrupt(consumer); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); @@ -257,4 +359,192 @@ describe("AcpRegistryRuntimeCoordinator", () => { yield* Fiber.interrupt(consumer); }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), ); + + it.effect( + "isolates per-runtime state, evaluates chained clear watermarks, and drops disposed instances", + () => + Effect.gen(function* () { + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const instanceId = ProviderInstanceId.make("acpRegistry_runtime_scoped"); + const metas: Array<{ + readonly label: string; + readonly meta: AcpRegistryRuntimeCoordinator.AcpRegistryLiveUpdateMeta; + }> = []; + const expectedCount = { target: 0, gate: yield* Deferred.make() }; + const watcher = yield* coordinator + .watchAvailableCommands(instanceId, (commands, meta) => + Effect.gen(function* () { + metas.push({ label: commands.slashCommands[0]?.name ?? "empty", meta }); + if (metas.length >= expectedCount.target) { + yield* Deferred.succeed(expectedCount.gate, undefined); + } + }), + ) + .pipe(Effect.forkChild); + + const publishAndWait = (name: string, runtimeIdentity?: string) => + Effect.gen(function* () { + expectedCount.target = metas.length + 1; + expectedCount.gate = yield* Deferred.make(); + yield* coordinator.publishAvailableCommands( + instanceId, + { slashCommands: [{ name }], skills: [] }, + runtimeIdentity, + ); + yield* Deferred.await(expectedCount.gate); + return metas[metas.length - 1]!.meta; + }); + + // 1. Late update from A must not evict B's stored entry. + const metaA = yield* publishAndWait("cmd-a", "runtime-a"); + const metaB = yield* publishAndWait("cmd-b", "runtime-b"); + const metaUntagged = yield* publishAndWait("cmd-untagged"); + const metaLateA = yield* publishAndWait("cmd-a-late", "runtime-a"); + expect( + yield* coordinator.getAvailableCommands(instanceId, { + runtimeIdentity: "runtime-b", + requireMatchingRuntimeIdentity: true, + }), + ).toEqual(Option.some({ slashCommands: [{ name: "cmd-b" }], skills: [] })); + expect(yield* metaA.isCurrent).toBe(true); + expect(yield* metaB.isCurrent).toBe(true); + expect(yield* metaUntagged.isCurrent).toBe(true); + expect(yield* metaLateA.isCurrent).toBe(true); + + // 2. Chained preserve clears (preserve B -> preserve C -> preserve B) keep only matching entries current. + yield* coordinator.clearAvailableCommands(instanceId, { + preserveRuntimeIdentity: "runtime-b", + }); + expect(yield* metaA.isCurrent).toBe(false); + expect(yield* metaLateA.isCurrent).toBe(false); + expect(yield* metaUntagged.isCurrent).toBe(false); + expect(yield* metaB.isCurrent).toBe(true); + expect( + yield* coordinator.getAvailableCommands(instanceId, { + runtimeIdentity: "runtime-a", + requireMatchingRuntimeIdentity: true, + }), + ).toEqual(Option.none()); + expect(yield* coordinator.getAvailableCommands(instanceId)).toEqual( + Option.some({ slashCommands: [{ name: "cmd-b" }], skills: [] }), + ); + + // Even after another runtime publishes later, untagged get prefers preservedRuntimeIdentity. + const metaC = yield* publishAndWait("cmd-c", "runtime-c"); + expect(yield* coordinator.getAvailableCommands(instanceId)).toEqual( + Option.some({ slashCommands: [{ name: "cmd-b" }], skills: [] }), + ); + yield* coordinator.clearAvailableCommands(instanceId, { + preserveRuntimeIdentity: "runtime-c", + }); + expect(yield* metaB.isCurrent).toBe(false); + expect(yield* metaC.isCurrent).toBe(true); + + // Returning to preserve B after preserve C must NOT resurrect the older pre-C metaB. + const metaB2 = yield* publishAndWait("cmd-b-2", "runtime-b"); + yield* coordinator.clearAvailableCommands(instanceId, { + preserveRuntimeIdentity: "runtime-b", + }); + expect(yield* metaB.isCurrent).toBe(false); + expect(yield* metaC.isCurrent).toBe(false); + expect(yield* metaB2.isCurrent).toBe(true); + + // 3. Full clear invalidates everything published before it; subsequent publications stay current. + yield* coordinator.clearAvailableCommands(instanceId); + expect(yield* metaB2.isCurrent).toBe(false); + expect(Option.isNone(yield* coordinator.getAvailableCommands(instanceId))).toBe(true); + + const metaAfterFullClear = yield* publishAndWait("cmd-fresh", "runtime-b"); + expect(yield* metaAfterFullClear.isCurrent).toBe(true); + + // 4. Disposing an instance drops its state and keeps pre-disposal updates permanently stale + // even after the same instance ID is reused for new publications. + yield* coordinator.clearAvailableCommands(instanceId, { dispose: true }); + expect(yield* metaAfterFullClear.isCurrent).toBe(false); + expect(Option.isNone(yield* coordinator.getAvailableCommands(instanceId))).toBe(true); + + const metaAfterReuse = yield* publishAndWait("cmd-reused", "runtime-b"); + expect(yield* metaAfterReuse.isCurrent).toBe(true); + expect(yield* metaAfterFullClear.isCurrent).toBe(false); + + // 5. A newly subscribed watcher replays retained per-runtime entries in ascending revision + // order and delivers subsequent live publications without replaying older revisions. + yield* coordinator.publishAvailableCommands( + instanceId, + { slashCommands: [{ name: "cmd-reused-c" }], skills: [] }, + "runtime-c", + ); + const replayedNames: Array = []; + const initialReplayDone = yield* Deferred.make(); + const replayDone = yield* Deferred.make(); + const secondWatcher = yield* coordinator + .watchAvailableCommands(instanceId, (commands) => + Effect.gen(function* () { + replayedNames.push(commands.slashCommands[0]?.name ?? "empty"); + if (replayedNames.length === 2) { + yield* Deferred.succeed(initialReplayDone, undefined); + } + if (replayedNames.length >= 3) { + yield* Deferred.succeed(replayDone, undefined); + } + }), + ) + .pipe(Effect.forkChild); + yield* Deferred.await(initialReplayDone); + yield* coordinator.publishAvailableCommands( + instanceId, + { slashCommands: [{ name: "cmd-after-watch" }], skills: [] }, + "runtime-b", + ); + yield* Deferred.await(replayDone); + expect(replayedNames).toEqual(["cmd-reused", "cmd-reused-c", "cmd-after-watch"]); + yield* Fiber.interrupt(secondWatcher); + + // 6. Concurrent publications for the same runtime are serialized so watchers always finish + // on the exact latest committed state returned by get(). + const concurrentCount = 12; + const concurrentNames: Array = []; + const concurrentReady = yield* Deferred.make(); + const concurrentDone = yield* Deferred.make(); + const concurrentWatcher = yield* coordinator + .watchAvailableCommands(instanceId, (commands) => + Effect.gen(function* () { + const name = commands.slashCommands[0]?.name ?? "empty"; + if (name === "cmd-after-watch") { + yield* Deferred.succeed(concurrentReady, undefined); + } else if (name.startsWith("concurrent-")) { + concurrentNames.push(name); + if (concurrentNames.length >= concurrentCount) { + yield* Deferred.succeed(concurrentDone, undefined); + } + } + }), + ) + .pipe(Effect.forkChild); + // Wait for concurrentWatcher itself to finish its initial replay before firing the batch. + yield* Deferred.await(concurrentReady); + yield* Effect.all( + Array.from({ length: concurrentCount }, (_, index) => + coordinator.publishAvailableCommands( + instanceId, + { slashCommands: [{ name: `concurrent-${index}` }], skills: [] }, + "runtime-b", + ), + ), + { concurrency: "unbounded", discard: true }, + ); + yield* Deferred.await(concurrentDone); + const committedLatest = Option.getOrThrow( + yield* coordinator.getAvailableCommands(instanceId, { + runtimeIdentity: "runtime-b", + requireMatchingRuntimeIdentity: true, + }), + ); + expect(concurrentNames[concurrentNames.length - 1]).toBe( + committedLatest.slashCommands[0]?.name, + ); + yield* Fiber.interrupt(concurrentWatcher); + yield* Fiber.interrupt(watcher); + }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)), + ); }); diff --git a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts index bec80c06ddd39..c81e2189cd942 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.ts @@ -17,14 +17,19 @@ import * as Stream from "effect/Stream"; import type { AcpRegistryAvailableCommands, AcpRegistryLiveConfiguration } from "./probe.ts"; -interface AvailableCommandsUpdate { - readonly instanceId: ProviderInstanceId; - readonly commands: AcpRegistryAvailableCommands; +export interface AcpRegistryLiveUpdateMeta { + readonly runtimeIdentity: string | undefined; + readonly isCurrent: Effect.Effect; } -interface LiveConfigurationUpdate { - readonly instanceId: ProviderInstanceId; - readonly configuration: AcpRegistryLiveConfiguration; +export interface AcpRegistryClearLiveStateOptions { + readonly preserveRuntimeIdentity?: string; + readonly dispose?: boolean; +} + +export interface AcpRegistryReadLiveStateOptions { + readonly runtimeIdentity?: string; + readonly requireMatchingRuntimeIdentity?: boolean; } interface UrlAuthActionUpdate { @@ -54,29 +59,45 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< readonly withSessionMutation: ( effect: Effect.Effect, ) => Effect.Effect; - readonly clearAvailableCommands: (instanceId: ProviderInstanceId) => Effect.Effect; + readonly clearAvailableCommands: ( + instanceId: ProviderInstanceId, + options?: AcpRegistryClearLiveStateOptions, + ) => Effect.Effect; readonly publishAvailableCommands: ( instanceId: ProviderInstanceId, commands: AcpRegistryAvailableCommands, + runtimeIdentity?: string, ) => Effect.Effect; readonly getAvailableCommands: ( instanceId: ProviderInstanceId, + options?: AcpRegistryReadLiveStateOptions, ) => Effect.Effect>; readonly watchAvailableCommands: ( instanceId: ProviderInstanceId, - onUpdate: (commands: AcpRegistryAvailableCommands) => Effect.Effect, + onUpdate: ( + commands: AcpRegistryAvailableCommands, + meta: AcpRegistryLiveUpdateMeta, + ) => Effect.Effect, + ) => Effect.Effect; + readonly clearLiveConfiguration: ( + instanceId: ProviderInstanceId, + options?: AcpRegistryClearLiveStateOptions, ) => Effect.Effect; - readonly clearLiveConfiguration: (instanceId: ProviderInstanceId) => Effect.Effect; readonly publishLiveConfiguration: ( instanceId: ProviderInstanceId, configuration: AcpRegistryLiveConfiguration, + runtimeIdentity?: string, ) => Effect.Effect; readonly getLiveConfiguration: ( instanceId: ProviderInstanceId, + options?: AcpRegistryReadLiveStateOptions, ) => Effect.Effect>; readonly watchLiveConfiguration: ( instanceId: ProviderInstanceId, - onUpdate: (configuration: AcpRegistryLiveConfiguration) => Effect.Effect, + onUpdate: ( + configuration: AcpRegistryLiveConfiguration, + meta: AcpRegistryLiveUpdateMeta, + ) => Effect.Effect, ) => Effect.Effect; readonly requestUrlAuthentication: ( instanceId: ProviderInstanceId, @@ -95,17 +116,282 @@ export class AcpRegistryRuntimeCoordinator extends Context.Service< } >()("@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator") {} +interface LiveStateClearState { + readonly allBeforeRevision: number; + readonly nonMatchingBeforeRevision: number; + readonly preservedRuntimeIdentity: string | undefined; +} + +function recordLiveStateClear( + current: LiveStateClearState | undefined, + clearRevision: number, + options?: AcpRegistryClearLiveStateOptions, +): LiveStateClearState { + const preserveRuntimeIdentity = options?.preserveRuntimeIdentity; + if (preserveRuntimeIdentity === undefined) { + return { + allBeforeRevision: clearRevision, + nonMatchingBeforeRevision: clearRevision, + preservedRuntimeIdentity: undefined, + }; + } + const previousAllBefore = current?.allBeforeRevision ?? 0; + const previousPreservedExpired = + current !== undefined && current.preservedRuntimeIdentity !== preserveRuntimeIdentity + ? current.nonMatchingBeforeRevision + : 0; + return { + allBeforeRevision: Math.max(previousAllBefore, previousPreservedExpired), + nonMatchingBeforeRevision: clearRevision, + preservedRuntimeIdentity: preserveRuntimeIdentity, + }; +} + +function isLiveUpdateCurrent( + clearState: LiveStateClearState | undefined, + updateRevision: number, + runtimeIdentity: string | undefined, +): boolean { + if (clearState === undefined) return true; + if (updateRevision < clearState.allBeforeRevision) return false; + if ( + updateRevision < clearState.nonMatchingBeforeRevision && + (clearState.preservedRuntimeIdentity === undefined || + runtimeIdentity !== clearState.preservedRuntimeIdentity) + ) { + return false; + } + return true; +} + +interface ChannelEntry { + readonly value: T; + readonly runtimeIdentity: string | undefined; + readonly revision: number; + readonly lifetime: number; +} + +interface InstanceChannelState { + readonly lifetime: number; + readonly entries: ReadonlyMap>; + readonly latestKey: string | undefined; + readonly hasLatest: boolean; + readonly clear: LiveStateClearState | undefined; +} + +interface ChannelState { + readonly revision: number; + readonly instances: ReadonlyMap>; +} + +interface ChannelUpdate { + readonly instanceId: ProviderInstanceId; + readonly value: T; + readonly runtimeIdentity: string | undefined; + readonly revision: number; + readonly lifetime: number; +} + +interface LiveStateChannelNames { + readonly clear: string; + readonly publish: string; + readonly get: string; + readonly watch: string; +} + +const makeLiveStateChannel = Effect.fn("AcpRegistryRuntimeCoordinator.makeLiveStateChannel")( + function* (names: LiveStateChannelNames) { + const updates = yield* PubSub.unbounded>(); + const publishPermit = yield* Semaphore.make(1); + const stateRef = yield* Ref.make>({ + revision: 0, + instances: new Map(), + }); + + const clear = Effect.fn(`AcpRegistryRuntimeCoordinator.${names.clear}`)(function* ( + instanceId: ProviderInstanceId, + options?: AcpRegistryClearLiveStateOptions, + ) { + yield* Ref.update(stateRef, (state) => { + const revision = state.revision + 1; + const nextInstances = new Map(state.instances); + if (options?.dispose === true) { + nextInstances.delete(instanceId); + return { revision, instances: nextInstances }; + } + const existing = state.instances.get(instanceId); + const lifetime = existing?.lifetime ?? revision; + const nextClear = recordLiveStateClear(existing?.clear, revision, options); + const nextEntries = new Map>(); + if (existing !== undefined) { + for (const [key, entry] of existing.entries) { + if (isLiveUpdateCurrent(nextClear, entry.revision, entry.runtimeIdentity)) { + nextEntries.set(key, entry); + } + } + } + const latestEntry = + existing !== undefined && existing.hasLatest + ? nextEntries.get(existing.latestKey) + : undefined; + const fallbackLatest = + latestEntry ?? + Array.from(nextEntries.values()).reduce | undefined>( + (best, entry) => (best === undefined || entry.revision > best.revision ? entry : best), + undefined, + ); + nextInstances.set(instanceId, { + lifetime, + entries: nextEntries, + latestKey: fallbackLatest?.runtimeIdentity, + hasLatest: fallbackLatest !== undefined, + clear: nextClear, + }); + return { revision, instances: nextInstances }; + }); + }); + + const publish = Effect.fn(`AcpRegistryRuntimeCoordinator.${names.publish}`)(function* ( + instanceId: ProviderInstanceId, + value: T, + runtimeIdentity?: string, + ) { + // Serialize state commit and PubSub publication so watchers always observe monotonic revisions. + yield* publishPermit.withPermits(1)( + Effect.uninterruptible( + Ref.modify(stateRef, (state) => { + const revision = state.revision + 1; + const existing = state.instances.get(instanceId); + const lifetime = existing?.lifetime ?? revision; + const nextEntries = new Map(existing?.entries); + nextEntries.set(runtimeIdentity, { value, runtimeIdentity, revision, lifetime }); + const nextInstances = new Map(state.instances); + nextInstances.set(instanceId, { + lifetime, + entries: nextEntries, + latestKey: runtimeIdentity, + hasLatest: true, + clear: existing?.clear, + }); + const update: ChannelUpdate = { + instanceId, + value, + runtimeIdentity, + revision, + lifetime, + }; + return [update, { revision, instances: nextInstances }] as const; + }).pipe( + Effect.flatMap((event) => PubSub.publish(updates, event)), + Effect.asVoid, + ), + ), + ); + }); + + const get = Effect.fn(`AcpRegistryRuntimeCoordinator.${names.get}`)(function* ( + instanceId: ProviderInstanceId, + options?: AcpRegistryReadLiveStateOptions, + ) { + const inst = (yield* Ref.get(stateRef)).instances.get(instanceId); + if (inst === undefined) return Option.none(); + const validEntry = (entry: ChannelEntry | undefined): Option.Option => + entry !== undefined && + isLiveUpdateCurrent(inst.clear, entry.revision, entry.runtimeIdentity) + ? Option.some(entry.value) + : Option.none(); + if (options?.runtimeIdentity !== undefined) { + const exact = validEntry(inst.entries.get(options.runtimeIdentity)); + if (Option.isSome(exact)) return exact; + if (options.requireMatchingRuntimeIdentity === true) return Option.none(); + return validEntry(inst.entries.get(undefined)); + } + if (inst.clear?.preservedRuntimeIdentity !== undefined) { + const preserved = validEntry(inst.entries.get(inst.clear.preservedRuntimeIdentity)); + if (Option.isSome(preserved)) return preserved; + } + return inst.hasLatest ? validEntry(inst.entries.get(inst.latestKey)) : Option.none(); + }); + + const watch = ( + instanceId: ProviderInstanceId, + onUpdate: (value: T, meta: AcpRegistryLiveUpdateMeta) => Effect.Effect, + ) => + Effect.scoped( + Effect.gen(function* () { + // Trace subscription setup once without keeping a long-lived parent span around callbacks. + const { subscription, snapshot } = yield* Effect.gen(function* () { + // Subscribe before reading to avoid missing publications. + const sub = yield* PubSub.subscribe(updates); + const snap = yield* Ref.get(stateRef); + return { subscription: sub, snapshot: snap }; + }).pipe(Effect.withSpan(`AcpRegistryRuntimeCoordinator.${names.watch}.subscribe`)); + const snapshotRevision = snapshot.revision; + const inst = snapshot.instances.get(instanceId); + const metaFor = ( + runtimeIdentity: string | undefined, + revision: number, + lifetime: number, + ): AcpRegistryLiveUpdateMeta => ({ + runtimeIdentity, + isCurrent: Ref.get(stateRef).pipe( + Effect.map((state) => { + const current = state.instances.get(instanceId); + return ( + current !== undefined && + current.lifetime === lifetime && + isLiveUpdateCurrent(current.clear, revision, runtimeIdentity) + ); + }), + ), + }); + const replayed = + inst === undefined + ? [] + : Array.from(inst.entries.values()) + .filter((entry) => + isLiveUpdateCurrent(inst.clear, entry.revision, entry.runtimeIdentity), + ) + .toSorted((left, right) => left.revision - right.revision); + for (const entry of replayed) { + yield* onUpdate( + entry.value, + metaFor(entry.runtimeIdentity, entry.revision, entry.lifetime), + ); + } + yield* Stream.fromSubscription(subscription).pipe( + Stream.filter( + (update) => update.instanceId === instanceId && update.revision > snapshotRevision, + ), + Stream.runForEach((update) => + onUpdate( + update.value, + metaFor(update.runtimeIdentity, update.revision, update.lifetime), + ), + ), + ); + }), + ); + + return { clear, publish, get, watch } as const; + }, +); + const make = Effect.gen(function* () { const foregroundStarts = yield* PubSub.unbounded(); const activeForegroundCounts = yield* Ref.make(new Map()); - const availableCommandsUpdates = yield* PubSub.unbounded(); - const availableCommandsByInstance = yield* Ref.make( - new Map(), - ); - const liveConfigurationUpdates = yield* PubSub.unbounded(); - const liveConfigurationByInstance = yield* Ref.make( - new Map(), - ); + const availableCommandsChannel = yield* makeLiveStateChannel({ + clear: "clearAvailableCommands", + publish: "publishAvailableCommands", + get: "getAvailableCommands", + watch: "watchAvailableCommands", + }); + const liveConfigurationChannel = yield* makeLiveStateChannel({ + clear: "clearLiveConfiguration", + publish: "publishLiveConfiguration", + get: "getLiveConfiguration", + watch: "watchLiveConfiguration", + }); const urlAuthActionUpdates = yield* PubSub.unbounded(); const pendingUrlAuthActions = yield* Ref.make( new Map(), @@ -158,95 +444,6 @@ const make = Effect.gen(function* () { effect, ) => sessionMutationPermit.withPermit(effect); - const clearAvailableCommands: AcpRegistryRuntimeCoordinator["Service"]["clearAvailableCommands"] = - (instanceId) => - Ref.update(availableCommandsByInstance, (current) => { - const next = new Map(current); - next.delete(instanceId); - return next; - }); - - const publishAvailableCommands: AcpRegistryRuntimeCoordinator["Service"]["publishAvailableCommands"] = - (instanceId, commands) => - Ref.update(availableCommandsByInstance, (current) => { - const next = new Map(current); - next.set(instanceId, commands); - return next; - }).pipe( - Effect.andThen( - PubSub.publish(availableCommandsUpdates, { - instanceId, - commands, - }), - ), - Effect.asVoid, - ); - - const getAvailableCommands: AcpRegistryRuntimeCoordinator["Service"]["getAvailableCommands"] = - Effect.fn("AcpRegistryRuntimeCoordinator.getAvailableCommands")(function* (instanceId) { - return Option.fromNullishOr((yield* Ref.get(availableCommandsByInstance)).get(instanceId)); - }); - - const watchAvailableCommands: AcpRegistryRuntimeCoordinator["Service"]["watchAvailableCommands"] = - (instanceId, onUpdate) => - Effect.scoped( - Effect.gen(function* () { - // Subscribe before reading to avoid missing publications. - const subscription = yield* PubSub.subscribe(availableCommandsUpdates); - const current = yield* getAvailableCommands(instanceId); - if (Option.isSome(current)) { - yield* onUpdate(current.value); - } - yield* Stream.fromSubscription(subscription).pipe( - Stream.filter((update) => update.instanceId === instanceId), - Stream.runForEach((update) => onUpdate(update.commands)), - ); - }), - ); - - const clearLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["clearLiveConfiguration"] = - (instanceId) => - Ref.update(liveConfigurationByInstance, (current) => { - const next = new Map(current); - next.delete(instanceId); - return next; - }); - - const publishLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["publishLiveConfiguration"] = - (instanceId, configuration) => - Ref.update(liveConfigurationByInstance, (current) => - new Map(current).set(instanceId, configuration), - ).pipe( - Effect.andThen( - PubSub.publish(liveConfigurationUpdates, { - instanceId, - configuration, - }), - ), - Effect.asVoid, - ); - - const getLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["getLiveConfiguration"] = - Effect.fn("AcpRegistryRuntimeCoordinator.getLiveConfiguration")(function* (instanceId) { - return Option.fromNullishOr((yield* Ref.get(liveConfigurationByInstance)).get(instanceId)); - }); - - const watchLiveConfiguration: AcpRegistryRuntimeCoordinator["Service"]["watchLiveConfiguration"] = - (instanceId, onUpdate) => - Effect.scoped( - Effect.gen(function* () { - const subscription = yield* PubSub.subscribe(liveConfigurationUpdates); - const current = yield* getLiveConfiguration(instanceId); - if (Option.isSome(current)) { - yield* onUpdate(current.value); - } - yield* Stream.fromSubscription(subscription).pipe( - Stream.filter((update) => update.instanceId === instanceId), - Stream.runForEach((update) => onUpdate(update.configuration)), - ); - }), - ); - const publishUrlAuthAction = ( instanceId: ProviderInstanceId, action: AcpRegistryUrlAuthAction | null, @@ -284,10 +481,10 @@ const make = Effect.gen(function* () { next.set(instanceId, { action: publishedAction, consent, expiresAt }); return [existing, next] as const; }); + yield* publishUrlAuthAction(instanceId, publishedAction); if (previous !== undefined) { - yield* Deferred.succeed(previous.consent, false).pipe(Effect.ignore); + yield* Deferred.succeed(previous.consent, false); } - yield* publishUrlAuthAction(instanceId, publishedAction); }), ); return yield* Deferred.await(consent).pipe( @@ -302,10 +499,20 @@ const make = Effect.gen(function* () { const acceptUrlAuthentication: AcpRegistryRuntimeCoordinator["Service"]["acceptUrlAuthentication"] = Effect.fn("AcpRegistryRuntimeCoordinator.acceptUrlAuthentication")(function* (input) { - const pending = (yield* Ref.get(pendingUrlAuthActions)).get(input.instanceId); - if (pending?.action.elicitationId !== input.elicitationId) return false; - if (DateTime.isGreaterThanOrEqualTo(yield* DateTime.now, pending.expiresAt)) { - yield* Deferred.succeed(pending.consent, false).pipe(Effect.ignore); + const now = yield* DateTime.now; + const pending = yield* Ref.modify(pendingUrlAuthActions, (current) => { + const existing = current.get(input.instanceId); + if (existing === undefined || existing.action.elicitationId !== input.elicitationId) { + return [undefined, current] as const; + } + const next = new Map(current); + next.delete(input.instanceId); + return [existing, next] as const; + }); + if (pending === undefined) return false; + yield* publishUrlAuthAction(input.instanceId, null); + if (DateTime.toEpochMillis(now) >= DateTime.toEpochMillis(pending.expiresAt)) { + yield* Deferred.succeed(pending.consent, false); return false; } return yield* Deferred.succeed(pending.consent, true); @@ -314,7 +521,15 @@ const make = Effect.gen(function* () { const getUrlAuthAction: AcpRegistryRuntimeCoordinator["Service"]["getUrlAuthAction"] = Effect.fn( "AcpRegistryRuntimeCoordinator.getUrlAuthAction", )(function* (instanceId) { - return Option.fromNullishOr((yield* Ref.get(pendingUrlAuthActions)).get(instanceId)?.action); + const now = yield* DateTime.now; + const pending = (yield* Ref.get(pendingUrlAuthActions)).get(instanceId); + if ( + pending === undefined || + DateTime.toEpochMillis(now) >= DateTime.toEpochMillis(pending.expiresAt) + ) { + return Option.none(); + } + return Option.some(pending.action); }); const watchUrlAuthAction: AcpRegistryRuntimeCoordinator["Service"]["watchUrlAuthAction"] = ( @@ -323,8 +538,11 @@ const make = Effect.gen(function* () { ) => Effect.scoped( Effect.gen(function* () { - const subscription = yield* PubSub.subscribe(urlAuthActionUpdates); - const current = yield* getUrlAuthAction(instanceId); + const { subscription, current } = yield* Effect.gen(function* () { + const sub = yield* PubSub.subscribe(urlAuthActionUpdates); + const cur = yield* getUrlAuthAction(instanceId); + return { subscription: sub, current: cur }; + }).pipe(Effect.withSpan("AcpRegistryRuntimeCoordinator.watchUrlAuthAction.subscribe")); if (Option.isSome(current)) { yield* onUpdate(current.value); } @@ -339,14 +557,14 @@ const make = Effect.gen(function* () { withForegroundStartup, runBackgroundProbe, withSessionMutation, - clearAvailableCommands, - publishAvailableCommands, - getAvailableCommands, - watchAvailableCommands, - clearLiveConfiguration, - publishLiveConfiguration, - getLiveConfiguration, - watchLiveConfiguration, + clearAvailableCommands: availableCommandsChannel.clear, + publishAvailableCommands: availableCommandsChannel.publish, + getAvailableCommands: availableCommandsChannel.get, + watchAvailableCommands: availableCommandsChannel.watch, + clearLiveConfiguration: liveConfigurationChannel.clear, + publishLiveConfiguration: liveConfigurationChannel.publish, + getLiveConfiguration: liveConfigurationChannel.get, + watchLiveConfiguration: liveConfigurationChannel.watch, requestUrlAuthentication, acceptUrlAuthentication, getUrlAuthAction, diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 75311d6598b7e..5cb231a61d208 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -1,4 +1,6 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { sha256 } from "@noble/hashes/sha2.js"; +import * as Hex from "effect/encoding/Hex"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; import { @@ -11,11 +13,15 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution } from "@t3tools/shared/shell"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Scheduler from "effect/Scheduler"; import * as Schema from "effect/Schema"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; @@ -756,695 +762,1031 @@ describe("AcpRegistrySupport", () => { ); }); - it.effect("installs and reuses a registry binary in the managed cache", () => { - const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho example\n"); - const agent = makeAgent({ - binary: { - "linux-x86_64": { - archive: archiveUrl, - cmd: "./bin/example-agent", - args: ["acp"], - sha256: "97b29a636d7ddf7bf3567ae4d48c0f2a9b03943fd808b6efbf74f1dd3db131b7", - }, - }, - }); - const requests: Array = []; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-install-", - }); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, - }); - const first = yield* resolver.resolve(settings(), "/workspace"); - const second = yield* resolver.resolve(settings(), "/workspace"); - - expect(first.spawn.command).toBe(second.spawn.command); - expect(first.spawn.command).toContain( - "/tools/example-agent/1.2.3/linux-x86_64/bin/example-agent", - ); - expect(yield* fileSystem.readFileString(first.spawn.command)).toBe( - "#!/bin/sh\necho example\n", - ); - expect(requests).toEqual([registryUrl, archiveUrl]); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => { - requests.push(request.url); - const response = - request.url === registryUrl - ? new Response(makeRegistry(agent)) - : new Response( - new ReadableStream({ - start(controller) { - controller.enqueue(binaryBytes.slice(0, 8)); - controller.enqueue(binaryBytes.slice(8)); - controller.close(); - }, - }), - ); - return Effect.succeed(HttpClientResponse.fromWeb(request, response)); - }), - ), - ); - }); - - it.effect("gives Antigravity a T3-owned temp directory that is removed with the process", () => { - const agent = { - ...makeAgent({ binary: { "linux-x86_64": { archive: archiveUrl, cmd: "./agy" } } }), - id: "antigravity-acp", - }; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-runtime-temp-", - }); - const runtimeTempDir = `${cacheDir}/antigravity-tmp/acp-registry`; - yield* fileSystem.makeDirectory(`${runtimeTempDir}/run-killed/_MEI123`, { recursive: true }); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - runtimeTempDir, - registryUrl, - }); - expect(yield* fileSystem.exists(`${runtimeTempDir}/run-killed`)).toBe(false); - - const temp = yield* Effect.scoped( - Effect.gen(function* () { - const resolved = yield* resolver.resolve( - settings({ agentId: "antigravity-acp" }), - "/workspace", - { TMPDIR: "/tmp" }, - ); - const directory = resolved.spawn.env?.TMPDIR ?? ""; - expect(directory.startsWith(`${runtimeTempDir}/run-`)).toBe(true); - expect(yield* fileSystem.exists(directory)).toBe(true); - return directory; - }), - ); - expect(yield* fileSystem.exists(temp)).toBe(false); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => - Effect.succeed( - HttpClientResponse.fromWeb( - request, - new Response(request.url === registryUrl ? makeRegistry(agent) : "#!/bin/sh\n"), - ), - ), - ), - ), - ); - }); - - it.effect("installs a contained binary whose name starts with two dots", () => { - const agent = makeAgent({ - binary: { "linux-x86_64": { archive: archiveUrl, cmd: "..example-agent" } }, - }); - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-dot-name-", - }); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, - }); - const resolved = yield* resolver.resolve(settings(), "/workspace"); - - expect(resolved.spawn.command).toContain( - "/tools/example-agent/1.2.3/linux-x86_64/..example-agent", - ); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => - Effect.succeed( - HttpClientResponse.fromWeb( - request, - new Response(request.url === registryUrl ? makeRegistry(agent) : "#!/bin/sh\n"), - ), - ), - ), - ), - ); - }); - - it.effect("keeps a prepared binary ready after the registry advances its version", () => { - const makeBinaryAgent = (version: string) => ({ - ...makeAgent({ - binary: { - "linux-x86_64": { - archive: `https://registry.test/example-agent-${version}.bin`, - cmd: "./bin/example-agent", - }, - }, - }), - version, - }); - let agent = makeBinaryAgent("1.2.3"); - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-advance-", - }); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, - }); - yield* resolver.prepare({ agentId: agent.id }); - - agent = makeBinaryAgent("1.2.4"); - yield* TestClock.adjust("6 minutes"); - yield* resolver.search({ query: "example" }); - - expect(yield* resolver.inspect(settings())).toMatchObject({ - status: "ready", - distribution: "binary", - }); - const resolved = yield* resolver.resolve(settings(), "/workspace", {}); - expect(resolved.spawn.command).toContain( - "/tools/example-agent/1.2.4/linux-x86_64/bin/example-agent", - ); - expect(yield* fileSystem.readFileString(resolved.spawn.command)).toBe( - "#!/bin/sh\necho 1.2.4\n", - ); - - expect(yield* resolver.uninstallManagedBinary({ agentId: agent.id })).toMatchObject({ - removed: true, - }); - expect(yield* resolver.inspect(settings())).toMatchObject({ status: "unprepared" }); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => - Effect.succeed( - HttpClientResponse.fromWeb( - request, - new Response( - request.url === registryUrl - ? makeRegistry(agent) - : `#!/bin/sh\necho ${agent.version}\n`, - ), - ), - ), - ), - ), - ); - }); - it.effect( - "prepares the registry version despite an older PATH binary and permits explicit overrides", + "installs, reuses, and replaces a registry binary in the managed cache when the artifact changes", () => { - const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho managed\n"); - const agent = makeAgent({ + const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho example\n"); + const replacementBytes = new TextEncoder().encode("#!/bin/sh\necho example-repackaged\n"); + const rehashedBytes = new TextEncoder().encode("#!/bin/sh\necho example-rehashed\n"); + const replacementArchiveUrl = "https://registry.test/example-agent-repackaged.bin"; + const replacementSha256 = Hex.encode(sha256(replacementBytes)); + const rehashedSha256 = Hex.encode(sha256(rehashedBytes)); + let serveRehashedAtReplacement = false; + let currentAgent = makeAgent({ binary: { "linux-x86_64": { archive: archiveUrl, cmd: "./bin/example-agent", args: ["acp"], - sha256: "e1eb7c905b91c400af2ec858628aec22866bfda1383b93ceb73ae01d9769fb31", + sha256: "97b29a636d7ddf7bf3567ae4d48c0f2a9b03943fd808b6efbf74f1dd3db131b7", }, }, }); const requests: Array = []; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-system-", + prefix: "t3-acp-registry-install-", }); - const systemBinDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-system-bin-", - }); - const systemBinary = path.join(systemBinDir, "example-agent"); - yield* fileSystem.writeFileString(systemBinary, "#!/bin/sh\necho system\n"); - yield* fileSystem.chmod(systemBinary, 0o755); - const environment = { PATH: systemBinDir }; - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir, toolsDir: `${cacheDir}/tools`, registryUrl, - }).pipe(Effect.provideService(HostProcess.Environment, environment)); - yield* resolver.search({ query: "example" }); - expect(yield* resolver.inspect(settings(), environment)).toMatchObject({ - status: "unprepared", }); + const first = yield* resolver.resolve(settings(), "/workspace"); + const second = yield* resolver.resolve(settings(), "/workspace"); - const overridden = settings({ commandPath: systemBinary }); - expect(yield* resolver.inspect(overridden, environment)).toMatchObject({ - status: "ready", - version: null, - }); - const custom = yield* resolver.resolve(overridden, "/workspace", environment); - expect(custom.spawn.command).toBe(systemBinary); - expect(custom.spawn.args).toEqual(["acp"]); - expect(requests).toEqual([registryUrl]); - - yield* resolver.prepare({ agentId: "example-agent" }); - const resolved = yield* resolver.resolve(settings(), "/workspace", environment); - expect(resolved.spawn.command).not.toBe(systemBinary); - expect(yield* fileSystem.readFileString(resolved.spawn.command)).toBe( - "#!/bin/sh\necho managed\n", + expect(first.spawn.command).toBe(second.spawn.command); + expect(first.spawn.command).toContain( + "/tools/example-agent/1.2.3/linux-x86_64/bin/example-agent", ); - expect(yield* fileSystem.readFileString(systemBinary)).toBe("#!/bin/sh\necho system\n"); + expect(yield* fileSystem.readFileString(first.spawn.command)).toBe( + "#!/bin/sh\necho example\n", + ); + expect(requests).toEqual([registryUrl, archiveUrl]); - const inspection = yield* resolver.inspect(settings(), environment); - expect(inspection).toMatchObject({ - status: "ready", - distribution: "binary", - version: "1.2.3", + // Repackaging at the same version installs into an immutable artifact-scoped sibling slot, + // keeping the primary install intact for active sessions while preferring the new slot. + currentAgent = makeAgent({ + binary: { + "linux-x86_64": { + archive: replacementArchiveUrl, + cmd: "./bin/example-agent", + args: ["acp"], + sha256: replacementSha256, + }, + }, }); + yield* resolver.invalidateIndex(); + yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const third = yield* resolver.resolve(settings(), "/workspace"); + const fourth = yield* resolver.resolve(settings(), "/workspace"); + expect(third.spawn.command).not.toBe(first.spawn.command); + expect(third.spawn.command).toMatch( + /\/tools\/example-agent\/1\.2\.3\/linux-x86_64-[0-9a-f]{12}\/bin\/example-agent$/u, + ); + expect(fourth.spawn.command).toBe(third.spawn.command); + expect(third.launchIdentity).not.toBe(first.launchIdentity); + expect(yield* fileSystem.readFileString(first.spawn.command)).toBe( + "#!/bin/sh\necho example\n", + ); + expect(yield* fileSystem.readFileString(third.spawn.command)).toBe( + "#!/bin/sh\necho example-repackaged\n", + ); + expect(requests).toEqual([registryUrl, archiveUrl, registryUrl, replacementArchiveUrl]); - expect(requests).toEqual([registryUrl, registryUrl, archiveUrl]); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => { - requests.push(request.url); - return Effect.succeed( - HttpClientResponse.fromWeb( - request, - request.url === registryUrl - ? new Response(makeRegistry(agent)) - : new Response(binaryBytes.buffer as ArrayBuffer), - ), - ); - }), - ), - ); - }, - ); + const path = yield* Path.Path; + const managedDirs = yield* AcpRegistrySupport.acpRegistryManagedBinaryDirectories({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + platform: "linux", + architecture: "x64", + }); + expect(managedDirs.slice(0, 2)).toEqual([ + path.dirname(third.spawn.command), + path.dirname(first.spawn.command), + ]); - it.effect("installs a tar archive with a root entry and a listing larger than 1 MiB", () => { - const downloadUrl = "https://registry.test/agent.tar.gz"; - const agent = makeAgent({ - binary: { "linux-x86_64": { archive: downloadUrl, cmd: "./agent" } }, - }); - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-root-entry-" }); - const source = `${cacheDir}/source`; - yield* fileSystem.makeDirectory(source); - yield* fileSystem.writeFileString(`${source}/agent`, "#!/bin/sh\necho managed\n"); - // 5,000 long names list past the generic 1 MiB command output cap. - const entries = `${source}/entries`; - yield* fileSystem.makeDirectory(entries); - yield* Effect.forEach( - Array.from({ length: 5_000 }, (_, index) => index), - (index) => fileSystem.writeFileString(`${entries}/${index}-${"e".repeat(240)}`, ""), - { concurrency: 16 }, - ); - const archivePath = `${cacheDir}/agent.tar.gz`; - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const tar = yield* spawner.spawn( - ChildProcess.make("tar", ["-czf", archivePath, "-C", source, "."]), - ); - expect(yield* tar.exitCode).toBe(0); - const archive = yield* fileSystem.readFile(archivePath); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, + // Rolling back to artifact A (in the primary receipted slot) ranks primary A ahead of the + // newer hashed replacement slot B on terminal PATH. + currentAgent = makeAgent({ + binary: { + "linux-x86_64": { + archive: archiveUrl, + cmd: "./bin/example-agent", + args: ["acp"], + sha256: "97b29a636d7ddf7bf3567ae4d48c0f2a9b03943fd808b6efbf74f1dd3db131b7", + }, + }, + }); + yield* resolver.invalidateIndex(); + yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const rolledBackToPrimary = yield* resolver.resolve(settings(), "/workspace"); + expect(rolledBackToPrimary.spawn.command).toBe(first.spawn.command); + const managedDirsAfterRollback = + yield* AcpRegistrySupport.acpRegistryManagedBinaryDirectories({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + platform: "linux", + architecture: "x64", + }); + expect(managedDirsAfterRollback.slice(0, 2)).toEqual([ + path.dirname(first.spawn.command), + path.dirname(third.spawn.command), + ]); + + // Changing only sha256 at the same archive URL & cmd must install into a new artifact slot. + serveRehashedAtReplacement = true; + currentAgent = makeAgent({ + binary: { + "linux-x86_64": { + archive: replacementArchiveUrl, + cmd: "./bin/example-agent", + args: ["acp"], + sha256: rehashedSha256, + }, + }, + }); + yield* resolver.invalidateIndex(); + yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const rehashed = yield* resolver.resolve(settings(), "/workspace"); + expect(rehashed.spawn.command).not.toBe(third.spawn.command); + expect(yield* fileSystem.readFileString(rehashed.spawn.command)).toBe( + "#!/bin/sh\necho example-rehashed\n", + ); + expect(yield* fileSystem.readFileString(third.spawn.command)).toBe( + "#!/bin/sh\necho example-repackaged\n", + ); + + // A failed replacement (checksum mismatch) leaves existing installed binaries intact. + currentAgent = makeAgent({ + binary: { + "linux-x86_64": { + archive: replacementArchiveUrl, + cmd: "./bin/example-agent", + args: ["acp"], + sha256: "0".repeat(64), + }, + }, + }); + yield* resolver.invalidateIndex(); + yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const checksumError = yield* resolver.resolve(settings(), "/workspace").pipe(Effect.flip); + expect(checksumError.reason).toBe("checksum_mismatch"); + expect(yield* fileSystem.readFileString(rehashed.spawn.command)).toBe( + "#!/bin/sh\necho example-rehashed\n", + ); + + // Uninstalling removes the primary slot and all artifact-scoped sibling slots. + expect(yield* resolver.uninstallManagedBinary({ agentId: "example-agent" })).toEqual({ + agentId: "example-agent", + removed: true, + }); + expect(yield* fileSystem.exists(`${cacheDir}/tools/example-agent`)).toBe(false); }).pipe( - Effect.provideService( - HttpClient.HttpClient, - HttpClient.make((request) => - Effect.succeed( - HttpClientResponse.fromWeb( - request, - request.url === registryUrl - ? new Response(makeRegistry(agent)) - : new Response(archive), - ), - ), - ), + Effect.scoped, + Effect.provide( + layerResolver((request) => { + requests.push(request.url); + const payload = + request.url === replacementArchiveUrl + ? serveRehashedAtReplacement + ? rehashedBytes + : replacementBytes + : binaryBytes; + const response = + request.url === registryUrl + ? new Response(makeRegistry(currentAgent)) + : new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(payload.slice(0, 8)); + controller.enqueue(payload.slice(8)); + controller.close(); + }, + }), + ); + return Effect.succeed(HttpClientResponse.fromWeb(request, response)); + }), ), ); - yield* resolver.prepare({ agentId: agent.id }); - const resolved = yield* resolver.resolve(settings(), "/workspace", {}); - expect(resolved.spawn.command).toBe( - yield* fileSystem.realPath(`${cacheDir}/tools/example-agent/1.2.3/linux-x86_64/agent`), - ); - expect(yield* fileSystem.readFileString(resolved.spawn.command)).toBe( - "#!/bin/sh\necho managed\n", - ); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll( - NodeServices.layer, - NodeCrypto.layer, - TestProviderHost.layer().pipe( - Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), - ), - ), - ), - Effect.provideService(HostProcess.Platform, "linux"), - Effect.provideService(HostProcess.Architecture, "x64"), - ); - }); + }, + ); - it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( - "leaves the mode of a file outside the install root when the command links to it", + it.effect( + "preserves offline legacy binaries without fabricating a receipt, retries same-version archive swaps on download failure, and falls back to prior receipted versions", () => { - const downloadUrl = "https://registry.test/agent.tar.gz"; - const agent = makeAgent({ - binary: { "linux-x86_64": { archive: downloadUrl, cmd: "./agent" } }, - }); + const legacyArchiveUrl = "https://example.test/example-agent-1.0.0.bin"; + const swappedArchiveUrl = "https://example.test/example-agent-1.0.0-fixed.bin"; + const v2ArchiveUrl = "https://example.test/example-agent-2.0.0.bin"; + const v1PrimaryBytes = new TextEncoder().encode("#!/bin/sh\necho v1-primary\n"); + const v1Bytes = new TextEncoder().encode("#!/bin/sh\necho v1-fixed\n"); + const v2Bytes = new TextEncoder().encode("#!/bin/sh\necho v2\n"); + let offline = true; + let failSwappedDownload = false; + let failV2Download = true; + let serveEmptyRegistry = false; + let checksumGate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + let requests: Array = []; + let currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: legacyArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v1"], + env: { AGENT_CHANNEL: "v1" }, + }, + }, + }), + version: "1.0.0", + }; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-outside-link-", + prefix: "t3-acp-registry-offline-fallback-", }); - const outsideFile = `${cacheDir}/outside`; - yield* fileSystem.writeFileString(outsideFile, "private\n"); - yield* fileSystem.chmod(outsideFile, 0o600); - const source = `${cacheDir}/source`; - yield* fileSystem.makeDirectory(source); - yield* fileSystem.symlink(outsideFile, `${source}/agent`); - const archivePath = `${cacheDir}/agent.tar.gz`; - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const tar = yield* spawner.spawn( - ChildProcess.make("tar", ["-czf", archivePath, "-C", source, "agent"]), + const toolsDir = path.join(cacheDir, "tools"); + const legacyRoot = path.join(toolsDir, "example-agent", "1.0.0", "linux-x86_64"); + const legacyBinary = path.join(legacyRoot, "bin", "example-agent"); + const legacyReceipt = path.join(legacyRoot, ".t3-artifact.json"); + yield* fileSystem.makeDirectory(path.dirname(legacyBinary), { recursive: true }); + yield* fileSystem.writeFileString(legacyBinary, "#!/bin/sh\necho legacy-v1\n"); + yield* fileSystem.chmod(legacyBinary, 0o755); + yield* fileSystem.makeDirectory(path.join(cacheDir, "acp-registry"), { recursive: true }); + yield* fileSystem.writeFileString( + path.join(cacheDir, "acp-registry", "registry.json"), + makeRegistry(currentAgent), ); - expect(yield* tar.exitCode).toBe(0); - const archive = yield* fileSystem.readFile(archivePath); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir, - toolsDir: `${cacheDir}/tools`, + toolsDir, registryUrl, - }).pipe( - Effect.provideService( - HttpClient.HttpClient, - HttpClient.make((request) => - Effect.succeed( - HttpClientResponse.fromWeb( - request, - request.url === registryUrl - ? new Response(makeRegistry(agent)) - : new Response(archive), - ), - ), - ), - ), - ); + }); - const error = yield* resolver.prepare({ agentId: agent.id }).pipe(Effect.flip); + // 1. Pre-existing receipt-less binary works offline without downloading or fabricating a receipt. + const offlineLegacy = yield* resolver.resolve(settings(), "/workspace"); + expect(offlineLegacy.agent?.version).toBe("1.0.0"); + expect(offlineLegacy.spawn.command).toBe(legacyBinary); + expect(offlineLegacy.fallback).toBeUndefined(); + expect(requests).toEqual([]); + expect(yield* fileSystem.exists(legacyReceipt)).toBe(false); - expect(error.reason).toBe("archive_invalid"); - expect((yield* fileSystem.stat(outsideFile)).mode & 0o777).toBe(0o600); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll( - NodeServices.layer, - NodeCrypto.layer, - TestProviderHost.layer().pipe( - Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), - ), - ), - ), - Effect.provideService(HostProcess.Platform, "linux"), - Effect.provideService(HostProcess.Architecture, "x64"), - ); - }, - ); + // Changing only args/env while keeping archive/cmd/sha256 unchanged still reuses the legacy binary. + offline = false; + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: legacyArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v1-updated-args"], + env: { AGENT_CHANNEL: "v1-updated" }, + }, + }, + }), + version: "1.0.0", + }; + yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const legacyWithUpdatedArgs = yield* resolver.resolve(settings(), "/workspace"); + expect(legacyWithUpdatedArgs.spawn.command).toBe(legacyBinary); + expect(legacyWithUpdatedArgs.spawn.args).toEqual(["--v1-updated-args"]); + expect(yield* fileSystem.exists(legacyReceipt)).toBe(false); - it.effect("searches compatible agents with deterministic ranking and bounded metadata", () => { - const exact = { - ...makeAgent({ npx: { package: "@example/acp@1.2.3" } }), - id: "codex-acp", - name: "Codex", - authors: ["OpenAI", "Zed Industries"], - license: "Apache-2.0", - website: "https://example.test/codex", - repository: "https://example.test/codex/source", - icon: "https://example.test/codex.svg", - } satisfies AcpRegistrySupport.AcpRegistryAgent; - const descriptionMatch = { - ...makeAgent({ npx: { package: "other-agent@1.2.3" } }), - id: "other-agent", - name: "Other Agent", - description: "An adapter for Codex workflows", - } satisfies AcpRegistrySupport.AcpRegistryAgent; - const incompatible = { - ...makeAgent({ - binary: { - "darwin-aarch64": { archive: archiveUrl, cmd: "agent" }, - }, - }), - id: "darwin-only", - name: "Codex Darwin", - } satisfies AcpRegistrySupport.AcpRegistryAgent; + // 2. If the registry updates the same-version archive URL and the new download fails, + // a durable baseline permanently rejects the receipt-less legacy binary for the new artifact + // across repeated calls and server restarts. + failSwappedDownload = true; + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: swappedArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v1-fixed"], + env: { AGENT_CHANNEL: "v1-fixed" }, + }, + }, + }), + version: "1.0.0", + }; + yield* resolver.invalidateIndex(); + yield* resolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const changedArtifactFailure1 = yield* resolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + expect(changedArtifactFailure1.reason).toBe("download_failed"); + const changedArtifactFailure2 = yield* resolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + expect(changedArtifactFailure2.reason).toBe("download_failed"); + const restartedResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir, + registryUrl, + }); + const changedArtifactAfterRestart = yield* restartedResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + expect(changedArtifactAfterRestart.reason).toBe("download_failed"); + // Superseded legacy primary slots are also excluded from managed terminal PATH directories. + expect( + yield* AcpRegistrySupport.acpRegistryManagedBinaryDirectories({ + cacheDir, + toolsDir, + platform: "linux", + architecture: "x64", + }), + ).not.toContain(path.dirname(legacyBinary)); - const lookups: string[] = []; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-search-", - }); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, - }).pipe( - Effect.provideService(SpawnExecutableResolution, async (command) => { - lookups.push(command); - return "/bin/npm"; - }), - ); - const result = yield* resolver.search({ query: "codex" }); + // 2b. A version bump (1.0.0 legacy A -> 2.0.0) followed by a rollback to 1.0.0 (archive B) + // still records legacy A's baseline during the bump so legacy A is never launched as B. + const versionBumpCacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-legacy-bump-", + }); + const versionBumpToolsDir = path.join(versionBumpCacheDir, "tools"); + const bumpLegacyBinary = path.join( + versionBumpToolsDir, + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(bumpLegacyBinary), { recursive: true }); + yield* fileSystem.writeFileString(bumpLegacyBinary, "#!/bin/sh\necho legacy-bump\n"); + yield* fileSystem.chmod(bumpLegacyBinary, 0o755); + yield* fileSystem.makeDirectory(path.join(versionBumpCacheDir, "acp-registry"), { + recursive: true, + }); + yield* fileSystem.writeFileString( + path.join(versionBumpCacheDir, "acp-registry", "registry.json"), + makeRegistry({ + ...makeAgent({ + binary: { + "linux-x86_64": { archive: legacyArchiveUrl, cmd: "./bin/example-agent" }, + }, + }), + version: "1.0.0", + }), + ); + const bumpResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: versionBumpCacheDir, + toolsDir: versionBumpToolsDir, + registryUrl, + }); + currentAgent = { + ...makeAgent({ + binary: { "linux-x86_64": { archive: v2ArchiveUrl, cmd: "./bin/example-agent" } }, + }), + version: "2.0.0", + }; + yield* bumpResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + currentAgent = { + ...makeAgent({ + binary: { "linux-x86_64": { archive: swappedArchiveUrl, cmd: "./bin/example-agent" } }, + }), + version: "1.0.0", + }; + yield* bumpResolver.invalidateIndex(); + yield* bumpResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const bumpRollbackError = yield* bumpResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + expect(bumpRollbackError.reason).toBe("download_failed"); - expect(lookups).toEqual(["npm"]); - expect(result.agents.map((agent) => agent.id)).toEqual(["codex-acp", "other-agent"]); - expect(result.agents[0]).toMatchObject({ - authors: ["OpenAI", "Zed Industries"], - distribution: "npx", - integrity: "registry", - license: "Apache-2.0", - }); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => - Effect.succeed( - HttpClientResponse.fromWeb( - request, - new Response( - JSON.stringify({ - version: "1.0.0", - agents: [descriptionMatch, incompatible, exact], - }), - ), - ), - ), + // 2c. If persisting legacy-baselines.json fails, registry.json must stay on artifact A so + // a restarted server never mistakes legacy A for artifact B. + const unwritableBaselineDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-baseline-fail-", + }); + const unwritableToolsDir = path.join(unwritableBaselineDir, "tools"); + const unwritableLegacyBin = path.join( + unwritableToolsDir, + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(unwritableLegacyBin), { recursive: true }); + yield* fileSystem.writeFileString( + unwritableLegacyBin, + "#!/bin/sh\necho legacy-unwritable\n", + ); + yield* fileSystem.chmod(unwritableLegacyBin, 0o755); + const unwritableRegistryPath = path.join( + unwritableBaselineDir, + "acp-registry", + "registry.json", + ); + yield* fileSystem.makeDirectory(path.dirname(unwritableRegistryPath), { recursive: true }); + const initialLegacyRegistryJson = makeRegistry({ + ...makeAgent({ + binary: { + "linux-x86_64": { archive: legacyArchiveUrl, cmd: "./bin/example-agent" }, + }, + }), + version: "1.0.0", + }); + yield* fileSystem.writeFileString(unwritableRegistryPath, initialLegacyRegistryJson); + const missingDirErr = yield* fileSystem + .readFileString(path.join(unwritableBaselineDir, "missing-sentinel")) + .pipe(Effect.flip); + const failBaselineWriteFs: FileSystem.FileSystem = { + ...fileSystem, + writeFileString: (filePath, data, options) => + filePath.includes("legacy-baselines.json") + ? Effect.fail(missingDirErr) + : fileSystem.writeFileString(filePath, data, options), + }; + const unwritableResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: unwritableBaselineDir, + toolsDir: unwritableToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, failBaselineWriteFs)); + yield* unwritableResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect( + (yield* unwritableResolver.resolve(settings(), "/workspace").pipe(Effect.flip)).reason, + ).toBe("download_failed"); + // Disk registry.json was NOT overwritten with B because baseline persistence failed. + expect(yield* fileSystem.readFileString(unwritableRegistryPath)).toBe( + initialLegacyRegistryJson, + ); + // After restart while offline, the catalog still reads A from disk (never B). + offline = true; + const restartedOfflineResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: unwritableBaselineDir, + toolsDir: unwritableToolsDir, + registryUrl, + }); + const offlineAfterFailedBaseline = yield* restartedOfflineResolver.resolve( + settings(), + "/workspace", + ); + expect(offlineAfterFailedBaseline.spawn.command).toBe(unwritableLegacyBin); + offline = false; + + // 3. A single resolve() starting from a stale failing archive URL refreshes the index, + // retries the updated same-version archive URL, and succeeds. + const retryCacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-stale-retry-", + }); + const staleRetryAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: "https://example.test/example-agent-1.0.0-removed.bin", + cmd: "./bin/example-agent", + args: ["--v1-old"], + }, + }, + }), + version: "1.0.0", + }; + yield* fileSystem.makeDirectory(path.join(retryCacheDir, "acp-registry"), { + recursive: true, + }); + yield* fileSystem.writeFileString( + path.join(retryCacheDir, "acp-registry", "registry.json"), + makeRegistry(staleRetryAgent), + ); + failSwappedDownload = false; + requests = []; + const retryResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: retryCacheDir, + toolsDir: path.join(retryCacheDir, "tools"), + registryUrl, + }); + const retriedResolved = yield* retryResolver.resolve(settings(), "/workspace"); + expect(retriedResolved.agent?.version).toBe("1.0.0"); + expect(yield* fileSystem.readFileString(retriedResolved.spawn.command)).toBe( + "#!/bin/sh\necho v1-fixed\n", + ); + expect(requests).toEqual([ + "https://example.test/example-agent-1.0.0-removed.bin", + registryUrl, + swappedArchiveUrl, + ]); + + // Install a receipted primary slot AND a newer receipted artifact slot in 1.0.0 on a clean cache + // so prior-version fallback and terminal PATH ordering can be verified unambiguously. + const fallbackCacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-prior-version-", + }); + const fallbackToolsDir = path.join(fallbackCacheDir, "tools"); + const fallbackResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: fallbackCacheDir, + toolsDir: fallbackToolsDir, + registryUrl, + }); + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: legacyArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v1-primary"], + env: { AGENT_CHANNEL: "v1-primary" }, + }, + }, + }), + version: "1.0.0", + }; + const primaryV1 = yield* fallbackResolver.resolve(settings(), "/workspace"); + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: swappedArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v1-fixed"], + env: { AGENT_CHANNEL: "v1-fixed" }, + }, + }, + }), + version: "1.0.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const swappedResolved = yield* fallbackResolver.resolve(settings(), "/workspace"); + expect(swappedResolved.spawn.command).toMatch( + /linux-x86_64-[0-9a-f]{12}[\\/]bin[\\/]example-agent$/, + ); + + // 4. A mismatched receipt at the same version is never reused when a repackaged download fails. + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: "https://example.test/example-agent-1.0.0-broken.bin", + cmd: "./bin/example-agent", + args: ["--v1-broken"], + }, + }, + }), + version: "1.0.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const mismatchedSameVersionError = yield* fallbackResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + expect(mismatchedSameVersionError.reason).toBe("download_failed"); + + // 5. When upstream publishes 2.0.0 whose download fails (or checksum mismatches), resolve falls + // back to the newest receipted prior slot (1.0.0 replacement) and terminal PATH keeps it first. + failV2Download = true; + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: v2ArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v2"], + env: { AGENT_CHANNEL: "v2" }, + }, + }, + }), + version: "2.0.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackToV1 = yield* fallbackResolver.resolve(settings(), "/workspace"); + expect(fallbackToV1.fallback).toBe(true); + expect(fallbackToV1.indexRevision).toBeUndefined(); + expect(fallbackToV1.agent?.version).toBe("1.0.0"); + expect(fallbackToV1.spawn.command).toBe(swappedResolved.spawn.command); + expect(fallbackToV1.spawn.args).toEqual(["--v1-fixed"]); + expect(fallbackToV1.spawn.env?.AGENT_CHANNEL).toBe("v1-fixed"); + expect(fallbackToV1.launchIdentity).toBe(swappedResolved.launchIdentity); + + const managedAfterV2Bump = yield* AcpRegistrySupport.acpRegistryManagedBinaryDirectories({ + cacheDir: fallbackCacheDir, + toolsDir: fallbackToolsDir, + platform: "linux", + architecture: "x64", + }); + expect(managedAfterV2Bump.slice(0, 2)).toEqual([ + path.dirname(swappedResolved.spawn.command), + path.dirname(primaryV1.spawn.command), + ]); + + // A broken 2.0.0 checksum also falls back to receipted 1.0.0 rather than stranding the user. + failV2Download = false; + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: v2ArchiveUrl, + cmd: "./bin/example-agent", + sha256: "0".repeat(64), + }, + }, + }), + version: "2.0.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const checksumFallback = yield* fallbackResolver.resolve(settings(), "/workspace"); + expect(checksumFallback.fallback).toBe(true); + expect(checksumFallback.agent?.version).toBe("1.0.0"); + expect(checksumFallback.spawn.command).toBe(swappedResolved.spawn.command); + + // 6. Installing 2.0.0 and then rolling back upstream to 1.5.0 (which fails download) must fall + // back only to versions strictly below 1.5.0 (1.0.0), never silently running newer 2.0.0. + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: v2ArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v2"], + }, + }, + }), + version: "2.0.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const installedV2 = yield* fallbackResolver.resolve(settings(), "/workspace"); + expect(installedV2.agent?.version).toBe("2.0.0"); + + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: "https://example.test/example-agent-1.5.0.bin", + cmd: "./bin/example-agent", + }, + }, + }), + version: "1.5.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const rollbackFallback = yield* fallbackResolver.resolve(settings(), "/workspace"); + expect(rollbackFallback.fallback).toBe(true); + expect(rollbackFallback.agent?.version).toBe("1.0.0"); + expect(rollbackFallback.failedTarget?.version).toBe("1.5.0"); + + // 7. SemVer 2.0.0 §11 prerelease ordering: non-numeric "1a" has higher precedence than + // numeric "2", so 2.1.0-1a must NOT be chosen as a fallback when 2.1.0-2 fails. + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { archive: v2ArchiveUrl, cmd: "./bin/example-agent" }, + }, + }), + version: "2.1.0-1a", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* fallbackResolver.resolve(settings(), "/workspace")).agent?.version).toBe( + "2.1.0-1a", + ); + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: "https://example.test/example-agent-2.1.0-2.bin", + cmd: "./bin/example-agent", + }, + }, + }), + version: "2.1.0-2", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const semverFallback = yield* fallbackResolver.resolve(settings(), "/workspace"); + expect(semverFallback.fallback).toBe(true); + expect(semverFallback.agent?.version).toBe("2.0.0"); + + // 8. A corrupt tar archive (tar exits non-zero) triggers archive_invalid and falls back to + // the newest receipted version below 2.2.0 (2.1.0-1a), whereas a locally corrupted cached + // slot fails with install_failed. + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: "https://example.test/corrupt-2.2.0.tar.gz", + cmd: "./bin/example-agent", + }, + }, + }), + version: "2.2.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const corruptArchiveFallback = yield* fallbackResolver.resolve(settings(), "/workspace"); + expect(corruptArchiveFallback.fallback).toBe(true); + expect(corruptArchiveFallback.agent?.version).toBe("2.1.0-1a"); + expect(corruptArchiveFallback.failedTarget?.version).toBe("2.2.0"); + + // Tampering with an already-installed cached executable must fail with install_failed + // instead of silently falling back to an older version. + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: v2ArchiveUrl, + cmd: "./bin/example-agent", + args: ["--v2"], + }, + }, + }), + version: "2.0.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* fileSystem.chmod(installedV2.spawn.command, 0o644); + const tamperedCacheError = yield* fallbackResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + expect(tamperedCacheError.reason).toBe("install_failed"); + yield* fileSystem.chmod(installedV2.spawn.command, 0o755); + + // 9. A concurrent agent removal published while a checksum_mismatch download is in flight + // is honored immediately instead of falling back to an older installed version. + const removalGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + checksumGate = removalGate; + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: v2ArchiveUrl, + cmd: "./bin/example-agent", + sha256: "0".repeat(64), + }, + }, + }), + version: "2.3.0", + }; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const resolvingChecksum = yield* fallbackResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(removalGate.started); + serveEmptyRegistry = true; + yield* fallbackResolver.invalidateIndex(); + yield* fallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + checksumGate = null; + yield* Deferred.succeed(removalGate.release, undefined); + const removedDuringChecksumError = yield* Fiber.join(resolvingChecksum); + expect(removedDuringChecksumError.reason).toBe("agent_not_found"); + serveEmptyRegistry = false; + + // 10. Stale-lock promotion interleaving never removes a concurrently published artifact slot. + const raceCacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-stale-lock-race-", + }); + const raceToolsDir = path.join(raceCacheDir, "tools"); + const raceBaseResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: raceCacheDir, + toolsDir: raceToolsDir, + registryUrl, + }); + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { archive: legacyArchiveUrl, cmd: "./bin/example-agent" }, + }, + }), + version: "1.0.0", + }; + yield* raceBaseResolver.resolve(settings(), "/workspace"); + currentAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { archive: swappedArchiveUrl, cmd: "./bin/example-agent" }, + }, + }), + version: "1.0.0", + }; + const renameBlocked = yield* Deferred.make(); + const releaseFirstRename = yield* Deferred.make(); + let firstRenameIntercepted = false; + let removedArtifactSlot = false; + const raceFs: FileSystem.FileSystem = { + ...fileSystem, + remove: (targetPath, options) => { + if (/linux-x86_64-[0-9a-f]{12}$/u.test(targetPath)) { + removedArtifactSlot = true; + } + return fileSystem.remove(targetPath, options); + }, + rename: (oldPath, newPath) => { + if (!firstRenameIntercepted && /linux-x86_64-[0-9a-f]{12}$/u.test(newPath)) { + firstRenameIntercepted = true; + return Deferred.succeed(renameBlocked, undefined).pipe( + Effect.andThen(Deferred.await(releaseFirstRename)), + Effect.andThen(fileSystem.rename(oldPath, newPath)), + ); + } + return fileSystem.rename(oldPath, newPath); + }, + }; + const raceInstaller1 = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: raceCacheDir, + toolsDir: raceToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, raceFs)); + const raceInstaller2 = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: raceCacheDir, + toolsDir: raceToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, raceFs)); + yield* raceInstaller1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* raceInstaller2.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const install1Fiber = yield* raceInstaller1 + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(renameBlocked); + // Age the lock past INSTALL_LOCK_STALE_MS so installer 2 takes over and publishes artifactRoot. + const lockPath = path.join(raceToolsDir, "example-agent", "1.0.0", "linux-x86_64.lock"); + yield* fileSystem.utimes(lockPath, 0, 0); + yield* TestClock.adjust("6 minutes"); + const installedBy2 = yield* raceInstaller2.resolve(settings(), "/workspace"); + yield* Deferred.succeed(releaseFirstRename, undefined); + const installedBy1 = yield* Fiber.join(install1Fiber); + expect(removedArtifactSlot).toBe(false); + expect(installedBy1.spawn.command).toBe(installedBy2.spawn.command); + expect(yield* fileSystem.readFileString(installedBy1.spawn.command)).toBe( + "#!/bin/sh\necho v1-fixed\n", + ); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + requests.push(request.url); + if (offline) { + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("offline", { status: 503 })), + ); + } + if (request.url === registryUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + serveEmptyRegistry + ? JSON.stringify({ version: "1.0.0", agents: [] }) + : makeRegistry(currentAgent), + ), + ), + ); + } + if (request.url === "https://example.test/corrupt-2.2.0.tar.gz") { + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("not-a-valid-tar-archive")), + ); + } + if (request.url === legacyArchiveUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(v1PrimaryBytes)), + ); + } + if (request.url === swappedArchiveUrl && !failSwappedDownload) { + return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(v1Bytes))); + } + if (request.url === v2ArchiveUrl && !failV2Download) { + const gate = checksumGate; + const respond = Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(v2Bytes)), + ); + return gate === null + ? respond + : Deferred.succeed(gate.started, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + Effect.andThen(respond), + ); + } + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("unavailable", { status: 503 })), + ); + }), ), - ), - ); - }); + ); + }, + ); - it.effect("searches reuse an index fetched in the last five minutes", () => { - const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); - let requests = 0; + it.effect("gives Antigravity a T3-owned temp directory that is removed with the process", () => { + const agent = { + ...makeAgent({ binary: { "linux-x86_64": { archive: archiveUrl, cmd: "./agy" } } }), + id: "antigravity-acp", + }; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-refresh-", + prefix: "t3-acp-registry-runtime-temp-", }); + const runtimeTempDir = `${cacheDir}/antigravity-tmp/acp-registry`; + yield* fileSystem.makeDirectory(`${runtimeTempDir}/run-killed/_MEI123`, { recursive: true }); const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir, toolsDir: `${cacheDir}/tools`, + runtimeTempDir, registryUrl, }); - yield* Effect.all( - [resolver.search({ query: "example" }), resolver.search({ query: "example" })], - { concurrency: "unbounded" }, - ); - expect(requests).toBe(1); - - yield* TestClock.adjust("4 minutes"); - yield* resolver.search({ query: "other" }); - expect(requests).toBe(1); + expect(yield* fileSystem.exists(`${runtimeTempDir}/run-killed`)).toBe(false); - yield* TestClock.adjust("1 minute"); - yield* resolver.search({ query: "example" }); - expect(requests).toBe(2); + const temp = yield* Effect.scoped( + Effect.gen(function* () { + const resolved = yield* resolver.resolve( + settings({ agentId: "antigravity-acp" }), + "/workspace", + { TMPDIR: "/tmp" }, + ); + const directory = resolved.spawn.env?.TMPDIR ?? ""; + expect(directory.startsWith(`${runtimeTempDir}/run-`)).toBe(true); + expect(yield* fileSystem.exists(directory)).toBe(true); + return directory; + }), + ); + expect(yield* fileSystem.exists(temp)).toBe(false); }).pipe( Effect.scoped, Effect.provide( - layerResolver((request) => { - requests += 1; - return Effect.yieldNow.pipe( - Effect.as(HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent)))), - ); - }), + layerResolver((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(request.url === registryUrl ? makeRegistry(agent) : "#!/bin/sh\n"), + ), + ), + ), ), ); }); - it.effect("searches retry the network after falling back to the cached index", () => { - const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); - let requests = 0; + it.effect("installs a contained binary whose name starts with two dots", () => { + const agent = makeAgent({ + binary: { "linux-x86_64": { archive: archiveUrl, cmd: "..example-agent" } }, + }); return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-retry-", + prefix: "t3-acp-registry-dot-name-", }); - yield* fileSystem.makeDirectory(`${cacheDir}/acp-registry`, { recursive: true }); - yield* fileSystem.writeFileString( - `${cacheDir}/acp-registry/registry.json`, - makeRegistry(agent), - ); const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir, toolsDir: `${cacheDir}/tools`, registryUrl, }); - const offline = yield* resolver.search({ query: "example" }); - expect(offline.agents.map((result) => result.id)).toEqual([agent.id]); - expect(requests).toBe(1); + const resolved = yield* resolver.resolve(settings(), "/workspace"); - yield* resolver.search({ query: "example" }); - expect(requests).toBe(2); - yield* resolver.search({ query: "example" }); - expect(requests).toBe(2); + expect(resolved.spawn.command).toContain( + "/tools/example-agent/1.2.3/linux-x86_64/..example-agent", + ); }).pipe( Effect.scoped, Effect.provide( - layerResolver((request) => { - requests += 1; - return Effect.succeed( + layerResolver((request) => + Effect.succeed( HttpClientResponse.fromWeb( request, - requests === 1 - ? new Response("unavailable", { status: 503 }) - : new Response(makeRegistry(agent)), + new Response(request.url === registryUrl ? makeRegistry(agent) : "#!/bin/sh\n"), ), - ); - }), + ), + ), ), ); }); - it.effect("searches retry the network after a refresh falls back within the reuse window", () => { - const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); - let requests = 0; - let online = true; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-refresh-fallback-", - }); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, - }); - yield* resolver.search({ query: "example" }); - expect(requests).toBe(1); - - // Prepare always refreshes; an unknown agent stops it right after the refresh. - online = false; - const missing = yield* resolver.prepare({ agentId: "missing-agent" }).pipe(Effect.flip); - expect(missing.reason).toBe("agent_not_found"); - expect(requests).toBe(2); - - online = true; - yield* resolver.search({ query: "example" }); - expect(requests).toBe(3); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => { - requests += 1; - return Effect.succeed( - HttpClientResponse.fromWeb( - request, - online - ? new Response(makeRegistry(agent)) - : new Response("unavailable", { status: 503 }), - ), - ); - }), - ), - ); - }); - - it.effect("filters runner recipes that the environment cannot prepare", () => { - const runnerAgent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); - const binaryAgent = { + it.effect("keeps a prepared binary ready after the registry advances its version", () => { + const makeBinaryAgent = (version: string) => ({ ...makeAgent({ binary: { - "linux-x86_64": { archive: archiveUrl, cmd: "example-agent" }, + "linux-x86_64": { + archive: `https://registry.test/example-agent-${version}.bin`, + cmd: "./bin/example-agent", + }, }, }), - id: "binary-agent", - name: "Binary Agent", - } satisfies AcpRegistrySupport.AcpRegistryAgent; + version, + }); + let agent = makeBinaryAgent("1.2.3"); return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-runner-filter-", + prefix: "t3-acp-registry-advance-", }); const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir, toolsDir: `${cacheDir}/tools`, registryUrl, }); - const result = yield* resolver.search({ query: "" }); + yield* resolver.prepare({ agentId: agent.id }); - expect(result.agents.map((agent) => agent.id)).toEqual(["binary-agent"]); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver( - (request) => - Effect.succeed( - HttpClientResponse.fromWeb( - request, - new Response( - JSON.stringify({ version: "1.0.0", agents: [runnerAgent, binaryAgent] }), - ), - ), - ), - { PATH: "" }, - ), - ), - ); - }); + agent = makeBinaryAgent("1.2.4"); + yield* TestClock.adjust("6 minutes"); + yield* resolver.search({ query: "example" }); - it.effect("discards registry agents with blank names or unsafe versions", () => { - const distribution = { - binary: { - "linux-x86_64": { archive: archiveUrl, cmd: "example-agent" }, - }, - } satisfies AcpRegistrySupport.AcpRegistryAgent["distribution"]; - const valid = makeAgent(distribution); - const blankName = { ...valid, id: "blank-name", name: " " }; - const blankVersion = { ...valid, id: "blank-version", version: "\t" }; - const parentVersion = { ...valid, id: "parent-version", version: ".." }; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-blank-fields-", - }); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, + expect(yield* resolver.inspect(settings())).toMatchObject({ + status: "ready", + distribution: "binary", }); - const result = yield* resolver.search({ query: "" }); + const resolved = yield* resolver.resolve(settings(), "/workspace", {}); + expect(resolved.spawn.command).toContain( + "/tools/example-agent/1.2.4/linux-x86_64/bin/example-agent", + ); + expect(yield* fileSystem.readFileString(resolved.spawn.command)).toBe( + "#!/bin/sh\necho 1.2.4\n", + ); - expect(result.agents.map((agent) => agent.id)).toEqual([valid.id]); + expect(yield* resolver.uninstallManagedBinary({ agentId: agent.id })).toMatchObject({ + removed: true, + }); + expect(yield* resolver.inspect(settings())).toMatchObject({ status: "unprepared" }); }).pipe( Effect.scoped, Effect.provide( @@ -1453,10 +1795,9 @@ describe("AcpRegistrySupport", () => { HttpClientResponse.fromWeb( request, new Response( - JSON.stringify({ - version: "1.0.0", - agents: [blankName, blankVersion, parentVersion, valid], - }), + request.url === registryUrl + ? makeRegistry(agent) + : `#!/bin/sh\necho ${agent.version}\n`, ), ), ), @@ -1465,653 +1806,5854 @@ describe("AcpRegistrySupport", () => { ); }); - it.effect("ignores unpinned runner recipes from the registry", () => { - const agent = makeAgent({ npx: { package: "@example/acp@latest" } }); + it.effect("refreshes a cached registry index according to maxAgeMs and explicit refresh", () => { + const makeBinaryAgent = (version: string) => ({ + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: `https://registry.test/example-agent-${version}.bin`, + cmd: "./bin/example-agent", + }, + }, + }), + version, + }); + let upstream = makeBinaryAgent("1.2.4"); + let online = true; + let registryRequests = 0; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-unpinned-", + prefix: "t3-acp-registry-refresh-index-", }); + yield* fileSystem.makeDirectory(`${cacheDir}/acp-registry`, { recursive: true }); + yield* fileSystem.writeFileString( + `${cacheDir}/acp-registry/registry.json`, + makeRegistry(makeBinaryAgent("1.2.3")), + ); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir, toolsDir: `${cacheDir}/tools`, registryUrl, }); - const result = yield* resolver.search({ query: "" }); - expect(result.agents).toEqual([]); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => - Effect.succeed(HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent)))), - ), - ), - ); - }); + // Cold inspection stays on disk with no network request. + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.3" }); + expect(registryRequests).toBe(0); - it.effect("rejects package syntax for the wrong runner", () => { - const invalidAgents = [ - { ...makeAgent({ npx: { package: "example-agent==1.2.3" } }), id: "bad-npx" }, - ]; - const validAgents = [ - { ...makeAgent({ uvx: { package: "minion-code@0.1.44" } }), id: "valid-at" }, - { ...makeAgent({ uvx: { package: "fast-agent-acp==0.9.30" } }), id: "valid-equals" }, - ]; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-runner-syntax-", - }); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, - }); - const invalid = yield* resolver.prepare({ agentId: "bad-npx" }).pipe(Effect.flip); - const validAt = yield* resolver.prepare({ agentId: "valid-at" }).pipe(Effect.flip); - const validEquals = yield* resolver.prepare({ agentId: "valid-equals" }).pipe(Effect.flip); + // Refreshing a disk-loaded index fetches the latest version once, then reuses it until maxAgeMs. + const refreshOptions = { maxAgeMs: 15 * 60 * 1_000, failureBackoffMs: 60_000 } as const; + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(1); + expect(registryRequests).toBe(1); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.4" }); - expect(invalid.reason).toBe("agent_not_found"); - expect(validAt.reason).toBe("runner_unavailable"); - expect(validEquals.reason).toBe("runner_unavailable"); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver( - (request) => - Effect.succeed( - HttpClientResponse.fromWeb( - request, - new Response( - JSON.stringify({ version: "1.0.0", agents: [...invalidAgents, ...validAgents] }), - ), - ), - ), - { PATH: "" }, - ), - ), - ); - }); + // Refreshing after maxAgeMs when upstream is unchanged renews freshness without advancing indexRevision. + yield* TestClock.adjust("15 minutes"); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(1); + expect(registryRequests).toBe(2); - it.effect("verifies declared SHA-256 before installing a binary", () => { - const agent = makeAgent({ - binary: { - "linux-x86_64": { - archive: archiveUrl, - cmd: "example-agent", - sha256: "0".repeat(64), - }, - }, - }); - const binaryBytes = new TextEncoder().encode("not the declared binary"); + upstream = makeBinaryAgent("1.2.5"); + yield* TestClock.adjust("14 minutes"); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(1); + expect(registryRequests).toBe(2); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.4" }); - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-checksum-", - }); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, - }); - const error = yield* resolver.prepare({ agentId: agent.id }).pipe(Effect.flip); + yield* TestClock.adjust("1 minute"); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(2); + expect(registryRequests).toBe(3); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.5" }); - expect(error.reason).toBe("checksum_mismatch"); + // Explicit invalidation clears the reuse window without discarding the in-memory index. + upstream = makeBinaryAgent("1.2.6"); + yield* resolver.invalidateIndex(); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.5" }); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(3); + expect(registryRequests).toBe(4); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.6" }); + + // An offline refresh prefers the in-memory index over a stale disk cache and backs off background retries. + yield* fileSystem.writeFileString( + `${cacheDir}/acp-registry/registry.json`, + makeRegistry(makeBinaryAgent("1.2.3")), + ); + online = false; + yield* resolver.invalidateIndex(); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(3); + expect(registryRequests).toBe(5); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.6" }); + + online = true; + upstream = makeBinaryAgent("1.2.7"); + yield* TestClock.adjust("59 seconds"); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(3); + expect(registryRequests).toBe(5); + + yield* TestClock.adjust("1 second"); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(4); + expect(registryRequests).toBe(6); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.7" }); }).pipe( Effect.scoped, Effect.provide( - layerResolver((request) => - Effect.succeed( + layerResolver((request) => { + registryRequests += 1; + return Effect.succeed( HttpClientResponse.fromWeb( request, - request.url === registryUrl - ? new Response(makeRegistry(agent)) - : new Response(binaryBytes.buffer as ArrayBuffer), + online + ? new Response(makeRegistry(upstream)) + : new Response("unavailable", { status: 503 }), ), - ), - ), - ), - ); - }); - - it.effect("falls back to a valid cached registry index when refresh fails", () => { - const agent = makeAgent({ - npx: { - package: "@example/acp@1.2.3", - args: ["--stdio"], - }, - }); - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-cache-", - }); - const registryDirectory = `${cacheDir}/acp-registry`; - yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); - yield* fileSystem.writeFileString(`${registryDirectory}/registry.json`, makeRegistry(agent)); - const toolchain = yield* makeFakeNpmToolchain(cacheDir); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, - }); - const resolved = yield* resolver.resolve(settings(), "/workspace", toolchain.environment); - - expect(resolved.spawn).toMatchObject({ - command: toolchain.executablePath, - args: ["--stdio"], - }); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => - Effect.succeed( - HttpClientResponse.fromWeb(request, new Response("unavailable", { status: 503 })), - ), - ), + ); + }), ), ); }); it.effect( - "installs the registry's current version when a cached index pins a removed build", + "backs off queued and subsequent background refreshes when uncached and offline while keeping prepare eligible", () => { - const binaryAgent = (version: string) => ({ + const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); + const newAgent = { ...makeAgent({ binary: { - "linux-x86_64": { - archive: `https://registry.test/example-agent-${version}.bin`, - cmd: "./bin/example-agent", - args: ["acp"], - }, + "darwin-aarch64": { archive: archiveUrl, cmd: "new-agent" }, }, }), - version, - }); - const requests: Array = []; + id: "new-agent", + name: "New Agent", + } satisfies AcpRegistrySupport.AcpRegistryAgent; + let upstreamAgents: ReadonlyArray = [agent]; + let online = false; + let registryRequests = 0; + let gate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-stale-", + prefix: "t3-acp-registry-cold-backoff-", }); - yield* fileSystem.makeDirectory(`${cacheDir}/acp-registry`, { recursive: true }); - yield* fileSystem.writeFileString( - `${cacheDir}/acp-registry/registry.json`, - makeRegistry(binaryAgent("1.2.3")), - ); const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir, toolsDir: `${cacheDir}/tools`, registryUrl, }); - const resolved = yield* resolver.resolve(settings(), "/workspace"); + const refreshOptions = { maxAgeMs: 15 * 60 * 1_000, failureBackoffMs: 60_000 } as const; - expect(resolved.agent?.version).toBe("1.2.4"); - expect(resolved.spawn.command).toContain("/tools/example-agent/1.2.4/"); - expect(requests).toContain(registryUrl); + const firstGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + gate = firstGate; + const firstRefresh = yield* resolver + .refreshIndex(refreshOptions) + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(firstGate.started); + const queuedRefresh = yield* resolver + .refreshIndex(refreshOptions) + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + + yield* Deferred.succeed(firstGate.release, undefined); + const firstRefreshError = yield* Fiber.join(firstRefresh); + expect(firstRefreshError.reason).toBe("registry_unavailable"); + expect(firstRefreshError.stage).toBe("http_request"); + expect((yield* Fiber.join(queuedRefresh)).reason).toBe("registry_unavailable"); + expect(registryRequests).toBe(1); + + // Subsequent background refreshes during the backoff window fail fast before acquiring the semaphore. + yield* TestClock.adjust("59 seconds"); + const prepareHoldGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + gate = prepareHoldGate; + online = true; + const holdingPrepare = yield* resolver + .prepare({ agentId: "missing-agent" }) + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(prepareHoldGate.started); + expect((yield* resolver.refreshIndex(refreshOptions).pipe(Effect.flip)).reason).toBe( + "registry_unavailable", + ); + expect(holdingPrepare.pollUnsafe()).toBeUndefined(); + expect(registryRequests).toBe(2); + yield* Deferred.succeed(prepareHoldGate.release, undefined); + expect((yield* Fiber.join(holdingPrepare)).reason).toBe("agent_not_found"); + + // Clock moving backwards below failedAtMs disables backoff suppression on both fast and semaphore paths. + const clockBackDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-clock-back-", + }); + const clockBackResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: clockBackDir, + toolsDir: `${clockBackDir}/tools`, + registryUrl, + }); + gate = null; + online = false; + yield* TestClock.adjust("10 minutes"); + expect( + (yield* clockBackResolver.refreshIndex(refreshOptions).pipe(Effect.flip)).reason, + ).toBe("registry_unavailable"); + const requestsAfterClockFailure = registryRequests; + online = true; + yield* TestClock.setTime(0); + expect(yield* clockBackResolver.refreshIndex(refreshOptions)).toBe(1); + expect(registryRequests).toBe(requestsAfterClockFailure + 1); + + // Concurrent cold uncached inspect() calls coalesce behind one failing network fetch. + const coldInspectDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-cold-inspect-coalesce-", + }); + const coldCachePath = path.join(coldInspectDir, "acp-registry", "registry.json"); + const missingColdCacheError = yield* fileSystem + .readFileString(coldCachePath) + .pipe(Effect.flip); + // Fail the missing cache read synchronously so the second inspect parks on the refresh semaphore before release. + const coldInspectFs: FileSystem.FileSystem = { + ...fileSystem, + readFileString: (filePath, encoding) => + filePath === coldCachePath + ? Effect.fail(missingColdCacheError) + : fileSystem.readFileString(filePath, encoding), + }; + const coldInspectResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coldInspectDir, + toolsDir: path.join(coldInspectDir, "tools"), + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, coldInspectFs)); + const coldInspectGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + gate = coldInspectGate; + online = false; + const requestsBeforeColdInspect = registryRequests; + const firstInspect = yield* coldInspectResolver + .inspect(settings()) + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(coldInspectGate.started); + const secondInspect = yield* coldInspectResolver + .inspect(settings()) + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + expect(secondInspect.pollUnsafe()).toBeUndefined(); + yield* Deferred.succeed(coldInspectGate.release, undefined); + expect((yield* Fiber.join(firstInspect)).reason).toBe("registry_unavailable"); + expect((yield* Fiber.join(secondInspect)).reason).toBe("registry_unavailable"); + expect(registryRequests).toBe(requestsBeforeColdInspect + 1); + + // A queued prepare() must not reuse a cached fallback from a failing background refresh. + const queuedPrepareDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-queued-prepare-", + }); + yield* fileSystem.makeDirectory(`${queuedPrepareDir}/acp-registry`, { recursive: true }); + yield* fileSystem.writeFileString( + `${queuedPrepareDir}/acp-registry/registry.json`, + makeRegistry({ ...agent, id: "older-agent" }), + ); + const queuedPrepareResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: queuedPrepareDir, + toolsDir: `${queuedPrepareDir}/tools`, + registryUrl, + }); + const fallbackGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + gate = fallbackGate; + online = false; + upstreamAgents = [agent, newAgent]; + const requestsBeforeQueuedPrepare = registryRequests; + const failingBackground = yield* queuedPrepareResolver + .refreshIndex(refreshOptions) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(fallbackGate.started); + const queuedPrepare = yield* queuedPrepareResolver + .prepare({ agentId: newAgent.id }) + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + expect(queuedPrepare.pollUnsafe()).toBeUndefined(); + // Flip online after the background refresh already captured 503 so only the queued prepare retries online. + online = true; + gate = null; + yield* Deferred.succeed(fallbackGate.release, undefined); + expect(yield* Fiber.join(failingBackground)).toBe(0); + // Reaching unsupported_distribution (instead of agent_not_found from older-agent) proves prepare retried. + expect((yield* Fiber.join(queuedPrepare)).reason).toBe("unsupported_distribution"); + expect(registryRequests).toBe(requestsBeforeQueuedPrepare + 2); }).pipe( Effect.scoped, Effect.provide( layerResolver((request) => { - requests.push(request.url); - const response = - request.url === registryUrl - ? new Response(makeRegistry(binaryAgent("1.2.4"))) - : request.url.endsWith("-1.2.4.bin") - ? new Response("#!/bin/sh\necho example\n") - : new Response("forbidden", { status: 403 }); - return Effect.succeed(HttpClientResponse.fromWeb(request, response)); + registryRequests += 1; + const activeGate = gate; + const shouldSucceed = online; + const body = JSON.stringify({ version: "1.0.0", agents: upstreamAgents }); + const respond = Effect.sync(() => + HttpClientResponse.fromWeb( + request, + shouldSucceed ? new Response(body) : new Response("unavailable", { status: 503 }), + ), + ); + return activeGate === null + ? respond + : Deferred.succeed(activeGate.started, undefined).pipe( + Effect.andThen(Deferred.await(activeGate.release)), + Effect.andThen(respond), + ); }), ), ); }, ); - it.effect("rejects unsafe command paths before downloading an archive", () => { - const agent = makeAgent({ - binary: { - "linux-x86_64": { - archive: archiveUrl, - cmd: "../outside", - }, - }, - }); - const requests: Array = []; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-invalid-", - }); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, - }); - const error = yield* resolver.resolve(settings(), "/workspace").pipe(Effect.flip); - - expect(error.reason).toBe("archive_invalid"); - expect(requests).toEqual([registryUrl]); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => { - requests.push(request.url); - return Effect.succeed( - HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent))), - ); - }), - ), - ); - }); - - it.effect("inspects from disk without waiting for a registry refresh", () => { - const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); - let requests = 0; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-cold-inspect-", + it.effect( + "does not mark a refresh fresh or backed off when invalidated after response receipt", + () => { + const makeNpxAgent = (version: string) => ({ + ...makeAgent({ npx: { package: `@example/acp@${version}` } }), + version, }); - const registryDirectory = `${cacheDir}/acp-registry`; - yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); - yield* fileSystem.writeFileString(`${registryDirectory}/registry.json`, makeRegistry(agent)); + let upstream = makeNpxAgent("1.2.4"); + let online = true; + let registryRequests = 0; + let fetchGate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-invalidate-race-", + }); + const registryDirectory = path.join(cacheDir, "acp-registry"); + const registryCachePath = path.join(registryDirectory, "registry.json"); + yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); + yield* fileSystem.writeFileString(registryCachePath, makeRegistry(makeNpxAgent("1.2.3"))); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, - }); - const inspection = yield* resolver.inspect(settings()); + let writeGate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + const gatedFileSystem: FileSystem.FileSystem = { + ...fileSystem, + writeFileString: (filePath, data, options) => { + const activeGate = + writeGate !== null && filePath.startsWith(`${registryCachePath}.`) ? writeGate : null; + return activeGate === null + ? fileSystem.writeFileString(filePath, data, options) + : Deferred.succeed(activeGate.started, undefined).pipe( + Effect.andThen(Deferred.await(activeGate.release)), + Effect.andThen(fileSystem.writeFileString(filePath, data, options)), + ); + }, + }; + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, gatedFileSystem)); + const refreshOptions = { maxAgeMs: 15 * 60 * 1_000, failureBackoffMs: 60_000 } as const; - expect(inspection).toMatchObject({ status: "ready", agentId: agent.id }); - expect(requests).toBe(0); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => { - requests += 1; - return Effect.succeed( - HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent))), - ); - }), - ), - ); - }); + // 1. Invalidate after HTTP response receipt (during writeRegistryCache) before cache publication. + const firstWriteGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + writeGate = firstWriteGate; + const firstRefresh = yield* resolver + .refreshIndex(refreshOptions) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(firstWriteGate.started); + expect(registryRequests).toBe(1); + yield* resolver.invalidateIndex(); + yield* Deferred.succeed(firstWriteGate.release, undefined); - it.effect("recovers inspection from a corrupt cache once the registry is reachable", () => { - const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); - let online = false; - let requests = 0; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-offline-", - }); - yield* fileSystem.makeDirectory(`${cacheDir}/acp-registry`, { recursive: true }); - yield* fileSystem.writeFileString(`${cacheDir}/acp-registry/registry.json`, "{not json"); - const options = { cacheDir, toolsDir: `${cacheDir}/tools`, registryUrl }; - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog(options); + // The fetched index is kept as fallback, while freshness stays unset so the next refresh fetches. + expect(yield* Fiber.join(firstRefresh)).toBe(1); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.4" }); - const offline = yield* resolver.inspect(settings()).pipe(Effect.flip); - expect(offline.reason).toBe("registry_unavailable"); + // 2. A post-invalidation caller queued behind an in-flight pre-invalidation fetch does not coalesce. + upstream = makeNpxAgent("1.2.5"); + const secondWriteGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + writeGate = secondWriteGate; + const secondRefresh = yield* resolver + .refreshIndex(refreshOptions) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(secondWriteGate.started); + expect(registryRequests).toBe(2); - online = true; - const concurrent = yield* Effect.all( - [resolver.inspect(settings()), resolver.inspect(settings())], - { concurrency: "unbounded" }, - ); - expect(concurrent).toMatchObject([{ status: "ready" }, { status: "ready" }]); - expect(requests).toBe(2); + yield* resolver.invalidateIndex(); + upstream = makeNpxAgent("1.2.6"); + writeGate = null; + const queuedPostInvalidation = yield* resolver + .refreshIndex(refreshOptions) + .pipe(Effect.forkScoped({ startImmediately: true })); + expect(queuedPostInvalidation.pollUnsafe()).toBeUndefined(); + yield* Deferred.succeed(secondWriteGate.release, undefined); - const restarted = yield* AcpRegistrySupport.makeAcpRegistryCatalog(options); - expect(yield* restarted.inspect(settings())).toMatchObject({ status: "ready" }); - expect(requests).toBe(2); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => { - requests += 1; - return Effect.succeed( - HttpClientResponse.fromWeb( - request, - online - ? new Response(makeRegistry(agent)) - : new Response("unavailable", { status: 503 }), - ), - ); - }), - ), - ); - }); + expect(yield* Fiber.join(secondRefresh)).toBe(2); + expect(yield* Fiber.join(queuedPostInvalidation)).toBe(3); + expect(registryRequests).toBe(3); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.6" }); - it.effect("uses the effective provider environment for inspection and resolution", () => { - const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-effective-env-", - }); - const registryDirectory = `${cacheDir}/acp-registry`; - yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); - yield* fileSystem.writeFileString(`${registryDirectory}/registry.json`, makeRegistry(agent)); - const toolchain = yield* makeFakeNpmToolchain(cacheDir); + // Attempts that started after invalidation still set freshness normally. + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(3); + expect(registryRequests).toBe(3); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, - }); - const hostInspection = yield* resolver.inspect(settings()); - const providerEnvironment = toolchain.environment; - const instanceInspection = yield* resolver.inspect(settings(), providerEnvironment); - const resolved = yield* resolver.resolve(settings(), "/workspace", providerEnvironment); + // 3. A failed refresh started before invalidation does not restore failure backoff. + yield* resolver.invalidateIndex(); + online = false; + const offlineGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + fetchGate = offlineGate; + const failedRefresh = yield* resolver + .refreshIndex(refreshOptions) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(offlineGate.started); + expect(registryRequests).toBe(4); + yield* resolver.invalidateIndex(); + yield* Deferred.succeed(offlineGate.release, undefined); + expect(yield* Fiber.join(failedRefresh)).toBe(3); - expect(hostInspection).toMatchObject({ status: "missing_runner", runner: "npm" }); - expect(instanceInspection).toMatchObject({ status: "ready", distribution: "npx" }); - expect(resolved.spawn).toMatchObject({ - command: toolchain.executablePath, - env: { PATH: expect.stringMatching(new RegExp(`^${toolchain.globalBin}:`, "u")) }, - }); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver( - (request) => - Effect.succeed(HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent)))), - { PATH: "" }, - ), - ), - ); - }); + online = true; + fetchGate = null; + upstream = makeNpxAgent("1.2.7"); + expect(yield* resolver.refreshIndex(refreshOptions)).toBe(4); + expect(registryRequests).toBe(5); + expect(yield* resolver.inspect(settings())).toMatchObject({ version: "1.2.7" }); - it.effect("requires a regular executable file in the managed binary cache", () => { - const agent = makeAgent({ - binary: { - "linux-x86_64": { - archive: archiveUrl, - cmd: "bin/example-agent", - }, - }, - }); - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-non-file-", - }); - const registryDirectory = `${cacheDir}/acp-registry`; - const fakeExecutable = `${cacheDir}/tools/example-agent/1.2.3/linux-x86_64/bin/example-agent`; - yield* fileSystem.makeDirectory(fakeExecutable, { recursive: true }); - yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); - yield* fileSystem.writeFileString(`${registryDirectory}/registry.json`, makeRegistry(agent)); + // 4. A cold inspect() queued behind an invalidated in-flight fetch accepts the resulting index without refetching. + const coldAcceptedDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-cold-accept-", + }); + const coldAcceptedCachePath = path.join(coldAcceptedDir, "acp-registry", "registry.json"); + const missingAcceptedCacheError = yield* fileSystem + .readFileString(coldAcceptedCachePath) + .pipe(Effect.flip); + const coldAcceptedFs: FileSystem.FileSystem = { + ...fileSystem, + readFileString: (filePath, encoding) => + filePath === coldAcceptedCachePath + ? Effect.fail(missingAcceptedCacheError) + : fileSystem.readFileString(filePath, encoding), + }; + const coldAcceptedResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coldAcceptedDir, + toolsDir: path.join(coldAcceptedDir, "tools"), + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, coldAcceptedFs)); + const coldFetchGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + fetchGate = coldFetchGate; + upstream = makeNpxAgent("1.2.8"); + const requestsBeforeColdAccept = registryRequests; + const inFlightRefresh = yield* coldAcceptedResolver + .refreshIndex(refreshOptions) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(coldFetchGate.started); + yield* coldAcceptedResolver.invalidateIndex(); + const queuedColdInspect = yield* coldAcceptedResolver + .inspect(settings()) + .pipe(Effect.forkScoped({ startImmediately: true })); + expect(queuedColdInspect.pollUnsafe()).toBeUndefined(); + fetchGate = null; + yield* Deferred.succeed(coldFetchGate.release, undefined); + expect(yield* Fiber.join(inFlightRefresh)).toBe(1); + expect(yield* Fiber.join(queuedColdInspect)).toMatchObject({ + version: "1.2.8", + indexRevision: 1, + }); + expect(registryRequests).toBe(requestsBeforeColdAccept + 1); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, - }); - const directoryError = yield* resolver.inspect(settings()).pipe(Effect.flip); + // 5. An uncached cold failure started before invalidation also does not record backoff. + const coldCacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-cold-invalidate-race-", + }); + const coldResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coldCacheDir, + toolsDir: `${coldCacheDir}/tools`, + registryUrl, + }); + online = false; + const coldOfflineGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + fetchGate = coldOfflineGate; + const coldFailedRefresh = yield* coldResolver + .refreshIndex(refreshOptions) + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(coldOfflineGate.started); + yield* coldResolver.invalidateIndex(); + yield* Deferred.succeed(coldOfflineGate.release, undefined); + expect((yield* Fiber.join(coldFailedRefresh)).reason).toBe("registry_unavailable"); - expect(directoryError.reason).toBe("archive_invalid"); + online = true; + fetchGate = null; + expect(yield* coldResolver.refreshIndex(refreshOptions)).toBe(1); + expect(registryRequests).toBe(8); - yield* fileSystem.remove(fakeExecutable, { recursive: true }); - yield* fileSystem.writeFileString(fakeExecutable, "#!/bin/sh\n"); - yield* fileSystem.chmod(fakeExecutable, 0o644); - const modeError = yield* resolver.inspect(settings()).pipe(Effect.flip); + // 6. launchIdentity tracks effective launch inputs for npx, commandOverride, and binary distributions. + const packageSwapDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-launch-identity-", + }); + const rawHostPlatform = HostProcess.Platform.defaultValue(); + const rawHostArchitecture = HostProcess.Architecture.defaultValue(); + const isSupportedHost = + (rawHostPlatform === "darwin" || + rawHostPlatform === "linux" || + rawHostPlatform === "win32") && + (rawHostArchitecture === "arm64" || rawHostArchitecture === "x64"); + const hostPlatform: NodeJS.Platform = isSupportedHost ? rawHostPlatform : "linux"; + const hostArchitecture: NodeJS.Architecture = isSupportedHost ? rawHostArchitecture : "x64"; + const isWindowsHost = hostPlatform === "win32"; + const hostBinaryOs = + hostPlatform === "darwin" ? "darwin" : isWindowsHost ? "windows" : "linux"; + const hostBinaryArch = hostArchitecture === "arm64" ? "aarch64" : "x86_64"; + const binaryTargetKey = `${hostBinaryOs}-${hostBinaryArch}` as const; + const swapResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: packageSwapDir, + toolsDir: `${packageSwapDir}/tools`, + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, hostPlatform), + Effect.provideService(HostProcess.Architecture, hostArchitecture), + Effect.provideService(SpawnExecutableResolution, (command) => + command === "npm" || command.endsWith("override-agent") ? command : undefined, + ), + ); + const swapEnvironment: NodeJS.ProcessEnv = {}; + upstream = { + ...makeAgent({ npx: { package: "@example/old@1.0.0" } }), + version: "1.0.0", + website: "https://example.test/docs-a", + }; + yield* swapResolver.refreshIndex(refreshOptions); + const oldPackageInspection = yield* swapResolver.inspect(settings(), swapEnvironment); + expect(oldPackageInspection).toMatchObject({ + status: "ready", + version: "1.0.0", + documentationUrl: "https://example.test/docs-a", + }); - expect(modeError.reason).toBe("archive_invalid"); + upstream = { + ...makeAgent({ npx: { package: "@example/new@1.0.0" } }), + version: "1.0.0", + website: "https://example.test/docs-a", + }; + yield* swapResolver.invalidateIndex(); + yield* swapResolver.refreshIndex(refreshOptions); + const newPackageInspection = yield* swapResolver.inspect(settings(), swapEnvironment); + expect(newPackageInspection).toMatchObject({ status: "ready", version: "1.0.0" }); + expect( + oldPackageInspection.status === "ready" && + newPackageInspection.status === "ready" && + oldPackageInspection.launchIdentity !== newPackageInspection.launchIdentity, + ).toBe(true); - yield* fileSystem.chmod(fakeExecutable, 0o755); - expect(yield* resolver.inspect(settings())).toMatchObject({ status: "ready" }); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => - Effect.succeed(HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent)))), + upstream = { + ...makeAgent({ npx: { package: "@example/new@1.0.0" } }), + version: "1.0.0", + website: "https://example.test/docs-b", + }; + yield* swapResolver.invalidateIndex(); + yield* swapResolver.refreshIndex(refreshOptions); + const docsOnlyInspection = yield* swapResolver.inspect(settings(), swapEnvironment); + expect(docsOnlyInspection).toMatchObject({ + status: "ready", + version: "1.0.0", + documentationUrl: "https://example.test/docs-b", + }); + expect( + newPackageInspection.status === "ready" && + docsOnlyInspection.status === "ready" && + newPackageInspection.launchIdentity === docsOnlyInspection.launchIdentity, + ).toBe(true); + + // commandOverride ignores version/package bumps it does not launch, while tracking args and env separately. + const overridePath = `${packageSwapDir}/override-agent`; + yield* fileSystem.writeFileString(overridePath, "#!/bin/sh\necho override\n"); + if (!isWindowsHost) { + yield* fileSystem.chmod(overridePath, 0o755); + } + const overrideSettings = settings({ commandPath: overridePath }); + const overrideBase = yield* swapResolver.inspect(overrideSettings, swapEnvironment); + upstream = { + ...makeAgent({ npx: { package: "@example/other@2.0.0" } }), + version: "2.0.0", + }; + yield* swapResolver.invalidateIndex(); + yield* swapResolver.refreshIndex(refreshOptions); + const overrideBumped = yield* swapResolver.inspect(overrideSettings, swapEnvironment); + expect(overrideBase.status === "ready" && overrideBumped.status === "ready").toBe(true); + expect( + overrideBase.status === "ready" && overrideBumped.status === "ready" + ? overrideBase.launchIdentity === overrideBumped.launchIdentity + : false, + ).toBe(true); + + upstream = { + ...makeAgent({ + npx: { package: "@example/other@2.0.0", args: ["--flag"] }, + }), + version: "2.0.0", + }; + yield* swapResolver.invalidateIndex(); + yield* swapResolver.refreshIndex(refreshOptions); + const overrideArgsOnly = yield* swapResolver.inspect(overrideSettings, swapEnvironment); + expect( + overrideBumped.status === "ready" && + overrideArgsOnly.status === "ready" && + overrideBumped.launchIdentity !== overrideArgsOnly.launchIdentity, + ).toBe(true); + + upstream = { + ...makeAgent({ + npx: { package: "@example/other@2.0.0", env: { MODE: "acp" } }, + }), + version: "2.0.0", + }; + yield* swapResolver.invalidateIndex(); + yield* swapResolver.refreshIndex(refreshOptions); + const overrideEnvOnly = yield* swapResolver.inspect(overrideSettings, swapEnvironment); + expect( + overrideBumped.status === "ready" && + overrideEnvOnly.status === "ready" && + overrideBumped.launchIdentity !== overrideEnvOnly.launchIdentity, + ).toBe(true); + + // Binary launchIdentity tracks archive, sha256, cmd, args, and env while ignoring website/icon changes. + const binaryExe = `${packageSwapDir}/tools/example-agent/1.0.0/${binaryTargetKey}/bin/agent`; + yield* fileSystem.makeDirectory( + `${packageSwapDir}/tools/example-agent/1.0.0/${binaryTargetKey}/bin`, + { + recursive: true, + }, + ); + yield* fileSystem.writeFileString(binaryExe, "#!/bin/sh\necho bin\n"); + if (!isWindowsHost) { + yield* fileSystem.chmod(binaryExe, 0o755); + } + const inspectBinary = ( + target: { + readonly archive: string; + readonly cmd: string; + readonly sha256?: string; + readonly args?: ReadonlyArray; + readonly env?: Readonly>; + }, + meta?: { readonly website?: string; readonly icon?: string }, + ) => + Effect.gen(function* () { + upstream = { + ...makeAgent({ binary: { [binaryTargetKey]: target } }), + version: "1.0.0", + ...(meta?.website ? { website: meta.website } : {}), + ...(meta?.icon ? { icon: meta.icon } : {}), + }; + yield* swapResolver.invalidateIndex(); + yield* swapResolver.refreshIndex(refreshOptions); + const inspected = yield* swapResolver.inspect(settings(), swapEnvironment); + expect(inspected.status).toBe("ready"); + return inspected.status === "ready" ? inspected.launchIdentity : undefined; + }); + const baseBinId = yield* inspectBinary( + { archive: archiveUrl, cmd: "./bin/agent", sha256: "a".repeat(64) }, + { + website: "https://example.test/a", + icon: "https://cdn.agentclientprotocol.com/registry/v1/latest/a.svg", + }, + ); + expect( + yield* inspectBinary( + { archive: archiveUrl, cmd: "./bin/agent", sha256: "a".repeat(64) }, + { + website: "https://example.test/b", + icon: "https://cdn.agentclientprotocol.com/registry/v1/latest/b.svg", + }, + ), + ).toBe(baseBinId); + expect( + yield* inspectBinary({ + archive: "https://registry.test/other.bin", + cmd: "./bin/agent", + sha256: "a".repeat(64), + }), + ).not.toBe(baseBinId); + expect( + yield* inspectBinary({ + archive: archiveUrl, + cmd: "./bin/agent", + sha256: "b".repeat(64), + }), + ).not.toBe(baseBinId); + expect( + yield* inspectBinary({ + archive: archiveUrl, + cmd: "./bin/agent-v2", + sha256: "a".repeat(64), + }), + ).not.toBe(baseBinId); + expect( + yield* inspectBinary({ + archive: archiveUrl, + cmd: "./bin/agent", + sha256: "a".repeat(64), + args: ["--extra"], + }), + ).not.toBe(baseBinId); + expect( + yield* inspectBinary({ + archive: archiveUrl, + cmd: "./bin/agent", + sha256: "a".repeat(64), + env: { EXTRA: "1" }, + }), + ).not.toBe(baseBinId); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + registryRequests += 1; + const activeGate = fetchGate; + const respond = Effect.sync(() => + HttpClientResponse.fromWeb( + request, + online + ? new Response(makeRegistry(upstream)) + : new Response("unavailable", { status: 503 }), + ), + ); + return activeGate === null + ? respond + : Deferred.succeed(activeGate.started, undefined).pipe( + Effect.andThen(Deferred.await(activeGate.release)), + Effect.andThen(respond), + ); + }), ), - ), - ); - }); + ); + }, + ); - it.effect.each([ - { name: "legacy registry", source: undefined, agentId: "example-agent", referenced: true }, - { name: "registry", source: "registry", agentId: "example-agent", referenced: true }, - { name: "padded registry", source: "registry", agentId: " example-agent ", referenced: true }, - { name: "local command", source: "local", agentId: "example-agent", referenced: false }, - ] as const)( - "checks $name references before uninstalling only managed binaries", - ({ source, agentId, referenced }) => { + it.effect( + "prepares the registry version despite an older PATH binary and permits explicit overrides", + () => { + const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho managed\n"); + const agent = makeAgent({ + binary: { + "linux-x86_64": { + archive: archiveUrl, + cmd: "./bin/example-agent", + args: ["acp"], + sha256: "e1eb7c905b91c400af2ec858628aec22866bfda1383b93ceb73ae01d9769fb31", + }, + }, + }); + const requests: Array = []; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-uninstall-", + prefix: "t3-acp-registry-system-", }); - const agentRoot = `${cacheDir}/tools/example-agent`; - const runnerCache = `${cacheDir}/external-npx-cache/example-agent/package.json`; - yield* fileSystem.makeDirectory(`${agentRoot}/1.2.3/linux-x86_64`, { recursive: true }); - yield* fileSystem.writeFileString(`${agentRoot}/1.2.3/linux-x86_64/agent`, "binary"); - yield* fileSystem.makeDirectory(`${cacheDir}/external-npx-cache/example-agent`, { - recursive: true, + const systemBinDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-system-bin-", }); - yield* fileSystem.writeFileString(runnerCache, "{}"); + const systemBinary = path.join(systemBinDir, "example-agent"); + yield* fileSystem.writeFileString(systemBinary, "#!/bin/sh\necho system\n"); + yield* fileSystem.chmod(systemBinary, 0o755); + const environment = { PATH: systemBinDir }; const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir, toolsDir: `${cacheDir}/tools`, registryUrl, + }).pipe(Effect.provideService(HostProcess.Environment, environment)); + yield* resolver.search({ query: "example" }); + expect(yield* resolver.inspect(settings(), environment)).toMatchObject({ + status: "unprepared", }); - const hostSettings = yield* TestProviderHost.TestProviderHostSettings; - const instanceId = ProviderInstanceId.make("uninstall-reference"); - yield* hostSettings.set({ - ...DEFAULT_SERVER_SETTINGS, - providerInstances: { - [instanceId]: { - driver: ProviderDriverKind.make("acpRegistry"), - displayName: "Uninstall reference", - enabled: true, - config: { - agentId, - commandPath: "/local/agent", - ...(source ? { source } : {}), - }, - }, - }, + + const overridden = settings({ commandPath: systemBinary }); + expect(yield* resolver.inspect(overridden, environment)).toMatchObject({ + status: "ready", + version: null, }); - const first = yield* resolver.uninstallManagedBinary({ agentId: "example-agent" }); - expect(first).toEqual({ agentId: "example-agent", removed: !referenced }); - expect(yield* fileSystem.exists(agentRoot)).toBe(referenced); - yield* hostSettings.set(DEFAULT_SERVER_SETTINGS); - const second = yield* resolver.uninstallManagedBinary({ agentId: "example-agent" }); + const custom = yield* resolver.resolve(overridden, "/workspace", environment); + expect(custom.spawn.command).toBe(systemBinary); + expect(custom.spawn.args).toEqual(["acp"]); + expect(requests).toEqual([registryUrl]); - expect(second).toEqual({ agentId: "example-agent", removed: referenced }); - expect(yield* resolver.uninstallManagedBinary({ agentId: "example-agent" })).toEqual({ - agentId: "example-agent", - removed: false, + yield* resolver.prepare({ agentId: "example-agent" }); + const resolved = yield* resolver.resolve(settings(), "/workspace", environment); + expect(resolved.spawn.command).not.toBe(systemBinary); + expect(yield* fileSystem.readFileString(resolved.spawn.command)).toBe( + "#!/bin/sh\necho managed\n", + ); + expect(yield* fileSystem.readFileString(systemBinary)).toBe("#!/bin/sh\necho system\n"); + + const inspection = yield* resolver.inspect(settings(), environment); + expect(inspection).toMatchObject({ + status: "ready", + distribution: "binary", + version: "1.2.3", }); - expect(yield* fileSystem.exists(agentRoot)).toBe(false); - expect(yield* fileSystem.exists(runnerCache)).toBe(true); + + expect(requests).toEqual([registryUrl, registryUrl, archiveUrl]); }).pipe( Effect.scoped, Effect.provide( - layerResolver((request) => - Effect.succeed(HttpClientResponse.fromWeb(request, new Response("unused"))), - ), + layerResolver((request) => { + requests.push(request.url); + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + request.url === registryUrl + ? new Response(makeRegistry(agent)) + : new Response(binaryBytes.buffer as ArrayBuffer), + ), + ); + }), ), ); }, ); - it.effect("keeps managed package installs when removing the same agent's binaries", () => - Effect.gen(function* () { + it.effect("installs a tar archive with a root entry and a listing larger than 1 MiB", () => { + const downloadUrl = "https://registry.test/agent.tar.gz"; + const agent = makeAgent({ + binary: { "linux-x86_64": { archive: downloadUrl, cmd: "./agent" } }, + }); + return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-uninstall-packages-", - }); - const versionRoot = `${cacheDir}/tools/example-agent/1.2.3`; - yield* fileSystem.makeDirectory(`${versionRoot}/linux-x86_64`, { recursive: true }); - yield* fileSystem.writeFileString(`${versionRoot}/linux-x86_64/agent`, "binary"); - yield* fileSystem.makeDirectory(`${versionRoot}/npm/bin`, { recursive: true }); - yield* fileSystem.writeFileString(`${versionRoot}/npm/bin/agent`, "package command"); + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-root-entry-" }); + const source = `${cacheDir}/source`; + yield* fileSystem.makeDirectory(source); + yield* fileSystem.writeFileString(`${source}/agent`, "#!/bin/sh\necho managed\n"); + // 5,000 long names list past the generic 1 MiB command output cap. + const entries = `${source}/entries`; + yield* fileSystem.makeDirectory(entries); + yield* Effect.forEach( + Array.from({ length: 5_000 }, (_, index) => index), + (index) => fileSystem.writeFileString(`${entries}/${index}-${"e".repeat(240)}`, ""), + { concurrency: 16 }, + ); + const archivePath = `${cacheDir}/agent.tar.gz`; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const tar = yield* spawner.spawn( + ChildProcess.make("tar", ["-czf", archivePath, "-C", source, "."]), + ); + expect(yield* tar.exitCode).toBe(0); + const archive = yield* fileSystem.readFile(archivePath); const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ cacheDir, toolsDir: `${cacheDir}/tools`, registryUrl, - }); - expect(yield* resolver.uninstallManagedBinary({ agentId: "example-agent" })).toEqual({ - agentId: "example-agent", - removed: true, - }); - expect(yield* fileSystem.exists(`${versionRoot}/linux-x86_64`)).toBe(false); - expect(yield* fileSystem.readFileString(`${versionRoot}/npm/bin/agent`)).toBe( - "package command", + }).pipe( + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + request.url === registryUrl + ? new Response(makeRegistry(agent)) + : new Response(archive), + ), + ), + ), + ), + ); + yield* resolver.prepare({ agentId: agent.id }); + const resolved = yield* resolver.resolve(settings(), "/workspace", {}); + expect(resolved.spawn.command).toBe( + yield* fileSystem.realPath(`${cacheDir}/tools/example-agent/1.2.3/linux-x86_64/agent`), + ); + expect(yield* fileSystem.readFileString(resolved.spawn.command)).toBe( + "#!/bin/sh\necho managed\n", ); - expect(yield* resolver.uninstallManagedBinary({ agentId: "example-agent" })).toEqual({ - agentId: "example-agent", - removed: false, - }); }).pipe( Effect.scoped, - Effect.provide(layerResolver(() => Effect.die("unexpected HTTP request"))), - ), + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + TestProviderHost.layer().pipe( + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(HostProcess.Architecture, "x64"), + ); + }); + + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "leaves the mode of a file outside the install root when the command links to it", + () => { + const downloadUrl = "https://registry.test/agent.tar.gz"; + const agent = makeAgent({ + binary: { "linux-x86_64": { archive: downloadUrl, cmd: "./agent" } }, + }); + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-outside-link-", + }); + const outsideFile = `${cacheDir}/outside`; + yield* fileSystem.writeFileString(outsideFile, "private\n"); + yield* fileSystem.chmod(outsideFile, 0o600); + const source = `${cacheDir}/source`; + yield* fileSystem.makeDirectory(source); + yield* fileSystem.symlink(outsideFile, `${source}/agent`); + const archivePath = `${cacheDir}/agent.tar.gz`; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const tar = yield* spawner.spawn( + ChildProcess.make("tar", ["-czf", archivePath, "-C", source, "agent"]), + ); + expect(yield* tar.exitCode).toBe(0); + const archive = yield* fileSystem.readFile(archivePath); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }).pipe( + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + request.url === registryUrl + ? new Response(makeRegistry(agent)) + : new Response(archive), + ), + ), + ), + ), + ); + + const error = yield* resolver.prepare({ agentId: agent.id }).pipe(Effect.flip); + + expect(error.reason).toBe("archive_invalid"); + expect((yield* fileSystem.stat(outsideFile)).mode & 0o777).toBe(0o600); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + TestProviderHost.layer().pipe( + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(HostProcess.Architecture, "x64"), + ); + }, ); - it.effect("keeps a binary prepared by another client while an uninstall is waiting", () => { - const agent = makeAgent({ - binary: { - "linux-x86_64": { - archive: archiveUrl, + it.effect("searches compatible agents with deterministic ranking and bounded metadata", () => { + const exact = { + ...makeAgent({ npx: { package: "@example/acp@1.2.3" } }), + id: "codex-acp", + name: "Codex", + authors: ["OpenAI", "Zed Industries"], + license: "Apache-2.0", + website: "https://example.test/codex", + repository: "https://example.test/codex/source", + icon: "https://example.test/codex.svg", + } satisfies AcpRegistrySupport.AcpRegistryAgent; + const descriptionMatch = { + ...makeAgent({ npx: { package: "other-agent@1.2.3" } }), + id: "other-agent", + name: "Other Agent", + description: "An adapter for Codex workflows", + } satisfies AcpRegistrySupport.AcpRegistryAgent; + const incompatible = { + ...makeAgent({ + binary: { + "darwin-aarch64": { archive: archiveUrl, cmd: "agent" }, + }, + }), + id: "darwin-only", + name: "Codex Darwin", + } satisfies AcpRegistrySupport.AcpRegistryAgent; + + const lookups: string[] = []; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-search-", + }); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }).pipe( + Effect.provideService(SpawnExecutableResolution, async (command) => { + lookups.push(command); + return "/bin/npm"; + }), + ); + const result = yield* resolver.search({ query: "codex" }); + + expect(lookups).toEqual(["npm"]); + expect(result.agents.map((agent) => agent.id)).toEqual(["codex-acp", "other-agent"]); + expect(result.agents[0]).toMatchObject({ + authors: ["OpenAI", "Zed Industries"], + distribution: "npx", + integrity: "registry", + license: "Apache-2.0", + }); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + JSON.stringify({ + version: "1.0.0", + agents: [descriptionMatch, incompatible, exact], + }), + ), + ), + ), + ), + ), + ); + }); + + it.effect("searches reuse an index fetched in the last five minutes", () => { + const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); + let requests = 0; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-refresh-", + }); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + yield* Effect.all( + [resolver.search({ query: "example" }), resolver.search({ query: "example" })], + { concurrency: "unbounded" }, + ); + expect(requests).toBe(1); + + yield* TestClock.adjust("4 minutes"); + yield* resolver.search({ query: "other" }); + expect(requests).toBe(1); + + yield* TestClock.adjust("1 minute"); + yield* resolver.search({ query: "example" }); + expect(requests).toBe(2); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + requests += 1; + return Effect.yieldNow.pipe( + Effect.as(HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent)))), + ); + }), + ), + ); + }); + + it.effect("searches retry the network after falling back to the cached index", () => { + const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); + let requests = 0; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-retry-", + }); + yield* fileSystem.makeDirectory(`${cacheDir}/acp-registry`, { recursive: true }); + yield* fileSystem.writeFileString( + `${cacheDir}/acp-registry/registry.json`, + makeRegistry(agent), + ); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const offline = yield* resolver.search({ query: "example" }); + expect(offline.agents.map((result) => result.id)).toEqual([agent.id]); + expect(requests).toBe(1); + + yield* resolver.search({ query: "example" }); + expect(requests).toBe(2); + yield* resolver.search({ query: "example" }); + expect(requests).toBe(2); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + requests += 1; + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + requests === 1 + ? new Response("unavailable", { status: 503 }) + : new Response(makeRegistry(agent)), + ), + ); + }), + ), + ); + }); + + it.effect("searches retry the network after a refresh falls back within the reuse window", () => { + const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); + let requests = 0; + let online = true; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-refresh-fallback-", + }); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + yield* resolver.search({ query: "example" }); + expect(requests).toBe(1); + + // Prepare always refreshes; an unknown agent stops it right after the refresh. + online = false; + const missing = yield* resolver.prepare({ agentId: "missing-agent" }).pipe(Effect.flip); + expect(missing.reason).toBe("agent_not_found"); + expect(requests).toBe(2); + + online = true; + yield* resolver.search({ query: "example" }); + expect(requests).toBe(3); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + requests += 1; + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + online + ? new Response(makeRegistry(agent)) + : new Response("unavailable", { status: 503 }), + ), + ); + }), + ), + ); + }); + + it.effect("filters runner recipes that the environment cannot prepare", () => { + const runnerAgent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); + const binaryAgent = { + ...makeAgent({ + binary: { + "linux-x86_64": { archive: archiveUrl, cmd: "example-agent" }, + }, + }), + id: "binary-agent", + name: "Binary Agent", + } satisfies AcpRegistrySupport.AcpRegistryAgent; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-runner-filter-", + }); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const result = yield* resolver.search({ query: "" }); + + expect(result.agents.map((agent) => agent.id)).toEqual(["binary-agent"]); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver( + (request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + JSON.stringify({ version: "1.0.0", agents: [runnerAgent, binaryAgent] }), + ), + ), + ), + { PATH: "" }, + ), + ), + ); + }); + + it.effect("discards registry agents with blank names or unsafe versions", () => { + const distribution = { + binary: { + "linux-x86_64": { archive: archiveUrl, cmd: "example-agent" }, + }, + } satisfies AcpRegistrySupport.AcpRegistryAgent["distribution"]; + const valid = makeAgent(distribution); + const blankName = { ...valid, id: "blank-name", name: " " }; + const blankVersion = { ...valid, id: "blank-version", version: "\t" }; + const parentVersion = { ...valid, id: "parent-version", version: ".." }; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-blank-fields-", + }); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const result = yield* resolver.search({ query: "" }); + + expect(result.agents.map((agent) => agent.id)).toEqual([valid.id]); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + JSON.stringify({ + version: "1.0.0", + agents: [blankName, blankVersion, parentVersion, valid], + }), + ), + ), + ), + ), + ), + ); + }); + + it.effect("ignores unpinned runner recipes from the registry", () => { + const agent = makeAgent({ npx: { package: "@example/acp@latest" } }); + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-unpinned-", + }); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const result = yield* resolver.search({ query: "" }); + + expect(result.agents).toEqual([]); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => + Effect.succeed(HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent)))), + ), + ), + ); + }); + + it.effect("rejects package syntax for the wrong runner", () => { + const invalidAgents = [ + { ...makeAgent({ npx: { package: "example-agent==1.2.3" } }), id: "bad-npx" }, + ]; + const validAgents = [ + { ...makeAgent({ uvx: { package: "minion-code@0.1.44" } }), id: "valid-at" }, + { ...makeAgent({ uvx: { package: "fast-agent-acp==0.9.30" } }), id: "valid-equals" }, + ]; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-runner-syntax-", + }); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const invalid = yield* resolver.prepare({ agentId: "bad-npx" }).pipe(Effect.flip); + const validAt = yield* resolver.prepare({ agentId: "valid-at" }).pipe(Effect.flip); + const validEquals = yield* resolver.prepare({ agentId: "valid-equals" }).pipe(Effect.flip); + + expect(invalid.reason).toBe("agent_not_found"); + expect(validAt.reason).toBe("runner_unavailable"); + expect(validEquals.reason).toBe("runner_unavailable"); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver( + (request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + JSON.stringify({ version: "1.0.0", agents: [...invalidAgents, ...validAgents] }), + ), + ), + ), + { PATH: "" }, + ), + ), + ); + }); + + it.effect("verifies declared SHA-256 before installing a binary", () => { + const agent = makeAgent({ + binary: { + "linux-x86_64": { + archive: archiveUrl, + cmd: "example-agent", + sha256: "0".repeat(64), + }, + }, + }); + const binaryBytes = new TextEncoder().encode("not the declared binary"); + + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-checksum-", + }); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const error = yield* resolver.prepare({ agentId: agent.id }).pipe(Effect.flip); + + expect(error.reason).toBe("checksum_mismatch"); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + request.url === registryUrl + ? new Response(makeRegistry(agent)) + : new Response(binaryBytes.buffer as ArrayBuffer), + ), + ), + ), + ), + ); + }); + + it.effect("falls back to a valid cached registry index when refresh fails", () => { + const agent = makeAgent({ + npx: { + package: "@example/acp@1.2.3", + args: ["--stdio"], + }, + }); + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-cache-", + }); + const registryDirectory = `${cacheDir}/acp-registry`; + yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); + yield* fileSystem.writeFileString(`${registryDirectory}/registry.json`, makeRegistry(agent)); + const toolchain = yield* makeFakeNpmToolchain(cacheDir); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const resolved = yield* resolver.resolve(settings(), "/workspace", toolchain.environment); + + expect(resolved.spawn).toMatchObject({ + command: toolchain.executablePath, + args: ["--stdio"], + }); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => + Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("unavailable", { status: 503 })), + ), + ), + ), + ); + }); + + it.effect( + "installs the registry's current version when a cached index pins a removed build", + () => { + const binaryAgent = (version: string) => ({ + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: `https://registry.test/example-agent-${version}.bin`, + cmd: "./bin/example-agent", + args: ["acp"], + }, + }, + }), + version, + }); + const requests: Array = []; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-stale-", + }); + yield* fileSystem.makeDirectory(`${cacheDir}/acp-registry`, { recursive: true }); + yield* fileSystem.writeFileString( + `${cacheDir}/acp-registry/registry.json`, + makeRegistry(binaryAgent("1.2.3")), + ); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const resolved = yield* resolver.resolve(settings(), "/workspace"); + + expect(resolved.agent?.version).toBe("1.2.4"); + expect(resolved.spawn.command).toContain("/tools/example-agent/1.2.4/"); + expect(requests).toContain(registryUrl); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + requests.push(request.url); + const response = + request.url === registryUrl + ? new Response(makeRegistry(binaryAgent("1.2.4"))) + : request.url.endsWith("-1.2.4.bin") + ? new Response("#!/bin/sh\necho example\n") + : new Response("forbidden", { status: 403 }); + return Effect.succeed(HttpClientResponse.fromWeb(request, response)); + }), + ), + ); + }, + ); + + it.effect("rejects unsafe command paths before downloading an archive", () => { + const agent = makeAgent({ + binary: { + "linux-x86_64": { + archive: archiveUrl, + cmd: "../outside", + }, + }, + }); + const requests: Array = []; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-invalid-", + }); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const error = yield* resolver.resolve(settings(), "/workspace").pipe(Effect.flip); + + expect(error.reason).toBe("archive_invalid"); + expect(requests).toEqual([registryUrl]); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + requests.push(request.url); + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent))), + ); + }), + ), + ); + }); + + it.effect("inspects from disk without waiting for a registry refresh", () => { + const makeNpxAgent = (version: string) => ({ + ...makeAgent({ npx: { package: `@example/acp@${version}` } }), + version, + }); + const agent = makeNpxAgent("1.2.3"); + let requests = 0; + let refreshGate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-cold-inspect-", + }); + const registryDirectory = `${cacheDir}/acp-registry`; + const registryCachePath = `${registryDirectory}/registry.json`; + yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); + yield* fileSystem.writeFileString(registryCachePath, makeRegistry(agent)); + + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const inspection = yield* resolver.inspect(settings()); + + expect(inspection).toMatchObject({ status: "ready", agentId: agent.id, version: "1.2.3" }); + expect(requests).toBe(0); + + // Cold inspection returns the disk cache immediately even while a refresh holds the semaphore. + refreshGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + const resolverWhileRefreshing = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const refreshFiber = yield* resolverWhileRefreshing + .refreshIndex({ maxAgeMs: 15 * 60 * 1_000, failureBackoffMs: 60_000 }) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(refreshGate.started); + expect(yield* resolverWhileRefreshing.inspect(settings())).toMatchObject({ + status: "ready", + version: "1.2.3", + }); + yield* Deferred.succeed(refreshGate.release, undefined); + yield* Fiber.join(refreshFiber); + expect(yield* resolverWhileRefreshing.inspect(settings())).toMatchObject({ + status: "ready", + version: "1.2.4", + }); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + requests += 1; + const gate = refreshGate; + const respond = Effect.sync(() => + HttpClientResponse.fromWeb(request, new Response(makeRegistry(makeNpxAgent("1.2.4")))), + ); + return gate === null + ? respond + : Deferred.succeed(gate.started, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + Effect.andThen(respond), + ); + }), + ), + ); + }); + + it.effect("keeps a refreshed index when an overlapping disk read finishes later", () => { + const makeNpxAgent = (version: string) => ({ + ...makeAgent({ npx: { package: `@example/acp@${version}` } }), + version, + }); + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-disk-race-", + }); + const registryDirectory = path.join(cacheDir, "acp-registry"); + const registryCachePath = path.join(registryDirectory, "registry.json"); + yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); + yield* fileSystem.writeFileString(registryCachePath, makeRegistry(makeNpxAgent("1.2.3"))); + + const diskReadStarted = yield* Deferred.make(); + const releaseDiskRead = yield* Deferred.make(); + const delayedFileSystem: FileSystem.FileSystem = { + ...fileSystem, + readFileString: (filePath, encoding) => + filePath === registryCachePath + ? fileSystem.readFileString(filePath, encoding).pipe( + Effect.tap(() => Deferred.succeed(diskReadStarted, undefined)), + Effect.tap(() => Deferred.await(releaseDiskRead)), + ) + : fileSystem.readFileString(filePath, encoding), + }; + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, delayedFileSystem)); + + const diskInspectFiber = yield* resolver + .inspect(settings()) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(diskReadStarted); + expect( + yield* resolver.refreshIndex({ maxAgeMs: 15 * 60 * 1_000, failureBackoffMs: 60_000 }), + ).toBe(1); + yield* Deferred.succeed(releaseDiskRead, undefined); + + expect(yield* Fiber.join(diskInspectFiber)).toMatchObject({ + status: "ready", + version: "1.2.4", + }); + expect(yield* resolver.inspect(settings())).toMatchObject({ + status: "ready", + version: "1.2.4", + }); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => + Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(makeRegistry(makeNpxAgent("1.2.4")))), + ), + ), + ), + ); + }); + + it.effect("recovers inspection from a corrupt cache once the registry is reachable", () => { + const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); + let online = false; + let requests = 0; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-offline-", + }); + yield* fileSystem.makeDirectory(`${cacheDir}/acp-registry`, { recursive: true }); + yield* fileSystem.writeFileString(`${cacheDir}/acp-registry/registry.json`, "{not json"); + const options = { cacheDir, toolsDir: `${cacheDir}/tools`, registryUrl }; + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog(options); + + const offline = yield* resolver.inspect(settings()).pipe(Effect.flip); + expect(offline.reason).toBe("registry_unavailable"); + + online = true; + const concurrent = yield* Effect.all( + [resolver.inspect(settings()), resolver.inspect(settings())], + { concurrency: "unbounded" }, + ); + expect(concurrent).toMatchObject([{ status: "ready" }, { status: "ready" }]); + expect(requests).toBe(2); + + const restarted = yield* AcpRegistrySupport.makeAcpRegistryCatalog(options); + expect(yield* restarted.inspect(settings())).toMatchObject({ status: "ready" }); + expect(requests).toBe(2); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + requests += 1; + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + online + ? new Response(makeRegistry(agent)) + : new Response("unavailable", { status: 503 }), + ), + ); + }), + ), + ); + }); + + it.effect("uses the effective provider environment for inspection and resolution", () => { + const agent = makeAgent({ npx: { package: "@example/acp@1.2.3" } }); + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-effective-env-", + }); + const registryDirectory = `${cacheDir}/acp-registry`; + yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); + yield* fileSystem.writeFileString(`${registryDirectory}/registry.json`, makeRegistry(agent)); + const toolchain = yield* makeFakeNpmToolchain(cacheDir); + + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const hostInspection = yield* resolver.inspect(settings()); + const providerEnvironment = toolchain.environment; + const instanceInspection = yield* resolver.inspect(settings(), providerEnvironment); + const resolved = yield* resolver.resolve(settings(), "/workspace", providerEnvironment); + + expect(hostInspection).toMatchObject({ status: "missing_runner", runner: "npm" }); + expect(instanceInspection).toMatchObject({ status: "ready", distribution: "npx" }); + expect(resolved.spawn).toMatchObject({ + command: toolchain.executablePath, + env: { PATH: expect.stringMatching(new RegExp(`^${toolchain.globalBin}:`, "u")) }, + }); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver( + (request) => + Effect.succeed(HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent)))), + { PATH: "" }, + ), + ), + ); + }); + + it.effect("requires a regular executable file in the managed binary cache", () => { + const agent = makeAgent({ + binary: { + "linux-x86_64": { + archive: archiveUrl, + cmd: "bin/example-agent", + }, + }, + }); + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-non-file-", + }); + const registryDirectory = `${cacheDir}/acp-registry`; + const fakeExecutable = `${cacheDir}/tools/example-agent/1.2.3/linux-x86_64/bin/example-agent`; + yield* fileSystem.makeDirectory(fakeExecutable, { recursive: true }); + yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); + yield* fileSystem.writeFileString(`${registryDirectory}/registry.json`, makeRegistry(agent)); + + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const directoryError = yield* resolver.inspect(settings()).pipe(Effect.flip); + + expect(directoryError.reason).toBe("archive_invalid"); + + yield* fileSystem.remove(fakeExecutable, { recursive: true }); + yield* fileSystem.writeFileString(fakeExecutable, "#!/bin/sh\n"); + yield* fileSystem.chmod(fakeExecutable, 0o644); + const modeError = yield* resolver.inspect(settings()).pipe(Effect.flip); + + expect(modeError.reason).toBe("archive_invalid"); + + yield* fileSystem.chmod(fakeExecutable, 0o755); + expect(yield* resolver.inspect(settings())).toMatchObject({ status: "ready" }); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => + Effect.succeed(HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent)))), + ), + ), + ); + }); + + it.effect.each([ + { name: "legacy registry", source: undefined, agentId: "example-agent", referenced: true }, + { name: "registry", source: "registry", agentId: "example-agent", referenced: true }, + { name: "padded registry", source: "registry", agentId: " example-agent ", referenced: true }, + { name: "local command", source: "local", agentId: "example-agent", referenced: false }, + ] as const)( + "checks $name references before uninstalling only managed binaries", + ({ source, agentId, referenced }) => { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-uninstall-", + }); + const agentRoot = `${cacheDir}/tools/example-agent`; + const runnerCache = `${cacheDir}/external-npx-cache/example-agent/package.json`; + yield* fileSystem.makeDirectory(`${agentRoot}/1.2.3/linux-x86_64`, { recursive: true }); + yield* fileSystem.writeFileString(`${agentRoot}/1.2.3/linux-x86_64/agent`, "binary"); + yield* fileSystem.makeDirectory(`${cacheDir}/external-npx-cache/example-agent`, { + recursive: true, + }); + yield* fileSystem.writeFileString(runnerCache, "{}"); + + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const hostSettings = yield* TestProviderHost.TestProviderHostSettings; + const instanceId = ProviderInstanceId.make("uninstall-reference"); + yield* hostSettings.set({ + ...DEFAULT_SERVER_SETTINGS, + providerInstances: { + [instanceId]: { + driver: ProviderDriverKind.make("acpRegistry"), + displayName: "Uninstall reference", + enabled: true, + config: { + agentId, + commandPath: "/local/agent", + ...(source ? { source } : {}), + }, + }, + }, + }); + const first = yield* resolver.uninstallManagedBinary({ agentId: "example-agent" }); + expect(first).toEqual({ agentId: "example-agent", removed: !referenced }); + expect(yield* fileSystem.exists(agentRoot)).toBe(referenced); + yield* hostSettings.set(DEFAULT_SERVER_SETTINGS); + const second = yield* resolver.uninstallManagedBinary({ agentId: "example-agent" }); + + expect(second).toEqual({ agentId: "example-agent", removed: referenced }); + expect(yield* resolver.uninstallManagedBinary({ agentId: "example-agent" })).toEqual({ + agentId: "example-agent", + removed: false, + }); + expect(yield* fileSystem.exists(agentRoot)).toBe(false); + expect(yield* fileSystem.exists(runnerCache)).toBe(true); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => + Effect.succeed(HttpClientResponse.fromWeb(request, new Response("unused"))), + ), + ), + ); + }, + ); + + it.effect("keeps managed package installs when removing the same agent's binaries", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-uninstall-packages-", + }); + const versionRoot = `${cacheDir}/tools/example-agent/1.2.3`; + yield* fileSystem.makeDirectory(`${versionRoot}/linux-x86_64`, { recursive: true }); + yield* fileSystem.writeFileString(`${versionRoot}/linux-x86_64/agent`, "binary"); + yield* fileSystem.makeDirectory(`${versionRoot}/npm/bin`, { recursive: true }); + yield* fileSystem.writeFileString(`${versionRoot}/npm/bin/agent`, "package command"); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + expect(yield* resolver.uninstallManagedBinary({ agentId: "example-agent" })).toEqual({ + agentId: "example-agent", + removed: true, + }); + expect(yield* fileSystem.exists(`${versionRoot}/linux-x86_64`)).toBe(false); + expect(yield* fileSystem.readFileString(`${versionRoot}/npm/bin/agent`)).toBe( + "package command", + ); + expect(yield* resolver.uninstallManagedBinary({ agentId: "example-agent" })).toEqual({ + agentId: "example-agent", + removed: false, + }); + }).pipe( + Effect.scoped, + Effect.provide(layerResolver(() => Effect.die("unexpected HTTP request"))), + ), + ); + + it.effect("keeps a binary prepared by another client while an uninstall is waiting", () => { + const agent = makeAgent({ + binary: { + "linux-x86_64": { + archive: archiveUrl, + cmd: "./bin/example-agent", + }, + }, + }); + const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho example\n"); + return Effect.gen(function* () { + const downloadStarted = yield* Deferred.make(); + const releaseDownload = yield* Deferred.make(); + return yield* Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-uninstall-race-", + }); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + + const prepareFiber = yield* resolver + .prepare({ agentId: agent.id }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(downloadStarted); + const uninstallFiber = yield* resolver + .uninstallManagedBinary({ agentId: agent.id }) + .pipe(Effect.forkChild({ startImmediately: true })); + + expect(uninstallFiber.pollUnsafe()).toBeUndefined(); + yield* Deferred.succeed(releaseDownload, undefined); + + expect(yield* Fiber.join(prepareFiber)).toMatchObject({ prepared: true }); + expect(yield* Fiber.join(uninstallFiber)).toEqual({ + agentId: agent.id, + removed: false, + }); + const agentRoot = `${cacheDir}/tools/${agent.id}`; + expect(yield* fileSystem.exists(agentRoot)).toBe(true); + + const hostSettings = yield* TestProviderHost.TestProviderHostSettings; + const instanceId = ProviderInstanceId.make("registry-reference"); + yield* hostSettings.set({ + ...DEFAULT_SERVER_SETTINGS, + providerInstances: { + [instanceId]: { + driver: ProviderDriverKind.make("acpRegistry"), + displayName: "Registry reference", + enabled: true, + config: { agentId: agent.id }, + }, + }, + }); + expect(yield* resolver.uninstallManagedBinary({ agentId: agent.id })).toEqual({ + agentId: agent.id, + removed: false, + }); + yield* hostSettings.set(DEFAULT_SERVER_SETTINGS); + expect(yield* resolver.uninstallManagedBinary({ agentId: agent.id })).toEqual({ + agentId: agent.id, + removed: true, + }); + expect(yield* resolver.uninstallManagedBinary({ agentId: agent.id })).toEqual({ + agentId: agent.id, + removed: false, + }); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + if (request.url === registryUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent))), + ); + } + return Deferred.succeed(downloadStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseDownload)), + Effect.as( + HttpClientResponse.fromWeb( + request, + new Response(binaryBytes.buffer as ArrayBuffer), + ), + ), + ); + }), + ), + ); + }); + }); + + it.effect("resolves an installed agent while another agent's download is still running", () => { + const slowArchiveUrl = "https://registry.test/slow-agent.bin"; + const agent = makeAgent({ + binary: { "linux-x86_64": { archive: archiveUrl, cmd: "./bin/example-agent" } }, + }); + const slowAgent = { + ...agent, + distribution: { + binary: { "linux-x86_64": { archive: slowArchiveUrl, cmd: "./bin/slow-agent" } }, + }, + id: "slow-agent", + name: "Slow Agent", + }; + const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho example\n"); + return Effect.gen(function* () { + const downloadStarted = yield* Deferred.make(); + const releaseDownload = yield* Deferred.make(); + return yield* Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-parallel-install-", + }); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + + yield* resolver.resolve(settings(), "/workspace"); + + const prepareFiber = yield* resolver + .prepare({ agentId: slowAgent.id }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(downloadStarted); + + const resolved = yield* resolver.resolve(settings(), "/workspace"); + expect(resolved.spawn.command).toContain( + "/tools/example-agent/1.2.3/linux-x86_64/bin/example-agent", + ); + expect(prepareFiber.pollUnsafe()).toBeUndefined(); + + yield* Deferred.succeed(releaseDownload, undefined); + expect(yield* Fiber.join(prepareFiber)).toMatchObject({ prepared: true }); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + if (request.url === registryUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(JSON.stringify({ version: "1.0.0", agents: [slowAgent, agent] })), + ), + ); + } + const response = HttpClientResponse.fromWeb( + request, + new Response(binaryBytes.buffer as ArrayBuffer), + ); + if (request.url !== slowArchiveUrl) return Effect.succeed(response); + return Deferred.succeed(downloadStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseDownload)), + Effect.as(response), + ); + }), + ), + ); + }); + }); + + it.effect("reserves a prepared binary until a configured instance inspects it", () => { + const agent = makeAgent({ + binary: { + "linux-x86_64": { + archive: archiveUrl, + cmd: "./bin/example-agent", + }, + }, + }); + const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho example\n"); + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-uninstall-reservation-", + }); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + + yield* resolver.prepare({ agentId: agent.id }); + expect(yield* resolver.uninstallManagedBinary({ agentId: agent.id })).toEqual({ + agentId: agent.id, + removed: false, + }); + expect(yield* resolver.inspect(settings())).toMatchObject({ status: "ready" }); + expect(yield* resolver.uninstallManagedBinary({ agentId: agent.id })).toEqual({ + agentId: agent.id, + removed: true, + }); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + request.url === registryUrl + ? new Response(makeRegistry(agent)) + : new Response(binaryBytes.buffer as ArrayBuffer), + ), + ), + ), + ), + ); + }); + + it.effect( + "repairs broken artifact slots, recovers corrupt or transiently unreadable legacy baselines, and prunes uninstalled baselines", + () => { + const archiveAUrl = "https://registry.test/v1-a.bin"; + const archiveBUrl = "https://registry.test/v1-b.bin"; + const archiveCUrl = "https://registry.test/v2-c.bin"; + const bytesA = new TextEncoder().encode("#!/bin/sh\necho archive-a\n"); + const bytesB = new TextEncoder().encode("#!/bin/sh\necho archive-b\n"); + const bytesC = new TextEncoder().encode("#!/bin/sh\necho archive-c\n"); + const binaryAgent = (version: string, archive: string) => ({ + ...makeAgent({ + binary: { + "linux-x86_64": { archive, cmd: "./bin/example-agent" }, + }, + }), + version, + }); + let upstream = binaryAgent("1.2.3", archiveAUrl); + let extraUpstreamAgents: ReadonlyArray = []; + let upstreamEmpty = false; + let archiveRequestsDuringLockedSlot = 0; + let countArchiveRequests = false; + + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + // 1. A broken artifact-scoped slot (receipt present, executable deleted) self-repairs on resolve(). + const repairDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-repair-slot-", + }); + const repairResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: repairDir, + toolsDir: `${repairDir}/tools`, + registryUrl, + }); + const resolvedA = yield* repairResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(resolvedA.spawn.command)).toBe( + "#!/bin/sh\necho archive-a\n", + ); + + upstream = binaryAgent("1.2.3", archiveBUrl); + yield* repairResolver.invalidateIndex(); + yield* repairResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const resolvedB = yield* repairResolver.resolve(settings(), "/workspace"); + expect(resolvedB.spawn.command).toMatch(/linux-x86_64-[0-9a-f]{12}\/bin\/example-agent$/u); + expect(yield* fileSystem.readFileString(resolvedB.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // Delete B's executable while leaving the artifact slot directory and receipt behind. + yield* fileSystem.remove(resolvedB.spawn.command); + expect(yield* fileSystem.exists(resolvedB.spawn.command)).toBe(false); + const repairedB = yield* repairResolver.resolve(settings(), "/workspace"); + expect(repairedB.spawn.command).toBe(resolvedB.spawn.command); + expect(yield* fileSystem.readFileString(repairedB.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // If moving a broken artifact slot fails (e.g., locked files on Windows), fail fast with + // install_failed before making any archive download request. + yield* fileSystem.remove(repairedB.spawn.command); + const brokenSlotRoot = path.dirname(path.dirname(repairedB.spawn.command)); + archiveRequestsDuringLockedSlot = 0; + countArchiveRequests = true; + const unmovableSlotFs: FileSystem.FileSystem = { + ...fileSystem, + rename: (oldPath, newPath) => + oldPath === brokenSlotRoot + ? fileSystem.readFileString(repairDir).pipe(Effect.asVoid) + : fileSystem.rename(oldPath, newPath), + }; + const lockedSlotResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: repairDir, + toolsDir: `${repairDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, unmovableSlotFs)); + const lockedSlotError = yield* lockedSlotResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + countArchiveRequests = false; + expect(lockedSlotError.reason).toBe("install_failed"); + expect(archiveRequestsDuringLockedSlot).toBe(0); + + // 2. A transient I/O failure reading legacy-baselines.json preserves A's baseline in memory + // so the next successful refresh still persists A and updates registry.json to B. + const ioDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-baseline-io-", + }); + const ioRegistryDir = path.join(ioDir, "acp-registry"); + const ioRegistryPath = path.join(ioRegistryDir, "registry.json"); + const ioBaselinesPath = path.join(ioRegistryDir, "legacy-baselines.json"); + const ioLegacyExe = path.join( + ioDir, + "tools", + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(ioLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(ioLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(ioLegacyExe, 0o755); + yield* fileSystem.makeDirectory(ioRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + ioRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveAUrl)), + ); + + let failLegacyRead = true; + const flakyBaselinesFs: FileSystem.FileSystem = { + ...fileSystem, + readFileString: (filePath, encoding) => + failLegacyRead && filePath === ioBaselinesPath + ? fileSystem.readFileString(ioDir, encoding) + : fileSystem.readFileString(filePath, encoding), + }; + upstream = binaryAgent("1.0.0", archiveBUrl); + const ioResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: ioDir, + toolsDir: path.join(ioDir, "tools"), + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, flakyBaselinesFs)); + yield* ioResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(ioRegistryPath)).toContain(archiveAUrl); + expect(yield* fileSystem.exists(ioBaselinesPath)).toBe(false); + + failLegacyRead = false; + yield* ioResolver.invalidateIndex(); + yield* ioResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(ioRegistryPath)).toContain(archiveBUrl); + const persistedBaselines = yield* fileSystem.readFileString(ioBaselinesPath); + expect(persistedBaselines).toContain("example-agent\\u00001.0.0\\u0000linux-x86_64"); + expect(persistedBaselines).toContain(archiveAUrl); + + // Restarting against the recovered disk files must install B instead of reusing legacy A. + const restartedIoResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: ioDir, + toolsDir: path.join(ioDir, "tools"), + registryUrl, + }); + const resolvedAfterIoRecovery = yield* restartedIoResolver.resolve( + settings(), + "/workspace", + ); + expect(yield* fileSystem.readFileString(resolvedAfterIoRecovery.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // 2b. Non-directory files and unreadable unrelated tool directories in shared tools/ + // (e.g., tools/codex/active.json, tools/.DS_Store, tools/chrome-headless-shell, or a + // non-directory file at a candidate platform slot) must not break legacy baseline scanning. + const sharedToolsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-shared-tools-", + }); + const sharedRegistryDir = path.join(sharedToolsDir, "acp-registry"); + const sharedRegistryPath = path.join(sharedRegistryDir, "registry.json"); + const sharedBaselinesPath = path.join(sharedRegistryDir, "legacy-baselines.json"); + const sharedToolsRoot = path.join(sharedToolsDir, "tools"); + const sharedLegacyExe = path.join( + sharedToolsRoot, + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(sharedLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(sharedLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(sharedLegacyExe, 0o755); + // Place a regular file at a candidate installRoot slot to exercise the directory check. + const nonDirSlotDir = path.join(sharedToolsRoot, "example-agent", "0.9.0"); + yield* fileSystem.makeDirectory(nonDirSlotDir, { recursive: true }); + yield* fileSystem.writeFileString(path.join(nonDirSlotDir, "linux-x86_64"), "not-a-dir"); + yield* fileSystem.makeDirectory(path.join(sharedToolsRoot, "codex"), { recursive: true }); + yield* fileSystem.writeFileString( + path.join(sharedToolsRoot, "codex", "active.json"), + '{"version":"1.0.0"}', + ); + yield* fileSystem.writeFileString(path.join(sharedToolsRoot, ".DS_Store"), "finder"); + const unreadableOtherTool = path.join(sharedToolsRoot, "chrome-headless-shell"); + yield* fileSystem.makeDirectory(unreadableOtherTool, { recursive: true }); + yield* fileSystem.makeDirectory(sharedRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + sharedRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveAUrl)), + ); + const sharedToolsFs: FileSystem.FileSystem = { + ...fileSystem, + readDirectory: (dirPath, options) => + dirPath === unreadableOtherTool + ? fileSystem.readDirectory(sharedLegacyExe, options) + : fileSystem.readDirectory(dirPath, options), + }; + upstream = binaryAgent("1.0.0", archiveBUrl); + const sharedToolsResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: sharedToolsDir, + toolsDir: sharedToolsRoot, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, sharedToolsFs)); + yield* sharedToolsResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(sharedRegistryPath)).toContain(archiveBUrl); + expect(yield* fileSystem.readFileString(sharedBaselinesPath)).toContain(archiveAUrl); + expect(yield* fileSystem.readFileString(sharedBaselinesPath)).not.toContain("0.9.0"); + const resolvedWithSharedTools = yield* sharedToolsResolver.resolve( + settings(), + "/workspace", + ); + expect(yield* fileSystem.readFileString(resolvedWithSharedTools.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // 2c. An incomplete tools-directory scan during A -> B keeps disk registry.json on A AND + // blocks live resolution from launching legacy A as B even before the scan recovers; once + // readable again, recovery persists A and clears the incomplete flag for eligible slots. + const scanDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-scan-error-", + }); + const scanRegistryDir = path.join(scanDir, "acp-registry"); + const scanRegistryPath = path.join(scanRegistryDir, "registry.json"); + const scanBaselinesPath = path.join(scanRegistryDir, "legacy-baselines.json"); + const scanToolsDir = path.join(scanDir, "tools"); + const scanAgentDir = path.join(scanToolsDir, "example-agent"); + const scanLegacyExe = path.join( + scanAgentDir, + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(scanLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(scanLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(scanLegacyExe, 0o755); + yield* fileSystem.makeDirectory(scanRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + scanRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveAUrl)), + ); + let failToolsScan = true; + const flakyScanFs: FileSystem.FileSystem = { + ...fileSystem, + readDirectory: (dirPath, options) => + failToolsScan && dirPath === scanAgentDir + ? fileSystem.readDirectory(scanLegacyExe, options) + : fileSystem.readDirectory(dirPath, options), + }; + upstream = binaryAgent("1.0.0", archiveBUrl); + const scanResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: scanDir, + toolsDir: scanToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, flakyScanFs)); + yield* scanResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(scanRegistryPath)).toContain(archiveAUrl); + expect(yield* fileSystem.exists(scanBaselinesPath)).toBe(false); + + // Resolving BEFORE clearing the scan failure must install B instead of running legacy A. + const resolvedDuringScanFailure = yield* scanResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(resolvedDuringScanFailure.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // A failed scan after restart must NOT overwrite a durable legacy baseline with registry.json: + // with legacy A on disk, durable baseline A, and registry.json at B, failing a scan on + // B -> C and rolling back to B while still failing must install B, not run legacy A as B. + const durableScanDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-durable-scan-", + }); + const durableRegistryDir = path.join(durableScanDir, "acp-registry"); + const durableRegistryPath = path.join(durableRegistryDir, "registry.json"); + const durableBaselinesPath = path.join(durableRegistryDir, "legacy-baselines.json"); + const durableToolsDir = path.join(durableScanDir, "tools"); + const durableAgentDir = path.join(durableToolsDir, "example-agent"); + const durableLegacyExe = path.join( + durableAgentDir, + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(durableLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(durableLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(durableLegacyExe, 0o755); + yield* fileSystem.makeDirectory(durableRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + durableRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveBUrl)), + ); + yield* fileSystem.writeFileString( + durableBaselinesPath, + JSON.stringify({ + "example-agent\u00001.0.0\u0000linux-x86_64": JSON.stringify({ + archive: archiveAUrl, + cmd: "./bin/example-agent", + sha256: null, + }), + }), + ); + const failDurableScanFs: FileSystem.FileSystem = { + ...fileSystem, + readDirectory: (dirPath, options) => + dirPath === durableAgentDir + ? fileSystem.readDirectory(durableLegacyExe, options) + : fileSystem.readDirectory(dirPath, options), + }; + const durableScanResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: durableScanDir, + toolsDir: durableToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, failDurableScanFs)); + upstream = binaryAgent("1.0.0", archiveCUrl); + yield* durableScanResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + upstream = binaryAgent("1.0.0", archiveBUrl); + yield* durableScanResolver.invalidateIndex(); + yield* durableScanResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const resolvedAgainstDurable = yield* durableScanResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(resolvedAgainstDurable.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // A transient I/O error reading registry.json during baseline discovery must also keep + // disk registry.json untouched rather than treating it as missing. + const regIoDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-reg-io-", + }); + const regIoRegistryDir = path.join(regIoDir, "acp-registry"); + const regIoRegistryPath = path.join(regIoRegistryDir, "registry.json"); + const regIoLegacyExe = path.join( + regIoDir, + "tools", + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(regIoLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(regIoLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(regIoLegacyExe, 0o755); + yield* fileSystem.makeDirectory(regIoRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + regIoRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveAUrl)), + ); + const failRegistryReadFs: FileSystem.FileSystem = { + ...fileSystem, + readFileString: (filePath, encoding) => + filePath === regIoRegistryPath + ? fileSystem.readFileString(regIoDir, encoding) + : fileSystem.readFileString(filePath, encoding), + }; + const regIoResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: regIoDir, + toolsDir: path.join(regIoDir, "tools"), + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, failRegistryReadFs)); + yield* regIoResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(regIoRegistryPath)).toContain(archiveAUrl); + // Live resolution during an unreadable disk registry.json must also install B rather than + // launching the unverified legacy A executable. + const resolvedDuringRegIo = yield* regIoResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(resolvedDuringRegIo.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // A transient stat I/O error on tools/ itself must keep disk registry.json on A and + // block live resolution from launching unverified legacy A. + const statIoDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-stat-io-", + }); + const statIoRegistryDir = path.join(statIoDir, "acp-registry"); + const statIoRegistryPath = path.join(statIoRegistryDir, "registry.json"); + const statIoToolsDir = path.join(statIoDir, "tools"); + const statIoLegacyExe = path.join( + statIoToolsDir, + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(statIoLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(statIoLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(statIoLegacyExe, 0o755); + yield* fileSystem.makeDirectory(statIoRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + statIoRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveAUrl)), + ); + const failToolsStatFs: FileSystem.FileSystem = { + ...fileSystem, + stat: (filePath) => + filePath === statIoToolsDir + ? fileSystem + .readFileString(statIoToolsDir) + .pipe(Effect.andThen(fileSystem.stat(filePath))) + : fileSystem.stat(filePath), + }; + const statIoResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: statIoDir, + toolsDir: statIoToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, failToolsStatFs)); + yield* statIoResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(statIoRegistryPath)).toContain(archiveAUrl); + const resolvedDuringStatIo = yield* statIoResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(resolvedDuringStatIo.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // Removing an agent present in the initial disk registry.json must still record its + // legacy baseline on the first refresh after restart so a later re-add at the same + // version with a different archive installs B instead of executing legacy A. + const removedAgentDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-removed-baseline-", + }); + const removedRegistryDir = path.join(removedAgentDir, "acp-registry"); + const removedRegistryPath = path.join(removedRegistryDir, "registry.json"); + const removedBaselinesPath = path.join(removedRegistryDir, "legacy-baselines.json"); + const removedToolsDir = path.join(removedAgentDir, "tools"); + const removedLegacyExe = path.join( + removedToolsDir, + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(removedLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(removedLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(removedLegacyExe, 0o755); + yield* fileSystem.makeDirectory(removedRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + removedRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveAUrl)), + ); + upstreamEmpty = true; + const removedAgentResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: removedAgentDir, + toolsDir: removedToolsDir, + registryUrl, + }); + yield* removedAgentResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(removedBaselinesPath)).toContain(archiveAUrl); + upstreamEmpty = false; + upstream = binaryAgent("1.0.0", archiveBUrl); + yield* removedAgentResolver.invalidateIndex(); + yield* removedAgentResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const resolvedAfterReadd = yield* removedAgentResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(resolvedAfterReadd.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + failToolsScan = false; + yield* scanResolver.invalidateIndex(); + yield* scanResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(scanRegistryPath)).toContain(archiveBUrl); + expect(yield* fileSystem.readFileString(scanBaselinesPath)).toContain(archiveAUrl); + // Once the scan recovers and baselines persist, legacyBaselineDiscoveryIncomplete is reset + // so an eligible unreceipted legacy slot at a matching version can be reused cleanly. + const scanLegacyV2Exe = path.join( + scanAgentDir, + "2.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(scanLegacyV2Exe), { recursive: true }); + yield* fileSystem.writeFileString(scanLegacyV2Exe, "#!/bin/sh\necho legacy-v2\n"); + yield* fileSystem.chmod(scanLegacyV2Exe, 0o755); + upstream = binaryAgent("2.0.0", archiveCUrl); + yield* scanResolver.invalidateIndex(); + yield* scanResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const reusedAfterRecovery = yield* scanResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(reusedAfterRecovery.spawn.command)).toBe( + "#!/bin/sh\necho legacy-v2\n", + ); + upstream = binaryAgent("1.0.0", archiveBUrl); + const restartedScanResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: scanDir, + toolsDir: scanToolsDir, + registryUrl, + }); + yield* restartedScanResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const resolvedAfterScanRecovery = yield* restartedScanResolver.resolve( + settings(), + "/workspace", + ); + expect(yield* fileSystem.readFileString(resolvedAfterScanRecovery.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // 3. A corrupt legacy-baselines.json is copied aside and rebuilt cleanly without inferring + // provenance from an unverified cached registry index: even on a B -> C refresh after + // restart, the unreceipted slot is marked "unknown" so a later rollback to B installs B + // instead of executing legacy A as B. uninstallManagedBinary prunes removed agents. + const corruptDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-baseline-corrupt-", + }); + const corruptRegistryDir = path.join(corruptDir, "acp-registry"); + const corruptRegistryPath = path.join(corruptRegistryDir, "registry.json"); + const corruptBaselinesPath = path.join(corruptRegistryDir, "legacy-baselines.json"); + const corruptToolsDir = path.join(corruptDir, "tools"); + const corruptLegacyExe = path.join( + corruptToolsDir, + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + const corruptUnreadableOtherTool = path.join(corruptToolsDir, "chrome-headless-shell"); + const corruptReadableRemovedExe = path.join( + corruptToolsDir, + "removed-readable-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + const corruptUnreadableRemovedDir = path.join(corruptToolsDir, "removed-unreadable-agent"); + const corruptUnreadableRemovedExe = path.join( + corruptUnreadableRemovedDir, + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(corruptLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(corruptLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(corruptLegacyExe, 0o755); + yield* fileSystem.makeDirectory(path.dirname(corruptReadableRemovedExe), { + recursive: true, + }); + yield* fileSystem.writeFileString(corruptReadableRemovedExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(corruptReadableRemovedExe, 0o755); + yield* fileSystem.makeDirectory(path.dirname(corruptUnreadableRemovedExe), { + recursive: true, + }); + yield* fileSystem.writeFileString( + corruptUnreadableRemovedExe, + "#!/bin/sh\necho legacy-a\n", + ); + yield* fileSystem.chmod(corruptUnreadableRemovedExe, 0o755); + yield* fileSystem.makeDirectory(corruptUnreadableOtherTool, { recursive: true }); + yield* fileSystem.makeDirectory(corruptRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + corruptRegistryPath, + makeRegistry(binaryAgent("1.0.0", archiveBUrl)), + ); + yield* fileSystem.writeFileString(corruptBaselinesPath, "{not json"); + let failRemovedUnreadable = true; + const corruptToolsFs: FileSystem.FileSystem = { + ...fileSystem, + readDirectory: (dirPath, options) => + dirPath === corruptUnreadableOtherTool || + (failRemovedUnreadable && dirPath === corruptUnreadableRemovedDir) + ? fileSystem.readDirectory(corruptLegacyExe, options) + : fileSystem.readDirectory(dirPath, options), + }; + + upstream = binaryAgent("2.0.0", archiveCUrl); + const corruptResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: corruptDir, + toolsDir: corruptToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, corruptToolsFs)); + yield* corruptResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(`${corruptBaselinesPath}.corrupt`)).toBe( + "{not json", + ); + expect(yield* fileSystem.readFileString(corruptRegistryPath)).toContain(archiveCUrl); + const rebuiltBaselines = JSON.parse( + yield* fileSystem.readFileString(corruptBaselinesPath), + ) as Record; + const exampleSlotKey = "example-agent\u00001.0.0\u0000linux-x86_64"; + const otherSlotKey = "other-agent\u00001.0.0\u0000linux-x86_64"; + expect(rebuiltBaselines[exampleSlotKey]).toBe("unknown"); + // Readable removed-agent slots are discovered and marked unknown; unreadable extra + // directories get an agent-level unknown sentinel so neither blocks recovery nor loses + // unknown provenance if the directory becomes readable and the agent is later re-added. + expect(rebuiltBaselines["removed-readable-agent\u00001.0.0\u0000linux-x86_64"]).toBe( + "unknown", + ); + expect(rebuiltBaselines["removed-unreadable-agent\u0000*"]).toBe("unknown"); + expect(rebuiltBaselines["chrome-headless-shell\u0000*"]).toBe("unknown"); + + // Verify \0* sentinels are excluded from normal requiredAgentIds, honored on direct disk + // and in-memory lookups and in recordDivergingInMemory, and pruned on uninstall. + failRemovedUnreadable = false; + upstream = binaryAgent("2.0.1", archiveCUrl); + yield* corruptResolver.invalidateIndex(); + yield* corruptResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(corruptRegistryPath)).toContain("2.0.1"); + + // Direct resolve without refreshIndex() verifies disk \0* check in isLegacyBinarySlotEligible, + // and a second resolve on a second unreceipted version verifies memory \0* check. + const corruptUnreadableV2Exe = path.join( + corruptUnreadableRemovedDir, + "2.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(corruptUnreadableV2Exe), { recursive: true }); + yield* fileSystem.writeFileString(corruptUnreadableV2Exe, "#!/bin/sh\necho legacy-v2\n"); + yield* fileSystem.chmod(corruptUnreadableV2Exe, 0o755); + yield* fileSystem.writeFileString( + corruptRegistryPath, + JSON.stringify({ + version: "1.0.0", + agents: [ + binaryAgent("2.0.1", archiveCUrl), + { ...binaryAgent("1.0.0", archiveAUrl), id: "removed-unreadable-agent" }, + ], + }), + ); + const directDiskSentinelCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: corruptDir, + toolsDir: corruptToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, corruptToolsFs)); + const resolvedDirectDiskSentinel = yield* directDiskSentinelCatalog.resolve( + settings({ agentId: "removed-unreadable-agent" }), + "/workspace", + ); + expect(yield* fileSystem.readFileString(resolvedDirectDiskSentinel.spawn.command)).toBe( + "#!/bin/sh\necho archive-a\n", + ); + // Refreshing 1.0.0 -> 2.0.0 while 2.0.0 stays unreceipted persists a slot-specific + // "unknown" baseline for 2.0.0 instead of attributing it to archiveA. + extraUpstreamAgents = [ + { ...binaryAgent("2.0.0", archiveBUrl), id: "removed-unreadable-agent" }, + ]; + yield* directDiskSentinelCatalog.invalidateIndex(); + yield* directDiskSentinelCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const baselinesAfterDiverge = JSON.parse( + yield* fileSystem.readFileString(corruptBaselinesPath), + ) as Record; + expect(baselinesAfterDiverge["removed-unreadable-agent\u00002.0.0\u0000linux-x86_64"]).toBe( + "unknown", + ); + const resolvedSlotSentinel = yield* directDiskSentinelCatalog.resolve( + settings({ agentId: "removed-unreadable-agent" }), + "/workspace", + ); + expect(yield* fileSystem.readFileString(resolvedSlotSentinel.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + // Resolve an unreceipted 3.0.0 legacy slot absent during the scan with the on-disk \0* + // sentinel removed so ONLY the cached in-memory \0* sentinel can reject legacy reuse. + extraUpstreamAgents = [ + { ...binaryAgent("3.0.0", archiveCUrl), id: "removed-unreadable-agent" }, + ]; + yield* directDiskSentinelCatalog.invalidateIndex(); + yield* directDiskSentinelCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const baselinesBeforeV3 = JSON.parse( + yield* fileSystem.readFileString(corruptBaselinesPath), + ) as Record; + expect( + baselinesBeforeV3["removed-unreadable-agent\u00003.0.0\u0000linux-x86_64"], + ).toBeUndefined(); + const { + ["removed-unreadable-agent\u0000*"]: _droppedDiskSentinel, + ...baselinesWithoutAgentSentinel + } = baselinesBeforeV3; + yield* fileSystem.writeFileString( + corruptBaselinesPath, + JSON.stringify(baselinesWithoutAgentSentinel), + ); + const corruptUnreadableV3Exe = path.join( + corruptUnreadableRemovedDir, + "3.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(corruptUnreadableV3Exe), { recursive: true }); + yield* fileSystem.writeFileString(corruptUnreadableV3Exe, "#!/bin/sh\necho legacy-v3\n"); + yield* fileSystem.chmod(corruptUnreadableV3Exe, 0o755); + const resolvedMemorySentinel = yield* directDiskSentinelCatalog.resolve( + settings({ agentId: "removed-unreadable-agent" }), + "/workspace", + ); + expect(yield* fileSystem.readFileString(resolvedMemorySentinel.spawn.command)).toBe( + "#!/bin/sh\necho archive-c\n", + ); + // Restore the on-disk \0* sentinel to confirm uninstallManagedBinary prunes both keys. + yield* fileSystem.writeFileString( + corruptBaselinesPath, + JSON.stringify(baselinesAfterDiverge), + ); + expect( + yield* directDiskSentinelCatalog.uninstallManagedBinary({ + agentId: "removed-unreadable-agent", + }), + ).toEqual({ agentId: "removed-unreadable-agent", removed: true }); + const baselinesAfterSentinelUninstall = JSON.parse( + yield* fileSystem.readFileString(corruptBaselinesPath), + ) as Record; + expect(baselinesAfterSentinelUninstall["removed-unreadable-agent\u0000*"]).toBeUndefined(); + expect( + baselinesAfterSentinelUninstall["removed-unreadable-agent\u00002.0.0\u0000linux-x86_64"], + ).toBeUndefined(); + expect(baselinesAfterSentinelUninstall["chrome-headless-shell\u0000*"]).toBe("unknown"); + extraUpstreamAgents = []; + + // Corrupt-baselines rebuild with ONLY an unreadable extra directory (zero readable legacy + // slots) must still copy aside .corrupt and persist the agent-level unknown sentinel. + const onlyUnscannedDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-only-unscanned-", + }); + const onlyUnscannedTools = path.join(onlyUnscannedDir, "tools"); + const onlyUnscannedTool = path.join(onlyUnscannedTools, "chrome-headless-shell"); + const onlyUnscannedDummyFile = path.join(onlyUnscannedDir, "not-a-dir"); + const onlyUnscannedRegDir = path.join(onlyUnscannedDir, "acp-registry"); + const onlyUnscannedBaselines = path.join(onlyUnscannedRegDir, "legacy-baselines.json"); + yield* fileSystem.makeDirectory(onlyUnscannedTool, { recursive: true }); + yield* fileSystem.writeFileString(onlyUnscannedDummyFile, "x"); + yield* fileSystem.makeDirectory(onlyUnscannedRegDir, { recursive: true }); + yield* fileSystem.writeFileString(onlyUnscannedBaselines, "{only-unscanned"); + const onlyUnscannedFs: FileSystem.FileSystem = { + ...fileSystem, + readDirectory: (dirPath, options) => + dirPath === onlyUnscannedTool + ? fileSystem.readDirectory(onlyUnscannedDummyFile, options) + : fileSystem.readDirectory(dirPath, options), + }; + const onlyUnscannedResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: onlyUnscannedDir, + toolsDir: onlyUnscannedTools, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, onlyUnscannedFs)); + yield* onlyUnscannedResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(`${onlyUnscannedBaselines}.corrupt`)).toBe( + "{only-unscanned", + ); + expect(JSON.parse(yield* fileSystem.readFileString(onlyUnscannedBaselines))).toEqual({ + "chrome-headless-shell\u0000*": "unknown", + }); + + // Rolling back from C (2.0.0) to B (1.0.0) must install B instead of running legacy A as B. + upstream = binaryAgent("1.0.0", archiveBUrl); + yield* corruptResolver.invalidateIndex(); + yield* corruptResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const resolvedAfterRollback = yield* corruptResolver.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(resolvedAfterRollback.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // Same check on B -> B after restart with a corrupt baseline file. + const unrecoverableDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-baseline-unrecoverable-", + }); + const unrecoverableRegistryDir = `${unrecoverableDir}/acp-registry`; + const unrecoverableBaselinesPath = `${unrecoverableRegistryDir}/legacy-baselines.json`; + const unrecoverableLegacyExe = `${unrecoverableDir}/tools/example-agent/1.0.0/linux-x86_64/bin/example-agent`; + yield* fileSystem.makeDirectory(path.dirname(unrecoverableLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(unrecoverableLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* fileSystem.chmod(unrecoverableLegacyExe, 0o755); + yield* fileSystem.makeDirectory(unrecoverableRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + `${unrecoverableRegistryDir}/registry.json`, + makeRegistry(binaryAgent("1.0.0", archiveBUrl)), + ); + yield* fileSystem.writeFileString(unrecoverableBaselinesPath, "{corrupt"); + + upstream = binaryAgent("1.0.0", archiveBUrl); + const unrecoverableResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: unrecoverableDir, + toolsDir: `${unrecoverableDir}/tools`, + registryUrl, + }); + yield* unrecoverableResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* fileSystem.readFileString(`${unrecoverableBaselinesPath}.corrupt`)).toBe( + "{corrupt", + ); + const unknownBaselines = JSON.parse( + yield* fileSystem.readFileString(unrecoverableBaselinesPath), + ) as Record; + expect(unknownBaselines[exampleSlotKey]).toBe("unknown"); + const resolvedAfterCorruptRebuild = yield* unrecoverableResolver.resolve( + settings(), + "/workspace", + ); + expect(yield* fileSystem.readFileString(resolvedAfterCorruptRebuild.spawn.command)).toBe( + "#!/bin/sh\necho archive-b\n", + ); + + // Add another agent's baseline and launch-options sidecar entries, uninstall example-agent, + // and verify only example-agent is pruned from both stores. + rebuiltBaselines[otherSlotKey] = "other-baseline"; + yield* fileSystem.writeFileString(corruptBaselinesPath, JSON.stringify(rebuiltBaselines)); + const corruptSidecarPath = path.join(corruptRegistryDir, "binary-launch-options.json"); + const exampleSlotRoot = path.join( + corruptDir, + "tools", + "example-agent", + "1.0.0", + "linux-x86_64", + ); + const otherSlotRoot = path.join( + corruptDir, + "tools", + "other-agent", + "1.0.0", + "linux-x86_64", + ); + yield* fileSystem.writeFileString( + corruptSidecarPath, + JSON.stringify({ + [exampleSlotRoot]: { + version: "1.0.0", + archive: archiveBUrl, + cmd: "./bin/example-agent", + sha256: null, + args: ["--old"], + launchOptionsRevision: 1, + }, + [otherSlotRoot]: { + version: "1.0.0", + archive: archiveAUrl, + cmd: "./bin/other-agent", + sha256: null, + args: ["--keep"], + launchOptionsRevision: 1, + }, + }), + ); + expect(yield* corruptResolver.uninstallManagedBinary({ agentId: "example-agent" })).toEqual( + { + agentId: "example-agent", + removed: true, + }, + ); + const prunedBaselines = JSON.parse( + yield* fileSystem.readFileString(corruptBaselinesPath), + ) as Record; + expect(prunedBaselines[exampleSlotKey]).toBeUndefined(); + expect(prunedBaselines[otherSlotKey]).toBe("other-baseline"); + const prunedSidecar = JSON.parse( + yield* fileSystem.readFileString(corruptSidecarPath), + ) as Record; + expect(prunedSidecar[exampleSlotRoot]).toBeUndefined(); + expect(prunedSidecar[otherSlotRoot]).toBeDefined(); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + if (request.url === registryUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + upstreamEmpty + ? JSON.stringify({ version: "1.0.0", agents: [] }) + : extraUpstreamAgents.length > 0 + ? JSON.stringify({ + version: "1.0.0", + agents: [upstream, ...extraUpstreamAgents], + }) + : makeRegistry(upstream), + ), + ), + ); + } + if (countArchiveRequests) { + archiveRequestsDuringLockedSlot += 1; + } + const bytes = + request.url === archiveAUrl ? bytesA : request.url === archiveBUrl ? bytesB : bytesC; + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(bytes.buffer as ArrayBuffer)), + ); + }), + ), + ); + }, + ); + + it.effect( + "enforces post-retry removal, archive extraction timeout, and pre-promotion concurrent slot checks", + () => { + const archiveV1Url = "https://registry.test/v1.bin"; + const archiveV2AUrl = "https://registry.test/v2-a.bin"; + const archiveV2BUrl = "https://registry.test/v2-b.bin"; + const archiveTarUrl = "https://registry.test/v3.tar.gz"; + const archivePlainUrl = "https://registry.test/v3-plain.bin"; + const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho ok\n"); + const binaryAgent = (version: string, archive: string, sha256Hex?: string) => ({ + ...makeAgent({ + binary: { + "linux-x86_64": { + archive, + cmd: "./bin/example-agent", + ...(sha256Hex ? { sha256: sha256Hex } : {}), + }, + }, + }), + version, + }); + let upstreamAgents: ReadonlyArray = [ + binaryAgent("1.0.0", archiveV1Url), + ]; + let downloadGate: { + readonly url: string; + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + + // 1. Post-retry concurrent removal: initial A fails checksum_mismatch while the index + // advances to B, then recheck-retry B fails checksum_mismatch while the agent is removed -> + // resolve() rechecks after retry B and fails with agent_not_found instead of falling back. + const removalDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-post-retry-remove-", + }); + const removalResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: removalDir, + toolsDir: `${removalDir}/tools`, + registryUrl, + }); + const v1Resolved = yield* removalResolver.resolve(settings(), "/workspace"); + expect(v1Resolved.agent?.version).toBe("1.0.0"); + + upstreamAgents = [binaryAgent("2.0.0", archiveV2AUrl, "0".repeat(64))]; + yield* removalResolver.invalidateIndex(); + yield* removalResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const aGate = { + url: archiveV2AUrl, + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + const bGate = { + url: archiveV2BUrl, + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + downloadGate = aGate; + const resolveFiber = yield* removalResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(aGate.started); + + // Advance the index from A to B while A's download is in flight, then arm bGate. + upstreamAgents = [binaryAgent("2.0.0", archiveV2BUrl, "0".repeat(64))]; + yield* removalResolver.invalidateIndex(); + yield* removalResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + downloadGate = bGate; + yield* Deferred.succeed(aGate.release, undefined); + yield* Deferred.await(bGate.started); + + // Concurrently remove the agent while the recheck's own retry B download is in flight. + upstreamAgents = []; + yield* removalResolver.invalidateIndex(); + yield* removalResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* Deferred.succeed(bGate.release, undefined); + expect((yield* Fiber.join(resolveFiber)).reason).toBe("agent_not_found"); + + // 1b. Multi-pass recheck retry: A fails checksum -> moves to B -> B fails checksum -> moves + // to valid C -> resolve() retries through B to C and succeeds with C. + upstreamAgents = [binaryAgent("2.0.0", archiveV2AUrl, "0".repeat(64))]; + yield* removalResolver.invalidateIndex(); + yield* removalResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const aGate2 = { + url: archiveV2AUrl, + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + const bGate2 = { + url: archiveV2BUrl, + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + downloadGate = aGate2; + const multiRetryFiber = yield* removalResolver + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(aGate2.started); + upstreamAgents = [binaryAgent("2.0.0", archiveV2BUrl, "0".repeat(64))]; + yield* removalResolver.invalidateIndex(); + yield* removalResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + downloadGate = bGate2; + yield* Deferred.succeed(aGate2.release, undefined); + yield* Deferred.await(bGate2.started); + upstreamAgents = [binaryAgent("2.0.0", archivePlainUrl)]; + yield* removalResolver.invalidateIndex(); + yield* removalResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* Deferred.succeed(bGate2.release, undefined); + const multiRetried = yield* Fiber.join(multiRetryFiber); + expect(multiRetried.fallback).toBeUndefined(); + expect(multiRetried.agent?.version).toBe("2.0.0"); + + // 2. Both archive extraction and listing timeouts map to archive_invalid (falling back when + // a prior receipted version exists, and surfacing archive_invalid while releasing locks + // when none exists). + let tarStartedGate: Deferred.Deferred | null = null; + let hangTarStage: "list" | "extract" = "extract"; + const hangingTarSpawner = ChildProcessSpawner.make((command) => { + if ( + ChildProcess.isStandardCommand(command) && + (command.command === "tar" || command.command.endsWith("/tar")) + ) { + const firstArg = command.args[0]; + const isListing = typeof firstArg === "string" && firstArg.startsWith("-t"); + if (isListing && hangTarStage === "extract") { + return Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.make(new TextEncoder().encode("bin/example-agent\n")), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ); + } + const gate = tarStartedGate; + tarStartedGate = null; + return (gate === null ? Effect.void : Deferred.succeed(gate, undefined)).pipe( + Effect.as( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.never, + isRunning: Effect.succeed(true), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ), + ); + } + return realSpawner.spawn(command); + }); + const timeoutFallbackResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: removalDir, + toolsDir: `${removalDir}/tools`, + registryUrl, + }).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, hangingTarSpawner), + Effect.provideService(SpawnExecutableResolution, (command) => command), + ); + upstreamAgents = [binaryAgent("3.0.0", archiveTarUrl)]; + yield* timeoutFallbackResolver.invalidateIndex(); + yield* timeoutFallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + hangTarStage = "extract"; + tarStartedGate = yield* Deferred.make(); + const tarWithFallback = tarStartedGate; + const fallbackTimeoutFiber = yield* timeoutFallbackResolver + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(tarWithFallback); + yield* TestClock.adjust("5 minutes"); + const fallbackOnTimeout = yield* Fiber.join(fallbackTimeoutFiber); + expect(fallbackOnTimeout.fallback).toBe(true); + expect(fallbackOnTimeout.agent?.version).toBe("2.0.0"); + + const noFallbackDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-extract-timeout-", + }); + const noFallbackResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: noFallbackDir, + toolsDir: `${noFallbackDir}/tools`, + registryUrl, + }).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, hangingTarSpawner), + Effect.provideService(SpawnExecutableResolution, (command) => command), + ); + hangTarStage = "list"; + tarStartedGate = yield* Deferred.make(); + const tarWithoutFallback = tarStartedGate; + const noFallbackTimeoutFiber = yield* noFallbackResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(tarWithoutFallback); + yield* TestClock.adjust("5 minutes"); + expect((yield* Fiber.join(noFallbackTimeoutFiber)).reason).toBe("archive_invalid"); + + // Locks and permits are released cleanly after extraction timeout so a later install succeeds. + upstreamAgents = [binaryAgent("3.0.0", archivePlainUrl)]; + yield* noFallbackResolver.invalidateIndex(); + yield* noFallbackResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const recoveredAfterTimeout = yield* noFallbackResolver.resolve(settings(), "/workspace"); + expect(recoveredAfterTimeout.agent?.version).toBe("3.0.0"); + + // 3. Pre-promotion concurrentSlot recheck returns the sibling install without renaming again. + const concurrentDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-pre-promote-", + }); + upstreamAgents = [binaryAgent("1.2.3", archiveV1Url)]; + const baseSeedResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: concurrentDir, + toolsDir: `${concurrentDir}/tools`, + registryUrl, + }); + yield* baseSeedResolver.resolve(settings(), "/workspace"); + + upstreamAgents = [binaryAgent("1.2.3", archivePlainUrl)]; + let receiptGate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + const firstReceiptGate = receiptGate; + let renameToArtifactCount = 0; + const instrumentedFs: FileSystem.FileSystem = { + ...fileSystem, + writeFileString: (filePath, data, options) => { + if (receiptGate !== null && filePath.endsWith("/.t3-artifact.json")) { + const gate = receiptGate; + receiptGate = null; + return fileSystem.writeFileString(filePath, data, options).pipe( + Effect.tap(() => Deferred.succeed(gate.started, undefined)), + Effect.tap(() => Deferred.await(gate.release)), + ); + } + return fileSystem.writeFileString(filePath, data, options); + }, + rename: (oldPath, newPath) => { + if (/linux-x86_64-[0-9a-f]{12}$/u.test(newPath)) { + renameToArtifactCount += 1; + } + return fileSystem.rename(oldPath, newPath); + }, + }; + const installer1 = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: concurrentDir, + toolsDir: `${concurrentDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, instrumentedFs)); + const installer2 = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: concurrentDir, + toolsDir: `${concurrentDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, instrumentedFs)); + yield* installer1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* installer2.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + + const firstInstallFiber = yield* installer1 + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(firstReceiptGate.started); + // Age installer1's lock and advance the clock past the 5-minute stale threshold explicitly + // so this check is independent of earlier clock adjustments. + yield* fileSystem.utimes( + `${concurrentDir}/tools/example-agent/1.2.3/linux-x86_64.lock`, + 0, + 0, + ); + yield* TestClock.adjust("6 minutes"); + const secondResult = yield* installer2.resolve(settings(), "/workspace"); + expect(renameToArtifactCount).toBe(1); + + yield* Deferred.succeed(firstReceiptGate.release, undefined); + const firstResult = yield* Fiber.join(firstInstallFiber); + expect(firstResult.spawn.command).toBe(secondResult.spawn.command); + expect(renameToArtifactCount).toBe(1); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + if (request.url === registryUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(JSON.stringify({ version: "1.0.0", agents: upstreamAgents })), + ), + ); + } + const respond = Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(binaryBytes.buffer as ArrayBuffer)), + ); + if (downloadGate !== null && request.url === downloadGate.url) { + const gate = downloadGate; + downloadGate = null; + return Deferred.succeed(gate.started, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + Effect.andThen(respond), + ); + } + return respond; + }), + ), + ); + }, + ); + + it.effect( + "rejects reserved receipt command paths, ignores superseded broken primaries on inspect, persists launch options when receipt writes fail, and enforces interruptible token-owned locks", + () => { + const archiveAUrl = "https://registry.test/receipt-a.bin"; + const archiveBUrl = "https://registry.test/receipt-b.bin"; + const archiveFailUrl = "https://registry.test/receipt-fail.bin"; + const bytesA = new TextEncoder().encode("#!/bin/sh\necho receipt-a\n"); + const bytesB = new TextEncoder().encode("#!/bin/sh\necho receipt-b\n"); + const makeBinary = ( + version: string, + target: { + readonly archive: string; + readonly cmd: string; + readonly args?: ReadonlyArray; + readonly env?: Readonly>; + }, + ) => ({ + ...makeAgent({ binary: { "linux-x86_64": target } }), + version, + }); + let upstream = makeBinary("1.0.0", { archive: archiveAUrl, cmd: ".t3-artifact.json" }); + let extraUpstream: ReturnType | null = null; + + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + // Model POSIX mode bits in memory so Linux mode assertions work identically on Windows. + const modeOverrides = new Map(); + let failReceiptTempWrite = false; + let failSidecarWrite = false; + let failSidecarRead = false; + let failSidecarReadWhileLockedPath: string | null = null; + let corruptSidecarWhileLockedPath: string | null = null; + let failReceiptReadWhileLockedPath: string | null = null; + let injectedReceiptReadFailures = 0; + let receiptRenameCount = 0; + let onStatPath: { + readonly matchPath: string; + readonly onHit: () => void; + } | null = null; + const posixModeFs: FileSystem.FileSystem = { + ...fileSystem, + chmod: (filePath, mode) => + Effect.sync(() => { + modeOverrides.set(filePath, mode); + }).pipe(Effect.andThen(fileSystem.chmod(filePath, mode).pipe(Effect.ignore))), + stat: (filePath) => + fileSystem.stat(filePath).pipe( + Effect.tap(() => + Effect.sync(() => { + if (onStatPath !== null && filePath === onStatPath.matchPath) { + onStatPath.onHit(); + } + }), + ), + Effect.map((info) => { + const override = modeOverrides.get(filePath); + return override === undefined + ? info + : { ...info, mode: (info.mode & ~0o777) | override }; + }), + ), + readFileString: (filePath, encoding) => { + const base = path.basename(filePath); + if (base === "binary-launch-options.json") { + if (failSidecarRead) { + return fileSystem.readFileString(path.dirname(filePath), encoding); + } + if (corruptSidecarWhileLockedPath !== null) { + const lockPath = corruptSidecarWhileLockedPath; + return fileSystem.exists(lockPath).pipe( + Effect.orElseSucceed(() => false), + Effect.flatMap((locked) => + locked + ? Effect.succeed("{corrupt-under-lock") + : fileSystem.readFileString(filePath, encoding), + ), + ); + } + if (failSidecarReadWhileLockedPath !== null) { + const lockPath = failSidecarReadWhileLockedPath; + return fileSystem.exists(lockPath).pipe( + Effect.orElseSucceed(() => false), + Effect.flatMap((locked) => + locked + ? fileSystem.readFileString(path.dirname(filePath), encoding) + : fileSystem.readFileString(filePath, encoding), + ), + ); + } + } + if (base === ".t3-artifact.json" && failReceiptReadWhileLockedPath !== null) { + const lockPath = failReceiptReadWhileLockedPath; + return fileSystem.exists(lockPath).pipe( + Effect.orElseSucceed(() => false), + Effect.flatMap((locked) => + locked + ? Effect.sync(() => { + injectedReceiptReadFailures += 1; + }).pipe( + Effect.andThen(fileSystem.readFileString(path.dirname(filePath), encoding)), + ) + : fileSystem.readFileString(filePath, encoding), + ), + ); + } + return fileSystem.readFileString(filePath, encoding); + }, + writeFileString: (filePath, data, options) => + (failReceiptTempWrite && path.basename(filePath).startsWith(".t3-artifact.json.")) || + (failSidecarWrite && + path.basename(filePath).startsWith("binary-launch-options.json.") && + filePath.endsWith(".tmp")) + ? fileSystem.readFileString(path.dirname(filePath)).pipe(Effect.asVoid) + : fileSystem.writeFileString(filePath, data, options), + rename: (oldPath, newPath) => + Effect.sync(() => { + if (path.basename(newPath) === ".t3-artifact.json") { + receiptRenameCount += 1; + } + }).pipe(Effect.andThen(fileSystem.rename(oldPath, newPath))), + }; + + // 1. A raw binary declaring .t3-artifact.json as its command fails with archive_invalid + // instead of letting the receipt overwrite the staged executable. + const reservedDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-reserved-receipt-", + }); + const reservedResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: reservedDir, + toolsDir: `${reservedDir}/tools`, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const reservedError = yield* reservedResolver + .resolve(settings(), "/workspace") + .pipe(Effect.flip); + expect(reservedError.reason).toBe("archive_invalid"); + + // 2. Unchanged no-env binaries skip receipt rewrites; updating args/env syncs the receipt; + // failed receipt writes persist in binary-launch-options.json across restarts without + // letting stale sidecar entries shadow newer receipts or dropping other slots on read errors. + const noEnvDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-no-env-skip-", + }); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1"], + }); + const noEnvResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: noEnvDir, + toolsDir: path.join(noEnvDir, "tools"), + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* noEnvResolver.resolve(settings(), "/workspace"); + receiptRenameCount = 0; + yield* noEnvResolver.resolve(settings(), "/workspace"); + yield* noEnvResolver.resolve(settings(), "/workspace"); + expect(receiptRenameCount).toBe(0); + // After populating syncedLaunchOptionsBySlotRoot for a no-env binary, subsequent resolves + // with the same args and omitted env must hit the memory fast path without rewriting. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--v2"], + }); + yield* noEnvResolver.invalidateIndex(); + yield* noEnvResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* noEnvResolver.resolve(settings(), "/workspace"); + receiptRenameCount = 0; + yield* noEnvResolver.resolve(settings(), "/workspace"); + yield* noEnvResolver.resolve(settings(), "/workspace"); + expect(receiptRenameCount).toBe(0); + + const supersededDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-superseded-inspect-", + }); + const supersededToolsDir = path.join(supersededDir, "tools"); + const supersededSidecarPath = path.join( + supersededDir, + "acp-registry", + "binary-launch-options.json", + ); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1"], + env: { STAGE: "initial" }, + }); + const supersededResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const installedA = yield* supersededResolver.resolve(settings(), "/workspace"); + expect(installedA.spawn.args).toEqual(["--v1"]); + expect(installedA.spawn.env?.STAGE).toBe("initial"); + + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--updated"], + env: { STAGE: "updated" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const syncedA = yield* supersededResolver.resolve(settings(), "/workspace"); + expect(syncedA.spawn.command).toBe(installedA.spawn.command); + expect(syncedA.spawn.args).toEqual(["--v1", "--updated"]); + expect(syncedA.spawn.env?.STAGE).toBe("updated"); + + // Failed receipt write persists --sidecar; reverting back to the receipt's --updated in the + // SAME process must update/clear the sidecar so fallback does not resurrect --sidecar. + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--sidecar"], + env: { STAGE: "sidecar" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const sidecarSyncedA = yield* supersededResolver.resolve(settings(), "/workspace"); + expect(sidecarSyncedA.spawn.args).toEqual(["--v1", "--sidecar"]); + expect(sidecarSyncedA.spawn.env?.STAGE).toBe("sidecar"); + + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--updated"], + env: { STAGE: "updated" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const sameProcessRevertFallback = yield* supersededResolver.resolve( + settings(), + "/workspace", + ); + expect(sameProcessRevertFallback.fallback).toBe(true); + expect(sameProcessRevertFallback.spawn.args).toEqual(["--v1", "--updated"]); + expect(sameProcessRevertFallback.spawn.env?.STAGE).toBe("updated"); + + // Write --sidecar to the sidecar again, restart, and verify fallback restores --sidecar. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--sidecar"], + env: { STAGE: "sidecar" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + + // A transient read failure on binary-launch-options.json must leave existing sidecar + // entries intact instead of replacing the file with an empty/partial map. + const preserveSlotKey = path.join( + supersededToolsDir, + "other-agent", + "1.0.0", + "linux-x86_64", + ); + const sidecarBeforeIo = JSON.parse( + yield* fileSystem.readFileString(supersededSidecarPath), + ) as Record; + yield* fileSystem.writeFileString( + supersededSidecarPath, + JSON.stringify({ + ...sidecarBeforeIo, + [preserveSlotKey]: { + version: "1.0.0", + archive: archiveBUrl, + cmd: "./bin/other-agent", + sha256: null, + args: ["--preserve"], + launchOptionsRevision: 1, + }, + }), + ); + failReceiptTempWrite = true; + failSidecarRead = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--sidecar-io"], + env: { STAGE: "sidecar-io" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarRead = false; + const sidecarAfterIo = JSON.parse( + yield* fileSystem.readFileString(supersededSidecarPath), + ) as Record; + expect(sidecarAfterIo[preserveSlotKey]).toBeDefined(); + + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const restartedSuperseded = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* restartedSuperseded.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackA = yield* restartedSuperseded.resolve(settings(), "/workspace"); + expect(fallbackA.fallback).toBe(true); + expect(fallbackA.agent?.version).toBe("1.0.0"); + expect(fallbackA.spawn.args).toEqual(["--v1", "--sidecar"]); + expect(fallbackA.spawn.env?.STAGE).toBe("sidecar"); + + // After storage recovers, re-resolving the SAME --sidecar-io options on supersededResolver + // (which only held them in memory when both receipt and sidecar writes failed) must retry + // persistence so a fresh catalog restores --sidecar-io on fallback. + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--sidecar-io"], + env: { STAGE: "sidecar-io" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const recoveredIoCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* recoveredIoCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackRecoveredIo = yield* recoveredIoCatalog.resolve(settings(), "/workspace"); + expect(fallbackRecoveredIo.fallback).toBe(true); + expect(fallbackRecoveredIo.spawn.args).toEqual(["--v1", "--sidecar-io"]); + expect(fallbackRecoveredIo.spawn.env?.STAGE).toBe("sidecar-io"); + + // A second catalog writing a newer sidecar revision must win over catalog A's older + // in-memory cached launch options during fallback AND must invalidate catalog A's skip path. + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--cat-a"], + env: { STAGE: "cat-a" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--cat-b"], + env: { STAGE: "cat-b" }, + }); + yield* recoveredIoCatalog.invalidateIndex(); + yield* recoveredIoCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* recoveredIoCatalog.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackSeesCatB = yield* supersededResolver.resolve(settings(), "/workspace"); + expect(fallbackSeesCatB.fallback).toBe(true); + expect(fallbackSeesCatB.spawn.args).toEqual(["--v1", "--cat-b"]); + expect(fallbackSeesCatB.spawn.env?.STAGE).toBe("cat-b"); + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--cat-a"], + env: { STAGE: "cat-a" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* recoveredIoCatalog.invalidateIndex(); + yield* recoveredIoCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackSeesNewerCatA = yield* recoveredIoCatalog.resolve(settings(), "/workspace"); + expect(fallbackSeesNewerCatA.fallback).toBe(true); + expect(fallbackSeesNewerCatA.spawn.args).toEqual(["--v1", "--cat-a"]); + expect(fallbackSeesNewerCatA.spawn.env?.STAGE).toBe("cat-a"); + + // If the sidecar cache file disappears (e.g. cache directory cleared), resolving the + // same --cat-a options on supersededResolver must re-persist them instead of trusting memory. + yield* fileSystem.remove(supersededSidecarPath, { force: true }); + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--cat-a"], + env: { STAGE: "cat-a" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const afterCacheWipeCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* afterCacheWipeCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackAfterCacheWipe = yield* afterCacheWipeCatalog.resolve( + settings(), + "/workspace", + ); + expect(fallbackAfterCacheWipe.fallback).toBe(true); + expect(fallbackAfterCacheWipe.spawn.args).toEqual(["--v1", "--cat-a"]); + expect(fallbackAfterCacheWipe.spawn.env?.STAGE).toBe("cat-a"); + + // A concurrent higher RECEIPT revision written by another catalog must also invalidate + // supersededResolver's memory cache when upstream returns to --cat-a. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--receipt-cat-b"], + env: { STAGE: "receipt-cat-b" }, + }); + yield* recoveredIoCatalog.invalidateIndex(); + yield* recoveredIoCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* recoveredIoCatalog.resolve(settings(), "/workspace"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--cat-a"], + env: { STAGE: "cat-a" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const afterReceiptBumpCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* afterReceiptBumpCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackAfterReceiptBump = yield* afterReceiptBumpCatalog.resolve( + settings(), + "/workspace", + ); + expect(fallbackAfterReceiptBump.fallback).toBe(true); + expect(fallbackAfterReceiptBump.spawn.args).toEqual(["--v1", "--cat-a"]); + expect(fallbackAfterReceiptBump.spawn.env?.STAGE).toBe("cat-a"); + + // Restore --updated to the receipt before testing corrupt-sidecar repair on both the + // matching-receipt path and the failed-receipt-write path. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--updated"], + env: { STAGE: "updated" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + yield* fileSystem.writeFileString(supersededSidecarPath, "{corrupt-match"); + const repairOnMatchCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* repairOnMatchCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* repairOnMatchCatalog.resolve(settings(), "/workspace"); + expect(yield* fileSystem.readFileString(`${supersededSidecarPath}.corrupt`)).toBe( + "{corrupt-match", + ); + expect(JSON.parse(yield* fileSystem.readFileString(supersededSidecarPath))).toEqual({}); + + // A corrupt binary-launch-options.json is copied aside and repaired cleanly on write. + yield* fileSystem.writeFileString(supersededSidecarPath, "{corrupt-sidecar"); + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--repaired-sidecar"], + env: { STAGE: "repaired" }, + }); + yield* supersededResolver.invalidateIndex(); + yield* supersededResolver.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* supersededResolver.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + expect(yield* fileSystem.readFileString(`${supersededSidecarPath}.corrupt`)).toBe( + "{corrupt-sidecar", + ); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const repairedSidecarCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* repairedSidecarCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackRepairedSidecar = yield* repairedSidecarCatalog.resolve( + settings(), + "/workspace", + ); + expect(fallbackRepairedSidecar.fallback).toBe(true); + expect(fallbackRepairedSidecar.spawn.args).toEqual(["--v1", "--repaired-sidecar"]); + expect(fallbackRepairedSidecar.spawn.env?.STAGE).toBe("repaired"); + // Restore preserveSlotKey before the revert check below. + const repairedSidecarEntries = JSON.parse( + yield* fileSystem.readFileString(supersededSidecarPath), + ) as Record; + yield* fileSystem.writeFileString( + supersededSidecarPath, + JSON.stringify({ + ...repairedSidecarEntries, + [preserveSlotKey]: { + version: "1.0.0", + archive: archiveBUrl, + cmd: "./bin/other-agent", + sha256: null, + args: ["--preserve"], + launchOptionsRevision: 1, + }, + }), + ); + + // Reverting upstream back to the receipt's earlier args/env after restart prunes the + // sidecar and persists the new generation; verify with ANOTHER fresh catalog instance. + const exampleSlotRootSuperseded = path.join( + supersededToolsDir, + "example-agent", + "1.0.0", + path.basename(path.dirname(path.dirname(installedA.spawn.command))), + ); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--updated"], + env: { STAGE: "updated" }, + }); + yield* restartedSuperseded.invalidateIndex(); + yield* restartedSuperseded.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const revertedA = yield* restartedSuperseded.resolve(settings(), "/workspace"); + expect(revertedA.spawn.args).toEqual(["--v1", "--updated"]); + expect(revertedA.spawn.env?.STAGE).toBe("updated"); + const sidecarAfterRevert = JSON.parse( + yield* fileSystem.readFileString(supersededSidecarPath), + ) as Record; + expect(sidecarAfterRevert[exampleSlotRootSuperseded]).toBeUndefined(); + expect(sidecarAfterRevert[preserveSlotKey]).toBeDefined(); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const afterRevertCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* afterRevertCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackAfterRevert = yield* afterRevertCatalog.resolve(settings(), "/workspace"); + expect(fallbackAfterRevert.fallback).toBe(true); + expect(fallbackAfterRevert.spawn.args).toEqual(["--v1", "--updated"]); + expect(fallbackAfterRevert.spawn.env?.STAGE).toBe("updated"); + + // A newer receipt write followed by a failed sidecar prune must still win over the older + // unpruned sidecar entry after restart. + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--stale-sidecar"], + env: { STAGE: "stale-sidecar" }, + }); + yield* afterRevertCatalog.invalidateIndex(); + yield* afterRevertCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* afterRevertCatalog.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1", "--newer-receipt"], + env: { STAGE: "newer-receipt" }, + }); + yield* afterRevertCatalog.invalidateIndex(); + yield* afterRevertCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* afterRevertCatalog.resolve(settings(), "/workspace"); + failSidecarWrite = false; + // Confirm the stale sidecar entry is still present on disk while the receipt has higher rev. + const unprunedSidecar = JSON.parse( + yield* fileSystem.readFileString(supersededSidecarPath), + ) as Record }>; + expect(unprunedSidecar[exampleSlotRootSuperseded]?.args).toEqual([ + "--v1", + "--stale-sidecar", + ]); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const newerReceiptCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: supersededDir, + toolsDir: supersededToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* newerReceiptCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackNewerReceipt = yield* newerReceiptCatalog.resolve(settings(), "/workspace"); + expect(fallbackNewerReceipt.fallback).toBe(true); + expect(fallbackNewerReceipt.spawn.args).toEqual(["--v1", "--newer-receipt"]); + expect(fallbackNewerReceipt.spawn.env?.STAGE).toBe("newer-receipt"); + + // Uninstalling clears in-memory launch options too so reinstalling uses the new receipt. + expect( + yield* afterRevertCatalog.uninstallManagedBinary({ agentId: "example-agent" }), + ).toEqual({ agentId: "example-agent", removed: true }); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--fresh-after-uninstall"], + }); + yield* afterRevertCatalog.invalidateIndex(); + yield* afterRevertCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const reinstalledA = yield* afterRevertCatalog.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* afterRevertCatalog.invalidateIndex(); + yield* afterRevertCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackAfterReinstall = yield* afterRevertCatalog.resolve(settings(), "/workspace"); + expect(fallbackAfterReinstall.fallback).toBe(true); + expect(fallbackAfterReinstall.spawn.args).toEqual(["--fresh-after-uninstall"]); + + // Reinstalling a broken slot in place must supersede/prune stale in-memory and sidecar + // launch options at that slot root so fallback uses the fresh install's options both + // in-process and after restart. + const inPlaceDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-inplace-reinstall-", + }); + const inPlaceToolsDir = path.join(inPlaceDir, "tools"); + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", + args: ["--b1"], + }); + const inPlaceCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: inPlaceDir, + toolsDir: inPlaceToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* inPlaceCatalog.resolve(settings(), "/workspace"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a1"], + }); + yield* inPlaceCatalog.invalidateIndex(); + yield* inPlaceCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const inPlaceSlotA = yield* inPlaceCatalog.resolve(settings(), "/workspace"); + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a2"], + }); + yield* inPlaceCatalog.invalidateIndex(); + yield* inPlaceCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* inPlaceCatalog.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + // Break slot A's executable, then resolve A with new args --a3 while sidecar reads fail + // so it reinstalls in place without being able to read or prune binary-launch-options.json; + // the fresh installId must still beat the old sidecar/memory --a2 entry in-process & restart. + yield* fileSystem.remove(inPlaceSlotA.spawn.command, { force: true }); + failSidecarRead = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a3"], + }); + yield* inPlaceCatalog.invalidateIndex(); + yield* inPlaceCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const reinstalledInPlace = yield* inPlaceCatalog.resolve(settings(), "/workspace"); + failSidecarRead = false; + expect(reinstalledInPlace.spawn.command).toBe(inPlaceSlotA.spawn.command); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* inPlaceCatalog.invalidateIndex(); + yield* inPlaceCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const inProcessFallbackA3 = yield* inPlaceCatalog.resolve(settings(), "/workspace"); + expect(inProcessFallbackA3.fallback).toBe(true); + expect(inProcessFallbackA3.spawn.args).toEqual(["--a3"]); + const restartedInPlaceCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: inPlaceDir, + toolsDir: inPlaceToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* restartedInPlaceCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const restartedFallbackA3 = yield* restartedInPlaceCatalog.resolve( + settings(), + "/workspace", + ); + expect(restartedFallbackA3.fallback).toBe(true); + expect(restartedFallbackA3.spawn.args).toEqual(["--a3"]); + + // Reinstalling a different artifact at the same primary path via another catalog must not + // let catalog A's cached memory entry for the old artifact skip updating the new receipt. + const swapPrimaryDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-swap-primary-", + }); + const swapPrimaryToolsDir = path.join(swapPrimaryDir, "tools"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--v1"], + }); + const swapCatA = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: swapPrimaryDir, + toolsDir: swapPrimaryToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const swapCatB = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: swapPrimaryDir, + toolsDir: swapPrimaryToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* swapCatA.resolve(settings(), "/workspace"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--shared-opt"], + }); + yield* swapCatA.invalidateIndex(); + yield* swapCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* swapCatA.resolve(settings(), "/workspace"); + // Catalog B uninstalls artifact A and installs artifact B with --other-opt at the same primary path. + yield* swapCatB.uninstallManagedBinary({ agentId: "example-agent" }); + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", + args: ["--other-opt"], + }); + yield* swapCatB.invalidateIndex(); + yield* swapCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* swapCatB.resolve(settings(), "/workspace"); + // Catalog A now resolves artifact B with --shared-opt (matching its stale memory entry for A). + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", + args: ["--shared-opt"], + }); + yield* swapCatA.invalidateIndex(); + yield* swapCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* swapCatA.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const swapVerifyCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: swapPrimaryDir, + toolsDir: swapPrimaryToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* swapVerifyCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const swapFallback = yield* swapVerifyCatalog.resolve(settings(), "/workspace"); + expect(swapFallback.fallback).toBe(true); + expect(swapFallback.spawn.args).toEqual(["--shared-opt"]); + + // Concurrent launch-option syncs on the same slot serialize revision allocation under the + // sidecar lock so a receipt write (rev 1) followed by a sidecar write gets rev 2 and wins, + // fallback reads the sidecar before receipts so concurrent receipt+prune never restores an + // older receipt, and uninstall prunes the sidecar before releasing the agent permit. + const coordDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-coord-sync-", + }); + const coordToolsDir = path.join(coordDir, "tools"); + const coordSidecarPath = path.join(coordDir, "acp-registry", "binary-launch-options.json"); + const coordSidecarLockPath = `${coordSidecarPath}.lock`; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--init"], + }); + const coordSeed = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coordDir, + toolsDir: coordToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const coordInitial = yield* coordSeed.resolve(settings(), "/workspace"); + const coordSlotRoot = path.join( + coordToolsDir, + "example-agent", + "1.0.0", + path.basename(path.dirname(path.dirname(coordInitial.spawn.command))), + ); + const coordReceiptPath = path.join(coordSlotRoot, ".t3-artifact.json"); + + // (a) Catalog 1 pauses during its rev-1 receipt write while Catalog 2 starts with --c2 + // (whose receipt write fails); Catalog 2 waits on the sidecar lock, reads rev-1 receipt, + // and writes sidecar rev 2 (--c2) so fallback selects --c2 over rev-1 --c1. + const cat1WriteStarted = yield* Deferred.make(); + const releaseCat1Write = yield* Deferred.make(); + const cat2LockWaited = yield* Deferred.make(); + let gateCat1Receipt = true; + const coordCat1Fs: FileSystem.FileSystem = { + ...posixModeFs, + writeFileString: (filePath, data, options) => { + if (gateCat1Receipt && path.basename(filePath).startsWith(".t3-artifact.json.")) { + gateCat1Receipt = false; + return Deferred.succeed(cat1WriteStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseCat1Write)), + Effect.andThen(posixModeFs.writeFileString(filePath, data, options)), + ); + } + return posixModeFs.writeFileString(filePath, data, options); + }, + }; + const coordCat2Fs: FileSystem.FileSystem = { + ...posixModeFs, + stat: (filePath) => + posixModeFs + .stat(filePath) + .pipe( + Effect.tap(() => + filePath === coordSidecarLockPath + ? Deferred.succeed(cat2LockWaited, undefined).pipe(Effect.asVoid) + : Effect.void, + ), + ), + writeFileString: (filePath, data, options) => + path.basename(filePath).startsWith(".t3-artifact.json.") + ? fileSystem.readFileString(path.dirname(filePath)).pipe(Effect.asVoid) + : posixModeFs.writeFileString(filePath, data, options), + }; + const coordCat1 = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coordDir, + toolsDir: coordToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, coordCat1Fs)); + const coordCat2 = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coordDir, + toolsDir: coordToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, coordCat2Fs)); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--c1"], + }); + yield* coordCat1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--c2"], + }); + yield* coordCat2.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const cat1Fiber = yield* coordCat1 + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(cat1WriteStarted); + const cat2Fiber = yield* coordCat2 + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(cat2LockWaited); + yield* Deferred.succeed(releaseCat1Write, undefined); + yield* Fiber.join(cat1Fiber); + yield* TestClock.adjust("100 millis"); + yield* Fiber.join(cat2Fiber); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const coordVerify = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coordDir, + toolsDir: coordToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* coordVerify.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const coordFallbackC2 = yield* coordVerify.resolve(settings(), "/workspace"); + expect(coordFallbackC2.fallback).toBe(true); + expect(coordFallbackC2.spawn.args).toEqual(["--c2"]); + + // (b) Fallback reads the sidecar BEFORE receipts: pausing fallback right before it reads + // .t3-artifact.json while another writer publishes rev-3 --c3 to the receipt and prunes + // the sidecar must still yield --c3 (never the older rev-1 receipt). + const fbReceiptGateStarted = yield* Deferred.make(); + const releaseFbReceiptGate = yield* Deferred.make(); + let fbSawSidecar = false; + let gateFbReceipt = true; + const coordFallbackFs: FileSystem.FileSystem = { + ...posixModeFs, + readFileString: (filePath, encoding) => { + if (filePath === coordSidecarPath) { + fbSawSidecar = true; + } + if (gateFbReceipt && fbSawSidecar && filePath === coordReceiptPath) { + gateFbReceipt = false; + return Deferred.succeed(fbReceiptGateStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseFbReceiptGate)), + Effect.andThen(posixModeFs.readFileString(filePath, encoding)), + ); + } + return posixModeFs.readFileString(filePath, encoding); + }, + }; + const coordFallbackReader = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coordDir, + toolsDir: coordToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, coordFallbackFs)); + yield* coordFallbackReader.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fbReaderFiber = yield* coordFallbackReader + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(fbReceiptGateStarted); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--c3"], + }); + yield* coordSeed.invalidateIndex(); + yield* coordSeed.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* coordSeed.resolve(settings(), "/workspace"); + yield* Deferred.succeed(releaseFbReceiptGate, undefined); + const coordFallbackC3 = yield* Fiber.join(fbReaderFiber); + expect(coordFallbackC3.fallback).toBe(true); + expect(coordFallbackC3.spawn.args).toEqual(["--c3"]); + + // (c) Uninstall finishes sidecar cleanup before releasing the agent permit so a concurrent + // reinstall cannot enter install I/O or write a sidecar entry before cleanup runs. + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--pre-uninstall"], + }); + yield* coordSeed.invalidateIndex(); + yield* coordSeed.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* coordSeed.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + const uninstallBeforeLockStarted = yield* Deferred.make(); + const releaseUninstallBeforeLock = yield* Deferred.make(); + let gateUninstallExists = true; + let reinstallEnteredInstall = false; + const markReinstallToolsTouch = (filePath: string) => { + if (!gateUninstallExists && filePath.startsWith(coordToolsDir)) { + reinstallEnteredInstall = true; + } + }; + const coordUninstallFs: FileSystem.FileSystem = { + ...posixModeFs, + exists: (filePath) => { + // Pause uninstall BEFORE it takes the sidecar lock so an early permit release would + // let reinstall enter installBinary while cleanup is paused. + if (gateUninstallExists && filePath === coordSidecarPath) { + gateUninstallExists = false; + return Deferred.succeed(uninstallBeforeLockStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseUninstallBeforeLock)), + Effect.andThen(posixModeFs.exists(filePath)), + ); + } + markReinstallToolsTouch(filePath); + return posixModeFs.exists(filePath); + }, + readFileString: (filePath, encoding) => + Effect.sync(() => markReinstallToolsTouch(filePath)).pipe( + Effect.andThen(posixModeFs.readFileString(filePath, encoding)), + ), + readDirectory: (dirPath, options) => + Effect.sync(() => markReinstallToolsTouch(dirPath)).pipe( + Effect.andThen(posixModeFs.readDirectory(dirPath, options)), + ), + stat: (filePath) => + Effect.sync(() => markReinstallToolsTouch(filePath)).pipe( + Effect.andThen(posixModeFs.stat(filePath)), + ), + makeDirectory: (dirPath, options) => + Effect.sync(() => markReinstallToolsTouch(dirPath)).pipe( + Effect.andThen(posixModeFs.makeDirectory(dirPath, options)), + ), + }; + const uninstallSchedulerDispatcher = new Scheduler.MixedScheduler("async").makeDispatcher(); + const uninstallScheduler: Scheduler.Scheduler = { + executionMode: "async", + shouldYield: () => false, + makeDispatcher: () => uninstallSchedulerDispatcher, + }; + const coordPermitCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: coordDir, + toolsDir: coordToolsDir, + registryUrl, + }).pipe( + Effect.provideService(FileSystem.FileSystem, coordUninstallFs), + Effect.provideService(Scheduler.Scheduler, uninstallScheduler), + ); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--after-uninstall"], + }); + yield* coordPermitCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const uninstallFiber = yield* coordPermitCatalog + .uninstallManagedBinary({ agentId: "example-agent" }) + .pipe( + Effect.provideService(Scheduler.Scheduler, uninstallScheduler), + Effect.forkScoped({ startImmediately: true }), + ); + yield* Deferred.await(uninstallBeforeLockStarted); + // Start reinstall on the same catalog while uninstall is paused BEFORE its sidecar lock; + // flush the scheduler and assert reinstall has NOT entered installBinary (blocked on permit). + const reinstallFiber = yield* coordPermitCatalog + .resolve(settings(), "/workspace") + .pipe( + Effect.provideService(Scheduler.Scheduler, uninstallScheduler), + Effect.forkScoped({ startImmediately: true }), + ); + uninstallSchedulerDispatcher.flush(); + expect(reinstallEnteredInstall).toBe(false); + yield* Deferred.succeed(releaseUninstallBeforeLock, undefined); + expect(yield* Fiber.join(uninstallFiber)).toEqual({ + agentId: "example-agent", + removed: true, + }); + const reinstalledAfterPermit = yield* Fiber.join(reinstallFiber); + expect(reinstallEnteredInstall).toBe(true); + expect(reinstalledAfterPermit.spawn.args).toEqual(["--after-uninstall"]); + + // (d) Sidecar io_error neither rewrites matching receipts nor allocates below unreadable + // sidecars; pending options stay separate from committed revisions; lock timeouts + // observe fast-path sidecar revisions for in-process fallback. + const edgeSyncDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-edge-sync-", + }); + const edgeSyncToolsDir = path.join(edgeSyncDir, "tools"); + const edgeSyncSidecarPath = path.join( + edgeSyncDir, + "acp-registry", + "binary-launch-options.json", + ); + const edgeSyncSidecarLockPath = `${edgeSyncSidecarPath}.lock`; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--edge-init"], + }); + const edgeCatA = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: edgeSyncDir, + toolsDir: edgeSyncToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const edgeCatB = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: edgeSyncDir, + toolsDir: edgeSyncToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* edgeCatA.resolve(settings(), "/workspace"); + // Write rev 1 and rev 2 to sidecar while receipt stays at rev 0 (--edge-init). + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--edge-sidecar-1"], + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatA.resolve(settings(), "/workspace"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--edge-sidecar-2"], + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatA.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + // 1) Matching receipt + sidecar io_error must NOT rewrite the receipt on every resolve. + failSidecarRead = true; + receiptRenameCount = 0; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--edge-init"], + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatB.resolve(settings(), "/workspace"); + yield* edgeCatB.resolve(settings(), "/workspace"); + expect(receiptRenameCount).toBe(0); + // 1b) Reverting to matching receipt (--edge-init rev 0) after observing newer sidecar rev 2 + // on the fast path, then hitting io_error while locked, keeps --edge-init pending. + failSidecarRead = false; + failSidecarReadWhileLockedPath = edgeSyncSidecarLockPath; + yield* edgeCatB.resolve(settings(), "/workspace"); + failSidecarReadWhileLockedPath = null; + expect(receiptRenameCount).toBe(0); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* edgeCatB.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--edge-init", + ]); + // 2) Different target + sidecar io_error does not allocate below sidecar rev 2 and keeps + // launch usable via pending options while the sidecar is STILL unreadable. + failSidecarRead = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--edge-after-io"], + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatB.resolve(settings(), "/workspace"); + expect(receiptRenameCount).toBe(0); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* edgeCatB.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--edge-after-io", + ]); + // Once reads recover, retrying the same target allocates rev 3 (> sidecar rev 2) cleanly. + failSidecarRead = false; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--edge-after-io"], + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatB.resolve(settings(), "/workspace"); + expect(receiptRenameCount).toBe(1); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + const edgeVerifyAfterIo = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: edgeSyncDir, + toolsDir: edgeSyncToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* edgeVerifyAfterIo.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* edgeVerifyAfterIo.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--edge-after-io", + ]); + // 3) Repeated failed writes do not inflate committed revisions, and a transient locked + // receipt reread error keeps pending --fail-2 until another catalog commits rev 4. + failReceiptTempWrite = true; + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--fail-1"], + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatA.resolve(settings(), "/workspace"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--fail-2"], + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatA.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = false; + // Transient locked receipt reread failure must preserve pending --fail-2. + injectedReceiptReadFailures = 0; + failReceiptReadWhileLockedPath = edgeSyncSidecarLockPath; + yield* edgeCatA.resolve(settings(), "/workspace"); + failReceiptReadWhileLockedPath = null; + expect(injectedReceiptReadFailures).toBe(1); + // Before catalog B commits a newer rev, edgeCatA's in-process fallback uses pending --fail-2. + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* edgeCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--fail-2", + ]); + // Now catalog B commits rev 4 (--commit-b); edgeCatA's fallback must prefer committed --commit-b. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--commit-b"], + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatB.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* edgeCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--commit-b", + ]); + // 4) Lock timeout preserves pending base rev 7; retrying with unreadable sidecars keeps + // base rev 7 so unchanged rev 7 does not override pending, while rev 8 still wins. + failReceiptTempWrite = true; + for (const arg of ["--s5", "--s6", "--s7"]) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatB.resolve(settings(), "/workspace"); + } + failReceiptTempWrite = false; + const lockTimeoutCat = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: edgeSyncDir, + toolsDir: edgeSyncToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* fileSystem.writeFileString(edgeSyncSidecarLockPath, "external-holder"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--lock-c"], + }); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + let nextLockStat = yield* Deferred.make(); + onStatPath = { + matchPath: edgeSyncSidecarLockPath, + onHit: () => { + Deferred.doneUnsafe(nextLockStat, Exit.void); + }, + }; + const lockTimeoutFiber = yield* lockTimeoutCat + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + for (let step = 0; step < 20; step += 1) { + yield* Deferred.await(nextLockStat); + nextLockStat = yield* Deferred.make(); + yield* TestClock.adjust("100 millis"); + } + onStatPath = null; + yield* Fiber.join(lockTimeoutFiber); + yield* fileSystem.remove(edgeSyncSidecarLockPath, { force: true }); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--lock-c", + ]); + // Retry with unreadable sidecar keeps baseDurableRevision=7 (not downgraded to receipt rev 4) + // across sidecar io_error, locked receipt reread failure, and a second lock timeout. + failSidecarRead = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--lock-c-retry"], + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* lockTimeoutCat.resolve(settings(), "/workspace"); + failSidecarRead = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--lock-c-retry", + ]); + // Locked receipt reread error while sidecar is unreadable also preserves base rev 7. + injectedReceiptReadFailures = 0; + failSidecarRead = true; + failReceiptReadWhileLockedPath = edgeSyncSidecarLockPath; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--lock-c-reread"], + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* lockTimeoutCat.resolve(settings(), "/workspace"); + failReceiptReadWhileLockedPath = null; + failSidecarRead = false; + expect(injectedReceiptReadFailures).toBe(1); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--lock-c-reread", + ]); + // A second lock timeout while sidecar is unreadable also preserves base rev 7. + failSidecarRead = true; + yield* fileSystem.writeFileString(edgeSyncSidecarLockPath, "external-holder-2"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--lock-c-timeout2"], + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + let nextLockStat2 = yield* Deferred.make(); + onStatPath = { + matchPath: edgeSyncSidecarLockPath, + onHit: () => { + Deferred.doneUnsafe(nextLockStat2, Exit.void); + }, + }; + const lockTimeoutFiber2 = yield* lockTimeoutCat + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + for (let step = 0; step < 20; step += 1) { + yield* Deferred.await(nextLockStat2); + nextLockStat2 = yield* Deferred.make(); + yield* TestClock.adjust("100 millis"); + } + onStatPath = null; + yield* Fiber.join(lockTimeoutFiber2); + yield* fileSystem.remove(edgeSyncSidecarLockPath, { force: true }); + failSidecarRead = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--lock-c-timeout2", + ]); + // Corrupt sidecar repaired by a fresh catalog (via sidecar OR receipt OR matching receipt) + // must outrank older higher-base pending entries via launchOptionsRecoveryId / receipt rev. + const savedSidecarBeforeCorrupt = yield* fileSystem.readFileString(edgeSyncSidecarPath); + const makeEdgePendingCat = () => + AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: edgeSyncDir, + toolsDir: edgeSyncToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const staleSidecarCat = yield* makeEdgePendingCat(); + const staleSidecarNormalCat = yield* makeEdgePendingCat(); + const staleReceiptCat = yield* makeEdgePendingCat(); + const freshRepairCat = yield* makeEdgePendingCat(); + failReceiptTempWrite = true; + failSidecarWrite = true; + for (const [cat, arg] of [ + [staleSidecarCat, "--stale-sidecar-pending"], + [staleSidecarNormalCat, "--stale-sidecar-normal"], + [staleReceiptCat, "--stale-receipt-pending"], + ] as const) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* cat.invalidateIndex(); + yield* cat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* cat.resolve(settings(), "/workspace"); + } + failReceiptTempWrite = false; + failSidecarWrite = false; + // (i) Sidecar repair (rev 5 < pending base 7) and subsequent normal write (rev 6 < 7). + yield* fileSystem.writeFileString(edgeSyncSidecarPath, "{corrupt-sidecar"); + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--fresh-b-sidecar-repair"], + }); + yield* freshRepairCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* freshRepairCat.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* staleSidecarCat.invalidateIndex(); + yield* staleSidecarCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* staleSidecarCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--fresh-b-sidecar-repair", + ]); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--fresh-b-sidecar-rev6"], + }); + yield* freshRepairCat.invalidateIndex(); + yield* freshRepairCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* freshRepairCat.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* staleSidecarNormalCat.invalidateIndex(); + yield* staleSidecarNormalCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* staleSidecarNormalCat.resolve(settings(), "/workspace")).spawn.args).toEqual( + ["--fresh-b-sidecar-rev6"], + ); + // (ii) Receipt repair (rev 5 < pending base 7) and matching-receipt repair on corrupt file. + yield* fileSystem.writeFileString(edgeSyncSidecarPath, "{corrupt-sidecar"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--fresh-b-receipt-repair"], + }); + yield* freshRepairCat.invalidateIndex(); + yield* freshRepairCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const freshReceiptResolved = yield* freshRepairCat.resolve(settings(), "/workspace"); + const edgeReceiptPath = path.join( + path.dirname(path.dirname(freshReceiptResolved.spawn.command)), + ".t3-artifact.json", + ); + const afterReceiptRepair = JSON.parse( + yield* fileSystem.readFileString(edgeReceiptPath), + ) as { readonly launchOptionsRevision?: number }; + expect(afterReceiptRepair.launchOptionsRevision).toBe(5); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* staleReceiptCat.invalidateIndex(); + yield* staleReceiptCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* staleReceiptCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--fresh-b-receipt-repair", + ]); + yield* fileSystem.writeFileString(edgeSyncSidecarPath, "{corrupt-sidecar-match"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--fresh-b-receipt-repair"], + }); + yield* freshRepairCat.invalidateIndex(); + yield* freshRepairCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* freshRepairCat.resolve(settings(), "/workspace"); + const afterMatchRepair = JSON.parse(yield* fileSystem.readFileString(edgeReceiptPath)) as { + readonly launchOptionsRevision?: number; + }; + expect(afterMatchRepair.launchOptionsRevision).toBe(6); + // Corrupt sidecar while lockTimeoutCat holds pending base rev 7 must allocate rev 8 (> 7). + yield* fileSystem.writeFileString(edgeSyncSidecarPath, "{corrupt-sidecar"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--after-corrupt-rev8"], + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* lockTimeoutCat.resolve(settings(), "/workspace"); + const afterCorruptReceipt = JSON.parse( + yield* fileSystem.readFileString(edgeReceiptPath), + ) as { readonly launchOptionsRevision?: number }; + expect(afterCorruptReceipt.launchOptionsRevision).toBe(8); + // Restore sidecar at rev 7 (lower than rev 8) and confirm rev 8 receipt wins cleanly. + yield* fileSystem.writeFileString(edgeSyncSidecarPath, savedSidecarBeforeCorrupt); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--after-corrupt-rev8", + ]); + // A newer committed rev 9 (--commit-8) still outranks everything cleanly. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--commit-8"], + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatB.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* lockTimeoutCat.invalidateIndex(); + yield* lockTimeoutCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* lockTimeoutCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--commit-8", + ]); + // Fresh catalog (no pending entry) that observes sidecar rev 10 on the fast path, then + // encounters a corrupt sidecar under the lock, allocates rev 11 (> observedDiskRev 10). + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--sidecar-rev10"], + }); + yield* edgeCatB.invalidateIndex(); + yield* edgeCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + const observedRevCat = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: edgeSyncDir, + toolsDir: edgeSyncToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--commit-8"], + }); + yield* observedRevCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + corruptSidecarWhileLockedPath = edgeSyncSidecarLockPath; + yield* observedRevCat.resolve(settings(), "/workspace"); + corruptSidecarWhileLockedPath = null; + const afterObservedRev = JSON.parse(yield* fileSystem.readFileString(edgeReceiptPath)) as { + readonly launchOptionsRevision?: number; + }; + expect(afterObservedRev.launchOptionsRevision).toBe(11); + + // (e) Recovery-ID edge cases: unreadable/corrupt sidecar fallback keeps pending options + // after a sidecar repair, unreadable-sidecar retries preserve the recovery ID, another + // slot's or uninstall's corrupt repair invalidates stale pending options, and receipt + // advances never pair stale pre-repair revisions with post-repair observations. + const recoveryEdgeDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-recovery-edge-", + }); + const recoveryEdgeToolsDir = path.join(recoveryEdgeDir, "tools"); + const recoveryEdgeSidecarPath = path.join( + recoveryEdgeDir, + "acp-registry", + "binary-launch-options.json", + ); + const recoveryEdgeLockPath = `${recoveryEdgeSidecarPath}.lock`; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--init"], + }); + const recCatA = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: recoveryEdgeDir, + toolsDir: recoveryEdgeToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* recCatA.resolve(settings(), "/workspace"); + // 1) Corrupt sidecar repaired via sidecar gets a recovery ID; pending options recorded over + // it must survive unreadable or corrupt sidecar fallbacks instead of reverting to --init. + failReceiptTempWrite = true; + yield* fileSystem.writeFileString(recoveryEdgeSidecarPath, "{corrupt-rec"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--repaired"], + }); + yield* recCatA.invalidateIndex(); + yield* recCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* recCatA.resolve(settings(), "/workspace"); + const savedRepairedSidecar = yield* fileSystem.readFileString(recoveryEdgeSidecarPath); + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--pending"], + }); + yield* recCatA.invalidateIndex(); + yield* recCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* recCatA.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* recCatA.invalidateIndex(); + yield* recCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* recCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--pending", + ]); + failSidecarRead = true; + expect((yield* recCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--pending", + ]); + failSidecarRead = false; + yield* fileSystem.writeFileString(recoveryEdgeSidecarPath, "{corrupt-after-pending"); + expect((yield* recCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--pending", + ]); + // 2) Fast-path observation of a repaired sidecar's recovery ID survives locked io_error, + // subsequent both-unreadable io_error retries, and locked receipt reread errors; a + // corrupt+matching-receipt sync when both writes fail clears stale pending options. + yield* fileSystem.writeFileString(recoveryEdgeSidecarPath, savedRepairedSidecar); + const ioChainCat = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: recoveryEdgeDir, + toolsDir: recoveryEdgeToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--fast-path-io"], + }); + yield* ioChainCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + failSidecarReadWhileLockedPath = recoveryEdgeLockPath; + yield* ioChainCat.resolve(settings(), "/workspace"); + failSidecarReadWhileLockedPath = null; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* ioChainCat.invalidateIndex(); + yield* ioChainCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* ioChainCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--fast-path-io", + ]); + failSidecarRead = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--both-io-retry"], + }); + yield* ioChainCat.invalidateIndex(); + yield* ioChainCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* ioChainCat.resolve(settings(), "/workspace"); + injectedReceiptReadFailures = 0; + failReceiptReadWhileLockedPath = recoveryEdgeLockPath; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--reread-io-retry"], + }); + yield* ioChainCat.invalidateIndex(); + yield* ioChainCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* ioChainCat.resolve(settings(), "/workspace"); + failReceiptReadWhileLockedPath = null; + failSidecarRead = false; + expect(injectedReceiptReadFailures).toBe(1); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* ioChainCat.invalidateIndex(); + yield* ioChainCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* ioChainCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--reread-io-retry", + ]); + yield* fileSystem.writeFileString(recoveryEdgeSidecarPath, "{corrupt-match-both-fail"); + failReceiptTempWrite = true; + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--init"], + }); + yield* ioChainCat.invalidateIndex(); + yield* ioChainCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* ioChainCat.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* ioChainCat.invalidateIndex(); + yield* ioChainCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* ioChainCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--init", + ]); + + // 3) Corrupt sidecar repaired by a DIFFERENT agent (or uninstall) wipes example-agent's + // entry; catalog B's rev-1 write gets a fresh recovery ID and beats catalog A's pending. + const otherSlotDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-other-slot-repair-", + }); + const otherSlotToolsDir = path.join(otherSlotDir, "tools"); + const otherSlotSidecarPath = path.join( + otherSlotDir, + "acp-registry", + "binary-launch-options.json", + ); + const otherSettings = () => settings({ agentId: "other-agent" }); + const makeOtherBinary = (version: string, args?: ReadonlyArray) => ({ + ...makeBinary(version, { + archive: archiveBUrl, + cmd: "./bin/other-agent", + ...(args ? { args } : {}), + }), + id: "other-agent", + name: "Other Agent", + }); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--init"], + }); + extraUpstream = makeOtherBinary("1.0.0", ["--other-init"]); + const otherCatA = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: otherSlotDir, + toolsDir: otherSlotToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const otherCatB = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: otherSlotDir, + toolsDir: otherSlotToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + yield* otherCatA.resolve(settings(), "/workspace"); + yield* otherCatA.resolve(otherSettings(), "/workspace"); + failReceiptTempWrite = true; + for (const arg of ["--a1", "--a2", "--a3"]) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* otherCatA.invalidateIndex(); + yield* otherCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* otherCatA.resolve(settings(), "/workspace"); + } + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a-pending"], + }); + yield* otherCatA.invalidateIndex(); + yield* otherCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* otherCatA.resolve(settings(), "/workspace"); + failSidecarWrite = false; + // Sidecar corrupts; catalog B repairs it while syncing other-agent, wiping example-agent. + yield* fileSystem.writeFileString(otherSlotSidecarPath, "{corrupt-other-slot"); + extraUpstream = makeOtherBinary("1.0.0", ["--other-repair"]); + yield* otherCatB.invalidateIndex(); + yield* otherCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* otherCatB.resolve(otherSettings(), "/workspace"); + expect(yield* fileSystem.readFileString(`${otherSlotSidecarPath}.corrupt`)).toBe( + "{corrupt-other-slot", + ); + const repairedByOtherEntries = JSON.parse( + yield* fileSystem.readFileString(otherSlotSidecarPath), + ) as Record }>; + expect( + Object.keys(repairedByOtherEntries).every((key) => key.includes("other-agent")), + ).toBe(true); + expect(Object.values(repairedByOtherEntries).map((entry) => entry.args)).toEqual([ + ["--other-repair"], + ]); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--b-newer"], + }); + yield* otherCatB.invalidateIndex(); + yield* otherCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* otherCatB.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* otherCatA.invalidateIndex(); + yield* otherCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* otherCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--b-newer", + ]); + // Same check when uninstall of other-agent repairs the corrupt sidecar. + for (const arg of ["--a4", "--a5"]) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* otherCatA.invalidateIndex(); + yield* otherCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* otherCatA.resolve(settings(), "/workspace"); + } + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a-pending2"], + }); + yield* otherCatA.invalidateIndex(); + yield* otherCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* otherCatA.resolve(settings(), "/workspace"); + failSidecarWrite = false; + yield* fileSystem.writeFileString(otherSlotSidecarPath, "{corrupt-uninstall-repair"); + yield* otherCatB.uninstallManagedBinary({ agentId: "other-agent" }); + expect(yield* fileSystem.readFileString(`${otherSlotSidecarPath}.corrupt`)).toBe( + "{corrupt-uninstall-repair", + ); + expect(JSON.parse(yield* fileSystem.readFileString(otherSlotSidecarPath))).toEqual({}); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--b-after-uninstall"], + }); + yield* otherCatB.invalidateIndex(); + yield* otherCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* otherCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* otherCatA.invalidateIndex(); + yield* otherCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* otherCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--b-after-uninstall", + ]); + extraUpstream = null; + + // 4) When another catalog advances the receipt after a corrupt sidecar and writes a newer + // sidecar, an unreadable-sidecar retry (and locked receipt reread) in catalog A must + // NOT carry stale pre-repair baseDurableRevision; same-chain newer sidecar writes beat + // and retire pending options, and a receipt advance resets lockedPendingBase cleanly. + const obsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-obs-pair-", + }); + const obsToolsDir = path.join(obsDir, "tools"); + const obsSidecarPath = path.join(obsDir, "acp-registry", "binary-launch-options.json"); + const obsLockPath = `${obsSidecarPath}.lock`; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--init"], + }); + const makeObsCat = () => + AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: obsDir, + toolsDir: obsToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const obsCatA = yield* makeObsCat(); + const obsCatA2 = yield* makeObsCat(); + const obsCatB = yield* makeObsCat(); + yield* obsCatA.resolve(settings(), "/workspace"); + // Same-chain newer sidecar write beats and retires catalog A's pending entry (so a later + // unreadable sidecar cannot resurrect the retired pending entry). + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--same-chain-1"], + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatA.resolve(settings(), "/workspace"); + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a-stale-same-chain"], + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatA.resolve(settings(), "/workspace"); + failSidecarWrite = false; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--b-newer-same-chain"], + }); + yield* obsCatB.invalidateIndex(); + yield* obsCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* obsCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--b-newer-same-chain", + ]); + failSidecarRead = true; + expect((yield* obsCatA.resolve(settings(), "/workspace")).spawn.args).toEqual(["--init"]); + failSidecarRead = false; + // Receipt advance pruning the sidecar resets lockedPendingBase when both writes later fail. + failReceiptTempWrite = true; + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a-before-r-prune"], + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatA.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = false; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--r1"], + }); + yield* obsCatB.invalidateIndex(); + yield* obsCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = true; + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a-after-r-prune"], + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatA.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* obsCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--a-after-r-prune", + ]); + // Build sidecar revs on top of receipt rev 3, record pending on BOTH obsCatA and obsCatA2, + // then let B repair receipt + write a lower-rev sidecar; test io_error and receipt reread. + failReceiptTempWrite = true; + for (const arg of ["--s2", "--s3", "--s4"]) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatA.resolve(settings(), "/workspace"); + } + failSidecarWrite = true; + for (const [cat, arg] of [ + [obsCatA, "--a-old"], + [obsCatA2, "--a-old-2"], + ] as const) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* cat.invalidateIndex(); + yield* cat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* cat.resolve(settings(), "/workspace"); + } + failReceiptTempWrite = false; + failSidecarWrite = false; + // Corrupt sidecar; B repairs receipt to rev 4 and writes sidecar rev 5 (< A's old base 6). + yield* fileSystem.writeFileString(obsSidecarPath, "{corrupt-obs"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--b-r2"], + }); + yield* obsCatB.invalidateIndex(); + yield* obsCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--b-s3"], + }); + yield* obsCatB.invalidateIndex(); + yield* obsCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + // (i) Locked sidecar io_error path on obsCatA: verify pending is recorded while unreadable, + // then superseded by --b-s3 once sidecar reads recover. + failSidecarRead = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a-io-after-r2"], + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatA.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* obsCatA.invalidateIndex(); + yield* obsCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* obsCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--a-io-after-r2", + ]); + failSidecarRead = false; + expect((yield* obsCatA.resolve(settings(), "/workspace")).spawn.args).toEqual(["--b-s3"]); + // (ii) Locked receipt-reread path on obsCatA2: verify fault count, pending recording while + // unreadable, and --b-s3 once sidecar reads recover. + failSidecarRead = true; + injectedReceiptReadFailures = 0; + failReceiptReadWhileLockedPath = obsLockPath; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--a-reread-after-r2"], + }); + yield* obsCatA2.invalidateIndex(); + yield* obsCatA2.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* obsCatA2.resolve(settings(), "/workspace"); + failReceiptReadWhileLockedPath = null; + expect(injectedReceiptReadFailures).toBe(1); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* obsCatA2.invalidateIndex(); + yield* obsCatA2.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* obsCatA2.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--a-reread-after-r2", + ]); + failSidecarRead = false; + expect((yield* obsCatA2.resolve(settings(), "/workspace")).spawn.args).toEqual(["--b-s3"]); + + // (f) Cross-chain sidecar repair: fallback retires old-chain pending on recovery-ID + // mismatch, and retries on the new chain (both locked write failure and fast-path ok + + // locked io_error) adopt the new chain's revision and recovery ID without old-chain base. + const xcDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-cross-chain-", + }); + const xcToolsDir = path.join(xcDir, "tools"); + const xcSidecarPath = path.join(xcDir, "acp-registry", "binary-launch-options.json"); + const xcLockPath = `${xcSidecarPath}.lock`; + const makeXcCat = () => + AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: xcDir, + toolsDir: xcToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const xcCatB = yield* makeXcCat(); + const xcRetireCat = yield* makeXcCat(); + const xcLockedCat = yield* makeXcCat(); + const xcUnreadableCat = yield* makeXcCat(); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--xc-init"], + }); + yield* xcCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = true; + for (const arg of ["--xc-y1", "--xc-y2", "--xc-y3", "--xc-y4"]) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* xcCatB.invalidateIndex(); + yield* xcCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* xcCatB.resolve(settings(), "/workspace"); + } + failSidecarWrite = true; + for (const [cat, arg] of [ + [xcRetireCat, "--xc-stale-retire"], + [xcLockedCat, "--xc-stale-locked"], + [xcUnreadableCat, "--xc-stale-unreadable"], + ] as const) { + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: [arg], + }); + yield* cat.invalidateIndex(); + yield* cat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* cat.resolve(settings(), "/workspace"); + } + failSidecarWrite = false; + // Prove old-chain pending options are active on all three catalogs while chain Y is readable. + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, cmd: "./bin/example-agent", - }, - }, - }); - const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho example\n"); - return Effect.gen(function* () { - const downloadStarted = yield* Deferred.make(); - const releaseDownload = yield* Deferred.make(); - return yield* Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-uninstall-race-", }); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, + for (const [cat, arg] of [ + [xcRetireCat, "--xc-stale-retire"], + [xcLockedCat, "--xc-stale-locked"], + [xcUnreadableCat, "--xc-stale-unreadable"], + ] as const) { + yield* cat.invalidateIndex(); + yield* cat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* cat.resolve(settings(), "/workspace")).spawn.args).toEqual([arg]); + } + // Corrupt sidecar and repair into chain Z at rev 1 (< old chain Y base rev 4). + yield* fileSystem.writeFileString(xcSidecarPath, "{corrupt-xc"); + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--xc-b-z1"], + }); + yield* xcCatB.invalidateIndex(); + yield* xcCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* xcCatB.resolve(settings(), "/workspace"); + // Retire-chain variant: recovery-ID mismatch retires stale pending so unreadable fallback + // cannot resurrect --xc-stale-retire. + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* xcRetireCat.invalidateIndex(); + yield* xcRetireCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* xcRetireCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--xc-b-z1", + ]); + failSidecarRead = true; + expect((yield* xcRetireCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--xc-init", + ]); + failSidecarRead = false; + // Locked-write-failure and fast-path-ok/locked-io_error retries adopt chain Z (rev 1, Z). + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--xc-a-locked-on-z"], + }); + yield* xcLockedCat.invalidateIndex(); + yield* xcLockedCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* xcLockedCat.resolve(settings(), "/workspace"); + failSidecarWrite = false; + failSidecarReadWhileLockedPath = xcLockPath; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--xc-a-unreadable-on-z"], + }); + yield* xcUnreadableCat.invalidateIndex(); + yield* xcUnreadableCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* xcUnreadableCat.resolve(settings(), "/workspace"); + failSidecarReadWhileLockedPath = null; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* xcLockedCat.invalidateIndex(); + yield* xcLockedCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* xcLockedCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--xc-a-locked-on-z", + ]); + yield* xcUnreadableCat.invalidateIndex(); + yield* xcUnreadableCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* xcUnreadableCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--xc-a-unreadable-on-z", + ]); + // B writes chain Z rev 2 (< old chain Y rev 4) -> beats both catalogs' rev-1 pending entries. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--xc-b-z2"], + }); + yield* xcCatB.invalidateIndex(); + yield* xcCatB.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* xcCatB.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", + }); + yield* xcLockedCat.invalidateIndex(); + yield* xcLockedCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* xcLockedCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--xc-b-z2", + ]); + yield* xcUnreadableCat.invalidateIndex(); + yield* xcUnreadableCat.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* xcUnreadableCat.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--xc-b-z2", + ]); + // Restore upstream to --commit-8 before step 5 below. + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--commit-8"], + }); + // 5) Fast-path hasMatchingPending gating: reverting to matching receipt --commit-8 clears + // earlier pending options instead of short-circuiting and leaving them active. + failReceiptTempWrite = true; + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--pending-stale"], + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatA.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = false; + upstream = makeBinary("1.0.0", { + archive: archiveAUrl, + cmd: "./bin/example-agent", + args: ["--commit-8"], + }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* edgeCatA.resolve(settings(), "/workspace"); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", }); + yield* edgeCatA.invalidateIndex(); + yield* edgeCatA.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* edgeCatA.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--commit-8", + ]); - const prepareFiber = yield* resolver - .prepare({ agentId: agent.id }) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(downloadStarted); - const uninstallFiber = yield* resolver - .uninstallManagedBinary({ agentId: agent.id }) - .pipe(Effect.forkChild({ startImmediately: true })); + // 3. A superseded primary executable that lost execute permission must not fail inspect() + // when the registry selects a different same-version artifact. + yield* posixModeFs.chmod(reinstalledA.spawn.command, 0o644); + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", + }); + yield* afterRevertCatalog.invalidateIndex(); + yield* afterRevertCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect(yield* afterRevertCatalog.inspect(settings())).toMatchObject({ + status: "ready", + version: "1.0.0", + }); + const installedB = yield* afterRevertCatalog.resolve(settings(), "/workspace"); + expect(installedB.spawn.command).not.toBe(reinstalledA.spawn.command); + expect(yield* fileSystem.readFileString(installedB.spawn.command)).toBe( + "#!/bin/sh\necho receipt-b\n", + ); - expect(uninstallFiber.pollUnsafe()).toBeUndefined(); - yield* Deferred.succeed(releaseDownload, undefined); + // 4. Waiting on a busy install lock is interruptible during sleep instead of blocking 30s. + const lockDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-lock-interrupt-", + }); + const versionDir = path.join(lockDir, "tools", "example-agent", "1.0.0"); + yield* fileSystem.makeDirectory(versionDir, { recursive: true }); + const lockFile = path.join(versionDir, "linux-x86_64.lock"); + yield* fileSystem.writeFileString(lockFile, "other-holder-token"); + const lockResolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: lockDir, + toolsDir: path.join(lockDir, "tools"), + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, posixModeFs)); + const lockFirstStat = yield* Deferred.make(); + const lockSecondStat = yield* Deferred.make(); + let lockStatHits = 0; + onStatPath = { + matchPath: lockFile, + onHit: () => { + lockStatHits += 1; + if (lockStatHits === 1) { + Deferred.doneUnsafe(lockFirstStat, Exit.void); + } else if (lockStatHits === 2) { + Deferred.doneUnsafe(lockSecondStat, Exit.void); + } + }, + }; + const waitingPrepare = yield* lockResolver + .prepare({ agentId: "example-agent" }) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(lockFirstStat); + yield* TestClock.adjust("100 millis"); + yield* Deferred.await(lockSecondStat); + onStatPath = null; + expect(waitingPrepare.pollUnsafe()).toBeUndefined(); + yield* Fiber.interrupt(waitingPrepare); + // Interrupting while waiting must leave the other holder's lock intact. + expect(yield* fileSystem.readFileString(lockFile)).toBe("other-holder-token"); - expect(yield* Fiber.join(prepareFiber)).toMatchObject({ prepared: true }); - expect(yield* Fiber.join(uninstallFiber)).toEqual({ - agentId: agent.id, - removed: false, + // 5. A stale lock holder neither overwrites a newer holder's baselines or launch-options + // sidecar nor deletes the newer holder's lock file on release (for both refresh & uninstall). + const fenceDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-baseline-fence-", + }); + const fenceRegistryDir = path.join(fenceDir, "acp-registry"); + const fenceRegistryPath = path.join(fenceRegistryDir, "registry.json"); + const fenceBaselinesPath = path.join(fenceRegistryDir, "legacy-baselines.json"); + const fenceLockPath = `${fenceBaselinesPath}.lock`; + const fenceSidecarPath = path.join(fenceRegistryDir, "binary-launch-options.json"); + const fenceSidecarLockPath = `${fenceSidecarPath}.lock`; + const fenceToolsDir = path.join(fenceDir, "tools"); + const fenceLegacyExe = path.join( + fenceToolsDir, + "example-agent", + "1.0.0", + "linux-x86_64", + "bin", + "example-agent", + ); + yield* fileSystem.makeDirectory(path.dirname(fenceLegacyExe), { recursive: true }); + yield* fileSystem.writeFileString(fenceLegacyExe, "#!/bin/sh\necho legacy-a\n"); + yield* posixModeFs.chmod(fenceLegacyExe, 0o755); + yield* fileSystem.makeDirectory(fenceRegistryDir, { recursive: true }); + yield* fileSystem.writeFileString( + fenceRegistryPath, + makeRegistry(makeBinary("1.0.0", { archive: archiveAUrl, cmd: "./bin/example-agent" })), + ); + const holder1Entered = yield* Deferred.make(); + const releaseHolder1 = yield* Deferred.make(); + let gatedHolder1 = true; + let baselinesReadCount = 0; + let sidecarFenceGate: { + readonly entered: Deferred.Deferred; + readonly release: Deferred.Deferred; + readonly requireLocked?: boolean; + } | null = null; + let uninstallFenceGate: { + readonly entered: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + const fencedFs: FileSystem.FileSystem = { + ...posixModeFs, + readFileString: (filePath, encoding) => { + if (gatedHolder1 && filePath === fenceBaselinesPath) { + baselinesReadCount += 1; + if (baselinesReadCount === 2) { + gatedHolder1 = false; + return Deferred.succeed(holder1Entered, undefined).pipe( + Effect.andThen(Deferred.await(releaseHolder1)), + Effect.andThen(posixModeFs.readFileString(filePath, encoding)), + ); + } + } + if (uninstallFenceGate !== null && filePath === fenceBaselinesPath) { + const gate = uninstallFenceGate; + uninstallFenceGate = null; + return Deferred.succeed(gate.entered, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + Effect.andThen(posixModeFs.readFileString(filePath, encoding)), + ); + } + if (sidecarFenceGate !== null && filePath === fenceSidecarPath) { + const gate = sidecarFenceGate; + if (gate.requireLocked === true) { + return fileSystem.exists(fenceSidecarLockPath).pipe( + Effect.orElseSucceed(() => false), + Effect.flatMap((locked) => { + if (!locked || sidecarFenceGate !== gate) { + return posixModeFs.readFileString(filePath, encoding); + } + sidecarFenceGate = null; + return Deferred.succeed(gate.entered, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + Effect.andThen(posixModeFs.readFileString(filePath, encoding)), + ); + }), + ); + } + sidecarFenceGate = null; + return Deferred.succeed(gate.entered, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + Effect.andThen(posixModeFs.readFileString(filePath, encoding)), + ); + } + return posixModeFs.readFileString(filePath, encoding); + }, + }; + upstream = makeBinary("1.0.0", { archive: archiveBUrl, cmd: "./bin/example-agent" }); + const holder1 = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: fenceDir, + toolsDir: fenceToolsDir, + registryUrl, + }).pipe(Effect.provideService(FileSystem.FileSystem, fencedFs)); + const holder1Refresh = yield* holder1 + .refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(holder1Entered); + // Simulate another holder taking over the stale lock and writing its own baseline map. + yield* fileSystem.writeFileString(fenceLockPath, "holder-2-token"); + yield* fileSystem.writeFileString( + fenceBaselinesPath, + JSON.stringify({ "keep-agent\u00001.0.0\u0000linux-x86_64": "holder-2-value" }), + ); + yield* Deferred.succeed(releaseHolder1, undefined); + yield* Fiber.join(holder1Refresh); + expect(yield* fileSystem.readFileString(fenceLockPath)).toBe("holder-2-token"); + expect(JSON.parse(yield* fileSystem.readFileString(fenceBaselinesPath))).toEqual({ + "keep-agent\u00001.0.0\u0000linux-x86_64": "holder-2-value", }); - const agentRoot = `${cacheDir}/tools/${agent.id}`; - expect(yield* fileSystem.exists(agentRoot)).toBe(true); - const hostSettings = yield* TestProviderHost.TestProviderHostSettings; - const instanceId = ProviderInstanceId.make("registry-reference"); - yield* hostSettings.set({ - ...DEFAULT_SERVER_SETTINGS, - providerInstances: { - [instanceId]: { - driver: ProviderDriverKind.make("acpRegistry"), - displayName: "Registry reference", - enabled: true, - config: { agentId: agent.id }, + // Sidecar lock-ownership fence: losing the lock leaves holder-2 intact while recording + // pending options in memory, and reverting to the matching receipt clears stale pending + // options even if the prune loses the lock. + yield* fileSystem.remove(fenceLockPath, { force: true }); + const fenceInstalledB = yield* holder1.resolve(settings(), "/workspace"); + const fenceSlotRoot = path.dirname(path.dirname(fenceInstalledB.spawn.command)); + failReceiptTempWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", + args: ["--fenced-sidecar"], + }); + yield* holder1.invalidateIndex(); + yield* holder1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const sidecarHolder1Entered = yield* Deferred.make(); + const releaseSidecarHolder1 = yield* Deferred.make(); + sidecarFenceGate = { entered: sidecarHolder1Entered, release: releaseSidecarHolder1 }; + const fencedSidecarResolve = yield* holder1 + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(sidecarHolder1Entered); + yield* fileSystem.writeFileString(fenceSidecarLockPath, "sidecar-holder-2"); + yield* fileSystem.writeFileString( + fenceSidecarPath, + JSON.stringify({ + "keep-slot": { + version: "1.0.0", + archive: archiveAUrl, + cmd: "./bin/keep", + sha256: null, + args: ["--holder-2"], + launchOptionsRevision: 1, }, - }, + }), + ); + yield* Deferred.succeed(releaseSidecarHolder1, undefined); + yield* Fiber.join(fencedSidecarResolve); + failReceiptTempWrite = false; + expect(yield* fileSystem.readFileString(fenceSidecarLockPath)).toBe("sidecar-holder-2"); + expect( + Object.keys(JSON.parse(yield* fileSystem.readFileString(fenceSidecarPath)) as object), + ).toEqual(["keep-slot"]); + // Verify lock-lost resolve recorded pending --fenced-sidecar for in-process fallback. + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", }); - expect(yield* resolver.uninstallManagedBinary({ agentId: agent.id })).toEqual({ - agentId: agent.id, - removed: false, + yield* holder1.invalidateIndex(); + yield* holder1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* holder1.resolve(settings(), "/workspace")).spawn.args).toEqual([ + "--fenced-sidecar", + ]); + // Reverting to the receipt's no-args target clears stale pending options even on lock loss + // (for both stale rev-0 sidecar entries and corrupt sidecar files). + yield* fileSystem.remove(fenceSidecarLockPath, { force: true }); + yield* fileSystem.writeFileString( + fenceSidecarPath, + JSON.stringify({ + [fenceSlotRoot]: { + version: "1.0.0", + archive: archiveBUrl, + cmd: "./bin/example-agent", + sha256: null, + args: ["--stale-rev0"], + launchOptionsRevision: 0, + }, + }), + ); + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", }); - yield* hostSettings.set(DEFAULT_SERVER_SETTINGS); - expect(yield* resolver.uninstallManagedBinary({ agentId: agent.id })).toEqual({ - agentId: agent.id, - removed: true, + yield* holder1.invalidateIndex(); + yield* holder1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const revertEntered = yield* Deferred.make(); + const releaseRevert = yield* Deferred.make(); + sidecarFenceGate = { + entered: revertEntered, + release: releaseRevert, + requireLocked: true, + }; + const fencedRevertResolve = yield* holder1 + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(revertEntered); + yield* fileSystem.writeFileString(fenceSidecarLockPath, "sidecar-holder-3"); + yield* Deferred.succeed(releaseRevert, undefined); + yield* Fiber.join(fencedRevertResolve); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", }); - expect(yield* resolver.uninstallManagedBinary({ agentId: agent.id })).toEqual({ - agentId: agent.id, - removed: false, + yield* holder1.invalidateIndex(); + yield* holder1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* holder1.resolve(settings(), "/workspace")).spawn.args).toEqual([]); + // Same lock-lost revert check on a corrupt sidecar file. + yield* fileSystem.remove(fenceSidecarLockPath, { force: true }); + failReceiptTempWrite = true; + failSidecarWrite = true; + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", + args: ["--fenced-before-corrupt"], }); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => { - if (request.url === registryUrl) { - return Effect.succeed( - HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent))), - ); - } - return Deferred.succeed(downloadStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseDownload)), - Effect.as( - HttpClientResponse.fromWeb( - request, - new Response(binaryBytes.buffer as ArrayBuffer), - ), - ), - ); - }), - ), - ); - }); - }); - - it.effect("resolves an installed agent while another agent's download is still running", () => { - const slowArchiveUrl = "https://registry.test/slow-agent.bin"; - const agent = makeAgent({ - binary: { "linux-x86_64": { archive: archiveUrl, cmd: "./bin/example-agent" } }, - }); - const slowAgent = { - ...agent, - distribution: { - binary: { "linux-x86_64": { archive: slowArchiveUrl, cmd: "./bin/slow-agent" } }, - }, - id: "slow-agent", - name: "Slow Agent", - }; - const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho example\n"); - return Effect.gen(function* () { - const downloadStarted = yield* Deferred.make(); - const releaseDownload = yield* Deferred.make(); - return yield* Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-parallel-install-", + yield* holder1.invalidateIndex(); + yield* holder1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* holder1.resolve(settings(), "/workspace"); + failReceiptTempWrite = false; + failSidecarWrite = false; + yield* fileSystem.writeFileString(fenceSidecarPath, "{corrupt-fence"); + upstream = makeBinary("1.0.0", { + archive: archiveBUrl, + cmd: "./bin/example-agent", }); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, + yield* holder1.invalidateIndex(); + yield* holder1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const corruptRevertEntered = yield* Deferred.make(); + const releaseCorruptRevert = yield* Deferred.make(); + sidecarFenceGate = { + entered: corruptRevertEntered, + release: releaseCorruptRevert, + requireLocked: true, + }; + const fencedCorruptRevert = yield* holder1 + .resolve(settings(), "/workspace") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(corruptRevertEntered); + yield* fileSystem.writeFileString(fenceSidecarLockPath, "sidecar-holder-4"); + yield* Deferred.succeed(releaseCorruptRevert, undefined); + yield* Fiber.join(fencedCorruptRevert); + upstream = makeBinary("2.0.0", { + archive: archiveFailUrl, + cmd: "./bin/example-agent", }); + yield* holder1.invalidateIndex(); + yield* holder1.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + expect((yield* holder1.resolve(settings(), "/workspace")).spawn.args).toEqual([]); - yield* resolver.resolve(settings(), "/workspace"); - - const prepareFiber = yield* resolver - .prepare({ agentId: slowAgent.id }) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(downloadStarted); - - const resolved = yield* resolver.resolve(settings(), "/workspace"); - expect(resolved.spawn.command).toContain( - "/tools/example-agent/1.2.3/linux-x86_64/bin/example-agent", + // Uninstall baselines prune lock-ownership fence: losing the lock leaves holder-2 intact. + yield* fileSystem.remove(fenceSidecarLockPath, { force: true }); + yield* fileSystem.writeFileString( + fenceBaselinesPath, + JSON.stringify({ + "example-agent\u00001.0.0\u0000linux-x86_64": "stale-value", + "keep-agent\u00001.0.0\u0000linux-x86_64": "holder-2-value", + }), ); - expect(prepareFiber.pollUnsafe()).toBeUndefined(); - - yield* Deferred.succeed(releaseDownload, undefined); - expect(yield* Fiber.join(prepareFiber)).toMatchObject({ prepared: true }); + const uninstallEntered = yield* Deferred.make(); + const releaseUninstall = yield* Deferred.make(); + uninstallFenceGate = { entered: uninstallEntered, release: releaseUninstall }; + const fencedUninstall = yield* holder1 + .uninstallManagedBinary({ agentId: "example-agent" }) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(uninstallEntered); + yield* fileSystem.writeFileString(fenceLockPath, "uninstall-holder-2"); + yield* fileSystem.writeFileString( + fenceBaselinesPath, + JSON.stringify({ + "example-agent\u00001.0.0\u0000linux-x86_64": "holder-2-new-value", + "keep-agent\u00001.0.0\u0000linux-x86_64": "holder-2-value", + }), + ); + yield* Deferred.succeed(releaseUninstall, undefined); + yield* Fiber.join(fencedUninstall); + expect(yield* fileSystem.readFileString(fenceLockPath)).toBe("uninstall-holder-2"); + expect(JSON.parse(yield* fileSystem.readFileString(fenceBaselinesPath))).toEqual({ + "example-agent\u00001.0.0\u0000linux-x86_64": "holder-2-new-value", + "keep-agent\u00001.0.0\u0000linux-x86_64": "holder-2-value", + }); }).pipe( Effect.scoped, Effect.provide( @@ -2120,72 +7662,28 @@ describe("AcpRegistrySupport", () => { return Effect.succeed( HttpClientResponse.fromWeb( request, - new Response(JSON.stringify({ version: "1.0.0", agents: [slowAgent, agent] })), + new Response( + extraUpstream === null + ? makeRegistry(upstream) + : JSON.stringify({ version: "1.0.0", agents: [upstream, extraUpstream] }), + ), ), ); } - const response = HttpClientResponse.fromWeb( - request, - new Response(binaryBytes.buffer as ArrayBuffer), - ); - if (request.url !== slowArchiveUrl) return Effect.succeed(response); - return Deferred.succeed(downloadStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseDownload)), - Effect.as(response), + if (request.url === archiveFailUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("unavailable", { status: 503 })), + ); + } + const bytes = request.url === archiveAUrl ? bytesA : bytesB; + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(bytes.buffer as ArrayBuffer)), ); }), ), ); - }); - }); - - it.effect("reserves a prepared binary until a configured instance inspects it", () => { - const agent = makeAgent({ - binary: { - "linux-x86_64": { - archive: archiveUrl, - cmd: "./bin/example-agent", - }, - }, - }); - const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho example\n"); - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-uninstall-reservation-", - }); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir, - toolsDir: `${cacheDir}/tools`, - registryUrl, - }); - - yield* resolver.prepare({ agentId: agent.id }); - expect(yield* resolver.uninstallManagedBinary({ agentId: agent.id })).toEqual({ - agentId: agent.id, - removed: false, - }); - expect(yield* resolver.inspect(settings())).toMatchObject({ status: "ready" }); - expect(yield* resolver.uninstallManagedBinary({ agentId: agent.id })).toEqual({ - agentId: agent.id, - removed: true, - }); - }).pipe( - Effect.scoped, - Effect.provide( - layerResolver((request) => - Effect.succeed( - HttpClientResponse.fromWeb( - request, - request.url === registryUrl - ? new Response(makeRegistry(agent)) - : new Response(binaryBytes.buffer as ArrayBuffer), - ), - ), - ), - ), - ); - }); + }, + ); }); describe("acpRegistryManagedBinaryDirectories", () => { diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 26d58fb4ea9ad..7ee088cfeb899 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -26,11 +26,13 @@ import * as Duration from "effect/Duration"; import * as Digest from "effect/crypto/Digest"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; +import * as Equal from "effect/Equal"; import * as Hex from "effect/encoding/Hex"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Result from "effect/Result"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; import * as PlatformError from "effect/PlatformError"; import * as Ref from "effect/Ref"; @@ -66,6 +68,7 @@ const REGISTRY_REQUEST_TIMEOUT = "30 seconds"; // Searches reuse an index fetched this recently; prepare always fetches the latest. const REGISTRY_SEARCH_MAX_AGE_MS = 5 * 60 * 1_000; const ARCHIVE_REQUEST_TIMEOUT = "20 minutes"; +const ARCHIVE_EXTRACT_TIMEOUT = "5 minutes"; const PACKAGE_INSTALL_TIMEOUT = "20 minutes"; const PACKAGE_QUERY_TIMEOUT = "30 seconds"; @@ -207,9 +210,23 @@ const decodeBoundedAgentId = Schema.decodeUnknownEffect(BoundedAgentId); export const AcpRegistryErrorReason = AcpRegistryOperationErrorReason; export type AcpRegistryErrorReason = typeof AcpRegistryErrorReason.Type; +export const AcpRegistryFetchStage = Schema.Literals([ + "invalid_url", + "http_request", + "request_timeout", + "response_read", + "response_timeout", + "response_too_large", + "invalid_utf8", + "invalid_json", + "invalid_index", +]); +export type AcpRegistryFetchStage = typeof AcpRegistryFetchStage.Type; + export class AcpRegistryError extends Schema.TaggedError()("AcpRegistryError", { reason: AcpRegistryErrorReason, detail: Schema.String, + stage: Schema.optional(AcpRegistryFetchStage), cause: Schema.optional(Schema.Defect()), }) { override get message(): string { @@ -380,6 +397,8 @@ export const acpRegistryManagedBinaryDirectories = Effect.fn("acpRegistryManaged } if (target === undefined) return Array.from(new Set(directories)); + const agentDirectories = (yield* listDirectories(installsDirectory)).toSorted(); + if (agentDirectories.length === 0) return Array.from(new Set(directories)); const cachedAgents = yield* fileSystem .readFileString(path.join(registryDirectory, "registry.json")) .pipe( @@ -398,26 +417,133 @@ export const acpRegistryManagedBinaryDirectories = Effect.fn("acpRegistryManaged (agent) => [`${agent.id}\0${encodeURIComponent(agent.version)}`, agent] as const, ), ); - for (const agent of (yield* listDirectories(installsDirectory)).toSorted()) { + let legacyBaselinesCache: Readonly> | undefined | null = null; + const getLegacyBaselines = Effect.gen(function* () { + if (legacyBaselinesCache !== null) return legacyBaselinesCache; + const result = yield* readLegacyBaselinesFile( + fileSystem, + path.join(registryDirectory, BINARY_LEGACY_BASELINES_FILENAME), + ); + legacyBaselinesCache = result.status === "ok" ? result.baselines : undefined; + return legacyBaselinesCache; + }); + for (const agent of agentDirectories) { const versions = (yield* listDirectories(path.join(installsDirectory, agent))).toSorted( - (left, right) => right.localeCompare(left, undefined, { numeric: true }), + (left, right) => + compareRegistryVersions(safeDecodeVersionDir(right), safeDecodeVersionDir(left)), ); for (const version of versions) { + const versionRoot = path.join(installsDirectory, agent, version); + const versionEntries = yield* listDirectories(versionRoot); for (const candidateTarget of resolveAcpRegistryPlatformTargetCandidates(target)) { - const installRoot = path.join(installsDirectory, agent, version, candidateTarget); - if (yield* fileSystem.exists(installRoot).pipe(Effect.orElseSucceed(() => false))) { - const binaryTarget = cachedAgentByInstall.get(`${agent}\0${version}`)?.distribution - .binary?.[candidateTarget]; - const commandSegments = - binaryTarget === undefined - ? undefined - : normalizeRegistryCommandPath(binaryTarget.cmd); - const directory = - commandSegments === undefined - ? installRoot - : path.join(installRoot, ...commandSegments.slice(0, -1)); - if (yield* fileSystem.exists(directory).pipe(Effect.orElseSucceed(() => false))) { - directories.push(directory); + const binaryTarget = cachedAgentByInstall.get(`${agent}\0${version}`)?.distribution + .binary?.[candidateTarget]; + const preferredCommandSegments = + binaryTarget === undefined ? undefined : normalizeRegistryCommandPath(binaryTarget.cmd); + const targetKey = + binaryTarget === undefined ? undefined : binaryArtifactIdentityKey(binaryTarget); + const slotKey = legacyBaselineSlotKey(agent, version, candidateTarget); + const matchingEntries = versionEntries.filter((entry) => + isBinaryPlatformEntry(entry, candidateTarget), + ); + const inspectedRaw = yield* Effect.forEach(matchingEntries, (entry) => + Effect.gen(function* () { + const installRoot = path.join(versionRoot, entry); + const rawReceipt = yield* fileSystem + .readFileString(path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME)) + .pipe(Effect.option); + const receipt = Option.flatMap(rawReceipt, decodeBinaryArtifactReceipt); + return { entry, installRoot, receipt }; + }), + ); + const hasReceiptedSlot = inspectedRaw.some((slot) => Option.isSome(slot.receipt)); + const inspectedSlots = yield* Effect.forEach( + inspectedRaw, + ({ entry, installRoot, receipt }) => + Effect.gen(function* () { + const isPrimary = entry === candidateTarget; + const receiptMatchesTarget = + binaryTarget !== undefined && + Option.isSome(receipt) && + binaryArtifactReceiptMatches(receipt.value, binaryTarget); + // Skip un-receipted artifact-scoped leftovers; they cannot be valid installs. + if (Option.isNone(receipt) && !isPrimary) { + return Option.none<{ + readonly rank: number; + readonly installRoot: string; + readonly isPrimary: boolean; + readonly entry: string; + readonly directory: string; + }>(); + } + // Skip superseded legacy primary slots once a receipted slot exists or a baseline disagrees. + if (Option.isNone(receipt) && isPrimary) { + if (hasReceiptedSlot) { + return Option.none<{ + readonly rank: number; + readonly installRoot: string; + readonly isPrimary: boolean; + readonly entry: string; + readonly directory: string; + }>(); + } + if (targetKey !== undefined) { + const legacyBaselines = yield* getLegacyBaselines; + if ( + legacyBaselines === undefined || + (legacyBaselines[slotKey] !== undefined && + legacyBaselines[slotKey] !== targetKey) + ) { + return Option.none<{ + readonly rank: number; + readonly installRoot: string; + readonly isPrimary: boolean; + readonly entry: string; + readonly directory: string; + }>(); + } + } + } + const receiptSegments = Option.isSome(receipt) + ? normalizeRegistryCommandPath(receipt.value.cmd) + : undefined; + const segments = receiptMatchesTarget + ? (preferredCommandSegments ?? receiptSegments) + : (receiptSegments ?? (isPrimary ? preferredCommandSegments : undefined)); + const directory = + segments === undefined + ? installRoot + : path.join(installRoot, ...segments.slice(0, -1)); + const rank = receiptMatchesTarget ? 0 : Option.isSome(receipt) ? 1 : 2; + return Option.some({ rank, installRoot, isPrimary, entry, directory }); + }), + ); + const candidateSlots = inspectedSlots.filter(Option.isSome).map((slot) => slot.value); + const rankCounts = new Map(); + for (const slot of candidateSlots) { + rankCounts.set(slot.rank, (rankCounts.get(slot.rank) ?? 0) + 1); + } + const rankedSlots = yield* Effect.forEach(candidateSlots, (slot) => + (rankCounts.get(slot.rank) ?? 0) > 1 + ? fileSystem.stat(slot.installRoot).pipe( + Effect.map((info) => ({ + ...slot, + mtimeMs: Option.isSome(info.mtime) ? info.mtime.value.getTime() : 0, + })), + Effect.orElseSucceed(() => ({ ...slot, mtimeMs: 0 })), + ) + : Effect.succeed({ ...slot, mtimeMs: 0 }), + ); + const orderedSlots = rankedSlots.toSorted( + (left, right) => + left.rank - right.rank || + right.mtimeMs - left.mtimeMs || + Number(left.isPrimary) - Number(right.isPrimary) || + left.entry.localeCompare(right.entry), + ); + for (const slot of orderedSlots) { + if (yield* fileSystem.exists(slot.directory).pipe(Effect.orElseSucceed(() => false))) { + directories.push(slot.directory); } } } @@ -476,19 +602,30 @@ export function resolveAcpRegistryDistribution(input: { return undefined; } +export interface AcpRegistryFailedTarget { + readonly version: string; + readonly launchIdentity: string; + readonly indexRevision: number; +} + export interface ResolvedAcpRegistryAgent { readonly agent?: AcpRegistryAgent; readonly distribution: AcpRegistryDistributionKind | "local"; + readonly launchIdentity?: string; + readonly indexRevision?: number; + readonly fallback?: boolean; + readonly failedTarget?: AcpRegistryFailedTarget; readonly spawn: AcpSessionRuntime.AcpSpawnInput; } export type AcpRegistryInspection = | { readonly status: "unconfigured" } - | { readonly status: "not_found"; readonly agentId: string } + | { readonly status: "not_found"; readonly agentId: string; readonly indexRevision?: number } | { readonly status: "unsupported"; readonly agentId: string; readonly version: string; + readonly indexRevision?: number; } | { readonly status: "missing_runner"; @@ -496,6 +633,7 @@ export type AcpRegistryInspection = readonly version: string; readonly distribution: AcpRegistryDistributionKind; readonly runner: string; + readonly indexRevision?: number; } | { readonly status: "missing_runner"; @@ -507,12 +645,16 @@ export type AcpRegistryInspection = readonly agentId: string; readonly version: string; readonly distribution: "binary"; + readonly indexRevision?: number; } | { readonly status: "ready"; readonly agentId: string; readonly version: string | null; readonly distribution: AcpRegistryDistributionKind | "local"; + readonly launchIdentity?: string; + readonly indexRevision?: number; + readonly icon?: string; readonly documentationUrl?: string; }; @@ -525,6 +667,12 @@ export class AcpRegistryCatalog extends Context.Service< readonly prepare: ( input: AcpRegistryPrepareInput, ) => Effect.Effect; + readonly refreshIndex: (options: { + readonly maxAgeMs: number; + readonly failureBackoffMs: number; + }) => Effect.Effect; + readonly currentIndexRevision: () => Effect.Effect; + readonly invalidateIndex: () => Effect.Effect; readonly inspect: ( settings: AcpRegistrySettings, environment?: NodeJS.ProcessEnv, @@ -573,8 +721,285 @@ const UNPACKING_AGENT_IDS: ReadonlySet = new Set(["antigravity-acp"]); const INSTALL_LOCK_RETRY_COUNT = 300; const INSTALL_LOCK_RETRY_DELAY = "100 millis"; const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000; +const LEGACY_BASELINES_LOCK_RETRY_COUNT = 20; +const LEGACY_BASELINES_LOCK_STALE_MS = 10 * 1_000; const PREPARED_BINARY_RESERVATION_MS = 30 * 1_000; +const BINARY_ARTIFACT_RECEIPT_FILENAME = ".t3-artifact.json"; +const BINARY_LEGACY_BASELINES_FILENAME = "legacy-baselines.json"; +const BINARY_LAUNCH_OPTIONS_FILENAME = "binary-launch-options.json"; +// Sentinel recorded for unrecoverable unreceipted slots when rebuilding a corrupt baselines file; +// never equals binaryArtifactIdentityKey (which is always JSON) so the slot must be reinstalled. +const LEGACY_BASELINE_UNKNOWN = "unknown"; +const BINARY_ARTIFACT_SLOT_HASH_LENGTH = 12; +const DOWNLOAD_RETRY_REGISTRY_BACKOFF_MS = 60 * 1_000; + +const AcpRegistryBinaryArtifactReceipt = Schema.Struct({ + version: Schema.optional(Schema.String), + archive: Schema.String, + cmd: Schema.String, + sha256: Schema.NullOr(Schema.String), + args: Schema.optional(Schema.Array(Schema.String)), + env: Schema.optional(Schema.Record(Schema.String, Schema.String)), + launchOptionsRevision: Schema.optional(Schema.Finite), + launchOptionsRecoveryId: Schema.optional(Schema.String), + installId: Schema.optional(Schema.String), +}); +type AcpRegistryBinaryArtifactReceipt = typeof AcpRegistryBinaryArtifactReceipt.Type; +const decodeBinaryArtifactReceipt = Schema.decodeUnknownOption( + Schema.fromJsonString(AcpRegistryBinaryArtifactReceipt), +); +const AcpRegistryBinaryLaunchOptionsStore = Schema.Record( + Schema.String, + AcpRegistryBinaryArtifactReceipt, +); +const decodeBinaryLaunchOptionsStore = Schema.decodeUnknownOption( + Schema.fromJsonString(AcpRegistryBinaryLaunchOptionsStore), +); + +type BinaryLaunchOptionsReadResult = + | { + readonly status: "ok"; + readonly entries: Readonly>; + } + | { readonly status: "corrupt" } + | { readonly status: "io_error" }; + +function readBinaryLaunchOptionsFile( + fileSystem: FileSystem.FileSystem, + launchOptionsPath: string, +): Effect.Effect { + return fileSystem.readFileString(launchOptionsPath).pipe( + Effect.map((raw): BinaryLaunchOptionsReadResult => { + const decoded = decodeBinaryLaunchOptionsStore(raw); + return Option.isSome(decoded) + ? { status: "ok", entries: decoded.value } + : { status: "corrupt" }; + }), + Effect.catch((error) => + Effect.succeed( + error.reason._tag === "NotFound" ? { status: "ok", entries: {} } : { status: "io_error" }, + ), + ), + ); +} + +const AcpRegistryLegacyBaselines = Schema.Record(Schema.String, Schema.String); +const decodeLegacyBaselines = Schema.decodeUnknownOption( + Schema.fromJsonString(AcpRegistryLegacyBaselines), +); + +type LegacyBaselinesReadResult = + | { readonly status: "ok"; readonly baselines: Readonly> } + | { readonly status: "corrupt" } + | { readonly status: "io_error" }; + +function legacyBaselineSlotKey( + agentId: string, + encodedVersion: string, + candidateTarget: AcpRegistryPlatformTarget, +): string { + return `${agentId}\0${encodedVersion}\0${candidateTarget}`; +} + +function legacyBaselineAgentUnknownKey(agentId: string): string { + return `${agentId}\0*`; +} + +function readLegacyBaselinesFile( + fileSystem: FileSystem.FileSystem, + baselinesPath: string, +): Effect.Effect { + return fileSystem.readFileString(baselinesPath).pipe( + Effect.map((raw): LegacyBaselinesReadResult => { + const decoded = decodeLegacyBaselines(raw); + return Option.isSome(decoded) + ? { status: "ok", baselines: decoded.value } + : { status: "corrupt" }; + }), + Effect.catch((error) => + Effect.succeed( + error.reason._tag === "NotFound" ? { status: "ok", baselines: {} } : { status: "io_error" }, + ), + ), + ); +} + +function safeDecodeVersionDir(value: string): string { + try { + return decodeURIComponent(value); + } catch { + return value; + } +} + +const NUMERIC_VERSION_IDENTIFIER = /^(?:0|[1-9]\d*)$/u; +const DIGITS_ONLY = /^\d+$/u; + +function compareNumericStrings(left: string, right: string): number { + const a = left.replace(/^0+(?=\d)/u, ""); + const b = right.replace(/^0+(?=\d)/u, ""); + if (a.length !== b.length) return a.length - b.length; + return compareText(a, b); +} + +function compareRegistryVersions(left: string, right: string): number { + const splitVersion = (raw: string) => { + const stripped = raw.replace(/^v(?=\d)/iu, "").split("+", 1)[0] ?? raw; + const hyphenIndex = stripped.indexOf("-"); + const core = hyphenIndex === -1 ? stripped : stripped.slice(0, hyphenIndex); + const prerelease = hyphenIndex === -1 ? undefined : stripped.slice(hyphenIndex + 1); + return { + core: core.split("."), + prerelease: prerelease === undefined ? undefined : prerelease.split("."), + }; + }; + const a = splitVersion(left); + const b = splitVersion(right); + const maxLen = Math.max(a.core.length, b.core.length); + for (let index = 0; index < maxLen; index += 1) { + const aPart = a.core[index] ?? "0"; + const bPart = b.core[index] ?? "0"; + if (aPart === bPart) continue; + const diff = + DIGITS_ONLY.test(aPart) && DIGITS_ONLY.test(bPart) + ? compareNumericStrings(aPart, bPart) + : compareText(aPart, bPart); + if (diff !== 0) return diff; + } + if (a.prerelease === undefined && b.prerelease === undefined) return 0; + if (a.prerelease === undefined) return 1; + if (b.prerelease === undefined) return -1; + // SemVer 2.0.0 §11.4: numeric identifiers compare numerically and have lower precedence than + // non-numeric identifiers, which compare lexically in ASCII order. + const minPre = Math.min(a.prerelease.length, b.prerelease.length); + for (let index = 0; index < minPre; index += 1) { + const aId = a.prerelease[index]!; + const bId = b.prerelease[index]!; + if (aId === bId) continue; + const aIsNum = NUMERIC_VERSION_IDENTIFIER.test(aId); + const bIsNum = NUMERIC_VERSION_IDENTIFIER.test(bId); + if (aIsNum && bIsNum) { + const diff = compareNumericStrings(aId, bId); + if (diff !== 0) return diff; + continue; + } + if (aIsNum) return -1; + if (bIsNum) return 1; + return compareText(aId, bId); + } + return a.prerelease.length - b.prerelease.length; +} + +function binaryArtifactIdentityKey(target: typeof AcpRegistryBinaryTarget.Type): string { + return JSON.stringify({ + archive: target.archive, + cmd: target.cmd, + sha256: target.sha256 ?? null, + }); +} + +function binaryArtifactDirName( + platformTarget: AcpRegistryPlatformTarget, + target: typeof AcpRegistryBinaryTarget.Type, +): string { + const digest = Hex.encode(sha256(new TextEncoder().encode(binaryArtifactIdentityKey(target)))); + return `${platformTarget}-${digest.slice(0, BINARY_ARTIFACT_SLOT_HASH_LENGTH)}`; +} + +function isBinaryPlatformEntry(entry: string, candidateTarget: AcpRegistryPlatformTarget): boolean { + if (entry === candidateTarget) return true; + if (!entry.startsWith(`${candidateTarget}-`)) return false; + return /^[0-9a-f]{12}$/u.test(entry.slice(candidateTarget.length + 1)); +} + +function binaryArtifactReceiptMatches( + receipt: AcpRegistryBinaryArtifactReceipt, + target: typeof AcpRegistryBinaryTarget.Type, +): boolean { + return ( + receipt.archive === target.archive && + receipt.cmd === target.cmd && + receipt.sha256 === (target.sha256 ?? null) + ); +} + +function receiptMatchesInstall( + candidate: AcpRegistryBinaryArtifactReceipt | undefined, + receipt: AcpRegistryBinaryArtifactReceipt, +): candidate is AcpRegistryBinaryArtifactReceipt { + return ( + candidate !== undefined && + candidate.archive === receipt.archive && + candidate.cmd === receipt.cmd && + (candidate.sha256 ?? null) === (receipt.sha256 ?? null) && + (candidate.installId ?? null) === (receipt.installId ?? null) + ); +} + +function receiptMatchesLaunchOptions( + receipt: AcpRegistryBinaryArtifactReceipt, + target: typeof AcpRegistryBinaryTarget.Type, +): boolean { + return ( + Equal.equals(receipt.args ?? [], target.args ?? []) && + Equal.equals(receipt.env ?? {}, target.env ?? {}) + ); +} + +function encodeBinaryArtifactReceipt( + agent: AcpRegistryAgent, + target: typeof AcpRegistryBinaryTarget.Type, + options?: { + readonly launchOptionsRevision?: number; + readonly installId?: string; + }, +): string { + return JSON.stringify({ + version: agent.version, + archive: target.archive, + cmd: target.cmd, + sha256: target.sha256 ?? null, + ...(target.args && target.args.length > 0 ? { args: target.args } : {}), + ...(target.env && Object.keys(target.env).length > 0 ? { env: target.env } : {}), + ...(options?.launchOptionsRevision !== undefined + ? { launchOptionsRevision: options.launchOptionsRevision } + : {}), + ...(options?.installId !== undefined ? { installId: options.installId } : {}), + }); +} + +function registryLaunchIdentity(input: { + readonly version: string | null; + readonly distribution: ResolvedAcpRegistryDistribution; + readonly commandOverride?: string; +}): string { + const envEntries = Object.entries(input.distribution.env).sort(([left], [right]) => + compareText(left, right), + ); + if (input.commandOverride) { + return JSON.stringify({ + commandOverride: input.commandOverride, + args: input.distribution.args, + env: envEntries, + }); + } + return JSON.stringify({ + version: input.version, + kind: input.distribution.kind, + ...(input.distribution.packageName ? { packageName: input.distribution.packageName } : {}), + ...(input.distribution.binaryTarget + ? { + archive: input.distribution.binaryTarget.archive, + cmd: input.distribution.binaryTarget.cmd, + sha256: input.distribution.binaryTarget.sha256 ?? null, + } + : {}), + args: input.distribution.args, + env: envEntries, + }); +} + function isAlreadyExists(error: PlatformError.PlatformError): boolean { return error.reason._tag === "AlreadyExists"; } @@ -684,6 +1109,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const registryUrl = input.registryUrl ?? ACP_REGISTRY_URL; const registryDirectory = path.join(input.cacheDir, "acp-registry"); const registryCachePath = path.join(registryDirectory, "registry.json"); + const legacyBaselinesPath = path.join(registryDirectory, BINARY_LEGACY_BASELINES_FILENAME); + const binaryLaunchOptionsPath = path.join(registryDirectory, BINARY_LAUNCH_OPTIONS_FILENAME); const installsDirectory = input.toolsDir; const agentInstallRoot = (agent: AcpRegistryAgent) => path.join(installsDirectory, agent.id, encodeURIComponent(agent.version)); @@ -694,11 +1121,36 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ? packageInstallRoot(agent, distribution) : path.join(packageInstallRoot(agent, distribution), "bin"); const packageReceiptsDirectory = path.join(registryDirectory, "package-installs"); - const registryRef = yield* Ref.make(undefined); - // When the network last served registryRef; unset while it holds the disk cache. - const registryFetchedAtMs = yield* Ref.make(undefined); - const registryRevision = yield* Ref.make(0); + interface RegistryCacheState { + readonly index: AcpRegistryIndex | undefined; + // When the network last served index; unset until fetched, on fallback, or after invalidateIndex. + readonly fetchedAtMs: number | undefined; + // When a network fetch last failed; lets background max-age refreshes back off while offline. + readonly failedAtMs: number | undefined; + // Last network failure; lets coalesced or backed-off callers fail fast when uncached. + readonly lastFailure: AcpRegistryError | undefined; + // Advances only on a successful non-invalidated network fetch; shared by all queued callers. + readonly fetchRevision: number; + // Advances on any completed non-invalidated refresh attempt (fetch, fallback, or uncached failure). + readonly attemptRevision: number; + // Advances only when a network fetch succeeds with a different index than the previous one. + readonly indexRevision: number; + // Advances on invalidateIndex so an in-flight attempt started earlier cannot mark the cache fresh or backed off. + readonly invalidationGeneration: number; + } + const registryState = yield* Ref.make({ + index: undefined, + fetchedAtMs: undefined, + failedAtMs: undefined, + lastFailure: undefined, + fetchRevision: 0, + attemptRevision: 0, + indexRevision: 0, + invalidationGeneration: 0, + }); const registrySemaphore = yield* Semaphore.make(1); + const legacyBaselinesSemaphore = yield* Semaphore.make(1); + const launchOptionsSemaphore = yield* Semaphore.make(1); // Long installs must only block operations on the same agent. const installPermits = new Map(); const withInstallPermit = (agentId: string) => { @@ -707,6 +1159,24 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return permit.withPermits(1); }; const preparedBinaryReservations = yield* Ref.make>(new Map()); + // In-memory mirror of durable legacy baselines so disk write errors still keep a superseded + // pre-receipt binary from matching a newly published artifact at the same version. + const legacyBaselineBySlotKey = new Map(); + // True after an incomplete tools-directory scan or disk-index read error during baseline + // discovery; requires positive baseline provenance before reusing unreceipted legacy installs. + let legacyBaselineDiscoveryIncomplete = false; + // In-memory mirror of uncommitted binary launch options when durable writes fail or cannot read + // the sidecar; tracked separately from committed revisions so failed writes never outrank later + // durable updates from another catalog. + const pendingLaunchOptionsBySlotRoot = new Map< + string, + { + readonly baseReceiptRevision: number; + readonly baseDurableRevision: number; + readonly baseRecoveryId: string | null; + readonly receipt: AcpRegistryBinaryArtifactReceipt; + } + >(); const runtimeTempDir = input.runtimeTempDir; if (runtimeTempDir !== undefined) { @@ -827,10 +1297,15 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const assertHttpsUrl = Effect.fn("AcpRegistryCatalog.assertHttpsUrl")(function* ( value: string, detail: string, + stage?: AcpRegistryFetchStage, ) { const valid = yield* decodeHttpsUrl(value).pipe(Effect.option); if (Option.isNone(valid)) { - return yield* new AcpRegistryError({ reason: "registry_unavailable", detail }); + return yield* new AcpRegistryError({ + reason: "registry_unavailable", + detail, + ...(stage === undefined ? {} : { stage }), + }); } return value; }); @@ -844,6 +1319,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct new AcpRegistryError({ reason: "registry_unavailable", detail: "ACP Registry returned invalid JSON.", + stage: "invalid_json", cause, }), ), @@ -854,6 +1330,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct new AcpRegistryError({ reason: "registry_unavailable", detail: "ACP Registry returned an invalid index.", + stage: "invalid_index", cause, }), ), @@ -889,7 +1366,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ); const fetchRegistry = Effect.fn("AcpRegistryCatalog.fetchRegistry")(function* () { - yield* assertHttpsUrl(registryUrl, "ACP Registry index URL must use HTTPS."); + yield* assertHttpsUrl(registryUrl, "ACP Registry index URL must use HTTPS.", "invalid_url"); const response = yield* httpClient.execute(HttpClientRequest.get(registryUrl)).pipe( Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.mapError( @@ -897,6 +1374,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct new AcpRegistryError({ reason: "registry_unavailable", detail: `Could not fetch ACP Registry index from ${registryUrl}.`, + stage: "http_request", cause, }), ), @@ -907,6 +1385,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct new AcpRegistryError({ reason: "registry_unavailable", detail: "Timed out fetching ACP Registry index.", + stage: "request_timeout", }), ), }), @@ -920,6 +1399,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct new AcpRegistryError({ reason: "registry_unavailable", detail: "Could not read ACP Registry response body.", + stage: "response_read", cause, }), ), @@ -930,6 +1410,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct new AcpRegistryError({ reason: "registry_unavailable", detail: "Timed out reading ACP Registry response body.", + stage: "response_timeout", }), ), }), @@ -938,152 +1419,800 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return yield* new AcpRegistryError({ reason: "registry_unavailable", detail: `ACP Registry index exceeds ${MAX_REGISTRY_BYTES} bytes.`, + stage: "response_too_large", }); } if (collected.invalidUtf8) { return yield* new AcpRegistryError({ reason: "registry_unavailable", detail: "ACP Registry index is not valid UTF-8.", + stage: "invalid_utf8", }); } const registry = yield* decodeRegistryText(collected.text); - yield* writeRegistryCache(collected.text); - return registry; + return { registry, text: collected.text }; }); - const refreshRegistry = Effect.fn("AcpRegistryCatalog.refreshRegistry")(function* () { - const observedRevision = yield* Ref.get(registryRevision); - return yield* registrySemaphore.withPermits(1)( - Effect.gen(function* () { - const currentRevision = yield* Ref.get(registryRevision); - const current = yield* Ref.get(registryRef); - if (current !== undefined && currentRevision !== observedRevision) return current; + const acquireFileLock = Effect.fn("AcpRegistryCatalog.acquireFileLock")(function* ( + lockPath: string, + options?: { + readonly retryCount?: number; + readonly staleMs?: number; + }, + ) { + const retryCount = options?.retryCount ?? INSTALL_LOCK_RETRY_COUNT; + const staleMs = options?.staleMs ?? INSTALL_LOCK_STALE_MS; + const token = yield* random.uuidV4(); + for (let attempt = 0; attempt < retryCount; attempt += 1) { + const acquired = yield* fileSystem.writeFileString(lockPath, token, { flag: "wx" }).pipe( + Effect.as(true), + Effect.catchIf( + (error) => isAlreadyExists(error), + () => Effect.succeed(false), + ), + ); + if (acquired) return token; + const now = yield* Clock.currentTimeMillis; + const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option); + const mtime = Option.flatMap(lockInfo, (info) => info.mtime); + if (Option.isSome(mtime) && now - mtime.value.getTime() > staleMs) { + yield* fileSystem.remove(lockPath, { force: true }); + continue; + } + // Keep the retry sleep interruptible inside acquireUseRelease so waiting on a busy lock + // never blocks provider refreshes, foreground preemption, or shutdown. + yield* Effect.interruptible(Effect.sleep(INSTALL_LOCK_RETRY_DELAY)); + } + return yield* new AcpRegistryError({ + reason: "install_failed", + detail: `Timed out waiting for ACP Registry install lock ${lockPath}.`, + }); + }); - const { registry, fetched } = yield* fetchRegistry().pipe( - Effect.map((registry) => ({ registry, fetched: true })), - Effect.catch((networkError) => - readCachedRegistry.pipe( - Effect.flatMap( - Option.match({ - onNone: () => Effect.fail(networkError), - onSome: (registry) => Effect.succeed({ registry, fetched: false }), - }), - ), - ), + const withFileLock = ( + lockPath: string, + use: (isLockOwned: Effect.Effect) => Effect.Effect, + options?: { + readonly retryCount?: number; + readonly staleMs?: number; + }, + ) => + Effect.acquireUseRelease( + acquireFileLock(lockPath, options), + (token) => + use( + fileSystem.readFileString(lockPath).pipe( + Effect.map((current) => current === token), + Effect.orElseSucceed(() => false), ), - ); - yield* Ref.set(registryRef, registry); - yield* Ref.set(registryFetchedAtMs, fetched ? yield* Clock.currentTimeMillis : undefined); - yield* Ref.update(registryRevision, (revision) => revision + 1); - return registry; + ), + (token) => + fileSystem.readFileString(lockPath).pipe( + Effect.flatMap((current) => + current === token ? fileSystem.remove(lockPath, { force: true }) : Effect.void, + ), + Effect.ignore, + ), + ); + + const writeJsonFileAtomically = (targetPath: string, value: unknown) => + random.uuidV4().pipe( + Effect.flatMap((id) => { + const temporaryPath = `${targetPath}.${process.pid}-${id}.tmp`; + return fileSystem + .makeDirectory(registryDirectory, { recursive: true }) + .pipe( + Effect.andThen(fileSystem.writeFileString(temporaryPath, JSON.stringify(value))), + Effect.andThen(fileSystem.rename(temporaryPath, targetPath)), + Effect.ensuring(fileSystem.remove(temporaryPath, { force: true }).pipe(Effect.ignore)), + ); }), ); - }); - const recentRegistry = Effect.fn("AcpRegistryCatalog.recentRegistry")(function* () { - const current = yield* Ref.get(registryRef); - const fetchedAtMs = yield* Ref.get(registryFetchedAtMs); - const now = yield* Clock.currentTimeMillis; - // A clock moved back makes the stamp untrustworthy, so it counts as stale. - if ( - current !== undefined && - fetchedAtMs !== undefined && - now >= fetchedAtMs && - now - fetchedAtMs < REGISTRY_SEARCH_MAX_AGE_MS - ) { - return current; - } - return yield* refreshRegistry(); - }); + const writeLegacyBaselinesAtomically = (baselines: Readonly>) => + writeJsonFileAtomically(legacyBaselinesPath, baselines); + + const withLegacyBaselinesLock = ( + use: (isLockOwned: Effect.Effect) => Effect.Effect, + ) => + legacyBaselinesSemaphore.withPermits(1)( + fileSystem.makeDirectory(registryDirectory, { recursive: true }).pipe( + Effect.andThen( + withFileLock(`${legacyBaselinesPath}.lock`, use, { + retryCount: LEGACY_BASELINES_LOCK_RETRY_COUNT, + staleMs: LEGACY_BASELINES_LOCK_STALE_MS, + }), + ), + ), + ); - const loadRegistry = Effect.fn("AcpRegistryCatalog.loadRegistry")(function* () { - const current = yield* Ref.get(registryRef); - if (current !== undefined) return current; + const withBinaryLaunchOptionsLock = ( + use: (isLockOwned: Effect.Effect) => Effect.Effect, + ) => + launchOptionsSemaphore.withPermits(1)( + fileSystem.makeDirectory(registryDirectory, { recursive: true }).pipe( + Effect.andThen( + withFileLock(`${binaryLaunchOptionsPath}.lock`, use, { + retryCount: LEGACY_BASELINES_LOCK_RETRY_COUNT, + staleMs: LEGACY_BASELINES_LOCK_STALE_MS, + }), + ), + ), + ); - const cached = yield* readCachedRegistry; - if (Option.isNone(cached)) return yield* refreshRegistry(); - yield* Ref.set(registryRef, cached.value); - return cached.value; + // Returns true when the desired state is durably persisted on disk (or already superseded by a + // newer revision), false on transient I/O errors or lock loss (leaving disk untouched). + // Corrupt sidecar files are copied aside and repaired cleanly once the lock is verified. + const updateBinaryLaunchOptionsStore = Effect.fn( + "AcpRegistryCatalog.updateBinaryLaunchOptionsStore", + )(function* ( + mutate: ( + entries: Readonly>, + ) => Readonly> | null, + ) { + return yield* withBinaryLaunchOptionsLock((isLockOwned) => + Effect.gen(function* () { + const current = yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath); + if (current.status === "io_error") return false; + const isCorrupt = current.status === "corrupt"; + const baseEntries = isCorrupt ? {} : current.entries; + const nextEntries = mutate(baseEntries); + if (nextEntries === null && !isCorrupt) return true; + if (!(yield* isLockOwned)) return false; + if (isCorrupt) { + yield* fileSystem + .copyFile(binaryLaunchOptionsPath, `${binaryLaunchOptionsPath}.corrupt`) + .pipe(Effect.ignore); + } + return yield* writeJsonFileAtomically(binaryLaunchOptionsPath, nextEntries ?? {}).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + }), + ).pipe(Effect.orElseSucceed(() => false)); }); - const runCommand = Effect.fn("AcpRegistryCatalog.runCommand")(function* ( - command: string, - args: ReadonlyArray, - options: { - readonly cwd?: string; - readonly env?: NodeJS.ProcessEnv; - readonly timeout?: Duration.Input; - readonly truncatedOutputReason?: AcpRegistryErrorReason; - readonly maxStdoutBytes?: number; - } = {}, + const recordLegacyBaselines = Effect.fn("AcpRegistryCatalog.recordLegacyBaselines")(function* ( + inMemoryPrevious: AcpRegistryIndex | undefined, + nextIndex: AcpRegistryIndex, ) { - const collect = Effect.gen(function* () { - const resolved = yield* resolveSpawnCommand( - command, - args, - options.env === undefined ? {} : { env: options.env }, - ); - const child = yield* spawner.spawn( - ChildProcess.make(resolved.command, resolved.args, { - ...(options.cwd ? { cwd: options.cwd } : {}), - ...(options.env === undefined ? {} : { env: options.env }), - shell: resolved.shell, - }), - ); - yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore)); - const [stdout, stderr, exitCode] = yield* Effect.all( - [ - collectUint8StreamText({ - stream: child.stdout, - maxBytes: options.maxStdoutBytes ?? MAX_COMMAND_OUTPUT_BYTES, - }), - child.stderr.pipe( - Stream.decodeText(), - Stream.runFold( - () => "", - (tail, text) => `${tail}${text}`.slice(-MAX_COMMAND_ERROR_TAIL_CHARS), + if (platformTarget === undefined) return true; + const candidates = resolveAcpRegistryPlatformTargetCandidates(platformTarget); + const readDiskPreviousIndex = Effect.fn("AcpRegistryCatalog.readDiskPreviousIndex")( + function* () { + return yield* fileSystem.readFileString(registryCachePath).pipe( + Effect.flatMap((text) => + decodeRegistryText(text).pipe( + Effect.map((index) => ({ status: "ok" as const, index })), + Effect.orElseSucceed(() => ({ status: "missing" as const })), ), ), - child.exitCode, - ], - { concurrency: "unbounded" }, + Effect.catch((error) => + Effect.succeed( + error.reason._tag === "NotFound" + ? ({ status: "missing" as const } as const) + : ({ status: "io_error" as const } as const), + ), + ), + ); + }, + ); + const readDirectoryOrMissing = (directory: string) => + fileSystem.readDirectory(directory).pipe( + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed>([]), + ), ); - if (Number(exitCode) !== 0) { - return yield* new AcpRegistryError({ - reason: "install_failed", - detail: `ACP Registry install command '${command}' exited with code ${Number(exitCode)}: ${stderr.trim()}`, - }); + const listSubdirectories = Effect.fn("AcpRegistryCatalog.listSubdirectories")(function* ( + directory: string, + ) { + const entries = yield* readDirectoryOrMissing(directory); + const directories: Array = []; + for (const entry of entries) { + const statResult = yield* fileSystem.stat(path.join(directory, entry)).pipe( + Effect.map((info) => ({ status: "ok" as const, info })), + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed({ status: "missing" as const }), + ), + ); + // Shared tools/ also holds non-directory files (e.g. tools/codex/active.json, .DS_Store). + if (statResult.status === "ok" && statResult.info.type === "Directory") { + directories.push(entry); + } } - // Truncated listings would bypass archive traversal validation. - if (stdout.truncated) { - return yield* new AcpRegistryError({ - reason: options.truncatedOutputReason ?? "archive_invalid", - detail: `ACP Registry install command '${command}' produced more output than expected.`, - }); + return directories; + }); + const scanAgentLegacySlots = Effect.fn("AcpRegistryCatalog.scanAgentLegacySlots")(function* ( + agentId: string, + ) { + const slots: Array<{ + readonly agentId: string; + readonly encodedVersion: string; + readonly candidateTarget: AcpRegistryPlatformTarget; + readonly slotKey: string; + }> = []; + const agentRoot = path.join(installsDirectory, agentId); + const agentStat = yield* fileSystem.stat(agentRoot).pipe( + Effect.map((info) => ({ status: "ok" as const, info })), + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed({ status: "missing" as const }), + ), + ); + if (agentStat.status !== "ok" || agentStat.info.type !== "Directory") return slots; + for (const encodedVersion of yield* listSubdirectories(agentRoot)) { + const versionRoot = path.join(agentRoot, encodedVersion); + for (const candidateTarget of candidates) { + const installRoot = path.join(versionRoot, candidateTarget); + const installStat = yield* fileSystem.stat(installRoot).pipe( + Effect.map((info) => ({ status: "ok" as const, info })), + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed({ status: "missing" as const }), + ), + ); + if (installStat.status !== "ok" || installStat.info.type !== "Directory") continue; + if (yield* fileSystem.exists(path.join(installRoot, BINARY_ARTIFACT_RECEIPT_FILENAME))) + continue; + slots.push({ + agentId, + encodedVersion, + candidateTarget, + slotKey: legacyBaselineSlotKey(agentId, encodedVersion, candidateTarget), + }); + } } - return stdout.text; + return slots; }); - const scoped = collect.pipe( - Effect.scoped, - Effect.mapError((cause) => - isAcpRegistryError(cause) - ? cause - : new AcpRegistryError({ - reason: "install_failed", - detail: `Could not run ACP Registry install command '${command}'.`, - cause, - }), + const scanUnreceiptedLegacySlots = Effect.fn("AcpRegistryCatalog.scanUnreceiptedLegacySlots")( + function* (requiredAgentIds: ReadonlyArray, includeExtraDirectories: boolean) { + const slots: Array<{ + readonly agentId: string; + readonly encodedVersion: string; + readonly candidateTarget: AcpRegistryPlatformTarget; + readonly slotKey: string; + }> = []; + const unscannedExtraAgents: Array = []; + for (const agentId of requiredAgentIds) { + slots.push(...(yield* scanAgentLegacySlots(agentId))); + } + if (includeExtraDirectories) { + // On corrupt-baselines rebuild, also discover readable removed-agent slots and record + // an agent-level unknown sentinel for unreadable extra directories (such as unrelated + // tools or temporarily unreadable removed agents) so normal refreshes stay isolated + // without losing unknown provenance if a removed agent is later re-added. + const requiredSet = new Set(requiredAgentIds); + for (const entry of yield* listSubdirectories(installsDirectory)) { + if (requiredSet.has(entry)) continue; + const extraResult = yield* Effect.result(scanAgentLegacySlots(entry)); + if (Result.isSuccess(extraResult)) { + slots.push(...extraResult.success); + } else { + unscannedExtraAgents.push(entry); + } + } + } + return { slots, unscannedExtraAgents }; + }, + ); + + const installsStat = yield* fileSystem.stat(installsDirectory).pipe( + Effect.map((info) => ({ status: "ok" as const, info })), + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed({ status: "missing" as const }), ), + Effect.orElseSucceed(() => ({ status: "io_error" as const })), ); - return yield* options.timeout === undefined - ? scoped - : scoped.pipe( + if (installsStat.status === "missing") { + legacyBaselineDiscoveryIncomplete = false; + return true; + } + if (installsStat.status === "io_error") { + legacyBaselineDiscoveryIncomplete = true; + yield* Effect.logDebug( + "Could not inspect managed ACP binary directory for legacy baselines; keeping existing disk registry cache.", + ); + return false; + } + + const initialDisk = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); + const initialDiskIndex = yield* readDiskPreviousIndex(); + if (initialDiskIndex.status === "io_error") { + legacyBaselineDiscoveryIncomplete = true; + yield* Effect.logDebug( + "Could not read cached ACP Registry index for legacy baselines; keeping existing disk registry cache.", + ); + return false; + } + // Scope normal scans to ACP agent directories referenced by the previous/next index or + // in-memory baselines so unrelated entries in shared tools/ never block registry refreshes. + // Include extra directories (best-effort) only when rebuilding a corrupt baselines file. + const requiredAgentIds = Array.from( + new Set([ + ...nextIndex.agents.map((agent) => agent.id), + ...(initialDiskIndex.status === "ok" + ? initialDiskIndex.index.agents.map((agent) => agent.id) + : []), + ...(inMemoryPrevious?.agents.map((agent) => agent.id) ?? []), + ...Array.from(legacyBaselineBySlotKey.keys()) + .filter((key) => !key.endsWith("\0*")) + .map((key) => key.split("\0")[0] ?? ""), + ]), + ).filter((id) => id.length > 0); + const initialIncludedExtraDirs = initialDisk.status === "corrupt"; + const scanResult = yield* Effect.result( + scanUnreceiptedLegacySlots(requiredAgentIds, initialIncludedExtraDirs), + ); + if (Result.isFailure(scanResult)) { + legacyBaselineDiscoveryIncomplete = true; + yield* Effect.logDebug( + "Could not scan managed ACP binary directories for legacy baselines; keeping existing disk registry cache.", + ); + return false; + } + const { slots: unreceiptedLegacySlots, unscannedExtraAgents } = scanResult.success; + if (unreceiptedLegacySlots.length === 0 && unscannedExtraAgents.length === 0) { + legacyBaselineDiscoveryIncomplete = false; + return true; + } + + const recordDivergingInMemory = Effect.fn("AcpRegistryCatalog.recordDivergingLegacyBaselines")( + function* (existingBaselines: Readonly>) { + const unpersistedSlots = unreceiptedLegacySlots.filter((slot) => { + const existingBaseline = existingBaselines[slot.slotKey]; + if (existingBaseline !== undefined) { + legacyBaselineBySlotKey.set(slot.slotKey, existingBaseline); + return false; + } + return true; + }); + if (unpersistedSlots.length === 0) { + return { + newBaselines: {} as Record, + hasUpdates: false, + readError: false, + }; + } + // Prefer the on-disk registry cache over in-memory state so a recovery refresh after a + // previous skipped disk write still compares against the index persisted on disk. + const diskIndexResult = yield* readDiskPreviousIndex(); + if (diskIndexResult.status === "io_error") { + legacyBaselineDiscoveryIncomplete = true; + return { + newBaselines: {} as Record, + hasUpdates: false, + readError: true, + }; + } + const previousIndex = + diskIndexResult.status === "ok" ? diskIndexResult.index : inMemoryPrevious; + const previousById = new Map( + (previousIndex?.agents ?? []).map((agent) => [agent.id, agent] as const), + ); + const nextById = new Map(nextIndex.agents.map((agent) => [agent.id, agent] as const)); + const newBaselines: Record = {}; + let hasUpdates = false; + for (const slot of unpersistedSlots) { + const agentUnknownKey = legacyBaselineAgentUnknownKey(slot.agentId); + if ( + existingBaselines[agentUnknownKey] === LEGACY_BASELINE_UNKNOWN || + legacyBaselineBySlotKey.get(agentUnknownKey) === LEGACY_BASELINE_UNKNOWN + ) { + legacyBaselineBySlotKey.set(slot.slotKey, LEGACY_BASELINE_UNKNOWN); + newBaselines[slot.slotKey] = LEGACY_BASELINE_UNKNOWN; + hasUpdates = true; + continue; + } + const existingInMemory = legacyBaselineBySlotKey.get(slot.slotKey); + if (existingInMemory !== undefined) { + newBaselines[slot.slotKey] = existingInMemory; + hasUpdates = true; + continue; + } + const previousAgent = previousById.get(slot.agentId); + if ( + previousAgent === undefined || + encodeURIComponent(previousAgent.version) !== slot.encodedVersion + ) { + continue; + } + const previousTarget = previousAgent.distribution.binary?.[slot.candidateTarget]; + if (previousTarget === undefined) continue; + const previousKey = binaryArtifactIdentityKey(previousTarget); + const nextAgent = nextById.get(slot.agentId); + const nextTarget = + nextAgent !== undefined && encodeURIComponent(nextAgent.version) === slot.encodedVersion + ? nextAgent.distribution.binary?.[slot.candidateTarget] + : undefined; + // Record the legacy artifact whenever the slot's artifact changes, version bumps, or disappears + // so a later rollback or repackage at the same version never mistakes the legacy install for it. + if (nextTarget !== undefined && binaryArtifactIdentityKey(nextTarget) === previousKey) { + continue; + } + legacyBaselineBySlotKey.set(slot.slotKey, previousKey); + newBaselines[slot.slotKey] = previousKey; + hasUpdates = true; + } + return { newBaselines, hasUpdates, readError: false }; + }, + ); + + const preserveAndFail = Effect.fn("AcpRegistryCatalog.preserveLegacyBaselinesOnError")( + function* (existingBaselines: Readonly>, reason: string) { + yield* recordDivergingInMemory(existingBaselines); + yield* Effect.logDebug(reason); + return false; + }, + ); + + if ( + initialDisk.status === "ok" && + unreceiptedLegacySlots.every((slot) => initialDisk.baselines[slot.slotKey] !== undefined) + ) { + for (const slot of unreceiptedLegacySlots) { + legacyBaselineBySlotKey.set(slot.slotKey, initialDisk.baselines[slot.slotKey]!); + } + legacyBaselineDiscoveryIncomplete = false; + return true; + } + if (initialDisk.status === "io_error") { + return yield* preserveAndFail( + {}, + "Could not read ACP Registry legacy baselines; keeping existing disk registry cache.", + ); + } + + return yield* withLegacyBaselinesLock((isLockOwned) => + Effect.gen(function* () { + const disk = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); + if (disk.status === "io_error") { + return yield* preserveAndFail( + {}, + "Could not read ACP Registry legacy baselines; keeping existing disk registry cache.", + ); + } + let mergedBaselines: Record; + if (disk.status === "corrupt") { + const corruptScan = initialIncludedExtraDirs + ? { slots: unreceiptedLegacySlots, unscannedExtraAgents } + : yield* Effect.result(scanUnreceiptedLegacySlots(requiredAgentIds, true)).pipe( + Effect.map((result) => (Result.isSuccess(result) ? result.success : null)), + ); + if (corruptScan === null) { + legacyBaselineDiscoveryIncomplete = true; + yield* Effect.logDebug( + "Could not scan managed ACP binary directories while rebuilding corrupt legacy baselines; keeping existing disk registry cache.", + ); + return false; + } + // Copy the corrupt bytes aside before atomically replacing legacy-baselines.json so there + // is no missing-file window. Never reconstruct provenance from the unverified cached + // registry index; preserve only baselines already verified in memory and mark others + // unknown so resolve() requires a fresh receipted install. + yield* fileSystem + .copyFile(legacyBaselinesPath, `${legacyBaselinesPath}.corrupt`) + .pipe(Effect.ignore); + mergedBaselines = {}; + for (const slot of corruptScan.slots) { + const baseline = legacyBaselineBySlotKey.get(slot.slotKey) ?? LEGACY_BASELINE_UNKNOWN; + mergedBaselines[slot.slotKey] = baseline; + legacyBaselineBySlotKey.set(slot.slotKey, baseline); + } + for (const unscannedAgentId of corruptScan.unscannedExtraAgents) { + const unknownKey = legacyBaselineAgentUnknownKey(unscannedAgentId); + mergedBaselines[unknownKey] = LEGACY_BASELINE_UNKNOWN; + legacyBaselineBySlotKey.set(unknownKey, LEGACY_BASELINE_UNKNOWN); + } + } else { + const { newBaselines, hasUpdates, readError } = yield* recordDivergingInMemory( + disk.baselines, + ); + if (readError) return false; + if (!hasUpdates) { + legacyBaselineDiscoveryIncomplete = false; + return true; + } + mergedBaselines = { ...disk.baselines, ...newBaselines }; + } + if (!(yield* isLockOwned)) { + yield* Effect.logDebug( + "Lost ACP Registry legacy baselines lock before writing; keeping existing disk registry cache.", + ); + return false; + } + return yield* writeLegacyBaselinesAtomically(mergedBaselines).pipe( + Effect.tap(() => + Effect.sync(() => { + legacyBaselineDiscoveryIncomplete = false; + }), + ), + Effect.as(true), + Effect.catch(() => + Effect.logDebug( + "Could not persist ACP Registry legacy baselines; keeping existing disk registry cache.", + ).pipe(Effect.as(false)), + ), + ); + }), + ).pipe( + Effect.catch(() => + preserveAndFail( + initialDisk.status === "ok" ? initialDisk.baselines : {}, + "Could not lock ACP Registry legacy baselines; keeping existing disk registry cache.", + ), + ), + ); + }); + + const refreshRegistry = Effect.fn("AcpRegistryCatalog.refreshRegistry")(function* (options?: { + readonly observedFetchRevision?: number; + readonly observedAttemptRevision?: number; + readonly failureBackoffMs?: number; + readonly coalesceFailure?: boolean; + readonly acceptAnyIndex?: boolean; + }) { + const initialState = yield* Ref.get(registryState); + const startFetchRevision = options?.observedFetchRevision ?? initialState.fetchRevision; + const startAttemptRevision = options?.observedAttemptRevision ?? initialState.attemptRevision; + const failureBackoffMs = options?.failureBackoffMs; + const coalesceFailure = options?.coalesceFailure ?? failureBackoffMs !== undefined; + return yield* registrySemaphore.withPermits(1)( + Effect.gen(function* () { + const current = yield* Ref.get(registryState); + if ( + current.index !== undefined && + (options?.acceptAnyIndex === true || + current.fetchRevision !== startFetchRevision || + (failureBackoffMs !== undefined && current.attemptRevision !== startAttemptRevision)) + ) { + return { index: current.index, indexRevision: current.indexRevision }; + } + if ( + coalesceFailure && + current.index === undefined && + current.attemptRevision !== startAttemptRevision && + current.lastFailure !== undefined + ) { + return yield* current.lastFailure; + } + if (failureBackoffMs !== undefined && current.failedAtMs !== undefined) { + const now = yield* Clock.currentTimeMillis; + if (now >= current.failedAtMs && now - current.failedAtMs < failureBackoffMs) { + if (current.index !== undefined) { + return { index: current.index, indexRevision: current.indexRevision }; + } + if (current.lastFailure !== undefined) { + return yield* current.lastFailure; + } + } + } + + const startInvalidationGeneration = current.invalidationGeneration; + const result = yield* fetchRegistry().pipe( + Effect.flatMap(({ registry, text }) => + recordLegacyBaselines(current.index, registry).pipe( + Effect.flatMap((baselinesPersisted) => + baselinesPersisted ? writeRegistryCache(text) : Effect.void, + ), + Effect.as({ index: registry, refreshed: true as const }), + ), + ), + Effect.catch((networkError) => + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + yield* Effect.logDebug("ACP Registry index refresh failed", { + reason: networkError.reason, + stage: networkError.stage ?? "unknown", + }); + // Prefer an already-loaded index over disk so a cache-write failure cannot regress it. + const inMemory = (yield* Ref.get(registryState)).index; + if (inMemory !== undefined) { + return { index: inMemory, refreshed: false as const, failure: networkError }; + } + const cached = yield* readCachedRegistry; + if (Option.isSome(cached)) { + return { index: cached.value, refreshed: false as const, failure: networkError }; + } + yield* Ref.update(registryState, (state) => + state.invalidationGeneration === startInvalidationGeneration + ? { + ...state, + failedAtMs: now, + lastFailure: networkError, + attemptRevision: state.attemptRevision + 1, + } + : state, + ); + return yield* networkError; + }), + ), + ); + const now = yield* Clock.currentTimeMillis; + const indexRevision = yield* Ref.modify(registryState, (state) => { + const invalidatedDuringFetch = + state.invalidationGeneration !== startInvalidationGeneration; + const indexChanged = + result.refreshed && + (state.index === undefined || !Equal.equals(result.index, state.index)); + const nextIndexRevision = indexChanged ? state.indexRevision + 1 : state.indexRevision; + return [ + nextIndexRevision, + { + ...state, + index: result.index, + fetchedAtMs: result.refreshed && !invalidatedDuringFetch ? now : undefined, + failedAtMs: !result.refreshed && !invalidatedDuringFetch ? now : undefined, + lastFailure: + !result.refreshed && !invalidatedDuringFetch ? result.failure : undefined, + fetchRevision: + result.refreshed && !invalidatedDuringFetch + ? state.fetchRevision + 1 + : state.fetchRevision, + attemptRevision: invalidatedDuringFetch + ? state.attemptRevision + : state.attemptRevision + 1, + indexRevision: nextIndexRevision, + }, + ] as const; + }); + return { index: result.index, indexRevision }; + }), + ); + }); + + const recentRegistry = Effect.fn("AcpRegistryCatalog.recentRegistry")(function* ( + maxAgeMs = REGISTRY_SEARCH_MAX_AGE_MS, + failureBackoffMs?: number, + ) { + const state = yield* Ref.get(registryState); + const now = yield* Clock.currentTimeMillis; + // A clock moved back makes the stamp untrustworthy, so it counts as stale. + if ( + state.index !== undefined && + state.fetchedAtMs !== undefined && + now >= state.fetchedAtMs && + now - state.fetchedAtMs < maxAgeMs + ) { + return { index: state.index, indexRevision: state.indexRevision }; + } + return yield* refreshRegistry({ + observedFetchRevision: state.fetchRevision, + observedAttemptRevision: state.attemptRevision, + ...(failureBackoffMs === undefined ? {} : { failureBackoffMs }), + }); + }); + + const refreshIndex: AcpRegistryCatalog["Service"]["refreshIndex"] = Effect.fn( + "AcpRegistryCatalog.refreshIndex", + )(function* ({ maxAgeMs, failureBackoffMs }) { + const state = yield* Ref.get(registryState); + const now = yield* Clock.currentTimeMillis; + if ( + state.failedAtMs !== undefined && + now >= state.failedAtMs && + now - state.failedAtMs < failureBackoffMs + ) { + if (state.index !== undefined) return state.indexRevision; + if (state.lastFailure !== undefined) return yield* state.lastFailure; + } + return (yield* recentRegistry(maxAgeMs, failureBackoffMs)).indexRevision; + }); + + const invalidateIndex: AcpRegistryCatalog["Service"]["invalidateIndex"] = Effect.fn( + "AcpRegistryCatalog.invalidateIndex", + )(function* () { + yield* Ref.update(registryState, (state) => ({ + ...state, + fetchedAtMs: undefined, + failedAtMs: undefined, + lastFailure: undefined, + invalidationGeneration: state.invalidationGeneration + 1, + })); + }); + + const loadRegistrySnapshot = Effect.fn("AcpRegistryCatalog.loadRegistry")(function* () { + const current = yield* Ref.get(registryState); + if (current.index !== undefined) { + return { index: current.index, indexRevision: current.indexRevision }; + } + + const cached = yield* readCachedRegistry; + if (Option.isNone(cached)) { + return yield* refreshRegistry({ coalesceFailure: true, acceptAnyIndex: true }); + } + // Publish without waiting on an in-flight refresh, while letting a completed refresh win. + return yield* Ref.modify(registryState, (state) => { + const index = state.index ?? cached.value; + return [ + { index, indexRevision: state.indexRevision }, + state.index !== undefined ? state : { ...state, index }, + ] as const; + }); + }); + + const runCommand = Effect.fn("AcpRegistryCatalog.runCommand")(function* ( + command: string, + args: ReadonlyArray, + options: { + readonly cwd?: string; + readonly env?: NodeJS.ProcessEnv; + readonly timeout?: Duration.Input; + readonly timeoutReason?: AcpRegistryErrorReason; + readonly nonZeroExitReason?: AcpRegistryErrorReason; + readonly truncatedOutputReason?: AcpRegistryErrorReason; + readonly maxStdoutBytes?: number; + } = {}, + ) { + const collect = Effect.gen(function* () { + const resolved = yield* resolveSpawnCommand( + command, + args, + options.env === undefined ? {} : { env: options.env }, + ); + const child = yield* spawner.spawn( + ChildProcess.make(resolved.command, resolved.args, { + ...(options.cwd ? { cwd: options.cwd } : {}), + ...(options.env === undefined ? {} : { env: options.env }), + shell: resolved.shell, + }), + ); + yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore)); + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + collectUint8StreamText({ + stream: child.stdout, + maxBytes: options.maxStdoutBytes ?? MAX_COMMAND_OUTPUT_BYTES, + }), + child.stderr.pipe( + Stream.decodeText(), + Stream.runFold( + () => "", + (tail, text) => `${tail}${text}`.slice(-MAX_COMMAND_ERROR_TAIL_CHARS), + ), + ), + child.exitCode, + ], + { concurrency: "unbounded" }, + ); + if (Number(exitCode) !== 0) { + return yield* new AcpRegistryError({ + reason: options.nonZeroExitReason ?? "install_failed", + detail: `ACP Registry install command '${command}' exited with code ${Number(exitCode)}: ${stderr.trim()}`, + }); + } + // Truncated listings would bypass archive traversal validation. + if (stdout.truncated) { + return yield* new AcpRegistryError({ + reason: options.truncatedOutputReason ?? "archive_invalid", + detail: `ACP Registry install command '${command}' produced more output than expected.`, + }); + } + return stdout.text; + }); + const scoped = collect.pipe( + Effect.scoped, + Effect.mapError((cause) => + isAcpRegistryError(cause) + ? cause + : new AcpRegistryError({ + reason: "install_failed", + detail: `Could not run ACP Registry install command '${command}'.`, + cause, + }), + ), + ); + return yield* options.timeout === undefined + ? scoped + : scoped.pipe( Effect.timeoutOrElse({ duration: options.timeout, orElse: () => Effect.fail( new AcpRegistryError({ - reason: "install_failed", + reason: options.timeoutReason ?? "install_failed", detail: `Timed out running ACP Registry install command '${command}'.`, }), ), @@ -1419,33 +2548,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct return installed.value; }); - const acquireInstallLock = Effect.fn("AcpRegistryCatalog.acquireInstallLock")(function* ( - lockPath: string, - ) { - for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) { - const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe( - Effect.as(true), - Effect.catchIf( - (error) => isAlreadyExists(error), - () => Effect.succeed(false), - ), - ); - if (acquired) return; - const now = yield* Clock.currentTimeMillis; - const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option); - const mtime = Option.flatMap(lockInfo, (info) => info.mtime); - if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) { - yield* fileSystem.remove(lockPath, { force: true }); - continue; - } - yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY); - } - return yield* new AcpRegistryError({ - reason: "install_failed", - detail: `Timed out waiting for ACP Registry install lock ${lockPath}.`, - }); - }); - const assertExecutableInRoot = Effect.fn("AcpRegistryCatalog.assertExecutableInRoot")(function* ( root: string, executablePath: string, @@ -1482,12 +2584,24 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct (candidate) => agent.distribution.binary?.[candidate] === target, ) ?? platformTarget; if (matchedPlatformTarget === undefined || commandSegments === undefined) return undefined; - const installRoot = path.join(agentInstallRoot(agent), matchedPlatformTarget); + const versionRoot = agentInstallRoot(agent); + const installRoot = path.join(versionRoot, matchedPlatformTarget); + const artifactRoot = path.join( + versionRoot, + binaryArtifactDirName(matchedPlatformTarget, target), + ); return { commandSegments, installRoot, + artifactRoot, platformTarget: matchedPlatformTarget, + slotKey: legacyBaselineSlotKey( + agent.id, + encodeURIComponent(agent.version), + matchedPlatformTarget, + ), executablePath: path.join(installRoot, ...commandSegments), + artifactExecutablePath: path.join(artifactRoot, ...commandSegments), }; }; @@ -1498,12 +2612,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct .readDirectory(agentRoot) .pipe(Effect.orElseSucceed((): Array => [])); for (const version of versions) { + const entries = yield* fileSystem + .readDirectory(path.join(agentRoot, version)) + .pipe(Effect.orElseSucceed((): Array => [])); for (const candidateTarget of resolveAcpRegistryPlatformTargetCandidates(platformTarget)) { - if ( - yield* fileSystem - .exists(path.join(agentRoot, version, candidateTarget)) - .pipe(Effect.orElseSucceed(() => false)) - ) { + if (entries.some((entry) => isBinaryPlatformEntry(entry, candidateTarget))) { return true; } } @@ -1512,6 +2625,412 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }, ); + const readMatchingBinaryReceipt = Effect.fn("AcpRegistryCatalog.readMatchingBinaryReceipt")( + function* (root: string, executablePath: string, target: typeof AcpRegistryBinaryTarget.Type) { + if (!(yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false)))) { + return Option.none(); + } + const receiptPath = path.join(root, BINARY_ARTIFACT_RECEIPT_FILENAME); + const rawReceipt = yield* fileSystem.readFileString(receiptPath).pipe(Effect.option); + const decoded = Option.flatMap(rawReceipt, decodeBinaryArtifactReceipt); + return Option.isSome(decoded) && binaryArtifactReceiptMatches(decoded.value, target) + ? Option.some(decoded.value) + : Option.none(); + }, + ); + + const isLegacyBinarySlotEligible = Effect.fn("AcpRegistryCatalog.isLegacyBinarySlotEligible")( + function* ( + paths: NonNullable>, + target: typeof AcpRegistryBinaryTarget.Type, + ) { + if ( + !(yield* fileSystem.exists(paths.executablePath).pipe(Effect.orElseSucceed(() => false))) + ) { + return false; + } + const versionRoot = path.dirname(paths.installRoot); + const versionEntries = yield* fileSystem + .readDirectory(versionRoot) + .pipe(Effect.orElseSucceed((): Array => [])); + for (const entry of versionEntries) { + if (!isBinaryPlatformEntry(entry, paths.platformTarget)) continue; + if ( + yield* fileSystem + .exists(path.join(versionRoot, entry, BINARY_ARTIFACT_RECEIPT_FILENAME)) + .pipe(Effect.orElseSucceed(() => false)) + ) { + return false; + } + } + const currentKey = binaryArtifactIdentityKey(target); + const agentUnknownKey = legacyBaselineAgentUnknownKey(paths.slotKey.split("\0")[0] ?? ""); + const memoryBaseline = legacyBaselineBySlotKey.get(paths.slotKey); + if (memoryBaseline !== undefined) { + return memoryBaseline === currentKey; + } + if (legacyBaselineBySlotKey.get(agentUnknownKey) === LEGACY_BASELINE_UNKNOWN) { + return false; + } + const diskResult = yield* readLegacyBaselinesFile(fileSystem, legacyBaselinesPath); + if (diskResult.status !== "ok") { + return false; + } + const diskBaseline = diskResult.baselines[paths.slotKey]; + if (diskBaseline === undefined) { + if (diskResult.baselines[agentUnknownKey] === LEGACY_BASELINE_UNKNOWN) { + legacyBaselineBySlotKey.set(agentUnknownKey, LEGACY_BASELINE_UNKNOWN); + return false; + } + return !legacyBaselineDiscoveryIncomplete; + } + legacyBaselineBySlotKey.set(paths.slotKey, diskBaseline); + return diskBaseline === currentKey; + }, + ); + + const findMatchingBinarySlot = Effect.fn("AcpRegistryCatalog.findMatchingBinarySlot")(function* ( + paths: NonNullable>, + target: typeof AcpRegistryBinaryTarget.Type, + ) { + const artifactReceipt = yield* readMatchingBinaryReceipt( + paths.artifactRoot, + paths.artifactExecutablePath, + target, + ); + if (Option.isSome(artifactReceipt)) { + return Option.some({ + root: paths.artifactRoot, + executablePath: paths.artifactExecutablePath, + receipt: artifactReceipt.value, + }); + } + const primaryReceipt = yield* readMatchingBinaryReceipt( + paths.installRoot, + paths.executablePath, + target, + ); + if (Option.isSome(primaryReceipt)) { + return Option.some({ + root: paths.installRoot, + executablePath: paths.executablePath, + receipt: primaryReceipt.value, + }); + } + if (yield* isLegacyBinarySlotEligible(paths, target)) { + return Option.some({ + root: paths.installRoot, + executablePath: paths.executablePath, + }); + } + return Option.none<{ + readonly root: string; + readonly executablePath: string; + readonly receipt?: AcpRegistryBinaryArtifactReceipt; + }>(); + }); + + const syncReceiptLaunchOptions = Effect.fn("AcpRegistryCatalog.syncReceiptLaunchOptions")( + function* ( + slot: { + readonly root: string; + readonly receipt?: AcpRegistryBinaryArtifactReceipt; + }, + agent: AcpRegistryAgent, + target: typeof AcpRegistryBinaryTarget.Type, + ) { + if (slot.receipt === undefined) return; + const initialReceipt = slot.receipt; + const hasSidecar = yield* fileSystem + .exists(binaryLaunchOptionsPath) + .pipe(Effect.orElseSucceed(() => false)); + const pendingEntry = pendingLaunchOptionsBySlotRoot.get(slot.root); + const hasMatchingPending = + pendingEntry !== undefined && receiptMatchesInstall(pendingEntry.receipt, initialReceipt); + const receiptRev = initialReceipt.launchOptionsRevision ?? 0; + let fastPathSidecarReadOk = false; + let observedDiskRev = 0; + let observedDiskRecoveryId: string | null = null; + if (!hasSidecar) { + fastPathSidecarReadOk = true; + if (!hasMatchingPending && receiptMatchesLaunchOptions(initialReceipt, target)) { + return; + } + } else { + const diskResult = yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath); + if (diskResult.status === "ok") { + fastPathSidecarReadOk = true; + const diskStored = diskResult.entries[slot.root]; + const diskMatches = receiptMatchesInstall(diskStored, initialReceipt); + observedDiskRev = diskMatches ? (diskStored.launchOptionsRevision ?? 0) : 0; + observedDiskRecoveryId = diskMatches + ? (diskStored.launchOptionsRecoveryId ?? null) + : null; + if (!hasMatchingPending) { + if (diskStored === undefined && receiptMatchesLaunchOptions(initialReceipt, target)) { + return; + } + if ( + diskMatches && + observedDiskRev > receiptRev && + receiptMatchesLaunchOptions(diskStored, target) + ) { + return; + } + } + } + } + + const receiptPath = path.join(slot.root, BINARY_ARTIFACT_RECEIPT_FILENAME); + type PendingBase = { + readonly baseReceiptRevision: number; + readonly baseDurableRevision: number; + readonly baseRecoveryId: string | null; + }; + const buildLaunchOptionsReceipt = ( + baseReceipt: AcpRegistryBinaryArtifactReceipt, + revision?: number, + recoveryId?: string | null, + ): AcpRegistryBinaryArtifactReceipt => ({ + version: agent.version, + archive: target.archive, + cmd: target.cmd, + sha256: target.sha256 ?? null, + ...(target.args && target.args.length > 0 ? { args: [...target.args] } : {}), + ...(target.env && Object.keys(target.env).length > 0 ? { env: { ...target.env } } : {}), + ...(revision !== undefined ? { launchOptionsRevision: revision } : {}), + ...(recoveryId ? { launchOptionsRecoveryId: recoveryId } : {}), + ...(baseReceipt.installId !== undefined ? { installId: baseReceipt.installId } : {}), + }); + const recordPending = (baseReceipt: AcpRegistryBinaryArtifactReceipt, base: PendingBase) => { + pendingLaunchOptionsBySlotRoot.set(slot.root, { + ...base, + receipt: buildLaunchOptionsReceipt(baseReceipt), + }); + }; + // Keep baseDurableRevision and baseRecoveryId paired from the same observation/chain so a + // pre-repair sidecar revision never gates a newer receipt or post-repair sidecar chain. + const resolvePendingBaseOnUnreadableSidecar = ( + baseReceiptRev: number, + priorPending: PendingBase | undefined, + ): PendingBase => { + if (fastPathSidecarReadOk && observedDiskRev > baseReceiptRev) { + return { + baseReceiptRevision: baseReceiptRev, + baseDurableRevision: observedDiskRev, + baseRecoveryId: observedDiskRecoveryId, + }; + } + if (priorPending !== undefined && baseReceiptRev <= priorPending.baseReceiptRevision) { + return priorPending; + } + return { + baseReceiptRevision: baseReceiptRev, + baseDurableRevision: baseReceiptRev, + baseRecoveryId: null, + }; + }; + const recordPendingForInitialReceipt = () => { + const currentPending = pendingLaunchOptionsBySlotRoot.get(slot.root); + const matchingPending = + currentPending !== undefined && + receiptMatchesInstall(currentPending.receipt, initialReceipt) + ? currentPending + : undefined; + recordPending( + initialReceipt, + resolvePendingBaseOnUnreadableSidecar( + receiptRev, + matchingPending ?? (hasMatchingPending ? pendingEntry : undefined), + ), + ); + }; + yield* withBinaryLaunchOptionsLock((isLockOwned) => + Effect.gen(function* () { + const freshReceiptRead = yield* Effect.result(fileSystem.readFileString(receiptPath)); + if (Result.isFailure(freshReceiptRead)) { + if (freshReceiptRead.failure.reason._tag === "NotFound") { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + } else { + recordPendingForInitialReceipt(); + } + return; + } + const decodedFreshReceipt = decodeBinaryArtifactReceipt(freshReceiptRead.success); + if ( + Option.isNone(decodedFreshReceipt) || + !receiptMatchesInstall(decodedFreshReceipt.value, initialReceipt) + ) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + return; + } + const freshReceipt = decodedFreshReceipt.value; + const freshReceiptRev = freshReceipt.launchOptionsRevision ?? 0; + const currentPending = pendingLaunchOptionsBySlotRoot.get(slot.root); + const matchingPending = + currentPending !== undefined && + receiptMatchesInstall(currentPending.receipt, freshReceipt) + ? currentPending + : undefined; + const diskResult = yield* readBinaryLaunchOptionsFile( + fileSystem, + binaryLaunchOptionsPath, + ); + if (diskResult.status === "io_error") { + // Never treat an unreadable sidecar as absent or allocate below it; keep the target + // pending until the sidecar can be read and reconciled under the lock. + recordPending( + freshReceipt, + resolvePendingBaseOnUnreadableSidecar(freshReceiptRev, matchingPending), + ); + return; + } + const isCorrupt = diskResult.status === "corrupt"; + const diskEntries = isCorrupt ? {} : diskResult.entries; + const diskStored = diskEntries[slot.root]; + const diskMatches = receiptMatchesInstall(diskStored, freshReceipt); + const freshDiskRev = diskMatches ? (diskStored.launchOptionsRevision ?? 0) : 0; + const sidecarIsAuthoritative = + !isCorrupt && diskMatches && freshDiskRev > freshReceiptRev; + const currentSidecarRecoveryId = sidecarIsAuthoritative + ? (diskStored.launchOptionsRecoveryId ?? null) + : null; + if (!isCorrupt && receiptMatchesLaunchOptions(freshReceipt, target)) { + if (diskStored === undefined) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + return; + } + if (freshDiskRev <= freshReceiptRev) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + if (!(yield* isLockOwned)) return; + const { [slot.root]: _removed, ...rest } = diskEntries; + yield* writeJsonFileAtomically(binaryLaunchOptionsPath, rest).pipe(Effect.ignore); + return; + } + } + if ( + diskMatches && + freshDiskRev > freshReceiptRev && + receiptMatchesLaunchOptions(diskStored, target) + ) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + return; + } + const allocationBaseRev = Math.max( + freshReceiptRev, + observedDiskRev, + freshDiskRev, + matchingPending?.baseDurableRevision ?? 0, + ); + const nextRevision = allocationBaseRev + 1; + const lockedPendingBase = (): PendingBase => + sidecarIsAuthoritative + ? { + baseReceiptRevision: freshReceiptRev, + baseDurableRevision: freshDiskRev, + baseRecoveryId: currentSidecarRecoveryId, + } + : { + baseReceiptRevision: freshReceiptRev, + baseDurableRevision: freshReceiptRev, + baseRecoveryId: null, + }; + if (!(yield* isLockOwned)) { + if (isCorrupt && receiptMatchesLaunchOptions(freshReceipt, target)) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + } else { + recordPending(freshReceipt, lockedPendingBase()); + } + return; + } + const receiptWrite = yield* Effect.result( + random.uuidV4().pipe( + Effect.flatMap((id) => { + const temporaryPath = `${receiptPath}.${process.pid}-${id}.tmp`; + return fileSystem + .writeFileString( + temporaryPath, + encodeBinaryArtifactReceipt(agent, target, { + launchOptionsRevision: nextRevision, + ...(freshReceipt.installId !== undefined + ? { installId: freshReceipt.installId } + : {}), + }), + ) + .pipe( + Effect.andThen(fileSystem.rename(temporaryPath, receiptPath)), + Effect.ensuring( + fileSystem.remove(temporaryPath, { force: true }).pipe(Effect.ignore), + ), + ); + }), + ), + ); + if (Result.isSuccess(receiptWrite)) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + if (isCorrupt || diskStored !== undefined) { + if (!(yield* isLockOwned)) return; + if (isCorrupt) { + yield* fileSystem + .copyFile(binaryLaunchOptionsPath, `${binaryLaunchOptionsPath}.corrupt`) + .pipe(Effect.ignore); + } + const { [slot.root]: _removed, ...rest } = diskEntries; + yield* writeJsonFileAtomically(binaryLaunchOptionsPath, rest).pipe(Effect.ignore); + } + return; + } + // If updating the receipt inside tools/ failed (e.g., read-only install directory or file + // lock), persist the updated launch options in registry cache storage so fallback still + // restores the last-resolved args and env even across restarts. + if (!(yield* isLockOwned)) { + if (isCorrupt && receiptMatchesLaunchOptions(freshReceipt, target)) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + } else { + recordPending(freshReceipt, lockedPendingBase()); + } + return; + } + if (isCorrupt) { + yield* fileSystem + .copyFile(binaryLaunchOptionsPath, `${binaryLaunchOptionsPath}.corrupt`) + .pipe(Effect.ignore); + } + // Stamp a fresh recovery ID whenever starting a new sidecar chain (including after + // corrupt repair by this or any other slot) so older higher-base pending options yield. + const nextSidecarRecoveryId = + sidecarIsAuthoritative && currentSidecarRecoveryId !== null + ? currentSidecarRecoveryId + : yield* random.uuidV4(); + const updatedSidecarReceipt = buildLaunchOptionsReceipt( + freshReceipt, + nextRevision, + nextSidecarRecoveryId, + ); + const sidecarWrite = yield* Effect.result( + writeJsonFileAtomically(binaryLaunchOptionsPath, { + ...diskEntries, + [slot.root]: updatedSidecarReceipt, + }), + ); + if (Result.isSuccess(sidecarWrite)) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + } else if (isCorrupt && receiptMatchesLaunchOptions(freshReceipt, target)) { + pendingLaunchOptionsBySlotRoot.delete(slot.root); + } else { + recordPending(freshReceipt, lockedPendingBase()); + } + }), + ).pipe( + Effect.catch(() => + Effect.sync(() => { + recordPendingForInitialReceipt(); + }), + ), + ); + }, + ); + const installBinary = Effect.fn("AcpRegistryCatalog.installBinary")(function* ( agent: AcpRegistryAgent, target: typeof AcpRegistryBinaryTarget.Type, @@ -1529,19 +3048,28 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct detail: `ACP Registry agent ${agent.id} declares an unsafe command path '${target.cmd}'.`, }); } - const { commandSegments, installRoot, executablePath } = paths; - if (yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false))) { - return yield* assertExecutableInRoot(installRoot, executablePath).pipe( - Effect.mapError((cause) => - isAcpRegistryError(cause) - ? cause - : new AcpRegistryError({ - reason: "install_failed", - detail: `Could not validate cached ACP Registry agent ${agent.id}.`, - cause, - }), + const { commandSegments, installRoot, artifactRoot } = paths; + const validateCachedSlot = (slot: { + readonly root: string; + readonly executablePath: string; + readonly receipt?: AcpRegistryBinaryArtifactReceipt; + }) => + assertExecutableInRoot(slot.root, slot.executablePath).pipe( + Effect.tap(() => syncReceiptLaunchOptions(slot, agent, target)), + Effect.mapError( + (cause) => + new AcpRegistryError({ + reason: "install_failed", + detail: isAcpRegistryError(cause) + ? cause.detail + : `Could not validate cached ACP Registry agent ${agent.id}.`, + cause, + }), ), ); + const cachedSlot = yield* findMatchingBinarySlot(paths, target); + if (Option.isSome(cachedSlot)) { + return yield* validateCachedSlot(cachedSlot.value); } yield* fileSystem.makeDirectory(path.dirname(installRoot), { recursive: true }).pipe( @@ -1555,151 +3083,235 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ), ); const lockPath = `${installRoot}.lock`; - yield* acquireInstallLock(lockPath).pipe( - Effect.mapError((cause) => - isAcpRegistryError(cause) - ? cause - : new AcpRegistryError({ - reason: "install_failed", - detail: `Could not acquire install lock for ACP Registry agent ${agent.id}.`, - cause, - }), - ), - ); - return yield* Effect.gen(function* () { - if (yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false))) { - return yield* assertExecutableInRoot(installRoot, executablePath); - } - const temporaryRoot = yield* fileSystem.makeTempDirectoryScoped({ - directory: path.dirname(installRoot), - prefix: `.${agent.id}-install-`, - }); - const extractionRoot = path.join(temporaryRoot, "extracted"); - yield* fileSystem.makeDirectory(extractionRoot, { recursive: true }); - const kind = archiveKind(target.archive); - const archivePath = path.join(temporaryRoot, archiveFileName(kind)); - const response = yield* httpClient.execute(HttpClientRequest.get(target.archive)).pipe( - Effect.flatMap(HttpClientResponse.filterStatusOk), - Effect.mapError( - (cause) => - new AcpRegistryError({ - reason: "download_failed", - detail: `Could not download ACP Registry agent ${agent.id} ${agent.version}.`, - cause, - }), - ), - Effect.timeoutOrElse({ - duration: ARCHIVE_REQUEST_TIMEOUT, - orElse: () => - Effect.fail( + return yield* withFileLock(lockPath, () => + Effect.gen(function* () { + const lockedSlot = yield* findMatchingBinarySlot(paths, target); + if (Option.isSome(lockedSlot)) { + return yield* validateCachedSlot(lockedSlot.value); + } + const primaryExists = yield* fileSystem + .exists(installRoot) + .pipe(Effect.orElseSucceed(() => false)); + // Keep an existing primary directory intact for active sessions (and Windows file locks) + // by installing same-version replacements into an immutable artifact-scoped sibling slot. + const destinationRoot = primaryExists ? artifactRoot : installRoot; + const destinationExecutable = path.join(destinationRoot, ...commandSegments); + const temporaryRoot = yield* fileSystem.makeTempDirectoryScoped({ + directory: path.dirname(installRoot), + prefix: `.${agent.id}-install-`, + }); + if ( + destinationRoot === artifactRoot && + (yield* fileSystem.exists(artifactRoot).pipe(Effect.orElseSucceed(() => false))) + ) { + // Under a freshly acquired lock after findMatchingBinarySlot returned None, an existing + // artifactRoot is a broken/incomplete slot (e.g., deleted executable). Move it aside + // before downloading; fail fast if moving fails (e.g., locked files on Windows) instead + // of wasting a full archive download. + yield* fileSystem + .rename(artifactRoot, path.join(temporaryRoot, "replaced-broken-slot")) + .pipe( + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.void, + ), + Effect.mapError( + (cause) => + new AcpRegistryError({ + reason: "install_failed", + detail: `Could not replace broken ACP Registry install slot for ${agent.id}.`, + cause, + }), + ), + ); + } + const extractionRoot = path.join(temporaryRoot, "extracted"); + yield* fileSystem.makeDirectory(extractionRoot, { recursive: true }); + const kind = archiveKind(target.archive); + const archivePath = path.join(temporaryRoot, archiveFileName(kind)); + const response = yield* httpClient.execute(HttpClientRequest.get(target.archive)).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.mapError( + (cause) => new AcpRegistryError({ reason: "download_failed", - detail: `Timed out downloading ACP Registry agent ${agent.id} ${agent.version}.`, - }), - ), - }), - ); - // Stream hashes to avoid buffering large archives; Effect Crypto requires a whole buffer. - const hash = sha256.create(); - let downloadedBytes = 0; - yield* response.stream.pipe( - Stream.tap((chunk) => { - if (downloadedBytes + chunk.byteLength > MAX_ARCHIVE_BYTES) { - return Effect.fail( - new AcpRegistryError({ - reason: "archive_invalid", - detail: `ACP Registry agent ${agent.id} archive exceeds ${MAX_ARCHIVE_BYTES} bytes.`, + detail: `Could not download ACP Registry agent ${agent.id} ${agent.version}.`, + cause, }), + ), + Effect.timeoutOrElse({ + duration: ARCHIVE_REQUEST_TIMEOUT, + orElse: () => + Effect.fail( + new AcpRegistryError({ + reason: "download_failed", + detail: `Timed out downloading ACP Registry agent ${agent.id} ${agent.version}.`, + }), + ), + }), + ); + // Stream hashes to avoid buffering large archives; Effect Crypto requires a whole buffer. + const hash = sha256.create(); + let downloadedBytes = 0; + yield* response.stream.pipe( + Stream.tap((chunk) => { + if (downloadedBytes + chunk.byteLength > MAX_ARCHIVE_BYTES) { + return Effect.fail( + new AcpRegistryError({ + reason: "archive_invalid", + detail: `ACP Registry agent ${agent.id} archive exceeds ${MAX_ARCHIVE_BYTES} bytes.`, + }), + ); + } + downloadedBytes += chunk.byteLength; + hash.update(chunk); + return Effect.void; + }), + Stream.run(fileSystem.sink(archivePath)), + Effect.mapError((cause) => + isAcpRegistryError(cause) + ? cause + : new AcpRegistryError({ + reason: "download_failed", + detail: `Could not save ACP Registry agent ${agent.id} ${agent.version}.`, + cause, + }), + ), + Effect.timeoutOrElse({ + duration: ARCHIVE_REQUEST_TIMEOUT, + orElse: () => + Effect.fail( + new AcpRegistryError({ + reason: "download_failed", + detail: `Timed out reading ACP Registry agent ${agent.id} download.`, + }), + ), + }), + ); + if (target.sha256 !== undefined) { + const actual = Hex.encode(hash.digest()); + if (actual !== target.sha256.toLowerCase()) { + return yield* new AcpRegistryError({ + reason: "checksum_mismatch", + detail: `ACP Registry agent ${agent.id} download did not match its declared SHA-256.`, + }); + } + } + + if (kind === "raw") { + const targetPath = path.join(extractionRoot, ...commandSegments); + yield* fileSystem.makeDirectory(path.dirname(targetPath), { recursive: true }); + yield* fileSystem.rename(archivePath, targetPath); + } else { + const tarCommand = + platformTarget === "windows-aarch64" && + paths.platformTarget === "windows-x86_64" && + kind === "zip" + ? cliArchiveTarCommand(platform, hostEnvironment) + : "tar"; + const listArgs = + kind === "tar_gz" + ? ["-tzf", archivePath] + : kind === "tar_bz2" + ? ["-tjf", archivePath] + : platform === "win32" + ? ["-tf", archivePath] + : undefined; + const listingOptions = { + maxStdoutBytes: MAX_ARCHIVE_LISTING_BYTES, + timeout: ARCHIVE_EXTRACT_TIMEOUT, + timeoutReason: "archive_invalid", + nonZeroExitReason: "archive_invalid", + } as const; + const extractOptions = { + timeout: ARCHIVE_EXTRACT_TIMEOUT, + timeoutReason: "archive_invalid", + nonZeroExitReason: "archive_invalid", + } as const; + const entries = + listArgs === undefined + ? yield* runCommand("unzip", ["-Z1", archivePath], listingOptions) + : yield* runCommand(tarCommand, listArgs, listingOptions); + if (!validateArchiveEntries(entries)) { + return yield* new AcpRegistryError({ + reason: "archive_invalid", + detail: `ACP Registry agent ${agent.id} archive contains an unsafe path.`, + }); + } + if (kind === "zip" && platform !== "win32") { + yield* runCommand("unzip", ["-q", archivePath, "-d", extractionRoot], extractOptions); + } else { + const extractFlag = kind === "tar_gz" ? "-xzf" : kind === "tar_bz2" ? "-xjf" : "-xf"; + yield* runCommand( + tarCommand, + [extractFlag, archivePath, "-C", extractionRoot], + extractOptions, ); } - downloadedBytes += chunk.byteLength; - hash.update(chunk); - return Effect.void; - }), - Stream.run(fileSystem.sink(archivePath)), - Effect.mapError((cause) => - isAcpRegistryError(cause) - ? cause - : new AcpRegistryError({ - reason: "download_failed", - detail: `Could not save ACP Registry agent ${agent.id} ${agent.version}.`, - cause, - }), - ), - Effect.timeoutOrElse({ - duration: ARCHIVE_REQUEST_TIMEOUT, - orElse: () => - Effect.fail( - new AcpRegistryError({ - reason: "download_failed", - detail: `Timed out reading ACP Registry agent ${agent.id} download.`, - }), - ), - }), - ); - if (target.sha256 !== undefined) { - const actual = Hex.encode(hash.digest()); - if (actual !== target.sha256.toLowerCase()) { - return yield* new AcpRegistryError({ - reason: "checksum_mismatch", - detail: `ACP Registry agent ${agent.id} download did not match its declared SHA-256.`, - }); } - } - if (kind === "raw") { - const targetPath = path.join(extractionRoot, ...commandSegments); - yield* fileSystem.makeDirectory(path.dirname(targetPath), { recursive: true }); - yield* fileSystem.rename(archivePath, targetPath); - } else { - const tarCommand = - platformTarget === "windows-aarch64" && - paths.platformTarget === "windows-x86_64" && - kind === "zip" - ? cliArchiveTarCommand(platform, hostEnvironment) - : "tar"; - const listArgs = - kind === "tar_gz" - ? ["-tzf", archivePath] - : kind === "tar_bz2" - ? ["-tjf", archivePath] - : platform === "win32" - ? ["-tf", archivePath] - : undefined; - const listingOptions = { maxStdoutBytes: MAX_ARCHIVE_LISTING_BYTES }; - const entries = - listArgs === undefined - ? yield* runCommand("unzip", ["-Z1", archivePath], listingOptions) - : yield* runCommand(tarCommand, listArgs, listingOptions); - if (!validateArchiveEntries(entries)) { + const stagedExecutable = path.join(extractionRoot, ...commandSegments); + if (!(yield* fileSystem.exists(stagedExecutable).pipe(Effect.orElseSucceed(() => false)))) { return yield* new AcpRegistryError({ reason: "archive_invalid", - detail: `ACP Registry agent ${agent.id} archive contains an unsafe path.`, + detail: `ACP Registry archive for ${agent.id} did not contain '${target.cmd}'.`, }); } - if (kind === "zip" && platform !== "win32") { - yield* runCommand("unzip", ["-q", archivePath, "-d", extractionRoot]); - } else { - const extractFlag = kind === "tar_gz" ? "-xzf" : kind === "tar_bz2" ? "-xjf" : "-xf"; - yield* runCommand(tarCommand, [extractFlag, archivePath, "-C", extractionRoot]); + yield* assertExecutableInRoot(extractionRoot, stagedExecutable, { makeExecutable: true }); + // Stamp a fresh installId so stale in-memory or sidecar launch options from any prior + // broken install at destinationRoot can never match or outrank the new receipt. + const installId = yield* random.uuidV4(); + yield* fileSystem + .writeFileString( + path.join(extractionRoot, BINARY_ARTIFACT_RECEIPT_FILENAME), + encodeBinaryArtifactReceipt(agent, target, { installId }), + { flag: "wx" }, + ) + .pipe( + Effect.mapError((cause) => + isAlreadyExists(cause) + ? new AcpRegistryError({ + reason: "archive_invalid", + detail: `ACP Registry archive for ${agent.id} contains a reserved '${BINARY_ARTIFACT_RECEIPT_FILENAME}' entry.`, + cause, + }) + : new AcpRegistryError({ + reason: "install_failed", + detail: `Could not write ACP Registry artifact receipt for ${agent.id}.`, + cause, + }), + ), + ); + // Recheck right before promotion in case a stale-lock takeover let another installer publish + // a valid receipt-matching slot while this staging download was in flight. Never remove an + // existing destinationRoot before rename so a concurrent publisher's directory cannot be deleted. + const concurrentSlot = yield* findMatchingBinarySlot(paths, target); + if (Option.isSome(concurrentSlot)) { + const validated = yield* assertExecutableInRoot( + concurrentSlot.value.root, + concurrentSlot.value.executablePath, + ).pipe(Effect.option); + if (Option.isSome(validated)) { + return validated.value; + } } - } - - const stagedExecutable = path.join(extractionRoot, ...commandSegments); - if (!(yield* fileSystem.exists(stagedExecutable).pipe(Effect.orElseSucceed(() => false)))) { - return yield* new AcpRegistryError({ - reason: "archive_invalid", - detail: `ACP Registry archive for ${agent.id} did not contain '${target.cmd}'.`, - }); - } - yield* assertExecutableInRoot(extractionRoot, stagedExecutable, { makeExecutable: true }); - yield* fileSystem.remove(installRoot, { recursive: true, force: true }); - yield* fileSystem.rename(extractionRoot, installRoot); - return yield* assertExecutableInRoot(installRoot, executablePath); - }).pipe( - Effect.scoped, - Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)), + return yield* fileSystem.rename(extractionRoot, destinationRoot).pipe( + Effect.andThen(() => assertExecutableInRoot(destinationRoot, destinationExecutable)), + Effect.catch((renameError) => + findMatchingBinarySlot(paths, target).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.fail(renameError), + onSome: (slot) => assertExecutableInRoot(slot.root, slot.executablePath), + }), + ), + Effect.mapError(() => renameError), + ), + ), + ); + }).pipe(Effect.scoped), + ).pipe( Effect.mapError((cause) => isAcpRegistryError(cause) ? cause @@ -1746,7 +3358,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const search: AcpRegistryCatalog["Service"]["search"] = Effect.fn("AcpRegistryCatalog.search")( function* (input) { - const registry = yield* recentRegistry(); + const { index: registry } = yield* recentRegistry(); const ranked = []; const managerAvailability = new Map(); for (const agent of registry.agents) { @@ -1798,7 +3410,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const prepare: AcpRegistryCatalog["Service"]["prepare"] = Effect.fn("AcpRegistryCatalog.prepare")( function* (input) { - const registry = yield* refreshRegistry(); + const { index: registry } = yield* refreshRegistry(); const agent = yield* findAgent(registry, input.agentId); const distribution = yield* compatibleDistribution(agent, "auto"); if (distribution.kind === "binary") { @@ -1850,17 +3462,18 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct } const agentId = settings.agentId.trim(); if (agentId.length === 0) return { status: "unconfigured" } as const; - const registry = yield* loadRegistry(); + const { index: registry, indexRevision } = yield* loadRegistrySnapshot(); const agent = registry.agents.find((candidate) => candidate.id === agentId); - if (agent === undefined) return { status: "not_found", agentId } as const; + if (agent === undefined) return { status: "not_found", agentId, indexRevision } as const; const documentationUrl = agent.website ?? agent.repository; + const icon = agent.icon; const distribution = resolveAcpRegistryDistribution({ agent, preference: settings.distribution, platformTarget, }); if (distribution === undefined) { - return { status: "unsupported", agentId, version: agent.version } as const; + return { status: "unsupported", agentId, version: agent.version, indexRevision } as const; } const commandOverride = settings.commandPath.trim(); @@ -1873,6 +3486,13 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct agentId, version: null, distribution: distribution.kind, + launchIdentity: registryLaunchIdentity({ + version: null, + distribution, + commandOverride, + }), + indexRevision, + ...(icon ? { icon } : {}), ...(documentationUrl ? { documentationUrl } : {}), } as const) : ({ @@ -1881,6 +3501,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct version: agent.version, distribution: distribution.kind, runner: commandOverride, + indexRevision, } as const); } @@ -1889,23 +3510,30 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct Effect.gen(function* () { const paths = binaryPaths(agent, distribution.binaryTarget!); if (paths === undefined) { - return { status: "unsupported", agentId, version: agent.version } as const; + return { + status: "unsupported", + agentId, + version: agent.version, + indexRevision, + } as const; } yield* consumePreparedBinaryReservation(agent.id); - const exists = yield* fileSystem - .exists(paths.executablePath) - .pipe(Effect.orElseSucceed(() => false)); + const activeSlot = yield* findMatchingBinarySlot(paths, distribution.binaryTarget!); // Any prepared version keeps the agent ready; resolve installs the current one on demand. - if (!exists && !(yield* hasInstalledBinaryVersion(agent.id))) { + if (Option.isNone(activeSlot) && !(yield* hasInstalledBinaryVersion(agent.id))) { return { status: "unprepared", agentId, version: agent.version, distribution: "binary", + indexRevision, } as const; } - if (exists) { - yield* assertExecutableInRoot(paths.installRoot, paths.executablePath).pipe( + if (Option.isSome(activeSlot)) { + yield* assertExecutableInRoot( + activeSlot.value.root, + activeSlot.value.executablePath, + ).pipe( Effect.mapError((cause) => isAcpRegistryError(cause) ? cause @@ -1922,6 +3550,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct agentId, version: agent.version, distribution: "binary", + launchIdentity: registryLaunchIdentity({ version: agent.version, distribution }), + indexRevision, + ...(icon ? { icon } : {}), ...(documentationUrl ? { documentationUrl } : {}), } as const; }), @@ -1937,6 +3568,9 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct agentId, version: agent.version, distribution: distribution.kind, + launchIdentity: registryLaunchIdentity({ version: agent.version, distribution }), + indexRevision, + ...(icon ? { icon } : {}), ...(documentationUrl ? { documentationUrl } : {}), } as const) : ({ @@ -1945,15 +3579,223 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct version: agent.version, distribution: distribution.kind, runner, + indexRevision, } as const); }, ); + const buildResolvedRegistrySpawn = Effect.fn("AcpRegistryCatalog.buildResolvedRegistrySpawn")( + function* (input: { + readonly agent: AcpRegistryAgent; + readonly distribution: ResolvedAcpRegistryDistribution; + readonly command: string; + readonly commandBinDirectory?: string; + readonly commandOverride?: string; + readonly cwd: string; + readonly effectiveEnvironment: NodeJS.ProcessEnv; + readonly indexRevision?: number; + readonly fallback?: boolean; + readonly failedTarget?: AcpRegistryFailedTarget; + }) { + const baseSpawnEnvironment = { + ...input.effectiveEnvironment, + ...input.distribution.env, + }; + const pathEnvironment = + input.commandBinDirectory === undefined + ? baseSpawnEnvironment + : withPreferredPath(baseSpawnEnvironment, input.commandBinDirectory, platform); + const spawnEnvironment = + runtimeTempDir !== undefined && UNPACKING_AGENT_IDS.has(input.agent.id) + ? yield* acquireRuntimeTempEnvironment(runtimeTempDir, pathEnvironment) + : pathEnvironment; + return { + agent: input.agent, + distribution: input.distribution.kind, + launchIdentity: registryLaunchIdentity({ + version: input.commandOverride ? null : input.agent.version, + distribution: input.distribution, + ...(input.commandOverride ? { commandOverride: input.commandOverride } : {}), + }), + ...(input.indexRevision === undefined ? {} : { indexRevision: input.indexRevision }), + ...(input.fallback ? { fallback: true } : {}), + ...(input.failedTarget === undefined ? {} : { failedTarget: input.failedTarget }), + spawn: { + command: input.command, + args: input.distribution.args, + cwd: input.cwd, + env: spawnEnvironment, + }, + } satisfies ResolvedAcpRegistryAgent; + }, + ); + + const resolveFallbackInstalledBinary = Effect.fn( + "AcpRegistryCatalog.resolveFallbackInstalledBinary", + )(function* ( + settings: AcpRegistrySettings, + cwd: string, + environment: NodeJS.ProcessEnv | undefined, + registry: AcpRegistryIndex, + indexRevision: number, + ) { + if (settings.commandPath.trim().length > 0 || platformTarget === undefined) { + return Option.none(); + } + const agent = registry.agents.find((candidate) => candidate.id === settings.agentId.trim()); + if (agent === undefined) return Option.none(); + const distribution = resolveAcpRegistryDistribution({ + agent, + preference: settings.distribution, + platformTarget, + }); + if (distribution === undefined || distribution.kind !== "binary") { + return Option.none(); + } + const failedTarget: AcpRegistryFailedTarget = { + version: agent.version, + launchIdentity: registryLaunchIdentity({ version: agent.version, distribution }), + indexRevision, + }; + const effectiveEnvironment = environment ?? hostEnvironment; + return yield* withInstallPermit(agent.id)( + Effect.gen(function* () { + // Fall back only to receipted versions strictly older than the registry's current version + // so failed upgrades do not strand the agent and upstream rollbacks never run a newer build. + const agentRoot = path.join(installsDirectory, agent.id); + const versions = (yield* fileSystem + .readDirectory(agentRoot) + .pipe(Effect.orElseSucceed((): Array => []))) + .filter( + (entry) => compareRegistryVersions(safeDecodeVersionDir(entry), agent.version) < 0, + ) + .toSorted((left, right) => + compareRegistryVersions(safeDecodeVersionDir(right), safeDecodeVersionDir(left)), + ); + // Read the launch-options sidecar BEFORE reading slot receipts so a concurrent writer that + // publishes a newer receipt and then prunes the older sidecar cannot leave fallback seeing + // both the older receipt and the post-prune empty sidecar. + const diskOverrideResult = (yield* fileSystem + .exists(binaryLaunchOptionsPath) + .pipe(Effect.orElseSucceed(() => false))) + ? yield* readBinaryLaunchOptionsFile(fileSystem, binaryLaunchOptionsPath) + : ({ status: "ok", entries: {} } as const); + for (const versionDir of versions) { + const versionRoot = path.join(agentRoot, versionDir); + const entries = yield* fileSystem + .readDirectory(versionRoot) + .pipe(Effect.orElseSucceed((): Array => [])); + for (const candidateTarget of resolveAcpRegistryPlatformTargetCandidates( + platformTarget, + )) { + const matchedDirs = entries.filter((entry) => + isBinaryPlatformEntry(entry, candidateTarget), + ); + const candidatesWithMtime = yield* Effect.forEach(matchedDirs, (entry) => { + const dir = path.join(versionRoot, entry); + return fileSystem.stat(dir).pipe( + Effect.map((info) => ({ + dir, + entry, + isPrimary: entry === candidateTarget, + mtimeMs: Option.isSome(info.mtime) ? info.mtime.value.getTime() : 0, + })), + Effect.orElseSucceed(() => ({ + dir, + entry, + isPrimary: entry === candidateTarget, + mtimeMs: 0, + })), + ); + }); + candidatesWithMtime.sort( + (left, right) => + right.mtimeMs - left.mtimeMs || + Number(left.isPrimary) - Number(right.isPrimary) || + left.entry.localeCompare(right.entry), + ); + for (const { dir } of candidatesWithMtime) { + const rawReceipt = yield* fileSystem + .readFileString(path.join(dir, BINARY_ARTIFACT_RECEIPT_FILENAME)) + .pipe(Effect.option); + const decoded = Option.flatMap(rawReceipt, decodeBinaryArtifactReceipt); + if (Option.isNone(decoded)) continue; + const receipt = decoded.value; + const commandSegments = normalizeRegistryCommandPath(receipt.cmd); + if (commandSegments === undefined) continue; + const executablePath = path.join(dir, ...commandSegments); + if ( + !(yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false))) + ) { + continue; + } + const validated = yield* assertExecutableInRoot(dir, executablePath).pipe( + Effect.option, + ); + if (Option.isNone(validated)) continue; + const diskOverride = + diskOverrideResult.status === "ok" ? diskOverrideResult.entries[dir] : undefined; + const durableFromSidecar = + receiptMatchesInstall(diskOverride, receipt) && + (diskOverride.launchOptionsRevision ?? 0) > (receipt.launchOptionsRevision ?? 0); + const durableReceipt = durableFromSidecar ? diskOverride : receipt; + const pendingOverride = pendingLaunchOptionsBySlotRoot.get(dir); + const usePendingOverride = + pendingOverride !== undefined && + receiptMatchesInstall(pendingOverride.receipt, receipt) && + (receipt.launchOptionsRevision ?? 0) <= pendingOverride.baseReceiptRevision && + (durableReceipt.launchOptionsRevision ?? 0) <= + pendingOverride.baseDurableRevision && + (!durableFromSidecar || + (durableReceipt.launchOptionsRecoveryId ?? null) === + pendingOverride.baseRecoveryId); + if (pendingOverride !== undefined && !usePendingOverride) { + pendingLaunchOptionsBySlotRoot.delete(dir); + } + const effectiveReceipt = usePendingOverride + ? pendingOverride.receipt + : durableReceipt; + const fallbackVersion = effectiveReceipt.version ?? safeDecodeVersionDir(versionDir); + const fallbackArgs = effectiveReceipt.args ?? []; + const fallbackEnv = effectiveReceipt.env ?? {}; + const fallbackTarget: typeof AcpRegistryBinaryTarget.Type = { + archive: receipt.archive, + cmd: receipt.cmd, + ...(receipt.sha256 ? { sha256: receipt.sha256 } : {}), + ...(fallbackArgs.length > 0 ? { args: fallbackArgs } : {}), + ...(Object.keys(fallbackEnv).length > 0 ? { env: fallbackEnv } : {}), + }; + const fallbackDistribution: ResolvedAcpRegistryDistribution = { + kind: "binary", + binaryTarget: fallbackTarget, + args: fallbackArgs, + env: fallbackEnv, + }; + const fallbackAgent: AcpRegistryAgent = { ...agent, version: fallbackVersion }; + const resolved = yield* buildResolvedRegistrySpawn({ + agent: fallbackAgent, + distribution: fallbackDistribution, + command: validated.value, + cwd, + effectiveEnvironment, + fallback: true, + failedTarget, + }); + return Option.some(resolved); + } + } + } + return Option.none(); + }), + ); + }); + const resolveWithRegistry = Effect.fn("AcpRegistryCatalog.resolveWithRegistry")(function* ( settings: AcpRegistrySettings, cwd: string, environment: NodeJS.ProcessEnv | undefined, registry: AcpRegistryIndex, + indexRevision: number, ) { const agentId = settings.agentId.trim(); if (agentId.length === 0) { @@ -1966,7 +3808,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const distribution = yield* compatibleDistribution(agent, settings.distribution); let command: string; - let args: ReadonlyArray; let commandBinDirectory: string | undefined; const effectiveEnvironment = environment ?? hostEnvironment; const commandOverride = settings.commandPath.trim(); @@ -1979,7 +3820,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); } command = resolvedOverride; - args = distribution.args; } else if (distribution.kind === "npx" || distribution.kind === "uvx") { const installed = yield* withInstallPermit(agent.id)( ensureGlobalPackage( @@ -1990,7 +3830,6 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct ), ); command = installed.executablePath; - args = distribution.args; commandBinDirectory = installed.binDirectory; } else { const target = distribution.binaryTarget!; @@ -1999,32 +3838,18 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct Effect.tap(() => consumePreparedBinaryReservation(agent.id)), ), ); - args = distribution.args; } - const baseSpawnEnvironment = { - ...effectiveEnvironment, - ...distribution.env, - }; - const pathEnvironment = - commandBinDirectory === undefined - ? baseSpawnEnvironment - : withPreferredPath(baseSpawnEnvironment, commandBinDirectory, platform); - const spawnEnvironment = - runtimeTempDir !== undefined && UNPACKING_AGENT_IDS.has(agent.id) - ? yield* acquireRuntimeTempEnvironment(runtimeTempDir, pathEnvironment) - : pathEnvironment; - - return { + return yield* buildResolvedRegistrySpawn({ agent, - distribution: distribution.kind, - spawn: { - command, - args, - cwd, - env: spawnEnvironment, - }, - } satisfies ResolvedAcpRegistryAgent; + distribution, + command, + ...(commandBinDirectory === undefined ? {} : { commandBinDirectory }), + ...(commandOverride.length > 0 ? { commandOverride } : {}), + cwd, + effectiveEnvironment, + indexRevision, + }); }); // A cached index can pin a version whose archive was since removed upstream. @@ -2052,18 +3877,109 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct spawn: { command, args: settings.commandArgs, cwd, env, shell: false }, } satisfies ResolvedAcpRegistryAgent; } - const registry = yield* loadRegistry(); - return yield* resolveWithRegistry(settings, cwd, environment, registry).pipe( + const { index: registry, indexRevision } = yield* loadRegistrySnapshot(); + const canFallbackOnError = (reason: AcpRegistryErrorReason) => + reason === "download_failed" || + reason === "checksum_mismatch" || + reason === "archive_invalid"; + return yield* resolveWithRegistry(settings, cwd, environment, registry, indexRevision).pipe( Effect.catchIf( - (error) => error.reason === "download_failed", + (error) => canFallbackOnError(error.reason), (error) => Effect.gen(function* () { - const latest = yield* refreshRegistry().pipe(Effect.mapError(() => error)); const agentId = settings.agentId.trim(); - const versionIn = (index: AcpRegistryIndex) => - index.agents.find((agent) => agent.id === agentId)?.version; - if (versionIn(latest) === versionIn(registry)) return yield* error; - return yield* resolveWithRegistry(settings, cwd, environment, latest); + const artifactSignatureIn = (index: AcpRegistryIndex) => { + const agent = index.agents.find((candidate) => candidate.id === agentId); + if (agent === undefined) return undefined; + const distribution = resolveAcpRegistryDistribution({ + agent, + preference: settings.distribution, + platformTarget, + }); + if (distribution === undefined) return agent.version; + if (distribution.kind === "binary" && distribution.binaryTarget !== undefined) { + return `${agent.version}\0${binaryArtifactIdentityKey(distribution.binaryTarget)}`; + } + return registryLaunchIdentity({ version: agent.version, distribution }); + }; + let activeRegistry = registry; + let activeRevision = indexRevision; + let activeError = error; + const retryIfSignatureChanged = Effect.fn( + "AcpRegistryCatalog.retryResolveOnIndexChange", + )(function* (candidateRegistry: AcpRegistryIndex, candidateRevision: number) { + if ( + artifactSignatureIn(candidateRegistry) === artifactSignatureIn(activeRegistry) + ) { + return Option.none(); + } + const retried = yield* Effect.result( + resolveWithRegistry( + settings, + cwd, + environment, + candidateRegistry, + candidateRevision, + ), + ); + if (Result.isSuccess(retried)) return Option.some(retried.success); + if (!canFallbackOnError(retried.failure.reason)) { + return yield* retried.failure; + } + activeRegistry = candidateRegistry; + activeRevision = candidateRevision; + activeError = retried.failure; + return Option.none(); + }); + if (error.reason === "download_failed") { + const refreshed = yield* Effect.result( + refreshRegistry({ failureBackoffMs: DOWNLOAD_RETRY_REGISTRY_BACKOFF_MS }), + ); + if (Result.isSuccess(refreshed)) { + const retried = yield* retryIfSignatureChanged( + refreshed.success.index, + refreshed.success.indexRevision, + ); + if (Option.isSome(retried)) return retried.value; + } + } + // Recheck the latest published index (including after any failed retry) so concurrent + // removals, incompatibilities, or fixes are honored before falling back. + for (let attempt = 0; attempt < 3; attempt += 1) { + const latestState = yield* Ref.get(registryState); + if ( + latestState.index === undefined || + latestState.indexRevision <= activeRevision || + artifactSignatureIn(latestState.index) === artifactSignatureIn(activeRegistry) + ) { + break; + } + const retried = yield* retryIfSignatureChanged( + latestState.index, + latestState.indexRevision, + ); + if (Option.isSome(retried)) return retried.value; + } + // Final authoritative check on the latest published index right before falling back. + const finalState = yield* Ref.get(registryState); + if (finalState.index !== undefined && finalState.indexRevision > activeRevision) { + const finalAgent = yield* findAgent(finalState.index, agentId); + yield* compatibleDistribution(finalAgent, settings.distribution); + if (artifactSignatureIn(finalState.index) !== artifactSignatureIn(activeRegistry)) { + return yield* activeError; + } + activeRegistry = finalState.index; + activeRevision = finalState.indexRevision; + } + const fallback = yield* resolveFallbackInstalledBinary( + settings, + cwd, + environment, + activeRegistry, + activeRevision, + ); + if (Option.isSome(fallback)) return fallback.value; + return yield* activeError; }), ), ); @@ -2124,7 +4040,10 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct for (const version of yield* fileSystem.readDirectory(agentRoot)) { const versionRoot = path.join(agentRoot, version); for (const entry of yield* fileSystem.readDirectory(versionRoot)) { - if (!/^(?:darwin|linux|windows)-(?:aarch64|x86_64)$/u.test(entry)) continue; + if ( + !/^(?:darwin|linux|windows)-(?:aarch64|x86_64)(?:-[0-9a-f]{12})?$/u.test(entry) + ) + continue; yield* fileSystem.remove(path.join(versionRoot, entry), { recursive: true, force: true, @@ -2146,6 +4065,69 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }), ), ); + if (removed) { + const prefix = `${safeAgentId}\0`; + for (const key of legacyBaselineBySlotKey.keys()) { + if (key.startsWith(prefix)) { + legacyBaselineBySlotKey.delete(key); + } + } + const agentRootPrefix = `${agentRoot}${path.sep}`; + for (const slotRoot of pendingLaunchOptionsBySlotRoot.keys()) { + if (slotRoot === agentRoot || slotRoot.startsWith(agentRootPrefix)) { + pendingLaunchOptionsBySlotRoot.delete(slotRoot); + } + } + // Finish durable metadata cleanup before releasing the agent permit so a concurrent + // reinstall cannot write new entries and have this uninstall prune them afterwards. + yield* Effect.all([ + fileSystem.exists(legacyBaselinesPath).pipe( + Effect.orElseSucceed(() => false), + Effect.flatMap((hasBaselinesFile) => + hasBaselinesFile + ? withLegacyBaselinesLock((isLockOwned) => + Effect.gen(function* () { + const disk = yield* readLegacyBaselinesFile( + fileSystem, + legacyBaselinesPath, + ); + if (disk.status !== "ok") return; + const remaining = Object.fromEntries( + Object.entries(disk.baselines).filter( + ([key]) => !key.startsWith(prefix), + ), + ); + if ( + Object.keys(remaining).length !== Object.keys(disk.baselines).length + ) { + if (!(yield* isLockOwned)) return; + yield* writeLegacyBaselinesAtomically(remaining); + } + }), + ).pipe(Effect.ignore) + : Effect.void, + ), + ), + fileSystem.exists(binaryLaunchOptionsPath).pipe( + Effect.orElseSucceed(() => false), + Effect.flatMap((hasLaunchOptionsFile) => + hasLaunchOptionsFile + ? updateBinaryLaunchOptionsStore((entries) => { + const remaining = Object.fromEntries( + Object.entries(entries).filter( + ([slotRoot]) => + slotRoot !== agentRoot && !slotRoot.startsWith(agentRootPrefix), + ), + ); + return Object.keys(remaining).length !== Object.keys(entries).length + ? remaining + : null; + }).pipe(Effect.asVoid) + : Effect.void, + ), + ), + ]).pipe(Effect.asVoid); + } return { agentId: safeAgentId, removed }; }), ), @@ -2162,9 +4144,15 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }), ); + const currentIndexRevision = () => + Ref.get(registryState).pipe(Effect.map((state) => state.indexRevision)); + return AcpRegistryCatalog.of({ search, prepare, + refreshIndex, + currentIndexRevision, + invalidateIndex, inspect, resolve, uninstallManagedBinary, diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 8eb5dbb30b8cc..9196f62be03d2 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -139,6 +139,10 @@ export function acpRegistryPromptFailure(agentId: string, cause: unknown) { function makeAcpRegistryRuntime( options: AcpRegistryAdapterV2Options, catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"], + onResolvedRuntime?: ( + runtime: AcpSessionRuntime.AcpSessionRuntime["Service"], + resolved: AcpRegistrySupport.ResolvedAcpRegistryAgent, + ) => void, ) { return ( input: AcpAdapterV2RuntimeInput, @@ -176,9 +180,11 @@ function makeAcpRegistryRuntime( ), }), ); - return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( + const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( Effect.provide(context), ); + onResolvedRuntime?.(runtime, resolved); + return runtime; }); } @@ -262,6 +268,10 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu // the unquoted "T3 Code (Beta).exe" path). Both take T3's MCP endpoint over ACP HTTP. const useHttpMcpServers = copilotRouting !== undefined || prefersHttpMcpTransport(options.settings); + const runtimeIdentityByRuntime = new WeakMap< + AcpSessionRuntime.AcpSessionRuntime["Service"], + string + >(); const flavor: AcpAdapterV2Flavor = { driver: ACP_REGISTRY_PROVIDER, // Cancelling a Copilot prompt also kills the background agents it started. @@ -343,14 +353,22 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu alwaysSetModel: true, }), mcpOverHttp: useHttpMcpServers, - makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(runtimeOptions, catalog), + makeRuntime: + options.makeRuntime ?? + makeAcpRegistryRuntime(runtimeOptions, catalog, (runtime, resolved) => { + const runtimeIdentity = resolved.launchIdentity ?? resolved.agent?.version; + if (runtimeIdentity !== undefined) { + runtimeIdentityByRuntime.set(runtime, runtimeIdentity); + } + }), ...(runtimeCoordinator === undefined ? {} : { - onAvailableCommandsUpdate: (commands) => + onAvailableCommandsUpdate: (commands, runtime) => runtimeCoordinator.publishAvailableCommands( options.instanceId, normalizeAcpRegistryCommands(commands), + runtime === undefined ? undefined : runtimeIdentityByRuntime.get(runtime), ), // A new Copilot session starts at its own effort, not the one the composer shows. ...(isCopilot @@ -374,10 +392,11 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu ), } : {}), - onSessionConfigurationUpdate: (configOptions, modeState, modelState) => + onSessionConfigurationUpdate: (configOptions, modeState, modelState, runtime) => runtimeCoordinator.publishLiveConfiguration( options.instanceId, normalizeAcpRegistryLiveConfiguration(configOptions, modeState, modelState), + runtime === undefined ? undefined : runtimeIdentityByRuntime.get(runtime), ), onUrlElicitation: ({ elicitationId, url, message }) => { const normalizedUrl = normalizeAcpRegistryWebUrl(url); diff --git a/packages/provider-acp-registry/src/server/auth.test.ts b/packages/provider-acp-registry/src/server/auth.test.ts index 45f72554152b6..343d9426643d6 100644 --- a/packages/provider-acp-registry/src/server/auth.test.ts +++ b/packages/provider-acp-registry/src/server/auth.test.ts @@ -54,6 +54,9 @@ const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { resolve: () => Effect.succeed(resolved), search: () => Effect.die("unused"), prepare: () => Effect.die("unused"), + refreshIndex: () => Effect.die("unused"), + currentIndexRevision: () => Effect.succeed(0), + invalidateIndex: () => Effect.die("unused"), uninstallManagedBinary: () => Effect.die("unused"), }; diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 564486b9d8269..7980426a2b543 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -9,20 +9,30 @@ import { import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; +import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { toCustomModelSetting } from "@t3tools/shared/model"; import { AcpRegistrySettings } from "../settings.ts"; import { describe, expect, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientResponse from "effect/http/HttpClientResponse"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Scheduler from "effect/Scheduler"; import * as Schema from "effect/Schema"; -import type * as Scope from "effect/Scope"; +import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import * as Tracer from "effect/Tracer"; +import * as AcpRegistryAuthenticationState from "./authenticationState.ts"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; import { @@ -63,6 +73,9 @@ function catalogWithInspection( return { search: () => Effect.die("unused search"), prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.succeed(0), + currentIndexRevision: () => Effect.succeed(0), + invalidateIndex: () => Effect.void, inspect: () => Effect.succeed(inspection), resolve: () => Effect.die("unused resolve"), uninstallManagedBinary: () => Effect.die("unused uninstall"), @@ -800,11 +813,17 @@ describe("acpRegistrySnapshotReadiness", () => { describe("acpRegistryEnrichmentCache", () => { it("reuses a local probe until expiry even when inspection has no version", () => { - const entry = { provider: providerWithModels([], null), expiresAt: 1_000 }; + const entry = { + provider: providerWithModels([], null), + expiresAt: 1_000, + launchIdentity: "launch-a", + }; expect(isAcpRegistryCacheValid(entry, null, true, 999)).toBe(true); expect(isAcpRegistryCacheValid(entry, null, true, 1_000)).toBe(false); expect(isAcpRegistryCacheValid(entry, "2.0.0", false, 999)).toBe(false); expect(isAcpRegistryCacheValid(entry, "1.0.0", false, 999)).toBe(true); + expect(isAcpRegistryCacheValid(entry, "1.0.0", false, 999, "launch-a")).toBe(true); + expect(isAcpRegistryCacheValid(entry, "1.0.0", false, 999, "launch-b")).toBe(false); }); const settledConfiguration = { models: [ @@ -819,7 +838,11 @@ describe("acpRegistryEnrichmentCache", () => { it("does not renew the cache deadline when live configuration is replayed unchanged", () => { const provider = providerWithModels(settledConfiguration.models, "auto"); - const cache = { generation: 1, entry: { provider, expiresAt: 1_000 } }; + const cache = { + invalidationGeneration: 1, + liveGenerationByRuntime: new Map(), + entry: { provider, expiresAt: 1_000 }, + }; const replayed = updateAcpRegistryEnrichmentCache({ cache, @@ -837,7 +860,11 @@ describe("acpRegistryEnrichmentCache", () => { [{ id: "smodel", name: "Default", description: null }], "smodel", ); - const cache = { generation: 1, entry: { provider, expiresAt: 1_000 } }; + const cache = { + invalidationGeneration: 1, + liveGenerationByRuntime: new Map(), + entry: { provider, expiresAt: 1_000 }, + }; const updated = updateAcpRegistryEnrichmentCache({ cache, @@ -848,11 +875,16 @@ describe("acpRegistryEnrichmentCache", () => { expect(updated.entry?.provider.models.map((m) => m.slug)).toEqual(["auto", "qmodel", "kmodel"]); expect((updated.entry?.expiresAt ?? 0) - 5_000).toBe(15 * 60 * 1_000); - expect(updated.generation).toBe(2); + expect(updated.invalidationGeneration).toBe(1); + expect(updated.liveGenerationByRuntime.get(null)).toBe(1); }); it("advances the cache epoch when a live update arrives before any probe lands", () => { - const cache = { generation: 4, entry: null }; + const cache = { + invalidationGeneration: 4, + liveGenerationByRuntime: new Map(), + entry: null, + }; const updated = updateAcpRegistryEnrichmentCache({ cache, @@ -861,9 +893,36 @@ describe("acpRegistryEnrichmentCache", () => { now: 5_000, }); - expect(updated.generation).toBe(5); + expect(updated.invalidationGeneration).toBe(4); + expect(updated.liveGenerationByRuntime.get(null)).toBe(1); expect(updated.entry).toBeNull(); }); + + it("advances the incoming runtime's generation without replacing another runtime's cached entry", () => { + const provider = providerWithModels( + [{ id: "smodel", name: "Default", description: null }], + "smodel", + ); + const cache = { + invalidationGeneration: 3, + liveGenerationByRuntime: new Map(), + entry: { provider, expiresAt: 1_000, launchIdentity: "runtime-v1" }, + }; + + const updated = updateAcpRegistryEnrichmentCache({ + cache, + configuration: settledConfiguration, + customModels: [], + now: 5_000, + runtimeIdentity: "runtime-v2", + }); + + expect(updated.entry).toBe(cache.entry); + expect(updated.invalidationGeneration).toBe(3); + expect(updated.liveGenerationByRuntime.get("runtime-v2")).toBe(1); + expect(updated.liveGenerationByRuntime.get("runtime-v1")).toBeUndefined(); + expect(updated.entry?.provider.models.map((m) => m.slug)).toEqual(["smodel"]); + }); }); describe("acpRegistryAdvertisesModelCatalog", () => { @@ -951,6 +1010,108 @@ createInterface({ input: process.stdin }).on("line", (line) => { }); `; +const isWindowsHost = HostProcess.Platform.defaultValue() === "win32"; +const testHostPlatform: NodeJS.Platform = isWindowsHost ? "win32" : "linux"; +const compatibleRegistryTarget: AcpRegistrySupport.AcpRegistryPlatformTarget = isWindowsHost + ? "windows-x86_64" + : "linux-x86_64"; +const incompatibleRegistryTarget: AcpRegistrySupport.AcpRegistryPlatformTarget = "darwin-aarch64"; + +const registryUrl = "https://registry.test/registry.json"; + +const makeBinaryRegistry = ( + version: string, + target: AcpRegistrySupport.AcpRegistryPlatformTarget = compatibleRegistryTarget, + options?: { + readonly website?: string; + readonly archiveSuffix?: string; + readonly extraAgentVersion?: string; + }, +) => + JSON.stringify({ + version: "1.0.0", + agents: [ + { + id: "test-agent", + name: "Test Agent", + version, + description: "Test binary agent", + ...(options?.website ? { website: options.website } : {}), + distribution: { + binary: { + [target]: { + archive: `https://registry.test/test-agent-${version}${options?.archiveSuffix ?? ""}.bin`, + cmd: "./bin/test-agent", + }, + }, + }, + }, + ...(options?.extraAgentVersion + ? [ + { + id: "other-agent", + name: "Other Agent", + version: options.extraAgentVersion, + description: "Unrelated agent", + distribution: { + binary: { + [target]: { + archive: `https://registry.test/other-agent-${options.extraAgentVersion}.bin`, + cmd: "./bin/other-agent", + }, + }, + }, + }, + ] + : []), + ], + }); + +// A disk-cached 1.0.0 index with its binary installed, as left behind by an earlier session. +const seedInstalledBinaryAgent = Effect.fn("seedInstalledBinaryAgent")(function* ( + prefix: string, + options?: { readonly website?: string }, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix }); + const agentPath = path.join(directory, "agent.mjs"); + const modelsPath = path.join(directory, "models.json"); + yield* fileSystem.writeFileString(agentPath, fakeAgentSource); + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["model-a", "model-b"])); + yield* fileSystem.makeDirectory(path.join(directory, "acp-registry"), { recursive: true }); + yield* fileSystem.writeFileString( + path.join(directory, "acp-registry", "registry.json"), + makeBinaryRegistry("1.0.0", compatibleRegistryTarget, options), + ); + const installedV1 = installedBinaryPath(path, directory, "1.0.0"); + yield* fileSystem.makeDirectory(path.dirname(installedV1), { recursive: true }); + yield* fileSystem.writeFileString(installedV1, "#!/bin/sh\necho 1.0.0\n"); + yield* fileSystem.writeFileString( + path.join(path.dirname(path.dirname(installedV1)), ".t3-artifact.json"), + JSON.stringify({ + archive: "https://registry.test/test-agent-1.0.0.bin", + cmd: "./bin/test-agent", + sha256: null, + }), + ); + if (!isWindowsHost) { + yield* fileSystem.chmod(installedV1, 0o755); + } + return { directory, agentPath, modelsPath }; +}); + +const installedBinaryPath = (path: Path.Path, directory: string, version: string) => + path.join( + directory, + "tools", + "test-agent", + version, + compatibleRegistryTarget, + "bin", + "test-agent", + ); + // Reports `effort` levels for its current model only and logs each model switch. const perModelEffortAgentSource = ` import { appendFileSync, readFileSync } from "node:fs"; @@ -1246,6 +1407,107 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = }), ); + it.effect("refreshes a cached registry index on enrichment and explicit cache invalidation", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { directory, agentPath, modelsPath } = + yield* seedInstalledBinaryAgent("acp-driver-update-"); + + let latestVersion = "2.0.0"; + let registryRequests = 0; + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, testHostPlatform), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => { + if (request.url === registryUrl) { + registryRequests += 1; + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(makeBinaryRegistry(latestVersion)), + ), + ); + } + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(`#!/bin/sh\necho ${latestVersion}\n`), + ), + ); + }), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + resolve: (settings, cwd, environment) => + realCatalog.resolve(settings, cwd, environment).pipe( + Effect.map((resolved) => ({ + ...resolved, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + })), + ), + }; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + + const waitForEnriched = (version: string) => + instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === version && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + ); + + // Initial enrichment refreshes the disk-cached 1.0.0 index and installs 2.0.0. + const upgradedToV2 = yield* waitForEnriched("2.0.0").pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const first = Option.getOrThrow(yield* Fiber.join(upgradedToV2)); + expect(first.version).toBe("2.0.0"); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "2.0.0"))).toBe(true); + + // Explicit cache invalidation refreshes past the in-memory reuse window and installs 3.0.0. + latestVersion = "3.0.0"; + const upgradedToV3 = yield* waitForEnriched("3.0.0").pipe( + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.invalidateCaches ?? Effect.void; + yield* instance.snapshot.refresh; + const second = Option.getOrThrow(yield* Fiber.join(upgradedToV3)); + expect(second.version).toBe("3.0.0"); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "3.0.0"))).toBe(true); + + // Disabled instances must not invalidate the shared registry freshness or fetch on refresh. + const disabledRequestsBefore = registryRequests; + latestVersion = "4.0.0"; + const disabled = yield* AcpRegistryDriver.create({ + instanceId: ProviderInstanceId.make("acpRegistry_disabled"), + displayName: "Disabled ACP", + enabled: false, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + yield* disabled.invalidateCaches ?? Effect.void; + yield* disabled.snapshot.refresh; + yield* catalog.refreshIndex({ maxAgeMs: 15 * 60 * 1_000, failureBackoffMs: 60_000 }); + expect(registryRequests).toBe(disabledRequestsBefore); + }), + ); + const makePerModelEffortAgent = Effect.fn("makePerModelEffortAgent")(function* ( levels: Readonly | null>>, ) { @@ -1466,3 +1728,4149 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = }), ); }); + +describe("AcpRegistryDriver registry recovery", () => { + it.effect( + "recovers when a refreshed index moves from compatible to incompatible and back without cache invalidation", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const { directory, agentPath, modelsPath } = + yield* seedInstalledBinaryAgent("acp-driver-recover-"); + + let remoteVersion = "2.0.0"; + let remoteTarget: AcpRegistrySupport.AcpRegistryPlatformTarget = incompatibleRegistryTarget; + let resolveAttempts = 0; + let inspectCount = 0; + let onRefreshDone: Effect.Effect = Effect.void; + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, testHostPlatform), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + request.url === registryUrl + ? makeBinaryRegistry(remoteVersion, remoteTarget) + : `#!/bin/sh\necho ${remoteVersion}\n`, + ), + ), + ), + ), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + inspect: (settings, environment) => + Effect.sync(() => { + inspectCount += 1; + }).pipe(Effect.andThen(() => realCatalog.inspect(settings, environment))), + refreshIndex: (options) => + realCatalog.refreshIndex(options).pipe(Effect.tap(() => onRefreshDone)), + resolve: (settings, cwd, environment) => + Effect.sync(() => { + resolveAttempts += 1; + }).pipe( + Effect.andThen(() => realCatalog.resolve(settings, cwd, environment)), + Effect.map((resolved) => ({ + ...resolved, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + })), + ), + }; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + + // 1. Compatible 1.0.0 transitions to incompatible 2.0.0. + const becameUnsupported = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => !snapshot.installed && snapshot.version === "2.0.0"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const unsupported = Option.getOrThrow(yield* Fiber.join(becameUnsupported)); + expect(unsupported.status).toBe("error"); + + // Same-revision refresh while uninstalled returns early without re-running inspect(). + const sameRevisionRefreshDone = yield* Deferred.make(); + onRefreshDone = Deferred.succeed(sameRevisionRefreshDone, undefined).pipe(Effect.asVoid); + const inspectsBeforeSameRevision = inspectCount; + yield* instance.snapshot.refresh; + yield* Deferred.await(sameRevisionRefreshDone); + // A follow-up refresh synchronizes past the previous enrichment fiber's synchronous early return. + const nextRefreshDone = yield* Deferred.make(); + onRefreshDone = Deferred.succeed(nextRefreshDone, undefined).pipe(Effect.asVoid); + yield* instance.snapshot.refresh; + yield* Deferred.await(nextRefreshDone); + onRefreshDone = Effect.void; + // 2 refreshes × (checkProvider + auth.refreshMethods), with 0 enrichment rechecks. + expect(inspectCount).toBe(inspectsBeforeSameRevision + 4); + + // 2. Live updates (config, commands, URL auth action) on the uninstalled snapshot cannot flip or leak into it; + // a post-TTL refresh to another incompatible version publishes it without probing. + const attemptsWhileUnsupported = resolveAttempts; + remoteVersion = "2.1.0"; + const unsupportedSnapshots = yield* instance.snapshot.streamChanges.pipe( + Stream.takeUntil((snapshot) => !snapshot.installed && snapshot.version === "2.1.0"), + Stream.runCollect, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "stale-model", + availableModels: [ + { modelId: "stale-model", name: "stale-model" }, + { modelId: "stale-other", name: "stale-other" }, + ], + }), + ); + yield* coordinator.publishAvailableCommands(identity.instanceId, { + slashCommands: [{ name: "stale-cmd" }], + skills: [], + }); + const authRequestWhileUnsupported = yield* coordinator + .requestUrlAuthentication(identity.instanceId, { + elicitationId: "uninstalled-auth", + url: "https://example.test/uninstalled-auth", + message: "Continue in your browser", + }) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* TestClock.adjust("16 minutes"); + yield* instance.snapshot.refresh; + const duringUnsupported = yield* Fiber.join(unsupportedSnapshots); + expect( + duringUnsupported.every( + (snapshot) => + !snapshot.installed && + snapshot.status === "error" && + snapshot.slashCommands.length === 0 && + snapshot.auth.action === undefined, + ), + ).toBe(true); + expect(resolveAttempts).toBe(attemptsWhileUnsupported); + yield* Fiber.interrupt(authRequestWhileUnsupported); + + // 3. Upstream restores compatible 3.0.0; one post-TTL refresh clears the error and stale live state before probing and installs 3.0.0. + remoteVersion = "3.0.0"; + remoteTarget = compatibleRegistryTarget; + const recoverySnapshots = yield* instance.snapshot.streamChanges.pipe( + Stream.takeUntil( + (snapshot) => + snapshot.installed && + snapshot.version === "3.0.0" && + snapshot.nativeSessions !== undefined, + ), + Stream.runCollect, + Effect.forkScoped({ startImmediately: true }), + ); + yield* TestClock.adjust("16 minutes"); + yield* instance.snapshot.refresh; + const snapshots = yield* Fiber.join(recoverySnapshots); + const recheckedIndex = snapshots.findIndex( + (snapshot) => + snapshot.installed && + snapshot.version === "3.0.0" && + snapshot.nativeSessions === undefined, + ); + expect(recheckedIndex).toBeGreaterThanOrEqual(0); + const ready = snapshots[snapshots.length - 1]!; + expect(recheckedIndex).toBeLessThan(snapshots.length - 1); + expect(ready.status).toBe("ready"); + expect(ready.version).toBe("3.0.0"); + expect(ready.nativeSessions).toBeDefined(); + expect(ready.models.map((model) => model.slug)).toEqual(["model-a", "model-b"]); + expect(ready.slashCommands).toEqual([]); + expect(resolveAttempts).toBeGreaterThan(attemptsWhileUnsupported); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "3.0.0"))).toBe(true); + }).pipe(Effect.scoped, Effect.provide(driverLayer)), + ); + + it.effect( + "publishes cold and cached probes immediately while backing off and reconciling failed upgrade fallbacks", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { directory, agentPath, modelsPath } = yield* seedInstalledBinaryAgent( + "acp-driver-slow-refresh-", + ); + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + + let remoteVersion = "2.0.0"; + let remoteWebsite: string | undefined = undefined; + let remoteExtraAgentVersion: string | undefined = undefined; + let failArchiveDownload = false; + let inspectCalls = 0; + let probeResolveAttempts = 0; + let onFallbackResolved: (() => Effect.Effect) | null = null; + let onEnrichmentEnd: ((exit: Exit.Exit) => void) | null = null; + const testTracer: Tracer.Tracer = { + span(options) { + const inner = Tracer.nativeTracer.span(options); + if (options.name !== "AcpRegistryDriver.publishEnrichment") return inner; + const origEnd = inner.end.bind(inner); + inner.end = (endTime, exit) => { + origEnd(endTime, exit); + onEnrichmentEnd?.(exit); + }; + return inner; + }, + }; + const initialGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + let gate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = initialGate; + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, testHostPlatform), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => { + const respond = Effect.sync(() => + HttpClientResponse.fromWeb( + request, + request.url === registryUrl + ? new Response( + makeBinaryRegistry(remoteVersion, compatibleRegistryTarget, { + ...(remoteWebsite ? { website: remoteWebsite } : {}), + ...(remoteExtraAgentVersion + ? { extraAgentVersion: remoteExtraAgentVersion } + : {}), + }), + ) + : failArchiveDownload + ? new Response("archive unavailable", { status: 503 }) + : new Response(`#!/bin/sh\necho ${remoteVersion}\n`), + ), + ); + const activeGate = request.url === registryUrl ? gate : null; + return activeGate === null + ? respond + : Deferred.succeed(activeGate.started, undefined).pipe( + Effect.andThen(Deferred.await(activeGate.release)), + Effect.andThen(respond), + ); + }), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + inspect: (settings, environment) => + Effect.sync(() => { + inspectCalls += 1; + }).pipe(Effect.andThen(() => realCatalog.inspect(settings, environment))), + resolve: (settings, cwd, environment) => + Effect.sync(() => { + if (environment?.MISE_OFFLINE === "1") { + probeResolveAttempts += 1; + } + }).pipe( + Effect.andThen(() => realCatalog.resolve(settings, cwd, environment)), + Effect.tap((resolved) => + resolved.fallback && onFallbackResolved !== null + ? onFallbackResolved() + : Effect.void, + ), + Effect.map((resolved) => ({ + ...resolved, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + })), + ), + }; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService(Tracer.Tracer, testTracer), + ); + + // On cold startup, the disk-cached 1.0.0 probe publishes before the slow 2.0.0 registry fetch finishes. + const coldReady = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "1.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const upgradedToV2 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "2.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Deferred.await(initialGate.started); + expect(Option.isSome(yield* Fiber.join(coldReady))).toBe(true); + + yield* Deferred.succeed(initialGate.release, undefined); + expect(Option.isSome(yield* Fiber.join(upgradedToV2))).toBe(true); + + // A live-session update at +10m extends enrichmentCache past +16m while the registry index expires. + yield* TestClock.adjust("10 minutes"); + const liveUpdated = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((model) => model.slug === "model-c")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "model-a", + availableModels: [ + { modelId: "model-a", name: "model-a" }, + { modelId: "model-c", name: "model-c" }, + ], + }), + ); + expect(Option.isSome(yield* Fiber.join(liveUpdated))).toBe(true); + + // At +16m, the registry fetch blocks, yet the cached 2.0.0 probe publishes immediately before release. + remoteVersion = "3.0.0"; + const secondGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + gate = secondGate; + const cachedPublished = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "2.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const upgradedToV3 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "3.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* TestClock.adjust("6 minutes"); + yield* instance.snapshot.refresh; + yield* Deferred.await(secondGate.started); + expect(Option.isSome(yield* Fiber.join(cachedPublished))).toBe(true); + + yield* Deferred.succeed(secondGate.release, undefined); + expect(Option.isSome(yield* Fiber.join(upgradedToV3))).toBe(true); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "3.0.0"))).toBe(true); + + // If 4.0.0 fails to download, the driver falls back to the installed 3.0.0 with a user-visible + // status message, stays flicker-free during backoff, does not acknowledge the 4.0.0 revision, + // and upgrades to 4.0.0 once backoff expires and the archive recovers. + const v3LiveApplied = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((command) => command.name === "v3-live-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands(identity.instanceId, { + slashCommands: [{ name: "v3-live-cmd" }], + skills: [], + }); + expect(Option.isSome(yield* Fiber.join(v3LiveApplied))).toBe(true); + + gate = null; + remoteVersion = "4.0.0"; + remoteWebsite = "https://example.test/v4"; + failArchiveDownload = true; + const fallbackObserved = yield* Deferred.make(); + onFallbackResolved = () => + Deferred.succeed(fallbackObserved, undefined).pipe(Effect.asVoid); + const fallbackPublished = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "3.0.0" && + snapshot.status === "ready" && + snapshot.setup?.documentationUrl === "https://example.test/v4" && + snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* TestClock.adjust("16 minutes"); + yield* instance.snapshot.refresh; + yield* Deferred.await(fallbackObserved); + const fallbackSnapshot = Option.getOrThrow(yield* Fiber.join(fallbackPublished)); + expect(fallbackSnapshot.message).toContain("4.0.0"); + expect(fallbackSnapshot.slashCommands).toEqual([{ name: "v3-live-cmd" }]); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "4.0.0"))).toBe(false); + onFallbackResolved = null; + + // Refreshing inside the 60s fallback backoff window must not flicker to 4.0.0, drop v3 live + // commands, or re-run probe/download attempts. + const resolvesBeforeBackoffRefresh = probeResolveAttempts; + const backoffSnapshots: Array = []; + const backoffCollector = yield* instance.snapshot.streamChanges.pipe( + Stream.runForEach((snapshot) => + Effect.sync(() => { + backoffSnapshots.push(snapshot); + }), + ), + Effect.forkScoped({ startImmediately: true }), + ); + const backoffEnrichmentDone = yield* Deferred.make(); + onEnrichmentEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(backoffEnrichmentDone, Exit.void); + } + }; + yield* TestClock.adjust("30 seconds"); + yield* instance.snapshot.refresh.pipe(Effect.provideService(Tracer.Tracer, testTracer)); + yield* Deferred.await(backoffEnrichmentDone); + onEnrichmentEnd = null; + yield* Fiber.interrupt(backoffCollector); + expect(probeResolveAttempts).toBe(resolvesBeforeBackoffRefresh); + expect(backoffSnapshots.every((snapshot) => snapshot.version === "3.0.0")).toBe(true); + expect( + backoffSnapshots.every((snapshot) => snapshot.message === fallbackSnapshot.message), + ).toBe(true); + expect( + backoffSnapshots.every((snapshot) => + snapshot.slashCommands.some((command) => command.name === "v3-live-cmd"), + ), + ).toBe(true); + + // Live configuration updates during fallback must also preserve the fallback warning message. + const v3LiveConfigDuringFallback = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.models.some((model) => + model.capabilities?.optionDescriptors?.some((opt) => opt.id === "fallback-effort"), + ), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([ + { + id: "fallback-effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [{ value: "high", name: "High" }], + }, + ]), + ); + const liveFallbackSnapshot = Option.getOrThrow( + yield* Fiber.join(v3LiveConfigDuringFallback), + ); + expect(liveFallbackSnapshot.message).toBe(fallbackSnapshot.message); + + // Unrelated agent changes or non-launch metadata updates during fallback backoff must + // refresh displayed metadata without re-probing or resetting backoff. + remoteWebsite = "https://example.test/v4-updated-docs"; + remoteExtraAgentVersion = "9.9.9"; + yield* realCatalog.invalidateIndex(); + const resolvesBeforeMetadataBackoff = probeResolveAttempts; + const metadataBackoffDone = yield* Deferred.make(); + onEnrichmentEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(metadataBackoffDone, Exit.void); + } + }; + yield* instance.snapshot.refresh.pipe(Effect.provideService(Tracer.Tracer, testTracer)); + yield* Deferred.await(metadataBackoffDone); + onEnrichmentEnd = null; + expect(probeResolveAttempts).toBe(resolvesBeforeMetadataBackoff); + const metadataBackoffSnapshot = yield* instance.snapshot.getSnapshot; + expect(metadataBackoffSnapshot.version).toBe("3.0.0"); + expect(metadataBackoffSnapshot.setup?.documentationUrl).toBe( + "https://example.test/v4-updated-docs", + ); + expect(metadataBackoffSnapshot.message).toBe(fallbackSnapshot.message); + + // A follow-up refresh at the same revision inside backoff skips enrichment recheck + // completely because targetIndexRevision was updated to the new revision. + const inspectsBeforeSameRevBackoff = inspectCalls; + const sameRevBackoffDone = yield* Deferred.make(); + onEnrichmentEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(sameRevBackoffDone, Exit.void); + } + }; + yield* instance.snapshot.refresh.pipe(Effect.provideService(Tracer.Tracer, testTracer)); + yield* Deferred.await(sameRevBackoffDone); + onEnrichmentEnd = null; + expect(probeResolveAttempts).toBe(resolvesBeforeMetadataBackoff); + // Only checkProvider + auth.refreshMethods run; 0 enrichment inspectReadiness rechecks. + expect(inspectCalls).toBe(inspectsBeforeSameRevBackoff + 2); + + // Once backoff expires, recovering without invalidating the cached 4.0.0 index still upgrades + // because fallback did not acknowledge the 4.0.0 revision. + failArchiveDownload = false; + const upgradedToV4 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "4.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* TestClock.adjust("31 seconds"); + yield* instance.snapshot.refresh; + const v4Snapshot = Option.getOrThrow(yield* Fiber.join(upgradedToV4)); + expect(v4Snapshot.message).toBeUndefined(); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "4.0.0"))).toBe(true); + + // A 1-model agent (30s provisional cache TTL) still respects the 60s fallback backoff at +31s, + // and invalidateCaches clears activeFallback so the next refresh retries immediately. + remoteVersion = "5.0.0"; + failArchiveDownload = true; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const singleModelInstanceId = ProviderInstanceId.make("acpRegistry_single_model_backoff"); + const singleModelFallbackDone = yield* Deferred.make(); + onEnrichmentEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(singleModelFallbackDone, Exit.void); + } + }; + const singleModelInstance = yield* AcpRegistryDriver.create({ + instanceId: singleModelInstanceId, + displayName: "Single Model Backoff", + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService(Tracer.Tracer, testTracer), + ); + yield* Deferred.await(singleModelFallbackDone); + onEnrichmentEnd = null; + const soloFallbackSnapshot = yield* singleModelInstance.snapshot.getSnapshot; + expect(soloFallbackSnapshot.version).toBe("4.0.0"); + expect(soloFallbackSnapshot.message).toContain("5.0.0"); + + // Narrow the cached fallback entry to a single explicit model (30s provisional TTL). + const soloModelApplied = yield* singleModelInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.models.some((model) => model.slug === "solo-v4-model"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + singleModelInstanceId, + normalizeAcpRegistryLiveConfiguration([ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: "solo-v4-model", + options: [{ value: "solo-v4-model", name: "Solo V4" }], + }, + ]), + ); + const soloAppliedSnapshot = Option.getOrThrow(yield* Fiber.join(soloModelApplied)); + expect(soloAppliedSnapshot.models.map((model) => model.slug)).toEqual(["solo-v4-model"]); + expect(soloAppliedSnapshot.message).toBe(soloFallbackSnapshot.message); + + const resolvesBeforeSolo31s = probeResolveAttempts; + const solo31sDone = yield* Deferred.make(); + onEnrichmentEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(solo31sDone, Exit.void); + } + }; + yield* TestClock.adjust("31 seconds"); + yield* singleModelInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, testTracer), + ); + yield* Deferred.await(solo31sDone); + onEnrichmentEnd = null; + expect(probeResolveAttempts).toBe(resolvesBeforeSolo31s); + const soloAfter31s = yield* singleModelInstance.snapshot.getSnapshot; + expect(soloAfter31s.message).toBe(soloFallbackSnapshot.message); + expect(soloAfter31s.models.map((model) => model.slug)).toEqual(["solo-v4-model"]); + + // Calling invalidateCaches clears activeFallback and retries immediately even inside 60s. + yield* singleModelInstance.invalidateCaches ?? Effect.void; + const soloAfterInvalidateDone = yield* Deferred.make(); + onEnrichmentEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(soloAfterInvalidateDone, Exit.void); + } + }; + yield* singleModelInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, testTracer), + ); + yield* Deferred.await(soloAfterInvalidateDone); + onEnrichmentEnd = null; + expect(probeResolveAttempts).toBe(resolvesBeforeSolo31s + 1); + const v5Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v5Inspection.status).toBe("ready"); + const v5Identity = v5Inspection.status === "ready" ? v5Inspection.launchIdentity! : ""; + + // When inspect() sees cached 5.0.0 while resolve() refreshes to failing 6.0.0 and falls back + // to 4.0.0, activeFallback records 6.0.0 (from resolved.failedTarget) and external 6.0.0 live + // state reconciles freshInstance to 6.0.0. + remoteVersion = "6.0.0"; + yield* realCatalog.invalidateIndex(); + const resolvesBeforeFreshFallback = probeResolveAttempts; + const freshFallbackDone = yield* Deferred.make(); + onEnrichmentEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(freshFallbackDone, Exit.void); + } + }; + const freshInstanceId = ProviderInstanceId.make("acpRegistry_fallback_single_probe"); + const freshInstance = yield* AcpRegistryDriver.create({ + instanceId: freshInstanceId, + displayName: "Fallback Single Probe", + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService(Tracer.Tracer, testTracer), + ); + yield* Deferred.await(freshFallbackDone); + onEnrichmentEnd = null; + const freshFallbackSnapshot = yield* freshInstance.snapshot.getSnapshot; + expect(freshFallbackSnapshot.version).toBe("4.0.0"); + expect(freshFallbackSnapshot.message).toContain("6.0.0"); + expect(probeResolveAttempts).toBe(resolvesBeforeFreshFallback + 1); + + // External 6.0.0 live state clears activeFallback and reconciles freshInstance to 6.0.0. + failArchiveDownload = false; + const v6Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v6Inspection.status).toBe("ready"); + const v6Identity = v6Inspection.status === "ready" ? v6Inspection.launchIdentity! : ""; + const freshReconciledToV6 = yield* freshInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "6.0.0" && + snapshot.nativeSessions !== undefined && + snapshot.slashCommands.some((command) => command.name === "v6-external-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + freshInstanceId, + { slashCommands: [{ name: "v6-external-cmd" }], skills: [] }, + v6Identity, + ); + const reconciledV6Snapshot = Option.getOrThrow(yield* Fiber.join(freshReconciledToV6)); + expect(reconciledV6Snapshot.version).toBe("6.0.0"); + expect(reconciledV6Snapshot.message).toBeUndefined(); + + // On cold-start fallback where inspect() already seeded activeRuntimeIdentity to the failing + // target (5.0.0 on singleModelInstance), 5.0.0 was never successfully started and must not be + // retired, so external 5.0.0 live state still reconciles singleModelInstance once 5.0.0 recovers. + remoteVersion = "5.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const singleReconciledToV5 = yield* singleModelInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "5.0.0" && + snapshot.nativeSessions !== undefined && + snapshot.slashCommands.some((command) => command.name === "v5-external-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + singleModelInstanceId, + { slashCommands: [{ name: "v5-external-cmd" }], skills: [] }, + v5Identity, + ); + const reconciledV5Snapshot = Option.getOrThrow(yield* Fiber.join(singleReconciledToV5)); + expect(reconciledV5Snapshot.version).toBe("5.0.0"); + expect(reconciledV5Snapshot.message).toBeUndefined(); + }).pipe(Effect.scoped, Effect.provide(driverLayer)), + ); + + it.effect( + "publishes same-version metadata updates without re-probing, re-probes same-version launch swaps, clears stale live state on upgrade, and retries skipped probes", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseCoordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const { directory, agentPath, modelsPath } = yield* seedInstalledBinaryAgent( + "acp-driver-meta-session-", + { website: "https://example.test/v1" }, + ); + + let remoteVersion = "1.0.0"; + let remoteWebsite: string | undefined = "https://example.test/v1"; + let remoteArchiveSuffix = ""; + let remoteExtraAgentVersion: string | undefined = undefined; + let registryRequests = 0; + let resolveAttempts = 0; + let lastResolvedCommand = ""; + let backgroundProbeCalls = 0; + let onInspectStart: (() => Effect.Effect) | null = null; + let onInspect: + | ((inspection: AcpRegistrySupport.AcpRegistryInspection) => Effect.Effect) + | null = null; + let onBackgroundProbeOutcome: ((skipped: boolean) => Effect.Effect) | null = null; + let onRefreshIndex: Effect.Effect = Effect.void; + let onPublishEnrichmentEnd: ((exit: Exit.Exit) => void) | null = null; + const makeEnrichmentTracer = ( + onEnd: () => ((exit: Exit.Exit) => void) | null, + ): Tracer.Tracer => ({ + span(options) { + const inner = Tracer.nativeTracer.span(options); + if (options.name !== "AcpRegistryDriver.publishEnrichment") return inner; + const origEnd = inner.end.bind(inner); + inner.end = (endTime, exit) => { + origEnd(endTime, exit); + onEnd()?.(exit); + }; + return inner; + }, + }); + const coordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"] = + { + ...baseCoordinator, + runBackgroundProbe: (agentId, effect) => + Effect.sync(() => { + backgroundProbeCalls += 1; + }).pipe( + Effect.andThen(() => baseCoordinator.runBackgroundProbe(agentId, effect)), + Effect.tap((outcome) => + onBackgroundProbeOutcome === null + ? Effect.void + : onBackgroundProbeOutcome(Option.isNone(outcome)), + ), + ), + }; + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, testHostPlatform), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => { + if (request.url === registryUrl) { + registryRequests += 1; + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + makeBinaryRegistry(remoteVersion, compatibleRegistryTarget, { + ...(remoteWebsite ? { website: remoteWebsite } : {}), + ...(remoteArchiveSuffix ? { archiveSuffix: remoteArchiveSuffix } : {}), + ...(remoteExtraAgentVersion + ? { extraAgentVersion: remoteExtraAgentVersion } + : {}), + }), + ), + ), + ); + } + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(`#!/bin/sh\necho ${remoteVersion}${remoteArchiveSuffix}\n`), + ), + ); + }), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + inspect: (settings, environment) => + (onInspectStart === null ? Effect.void : onInspectStart()).pipe( + Effect.andThen(() => realCatalog.inspect(settings, environment)), + Effect.tap((inspection) => + onInspect === null ? Effect.void : onInspect(inspection), + ), + ), + refreshIndex: (options) => + realCatalog.refreshIndex(options).pipe(Effect.tap(() => onRefreshIndex)), + resolve: (settings, cwd, environment) => + Effect.sync(() => { + resolveAttempts += 1; + }).pipe( + Effect.andThen(() => realCatalog.resolve(settings, cwd, environment)), + Effect.tap((resolved) => + Effect.sync(() => { + lastResolvedCommand = resolved.spawn.command; + }), + ), + Effect.map((resolved) => ({ + ...resolved, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + })), + ), + }; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService( + Tracer.Tracer, + makeEnrichmentTracer(() => onPublishEnrichmentEnd), + ), + ); + + // Prime the 1.0.0 probe cache first so subsequent metadata-only refreshes can assert zero re-probes. + const initialReady = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.setup?.documentationUrl === "https://example.test/v1" && + snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(initialReady))).toBe(true); + const resolvesAfterInitialProbe = resolveAttempts; + + // 1. Same-version metadata update publishes the new documentationUrl while preserving cached models, commands, and auth actions without re-probing. + yield* coordinator.publishAvailableCommands(identity.instanceId, { + slashCommands: [{ name: "status" }], + skills: [], + }); + const authActionReady = yield* Deferred.make(); + const authWatcher = yield* coordinator + .watchUrlAuthAction(identity.instanceId, (action) => + action === null + ? Effect.void + : Deferred.succeed(authActionReady, undefined).pipe(Effect.asVoid), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + const authRequest = yield* coordinator + .requestUrlAuthentication(identity.instanceId, { + elicitationId: "auth-1", + url: "https://example.test/auth", + message: "Continue in your browser", + }) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(authActionReady); + yield* Fiber.interrupt(authWatcher); + remoteWebsite = "https://example.test/v1-updated"; + const updatedDocs = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.setup?.documentationUrl === "https://example.test/v1-updated" && + snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* catalog.invalidateIndex(); + yield* instance.snapshot.refresh; + const withUpdatedDocs = Option.getOrThrow(yield* Fiber.join(updatedDocs)); + expect(withUpdatedDocs.models.map((model) => model.slug)).toEqual(["model-a", "model-b"]); + expect(withUpdatedDocs.slashCommands).toEqual([{ name: "status" }]); + expect(withUpdatedDocs.auth.action).toMatchObject({ + elicitationId: "auth-1", + url: "https://example.test/auth", + }); + expect(resolveAttempts).toBe(resolvesAfterInitialProbe); + yield* Fiber.interrupt(authRequest); + + // Removing website clears setup.documentationUrl via the cached probe without re-probing. + remoteWebsite = undefined; + const clearedDocs = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.setup?.documentationUrl === undefined && + snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* catalog.invalidateIndex(); + yield* instance.snapshot.refresh; + const withClearedDocs = Option.getOrThrow(yield* Fiber.join(clearedDocs)); + expect(withClearedDocs.models.map((model) => model.slug)).toEqual(["model-a", "model-b"]); + expect(resolveAttempts).toBe(resolvesAfterInitialProbe); + + // 2. An unrelated registry change plus a live command update does not schedule a second probe + // and acknowledges the revision so a follow-up refresh skips rechecking. + remoteExtraAgentVersion = "9.9.9"; + let unrelatedRefreshed = false; + const unrelatedEnrichmentDone = yield* Deferred.make(); + onRefreshIndex = Effect.sync(() => { + unrelatedRefreshed = true; + }); + onPublishEnrichmentEnd = (exit) => { + if (unrelatedRefreshed && Exit.isSuccess(exit)) { + Deferred.doneUnsafe(unrelatedEnrichmentDone, Exit.void); + } + }; + const liveCommandApplied = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((command) => command.name === "live-updated"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const probesBeforeUnrelated = backgroundProbeCalls; + yield* coordinator.publishAvailableCommands(identity.instanceId, { + slashCommands: [{ name: "live-updated" }], + skills: [], + }); + yield* catalog.invalidateIndex(); + yield* instance.snapshot.refresh.pipe( + Effect.provideService( + Tracer.Tracer, + makeEnrichmentTracer(() => onPublishEnrichmentEnd), + ), + ); + // Wait for publishEnrichment itself to finish its post-refresh decision before asserting counts. + yield* Deferred.await(unrelatedEnrichmentDone); + expect(Option.isSome(yield* Fiber.join(liveCommandApplied))).toBe(true); + onRefreshIndex = Effect.void; + onPublishEnrichmentEnd = null; + // 1 auth.refreshMethods + 1 initialProbe; 0 post-recheck probe calls. + expect(backgroundProbeCalls).toBe(probesBeforeUnrelated + 2); + expect(resolveAttempts).toBe(resolvesAfterInitialProbe); + expect((yield* instance.snapshot.getSnapshot).slashCommands).toEqual([ + { name: "live-updated" }, + ]); + + // A freshly created instance on an already-refreshed catalog does not recheck the same revision. + const secondInstanceId = ProviderInstanceId.make("acpRegistry_second_fresh"); + let secondInstanceRefreshed = false; + let secondInstancePostRefreshInspects = 0; + const secondEnrichmentDone = yield* Deferred.make(); + onRefreshIndex = Effect.sync(() => { + secondInstanceRefreshed = true; + }); + onInspectStart = () => + secondInstanceRefreshed + ? Effect.sync(() => { + secondInstancePostRefreshInspects += 1; + }) + : Effect.void; + let onSecondEnrichmentEnd: ((exit: Exit.Exit) => void) | null = ( + exit, + ) => { + if (secondInstanceRefreshed && Exit.isSuccess(exit)) { + Deferred.doneUnsafe(secondEnrichmentDone, Exit.void); + } + }; + yield* AcpRegistryDriver.create({ + instanceId: secondInstanceId, + displayName: "Second ACP", + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService( + Tracer.Tracer, + makeEnrichmentTracer(() => onSecondEnrichmentEnd), + ), + ); + // Wait for secondInstance's publishEnrichment span to complete past the revision skip decision. + yield* Deferred.await(secondEnrichmentDone); + onSecondEnrichmentEnd = null; + onRefreshIndex = Effect.void; + onInspectStart = null; + expect(secondInstancePostRefreshInspects).toBe(0); + + // 3. Same-version launch distribution swap installs into an immutable artifact slot without + // mutating the existing binary, invalidates the probe cache, and re-probes. + remoteArchiveSuffix = "-repackaged"; + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["model-swapped-a", "model-swapped-b"]), + ); + const swappedReady = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.models.some((model) => model.slug === "model-swapped-a"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const resolvesBeforeSwap = resolveAttempts; + yield* catalog.invalidateIndex(); + yield* instance.snapshot.refresh; + const swapped = Option.getOrThrow(yield* Fiber.join(swappedReady)); + expect(swapped.models.map((model) => model.slug)).toEqual([ + "model-swapped-a", + "model-swapped-b", + ]); + expect(lastResolvedCommand).toMatch( + new RegExp(`${compatibleRegistryTarget}-[0-9a-f]{12}[\\\\/]bin[\\\\/]test-agent$`), + ); + expect(yield* fileSystem.readFileString(lastResolvedCommand)).toBe( + "#!/bin/sh\necho 1.0.0-repackaged\n", + ); + expect( + yield* fileSystem.readFileString(installedBinaryPath(path, directory, "1.0.0")), + ).toBe("#!/bin/sh\necho 1.0.0\n"); + const resolvesAfterSwap = resolveAttempts; + expect(resolvesAfterSwap).toBeGreaterThan(resolvesBeforeSwap); + + // 4. Retained v1 live configuration/commands do not leak onto v2 readiness or probe snapshots, + // and a probe skipped during a foreground session stays pending until the session ends. + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "v1-stale-a", + availableModels: [ + { modelId: "v1-stale-a", name: "v1-stale-a" }, + { modelId: "v1-stale-b", name: "v1-stale-b" }, + ], + }), + ); + yield* coordinator.publishAvailableCommands(identity.instanceId, { + slashCommands: [{ name: "v1-stale-cmd" }], + skills: [], + }); + remoteVersion = "2.0.0"; + remoteWebsite = "https://example.test/v2"; + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["v2-model-a", "v2-model-b"])); + const sessionStarted = yield* Deferred.make(); + const releaseSession = yield* Deferred.make(); + const sessionFiber = yield* coordinator + .withForegroundStartup( + "test-agent", + Deferred.succeed(sessionStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseSession)), + ), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(sessionStarted); + + let sawV2InFirstRefresh = false; + const firstV2ProbeSkipped = yield* Deferred.make(); + onInspect = (inspection) => + inspection.status === "ready" && inspection.version === "2.0.0" + ? Effect.sync(() => { + sawV2InFirstRefresh = true; + }) + : Effect.void; + onBackgroundProbeOutcome = (skipped) => + skipped && sawV2InFirstRefresh + ? Deferred.succeed(firstV2ProbeSkipped, undefined).pipe(Effect.asVoid) + : Effect.void; + yield* TestClock.adjust("16 minutes"); + yield* instance.snapshot.refresh; + yield* Deferred.await(firstV2ProbeSkipped); + + // Collect every snapshot from Refresh #2 through v2 recovery to verify no v2 snapshot ever carries v1 live state. + const v2TransitionSnapshots = yield* instance.snapshot.streamChanges.pipe( + Stream.takeUntil( + (snapshot) => + snapshot.version === "2.0.0" && + snapshot.setup?.documentationUrl === "https://example.test/v2" && + snapshot.nativeSessions !== undefined, + ), + Stream.runCollect, + Effect.forkScoped({ startImmediately: true }), + ); + + // A second refresh while the session is still active skips both probes (auth + enrichment) AND rechecks v2 after refreshIndex. + let secondRefreshSkips = 0; + let secondRefreshIndexChecked = false; + const secondRefreshAllSkips = yield* Deferred.make(); + const secondRefreshRechecked = yield* Deferred.make(); + onBackgroundProbeOutcome = (skipped) => + skipped + ? Effect.sync(() => { + secondRefreshSkips += 1; + return secondRefreshSkips; + }).pipe( + Effect.flatMap((count) => + count >= 2 + ? Deferred.succeed(secondRefreshAllSkips, undefined).pipe(Effect.asVoid) + : Effect.void, + ), + ) + : Effect.void; + onRefreshIndex = Effect.sync(() => { + secondRefreshIndexChecked = true; + }); + onInspect = (inspection) => + secondRefreshIndexChecked && + inspection.status === "ready" && + inspection.version === "2.0.0" + ? Deferred.succeed(secondRefreshRechecked, undefined).pipe(Effect.asVoid) + : Effect.void; + yield* instance.snapshot.refresh; + yield* Deferred.await(secondRefreshAllSkips); + yield* Deferred.await(secondRefreshRechecked); + expect(resolveAttempts).toBe(resolvesAfterSwap); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "2.0.0"))).toBe(false); + + // Once the session ends, the next refresh installs v2 without another registry fetch and discards v1's stale live state. + onInspect = null; + onRefreshIndex = Effect.void; + onBackgroundProbeOutcome = null; + yield* Deferred.succeed(releaseSession, undefined); + yield* Fiber.join(sessionFiber); + const requestsBeforeRecovery = registryRequests; + yield* instance.snapshot.refresh; + const transitionSnapshots = yield* Fiber.join(v2TransitionSnapshots); + const v2Snapshots = transitionSnapshots.filter((snapshot) => snapshot.version === "2.0.0"); + expect(v2Snapshots.length).toBeGreaterThanOrEqual(2); + expect( + v2Snapshots.every( + (snapshot) => + !snapshot.slashCommands.some((command) => command.name === "v1-stale-cmd") && + !snapshot.models.some((model) => model.slug === "v1-stale-a"), + ), + ).toBe(true); + const recovered = v2Snapshots[v2Snapshots.length - 1]!; + expect(recovered.version).toBe("2.0.0"); + expect(recovered.models.map((model) => model.slug)).toEqual(["v2-model-a", "v2-model-b"]); + expect(recovered.slashCommands).toEqual([]); + expect(registryRequests).toBe(requestsBeforeRecovery); + expect(yield* fileSystem.exists(installedBinaryPath(path, directory, "2.0.0"))).toBe(true); + }).pipe(Effect.scoped, Effect.provide(driverLayer)), + ); + + it.effect("labels and caches probes using the runtime selected by catalog.resolve", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { directory, agentPath, modelsPath } = yield* seedInstalledBinaryAgent( + "acp-driver-resolved-identity-", + { website: "https://example.test/v1" }, + ); + + let remoteVersion = "2.0.0"; + let remoteWebsite = "https://example.test/v2"; + let switchedBeforeResolve = false; + let probeResolveAttempts = 0; + const inspectedVersionsBeforeSwitch: Array = []; + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, testHostPlatform), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + request.url === registryUrl + ? makeBinaryRegistry(remoteVersion, compatibleRegistryTarget, { + website: remoteWebsite, + }) + : `#!/bin/sh\necho ${remoteVersion}\n`, + ), + ), + ), + ), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + inspect: (settings, environment) => + realCatalog.inspect(settings, environment).pipe( + Effect.tap((inspection) => + !switchedBeforeResolve && inspection.status === "ready" + ? Effect.sync(() => { + inspectedVersionsBeforeSwitch.push(inspection.version); + }) + : Effect.void, + ), + ), + resolve: (settings, cwd, environment) => + Effect.gen(function* () { + const isProbeResolve = environment?.MISE_OFFLINE === "1"; + if (isProbeResolve) { + probeResolveAttempts += 1; + // Simulate a concurrent registry refresh advancing the index to 2.0.0 after inspect() saw 1.0.0. + if (!switchedBeforeResolve) { + switchedBeforeResolve = true; + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + } + } + const resolved = yield* realCatalog.resolve(settings, cwd, environment); + return { + ...resolved, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + }; + }), + }; + + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["v2-resolved-a", "v2-resolved-b"]), + ); + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + + // Let the initial startup check run once without triggering a concurrent refresh. + const firstProbed = Option.getOrThrow( + yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.nativeSessions !== undefined), + Stream.runHead, + ), + ); + // Even though inspect() saw 1.0.0, the published probe carries 2.0.0's resolved version and metadata. + expect(inspectedVersionsBeforeSwitch.length).toBeGreaterThan(0); + expect(inspectedVersionsBeforeSwitch.every((version) => version === "1.0.0")).toBe(true); + expect(firstProbed.version).toBe("2.0.0"); + expect(firstProbed.setup?.documentationUrl).toBe("https://example.test/v2"); + expect(firstProbed.models.map((model) => model.slug)).toEqual([ + "v2-resolved-a", + "v2-resolved-b", + ]); + expect(probeResolveAttempts).toBe(1); + + // Refreshing on 2.0.0 reuses the cached probe keyed by 2.0.0's resolved launch identity. + const cachedV2 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "2.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(cachedV2))).toBe(true); + expect(probeResolveAttempts).toBe(1); + + // Reverting upstream to 1.0.0 must miss the cache (proving v2's probe was not cached under 1.0.0's identity). + remoteVersion = "1.0.0"; + remoteWebsite = "https://example.test/v1"; + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["v1-fresh-a", "v1-fresh-b"])); + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const revertedV1 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.models.some((model) => model.slug === "v1-fresh-a"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const secondProbed = Option.getOrThrow(yield* Fiber.join(revertedV1)); + expect(secondProbed.models.map((model) => model.slug)).toEqual(["v1-fresh-a", "v1-fresh-b"]); + expect(probeResolveAttempts).toBe(2); + }).pipe(Effect.scoped, Effect.provide(driverLayer)), + ); + + it.effect( + "retires cached probes and live state when base checkProvider observes an uninstalled transition", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const { directory, agentPath, modelsPath } = yield* seedInstalledBinaryAgent( + "acp-driver-base-uninstall-", + ); + + let remoteVersion = "1.0.0"; + let remoteTarget: AcpRegistrySupport.AcpRegistryPlatformTarget = compatibleRegistryTarget; + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, testHostPlatform), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + request.url === registryUrl + ? makeBinaryRegistry(remoteVersion, remoteTarget) + : `#!/bin/sh\necho ${remoteVersion}\n`, + ), + ), + ), + ), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + resolve: (settings, cwd, environment) => + realCatalog.resolve(settings, cwd, environment).pipe( + Effect.map((resolved) => ({ + ...resolved, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + })), + ), + }; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog)); + + // Prime 1.0.0 cache and live state. + const initialReady = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "1.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(initialReady))).toBe(true); + yield* coordinator.publishAvailableCommands(identity.instanceId, { + slashCommands: [{ name: "stale-before-uninstall" }], + skills: [], + }); + + // Another caller refreshes the shared catalog to incompatible 2.0.0 so checkProvider directly sees !installed. + remoteVersion = "2.0.0"; + remoteTarget = incompatibleRegistryTarget; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const uninstalledSeen = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => !snapshot.installed && snapshot.version === "2.0.0"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(uninstalledSeen))).toBe(true); + + // Restoring 1.0.0 before the 15-minute probe TTL must re-probe fresh models and not restore stale commands. + remoteVersion = "1.0.0"; + remoteTarget = compatibleRegistryTarget; + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["recovered-fresh-a", "recovered-fresh-b"]), + ); + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const recovered = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.installed && + snapshot.version === "1.0.0" && + snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const freshSnapshot = Option.getOrThrow(yield* Fiber.join(recovered)); + expect(freshSnapshot.models.map((model) => model.slug)).toEqual([ + "recovered-fresh-a", + "recovered-fresh-b", + ]); + expect(freshSnapshot.slashCommands).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(driverLayer)), + ); + + it.effect( + "preserves new-runtime live state across upgrades while rejecting older or queued stale watcher updates", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseCoordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const { directory, agentPath, modelsPath } = yield* seedInstalledBinaryAgent( + "acp-driver-runtime-tagged-live-", + ); + + let remoteVersion = "1.0.0"; + let failProbeSpawn = false; + let failProbeSpawnOnce = false; + let inspectCalls = 0; + let resolveGate: { + readonly matchVersion: string; + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + let onInspectCallback: (() => Effect.Effect) | null = null; + let onCommandHandled: { + readonly matchName: string; + readonly done: Deferred.Deferred; + } | null = null; + let queuedStaleConfigGate: { + readonly entered: Deferred.Deferred; + readonly release: Deferred.Deferred; + readonly matchSlug: string; + } | null = null; + const coordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"] = + { + ...baseCoordinator, + watchAvailableCommands: (instanceId, onUpdate) => + baseCoordinator.watchAvailableCommands(instanceId, (commands, meta) => + onUpdate(commands, meta).pipe( + Effect.tap(() => { + if ( + onCommandHandled !== null && + commands.slashCommands.some((cmd) => cmd.name === onCommandHandled!.matchName) + ) { + const handled = onCommandHandled; + onCommandHandled = null; + return Deferred.succeed(handled.done, undefined).pipe(Effect.asVoid); + } + return Effect.void; + }), + ), + ), + watchLiveConfiguration: (instanceId, onUpdate) => + baseCoordinator.watchLiveConfiguration(instanceId, (configuration, meta) => { + const activeGate = + queuedStaleConfigGate !== null && + configuration.models.some( + (model) => model.id === queuedStaleConfigGate!.matchSlug, + ) + ? queuedStaleConfigGate + : null; + if (activeGate === null) return onUpdate(configuration, meta); + queuedStaleConfigGate = null; + return Deferred.succeed(activeGate.entered, undefined).pipe( + Effect.andThen(Deferred.await(activeGate.release)), + Effect.andThen(onUpdate(configuration, meta)), + ); + }), + }; + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, testHostPlatform), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + request.url === registryUrl + ? makeBinaryRegistry(remoteVersion) + : `#!/bin/sh\necho ${remoteVersion}\n`, + ), + ), + ), + ), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + inspect: (settings, environment) => + Effect.sync(() => { + inspectCalls += 1; + }).pipe( + Effect.andThen(() => realCatalog.inspect(settings, environment)), + Effect.tap(() => (onInspectCallback === null ? Effect.void : onInspectCallback())), + ), + resolve: (settings, cwd, environment) => + Effect.gen(function* () { + const resolved = yield* realCatalog.resolve(settings, cwd, environment); + if ( + environment?.MISE_OFFLINE === "1" && + resolveGate !== null && + resolved.agent?.version === resolveGate.matchVersion + ) { + const gate = resolveGate; + resolveGate = null; + yield* Deferred.succeed(gate.started, undefined); + yield* Deferred.await(gate.release); + } + if (environment?.MISE_OFFLINE === "1" && (failProbeSpawn || failProbeSpawnOnce)) { + failProbeSpawnOnce = false; + return yield* new AcpRegistrySupport.AcpRegistryError({ + reason: "install_failed", + detail: `Simulated probe install failure for ${resolved.agent?.version ?? "unknown"}.`, + }); + } + return { + ...resolved, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + }; + }), + }; + + const instance = yield* AcpRegistryDriver.create({ + instanceId: identity.instanceId, + displayName: identity.displayName, + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + ); + + // Prime 1.0.0 and capture its launch identity. + const initialReady = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "1.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + expect(Option.isSome(yield* Fiber.join(initialReady))).toBe(true); + const v1Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v1Inspection.status).toBe("ready"); + const v1Identity = v1Inspection.status === "ready" ? v1Inspection.launchIdentity! : ""; + + // 0. Same-runtime live config update arriving while a v1 probe is in flight discards the + // older v1 probe so stale probe models cannot overwrite newer live configuration. + // Publish an option-only update (models: []) so without the generation guard the stale + // probe's ["v1-stale-probe-a", "v1-stale-probe-b"] catalog would overwrite ["model-a", "model-b"]. + let onEnrichmentSpanEnd: ((exit: Exit.Exit) => void) | null = null; + const enrichmentTracer: Tracer.Tracer = { + span(options) { + const inner = Tracer.nativeTracer.span(options); + if (options.name !== "AcpRegistryDriver.publishEnrichment") return inner; + const origEnd = inner.end.bind(inner); + inner.end = (endTime, exit) => { + origEnd(endTime, exit); + onEnrichmentSpanEnd?.(exit); + }; + return inner; + }, + }; + yield* instance.invalidateCaches ?? Effect.void; + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["v1-stale-probe-a", "v1-stale-probe-b"]), + ); + const v1ProbeGate = { + matchVersion: "1.0.0", + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + resolveGate = v1ProbeGate; + const v1ProbeSnapshots: Array = []; + const v1ProbeCollector = yield* instance.snapshot.streamChanges.pipe( + Stream.runForEach((snapshot) => + Effect.sync(() => { + v1ProbeSnapshots.push(snapshot); + }), + ), + Effect.forkScoped({ startImmediately: true }), + ); + const v1StaleEnrichmentDone = yield* Deferred.make(); + onEnrichmentSpanEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(v1StaleEnrichmentDone, Exit.void); + } + }; + yield* instance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(v1ProbeGate.started); + const v1NewerLiveApplied = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.models.some((model) => + model.capabilities?.optionDescriptors?.some((opt) => opt.id === "v1-live-effort"), + ), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([ + { + id: "v1-live-effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [{ value: "high", name: "High" }], + }, + ]), + v1Identity, + ); + expect(Option.isSome(yield* Fiber.join(v1NewerLiveApplied))).toBe(true); + yield* Deferred.succeed(v1ProbeGate.release, undefined); + yield* Deferred.await(v1StaleEnrichmentDone); + onEnrichmentSpanEnd = null; + yield* Fiber.interrupt(v1ProbeCollector); + const v1AfterSuperseded = yield* instance.snapshot.getSnapshot; + // Without isProbeStillCurrent, the released probe would overwrite ["default"] with + // ["v1-stale-probe-a", "v1-stale-probe-b"] because the live update sent models: []. + expect(v1AfterSuperseded.models.map((model) => model.slug)).toEqual(["default"]); + expect( + v1AfterSuperseded.models.some((model) => + model.capabilities?.optionDescriptors?.some((opt) => opt.id === "v1-live-effort"), + ), + ).toBe(true); + expect( + v1ProbeSnapshots.every( + (snapshot) => !snapshot.models.some((model) => model.slug === "v1-stale-probe-a"), + ), + ).toBe(true); + + // Start a refresh that upgrades 1.0.0 -> 2.0.0 mid-enrichment while the live watcher stays active. + remoteVersion = "2.0.0"; + yield* fileSystem.writeFileString( + modelsPath, + JSON.stringify(["v2-probed-a", "v2-probed-b"]), + ); + yield* realCatalog.invalidateIndex(); + const v2ProbeGate = { + matchVersion: "2.0.0", + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + resolveGate = v2ProbeGate; + const v2ProbedReady = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "2.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Deferred.await(v2ProbeGate.started); + const v2Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v2Inspection.status).toBe("ready"); + const v2Identity = v2Inspection.status === "ready" ? v2Inspection.launchIdentity! : ""; + expect(v2Identity).not.toBe(v1Identity); + + // 1. A live config update from displayed runtime v1 (which also learns an effort option on shared-model) + // updates v1's displayed snapshot without discarding the in-flight v2 upgrade probe. + const v1LiveUpdated = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.models.some((model) => model.slug === "v1-during-probe-a"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration( + [ + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [ + { value: "low", name: "Low" }, + { value: "high", name: "High" }, + ], + }, + ], + undefined, + { + currentModelId: "shared-model", + availableModels: [ + { modelId: "v1-during-probe-a", name: "v1-during-probe-a" }, + { modelId: "shared-model", name: "shared-model" }, + ], + }, + ), + v1Identity, + ); + expect(Option.isSome(yield* Fiber.join(v1LiveUpdated))).toBe(true); + + // 2. Queue an UNTAGGED stale update on this active enrichment fiber before v2 commits + // so rejecting it later proves the clear watermark (!isCurrent) independently of runtimeIdentity. + const staleGate = { + entered: yield* Deferred.make(), + release: yield* Deferred.make(), + matchSlug: "v1-queued-a", + }; + queuedStaleConfigGate = staleGate; + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "v1-queued-a", + availableModels: [ + { modelId: "v1-queued-a", name: "v1-queued-a" }, + { modelId: "v1-queued-b", name: "v1-queued-b" }, + ], + }), + ); + yield* Deferred.await(staleGate.entered); + + // 3. Publish v2 live state while the v2 probe is already in flight; inFlightProbeIdentity must + // skip spawning a redundant reconcile inspect, and v2 must preserve its live state without + // inheriting v1 learnedModels. + const inspectsBeforeInFlightV2 = inspectCalls; + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v2-live-cmd" }], skills: [] }, + v2Identity, + ); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "v2-live-a", + availableModels: [ + { modelId: "v2-live-a", name: "v2-live-a" }, + { modelId: "shared-model", name: "shared-model" }, + ], + }), + v2Identity, + ); + yield* Deferred.succeed(v2ProbeGate.release, undefined); + + const publishedV2 = Option.getOrThrow(yield* Fiber.join(v2ProbedReady)); + expect(inspectCalls).toBe(inspectsBeforeInFlightV2); + expect(publishedV2.models.map((model) => model.slug)).toEqual([ + "v2-live-a", + "shared-model", + ]); + expect( + publishedV2.models.find((model) => model.slug === "shared-model")?.capabilities + ?.optionDescriptors ?? [], + ).toEqual([]); + expect(publishedV2.slashCommands).toEqual([{ name: "v2-live-cmd" }]); + + // Synchronize past runProbeAndPublish releasing liveSnapshotSemaphore (so clearLiveState has completed). + const v2PostClear = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((command) => command.name === "v2-post-clear"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v2-post-clear" }], skills: [] }, + v2Identity, + ); + expect(Option.isSome(yield* Fiber.join(v2PostClear))).toBe(true); + + // 4. Release the queued untagged update (rejected solely by !isCurrent), then publish post-clear v1-tagged + // updates (whose revision is AFTER clear, so rejected solely by runtimeIdentity) without evicting v2 state + // and without triggering reconcile catalog.inspect disk I/O for retired v1. + const inspectsBeforeRetiredV1 = inspectCalls; + const liveRaceSnapshots = yield* instance.snapshot.streamChanges.pipe( + Stream.takeUntil( + (snapshot) => + snapshot.models.some((model) => model.slug === "v2-final-a") && + snapshot.slashCommands.some((command) => command.name === "v2-after-race"), + ), + Stream.runCollect, + Effect.forkScoped({ startImmediately: true }), + ); + yield* Deferred.succeed(staleGate.release, undefined); + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "v1-late-a", + availableModels: [ + { modelId: "v1-late-a", name: "v1-late-a" }, + { modelId: "v1-late-b", name: "v1-late-b" }, + ], + }), + v1Identity, + ); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v1-late-cmd" }], skills: [] }, + v1Identity, + ); + // Late v1 publications must not evict v2's stored coordinator entry. + expect( + yield* coordinator.getAvailableCommands(identity.instanceId, { + runtimeIdentity: v2Identity, + requireMatchingRuntimeIdentity: true, + }), + ).toEqual(Option.some({ slashCommands: [{ name: "v2-post-clear" }], skills: [] })); + + yield* coordinator.publishLiveConfiguration( + identity.instanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "v2-final-a", + availableModels: [ + { modelId: "v2-final-a", name: "v2-final-a" }, + { modelId: "v2-final-b", name: "v2-final-b" }, + ], + }), + v2Identity, + ); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v2-after-race" }], skills: [] }, + v2Identity, + ); + const observedAfterRace = yield* Fiber.join(liveRaceSnapshots); + // Trigger a subsequent unmatched identity inspect on driverScope to drain any concurrently + // forked fibers from retired v1 updates: exactly 1 inspect (for the sentinel) must run. + const retiredDrainDone = yield* Deferred.make(); + onInspectCallback = () => Deferred.succeed(retiredDrainDone, undefined).pipe(Effect.asVoid); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "sentinel-after-retired" }], skills: [] }, + "retired-drain-sentinel", + ); + yield* Deferred.await(retiredDrainDone); + onInspectCallback = null; + expect(inspectCalls).toBe(inspectsBeforeRetiredV1 + 1); + expect( + observedAfterRace.every( + (snapshot) => + !snapshot.models.some( + (model) => model.slug === "v1-queued-a" || model.slug === "v1-late-a", + ) && !snapshot.slashCommands.some((command) => command.name === "v1-late-cmd"), + ), + ).toBe(true); + const afterRace = observedAfterRace[observedAfterRace.length - 1]!; + expect(afterRace.models.map((model) => model.slug)).toEqual(["v2-final-a", "v2-final-b"]); + expect(afterRace.slashCommands).toEqual([{ name: "v2-after-race" }]); + + // 5. When the shared catalog advances to 3.0.0 and a 3.0.0 session publishes live commands before this + // instance refreshes, the driver automatically reconciles to 3.0.0 instead of dropping the update. + remoteVersion = "3.0.0"; + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["v3-model-a", "v3-model-b"])); + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const v3Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v3Inspection.status).toBe("ready"); + const v3Identity = v3Inspection.status === "ready" ? v3Inspection.launchIdentity! : ""; + const reconciledV3 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "3.0.0" && + snapshot.nativeSessions !== undefined && + snapshot.slashCommands.some((command) => command.name === "v3-session-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const v3EnrichmentSettled = yield* Deferred.make(); + let sawV3Enrichment = false; + const v3Tracer: Tracer.Tracer = { + span(options) { + const inner = Tracer.nativeTracer.span(options); + if (options.name !== "AcpRegistryDriver.publishEnrichment") return inner; + const origEnd = inner.end.bind(inner); + inner.end = (endTime, exit) => { + origEnd(endTime, exit); + if (sawV3Enrichment && Exit.isSuccess(exit)) { + Deferred.doneUnsafe(v3EnrichmentSettled, Exit.void); + } + }; + return inner; + }, + }; + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v3-session-cmd" }], skills: [] }, + v3Identity, + ); + const v3Snapshot = Option.getOrThrow(yield* Fiber.join(reconciledV3)); + expect(v3Snapshot.version).toBe("3.0.0"); + expect(v3Snapshot.slashCommands).toEqual([{ name: "v3-session-cmd" }]); + // Settle the 3.0.0 enrichment cycle before counting inspects for the unmatched-runtime check. + sawV3Enrichment = true; + yield* instance.snapshot.refresh.pipe(Effect.provideService(Tracer.Tracer, v3Tracer)); + yield* Deferred.await(v3EnrichmentSettled); + + // An unrecognized runtime identity that does NOT match catalog.inspect must not trigger a refresh. + const unmatchedChecked = yield* Deferred.make(); + onInspectCallback = () => Deferred.succeed(unmatchedChecked, undefined).pipe(Effect.asVoid); + const inspectsBeforeUnmatched = inspectCalls; + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "bogus-future-cmd" }], skills: [] }, + "unmatched-future-runtime", + ); + yield* Deferred.await(unmatchedChecked); + onInspectCallback = null; + const v3Check = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((command) => command.name === "v3-still-active"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v3-still-active" }], skills: [] }, + v3Identity, + ); + expect(Option.isSome(yield* Fiber.join(v3Check))).toBe(true); + // Only the 1 reconcile inspect ran; no refresh (which would invoke another inspect) fired. + expect(inspectCalls).toBe(inspectsBeforeUnmatched + 1); + + // 6. A failed upgrade probe (4.0.0 fails before resolving/starting) must NOT report 4.0.0 as + // installed, drop v3's discovered models, wipe v3 coordinator state, or reject v3 live updates— + // even across repeated refreshes while 4.0.0 remains broken. + remoteVersion = "4.0.0"; + failProbeSpawn = true; + yield* realCatalog.invalidateIndex(); + const failedUpgradeWarning = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.status === "warning"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const warningSnapshot = Option.getOrThrow(yield* Fiber.join(failedUpgradeWarning)); + expect(warningSnapshot.version).toBe("3.0.0"); + expect(warningSnapshot.models.map((model) => model.slug)).toEqual([ + "v3-model-a", + "v3-model-b", + ]); + expect(warningSnapshot.slashCommands).toEqual([{ name: "v3-still-active" }]); + expect( + yield* coordinator.getAvailableCommands(identity.instanceId, { + runtimeIdentity: v3Identity, + requireMatchingRuntimeIdentity: true, + }), + ).toEqual(Option.some({ slashCommands: [{ name: "v3-still-active" }], skills: [] })); + const v3AfterFailedUpgrade = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((command) => command.name === "v3-after-failed-v4"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v3-after-failed-v4" }], skills: [] }, + v3Identity, + ); + expect(Option.isSome(yield* Fiber.join(v3AfterFailedUpgrade))).toBe(true); + + // A second refresh while 4.0.0 is still failing must stay on 3.0.0 without flickering to + // 4.0.0 and must preserve v3's discovered models and live commands. + const secondFailedRefreshSnapshots: Array = []; + const secondFailedCollector = yield* instance.snapshot.streamChanges.pipe( + Stream.runForEach((snapshot) => + Effect.sync(() => { + secondFailedRefreshSnapshots.push(snapshot); + }), + ), + Effect.forkScoped({ startImmediately: true }), + ); + const secondFailedDone = yield* Deferred.make(); + onEnrichmentSpanEnd = (exit) => { + if (Exit.isSuccess(exit)) { + Deferred.doneUnsafe(secondFailedDone, Exit.void); + } + }; + yield* instance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(secondFailedDone); + onEnrichmentSpanEnd = null; + yield* Fiber.interrupt(secondFailedCollector); + expect(secondFailedRefreshSnapshots.every((snapshot) => snapshot.version === "3.0.0")).toBe( + true, + ); + const afterSecondFailed = yield* instance.snapshot.getSnapshot; + expect(afterSecondFailed.version).toBe("3.0.0"); + expect(afterSecondFailed.status).toBe("warning"); + expect(afterSecondFailed.models.map((model) => model.slug)).toEqual([ + "v3-model-a", + "v3-model-b", + ]); + expect(afterSecondFailed.slashCommands).toEqual([{ name: "v3-after-failed-v4" }]); + + // Once 4.0.0 recovers, the next refresh cleanly upgrades and clears the warning. + failProbeSpawn = false; + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(["v4-model-a", "v4-model-b"])); + const recoveredToV4 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "4.0.0" && + snapshot.status === "ready" && + snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + const v4Recovered = Option.getOrThrow(yield* Fiber.join(recoveredToV4)); + expect(v4Recovered.models.map((model) => model.slug)).toEqual(["v4-model-a", "v4-model-b"]); + expect(v4Recovered.message).toBeUndefined(); + const v4Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v4Inspection.status).toBe("ready"); + const v4Identity = v4Inspection.status === "ready" ? v4Inspection.launchIdentity! : ""; + + // 7. Rolling the shared registry back to a previously retired version (3.0.0) allows a new + // 3.0.0 session's live state to reconcile the driver back to 3.0.0. + remoteVersion = "3.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const rolledBackToV3 = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "3.0.0" && + snapshot.nativeSessions !== undefined && + snapshot.slashCommands.some((command) => command.name === "v3-rollback-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v3-rollback-cmd" }], skills: [] }, + v3Identity, + ); + expect(Option.isSome(yield* Fiber.join(rolledBackToV3))).toBe(true); + + // 8. If a live update parks in pendingReconcileIdentity while an upgrade probe is in flight + // (while 3.0.0 is still displayed) and that probe fails, releasing inFlightProbeIdentity + // first lets the parked identity drain and reconcile automatically without another event. + remoteVersion = "4.0.0"; + yield* realCatalog.invalidateIndex(); + const v4ParkedGate = { + matchVersion: "4.0.0", + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + resolveGate = v4ParkedGate; + failProbeSpawnOnce = true; + const v4ReconciledFromParked = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "4.0.0" && + snapshot.status === "ready" && + snapshot.nativeSessions !== undefined && + snapshot.slashCommands.some((command) => command.name === "v4-parked-after-fail"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Deferred.await(v4ParkedGate.started); + const v4ParkedHandled = yield* Deferred.make(); + onCommandHandled = { matchName: "v4-parked-after-fail", done: v4ParkedHandled }; + yield* coordinator.publishAvailableCommands( + identity.instanceId, + { slashCommands: [{ name: "v4-parked-after-fail" }], skills: [] }, + v4Identity, + ); + // Wait for the watcher to park v4Identity in pendingReconcileIdentity while the probe is still blocked. + yield* Deferred.await(v4ParkedHandled); + yield* Deferred.succeed(v4ParkedGate.release, undefined); + const reconciledFromParked = Option.getOrThrow(yield* Fiber.join(v4ReconciledFromParked)); + expect(reconciledFromParked.version).toBe("4.0.0"); + expect(reconciledFromParked.message).toBeUndefined(); + + // 9. Disposing a driver instance removes its coordinator state and marks earlier metadata stale. + const disposedInstanceId = ProviderInstanceId.make("acpRegistry_disposed_cleanup"); + const disposedScope = yield* Scope.make(); + let disposedMeta: AcpRegistryRuntimeCoordinator.AcpRegistryLiveUpdateMeta | null = null; + const disposedWatched = yield* Deferred.make(); + const disposedWatcher = yield* coordinator + .watchAvailableCommands(disposedInstanceId, (_commands, meta) => + Effect.sync(() => { + disposedMeta = meta; + }).pipe(Effect.andThen(Deferred.succeed(disposedWatched, undefined)), Effect.asVoid), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* AcpRegistryDriver.create({ + instanceId: disposedInstanceId, + displayName: "Disposed ACP", + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Scope.provide(disposedScope), + ); + yield* coordinator.publishAvailableCommands( + disposedInstanceId, + { slashCommands: [{ name: "before-dispose" }], skills: [] }, + v3Identity, + ); + yield* Deferred.await(disposedWatched); + expect(disposedMeta).not.toBeNull(); + expect(yield* disposedMeta!.isCurrent).toBe(true); + yield* Scope.close(disposedScope, Exit.void); + expect(Option.isNone(yield* coordinator.getAvailableCommands(disposedInstanceId))).toBe( + true, + ); + expect(yield* disposedMeta!.isCurrent).toBe(false); + yield* Fiber.interrupt(disposedWatcher); + }).pipe(Effect.scoped, Effect.provide(driverLayer)), + ); + + it.effect( + "preserves foreground-only live runtimes on upgrade failure, stamps fallback retirements at the failed target revision, and drains events arriving during in-flight reconciliation", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseCoordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const { directory, agentPath, modelsPath } = yield* seedInstalledBinaryAgent( + "acp-driver-reconcile-edge-", + ); + const authFailAgentPath = path.join(directory, "auth-fail-agent.mjs"); + const exitFailAgentPath = path.join(directory, "exit-fail-agent.mjs"); + const logoutAgentPath = path.join(directory, "logout-agent.mjs"); + const authLoginAgentPath = path.join(directory, "auth-login-agent.mjs"); + const versionlessLocalAgentPath = path.join(directory, "versionless-local-agent.mjs"); + yield* fileSystem.writeFileString(exitFailAgentPath, "process.exit(1);\n"); + yield* fileSystem.writeFileString( + logoutAgentPath, + fakeAgentSource.replace( + "agentCapabilities: {}", + "agentCapabilities: { auth: { logout: {} } }", + ), + ); + yield* fileSystem.writeFileString( + authLoginAgentPath, + fakeAgentSource.replace( + "authMethods: []", + 'authMethods: [{ id: "agent-login", name: "Agent Login", type: "agent" }]', + ), + ); + yield* fileSystem.writeFileString( + versionlessLocalAgentPath, + fakeAgentSource.replace( + 'agentInfo: { name: "fake", version: "1.5.9" }', + 'agentInfo: { name: "fake", version: "" }', + ), + ); + yield* fileSystem.writeFileString( + authFailAgentPath, + ` +import { createInterface } from "node:readline"; +const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); +createInterface({ input: process.stdin }).on("line", (line) => { + const { id, method } = JSON.parse(line); + if (id === undefined) return; + if (method === "initialize") { + send({ + id, + result: { + protocolVersion: 1, + agentCapabilities: {}, + authMethods: [{ id: "api-key", name: "API key", type: "env_var", vars: [{ name: "API_KEY" }] }], + agentInfo: { name: "fake", version: "2.0.0" }, + }, + }); + } else if (method === "session/new") { + send({ id, error: { code: -32000, message: "Authentication required" } }); + } else { + send({ id, result: {} }); + } +}); +`, + ); + + let remoteVersion = "1.0.0"; + let remoteExtraAgentVersion: string | undefined = undefined; + let failArchiveVersions = new Set(); + let failProbeSpawn = false; + let failProbeAuth = false; + let failProbeExit = false; + let useLogoutAgent = false; + let useAuthLoginAgent = false; + let probeResolveCount = 0; + let defectInspectCount = 0; + let interruptInspectOnce = false; + let inspectCalls = 0; + let onRefreshIndex: (() => Effect.Effect) | null = null; + let onBeforeProbeResolve: (() => Effect.Effect) | null = null; + let recordedInspectRevisions: Array | null = null; + let resolveGate: { + readonly matchVersion: string; + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + let inspectGate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + let getAvailableCommandsGate: { + readonly instanceId: ProviderInstanceId; + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + readonly interrupted: Deferred.Deferred; + } | null = null; + let onCommandHandled: { + readonly matchName: string; + readonly done: Deferred.Deferred; + } | null = null; + let onConfigHandled: { + readonly matchModelId: string; + readonly done: Deferred.Deferred; + } | null = null; + let onEnrichmentEnd: (() => void) | null = null; + let onReconcileEnd: ((exit: Exit.Exit) => void) | null = null; + const enrichmentTracer: Tracer.Tracer = { + span(options) { + const inner = Tracer.nativeTracer.span(options); + if ( + options.name !== "AcpRegistryDriver.publishEnrichment" && + options.name !== "AcpRegistryDriver.reconcileUnmatchedRuntime" + ) { + return inner; + } + const origEnd = inner.end.bind(inner); + inner.end = (endTime, exit) => { + origEnd(endTime, exit); + if (options.name === "AcpRegistryDriver.publishEnrichment" && Exit.isSuccess(exit)) { + const cb = onEnrichmentEnd; + onEnrichmentEnd = null; + cb?.(); + } else if (options.name === "AcpRegistryDriver.reconcileUnmatchedRuntime") { + const cb = onReconcileEnd; + onReconcileEnd = null; + cb?.(exit); + } + }; + return inner; + }, + }; + const coordinator: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"] = + { + ...baseCoordinator, + getAvailableCommands: (instanceId, options) => { + if ( + getAvailableCommandsGate !== null && + getAvailableCommandsGate.instanceId === instanceId + ) { + const gate = getAvailableCommandsGate; + getAvailableCommandsGate = null; + return Deferred.succeed(gate.started, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + Effect.onInterrupt(() => + Deferred.succeed(gate.interrupted, undefined).pipe(Effect.asVoid), + ), + Effect.andThen(baseCoordinator.getAvailableCommands(instanceId, options)), + ); + } + return baseCoordinator.getAvailableCommands(instanceId, options); + }, + watchAvailableCommands: (instanceId, onUpdate) => + baseCoordinator.watchAvailableCommands(instanceId, (commands, meta) => + onUpdate(commands, meta).pipe( + Effect.tap(() => { + if ( + onCommandHandled !== null && + commands.slashCommands.some((cmd) => cmd.name === onCommandHandled!.matchName) + ) { + const handled = onCommandHandled; + onCommandHandled = null; + return Deferred.succeed(handled.done, undefined).pipe(Effect.asVoid); + } + return Effect.void; + }), + ), + ), + watchLiveConfiguration: (instanceId, onUpdate) => + baseCoordinator.watchLiveConfiguration(instanceId, (configuration, meta) => + onUpdate(configuration, meta).pipe( + Effect.tap(() => { + if ( + onConfigHandled !== null && + configuration.models.some( + (model) => model.id === onConfigHandled!.matchModelId, + ) + ) { + const handled = onConfigHandled; + onConfigHandled = null; + return Deferred.succeed(handled.done, undefined).pipe(Effect.asVoid); + } + return Effect.void; + }), + ), + ), + }; + const realCatalog = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir: directory, + toolsDir: path.join(directory, "tools"), + registryUrl, + }).pipe( + Effect.provideService(HostProcess.Platform, testHostPlatform), + Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => { + if (request.url === registryUrl) { + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + makeBinaryRegistry( + remoteVersion, + compatibleRegistryTarget, + remoteExtraAgentVersion + ? { extraAgentVersion: remoteExtraAgentVersion } + : undefined, + ), + ), + ), + ); + } + const failDownload = Array.from(failArchiveVersions).some((version) => + request.url.includes(`-${version}.bin`), + ); + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + failDownload + ? new Response("unavailable", { status: 503 }) + : new Response(`#!/bin/sh\necho ${remoteVersion}\n`), + ), + ); + }), + ), + ); + const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...realCatalog, + refreshIndex: (options) => + Effect.gen(function* () { + if (onRefreshIndex !== null) { + const hook = onRefreshIndex; + onRefreshIndex = null; + yield* hook(); + } + return yield* realCatalog.refreshIndex(options); + }), + inspect: (settings, environment) => + Effect.gen(function* () { + inspectCalls += 1; + if (interruptInspectOnce) { + interruptInspectOnce = false; + if (inspectGate !== null) { + const gate = inspectGate; + inspectGate = null; + yield* Deferred.succeed(gate.started, undefined); + yield* Deferred.await(gate.release); + } + return yield* Effect.interrupt; + } + if (defectInspectCount > 0) { + defectInspectCount -= 1; + if (inspectGate !== null) { + const gate = inspectGate; + inspectGate = null; + yield* Deferred.succeed(gate.started, undefined); + yield* Deferred.await(gate.release); + } + return yield* Effect.die("simulated reconcile inspect defect"); + } + const result = yield* realCatalog.inspect(settings, environment); + if (recordedInspectRevisions !== null) { + recordedInspectRevisions.push( + "indexRevision" in result ? result.indexRevision : undefined, + ); + } + if (inspectGate !== null) { + const gate = inspectGate; + inspectGate = null; + yield* Deferred.succeed(gate.started, undefined); + yield* Deferred.await(gate.release); + } + return result; + }), + resolve: (settings, cwd, environment) => + Effect.gen(function* () { + if (environment?.MISE_OFFLINE === "1") { + probeResolveCount += 1; + } + if (environment?.MISE_OFFLINE === "1" && onBeforeProbeResolve !== null) { + const hook = onBeforeProbeResolve; + onBeforeProbeResolve = null; + yield* hook(); + } + const resolved = yield* realCatalog.resolve(settings, cwd, environment); + if ( + environment?.MISE_OFFLINE === "1" && + resolveGate !== null && + resolved.agent?.version === resolveGate.matchVersion + ) { + const gate = resolveGate; + resolveGate = null; + yield* Deferred.succeed(gate.started, undefined); + yield* Deferred.await(gate.release); + } + if (environment?.MISE_OFFLINE === "1" && failProbeSpawn) { + return yield* new AcpRegistrySupport.AcpRegistryError({ + reason: "install_failed", + detail: `Simulated probe install failure for ${resolved.agent?.version ?? "unknown"}.`, + }); + } + return { + ...resolved, + spawn: { + command: process.execPath, + args: + environment?.MISE_OFFLINE === "1" && failProbeExit + ? [exitFailAgentPath] + : environment?.MISE_OFFLINE === "1" && failProbeAuth + ? [authFailAgentPath] + : [ + useAuthLoginAgent + ? authLoginAgentPath + : useLogoutAgent + ? logoutAgentPath + : agentPath, + modelsPath, + ], + }, + }; + }), + }; + + // 1. Foreground startup skips initial 1.0.0 probe while live 1.0.0 sessions publish config + // only OR commands only; when 2.0.0 later fails (including authentication_failed), each + // snapshot retains 1.0.0 without copying 2.0.0's unauthenticated state onto 1.0.0. + const fgConfigOnlyId = ProviderInstanceId.make("acpRegistry_fg_config_only_v1"); + const fgCmdOnlyId = ProviderInstanceId.make("acpRegistry_fg_cmd_only_v1"); + const fgStarted = yield* Deferred.make(); + const releaseFg = yield* Deferred.make(); + const fgFiber = yield* coordinator + .withForegroundStartup( + "test-agent", + Deferred.succeed(fgStarted, undefined).pipe(Effect.andThen(Deferred.await(releaseFg))), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(fgStarted); + + const fgConfigInstance = yield* AcpRegistryDriver.create({ + instanceId: fgConfigOnlyId, + displayName: "FG Config Only", + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + ); + const fgCmdInstance = yield* AcpRegistryDriver.create({ + instanceId: fgCmdOnlyId, + displayName: "FG Cmd Only", + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + ); + const v1Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v1Inspection.status).toBe("ready"); + const v1Identity = v1Inspection.status === "ready" ? v1Inspection.launchIdentity! : ""; + const fgConfigLiveReady = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.models.some((model) => model.slug === "fg-v1-a"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const fgCmdLiveReady = yield* fgCmdInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "1.0.0" && + snapshot.slashCommands.some((cmd) => cmd.name === "fg-v1-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* fgConfigInstance.snapshot.refresh; + yield* fgCmdInstance.snapshot.refresh; + yield* coordinator.publishLiveConfiguration( + fgConfigOnlyId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "fg-v1-a", + availableModels: [ + { modelId: "fg-v1-a", name: "fg-v1-a" }, + { modelId: "fg-v1-b", name: "fg-v1-b" }, + ], + }), + v1Identity, + ); + yield* coordinator.publishAvailableCommands( + fgCmdOnlyId, + { slashCommands: [{ name: "fg-v1-cmd" }], skills: [] }, + v1Identity, + ); + expect(Option.isSome(yield* Fiber.join(fgConfigLiveReady))).toBe(true); + expect(Option.isSome(yield* Fiber.join(fgCmdLiveReady))).toBe(true); + + // End foreground startup, move index to 2.0.0 failing with authentication_failed, and + // verify both 1.0.0 snapshots stay on 1.0.0 without copying 2.0.0's unauthenticated auth. + yield* Deferred.succeed(releaseFg, undefined); + yield* Fiber.join(fgFiber); + remoteVersion = "2.0.0"; + failProbeAuth = true; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fgConfigWarning = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.status === "warning"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const fgCmdWarning = yield* fgCmdInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.status === "warning"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const fgConfigWarningDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fgConfigWarningDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + const fgConfigWarningSnapshot = Option.getOrThrow(yield* Fiber.join(fgConfigWarning)); + yield* Deferred.await(fgConfigWarningDone); + const fgCmdWarningDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fgCmdWarningDone, Exit.void); + yield* fgCmdInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + expect(fgConfigWarningSnapshot.version).toBe("1.0.0"); + expect(fgConfigWarningSnapshot.auth.status).toBe("unknown"); + expect(fgConfigWarningSnapshot.message).toContain("API key"); + expect(fgConfigWarningSnapshot.models.map((model) => model.slug)).toEqual([ + "fg-v1-a", + "fg-v1-b", + ]); + const fgCmdWarningSnapshot = Option.getOrThrow(yield* Fiber.join(fgCmdWarning)); + yield* Deferred.await(fgCmdWarningDone); + expect(fgCmdWarningSnapshot.version).toBe("1.0.0"); + expect(fgCmdWarningSnapshot.auth.status).toBe("unknown"); + expect(fgCmdWarningSnapshot.slashCommands).toEqual([{ name: "fg-v1-cmd" }]); + + // A live config update while retaining 1.0.0 under an upgrade failure must not bake the + // transient upgrade warning message into lastSuccessfulRuntime: when 1.0.0 is rolled back + // to and probed again, the old 2.0.0 warning message is gone. + const fgConfigUpdatedDuringWarn = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((model) => model.slug === "fg-v1-c")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + fgConfigOnlyId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "fg-v1-c", + availableModels: [ + { modelId: "fg-v1-a", name: "fg-v1-a" }, + { modelId: "fg-v1-c", name: "fg-v1-c" }, + ], + }), + v1Identity, + ); + const warnedWithC = Option.getOrThrow(yield* Fiber.join(fgConfigUpdatedDuringWarn)); + expect(warnedWithC.message).toContain("API key"); + // Another refresh while 2.0.0 still fails must publish 1.0.0 with non-unauthenticated auth + // and the auth warning once the second probe's enrichment actually completes. + const secondAuthEnrichmentDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(secondAuthEnrichmentDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(secondAuthEnrichmentDone); + const secondAuthPublished = yield* fgConfigInstance.snapshot.getSnapshot; + expect(secondAuthPublished.version).toBe("1.0.0"); + expect(secondAuthPublished.status).toBe("warning"); + expect(secondAuthPublished.auth.status).toBe("unknown"); + expect(secondAuthPublished.message).toContain("API key"); + + // Post-resolution authentication_failed uses the ACTUALLY RESOLVED runtime identity: + // (a) inspect reads 1.0.0, resolve refreshes/launches 2.0.0 which fails auth -> retained + // 1.0.0 stays auth.status === "unknown" (not marked unauthenticated). + remoteVersion = "1.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + // Ensure 1.0.0 has a valid receipted install on disk for fallback check (b) below. + yield* realCatalog.resolve(decodeSettings({ agentId: "test-agent" }), directory); + onBeforeProbeResolve = () => { + remoteVersion = "2.0.0"; + return realCatalog + .invalidateIndex() + .pipe( + Effect.andThen(realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 })), + Effect.ignore, + ); + }; + const mismatchUpgradeDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(mismatchUpgradeDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(mismatchUpgradeDone); + const mismatchUpgradeSnapshot = yield* fgConfigInstance.snapshot.getSnapshot; + expect(mismatchUpgradeSnapshot.version).toBe("1.0.0"); + expect(mismatchUpgradeSnapshot.status).toBe("warning"); + expect(mismatchUpgradeSnapshot.auth.status).toBe("unknown"); + expect(mismatchUpgradeSnapshot.message).toContain("API key"); + + // (b) inspect reads 2.0.0, resolve falls back to installed 1.0.0 (503 on 2.0.0), and + // 1.0.0 fails auth -> 1.0.0's OWN auth.status becomes "unauthenticated". + yield* fileSystem.remove(path.join(directory, "tools", "test-agent", "2.0.0"), { + recursive: true, + force: true, + }); + remoteVersion = "2.0.0"; + failArchiveVersions = new Set(["2.0.0"]); + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fallbackAuthDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fallbackAuthDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fallbackAuthDone); + const fallbackAuthSnapshot = yield* fgConfigInstance.snapshot.getSnapshot; + expect(fallbackAuthSnapshot.version).toBe("1.0.0"); + expect(fallbackAuthSnapshot.status).toBe("warning"); + expect(fallbackAuthSnapshot.auth.status).toBe("unauthenticated"); + expect(fallbackAuthSnapshot.message).toContain("API key"); + + // A live config update while the active runtime itself is unauthenticated must preserve + // warning status, unauthenticated auth, and sign-in guidance instead of flipping to ready. + const unauthLiveUpdated = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((model) => model.slug === "fg-v1-d")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + fgConfigOnlyId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "fg-v1-d", + availableModels: [ + { modelId: "fg-v1-a", name: "fg-v1-a" }, + { modelId: "fg-v1-d", name: "fg-v1-d" }, + ], + }), + v1Identity, + ); + const unauthWithD = Option.getOrThrow(yield* Fiber.join(unauthLiveUpdated)); + expect(unauthWithD.status).toBe("warning"); + expect(unauthWithD.auth.status).toBe("unauthenticated"); + expect(unauthWithD.message).toContain("API key"); + + // (c) Fallback auth failure records failedTarget.indexRevision so a refresh where resolve + // discovers a newer failing target (2.0.1) and falls back to 1.0.0 does not re-probe + // 2.0.1 / 1.0.0 a second time inside the same refresh. + failArchiveVersions = new Set(["2.0.0", "2.0.1"]); + onBeforeProbeResolve = () => { + remoteVersion = "2.0.1"; + return realCatalog + .invalidateIndex() + .pipe( + Effect.andThen(realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 })), + Effect.ignore, + ); + }; + probeResolveCount = 0; + const fallbackRevDedupDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fallbackRevDedupDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fallbackRevDedupDone); + expect(probeResolveCount).toBe(1); + + // (d) A post-resolution non-auth failure after fallback (2.0.1 download fails, fallback + // 1.0.0 exits immediately) must preserve warning + the real probe error and replace + // failedUpgradeTarget so the stale "API key" message does not return on live updates. + failProbeAuth = false; + failProbeExit = true; + const fallbackExitDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fallbackExitDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fallbackExitDone); + const fallbackExitSnapshot = yield* fgConfigInstance.snapshot.getSnapshot; + expect(fallbackExitSnapshot.version).toBe("1.0.0"); + expect(fallbackExitSnapshot.status).toBe("warning"); + // Retains step (b)'s auth rejection rather than clearing it on a startup crash. + expect(fallbackExitSnapshot.auth.status).toBe("unauthenticated"); + expect(fallbackExitSnapshot.message).toBeDefined(); + expect(fallbackExitSnapshot.message).not.toContain("API key"); + const exitLiveUpdated = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((model) => model.slug === "fg-v1-e")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + fgConfigOnlyId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "fg-v1-e", + availableModels: [ + { modelId: "fg-v1-a", name: "fg-v1-a" }, + { modelId: "fg-v1-e", name: "fg-v1-e" }, + ], + }), + v1Identity, + ); + const exitWithE = Option.getOrThrow(yield* Fiber.join(exitLiveUpdated)); + expect(exitWithE.status).toBe("warning"); + expect(exitWithE.message).toBeDefined(); + expect(exitWithE.message).not.toContain("API key"); + failProbeExit = false; + + // (e) Non-upgrade same-runtime auth failure clears failedUpgradeTarget and preserves + // warning + unauthenticated + sign-in message across live config updates via + // preserveUnauthenticated (without failedUpgradeTarget or activeFallback). + failArchiveVersions = new Set(); + remoteVersion = "1.0.0"; + failProbeAuth = true; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const directUnauthDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(directUnauthDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(directUnauthDone); + const directUnauthLive = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((model) => model.slug === "fg-v1-f")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + fgConfigOnlyId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "fg-v1-f", + availableModels: [ + { modelId: "fg-v1-a", name: "fg-v1-a" }, + { modelId: "fg-v1-f", name: "fg-v1-f" }, + ], + }), + v1Identity, + ); + const directUnauthWithF = Option.getOrThrow(yield* Fiber.join(directUnauthLive)); + expect(directUnauthWithF.status).toBe("warning"); + expect(directUnauthWithF.auth.status).toBe("unauthenticated"); + expect(directUnauthWithF.message).toContain("API key"); + + // (f) After a successful fallback sets activeFallback, a subsequent auth rejection on the + // fallback runtime preserves the auth warning across live config updates (taking + // precedence over activeFallback's install notice) and clears activeFallback so + // subsequent refreshes don't mask it behind backoff. + failProbeAuth = false; + remoteVersion = "2.0.0"; + failArchiveVersions = new Set(["2.0.0"]); + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const activeFbReadyDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(activeFbReadyDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(activeFbReadyDone); + expect((yield* fgConfigInstance.snapshot.getSnapshot).status).toBe("ready"); + expect((yield* fgConfigInstance.snapshot.getSnapshot).message).toContain("2.0.0"); + yield* TestClock.adjust("61 seconds"); + failProbeAuth = true; + const activeFbUnauthDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(activeFbUnauthDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(activeFbUnauthDone); + const activeFbUnauthLive = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((model) => model.slug === "fg-v1-g")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + fgConfigOnlyId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "fg-v1-g", + availableModels: [ + { modelId: "fg-v1-a", name: "fg-v1-a" }, + { modelId: "fg-v1-g", name: "fg-v1-g" }, + ], + }), + v1Identity, + ); + const activeFbWithG = Option.getOrThrow(yield* Fiber.join(activeFbUnauthLive)); + expect(activeFbWithG.status).toBe("warning"); + expect(activeFbWithG.auth.status).toBe("unauthenticated"); + expect(activeFbWithG.message).toContain("API key"); + // Follow-up refresh must never mask the rejection behind activeFallback or drop + // latestAcceptedAuth during readiness (every emitted snapshot stays warning/unauthenticated). + const followUpSnapshots: Array = []; + const followUpCollector = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.runForEach((snapshot) => + Effect.sync(() => { + followUpSnapshots.push(snapshot); + }), + ), + Effect.forkScoped({ startImmediately: true }), + ); + const activeFbFollowUpDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(activeFbFollowUpDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(activeFbFollowUpDone); + yield* Fiber.interrupt(followUpCollector); + expect(followUpSnapshots.length).toBeGreaterThan(0); + for (const emitted of followUpSnapshots) { + expect(emitted.status).toBe("warning"); + expect(emitted.auth.status).toBe("unauthenticated"); + } + failProbeAuth = false; + failArchiveVersions = new Set(); + remoteVersion = "2.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + + // Now make 2.0.0 fail with a different install_failed message and verify the earlier + // auth warning message did not leak into lastSuccessfulRuntime. + failProbeSpawn = true; + const fgSwitchedWarning = yield* fgConfigInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => Boolean(snapshot.message?.includes("2.0.0"))), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const fgSwitchedDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fgSwitchedDone, Exit.void); + yield* fgConfigInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + const fgSwitchedSnapshot = Option.getOrThrow(yield* Fiber.join(fgSwitchedWarning)); + yield* Deferred.await(fgSwitchedDone); + expect(fgSwitchedSnapshot.version).toBe("1.0.0"); + expect(fgSwitchedSnapshot.message).not.toContain("API key"); + expect(fgSwitchedSnapshot.models.map((model) => model.slug)).toContain("fg-v1-g"); + + // 2. When no snapshot was ever accepted for 1.0.0 (neither probe nor live session), a failed + // 2.0.0 probe discovered via recheck (with expectedRuntimeIdentity still on 1.0.0!) publishes + // 2.0.0's failure snapshot without attaching 1.0.0 live state AND aligns watcher identities + // to 2.0.0 so subsequent 1.0.0 updates cannot land on it. + remoteVersion = "1.0.0"; + failProbeSpawn = false; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const coldFgStarted = yield* Deferred.make(); + const releaseColdFg = yield* Deferred.make(); + const coldFgDone = yield* Deferred.make(); + const coldFgFiber = yield* coordinator + .withForegroundStartup( + "test-agent", + Deferred.succeed(coldFgStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseColdFg)), + ), + ) + .pipe( + Effect.ensuring(Deferred.succeed(coldFgDone, undefined)), + Effect.forkScoped({ startImmediately: true }), + ); + yield* Deferred.await(coldFgStarted); + const noAcceptId = ProviderInstanceId.make("acpRegistry_no_accepted_v1"); + // Drain makeManagedServerProvider's automatic startup enrichment before arming hooks + // so it cannot consume onRefreshIndex out of order. + const noAcceptStartupDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(noAcceptStartupDone, Exit.void); + const noAcceptInstance = yield* AcpRegistryDriver.create({ + instanceId: noAcceptId, + displayName: "No Accepted V1", + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(noAcceptStartupDone); + const noAcceptColdEnrichmentDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(noAcceptColdEnrichmentDone, Exit.void); + yield* noAcceptInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(noAcceptColdEnrichmentDone); + // Keep disk registry.json on 1.0.0 and keep coldFgFiber held during initialProbe so + // checkProvider sees 1.0.0 (expectedRuntimeIdentity === v1Identity), initialProbe skips, + // and publishEnrichment's refreshIndex releases coldFgFiber and discovers failing 2.0.0. + remoteVersion = "2.0.0"; + failProbeSpawn = true; + yield* realCatalog.invalidateIndex(); + onRefreshIndex = () => + Deferred.succeed(releaseColdFg, undefined).pipe( + Effect.andThen(Deferred.await(coldFgDone)), + ); + const noAcceptWarning = yield* noAcceptInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.status === "warning"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const noAcceptFailDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(noAcceptFailDone, Exit.void); + yield* noAcceptInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + const noAcceptSnapshot = Option.getOrThrow(yield* Fiber.join(noAcceptWarning)); + yield* Deferred.await(noAcceptFailDone); + yield* Fiber.join(coldFgFiber); + expect(noAcceptSnapshot.version).toBe("2.0.0"); + expect(noAcceptSnapshot.message).toContain("2.0.0"); + expect(noAcceptSnapshot.slashCommands).toEqual([]); + // A subsequent 1.0.0 update must NOT land on 2.0.0's failure snapshot (requires + // runProbeAndPublish to have updated expectedRuntimeIdentity from v1Identity to v2Identity). + const lateV1AfterFailHandled = yield* Deferred.make(); + onCommandHandled = { matchName: "v1-after-v2-fail", done: lateV1AfterFailHandled }; + yield* coordinator.publishAvailableCommands( + noAcceptId, + { slashCommands: [{ name: "v1-after-v2-fail" }], skills: [] }, + v1Identity, + ); + yield* Deferred.await(lateV1AfterFailHandled); + const noAcceptAfterLateV1 = yield* noAcceptInstance.snapshot.getSnapshot; + expect(noAcceptAfterLateV1.version).toBe("2.0.0"); + expect(noAcceptAfterLateV1.slashCommands).toEqual([]); + // Once 2.0.0 succeeds, noAcceptInstance adopts 2.0.0 cleanly. + failProbeSpawn = false; + const noAcceptV2Adopted = yield* noAcceptInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "2.0.0" && + snapshot.status === "ready" && + snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const noAcceptV2AdoptedDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(noAcceptV2AdoptedDone, Exit.void); + yield* noAcceptInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + expect(Option.isSome(yield* Fiber.join(noAcceptV2Adopted))).toBe(true); + yield* Deferred.await(noAcceptV2AdoptedDone); + + // 3. Fallback retirement stamps failedTarget's revision (v3), not a concurrently restored + // v4 revision, so a new v4 session reconciles immediately even if v4 restored mid-probe. + failProbeSpawn = false; + const fallbackRetireId = ProviderInstanceId.make("acpRegistry_fallback_retire_rev"); + remoteVersion = "2.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const controlledDispatcher = new Scheduler.MixedScheduler("async").makeDispatcher(); + const controlledScheduler: Scheduler.Scheduler = { + executionMode: "async", + shouldYield: () => false, + makeDispatcher: () => controlledDispatcher, + }; + const fallbackStartupDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fallbackStartupDone, Exit.void); + const fallbackRetireInstance = yield* AcpRegistryDriver.create({ + instanceId: fallbackRetireId, + displayName: "Fallback Retire Rev", + enabled: true, + environment: [{ name: "MISE_OFFLINE", value: "0", sensitive: false }], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + Effect.provideService(Scheduler.Scheduler, controlledScheduler), + ); + yield* Deferred.await(fallbackStartupDone); + const v2Ready = yield* fallbackRetireInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "2.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const v2ReadyDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(v2ReadyDone, Exit.void); + yield* fallbackRetireInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + Effect.provideService(Scheduler.Scheduler, controlledScheduler), + ); + expect(Option.isSome(yield* Fiber.join(v2Ready))).toBe(true); + yield* Deferred.await(v2ReadyDone); + const v2Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v2Inspection.status).toBe("ready"); + const v2Identity = v2Inspection.status === "ready" ? v2Inspection.launchIdentity! : ""; + + remoteVersion = "4.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const v4Ready = yield* fallbackRetireInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => snapshot.version === "4.0.0" && snapshot.nativeSessions !== undefined, + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const v4InitialDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(v4InitialDone, Exit.void); + yield* fallbackRetireInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + Effect.provideService(Scheduler.Scheduler, controlledScheduler), + ); + expect(Option.isSome(yield* Fiber.join(v4Ready))).toBe(true); + yield* Deferred.await(v4InitialDone); + const v4Inspection = yield* realCatalog.inspect(decodeSettings({ agentId: "test-agent" })); + expect(v4Inspection.status).toBe("ready"); + const v4Identity = v4Inspection.status === "ready" ? v4Inspection.launchIdentity! : ""; + + // Move upstream to failing 3.0.0 while keeping disk cache on 4.0.0 and only 2.0.0 on disk: + // enrichment's index refresh discovers 3.0.0 (R3), fails download, and falls back to 2.0.0. + // Pause during 2.0.0 fallback resolve while another caller restores 4.0.0 at R4 > R3. + yield* fileSystem.remove(path.join(directory, "tools", "test-agent", "4.0.0"), { + recursive: true, + force: true, + }); + remoteVersion = "3.0.0"; + failArchiveVersions = new Set(["3.0.0"]); + yield* realCatalog.invalidateIndex(); + const v2FallbackGate = { + matchVersion: "2.0.0", + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + resolveGate = v2FallbackGate; + const v2FallbackPublished = yield* fallbackRetireInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "2.0.0" && Boolean(snapshot.message?.includes("3.0.0")), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const fallbackEnrichmentDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fallbackEnrichmentDone, Exit.void); + yield* fallbackRetireInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + Effect.provideService(Scheduler.Scheduler, controlledScheduler), + ); + yield* Deferred.await(v2FallbackGate.started); + remoteVersion = "4.0.0"; + failArchiveVersions = new Set(); + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* Deferred.succeed(v2FallbackGate.release, undefined); + expect(Option.isSome(yield* Fiber.join(v2FallbackPublished))).toBe(true); + yield* Deferred.await(fallbackEnrichmentDone); + + // Because v4 was retired at R3 (not R4), a new v4 live update at R4 reconciles immediately. + const v4Restored = yield* fallbackRetireInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "4.0.0" && + snapshot.nativeSessions !== undefined && + snapshot.slashCommands.some((cmd) => cmd.name === "v4-restored-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const v4RestoredEnrichmentDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(v4RestoredEnrichmentDone, Exit.void); + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v4-restored-cmd" }], skills: [] }, + v4Identity, + ); + expect(Option.isSome(yield* Fiber.join(v4Restored))).toBe(true); + yield* Deferred.await(v4RestoredEnrichmentDone); + + // 4. An event arriving while a reconciliation inspect for the same identity is in flight + // is parked and drained once the older inspection finishes, and unrelated revision bumps + // re-stamp retirement so subsequent late updates do not repeat catalog.inspect. + remoteExtraAgentVersion = "9.9.9"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const staleReconcileInspect = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + inspectGate = staleReconcileInspect; + // First retired v2 event at unrelated revision R5 triggers a coalesced inspect (paused on gate). + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v2-stale-at-r5" }], skills: [] }, + v2Identity, + ); + yield* Deferred.await(staleReconcileInspect.started); + // While inspect #1 (at R5 = 4.0.0) is in flight, roll catalog back to 2.0.0 at R6 and send a new v2 update. + remoteVersion = "2.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const v2ParkedHandled = yield* Deferred.make(); + onCommandHandled = { matchName: "v2-during-reconcile", done: v2ParkedHandled }; + const v2DrainedReconciled = yield* fallbackRetireInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "2.0.0" && + snapshot.nativeSessions !== undefined && + snapshot.slashCommands.some((cmd) => cmd.name === "v2-during-reconcile"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const v2RestoredEnrichmentDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(v2RestoredEnrichmentDone, Exit.void); + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v2-during-reconcile" }], skills: [] }, + v2Identity, + ); + yield* Deferred.await(v2ParkedHandled); + yield* Deferred.succeed(staleReconcileInspect.release, undefined); + expect(Option.isSome(yield* Fiber.join(v2DrainedReconciled))).toBe(true); + yield* Deferred.await(v2RestoredEnrichmentDone); + + // Verify re-stamping on an unrelated revision bump suppresses repeated inspects for retired v4, + // waiting for the full reconciliation span (including retirement stamping and claim release) + // before sending the second same-revision event and before advancing to the next revision. + remoteExtraAgentVersion = "10.0.0"; + yield* realCatalog.invalidateIndex(); + const r7 = yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + recordedInspectRevisions = []; + const firstRestampSpanDone = yield* Deferred.make(); + onReconcileEnd = () => Deferred.doneUnsafe(firstRestampSpanDone, Exit.void); + const inspectsBeforeRestamp = inspectCalls; + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v4-late-1" }], skills: [] }, + v4Identity, + ); + yield* Deferred.await(firstRestampSpanDone); + expect(inspectCalls).toBe(inspectsBeforeRestamp + 1); + expect(recordedInspectRevisions).toEqual([r7]); + + // A second late v4 event at the same revision R7 must NOT trigger another reconcile inspect. + const secondLateHandled = yield* Deferred.make(); + onCommandHandled = { matchName: "v4-late-2", done: secondLateHandled }; + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v4-late-2" }], skills: [] }, + v4Identity, + ); + yield* Deferred.await(secondLateHandled); + expect(inspectCalls).toBe(inspectsBeforeRestamp + 1); + expect(recordedInspectRevisions).toEqual([r7]); + + // Advancing to a new unrelated revision R8 triggers exactly one more inspect (total [r7, r8]). + remoteExtraAgentVersion = "10.0.1"; + yield* realCatalog.invalidateIndex(); + const r8 = yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const secondRestampSpanDone = yield* Deferred.make(); + onReconcileEnd = () => Deferred.doneUnsafe(secondRestampSpanDone, Exit.void); + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v4-late-3" }], skills: [] }, + v4Identity, + ); + yield* Deferred.await(secondRestampSpanDone); + expect(inspectCalls).toBe(inspectsBeforeRestamp + 2); + expect(recordedInspectRevisions).toEqual([r7, r8]); + recordedInspectRevisions = null; + + // A defect inside reconciliation releases the reconcilingState claim AND replays a parked + // pending event for the same identity once without needing a third event. + remoteExtraAgentVersion = "10.0.2"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const defectInspectGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + inspectGate = defectInspectGate; + defectInspectCount = 1; + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v4-defect-probe" }], skills: [] }, + v4Identity, + ); + yield* Deferred.await(defectInspectGate.started); + // While the defecting reconcile is in flight, restore 4.0.0 and park a second v4 event. + remoteVersion = "4.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const parkedDuringDefectHandled = yield* Deferred.make(); + onCommandHandled = { matchName: "v4-parked-on-defect", done: parkedDuringDefectHandled }; + const v4RecoveredByReplay = yield* fallbackRetireInstance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + snapshot.version === "4.0.0" && + snapshot.nativeSessions !== undefined && + snapshot.slashCommands.some((cmd) => cmd.name === "v4-parked-on-defect"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const v4RecoveredEnrichmentDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(v4RecoveredEnrichmentDone, Exit.void); + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v4-parked-on-defect" }], skills: [] }, + v4Identity, + ); + yield* Deferred.await(parkedDuringDefectHandled); + yield* Deferred.succeed(defectInspectGate.release, undefined); + expect(Option.isSome(yield* Fiber.join(v4RecoveredByReplay))).toBe(true); + yield* Deferred.await(v4RecoveredEnrichmentDone); + + // A defect with no parked update does not self-loop, and scope interruption of a + // reconciliation with a parked update does NOT replay (!Cause.hasInterruptsOnly). + remoteExtraAgentVersion = "10.0.3"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + defectInspectCount = 1; + const inspectsBeforeNoPending = inspectCalls; + const noPendingDefectDone = yield* Deferred.make(); + onReconcileEnd = () => Deferred.doneUnsafe(noPendingDefectDone, Exit.void); + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v2-defect-no-pending" }], skills: [] }, + v2Identity, + ); + yield* Deferred.await(noPendingDefectDone); + controlledDispatcher.flush(); + expect(inspectCalls).toBe(inspectsBeforeNoPending + 1); + + // Interruption of a reconciliation fiber while driverScope is still OPEN (with a parked + // event) must NOT replay (!Cause.hasInterruptsOnly). + const interruptGate = { + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + inspectGate = interruptGate; + interruptInspectOnce = true; + const inspectsBeforeInterrupt = inspectCalls; + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v2-interrupt-1" }], skills: [] }, + v2Identity, + ); + yield* Deferred.await(interruptGate.started); + const interruptParked = yield* Deferred.make(); + onCommandHandled = { matchName: "v2-interrupt-2", done: interruptParked }; + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v2-interrupt-2" }], skills: [] }, + v2Identity, + ); + yield* Deferred.await(interruptParked); + const interruptSpanDone = yield* Deferred.make(); + onReconcileEnd = () => Deferred.doneUnsafe(interruptSpanDone, Exit.void); + yield* Deferred.succeed(interruptGate.release, undefined); + yield* Deferred.await(interruptSpanDone); + controlledDispatcher.flush(); + const interruptBarrierHandled = yield* Deferred.make(); + onCommandHandled = { matchName: "v4-interrupt-barrier", done: interruptBarrierHandled }; + yield* coordinator.publishAvailableCommands( + fallbackRetireId, + { slashCommands: [{ name: "v4-interrupt-barrier" }], skills: [] }, + v4Identity, + ); + yield* Deferred.await(interruptBarrierHandled); + controlledDispatcher.flush(); + expect(inspectCalls).toBe(inspectsBeforeInterrupt + 1); + + // 5. Saved sign-in confirmation: first-probe auth rejection clears it without + // lastSuccessfulRuntime, rejected publications keep it, and a later failure on B + // never restores confirmation after A rejected auth. + const host = yield* ProviderHost.ProviderHost; + const authConfirmId = ProviderInstanceId.make("acpRegistry_confirmed_auth_edge"); + const authConfirmEnv = [{ name: "MISE_OFFLINE", value: "0", sensitive: false }] as const; + const authConfirmSettings = decodeSettings({ agentId: "test-agent" }); + const seedConfirmedAuth = () => + AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId: authConfirmId, + settings: authConfirmSettings, + environment: authConfirmEnv, + processEnvironment: process.env, + }); + remoteVersion = "1.0.0"; + failProbeSpawn = false; + failProbeExit = false; + failProbeAuth = true; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* (yield* seedConfirmedAuth()).set(true); + const firstRejectScope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(firstRejectScope, Exit.void)); + const firstRejectStartupDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(firstRejectStartupDone, Exit.void); + const firstRejectInstance = yield* AcpRegistryDriver.create({ + instanceId: authConfirmId, + displayName: "Confirmed Auth Edge", + enabled: true, + environment: authConfirmEnv, + config: authConfirmSettings, + }).pipe( + Scope.provide(firstRejectScope), + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(firstRejectStartupDone); + expect((yield* firstRejectInstance.snapshot.getSnapshot).auth.status).toBe( + "unauthenticated", + ); + expect(yield* (yield* seedConfirmedAuth()).get).toBe(false); + yield* Scope.close(firstRejectScope, Exit.void); + + // (b) & (c): Re-seed saved confirmation, verify stale rejected publication leaves it intact, + // verify B's auth failure preserves A's authenticated state, then A's own auth + // rejection clears it and a later B failure never restores old confirmation. + yield* (yield* seedConfirmedAuth()).set(true); + failProbeAuth = false; + const authRetainStartupDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(authRetainStartupDone, Exit.void); + const authRetainInstance = yield* AcpRegistryDriver.create({ + instanceId: authConfirmId, + displayName: "Confirmed Auth Retain", + enabled: true, + environment: authConfirmEnv, + config: authConfirmSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(authRetainStartupDone); + expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe("authenticated"); + + // Start a 1.0.0 probe that rejects auth, pause it inside withLiveRuntimeState before + // tryPublishSnapshot, and supersede it with a succeeding refresh -> confirmation stays true. + yield* authRetainInstance.invalidateCaches ?? Effect.void; + const staleUnauthGate = { + matchVersion: "1.0.0", + started: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + resolveGate = staleUnauthGate; + failProbeAuth = true; + yield* authRetainInstance.snapshot.refresh; + yield* Deferred.await(staleUnauthGate.started); + const staleWithLiveStarted = yield* Deferred.make(); + const staleWithLiveRelease = yield* Deferred.make(); + const staleWithLiveInterrupted = yield* Deferred.make(); + getAvailableCommandsGate = { + instanceId: authConfirmId, + started: staleWithLiveStarted, + release: staleWithLiveRelease, + interrupted: staleWithLiveInterrupted, + }; + yield* Deferred.succeed(staleUnauthGate.release, undefined); + // Wait until authFailAgentPath returned authentication_failed and entered withLiveRuntimeState. + yield* Deferred.await(staleWithLiveStarted); + failProbeAuth = false; + const supersedingRefreshDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(supersedingRefreshDone, Exit.void); + yield* authRetainInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(staleWithLiveInterrupted); + yield* Deferred.await(supersedingRefreshDone); + expect(yield* (yield* seedConfirmedAuth()).get).toBe(true); + expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe("authenticated"); + + // B fails auth -> retained A keeps authenticated. + remoteVersion = "2.0.0"; + failProbeAuth = true; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const bFailKeepAuthDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(bFailKeepAuthDone, Exit.void); + yield* authRetainInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(bFailKeepAuthDone); + expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe("authenticated"); + + // While A's 15m probe cache entry is still fresh, B's download fails (503) and fallback A + // rejects auth -> invalidates A's cached probe so rolling back to A before TTL expires + // does not serve stale cached unknown auth and erase the rejection. + yield* fileSystem.remove(path.join(directory, "tools", "test-agent", "2.0.0"), { + recursive: true, + force: true, + }); + failArchiveVersions = new Set(["2.0.0"]); + const fallbackARejectDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fallbackARejectDone, Exit.void); + yield* authRetainInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fallbackARejectDone); + expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe( + "unauthenticated", + ); + expect(yield* (yield* seedConfirmedAuth()).get).toBe(false); + remoteVersion = "1.0.0"; + failArchiveVersions = new Set(); + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const rollbackNoCacheDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(rollbackNoCacheDone, Exit.void); + yield* authRetainInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(rollbackNoCacheDone); + expect((yield* authRetainInstance.snapshot.getSnapshot).status).toBe("warning"); + expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe( + "unauthenticated", + ); + + // Now B fails without launching A -> retained A MUST stay unauthenticated (never restoring + // A's old authenticated state from lastSuccessfulRuntime). + remoteVersion = "2.0.0"; + failProbeAuth = false; + failProbeSpawn = true; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const bFailAfterARejectDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(bFailAfterARejectDone, Exit.void); + yield* authRetainInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(bFailAfterARejectDone); + expect((yield* authRetainInstance.snapshot.getSnapshot).version).toBe("1.0.0"); + expect((yield* authRetainInstance.snapshot.getSnapshot).auth.status).toBe( + "unauthenticated", + ); + + // (d) Logout invalidates confirmed authentication without restoring historical + // "authenticated" from lastSuccessfulRuntime on subsequent non-auth failures. + failProbeSpawn = false; + useLogoutAgent = true; + remoteVersion = "1.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const logoutInstanceId = ProviderInstanceId.make("acpRegistry_logout_edge"); + const seedLogoutAuth = () => + AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId: logoutInstanceId, + settings: authConfirmSettings, + environment: authConfirmEnv, + processEnvironment: process.env, + }); + yield* (yield* seedLogoutAuth()).set(true); + const beforeLogoutDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(beforeLogoutDone, Exit.void); + const logoutInstance = yield* AcpRegistryDriver.create({ + instanceId: logoutInstanceId, + displayName: "Logout Edge", + enabled: true, + environment: authConfirmEnv, + config: authConfirmSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(beforeLogoutDone); + const beforeLogoutSnap = yield* logoutInstance.snapshot.getSnapshot; + expect(beforeLogoutSnap.auth.status).toBe("authenticated"); + expect(beforeLogoutSnap.auth.canLogout).toBe(true); + expect(beforeLogoutSnap.models.map((model) => model.slug)).toEqual(["model-a", "model-b"]); + // Live config update while authenticated must also strip "authenticated" in lastSuccessfulRuntime. + const logoutLiveUpdated = yield* logoutInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.some((model) => model.slug === "model-live")), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + logoutInstanceId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "model-live", + availableModels: [ + { modelId: "model-a", name: "model-a" }, + { modelId: "model-b", name: "model-b" }, + { modelId: "model-live", name: "model-live" }, + ], + }), + v1Identity, + ); + expect( + Option.getOrThrow(yield* Fiber.join(logoutLiveUpdated)).models.map((model) => model.slug), + ).toEqual(["model-a", "model-b", "model-live"]); + // Set failProbeSpawn before logout so logout's own refresh cannot overwrite + // lastSuccessfulRuntime with a fresh probe before we assert auth.status === "unknown". + failProbeSpawn = true; + yield* logoutInstance.acpSessionManagement!.logout(directory); + expect(yield* (yield* seedLogoutAuth()).get).toBe(false); + // Same-runtime non-auth failure after logout must show unknown (never authenticated). + const afterLogoutSameFailDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(afterLogoutSameFailDone, Exit.void); + yield* logoutInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(afterLogoutSameFailDone); + expect((yield* logoutInstance.snapshot.getSnapshot).status).toBe("warning"); + expect((yield* logoutInstance.snapshot.getSnapshot).auth.status).toBe("unknown"); + // Failed upgrade to 2.0.0 after logout keeps A's discovered models and stays unknown + // across both retained-runtime publication and follow-up inspectReadiness. + remoteVersion = "2.0.0"; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const afterLogoutUpgradeFailDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(afterLogoutUpgradeFailDone, Exit.void); + yield* logoutInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(afterLogoutUpgradeFailDone); + const afterLogoutUpgradeSnap = yield* logoutInstance.snapshot.getSnapshot; + expect(afterLogoutUpgradeSnap.version).toBe("1.0.0"); + expect(afterLogoutUpgradeSnap.status).toBe("warning"); + expect(afterLogoutUpgradeSnap.auth.status).toBe("unknown"); + expect(afterLogoutUpgradeSnap.models.map((model) => model.slug)).toEqual([ + "model-a", + "model-b", + "model-live", + ]); + const afterLogoutSnapshots: Array = []; + const afterLogoutCollector = yield* logoutInstance.snapshot.streamChanges.pipe( + Stream.runForEach((snapshot) => + Effect.sync(() => { + afterLogoutSnapshots.push(snapshot); + }), + ), + Effect.forkScoped({ startImmediately: true }), + ); + const afterLogoutFollowUpDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(afterLogoutFollowUpDone, Exit.void); + yield* logoutInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(afterLogoutFollowUpDone); + yield* Fiber.interrupt(afterLogoutCollector); + expect(afterLogoutSnapshots.length).toBeGreaterThan(0); + for (const emitted of afterLogoutSnapshots) { + expect(emitted.auth.status).not.toBe("authenticated"); + } + + // Foreground-skipped startup runtimes populated only via live commands or live config + // while authenticated must also strip "authenticated" before logout + probe failure. + remoteVersion = "1.0.0"; + failProbeSpawn = false; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + const fgLogoutStarted = yield* Deferred.make(); + const releaseFgLogout = yield* Deferred.make(); + const fgLogoutFiber = yield* coordinator + .withForegroundStartup( + "test-agent", + Deferred.succeed(fgLogoutStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseFgLogout)), + ), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(fgLogoutStarted); + const fgCmdLogoutId = ProviderInstanceId.make("acpRegistry_fg_cmd_logout"); + const fgCfgLogoutId = ProviderInstanceId.make("acpRegistry_fg_cfg_logout"); + const seedAuthFor = (id: ProviderInstanceId) => + AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId: id, + settings: authConfirmSettings, + environment: authConfirmEnv, + processEnvironment: process.env, + }); + yield* (yield* seedAuthFor(fgCmdLogoutId)).set(true); + yield* (yield* seedAuthFor(fgCfgLogoutId)).set(true); + const fgCmdInitDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fgCmdInitDone, Exit.void); + const fgCmdLogoutInstance = yield* AcpRegistryDriver.create({ + instanceId: fgCmdLogoutId, + displayName: "FG Cmd Logout", + enabled: true, + environment: authConfirmEnv, + config: authConfirmSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fgCmdInitDone); + const fgCfgInitDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fgCfgInitDone, Exit.void); + const fgCfgLogoutInstance = yield* AcpRegistryDriver.create({ + instanceId: fgCfgLogoutId, + displayName: "FG Cfg Logout", + enabled: true, + environment: authConfirmEnv, + config: authConfirmSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fgCfgInitDone); + const fgCmdPopulated = yield* fgCmdLogoutInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.slashCommands.some((cmd) => cmd.name === "fg-logout-cmd"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const fgCfgPopulated = yield* fgCfgLogoutInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.models.some((model) => model.slug === "fg-logout-model"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishAvailableCommands( + fgCmdLogoutId, + { slashCommands: [{ name: "fg-logout-cmd" }], skills: [] }, + v1Identity, + ); + yield* coordinator.publishLiveConfiguration( + fgCfgLogoutId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "fg-logout-model", + availableModels: [ + { modelId: "model-a", name: "model-a" }, + { modelId: "fg-logout-model", name: "fg-logout-model" }, + ], + }), + v1Identity, + ); + expect(Option.getOrThrow(yield* Fiber.join(fgCmdPopulated)).auth.status).toBe( + "authenticated", + ); + expect(Option.getOrThrow(yield* Fiber.join(fgCfgPopulated)).auth.status).toBe( + "authenticated", + ); + yield* Deferred.succeed(releaseFgLogout, undefined); + yield* Fiber.join(fgLogoutFiber); + failProbeSpawn = true; + yield* fgCmdLogoutInstance.acpSessionManagement!.logout(directory); + yield* fgCfgLogoutInstance.acpSessionManagement!.logout(directory); + const fgCmdAfterLogoutDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fgCmdAfterLogoutDone, Exit.void); + yield* fgCmdLogoutInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fgCmdAfterLogoutDone); + const fgCfgAfterLogoutDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(fgCfgAfterLogoutDone, Exit.void); + yield* fgCfgLogoutInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(fgCfgAfterLogoutDone); + const fgCmdAfterLogout = yield* fgCmdLogoutInstance.snapshot.getSnapshot; + expect(fgCmdAfterLogout.auth.status).toBe("unknown"); + expect(fgCmdAfterLogout.slashCommands).toEqual([{ name: "fg-logout-cmd" }]); + const fgCfgAfterLogout = yield* fgCfgLogoutInstance.snapshot.getSnapshot; + expect(fgCfgAfterLogout.auth.status).toBe("unknown"); + expect(fgCfgAfterLogout.models.map((model) => model.slug)).toEqual([ + "model-a", + "fg-logout-model", + ]); + useLogoutAgent = false; + failProbeSpawn = false; + + // Live config update while unauthenticated must not bake "unauthenticated" into + // lastSuccessfulRuntime: signing in again then failing probe promotes back to authenticated. + useAuthLoginAgent = true; + const reauthId = ProviderInstanceId.make("acpRegistry_unauth_live_reauth"); + const reauthStartupDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(reauthStartupDone, Exit.void); + const reauthInstance = yield* AcpRegistryDriver.create({ + instanceId: reauthId, + displayName: "Unauth Live Reauth", + enabled: true, + environment: authConfirmEnv, + config: authConfirmSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(reauthStartupDone); + yield* TestClock.adjust("16 minutes"); + failProbeAuth = true; + const reauthUnauthDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(reauthUnauthDone, Exit.void); + yield* reauthInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(reauthUnauthDone); + expect((yield* reauthInstance.snapshot.getSnapshot).auth.status).toBe("unauthenticated"); + const reauthLiveUpdated = yield* reauthInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.models.some((model) => model.slug === "reauth-live-model"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + reauthId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "reauth-live-model", + availableModels: [ + { modelId: "model-a", name: "model-a" }, + { modelId: "reauth-live-model", name: "reauth-live-model" }, + ], + }), + v1Identity, + ); + expect(Option.getOrThrow(yield* Fiber.join(reauthLiveUpdated)).auth.status).toBe( + "unauthenticated", + ); + failProbeAuth = false; + failProbeSpawn = true; + const reauthAuthFinished = yield* reauthInstance.auth!.subscribe("reauth-owner").pipe( + Stream.filter((state) => state.phase === "succeeded" || state.phase === "failed"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const reauthPostSignInDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(reauthPostSignInDone, Exit.void); + yield* reauthInstance + .auth!.start("reauth-owner", Effect.void, "agent-login") + .pipe(Effect.provideService(Tracer.Tracer, enrichmentTracer)); + expect(Option.getOrThrow(yield* Fiber.join(reauthAuthFinished)).phase).toBe("succeeded"); + yield* Deferred.await(reauthPostSignInDone); + const reauthAfterSignIn = yield* reauthInstance.snapshot.getSnapshot; + expect(reauthAfterSignIn.status).toBe("ready"); + expect(reauthAfterSignIn.auth.status).toBe("authenticated"); + expect(reauthAfterSignIn.models.map((model) => model.slug)).toEqual([ + "model-a", + "reauth-live-model", + ]); + // Subsequent refresh checkProvider commit must keep authenticated via latestAuthConfirmed. + const reauthCheckedDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(reauthCheckedDone, Exit.void); + const reauthChecked = yield* reauthInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + expect(reauthChecked.auth.status).toBe("authenticated"); + yield* Deferred.await(reauthCheckedDone); + useAuthLoginAgent = false; + failProbeSpawn = false; + + // (e) Cold-start direct-publish branch clears saved confirmation when fallback runtime + // rejects auth so the next refresh does not flash authenticated. + const coldFallbackAuthId = ProviderInstanceId.make("acpRegistry_cold_fallback_unauth"); + const seedColdFallbackAuth = () => + AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId: coldFallbackAuthId, + settings: authConfirmSettings, + environment: authConfirmEnv, + processEnvironment: process.env, + }); + yield* fileSystem.remove(path.join(directory, "tools", "test-agent", "3.0.0"), { + recursive: true, + force: true, + }); + remoteVersion = "3.0.0"; + failArchiveVersions = new Set(["3.0.0"]); + failProbeAuth = true; + yield* realCatalog.invalidateIndex(); + yield* realCatalog.refreshIndex({ maxAgeMs: 0, failureBackoffMs: 0 }); + yield* (yield* seedColdFallbackAuth()).set(true); + const coldFallbackDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(coldFallbackDone, Exit.void); + const coldFallbackInstance = yield* AcpRegistryDriver.create({ + instanceId: coldFallbackAuthId, + displayName: "Cold Fallback Unauth", + enabled: true, + environment: authConfirmEnv, + config: authConfirmSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(coldFallbackDone); + const coldFallbackSnap = yield* coldFallbackInstance.snapshot.getSnapshot; + expect(coldFallbackSnap.version).toBe("2.0.0"); + expect(coldFallbackSnap.status).toBe("warning"); + expect(coldFallbackSnap.auth.status).toBe("unauthenticated"); + expect(yield* (yield* seedColdFallbackAuth()).get).toBe(false); + const coldFollowUpSnaps: Array = []; + const coldFollowUpCollector = yield* coldFallbackInstance.snapshot.streamChanges.pipe( + Stream.runForEach((snapshot) => + Effect.sync(() => { + coldFollowUpSnaps.push(snapshot); + }), + ), + Effect.forkScoped({ startImmediately: true }), + ); + const coldFollowUpDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(coldFollowUpDone, Exit.void); + yield* coldFallbackInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(coldFollowUpDone); + yield* Fiber.interrupt(coldFollowUpCollector); + expect(coldFollowUpSnaps.length).toBeGreaterThan(0); + for (const emitted of coldFollowUpSnaps) { + expect(emitted.auth.status).not.toBe("authenticated"); + } + + // (f) Local agent (previousIdentity === null, normal branch): a superseded auth rejection + // keeps saved confirmation intact, while an accepted auth rejection clears it. + const localUnauthId = ProviderInstanceId.make("acpRegistry_local_unauth"); + const localUnauthSettings = decodeSettings({ + source: "local", + commandPath: "local-auth-fail", + }); + const localUnauthEnv = [{ name: "MISE_OFFLINE", value: "0", sensitive: false }] as const; + const seedLocalAuth = () => + AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId: localUnauthId, + settings: localUnauthSettings, + environment: localUnauthEnv, + processEnvironment: process.env, + }); + yield* (yield* seedLocalAuth()).set(true); + let localFailAuth = true; + let localUseVersionless = false; + let localProbeCount = 0; + let localResolveGate: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + const localWithLiveStarted = yield* Deferred.make(); + const localWithLiveRelease = yield* Deferred.make(); + const localWithLiveInterrupted = yield* Deferred.make(); + let localGateArmed = false; + const localCatalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = { + ...catalogWithInspection({ + status: "ready", + agentId: "local-auth-fail", + version: null, + distribution: "local", + }), + resolve: (_settings, _cwd, environment) => + Effect.gen(function* () { + if (environment?.MISE_OFFLINE === "1") { + localProbeCount += 1; + if (!localGateArmed) { + localGateArmed = true; + getAvailableCommandsGate = { + instanceId: localUnauthId, + started: localWithLiveStarted, + release: localWithLiveRelease, + interrupted: localWithLiveInterrupted, + }; + } + if (localResolveGate !== null) { + const gate = localResolveGate; + localResolveGate = null; + yield* Deferred.succeed(gate.started, undefined); + yield* Deferred.await(gate.release); + } + } + return { + distribution: "local" as const, + spawn: { + command: process.execPath, + args: localFailAuth + ? [authFailAgentPath] + : [localUseVersionless ? versionlessLocalAgentPath : agentPath, modelsPath], + cwd: directory, + env: process.env, + }, + }; + }), + }; + // Startup probe runs with previousIdentity === null (normal branch), fails auth, and pauses + // inside withLiveRuntimeState before tryPublishSnapshot; superseding refresh keeps auth. + const localUnauthInstance = yield* AcpRegistryDriver.create({ + instanceId: localUnauthId, + displayName: "Local Unauth", + enabled: true, + environment: localUnauthEnv, + config: localUnauthSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, localCatalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(localWithLiveStarted); + localFailAuth = false; + const localSupersedingDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(localSupersedingDone, Exit.void); + yield* localUnauthInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(localWithLiveInterrupted); + yield* Deferred.await(localSupersedingDone); + expect(yield* (yield* seedLocalAuth()).get).toBe(true); + expect((yield* localUnauthInstance.snapshot.getSnapshot).auth.status).toBe("authenticated"); + // Accepted normal-branch local auth rejection clears saved confirmation. + const localAcceptedId = ProviderInstanceId.make("acpRegistry_local_unauth_accepted"); + const seedLocalAcceptedAuth = () => + AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId: localAcceptedId, + settings: localUnauthSettings, + environment: localUnauthEnv, + processEnvironment: process.env, + }); + yield* (yield* seedLocalAcceptedAuth()).set(true); + localFailAuth = true; + const localUnauthDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(localUnauthDone, Exit.void); + const localAcceptedInstance = yield* AcpRegistryDriver.create({ + instanceId: localAcceptedId, + displayName: "Local Unauth Accepted", + enabled: true, + environment: localUnauthEnv, + config: localUnauthSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, localCatalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(localUnauthDone); + expect((yield* localAcceptedInstance.snapshot.getSnapshot).auth.status).toBe( + "unauthenticated", + ); + expect(yield* (yield* seedLocalAcceptedAuth()).get).toBe(false); + // Version-less local agent (entryIdentity === null): an accepted auth rejection must evict + // the cached probe entry so a live config update cannot revive it on the next refresh. + localUseVersionless = true; + localFailAuth = false; + const localVersionlessId = ProviderInstanceId.make("acpRegistry_local_versionless_cache"); + const localVersionlessReadyDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(localVersionlessReadyDone, Exit.void); + const localVersionlessInstance = yield* AcpRegistryDriver.create({ + instanceId: localVersionlessId, + displayName: "Local Versionless Cache", + enabled: true, + environment: localUnauthEnv, + config: localUnauthSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, localCatalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(localVersionlessReadyDone); + expect((yield* localVersionlessInstance.snapshot.getSnapshot).version).toBeNull(); + expect((yield* localVersionlessInstance.snapshot.getSnapshot).status).toBe("ready"); + yield* TestClock.adjust("16 minutes"); + localFailAuth = true; + const localVersionlessUnauthDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(localVersionlessUnauthDone, Exit.void); + yield* localVersionlessInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(localVersionlessUnauthDone); + expect((yield* localVersionlessInstance.snapshot.getSnapshot).auth.status).toBe( + "unauthenticated", + ); + const localVersionlessLive = yield* localVersionlessInstance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => + snapshot.models.some((model) => model.slug === "local-unauth-live"), + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const localVersionlessConfigHandled = yield* Deferred.make(); + onConfigHandled = { + matchModelId: "local-unauth-live", + done: localVersionlessConfigHandled, + }; + yield* coordinator.publishLiveConfiguration( + localVersionlessId, + normalizeAcpRegistryLiveConfiguration([], undefined, { + currentModelId: "local-unauth-live", + availableModels: [ + { modelId: "model-a", name: "model-a" }, + { modelId: "local-unauth-live", name: "local-unauth-live" }, + ], + }), + ); + expect(Option.getOrThrow(yield* Fiber.join(localVersionlessLive)).auth.status).toBe( + "unauthenticated", + ); + // Wait until the watcher callback finishes (including cache update) before refreshing. + yield* Deferred.await(localVersionlessConfigHandled); + const probesBeforeRecheck = localProbeCount; + const localVersionlessRecheckDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(localVersionlessRecheckDone, Exit.void); + yield* localVersionlessInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(localVersionlessRecheckDone); + expect(localProbeCount).toBe(probesBeforeRecheck + 1); + const localVersionlessAfter = yield* localVersionlessInstance.snapshot.getSnapshot; + expect(localVersionlessAfter.status).toBe("warning"); + expect(localVersionlessAfter.auth.status).toBe("unauthenticated"); + expect(localVersionlessAfter.message).toContain("API key"); + + // (g) A refresh checkProvider that read confirmedAuthentication=true before an in-flight + // enrichment probe accepted an auth rejection must NOT commit auth.status="authenticated". + const raceAuthId = ProviderInstanceId.make("acpRegistry_check_vs_reject_race"); + const seedRaceAuth = () => + AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId: raceAuthId, + settings: localUnauthSettings, + environment: localUnauthEnv, + processEnvironment: process.env, + }); + yield* (yield* seedRaceAuth()).set(true); + localFailAuth = true; + const raceProbeStarted = yield* Deferred.make(); + const raceProbeRelease = yield* Deferred.make(); + localResolveGate = { started: raceProbeStarted, release: raceProbeRelease }; + const raceAuthInstance = yield* AcpRegistryDriver.create({ + instanceId: raceAuthId, + displayName: "Check vs Reject Race", + enabled: true, + environment: localUnauthEnv, + config: localUnauthSettings, + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, localCatalog), + Effect.provideService( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + coordinator, + ), + Effect.provideService(Tracer.Tracer, enrichmentTracer), + ); + yield* Deferred.await(raceProbeStarted); + const raceCheckStarted = yield* Deferred.make(); + const raceCheckRelease = yield* Deferred.make(); + const raceCheckInterrupted = yield* Deferred.make(); + getAvailableCommandsGate = { + instanceId: raceAuthId, + started: raceCheckStarted, + release: raceCheckRelease, + interrupted: raceCheckInterrupted, + }; + const raceRefreshFiber = yield* raceAuthInstance.snapshot.refresh.pipe( + Effect.provideService(Tracer.Tracer, enrichmentTracer), + Effect.forkScoped({ startImmediately: true }), + ); + // Refresh gen 2 already observed confirmedAuthentication=true and paused in checkProvider. + yield* Deferred.await(raceCheckStarted); + const raceGen1RejectDone = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(raceGen1RejectDone, Exit.void); + yield* Deferred.succeed(raceProbeRelease, undefined); + yield* Deferred.await(raceGen1RejectDone); + expect((yield* raceAuthInstance.snapshot.getSnapshot).auth.status).toBe("unauthenticated"); + expect(yield* (yield* seedRaceAuth()).get).toBe(false); + const raceSnapsAfterReject: Array = []; + const raceCollector = yield* raceAuthInstance.snapshot.streamChanges.pipe( + Stream.runForEach((snapshot) => + Effect.sync(() => { + raceSnapsAfterReject.push(snapshot); + }), + ), + Effect.forkScoped({ startImmediately: true }), + ); + const raceGen2Done = yield* Deferred.make(); + onEnrichmentEnd = () => Deferred.doneUnsafe(raceGen2Done, Exit.void); + yield* Deferred.succeed(raceCheckRelease, undefined); + yield* Fiber.join(raceRefreshFiber); + yield* Deferred.await(raceGen2Done); + yield* Fiber.interrupt(raceCollector); + expect(raceSnapsAfterReject.length).toBeGreaterThan(0); + for (const emitted of raceSnapsAfterReject) { + expect(emitted.auth.status).not.toBe("authenticated"); + } + const raceFinal = yield* raceAuthInstance.snapshot.getSnapshot; + expect(raceFinal.status).toBe("warning"); + expect(raceFinal.auth.status).toBe("unauthenticated"); + }).pipe(Effect.scoped, Effect.provide(driverLayer)), + ); +}); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 33c5ab9a46663..e6b38bfd2ce23 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -12,7 +12,9 @@ import { import { AcpRegistrySettings } from "../settings.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { createModelCapabilities } from "@t3tools/shared/model"; +import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; +import * as Deferred from "effect/Deferred"; import * as Digest from "effect/crypto/Digest"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; @@ -51,6 +53,7 @@ import { import { type AcpRegistryAvailableCommands, type AcpRegistryConfigurationProbe, + type AcpRegistryConfigurationProbeResolved, type AcpRegistryConfigurationProbeResult, type AcpRegistryLiveConfiguration, type AcpRegistryModelDiscovery, @@ -78,6 +81,9 @@ const decodeSettings = Schema.decodeSync(AcpRegistrySettings); // Cache only successful authenticated probes so sign-in changes remain visible. const PROBE_SUCCESS_TTL_MS = 15 * 60 * 1_000; const PROBE_PROVISIONAL_TTL_MS = 30 * 1_000; +const REGISTRY_INDEX_MAX_AGE_MS = 15 * 60 * 1_000; +const REGISTRY_FAILURE_BACKOFF_MS = 60 * 1_000; +const FALLBACK_RETRY_BACKOFF_MS = 60 * 1_000; function acpRegistryProbeTtlMs(provider: ServerProvider): number { const discoveredModels = provider.models.filter((model) => !model.isCustom); @@ -85,23 +91,41 @@ function acpRegistryProbeTtlMs(provider: ServerProvider): number { } interface AcpRegistryEnrichmentCache { - readonly generation: number; + readonly invalidationGeneration: number; + readonly liveGenerationByRuntime: ReadonlyMap; readonly entry: { readonly provider: ServerProvider; readonly expiresAt: number; + readonly launchIdentity?: string | null; } | null; } +function nextLiveGenerationByRuntime( + current: ReadonlyMap, + runtimeIdentity: string | null, +): ReadonlyMap { + const next = new Map(current); + next.set(runtimeIdentity, (next.get(runtimeIdentity) ?? 0) + 1); + return next; +} + export function isAcpRegistryCacheValid( entry: NonNullable, inspectedVersion: string | null, local: boolean, now: number, + inspectedLaunchIdentity?: string | null, ): boolean { - return ( - entry.expiresAt > now && - ((local && inspectedVersion === null) || entry.provider.version === inspectedVersion) - ); + if (entry.expiresAt <= now) return false; + if (local && inspectedVersion === null) return true; + if ( + entry.launchIdentity !== undefined && + inspectedLaunchIdentity !== undefined && + entry.launchIdentity !== inspectedLaunchIdentity + ) { + return false; + } + return entry.provider.version === inspectedVersion; } export function updateAcpRegistryEnrichmentCache(input: { @@ -109,13 +133,43 @@ export function updateAcpRegistryEnrichmentCache(input: { readonly configuration: AcpRegistryLiveConfiguration; readonly customModels: ReadonlyArray; readonly now: number; + readonly runtimeIdentity?: string | null; }): AcpRegistryEnrichmentCache { - const { cache, configuration, customModels, now } = input; + const { cache, configuration, customModels, now, runtimeIdentity } = input; + const runtimeKey = runtimeIdentity ?? null; if (cache.entry === null) { // No probe has landed yet, but the live session published its - // configuration to the snapshot. Advance the cache epoch so a probe that - // was still in flight cannot overwrite that newer state when it lands. - return { ...cache, generation: cache.generation + 1 }; + // configuration to the snapshot. Advance the epoch for this runtime so an + // in-flight probe for the same runtime cannot overwrite newer live state, + // without discarding an upgrade probe targeting a different runtime. + return { + ...cache, + liveGenerationByRuntime: nextLiveGenerationByRuntime( + cache.liveGenerationByRuntime, + runtimeKey, + ), + }; + } + const entryRuntimeIdentity = runtimeIdentityFor( + cache.entry.provider, + cache.entry.launchIdentity ?? null, + ); + if ( + runtimeIdentity !== undefined && + runtimeIdentity !== null && + entryRuntimeIdentity !== null && + entryRuntimeIdentity !== runtimeIdentity + ) { + // Keep the cached entry for the older runtime intact, while advancing the + // incoming runtime's live epoch so an older in-flight probe for that + // incoming runtime cannot overwrite this newer live configuration. + return { + ...cache, + liveGenerationByRuntime: nextLiveGenerationByRuntime( + cache.liveGenerationByRuntime, + runtimeKey, + ), + }; } const provider = applyAcpRegistryLiveConfiguration( cache.entry.provider, @@ -125,10 +179,10 @@ export function updateAcpRegistryEnrichmentCache(input: { if (Equal.equals(provider, cache.entry.provider)) return cache; return { ...cache, - // The live session advanced the provider past what an in-flight probe - // started from; bump the epoch so the probe discards its stale result - // instead of overwriting this entry and publishing it. - generation: cache.generation + 1, + // Advance only this runtime's live epoch so an in-flight probe for the same + // runtime discards stale results without invalidating an upgrade probe for + // a newer runtime. + liveGenerationByRuntime: nextLiveGenerationByRuntime(cache.liveGenerationByRuntime, runtimeKey), entry: { ...cache.entry, provider, @@ -292,6 +346,7 @@ function baseSnapshot( readonly version: string | null; readonly status: ServerProvider["status"]; readonly auth: ServerProvider["auth"]; + readonly icon?: string; readonly documentationUrl?: string; readonly message?: string; readonly probe?: AcpRegistryConfigurationProbeResult; @@ -301,7 +356,7 @@ function baseSnapshot( const iconUrl = input.settings.source === "local" ? null - : (resolveOfficialAcpRegistryIconUrl(input.probe?.probe.icon) ?? + : (resolveOfficialAcpRegistryIconUrl(input.probe?.probe.icon ?? input.icon) ?? officialAcpRegistryIconUrlForAgentId(input.settings.agentId)); return { instanceId: input.instanceId, @@ -438,6 +493,26 @@ function applyAcpRegistryUrlAuthAction( }; } +function applyRegistryReadinessMetadata( + provider: ServerProvider, + baseSnapshot: ServerProvider, +): ServerProvider { + let next = provider; + const documentationUrl = baseSnapshot.setup?.documentationUrl; + if (next.setup !== undefined && next.setup.documentationUrl !== documentationUrl) { + const { documentationUrl: _previous, ...setup } = next.setup; + next = { + ...next, + setup: documentationUrl === undefined ? setup : { ...setup, documentationUrl }, + }; + } + if (next.iconUrl !== baseSnapshot.iconUrl) { + const { iconUrl: _previousIcon, ...rest } = next; + next = baseSnapshot.iconUrl === undefined ? rest : { ...rest, iconUrl: baseSnapshot.iconUrl }; + } + return next; +} + const buildInitialAcpRegistrySnapshot = Effect.fn("AcpRegistryDriver.buildInitialSnapshot")( function* (input: SnapshotIdentity & { readonly settings: AcpRegistrySettings }) { const checkedAt = DateTime.formatIso(yield* DateTime.now); @@ -484,6 +559,9 @@ export function buildCheckedAcpRegistrySnapshot( : undefined; return baseSnapshot({ ...input, + ...(input.inspection.status === "ready" && input.inspection.icon + ? { icon: input.inspection.icon } + : {}), ...(input.inspection.status === "ready" && input.inspection.documentationUrl ? { documentationUrl: input.inspection.documentationUrl } : {}), @@ -519,89 +597,316 @@ export function buildCheckedAcpRegistrySnapshot( }); } -export const checkAcpRegistryProviderStatus = Effect.fn("AcpRegistryDriver.checkProviderStatus")( - function* ( - input: SnapshotIdentity & { - readonly settings: AcpRegistrySettings; - readonly cwd: string; - readonly environment: NodeJS.ProcessEnv; - readonly modelDiscovery?: Omit & { - readonly onProbed: (provider: ServerProvider) => Effect.Effect>; - }; - }, - probeConfiguration: AcpRegistryConfigurationProbe, - ): Effect.fn.Return { - const checkedAt = DateTime.formatIso(yield* DateTime.now); - if (!input.settings.enabled) { - return yield* buildInitialAcpRegistrySnapshot(input); - } - const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; - const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment)); - if (Result.isFailure(inspected)) { - return buildCheckedAcpRegistrySnapshot({ +interface CheckedAcpRegistryReadiness { + readonly snapshot: ServerProvider; + readonly launchIdentity: string | null; + readonly indexRevision: number | null; + readonly fallback?: boolean; + readonly fallbackTargetIndexRevision?: number | null; + readonly retryFailedUpgrade?: boolean; + readonly probeFailed?: boolean; +} + +interface CheckedAcpRegistryProviderStatus { + readonly provider: ServerProvider; + readonly launchIdentity: string | null; + readonly indexRevision: number | null; + readonly cacheable: boolean; + readonly fallback?: boolean; + readonly fallbackTargetLaunchIdentity?: string | null; + readonly fallbackTargetVersion?: string | null; + readonly fallbackTargetIndexRevision?: number | null; + readonly probedLaunchIdentity?: string | null; + readonly failedTargetLaunchIdentity?: string | null; + readonly probeFailed?: boolean; +} + +interface ActiveFallbackState { + readonly targetLaunchIdentity: string | null; + readonly targetVersion: string | null; + readonly targetIndexRevision: number | null; + readonly fallbackVersion: string | null; + readonly fallbackLaunchIdentity: string | null; + readonly failedAtMs: number; + readonly message: string; +} + +interface FailedUpgradeTargetState { + readonly targetLaunchIdentity: string | null; + readonly status: ServerProvider["status"]; + readonly message: string | undefined; +} + +function runtimeIdentityFor( + provider: Pick, + launchIdentity: string | null, +): string | null { + return launchIdentity ?? provider.version; +} + +function readinessSignature(readiness: CheckedAcpRegistryReadiness) { + return { + installed: readiness.snapshot.installed, + version: readiness.snapshot.version, + status: readiness.snapshot.status, + message: readiness.snapshot.message, + documentationUrl: readiness.snapshot.setup?.documentationUrl, + iconUrl: readiness.snapshot.iconUrl, + launchIdentity: readiness.launchIdentity, + }; +} + +function installedRegistrySignature(readiness: CheckedAcpRegistryReadiness) { + return { + installed: readiness.snapshot.installed, + version: readiness.snapshot.version, + documentationUrl: readiness.snapshot.setup?.documentationUrl, + iconUrl: readiness.snapshot.iconUrl, + launchIdentity: readiness.launchIdentity, + }; +} + +const checkAcpRegistryProviderStatusWithIdentity = Effect.fn( + "AcpRegistryDriver.checkProviderStatus", +)(function* ( + input: SnapshotIdentity & { + readonly settings: AcpRegistrySettings; + readonly cwd: string; + readonly environment: NodeJS.ProcessEnv; + readonly modelDiscovery?: Omit & { + readonly onProbed: ( + probed: CheckedAcpRegistryProviderStatus, + ) => Effect.Effect>; + }; + }, + probeConfiguration: AcpRegistryConfigurationProbe, +): Effect.fn.Return< + CheckedAcpRegistryProviderStatus, + never, + AcpRegistrySupport.AcpRegistryCatalog | Requirements +> { + const checkedAt = DateTime.formatIso(yield* DateTime.now); + if (!input.settings.enabled) { + return { + provider: yield* buildInitialAcpRegistrySnapshot(input), + launchIdentity: null, + indexRevision: null, + cacheable: false, + }; + } + const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; + const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment)); + if (Result.isFailure(inspected)) { + return { + provider: buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, inspection: { status: "failed", message: `Could not inspect ACP Registry agent: ${inspected.failure.message}`, }, - }); - } - if (inspected.success.status !== "ready") { - return buildCheckedAcpRegistrySnapshot({ + }), + launchIdentity: null, + indexRevision: null, + cacheable: false, + }; + } + const inspectedIndexRevision = + "indexRevision" in inspected.success ? (inspected.success.indexRevision ?? null) : null; + if (inspected.success.status !== "ready") { + return { + provider: buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, inspection: inspected.success, - }); - } - const inspection = inspected.success; - const modelDiscovery = input.modelDiscovery; - const probed = yield* Effect.result( - probeConfiguration({ - instanceId: input.instanceId, - settings: input.settings, - cwd: input.cwd, - environment: providerProbeEnvironment(input.environment), - ...(modelDiscovery === undefined - ? {} - : { - modelDiscovery: { - onProbed: (probe) => - modelDiscovery.onProbed( - buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, inspection, probe }), - ), - onDiscovered: modelDiscovery.onDiscovered, - }, - }), }), - ); - return Result.isFailure(probed) - ? buildCheckedAcpRegistrySnapshot({ + launchIdentity: null, + indexRevision: inspectedIndexRevision, + cacheable: false, + }; + } + const readyInspection = inspected.success; + const buildProbedStatus = ( + probe: AcpRegistryConfigurationProbeResult, + ): CheckedAcpRegistryProviderStatus => { + if (input.settings.source === "local") { + return { + provider: buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, - inspection: inspected.success, - probeError: probed.failure, - }) - : buildCheckedAcpRegistrySnapshot({ + inspection: readyInspection, + probe, + }), + launchIdentity: null, + indexRevision: null, + cacheable: true, + }; + } + const resolved = probe.resolved; + if (resolved === undefined) { + return { + provider: buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, - inspection: inspected.success, - probe: probed.success, - }); + inspection: readyInspection, + probe, + }), + launchIdentity: null, + indexRevision: null, + cacheable: readyInspection.launchIdentity === undefined, + }; + } + const resolvedVersion = + input.settings.commandPath.trim().length > 0 + ? null + : (resolved.agent?.version ?? readyInspection.version); + const resolvedDocumentationUrl = + resolved.agent === undefined + ? readyInspection.documentationUrl + : (resolved.agent.website ?? resolved.agent.repository); + const resolvedIcon = resolved.agent === undefined ? readyInspection.icon : resolved.agent.icon; + const resolvedInspection: AcpRegistrySupport.AcpRegistryInspection = { + status: "ready", + agentId: readyInspection.agentId, + version: resolvedVersion, + distribution: resolved.distribution, + ...(resolved.launchIdentity === undefined ? {} : { launchIdentity: resolved.launchIdentity }), + ...(resolved.indexRevision === undefined ? {} : { indexRevision: resolved.indexRevision }), + ...(resolvedIcon ? { icon: resolvedIcon } : {}), + ...(resolvedDocumentationUrl ? { documentationUrl: resolvedDocumentationUrl } : {}), + }; + return { + provider: buildCheckedAcpRegistrySnapshot({ + ...input, + checkedAt, + inspection: resolvedInspection, + probe, + }), + launchIdentity: resolved.launchIdentity ?? null, + indexRevision: resolved.indexRevision ?? null, + cacheable: + resolved.launchIdentity !== undefined || readyInspection.launchIdentity === undefined, + ...(resolved.fallback + ? { + fallback: true, + fallbackTargetLaunchIdentity: + resolved.failedTarget?.launchIdentity ?? readyInspection.launchIdentity ?? null, + fallbackTargetVersion: resolved.failedTarget?.version ?? readyInspection.version, + fallbackTargetIndexRevision: + resolved.failedTarget?.indexRevision ?? inspectedIndexRevision, + } + : {}), + }; + }; + const resolvedDuringProbeRef = yield* Ref.make( + undefined, + ); + const modelDiscovery = input.modelDiscovery; + const probed = yield* Effect.result( + probeConfiguration({ + instanceId: input.instanceId, + settings: input.settings, + cwd: input.cwd, + environment: providerProbeEnvironment(input.environment), + onResolved: (resolved) => Ref.set(resolvedDuringProbeRef, resolved), + ...(modelDiscovery === undefined + ? {} + : { + modelDiscovery: { + onProbed: (probe) => modelDiscovery.onProbed(buildProbedStatus(probe)), + onDiscovered: modelDiscovery.onDiscovered, + }, + }), + }), + ); + if (Result.isFailure(probed)) { + const resolvedDuringProbe = yield* Ref.get(resolvedDuringProbeRef); + const failedInspection: AcpRegistrySupport.AcpRegistryInspection = + resolvedDuringProbe === undefined || input.settings.source === "local" + ? readyInspection + : { + ...readyInspection, + version: + input.settings.commandPath.trim().length > 0 + ? null + : (resolvedDuringProbe.agent?.version ?? readyInspection.version), + ...(resolvedDuringProbe.launchIdentity === undefined + ? {} + : { launchIdentity: resolvedDuringProbe.launchIdentity }), + }; + const probedLaunchIdentity = + resolvedDuringProbe?.launchIdentity ?? readyInspection.launchIdentity ?? null; + const failedTargetLaunchIdentity = + (resolvedDuringProbe?.fallback + ? resolvedDuringProbe.failedTarget?.launchIdentity + : undefined) ?? probedLaunchIdentity; + const failedIndexRevision = + (resolvedDuringProbe?.fallback + ? resolvedDuringProbe.failedTarget?.indexRevision + : undefined) ?? + resolvedDuringProbe?.indexRevision ?? + inspectedIndexRevision; + return { + provider: buildCheckedAcpRegistrySnapshot({ + ...input, + checkedAt, + inspection: failedInspection, + probeError: probed.failure, + }), + launchIdentity: null, + indexRevision: failedIndexRevision, + cacheable: false, + probedLaunchIdentity, + failedTargetLaunchIdentity, + probeFailed: true, + }; + } + return buildProbedStatus(probed.success); +}); + +export const checkAcpRegistryProviderStatus = ( + input: SnapshotIdentity & { + readonly settings: AcpRegistrySettings; + readonly cwd: string; + readonly environment: NodeJS.ProcessEnv; + readonly modelDiscovery?: Omit & { + readonly onProbed: (provider: ServerProvider) => Effect.Effect>; + }; }, -); + probeConfiguration: AcpRegistryConfigurationProbe, +): Effect.Effect => { + const { modelDiscovery, ...rest } = input; + return checkAcpRegistryProviderStatusWithIdentity( + { + ...rest, + ...(modelDiscovery === undefined + ? {} + : { + modelDiscovery: { + onProbed: (probed) => modelDiscovery.onProbed(probed.provider), + onDiscovered: modelDiscovery.onDiscovered, + }, + }), + }, + probeConfiguration, + ).pipe(Effect.map(({ provider }) => provider)); +}; -export const checkAcpRegistryProviderReadiness = Effect.fn( +const checkAcpRegistryProviderReadinessWithIdentity = Effect.fn( "AcpRegistryDriver.checkProviderReadiness", )(function* ( input: SnapshotIdentity & { readonly settings: AcpRegistrySettings; readonly environment: NodeJS.ProcessEnv; }, -): Effect.fn.Return { +): Effect.fn.Return { const checkedAt = DateTime.formatIso(yield* DateTime.now); if (!input.settings.enabled) { - return yield* buildInitialAcpRegistrySnapshot(input); + return { + snapshot: yield* buildInitialAcpRegistrySnapshot(input), + launchIdentity: null, + indexRevision: null, + }; } const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment)); @@ -615,14 +920,30 @@ export const checkAcpRegistryProviderReadiness = Effect.fn( } : inspected.success, }); + const indexRevision = + inspected._tag === "Success" && "indexRevision" in inspected.success + ? (inspected.success.indexRevision ?? null) + : null; return inspected._tag === "Success" && inspected.success.status === "ready" ? { - ...snapshot, - message: "Checking ACP authentication, models, and commands in the background...", + snapshot: { + ...snapshot, + message: "Checking ACP authentication, models, and commands in the background...", + }, + launchIdentity: inspected.success.launchIdentity ?? null, + indexRevision, } - : snapshot; + : { snapshot, launchIdentity: null, indexRevision }; }); +export const checkAcpRegistryProviderReadiness = ( + input: SnapshotIdentity & { + readonly settings: AcpRegistrySettings; + readonly environment: NodeJS.ProcessEnv; + }, +): Effect.Effect => + checkAcpRegistryProviderReadinessWithIdentity(input).pipe(Effect.map(({ snapshot }) => snapshot)); + export type AcpRegistryDriverEnv = | AcpRegistryAdapterV2DriverEnv | Digest.Digest @@ -645,6 +966,7 @@ export const AcpRegistryDriver: ProviderDriver runtimeCoordinator.value - .clearAvailableCommands(instanceId) - .pipe(Effect.andThen(runtimeCoordinator.value.clearLiveConfiguration(instanceId))), + .clearAvailableCommands(instanceId, { dispose: true }) + .pipe( + Effect.andThen( + runtimeCoordinator.value.clearLiveConfiguration(instanceId, { dispose: true }), + ), + ), ); } const random = yield* SecureRandom.SecureRandom; @@ -720,22 +1046,89 @@ export const AcpRegistryDriver: ProviderDriver(null); + // Probes never produce "authenticated" directly; saved confirmation re-promotes "unknown" + // in withLiveRuntimeState, so stripping it prevents historical auth surviving logout. + const stripConfirmedAuth = (auth: ServerProvider["auth"]): ServerProvider["auth"] => + auth.status === "authenticated" ? { ...auth, status: "unknown" } : auth; + const lastSuccessfulRuntime = yield* Ref.make<{ + readonly identity: string; + readonly provider: ServerProvider; + } | null>(null); + // Tracks the latest accepted auth result per runtime separately from lastSuccessfulRuntime + // capabilities so an un-adopted failure on B neither clears retained A's confirmation nor + // restores lost confirmation. + const latestAcceptedAuth = yield* Ref.make<{ + readonly identity: string; + readonly auth: ServerProvider["auth"]; + } | null>(null); + const failedUpgradeTarget = yield* Ref.make(null); + const clearLiveState = ( + options?: AcpRegistryRuntimeCoordinator.AcpRegistryClearLiveStateOptions, + ) => + (Option.isSome(runtimeCoordinator) + ? runtimeCoordinator.value + .clearLiveConfiguration(instanceId, options) + .pipe( + Effect.andThen(runtimeCoordinator.value.clearAvailableCommands(instanceId, options)), + ) + : Effect.void + ).pipe( + Effect.andThen(clearLearnedModels), + Effect.andThen(Ref.set(activeRuntimeIdentity, options?.preserveRuntimeIdentity ?? null)), + Effect.andThen( + options?.preserveRuntimeIdentity === undefined + ? Ref.set(lastSuccessfulRuntime, null).pipe( + Effect.andThen(Ref.set(latestAcceptedAuth, null)), + Effect.andThen(Ref.set(failedUpgradeTarget, null)), + ) + : Ref.update(latestAcceptedAuth, (current) => + current !== null && current.identity === options.preserveRuntimeIdentity + ? current + : null, + ), + ), + ); const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* ( input: ServerProvider, + options?: { + readonly applySessionLiveState?: boolean; + readonly sessionRuntimeIdentity?: string | null; + readonly requireMatchingRuntimeIdentity?: boolean; + readonly useLearnedModels?: boolean; + readonly persistLearnedModels?: boolean; + }, ) { - if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false); - if (input.installed) yield* learnedModelOptions.setVersion(input.version); + if (!input.installed) { + return { + provider: input, + appliedLiveConfiguration: undefined as AcpRegistryLiveConfiguration | undefined, + }; + } + if (options?.persistLearnedModels !== false && options?.useLearnedModels !== false) { + yield* learnedModelOptions.setVersion(input.version); + } const provider = input.enabled && input.installed && @@ -744,70 +1137,267 @@ export const AcpRegistryDriver: ProviderDriver + options?.useLearnedModels === false + ? Effect.succeed(withCommands) + : learnedModelOptions.get.pipe( + Effect.map((learned) => withAcpRegistryLearnedModelOptions(withCommands, learned)), + ), + onSome: (liveConfiguration) => + applyLiveConfiguration(withCommands, liveConfiguration, { + ...(options?.useLearnedModels === undefined + ? {} + : { useLearnedModels: options.useLearnedModels }), + ...(options?.persistLearnedModels === undefined + ? {} + : { persistLearnedModels: options.persistLearnedModels }), + }), + }); + return { + provider: applyAcpRegistryUrlAuthAction(withConfiguration, authAction), + appliedLiveConfiguration: Option.getOrUndefined(configuration), + }; }); // A local executable's version comes only from probing it, so readiness checks reuse the last report. const reportedLocalVersion = yield* Ref.make(null); - const checkProvider = checkAcpRegistryProviderReadiness(readinessInput).pipe( - Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), - Effect.flatMap((provider) => - Ref.get(reportedLocalVersion).pipe( - Effect.map((version) => - provider.installed && provider.version === null && version !== null - ? { ...provider, version } - : provider, + const latestCheckedReadiness = yield* Ref.make(null); + const activeFallback = yield* Ref.make(null); + const retiredRuntimeIdentities = yield* Ref.make>(new Map()); + const inspectReadiness = (options?: { + readonly applySessionLiveState?: boolean; + readonly seedActiveRuntimeIdentity?: boolean; + readonly preserveActiveFallback?: boolean; + }) => + checkAcpRegistryProviderReadinessWithIdentity(readinessInput).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.flatMap(({ snapshot, launchIdentity, indexRevision }) => + Effect.all({ + version: Ref.get(reportedLocalVersion), + fallbackState: Ref.get(activeFallback), + failedUpgrade: Ref.get(failedUpgradeTarget), + lastRuntime: Ref.get(lastSuccessfulRuntime), + acceptedAuth: Ref.get(latestAcceptedAuth), + activeIdentity: Ref.get(activeRuntimeIdentity), + }).pipe( + Effect.map( + ({ + version, + fallbackState, + failedUpgrade, + lastRuntime, + acceptedAuth, + activeIdentity, + }) => { + const withLocalVersion = + snapshot.installed && snapshot.version === null && version !== null + ? { ...snapshot, version } + : snapshot; + if ( + options?.preserveActiveFallback === true && + fallbackState !== null && + withLocalVersion.installed && + launchIdentity !== null && + launchIdentity === fallbackState.targetLaunchIdentity + ) { + const preservedBase = + lastRuntime !== null && + fallbackState.fallbackLaunchIdentity !== null && + lastRuntime.identity === fallbackState.fallbackLaunchIdentity + ? applyRegistryReadinessMetadata(lastRuntime.provider, withLocalVersion) + : withLocalVersion; + return { + snapshot: { + ...preservedBase, + checkedAt: withLocalVersion.checkedAt, + installed: true, + version: fallbackState.fallbackVersion, + status: withLocalVersion.enabled ? ("ready" as const) : ("disabled" as const), + }, + launchIdentity: fallbackState.fallbackLaunchIdentity, + indexRevision, + fallback: true as const, + fallbackTargetIndexRevision: fallbackState.targetIndexRevision, + retryFailedUpgrade: false as const, + preserveStatus: undefined as ServerProvider["status"] | undefined, + preserveMessage: fallbackState.message as string | undefined, + }; + } + if ( + options?.preserveActiveFallback === true && + failedUpgrade !== null && + lastRuntime !== null && + activeIdentity !== null && + lastRuntime.identity === activeIdentity && + withLocalVersion.installed && + launchIdentity !== null && + launchIdentity === failedUpgrade.targetLaunchIdentity + ) { + const { message: _previousMessage, ...lastProviderWithoutMessage } = + lastRuntime.provider; + const preservedAuth = + acceptedAuth !== null && acceptedAuth.identity === lastRuntime.identity + ? acceptedAuth.auth + : lastProviderWithoutMessage.auth; + return { + snapshot: { + ...lastProviderWithoutMessage, + auth: preservedAuth, + checkedAt: withLocalVersion.checkedAt, + installed: true, + status: withLocalVersion.enabled + ? failedUpgrade.status + : ("disabled" as const), + ...(failedUpgrade.message !== undefined + ? { message: failedUpgrade.message } + : {}), + }, + launchIdentity: lastRuntime.identity, + indexRevision, + fallback: false as const, + fallbackTargetIndexRevision: null as number | null, + retryFailedUpgrade: true as const, + preserveStatus: (withLocalVersion.enabled + ? failedUpgrade.status + : "disabled") as ServerProvider["status"] | undefined, + preserveMessage: failedUpgrade.message, + }; + } + return { + snapshot: withLocalVersion, + launchIdentity, + indexRevision, + fallback: false as const, + fallbackTargetIndexRevision: null as number | null, + retryFailedUpgrade: false as const, + preserveStatus: undefined as ServerProvider["status"] | undefined, + preserveMessage: undefined as string | undefined, + }; + }, + ), ), ), - ), - Effect.flatMap(withLiveRuntimeState), + Effect.flatMap( + ({ + snapshot, + launchIdentity, + indexRevision, + fallback, + fallbackTargetIndexRevision, + retryFailedUpgrade, + preserveStatus, + preserveMessage, + }) => { + const nextIdentity = snapshot.installed + ? runtimeIdentityFor(snapshot, launchIdentity) + : null; + return Ref.modify(activeRuntimeIdentity, (previousIdentity) => { + if ( + options?.seedActiveRuntimeIdentity === true && + snapshot.installed && + previousIdentity === null && + nextIdentity !== null + ) { + return [nextIdentity, nextIdentity] as const; + } + return [previousIdentity, previousIdentity] as const; + }).pipe( + Effect.flatMap((previousIdentity) => { + const runtimeChanged = + previousIdentity !== null && + nextIdentity !== null && + previousIdentity !== nextIdentity; + return withLiveRuntimeState(snapshot, { + applySessionLiveState: options?.applySessionLiveState ?? true, + sessionRuntimeIdentity: nextIdentity, + requireMatchingRuntimeIdentity: runtimeChanged, + useLearnedModels: !runtimeChanged, + persistLearnedModels: !runtimeChanged, + }).pipe( + Effect.map(({ provider }) => ({ + snapshot: + preserveMessage !== undefined || preserveStatus !== undefined + ? { + ...provider, + ...(preserveStatus !== undefined ? { status: preserveStatus } : {}), + ...(preserveMessage !== undefined ? { message: preserveMessage } : {}), + } + : provider, + launchIdentity, + indexRevision, + ...(fallback ? { fallback: true, fallbackTargetIndexRevision } : {}), + ...(retryFailedUpgrade ? { retryFailedUpgrade: true } : {}), + })), + ); + }), + ); + }, + ), + ); + const checkProvider = inspectReadiness({ + seedActiveRuntimeIdentity: true, + preserveActiveFallback: true, + }).pipe( + Effect.tap((readiness) => Ref.set(latestCheckedReadiness, readiness)), + Effect.map(({ snapshot }) => snapshot), ); - const modelsToDiscover = Effect.fn("AcpRegistryDriver.modelsToDiscover")(function* ( - provider: ServerProvider, - ) { - yield* learnedModelOptions.setVersion(provider.version); - const settings = yield* host.settings.get.pipe(Effect.option); - // Without settings the hidden models are unknown, so nothing is opened. - if (Option.isNone(settings)) return []; - return acpRegistryModelsToDiscover({ - provider, - settings: settings.value, - learned: yield* learnedModelOptions.get, - }); - }); - const enrichProvider = (publishProbed: (provider: ServerProvider) => Effect.Effect) => - checkAcpRegistryProviderStatus( + interface EnrichedAcpRegistryProvider { + readonly provider: ServerProvider; + readonly launchIdentity: string | null; + readonly indexRevision: number | null; + readonly fallback: boolean; + readonly fallbackTargetLaunchIdentity: string | null; + readonly fallbackTargetVersion: string | null; + readonly fallbackTargetIndexRevision: number | null; + readonly probedLaunchIdentity: string | null; + readonly failedTargetLaunchIdentity: string | null; + readonly probeFailed: boolean; + readonly fromCache: boolean; + readonly captured: { + readonly invalidationGeneration: number; + readonly liveGenerationByRuntime: ReadonlyMap; + }; + } + const enrichProvider = ( + modelDiscovery: Omit & { + readonly onProbed: ( + probed: CheckedAcpRegistryProviderStatus, + ) => Effect.Effect>; + }, + ) => + checkAcpRegistryProviderStatusWithIdentity( { ...readinessInput, cwd: host.paths.cwd, - modelDiscovery: { - // Publish what the probe found first; discovery only adds options to it. - onProbed: (provider) => - modelsToDiscover(provider).pipe( - Effect.tap((modelIds) => - modelIds.length === 0 ? Effect.void : publishProbed(provider), - ), - ), - onDiscovered: (configuration) => { - const discovered = acpRegistryCurrentModelOptions(configuration); - return discovered === undefined - ? Effect.void - : learnedModelOptions.learn(discovered.modelId, discovered.options, "discovered"); - }, - }, + modelDiscovery, }, probeAcpRegistryConfiguration, ).pipe( @@ -817,68 +1407,254 @@ export const AcpRegistryDriver: ProviderDriver 0; + const currentCatalogIndexRevision = catalog.currentIndexRevision(); + const lastSeenIndexRevision = yield* Ref.make(0); + const acknowledgeRevision = (revision: number) => + Ref.update(lastSeenIndexRevision, (seen) => Math.max(seen, revision)); + const refreshRegistryIndex = Effect.fn("AcpRegistryDriver.refreshRegistryIndex")(function* () { + return yield* catalog + .refreshIndex({ + maxAgeMs: REGISTRY_INDEX_MAX_AGE_MS, + failureBackoffMs: REGISTRY_FAILURE_BACKOFF_MS, + }) + .pipe(Effect.catch(() => Ref.get(lastSeenIndexRevision))); + }); const enrichmentCache = yield* Ref.make({ - generation: 0, + invalidationGeneration: 0, + liveGenerationByRuntime: new Map(), entry: null, }); const liveSnapshotSemaphore = yield* Semaphore.make(1); - const invalidateEnrichmentCache = Ref.update(enrichmentCache, (current) => ({ - generation: current.generation + 1, - entry: null, - })); + const invalidateEnrichmentCache = Ref.set(activeFallback, null).pipe( + Effect.andThen(Ref.set(failedUpgradeTarget, null)), + Effect.andThen( + Ref.update(enrichmentCache, (current) => ({ + invalidationGeneration: current.invalidationGeneration + 1, + liveGenerationByRuntime: new Map(), + entry: null, + })), + ), + ); + const clearCachedProbeForRuntime = (runtimeIdentity: string | null) => + Ref.update(enrichmentCache, (cache) => { + if (cache.entry === null) return cache; + const entryIdentity = runtimeIdentityFor( + cache.entry.provider, + cache.entry.launchIdentity ?? null, + ); + return effectiveConfig.source === "local" || + (runtimeIdentity !== null && entryIdentity === runtimeIdentity) + ? { ...cache, entry: null } + : cache; + }); + let latestAuthConfirmed = yield* confirmedAuthentication.get; + const setConfirmedAuth = (authenticated: boolean) => + Effect.uninterruptible( + Effect.sync(() => { + latestAuthConfirmed = authenticated; + }).pipe(Effect.andThen(confirmedAuthentication.set(authenticated))), + ); + const markAuthConfirmationCleared = () => { + latestAuthConfirmed = false; + }; + const recordAcceptedAuthRejection = (identity: string | null, auth: ServerProvider["auth"]) => + clearCachedProbeForRuntime(identity).pipe( + Effect.andThen( + identity === null ? Effect.void : Ref.set(latestAcceptedAuth, { identity, auth }), + ), + Effect.andThen(setConfirmedAuth(false)), + ); + const isProbeStillCurrent = ( + current: AcpRegistryEnrichmentCache, + captured: { + readonly invalidationGeneration: number; + readonly liveGenerationByRuntime: ReadonlyMap; + }, + probeIdentity: string | null, + ) => + current.invalidationGeneration === captured.invalidationGeneration && + (current.liveGenerationByRuntime.get(probeIdentity) ?? 0) === + (captured.liveGenerationByRuntime.get(probeIdentity) ?? 0); const enrichProviderCached = Effect.fn("AcpRegistryDriver.enrichProviderCached")(function* ( - baseSnapshot: ServerProvider, - publish: (enriched: { - readonly provider: ServerProvider; - readonly generation: number; - }) => Effect.Effect, - ) { + target: CheckedAcpRegistryReadiness, + publishProbed: ( + enriched: EnrichedAcpRegistryProvider, + ) => Effect.Effect<{ readonly published: boolean }>, + ): Effect.fn.Return { const now = yield* Clock.currentTimeMillis; const cacheState = yield* Ref.get(enrichmentCache); + const captured = { + invalidationGeneration: cacheState.invalidationGeneration, + liveGenerationByRuntime: cacheState.liveGenerationByRuntime, + }; const cached = cacheState.entry; - if ( + if (target.fallback === true) { + const fallbackState = yield* Ref.get(activeFallback); + // Enforce fallback retry backoff before probing so 30s provisional cache expiry on + // 1-model agents cannot re-trigger downloads or reset failedAtMs inside the 60s window. + if ( + fallbackState !== null && + now >= fallbackState.failedAtMs && + now - fallbackState.failedAtMs < FALLBACK_RETRY_BACKOFF_MS + ) { + const targetIdentity = runtimeIdentityFor(target.snapshot, target.launchIdentity); + const cachedMatchesTarget = + cached !== null && + cached.provider.version === target.snapshot.version && + (cached.launchIdentity === undefined || + target.launchIdentity === null || + cached.launchIdentity === target.launchIdentity); + const lastRuntime = cachedMatchesTarget ? null : yield* Ref.get(lastSuccessfulRuntime); + const baseFallbackProvider = cachedMatchesTarget + ? cached.provider + : lastRuntime !== null && lastRuntime.identity === targetIdentity + ? lastRuntime.provider + : target.snapshot; + return { + provider: { + ...applyRegistryReadinessMetadata(baseFallbackProvider, target.snapshot), + checkedAt: target.snapshot.checkedAt, + status: target.snapshot.enabled ? ("ready" as const) : ("disabled" as const), + message: fallbackState.message, + }, + launchIdentity: target.launchIdentity, + indexRevision: target.indexRevision, + fallback: true, + fallbackTargetLaunchIdentity: fallbackState.targetLaunchIdentity, + fallbackTargetVersion: fallbackState.targetVersion, + fallbackTargetIndexRevision: fallbackState.targetIndexRevision, + probedLaunchIdentity: null, + failedTargetLaunchIdentity: null, + probeFailed: false, + fromCache: true, + captured, + }; + } + } else if ( + target.retryFailedUpgrade !== true && cached !== null && isAcpRegistryCacheValid( cached, - baseSnapshot.version, + target.snapshot.version, effectiveConfig.source === "local", now, + target.launchIdentity, ) ) { return { - provider: { ...cached.provider, checkedAt: baseSnapshot.checkedAt }, - generation: cacheState.generation, + provider: { + ...applyRegistryReadinessMetadata(cached.provider, target.snapshot), + checkedAt: target.snapshot.checkedAt, + }, + launchIdentity: target.launchIdentity, + indexRevision: target.indexRevision, + fallback: false, + fallbackTargetLaunchIdentity: null, + fallbackTargetVersion: null, + fallbackTargetIndexRevision: null, + probedLaunchIdentity: null, + failedTargetLaunchIdentity: null, + probeFailed: false, + fromCache: true, + captured, }; } + const toEnriched = ( + status: CheckedAcpRegistryProviderStatus, + ): EnrichedAcpRegistryProvider => ({ + provider: status.provider, + launchIdentity: status.launchIdentity, + indexRevision: status.indexRevision, + fallback: status.fallback === true, + fallbackTargetLaunchIdentity: status.fallbackTargetLaunchIdentity ?? target.launchIdentity, + fallbackTargetVersion: status.fallbackTargetVersion ?? target.snapshot.version, + fallbackTargetIndexRevision: status.fallbackTargetIndexRevision ?? target.indexRevision, + probedLaunchIdentity: status.probedLaunchIdentity ?? null, + failedTargetLaunchIdentity: status.failedTargetLaunchIdentity ?? null, + probeFailed: status.probeFailed === true, + fromCache: false, + captured, + }); const remember = Effect.fn("AcpRegistryDriver.rememberEnrichment")(function* ( - enriched: ServerProvider, + status: CheckedAcpRegistryProviderStatus, ) { - if (effectiveConfig.source === "local" && enriched.status === "ready") { - yield* Ref.set(reportedLocalVersion, enriched.version); + if (effectiveConfig.source === "local" && status.provider.status === "ready") { + yield* Ref.set(reportedLocalVersion, status.provider.version); } - if (enriched.status === "ready") { + const probeIdentity = status.provider.installed + ? runtimeIdentityFor(status.provider, status.launchIdentity) + : null; + if (status.cacheable && status.provider.status === "ready") { const completedAt = yield* Clock.currentTimeMillis; yield* Ref.update(enrichmentCache, (current) => - current.generation === cacheState.generation + isProbeStillCurrent(current, captured, probeIdentity) ? { ...current, entry: { - provider: enriched, - expiresAt: completedAt + acpRegistryProbeTtlMs(enriched), + provider: status.provider, + expiresAt: completedAt + acpRegistryProbeTtlMs(status.provider), + launchIdentity: status.launchIdentity, }, } : current, ); } }); - const enriched = yield* enrichProvider((provider) => - remember(provider).pipe( - Effect.andThen(publish({ provider, generation: cacheState.generation })), - ), - ); + let probedRuntimeIdentity: string | null = null; + const enriched = yield* enrichProvider({ + // Publish what the probe found first; discovery only adds options to it. + onProbed: Effect.fn("AcpRegistryDriver.onProbed")(function* (probed) { + const probeIdentity = probed.provider.installed + ? runtimeIdentityFor(probed.provider, probed.launchIdentity) + : null; + probedRuntimeIdentity = probeIdentity; + if (!isProbeStillCurrent(yield* Ref.get(enrichmentCache), captured, probeIdentity)) { + return []; + } + const previousIdentity = yield* Ref.get(activeRuntimeIdentity); + const runtimeChanged = + previousIdentity !== null && + probeIdentity !== null && + previousIdentity !== probeIdentity; + if (!runtimeChanged && probed.provider.installed) { + yield* learnedModelOptions.setVersion(probed.provider.version); + } + const settings = yield* host.settings.get.pipe(Effect.option); + // Without settings the hidden models are unknown, so nothing is opened. + if (Option.isNone(settings)) return []; + const learned = runtimeChanged ? new Map() : yield* learnedModelOptions.get; + const modelIds = acpRegistryModelsToDiscover({ + provider: probed.provider, + settings: settings.value, + learned, + }); + if (modelIds.length === 0) return []; + yield* remember(probed); + const { published } = yield* publishProbed(toEnriched(probed)); + return published ? modelIds : []; + }), + onDiscovered: Effect.fn("AcpRegistryDriver.onDiscovered")(function* (configuration) { + if ( + !isProbeStillCurrent(yield* Ref.get(enrichmentCache), captured, probedRuntimeIdentity) + ) { + return; + } + const discovered = acpRegistryCurrentModelOptions(configuration); + if (discovered !== undefined) { + yield* learnedModelOptions.learn(discovered.modelId, discovered.options, "discovered"); + } + }), + }); yield* remember(enriched); - return { provider: enriched, generation: cacheState.generation }; + return toEnriched(enriched); }); + const reconcilingState = yield* Ref.make>(new Map()); + const refreshTarget = yield* Deferred.make>(); + const triggerSnapshotRefresh = Deferred.await(refreshTarget).pipe(Effect.flatten); const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); const snapshot = yield* makeManagedServerProvider< ProviderSnapshotSettings @@ -890,107 +1666,985 @@ export const AcpRegistryDriver: ProviderDriver buildInitialAcpRegistrySnapshot(readinessInput), checkProvider, - enrichSnapshot: Effect.fn("enrichSnapshot")(function ({ + reconcileCheckedSnapshot: (probed) => + !latestAuthConfirmed && probed.auth.status === "authenticated" + ? { ...probed, auth: stripConfirmedAuth(probed.auth) } + : probed, + enrichSnapshot: Effect.fn("enrichSnapshot")(function* ({ snapshot, getSnapshot, - publishSnapshot, + tryPublishSnapshot, }) { - if (!snapshot.installed) return Effect.void; + const initialReadiness: CheckedAcpRegistryReadiness = yield* Ref.get( + latestCheckedReadiness, + ).pipe( + Effect.map((latest) => + latest !== null && + latest.snapshot.checkedAt === snapshot.checkedAt && + latest.snapshot.installed === snapshot.installed && + latest.snapshot.version === snapshot.version + ? { + snapshot, + launchIdentity: latest.launchIdentity, + indexRevision: latest.indexRevision, + ...(latest.fallback + ? { + fallback: true, + fallbackTargetIndexRevision: latest.fallbackTargetIndexRevision ?? null, + } + : {}), + ...(latest.retryFailedUpgrade ? { retryFailedUpgrade: true } : {}), + } + : { snapshot, launchIdentity: null, indexRevision: null }, + ), + ); + const expectedRuntimeIdentity = yield* Ref.make( + snapshot.installed + ? runtimeIdentityFor(initialReadiness.snapshot, initialReadiness.launchIdentity) + : null, + ); + const probeReconcileState = yield* Ref.make<{ + readonly inFlight: string | null; + readonly pending: string | null; + }>({ inFlight: null, pending: null }); + const maybeReconcileUnmatchedRuntime = ( + incomingIdentity: string | undefined, + ): Effect.Effect => { + if (incomingIdentity === undefined || !tracksRegistryIndex) return Effect.void; + return Effect.gen(function* () { + const retiredAtRevision = (yield* Ref.get(retiredRuntimeIdentities)).get( + incomingIdentity, + ); + const currentRevision = + retiredAtRevision === undefined ? undefined : yield* currentCatalogIndexRevision; + if ( + retiredAtRevision !== undefined && + currentRevision !== undefined && + currentRevision <= retiredAtRevision + ) { + return; + } + const parkedOnProbe = yield* Ref.modify(probeReconcileState, (state) => + state.inFlight === incomingIdentity + ? ([true, { ...state, pending: incomingIdentity }] as const) + : ([false, state] as const), + ); + if (parkedOnProbe) return; + const claimed = yield* Ref.modify(reconcilingState, (state) => { + const next = new Map(state); + if (state.has(incomingIdentity)) { + next.set(incomingIdentity, true); + return [false, next] as const; + } + next.set(incomingIdentity, false); + return [true, next] as const; + }); + if (!claimed) return; + yield* Effect.gen(function* () { + const inspected = yield* Effect.result( + catalog.inspect(readinessInput.settings, readinessInput.environment), + ); + let matched = false; + if ( + Result.isSuccess(inspected) && + inspected.success.status === "ready" && + inspected.success.launchIdentity === incomingIdentity + ) { + matched = true; + yield* Ref.update(activeFallback, (current) => + current?.targetLaunchIdentity === incomingIdentity ? null : current, + ); + yield* Ref.update(failedUpgradeTarget, (current) => + current?.targetLaunchIdentity === incomingIdentity ? null : current, + ); + yield* triggerSnapshotRefresh; + } else if ( + retiredAtRevision !== undefined && + currentRevision !== undefined && + Result.isSuccess(inspected) + ) { + const stampRevision = + "indexRevision" in inspected.success && + typeof inspected.success.indexRevision === "number" + ? inspected.success.indexRevision + : currentRevision; + yield* Ref.update(retiredRuntimeIdentities, (retired) => { + if (!retired.has(incomingIdentity)) return retired; + const next = new Map(retired); + next.set( + incomingIdentity, + Math.max(retired.get(incomingIdentity) ?? 0, stampRevision), + ); + return next; + }); + } + const replayPending = yield* Ref.modify(reconcilingState, (state) => { + if (!state.has(incomingIdentity)) return [false, state] as const; + const next = new Map(state); + const pending = next.get(incomingIdentity) === true; + next.delete(incomingIdentity); + return [pending, next] as const; + }); + if (!matched && replayPending) { + yield* maybeReconcileUnmatchedRuntime(incomingIdentity); + } + }).pipe( + Effect.onError((cause) => + Ref.modify(reconcilingState, (state) => { + if (!state.has(incomingIdentity)) return [false, state] as const; + const next = new Map(state); + const pending = next.get(incomingIdentity) === true; + next.delete(incomingIdentity); + return [pending, next] as const; + }).pipe( + Effect.flatMap((replayPending) => + // Replay a parked update after an unexpected defect (never on interruption). + replayPending && !Cause.hasInterruptsOnly(cause) + ? maybeReconcileUnmatchedRuntime(incomingIdentity) + : Effect.void, + ), + ), + ), + Effect.withSpan("AcpRegistryDriver.reconcileUnmatchedRuntime"), + Effect.forkIn(driverScope), + ); + }); + }; + const checkLiveUpdate = (meta: AcpRegistryRuntimeCoordinator.AcpRegistryLiveUpdateMeta) => + Effect.all({ + isCurrent: meta.isCurrent, + expected: Ref.get(expectedRuntimeIdentity), + active: Ref.get(activeRuntimeIdentity), + }).pipe( + Effect.map(({ isCurrent, expected, active }) => { + const runtimeTransitioning = + active !== null && expected !== null && active !== expected; + if (!isCurrent) { + return { + accepted: false, + reconcileIdentity: undefined, + expected, + runtimeTransitioning, + } as const; + } + if (meta.runtimeIdentity !== undefined) { + const accepted = expected === null || meta.runtimeIdentity === expected; + return { + accepted, + reconcileIdentity: accepted ? undefined : meta.runtimeIdentity, + expected, + runtimeTransitioning, + } as const; + } + return { + accepted: !runtimeTransitioning, + reconcileIdentity: undefined, + expected, + runtimeTransitioning, + } as const; + }), + ); const publishEnriched = ({ provider, - generation, - }: { - readonly provider: ServerProvider; - readonly generation: number; - }) => + launchIdentity, + indexRevision, + fallback, + fallbackTargetLaunchIdentity, + fallbackTargetVersion, + fallbackTargetIndexRevision, + probedLaunchIdentity, + failedTargetLaunchIdentity, + probeFailed, + fromCache, + captured, + }: EnrichedAcpRegistryProvider) => liveSnapshotSemaphore.withPermit( - Ref.get(enrichmentCache).pipe( - Effect.flatMap((current) => - current.generation === generation - ? withLiveRuntimeState(provider).pipe(Effect.flatMap(publishSnapshot)) - : Effect.void, - ), - ), + Effect.gen(function* () { + const previousIdentity = yield* Ref.get(activeRuntimeIdentity); + const resolvedIdentity = + provider.installed && !probeFailed + ? runtimeIdentityFor(provider, launchIdentity) + : null; + const current = yield* Ref.get(enrichmentCache); + if (!isProbeStillCurrent(current, captured, resolvedIdentity)) { + return { + published: false, + readiness: null, + publishedIdentity: null, + }; + } + if (probeFailed && provider.installed && previousIdentity !== null) { + // The new runtime failed before resolving/starting; preserve the last + // accepted snapshot only when one exists for previousIdentity so we never + // overlay A's live models/commands onto B's failure snapshot. + const lastRuntime = yield* Ref.get(lastSuccessfulRuntime); + const isProbedDifferentRuntime = + probedLaunchIdentity !== null && probedLaunchIdentity !== previousIdentity; + const isUpgradeFailure = + failedTargetLaunchIdentity !== null && + failedTargetLaunchIdentity !== previousIdentity; + if (lastRuntime !== null && lastRuntime.identity === previousIdentity) { + const { message: _previousMessage, ...base } = lastRuntime.provider; + const acceptedAuth = yield* Ref.get(latestAcceptedAuth); + const retainedAuth = + acceptedAuth !== null && acceptedAuth.identity === previousIdentity + ? acceptedAuth.auth + : base.auth; + const activeRuntimeUnauthenticated = + !isProbedDifferentRuntime && provider.auth.status === "unauthenticated"; + const preservedBase: ServerProvider = { + ...base, + checkedAt: provider.checkedAt, + status: provider.status, + auth: activeRuntimeUnauthenticated ? provider.auth : retainedAuth, + ...(provider.message !== undefined ? { message: provider.message } : {}), + }; + const { provider: nextSnapshotRaw } = yield* withLiveRuntimeState(preservedBase, { + sessionRuntimeIdentity: previousIdentity, + requireMatchingRuntimeIdentity: false, + useLearnedModels: true, + persistLearnedModels: false, + }); + const preserveProbeFailure = + isUpgradeFailure || provider.auth.status === "unauthenticated"; + const nextSnapshot = preserveProbeFailure + ? { + ...nextSnapshotRaw, + status: provider.status, + ...(provider.message !== undefined ? { message: provider.message } : {}), + } + : nextSnapshotRaw; + const published = yield* Effect.uninterruptible( + tryPublishSnapshot( + nextSnapshot, + activeRuntimeUnauthenticated ? markAuthConfirmationCleared : undefined, + ).pipe( + Effect.tap((didPublish) => + didPublish + ? Effect.gen(function* () { + if (activeRuntimeUnauthenticated) { + // Clear fallback backoff so a user's sign-in retry probes immediately. + yield* Ref.set(activeFallback, null); + yield* recordAcceptedAuthRejection(previousIdentity, provider.auth); + } + yield* Ref.set(expectedRuntimeIdentity, previousIdentity); + yield* Ref.set( + failedUpgradeTarget, + isUpgradeFailure + ? { + targetLaunchIdentity: failedTargetLaunchIdentity, + status: provider.status, + message: provider.message, + } + : null, + ); + }) + : Effect.void, + ), + ), + ); + return { + published, + readiness: published + ? { + snapshot: nextSnapshot, + launchIdentity: previousIdentity, + indexRevision, + probeFailed: true, + } + : null, + publishedIdentity: published ? previousIdentity : null, + }; + } + // No accepted snapshot exists for previousIdentity; publish the failure + // snapshot directly without attaching previousIdentity's live state and + // align watcher identities so previousIdentity updates cannot land on it. + const failedIdentity = runtimeIdentityFor( + provider, + probedLaunchIdentity ?? failedTargetLaunchIdentity, + ); + const published = yield* Effect.uninterruptible( + tryPublishSnapshot( + provider, + provider.auth.status === "unauthenticated" + ? markAuthConfirmationCleared + : undefined, + ).pipe( + Effect.tap((didPublish) => + didPublish + ? Effect.gen(function* () { + if (provider.auth.status === "unauthenticated") { + // Adopting failedIdentity with no retained runtime clears + // saved confirmation so refreshes do not flash authenticated. + yield* recordAcceptedAuthRejection(failedIdentity, provider.auth); + } + if (failedIdentity !== null && failedIdentity !== previousIdentity) { + yield* clearLiveState({ + preserveRuntimeIdentity: failedIdentity, + }); + } + yield* Ref.set(expectedRuntimeIdentity, failedIdentity); + }) + : Effect.void, + ), + ), + ); + return { + published, + readiness: published + ? { + snapshot: provider, + launchIdentity: failedIdentity, + indexRevision, + probeFailed: true, + } + : null, + publishedIdentity: null, + }; + } + const existingFallback = fallback ? yield* Ref.get(activeFallback) : null; + const fallbackMessage = + fallback && !fromCache + ? fallbackTargetVersion !== null && + provider.version !== null && + fallbackTargetVersion !== provider.version + ? `Could not install ${effectiveConfig.agentId} ${fallbackTargetVersion}; using installed ${provider.version}. Will retry on the next refresh.` + : "Could not install the latest agent update; using the previously installed version. Will retry on the next refresh." + : existingFallback?.message; + const effectiveMessage = fallback + ? (fallbackMessage ?? provider.message) + : provider.message; + const providerToPublish = + fallback && effectiveMessage !== undefined + ? { ...provider, message: effectiveMessage } + : provider; + const runtimeChanged = + previousIdentity !== null && + resolvedIdentity !== null && + previousIdentity !== resolvedIdentity; + const { provider: nextSnapshotRaw, appliedLiveConfiguration } = + yield* withLiveRuntimeState(providerToPublish, { + sessionRuntimeIdentity: resolvedIdentity, + requireMatchingRuntimeIdentity: runtimeChanged, + useLearnedModels: !runtimeChanged, + persistLearnedModels: false, + }); + const preserveUnauthenticated = providerToPublish.auth.status === "unauthenticated"; + const nextSnapshot = preserveUnauthenticated + ? { + ...nextSnapshotRaw, + status: providerToPublish.status, + ...(providerToPublish.message !== undefined + ? { message: providerToPublish.message } + : {}), + } + : fallback && effectiveMessage !== undefined + ? { ...nextSnapshotRaw, message: effectiveMessage } + : nextSnapshotRaw; + const published = yield* Effect.uninterruptible( + tryPublishSnapshot( + nextSnapshot, + providerToPublish.installed && nextSnapshot.auth.status === "unauthenticated" + ? markAuthConfirmationCleared + : undefined, + ).pipe( + Effect.tap((didPublish) => + didPublish + ? Effect.gen(function* () { + if (!providerToPublish.installed) { + yield* Ref.set(activeFallback, null); + yield* Ref.set(failedUpgradeTarget, null); + yield* Ref.set(lastSuccessfulRuntime, null); + yield* Ref.set(latestAcceptedAuth, null); + if (previousIdentity !== null || current.entry !== null) { + yield* clearLiveState(); + yield* invalidateEnrichmentCache; + } + yield* Ref.set(expectedRuntimeIdentity, null); + } else { + const previousLastSuccessful = yield* Ref.get(lastSuccessfulRuntime); + if (nextSnapshot.auth.status === "unauthenticated") { + yield* recordAcceptedAuthRejection( + resolvedIdentity ?? + runtimeIdentityFor(providerToPublish, probedLaunchIdentity), + nextSnapshot.auth, + ); + } + if (!probeFailed) { + yield* Ref.set(failedUpgradeTarget, null); + } + if (fallback && !fromCache) { + const now = yield* Clock.currentTimeMillis; + const keepFailedAt = + existingFallback !== null && + existingFallback.targetLaunchIdentity === + fallbackTargetLaunchIdentity && + now >= existingFallback.failedAtMs && + now - existingFallback.failedAtMs < FALLBACK_RETRY_BACKOFF_MS; + yield* Ref.set(activeFallback, { + targetLaunchIdentity: fallbackTargetLaunchIdentity, + targetVersion: fallbackTargetVersion, + targetIndexRevision: fallbackTargetIndexRevision, + fallbackVersion: providerToPublish.version, + fallbackLaunchIdentity: launchIdentity, + failedAtMs: keepFailedAt ? existingFallback.failedAtMs : now, + message: + fallbackMessage ?? + existingFallback?.message ?? + "Using the previously installed version.", + }); + } else if (!fallback && !probeFailed) { + yield* Ref.set(activeFallback, null); + } + if (runtimeChanged) { + yield* clearLiveState({ + preserveRuntimeIdentity: resolvedIdentity, + }); + const retiredAtRevision = + (fallback ? fallbackTargetIndexRevision : indexRevision) ?? + (yield* currentCatalogIndexRevision); + yield* Ref.update(retiredRuntimeIdentities, (retired) => { + const next = new Map(retired); + // Retire only a runtime that actually succeeded; a + // never-installed target replaced during cold fallback + // stays eligible to reconcile. + if (previousLastSuccessful?.identity === previousIdentity) { + next.set(previousIdentity, retiredAtRevision); + } + next.delete(resolvedIdentity); + return next; + }); + yield* learnedModelOptions.setVersion(providerToPublish.version); + if (appliedLiveConfiguration !== undefined) { + const reported = + acpRegistryCurrentModelOptions(appliedLiveConfiguration); + if (reported !== undefined) { + yield* learnedModelOptions.learn( + reported.modelId, + reported.options, + "live", + ); + } + } + yield* Ref.set(expectedRuntimeIdentity, resolvedIdentity); + } else { + yield* learnedModelOptions.setVersion(providerToPublish.version); + if (appliedLiveConfiguration !== undefined) { + const reported = + acpRegistryCurrentModelOptions(appliedLiveConfiguration); + if (reported !== undefined) { + yield* learnedModelOptions.learn( + reported.modelId, + reported.options, + "live", + ); + } + } + if (resolvedIdentity !== null) { + yield* Ref.set(activeRuntimeIdentity, resolvedIdentity); + yield* Ref.update(retiredRuntimeIdentities, (retired) => { + if (!retired.has(resolvedIdentity)) return retired; + const next = new Map(retired); + next.delete(resolvedIdentity); + return next; + }); + } + yield* Ref.set(expectedRuntimeIdentity, resolvedIdentity); + } + if (!probeFailed && resolvedIdentity !== null) { + const { message: _fallbackMsg, ...cleanProvider } = nextSnapshotRaw; + const storedProvider = fallback ? cleanProvider : nextSnapshotRaw; + yield* Ref.set(lastSuccessfulRuntime, { + identity: resolvedIdentity, + provider: { + ...storedProvider, + auth: stripConfirmedAuth(storedProvider.auth), + }, + }); + yield* Ref.set(latestAcceptedAuth, { + identity: resolvedIdentity, + auth: stripConfirmedAuth(nextSnapshot.auth), + }); + } + } + }) + : Effect.void, + ), + ), + ); + return { + published, + readiness: published + ? { + snapshot: providerToPublish, + launchIdentity, + indexRevision, + ...(fallback + ? { + fallback: true, + fallbackTargetIndexRevision, + } + : {}), + ...(probeFailed ? { probeFailed: true } : {}), + } + : null, + publishedIdentity: published ? resolvedIdentity : null, + }; + }), ); - const enrichment = enrichProviderCached(snapshot, publishEnriched); - const publishEnrichment = ( - Option.isSome(runtimeCoordinator) + const runProbeAndPublish = (target: CheckedAcpRegistryReadiness) => { + const targetIdentity = target.snapshot.installed + ? runtimeIdentityFor(target.snapshot, target.launchIdentity) + : null; + const enrichment = enrichProviderCached(target, publishEnriched); + const probeEffect = Option.isSome(runtimeCoordinator) ? runtimeCoordinator.value.runBackgroundProbe( effectiveConfig.source === "local" ? `local:${instanceId}` : effectiveConfig.agentId, enrichment, ) - : enrichment.pipe(Effect.asSome) - ).pipe( - Effect.flatMap( - Option.match({ - onNone: () => Effect.void, - onSome: publishEnriched, - }), - ), - ); - if (Option.isNone(runtimeCoordinator)) return publishEnrichment; - - const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands( - instanceId, - ({ slashCommands, skills }) => - liveSnapshotSemaphore.withPermit( - getSnapshot.pipe( - Effect.flatMap((current) => - publishSnapshot({ - ...current, - slashCommands, - skills, + : enrichment.pipe(Effect.asSome); + let drainedPending: string | null = null; + return Ref.update(probeReconcileState, (state) => ({ + ...state, + inFlight: targetIdentity, + })).pipe( + Effect.andThen(probeEffect), + Effect.flatMap( + Option.match({ + onNone: () => + Effect.succeed<{ + readonly published: boolean; + readonly readiness: CheckedAcpRegistryReadiness | null; + readonly publishedIdentity: string | null; + }>({ published: false, readiness: null, publishedIdentity: null }), + onSome: publishEnriched, + }), + ), + Effect.ensuring( + Ref.modify(probeReconcileState, (state) => + state.inFlight === targetIdentity + ? ([state.pending, { inFlight: null, pending: null }] as const) + : ([null, state] as const), + ).pipe( + Effect.tap((pending) => + Effect.sync(() => { + drainedPending = pending; }), ), + Effect.asVoid, ), ), - ); - const publishLiveConfiguration = runtimeCoordinator.value.watchLiveConfiguration( - instanceId, - (configuration) => - liveSnapshotSemaphore.withPermit( - getSnapshot.pipe( - Effect.flatMap((current) => applyLiveConfiguration(current, configuration)), - Effect.tap(() => - Clock.currentTimeMillis.pipe( - Effect.flatMap((now) => - Ref.update(enrichmentCache, (cache) => - updateAcpRegistryEnrichmentCache({ - cache, - configuration, - customModels: effectiveConfig.customModels, - now, - }), - ), - ), + Effect.tap(({ publishedIdentity }) => + drainedPending !== null && drainedPending !== publishedIdentity + ? maybeReconcileUnmatchedRuntime(drainedPending) + : Effect.void, + ), + Effect.map(({ published, readiness }) => ({ published, readiness })), + ); + }; + const runWithLiveWatchers = (enrichment: Effect.Effect) => { + if (Option.isNone(runtimeCoordinator)) return enrichment; + + const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands( + instanceId, + ({ slashCommands, skills }, meta) => + liveSnapshotSemaphore + .withPermit( + Effect.gen(function* () { + const gate = yield* checkLiveUpdate(meta); + if (!gate.accepted) return gate.reconcileIdentity; + const current = yield* getSnapshot; + if (!current.installed) return undefined; + const published = yield* tryPublishSnapshot({ + ...current, + slashCommands, + skills, + }); + if (published && !gate.runtimeTransitioning) { + const activeId = yield* Ref.get(activeRuntimeIdentity); + if (activeId !== null) { + const { message: _transientMsg, ...currentClean } = current; + yield* Ref.update(lastSuccessfulRuntime, (prev) => + prev !== null && prev.identity === activeId + ? { + identity: prev.identity, + provider: { ...prev.provider, slashCommands, skills }, + } + : prev === null && current.auth.status !== "unauthenticated" + ? { + identity: activeId, + provider: { + ...currentClean, + auth: stripConfirmedAuth(currentClean.auth), + status: current.enabled + ? ("ready" as const) + : ("disabled" as const), + slashCommands, + skills, + }, + } + : prev, + ); + } + } + return undefined; + }), + ) + .pipe(Effect.flatMap(maybeReconcileUnmatchedRuntime)), + ); + const publishLiveConfiguration = runtimeCoordinator.value.watchLiveConfiguration( + instanceId, + (configuration, meta) => + liveSnapshotSemaphore + .withPermit( + Effect.gen(function* () { + const gate = yield* checkLiveUpdate(meta); + if (!gate.accepted) return gate.reconcileIdentity; + const current = yield* getSnapshot; + if (!current.installed) return undefined; + const baseApplied = applyAcpRegistryLiveConfiguration( + current, + configuration, + effectiveConfig.customModels, + ); + const applied = gate.runtimeTransitioning + ? baseApplied + : withAcpRegistryLearnedModelOptions( + baseApplied, + yield* learnedModelOptions.get, + ); + const activeId = yield* Ref.get(activeRuntimeIdentity); + const fallbackState = yield* Ref.get(activeFallback); + const failedUpgrade = yield* Ref.get(failedUpgradeTarget); + const effectiveIdentity = meta.runtimeIdentity ?? activeId ?? gate.expected; + const preserveUnauthenticated = current.auth.status === "unauthenticated"; + const preserveFallbackMessage = + !preserveUnauthenticated && + fallbackState !== null && + fallbackState.fallbackLaunchIdentity !== null && + effectiveIdentity === fallbackState.fallbackLaunchIdentity; + const preserveUpgradeFailure = + !preserveUnauthenticated && + !preserveFallbackMessage && + failedUpgrade !== null && + activeId !== null && + failedUpgrade.targetLaunchIdentity !== activeId; + const next = preserveUnauthenticated + ? { + ...applied, + status: applied.enabled ? current.status : applied.status, + ...(current.message !== undefined ? { message: current.message } : {}), + } + : preserveFallbackMessage + ? { ...applied, message: fallbackState.message } + : preserveUpgradeFailure + ? { + ...applied, + status: applied.enabled ? failedUpgrade.status : applied.status, + ...(failedUpgrade.message !== undefined + ? { message: failedUpgrade.message } + : {}), + } + : applied; + const published = yield* tryPublishSnapshot(next); + if (!published) return undefined; + if (!gate.runtimeTransitioning) { + yield* learnedModelOptions.setVersion(current.version); + const reported = acpRegistryCurrentModelOptions(configuration); + if (reported !== undefined) { + yield* learnedModelOptions.learn( + reported.modelId, + reported.options, + "live", + ); + } + } + if (!gate.runtimeTransitioning && activeId !== null) { + const { message: _transientMsg, ...appliedClean } = applied; + const isUnauthenticated = current.auth.status === "unauthenticated"; + yield* Ref.update(lastSuccessfulRuntime, (prev) => + prev !== null && prev.identity === activeId + ? { + identity: prev.identity, + provider: isUnauthenticated + ? { ...appliedClean, auth: prev.provider.auth } + : { ...appliedClean, auth: stripConfirmedAuth(appliedClean.auth) }, + } + : prev === null && !isUnauthenticated + ? { + identity: activeId, + provider: { + ...appliedClean, + auth: stripConfirmedAuth(appliedClean.auth), + status: current.enabled + ? ("ready" as const) + : ("disabled" as const), + }, + } + : prev, + ); + } + const snapshotChanged = !Equal.equals(next, current); + const now = yield* Clock.currentTimeMillis; + yield* Ref.update(enrichmentCache, (cache) => + cache.entry === null && !snapshotChanged + ? cache + : updateAcpRegistryEnrichmentCache({ + cache, + configuration, + customModels: effectiveConfig.customModels, + now, + runtimeIdentity: meta.runtimeIdentity ?? gate.expected, + }), + ); + return undefined; + }), + ) + .pipe(Effect.flatMap(maybeReconcileUnmatchedRuntime)), + ); + const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction( + instanceId, + (action) => + liveSnapshotSemaphore.withPermit( + getSnapshot.pipe( + Effect.flatMap((current) => + current.installed + ? tryPublishSnapshot( + applyAcpRegistryUrlAuthAction(current, Option.fromNullishOr(action)), + ).pipe(Effect.asVoid) + : Effect.void, ), ), - Effect.flatMap(publishSnapshot), + ), + ); + return Effect.all( + [enrichment, publishLiveCommands, publishLiveConfiguration, publishUrlAuthAction], + { + concurrency: "unbounded", + discard: true, + }, + ); + }; + const retireActiveRuntimeIfNeeded = () => + liveSnapshotSemaphore.withPermit( + Effect.all({ + active: Ref.get(activeRuntimeIdentity), + cache: Ref.get(enrichmentCache), + }).pipe( + Effect.flatMap(({ active, cache }) => + active === null && cache.entry === null + ? Effect.void + : tryPublishSnapshot(snapshot).pipe( + Effect.tap((published) => + published + ? clearLiveState().pipe( + Effect.andThen(invalidateEnrichmentCache), + Effect.andThen(Ref.set(expectedRuntimeIdentity, null)), + ) + : Effect.void, + ), + Effect.asVoid, + ), ), ), - ); - const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction( - instanceId, - (action) => - liveSnapshotSemaphore.withPermit( - getSnapshot.pipe( - Effect.flatMap((current) => - publishSnapshot( - applyAcpRegistryUrlAuthAction(current, Option.fromNullishOr(action)), - ), - ), + ); + const publishUninstalled = ( + rechecked: CheckedAcpRegistryReadiness, + shouldClearLiveState: boolean, + ) => + liveSnapshotSemaphore.withPermit( + tryPublishSnapshot( + Equal.equals(readinessSignature(rechecked), readinessSignature(initialReadiness)) + ? snapshot + : rechecked.snapshot, + ).pipe( + Effect.tap((published) => + published && shouldClearLiveState + ? clearLiveState().pipe( + Effect.andThen(invalidateEnrichmentCache), + Effect.andThen(Ref.set(expectedRuntimeIdentity, null)), + ) + : Effect.void, ), ), - ); - return Effect.all( - [publishEnrichment, publishLiveCommands, publishLiveConfiguration, publishUrlAuthAction], - { - concurrency: "unbounded", - discard: true, - }, - ); + ); + if (!snapshot.installed) { + yield* retireActiveRuntimeIfNeeded(); + if (!tracksRegistryIndex) return; + const revision = yield* refreshRegistryIndex(); + if (revision <= (yield* Ref.get(lastSeenIndexRevision))) return; + if ( + initialReadiness.indexRevision !== null && + revision <= initialReadiness.indexRevision + ) { + yield* acknowledgeRevision(revision); + return; + } + const rechecked = yield* inspectReadiness({ applySessionLiveState: false }); + if (!rechecked.snapshot.installed) { + const published = yield* publishUninstalled(rechecked, false); + if ( + published && + (rechecked.indexRevision === null || rechecked.indexRevision >= revision) + ) { + yield* acknowledgeRevision(rechecked.indexRevision ?? revision); + } + return; + } + const nextIdentity = runtimeIdentityFor(rechecked.snapshot, rechecked.launchIdentity); + const publishedRechecked = yield* liveSnapshotSemaphore.withPermit( + tryPublishSnapshot(rechecked.snapshot).pipe( + Effect.tap((published) => + published + ? clearLiveState( + nextIdentity === null ? undefined : { preserveRuntimeIdentity: nextIdentity }, + ).pipe(Effect.andThen(Ref.set(expectedRuntimeIdentity, nextIdentity))) + : Effect.void, + ), + ), + ); + if (!publishedRechecked) return; + yield* runWithLiveWatchers( + runProbeAndPublish(rechecked).pipe( + Effect.tap(({ published, readiness }) => + published && + readiness !== null && + !readiness.fallback && + !readiness.probeFailed && + (readiness.indexRevision === null || readiness.indexRevision >= revision) + ? acknowledgeRevision(readiness.indexRevision ?? revision) + : Effect.void, + ), + Effect.asVoid, + ), + ); + return; + } + const publishEnrichment = Effect.gen(function* () { + // Probe or restore cached models before awaiting the network so startup and refreshes stay fast. + const initialProbe = yield* runProbeAndPublish(initialReadiness); + if (!tracksRegistryIndex) return; + const revision = yield* refreshRegistryIndex(); + if (revision <= (yield* Ref.get(lastSeenIndexRevision))) return; + const publishedReadiness = + initialProbe.published && initialProbe.readiness !== null + ? initialProbe.readiness + : initialReadiness; + const fallbackTargetRevision = + publishedReadiness.fallbackTargetIndexRevision ?? initialReadiness.indexRevision; + if ( + initialProbe.published && + publishedReadiness.fallback && + fallbackTargetRevision !== null && + fallbackTargetRevision >= revision + ) { + const fallbackState = yield* Ref.get(activeFallback); + const now = yield* Clock.currentTimeMillis; + if ( + fallbackState === null || + (now >= fallbackState.failedAtMs && + now - fallbackState.failedAtMs < FALLBACK_RETRY_BACKOFF_MS) + ) { + return; + } + } + if ( + initialProbe.published && + publishedReadiness.probeFailed && + publishedReadiness.indexRevision !== null && + publishedReadiness.indexRevision >= revision + ) { + return; + } + if ( + initialProbe.published && + !publishedReadiness.fallback && + !publishedReadiness.probeFailed && + publishedReadiness.indexRevision !== null && + publishedReadiness.indexRevision >= revision + ) { + yield* acknowledgeRevision(publishedReadiness.indexRevision); + return; + } + const rechecked = yield* inspectReadiness(); + if (!rechecked.snapshot.installed) { + const published = yield* publishUninstalled(rechecked, true); + if ( + published && + (rechecked.indexRevision === null || rechecked.indexRevision >= revision) + ) { + yield* acknowledgeRevision(rechecked.indexRevision ?? revision); + } + return; + } + const activeFallbackState = yield* Ref.get(activeFallback); + const now = yield* Clock.currentTimeMillis; + if ( + activeFallbackState !== null && + now >= activeFallbackState.failedAtMs && + now - activeFallbackState.failedAtMs < FALLBACK_RETRY_BACKOFF_MS && + rechecked.launchIdentity !== null && + rechecked.launchIdentity === activeFallbackState.targetLaunchIdentity + ) { + // Unrelated agents or non-launch metadata changed while the failed target itself is + // unchanged; stay in backoff without re-probing while keeping displayed metadata fresh. + yield* liveSnapshotSemaphore.withPermit( + Effect.gen(function* () { + const liveFallback = yield* Ref.get(activeFallback); + if ( + liveFallback === null || + liveFallback.targetLaunchIdentity !== activeFallbackState.targetLaunchIdentity + ) { + return; + } + yield* Ref.set(activeFallback, { + ...liveFallback, + targetIndexRevision: rechecked.indexRevision ?? revision, + }); + const currentSnapshot = yield* getSnapshot; + if (!currentSnapshot.installed) return; + const withMetadata = applyRegistryReadinessMetadata( + currentSnapshot, + rechecked.snapshot, + ); + if (!Equal.equals(withMetadata, currentSnapshot)) { + yield* tryPublishSnapshot(withMetadata); + } + }), + ); + return; + } + if ( + !Equal.equals( + installedRegistrySignature(rechecked), + installedRegistrySignature(publishedReadiness), + ) + ) { + const recheckedProbe = yield* runProbeAndPublish(rechecked); + if ( + recheckedProbe.published && + recheckedProbe.readiness !== null && + !recheckedProbe.readiness.fallback && + !recheckedProbe.readiness.probeFailed && + (recheckedProbe.readiness.indexRevision === null || + recheckedProbe.readiness.indexRevision >= revision) + ) { + yield* acknowledgeRevision(recheckedProbe.readiness.indexRevision ?? revision); + } + return; + } + if ( + initialProbe.published && + !publishedReadiness.fallback && + !publishedReadiness.probeFailed && + (rechecked.indexRevision === null || rechecked.indexRevision >= revision) + ) { + yield* acknowledgeRevision(rechecked.indexRevision ?? revision); + } + }).pipe(Effect.withSpan("AcpRegistryDriver.publishEnrichment")); + yield* runWithLiveWatchers(publishEnrichment); }), }).pipe( Effect.mapError( @@ -1003,6 +2657,7 @@ export const AcpRegistryDriver: ProviderDriver( effect: Effect.Effect< @@ -1028,27 +2683,20 @@ export const AcpRegistryDriver: ProviderDriver - confirmedAuthentication - .set(authenticated) - .pipe( - Effect.andThen(authenticated ? Effect.void : clearLiveState), - Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)), - Effect.andThen(snapshot.refresh), - Effect.asVoid, - ), + liveSnapshotSemaphore + .withPermit( + setConfirmedAuth(authenticated).pipe( + Effect.andThen(authenticated ? Ref.set(latestAcceptedAuth, null) : clearLiveState()), + Effect.andThen(invalidateEnrichmentCache), + ), + ) + .pipe(Effect.andThen(snapshot.refresh), Effect.asVoid), }).pipe( Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), @@ -1057,9 +2705,14 @@ export const AcpRegistryDriver: ProviderDriver confirmedAuthentication.set(false)), Effect.tap(() => liveSnapshotSemaphore.withPermit( - invalidateEnrichmentCache.pipe( + setConfirmedAuth(false).pipe( + Effect.andThen(Ref.set(latestAcceptedAuth, null)), + Effect.andThen(invalidateEnrichmentCache), Effect.andThen( Option.isSome(runtimeCoordinator) ? Effect.all( diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index ddce17eb3b0a8..40f4456514852 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -396,15 +396,26 @@ export interface AcpRegistryConfigurationProbeInput { readonly settings: AcpRegistrySettings; readonly cwd: string; readonly environment: NodeJS.ProcessEnv; + readonly onResolved?: (resolved: AcpRegistryConfigurationProbeResolved) => Effect.Effect; readonly modelDiscovery?: AcpRegistryModelDiscovery; } type AcpRegistryManagementInput = AcpRegistryConfigurationProbeInput; +export interface AcpRegistryConfigurationProbeResolved { + readonly agent?: AcpRegistrySupport.AcpRegistryAgent; + readonly distribution: AcpRegistrySupport.ResolvedAcpRegistryAgent["distribution"]; + readonly launchIdentity?: string; + readonly indexRevision?: number; + readonly fallback?: boolean; + readonly failedTarget?: AcpRegistrySupport.AcpRegistryFailedTarget; +} + export interface AcpRegistryConfigurationProbeResult { readonly probe: AcpRegistryProbeResult; readonly slashCommands: ReadonlyArray; readonly skills: ReadonlyArray; + readonly resolved?: AcpRegistryConfigurationProbeResolved; } export type AcpRegistryConfigurationProbe = ( @@ -523,182 +534,197 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo const random = yield* SecureRandom.SecureRandom; const pty = yield* Effect.serviceOption(PtyAdapter.PtyAdapter); - const openSession = Effect.gen(function* () { - // Resolution may install packages; bound it by the probe deadline. + return yield* Effect.gen(function* () { + // Binary downloads and package installs carry their own bounded timeouts inside AcpRegistryCatalog; + // apply the probe timeout only to spawning and probing the resolved agent. const resolved = yield* catalog .resolve(input.settings, input.cwd, input.environment) .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError)); - const spawn = yield* isolateDeepSeekProbeHistory( - input.settings.commandPath, - resolved.spawn, - ).pipe( - Effect.mapError( - (cause) => - new AcpRegistryOperationError({ - reason: "probe_failed", - message: "Could not prepare temporary history for the DeepSeek Harness probe.", - cause, - }), - ), - ); - const authMethodsRef = yield* Ref.make>([]); - const authActionRef = yield* Ref.make(undefined); - const runtimeCoordinator = yield* Effect.serviceOption( - AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, - ); - const runtimeContext = yield* Layer.build( - AcpSessionRuntime.layer({ - spawn, - cwd: input.cwd, - clientCapabilities: { - auth: { terminal: Option.isSome(pty) }, - elicitation: { url: {} }, - fs: { readTextFile: false, writeTextFile: false }, - terminal: false, - }, - clientInfo: { name: "t3-code-provider-test", version: "0.0.0" }, - authenticateOnAuthRequired: false, - onInitialized: (initializeResult) => - Ref.set( - authMethodsRef, - normalizeAcpRegistryAuthMethods(initializeResult.authMethods, { - command: resolved.spawn.command, - args: resolved.spawn.args, + const resolvedMetadata: AcpRegistryConfigurationProbeResolved = { + ...(resolved.agent === undefined ? {} : { agent: resolved.agent }), + distribution: resolved.distribution, + ...(resolved.launchIdentity === undefined + ? {} + : { launchIdentity: resolved.launchIdentity }), + ...(resolved.indexRevision === undefined ? {} : { indexRevision: resolved.indexRevision }), + ...(resolved.fallback ? { fallback: true } : {}), + ...(resolved.failedTarget === undefined ? {} : { failedTarget: resolved.failedTarget }), + }; + if (input.onResolved !== undefined) { + yield* input.onResolved(resolvedMetadata); + } + const session = yield* Effect.gen(function* () { + const spawn = yield* isolateDeepSeekProbeHistory( + input.settings.commandPath, + resolved.spawn, + ).pipe( + Effect.mapError( + (cause) => + new AcpRegistryOperationError({ + reason: "probe_failed", + message: "Could not prepare temporary history for the DeepSeek Harness probe.", + cause, }), - ), - ...(input.settings.authMethodId ? { authMethodId: input.settings.authMethodId } : {}), - }).pipe( - Layer.provide( - Layer.mergeAll( - Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), - Layer.succeed(SecureRandom.SecureRandom, random), + ), + ); + const authMethodsRef = yield* Ref.make>([]); + const authActionRef = yield* Ref.make(undefined); + const runtimeCoordinator = yield* Effect.serviceOption( + AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, + ); + const runtimeContext = yield* Layer.build( + AcpSessionRuntime.layer({ + spawn, + cwd: input.cwd, + clientCapabilities: { + auth: { terminal: Option.isSome(pty) }, + elicitation: { url: {} }, + fs: { readTextFile: false, writeTextFile: false }, + terminal: false, + }, + clientInfo: { name: "t3-code-provider-test", version: "0.0.0" }, + authenticateOnAuthRequired: false, + onInitialized: (initializeResult) => + Ref.set( + authMethodsRef, + normalizeAcpRegistryAuthMethods(initializeResult.authMethods, { + command: resolved.spawn.command, + args: resolved.spawn.args, + }), + ), + ...(input.settings.authMethodId ? { authMethodId: input.settings.authMethodId } : {}), + }).pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), + Layer.succeed(SecureRandom.SecureRandom, random), + ), ), ), - ), - ); - const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( - Effect.provide(runtimeContext), - ); - const commandsRef = yield* Ref.make( - emptyAcpRegistryAvailableCommands(), - ); - const commandsAdvertised = yield* Deferred.make(); - const configOptionsRef = yield* Ref.make< - ReadonlyArray | undefined - >(undefined); - const modelsAdvertised = yield* Deferred.make(); - yield* runtime.handleElicitation((request) => - Effect.gen(function* () { - if ( - request.mode !== "url" || - !("url" in request) || - !("elicitationId" in request) || - typeof request.url !== "string" || - typeof request.elicitationId !== "string" - ) { - return { action: "decline" } as const; + ); + const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( + Effect.provide(runtimeContext), + ); + const commandsRef = yield* Ref.make( + emptyAcpRegistryAvailableCommands(), + ); + const commandsAdvertised = yield* Deferred.make(); + const configOptionsRef = yield* Ref.make< + ReadonlyArray | undefined + >(undefined); + const modelsAdvertised = yield* Deferred.make(); + yield* runtime.handleElicitation((request) => + Effect.gen(function* () { + if ( + request.mode !== "url" || + !("url" in request) || + !("elicitationId" in request) || + typeof request.url !== "string" || + typeof request.elicitationId !== "string" + ) { + return { action: "decline" } as const; + } + const url = normalizeAcpRegistryWebUrl(request.url); + const elicitationId = boundedOpaqueValue(request.elicitationId, MAX_ID_LENGTH); + if (url === undefined || elicitationId === undefined) { + return { action: "decline" } as const; + } + const action: AcpRegistryUrlAuthAction = { + elicitationId, + url, + message: boundedText(request.message, MAX_DESCRIPTION_LENGTH), + }; + yield* Ref.set(authActionRef, action); + const accepted = yield* Option.match(runtimeCoordinator, { + onNone: () => Effect.succeed(false), + onSome: (coordinator) => + coordinator.requestUrlAuthentication(input.instanceId, action), + }); + return accepted ? ({ action: "accept" } as const) : ({ action: "decline" } as const); + }), + ); + yield* runtime.handleSessionUpdate((notification) => { + const update = notification.update; + if (update.sessionUpdate === "available_commands_update") { + return Ref.set( + commandsRef, + normalizeAcpRegistryCommands(update.availableCommands), + ).pipe(Effect.andThen(Deferred.succeed(commandsAdvertised, undefined)), Effect.asVoid); } - const url = normalizeAcpRegistryWebUrl(request.url); - const elicitationId = boundedOpaqueValue(request.elicitationId, MAX_ID_LENGTH); - if (url === undefined || elicitationId === undefined) { - return { action: "decline" } as const; + if (update.sessionUpdate === "config_option_update") { + const hasAdvertisedModels = acpRegistryAdvertisesModelCatalog(update.configOptions); + return Ref.set(configOptionsRef, update.configOptions).pipe( + Effect.andThen( + hasAdvertisedModels + ? Deferred.succeed(modelsAdvertised, undefined).pipe(Effect.asVoid) + : Effect.void, + ), + ); } - const action: AcpRegistryUrlAuthAction = { - elicitationId, - url, - message: boundedText(request.message, MAX_DESCRIPTION_LENGTH), - }; - yield* Ref.set(authActionRef, action); - const accepted = yield* Option.match(runtimeCoordinator, { - onNone: () => Effect.succeed(false), - onSome: (coordinator) => coordinator.requestUrlAuthentication(input.instanceId, action), - }); - return accepted ? ({ action: "accept" } as const) : ({ action: "decline" } as const); - }), - ); - yield* runtime.handleSessionUpdate((notification) => { - const update = notification.update; - if (update.sessionUpdate === "available_commands_update") { - return Ref.set(commandsRef, normalizeAcpRegistryCommands(update.availableCommands)).pipe( - Effect.andThen(Deferred.succeed(commandsAdvertised, undefined)), - Effect.asVoid, + return Effect.void; + }); + const startResult = yield* Effect.result(runtime.start()); + if (Result.isFailure(startResult)) { + return yield* acpRegistryProbeFailure( + startResult.failure, + yield* Ref.get(authMethodsRef), + yield* Ref.get(authActionRef), ); } - if (update.sessionUpdate === "config_option_update") { - const hasAdvertisedModels = acpRegistryAdvertisesModelCatalog(update.configOptions); - return Ref.set(configOptionsRef, update.configOptions).pipe( - Effect.andThen( - hasAdvertisedModels - ? Deferred.succeed(modelsAdvertised, undefined).pipe(Effect.asVoid) - : Effect.void, + const started = startResult.success; + // Agents that persist sessions (OpenCode) would otherwise keep one empty session per probe. + // The runtime only sends session/delete when the agent advertises it. + yield* Effect.addFinalizer(() => + runtime + .deleteSession(started.sessionId) + .pipe(Effect.timeoutOption(PROBE_SESSION_DELETE_TIMEOUT), Effect.ignore), + ); + const hasInitialModels = acpRegistryAdvertisesModelCatalog( + started.sessionSetupResult.configOptions, + started.sessionSetupResult.models, + ); + + yield* Effect.all( + [ + hasInitialModels + ? Effect.void + : Deferred.await(modelsAdvertised).pipe( + Effect.timeoutOption(MODEL_ADVERTISEMENT_GRACE), + ), + Deferred.await(commandsAdvertised).pipe( + Effect.timeoutOption(COMMAND_ADVERTISEMENT_GRACE), ), - ); - } - return Effect.void; - }); - const startResult = yield* Effect.result(runtime.start()); - if (Result.isFailure(startResult)) { - return yield* acpRegistryProbeFailure( - startResult.failure, - yield* Ref.get(authMethodsRef), - yield* Ref.get(authActionRef), + ], + { concurrency: "unbounded" }, ); - } - const started = startResult.success; - // Agents that persist sessions (OpenCode) would otherwise keep one empty session per probe. - // The runtime only sends session/delete when the agent advertises it. - yield* Effect.addFinalizer(() => - runtime - .deleteSession(started.sessionId) - .pipe(Effect.timeoutOption(PROBE_SESSION_DELETE_TIMEOUT), Effect.ignore), - ); - const hasInitialModels = acpRegistryAdvertisesModelCatalog( - started.sessionSetupResult.configOptions, - started.sessionSetupResult.models, - ); - yield* Effect.all( - [ - hasInitialModels - ? Effect.void - : Deferred.await(modelsAdvertised).pipe( - Effect.timeoutOption(MODEL_ADVERTISEMENT_GRACE), - ), - Deferred.await(commandsAdvertised).pipe( - Effect.timeoutOption(COMMAND_ADVERTISEMENT_GRACE), - ), - ], - { concurrency: "unbounded" }, - ); + // config_option_update replaces the full option set, so an empty notice is authoritative. + const liveConfiguration = normalizeAcpRegistryLiveConfiguration( + (yield* Ref.get(configOptionsRef)) ?? (yield* runtime.getConfigOptions), + (yield* runtime.getModeState) ?? parseSessionModeState(started.sessionSetupResult), + started.sessionSetupResult.models, + ); - // config_option_update replaces the full option set, so an empty notice is authoritative. - const liveConfiguration = normalizeAcpRegistryLiveConfiguration( - (yield* Ref.get(configOptionsRef)) ?? (yield* runtime.getConfigOptions), - (yield* runtime.getModeState) ?? parseSessionModeState(started.sessionSetupResult), - started.sessionSetupResult.models, + return { + resolved, + resolvedMetadata, + started, + commands: yield* Ref.get(commandsRef), + liveConfiguration, + runtime, + }; + }).pipe( + Effect.timeoutOrElse({ + duration: probeTimeoutMs, + orElse: () => + Effect.fail( + new AcpRegistryOperationError({ + reason: "probe_failed", + message: `The ACP agent did not create a test session within ${probeTimeoutMs / 1_000} seconds. Agent startup may be slow; this check retries on the next provider refresh.`, + }), + ), + }), ); - - return { - resolved, - started, - commands: yield* Ref.get(commandsRef), - liveConfiguration, - runtime, - }; - }).pipe( - Effect.timeoutOrElse({ - duration: probeTimeoutMs, - orElse: () => - Effect.fail( - new AcpRegistryOperationError({ - reason: "probe_failed", - message: `The ACP agent did not resolve and create a test session within ${probeTimeoutMs / 1_000} seconds. Package installation or agent startup may be slow; this check retries on the next provider refresh.`, - }), - ), - }), - ); - return yield* Effect.gen(function* () { - const session = yield* openSession; const result: AcpRegistryConfigurationProbeResult = { probe: acpRegistryProbeResult( input.instanceId, @@ -712,6 +738,7 @@ export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeCo ), slashCommands: session.commands.slashCommands, skills: session.commands.skills, + resolved: session.resolvedMetadata, }; // Runs in the probe session before it is deleted, outside the setup deadline. if (input.modelDiscovery !== undefined) { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index d4d8b0b54505b..0fc8f92c7e425 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -473,11 +473,13 @@ export interface AcpAdapterV2Flavor { readonly ignoreSessionUpdate?: (notification: EffectAcpSchema.SessionNotification) => boolean; readonly onAvailableCommandsUpdate?: ( commands: ReadonlyArray, + runtime?: AcpSessionRuntime.AcpSessionRuntime["Service"], ) => Effect.Effect; readonly onSessionConfigurationUpdate?: ( configOptions: ReadonlyArray, modeState: AcpSessionModeState | undefined, modelState: EffectAcpSchema.SessionModelState | null | undefined, + runtime?: AcpSessionRuntime.AcpSessionRuntime["Service"], ) => Effect.Effect; readonly onUrlElicitation?: (input: { readonly elicitationId: string; @@ -7284,7 +7286,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); return updated; }); - yield* flavor.onAvailableCommandsUpdate?.(advertisedCommands) ?? Effect.void; + yield* ( + flavor.onAvailableCommandsUpdate?.(advertisedCommands, runtime) ?? Effect.void + ); } if ( notification.update.sessionUpdate === "config_option_update" || @@ -7295,6 +7299,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* runtime.getConfigOptions, yield* runtime.getModeState, (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models, + runtime, ) ?? Effect.void ); } @@ -7431,6 +7436,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* targetRuntime.getConfigOptions, yield* targetRuntime.getModeState, result.sessionSetupResult.models, + targetRuntime, ) ?? Effect.void ); }); @@ -8576,6 +8582,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* runtime.getConfigOptions, yield* runtime.getModeState, (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models, + runtime, ) ?? Effect.void ); }); diff --git a/packages/provider-core/src/server/managedProvider.test.ts b/packages/provider-core/src/server/managedProvider.test.ts index 0eccada27c508..b661c96ed7794 100644 --- a/packages/provider-core/src/server/managedProvider.test.ts +++ b/packages/provider-core/src/server/managedProvider.test.ts @@ -668,7 +668,7 @@ describe("makeManagedServerProvider", () => { it.effect("ignores stale enrichment callbacks after a newer refresh advances generation", () => Effect.scoped( Effect.gen(function* () { - const publishCallbacks: Array<(snapshot: ServerProvider) => Effect.Effect> = []; + const publishCallbacks: Array<(snapshot: ServerProvider) => Effect.Effect> = []; const refreshCount = yield* Ref.make(0); const firstCallbackReady = yield* Deferred.make(); const secondCallbackReady = yield* Deferred.make(); @@ -686,9 +686,9 @@ describe("makeManagedServerProvider", () => { : Effect.succeed(refreshedSnapshotSecond), ), ), - enrichSnapshot: ({ publishSnapshot }) => + enrichSnapshot: ({ tryPublishSnapshot }) => Effect.gen(function* () { - publishCallbacks.push(publishSnapshot); + publishCallbacks.push(tryPublishSnapshot); if (publishCallbacks.length === 1) { yield* Deferred.succeed(firstCallbackReady, undefined).pipe(Effect.ignore); } else if (publishCallbacks.length === 2) { @@ -710,8 +710,9 @@ describe("makeManagedServerProvider", () => { yield* provider.refresh; yield* Deferred.await(secondCallbackReady); - yield* publishCallbacks[0]!(enrichedSnapshot); - yield* publishCallbacks[1]!(enrichedSnapshotSecond); + assert.strictEqual(yield* publishCallbacks[0]!(enrichedSnapshot), false); + assert.strictEqual(yield* publishCallbacks[1]!(enrichedSnapshotSecond), true); + assert.strictEqual(yield* publishCallbacks[1]!(enrichedSnapshotSecond), true); const updates = Array.from(yield* Fiber.join(updatesFiber)); const latest = yield* provider.getSnapshot; diff --git a/packages/provider-core/src/server/managedProvider.ts b/packages/provider-core/src/server/managedProvider.ts index 2762930b5e1e9..d50b62da1f0aa 100644 --- a/packages/provider-core/src/server/managedProvider.ts +++ b/packages/provider-core/src/server/managedProvider.ts @@ -69,7 +69,12 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( readonly snapshot: ServerProvider; readonly getSnapshot: Effect.Effect; readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect; + readonly tryPublishSnapshot: ( + snapshot: ServerProvider, + onAccepted?: () => void, + ) => Effect.Effect; }) => Effect.Effect; + readonly reconcileCheckedSnapshot?: (probed: ServerProvider) => ServerProvider; readonly refreshInterval?: Duration.Input; readonly refreshOnInterval?: boolean | ((snapshot: ServerProvider) => boolean); readonly checkProviderOnSettingsChange?: (previous: Settings, next: Settings) => boolean; @@ -101,30 +106,37 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( const publishEnrichedSnapshot = Effect.fn("publishEnrichedSnapshot")(function* ( generation: number, nextSnapshot: ServerProvider, - ) { - const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => { + onAccepted?: () => void, + ): Effect.fn.Return { + const outcome = yield* Ref.modify(snapshotStateRef, (state) => { + let applied = true; + let snapshot: ServerProvider | null = null; + let nextState = state; if (state.enrichmentGeneration !== generation) { - return [null, state] as const; - } - // Enrichment must not revert usage updates newer than its input snapshot. - const merged = withUsageLimits( - state.usageAuthLabel === undefined - ? nextSnapshot - : { - ...nextSnapshot, - auth: { ...nextSnapshot.auth, label: state.usageAuthLabel ?? undefined }, - }, - state.snapshot.usageLimits, - ); - if (Equal.equals(state.snapshot, merged)) { - return [null, state] as const; + applied = false; + } else { + onAccepted?.(); + // Enrichment must not revert usage updates newer than its input snapshot. + const merged = withUsageLimits( + state.usageAuthLabel === undefined + ? nextSnapshot + : { + ...nextSnapshot, + auth: { ...nextSnapshot.auth, label: state.usageAuthLabel ?? undefined }, + }, + state.snapshot.usageLimits, + ); + if (!Equal.equals(state.snapshot, merged)) { + snapshot = merged; + nextState = { ...state, snapshot: merged }; + } } - return [merged, { ...state, snapshot: merged }] as const; + return [{ applied, snapshot }, nextState] as const; }); - if (snapshotToPublish === null) { - return; + if (outcome.snapshot !== null) { + yield* PubSub.publish(changesPubSub, outcome.snapshot); } - yield* PubSub.publish(changesPubSub, snapshotToPublish); + return outcome.applied; }); const restartSnapshotEnrichment = Effect.fn("restartSnapshotEnrichment")(function* ( @@ -146,7 +158,10 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( settings, snapshot, getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)), - publishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot), + publishSnapshot: (nextSnapshot) => + publishEnrichedSnapshot(generation, nextSnapshot).pipe(Effect.asVoid), + tryPublishSnapshot: (nextSnapshot, onAccepted) => + publishEnrichedSnapshot(generation, nextSnapshot, onAccepted), }) .pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(scope)); @@ -208,38 +223,41 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( const generation = input.enrichSnapshot ? state.enrichmentGeneration + 1 : state.enrichmentGeneration; + const checkedSnapshot = input.reconcileCheckedSnapshot + ? input.reconcileCheckedSnapshot(probedSnapshot) + : probedSnapshot; // Failed reads retain limits only for the same account and original workspace. const previous = state.snapshot.auth; const differs = (a: string | undefined, b: string | undefined) => a !== undefined && b !== undefined && a !== b; const switchedAccount = - differs(probedSnapshot.auth.email?.toLowerCase(), previous.email?.toLowerCase()) || - (probedSnapshot.auth.workspaceId !== undefined && - probedSnapshot.auth.workspaceId !== previous.workspaceId); + differs(checkedSnapshot.auth.email?.toLowerCase(), previous.email?.toLowerCase()) || + (checkedSnapshot.auth.workspaceId !== undefined && + checkedSnapshot.auth.workspaceId !== previous.workspaceId); const usageLimits = switchedAccount - ? probedSnapshot.usageLimits - : probedSnapshot.usageLimits === undefined && + ? checkedSnapshot.usageLimits + : checkedSnapshot.usageLimits === undefined && state.snapshot.usageLimits !== usageBeforeProbe ? state.snapshot.usageLimits : resolveUsageLimitsAfterProbe({ published: state.snapshot.usageLimits, - probed: probedSnapshot.usageLimits, + probed: checkedSnapshot.usageLimits, }); const workspaceId = - usageLimits === probedSnapshot.usageLimits ? undefined : state.snapshot.auth.workspaceId; + usageLimits === checkedSnapshot.usageLimits ? undefined : state.snapshot.auth.workspaceId; const usageAuthLabel = !switchedAccount && usageLimits?.checkedAt === state.snapshot.usageLimits?.checkedAt ? state.usageAuthLabel : undefined; const labeledProbe = usageAuthLabel === undefined - ? probedSnapshot + ? checkedSnapshot : { - ...probedSnapshot, - auth: { ...probedSnapshot.auth, label: usageAuthLabel ?? undefined }, + ...checkedSnapshot, + auth: { ...checkedSnapshot.auth, label: usageAuthLabel ?? undefined }, }; const snapshot = withUsageLimits( - workspaceId && !probedSnapshot.auth.workspaceId + workspaceId && !checkedSnapshot.auth.workspaceId ? { ...labeledProbe, auth: { ...labeledProbe.auth, workspaceId } } : labeledProbe, usageLimits,