Files
PaperClipAI/server/src/services/native-runtime/runtime-mode.ts
T
DottaandPaperclip 734c265339 Default new Pi agents to Paperclip Runner (#17142)
## Thinking Path

> - Paperclip manages AI agents and their work.
> - Users choose a harness during agent setup.
> - Claude, Codex, and OpenCode already receive their qualified Runner
default.
> - Pi has a qualified native integration but new Pi agents still use
the direct adapter.
> - This change gives new Pi agents the native default on supported
targets.
> - Saved agents keep their runner and compatible settings. Legacy
remains available in Advanced.

## Linked Issues or Issue Description

Refs #17120, #14921, #14922, #14923, #14924, and #14956. Related generic
default work: #15422. This PR is the separate Pi follow-up to the merged
OpenCode change.

**Current behavior**

Choosing Pi for a new agent saves the direct Pi adapter. The native Pi
integration remains behind the generic experimental flag.

**Proposed behavior**

Default new Pi agents to ACPX Pi on macOS ARM64/x64 and GNU/Linux x64
with supported glibc. Keep unsupported targets and explicit Legacy
selections on the direct adapter. Require an explicit provider/model
before test or hire. Permit model-free inactive setup drafts.

**Reason and benefit**

Users choose Pi once and receive its qualified runner. Saved agents
retain their identity and settings. Conversions reject unsupported
legacy thinking and launch settings instead of dropping them.

## What Changed

- Add Pi to the shared platform/default contract and server creation
selection.
- Admit native Pi without the generic experimental flag.
- Preserve provider models, credentials, workspace settings, exact
thinking, and saved native policies.
- Add Pi runner controls, branding, setup resume, onboarding, built-in
configuration, and import handling.
- Add managed Pi OpenRouter routing and matching native provider API-key
accounts. Keep subscription and custom gateway exclusions. Clear
alternate credentials and reject custom Pi provider overrides.
- Keep Pi draft models empty instead of applying Claude's default model.
- Verify setup against the pinned Pi runtime. For native Pi on the
official OpenRouter route, reverify the API key live without requiring a
global Legacy Pi CLI.
- Match Pi’s bounded controller close window to its native snapshot
cleanup and lifetime verification, preserving explicit caller deadlines
and the mandatory drain/suspension proof.
- Bind Pi sidecars to the package that owns the pinned native assets,
including source and vendored server layouts. Other providers retain
their existing package authority.
- Keep protocol-owned finish/block tools out of the ACPX forwarded
catalog. The trusted bridge installs these tools itself; the complete
Rust authorization catalog and terminal receipt ledger remain intact.
This fixes actual Pi session startup and applies to other ACPX
consumers.
- Advance Copilot’s shared-source attestation to v58 because it pins the
shared files touched by Pi. Preserve immutable v57 bytes and historical
decoding; Pi’s own release identity is unchanged.
- Add regression coverage and update the paired maps and developer
documentation.

## Verification

- Passed: full repository typecheck and full production build on final
head 656d304783, including the generated attestation repair.
- Passed: focused shared/server/UI suites covering default selection,
platform fallback, conversion preservation, inactive drafts, managed
account compatibility, credential isolation, OpenRouter routing/model
IDs, exact thinking controls, and saved-account selection. Relevant
batches include 375 server/conversion tests, 267 account/routing tests,
and 110 UI setup/account tests.
- Passed: 179 attestation, historical-profile, qualified-profile, and
native-execution contract tests after CI identified stale Copilot source
hashes. The identity generator check passes; the only delta after the
passing Pi browser run is this Copilot attestation/history repair.
- Passed: 145 managed-account tests, including actual service
preparation and API-key adoption/rejection for native Pi without the
Legacy CLI; 6 pinned-installation probe tests.
- Red then green: an actual task failed session.open because its
54-operation catalog included the bridge-owned terminal tools. The
regression with those tools failed before the filter; all 399 Rust
library tests pass after it. The full product retry exposed an
additional package-authority mismatch. Four authority tests failed
before that repair; 11 authority checks and 14 installation/asset checks
pass afterward. Direct real Pi session initialization with the corrected
package root and catalog succeeds. No model prompt was sent by that
diagnostic.
- Red then green: real Pi posted Hello from Pi but its controller closed
before native cleanup could finish. The cleanup-budget test failed with
the old default and passes with the bounded Pi window. All 46 selected
suspension, drain, and package-authority tests pass after building their
native fixture.
- Passed: token gates, paired map checks, Rust formatting, and git diff
--check.
- Passed real browser acceptance on macOS ARM64, generic native runner
flag disabled, source a433748a12 (Pi code unchanged afterward): the UI
selects Paperclip Runner by default, retains Pi and the selected
model/account, and verifies the pinned runtime plus live OpenRouter key.
A fresh UI-created task, assigned to the UI-created native Pi agent,
posted exactly `Hello from Pi` and reached Done without retry or
restart. The native run and workspace finalization succeeded; the
response and Done persisted after Reload.
- Evidence: 8 preserved browser attempts, including the final passing
18-step journey with all screenshots. Prior failures remain recorded.
The earlier failed checkpoint run recovered on server restart; that
recovery is separate from the fresh final task’s clean success.
- Preserved browser failures: missing account control/inherited Claude
draft model; incompatible managed-account/model-prefix handling; generic
npm probe for Pi; Legacy CLI hello check; duplicate terminal tools and
wrong provider-package authority at actual native session.open; a real
Hello from Pi comment followed by premature checkpoint cleanup timeout.
Each failure has retained screenshots/logs and a corresponding focused
repair. The fresh final task proves these repairs end to end.
- The exact Runner Vitest shard was also run locally after the
attestation fix: the stale-hash failure is gone; 1,833 tests passed, 10
skipped, and two Codex retained-control settlement scenarios failed with
`native_cleanup_maintenance_unproven` during terminal ACK/suspension
replay. Both scenarios passed in an isolated rerun (2/2), and the same
19-test file passed in the preceding Linux CI run. The precise
full-shard timing cause is not established. These Codex scenarios are
outside the changed Pi paths; the original local failures are retained;
no complete local Runner-shard pass is claimed. The corresponding Runner
shard now passes on the final head in hosted Linux CI. All 60 final-head
check runs are now terminal and clean (55 successful, 1 neutral, 4
skipped), and the legacy Snyk status is successful.
- Local full repository tests were attempted but not completed:
provisioning briefly confused a workspace symlink, then a later run was
stopped before browser-driven repairs. No full local-suite pass is
claimed. Final-head hosted CI is green and fresh Greptile review is 5/5
with all review threads resolved; earlier jobs canceled by runner
shutdown are not counted as a pass.

## Risks

- Pi cleanup has a finite 45-second default window, accounting for the
native 30-second snapshot cleanup and 5-second lifetime fence. Other
providers and explicit caller deadlines retain their prior behavior.
- Pi requires explicit operator setup with `paperclipai runtime setup
pi` on the execution host. This PR does not add automatic downloads.
- Linux ARM64, Windows, musl, and unqualified targets retain Legacy.
- Legacy thinking levels minimal, medium, and xhigh cannot be translated
exactly. Native max thinking, warm lifecycle, or restricted permissions
cannot be dropped during a return to Legacy.
- Copilot’s bound profile advances to v58 with exact current launch
admission; v57 remains decodable for recovery. No historical identity is
rewritten.
- Existing agents and immutable run descriptors are not migrated. Cloud
Pi availability is unchanged.

## Model Used

OpenAI GPT-6 through Codex with reasoning, code editing, command
execution, and browser use. The exact serving model ID and
context-window size are not exposed in this session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-21 17:10:00 -05:00

568 lines
19 KiB
TypeScript

import {
NATIVE_STATUS_ARBITER_POLICY_VERSION,
type NativeAuthoritativeIssueStatus,
type NativeStatusDecision,
} from "./status-arbiter.js";
import {
PaperclipRunnerProviderProfileError,
resolvePaperclipRunnerProviderProfile,
type PaperclipRunnerProviderProfile,
} from "./provider-profile.js";
/**
* Public compatibility resolver version. This value is persisted by the
* original heartbeat selection seam and must remain stable for existing runs
* and downstream importers.
*/
export const NATIVE_RUNTIME_RESOLVER_VERSION = "paperclip-runner-v1" as const;
/** Resolver version for the richer native runtime profile used by runnerd. */
export const NATIVE_RUNTIME_PROFILE_RESOLVER_VERSION = "phase6-v1" as const;
export type HeartbeatRuntimeResolution =
| {
kind: "legacy";
resolverVersion: typeof NATIVE_RUNTIME_RESOLVER_VERSION;
reason: "direct_adapter" | "persisted_legacy_selection";
}
| {
kind: "native";
resolverVersion: typeof NATIVE_RUNTIME_RESOLVER_VERSION;
reason: "explicit_paperclip_runner" | "persisted_native_selection";
provider: PaperclipRunnerProviderProfile["provider"];
};
export type NativeRuntimeResolution =
| {
kind: "legacy";
resolverVersion: typeof NATIVE_RUNTIME_PROFILE_RESOLVER_VERSION;
reason: string;
authorityDecision?: NativeStatusDecision;
}
| {
kind: "native";
resolverVersion: typeof NATIVE_RUNTIME_PROFILE_RESOLVER_VERSION;
reason: "eligible_opt_in";
profile: {
mode: "native";
backend:
| "codex_app_server"
| "opencode_server"
| "claude_managed_agents_api"
| "aws_agentcore_harness_api"
| "acpx_runtime"
| "openai_dot_mcp"
| "grok_bot_mcp"
| "muse_external";
protocolVersion: 1;
};
authorityDecision: NativeStatusDecision;
};
/**
* Runner ingress follows the resolved runtime decision, not a second instance
* flag. Persisted native runs therefore keep their transport during recovery
* after the rollout flag is disabled, while legacy runs never gain ingress.
*/
export function isRunnerIngressAuthorized(
resolution: NativeRuntimeResolution,
): boolean {
return resolution.kind === "native";
}
export class NativeRunnerSelectionError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "NativeRunnerSelectionError";
}
}
export class NativeRuntimeEligibilityError extends NativeRunnerSelectionError {
constructor(
code: string,
reason?: string,
) {
super(code, reason ?? `Native runner profile is ineligible: ${code}`);
this.name = "NativeRuntimeEligibilityError";
}
}
function ineligible(
code: string,
reason: string,
): NativeRuntimeEligibilityError {
return new NativeRuntimeEligibilityError(
code,
reason,
);
}
export function resolveNativeRuntimeMode(input: {
enabled: boolean;
museEnabled?: boolean;
dotEnabled?: boolean;
grokEnabled?: boolean;
runtimeConfig: unknown;
adapterConfig?: unknown;
agent: { id?: string; status: string; adapterType: string | null };
issue: { id: string; workMode: string; executionWorkspaceId?: string | null } | null;
target: { kind?: string } | null | undefined;
workspaceId: string | null;
}): NativeRuntimeResolution {
const runnerAdapterSelected = input.agent.adapterType === "paperclip_runner";
// Fresh direct-adapter runs never enter the native control plane, even if an
// obsolete runtimeConfig.nativeRunner value is still present. Persisted
// native runs are handled by resolveHeartbeatNativeRuntimeMode above this
// fresh-selection seam so they remain recoverable after rollout changes.
if (!runnerAdapterSelected) {
return {
kind: "legacy",
resolverVersion: NATIVE_RUNTIME_PROFILE_RESOLVER_VERSION,
reason: "direct_adapter",
};
}
let runnerProfile: PaperclipRunnerProviderProfile;
try {
runnerProfile = resolvePaperclipRunnerProviderProfile(input.adapterConfig);
} catch (error) {
if (error instanceof PaperclipRunnerProviderProfileError) {
throw ineligible(error.code, error.message);
}
throw error;
}
// Dot has its own rollout; enabling it does not opt in other Runner providers.
if (runnerProfile.provider === "muse") {
if (!input.enabled) throw ineligible("paperclip_runner_rollout_disabled", "Paperclip Runner is experimental and disabled on this instance.");
if (input.museEnabled !== true) throw ineligible("paperclip_runner_muse_disabled", "Enable Muse personal-agent connections in experimental settings before assigning new work.");
} else if (runnerProfile.provider === "openai_dot") {
if (input.dotEnabled !== true) throw ineligible("paperclip_runner_dot_disabled", "Enable OpenAI Dot and Assistant connections (MCP) in experimental settings before assigning new work.");
} else if (runnerProfile.provider === "grok_bot" && (input.grokEnabled !== true || !input.enabled)) {
throw ineligible("paperclip_runner_grok_disabled", "Enable Grok Bot, Paperclip Runner, and Assistant connections (MCP) before assigning new work.");
} else if (runnerProfile.provider !== "codex" && runnerProfile.provider !== "opencode"
&& !(runnerProfile.provider === "acpx"
&& (["claude", "copilot", "pi"].includes(runnerProfile.acpxAgent ?? "")))
&& !input.enabled) {
throw ineligible(
"paperclip_runner_rollout_disabled",
"Paperclip Runner is experimental and disabled on this instance.",
);
}
if (
input.agent.adapterType !== "paperclip_runner"
|| input.agent.status !== "active" && input.agent.status !== "running"
) {
throw ineligible(
"paperclip_runner_agent_ineligible",
"Paperclip Runner requires an active agent.",
);
}
const allowedWorkModes = ["standard", "planning", "ask"];
if (!input.issue || !allowedWorkModes.includes(input.issue.workMode)) {
throw ineligible(
"paperclip_runner_issue_ineligible",
"Paperclip Runner requires a standard, planning, or ask task.",
);
}
const rollout = resolveNativeMigrationStatus({
facts: { applicationEnabled: true },
priorIssueStatus: "in_progress",
agentId: input.agent.id ?? "00000000-0000-4000-8000-000000000000",
});
if (!rollout.effects.some((effect) => effect.kind === "record_mode_native")) {
throw ineligible(
"paperclip_runner_rollout_policy_rejected",
"Native rollout policy did not select native mode.",
);
}
return {
kind: "native",
resolverVersion: NATIVE_RUNTIME_PROFILE_RESOLVER_VERSION,
reason: "eligible_opt_in",
profile: {
mode: "native",
backend: runnerProfile.backend,
protocolVersion: 1,
},
authorityDecision: rollout,
};
}
/**
* Backward-compatible heartbeat selection API. New runnerd code consumes the
* richer profile from resolveHeartbeatNativeRuntimeMode; this public seam
* keeps the original result shape, reason codes, and resolver version.
*/
export function resolveHeartbeatRuntimeMode(input: {
persisted: {
runtimeMode: string | null;
runtimeModeResolvedAt: Date | null;
};
enabled: boolean;
museEnabled?: boolean;
dotEnabled?: boolean;
grokEnabled?: boolean;
adapterType: string | null;
adapterConfig: unknown;
agentStatus: string;
issue: { workMode: string } | null;
executionTarget: { kind?: string } | null | undefined;
}): HeartbeatRuntimeResolution {
if (input.persisted.runtimeModeResolvedAt) {
if (input.persisted.runtimeMode === "native") {
return {
kind: "native",
resolverVersion: NATIVE_RUNTIME_RESOLVER_VERSION,
reason: "persisted_native_selection",
provider: "codex",
};
}
return {
kind: "legacy",
resolverVersion: NATIVE_RUNTIME_RESOLVER_VERSION,
reason: "persisted_legacy_selection",
};
}
let resolution: NativeRuntimeResolution;
try {
resolution = resolveNativeRuntimeMode({
enabled: input.enabled,
museEnabled: input.museEnabled,
dotEnabled: input.dotEnabled,
grokEnabled: input.grokEnabled,
runtimeConfig: {},
adapterConfig: input.adapterConfig,
agent: {
status: input.agentStatus,
adapterType: input.adapterType,
},
issue: input.issue
? { id: "heartbeat-runtime-selection", workMode: input.issue.workMode }
: null,
target: input.executionTarget,
workspaceId: null,
});
} catch (error) {
if (error instanceof NativeRuntimeEligibilityError) {
throw new NativeRunnerSelectionError(error.code, error.message);
}
throw error;
}
if (resolution.kind === "legacy") {
return {
kind: "legacy",
resolverVersion: NATIVE_RUNTIME_RESOLVER_VERSION,
reason: "direct_adapter",
};
}
return {
kind: "native",
resolverVersion: NATIVE_RUNTIME_RESOLVER_VERSION,
reason: "explicit_paperclip_runner",
provider: resolution.profile.backend === "opencode_server"
? "opencode"
: resolution.profile.backend === "claude_managed_agents_api"
? "claude_managed"
: resolution.profile.backend === "aws_agentcore_harness_api"
? "aws_agentcore"
: resolution.profile.backend === "muse_external" ? "muse"
: resolution.profile.backend === "grok_bot_mcp" ? "grok_bot"
: resolution.profile.backend === "openai_dot_mcp" ? "openai_dot"
: resolution.profile.backend === "acpx_runtime"
? "acpx"
: "codex",
};
}
/**
* Production heartbeat selection seam. A resolved run keeps its persisted
* mode across configuration changes; only a fresh unresolved run consults the
* current global flag and agent profile.
*/
export function resolveHeartbeatNativeRuntimeMode(input: {
persisted: {
runtimeMode: string | null;
runtimeModeReason: string | null;
runtimeModeResolvedAt: Date | null;
driverKind?: string | null;
};
enabled: boolean;
museEnabled?: boolean;
dotEnabled?: boolean;
grokEnabled?: boolean;
runtimeConfig: unknown;
adapterConfig?: unknown;
agent: { id?: string; status: string; adapterType: string | null };
issue: { id: string; workMode: string; executionWorkspaceId?: string | null } | null;
target: { kind?: string } | null | undefined;
workspaceId: string | null;
}): NativeRuntimeResolution {
if (input.persisted.runtimeModeResolvedAt) {
if (input.persisted.runtimeMode === "native") {
if (input.agent.adapterType !== "paperclip_runner") {
throw ineligible(
"paperclip_runner_adapter_binding_mismatch",
"A persisted native run must remain bound to the Paperclip Runner adapter.",
);
}
if (
input.agent.status !== "active" &&
input.agent.status !== "running"
) {
throw ineligible(
"paperclip_runner_agent_ineligible",
"A persisted Paperclip Runner run cannot recover through a non-invokable agent.",
);
}
const driverKind = input.persisted.driverKind;
const backend = driverKind === "opencode_server"
? "opencode_server"
: driverKind === "claude_managed_agents_api"
? "claude_managed_agents_api"
: driverKind === "aws_agentcore_harness_api"
? "aws_agentcore_harness_api"
: driverKind === "muse_external" ? "muse_external"
: driverKind === "grok_bot_mcp" ? "grok_bot_mcp"
: driverKind === "openai_dot_mcp" ? "openai_dot_mcp"
: driverKind === "acpx_runtime"
? "acpx_runtime"
: driverKind === null
|| driverKind === undefined
|| driverKind === "codex"
|| driverKind === "codex_app_server"
? "codex_app_server"
: null;
if (backend === null) {
throw ineligible(
"paperclip_runner_driver_unsupported",
`Persisted Paperclip Runner driver is unsupported: ${driverKind}`,
);
}
return {
kind: "native",
resolverVersion: NATIVE_RUNTIME_PROFILE_RESOLVER_VERSION,
reason: "eligible_opt_in",
profile: {
mode: "native",
backend,
protocolVersion: 1,
},
authorityDecision: resolveNativeMigrationStatus({
facts: input.enabled
? { applicationEnabled: true }
: { killSwitchActiveForNewRuns: true },
priorIssueStatus: "in_progress",
agentId: input.agent.id ?? "00000000-0000-4000-8000-000000000000",
}),
};
}
return {
kind: "legacy",
resolverVersion: NATIVE_RUNTIME_PROFILE_RESOLVER_VERSION,
reason: input.persisted.runtimeModeReason ?? "persisted_legacy_selection",
};
}
return resolveNativeRuntimeMode(input);
}
/** Production read-model facts used by compatibility and mixed-ledger views. */
export function inspectNativeCompatibilityState(input: {
resolution: NativeRuntimeResolution;
nativeRecordCount: number;
decisionCount: number;
issueStatus: string;
statusVersion: number;
persistedEffectKinds: string[];
}) {
const effects = input.persistedEffectKinds.length > 0
? [...input.persistedEffectKinds]
: input.resolution.kind === "legacy"
? ["legacy_existing_behavior"]
: input.nativeRecordCount === 0 && input.statusVersion === 0
? ["initialize_status_version_zero"]
: [];
return {
mode: input.resolution.kind,
native: input.nativeRecordCount > 0,
hasNativeDecisionLineage: input.decisionCount > 0,
issueStatus: input.issueStatus,
statusVersion: input.statusVersion,
statusAction: input.resolution.kind === "legacy" ? "legacy_finalizer" : "preserve",
reasonCode: null,
effects,
} as const;
}
/** Expand-only migration evidence; it never mutates or synthesizes history. */
export function inspectNativeMigrationState(input: {
resolution: NativeRuntimeResolution;
nativeRecordCount: number;
decisionCount: number;
issueStatusBefore: string;
issueStatusAfter: string;
statusVersion: number;
hasPendingReview: boolean;
}) {
const effects = input.resolution.kind === "legacy"
? input.issueStatusBefore === "done"
? ["retain_legacy_mode", "retain_audit_lineage"]
: ["return_native_false"]
: input.nativeRecordCount === 0 && input.hasPendingReview && input.statusVersion > 0
? ["increment_status_version_once", "bind_reviewer"]
: input.nativeRecordCount === 0
? ["expand_schema", "status_version_default_zero"]
: [];
return {
mode: input.resolution.kind,
native: input.nativeRecordCount > 0,
hasSyntheticHistory: input.nativeRecordCount === 0 && input.decisionCount > 0,
statusPreserved: input.issueStatusBefore === input.issueStatusAfter,
statusVersion: input.statusVersion,
statusAction: input.resolution.kind === "legacy" ? "legacy_finalizer"
: input.hasPendingReview ? input.issueStatusAfter : "preserve",
reasonCode: null,
effects,
} as const;
}
export type NativeCompatibilityFacts = {
invalidNativeFinalization?: boolean;
terminalResumeAuthorized?: boolean;
shadowApplicationDisabled?: boolean;
mixedLedger?: boolean;
statusWriterAdvancedVersion?: boolean;
};
export function resolveNativeCompatibilityStatus(input: {
facts: NativeCompatibilityFacts;
priorIssueStatus: NativeAuthoritativeIssueStatus;
agentId: string;
}): NativeStatusDecision {
const preserve = (reasonCode: string, effects: NativeStatusDecision["effects"]): NativeStatusDecision => ({
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "preserve",
toStatus: input.priorIssueStatus,
reasonCode,
unblockDescriptor: null,
effects,
});
if (input.facts.invalidNativeFinalization) {
return preserve("native_finalization_invalid", [{
kind: "record_finalization_error",
cause: "native_finalization_invalid",
nextAction: "Repair the persisted native result.",
agentId: input.agentId,
}]);
}
if (input.facts.terminalResumeAuthorized) {
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "in_progress",
toStatus: "in_progress",
reasonCode: "authorized_resume",
unblockDescriptor: null,
effects: [{
kind: "enqueue_continuation",
continuationKind: "same_agent",
summary: "Resume the terminal issue through the authorized compatibility path.",
idempotencyKey: "native-compatibility:authorized-resume",
agentId: input.agentId,
}],
};
}
if (input.facts.shadowApplicationDisabled) {
return preserve("completion_contract_satisfied", [{ kind: "record_shadow_decision" }]);
}
if (input.facts.mixedLedger) {
return preserve("completion_contract_satisfied", [{ kind: "render_four_layers" }]);
}
if (input.facts.statusWriterAdvancedVersion) {
return preserve("arbitration_conflict_reloaded", [
{ kind: "increment_status_version" },
{ kind: "schedule_reconciliation" },
]);
}
throw new Error("native_compatibility_facts_invalid");
}
export type NativeMigrationFacts = {
shadowMaterialization?: boolean;
classifiedDivergence?: boolean;
applicationEnabled?: boolean;
policyPinned?: boolean;
killSwitchActiveForNewRuns?: boolean;
};
export function resolveNativeMigrationStatus(input: {
facts: NativeMigrationFacts;
priorIssueStatus: NativeAuthoritativeIssueStatus;
agentId: string;
}): NativeStatusDecision {
const preserve = (reasonCode: string, effects: NativeStatusDecision["effects"]): NativeStatusDecision => ({
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "preserve",
toStatus: input.priorIssueStatus,
reasonCode,
unblockDescriptor: null,
effects,
});
if (input.facts.shadowMaterialization) {
return preserve("completion_contract_satisfied", [
{ kind: "materialize_contract" },
{ kind: "record_shadow_decision" },
]);
}
if (input.facts.classifiedDivergence) {
return preserve("completion_evidence_incomplete", [{ kind: "record_mode_labeled_divergence" }]);
}
if (input.facts.killSwitchActiveForNewRuns) {
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "in_progress",
toStatus: "in_progress",
reasonCode: "live_continuation_registered",
unblockDescriptor: null,
effects: [
{
kind: "enqueue_continuation",
continuationKind: "same_agent",
summary: "Finish the already-active run in native mode.",
idempotencyKey: "native-migration:kill-switch-active-run",
agentId: input.agentId,
},
{ kind: "finish_as_native" },
],
};
}
if (input.facts.policyPinned) {
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "done",
toStatus: "done",
reasonCode: "completion_contract_satisfied",
unblockDescriptor: null,
effects: [{ kind: "record_mode_native" }, { kind: "record_policy_version" }],
};
}
if (input.facts.applicationEnabled) {
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "in_progress",
toStatus: "in_progress",
reasonCode: "live_continuation_registered",
unblockDescriptor: null,
effects: [
{
kind: "enqueue_continuation",
continuationKind: "same_agent",
summary: "Continue the allowlisted native run.",
idempotencyKey: "native-migration:application-enabled",
agentId: input.agentId,
},
{ kind: "record_mode_native" },
],
};
}
throw new Error("native_migration_facts_invalid");
}