mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 15:52:36 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - OpenAI Dot connects to Paperclip through a dedicated agent OAuth
grant and a signed MCP Events subscription
(`paperclip.dot.mailbox_updated`).
> - Three compounding bugs broke paired Dot connections: (1) event
subscriptions expire after 24 hours with no renewal instructions and an
unclear "required" UI state that pushed operators to re-pair; (2) the
`/mcp/runner` 401 challenge and omitted-scope OAuth defaults requested
only `paperclip:agent` without `offline_access`, so clients received no
refresh token and broke after 15 minutes while the pairing preview still
promised ongoing access; and (3) expired or unpaired Dot runs failed as
generic `adapter_failed`, triggering an endless 15-minute automatic
recovery retry loop.
> - Operators should not have to re-pair a Dot every day, lose OAuth
access after 15 minutes, or watch failed runs loop every 15 minutes on a
missing or expired connection.
> - This pull request adds 24-hour subscription renewal instructions and
expired-subscription status/guidance, includes `offline_access` in the
Dot OAuth 401 challenge and default scopes with an accurate pairing
preview, and classifies missing or expired Dot connections as
non-retryable `configuration_incomplete` with clear operator
instructions.
> - The benefit is durable Dot OAuth and event-subscription renewal
without needless re-pairing, honest pairing previews, and clean
blocked-task guidance instead of infinite retry loops.
## Linked Issues or Issue Description
**What happened?**
1. `paperclip.dot.mailbox_updated` event subscriptions expire after 24
hours (`lifetime` in `server/src/services/public-mcp/events.ts`), but
neither the Dot setup prompt nor pairing `eventInstructions` told Dot to
resubscribe before `refreshBefore`. After 24 hours, new runs failed with
`"Dot must be paired with a verified event subscription and a completed
event test."` and `DotRunnerConnection` displayed `"Event subscription:
required"`, pushing operators to re-pair needlessly.
2. The `/mcp/runner` 401 `WWW-Authenticate` challenge
(`server/src/routes/public-mcp.ts`) and omitted-scope OAuth defaults
(`server/src/services/public-mcp/oauth.ts`) requested only
`paperclip:agent` instead of `paperclip:agent offline_access`. Clients
following the challenge or omitting `scope` received no refresh token
and failed after 15 minutes even though the pairing preview promised
`"Ongoing until revoked"`.
3. When a Dot binding was unpaired or its event subscription expired,
runs failed with generic `adapter_failed` (before `nativeExecutionInput`
was persisted), so automatic recovery (`issue_recovery_action_restored`
/ `issue_continuation_needed`) kept retrying every 15 minutes
indefinitely.
**Expected behavior**
1. Dot receives explicit instructions to renew
`paperclip.dot.mailbox_updated` before `refreshBefore` and on expiry;
when expired, Paperclip names the expiry and shows `"Event subscription:
expired"` with resubscribe guidance (no new pairing needed).
2. Dot OAuth challenges and default scopes include `offline_access` so
paired clients receive rotating refresh tokens; an explicit agent-only
request without `offline_access` displays an accurate 15-minute
non-renewable access preview.
3. Missing or expired Dot connections fail as non-retryable
`configuration_incomplete` with dedicated operator recovery notices,
moving the task to `blocked` and stopping automatic recovery loops.
**Steps to reproduce**
1. Pair an OpenAI Dot agent and omit `scope` (or follow the
`/mcp/runner` 401 `WWW-Authenticate` challenge); inspect the issued
OAuth tokens (no `refresh_token`) and the pairing preview for an
explicit `paperclip:agent` request.
2. Expire the agent's `mcp_event_subscriptions` row past 24 hours or
revoke the binding, then assign a task to the Dot agent.
3. Observe the run failing as `adapter_failed` and automatic recovery
repeatedly queuing continuation runs every 15 minutes.
**Paperclip version or commit**
Base commit `2d065677959b585065ff3fec8718156a4cf6f41d` on `master`.
## What Changed
- **24-hour event subscription renewal & expired UX**:
- Updated `pair()` `eventInstructions` in
`server/src/modules/external-agents/dot.ts` and `buildDotSetupPrompt` in
`ui/src/lib/dot-setup-prompt.ts` to instruct Dot to renew
`paperclip.dot.mailbox_updated` before `refreshBefore` and whenever
Paperclip reports expiry.
- Added `subscriptionExpired` to `bindingForAgent()`, surfaced an
explicit expired-subscription error in `snapshot()` and the Dot
environment check (`server/src/routes/agents.ts`), added
`subscriptionExpired` to the OpenAPI schema
(`server/src/routes/openapi.ts`), and updated
`ui/src/components/DotRunnerConnection.tsx` to display `"Event
subscription: expired"` with resubscribe guidance without re-pairing.
- **OAuth `offline_access` challenge, default scopes, and honest
preview**:
- Updated the `/mcp/runner` 401 `WWW-Authenticate` challenge
(`server/src/routes/public-mcp.ts`) and Dot `defaultScope` for both
`authorize` and `deviceAuthorize`
(`server/src/services/public-mcp/oauth.ts`) to use
`DOT_RUNNER_MCP_SCOPES` (`paperclip:agent offline_access`).
- Updated `describeDotPairing()`
(`server/src/services/public-mcp/oauth.ts`) to show a 15-minute
non-renewable duration when a client explicitly requests
`paperclip:agent` without `offline_access`.
- **Non-retryable recovery on expired or unpaired Dot**:
- Tagged unavailable Dot binding errors in
`server/src/modules/external-agents/dot.ts` with typed
`DotBindingUnavailableReason` (`dot_subscription_expired` /
`dot_pairing_required`) on `McpOAuthError`, mapped them to
`ConfigurationIncompleteFailure` in
`server/src/services/heartbeat/runtime-selection.ts`, and mapped
`paperclip_runner_dot_config_invalid` / `paperclip_runner_dot_disabled`
to `ConfigurationIncompleteFailure` in
`server/src/services/heartbeat/run-completion.ts`.
- Added `dot_subscription_expired` and `dot_pairing_required` notices in
`server/src/services/recovery/stranded-notice.ts`, added
`configuration_incomplete` to `NON_RETRYABLE_CONTINUATION_ERROR_CODES`,
and extended `CONFIGURATION_INCOMPLETE_ERROR_RE` in
`server/src/services/recovery/service.ts` so pre-existing legacy
`adapter_failed` Dot runs also stop looping immediately.
- Note on file size: `runtime-selection.ts`, `run-completion.ts`,
`recovery/service.ts`, `agents.ts`, and `openapi.ts` already exceeded
1,000 lines on `master`; this PR adds only narrow, owning-module changes
(2 to 31 lines each) without introducing new modules.
- **Tests**:
- Extended `server/src/__tests__/dot-runner.test.ts` with
embedded-Postgres tests covering 24h subscription expiry + resubscribe
recovery without re-pairing, OAuth 401 `offline_access` challenge +
omitted-scope refresh token rotation, and full heartbeat +
`assignedWorkSweep` + recovery classification proof that expired and
unpaired Dot runs fail as non-retryable `configuration_incomplete`
without looping.
- Extended `server/src/__tests__/dot-oauth-onboarding.test.ts` for
omitted-scope device authorization (`offlineAccess: true`) and honest
15-minute pairing preview on explicit agent-only scope.
- Added focused UI regression tests in
`ui/src/components/DotRunnerConnection.test.tsx`.
## Verification
- `pnpm exec vitest run server/src/__tests__/dot-runner.test.ts
server/src/__tests__/dot-oauth-onboarding.test.ts
server/src/__tests__/grok-bot-routine.test.ts
server/src/services/public-mcp/discovery.test.ts`: **4 files, 124 passed
(124)** (`dot-runner`: 59, `dot-oauth-onboarding`: 18,
`grok-bot-routine`: 45, `discovery`: 2).
- `pnpm exec vitest run server/src/__tests__/public-mcp.test.ts
server/src/services/antigravity-swarm.test.ts
server/src/__tests__/disposition-repair.test.ts`: **3 files, 90 passed
(90)**.
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/DotRunnerConnection.test.tsx`: **1 file, 2 passed (2)**.
- `pnpm --filter @paperclipai/ui typecheck` && `pnpm --filter
@paperclipai/server typecheck` (all 7 layers): **PASS**.
- `pnpm check:token-gates`: **All 4 gates CLEAN, cliplab character in
sync**.
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/dot-runner.test.ts
server/src/__tests__/dot-oauth-onboarding.test.ts
ui/src/components/DotRunnerConnection.test.tsx`: **PASS (110 nightly
suites validated, 3 test file(s) checked)**.
- `pnpm verify --base 2d06567795
--explain` selected 2,224/2,927 files because shared server modules
(`oauth.ts`, `run-completion.ts`, `recovery/service.ts`) are modified;
focused affected suites and full UI/server typechecks ran locally, and
sharded PR CI covers the full repository suite.
## Risks
- **Low risk.** No database migrations, no changes to existing OAuth
grants, no changes to the 24-hour subscription security lifetime, and no
changes to Personal MCP, Muse, or Grok Bot scopes or admission gates.
- Existing Dot grants created without `offline_access` retain their
original scopes and will need one reconnect after deploy to obtain
refresh tokens.
- Real ChatGPT/OpenAI Dot client renewal beyond 15 minutes and automatic
idle wake reliability remain subject to OpenAI's external client
behavior (unrelated to Paperclip's webhook delivery path).
## Model Used
- **Provider & Model:** Claude (Anthropic) via Antigravity agent runtime
(exact model snapshot ID and context window size are not exposed in this
environment).
- **Capabilities Used:** Codebase inspection, reasoning,
TypeScript/React editing, shell execution, embedded-Postgres and Vitest
verification, and GitHub CLI PR creation.
## 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
484 lines
17 KiB
TypeScript
484 lines
17 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";
|
|
import { antigravityCandidateTarget } from "./antigravity-release.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 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"
|
|
| "cursor_cloud_api";
|
|
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,
|
|
readonly detailReason?: string,
|
|
) {
|
|
super(code, reason ?? `Native runner profile is ineligible: ${code}`);
|
|
this.name = "NativeRuntimeEligibilityError";
|
|
}
|
|
}
|
|
|
|
function ineligible(
|
|
code: string,
|
|
reason: string,
|
|
detailReason?: string,
|
|
): NativeRuntimeEligibilityError {
|
|
return new NativeRuntimeEligibilityError(
|
|
code,
|
|
reason,
|
|
detailReason,
|
|
);
|
|
}
|
|
|
|
export function resolveNativeRuntimeMode(input: {
|
|
enabled: boolean;
|
|
museEnabled?: boolean;
|
|
dotEnabled?: boolean;
|
|
grokEnabled?: boolean;
|
|
runtimeConfig: unknown;
|
|
adapterConfig?: unknown;
|
|
agent: { id?: string; companyId?: 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, { companyId: input.agent.companyId,
|
|
candidateTarget: antigravityCandidateTarget((input.target?.kind ?? "local") === "remote") });
|
|
} catch (error) {
|
|
if (error instanceof PaperclipRunnerProviderProfileError) {
|
|
throw ineligible(error.code, error.message, error.detailReason);
|
|
}
|
|
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 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 and Paperclip Runner before assigning new work.");
|
|
} else if (runnerProfile.provider !== "codex" && runnerProfile.provider !== "opencode"
|
|
&& !(runnerProfile.provider === "acpx"
|
|
&& (["claude", "copilot", "pi", "antigravity"].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.",
|
|
);
|
|
}
|
|
if (runnerProfile.provider === "cursor_cloud" && (input.target?.kind ?? "local") !== "local") {
|
|
throw ineligible("paperclip_runner_cursor_cloud_local_controller_required", "Cursor Cloud currently requires a local Paperclip controller. Cursor hosts its execution environment.");
|
|
}
|
|
if (!input.issue) {
|
|
throw ineligible(
|
|
"paperclip_runner_task_required",
|
|
"Paperclip Runner requires a task to run. Assign or open a task for this agent.",
|
|
);
|
|
}
|
|
const allowedWorkModes = ["standard", "planning", "ask", "skill_test"];
|
|
if (!allowedWorkModes.includes(input.issue.workMode)) {
|
|
throw ineligible(
|
|
"paperclip_runner_issue_ineligible",
|
|
"Paperclip Runner requires a standard, planning, ask, or skill test 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,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 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; companyId?: 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 === "cursor_cloud_api" ? "cursor_cloud_api"
|
|
: 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");
|
|
}
|