{"version":3,"file":"step-up.mjs","names":[],"sources":["../src/step-up.ts"],"sourcesContent":["/**\n * Step-up enforce orchestration core — runtime-neutral (T3-edge keystone).\n *\n * The single source of truth for \"given an enforce-mode policy decision, run\n * the N-of-M HITL step-up gate and return a transport-neutral outcome\", shared\n * by every runtime that enforces in-process: the central Hono gateway (the\n * first consumer) and — via the adapter lanes — the SDK middleware runtimes\n * (Express / Next.js / .NET-port / Cloudflare worker). Before this module the\n * gateway hand-rolled the branch inline in `routes/mcp.ts`; each edge runtime\n * would have re-implemented the same fail-closed ordering, the TOCTOU binding,\n * and the six `policy.enforce.*` events — exactly the divergence the engine-as-\n * SSOT mandate forbids.\n *\n * Pure TS over STRUCTURAL types + an INJECTED quorum verifier — no WASM, no\n * `node:*`, and (deliberately) no `@kya-os/mcp` import, so it loads identically\n * on Node and edge and adds no dependency to this published package. The host\n * injects `verifyQuorum` (the gateway binds `@kya-os/mcp`'s\n * `verifyApprovalQuorum` with its own approval-signature verifier) and maps the\n * returned {@link StepUpEvaluationResult} to its transport (the gateway →\n * `@kya-os/mcp` `createNeedsApprovalError` → a JSON-RPC envelope; an edge\n * runtime → an HTTP status). This mirrors `composed-policy.ts`, which injects\n * its `compile` fn rather than importing the WASM engine.\n *\n * The HOST owns everything around the decision: computing the `enforce` flag\n * (so `evaluateStepUp` is only ever called when enforcing), stripping the\n * `_kyaos_approvals` control envelope from the forwarded args (it must be\n * stripped on EVERY path, including observe — so it stays at the route), and\n * hashing the canonical clean args into `requestHash`.\n */\n\nimport {\n  validateStepUpQuorum,\n  type StepUpQuorumLike,\n} from '@kya-os/checkpoint-shared/policy/enforcement';\n\n/**\n * The policy decision the orchestrator branches on. Structural mirror of the\n * `@kya-os/mcp` `PolicyDecision` discriminated union, kept local so the core\n * takes no `@kya-os/mcp` dependency; the host's real `PolicyDecision` is\n * structurally assignable. `reason` is present on `deny`, `quorum` on `step_up`.\n */\nexport interface StepUpDecision {\n  decision: 'allow' | 'deny' | 'step_up';\n  reason?: string;\n  quorum?: StepUpQuorumLike;\n}\n\n/** Outcome of the injected approval-quorum check (mirrors `@kya-os/mcp` `QuorumResult`). */\nexport interface QuorumVerifyResult {\n  satisfied: boolean;\n  reason?: string;\n}\n\n/**\n * Injected: verify the presented grants satisfy the quorum, bound to\n * `requestHash` (TOCTOU defense). The gateway binds `@kya-os/mcp`\n * `verifyApprovalQuorum` with its own per-grant signature verifier (today a\n * deliberate reject-all kill switch, pending E3.2 / #2889). Required — there is\n * no default, so a missing injection is a type error, never an accidental\n * permissive pass.\n */\nexport type QuorumVerifier<TGrant = unknown> = (\n  grants: TGrant[],\n  requestHash: string,\n  quorum: StepUpQuorumLike\n) => Promise<QuorumVerifyResult>;\n\n/** Minimal structural logger the host supplies; a pino instance satisfies it. */\nexport interface StepUpLogger {\n  info(obj: object, msg?: string): void;\n  warn(obj: object, msg?: string): void;\n}\n\n/**\n * Transport-neutral NEEDS_APPROVAL descriptor. The host maps it to its wire\n * error: the gateway feeds it to `@kya-os/mcp` `createNeedsApprovalError`\n * (→ JSON-RPC `-32008`); an edge runtime renders it as an HTTP response. The\n * field set matches `@kya-os/mcp`'s `createNeedsApprovalError` init so the\n * gateway can pass it straight through.\n */\nexport interface NeedsApprovalDescriptor {\n  message: string;\n  resumeToken: string;\n  /** Unix seconds. */\n  expiresAt: number;\n  requestHash: string;\n  quorum: StepUpQuorumLike;\n}\n\n/** Everything {@link evaluateStepUp} needs for ONE tool call's enforce decision. */\nexport interface StepUpContext<TGrant = unknown> {\n  /** The neutral policy decision (allow / deny / step_up) from the policy gate. */\n  decision: StepUpDecision;\n  /** True when the gate faulted (the host's `PolicyGateResult.faulted`). */\n  faulted: boolean;\n  /** SHA-256 of the suspended action's canonical (clean) args — host computes it. */\n  requestHash: string;\n  /** Presented approval grants parsed from the stripped control envelope. */\n  grants: TGrant[];\n  /** Injected per-grant quorum verifier (TOCTOU-bound to `requestHash`). */\n  verifyQuorum: QuorumVerifier<TGrant>;\n  /** Fields echoed verbatim into every emitted `policy.enforce.*` event\n   *  (the gateway passes `{ orgId, projectId, agentDid, tool }`). */\n  logContext?: Record<string, unknown>;\n  /** Optional structured logger; the six enforce events are emitted through it. */\n  log?: StepUpLogger;\n  /** Builds the human NEEDS_APPROVAL message; the host owns the wire copy. */\n  buildMessage?: (quorum: StepUpQuorumLike, reason: string) => string;\n  /** Seconds until the resume token expires (default 300, matching the gateway). */\n  approvalTtlSeconds?: number;\n}\n\n/** Tagged outcome the host maps to its transport. */\nexport type StepUpEvaluationResult =\n  | { status: 'allow' }\n  | { status: 'deny'; reason: string }\n  | { status: 'needs-approval'; needs: NeedsApprovalDescriptor };\n\nconst DEFAULT_APPROVAL_TTL_SECONDS = 300;\n\n/**\n * Run the enforce-mode step-up gate for one tool call. Only called when the host\n * has already decided to ENFORCE. Pure: never throws on the live path; emits the\n * six `policy.enforce.*` events; runs {@link validateStepUpQuorum} (fail-closed)\n * BEFORE the verifier; and calls the injected `verifyQuorum`.\n *\n * Behavioral parity with the gateway's prior inline branch\n * (`apps/gateway/src/routes/mcp.ts`): fault → deny `policy_evaluation_failed`;\n * `deny` → deny with the engine reason; `step_up` → fail-closed quorum guard,\n * then quorum verify (TOCTOU-bound) → `needs-approval` when unmet, else allow.\n */\nexport async function evaluateStepUp<TGrant = unknown>(\n  ctx: StepUpContext<TGrant>\n): Promise<StepUpEvaluationResult> {\n  const {\n    decision,\n    faulted,\n    requestHash,\n    grants,\n    verifyQuorum,\n    logContext = {},\n    log,\n    buildMessage,\n    approvalTtlSeconds = DEFAULT_APPROVAL_TTL_SECONDS,\n  } = ctx;\n\n  // Fault → fail closed. A gate fault (engine/classifier/projection threw) is a\n  // deny in enforce mode (the host fails OPEN only in observe).\n  if (faulted) {\n    log?.warn(\n      { event: 'policy.enforce.fault', ...logContext },\n      'policy gate decision (enforce: fault)'\n    );\n    return { status: 'deny', reason: 'policy_evaluation_failed' };\n  }\n\n  if (decision.decision === 'allow') {\n    log?.info(\n      { event: 'policy.enforce.allow', ...logContext },\n      'policy gate decision (enforce: allow)'\n    );\n    return { status: 'allow' };\n  }\n\n  if (decision.decision === 'deny') {\n    const reason = decision.reason ?? 'policy_denied';\n    log?.info(\n      { event: 'policy.enforce.deny', ...logContext, reason },\n      'policy gate decision (enforce: deny)'\n    );\n    return { status: 'deny', reason };\n  }\n\n  // decision.decision === 'step_up'\n  const quorum = decision.quorum;\n  // A `step_up` with no quorum is a malformed decision — fail closed. (The\n  // structural decision type loosens `quorum` to optional; the host's real\n  // PolicyDecision always carries it on step_up.)\n  const quorumCheck = quorum\n    ? validateStepUpQuorum(quorum)\n    : ({ ok: false, reason: 'invalid_step_up_quorum' } as const);\n  if (!quorumCheck.ok) {\n    log?.info(\n      {\n        event: 'policy.enforce.invalid_step_up',\n        ...logContext,\n        quorumN: quorum?.n ?? 0,\n        approverCount: Array.isArray(quorum?.approvers) ? quorum.approvers.length : 0,\n        reason: quorumCheck.reason,\n      },\n      'policy gate decision (enforce: invalid step_up quorum)'\n    );\n    return { status: 'deny', reason: quorumCheck.reason };\n  }\n\n  // quorumCheck.ok ⇒ quorum is a real gate (validateStepUpQuorum returns ok only\n  // for a defined, positive-n, named-approver quorum).\n  const verifiedQuorum = quorum as StepUpQuorumLike;\n  const quorumResult = await verifyQuorum(grants, requestHash, verifiedQuorum);\n  if (!quorumResult.satisfied) {\n    const reason = quorumResult.reason ?? 'quorum_not_met';\n    log?.info(\n      {\n        event: 'policy.enforce.step_up_required',\n        ...logContext,\n        quorumN: verifiedQuorum.n,\n        presentedCount: grants.length,\n        requestHash,\n        reason,\n      },\n      'policy gate decision (enforce: step_up required)'\n    );\n    return {\n      status: 'needs-approval',\n      needs: {\n        message: buildMessage\n          ? buildMessage(verifiedQuorum, reason)\n          : `Step-up approval required (${verifiedQuorum.n}-of-N): ${reason}.`,\n        resumeToken: `step_up:${requestHash}`,\n        expiresAt: Math.floor(Date.now() / 1000) + approvalTtlSeconds,\n        requestHash,\n        quorum: verifiedQuorum,\n      },\n    };\n  }\n\n  // Quorum satisfied — proceed. The host's forwarded args are already clean\n  // (the control envelope is stripped at the route on every path).\n  log?.info(\n    {\n      event: 'policy.enforce.step_up_approved',\n      ...logContext,\n      quorumN: verifiedQuorum.n,\n      presentedCount: grants.length,\n      requestHash,\n    },\n    'policy gate decision (enforce: step_up approved)'\n  );\n  return { status: 'allow' };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Pending-approval store — DORMANT. Relocated from the gateway as part of the\n// T3-edge keystone so the edge adapter lanes share one home. It tracks a\n// suspended action across the NEEDS_APPROVAL → resume gap, keyed by requestId,\n// so a resumed call can confirm the quorum requirement hasn't shifted (TOCTOU-\n// safe binding to the requestHash an approver signed). NOT on the live enforce\n// path today — a later lane wires it into the resume flow. Single-pod in-memory\n// MVP; a multi-pod runtime supplies a Redis/DO-backed impl behind the same\n// `ApprovalStore` interface.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Pending action awaiting an N-of-M approval quorum. `requestHash` is the\n * SHA-256 of the suspended action's canonical args, which both the agent's\n * resume token and every approver signature MUST bind to (TOCTOU defense).\n */\nexport interface PendingApproval {\n  requestId: string;\n  requestHash: string;\n  quorum: StepUpQuorumLike;\n  createdAt: number;\n  expiresAt: number;\n}\n\n/**\n * Storage for pending approvals — write a pending record, read it back by id.\n * Quorum verification of the presented grants lives in the host's injected\n * verifier, not here; this store only tracks the action-binding state across\n * the suspend → resume gap.\n */\nexport interface ApprovalStore {\n  recordPending(entry: PendingApproval): Promise<void>;\n  /** Returns the entry if present and not expired; otherwise null. */\n  getPending(\n    requestId: string\n  ): Promise<{ requestHash: string; quorum: StepUpQuorumLike; expiresAt: number } | null>;\n}\n\ninterface StoredEntry {\n  requestHash: string;\n  quorum: StepUpQuorumLike;\n  expiresAt: number;\n}\n\n/**\n * In-memory implementation. Single-pod, process-restart resets. Entries past\n * `expiresAt` are treated as absent at read time AND lazily evicted on the same\n * read (no background sweep — the suspend → resume window is bounded by the\n * NEEDS_APPROVAL `expiresAt`).\n */\nexport class InMemoryApprovalStore implements ApprovalStore {\n  private readonly entries = new Map<string, StoredEntry>();\n\n  async recordPending(entry: PendingApproval): Promise<void> {\n    // Latest write wins: a retry of the same suspended action with a refreshed\n    // quorum replaces the prior binding rather than keeping a stale one.\n    this.entries.set(entry.requestId, {\n      requestHash: entry.requestHash,\n      quorum: entry.quorum,\n      expiresAt: entry.expiresAt,\n    });\n  }\n\n  async getPending(\n    requestId: string\n  ): Promise<{ requestHash: string; quorum: StepUpQuorumLike; expiresAt: number } | null> {\n    const found = this.entries.get(requestId);\n    if (!found) return null;\n    if (Date.now() >= found.expiresAt) {\n      // Lazy eviction keeps the map bounded under steady-state load.\n      this.entries.delete(requestId);\n      return null;\n    }\n    return { ...found };\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsHA,MAAM,+BAA+B;;;;;;;;;;;;AAarC,eAAsB,eACpB,KACiC;CACjC,MAAM,EACJ,UACA,SACA,aACA,QACA,cACA,aAAa,CAAC,GACd,KACA,cACA,qBAAqB,iCACnB;CAIJ,IAAI,SAAS;EACX,KAAK,KACH;GAAE,OAAO;GAAwB,GAAG;EAAW,GAC/C,uCACF;EACA,OAAO;GAAE,QAAQ;GAAQ,QAAQ;EAA2B;CAC9D;CAEA,IAAI,SAAS,aAAa,SAAS;EACjC,KAAK,KACH;GAAE,OAAO;GAAwB,GAAG;EAAW,GAC/C,uCACF;EACA,OAAO,EAAE,QAAQ,QAAQ;CAC3B;CAEA,IAAI,SAAS,aAAa,QAAQ;EAChC,MAAM,SAAS,SAAS,UAAU;EAClC,KAAK,KACH;GAAE,OAAO;GAAuB,GAAG;GAAY;EAAO,GACtD,sCACF;EACA,OAAO;GAAE,QAAQ;GAAQ;EAAO;CAClC;CAGA,MAAM,SAAS,SAAS;CAIxB,MAAM,cAAc,SAChB,qBAAqB,MAAM,IAC1B;EAAE,IAAI;EAAO,QAAQ;CAAyB;CACnD,IAAI,CAAC,YAAY,IAAI;EACnB,KAAK,KACH;G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