mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 14:20:12 +01:00
## Thinking Path > - Paperclip manages work carried out by agents and people. > - Native finalization converts a runner result into a durable task status and follow-up effects. > - A blocked result can name the person who must decide what happens next. > - The classifier discarded that identity, and the arbiter saved a generic board owner. > - This could replace an explicit user owner saved through the task API and leave the decision outside that person's inbox. > - This pull request resolves human owners against active company membership and preserves them through commit. > - The named person receives the existing blocker card, and the blocked worker does not get another wake. ## Linked Issues or Issue Description **What happened?** Native finalization replaced a named human unblock owner with `board`. It also overwrote an explicit user owner saved through the task API during the turn. **Expected behavior** Keep a valid human unblock owner and route the blocker card to that person's inbox. Use the board when the reference is unknown, inactive, ambiguous, or outside the company. **Steps to reproduce** 1. Create an active company member with a distinct display name. 2. Have a native worker report a human blocker using that name. 3. Finalize the run and read the task's unblock owner and the member's inbox. Related: #21265 covers named agent handoffs and retains board ownership for people. This change covers human member routing and does not add agent handoffs. ## What Changed - Resolve a human owner from an explicit user ID, an API-bound user, or one matching company member by ID, full name, or email. - Preserve the user owner for both blocker scopes and durable dependency waits. - Recheck the accepted result and active membership under the status commit lock, including board fallbacks. Rebuild the assessment on every status retry so a newly saved owner or revoked membership cannot be overwritten by stale evidence. - Enforce `canAssignTasksToHumans` before binding a human owner, including dependency waits that do not emit a `bind_blocker` effect. - Validate the result before retiring automatic completion reviews. Invalid results leave existing reviews pending; valid results retain the normal cleanup path. - Keep human blocker routing out of the agent wake queue. - Add embedded Postgres regressions for finalization, replay, personal attention, invalid owners, late API ownership changes, membership revocation, permission denial, and answer continuation for human-owned blockers. - Make the answer-continuation fixture persist the same result it classifies, so commit-time evidence validation sees realistic saved evidence. Assert the resolved user owner in both blocker scopes. - Let the recovery census clock advance at real-time pace during delivery I/O waits. This handles callbacks and nested timers without jumping to maintenance deadlines. Preserve the existing real-clock timeout and recovery assertions, and name pending queues in failures. - Document human blocker resolution and compatibility. ## Verification - Red-green reproduction: three ownership regressions failed on the original implementation and passed with the fix. - Red-green race reproduction: late API ownership changes and membership revocation failed before the commit recheck and per-retry reassessment fixes. Each finalization invocation now has to commit; a later replay cannot hide an exhausted retry. - Red-green review-retirement reproduction: a new invalid result cancelled a proven automatic review before throwing `native_result_invalid_disposition`. The new invalid/valid regression pair verifies that invalid results preserve the pending review and task decision, while valid completion still retires the card. - Red-green answer-continuation reproduction: both human-owner cases failed with `native_status_race` while saved evidence was empty. Persisting the classified result and asserting `{ userId }` restored all 13 answer-continuation cases, including worker resumption. - Red-green permission reproduction: an agent with `canAssignTasksToHumans: false` could bind a human blocker before the permission check. Direct and dependency cases now refuse finalization without creating a personal blocker card. - On refreshed head `a6d37916546`, `pnpm --filter @paperclipai/server exec node scripts/typecheck-layers.mjs` passed on macOS with Node 24. - On refreshed head `a6d37916546`, from the repository root, `CI=true node node_modules/vitest/vitest.mjs run server/src/services/native-runtime/native-agent-blocker.integration.test.ts server/src/services/native-runtime/status-arbiter.test.ts server/src/services/native-runtime/evidence-classifier.test.ts server/src/__tests__/native-status-reassessment-work.test.ts server/src/__tests__/routable-blocked.test.ts server/src/__tests__/native-status-arbiter-corpus.test.ts server/src/services/native-runtime/native-environment-blocker.integration.test.ts server/src/__tests__/heartbeat-blocked-question-answer.test.ts server/src/__tests__/issue-recovery-live-run-agent-census.test.ts` passed: 292 tests in nine files on macOS with Node 24. - Red-green census reproduction: both post-I/O callbacks and nested timers must settle without jumping to a future maintenance deadline. The nested case timed out under a zero-only clock pump; the shared automatically advancing census clock handles both. - Final CI at `a6d37916546`: [run 44848053016, attempt 2](https://github.com/paperclipai/paperclip/actions/runs/44848053016/attempts/2) completed successfully. Build, Canary Dry Run, policy, every server and workspace test shard, Runner checks, serialized suites, e2e, and verify are green. Greptile review 7 is 5/5 on the same head, Superagent and other security checks pass, and no review threads remain unresolved. A local merge-tree check against master `621c5577cdf` also passed with no conflicts. - Current CI at `a6d37916546`, [run 44848053016](https://github.com/paperclipai/paperclip/actions/runs/44848053016): attempt 1 finished with 13 interrupted nonaggregate jobs, each with an explicit runner shutdown signal in its log. Nine signals occurred within three seconds on separate m6a.xlarge hosts in us-east-1a; Build and Canary also shut down later. Aggregate e2e and verify failed on those dependency results. The underlying termination cause remains unknown. Shared CI settings are unchanged. - The [automatic recovery run](https://github.com/paperclipai/paperclip/actions/runs/44849704877) skipped retry because Build had only the annotation `Process completed with exit code 143.` The classifier reads logs for cancellation annotations, but did not read this job's log. That log explicitly records a runner shutdown at 01:10:49 UTC. The other 12 failed jobs were recognized as runner loss. After verifying all 13 logs, manually requested failed-job attempt 2; it completed successfully without source or configuration changes between attempts. The shared recovery classifier is unchanged; this false negative remains a documented follow-up. - Historical CI at `cf601ba`: all server shards (including the census), Runner checks, typecheck/release registry, serialized suites, e2e, and canary dry run passed. Build received runner shutdown signals on attempts 1–7; aggregate verify failed because Build failed. Attempt 5 diagnostics show shutdown while the job lease was valid. Attempt 7 stopped after server dependency preparation, without a compiler error. The termination cause remains unknown. Three recent PRs completed Build on the same AWS fleet; this is not evidence of a fleet-wide outage. Shared CI settings are unchanged. - Diagnostic comparison at `cf601ba`: the server compiler passed locally on macOS with four checkers, full typechecking, and declaration/JavaScript emission (`node ../scripts/run-tsc.mjs --checkers 4 --extendedDiagnostics` under Node 24). The monitored process group peaked at about 10.5 GiB RSS and finished in 25.8 seconds. This does not establish the cause of the Linux runner shutdowns. - Refreshed the branch onto master `611dc68581c` without conflicts; the PR source diff is unchanged. Greptile review 7 scored head `a6d37916546` 5/5 with no new actionable findings and no unresolved review threads. All applicable CI gates passed on attempt 2. - Full local workspace build at `cf601ba` passed on macOS using Node 24 and the documented single-thread compiler mode: `PAPERCLIP_TYPECHECK_LOW_MEMORY=1 npx --yes --package=node@24 --package=pnpm@9.15.4 pnpm build`. This includes typechecking and artifact emission. The tracked working tree stayed clean. - `pnpm verify --explain` returned exit 2 because this documentation path requires broad CI coverage. Fresh CI will supply that coverage; the full local test suite was not run. - Earlier CI build and canary jobs received runner shutdown signals. The server shard also exposed an answer-continuation fixture that saved an empty result while classifying a named human. That mismatch was reproduced locally, and the fixture now persists the classified result and checks the user owner. Fresh CI is required for this revision. - `git diff --check` and the staged gitleaks scan passed. The diff was also checked for private issue references, identifiers, URLs, and personal data. ## Risks - Name and email matching ignore case. Several matches fall back to the board. Invalid explicit IDs never fall through to another person. - Resolution adds bounded reads only when a native result reports a human blocker. It adds no worker, timer, or idle scan. - No database or result-schema migration is required. Existing board and agent decisions remain readable. Committed historical decisions are not rewritten; new finalizations use current membership. - This changes human routing only. It grants no access and changes no merge, approval, or dependency policy. ## Model Used - OpenAI GPT-6.1 Sol (`gpt-6.1-sol`) through Codex in T3 Code, with xhigh reasoning effort, code editing, shell tools, and test execution. ## 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 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>
454 lines
21 KiB
TypeScript
454 lines
21 KiB
TypeScript
import { and, eq, or } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import { nativeBlockerUserId } from "./native-blocker-owner.js";
|
|
import {
|
|
approvals,
|
|
caseHandoffs,
|
|
agents,
|
|
heartbeatRunEvents,
|
|
issueApprovals,
|
|
issueAttachments,
|
|
issueThreadInteractions,
|
|
issueWorkProducts,
|
|
} from "@paperclipai/db";
|
|
import {
|
|
normalizePrpResultSignals,
|
|
type PrpIgnoredAttentionRequest,
|
|
type PrpNormalizedAttentionRequest,
|
|
type PrpVerificationReasonCode,
|
|
} from "../../vendor/paperclip-runner/index.js";
|
|
|
|
export type NativeEvidenceOutcome = "accepted" | "missing" | "rejected" | "unverifiable";
|
|
|
|
export interface NativeEvidenceRefAssessment {
|
|
ref: string;
|
|
kind: "event" | "work_product" | "approval" | "interaction" | "attachment" | "case_handoff" | "unknown";
|
|
outcome: NativeEvidenceOutcome;
|
|
reasonCode: string;
|
|
durableRecordId: string | null;
|
|
}
|
|
|
|
export type NativeBlockerOwnerKind = "agent" | "user" | "system" | "external" | "board" | "unspecified";
|
|
|
|
export function nativeBlockerOwnerKind(owner: Record<string, unknown>): NativeBlockerOwnerKind {
|
|
if (owner.owner === "board") return "board";
|
|
return ["agent", "user", "system", "external", "board"].includes(String(owner.kind))
|
|
? owner.kind as NativeBlockerOwnerKind : "unspecified";
|
|
}
|
|
|
|
export interface NativeEvidenceAssessment {
|
|
objectiveClaimSatisfied: boolean;
|
|
objectiveSatisfied: boolean;
|
|
allCriteriaSatisfied: boolean;
|
|
verificationPassed: boolean;
|
|
hasFailedVerification: boolean;
|
|
hasBlockingRemainingWork: boolean;
|
|
reportedDisposition: "done" | "blocked" | "needs_review" | "yielded";
|
|
summary: string;
|
|
contractRevisionMatches: boolean;
|
|
criterionAssessments: Array<{
|
|
criterionId: string;
|
|
claimStatus: "satisfied" | "not_satisfied" | "unknown" | null;
|
|
outcome: NativeEvidenceOutcome;
|
|
evidenceRefs: NativeEvidenceRefAssessment[];
|
|
reasonCode: string;
|
|
}>;
|
|
verificationAssessments: Array<{
|
|
commandOrCheck: string;
|
|
claimStatus: "passed" | "failed" | "not_run";
|
|
outcome: NativeEvidenceOutcome;
|
|
evidenceRef: NativeEvidenceRefAssessment | null;
|
|
reasonCode: string;
|
|
reportedReasonCode: PrpVerificationReasonCode | null;
|
|
detail: string | null;
|
|
}>;
|
|
verificationCaveats: Array<{
|
|
commandOrCheck: string;
|
|
reasonCode: PrpVerificationReasonCode | null;
|
|
detail: string | null;
|
|
}>;
|
|
acceptedEvidenceRefs: string[];
|
|
missingRequirements: string[];
|
|
rejectedEvidence: Array<{ ref: string; reasonCode: string }>;
|
|
unverifiableEvidence: Array<{ ref: string; reasonCode: string }>;
|
|
blocker: {
|
|
unblockAction: string;
|
|
boardOwned: boolean;
|
|
ownerKind?: NativeBlockerOwnerKind;
|
|
ownerUserId?: string;
|
|
scope: "current_track" | "task_wide";
|
|
} | null;
|
|
continuation: {
|
|
kind: "same_agent" | "retry" | "delegated_issue" | "response_wake" | "monitor" | "case_handoff";
|
|
summary: string;
|
|
idempotencyKey: string;
|
|
handoffId?: string;
|
|
} | null;
|
|
/** Actionable, blocking requests only. */
|
|
attentionRequests: PrpNormalizedAttentionRequest[];
|
|
ignoredAttentionRequests: PrpIgnoredAttentionRequest[];
|
|
}
|
|
|
|
function record(value: unknown): Record<string, unknown> {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
? value as Record<string, unknown>
|
|
: {};
|
|
}
|
|
|
|
function text(value: unknown): string | null {
|
|
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
|
}
|
|
|
|
function uuidRef(ref: string, prefixes: string[]): string | null {
|
|
for (const prefix of prefixes) {
|
|
if (!ref.startsWith(`${prefix}:`)) continue;
|
|
const value = ref.slice(prefix.length + 1).trim();
|
|
// Model-authored evidence often annotates a durable reference, for example
|
|
// `interaction:<uuid> (request_confirmation, status accepted)`. Extract the
|
|
// canonical UUID only; never pass the descriptive suffix (or arbitrary
|
|
// malformed text) to a Postgres UUID comparison.
|
|
const match = /^([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})(?=$|[^0-9a-f-])/i.exec(value);
|
|
return match?.[1] ?? null;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export function readNativeEventEvidenceOutcome(value: unknown): "accepted" | "rejected" | null {
|
|
const event = record(value);
|
|
if (event.sourceKind !== "control_plane") return null;
|
|
const outcome = text(record(event.payload).evidenceOutcome);
|
|
return outcome === "accepted" || outcome === "rejected" ? outcome : null;
|
|
}
|
|
|
|
async function classifyEvidenceRef(input: {
|
|
db: Db;
|
|
companyId: string;
|
|
issueId: string;
|
|
runId: string;
|
|
ref: string;
|
|
lockSources?: boolean;
|
|
}): Promise<NativeEvidenceRefAssessment> {
|
|
const handoffId = uuidRef(input.ref, ["case-handoff"]);
|
|
if (handoffId) {
|
|
const query = input.db.select({ id: caseHandoffs.id, state: caseHandoffs.state }).from(caseHandoffs).where(and(
|
|
eq(caseHandoffs.id, handoffId), eq(caseHandoffs.companyId, input.companyId), eq(caseHandoffs.issueId, input.issueId),
|
|
eq(caseHandoffs.sourceRunId, input.runId),
|
|
)).limit(1);
|
|
const [row] = await (input.lockSources ? query.for("share", { noWait: true }) : query);
|
|
return { ref: input.ref, kind: "case_handoff", outcome: !row ? "missing" : row.state === "cancelled" ? "rejected" : "accepted",
|
|
reasonCode: !row ? "case_handoff_missing" : row.state === "cancelled" ? "case_handoff_cancelled" : "case_handoff_persisted", durableRecordId: row?.id ?? null };
|
|
}
|
|
const eventMatch = /^event:(\d+)$/.exec(input.ref);
|
|
if (eventMatch) {
|
|
const cursor = Number(eventMatch[1]);
|
|
const query = input.db.select({
|
|
id: heartbeatRunEvents.id,
|
|
eventType: heartbeatRunEvents.eventType,
|
|
payload: heartbeatRunEvents.payload,
|
|
})
|
|
.from(heartbeatRunEvents)
|
|
.where(and(
|
|
eq(heartbeatRunEvents.companyId, input.companyId),
|
|
eq(heartbeatRunEvents.runId, input.runId),
|
|
or(eq(heartbeatRunEvents.seq, cursor), eq(heartbeatRunEvents.sourceSeq, cursor)),
|
|
)).limit(1);
|
|
const [event] = await (input.lockSources ? query.for("share", { noWait: true }) : query);
|
|
if (!event) {
|
|
return { ref: input.ref, kind: "event", outcome: "missing", reasonCode: "durable_run_event_missing", durableRecordId: null };
|
|
}
|
|
const evidenceOutcome = readNativeEventEvidenceOutcome(record(event.payload).prpEvent);
|
|
if (evidenceOutcome === "accepted") {
|
|
return { ref: input.ref, kind: "event", outcome: "accepted", reasonCode: "control_plane_evidence_accepted", durableRecordId: String(event.id) };
|
|
}
|
|
if (evidenceOutcome === "rejected") {
|
|
return { ref: input.ref, kind: "event", outcome: "rejected", reasonCode: "control_plane_evidence_rejected", durableRecordId: String(event.id) };
|
|
}
|
|
return {
|
|
ref: input.ref,
|
|
kind: "event",
|
|
outcome: "unverifiable",
|
|
reasonCode: event.eventType === "run.result.proposed"
|
|
? "model_result_event_is_claim_only"
|
|
: "run_event_has_no_authoritative_evidence_verdict",
|
|
durableRecordId: String(event.id),
|
|
};
|
|
}
|
|
|
|
const workProductId = uuidRef(input.ref, ["work_product", "work-product", "artifact"]);
|
|
if (workProductId) {
|
|
const query = input.db.select({
|
|
id: issueWorkProducts.id,
|
|
status: issueWorkProducts.status,
|
|
reviewState: issueWorkProducts.reviewState,
|
|
}).from(issueWorkProducts).where(and(
|
|
eq(issueWorkProducts.id, workProductId),
|
|
eq(issueWorkProducts.companyId, input.companyId),
|
|
eq(issueWorkProducts.issueId, input.issueId),
|
|
)).limit(1);
|
|
const [row] = await (input.lockSources ? query.for("share", { noWait: true }) : query);
|
|
if (!row) return { ref: input.ref, kind: "work_product", outcome: "missing", reasonCode: "work_product_missing", durableRecordId: null };
|
|
if (
|
|
["failed", "error", "cancelled", "rejected", "changes_requested"].includes(row.status)
|
|
|| ["rejected", "changes_requested"].includes(row.reviewState)
|
|
) {
|
|
return { ref: input.ref, kind: "work_product", outcome: "rejected", reasonCode: "work_product_rejected", durableRecordId: row.id };
|
|
}
|
|
if (
|
|
row.reviewState === "approved"
|
|
|| ["approved", "passed", "succeeded", "completed", "merged", "published"].includes(row.status)
|
|
) {
|
|
return { ref: input.ref, kind: "work_product", outcome: "accepted", reasonCode: "work_product_authoritatively_accepted", durableRecordId: row.id };
|
|
}
|
|
return { ref: input.ref, kind: "work_product", outcome: "unverifiable", reasonCode: "work_product_not_yet_accepted", durableRecordId: row.id };
|
|
}
|
|
|
|
const approvalId = uuidRef(input.ref, ["approval"]);
|
|
if (approvalId) {
|
|
const query = input.db.select({ id: approvals.id, status: approvals.status })
|
|
.from(issueApprovals)
|
|
.innerJoin(approvals, eq(issueApprovals.approvalId, approvals.id))
|
|
.where(and(
|
|
eq(issueApprovals.companyId, input.companyId),
|
|
eq(issueApprovals.issueId, input.issueId),
|
|
eq(approvals.companyId, input.companyId),
|
|
eq(approvals.id, approvalId),
|
|
)).limit(1);
|
|
const [row] = await (input.lockSources ? query.for("share", { noWait: true }) : query);
|
|
if (!row) return { ref: input.ref, kind: "approval", outcome: "missing", reasonCode: "approval_missing", durableRecordId: null };
|
|
if (row.status === "approved") return { ref: input.ref, kind: "approval", outcome: "accepted", reasonCode: "approval_approved", durableRecordId: row.id };
|
|
if (["rejected", "cancelled"].includes(row.status)) return { ref: input.ref, kind: "approval", outcome: "rejected", reasonCode: "approval_rejected", durableRecordId: row.id };
|
|
return { ref: input.ref, kind: "approval", outcome: "missing", reasonCode: "approval_pending", durableRecordId: row.id };
|
|
}
|
|
|
|
const interactionId = uuidRef(input.ref, ["interaction"]);
|
|
if (interactionId) {
|
|
const query = input.db.select({
|
|
id: issueThreadInteractions.id,
|
|
status: issueThreadInteractions.status,
|
|
result: issueThreadInteractions.result,
|
|
}).from(issueThreadInteractions).where(and(
|
|
eq(issueThreadInteractions.id, interactionId),
|
|
eq(issueThreadInteractions.companyId, input.companyId),
|
|
eq(issueThreadInteractions.issueId, input.issueId),
|
|
)).limit(1);
|
|
const [row] = await (input.lockSources ? query.for("share", { noWait: true }) : query);
|
|
if (!row) return { ref: input.ref, kind: "interaction", outcome: "missing", reasonCode: "interaction_missing", durableRecordId: null };
|
|
const outcome = text(record(row.result).outcome);
|
|
if (["accepted", "answered", "resolved"].includes(outcome ?? "") || ["accepted", "answered"].includes(row.status)) {
|
|
return { ref: input.ref, kind: "interaction", outcome: "accepted", reasonCode: "interaction_resolved", durableRecordId: row.id };
|
|
}
|
|
if (["rejected", "expired", "cancelled"].includes(row.status) || ["rejected", "withdrawn", "issue_closed"].includes(outcome ?? "")) {
|
|
return { ref: input.ref, kind: "interaction", outcome: "rejected", reasonCode: "interaction_rejected", durableRecordId: row.id };
|
|
}
|
|
return { ref: input.ref, kind: "interaction", outcome: "missing", reasonCode: "interaction_pending", durableRecordId: row.id };
|
|
}
|
|
|
|
const attachmentId = uuidRef(input.ref, ["attachment"]);
|
|
if (attachmentId) {
|
|
const query = input.db.select({ id: issueAttachments.id }).from(issueAttachments).where(and(
|
|
eq(issueAttachments.id, attachmentId),
|
|
eq(issueAttachments.companyId, input.companyId),
|
|
eq(issueAttachments.issueId, input.issueId),
|
|
)).limit(1);
|
|
const [row] = await (input.lockSources ? query.for("share", { noWait: true }) : query);
|
|
return row
|
|
? { ref: input.ref, kind: "attachment", outcome: "accepted", reasonCode: "attachment_persisted", durableRecordId: row.id }
|
|
: { ref: input.ref, kind: "attachment", outcome: "missing", reasonCode: "attachment_missing", durableRecordId: null };
|
|
}
|
|
|
|
return {
|
|
ref: input.ref,
|
|
kind: "unknown",
|
|
outcome: "unverifiable",
|
|
reasonCode: "unsupported_evidence_reference",
|
|
durableRecordId: null,
|
|
};
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export async function classifyNativeEvidence(input: {
|
|
db: Db;
|
|
companyId: string;
|
|
issueId: string;
|
|
runId: string;
|
|
contract: Record<string, unknown>;
|
|
result: Record<string, unknown>;
|
|
|
|
lockSources?: boolean;
|
|
}): Promise<NativeEvidenceAssessment> {
|
|
const claim = record(input.result.completionClaim);
|
|
const claimedCriteria = Array.isArray(claim.criteria) ? claim.criteria.map(record) : [];
|
|
const contractCriteria = Array.isArray(input.contract.criteria) ? input.contract.criteria.map(record) : [];
|
|
const remaining = Array.isArray(claim.remainingWork) ? claim.remainingWork.map(record) : [];
|
|
const normalizedSignals = normalizePrpResultSignals(input.result);
|
|
const verification = normalizedSignals.verification;
|
|
const reported = input.result.reportedWorkDisposition;
|
|
const blocker = record(input.result.blocker);
|
|
const blockerOwner = record(blocker.owner);
|
|
const ownerUserId = reported === "blocked" && typeof blocker.unblockAction === "string"
|
|
? await nativeBlockerUserId({ ...input, owner: blockerOwner }) : null;
|
|
const continuation = record(input.result.continuation);
|
|
if (!["done", "blocked", "needs_review", "yielded"].includes(String(reported))) {
|
|
throw new Error("native_result_invalid_disposition");
|
|
}
|
|
|
|
const contractRevision = text(input.contract.revision);
|
|
const contractRevisionMatches = contractRevision !== null && text(claim.contractRevision) === contractRevision;
|
|
const cache = new Map<string, Promise<NativeEvidenceRefAssessment>>();
|
|
const resolveRef = (ref: string) => {
|
|
let pending = cache.get(ref);
|
|
if (!pending) {
|
|
pending = classifyEvidenceRef({ ...input, ref });
|
|
cache.set(ref, pending);
|
|
}
|
|
return pending;
|
|
};
|
|
|
|
const criterionAssessments = await Promise.all(contractCriteria.map(async (criterion) => {
|
|
const criterionId = text(criterion.id) ?? "invalid-contract-criterion";
|
|
const claimed = claimedCriteria.find((entry) => text(entry.criterionId) === criterionId) ?? null;
|
|
const claimStatus = claimed && ["satisfied", "not_satisfied", "unknown"].includes(String(claimed.status))
|
|
? claimed.status as "satisfied" | "not_satisfied" | "unknown"
|
|
: null;
|
|
const refs = claimed && Array.isArray(claimed.evidenceRefs)
|
|
? claimed.evidenceRefs.flatMap((value) => text(value) ? [text(value)!] : [])
|
|
: [];
|
|
const evidenceRefs = await Promise.all(refs.map(resolveRef));
|
|
let outcome: NativeEvidenceOutcome;
|
|
let reasonCode: string;
|
|
if (!contractRevisionMatches) {
|
|
outcome = "rejected";
|
|
reasonCode = "contract_revision_stale";
|
|
} else if (!claimed) {
|
|
outcome = "missing";
|
|
reasonCode = "criterion_claim_missing";
|
|
} else if (claimStatus === "not_satisfied") {
|
|
outcome = "rejected";
|
|
reasonCode = "criterion_reported_not_satisfied";
|
|
} else if (claimStatus !== "satisfied") {
|
|
outcome = "unverifiable";
|
|
reasonCode = "criterion_claim_not_satisfied";
|
|
} else if (refs.length === 0) {
|
|
outcome = "missing";
|
|
reasonCode = "criterion_evidence_missing";
|
|
} else if (evidenceRefs.some((entry) => entry.outcome === "rejected")) {
|
|
outcome = "rejected";
|
|
reasonCode = "criterion_evidence_rejected";
|
|
} else if (evidenceRefs.some((entry) => entry.outcome === "unverifiable")) {
|
|
outcome = "unverifiable";
|
|
reasonCode = "criterion_evidence_unverifiable";
|
|
} else if (evidenceRefs.some((entry) => entry.outcome === "missing")) {
|
|
outcome = "missing";
|
|
reasonCode = "criterion_evidence_missing";
|
|
} else {
|
|
outcome = "accepted";
|
|
reasonCode = "criterion_evidence_accepted";
|
|
}
|
|
return { criterionId, claimStatus, outcome, evidenceRefs, reasonCode };
|
|
}));
|
|
|
|
const verificationAssessments = await Promise.all(verification.map(async (entry) => {
|
|
const commandOrCheck = entry.commandOrCheck;
|
|
const claimStatus = entry.status;
|
|
const ref = entry.artifactRef;
|
|
const evidenceRef = ref ? await resolveRef(ref) : null;
|
|
const common = { commandOrCheck, claimStatus, evidenceRef, reportedReasonCode: entry.reasonCode, detail: entry.detail };
|
|
if (claimStatus === "failed") return { ...common, outcome: "rejected" as const, reasonCode: "verification_reported_failed" };
|
|
if (claimStatus === "not_run") return { ...common, outcome: "missing" as const, reasonCode: "verification_not_run" };
|
|
if (!evidenceRef) return { ...common, outcome: "unverifiable" as const, reasonCode: "verification_has_no_durable_reference" };
|
|
return {
|
|
...common,
|
|
outcome: evidenceRef.outcome,
|
|
reasonCode: evidenceRef.outcome === "accepted" ? "verification_evidence_accepted" : evidenceRef.reasonCode,
|
|
};
|
|
}));
|
|
|
|
const allRefs = [...cache.keys()].map((ref) => cache.get(ref)!);
|
|
const resolvedRefs = await Promise.all(allRefs);
|
|
const acceptedEvidenceRefs = resolvedRefs.filter((entry) => entry.outcome === "accepted").map((entry) => entry.ref);
|
|
const missingRequirements = [
|
|
...criterionAssessments.filter((entry) => entry.outcome === "missing").map((entry) => entry.criterionId),
|
|
...verificationAssessments.filter((entry) => entry.outcome === "missing").map((entry) => entry.commandOrCheck),
|
|
];
|
|
const rejectedEvidence = resolvedRefs.filter((entry) => entry.outcome === "rejected").map((entry) => ({ ref: entry.ref, reasonCode: entry.reasonCode }));
|
|
const unverifiableEvidence = resolvedRefs.filter((entry) => entry.outcome === "unverifiable").map((entry) => ({ ref: entry.ref, reasonCode: entry.reasonCode }));
|
|
const allCriteriaSatisfied = contractCriteria.length > 0 && criterionAssessments.every((entry) => entry.outcome === "accepted");
|
|
const verificationPassed = verificationAssessments.length > 0 && verificationAssessments.every((entry) => entry.outcome === "accepted");
|
|
const hasFailedVerification = verificationAssessments.some((entry) => entry.claimStatus === "failed");
|
|
const continuationKind = continuation.kind;
|
|
const actionableAttentionRequests: PrpNormalizedAttentionRequest[] = [];
|
|
const ignoredAttentionRequests = [...normalizedSignals.ignoredAttentionRequests];
|
|
for (const request of normalizedSignals.actionableAttentionRequests) {
|
|
if (request.ownerClass === "agent" && request.targetAgentId) {
|
|
const targetQuery = input.db.select({ id: agents.id }).from(agents).where(and(
|
|
eq(agents.id, request.targetAgentId),
|
|
eq(agents.companyId, input.companyId),
|
|
)).limit(1);
|
|
const targets = await (input.lockSources ? targetQuery.for("share", { noWait: true }) : targetQuery);
|
|
if (targets.length === 0) {
|
|
ignoredAttentionRequests.push({
|
|
sourceIndex: request.sourceIndex,
|
|
sourceKind: request.sourceKind,
|
|
summary: request.summary,
|
|
disposition: "rejected",
|
|
reasonCode: "attention_request_target_agent_unavailable",
|
|
});
|
|
continue;
|
|
}
|
|
}
|
|
actionableAttentionRequests.push(request);
|
|
}
|
|
|
|
return {
|
|
objectiveClaimSatisfied: claim.objectiveSatisfied === true,
|
|
objectiveSatisfied: claim.objectiveSatisfied === true && allCriteriaSatisfied,
|
|
allCriteriaSatisfied,
|
|
verificationPassed,
|
|
hasFailedVerification,
|
|
hasBlockingRemainingWork:
|
|
remaining.some((entry) => entry.blocksCompletion === true)
|
|
|| (reported === "done" && Object.keys(blocker).length > 0),
|
|
reportedDisposition: reported as NativeEvidenceAssessment["reportedDisposition"],
|
|
summary: typeof input.result.summary === "string" ? input.result.summary : "Native run completed.",
|
|
contractRevisionMatches,
|
|
criterionAssessments,
|
|
verificationAssessments,
|
|
verificationCaveats: verificationAssessments
|
|
.filter((entry) => entry.claimStatus === "not_run")
|
|
.map((entry) => ({
|
|
commandOrCheck: entry.commandOrCheck,
|
|
reasonCode: entry.reportedReasonCode,
|
|
detail: entry.detail,
|
|
})),
|
|
acceptedEvidenceRefs,
|
|
missingRequirements,
|
|
rejectedEvidence,
|
|
unverifiableEvidence,
|
|
blocker: reported === "blocked" && typeof blocker.unblockAction === "string"
|
|
? {
|
|
unblockAction: blocker.unblockAction,
|
|
boardOwned: ["board", "user"].includes(String(blockerOwner.kind)) || blockerOwner.owner === "board",
|
|
...(ownerUserId ? { ownerUserId } : {}),
|
|
ownerKind: nativeBlockerOwnerKind(blockerOwner),
|
|
scope: blocker.scope === "task_wide" ? "task_wide" : "current_track",
|
|
}
|
|
: null,
|
|
continuation: reported === "yielded"
|
|
&& ["same_agent", "retry", "delegated_issue", "response_wake", "monitor", "case_handoff"].includes(String(continuationKind))
|
|
&& text(continuation.summary)
|
|
&& text(continuation.idempotencyKey)
|
|
? {
|
|
kind: continuationKind as NativeEvidenceAssessment["continuation"] extends infer T ? T extends { kind: infer K } ? K : never : never,
|
|
summary: text(continuation.summary)!,
|
|
idempotencyKey: text(continuation.idempotencyKey)!,
|
|
...(continuationKind === "case_handoff" && text(continuation.handoffId) ? { handoffId: text(continuation.handoffId)! } : {}),
|
|
}
|
|
: null,
|
|
attentionRequests: actionableAttentionRequests,
|
|
ignoredAttentionRequests,
|
|
};
|
|
}
|