import { a as WorkProductProvenance, d as WorkProductStorePort, e as WorkProductAuditEvent, b as WorkProductRecord, f as WorkProductArtifact, Q as QualityCheck, E as EvidenceEntry, g as ExceptionEntry, h as WorkProductStatus, c as WorkProductPersistedPart } from '../types-DeEOhQbv.js';
export { A as AgentCheckInput, i as EvidenceLocator, j as EvidenceSpan, k as ExceptionSeverity, P as ProfileBacktestSummary, l as QuoteBasis, m as WorkProductParseResult, n as WorkProductPatch, W as WorkProductRef, o as WorkProductUpdateGuard, p as WorkProductVersionEntry, q as isWorkProductStatus, r as parseAgentCheckInput, s as parseArtifactInput, t as parseEvidenceInput, u as parseExceptionInput, v as persistedPartToWorkProduct, w as unresolvedBlockingExceptions, x as workProductToPersistedPart } from '../types-DeEOhQbv.js';
import { a as AppToolContext, c as AppToolDefinition } from '../types-BCxK0wyS.js';
import { JudgeVerdict } from '@tangle-network/agent-eval';
import { T as TrustItem } from '../trust-gate-Dcm5xSva.js';
export { R as ReviewQueueInputs, a as ReviewQueueItem, b as ReviewQueuePendingAsk, c as ReviewQueueState, d as ReviewQueueThread, p as parseReviewQueueItem, e as projectReviewQueue } from '../queue-DBkulxW1.js';

/**
 * The guarded work-product status machine — the `/missions` service PATTERN
 * (load → validate against a transition table → CAS-write guarded on what was
 * read → audit event) over {@link WorkProductStorePort}. Deliberately NOT a
 * reuse of the mission service: missions' cursor/plan/budget machinery does
 * not apply here, and the six-status review machine is a different contract.
 *
 * Concurrency contract: a scope's draft is driven by a single serialized turn
 * owner, so real contention is rare. The service is the typed guard layer,
 * not a serializer — every mutation re-reads the record and CAS-writes
 * guarded on the `{status, version}` it read. A guard miss surfaces as
 * `{ succeeded: false, conflict: true }` (retryable: re-read and re-apply),
 * never a silent clobber.
 */

/** Discriminated outcome for guarded operations — `conflict` distinguishes a
 *  lost guarded race (retryable) from a logic rejection (illegal edge,
 *  missing row — deterministic, never retried). */
type WorkProductOutcome<T> = {
    succeeded: true;
    value: T;
} | {
    succeeded: false;
    error: string;
    conflict: boolean;
};
/** Whether a legal edge exists from `from` to `to` in the review machine. */
declare function canTransitionWorkProduct(from: WorkProductStatus, to: WorkProductStatus): boolean;
/** Statuses a work product can never leave. */
declare function isWorkProductTerminal(status: WorkProductStatus): boolean;
/** Define the input required to create a new draft work product row */
interface CreateWorkProductInput {
    /** Explicit row id — omit to use the service's generator. The MODEL never
     *  supplies ids; this is for deterministic server-side creation. */
    id?: string;
    workspaceId: string;
    threadId: string | null;
    scopeKey: string;
    /** Version this draft will become; default 1. The tool layer passes
     *  `last reviewed version + 1` when a scope is re-engaged after approval. */
    version?: number;
    provenance: WorkProductProvenance;
    /** Opaque product-column values handed VERBATIM to the store's insert. */
    extras?: Record<string, unknown>;
}
/** Payload for the draft→ready submit transition */
interface SubmitWorkProductInput {
    artifact: WorkProductArtifact;
    checks: QualityCheck[];
    provenance: WorkProductProvenance;
    /** Frozen snapshot ref of this version's body for the history entry;
     *  defaults to `artifact.path`. */
    artifactPath?: string;
}
/** Reviewer verdict payload for the ready→approved / ready→changes_requested transition */
interface WorkProductVerdictInput {
    verdict: 'approve' | 'request_changes';
    reviewedBy: string;
    note?: string;
}
/** Guarded mutation surface over the work-product store */
interface WorkProductService {
    create(input: CreateWorkProductInput): Promise<WorkProductRecord>;
    get(id: string): Promise<WorkProductRecord | null>;
    /** The scope's open accumulator row (`draft`/`blocked`), or null. */
    openDraft(workspaceId: string, scopeKey: string): Promise<WorkProductRecord | null>;
    /** The scope's `changes_requested` row awaiting its correction turn, or null. */
    awaitingCorrection(workspaceId: string, scopeKey: string): Promise<WorkProductRecord | null>;
    /** The scope's `ready` row awaiting review, or null. */
    awaitingReview(workspaceId: string, scopeKey: string): Promise<WorkProductRecord | null>;
    /** `max(version over the scope's approved/superseded rows) + 1` — the
     *  version a fresh draft for the scope should carry. */
    nextVersion(workspaceId: string, scopeKey: string): Promise<number>;
    /** Re-open a `changes_requested` row as the next draft: version bumps +1
     *  and the correction turn accumulates into the same scope row. */
    reopen(id: string): Promise<WorkProductOutcome<WorkProductRecord>>;
    /** Merge evidence entries by id (same id replaces — the agent can correct
     *  itself mid-turn). Legal only while `draft`/`blocked`. */
    upsertEvidence(id: string, entries: readonly EvidenceEntry[]): Promise<WorkProductOutcome<WorkProductRecord>>;
    /** Merge exception entries by id, then reconcile the blocked flag: any
     *  unresolved blocking entry parks `draft`→`blocked`; resolving the last
     *  one releases `blocked`→`draft`. */
    upsertExceptions(id: string, entries: readonly ExceptionEntry[]): Promise<WorkProductOutcome<WorkProductRecord>>;
    /** Persist a checks array without transitioning — how a failed platform
     *  gate (e.g. evidence_coverage) stays visible on the still-draft row. */
    recordChecks(id: string, checks: readonly QualityCheck[]): Promise<WorkProductOutcome<WorkProductRecord>>;
    /** The terminal agent call: CAS `draft`→`ready` with artifact + checks +
     *  provenance, appending the version-history entry. Refuses while an
     *  unresolved blocking exception exists. */
    submit(id: string, input: SubmitWorkProductInput): Promise<WorkProductOutcome<WorkProductRecord>>;
    /** Reviewer verdict: CAS `ready`→`approved`/`changes_requested` + history
     *  entry. Approval also supersedes the scope's prior approved versions so
     *  exactly one approved version is current per scope. */
    applyVerdict(id: string, input: WorkProductVerdictInput): Promise<WorkProductOutcome<WorkProductRecord>>;
    /** Explicit replacement: CAS to `superseded` (legal from ready /
     *  changes_requested / approved). */
    supersede(id: string): Promise<WorkProductOutcome<WorkProductRecord>>;
}
/** Configuration options for creating a work product service */
interface WorkProductServiceOptions {
    store: WorkProductStorePort;
    /** Injectable clock (epoch ms). Default `Date.now`. */
    now?: () => number;
    /** Row-id generator. Default `crypto.randomUUID()`. */
    generateId?: () => string;
}
/** Create the guarded work-product service over a store port */
declare function createWorkProductService(options: WorkProductServiceOptions): WorkProductService;
/** In-memory store surface with audit trail access and unguarded direct writes for tests */
interface InMemoryWorkProductStore extends WorkProductStorePort {
    /** The full audit trail, append order. */
    events(): WorkProductAuditEvent[];
    /** Unguarded direct write — simulates a concurrent owner in tests. */
    put(record: WorkProductRecord): void;
}
/**
 * In-memory {@link WorkProductStorePort} — the portable backend for tests and
 * reference assemblies. Records are deep-copied on every boundary so callers
 * can never mutate stored state around the guards.
 */
declare function createInMemoryWorkProductStore(): InMemoryWorkProductStore;

/**
 * Provenance stamping — the backtest spine. Every version of every work
 * product carries `profileHash + runId + servingModels`, stamped at the two
 * honest moments:
 *
 *  1. At dispatch, the product route composes the turn's profile and computes
 *     agent-eval's `agentProfileHash(profile)` — the SAME hash that keys the
 *     app's scorecard cells — and closes it (plus runId/sessionId) into the
 *     `provenance` seam `buildWorkProductTools` receives, so the model can
 *     neither omit nor forge it.
 *  2. At turn completion, the route's existing lifecycle seam calls
 *     {@link finalizeWorkProductProvenance}: serving model and cost come from
 *     the usage receipt, because only the completed turn knows what actually
 *     served. `servingModels` is honestly EMPTY until then.
 *
 * The trust bridge ({@link workProductTrustInputs}) maps judge-sourced
 * quality verdicts into `/eval-campaign`'s `trustVerdicts()` input with
 * type-only imports — products call `trustVerdicts` from
 * `@tangle-network/agent-app/eval-campaign` (which they already import for
 * their ensemble loop). Deliberately NOT a value re-export here: it would put
 * agent-eval's runtime on `/work-product`'s import path and drag the eval
 * engine into every product worker bundle.
 */

/** The dispatch-time provenance closure's output: everything the route knows
 *  before the turn completes. */
type WorkProductProvenanceBase = Omit<WorkProductProvenance, 'servingModels' | 'producedAt'>;
/** Stamp a full provenance from the dispatch-time base. `servingModels` starts
 *  empty (honestly absent — never guessed) until the completion back-fill. */
declare function stampProvenance(base: WorkProductProvenanceBase, now?: () => number): WorkProductProvenance;
/** Completion receipt for one run, from the turn's usage/lifecycle seam. */
interface FinalizeWorkProductProvenanceInput {
    workspaceId: string;
    /** The chat turnId / mission-step run id the records were stamped with. */
    runId: string;
    /** What actually served, from the usage receipt / serving-model header. */
    servingModels: readonly string[];
    costUsd?: number;
    logger?: Pick<Console, 'warn'>;
}
/**
 * Back-fill `servingModels`/`costUsd` onto every record (and its history
 * entries) stamped with `runId` — wire it into the chat route's existing
 * `lifecycle.onTurnComplete` seam; no new hook. Returns the updated records.
 * A CAS miss on one record is logged and skipped (the next completion or a
 * re-read re-applies); it never throws mid-fleet.
 */
declare function finalizeWorkProductProvenance(store: WorkProductStorePort, input: FinalizeWorkProductProvenanceInput): Promise<WorkProductRecord[]>;
/**
 * Trust-gate bridge: one `TrustItem` per work product whose production
 * quality was scored by the product's eval-campaign ensemble. `verdictsFor`
 * returns the per-judge raw verdicts the product retained for a record (the
 * same verdicts `aggregateJudgeVerdicts` reduces); records without verdicts
 * are omitted. Feed the result to `/eval-campaign`'s `trustVerdicts()` —
 * an untrusted verdict renders as "quality: unverified", never a naked
 * number. Zero statistics code here: pure mapping.
 */
declare function workProductTrustInputs<D extends string = string>(records: readonly WorkProductRecord[], verdictsFor: (record: WorkProductRecord) => readonly JudgeVerdict<D>[] | undefined): TrustItem<D>[];

/**
 * The agent-facing work-product side channel — three registry `customTools`
 * built on `/tools`' `defineAppTool`, dispatched through `dispatchAppTool`'s
 * single validation/outcome path (a thrown `ToolInputError` → correctable 4xx
 * back to the model; any other throw → internal error; a call never silently
 * succeeds without its effect). Deliberately NOT new `/tools` built-ins:
 * extending `AppToolHandlers` would break every existing consumer, and the
 * registry seam exists precisely for a product tool family like this.
 *
 * Partial-emission contract across a long turn: the draft ROW is the
 * accumulator. Evidence and exceptions stream in as found via small batched
 * calls; the artifact arrives once at the end. The agent addresses everything
 * by `scopeKey` — the server mints row ids, the model never invents them, and
 * identity (userId/workspaceId/threadId) rides the trusted `AppToolContext`
 * from headers, never model args. A turn that dies mid-emission leaves a
 * consistent draft the next turn resumes by the same scopeKey.
 */

/** Max entries per `upsert_evidence`/`flag_exception` call — keeps each call a
 *  small batch the model can correct precisely on a named-index failure. */
declare const MAX_WORK_PRODUCT_BATCH = 50;
/** Platform check: every material target has ≥1 evidence row. Recorded as
 *  `QualityCheck{source:'platform'}`. */
declare const EVIDENCE_COVERAGE_CHECK = "evidence_coverage";
/** Platform check: how many evidence entries carry a quote the shell PROVED
 *  occurs in the source it names. Recorded when `readSourceText` is wired, so
 *  a reviewer reads the strength of the lineage off the row itself rather than
 *  trusting that a quote was checked. */
declare const QUOTE_VERIFICATION_CHECK = "quote_verification";
/** Domain seams for the three work-product tools — every domain word is a
 *  parameter; the shell bakes none. */
interface WorkProductToolConfig {
    store: WorkProductStorePort;
    /** PARAMETER — accepted `artifact.kind` values, validated on submit. */
    artifactKinds: readonly string[];
    /** PARAMETER — accepted exception `kind` values. */
    exceptionKinds: readonly string[];
    /** Fail-loud source check: resolve an evidence `sourceRef` to existence
     *  (vault stat / attachment lookup). A dangling ref is a `ToolInputError`
     *  naming the entry index — lineage can never point at nothing. */
    resolveSourceRef: (ref: string, ctx: AppToolContext) => Promise<boolean>;
    /** Fail-loud QUOTE verification: return the source document's TEXT for a
     *  ref so the shell can prove each `locator.quote` occurs in it verbatim.
     *  Wiring this turns the gate ON — a quote that does not occur is a
     *  `ToolInputError` naming the entry index, so the model re-extracts from
     *  the document instead of persisting invented lineage.
     *
     *  Return `null` ONLY when the ref genuinely has no extractable text (an
     *  image scan, an opaque blob). The gate is fail-CLOSED on `null`: a quote
     *  that cannot be checked is refused, because "unverifiable" and "verified"
     *  must never look the same to a reviewer. Such an entry is still recordable
     *  without `locator.quote` — `claim` carries the assertion.
     *
     *  Omit the seam entirely and no quote is checked. */
    readSourceText?: (ref: string, ctx: AppToolContext) => Promise<string | null>;
    /** The material targets the platform coverage check requires evidence for.
     *  Product-owned vocabulary; omit to skip the coverage gate.
     *
     *  Return ONLY targets a source document can actually evidence. A gate that
     *  demands document lineage for a value the session COMPUTED is not
     *  satisfiable by any honest answer, and an unsatisfiable gate does not stop
     *  a submit — it selects for an invented one. Computed values belong to a
     *  product's own computation check, where "matches what we already
     *  calculated" is satisfiable by construction. */
    materialTargets?: (artifact: WorkProductArtifact) => string[];
    /** Require every material target to carry a SOURCE ANCHOR — a span-sliced or
     *  verified quote — not merely an evidence row. Off by default (a bare
     *  `claim` is legitimate lineage for products with no readable sources);
     *  turn it ON once `readSourceText` is wired and `materialTargets` names only
     *  document-derived targets, and coverage stops being satisfiable by
     *  assertion. */
    requireAnchoredEvidence?: boolean;
    /** Per-turn provenance closure the ROUTE supplies (profileHash + runId are
     *  known at dispatch; trusted, never read from model args). */
    provenance: (ctx: AppToolContext) => WorkProductProvenanceBase;
    /** Called on the draft→ready commit so the route persists the transcript
     *  anchor part and the queue projection updates. */
    onReady?: (record: WorkProductRecord, ctx: AppToolContext) => void | Promise<void>;
    /** Injectable clock / id generator (tests, deterministic ids). */
    now?: () => number;
    generateId?: () => string;
}
/** Build the three work-product tools for `customTools` registration on the
 *  MCP server / HTTP handler / runtime executor. */
declare function buildWorkProductTools(config: WorkProductToolConfig): AppToolDefinition[];

/**
 * Verbatim quote verification — the lineage gate.
 *
 * An evidence `locator.quote` is the reviewer's click target: it must land on
 * text that is actually in the document the entry names. Nothing here is
 * fuzzy. The only latitude is representational — the same characters written
 * differently by a PDF extractor, a text transcription, or a model repeating
 * what it read: Unicode compatibility forms, curly quotes, the several dash
 * codepoints, non-breaking spaces, and run-length whitespace. A quote that
 * still does not occur after that is not a formatting difference; it is text
 * the document does not contain.
 *
 * Deliberately NOT tolerated, because each one re-opens the hole this closes:
 * case (a quote is a quote), token subsets, edit distance, word-overlap
 * scoring, and "the numbers match" heuristics. A fabricated quote and a real
 * one differ by exactly the thing a fuzzy matcher forgives.
 */
/**
 * Fold a string to the form both sides of a quote comparison are measured in.
 * Composition and presentation only: NFKC, one dash, one apostrophe, one
 * double quote, runs of any whitespace to a single space, trimmed. Case is
 * PRESERVED — lowercasing would let "Box 1" match "box 1", and a citation
 * that cannot reproduce capitalization did not read the document.
 */
declare function normalizeQuoteText(value: string): string;
/**
 * Does `quote` occur in `sourceText`? Exact substring first (the common case,
 * and free); the normalized comparison second, for the representational
 * differences above. Nothing else.
 *
 * An empty or whitespace-only quote is NOT a match — it would otherwise be a
 * substring of every document and pass the gate vacuously.
 */
declare function sourceContainsQuote(sourceText: string, quote: string): boolean;
/**
 * Slice a citation out of the source text by character offset — the reason
 * this module exists in its stronger form.
 *
 * Verification above is a REJECTION gate: the model retypes a quote and the
 * shell refuses it when the characters do not occur. That gate is correct and
 * it works, but a model that reproduces a line character-for-character only
 * some of the time cannot USE it — every miss is a refusal, and the package
 * ends up with no lineage at all rather than false lineage. A measured 9 of 59
 * on the live tax surface is what "some of the time" meant in practice.
 *
 * A span inverts it. The model names two integers into text it just read; the
 * PLATFORM produces the quote from the bytes it already holds. There is no
 * retyping step to get wrong, so a fabricated quote is not rejected — it is
 * unrepresentable. `sourceContainsQuote(text, sliceSourceSpan(text, span))` is
 * true for every span this function returns, by construction.
 *
 * Offsets index the SAME string the product's document-reading tool pages
 * with an offset, which is the same string its `readSourceText` seam returns.
 * That is the one contract a product must keep; violate it and spans point at
 * the wrong characters (still real characters of that document — never
 * invented text, but the wrong line).
 *
 * Half-open `[start, end)`, matching `String.prototype.slice` and the
 * `offset`/`offset + text.length` window a paged read already reports.
 */
type SourceSpanFailure = {
    reason: 'not_integer';
    field: 'start' | 'end';
} | {
    reason: 'negative';
    field: 'start' | 'end';
} | {
    reason: 'inverted';
} | {
    reason: 'out_of_range';
    totalChars: number;
} | {
    reason: 'blank';
};
type SourceSpanResult = {
    ok: true;
    quote: string;
} | {
    ok: false;
    failure: SourceSpanFailure;
};
/** Resolve `[start, end)` against `sourceText`. Every rejection is a caller
 *  mistake the model can correct from the paged read it already has, so each
 *  carries the discriminator a tool layer turns into a specific message. */
declare function sliceSourceSpan(sourceText: string, span: {
    start: number;
    end: number;
}): SourceSpanResult;

/**
 * Framework-neutral work-product review endpoints — the
 * `createInteractionAnswerRoute` factory pattern: web-standard
 * `Request`/`Response`, ONE product-supplied `authorize` seam (session auth,
 * workspace access, reviewer identity, rate limits), everything behind it
 * mechanism. Server-only and subpath-only: never reachable from a client
 * bundle (enforced by the browser-safety test).
 *
 * The verdict endpoint is deliberately NOT a second approval broker: agent
 * asks stay on `/interactions`; this is the REVIEWER's plain authorized
 * verdict on a ready package — one human-in-the-loop channel per direction.
 * A `request_changes` note re-enters chat as the correction turn via the
 * `onVerdict` seam; chat remains the driver surface.
 */

/** Reviewer verdict wire body for the POST endpoint. */
type WorkProductVerdictBody = {
    ok: true;
    id: string;
    verdict: 'approve';
    note?: string;
} | {
    ok: true;
    id: string;
    verdict: 'request_changes';
    note: string;
} | {
    ok: false;
    error: string;
};
/** Validate the verdict POST body: `{ id, verdict, note? }`; a
 *  `request_changes` verdict REQUIRES a non-empty note — the note IS the
 *  correction turn the agent works from. */
declare function validateWorkProductVerdictBody(body: Record<string, unknown>): WorkProductVerdictBody;
/** The product seam's verdict for one request: authenticated reviewer +
 *  workspace, or a product-authored short-circuit Response (401/403/429…). */
type WorkProductRouteAuthorization = {
    ok: true;
    workspaceId: string;
    reviewedBy: string;
} | {
    ok: false;
    response: Response;
};
/** Auth seam arguments carrying the request, the endpoint intent, and the parsed verdict body */
interface WorkProductAuthorizeArgs {
    request: Request;
    intent: 'list' | 'detail' | 'verdict';
    /** The parsed, validated POST body (verdict intent only). */
    body?: Record<string, unknown>;
}
/** Configuration options assembling the review endpoints from the store and product seams */
interface WorkProductRoutesOptions {
    store: WorkProductStorePort;
    /** Authenticate + authorize the caller; the ONLY product access step. */
    authorize: (args: WorkProductAuthorizeArgs) => Promise<WorkProductRouteAuthorization>;
    /** Post-verdict product seam: post the `request_changes` note into the
     *  driving chat thread as the correction turn, notify, etc. Runs after the
     *  transition commits; a throw is logged, never unwinds the verdict. */
    onVerdict?: (args: {
        record: WorkProductRecord;
        verdict: 'approve' | 'request_changes';
        note?: string;
        reviewedBy: string;
    }) => void | Promise<void>;
    /** Persist/update the transcript anchor part reflecting the new status, so
     *  the chat card flips with the verdict. */
    persistAnchorPart?: (part: WorkProductPersistedPart, record: WorkProductRecord) => void | Promise<void>;
    /** Future integration point fired on approval (push to a DMS/CRM/export
     *  pipeline). A stub seam by design — export itself stays the product's
     *  signed object-store download. */
    onExport?: (record: WorkProductRecord) => void | Promise<void>;
    logger?: Pick<Console, 'warn' | 'error'>;
    now?: () => number;
}
/** Assembled review endpoints returning web-standard Responses */
interface WorkProductRoutes {
    /** GET — the workspace's records for the queue projection. Optional
     *  `?status=a,b` filter. */
    list: (request: Request) => Promise<Response>;
    /** GET — one record by id (404 when absent or outside the workspace). */
    detail: (request: Request, id: string) => Promise<Response>;
    /** POST `{ id, verdict, note? }` — the reviewer verdict: CAS transition +
     *  history entry + product seams. 409 when the record is no longer ready. */
    verdict: (request: Request) => Promise<Response>;
}
/** Create the work-product review endpoints over the store port and product seams */
declare function createWorkProductRoutes(options: WorkProductRoutesOptions): WorkProductRoutes;

export { type CreateWorkProductInput, EVIDENCE_COVERAGE_CHECK, EvidenceEntry, ExceptionEntry, type FinalizeWorkProductProvenanceInput, type InMemoryWorkProductStore, MAX_WORK_PRODUCT_BATCH, QUOTE_VERIFICATION_CHECK, QualityCheck, type SourceSpanFailure, type SourceSpanResult, type SubmitWorkProductInput, TrustItem, WorkProductArtifact, WorkProductAuditEvent, type WorkProductAuthorizeArgs, type WorkProductOutcome, WorkProductPersistedPart, WorkProductProvenance, type WorkProductProvenanceBase, WorkProductRecord, type WorkProductRouteAuthorization, type WorkProductRoutes, type WorkProductRoutesOptions, type WorkProductService, type WorkProductServiceOptions, WorkProductStatus, WorkProductStorePort, type WorkProductToolConfig, type WorkProductVerdictBody, type WorkProductVerdictInput, buildWorkProductTools, canTransitionWorkProduct, createInMemoryWorkProductStore, createWorkProductRoutes, createWorkProductService, finalizeWorkProductProvenance, isWorkProductTerminal, normalizeQuoteText, sliceSourceSpan, sourceContainsQuote, stampProvenance, validateWorkProductVerdictBody, workProductTrustInputs };
