@vostride/agent-qa-schema 0.0.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/primitives/ref.ts","../src/action/wire-schema.ts","../src/action/family.ts","../src/screen/normalize-name.ts","../src/screen/element-ordinal.ts","../src/screen/toggle.ts","../src/determinism/canonical-json.ts","../src/config-mutation/utf8.ts","../src/determinism/sha256.ts","../src/screen/distilled-state-digest.ts","../src/embedding-profile/embedding-profile.ts","../src/config/base.ts","../src/config/browser.ts","../src/config/config-write.ts","../src/config/leaves.ts","../src/safety/action-descriptor.ts","../src/config/production.ts","../src/config/device.ts","../src/config/remote-device.ts","../src/config/platform-config.ts","../src/config/use.ts","../src/config/planner-limits.ts","../src/determinism/screen-hash.ts","../src/determinism/env-digest.ts","../src/determinism/cache-key.ts","../src/determinism/tool-schema-digest.ts","../src/identity/normalize-anchor.ts","../src/identity/identity-tuple.ts","../src/identity/graph-node.ts","../src/handoff/sub-action-evidence.ts","../src/identity/exercised-anchors.ts","../src/identity/supersession-key.ts","../src/versioning/create-version-guard.ts","../src/run/run-id.ts","../src/ids/slug.ts","../src/run/run-artifact.ts","../src/run/evidence.ts","../src/ids/artifact-ref.ts","../src/run/run-status.ts","../src/run/live-stream.ts","../src/run/live-url.ts","../src/run/bus-events.ts","../src/run/model-usage.ts","../src/run/bus-projections.ts","../src/run/handle-scope.ts","../src/functions/runs.ts","../src/brief/retrieval-rung.ts","../src/brief/retrieval-trace.ts","../src/knowledge/review-verbs.ts","../src/functions/feedback.ts","../src/knowledge/gate-receipt.ts","../src/knowledge/promotion-path.ts","../src/knowledge/change.ts","../src/delta/delta.ts","../src/delta/envelope.ts","../src/entity/entity-card.ts","../src/entity/kinds.ts","../src/entity/uri.ts","../src/knowledge/bundle-files.ts","../src/verdict/verdict.ts","../src/functions/record-join.ts","../src/knowledge/maintenance-views.ts","../src/notification/curation-snapshot.ts","../src/notification/run-notification.ts","../src/notification/post-processing-status.ts","../src/job/job.ts","../src/job/job-id.ts","../src/run/recording.ts","../src/functions/output-contract.ts","../src/functions/runs-overview.ts","../src/ids/record-id.ts","../src/ids/compute-evidence-token.ts","../src/ids/content-address.ts","../src/brief/compute-brief-digest.ts","../src/brief/guard-lossless-served-brief.ts","../src/brief/served-brief.ts","../src/handoff/completed-run-handoff.ts","../src/verdict/misdirection-evidence.ts","../src/handoff/condition-evidence.ts","../src/handoff/load-completed-run-handoff.ts","../src/handoff/limit-evidence.ts","../src/handoff/operation-evidence.ts","../src/notification/run-digest.ts","../src/functions/analysis-get.ts","../src/verdict/resolved-verdicts.ts","../src/verdict/sentence-parts.ts","../src/verdict/analysis-artifact.ts","../src/verdict/failure-fingerprint.ts","../src/result/no-input.ts","../src/verdict/action-anchor-fingerprint.ts","../src/verdict/fingerprint-input.ts","../src/verdict/validate-analysis.ts","../src/quarantine/quarantine-ledger.ts","../src/quarantine/quarantine-ops.ts","../src/memory/working-memory-entry.ts","../src/job/job-enqueue.ts","../src/job/job-checkpoint.ts","../src/job/job-outcome.ts","../src/job/analyze-run-payload.ts","../src/patch/patch.ts","../src/patch/patch-id.ts","../src/config-mutation/base64.ts","../src/config-mutation/line-diff.ts","../src/config-mutation/diff-digest.ts","../src/config-mutation/constants.ts","../src/config-mutation/file-set.ts","../src/config-mutation/actions.ts","../src/config-mutation/references.ts","../src/result/annotation.ts","../src/result/action-result.ts","../src/result/target-refusal.ts","../src/result/binding-outcome.ts","../src/reader/serving-admission.ts","../src/knowledge/outcome-event.ts","../src/knowledge/trust-fold.ts","../src/knowledge/distilled-observation.ts","../src/knowledge/promotion-gate.ts","../src/knowledge/cold-start.ts","../src/knowledge/measurement-fold.ts","../src/knowledge/manifest-identity.ts","../src/knowledge/record-frontmatter.ts","../src/knowledge/procedure-steps.ts","../src/knowledge/embedding-input.ts","../src/knowledge/evidence-token.ts","../src/knowledge/candidate-injection.ts","../src/functions/knowledge.ts","../src/knowledge/curator-tier.ts","../src/knowledge/planner-tier.ts","../src/knowledge/procedure-fillability.ts","../src/knowledge/procedure-binding-coercion.ts","../src/action/replayability.ts","../src/functions/function-caller.ts","../src/functions/config.ts","../src/functions/authoring.ts","../src/authoring/funnel.ts","../src/authoring/disposition.ts","../src/authoring/draft-receipt.ts","../src/authoring/fan-out.ts","../src/authoring/patch-ops.ts","../src/authoring/proposal-arms.ts","../src/functions/tool-folds.ts","../src/functions/run-service.ts","../src/authoring/suite-stability.ts","../src/authoring/procedure-reference.ts","../src/entity/dashboard-route.ts","../src/entity/url.ts","../src/entity/resolution.ts","../src/chat/session-events.ts","../src/chat/turn-receipts.ts","../src/chat/agent-ask.ts","../src/chat/scenario-expectation.ts","../src/capability-catalog.ts","../src/explain.ts","../src/llm/provider-error.ts","../src/llm/connect.ts"],"sourcesContent":["export { asRef, type Ref, type Point, type BoundingBox, type Viewport } from './primitives/index'\n\nexport type {\n Action,\n AndroidAction,\n CommonAction,\n IosAction,\n MobileAction,\n Platform,\n RefTargeted,\n Surface,\n TabSelector,\n WebAction,\n} from './action/index'\nexport type { ActionExecutor, ActionsFor } from './action/adapter'\nexport { ACTION_WIRE_SCHEMAS_BY_TYPE, actionWireSchema } from './action/wire-schema'\nexport {\n type ActionFamily,\n ACTION_FAMILIES,\n ActionFamilySchema,\n ACTION_FAMILY_BY_TYPE,\n actionFamilyOf,\n} from './action/family'\nexport type {\n EmittedTargetDescriptor,\n Fill,\n PlannedFill,\n PlannedScroll,\n Scroll,\n SwipeByDirection,\n SwipeByPath,\n WaitFor,\n WithEmittedRef,\n WithEmittedTarget,\n} from './action/params'\nexport type { ActionAnnotation, ActionResult } from './result/index'\nexport {\n elementOrdinal,\n normalizeAccessibleName,\n distilledScreenStateDigest,\n isToggleElement,\n TOGGLE_ROLES,\n} from './screen/index'\nexport type { DistilledScreenStateInput } from './screen/index'\nexport type { ElementBounds, ScrollContext } from './screen/index'\nexport type { ElementInfo, ElementState, ElementLabels, ElementHierarchy } from './screen/index'\nexport type { ScreenState } from './screen/index'\nexport type { ScreenStateMetadata, ScreenStateMetadataBase } from './screen/index'\nexport type { TargetDescriptor, GroundingAttempt, GroundingEvidence } from './screen/index'\nexport type { ModelCapabilities } from './capability/index'\nexport type { ModelProfile, ModelProviderId, ModelAuthDeclaration } from './model-profile/index'\nexport type { EmbeddingProfile } from './embedding-profile/index'\nexport {\n DEFAULT_EMBEDDING_PROFILE,\n STATIC_FLOOR_EMBEDDING_PROFILE,\n} from './embedding-profile/index'\nexport type {\n AndroidPlatformConfig,\n BrowserConfig,\n ConfigActionRefusal,\n ConfigChange,\n ConfigLeafPattern,\n ConfigNamedArray,\n ConfigPathSegment,\n ConfigUndoRequest,\n ConfigUndoResult,\n // 2026-09-27, 429-44 WR-01\n ConfigWriteDeniedRoot,\n ConfigWriteIssue,\n ConfigWriteOp,\n ConfigWriteRefusal,\n ConfigWriteRequest,\n ConfigWriteResult,\n DeviceConfig,\n EffectiveWorkersInput,\n IosPlatformConfig,\n PlatformBase,\n PlatformConfig,\n // 2026-10-07 (436-04, D-01..D-03)\n PlannerLimits,\n PlannerLimitsPerTest,\n PlannerLimitsRecord,\n RemoteDeviceConfig,\n TimeoutConfig,\n Use,\n UseAndroid,\n UseConcurrency,\n UseIos,\n UseWeb,\n UseWebAuthState,\n WebAuthStateConfig,\n WebPlatformConfig,\n} from './config/index'\nexport {\n // 432 D-18: the production refusal's one sentence (the run core and the live editor).\n ALLOW_PRODUCTION_OPT_IN,\n appStateSchema,\n browserConfigSchema,\n buildProductionRefusal,\n CONFIG_ACTION_REFUSALS,\n CONFIG_NAMED_ARRAYS,\n CONFIG_REVISION_ABSENT,\n CONFIG_SCHEMA_LEAVES,\n // 2026-09-27, 429-44 WR-01: the page write door's denied roots and path policy.\n CONFIG_WRITE_DENIED_ROOTS,\n CONFIG_WRITE_OPS,\n CONFIG_WRITE_REFUSALS,\n ConfigChangeSchema,\n configLeafOwner,\n ConfigPathSegmentSchema,\n ConfigUndoRequestSchema,\n ConfigWriteRequestSchema,\n DEFAULT_PARALLEL_WORKERS,\n // 2026-10-07 (436-04, D-01..D-03): the one default pair and resolver every door calls.\n DEFAULT_PLANNER_LIMITS,\n deviceConfigSchema,\n distinctInFirstOccurrenceOrder,\n isConfigSchemaPath,\n isPageWritableConfigPath,\n // 441 GAP2-D4: the marker_written_back refusal's one sentence.\n MARKER_WRITTEN_BACK_SENTENCE,\n platformBase,\n platformConfigSchema,\n PLANNER_LIMIT_KEYS,\n remoteDeviceSchema,\n resolveEffectiveWorkers,\n resolvePlannerLimits,\n timeoutConfigSchema,\n useSchema,\n viewportSchema,\n} from './config/index'\nexport {\n canonicalJson,\n canonicalValue,\n committedFileText,\n sha256hex,\n sha256hex16,\n sha256hexBytes,\n} from './determinism/index'\nexport type {\n ScopeKey,\n ScopeTier,\n Anchor,\n GraphNodeType,\n GraphEdgeType,\n GraphNodeNaturalKey,\n} from './identity/index'\nexport {\n normalizeAnchor,\n identityTupleKey,\n graphNodeId,\n anchorGraphNode,\n recordGraphNode,\n} from './identity/index'\n// 389 D-13: the exercised-anchors walk, promoted from the CLI curation tail so the agent\n// cluster function, 390's recurrence window and the tail all consume ONE spelling.\nexport {\n actionRefs,\n classifySubActionRoute,\n elementAnchor,\n exercisedAnchors,\n resolvedElementEvidence,\n uniqueAnchors,\n} from './identity/exercised-anchors'\nexport type {\n ClassifiedRoute,\n ResolvedElementEvidence,\n} from './identity/exercised-anchors'\nexport { supersessionKey } from './identity/supersession-key'\nexport {\n screenIdentityHash,\n screenStateHash,\n relevantEnvDigest,\n computeCacheKey,\n computeToolSchemaDigest,\n} from './determinism/index'\nexport type {\n CacheKey,\n CacheableStepInput,\n NonCacheableStepInput,\n RedactedEnvVar,\n ToolSurfaceEntry,\n} from './determinism/index'\n\n// 367 D-13: one shared version-guard rule for every versioned document contract.\nexport { createVersionGuard, VersionGuardError } from './versioning/create-version-guard'\nexport type {\n MigrationRegistry,\n VersionGuardConfig,\n} from './versioning/create-version-guard'\n\n// 314 async-seam\nexport { asRunId } from './run/index'\nexport { MODEL_USAGE_ROLES, ModelUsageRoleSchema, ModelUsageIdentitySchema, ModelUsageSchema } from './run/model-usage'\nexport type { ModelUsageRole, ModelUsage, ModelTokenUsage, ModelUsageObservations } from './run/model-usage'\nexport { RunModelSummarySchema } from './functions/runs'\nexport type { RunModelSummary } from './functions/runs'\n// 431 D-06: the runs.overview read's contracts.\nexport {\n RUN_OVERVIEW_TEXT_MAX_CODE_POINTS,\n RUN_OVERVIEW_TRUNCATION_INDICATOR,\n RunOverviewArtifactAddressSchema,\n RunOverviewAriaSchema,\n RunOverviewBriefAddressSchema,\n RunOverviewBriefSchema,\n RunOverviewEvidenceAddressSchema,\n RunOverviewLearnedSchema,\n RunOverviewProjectionSchema,\n RunOverviewRecordingSchema,\n RunOverviewRecordSchema,\n RunOverviewScreenshotSchema,\n RunOverviewStepEvidenceSchema,\n RunOverviewStepSchema,\n RunOverviewTestSchema,\n RunOverviewTextSchema,\n RunsOverviewInputSchema,\n} from './functions/runs-overview'\nexport type {\n RunOverviewArtifactAddress,\n RunOverviewAria,\n RunOverviewBriefAddress,\n RunOverviewEvidenceAddress,\n RunOverviewLearned,\n RunOverviewProjection,\n RunOverviewRecord,\n RunOverviewRecording,\n RunOverviewScreenshot,\n RunOverviewStep,\n RunOverviewStepEvidence,\n RunOverviewTest,\n RunOverviewText,\n RunsOverviewInput,\n} from './functions/runs-overview'\nexport {\n EVIDENCE_REF_PREFIXES,\n EvidenceArtifactRefSchema,\n} from './ids/artifact-ref'\nexport type { EvidenceRefPrefix, EvidenceArtifactRef } from './ids/artifact-ref'\nexport {\n RECORDING_STATES,\n RECORDING_CONTENT_TYPES,\n RECORDING_REF_PREFIX,\n RecordingRefSchema,\n RecordingEntrySchema,\n} from './run/recording'\nexport type {\n RecordingState,\n RecordingContentType,\n RecordingRef,\n RecordingEntry,\n} from './run/recording'\nexport {\n EVIDENCE_KINDS,\n NETWORK_BODY_CONTENT_TYPES,\n NETWORK_BODY_MAX_BYTES,\n EVIDENCE_ABSENCE_REASONS,\n RUN_EVIDENCE_DOCUMENT_SCHEMA_VERSION,\n EvidenceKindSchema,\n EvidenceAbsenceReasonSchema,\n EvidenceDocumentSchema,\n EvidenceEntrySchema,\n ConsoleEvidenceRecordSchema,\n NetworkEvidenceRecordSchema,\n A11yEvidenceRecordSchema,\n ConsoleEvidenceDocumentSchema,\n NetworkEvidenceDocumentSchema,\n A11yEvidenceDocumentSchema,\n AriaEvidenceDocumentSchema,\n VariablesEvidenceDocumentSchema,\n VariableSnapshotSchema,\n} from './run/evidence'\nexport type {\n EvidenceKind,\n NetworkBodyContentType,\n EvidenceAbsenceReason,\n EvidenceDocument,\n EvidenceEntry,\n AriaEvidenceEntry,\n StepEvidenceEntries,\n VariableSnapshot,\n} from './run/evidence'\nexport {\n BUNDLE_ID_HASH_SUFFIX_LENGTH,\n BUNDLE_SLUG_MAX_LENGTH,\n asRecordId,\n asEvidenceToken,\n bundleSlug,\n computeBundleIdentityHash,\n computeStepSequenceSignature,\n deriveDiscriminantKey,\n mintBundleId,\n slugBranch,\n} from './ids/index'\nexport {\n LosslessServedBriefError,\n LosslessServedBriefSchema,\n SERVED_BRIEF_PROOF_SCHEMA_VERSION,\n computeBriefDigest,\n guardLosslessServedBrief,\n} from './brief/index'\n// 387 KREV-02 D-13/D-14: the serve-time retrieval trace, persisted beside ServedBrief.\nexport {\n RETRIEVAL_TRACE_LEGS,\n RETRIEVAL_TRACE_SCHEMA_VERSION,\n ServedRetrievalTraceV1Schema,\n TRACE_TRUNCATION_TOP_K,\n TraceLineSchema,\n} from './brief/index'\n// 407 TRST-01 D-13/D-17: the closed retrieval-rung vocabulary and its recorded form, plus the\n// durable D-16 marker that says no knowledge reader was bound at all. One spelling for the\n// runner that records, the banner that prints and the doctor row that grades.\nexport {\n NO_KNOWLEDGE_READER_TRUNCATION,\n RETRIEVAL_RUNGS,\n RETRIEVAL_RUNG_REASONS,\n RecordedRetrievalRungSchema,\n} from './brief/index'\nexport { CURRENT_HANDOFF_SCHEMA_VERSION } from './handoff/index'\n// 361 D-19: the one handoff version guard (SESSION-05 read-side discipline).\nexport { guardCompletedRunHandoff, HandoffVersionError, HANDOFF_MIGRATIONS } from './handoff/index'\n// 388 D-09/D-11/D-14/D-15: the chain-terminal notification record and THE one chip-status\n// vocabulary. Both are minted here rather than beside a consumer because each has several —\n// the notification row is read by chat and by the dashboard, and the chip words are spoken by\n// the bus, the read op and the CLI's summary line.\n// 391 D-16/D-18: the per-run digest's read-time contract, minted beside the frozen row it\n// deliberately does not widen. Nothing persists a digest — it is composed live, keyed by runId,\n// which is what makes \"exactly one digest per run\" structural rather than throttled.\nexport {\n CURATION_SNAPSHOT_WITHHELD_REASONS,\n CURRENT_RUN_NOTIFICATION_SCHEMA_VERSION,\n CurationSnapshotWithheldSchema,\n POST_PROCESSING_CHIP_STATUSES,\n POST_PROCESSING_DETAIL_STAGES,\n POST_PROCESSING_SKIP_REASON_WORDS,\n POST_PROCESSING_SKIP_REASONS,\n PostProcessingSkippedSchema,\n PostProcessingStageDetailSchema,\n RunDigestCandidateReportSchema,\n RunDigestChainOutcomesSchema,\n RunDigestMarkChangeSchema,\n RunDigestQuarantineReportSchema,\n RunDigestSchema,\n RUN_NOTIFICATION_VIEW_STATUSES,\n RunNotificationSchemaError,\n RunsDigestInputSchema,\n guardRunNotification,\n isPostProcessingChipStatus,\n toRunNotificationView,\n} from './notification/index'\nexport type {\n CurationSnapshotWithheldReason,\n PostProcessingChipStatus,\n PostProcessingChips,\n PostProcessingDetailStage,\n PostProcessingSkipReason,\n PostProcessingStageDetail,\n PostProcessingStatus,\n RunDigest,\n RunDigestCandidateReport,\n RunDigestChainOutcomes,\n RunDigestMarkChange,\n RunDigestQuarantineReport,\n RunNotification,\n RunNotificationOutcome,\n RunNotificationStageStatus,\n RunNotificationStages,\n RunNotificationVerdictSummary,\n RunNotificationView,\n RunNotificationViewStages,\n RunNotificationViewStatus,\n RunsDigestInput,\n} from './notification/index'\nexport type { RunStatus, ExecutionContext, RunId } from './run/index'\nexport {\n CURATION_BREAKDOWN_BUCKETS,\n CURATION_BUCKET_PRECEDENCE,\n CURATION_SNAPSHOT_SCHEMA_VERSION,\n CurationBucketSchema,\n CurationSnapshotChangeSchema,\n CurationSnapshotRowSchema,\n CurationBreakdownSchema,\n CurationSnapshotSchema,\n} from './notification/curation-snapshot'\nexport type {\n CurationBucket,\n CurationSnapshotChange,\n CurationSnapshotRow,\n CurationBreakdown,\n CurationSnapshot,\n} from './notification/curation-snapshot'\nexport type {\n ArtifactRef,\n BundleDiscriminant,\n BundleIdentityCore,\n BundleIdentityInput,\n EvidenceToken,\n RecordId,\n} from './ids/index'\nexport type { Verdict, VerdictClass, VerdictEvidence } from './verdict/index'\nexport { VERDICT_CLASSES, isVerdictClass } from './verdict/index'\n// 390 D-01/D-03/D-11/D-12: the committed quarantine ledger's event contract and the state\n// vocabulary every quarantine surface speaks — the fold, the list verb, the entity card and the\n// recurrence clause's ladder arms. `'expired'` is a COMPUTED state, never an event.\nexport {\n CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION,\n QUARANTINE_ENTRY_STATE_NAMES,\n QUARANTINE_EVENT_KINDS,\n QUARANTINE_LEDGER_MIGRATIONS,\n QUARANTINE_UNASSIGNED_OWNER,\n QuarantineLedgerVersionError,\n guardQuarantineLedgerEvent,\n hasQuarantineEventShape,\n isQuarantineEventKind,\n quarantineAppliesToTest,\n} from './quarantine/index'\nexport type {\n QuarantineAppliedEntry,\n QuarantineEnteredEvent,\n QuarantineEntryState,\n QuarantineEntryStateName,\n QuarantineEventKind,\n QuarantineLadderState,\n QuarantineLedgerEvent,\n QuarantineOwner,\n QuarantineReleasedEvent,\n QuarantineRenewedEvent,\n QuarantineSnapshotMatch,\n} from './quarantine/index'\n// 390 D-12/D-13: the three verbs' wire contract and the port they dispatch through. Minted\n// here rather than beside the op specs because two packages consume it and neither may import\n// the other — `agent` declares the specs against these validators, knowledge-local implements\n// the port over the committed ledger. `release`'s no-entry and `add`'s renewed are result\n// ARMS, never throws.\nexport {\n QuarantineAddInputSchema,\n QuarantineAddOutputSchema,\n QuarantineEntrySchema,\n QuarantineListInputSchema,\n QuarantineListOutputSchema,\n QuarantineReleaseInputSchema,\n QuarantineReleaseOutputSchema,\n} from './quarantine/index'\nexport type {\n QuarantineAddInput,\n QuarantineAddOutput,\n QuarantineListInput,\n QuarantineListOutput,\n QuarantineOperationsPort,\n QuarantineReleaseInput,\n QuarantineReleaseOutput,\n} from './quarantine/index'\n// 389 D-05/D-07/D-09/D-10: the verdict truth vocabulary — sentence parts joined to Verdict\n// by perTest (beside, never inside the frozen §A9 union), the version-guarded run analysis\n// artifact, and the ONE resolved-verdict accessor every consumer routes through. 390 FLAK-01\n// adds the fingerprint's INPUT stage (`failingStepOf`/`errorTextOf`) beside the frozen recipe,\n// hoisted out of agent so knowledge-local's recurrence windows can key the same way.\nexport {\n admitAnalysisArtifactForRun,\n ANALYSIS_FILE,\n ANALYSIS_MIGRATIONS,\n AnalysisVersionError,\n CURRENT_ANALYSIS_SCHEMA_VERSION,\n errorTextOf,\n failingStepOf,\n failureFingerprint,\n guardRunAnalysisArtifact,\n QUOTE_SEARCHED_STEP_FIELDS,\n QUOTE_SEARCHED_TEST_OUTCOME_FIELDS,\n resolveRunVerdicts,\n resolveVerdictMisdirection,\n searchedQuoteTexts,\n searchedTestOutcomeTexts,\n validateAnalysisAgainstHandoff,\n VerdictSentencePartsSchema,\n // 393 D-13: the sibling anchor-coverage recipe (gate 3), beside the frozen failure recipe.\n // `testFingerprintElements` is the ONE walk both sides of gate 3's comparison go through —\n // knowledge-local's suite fold and the agent's draft side alike (393-06).\n ACTION_ANCHOR_FINGERPRINT_VERSION,\n ASSERT_ACTION_TYPES,\n actionAnchorElement,\n actionAnchorSequence,\n testFingerprintElements,\n} from './verdict/index'\nexport type {\n ActionAnchorElementInput,\n FingerprintEvidenceLike,\n AnalysisArtifactAdmission,\n AnalysisValidationOptions,\n AnalysisValidationReject,\n AnalysisValidationResult,\n FailureFingerprintInput,\n ResolvedMisdirection,\n RunAnalysisArtifact,\n VerdictGroundingQuote,\n VerdictSentenceParts,\n} from './verdict/index'\n// 422 D-17/D-19/D-20: the circularity guard's evidence vocabulary. `memoryOnPath` membership is\n// derived by CODE from the run's own served briefs and the per-record cross-check is folded\n// under one law, so a producer composing evidence and the validator checking it cannot drift.\nexport {\n aggregateMisdirectionEvidence,\n deriveMemoryOnPath,\n deriveMemoryOnPathSites,\n guardMisdirectionEvidence,\n MEMORY_ON_PATH_TRUSTS,\n MemoryOnPathEntrySchema,\n memoryOnPathTrustOf,\n MISDIRECTION_BACKINGS,\n MISDIRECTION_ROOT_POSTURES,\n misdirectionSourceDigest,\n MisdirectionEvidenceError,\n MisdirectionEvidenceSchema,\n MisdirectionRecordResultSchema,\n} from './verdict/index'\nexport type {\n MemoryOnPathEntry,\n MemoryOnPathSite,\n MemoryOnPathTrust,\n MisdirectionAggregate,\n MisdirectionAggregationInput,\n MisdirectionBacking,\n MisdirectionEvidence,\n MisdirectionRecordResult,\n MisdirectionRootPosture,\n MisdirectionSamples,\n} from './verdict/index'\nexport type {\n DeltaEnvelope,\n CompareAndSet,\n BundleDraft,\n CurationAuthorship,\n CurationAuthorshipPath,\n CurationFallbackReason,\n Delta,\n DeltaKind,\n DeltaOrigin,\n} from './delta/index'\n// 387 D-17: runtime projections of the §7.3 discriminant and origin vocabularies, so a\n// proposal boundary can name what a delta is without re-declaring the union.\nexport { DELTA_KINDS, DELTA_ORIGINS } from './delta/index'\nexport type {\n BriefLine,\n CautionLine,\n LosslessServedBrief,\n LosslessServedBriefProofV1,\n ReadTrace,\n RecordedRetrievalRung,\n RetrievalRung,\n RetrievalRungReason,\n RetrievalTraceLeg,\n ServedAdmissionEvent,\n ServedAdmissionSurface,\n ServedBrief,\n ServedPromptTurn,\n ServedRetrievalTraceV1,\n TraceLine,\n} from './brief/index'\nexport type {\n CacheMissReason,\n CompletedRunHandoff,\n CycleEvidence,\n DeclaredModelProfile,\n LocalEffectEvidence,\n InterpolatedVariable,\n ModelCallRecord,\n ModelIdentity,\n PerTestOutcome,\n PlanningFailureEvidence,\n SamplingParams,\n StagnationClass,\n StagnationEvidence,\n StepEvidence,\n StepPlanSource,\n SubActionEvidence,\n ToolExchangeEvidence,\n} from './handoff/index'\nexport { actedPair } from './handoff/index'\n// 360 termination-verb & AI-assertion evidence vocabulary (EXEC-05/EXEC-07)\nexport type {\n AiJudgmentEvidence,\n AssertValueEvidence,\n AssertValueOp,\n ReportedValueEvidence,\n TerminationEvidence,\n VerdictSource,\n} from './handoff/index'\n// 2026-10-07 (436-04, D-11..D-13): the per-step limit stop and usage.\nexport type { CompoundInputCount, LimitStopEvidence, StepLimitUsage } from './handoff/index'\nexport { formatLimitStopReason, LIMIT_STOP_EVIDENCE_KEYS, STEP_LIMIT_USAGE_KEYS } from './handoff/index'\nexport type {\n CitationSource,\n ConditionCitation,\n ConditionEnding,\n ConditionFileCheck,\n ConditionGuard,\n ConditionNeed,\n ConditionRecord,\n ConditionVerdict,\n ConditionVerdictsEvidence,\n OpenDialogAccount,\n} from './handoff/index'\nexport {\n CITATION_SOURCES,\n CONDITION_ENDINGS,\n CONDITION_GUARDS,\n CONDITION_NEEDS,\n CONDITION_RECORD_KEYS,\n CONDITION_VERDICTS,\n CONDITION_VERDICTS_EVIDENCE_KEYS,\n stepOutcomeUnproven,\n} from './handoff/index'\n// 2026-10-07 (436-10, D-19..D-23): operation-specific evidence on the triggering action.\nexport type {\n ClipboardEvidence,\n DownloadEvidence,\n OperationCaptureAvailability,\n OperationEvidence,\n} from './handoff/index'\nexport {\n CLIPBOARD_EVIDENCE_KEYS,\n DOWNLOAD_EVIDENCE_KEYS,\n OPERATION_CAPTURE_AVAILABILITY_KEYS,\n} from './handoff/index'\n// 2026-10-08 (437-02, D-05): what an action's input delivered, on the same evidence.\nexport type {\n FillVerdict,\n InputEvidence,\n InputPath,\n SubmitOutcome,\n SubmitReason,\n} from './handoff/index'\nexport { INPUT_EVIDENCE_KEYS } from './handoff/index'\n\n// 358 working-memory vocabulary (WM-01)\nexport type { WorkingMemoryEntry } from './memory/index'\nexport { workingMemoryEntrySchema } from './memory/index'\n\n// 315 run+agent DTOs\nexport type { RunSession } from './run/index'\n// 403 D-05/D-08: live-view frame vocabulary — frames as data, capability declared per handle.\nexport { LIVE_FRAME_END_REASONS, LIVE_STREAM_KINDS, LiveStreamDeclarationSchema } from './run/index'\n// 403 D-01..D-04: the liveUrl capability-token vocabulary (types + refusal names only).\nexport { LIVE_URL_REFUSAL_REASONS, LIVE_URL_SCOPE, LIVE_VIEW_SUBJECT_KINDS } from './run/index'\nexport type {\n LiveUrlClaims,\n LiveUrlRefusalReason,\n LiveUrlSigner,\n LiveUrlVerdict,\n LiveViewSubject,\n LiveViewSubjectKind,\n LiveViewSubjectRef,\n} from './run/index'\nexport type {\n LiveFrame,\n LiveFrameEndReason,\n LiveFrameMetadata,\n LiveFrameSubscription,\n LiveStreamDeclaration,\n LiveStreamKind,\n} from './run/index'\n// 363 D-08: run-artifact payload type family (relocated from core/src/artifacts).\nexport { RUN_ARTIFACT_SCHEMA_VERSION } from './run/index'\nexport type {\n ArtifactRecord,\n JsonArray,\n JsonObject,\n JsonPrimitive,\n JsonValue,\n RunArtifactConfigSnapshot,\n RunArtifactFinalizeInput,\n RunArtifactKind,\n RunArtifactMetadata,\n RunArtifactPayload,\n RunArtifactReporterContext,\n RunArtifactRuntimeSnapshot,\n RunArtifactStageInput,\n RunArtifactSuiteMemberSnapshot,\n RunArtifactSuiteSourceSnapshot,\n RunArtifactTerminalError,\n RunArtifactTestSourceSnapshot,\n RunArtifactTestsSourceSnapshot,\n} from './run/index'\n// The bus schema version and the session vocabulary\nexport { CURRENT_BUS_SCHEMA_VERSION, RUN_EVENT_TYPES } from './run/index'\n// 361 D-10/D-09: pure masked payload projections (SESSION-03 projection layer).\nexport {\n maskPayloadStrings,\n maskPayloadTree,\n projectStepFinalized,\n projectSubActionRecorded,\n projectTestFinished,\n // 363 D-01 parity appends: hook lifecycle + retry projections (masked at the sink).\n projectHookStarted,\n projectHookFinished,\n projectTestRetryScheduled,\n} from './run/index'\nexport type { MaskFn } from './run/index'\n// 402-04 D-10/D-14: handle identity — the TOTAL event-scope classification, the one filter\n// predicate, the composite id spelling and the additive runStarted roster reader.\nexport {\n HANDLE_ID_SEPARATOR,\n RUN_EVENT_SCOPE,\n RUN_EVENT_SCOPE_TYPES,\n handleId,\n handleRosterOf,\n memberIndexOf,\n parseHandleId,\n parseHandleParam,\n passesHandleFilter,\n} from './run/index'\nexport type { HandleParamParse, RunEventScope } from './run/index'\nexport type {\n MemberTestOutcome,\n RunCompletion,\n RunEvent,\n RunEventEnvelope,\n RunEventPayload,\n RunEventType,\n RunStartedPayload,\n RunFinishedPayload,\n // 404-01 (D-09): the ratified post-processing posture union `runFinished.disposition` carries.\n PostProcessingDisposition,\n VerdictPayload,\n RunWarningPayload,\n RunErrorPayload,\n HeartbeatPayload,\n TestStartedPayload,\n TestFinishedPayload,\n StepStartedPayload,\n StepFinalizedPayload,\n SubActionRecordedPayload,\n ChipEventPayload,\n // 363 D-01 parity appends: hook lifecycle + retry payloads.\n HookStartedPayload,\n HookFinishedPayload,\n TestRetryScheduledPayload,\n} from './run/index'\nexport type { Job, JobKind, JobStatus, JobConclusionKind, JobId } from './job/index'\nexport { asJobId, isJobKind, jobSchema } from './job/index'\n// 385 plan 02 (JOBQ-01/JOBQ-02/JOBQ-05): the agent job queue's DTO vocabulary.\nexport type {\n ChainedJobRequest,\n JobCheckpointEnvelope,\n JobEnqueueRequest,\n JobHandlerOutcome,\n} from './job/index'\nexport {\n JOB_CHECKPOINT_SCHEMA_VERSION,\n chainedJobRequestSchema,\n jobCheckpointEnvelopeSchema,\n jobEnqueueRequestSchema,\n jobHandlerOutcomeSchema,\n // 393 D-20 (WTST-06): the analyze-run payload mirror, validated producer-side at enqueue.\n AnalyzeRunPayloadSchema,\n} from './job/index'\nexport type { AnalyzeRunPayload } from './job/index'\nexport type { Patch, FileChange, Hunk, PatchStatus, PatchId } from './patch/index'\nexport { asPatchId, patchSchema } from './patch/index'\n// 395 D-01/D-17 · CFGM-01/03/04: the config editor's DTOs, and THE diff/digest primitive both\n// halves of a config change call — construction in `agent`, the write in `cli`. The primitive is\n// exported from here and from nowhere else for the reason its own header states: two recipes for\n// one digest contract is 394's CR-02 defect class, and this phase's whole freshness guarantee is\n// the two halves agreeing byte for byte.\nexport {\n CONFIG_BLOCKED_REASONS,\n CONFIG_DIFF_OUTCOMES,\n CONFIG_FILE_CHANGE_KINDS,\n CONFIG_HOOK_RUNTIMES,\n CONFIG_CHANGE_REFUSAL_REASONS,\n CONFIG_REFERENCE_KINDS,\n CONFIG_SET_DEFAULT_HOOKS_FILE,\n CONFIG_SET_GITIGNORE,\n CROSS_BOUNDARY_REASONS,\n ConfigAuthSetInputSchema,\n ConfigChangeFileSchema,\n ConfigChangeOutputSchema,\n ConfigFieldSetInputSchema,\n ConfigHookAddInputSchema,\n ConfigProjectScaffoldInputSchema,\n ConfigTargetCreateInputSchema,\n ConfigTargetEditInputSchema,\n EmptyConfigDiffFileError,\n MAX_CONFIG_REFERENCE_LENGTH,\n SECRET_ADJACENT_CONFIG_FIELDS,\n UnrenderableConfigDiffError,\n base64Decode,\n base64Encode,\n enumerateConfigFileSet,\n isLegalConfigReference,\n isSecretAdjacentConfigField,\n renderConfigDiff,\n utf8Decode,\n utf8Encode,\n} from './config-mutation/index'\nexport type {\n ConfigAuthSetInput,\n ConfigBlockedReason,\n ConfigChangeFile,\n ConfigChangeOutput,\n ConfigChangeRefusalReason,\n ConfigDiffChanged,\n ConfigDiffFileInput,\n ConfigDiffOutcome,\n ConfigDiffResult,\n ConfigDiffUnchanged,\n ConfigFieldSetInput,\n ConfigFileChangeKind,\n ConfigFileDigest,\n ConfigHookAddInput,\n ConfigHookRuntime,\n ConfigProjectScaffoldInput,\n ConfigReferenceKind,\n ConfigTargetCreateInput,\n ConfigTargetEditInput,\n CrossBoundaryReason,\n SecretAdjacentConfigField,\n} from './config-mutation/index'\n\n// 316 seam helpers\nexport type { RecordedActionResult } from './result/index'\nexport type { VerifierVerdict, Decision } from './handoff/index'\nexport type { BundleKind, FactSubtype, OriginStage } from './delta/index'\nexport { toRecordedActionResult } from './result/index'\nexport { validRecordingAnnotation, validRecordedAnnotation } from './result/index'\nexport type { RecordingAnnotationWitness } from './result/index'\nexport type { IdempotentNoopMeta } from './result/index'\nexport { actionDidNotFail, readIdempotentNoopMeta } from './result/index'\nexport type { TargetIdentity, TargetMismatchReason, TargetRefusalMeta } from './result/index'\nexport { readTargetRefusalMeta, TARGET_IDENTITY_KEYS, TARGET_REFUSAL_KEYS } from './result/index'\nexport type { BindingOutcome, BindingOutcomeMeta } from './result/index'\nexport { BINDING_OUTCOME_KEYS, readBindingOutcomeMeta } from './result/index'\nexport { computeEvidenceToken } from './ids/index'\n\n// 338 reader DTOs (PORT-03)\nexport type { IndexEntry, RecordBody, BriefBlock, CautionBlock, ProcedureMatch } from './reader/index'\n// 381 authoring-brief contracts (D-13/D-16/ABRF-01)\nexport type { AuthoringBrief, CoverageMap, ExemplarTest } from './reader/index'\nexport type { SearchOptions, ReadOptions, BuildRange, CanaryOutcome, CanaryAblationEvidence } from './reader/index'\nexport {\n createServingAdmissionState,\n inspectServingRecord,\n servingClusterKey,\n servingRecordMetadata,\n tryAdmitServingRecord,\n} from './reader/index'\nexport type {\n ServingAdmissionDecision,\n ServingAdmissionInput,\n ServingAdmissionRejectionReason,\n ServingAdmissionState,\n ServingRecordMetadata,\n} from './reader/index'\n\n// 374 D-03/BNDL-03: pure event vocabulary and derivations stay storage-neutral.\nexport {\n BundleOutcomeEventSchema,\n dedupeEvents,\n eventDedupKey,\n survivingOutcomeEvents,\n} from './knowledge/index'\nexport type { BundleOutcomeEvent, OriginClass } from './knowledge/index'\nexport {\n EVIDENCE_INCOMPLETE_ALPHA_DISCOUNT,\n ORIGIN_PRIORS,\n SERVING_ATTRIBUTION_WEIGHT,\n foldBundleTrust,\n} from './knowledge/index'\nexport type { BundleStatus, DerivedTrustState } from './knowledge/index'\nexport { guardTrustPriorTable } from './knowledge/trust-fold'\nexport type { TrustPriorTable } from './knowledge/trust-fold'\nexport {\n INSPECT_RECORD_VIEW_SCHEMA_VERSION,\n RECORD_CHANGE_SCHEMA_VERSION,\n InspectFilterSchema,\n InspectRecordViewSchema,\n RecordChangeSchema,\n guardInspectRecordView,\n guardRecordChange,\n} from './knowledge/index'\nexport type {\n InspectFilter,\n InspectRecordView,\n RecordChange,\n} from './knowledge/index'\nexport {\n BIMODAL_GAP_THRESHOLD,\n BIMODAL_MIN_MODE_N,\n CI_SEPARATION_Z,\n CUSUM_DECISION_H,\n CUSUM_SLACK_K,\n DRIFT_RELATIVE_THRESHOLD,\n DRIFT_SIGMA_K,\n KIND_CV_FLOOR,\n KIND_DEFAULT_CV,\n MEASUREMENT_MIN_N,\n MULTIMODAL_TRAILING_BUILDS,\n SHRINKAGE_PSEUDO_N,\n decideMeasurementDrift,\n foldMeasurements,\n measurementBaselineSchema,\n measurementObservationSchema,\n shrunkSigma,\n} from './knowledge/index'\nexport type {\n MeasurementBaseline,\n MeasurementObservation,\n} from './knowledge/index'\nexport { GATE_SET_VERDICT_WORDS, evaluatePromotionGate } from './knowledge/index'\nexport type {\n PromotionGateHoldReason,\n PromotionGateInput,\n PromotionGatePosture,\n ResolvedPromotionGatePosture,\n UnavailablePromotionGatePosture,\n GateSetVerdictWord,\n PromotionJudgePosture,\n PromotionCanaryPosture,\n PromotionPostureScope,\n PromotionGateSetCounts,\n PromotionGateObservation,\n PromotionGateVerdict,\n} from './knowledge/index'\nexport {\n COLD_START_MAX_BUDGET_FRACTION,\n COLD_START_MAX_RECORDS,\n COLD_START_TRUST_DISCOUNT,\n LOWER_TRUST_PATH_DISCOUNT,\n GATE2_DEFAULT_STALE_CONFIRMATIONS,\n GATE2_DEFAULT_MAX_LOWER_TRUST_PER_SCOPE,\n applyColdStartSubCap,\n isVettedCandidate,\n} from './knowledge/index'\nexport type {\n ColdStartBudgetEntry,\n VettedCandidateInput,\n} from './knowledge/index'\nexport {\n cautionRootCauseClassSchema,\n DISTILLED_OBSERVATION_SCHEMA_VERSION,\n distilledObservationSchema,\n guardDistilledObservation,\n} from './knowledge/distilled-observation'\nexport type {\n CautionRootCauseClass,\n DistilledObservation,\n} from './knowledge/distilled-observation'\nexport {\n ArtifactsIndexSchema,\n BUNDLE_SCHEMA_VERSION,\n BundleManifestSchema,\n BundleProvenanceSchema,\n BundleRelationsSchema,\n computeMutableStateHash,\n deriveEvidenceToken,\n guardArtifactsIndex,\n guardBundleManifest,\n guardBundleProvenance,\n guardBundleRelations,\n verifyManifestIdentity,\n} from './knowledge/index'\nexport type {\n ArtifactsIndex,\n BundleManifest,\n BundleProvenance,\n BundleRelation,\n BundleRelations,\n MutableStateHashInput,\n} from './knowledge/index'\nexport {\n emitRecordMarkdown,\n parseRecordMarkdown,\n renderEmbeddingInput,\n screenStateSnapshotRelPath,\n} from './knowledge/index'\nexport type { RecordFrontmatter } from './knowledge/index'\n\n// 387 KREV-01 D-17/D-19: the review-verb read contracts every 387-06/387-08 op imports rather than\n// re-minting. 2026-10-01 (432-17, D-05): with the direct knowledge change contracts that replaced the\n// propose+apply seam (`knowledge/change.ts`); the proposal payload and its apply contracts are gone.\nexport {\n BRIEF_WHY_NO_TRACE_REASONS,\n BRIEF_WHY_RESULT_KINDS,\n BriefWhyInputSchema,\n BriefWhyResultSchema,\n DeltaSchema,\n FORGET_RECEIPT_SCHEMA_VERSION,\n ForgetReceiptV1Schema,\n ForgetTargetRefSchema,\n KNOWLEDGE_CHANGE_VERBS,\n KNOWLEDGE_PROJECTIONS,\n KNOWLEDGE_REVIEW_VERBS,\n KnowledgeChangeIdSchema,\n KnowledgeChangeOperationIdSchema,\n KnowledgeAcceptInputSchema,\n KnowledgeAcceptChangeInputSchema,\n KnowledgeChangeOutputSchema,\n KNOWLEDGE_CHANGE_REFUSAL_REASONS,\n KnowledgeForgetInputSchema,\n KnowledgeForgetChangeInputSchema,\n KnowledgeRecordShowInputSchema,\n KnowledgeRecordShowOutputSchema,\n KnowledgeRecordShowResultSchema,\n KnowledgeRecordsDiffInputSchema,\n KnowledgeRecordsDiffOutputSchema,\n KnowledgeRecordsInspectInputSchema,\n KnowledgeRecordsInspectOutputSchema,\n KnowledgeRejectInputSchema,\n KnowledgeRejectChangeInputSchema,\n KnowledgeTargetRefSchema,\n MarkChangeStampSchema,\n TombstonedRecordSchema,\n} from './knowledge/index'\nexport type {\n BriefWhyInput,\n BriefWhyNoTraceReason,\n BriefWhyResult,\n BriefWhyResultKind,\n ForgetReceiptV1,\n ForgetTargetRef,\n KnowledgeAcceptInput,\n KnowledgeAcceptChangeInput,\n KnowledgeChangeVerb,\n KnowledgeChangeOutput,\n KnowledgeChangeRefusalReason,\n KnowledgeForgetInput,\n KnowledgeForgetChangeInput,\n KnowledgeProjection,\n KnowledgeRecordShowInput,\n KnowledgeRecordShowOutput,\n KnowledgeRecordShowResult,\n KnowledgeRecordsDiffInput,\n KnowledgeRecordsDiffOutput,\n KnowledgeRecordsInspectInput,\n KnowledgeRecordsInspectOutput,\n KnowledgeRejectInput,\n KnowledgeRejectChangeInput,\n KnowledgeReviewVerb,\n KnowledgeTargetRef,\n MarkChangeStamp,\n} from './knowledge/index'\n\n// 381 procedure & guarded-replay contracts (D-03/D-04/D-06, Pitfall 6)\nexport { curatorTier } from './knowledge/curator-tier'\nexport type { CuratorTier, ProcedureParamType } from './knowledge/curator-tier'\nexport { plannerCapabilityTier } from './knowledge/planner-tier'\nexport type { PlannerCapability, PlannerCapabilityEvidence } from './knowledge/planner-tier'\nexport {\n PROCEDURE_BODY_SCHEMA_VERSION,\n parseProcedureBody,\n procedureJsonValueSchema,\n procedureStepKeys,\n serializeProcedureBody,\n} from './knowledge/procedure-steps'\nexport type {\n ProcedureBodyPayload,\n ProcedureGuardDescriptor,\n ProcedureGuardTarget,\n ProcedureJsonValue,\n ProcedureParameterSpec,\n ProcedureStepSpec,\n ProcedureValueSlot,\n} from './knowledge/procedure-steps'\nexport {\n EMPTY_PROCEDURE_BINDING_AVAILABILITY,\n procedureParameterFillability,\n} from './knowledge/procedure-fillability'\nexport type { ProcedureBindingAvailability } from './knowledge/procedure-fillability'\nexport {\n coerceProcedureBindingValue,\n procedureSourceBinding,\n} from './knowledge/procedure-binding-coercion'\nexport type { ProcedureSourceBinding } from './knowledge/procedure-binding-coercion'\nexport {\n COORDINATE_ACTION_KEYS,\n NON_REPLAYABLE_ACTION_TYPES,\n isReplayableActionShape,\n} from './action/replayability'\n\n// 384 function-layer contract vocabulary (D-13/D-16): the caller record and the seed op DTOs\n// surfaces type against under the import firewall. 2026-10-02 (432-39, D-10/D-12): the\n// capability-scope union is deleted.\nexport {\n FUNCTION_CALLER_ORIGINS,\n RUN_SUMMARY_SCHEMA_VERSION,\n RUN_DETAIL_SCHEMA_VERSION,\n RunSummarySchema,\n RunDetailSchema,\n RunTestDetailSchema,\n RunsListInputSchema,\n RunsGetInputSchema,\n RunsStartInputSchema,\n RunsEventsInputSchema,\n // 403 D-03: the runs.liveurl mint op's two contracts.\n RunsLiveUrlInputSchema,\n RunsLiveUrlResultSchema,\n // 428 D-07: the editor subject's mint op contracts.\n EditorLiveUrlInputSchema,\n EditorLiveUrlResultSchema,\n // 388 D-14: the chip-truth read op's two contracts, and the notification's wire shape.\n RunsPostProcessingInputSchema,\n RunNotificationViewSchema,\n PostProcessingStatusSchema,\n // 405 D-03: the run-detail read op's contracts.\n RunsDetailInputSchema,\n RunDetailMemberSchema,\n RunStepTokenUsageSchema,\n RunDetailStepSchema,\n RunDetailSubActionSchema,\n RunTokenTotalsSchema,\n RunDetailProjectionSchema,\n // 405-05 D-12/D-13: the artifact read op's two contracts.\n RunsArtifactInputSchema,\n RunsArtifactResultSchema,\n RunsEvidenceInputSchema,\n RunsEvidenceResultSchema,\n // 407 LERN-01/LERN-02 D-05: the `runs.knowledge` panel read's contracts.\n RunsKnowledgeInputSchema,\n RunKnowledgeBriefLineSchema,\n RunKnowledgeReadTraceSchema,\n RunKnowledgeCautionLineSchema,\n RunKnowledgeTraceSchema,\n RunKnowledgePlanSourceSchema,\n RunKnowledgeStepSchema,\n RunKnowledgeCanaryAttributionSchema,\n RunKnowledgeProjectionSchema,\n RUN_START_ACKNOWLEDGEMENT_SCHEMA_VERSION,\n RunStartAcknowledgementSchema,\n PlannerLimitsRecordSchema,\n RUN_EVENT_ENVELOPE_SCHEMA_VERSION,\n RunEventEnvelopeSchema,\n // 389 D-11: the analysis.get op's contracts.\n AnalysisGetInputSchema,\n AnalysisGetOutputSchema,\n AnalysisCitedArtifactSchema,\n AnalysisVerdictEvidenceSchema,\n AnalysisResolvedVerdictSchema,\n AnalysisSentenceSchema,\n AnalysisClusterViewSchema,\n // 422 D-17/D-19/D-20: a resolved verdict's circularity evidence, as a surface reads it.\n ANALYSIS_MISDIRECTION_REASONS,\n AnalysisMisdirectionRecordSchema,\n AnalysisMemoryOnPathEntrySchema,\n AnalysisVerdictMisdirectionSchema,\n projectVerdictMisdirection,\n KNOWLEDGE_BUNDLE_SUMMARY_SCHEMA_VERSION,\n KnowledgeBundleSummarySchema,\n KnowledgeBundlesListInputSchema,\n KnowledgeBundlesListOutputSchema,\n MASKED_RESOLVED_CONFIG_SCHEMA_VERSION,\n MaskedConfigEntrySchema,\n MaskedResolvedConfigSchema,\n ConfigGetInputSchema,\n // 393 D-01: the authoring.draft.verify op contracts (D-01 sketches the verb as\n // `verify_draft`; that spelling is unrepresentable — see functions/authoring.ts).\n AuthoringVerifyDraftInputSchema,\n AuthoringVerifyDraftOutputSchema,\n // 394 D-01: the authoring.draft.write op contracts and the closed loop-outcome vocabulary.\n AUTHORING_LOOP_OUTCOMES,\n AuthoringDraftWriteInputSchema,\n AuthoringDraftWriteOutputSchema,\n // 394 D-04: the stage-2 dedup refusal's payload and its two named continuations.\n AUTHORING_DEDUP_CONTINUATIONS,\n AuthoringDedupRefusalSchema,\n // 440 D-09: the stated-value refusal's payload and its two stages.\n AUTHORING_STATED_VALUE_STAGES,\n AuthoringStatedValueRefusalSchema,\n // 411 D-05..D-08: the stop payload a `stopped` invocation reports its verdict on.\n AUTHORING_REPAIR_ABANDONMENTS,\n AUTHORING_STOP_SIGNAL_CLASSES,\n AuthoringStopFailurePointSchema,\n AuthoringStopSchema,\n // 394-09 D-21: the authoring.draft.edit op contracts — the patch contract's second consumer.\n AuthoringDraftEditInputSchema,\n AuthoringDraftEditOutputSchema,\n // 394-07 D-12: the authoring.funnel.get op contracts and the closed window scope.\n AuthoringFunnelGetInputSchema,\n AuthoringFunnelGetOutputSchema,\n AuthoringFunnelWindowSchema,\n // 402-01 (D-06/D-13/D-15 · INVK-03): the authed run service's wire vocabulary.\n RUN_SERVICE_CONTRACT_VERSION,\n RUN_SERVICE_ERROR_CODES,\n RUN_SERVICE_REFUSED_REQUEST_FIELDS,\n RunServiceDenialBodySchema,\n RunServiceErrorBodySchema,\n RunServiceReadinessSchema,\n RunServiceReplayFloorBodySchema,\n RunServiceStartRequestSchema,\n} from './functions/index'\nexport type {\n FunctionCaller,\n FunctionCallerOrigin,\n RunSummary,\n RunDetail,\n RunTestDetail,\n RunsListInput,\n RunsGetInput,\n RunsStartInput,\n RunsEventsInput,\n RunsLiveUrlInput,\n RunsLiveUrlResult,\n EditorLiveUrlInput,\n EditorLiveUrlResult,\n RunsPostProcessingInput,\n RunStartAcknowledgement,\n // 405 D-03: the run-detail shapes — the port's rows and the op's projection over them.\n RunsDetailInput,\n RunDetailMember,\n RunStepTokenUsage,\n RunDetailStep,\n RunDetailSubAction,\n RunTokenTotals,\n RunDetailRows,\n RunDetailProjection,\n // 405-05 D-12/D-13/D-15: the artifact read's shapes and the port's three-arm lookup answer.\n RunsArtifactInput,\n RunsArtifactResult,\n RunsEvidenceInput,\n RunsEvidenceResult,\n // 407 D-05: the panel projection's inferred shapes.\n RunsKnowledgeInput,\n RunKnowledgeProjection,\n RunKnowledgeStep,\n RunKnowledgeTrace,\n RunKnowledgePlanSource,\n RunKnowledgeCanaryAttribution,\n EvidenceBlobLookup,\n EvidenceBlobPresence,\n RunDetailArtifactRef,\n AnalysisGetInput,\n AnalysisGetOutput,\n AnalysisCitedArtifact,\n AnalysisVerdictEvidence,\n AnalysisResolvedVerdict,\n AnalysisSentence,\n AnalysisClusterMemberRef,\n AnalysisClusterView,\n AnalysisMisdirectionReason,\n AnalysisMisdirectionRecord,\n AnalysisMemoryOnPathEntry,\n AnalysisVerdictMisdirection,\n KnowledgeBundleSummary,\n KnowledgeBundlesListInput,\n ConfigValueSource,\n MaskedConfigEntry,\n MaskedResolvedConfig,\n ConfigGetInput,\n AuthoringVerifyDraftInput,\n AuthoringVerifyDraftOutput,\n AuthoringDraftWriteInput,\n AuthoringDraftWriteOutput,\n AuthoringLoopOutcomeKind,\n AuthoringDedupContinuation,\n AuthoringDedupRefusal,\n AuthoringStatedValueRefusal,\n AuthoringStatedValueStage,\n AuthoringRepairAbandonment,\n AuthoringStop,\n AuthoringStopFailurePoint,\n AuthoringStopSignalClass,\n AuthoringDraftEditInput,\n AuthoringDraftEditOutput,\n AuthoringFunnelGetInput,\n AuthoringFunnelGetOutput,\n AuthoringFunnelWindow,\n RunServiceDenialBody,\n RunServiceErrorBody,\n RunServiceErrorCode,\n RunServiceReadiness,\n RunServiceReplayFloorBody,\n RunServiceStartRequest,\n} from './functions/index'\n\n// 393 (WTST-02, D-18/D-19): the keep-gate authoring vocabulary. `computeDraftDisposition` is\n// the ONE derivation of a draft's disposition — 394 consumes it and must not re-derive its own.\nexport {\n computeDraftDisposition,\n DRAFT_DISPOSITIONS,\n DRAFT_GATE_NAMES,\n DRAFT_STABILITY_RUNS_N,\n CURRENT_DRAFT_RECEIPT_SCHEMA_VERSION,\n AddsValueFindingSchema,\n DraftGateResultsSchema,\n DraftReceiptSchema,\n DraftRefSchema,\n GateRunRecordSchema,\n StepClassificationRowSchema,\n} from './authoring/index'\nexport type {\n AddsValueFinding,\n DraftDisposition,\n DraftDispositionInput,\n DraftGateBooleans,\n DraftGateName,\n DraftGateResults,\n DraftReceipt,\n DraftRef,\n GateRunRecord,\n StepClassificationRow,\n} from './authoring/index'\n\n// 432 D-06/D-07: the direct write of a final authored test. Which dispositions are written, what\n// the writer reports for one file, and the written-test receipt with the four gate booleans.\nexport {\n DRAFT_WRITTEN_DISPOSITIONS,\n DraftGateBooleansSchema,\n TEST_FILE_NOT_WRITTEN_REASONS,\n TEST_FILE_WRITE_REFUSALS,\n TestFileWriteSchema,\n WrittenTestReceiptSchema,\n draftDispositionWritesTarget,\n draftGateBooleans,\n} from './authoring/index'\nexport type {\n DraftWrittenDisposition,\n TestFileWrite,\n WrittenTestReceipt,\n} from './authoring/index'\n\n// 394 (WTST-07, D-20): the RFC-6902 `{thoughts, patches}` edit vocabulary and the pinned\n// editable-region fence. The CST applier in `core` is its only mutating consumer.\nexport {\n EDITABLE_POINTER_ROOTS,\n PATCH_OP_KINDS,\n PatchOpSchema,\n TestEditPatchSetSchema,\n isEditablePointer,\n parseJsonPointer,\n pointerRootOf,\n} from './authoring/index'\nexport type {\n EditablePointerRoot,\n PatchOp,\n PatchOpKind,\n TestEditPatchSet,\n} from './authoring/index'\n\n// 394-06 (WTST-01, D-05): the ONE envelope payload arm — a verified draft awaiting a human\n// decision — plus the ONE run-evidence coordinate vocabulary the router builds and the stop arm\n// carries.\nexport {\n AUTHORED_SUITE_SLUG_MAX_LENGTH,\n RUN_EVIDENCE_CHANNELS,\n RunEvidenceRefSchema,\n authoredSuiteTargetPath,\n} from './authoring/index'\nexport type {\n RunEvidenceChannel,\n RunEvidenceRef,\n} from './authoring/index'\n\n// 394-07 (WTST-05, D-13/D-15): the honesty funnel. `computeAuthoringFunnel` is the ONE\n// derivation of the four frozen stages, the keep rate and the acceptance-failure flag —\n// every caller renders what it returns and derives nothing. Today that is `authoring.funnel.get`.\n// `successFramingViolations` is the prohibition made mechanical: it is exported so a surface\n// composing a BLOCK around the funnel's line screens its own wording through the same words.\nexport {\n AUTHORING_FUNNEL_STAGES,\n AuthoringFunnelSchema,\n FUNNEL_MIN_DRAFTS_FLOOR,\n FUNNEL_PHRASES,\n FUNNEL_SUCCESS_FRAMING_LEXICON,\n FunnelSuccessFramingError,\n KEEP_RATE_CEILING,\n computeAuthoringFunnel,\n renderFunnelLine,\n successFramingViolations,\n} from './authoring/index'\nexport type {\n AuthoringFunnel,\n AuthoringFunnelInput,\n AuthoringFunnelStage,\n FunnelRenderParts,\n FunnelSideCounters,\n} from './authoring/index'\n\n// 394-07 (WTST-05, D-14): the mixed-verdict suite-stability read. PURE and it starts zero runs —\n// D-14 is read-side precisely so WTST-08's fan-out preview stays a number somebody can honour.\nexport {\n NEIGHBOUR_INSTABILITY_REASONS,\n SUITE_STABILITY_POSTURES,\n assessSuiteStability,\n suiteTestRef,\n} from './authoring/index'\nexport type {\n FlakyNeighbour,\n NeighbourInstabilityReason,\n SuiteNeighbourRow,\n SuiteStabilityAssessment,\n SuiteStabilityInput,\n SuiteStabilityPosture,\n} from './authoring/index'\n\n// 394-08 (WTST-08, D-03/D-10): the ONE fan-out arithmetic. `computeFanOutBound` is the only place\n// `initial N + K probes + final N` is added up — the dispatch confirm renders it and the finished\n// proposal reports against it, so a preview that understated what the loop would spend cannot be\n// produced by one surface disagreeing with the other.\nexport {\n ConsumedRunSchema,\n FAN_OUT_PHRASES,\n FAN_OUT_RUN_PURPOSES,\n FanOutBoundError,\n FanOutBoundInputSchema,\n FanOutBoundSchema,\n FanOutReportSchema,\n NO_RUNS_FAN_OUT_BOUND,\n buildFanOutReport,\n computeFanOutBound,\n renderFanOutPreview,\n renderFanOutReport,\n} from './authoring/index'\nexport type {\n ConsumedRun,\n FanOutBound,\n FanOutBoundInput,\n FanOutReport,\n FanOutRunPurpose,\n} from './authoring/index'\n\n// 394-09 (WTST-01, D-17): procedure-by-reference. A served procedure reaches a compiled draft as\n// an ordinary NL step written in the procedure's own anchor vocabulary, matched and replayed at run\n// time against the LIVE record — so a later procedure fix propagates and the committed test carries\n// no learned-shelf record id that supersession or collection could rot.\nexport { procedureStepVocabulary } from './authoring/index'\n\n// 387 ENTY-01/ENTY-02 — entity addressing: short-IDs, the agentqa:// URI scheme, the one\n// card shape and the two resolution unions.\nexport {\n ENTITY_CARD_MAX_ACTIONS,\n ENTITY_CARD_MAX_KEY_FACTS,\n ENTITY_DASHBOARD_ROUTES,\n ENTITY_DASHBOARD_ROUTE_GRAINS,\n ENTITY_EXACT_MATCH_SCORE,\n ENTITY_FIRST_ORDINAL,\n ENTITY_IDENTITY_FACT_LABELS,\n ENTITY_KINDS,\n ENTITY_NO_MATCH_REASONS,\n ENTITY_ORDINAL_MIN_DIGITS,\n ENTITY_RESOLUTION_MAX_CANDIDATES,\n ENTITY_STATUSES,\n ENTITY_URI_SCHEME,\n ENTITY_URI_SEGMENTS,\n ENTITY_URL_ROUTE,\n ENTITY_URL_ROUTE_PARAMS,\n ENTITY_URL_SLUG_MAX_LENGTH,\n SLUG_ADDRESSED_ENTITY_KINDS,\n ActionRefSchema,\n EntitiesGetInputSchema,\n EntitiesResolveInputSchema,\n EntityCardResolutionSchema,\n EntityCardSchema,\n EntityDescriptorSchema,\n EntityResolutionSchema,\n EntityUriSchema,\n KeyFactSchema,\n canonicalShortId,\n entityKindForUriSegment,\n entityTitleSlug,\n entityUriSegmentFor,\n formatEntityOrdinal,\n formatEntityUri,\n formatEntityUrl,\n formatOrdinalShortId,\n formatSlugShortId,\n isEntityKind,\n isEntityUri,\n isRoutedEntityKind,\n isSlugAddressedKind,\n parseEntityUri,\n parseShortId,\n} from './entity/index'\nexport type {\n ActionRef,\n EntitiesGetInput,\n EntitiesResolveInput,\n EntityCard,\n EntityCardResolution,\n EntityDashboardRoute,\n EntityDashboardRouteGrain,\n EntityDescriptor,\n EntityKind,\n EntityNoMatchReason,\n EntityResolution,\n EntityStatus,\n EntityStatusFor,\n EntityUriSegment,\n EntityUrlInput,\n KeyFact,\n ParsedEntityUri,\n ParsedShortId,\n} from './entity/index'\n\n// 342 safety contracts\n// 2026-10-15 (441-45, D-12/D-15): the guardrail policy schema, the masking context, the scan, the\n// content origin and the hook results are deleted; the risk tier and the disclosure scrub remain.\n// 2026-10-01 (432-18, D-14/D-15/D-22): the standing-grant ledger's event vocabulary and guards are\n// deleted with the ledger. `STANDING_APPROVAL_SCOPE` moved to `trust-credential.ts` (432-18) and was\n// deleted with the MCP bearer credential that carried it (432-21, D-12).\n// 2026-10-02 (432-42, D-12): the scope key set (391-11) is deleted with its module; no caller,\n// credential or projection ranges it any more.\n// 401-15 (WR-01 / T-401-G5 / T-401-G6): the disclosure scrub. 2026-10-02 (432-42, D-14): the\n// descriptor field it was written for and the per-op disclosure are deleted; the production refusal\n// sentence (`config/production.ts`) is the composition that applies it now.\nexport {\n DISCLOSURE_FRAGMENT_MAX_LENGTH,\n DISCLOSURE_REPLACEMENT_CHARACTER,\n DISCLOSURE_TEXT_MAX_LENGTH,\n DISCLOSURE_TRUNCATION_MARK,\n scrubDisclosureFragment,\n scrubDisclosureText,\n} from './safety/index'\n// 2026-10-01 (432-19, D-15): the remedy vocabulary, the execution-policy verdict and result, and the\n// standing-approval contract are deleted with the gate. A refusal is a plain reason.\n// 2026-10-01 (432-18): the grant verbs' contracts, the protected-class set and the standing-grants\n// port are deleted. 2026-10-01 (432-22, D-12): the trust-scope wire projection leaves with its last\n// consumer, the run-service token DTO. 2026-10-02 (432-39, D-12): the `TrustScope` and\n// `TrustCredential` caller types are deleted with the caller's `credential` member.\nexport type { RiskActionDescriptor, RiskTier } from './safety/index'\n// 392 CHAT-01/CHAT-05, D-14/D-18/D-24: the conversational surface's whole vocabulary — the session\n// log's event grammar and header, the per-clause turn receipts, the `agent.ask` contracts, and the\n// session-log port. Minted here rather than beside the turn engine because every one of them has\n// several consumers that may not import each other: `agent` emits, `agent-local` persists, `cli`\n// renders, and 396's MCP projection plus M5's dashboard read the same bytes (388 C13).\nexport {\n AgentAskInputSchema,\n AgentAskResultSchema,\n CHAT_SESSION_EVENT_KINDS,\n CHAT_STAGE_OUTCOMES,\n CHAT_TURN_STAGES,\n CHAT_TURN_STATUSES,\n CLAUSE_RECEIPT_STATUSES,\n CURRENT_CHAT_SESSION_SCHEMA_VERSION,\n ChatScenarioSchema,\n ChatSessionEventSchemaError,\n ClauseReceiptSchema,\n ClauseResultSchema,\n SCENARIO_CLASSES,\n SCENARIO_EXPECTATIONS,\n SCENARIO_LANES,\n ScenarioExpectationSchema,\n clauseReachedCapability,\n guardChatSessionEvent,\n} from './chat/index'\nexport type {\n AgentAskInput,\n AgentAskResult,\n ChatAbortedEvent,\n ChatActiveToolsChangeEvent,\n ChatApprovalDecisionEvent,\n ChatClauseReceiptEvent,\n ChatClauseResultEvent,\n ChatCompactionEvent,\n ChatMarkUnhandledEvent,\n ChatModelChangeEvent,\n ChatScenario,\n ChatSessionEvent,\n ChatSessionEventBase,\n ChatSessionEventKind,\n ChatSessionHandle,\n ChatSessionHeader,\n ChatStageOutcome,\n ChatStageOutcomeEvent,\n ChatTurnCompleteEvent,\n ChatTurnStage,\n ChatTurnStatus,\n ChatUserMessageEvent,\n ClauseReceipt,\n ClauseReceiptStatus,\n ClauseResult,\n OpenedChatSession,\n RefusedChatSessionLine,\n ScenarioClass,\n ScenarioExpectation,\n ScenarioExpectationKind,\n ScenarioLane,\n SessionLogPort,\n} from './chat/index'\n\n// 396-04 (D-01 / D-16 · MCPS-02): `runs.list`'s named output contract and the three declared fold\n// contracts the MCP catalogue advertises. Published on the barrel because `packages/mcp` is their\n// consumer and it reaches this package only through here. 431-03 adds the canonical output\n// contracts beside them.\nexport {\n RunsListOutputSchema,\n RunsListOutputContract,\n RunsArtifactOutputContract,\n RunsEvidenceOutputContract,\n createOutputContract,\n deriveWireOutputRepresentation,\n wireOutputContract,\n RUNS_LIST_DEFAULT_LIMIT,\n RUNS_LIST_MAX_LIMIT,\n TOOL_FOLD_DISCRIMINANT,\n AuthoringRefineFoldInputSchema,\n AuthoringRefineFoldOutputSchema,\n ConfigChangeFoldInputSchema,\n ConfigChangeFoldOutputSchema,\n KnowledgeChangeFoldInputSchema,\n KnowledgeChangeFoldOutputSchema,\n RunsEvidenceFoldInputSchema,\n RunsEvidenceFoldOutputContract,\n} from './functions/index'\nexport type {\n RunsListOutput,\n JsonSchemaDocument,\n OutputContract,\n RecordedTargets,\n RunSummaryTest,\n AuthoringRefineFoldInput,\n ConfigChangeFoldInput,\n KnowledgeChangeFoldInput,\n RunsEvidenceFoldInput,\n} from './functions/index'\n\n// 398-01 (D-05 / D-08 · XPLN-01): the capability-catalog row DTOs. Minted here per 384 D-16 —\n// the artifact is produced in `packages/cli` and read back by the CLI's runtime loader, so the\n// contract between the producer and every consumer belongs in the package neither of them owns.\n// 398-08 (D-08 / D-14 · XPLN-03): the derived example call and the projected migration entry join\n// the same block — one artifact, one contract, one place a consumer reads its shape from.\nexport {\n AgentManifestPostureSchema,\n AgentManifestSchema,\n CapabilityCatalogSchema,\n CatalogAliasRowSchema,\n CatalogExampleCallSchema,\n CatalogMigrationArmSchema,\n CatalogMigrationEntrySchema,\n CatalogOpRowSchema,\n CatalogRowSchema,\n CatalogSkillRowSchema,\n CatalogSurfaceSchema,\n catalogRowKey,\n} from './capability-catalog'\nexport type {\n AgentManifest,\n AgentManifestPosture,\n CapabilityCatalog,\n CatalogAliasRow,\n CatalogExampleCall,\n CatalogMigrationArm,\n CatalogMigrationEntry,\n CatalogOpRow,\n CatalogRow,\n CatalogSkillRow,\n CatalogSurface,\n} from './capability-catalog'\n\n// 398-04 (D-10 / D-11 · XPLN-02): the `explain` contract — the binary answer|abstention union with\n// no confidence member, and the closed citation shape that is the whole of the model's output\n// contract. Minted here per 384 D-16: the deterministic renderer lives in `packages/agent` and the\n// op's host binding in `packages/agent-local`, so the shape they agree on belongs to neither.\nexport {\n ExplainAbstentionSchema,\n ExplainAnswerSchema,\n ExplainCitationSchema,\n ExplainCitedCapabilitySchema,\n ExplainCitedRowKindSchema,\n ExplainInputSchema,\n ExplainOutputSchema,\n ExplainProseSegmentSchema,\n} from './explain'\nexport type {\n ExplainAbstention,\n ExplainAnswer,\n ExplainCitation,\n ExplainCitedCapability,\n ExplainCitedRowKind,\n ExplainInput,\n ExplainOutput,\n ExplainProseSegment,\n} from './explain'\n// 416 receipt vocabulary and the promotion result seam.\nexport { GATE_RECEIPT_SCHEMA_VERSION, GATE_NUMBERS, GATE_VERDICTS, GateReceiptSchema,\n PromotionReceiptSchema, GateLineSchema, receiptDigestOf, stampReceiptDigest,\n isPromotionReceipt, standingReceiptsByGate, strongestPromotionPath } from './knowledge/gate-receipt'\nexport type { GateNumber, GateVerdict, GateReceipt, PromotionReceipt, GateLine } from './knowledge/gate-receipt'\nexport { PROMOTION_PATHS, PROMOTION_PATH_STRENGTH, strongerPromotionPath } from './knowledge/promotion-path'\nexport type { PromotionPath } from './knowledge/promotion-path'\nexport type { PromotionOutcome, GateReceiptRecordOutcome, PromotionCandidateProvenance,\n PromotionPostureCandidate, ResolvePromotionPosture } from './knowledge/promotion-gate'\nexport { GATE_INCONSISTENCY_SHAPES, detectGateInconsistency } from './knowledge/promotion-gate'\nexport type { GateInconsistencyShape, GateInconsistency } from './knowledge/promotion-gate'\nexport { KnowledgeGatesListInputSchema, KnowledgeGatesListResultSchema,\n PromotionGateVerdictSchema } from './functions/knowledge'\nexport type { KnowledgeGatesListInput, KnowledgeGatesListResult } from './functions/knowledge'\n\nexport { PER_AXIS_SCORE_AXES, CROSS_CHECKS, DEGRADATIONS, BENEFITS, MARKS, STATE_VALIDITIES,\n axisScoreSchema, perAxisScoreSchema, corpusVersionSchema, samplesSchema, noiseFloorRefSchema,\n gate1ArmSchema, gate2ArmSchema, gate3ArmSchema, gate2SpendSchema } from './knowledge/gate-receipt'\nexport type { PerAxisScoreAxis, CrossCheck, Degradation, Benefit, Mark, StateValidity,\n Gate1Receipt, Gate2Receipt, Gate3Receipt } from './knowledge/gate-receipt'\n// 2026-09-07, 417: neutral replay receipt and candidate DATA contracts.\nexport { GATE1_REASONS, GATE1_TARGET_SOURCES, GATE1_K_SOURCES, GATE1_HARM_ORIGINS,\n gate1CapSchema, gate1SpendSchema, gate1TargetSchema, gate1HarmedSchema } from './knowledge/gate-receipt'\nexport type { Gate1Reason, Gate1TargetSource, Gate1KSource, Gate1HarmOrigin } from './knowledge/gate-receipt'\nexport { CandidateInjectionSchema, KnowledgeCandidateInjectionResultSchema } from './knowledge/candidate-injection'\nexport type { CandidateInjection, KnowledgeCandidateInjectionResult } from './knowledge/candidate-injection'\nexport { RecordAnchorsSchema, RecordScopeSchema } from './knowledge/record-frontmatter'\nexport { BundleKindSchema, BundleStatusSchema } from './functions/knowledge'\nexport { BriefLineSchema } from './brief/guard-lossless-served-brief'\n\n// 2026-09-08, 419 D-06: the Gate-3 feedback contracts\nexport {\n MARK_QUARANTINE_CLASSES, MARK_FIX_KINDS, MARK_DISPOSITIONS, MARK_FIX_REFUSALS,\n // 2026-09-30, 432-09: the applied fix and the historical drafted receipt (the plain mark refusal,\n // MarkRefusalSchema, was deleted by 432-42)\n MARK_HISTORICAL_DISPOSITIONS, MARK_APPLIED_CHANGE_KINDS, MarkAppliedChangeSchema,\n MARK_RECEIPT_SCHEMA_VERSION, IMPROVEMENT_PLAN_SCHEMA_VERSION, COMMIT_RECEIPT_SCHEMA_VERSION,\n NoDraftableFixCheckedSchema, MarkDispositionSchema, MarkAddressSchema, MarkReceiptSchema,\n RunsMarkInputSchema, RunsMarkOutcomeSchema, ImprovementPlanKnowledgeSchema,\n ImprovementPlanSchema, CommitReceiptSchema, RunDetailMemberMarkSchema, deriveMarkStepId,\n // 2026-09-15, 423 D-19: marks history\n markAddressKey, MARKS_HISTORY_OUTCOMES, MarkHistoryChangedRecordSchema,\n RunsMarksHistoryInputSchema, MarkHistoryEntrySchema, RunsMarksHistoryResultSchema,\n // 2026-09-15, 423 D-16/D-17: mark consequence preview\n MARK_PREVIEW_REFUSALS, MARK_PREVIEW_OUTCOMES, MARK_TARGET_REASONS, MARK_GOLD_CHANNELS,\n MARK_PREVIEW_LATEST_KINDS, MARK_PREVIEW_DRAFT_KINDS, MarkPreviewBasisSchema, MarkPreviewLatestSchema,\n MarkPreviewGroundTruthSchema, MarkPreviewLabelSchema, MarkPreviewKnowledgeSchema, MarkPreviewDraftSchema,\n RunsMarkPreviewResultSchema,\n MARK_PREVIEW_EVIDENCE_DIRECTIONS, MARK_PREVIEW_RECORD_EVIDENCE_KINDS, MarkPreviewEvidenceEffectSchema,\n MarkPreviewKnowledgeRecordSchema,\n} from './functions/feedback'\nexport type {\n MarkQuarantineClass, MarkFixKind, MarkFixRefusal, MarkDisposition, NoDraftableFixChecked, MarkAddress,\n MarkReceipt, RunsMarkInput, RunsMarkOutcome, ImprovementPlanKnowledge, ImprovementPlan,\n CommitReceipt, RunDetailMemberMark, FeedbackPort, MarkAppliedChange,\n MarkHistoryChangedRecord, RunsMarksHistoryInput, MarkHistoryEntry,\n RunsMarksHistoryResult, MarkHistoryReadEntry, MarkHistoryRead, FeedbackReadsPort,\n MarkPreviewBasis, MarkPreviewLatest, MarkPreviewGroundTruth, MarkPreviewLabel, MarkPreviewKnowledge,\n MarkPreviewDraft, RunsMarkPreviewResult, MarkPreviewEvidenceEffect,\n MarkPreviewKnowledgeRecord,\n} from './functions/feedback'\n// 2026-09-15, 423 D-20/D-17: the one read-time record join, shared by runs.knowledge and runs.mark.preview\nexport { projectRecordContent, maskRecordContent } from './functions/record-join'\nexport type { RunKnowledgeRecordContent, RunKnowledgeContentAbsence } from './functions/record-join'\nexport { KnowledgeMarkInputSchema } from './knowledge/review-verbs'\nexport type { KnowledgeMarkInput } from './knowledge/review-verbs'\nexport { OVERTURNED_EVENT_TYPE } from './knowledge/outcome-event'\n// 2026-09-26, 429-04 D-18: the one provider-error classifier the CLI, the dashboard server and\n// the UI share, with the CLI's order and sentences.\nexport {\n classifyProviderError,\n extractProviderError,\n PROVIDER_ERROR_CLASSES,\n providerErrorSentence,\n} from './llm/provider-error'\nexport type { ProviderErrorClass } from './llm/provider-error'\n// 2026-09-26, 429-04 D-15/D-09/D-24: the draft connect, credential save and move DTOs.\nexport {\n LLM_SETUP_REFUSALS,\n LlmConnectRequestSchema,\n LlmCredentialMoveRequestSchema,\n} from './llm/connect'\nexport type {\n LlmConnectRequest,\n LlmConnectResult,\n LlmCredentialMoveRequest,\n LlmCredentialSaveResult,\n LlmSetupRefusal,\n} from './llm/connect'\n","declare const refBrand: unique symbol\n\nexport type Ref = string & { readonly [refBrand]: 'Ref' }\n\nexport const asRef = (value: string): Ref => value as Ref\n","import type { Action } from './index'\nimport { z } from 'zod'\n\nconst refSchema = z.string().min(1)\nconst pointSchema = z.object({ x: z.number(), y: z.number() }).passthrough()\nconst coordSpaceSchema = z.enum(['viewport', 'content', 'screen'])\nconst directionSchema = z.enum(['up', 'down', 'left', 'right'])\nconst desiredStateSchema = z.enum(['checked', 'unchecked', 'selected', 'unselected'])\nconst assertValueOpSchema = z.enum([\n 'isNull',\n 'isDefined',\n 'equals',\n 'notEquals',\n 'gt',\n 'lt',\n 'contains',\n])\n\nconst tabSelectorSchema = z\n .object({\n index: z.number().optional(),\n title: z.string().optional(),\n url: z.string().optional(),\n })\n .passthrough()\n .superRefine((value, ctx) => {\n if (value.index === undefined && value.title === undefined && value.url === undefined) {\n ctx.addIssue({ code: 'custom', message: 'requires at least one of index, title, or url' })\n }\n })\n\nconst fillSchema = z\n .object({\n type: z.literal('fill'),\n ref: refSchema,\n text: z.string(),\n clearMode: z.enum(['replace', 'append']),\n submit: z.boolean(),\n })\n .passthrough()\n\nconst navigateSchema = z.discriminatedUnion('to', [\n z.object({ type: z.literal('navigate'), to: z.literal('url'), url: z.string() }).passthrough(),\n z.object({ type: z.literal('navigate'), to: z.literal('back') }).passthrough(),\n z.object({ type: z.literal('navigate'), to: z.literal('forward') }).passthrough(),\n z.object({ type: z.literal('navigate'), to: z.literal('reload') }).passthrough(),\n])\n\nconst tabSchema = z.union([\n z.object({ type: z.literal('tab'), action: z.literal('new'), url: z.string() }).passthrough(),\n z\n .object({\n type: z.literal('tab'),\n action: z.literal('switch'),\n index: z.number().optional(),\n title: z.string().optional(),\n url: z.string().optional(),\n })\n .passthrough()\n .superRefine((value, ctx) => {\n if (value.index === undefined && value.title === undefined && value.url === undefined) {\n ctx.addIssue({ code: 'custom', message: 'tab switch requires index, title, or url' })\n }\n }),\n])\n\nconst inspectSchema = z.discriminatedUnion('what', [\n z\n .object({\n type: z.literal('inspect'),\n what: z.literal('console'),\n level: z.enum(['log', 'info', 'warn', 'error']).optional(),\n tab: tabSelectorSchema.optional(),\n })\n .passthrough(),\n z\n .object({\n type: z.literal('inspect'),\n what: z.literal('network'),\n urlPattern: z.string().optional(),\n tab: tabSelectorSchema.optional(),\n })\n .passthrough(),\n z\n .object({ type: z.literal('inspect'), what: z.literal('cookies'), name: z.string().optional() })\n .passthrough(),\n z\n .object({\n type: z.literal('inspect'),\n what: z.literal('localStorage'),\n key: z.string().optional(),\n })\n .passthrough(),\n])\n\nconst networkStateSchema = z.discriminatedUnion('mode', [\n z.object({ type: z.literal('networkState'), mode: z.literal('offline') }).passthrough(),\n z\n .object({\n type: z.literal('networkState'),\n mode: z.literal('throttle'),\n latencyMs: z.number(),\n downloadKbps: z.number(),\n uploadKbps: z.number(),\n })\n .passthrough(),\n])\n\nconst storageStateSchema = z.discriminatedUnion('op', [\n z.object({ type: z.literal('storageState'), op: z.literal('save'), name: z.string() }).passthrough(),\n z\n .object({ type: z.literal('storageState'), op: z.literal('restore'), name: z.string() })\n .passthrough(),\n])\n\nconst cookieSchema = z\n .object({\n name: z.string(),\n value: z.string(),\n domain: z.string().optional(),\n path: z.string().optional(),\n httpOnly: z.boolean().optional(),\n secure: z.boolean().optional(),\n sameSite: z.enum(['Strict', 'Lax', 'None']).optional(),\n expires: z.number().optional(),\n })\n .passthrough()\n\nconst fingersSchema = z.union([z.literal(2), z.literal(3)])\n\nconst swipeSchema = z.discriminatedUnion('mode', [\n z\n .object({\n type: z.literal('swipe'),\n mode: z.literal('direction'),\n durationMs: z.number(),\n direction: directionSchema,\n ref: refSchema.optional(),\n })\n .passthrough(),\n z\n .object({\n type: z.literal('swipe'),\n mode: z.literal('path'),\n durationMs: z.number(),\n from: pointSchema,\n to: pointSchema,\n coordSpace: z.enum(['viewport', 'screen']),\n })\n .passthrough(),\n])\n\nconst pickerSelectSchema = z.union([\n z.object({ type: z.literal('pickerSelect'), ref: refSchema, value: z.string() }).passthrough(),\n z.object({ type: z.literal('pickerSelect'), ref: refSchema, order: z.number() }).passthrough(),\n])\n\nconst assertValueSchema = z.union([\n z\n .object({\n type: z.literal('assertValue'),\n source: z.enum(['url', 'storage', 'network', 'expr-result']),\n op: assertValueOpSchema,\n expected: z.string().optional(),\n })\n .passthrough(),\n z\n .object({\n type: z.literal('assertValue'),\n expr: z.string(),\n op: assertValueOpSchema,\n expected: z.string().optional(),\n })\n .passthrough(),\n])\n\nconst extractAIFieldSchema = z\n .object({\n name: z.string(),\n type: z.enum(['string', 'number', 'boolean', 'array', 'object']),\n description: z.string(),\n item: z.object({ type: z.enum(['string', 'number', 'boolean', 'object']) }).passthrough().optional(),\n })\n .passthrough()\n\nconst waitForSchema = z.discriminatedUnion('on', [\n z\n .object({\n type: z.literal('waitFor'),\n on: z.literal('text'),\n text: z.string(),\n timeoutMs: z.number(),\n })\n .passthrough(),\n z\n .object({\n type: z.literal('waitFor'),\n on: z.literal('selector'),\n selector: z.string(),\n timeoutMs: z.number(),\n })\n .passthrough(),\n z\n .object({\n type: z.literal('waitFor'),\n on: z.literal('gone'),\n text: z.string(),\n timeoutMs: z.number(),\n })\n .passthrough(),\n])\n\nconst scrollSchema = z.discriminatedUnion('mode', [\n z\n .object({\n type: z.literal('scroll'),\n mode: z.literal('direction'),\n direction: directionSchema,\n ref: refSchema.optional(),\n amount: z.enum(['page', 'halfPage', 'toEnd']),\n retryOpposite: z.boolean(),\n })\n .passthrough(),\n z\n .object({\n type: z.literal('scroll'),\n mode: z.literal('untilVisible'),\n text: z.string(),\n ref: refSchema.optional(),\n direction: directionSchema,\n maxSwipes: z.number(),\n retryOpposite: z.boolean(),\n })\n .passthrough(),\n])\n\nconst intentExtraSchema = z\n .object({\n key: z.string(),\n type: z.enum(['string', 'int', 'long', 'float', 'bool']),\n value: z.string(),\n })\n .passthrough()\n\nconst refTargeted = (type: Action['type']) =>\n z.object({ type: z.literal(type), ref: refSchema }).passthrough()\n\n/** Exhaustive Action wire schemas keyed by `Action['type']` (D-15). */\nexport const ACTION_WIRE_SCHEMAS_BY_TYPE = {\n navigate: navigateSchema,\n waitForUrl: z.object({ type: z.literal('waitForUrl'), pattern: z.string() }).passthrough(),\n click: z\n .object({\n type: z.literal('click'),\n ref: refSchema,\n clickDelay: z.number().optional(),\n desiredState: desiredStateSchema.optional(),\n })\n .passthrough(),\n doubleClick: z\n .object({\n type: z.literal('doubleClick'),\n ref: refSchema,\n relativePosition: pointSchema.optional(),\n clickDelay: z.number().optional(),\n })\n .passthrough(),\n rightClick: z\n .object({\n type: z.literal('rightClick'),\n ref: refSchema,\n relativePosition: pointSchema.optional(),\n clickDelay: z.number().optional(),\n })\n .passthrough(),\n fill: fillSchema,\n select: z\n .object({ type: z.literal('select'), value: z.string(), ref: refSchema })\n .passthrough(),\n hover: refTargeted('hover'),\n paste: z.object({ type: z.literal('paste'), value: z.string(), ref: refSchema }).passthrough(),\n copy: refTargeted('copy'),\n fileUpload: z\n .object({ type: z.literal('fileUpload'), files: z.array(z.string()), ref: refSchema })\n .passthrough(),\n tab: tabSchema,\n inspect: inspectSchema,\n route: z\n .object({\n type: z.literal('route'),\n urlPattern: z.string(),\n headers: z.record(z.string(), z.string()).optional(),\n body: z.string().optional(),\n contentType: z.string().optional(),\n })\n .passthrough(),\n unroute: z\n .object({ type: z.literal('unroute'), urlPattern: z.string().optional() })\n .passthrough(),\n networkState: networkStateSchema,\n storageState: storageStateSchema,\n handleDialog: z\n .object({\n type: z.literal('handleDialog'),\n accept: z.boolean(),\n promptText: z.string().optional(),\n })\n .passthrough(),\n uniqueValue: z.object({ type: z.literal('uniqueValue'), prefix: z.string() }).passthrough(),\n focus: refTargeted('focus'),\n setCookies: z\n .object({ type: z.literal('setCookies'), cookies: z.array(cookieSchema) })\n .passthrough(),\n setLocalStorage: z\n .object({\n type: z.literal('setLocalStorage'),\n entries: z.array(z.object({ key: z.string(), value: z.string() }).passthrough()),\n })\n .passthrough(),\n tap: z\n .object({\n type: z.literal('tap'),\n ref: refSchema,\n desiredState: desiredStateSchema.optional(),\n })\n .passthrough(),\n doubleTap: refTargeted('doubleTap'),\n multiTap: z.union([\n z.object({ type: z.literal('multiTap'), fingers: fingersSchema, ref: refSchema }).passthrough(),\n z\n .object({\n type: z.literal('multiTap'),\n fingers: fingersSchema,\n x: z.number(),\n y: z.number(),\n coordSpace: coordSpaceSchema,\n })\n .passthrough(),\n ]),\n tapCoordinate: z\n .object({\n type: z.literal('tapCoordinate'),\n x: z.number(),\n y: z.number(),\n coordSpace: coordSpaceSchema,\n })\n .passthrough(),\n swipe: swipeSchema,\n longpress: z\n .object({\n type: z.literal('longpress'),\n ref: refSchema,\n duration: z.number().optional(),\n })\n .passthrough(),\n pinch: z.union([\n z.object({ type: z.literal('pinch'), scale: z.number(), ref: refSchema }).passthrough(),\n z\n .object({\n type: z.literal('pinch'),\n scale: z.number(),\n x: z.number(),\n y: z.number(),\n coordSpace: coordSpaceSchema,\n })\n .passthrough(),\n ]),\n drag: z\n .object({ type: z.literal('drag'), fromRef: refSchema, toRef: refSchema })\n .passthrough(),\n nativeSelect: z\n .object({ type: z.literal('nativeSelect'), value: z.string(), ref: refSchema })\n .passthrough(),\n hideKeyboard: z.object({ type: z.literal('hideKeyboard') }).passthrough(),\n setOrientation: z\n .object({\n type: z.literal('setOrientation'),\n orientation: z.enum(['portrait', 'landscape']),\n })\n .passthrough(),\n stopApp: z.object({ type: z.literal('stopApp'), bundleId: z.string() }).passthrough(),\n pressBack: z.object({ type: z.literal('pressBack') }).passthrough(),\n pressHome: z.object({ type: z.literal('pressHome') }).passthrough(),\n pressRecent: z.object({ type: z.literal('pressRecent') }).passthrough(),\n openNotifications: z.object({ type: z.literal('openNotifications') }).passthrough(),\n openQuickSettings: z.object({ type: z.literal('openQuickSettings') }).passthrough(),\n intent: z\n .object({\n type: z.literal('intent'),\n action: z.string(),\n data: z.string().optional(),\n packageName: z.string().optional(),\n extras: z.array(intentExtraSchema).optional(),\n })\n .passthrough(),\n keyevent: z.object({ type: z.literal('keyevent'), keycode: z.string() }).passthrough(),\n pressButton: z\n .object({ type: z.literal('pressButton'), button: z.enum(['home', 'volumeUp', 'action']) })\n .passthrough(),\n pickerSelect: pickerSelectSchema,\n swipeFromEdge: z\n .object({\n type: z.literal('swipeFromEdge'),\n edge: z.enum(['left', 'right', 'top', 'bottom']),\n })\n .passthrough(),\n openUniversalLink: z\n .object({\n type: z.literal('openUniversalLink'),\n url: z.string(),\n bundleId: z.string().optional(),\n })\n .passthrough(),\n assertAI: z\n .object({\n type: z.literal('assertAI'),\n claim: z.string(),\n mode: z.enum(['multimodal', 'visual', 'text']),\n effort: z.enum(['low', 'medium', 'high']),\n consensus: z.number(),\n video: z.boolean().optional(),\n })\n .passthrough(),\n assertValue: assertValueSchema,\n extractAI: z\n .object({\n type: z.literal('extractAI'),\n query: z.string(),\n schema: z.array(extractAIFieldSchema),\n scope: z.enum(['run', 'global']),\n })\n .passthrough(),\n waitFor: waitForSchema,\n delay: z.object({ type: z.literal('delay'), ms: z.number() }).passthrough(),\n scroll: scrollSchema,\n clearText: refTargeted('clearText'),\n reportValue: z.object({ type: z.literal('reportValue'), value: z.string() }).passthrough(),\n openApp: z.union([\n z.object({ type: z.literal('openApp'), appName: z.string() }).passthrough(),\n z.object({ type: z.literal('openApp'), bundleId: z.string() }).passthrough(),\n ]),\n executeScript: z\n .object({ type: z.literal('executeScript'), command: z.string(), args: z.unknown().optional() })\n .passthrough(),\n setVariable: z\n .object({ type: z.literal('setVariable'), name: z.string(), value: z.string() })\n .passthrough(),\n keypress: z\n .object({\n type: z.literal('keypress'),\n keys: z.array(z.string()),\n mode: z.enum(['press', 'down', 'up']),\n convertPlatformKeys: z.boolean().optional(),\n })\n .passthrough(),\n} satisfies { [K in Action['type']]: z.ZodTypeAny }\n\n/** Known-variant wire validator that dispatches by `Action['type']` (D-15/D-03). */\nexport const actionWireSchema = z\n .object({ type: z.string().min(1) })\n .passthrough()\n .superRefine((value, ctx) => {\n if (Object.prototype.hasOwnProperty.call(value, 'platform')) {\n ctx.addIssue({\n code: 'custom',\n path: ['platform'],\n message: 'platform is not allowed on an action payload',\n })\n }\n\n const schema = ACTION_WIRE_SCHEMAS_BY_TYPE[\n value.type as keyof typeof ACTION_WIRE_SCHEMAS_BY_TYPE\n ] as z.ZodTypeAny | undefined\n\n if (!Object.hasOwn(ACTION_WIRE_SCHEMAS_BY_TYPE, value.type) || schema === undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['type'],\n message: `unknown action type \"${value.type}\"`,\n })\n return\n }\n\n const result = schema.safeParse(value)\n if (!result.success) {\n for (const issue of result.error.issues) {\n ctx.addIssue({ code: 'custom', path: [...issue.path], message: issue.message })\n }\n }\n })\n","import { z } from 'zod'\nimport type { Action } from './index'\n\nexport type ActionFamily =\n | 'pointer'\n | 'input'\n | 'gesture'\n | 'navigate'\n | 'verify'\n | 'extract'\n | 'wait'\n | 'device'\n | 'environment'\n | 'script'\n\nexport const ACTION_FAMILIES = [\n 'pointer', 'input', 'gesture', 'navigate', 'verify', 'extract', 'wait', 'device',\n 'environment', 'script',\n] as const satisfies readonly ActionFamily[]\n\nexport const ActionFamilySchema = z.enum(ACTION_FAMILIES)\n\nexport const ACTION_FAMILY_BY_TYPE = {\n click: 'pointer',\n doubleClick: 'pointer',\n rightClick: 'pointer',\n hover: 'pointer',\n focus: 'pointer',\n tap: 'pointer',\n doubleTap: 'pointer',\n multiTap: 'pointer',\n longpress: 'pointer',\n tapCoordinate: 'pointer',\n fill: 'input',\n paste: 'input',\n copy: 'input',\n clearText: 'input',\n keypress: 'input',\n keyevent: 'input',\n select: 'input',\n nativeSelect: 'input',\n pickerSelect: 'input',\n fileUpload: 'input',\n scroll: 'gesture',\n swipe: 'gesture',\n drag: 'gesture',\n pinch: 'gesture',\n swipeFromEdge: 'gesture',\n navigate: 'navigate',\n tab: 'navigate',\n openUniversalLink: 'navigate',\n assertAI: 'verify',\n assertValue: 'verify',\n extractAI: 'extract',\n inspect: 'extract',\n reportValue: 'extract',\n setVariable: 'extract',\n uniqueValue: 'extract',\n waitFor: 'wait',\n waitForUrl: 'wait',\n delay: 'wait',\n pressBack: 'device',\n pressHome: 'device',\n pressRecent: 'device',\n pressButton: 'device',\n hideKeyboard: 'device',\n setOrientation: 'device',\n openApp: 'device',\n stopApp: 'device',\n openNotifications: 'device',\n openQuickSettings: 'device',\n intent: 'device',\n setCookies: 'environment',\n setLocalStorage: 'environment',\n storageState: 'environment',\n route: 'environment',\n unroute: 'environment',\n networkState: 'environment',\n handleDialog: 'environment',\n executeScript: 'script',\n} as const satisfies Record<Action['type'], ActionFamily>\n\nexport function actionFamilyOf(type: Action['type']): ActionFamily {\n return ACTION_FAMILY_BY_TYPE[type]\n}\n","const TRAILING_BADGE = /\\s*(?:\\([\\s\\d]*\\d[\\s\\d]*\\)|\\[[\\s\\d]*\\d[\\s\\d]*\\]|[•·●]|\\s\\d+)\\s*$/\n\n/**\n * Normalizes app-observed accessible-name data into the stable nameNormalized value.\n */\nexport function normalizeAccessibleName(raw: string): string {\n const input = raw ?? ''\n const collapsed = input.trim().replace(/\\s+/g, ' ')\n const stripped = collapsed.replace(TRAILING_BADGE, '').trimEnd()\n return stripped.toLowerCase()\n}\n","import type { ElementInfo } from './element-info'\n\n/**\n * Return an element's document-order ordinal among elements with the same role and normalized\n * accessible name. Callers must pass the live screen's element list containing `element`.\n */\nexport function elementOrdinal(\n element: ElementInfo,\n elements: readonly ElementInfo[],\n): number {\n let ordinal = 0\n for (const candidate of elements) {\n if (\n candidate.role !== element.role\n || candidate.nameNormalized !== element.nameNormalized\n ) {\n continue\n }\n if (candidate.ref === element.ref) return ordinal\n ordinal += 1\n }\n return ordinal\n}\n","export const TOGGLE_ROLES: ReadonlySet<string> = new Set(['switch', 'checkbox', 'radio'])\n\nexport function isToggleElement(el: {\n role: string\n attributes?: Readonly<Record<string, string>>\n}): boolean {\n return el.attributes?.['checkable'] === 'true' || TOGGLE_ROLES.has(el.role)\n}\n","/**\n * Phase 374 hoist of the ONE canonical JSON serializer shared by schema and eval.\n * Object keys sort recursively, array order stays semantic, and scalar values pass through.\n */\nexport function canonicalValue(input: unknown): unknown {\n if (Array.isArray(input)) return input.map(canonicalValue)\n if (input === null || typeof input !== 'object') return input\n\n const source = input as Record<string, unknown>\n const sorted: Record<string, unknown> = {}\n for (const key of Object.keys(source).sort()) {\n sorted[key] = canonicalValue(source[key])\n }\n return sorted\n}\n\n/** Compact canonical JSON for hashes and deterministic comparisons. */\nexport function canonicalJson(value: unknown): string {\n return JSON.stringify(canonicalValue(value))\n}\n\n/** Pretty canonical JSON for committed files, ending in exactly one newline. */\nexport function committedFileText(value: unknown): string {\n return `${JSON.stringify(canonicalValue(value), null, 2)}\\n`\n}\n","// The vendored UTF-8 codec (Phase 395, D-17).\n//\n// THE SCHEMA PACKAGE HAS NO HOST APIs. The platform's own text encoder, `Buffer` and the global\n// object are all refused by `__tests__/module-discipline.test.ts` — which scans SOURCE TEXT, so\n// naming them here would red it too. The one string<->bytes edge this package needs is therefore\n// vendored, beside the vendored sha256, the same posture `determinism/sha256.ts` already takes\n// about hashing rather than reaching for a platform digest API.\n//\n// THIS IS THE ONLY ENCODER IN THE PACKAGE. `sha256hex` reaches it too, so a string hashed and a\n// string diffed are turned into bytes by one recipe. A second encoder beside this one is exactly\n// the two-representations arrangement 394's CR-02 defect class is made of: two halves of one\n// contract, each converting the same value its own way, agreeing until the first input that is not\n// plain ASCII.\n//\n// THE DIGEST BASIS NEVER PASSES THROUGH HERE. Content digests are taken over the RAW bytes a file\n// holds (D-17); this codec exists for the diff renderer's text edge and for the bytes a mutation\n// produced as a string. Decoding a file in order to digest it would re-open CR-02 from the other\n// side.\n\n/** UTF-8 bytes for one string. Lone surrogates encode as U+FFFD, as every conformant encoder does. */\nexport function utf8Encode(text: string): Uint8Array {\n const bytes: number[] = []\n\n for (let index = 0; index < text.length; index++) {\n let code = text.charCodeAt(index)\n\n if (code >= 0xd800 && code <= 0xdbff) {\n const low = index + 1 < text.length ? text.charCodeAt(index + 1) : 0\n if (low >= 0xdc00 && low <= 0xdfff) {\n code = 0x10000 + ((code - 0xd800) << 10) + (low - 0xdc00)\n index++\n }\n }\n\n if (code < 0x80) {\n bytes.push(code)\n } else if (code < 0x800) {\n bytes.push(0xc0 | (code >>> 6), 0x80 | (code & 0x3f))\n } else if (code < 0x10000) {\n bytes.push(0xe0 | (code >>> 12), 0x80 | ((code >>> 6) & 0x3f), 0x80 | (code & 0x3f))\n } else {\n bytes.push(\n 0xf0 | (code >>> 18),\n 0x80 | ((code >>> 12) & 0x3f),\n 0x80 | ((code >>> 6) & 0x3f),\n 0x80 | (code & 0x3f),\n )\n }\n }\n\n return Uint8Array.from(bytes)\n}\n\n/**\n * One string from UTF-8 bytes. Every malformed sequence becomes U+FFFD rather than throwing.\n *\n * REPLACEMENT IS NOT LOSSLESS AND IS NEVER TREATED AS IF IT WERE. This decode feeds the RENDERED\n * diff a person reads; it is not on the path any digest or any written byte takes. 394-23's\n * rollback is the recorded cost of confusing those two — it wrote U+FFFD back over every sequence\n * the decoder could not read, and called the result \"restored\".\n */\nexport function utf8Decode(bytes: Uint8Array): string {\n let out = ''\n let index = 0\n\n while (index < bytes.length) {\n const first = bytes[index]!\n let code: number\n let width: number\n\n if (first < 0x80) {\n code = first\n width = 1\n } else if ((first & 0xe0) === 0xc0) {\n code = first & 0x1f\n width = 2\n } else if ((first & 0xf0) === 0xe0) {\n code = first & 0x0f\n width = 3\n } else if ((first & 0xf8) === 0xf0) {\n code = first & 0x07\n width = 4\n } else {\n out += '�'\n index++\n continue\n }\n\n if (index + width > bytes.length) {\n out += '�'\n index++\n continue\n }\n\n let malformed = false\n for (let offset = 1; offset < width; offset++) {\n const next = bytes[index + offset]!\n if ((next & 0xc0) !== 0x80) {\n malformed = true\n break\n }\n code = (code << 6) | (next & 0x3f)\n }\n\n // Overlong forms, surrogate halves and out-of-range scalars are all malformed, and each is a\n // sequence a permissive decoder would turn into a character no encoder can produce.\n if (\n malformed\n || code > 0x10ffff\n || (code >= 0xd800 && code <= 0xdfff)\n || (width === 2 && code < 0x80)\n || (width === 3 && code < 0x800)\n || (width === 4 && code < 0x10000)\n ) {\n out += '�'\n index++\n continue\n }\n\n if (code > 0xffff) {\n const shifted = code - 0x10000\n out += String.fromCharCode(0xd800 + (shifted >>> 10), 0xdc00 + (shifted & 0x3ff))\n } else {\n out += String.fromCharCode(code)\n }\n index += width\n }\n\n return out\n}\n","const K = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]\n\nimport { utf8Encode } from '../config-mutation/utf8'\n\nfunction rightRotate(value: number, bits: number): number {\n return (value >>> bits) | (value << (32 - bits))\n}\n\nfunction hexWord(value: number): string {\n return (value >>> 0).toString(16).padStart(8, '0')\n}\n\n/**\n * sha256 of RAW BYTES, hex — the one place this package's digest is computed (395 D-17).\n *\n * Split out of {@link sha256hex} rather than copied beside it, and the split is the whole point.\n * 395's config apply digests a file as it stands on disk while the proposal digested the same file\n * as it stood at proposal time, and the two halves must be one recipe over one representation: a\n * second implementation taking bytes is precisely 394's CR-02 defect class, where two halves of one\n * digest contract hashed different representations and agreed on every input anyone had tried.\n */\nexport function sha256hexBytes(input: Uint8Array): string {\n return digestBytes(Array.from(input))\n}\n\nexport function sha256hex(input: string): string {\n return digestBytes(Array.from(utf8Encode(input)))\n}\n\nfunction digestBytes(bytes: number[]): string {\n const bitLengthHigh = Math.floor(bytes.length / 0x20000000)\n const bitLengthLow = (bytes.length << 3) >>> 0\n\n bytes.push(0x80)\n while (bytes.length % 64 !== 56) {\n bytes.push(0)\n }\n\n bytes.push(\n (bitLengthHigh >>> 24) & 0xff,\n (bitLengthHigh >>> 16) & 0xff,\n (bitLengthHigh >>> 8) & 0xff,\n bitLengthHigh & 0xff,\n (bitLengthLow >>> 24) & 0xff,\n (bitLengthLow >>> 16) & 0xff,\n (bitLengthLow >>> 8) & 0xff,\n bitLengthLow & 0xff,\n )\n\n let h0 = 0x6a09e667\n let h1 = 0xbb67ae85\n let h2 = 0x3c6ef372\n let h3 = 0xa54ff53a\n let h4 = 0x510e527f\n let h5 = 0x9b05688c\n let h6 = 0x1f83d9ab\n let h7 = 0x5be0cd19\n\n for (let offset = 0; offset < bytes.length; offset += 64) {\n const w: number[] = []\n\n for (let i = 0; i < 16; i++) {\n const j = offset + i * 4\n w[i] = (\n (bytes[j] << 24) |\n (bytes[j + 1] << 16) |\n (bytes[j + 2] << 8) |\n bytes[j + 3]\n ) >>> 0\n }\n\n for (let i = 16; i < 64; i++) {\n const s0 = (rightRotate(w[i - 15], 7) ^ rightRotate(w[i - 15], 18) ^ (w[i - 15] >>> 3)) >>> 0\n const s1 = (rightRotate(w[i - 2], 17) ^ rightRotate(w[i - 2], 19) ^ (w[i - 2] >>> 10)) >>> 0\n w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0\n }\n\n let a = h0\n let b = h1\n let c = h2\n let d = h3\n let e = h4\n let f = h5\n let g = h6\n let h = h7\n\n for (let i = 0; i < 64; i++) {\n const s1 = (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) >>> 0\n const ch = ((e & f) ^ (~e & g)) >>> 0\n const temp1 = (h + s1 + ch + K[i] + w[i]) >>> 0\n const s0 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) >>> 0\n const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0\n const temp2 = (s0 + maj) >>> 0\n\n h = g\n g = f\n f = e\n e = (d + temp1) >>> 0\n d = c\n c = b\n b = a\n a = (temp1 + temp2) >>> 0\n }\n\n h0 = (h0 + a) >>> 0\n h1 = (h1 + b) >>> 0\n h2 = (h2 + c) >>> 0\n h3 = (h3 + d) >>> 0\n h4 = (h4 + e) >>> 0\n h5 = (h5 + f) >>> 0\n h6 = (h6 + g) >>> 0\n h7 = (h7 + h) >>> 0\n }\n\n return [h0, h1, h2, h3, h4, h5, h6, h7].map(hexWord).join('')\n}\n\nexport function sha256hex16(input: string): string {\n return sha256hex(input).slice(0, 16)\n}\n","// 2026-09-07, 418 D-11/D-23: ONE distilled digest for stateValidity and novelty.\n// Route + ordered role/name/ordinal is pinned by a literal fixture digest.\n// Volatile capture fields never participate; dynamic non-badge names can still drift.\nimport { canonicalJson } from '../determinism/canonical-json'\nimport { sha256hex } from '../determinism/sha256'\nimport { elementOrdinal } from './element-ordinal'\nimport { normalizeAccessibleName } from './normalize-name'\nimport type { ScreenState } from './screen-state'\n\nexport type DistilledScreenStateInput = Pick<ScreenState, 'platform' | 'elements'> & { url?: string }\n\nexport function distilledScreenStateDigest(state: DistilledScreenStateInput): string {\n let route: string | null = null\n if (state.url !== undefined) {\n try {\n const url = new URL(state.url)\n route = (url.origin + url.pathname).replace(/\\/$/, '')\n } catch {\n // Missing and non-parseable routes have the same explicit absent identity.\n }\n }\n const elements = state.elements.map((element) => [\n element.role,\n normalizeAccessibleName(element.name),\n elementOrdinal(element, state.elements),\n ])\n return sha256hex(canonicalJson({ platform: state.platform, route, elements }))\n}\n","import type { JsonObject } from '../run/run-artifact'\n\nexport interface EmbeddingProfile {\n /** Embedding model id selected by the memidex profile. */\n model_id: string\n /**\n * Model revision pinned for index identity.\n *\n * Phase 376's embed cache is keyed (model_id, dtype, revision,\n * sha256(rendering)) and the per-model vec0 table identity includes it.\n * Locked production profiles use the exact commit hash exercised by the\n * embedding bench so upstream re-uploads cannot change index identity.\n */\n revision: string\n /** Output vector dimensionality for the selected model. */\n dim: number\n /** Quantized weight format locked by the benchmarked default. */\n dtype: 'q8'\n /** Token-to-sentence pooling locked by the benchmarked default. */\n pooling: 'mean'\n /** L2 normalization stays locked so cosine ranking matches dot-product ranking. */\n normalize: true\n /**\n * Text prepended to query inputs before embedding.\n *\n * BGE-family models require the asymmetric instruction on the query side\n * only; documents are embedded raw. Symmetric alternates (e.g.\n * gte-modernbert-base) set both prefixes empty, so a model swap stays\n * purely declarative.\n */\n query_prefix: string\n /**\n * Text prepended to document inputs before embedding.\n *\n * Symmetric models use an empty prefix. BGE-family models embed documents\n * raw, so this remains an empty string while query_prefix carries the\n * query-side instruction.\n */\n doc_prefix: string\n /**\n * Execution backend.\n *\n * 'node' is the onnxruntime-node native CPU path (transformers.js v4's\n * default device in Node). 'static' is the bundled potion-retrieval-32M\n * pure-TS floor profile; only the vocabulary ships now — its runtime\n * arrives with Phase 376.\n */\n backend: 'node' | 'static'\n /**\n * ORT session tuning passed through verbatim by the embedding runtime.\n *\n * Loose JSON by design: schema is host-API-free and never imports\n * onnxruntime types; knowledge-local hands this object to ORT unchanged.\n */\n session_options: JsonObject\n /**\n * Per-leg dense admission floor for this model.\n *\n * Each profile's value is calibrated from the recorded gold-pair cosine\n * distribution. The value may change after a benchmark gate, but the\n * required profile-owned shape stays fixed for every retrieval consumer.\n */\n tau_dense: number\n}\n\nexport const DEFAULT_EMBEDDING_PROFILE = {\n model_id: 'Xenova/bge-small-en-v1.5',\n /**\n * Locked 2026-07-14 from the embedding benchmark (D-07).\n * This pin changes vec-table identity; old revision-keyed tables are\n * disposable rebuildable projections and are rebuilt, never migrated.\n */\n revision: 'ea104dacec62c0de699686887e3f920caeb4f3e3',\n dim: 384,\n dtype: 'q8',\n pooling: 'mean',\n normalize: true,\n query_prefix: 'Represent this sentence for searching relevant passages: ',\n doc_prefix: '',\n backend: 'node',\n session_options: {\n intraOpNumThreads: 2,\n extra: {\n session: { intra_op: { allow_spinning: '0' } },\n optimization: { enable_gelu_approximation: '1' },\n },\n },\n /**\n * Locked 2026-07-14 from the embedding benchmark's recorded gold-pair p05 0.385200;\n * rounded down to two decimals.\n */\n tau_dense: 0.38,\n} as const satisfies EmbeddingProfile\n\n/**\n * Bundled pure-TypeScript degradation floor (D-12/D-13).\n *\n * A floor that must be fetched isn't a floor — the hosts that need it are\n * exactly the hosts that can't download it.\n */\nexport const STATIC_FLOOR_EMBEDDING_PROFILE = {\n model_id: 'minishlab/potion-retrieval-32M',\n revision: '6fc8051fab2a1e0ee76689cf08c853792ac285e7',\n dim: 512,\n dtype: 'q8',\n pooling: 'mean',\n normalize: true,\n query_prefix: '',\n doc_prefix: '',\n backend: 'static',\n /** ORT session options are inert for the static backend. */\n session_options: {},\n /**\n * Locked 2026-07-14 from the embedding benchmark's recorded gold-pair p05 -0.012736;\n * rounded down to two decimals.\n */\n tau_dense: -0.02,\n} as const satisfies EmbeddingProfile\n","import { z } from 'zod'\n\nimport type { Viewport } from '../primitives/viewport'\nimport { viewportSchema } from './browser'\n\nexport interface TimeoutConfig {\n step?: number\n test?: number\n navigation?: number\n}\n\nexport interface PlatformBase {\n timeouts?: TimeoutConfig\n recording?: { enabled: boolean; videoDir: string; videoSize?: Viewport }\n verbose?: boolean\n farmSession?: { hostname: string; port: number; path: string; capabilities: Record<string, unknown> }\n logCapture?: { console?: boolean; network?: boolean }\n}\n\nexport const timeoutConfigSchema = z.object({\n step: z.number().optional(),\n test: z.number().optional(),\n navigation: z.number().optional(),\n}).strict()\n\nexport const platformBaseShape = {\n timeouts: timeoutConfigSchema.optional(),\n recording: z.object({\n enabled: z.boolean(),\n videoDir: z.string(),\n videoSize: viewportSchema.optional(),\n }).strict().optional(),\n verbose: z.boolean().optional(),\n farmSession: z.object({\n hostname: z.string(),\n port: z.number(),\n path: z.string(),\n capabilities: z.record(z.string(), z.unknown()),\n }).strict().optional(),\n logCapture: z.object({\n console: z.boolean().optional(),\n network: z.boolean().optional(),\n }).strict().optional(),\n}\n\nexport const platformBase = z.object(platformBaseShape).strict()\n","import { z } from 'zod'\n\nimport type { Viewport } from '../primitives/viewport'\n\nexport interface BrowserConfig {\n name: 'chromium' | 'firefox' | 'webkit'\n headless?: boolean\n viewport?: Viewport\n}\n\nexport const viewportSchema = z.object({\n width: z.number(),\n height: z.number(),\n}).strict()\n\nexport const appStateSchema = z.enum(['preserve', 'reset'])\n\nexport const browserConfigSchema = z.object({\n name: z.enum(['chromium', 'firefox', 'webkit']),\n headless: z.boolean().optional(),\n viewport: viewportSchema.optional(),\n}).strict()\n","// 2026-09-26, 429-01 D-19/D-22: the field-merge write DTO behind PATCH /api/config. A change\n// names one field by segments, never a dotted string, so a key holding a dot stays addressable\n// and an outside edit to a sibling field is never rewritten.\nimport { z } from 'zod'\nimport { isConfigSchemaPath } from './leaves'\n\n/**\n * What one change does to the field its path names.\n * - `set-if-absent`: writes only when the field is absent from the file at merge time\n * (required-sibling completion, 429-42).\n * - `move`: re-keys a field inside the server, so its value never travels (a header rename).\n * - `expect`: a precondition checked against the file as read; its value is null for an absent field.\n */\nexport type ConfigWriteOp =\n | 'set'\n | 'unset'\n | 'append'\n | 'set-if-absent'\n | 'move'\n | 'expect'\n// prettier-ignore\nexport const CONFIG_WRITE_OPS = [\n 'set',\n 'unset',\n 'append',\n 'set-if-absent',\n 'move',\n 'expect',\n] as const satisfies readonly ConfigWriteOp[]\n\n/**\n * Why a write was refused, as the route answers it.\n * - `invalid_write_input`: the body is not a well-formed change set.\n * - `file_invalid`: the file does not parse as YAML.\n * - `path_not_found`: a `{ name }` selector names no entry.\n * - `validation_failed`: the merged config fails whole-config validation.\n * - `write_failed`: the atomic write itself failed.\n * - `field_changed`: an `expect` found the field changed since the page read it.\n * - `path_not_writable`: the path is not one this door may write or test.\n * - `marker_written_back`: a value or path of the change holds a `[secret:<name>]` marker, which\n * is how a read shows a declared secret, so writing it would replace the real value (441 GAP-D7).\n * Only ops that write are checked; an `expect` is not.\n */\nexport type ConfigWriteRefusal =\n | 'invalid_write_input'\n | 'file_invalid'\n | 'path_not_found'\n | 'validation_failed'\n | 'write_failed'\n | 'field_changed'\n | 'path_not_writable'\n | 'marker_written_back'\n// prettier-ignore\nexport const CONFIG_WRITE_REFUSALS = [\n 'invalid_write_input',\n 'file_invalid',\n 'path_not_found',\n 'validation_failed',\n 'write_failed',\n 'field_changed',\n 'path_not_writable',\n 'marker_written_back',\n] as const satisfies readonly ConfigWriteRefusal[]\n\n// 441 GAP2-D4: the one sentence every write door answers `marker_written_back` with.\nexport const MARKER_WRITTEN_BACK_SENTENCE =\n \"This holds [secret:<name>], the way a declared secret is shown, so it can't be saved here. \"\n + \"Edit your config or test file directly instead, and don't copy [secret:<name>] into it; \"\n + \"the secret's value stays in your secrets file.\"\n\n/**\n * The only arrays a `{ name }` segment may select inside. Selecting by name rather than index\n * keeps a change on its entry when an outside edit reorders the list.\n */\nexport type ConfigNamedArray = 'registry.llms'\n// prettier-ignore\nexport const CONFIG_NAMED_ARRAYS = [\n 'registry.llms',\n] as const satisfies readonly ConfigNamedArray[]\n\n/** A mapping key, an array index, or a `{ name }` selector inside a named array. */\nexport type ConfigPathSegment = string | number | { name: string }\n\nexport const ConfigPathSegmentSchema = z.union([\n z.string().min(1),\n z.number().int().nonnegative(),\n z.object({ name: z.string().min(1) }).strict(),\n])\n\nconst ConfigPathSchema = z.array(ConfigPathSegmentSchema).min(1)\n\n// 2026-09-27, 429-44 WR-01: the page's write door writes exactly what the page renders a field\n// for, which is every schema leaf outside these roots.\n\n/**\n * Roots the page's write door never writes.\n * - `plugins`: names code the CLI loads, so it stays a file edit (D-06).\n *\n * 2026-10-01 (432-22, D-18/D-22): `safety` left this list with the schema root it named; a path\n * under it is not a schema path, so the door refuses it like any unknown path. The new root leaf\n * `allowProduction` is not denied: the page owns it.\n */\nexport type ConfigWriteDeniedRoot = 'plugins'\n// prettier-ignore\nexport const CONFIG_WRITE_DENIED_ROOTS = [\n 'plugins',\n] as const satisfies readonly ConfigWriteDeniedRoot[]\n\n/**\n * True when the page's write door may change the path: a schema leaf or an ancestor of one,\n * outside the denied roots. A `{ name }` selector is read as an array item.\n */\nexport function isPageWritableConfigPath(path: readonly ConfigPathSegment[]): boolean {\n const root = path[0]\n if (typeof root !== 'string') return false\n if ((CONFIG_WRITE_DENIED_ROOTS as readonly string[]).includes(root)) return false\n return isConfigSchemaPath(path.map(segment => (typeof segment === 'object' ? 0 : segment)))\n}\n\nconst [SET_OP, UNSET_OP, APPEND_OP, SET_IF_ABSENT_OP, MOVE_OP, EXPECT_OP] = CONFIG_WRITE_OPS\n\nexport const ConfigChangeSchema = z.discriminatedUnion('op', [\n z.object({ op: z.literal(SET_OP), path: ConfigPathSchema, value: z.unknown() }).strict(),\n z.object({ op: z.literal(UNSET_OP), path: ConfigPathSchema }).strict(),\n z.object({ op: z.literal(APPEND_OP), path: ConfigPathSchema, value: z.unknown() }).strict(),\n z.object({ op: z.literal(SET_IF_ABSENT_OP), path: ConfigPathSchema, value: z.unknown() }).strict(),\n z.object({ op: z.literal(MOVE_OP), from: ConfigPathSchema, path: ConfigPathSchema }).strict(),\n z.object({ op: z.literal(EXPECT_OP), path: ConfigPathSchema, value: z.unknown() }).strict(),\n])\n\nexport type ConfigChange = z.infer<typeof ConfigChangeSchema>\n\nexport const ConfigWriteRequestSchema = z.object({\n changes: z.array(ConfigChangeSchema).min(1),\n undoable: z.boolean().optional(),\n}).strict()\n\nexport type ConfigWriteRequest = z.infer<typeof ConfigWriteRequestSchema>\n\nexport type ConfigWriteIssue = { path: (string | number)[]; message: string }\n\nexport type ConfigWriteResult = {\n revision: string\n /** The sha256 of the bytes the write merged onto; CONFIG_REVISION_ABSENT when the file did not exist. */\n baseRevision?: string\n undo?: { token: string; expiresAt: number }\n}\n\n/** The revision a config file that does not exist yet reports. */\nexport const CONFIG_REVISION_ABSENT = 'absent'\n\n// 2026-09-26, 429-04 D-24: the server-side Undo.\n\nexport const ConfigUndoRequestSchema = z.object({\n token: z.string().min(1),\n}).strict()\n\nexport type ConfigUndoRequest = z.infer<typeof ConfigUndoRequestSchema>\n\nexport type ConfigUndoResult = { restored: true; revision?: string }\n\n/**\n * Why an Undo was refused.\n * - `undo_expired`: the token is unknown or its window has passed.\n * - `undo_conflict`: the field changed since the write the token undoes.\n */\nexport type ConfigActionRefusal =\n | 'undo_expired'\n | 'undo_conflict'\n// prettier-ignore\nexport const CONFIG_ACTION_REFUSALS = [\n 'undo_expired',\n 'undo_conflict',\n] as const satisfies readonly ConfigActionRefusal[]\n","// The leaves of the published config schema (429-03 D-06), pinned against the real schema by\n// core's config-schema-leaves test. 2026-10-15 (441-40, D-29): the list no longer classes a leaf\n// for masking; the config output's only mask is the declared one.\n//\n// Pattern format: dot-joined tokens, where '*' is an operator-named record key and a key\n// suffixed '[]' is an array item (`registry.llms[].name`, `registry.targets.*.url`).\n\n// prettier-ignore\nexport const CONFIG_SCHEMA_LEAVES = Object.freeze([\n 'allowProduction',\n 'analytics.passRateScope.attributes.*',\n 'analytics.passRateScope.attributes.*.regex',\n 'analytics.privacy',\n 'eval.adversarial.maxProbeCalls',\n 'eval.adversarial.maxSeedsPerRefresh',\n 'eval.gate1.maxPerJob',\n 'eval.gate1.maxScreens',\n 'eval.gate2.canaryHorizonBuilds',\n 'eval.gate2.maxAblations',\n 'eval.gate2.maxLowerTrustPerScope',\n 'eval.judge',\n 'eval.judgeAllowSameFamily',\n 'eval.judges[]',\n 'eval.k',\n 'eval.seed',\n 'eval.seeding.silverPerTestCap',\n 'knowledge.commitArtifacts',\n 'knowledge.contextBudgetTokens',\n 'knowledge.dir',\n 'plugins.auth[].package',\n 'plugins.auth[].path',\n 'plugins.providers[].package',\n 'plugins.providers[].path',\n 'registry.devices.*.match.*',\n 'registry.devices.*.platform',\n 'registry.devices.*.transport',\n 'registry.llms[].baseURL',\n 'registry.llms[].contextWindow',\n 'registry.llms[].model',\n 'registry.llms[].name',\n 'registry.llms[].provider',\n 'registry.llms[].providerHeaders.*',\n 'registry.llms[].vision',\n 'registry.providers.*.*',\n 'registry.targets.*.app.browserstack',\n 'registry.targets.*.app.path',\n 'registry.targets.*.appActivity',\n 'registry.targets.*.appPackage',\n 'registry.targets.*.bundleId',\n 'registry.targets.*.environment',\n 'registry.targets.*.platform',\n 'registry.targets.*.product',\n 'registry.targets.*.url',\n 'services.accessibility.disableRules[]',\n 'services.accessibility.enabled',\n 'services.accessibility.exclude[]',\n 'services.accessibility.failOnViolation',\n 'services.accessibility.runAfter',\n 'services.accessibility.standard',\n 'services.authState.dir',\n 'services.cache.dir',\n 'services.cache.ttl',\n 'services.dashboard.artifactsDir',\n 'services.dashboard.baseUrl',\n 'services.dashboard.dbPath',\n 'services.dashboard.host',\n 'services.dashboard.port',\n 'services.dashboard.workspace',\n 'services.logging.level',\n 'services.mcp.enabled',\n 'services.mcp.host',\n 'services.mcp.path',\n 'services.mcp.port',\n 'services.mcp.transport',\n 'services.recording.enabled',\n 'services.recording.keepFailuresOnly',\n 'services.vision.effectiveResolution',\n 'services.vision.screenshotSize',\n 'use.browser.headless',\n 'use.browser.name',\n 'use.browser.viewport.height',\n 'use.browser.viewport.width',\n 'use.buildTag',\n 'use.cache',\n 'use.llm',\n 'use.logCapture.console',\n 'use.logCapture.network',\n 'use.mobile.appState',\n 'use.parallel',\n 'use.planner.maxActions',\n 'use.planner.maxPlanningTurns',\n 'use.planner.previousStepCount',\n 'use.timeout.navigation',\n 'use.timeout.step',\n 'use.timeout.test',\n 'use.workers',\n 'workspace.envFile',\n 'workspace.hooksFile',\n 'workspace.secretsFile',\n 'workspace.suiteMatch[]',\n 'workspace.testMatch[]',\n 'workspace.testPathIgnore[]',\n] as const)\n\nexport type ConfigLeafPattern = (typeof CONFIG_SCHEMA_LEAVES)[number]\n\nconst RECORD_KEY = '*'\nconst ARRAY_ITEM = '[]'\n\ninterface TrieNode {\n children: Map<string, TrieNode>\n}\n\nfunction patternSteps(pattern: string): string[] {\n const steps: string[] = []\n for (const token of pattern.split('.')) {\n let key = token\n let items = 0\n while (key.endsWith(ARRAY_ITEM)) {\n key = key.slice(0, -ARRAY_ITEM.length)\n items++\n }\n steps.push(key)\n for (let i = 0; i < items; i++) steps.push(ARRAY_ITEM)\n }\n return steps\n}\n\nconst TRIE: TrieNode = (() => {\n const root: TrieNode = { children: new Map() }\n for (const pattern of CONFIG_SCHEMA_LEAVES) {\n let node = root\n for (const step of patternSteps(pattern)) {\n let child = node.children.get(step)\n if (child === undefined) {\n child = { children: new Map() }\n node.children.set(step, child)\n }\n node = child\n }\n }\n return root\n})()\n\n/**\n * True when the path is one the published schema describes: a leaf or an ancestor of one.\n * A number segment is an array index, and a string segment never stands for an array item,\n * even when spelled '[]'.\n */\nexport function isConfigSchemaPath(segments: readonly (string | number)[]): boolean {\n let node = TRIE\n for (const segment of segments) {\n let next: TrieNode | undefined\n if (typeof segment === 'number') {\n next = node.children.get(ARRAY_ITEM)\n } else if (segment === ARRAY_ITEM) {\n next = node.children.get(RECORD_KEY)\n } else {\n next = node.children.get(segment) ?? node.children.get(RECORD_KEY)\n }\n if (next === undefined) return false\n node = next\n }\n return true\n}\n\n/**\n * The list owner of a leaf pattern: the prefix before its first '*' or '[]' token, or the\n * pattern itself when it has neither.\n */\nexport function configLeafOwner(pattern: string): string {\n const owner: string[] = []\n for (const token of pattern.split('.')) {\n if (token === RECORD_KEY) break\n const arrayAt = token.indexOf(ARRAY_ITEM)\n if (arrayAt !== -1) {\n owner.push(token.slice(0, arrayAt))\n break\n }\n owner.push(token)\n }\n return owner.join('.')\n}\n","import type { RiskTier } from './risk-tier'\nimport type { Surface } from '../action'\n\n/**\n * Neutral, browser-safe descriptor the static risk classifier consumes.\n * Core, chat, skill, and shell actions project into this schema-owned shape.\n */\nexport interface RiskActionDescriptor {\n /** Action verb/id, e.g. 'web_navigate', 'git_push', or 'trigger_cloud_run'. */\n name: string\n /** True when the action is a known or registered action. */\n recognized: boolean\n /** Optional originating surface, when known. */\n surface?: Surface\n /** Advisory \"has a side effect\" hint, not the destructive risk tier. */\n destructive?: boolean\n /** Advisory read-only hint. */\n readOnly?: boolean\n /** Explicit tier declaration; later classifier signals may raise this floor. */\n declaredTier?: RiskTier\n // 2026-10-02 (432-42, D-14/D-16): the `command` payload and the per-invocation `disclosure` are\n // deleted. The classifier stopped reading a command when the command-pattern list went (432-19),\n // and the disclosure was display text for the confirm prompt, which no door shows any more.\n}\n\n\n// ---- the scrub, beside the descriptor it used to serve (401-15, WR-01 / T-401-G5 / T-401-G6) ----\n//\n// The scrub was written for the deleted per-invocation disclosure. It survives because the\n// production refusal (`config/production.ts`) interpolates target names out of a config document\n// into its one sentence, and those names are text this module does not own: control bytes are\n// replaced, length is capped and the cut is visible, on every channel the sentence reaches.\n//\n// PURE, SYNCHRONOUS, DEPENDENCY-FREE. `packages/schema` is browser-safe with zero internal\n// dependencies and may take none; everything below is string work.\n\n/**\n * What a scrubbed control character leaves behind.\n *\n * REPLACED, NEVER DROPPED. A deleted control byte turns a hostile name into one that reads like an\n * ordinary name — the attack succeeds at looking innocent. A visible replacement leaves a name that\n * reads as odd, which is the outcome a person can act on.\n */\nexport const DISCLOSURE_REPLACEMENT_CHARACTER = '\\uFFFD'\n\n/** The mark a truncated fragment ends with, so shortening is visible rather than silent. */\nexport const DISCLOSURE_TRUNCATION_MARK = '…'\n\n/** How much of one untrusted fragment survives into the sentence. */\nexport const DISCLOSURE_FRAGMENT_MAX_LENGTH = 48\n\n/**\n * Everything a terminal or a browser ACTS on rather than draws.\n *\n * C0 (\\u0000-\\u001F) and C1 (\\u007F-\\u009F) cover the newline that adds a line, the carriage return\n * that redraws one, and the ESC that introduces every CSI sequence — including the erase-line and\n * cursor-up pair that overwrites the line above without adding anything.\n *\n * The four beyond the control ranges are line/paragraph separators and the bidi overrides: \\u2028\n * and \\u2029 break lines in a browser exactly as \\u000A does in a terminal, and \\u202A-\\u202E /\n * \\u2066-\\u2069 reorder what a reader sees without changing a byte of what they are reading.\n */\nconst DISCLOSURE_UNSAFE = /[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029\\u202a-\\u202e\\u2066-\\u2069]/g\n\n/**\n * Make one untrusted fragment safe to interpolate into a single line a person reads.\n *\n * THREE THINGS, AND EACH ONE IS A SEPARATE ATTACK CLOSED:\n * - control bytes replaced, so no fragment can add, erase or reorder a line;\n * - a length cap with a visible mark, so no fragment can consume the sentence it sits in;\n * - quoting, so where the fragment ENDS is legible — an odd name reads as odd rather than as prose\n * the product wrote.\n *\n * IT IS NOT AN ESCAPER AND MUST NOT BECOME ONE. The output is for a person to read, not for a shell\n * or a parser to consume. Nothing here promises round-tripping; a scrubbed name is a rendering.\n */\nexport function scrubDisclosureFragment(fragment: string): string {\n const flattened = fragment.replace(DISCLOSURE_UNSAFE, DISCLOSURE_REPLACEMENT_CHARACTER)\n const capped = flattened.length > DISCLOSURE_FRAGMENT_MAX_LENGTH\n ? `${flattened.slice(0, DISCLOSURE_FRAGMENT_MAX_LENGTH)}${DISCLOSURE_TRUNCATION_MARK}`\n : flattened\n return `\"${capped}\"`\n}\n\n/** How much of a whole composed disclosure line survives. */\nexport const DISCLOSURE_TEXT_MAX_LENGTH = 512\n\n/**\n * The same hygiene for a WHOLE composed disclosure, where the composition owns the prose.\n *\n * SEPARATE FROM THE FRAGMENT FORM BECAUSE THE INPUT IS A DIFFERENT SHAPE. A fragment is a noun the\n * sentence interpolates and quoting it is exactly right; a whole composed sentence (since 432-42\n * only the production refusal's, `buildProductionRefusal`; the per-op `FunctionSpec.disclose` is\n * deleted) would render as a quotation if wrapped. What\n * both share is the rule that actually matters — no byte on this channel may act on the channel.\n *\n * THE CAP IS GENEROUS AND STILL A CAP. An op composes its own prose, so the realistic risk is an\n * unbounded caller-derived substring rather than a long sentence; a bound that no honest disclosure\n * reaches still removes \"unbounded\" from what a caller controls.\n */\nexport function scrubDisclosureText(text: string): string {\n const flattened = text.replace(DISCLOSURE_UNSAFE, DISCLOSURE_REPLACEMENT_CHARACTER)\n return flattened.length > DISCLOSURE_TEXT_MAX_LENGTH\n ? `${flattened.slice(0, DISCLOSURE_TEXT_MAX_LENGTH)}${DISCLOSURE_TRUNCATION_MARK}`\n : flattened\n}\n","// The production refusal's one spelling (432 D-18).\n//\n// Every door that can drive a target shows the same sentence: the run core (agent-local) and the\n// dashboard live editor, which starts sessions without the core. It lives here because both of\n// those packages depend on this one and the dashboard may not import agent-local.\n\nimport { scrubDisclosureText } from '../safety/action-descriptor'\n\n/** The one line a config adds to run against production (432-03, D-18). */\nexport const ALLOW_PRODUCTION_OPT_IN = 'allowProduction: true'\n\n/**\n * The distinct names, in first-occurrence order. Two members driving one target are one target to\n * the person reading a refusal; the order is the members' own, never a re-sort.\n */\nexport function distinctInFirstOccurrenceOrder(names: readonly string[]): string[] {\n return [...new Set(names)]\n}\n\n/**\n * The production refusal, as the one plain sentence every door shows (432-03, D-18).\n *\n * It names the production targets and the line to add, and nothing else: no remedy, no prompt, no\n * flag. Each name keeps its exact spelling apart from the characters a terminal or a browser acts\n * on, which are replaced, so the sentence stays one line on every channel.\n */\nexport function buildProductionRefusal(productionTargetNames: readonly string[]): string {\n const names = distinctInFirstOccurrenceOrder(productionTargetNames)\n .map((name) => `\"${scrubDisclosureText(name)}\"`)\n const subject =\n names.length === 0\n ? 'A target this run drives is'\n : names.length === 1\n ? `Target ${names[0]!} is`\n : `Targets ${names.join(', ')} are`\n return (\n `${subject} declared environment: production, and this config does not allow production runs. `\n + `Add ${ALLOW_PRODUCTION_OPT_IN} at the top level of agent-qa.config.yaml to allow them.`\n )\n}\n","import { z } from 'zod'\n\nexport interface DeviceConfig {\n name: string\n platform: 'android' | 'ios'\n transport: 'local' | 'remote'\n /**\n * Permissive provider-specific Appium/farm capability and selector bag.\n * Common keys include deviceName, osVersion, and platformVersion.\n */\n match: Record<string, unknown>\n}\n\nexport const deviceConfigSchema = z.object({\n name: z.string(),\n platform: z.enum(['android', 'ios']),\n transport: z.enum(['local', 'remote']),\n match: z.record(z.string(), z.unknown()),\n}).strict()\n","import { z } from 'zod'\n\nexport interface RemoteDeviceConfig {\n appiumUrl?: string\n webDriverAgentUrl?: string\n app?: string\n capabilities?: Record<string, unknown>\n}\n\nexport const remoteDeviceSchema = z.object({\n appiumUrl: z.string().optional(),\n webDriverAgentUrl: z.string().optional(),\n app: z.string().optional(),\n capabilities: z.record(z.string(), z.unknown()).optional(),\n}).strict().superRefine((val, ctx) => {\n if (!val.appiumUrl && !val.webDriverAgentUrl) {\n ctx.addIssue({\n code: 'custom',\n message: 'remoteDevice requires at least one of appiumUrl or webDriverAgentUrl',\n })\n }\n})\n","import { z } from 'zod'\n\nimport type { PlatformBase } from './base'\nimport { platformBase } from './base'\nimport type { BrowserConfig } from './browser'\nimport { appStateSchema, browserConfigSchema } from './browser'\nimport type { DeviceConfig } from './device'\nimport { deviceConfigSchema } from './device'\nimport type { RemoteDeviceConfig } from './remote-device'\nimport { remoteDeviceSchema } from './remote-device'\n\nexport interface WebAuthStateConfig {\n name: string\n load?: boolean\n capture?: boolean\n}\n\nexport interface WebPlatformConfig extends PlatformBase {\n platform: 'web'\n browser: BrowserConfig\n authState?: WebAuthStateConfig\n}\n\nexport interface AndroidPlatformConfig extends PlatformBase {\n platform: 'android'\n device: DeviceConfig\n appPackage?: string\n appActivity?: string\n bundleId?: string\n appPath?: string\n appState?: 'preserve' | 'reset'\n appiumUrl?: string\n deepLinkAppId?: string\n remoteDevice?: RemoteDeviceConfig\n}\n\nexport interface IosPlatformConfig extends PlatformBase {\n platform: 'ios'\n device: DeviceConfig\n bundleId?: string\n appPath?: string\n appState?: 'preserve' | 'reset'\n appiumUrl?: string\n webDriverAgentUrl?: string\n deepLinkAppId?: string\n remoteDevice?: RemoteDeviceConfig\n}\n\nexport type PlatformConfig = WebPlatformConfig | AndroidPlatformConfig | IosPlatformConfig\n\nexport const webAuthStateSchema = z.object({\n name: z.string(),\n load: z.boolean().optional(),\n capture: z.boolean().optional(),\n}).strict()\n\nconst webArm = platformBase.extend({\n platform: z.literal('web'),\n browser: browserConfigSchema,\n authState: webAuthStateSchema.optional(),\n}).strict()\n\nconst androidArm = platformBase.extend({\n platform: z.literal('android'),\n device: deviceConfigSchema,\n appPackage: z.string().optional(),\n appActivity: z.string().optional(),\n bundleId: z.string().optional(),\n appPath: z.string().optional(),\n appState: appStateSchema.optional(),\n appiumUrl: z.string().optional(),\n deepLinkAppId: z.string().optional(),\n remoteDevice: remoteDeviceSchema.optional(),\n}).strict()\n\nconst iosArm = platformBase.extend({\n platform: z.literal('ios'),\n device: deviceConfigSchema,\n bundleId: z.string().optional(),\n appPath: z.string().optional(),\n appState: appStateSchema.optional(),\n appiumUrl: z.string().optional(),\n webDriverAgentUrl: z.string().optional(),\n deepLinkAppId: z.string().optional(),\n remoteDevice: remoteDeviceSchema.optional(),\n}).strict()\n\nexport const platformConfigSchema = z.discriminatedUnion('platform', [webArm, androidArm, iosArm])\n","import { z } from 'zod'\n\nimport type { BrowserConfig } from './browser'\nimport { appStateSchema, browserConfigSchema } from './browser'\nimport type { RemoteDeviceConfig } from './remote-device'\nimport { remoteDeviceSchema } from './remote-device'\n\n/**\n * useSchema validates authored test/suite overrides and intentionally requires\n * platform so web/android/ios arms can reject wrong-platform keys structurally.\n * The residual rule that disallows use.platform at the global config tier\n * belongs on the future global-config wrapper; Phase 312 has no such wrapper,\n * so that tier rule is deferred to the consumer-migration milestone.\n */\n\nexport type UseWebAuthState = string | {\n name: string\n load?: boolean\n capture?: boolean\n}\n\n/**\n * 402-03 (D-12): member concurrency, as a CONFIG author writes it.\n *\n * `parallel` absent or false means one member at a time — today's behaviour, byte for byte.\n * `workers` is the ceiling a config owner tunes; absent means `DEFAULT_PARALLEL_WORKERS`.\n *\n * IT IS DELIBERATELY NOT AN ARM-SPECIFIC FIELD. Concurrency is a property of the RUN, not of the\n * platform it drives, so the two fields repeat identically on all three arms rather than belonging\n * to one — which is also why they are declared here, above the arms, instead of inside the web arm\n * where a web-only knob would live.\n *\n * NO ZOD `.default()`, on purpose: a defaulted field changes the PARSED type and every hand-built\n * config fixture in the workspace then needs the key. The default lives in\n * `resolveEffectiveWorkers`, which is the one place a worker COUNT is ever decided.\n */\nexport interface UseConcurrency {\n parallel?: boolean\n workers?: number\n}\n\nexport interface UseWeb extends UseConcurrency {\n platform: 'web'\n browser?: BrowserConfig\n authState?: UseWebAuthState\n}\n\nexport interface UseAndroid extends UseConcurrency {\n platform: 'android'\n device?: string\n appState?: 'preserve' | 'reset'\n remoteDevice?: RemoteDeviceConfig\n}\n\nexport interface UseIos extends UseConcurrency {\n platform: 'ios'\n device?: string\n appState?: 'preserve' | 'reset'\n remoteDevice?: RemoteDeviceConfig\n}\n\nexport type Use = UseWeb | UseAndroid | UseIos\n\nconst useWebAuthStateSchema = z.union([\n z.string(),\n z.object({\n name: z.string(),\n load: z.boolean().optional(),\n capture: z.boolean().optional(),\n }).strict(),\n])\n\n/** The two concurrency fields, spelled ONCE and spread into every arm (D-12). */\nconst useConcurrencyShape = {\n parallel: z.boolean().optional(),\n workers: z.number().int().positive().optional(),\n} as const\n\nconst useWebArm = z.object({\n platform: z.literal('web'),\n browser: browserConfigSchema.optional(),\n authState: useWebAuthStateSchema.optional(),\n ...useConcurrencyShape,\n}).strict()\n\nconst useAndroidArm = z.object({\n platform: z.literal('android'),\n device: z.string().optional(),\n appState: appStateSchema.optional(),\n remoteDevice: remoteDeviceSchema.optional(),\n ...useConcurrencyShape,\n}).strict()\n\nconst useIosArm = z.object({\n platform: z.literal('ios'),\n device: z.string().optional(),\n appState: appStateSchema.optional(),\n remoteDevice: remoteDeviceSchema.optional(),\n ...useConcurrencyShape,\n}).strict()\n\nexport const useSchema = z.discriminatedUnion('platform', [useWebArm, useAndroidArm, useIosArm])\n\n/**\n * The conservative ceiling a `use.parallel: true` with no explicit count resolves to (402-03).\n *\n * THREE, not \"as many as there are members\": every concurrent member owns a browser or a device\n * session, and RESEARCH Pitfall 11 is the memory/handle exhaustion that follows from letting a\n * run's member count decide how much of the machine it takes. A config owner who wants more says\n * so with `use.workers`.\n */\nexport const DEFAULT_PARALLEL_WORKERS = 3\n\n/** What the one formula reads: the config's two fields, and how many members this run has. */\nexport interface EffectiveWorkersInput {\n /** `use.parallel` — absent or false means sequential. */\n readonly parallel?: boolean | undefined\n /** `use.workers` — absent means `DEFAULT_PARALLEL_WORKERS`. */\n readonly workers?: number | undefined\n /** How many members this run assembled. */\n readonly memberCount: number\n}\n\n/**\n * THE ONE PLACE A WORKER COUNT IS DECIDED (402-03, D-12).\n *\n * `min(memberCount, workers ?? DEFAULT_PARALLEL_WORKERS)` when `parallel` is true, and 1 otherwise\n * — never below 1, so a zero-member run still resolves to the sequential shape the shell defaults\n * to. Both doors (`agent-qa run` and the service's `runs.start`) reach the pool through this\n * function; there is no second spelling of the default, and none of its inputs can come from a\n * request (`RunsStartInput` names neither field — pinned in `runs-start-input-posture.test.ts`).\n *\n * A WORKERS VALUE THE SCHEMA WOULD HAVE REFUSED resolves to the default rather than to something\n * unbounded — zero, negative, fractional-below-one and non-finite counts are all \"not a count\", and\n * the honest answer to \"not a count\" is the same conservative ceiling an absent one gets (T-402-12).\n */\nexport function resolveEffectiveWorkers(input: EffectiveWorkersInput): number {\n if (input.parallel !== true) return 1\n const requested = input.workers === undefined ? DEFAULT_PARALLEL_WORKERS : Math.floor(input.workers)\n const ceiling = Number.isFinite(requested) && requested >= 1 ? requested : DEFAULT_PARALLEL_WORKERS\n return Math.max(1, Math.min(input.memberCount, ceiling))\n}\n","// The per-step planner limits (436 D-01..D-03): one default pair and one resolver every door calls.\n\n/** The two per-step limits, each a positive integer consumed monotonically by the runner. */\nexport interface PlannerLimits {\n maxActions: number\n maxPlanningTurns: number\n}\n\nexport const DEFAULT_PLANNER_LIMITS: Readonly<PlannerLimits> = Object.freeze({\n maxActions: 30,\n maxPlanningTurns: 30,\n})\n\nexport const PLANNER_LIMIT_KEYS = ['maxActions', 'maxPlanningTurns'] as const\n\n/** A test whose own `use.planner` limits differ from the project's. */\nexport interface PlannerLimitsPerTest {\n testName: string\n filePath: string\n maxActions: number\n maxPlanningTurns: number\n}\n\n/** The effective limits a run recorded, with the tests whose own limits differ. */\nexport interface PlannerLimitsRecord extends PlannerLimits {\n perTest?: PlannerLimitsPerTest[]\n}\n\nfunction plannerLimitValue(useBlock: unknown, key: keyof PlannerLimits): number | undefined {\n if (typeof useBlock !== 'object' || useBlock === null) return undefined\n const planner = (useBlock as { planner?: unknown }).planner\n if (typeof planner !== 'object' || planner === null) return undefined\n const value = (planner as Record<string, unknown>)[key]\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : undefined\n}\n\n/**\n * The effective limits for a step, from `use` blocks in increasing precedence (project, suite,\n * test). Per key, the last block whose `planner.<key>` is a positive safe integer wins; otherwise\n * the default applies.\n */\nexport function resolvePlannerLimits(...useBlocks: unknown[]): PlannerLimits {\n const resolved: PlannerLimits = { ...DEFAULT_PLANNER_LIMITS }\n for (const block of useBlocks) {\n for (const key of PLANNER_LIMIT_KEYS) {\n const value = plannerLimitValue(block, key)\n if (value !== undefined) resolved[key] = value\n }\n }\n return resolved\n}\n","import type { BoundingBox } from '../primitives/bounding-box'\nimport { asRef } from '../primitives/ref'\nimport type { Ref } from '../primitives/ref'\nimport type { ElementBounds } from '../screen/element-bounds'\nimport type { ElementInfo } from '../screen/element-info'\nimport type { ScreenState } from '../screen/screen-state'\nimport { sha256hex } from './sha256'\n\ntype ScreenRegion = 'above' | 'visible' | 'below'\n\nconst FIELD = '\\x1f'\nconst RECORD = '\\x01'\n\nfunction text(value: string): string {\n return `${value.length}:${value}`\n}\n\nfunction numberValue(value: number): string {\n return String(value)\n}\n\nfunction booleanValue(value: boolean): string {\n return value ? '1' : '0'\n}\n\nfunction optionalString(value: string | undefined): string {\n return value === undefined ? '0' : `1${FIELD}${text(value)}`\n}\n\nfunction optionalBoolean(value: boolean | undefined): string {\n return value === undefined ? '0' : `1${FIELD}${booleanValue(value)}`\n}\n\nfunction record(tag: string, fields: string[]): string {\n return [tag, ...fields].join(FIELD)\n}\n\nfunction arrayValue(values: string[]): string {\n return [numberValue(values.length), ...values].join(FIELD)\n}\n\nfunction regionOf(bounds: BoundingBox, scrollOffsetY: number, viewportHeight: number): ScreenRegion {\n const windowTop = scrollOffsetY\n const windowBottom = scrollOffsetY + viewportHeight\n const elementTop = bounds.y\n const elementBottom = bounds.y + bounds.height\n\n if (elementBottom <= windowTop) {\n return 'above'\n }\n\n if (elementTop >= windowBottom) {\n return 'below'\n }\n\n return 'visible'\n}\n\nfunction serializeBounds(bounds: BoundingBox): string {\n return record('bounds', [\n numberValue(bounds.x),\n numberValue(bounds.y),\n numberValue(bounds.width),\n numberValue(bounds.height),\n ])\n}\n\nfunction serializePoint(point: { x: number; y: number }): string {\n return record('point', [\n numberValue(point.x),\n numberValue(point.y),\n ])\n}\n\nfunction optionalBounds(bounds: BoundingBox | undefined): string {\n return bounds === undefined ? '0' : `1${FIELD}${serializeBounds(bounds)}`\n}\n\nfunction optionalPoint(point: { x: number; y: number } | undefined): string {\n return point === undefined ? '0' : `1${FIELD}${serializePoint(point)}`\n}\n\nfunction optionalRef(ref: Ref | undefined): string {\n return ref === undefined ? '0' : `1${FIELD}${text(ref)}`\n}\n\nfunction optionalRefArray(refs: Ref[] | undefined): string {\n return refs === undefined ? '0' : `1${FIELD}${arrayValue(refs.map(ref => text(ref)))}`\n}\n\nfunction serializeStringMap(values: Record<string, string>): string {\n return arrayValue(\n Object.keys(values).sort().map(key => record('entry', [\n text(key),\n text(values[key]),\n ])),\n )\n}\n\nfunction serializeElement(element: ElementInfo): string {\n return record('element', [\n text(element.ref),\n text(element.role),\n text(element.name),\n text(element.nameNormalized),\n optionalString(element.value),\n optionalBounds(element.bounds),\n optionalPoint(element.center),\n record('state', [\n booleanValue(element.state.enabled),\n booleanValue(element.state.focused),\n booleanValue(element.state.visible),\n optionalBoolean(element.state.selected),\n optionalBoolean(element.state.checked),\n optionalBoolean(element.state.editable),\n optionalBoolean(element.state.clickable),\n ]),\n record('labels', [\n optionalString(element.labels.testId),\n optionalString(element.labels.ariaLabel),\n optionalString(element.labels.placeholder),\n optionalString(element.labels.title),\n ]),\n element.hierarchy === undefined\n ? '0'\n : `1${FIELD}${record('hierarchy', [\n optionalRef(element.hierarchy.parentRef),\n optionalRefArray(element.hierarchy.childRefs),\n ])}`,\n serializeStringMap(element.attributes),\n ])\n}\n\nfunction serializeElementBounds(bounds: ElementBounds): string {\n return record('elementBounds', [\n serializeBounds(bounds.bounds),\n serializePoint(bounds.center),\n bounds.scrollContext === undefined\n ? '0'\n : `1${FIELD}${record('scrollContext', [\n optionalRef(bounds.scrollContext.container),\n numberValue(bounds.scrollContext.offsetX),\n numberValue(bounds.scrollContext.offsetY),\n ])}`,\n ])\n}\n\nfunction serializeRefMap(refMap: ScreenState['refMap']): string {\n return arrayValue(\n Object.keys(refMap).sort().map(key => {\n const ref = asRef(key)\n return record('refMapEntry', [\n text(key),\n serializeElementBounds(refMap[ref]),\n ])\n }),\n )\n}\n\nfunction serializeMetadata(metadata: ScreenState['metadata']): string {\n const base = [\n metadata.captureMode,\n metadata.coordSpace,\n numberValue(metadata.viewportWidth),\n numberValue(metadata.viewportHeight),\n record('scroll', [\n numberValue(metadata.scroll.offsetX),\n numberValue(metadata.scroll.offsetY),\n numberValue(metadata.scroll.contentWidth),\n numberValue(metadata.scroll.contentHeight),\n ]),\n optionalString(metadata.domContext),\n ]\n\n if (metadata.captureMode === 'full') {\n return record('metadata', [\n ...base,\n numberValue(metadata.imageWidth),\n numberValue(metadata.imageHeight),\n ])\n }\n\n return record('metadata', base)\n}\n\nfunction canonicalScreenState(state: ScreenState): string {\n return [\n 'screen-state:v1',\n text(state.platform),\n text(state.tree),\n arrayValue(state.elements.map(serializeElement)),\n serializeRefMap(state.refMap),\n optionalString(state.url),\n numberValue(state.timestamp),\n serializeMetadata(state.metadata),\n ].join(RECORD)\n}\n\nexport function screenIdentityHash(state: ScreenState): string {\n const scrollOffsetY = state.metadata.scroll.offsetY\n const viewportHeight = state.metadata.viewportHeight\n const elements = state.elements.map(element => record('identityElement', [\n text(element.role),\n text(element.nameNormalized),\n element.bounds === undefined ? 'visible' : regionOf(element.bounds, scrollOffsetY, viewportHeight),\n ]))\n\n return sha256hex(['screen-identity:v1', ...elements].join(RECORD))\n}\n\nexport function screenStateHash(state: ScreenState): string {\n return sha256hex(canonicalScreenState(state))\n}\n","import { sha256hex } from './sha256'\n\nexport interface RedactedEnvVar {\n name: string\n present: boolean\n kind: string\n lengthBucket?: number\n}\n\nfunction text(input: string): string {\n return `${input.length}:${input}`\n}\n\nfunction numberText(input: number): string {\n return String(input)\n}\n\nfunction booleanText(input: boolean): string {\n return input ? '1' : '0'\n}\n\nfunction compareEnvVar(left: RedactedEnvVar, right: RedactedEnvVar): number {\n if (left.name !== right.name) {\n return left.name < right.name ? -1 : 1\n }\n\n if (left.present !== right.present) {\n return left.present ? 1 : -1\n }\n\n if (left.kind !== right.kind) {\n return left.kind < right.kind ? -1 : 1\n }\n\n const leftBucket = left.lengthBucket ?? -1\n const rightBucket = right.lengthBucket ?? -1\n return leftBucket - rightBucket\n}\n\nfunction envRecord(input: RedactedEnvVar): string {\n return [\n text(input.name),\n booleanText(input.present),\n text(input.kind),\n input.lengthBucket === undefined ? '' : numberText(input.lengthBucket),\n ].join('')\n}\n\nexport function relevantEnvDigest(vars: readonly RedactedEnvVar[], salt: string): string {\n const body = [...vars].sort(compareEnvVar).map(envRecord).join('')\n return sha256hex(`${text(salt)}${body}`)\n}\n","import type { Platform } from '../action/index'\nimport { sha256hex16 } from './sha256'\n\ndeclare const cacheKeyBrand: unique symbol\n\nexport type CacheKey = string & { readonly [cacheKeyBrand]: 'CacheKey' }\n\nexport interface CacheableStepInput {\n platform: Platform\n suiteConfigDigest: string\n testConfigDigest: string\n stepText: string\n stepIndex: number\n testIndex: number\n relevantEnvDigest: string\n screenIdentityHash: string\n}\n\nexport interface NonCacheableStepInput {\n cacheable: false\n reason: string\n}\n\nfunction text(input: string): string {\n return `${input.length}:${input}`\n}\n\nexport function computeCacheKey(input: CacheableStepInput): CacheKey {\n const preimage = [\n input.platform,\n input.suiteConfigDigest,\n input.testConfigDigest,\n input.stepText,\n String(input.stepIndex),\n String(input.testIndex),\n input.relevantEnvDigest,\n input.screenIdentityHash,\n ].map(text).join('')\n\n return sha256hex16(preimage) as CacheKey\n}\n","import { canonicalJson } from './canonical-json'\nimport { sha256hex } from './sha256'\n\n/**\n * One model-visible tool definition with parameters already converted to plain JSON Schema.\n * The runner-side `describeBoundSurface` producer converts with `z.toJSONSchema`; Zod never\n * enters this browser-safe schema package (D-15).\n */\nexport interface ToolSurfaceEntry {\n name: string\n description: string\n parameters: unknown\n}\n\nfunction text(input: string): string {\n return `${input.length}:${input}`\n}\n\nfunction compareTool(left: ToolSurfaceEntry, right: ToolSurfaceEntry): number {\n if (left.name === right.name) {\n return 0\n }\n return left.name < right.name ? -1 : 1\n}\n\nfunction toolRecord(input: ToolSurfaceEntry): string {\n return text(\n canonicalJson({\n name: input.name,\n description: input.description,\n parameters: input.parameters,\n }),\n )\n}\n\n/**\n * Hash the complete model-visible tool surface using deterministic canonical JSON (D-14).\n * Object keys and tool names are sorted; array order remains semantic and is preserved.\n */\nexport function computeToolSchemaDigest(tools: readonly ToolSurfaceEntry[]): string {\n const body = [...tools].sort(compareTool).map(toolRecord).join('')\n return sha256hex(`${text('tool-schema-digest')}${body}`)\n}\n","import { normalizeAccessibleName } from '../screen/index'\nimport type { Anchor } from './anchor'\n\nfunction normalizeHumanText(value: string): string {\n return value.trim().replace(/\\s+/g, ' ').toLowerCase()\n}\n\nfunction normalizeRoute(route: string): string {\n const normalized = normalizeHumanText(route)\n const hashIndex = normalized.indexOf('#')\n const withoutHash = hashIndex === -1 ? normalized : normalized.slice(0, hashIndex)\n const queryIndex = withoutHash.indexOf('?')\n const path = queryIndex === -1 ? withoutHash : withoutHash.slice(0, queryIndex)\n const query = queryIndex === -1 ? '' : withoutHash.slice(queryIndex)\n const pathWithoutTrailingSlash = path === '/' ? path : path.replace(/\\/+$/, '')\n return `${pathWithoutTrailingSlash}${query}`\n}\n\n/**\n * D-07's provisional-shape-locked anchor normalization contract. Phase 377 may extend the\n * normalization values but must reuse this function: page routes casefold and lose hashes and\n * trailing slashes; flow and element names reuse normalizeAccessibleName; element roles trim and\n * casefold while ordinals survive; platform anchors are unchanged; selectors trim only; error\n * messages casefold, collapse whitespace, and replace digit runs with '#'.\n */\nexport function normalizeAnchor(anchor: Anchor): Anchor {\n switch (anchor.t) {\n case 'page':\n return { t: 'page', route: normalizeRoute(anchor.route) }\n case 'flow':\n return { t: 'flow', name: normalizeAccessibleName(anchor.name) }\n case 'el': {\n const normalized = {\n t: 'el' as const,\n role: normalizeHumanText(anchor.role),\n name: normalizeAccessibleName(anchor.name),\n }\n return anchor.ordinal === undefined ? normalized : { ...normalized, ordinal: anchor.ordinal }\n }\n case 'platform':\n return anchor\n case 'selector':\n return { t: 'selector', literal: anchor.literal.trim() }\n case 'error':\n return { t: 'error', message: normalizeHumanText(anchor.message).replace(/\\d+/g, '#') }\n }\n}\n","/**\n * THE one canonical collision-free tuple encoding for product/scope/file/test identities\n * (ABRF-02, D-14 stable identity). JSON array serialization is injective over string tuples:\n * every quote/backslash/control character is escaped and the array form distinguishes both\n * part boundaries and arity, so distinct tuples never collide regardless of what delimiters\n * their parts contain. Keys are IN-MEMORY join/dedup/admission identities — never a storage\n * schema; projection columns stay separate. Equality is exact code-unit equality with NO\n * unicode normalization by design, matching SQLite's byte equality on the projection columns.\n */\nexport function identityTupleKey(parts: readonly string[]): string {\n return JSON.stringify(parts)\n}\n","/**\n * Phase 375 D-01 graph identity contract (memory.md §6.1). Following Phase 374's D-06/D-07\n * early-identity precedent, node ids are stable before the first projection row exists: Phase 377\n * may extend ontology members, but it must never re-key this identity.\n */\nimport type { Platform } from '../action/index'\nimport { canonicalJson } from '../determinism/canonical-json'\nimport { sha256hex } from '../determinism/sha256'\nimport type { JsonObject } from '../run/run-artifact'\nimport type { Anchor } from './anchor'\nimport { normalizeAnchor } from './normalize-anchor'\n\nexport type GraphNodeType =\n | 'fact'\n | 'procedure'\n | 'caution'\n | 'unknown'\n | 'policy'\n | 'app'\n | 'suite'\n | 'test'\n | 'step'\n | 'flow'\n | 'error'\n | 'element'\n | 'page'\n | 'web-page'\n | 'web-element'\n | 'web-locator'\n | 'mobile-screen'\n | 'mobile-element'\n | 'android-locator'\n | 'ios-locator'\n\nexport type GraphEdgeType =\n | 'about'\n | 'part-of'\n | 'supersedes'\n | 'superseded-by'\n | 'derived-from'\n | 'conflicts-with'\n | 'relates-to'\n | 'renamed-from'\n | 'contains'\n | 'composed-of'\n | 'precedes'\n | 'on'\n | 'locates-via'\n | 'uses'\n | 'caused-by'\n | 'equivalent-to'\n\nexport type GraphNodeNaturalKey = string | JsonObject\n\ntype GraphNode = {\n type: GraphNodeType\n naturalKey: GraphNodeNaturalKey\n nodeId: string\n}\n\n/** Canonical type-plus-natural-key identity; tuple serialization prevents concatenation ambiguity. */\nexport function graphNodeId(type: GraphNodeType, naturalKey: GraphNodeNaturalKey): string {\n return sha256hex(canonicalJson([type, naturalKey]))\n}\n\nfunction graphNode(type: GraphNodeType, naturalKey: GraphNodeNaturalKey): GraphNode {\n return { type, naturalKey, nodeId: graphNodeId(type, naturalKey) }\n}\n\nfunction elementType(platform?: Platform): GraphNodeType {\n if (platform === 'web') return 'web-element'\n if (platform === undefined) return 'element'\n return 'mobile-element'\n}\n\nfunction pageType(platform?: Platform): GraphNodeType {\n if (platform === 'web') return 'web-page'\n if (platform === undefined) return 'page'\n return 'mobile-screen'\n}\n\n/** D-01 normalize-before-key projection from a bundle anchor into the closed graph ontology. */\nexport function anchorGraphNode(anchor: Anchor, platform?: Platform): GraphNode | null {\n const normalized = normalizeAnchor(anchor)\n\n switch (normalized.t) {\n case 'el': {\n const naturalKey: JsonObject =\n normalized.ordinal === undefined\n ? { role: normalized.role, name: normalized.name }\n : { role: normalized.role, name: normalized.name, ordinal: normalized.ordinal }\n return graphNode(elementType(platform), naturalKey)\n }\n case 'page':\n return graphNode(pageType(platform), normalized.route)\n case 'flow':\n return graphNode('flow', normalized.name)\n case 'error':\n return graphNode('error', normalized.message)\n case 'selector': {\n if (platform === undefined) return null\n const type =\n platform === 'web'\n ? 'web-locator'\n : platform === 'android'\n ? 'android-locator'\n : 'ios-locator'\n return graphNode(type, normalized.literal)\n }\n case 'platform':\n return null\n }\n}\n\n/** Total record-node mapping: the canonical bundle kind is the graph node type. */\nexport function recordGraphNode(\n kind: 'fact' | 'procedure' | 'caution' | 'unknown' | 'policy',\n bundleId: string,\n): { type: GraphNodeType; naturalKey: string; nodeId: string } {\n return { type: kind, naturalKey: bundleId, nodeId: graphNodeId(kind, bundleId) }\n}\n","import type { Action } from '../action/index'\nimport type { ArtifactRef } from '../ids/artifact-ref'\nimport type { RecordedActionResult } from '../result/index'\nimport type { ScreenState } from '../screen/screen-state'\nimport type { GroundingEvidence } from '../screen/target-descriptor'\nimport type { ModelCallRecord } from './model-call-profile'\nimport type { OperationEvidence } from './operation-evidence'\nimport type { LocalEffectEvidence } from './progress-evidence'\nimport type { ToolExchangeEvidence } from './tool-exchange'\n\nexport interface SubActionEvidence {\n plan: string\n plannedAction: Action\n stateBefore: ScreenState\n stateAfter?: ScreenState\n result: RecordedActionResult\n decisionScreenshotRef?: ArtifactRef\n artifactRefs?: ArtifactRef[]\n /**\n * The ordered non-action tool exchanges from the live planning turn that produced this\n * decision (D-01). Present, possibly empty, for live-turn decisions and structurally\n * absent for cache-hit or replayed sub-actions; values arrive masked under D-02.\n */\n exchanges?: ToolExchangeEvidence[]\n /**\n * Observed enrichment for the live call that produced this decision (D-05/D-08).\n * Absent when no live model call happened; unknown values are never fabricated.\n */\n callRecord?: ModelCallRecord\n /**\n * The §A8 grounding evidence (GROUND-02). Present only when the grounder ran for\n * this sub-action: it carries the descriptor the planner emitted plus one attempt\n * entry per ladder rung run — an unattempted visual rung records outcome 'skipped',\n * and `resolvedRef` is present only on a 'resolved' rung.\n */\n grounding?: GroundingEvidence\n /**\n * The §A8 differential-observation oracle outcome (CYCLE-01, D-07). Present only when\n * the per-verb intended-effect oracle ran for this sub-action: which oracle row keyed\n * on the verb class and whether the action's local intended effect was achieved.\n */\n localEffect?: LocalEffectEvidence\n /**\n * What this action produced outside the page (436 D-22): the downloads it started, and the\n * clipboard writes the app made. Absent when the action produced none; values arrive masked.\n */\n operationEvidence?: OperationEvidence\n // 2026-10-19 (444.1-08, D-14): plannedAction/stateBefore stay the planner's own; a heal that\n // re-dispatched records what it sent here (optional-additive).\n healedDispatch?: { action: Action; stateBefore: ScreenState }\n}\n\nexport function actedPair(\n subAction: SubActionEvidence,\n): { action: Action; stateBefore: ScreenState } {\n return subAction.healedDispatch ?? {\n action: subAction.plannedAction,\n stateBefore: subAction.stateBefore,\n }\n}\n\nexport function isRedispatchedHeal(subAction: SubActionEvidence): boolean {\n return subAction.healedDispatch !== undefined\n}\n","// The exercised-anchors walk, promoted from the CLI's curation tail (Phase 389, D-13).\n//\n// Pure over schema types — StepEvidence in, Anchor[] out — and promoted HERE because three\n// consumers now need one spelling of it: the CLI's candidate/canary emission (which\n// re-exports from this module so every existing call site compiles unchanged), plan 05's\n// agent-side cluster function, and 390's recurrence window. knowledge-local already treats\n// the extraction as an injected pure seam (`ExtractStepAnchors`); this is that seam's one\n// implementation, living where both sides of the package graph can reach it.\n\nimport type { StepEvidence } from '../handoff/step-evidence'\nimport { isRedispatchedHeal, type SubActionEvidence } from '../handoff/sub-action-evidence'\nimport type { ElementInfo } from '../screen/element-info'\nimport { elementOrdinal } from '../screen/element-ordinal'\nimport type { Anchor } from './anchor'\n\nexport interface ResolvedElementEvidence {\n subAction: SubActionEvidence\n element: ElementInfo\n ordinal: number\n locator?: string\n}\n\nexport interface ClassifiedRoute {\n navigated: boolean\n route?: string\n}\n\nfunction quoteAttribute(value: string): string {\n return value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"')\n}\n\nfunction locatorForElement(element: ElementInfo): string | undefined {\n const explicit =\n element.attributes.selector\n ?? element.attributes.cssSelector\n ?? element.attributes.xpath\n if (explicit !== undefined && explicit.trim() !== '') return explicit.trim()\n\n const testId = element.attributes['data-testid'] ?? element.labels.testId\n if (testId !== undefined && testId !== '') {\n return `[data-testid=\"${quoteAttribute(testId)}\"]`\n }\n\n const resourceId = element.attributes['resource-id']\n if (resourceId !== undefined && resourceId !== '') {\n return `[resource-id=\"${quoteAttribute(resourceId)}\"]`\n }\n\n const accessibilityId = element.attributes['accessibility-id']\n if (accessibilityId !== undefined && accessibilityId !== '') {\n return `[accessibility-id=\"${quoteAttribute(accessibilityId)}\"]`\n }\n\n const id = element.attributes.id\n return id === undefined || id === '' ? undefined : `[id=\"${quoteAttribute(id)}\"]`\n}\n\nexport function actionRefs(subAction: SubActionEvidence): string[] {\n const action = subAction.plannedAction\n const refs: string[] = []\n if ('ref' in action && typeof action.ref === 'string') refs.push(action.ref)\n if ('fromRef' in action && typeof action.fromRef === 'string') refs.push(action.fromRef)\n if ('toRef' in action && typeof action.toRef === 'string') refs.push(action.toRef)\n return refs\n}\n\nfunction resolvedActionRefs(subAction: SubActionEvidence): string[] {\n // 2026-10-19 (444.1-08, D-14): a heal's grounding refs index the dispatch tree, not stateBefore.\n if (isRedispatchedHeal(subAction)) return actionRefs(subAction)\n const grounded = (subAction.grounding?.attempts ?? []).flatMap((attempt) =>\n attempt.outcome === 'resolved' && attempt.resolvedRef !== undefined\n ? [attempt.resolvedRef]\n : [],\n )\n return grounded.length === 0 ? actionRefs(subAction) : grounded\n}\n\n/** Shared handoff walk for evidence that resolved against the live pre-action screen. */\nexport function resolvedElementEvidence(step: StepEvidence): ResolvedElementEvidence[] {\n const byIdentity = new Map<string, ResolvedElementEvidence>()\n for (const subAction of step.subActions) {\n for (const ref of resolvedActionRefs(subAction)) {\n const element = subAction.stateBefore.elements.find((candidate) => candidate.ref === ref)\n if (element === undefined) continue\n const ordinal = elementOrdinal(element, subAction.stateBefore.elements)\n const identity = [\n subAction.stateBefore.platform,\n element.role,\n element.nameNormalized,\n ordinal,\n ].join('\\u0000')\n if (!byIdentity.has(identity)) {\n const locator = locatorForElement(element)\n byIdentity.set(identity, {\n subAction,\n element,\n ordinal,\n ...(locator === undefined ? {} : { locator }),\n })\n }\n }\n }\n return [...byIdentity.values()]\n}\n\nexport function elementAnchor(\n evidence: ResolvedElementEvidence,\n): Extract<Anchor, { t: 'el' }> {\n return {\n t: 'el',\n role: evidence.element.role,\n name: evidence.element.nameNormalized,\n ordinal: evidence.ordinal,\n }\n}\n\nexport function classifySubActionRoute(subAction: SubActionEvidence): ClassifiedRoute {\n const before = subAction.stateBefore.url\n const after = subAction.stateAfter?.url\n if (before !== undefined && after !== undefined && before !== after) {\n return { navigated: true, route: after }\n }\n return {\n navigated: false,\n ...(before === undefined ? {} : { route: before }),\n }\n}\n\nexport function uniqueAnchors(anchors: readonly Anchor[]): Anchor[] {\n const seen = new Set<string>()\n return anchors.filter((anchor) => {\n const key = JSON.stringify(anchor)\n if (seen.has(key)) return false\n seen.add(key)\n return true\n })\n}\n\n/** Pin 1: typed handoff evidence currently carries element and page contact, not flow contact. */\nexport function exercisedAnchors(step: StepEvidence): Anchor[] {\n return uniqueAnchors([\n ...resolvedElementEvidence(step).map(elementAnchor),\n ...step.subActions.flatMap((subAction) => {\n const { route } = classifySubActionRoute(subAction)\n return route === undefined ? [] : [{ t: 'page' as const, route }]\n }),\n ])\n}\n","/**\n * Phase 377 read-side mirror of memory.md §7.3.2 supersession grouping.\n * Phase 378's write-side disposition must share this helper so Curator and retrieval collapse use\n * the same normalized, order-independent anchor identity (377 Pitfall 7).\n */\nimport { canonicalJson } from '../determinism/canonical-json'\nimport { sha256hex } from '../determinism/sha256'\nimport type { Anchor } from './anchor'\nimport { normalizeAnchor } from './normalize-anchor'\n\n/** Hashes a normalized anchor set without mutating the caller's array. */\nexport function supersessionKey(anchors: readonly Anchor[]): string {\n const sortedNormalized = anchors.map(normalizeAnchor)\n sortedNormalized.sort((left, right) => {\n const leftJson = canonicalJson(left)\n const rightJson = canonicalJson(right)\n return leftJson < rightJson ? -1 : leftJson > rightJson ? 1 : 0\n })\n\n return sha256hex(canonicalJson(sortedNormalized))\n}\n","/** A source-version keyed sequence of one-version-at-a-time migrations (D-13). */\nexport type MigrationRegistry = Record<number, (doc: unknown) => unknown>\n\nexport interface VersionGuardConfig<T> {\n name: string\n current: number\n migrations: MigrationRegistry\n error?: new (found: number, supported: number) => Error\n /**\n * Fail-closed structural check applied after the migration walk. `schemaVersion`\n * states which contract a document claims; this hook verifies that the migrated\n * document structurally honors the current contract before consumers traverse it.\n */\n shape?: (migrated: unknown) => boolean\n}\n\n/** Typed rejection shared by every schema-versioned document guard (D-13). */\nexport class VersionGuardError extends Error {\n readonly documentName: string\n readonly foundVersion: number\n readonly supportedVersion: number\n\n constructor(documentName: string, found: number, supported: number) {\n super(\n `${documentName} schemaVersion ${found} is not supported (this build supports ${supported})`,\n )\n this.name = 'VersionGuardError'\n this.documentName = documentName\n this.foundVersion = found\n this.supportedVersion = supported\n }\n}\n\n/**\n * Builds the ONE parse → reject-newer → migration-walk → cast version guard flow (D-13).\n */\nexport function createVersionGuard<T>(config: VersionGuardConfig<T>): (value: unknown) => T {\n const versionError = (found: number): Error =>\n config.error === undefined\n ? new VersionGuardError(config.name, found, config.current)\n : new config.error(found, config.current)\n\n return (value: unknown): T => {\n if (value === null || typeof value !== 'object') {\n throw new TypeError(`${config.name} must be an object`)\n }\n\n const version = (value as { schemaVersion?: unknown }).schemaVersion\n if (typeof version !== 'number' || !Number.isFinite(version)) {\n throw new TypeError(`${config.name} requires a numeric schemaVersion`)\n }\n\n if (version > config.current) {\n throw versionError(version)\n }\n\n let migrated: unknown = value\n for (let from = version; from < config.current; from++) {\n const migrate = config.migrations[from]\n if (migrate === undefined) {\n throw versionError(version)\n }\n migrated = migrate(migrated)\n }\n\n if (config.shape !== undefined && !config.shape(migrated)) {\n throw new TypeError(`${config.name} failed structural validation`)\n }\n\n return migrated as T\n }\n}\n","import { z } from 'zod'\n\nimport { slugBranch } from '../ids/slug'\n\ndeclare const runIdBrand: unique symbol\n\nexport type RunId = string & { readonly [runIdBrand]: 'RunId' }\n\nexport const asRunId = (value: string): RunId => value as RunId\n\n/**\n * THE run-id codec (2026-08-23, Phase 401 plan 20 · CR-04). One declaration, four call sites.\n *\n * WHAT IT REFUSES, AND WHY SCHEMA IS ALLOWED TO. A run id BECOMES A DIRECTORY NAME:\n * `<configDir>/.agent-qa/runs/<slugBranch(runId)>/` is where a run's `events.jsonl`, its\n * `handoff.json` and its audit rows live. Path-safety on the value that names that directory is\n * therefore a property of the id itself, and it is judgeable without leaving this package.\n *\n * THE PREDICATE IS `slugBranch` — NOT A SECOND SPELLING OF ITS RULES. The one security-reviewed\n * path-segment sanitizer already lives here (`ids/slug.ts`), and the run directory is derived\n * through it. So the rule this codec states is exactly: *an id the path layer would have to\n * REWRITE is refused rather than rewritten*. Re-deriving \"separators, `..`, control characters\"\n * as a regex here would be a second copy of that file's rules, free to disagree with it the day\n * either one changes — and it is a disagreement between those two that a traversal defect is made\n * of. Empty falls out of the same clause: `slugBranch('')` is `'default'`, which is precisely the\n * rewrite this refuses (measured pre-fix: an empty caller-supplied id ran a whole run into a\n * shared `runs/default/` directory).\n *\n * IT IS DELIBERATELY NOT THE CANONICAL ID SHAPE. `r_`-prefixed ten-word ids are\n * `@vostride/agent-qa-ids`' vocabulary; this package has zero internal dependencies and may not\n * name it, and re-spelling `isCanonicalRunId` here would be a second definition of a run's\n * identity. \"Is this an id this system would have minted\" is asked in the invocation core, where\n * the canonical predicate can be injected from the package that owns it.\n */\nexport const runIdSchema = z\n .string()\n .refine((value) => slugBranch(value) === value, {\n message:\n 'a run id must be usable, exactly as written, as the name of the run\\'s own directory: '\n + 'it may not be empty, and may not carry path separators, parent-directory segments or '\n + 'control characters',\n })\n .transform(asRunId)\n","// The ONE security-reviewed pure path-segment sanitizer (D-07 / T-360-03).\n// It lives in schema so provider/storage-neutral eval core can derive safe cassette ids\n// without depending on runner-local or duplicating traversal-sensitive string handling.\n\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARS_RE = /[\\u0000-\\u001f\\u007f]/g\n\n/**\n * Turn a branch name into a single safe path segment (security V5): strip control\n * characters, neutralize path separators and parent-dir `..` sequences, and reject\n * leading/trailing dots so a branch name can never traverse out of the cache root.\n */\nexport function slugBranch(name: string): string {\n const slug = name\n .replace(CONTROL_CHARS_RE, '') // control chars\n .replace(/\\.\\.+/g, '-') // parent-dir sequences\n .replace(/[/\\\\]/g, '-') // path separators\n .replace(/[^A-Za-z0-9._-]/g, '-') // anything else unsafe\n .replace(/^[.\\-]+/, '') // no leading dot/dash (., .., hidden dirs)\n .replace(/[.\\-]+$/, '') // no trailing dot/dash\n\n return slug.length > 0 ? slug : 'default'\n}\n","// Run-artifact payload type family (Phase 363, D-08 — relocated from core/src/artifacts).\n//\n// These are PURE, host-API-free types (the schema-package discipline: no globalThis/fetch/fs/\n// node:*). They describe the durable \"run-artifact document\": the config snapshot + test/suite\n// source snapshot + terminal errors a run persists. Two consumers share the shapes — the\n// dashboard SQLite `run_artifacts` payload (the real document) and the runner-owned\n// `FsRunArtifactStore` file-side artifact.json (D-08, RESEARCH Q5) — so the type family lives in\n// the lowest shared layer (schema) rather than core. `attributes` is typed structurally as\n// `Record<string, string>` (the core `RunAttributes` alias) so schema takes no core dependency.\n\nexport const RUN_ARTIFACT_SCHEMA_VERSION = 2 as const\n\n/**\n * What a finalized run artifact is ABOUT (405-11, closing 405-07's deferral).\n *\n * TWO MEMBERS, NOT FOUR. It used to admit a suite parent and a suite child as well. 405-07 narrowed\n * the dashboard store's own column to refuse both — after the parent/child split was retired, a\n * suite's members live under ONE run as handles — so nothing can write either value and the two\n * members were unreachable breadth on every reader. They were left in place then because the UI\n * badge switches on this value and narrowing a union a render site reads belongs with that render\n * site; that edit landed with this one.\n */\nexport type RunArtifactKind = 'test' | 'unknown'\n\nexport type JsonPrimitive = string | number | boolean | null\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray\nexport interface JsonObject {\n [key: string]: JsonValue\n}\nexport type JsonArray = JsonValue[]\n\nexport type ArtifactRecord = Record<string, unknown>\n\nexport interface RunArtifactMetadata extends ArtifactRecord {\n // Structurally the core `RunAttributes` alias (Record<string, string>); inlined so schema\n // stays free of a core dependency.\n attributes?: Record<string, string>\n}\n\nexport interface RunArtifactTerminalError {\n code: string\n message: string\n phase: string\n details?: unknown\n}\n\nexport interface RunArtifactConfigSnapshot {\n rawConfigContent?: string | null\n parsedConfig?: unknown\n effectiveConfig?: unknown\n envFile?: {\n path: string | null\n content: string | null\n variables: Record<string, string>\n }\n secretsFile?: {\n path: string | null\n status: 'loaded' | 'missing' | 'unreadable' | 'invalid'\n count?: number\n } | null\n cliVars?: Record<string, string>\n inlineVars?: Record<string, string>\n hooks?: Array<{ id: string; name: string; runtime?: string; sourcePath?: string }>\n model?: {\n planner?: { provider?: string; model?: string }\n verifier?: { provider?: string; model?: string }\n }\n runtime?: ArtifactRecord\n timeouts?: ArtifactRecord\n cache?: ArtifactRecord\n memory?: ArtifactRecord\n}\n\nexport interface RunArtifactTestSourceSnapshot {\n kind: 'test'\n testId?: string | null\n name?: string | null\n filePath?: string | null\n rawYaml?: string | null\n resolvedDefinition?: unknown\n loadStatus?: 'queued' | 'loaded' | 'parse-error' | 'setup-error' | 'runtime-error' | 'missing' | 'validation-error' | 'skipped'\n error?: RunArtifactTerminalError\n}\n\nexport interface RunArtifactSuiteMemberSnapshot {\n index: number\n ref: { test: string; id?: string }\n filePath?: string | null\n testId?: string | null\n name?: string | null\n target?: string | null\n rawYaml?: string | null\n resolvedDefinition?: unknown | null\n loadStatus: 'loaded' | 'missing' | 'parse-error' | 'validation-error' | 'skipped'\n error?: RunArtifactTerminalError\n childRunId?: string\n skipReason?: string\n config?: RunArtifactConfigSnapshot | ArtifactRecord\n}\n\nexport interface RunArtifactSuiteSourceSnapshot {\n kind: 'suite'\n suiteId?: string | null\n name?: string | null\n filePath?: string | null\n rawYaml?: string | null\n resolvedDefinition?: unknown\n loadStatus?: 'queued' | 'loaded' | 'parse-error' | 'setup-error' | 'runtime-error' | 'missing' | 'validation-error' | 'skipped'\n members?: RunArtifactSuiteMemberSnapshot[]\n error?: RunArtifactTerminalError\n}\n\n// 2026-10-17 (444-03, D-07): a run of several tests outside one suite; each member carries its own\n// source and config, and the run holds none of its own.\nexport interface RunArtifactTestsSourceSnapshot {\n kind: 'tests'\n members: RunArtifactSuiteMemberSnapshot[]\n}\n\nexport interface RunArtifactRuntimeSnapshot extends ArtifactRecord {\n status?: string\n duration?: number\n startedAt?: string\n endedAt?: string\n failureSummary?: string | null\n}\n\nexport interface RunArtifactPayload {\n schemaVersion: typeof RUN_ARTIFACT_SCHEMA_VERSION\n config?: RunArtifactConfigSnapshot | ArtifactRecord\n source?:\n | RunArtifactTestSourceSnapshot\n | RunArtifactSuiteSourceSnapshot\n | RunArtifactTestsSourceSnapshot\n | ArtifactRecord\n runtime?: RunArtifactRuntimeSnapshot\n errors?: RunArtifactTerminalError[]\n metadata?: RunArtifactMetadata\n}\n\nexport interface RunArtifactStageInput extends Partial<Omit<RunArtifactPayload, 'schemaVersion'>> {\n schemaVersion?: typeof RUN_ARTIFACT_SCHEMA_VERSION\n}\n\nexport interface RunArtifactFinalizeInput extends RunArtifactStageInput {\n finalizedAt?: string\n}\n\nexport interface RunArtifactReporterContext {\n runId?: string\n parentRunId?: string | null\n artifact?: RunArtifactStageInput & {\n kind?: RunArtifactKind\n suiteIndex?: number\n parentRunId?: string | null\n }\n}\n","import { z } from 'zod'\nimport { EvidenceArtifactRefSchema } from '../ids/artifact-ref'\n\nexport type NetworkBodyContentType =\n | 'application/json' | 'text/html' | 'text/plain' | 'application/xml'\n | 'text/xml' | 'application/x-www-form-urlencoded'\nexport const NETWORK_BODY_CONTENT_TYPES = [\n 'application/json', 'text/html', 'text/plain', 'application/xml', 'text/xml',\n 'application/x-www-form-urlencoded',\n] as const satisfies readonly NetworkBodyContentType[]\nexport const NETWORK_BODY_MAX_BYTES = 32768\n\nexport type EvidenceKind = 'console' | 'network' | 'a11y' | 'aria' | 'variables'\nexport const EVIDENCE_KINDS = [\n 'console', 'network', 'a11y', 'aria', 'variables',\n] as const satisfies readonly EvidenceKind[]\nexport type EvidenceAbsenceReason =\n | 'empty' | 'not-captured' | 'unsupported' | 'unavailable' | 'failed'\nexport const EVIDENCE_ABSENCE_REASONS = [\n 'empty', 'not-captured', 'unsupported', 'unavailable', 'failed',\n] as const satisfies readonly EvidenceAbsenceReason[]\nexport const EvidenceKindSchema = z.enum(EVIDENCE_KINDS)\nexport const EvidenceAbsenceReasonSchema = z.enum(EVIDENCE_ABSENCE_REASONS)\n\nconst count = z.number().int().nonnegative()\nexport const ConsoleEvidenceRecordSchema = z.strictObject({\n level: z.string(), text: z.string(), timestamp: z.number(),\n location: z.strictObject({ url: z.string(), lineNumber: count, columnNumber: count }).optional(),\n})\nexport const NetworkEvidenceRecordSchema = z.strictObject({\n url: z.string(), method: z.string(), status: count,\n requestHeaders: z.record(z.string(), z.string()),\n responseHeaders: z.record(z.string(), z.string()),\n body: z.string().optional(), requestBody: z.string().optional(),\n startTime: z.number(), endTime: z.number(),\n timing: z.record(z.string(), z.number()).optional(),\n requestSize: count.optional(), responseSize: count.optional(),\n})\nexport const A11yEvidenceRecordSchema = z.strictObject({\n ruleId: z.string(), impact: z.enum(['minor', 'moderate', 'serious', 'critical']),\n description: z.string(), help: z.string(), helpUrl: z.string(),\n nodes: z.array(z.strictObject({ html: z.string(), target: z.array(z.string()) })),\n})\nconst VariableSnapshotEntrySchema = z.strictObject({\n value: z.string(), source: z.enum(['env', 'inline', 'suite', 'cli', 'capture', 'hook', 'step']),\n})\ntype VariableSnapshotEntry = z.infer<typeof VariableSnapshotEntrySchema>\nconst PRESERVED_PROTO = Symbol('preserved __proto__ entry')\ntype PreservedProto = { [PRESERVED_PROTO]?: VariableSnapshotEntry }\n// Captured names are data, but Zod's record parser skips an own __proto__ and its intersection\n// merge deletes one. The second arm validates that entry and carries it through the merge under a\n// symbol, and the last stage restores it as an own property. The record supplies the JSON-schema\n// input contract and validates every other entry.\nexport const VariableSnapshotSchema = z.record(z.string(), VariableSnapshotEntrySchema).and(\n z.unknown().transform((input, ctx): object => {\n if (typeof input !== 'object' || input === null || !Object.hasOwn(input, '__proto__')) return {}\n const entry = VariableSnapshotEntrySchema.safeParse(\n Object.getOwnPropertyDescriptor(input, '__proto__')?.value,\n )\n if (entry.success) return { [PRESERVED_PROTO]: entry.data } satisfies PreservedProto\n for (const issue of entry.error.issues) {\n ctx.addIssue({ code: 'custom', message: issue.message, path: ['__proto__', ...issue.path] })\n }\n return {}\n }),\n).transform((merged): Record<string, VariableSnapshotEntry> => {\n const { [PRESERVED_PROTO]: preserved, ...entries } = merged as typeof merged & PreservedProto\n return preserved === undefined ? entries : Object.defineProperty(entries, '__proto__', {\n value: preserved, enumerable: true, writable: true, configurable: true,\n })\n})\nexport type VariableSnapshot = z.infer<typeof VariableSnapshotSchema>\n\nexport const RUN_EVIDENCE_DOCUMENT_SCHEMA_VERSION = 2\n\nexport const ConsoleEvidenceDocumentSchema = z.strictObject({\n schemaVersion: z.literal(RUN_EVIDENCE_DOCUMENT_SCHEMA_VERSION), kind: z.literal('console'),\n records: z.array(ConsoleEvidenceRecordSchema),\n})\nexport const NetworkEvidenceDocumentSchema = z.strictObject({\n schemaVersion: z.literal(RUN_EVIDENCE_DOCUMENT_SCHEMA_VERSION), kind: z.literal('network'),\n records: z.array(NetworkEvidenceRecordSchema),\n})\nexport const A11yEvidenceDocumentSchema = z.strictObject({\n schemaVersion: z.literal(RUN_EVIDENCE_DOCUMENT_SCHEMA_VERSION), kind: z.literal('a11y'),\n records: z.array(A11yEvidenceRecordSchema),\n})\nexport const AriaEvidenceDocumentSchema = z.strictObject({\n schemaVersion: z.literal(RUN_EVIDENCE_DOCUMENT_SCHEMA_VERSION), kind: z.literal('aria'),\n tree: z.string(),\n})\n// Variables share the read-document shape but remain inline; they have no blob ref kind.\nexport const VariablesEvidenceDocumentSchema = z.strictObject({\n schemaVersion: z.literal(RUN_EVIDENCE_DOCUMENT_SCHEMA_VERSION), kind: z.literal('variables'),\n records: VariableSnapshotSchema,\n})\nexport const EvidenceDocumentSchema = z.discriminatedUnion('kind', [\n ConsoleEvidenceDocumentSchema, NetworkEvidenceDocumentSchema, A11yEvidenceDocumentSchema,\n AriaEvidenceDocumentSchema, VariablesEvidenceDocumentSchema,\n])\nexport type EvidenceDocument = z.infer<typeof EvidenceDocumentSchema>\n\nconst consolePresent = z.strictObject({\n kind: z.literal('console'), state: z.literal('present'),\n ref: EvidenceArtifactRefSchema.refine(ref => ref.id.startsWith('console-evidence:')),\n counts: z.strictObject({ total: count, errors: count, warnings: count }),\n})\nconst networkPresent = z.strictObject({\n kind: z.literal('network'), state: z.literal('present'),\n ref: EvidenceArtifactRefSchema.refine(ref => ref.id.startsWith('network-evidence:')),\n counts: z.strictObject({ total: count, failed: count, errored: count }),\n})\nconst a11yPresent = z.strictObject({\n kind: z.literal('a11y'), state: z.literal('present'),\n ref: EvidenceArtifactRefSchema.refine(ref => ref.id.startsWith('a11y-evidence:')),\n counts: z.strictObject({ minor: count, moderate: count, serious: count, critical: count }),\n})\nconst ariaPresent = z.strictObject({\n kind: z.literal('aria'), state: z.literal('present'),\n ref: EvidenceArtifactRefSchema.refine(ref => ref.id.startsWith('aria-state:')),\n})\nconst variablesPresent = z.strictObject({\n kind: z.literal('variables'), state: z.literal('present'), counts: z.strictObject({ count }),\n})\nconst absent = z.strictObject({\n kind: EvidenceKindSchema, state: z.literal('absent'), reason: EvidenceAbsenceReasonSchema,\n evidenceIncomplete: z.boolean().optional(),\n})\nexport const EvidenceEntrySchema = z.union([\n consolePresent, networkPresent, a11yPresent, ariaPresent, variablesPresent, absent,\n])\nexport type EvidenceEntry = z.infer<typeof EvidenceEntrySchema>\nconst presentByKind = {\n console: consolePresent, network: networkPresent, a11y: a11yPresent, aria: ariaPresent,\n variables: variablesPresent,\n}\n// Not EvidenceEntrySchema intersected with a kind literal: Zod reconciles away a key that only one\n// side of an intersection rejects, so a strict arm's stray key would pass.\nexport const evidenceEntryOfKind = <Kind extends EvidenceKind>(kind: Kind) =>\n z.union([presentByKind[kind], absent.extend({ kind: z.literal(kind) })])\nexport type AriaEvidenceEntry =\n | Extract<EvidenceEntry, { kind: 'aria'; state: 'present' }>\n | (Extract<EvidenceEntry, { state: 'absent' }> & { kind: 'aria' })\nexport type StepEvidenceEntries = {\n [K in Exclude<EvidenceKind, 'aria'>]:\n | Extract<EvidenceEntry, { kind: K; state: 'present' }>\n | (Extract<EvidenceEntry, { state: 'absent' }> & { kind: K })\n}\n","import { z } from 'zod'\n\nexport interface ArtifactRef {\n id: string\n sha: string\n evidenceIncomplete?: boolean\n}\n\nexport type EvidenceRefPrefix =\n | 'decision-screenshot:'\n | 'console-evidence:'\n | 'network-evidence:'\n | 'a11y-evidence:'\n | 'aria-state:'\n\nexport const EVIDENCE_REF_PREFIXES = [\n 'decision-screenshot:',\n 'console-evidence:',\n 'network-evidence:',\n 'a11y-evidence:',\n 'aria-state:',\n] as const satisfies readonly EvidenceRefPrefix[]\n\nexport const EvidenceArtifactRefSchema = z.strictObject({\n id: z.templateLiteral([z.enum(EVIDENCE_REF_PREFIXES), z.string()]),\n sha: z.string().regex(/^[a-f0-9]{64}$/),\n evidenceIncomplete: z.boolean().optional(),\n}).refine(ref => EVIDENCE_REF_PREFIXES.some(prefix => ref.id === `${prefix}${ref.sha}`), {\n message: 'Evidence ref id must contain its exact SHA and a known prefix',\n})\n\nexport type EvidenceArtifactRef = z.infer<typeof EvidenceArtifactRefSchema>\n","export type RunStatus = 'passed' | 'failed' | 'healed' | 'timeout' | 'cancelled'\n\nexport type ExecutionContext = 'local-interactive' | 'local-headless' | 'ci' | 'cloud'\n\n/**\n * The execution-context vocabulary as a VALUE, so more than one zod schema can enumerate it\n * without each keeping its own copy (393: the analyze-run payload mirror is the second reader).\n * Spelled once, beside the type it closes over, per the one-exported-vocabulary rule.\n */\nexport const EXECUTION_CONTEXT_VALUES = [\n 'local-interactive',\n 'local-headless',\n 'ci',\n 'cloud',\n] as const satisfies readonly ExecutionContext[]\n","import { z } from 'zod'\n\n/**\n * The live-view transport families a run handle can declare (403 D-05/D-08). `cdp-screencast` is\n * the continuous stream; `snapshot` is the labelled 1s fallback frames arrive through when\n * continuous streaming is unavailable (PXH-LIVE-02, 428 D-11), delivered on the same hub, socket\n * and embed page. `snapshot` supersedes 403 D-08's rejection of stills (the dated note lands in\n * 428 Plan 27). `mjpeg` (mobile, M6) and `webrtc` (headful phase 2) are named here so a consumer\n * switches on a DECLARED kind rather than on a browser name or an adapter class (LIVE-04's\n * prohibition).\n */\nexport type LiveStreamKind = 'cdp-screencast' | 'snapshot' | 'mjpeg' | 'webrtc'\n// prettier-ignore\nexport const LIVE_STREAM_KINDS = [\n 'cdp-screencast',\n 'snapshot',\n 'mjpeg',\n 'webrtc',\n] as const satisfies readonly LiveStreamKind[]\n\n/**\n * What a handle declares about its live stream. `{ kind: 'none' }` is the HONEST absent state —\n * a non-Chromium target, a finished member, or an adapter with no capability. It is never an\n * error and never a blank frame: the surface renders the no-stream state by name.\n */\nexport type LiveStreamDeclaration = { kind: LiveStreamKind } | { kind: 'none' }\n\n/** The zod mirror of {@link LiveStreamDeclaration} — a discriminated union on `kind`. */\nexport const LiveStreamDeclarationSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('cdp-screencast') }).strict(),\n z.object({ kind: z.literal('snapshot') }).strict(),\n z.object({ kind: z.literal('mjpeg') }).strict(),\n z.object({ kind: z.literal('webrtc') }).strict(),\n z.object({ kind: z.literal('none') }).strict(),\n])\n\n/**\n * Per-frame geometry as the producer reported it (CDP `screencastFrame.metadata`), plus the frame's\n * time. `timestamp` is the frame's CAPTURE time in integer epoch milliseconds, stamped by the\n * producer at capture (428 D-15). It is the one definition of a frame's time on every layer: the\n * hub fills it from its own clock only when a producer left it out, and never overwrites it.\n */\nexport interface LiveFrameMetadata {\n width: number\n height: number\n timestamp?: number\n scrollOffsetX?: number\n scrollOffsetY?: number\n}\n\n/**\n * ONE live frame as DATA (403 D-05): an id to ack with, the encoded bytes, and geometry. No\n * `Page`, no `CDPSession`, no handle of any kind crosses this type — which is what lets frames\n * travel a side channel while the run event bus stays silent about them (LIVE-03).\n */\nexport interface LiveFrame {\n id: number\n bytes: Uint8Array\n metadata: LiveFrameMetadata\n /** The kind of the capability that produced this frame, stamped by the hub when the producer did not set it. */\n kind?: LiveStreamKind\n}\n\n/**\n * Why a handle's frame stream ended under its subscribers (428; the hub speaks them from Plan 04).\n * `withdrawn`: the member's capability was withdrawn or replaced while its run continues.\n * `closed`: the hub itself closed, because the run or the editor session is over.\n */\nexport type LiveFrameEndReason = 'withdrawn' | 'closed'\n// prettier-ignore\nexport const LIVE_FRAME_END_REASONS = [\n 'withdrawn',\n 'closed',\n] as const satisfies readonly LiveFrameEndReason[]\n\n/**\n * A subscriber's hold on a handle's frame stream. `ack` reports that this subscriber consumed the\n * frame (the producer only asks for the next one once every subscriber has, or the ack bound\n * elapses); `unsubscribe` drops the hold and counts as acked for every outstanding frame.\n */\nexport interface LiveFrameSubscription {\n ack(frameId: number): void\n unsubscribe(): void\n}\n","/**\n * The `liveUrl` capability-token VOCABULARY (403 D-01..D-04).\n *\n * Types only — no minting, no validating, no key. The mint/validate PAIR lives at the function\n * layer (`packages/agent/src/functions/live-url.ts`) and the key lives in exactly one CLI\n * composition file, so a surface that wants a live view has to ask the function layer for one and\n * cannot grow a private token power of its own (LIVE-02's prohibition).\n */\n\n/** The only scope a `liveUrl` may carry today. Mode A control tokens are post-v2.0 (D-05). */\nexport const LIVE_URL_SCOPE = 'view' as const\n\n/**\n * Who a live-view token lets you watch: a run token never opens an editor session and the reverse\n * (428 D-07).\n */\nexport type LiveViewSubject =\n | { kind: 'run'; runId: string; handle: number }\n | { kind: 'editor'; sessionId: string }\n\nexport type LiveViewSubjectKind = LiveViewSubject['kind']\n\n// prettier-ignore\nexport const LIVE_VIEW_SUBJECT_KINDS = [\n 'run',\n 'editor',\n] as const satisfies readonly LiveViewSubject['kind'][]\n\n/** The expectation a validator is called with: the subject's kind and its path id. */\nexport type LiveViewSubjectRef = { kind: LiveViewSubjectKind; id: string }\n\n/**\n * What a `liveUrl` token asserts. `subject` is who the token lets you watch: a run handle (the\n * per-member handle the viewer attaches to) or an editor session. A run token never opens an\n * editor session and the reverse (428 D-07). `iat`/`exp` are ms-epoch, so the whole claims body is\n * JSON-and-integer only — no date parsing on the refusal path, and no ambiguity about units at the\n * boundary.\n */\nexport interface LiveUrlClaims {\n subject: LiveViewSubject\n scope: typeof LIVE_URL_SCOPE\n iat: number\n exp: number\n}\n\n/**\n * Every way a token can be refused, BY NAME (D-02/D-04). A refusal that a viewer can read is the\n * whole point: an expired link says so, a tampered one says so, and neither renders as a blank\n * frame that a person would read as \"the run is broken\".\n */\nexport const LIVE_URL_REFUSAL_REASONS = ['malformed', 'bad_signature', 'expired', 'scope_mismatch'] as const\n\nexport type LiveUrlRefusalReason = (typeof LIVE_URL_REFUSAL_REASONS)[number]\n\n/** The validator's total answer: accepted claims, or a named refusal. Never a boolean. */\nexport type LiveUrlVerdict =\n | { kind: 'ok'; claims: LiveUrlClaims }\n | { kind: 'refused'; reason: LiveUrlRefusalReason }\n\n/**\n * The signing seam (D-01). The function layer holds the ALGORITHM-FREE contract; the CLI\n * composition holds the per-process ephemeral key and the HMAC. `equals` is a member rather than a\n * `===` at the call site because a constant-time compare is a property of the implementation, and\n * a length-guarded one at that (Pitfall 9 — `timingSafeEqual` throws on unequal lengths).\n */\nexport interface LiveUrlSigner {\n sign(data: string): string\n equals(a: string, b: string): boolean\n}\n","import type { Action } from '../action/index'\nimport type { ArtifactRef } from '../ids/artifact-ref'\nimport type { RecordedActionResult } from '../result/index'\nimport type { GroundingEvidence } from '../screen/target-descriptor'\nimport type { ScopeKey } from '../identity/scope-key'\nimport type { MemberTestOutcome } from './member-outcome'\nimport type { ExecutionContext, RunStatus } from './run-status'\nimport type { RecordedRetrievalRung } from '../brief/retrieval-rung'\nimport type { VerifierVerdict } from '../handoff/step-evidence'\nimport type { AriaEvidenceEntry, StepEvidenceEntries, VariableSnapshot } from './evidence'\nimport type { ModelTokenUsage, ModelUsage } from './model-usage'\nimport type { RecordingEntry } from './recording'\n\n/** The bus schema version, declared once per run in `runStarted.payload.busSchemaVersion`. */\nexport const CURRENT_BUS_SCHEMA_VERSION = 2\n\n/**\n * The complete §2.2 event vocabulary M1 ships: every group EXCEPT the reserved\n * control/arbiter group (Live view / M5). Eleven lifecycle/diagnostic events plus the\n * six post-processing chip events — camelCase, names verbatim per spec §2.2\n * (Ratified 2026-07-05). The enum is append-only; the chip group is DEFINED here but\n * emitted by no M1 producer.\n *\n * 2026-08-26, Phase 404 D-02: the three reserved `issues*` chip names (started/completed/\n * failed) were REMOVED from this enum, from the payload aliases, from the {@link RunEvent}\n * union and from `handle-scope.ts`. They are spelled by pattern rather than verbatim here\n * on purpose: D-04's chip-side grep-clean bar treats a literal occurrence of any of the\n * three as a live reference, and a comment is not an exception worth carving. They were defined in bus schema 1 and emitted by no producer,\n * ever; they are removed after the 2026-08-25 amendment of `live-view.md` §4.3 and\n * `runner.md` §2.2 retired the reserved third chip. The append-only law protects\n * consumers of SHIPPED producers and therefore did not bind here — no reader on any wire\n * loses a name it could have received. Consumers now get a six-arm exhaustive switch\n * with no dead arms.\n */\nexport const RUN_EVENT_TYPES = [\n // Run lifecycle\n 'runStarted',\n 'runFinished',\n // Member-test lifecycle\n 'testStarted',\n 'testFinished',\n // Step lifecycle\n 'stepStarted',\n 'stepFinalized',\n // Sub-action evidence tick\n 'subActionRecorded',\n // Verdict\n 'verdict',\n // Diagnostics\n 'runWarning',\n 'runError',\n // Liveness\n 'heartbeat',\n // Post-processing / status chips — DEFINED in v1, emitted by no M1 producer\n 'analysisStarted',\n 'analysisCompleted',\n 'analysisFailed',\n 'curationStarted',\n 'curationCompleted',\n 'curationFailed',\n // Phase 363 D-01/Q-3 parity appends (append-only per spec §2.2): hook lifecycle\n // (hookStarted/hookFinished) closes the reporter-parity gap before the v1 Reporter\n // interface is deleted; testRetryScheduled (resolves RESEARCH Open Q-3) marks a\n // per-test attempt reset so subscribers don't corrupt accumulation on retries.\n 'hookStarted',\n 'hookFinished',\n 'testRetryScheduled',\n] as const\n\nexport type RunEventType = (typeof RUN_EVENT_TYPES)[number]\n\n// --- Run lifecycle payloads -------------------------------------------------\n\n/** `runStarted`: the {@link CompletedRunHandoff} header fields + the bus schema version. */\nexport interface RunStartedPayload {\n busSchemaVersion: number\n scope: ScopeKey\n executionContext: ExecutionContext\n buildOrdinal: number\n configDigests: {\n suiteConfigDigest: string\n testConfigDigest: string\n }\n memberTestCount: number\n /**\n * 402-04 D-10/D-14 additive-optional append (§2.2 payload-additive; the envelope shape and the\n * event-type list are both untouched): the run's HANDLE ROSTER — each member's derived\n * `testIndex`, in member order.\n *\n * This is the run announcing which per-member streams are attachable, so a client can validate\n * a `?handle=` request against a roster rather than against a guess, and so the roster is\n * announced by a PAYLOAD field rather than by a second event vocabulary on the wire. Optional\n * because the field is additive: a run that announces none simply cannot answer a per-handle\n * question. The shell always emits it.\n */\n handles?: readonly number[]\n}\n\n/**\n * `runFinished`: the last VERDICT-SCOPED event, exactly once.\n *\n * \"Always last\" until Phase 388, relaxed there to \"last verdict-scoped event\" — the wording,\n * not the guarantee (388 D-13/D-16; dated reconciliation C13 in `.planning/REQUIREMENTS.md`). It remains the last thing the run bus ever publishes and the last line of the\n * run's log at the moment the exit code is frozen — `finalSeq` is still its own seq, and every\n * bus subscriber has already been flushed. What may now follow it IN THE FILE is a\n * postProcessing chip envelope, appended directly to `events.jsonl` by the in-process post-run\n * tail and continuing this seq. That producer is not on the bus at all, so no subscriber can\n * observe an event after the one it was promised was last.\n *\n * Only the in-process leg appends. When the daemon drains the chain instead, nothing is\n * emitted onto the run bus and durable job state is the only truth — which is the 386 D-16\n * two-receipt rule: a second process never writes a finished run's log.\n *\n * `disposition` — SUPERSEDED 2026-08-26 (Phase 404, D-09). It read \"stays the literal\n * `'detached'`, deliberately\" while nothing decided it; it now carries the ratified three-value\n * {@link PostProcessingDisposition}, and the reason the old paragraph gave is exactly why the\n * three values mean what they do: this field is the POSTURE decided at the verdict, never a\n * report of the chain.\n *\n * - `handedOff` — a current-epoch writer-lease holder exists, so somebody else will drain.\n * - `drained` — no holder; THIS process took the lease and will pump under it.\n * - `detached` — `--detach`, a gate-run skip, or an undecidable consult (a refused lease, no\n * queue composed on this host, a step that threw or overran its budget). Every\n * undecidable case is `detached` PLUS a named `runWarning` (D-11); the union is\n * never widened with a fourth arm.\n *\n * What actually BECAME of the chain is chip truth — `runs.postprocessing` over durable job state\n * (D-14) — and never this field. A `drained` run whose pump then failed still reads `drained`\n * here, because the promise this field makes is about who owns the work, not about the outcome.\n * Pre-404 logs carry the literal `'detached'`, which remains true of them.\n */\nexport type PostProcessingDisposition = 'drained' | 'handedOff' | 'detached'\n\nexport interface RunFinishedPayload {\n aggregateVerdict: RunStatus\n disposition: PostProcessingDisposition\n finalSeq: number\n}\n\n/** `verdict`: exactly once, the terminal aggregate {@link RunStatus} — the exit-code moment. */\nexport interface VerdictPayload {\n verdict: RunStatus\n}\n\n// --- Diagnostics payloads ---------------------------------------------------\n\n/** `runWarning` / `runError`: non-terminal diagnostics. */\nexport interface RunWarningPayload {\n code: string\n message: string\n context?: Record<string, string>\n}\n\nexport type RunErrorPayload = RunWarningPayload\n\n/** `heartbeat`: empty payload, emitted after ~10 s of bus silence (the v1 cadence). */\nexport type HeartbeatPayload = Record<string, never>\n\n// --- Member-test lifecycle payloads -----------------------------------------\n\n/**\n * `testStarted`: the {@link PerTestOutcome} identity fields (never the embedded steps).\n * Phase 363 D-01 additive-optional appends (§2.2 append-only, RESEARCH A2): suite grouping\n * rides testStarted rather than a new suite lifecycle event — the shell is suite-agnostic,\n * so reporters derive suite boundaries by watching the grouping change. `filePath`/`totalSteps`\n * restore console/JUnit/wire parity (RESEARCH Q1 table).\n */\nexport interface TestStartedPayload {\n testId: string\n testIndex: number\n name: string\n filePath?: string\n suiteId?: string\n suiteName?: string\n suiteIndex?: number\n suiteTotal?: number\n totalSteps?: number\n /**\n * 2026-09-26, owner decision (2), G-428-2. The same 363 D-01 additive-optional footing as the\n * fields above: the member's authored step texts, in step order, so a live row can show a step's\n * real text before the step starts. Masked at the producer by the run's redactor, exactly\n * as `stepStarted.stepText` is, so entry i equals step i's announced text. Absent from older\n * producers and recorded runs; a consumer that ignores it loses nothing but the pending text.\n */\n stepTexts?: readonly string[]\n}\n\n/**\n * `testFinished`: the {@link PerTestOutcome} identity fields plus `outcome`; the embedded\n * `steps` array is structurally excluded — projections never carry it (D-10/D-11).\n */\nexport interface TestFinishedPayload {\n testId: string\n testIndex: number\n outcome: MemberTestOutcome\n /**\n * Phase 363 D-01 additive-optional appends (§2.2, RESEARCH Q1). Sourced from the runner\n * `TestResult` at projection time — NOT new fields on the §A8 `PerTestOutcome` DTO\n * (Pitfall 2). `failureSummary` is masked at the sink.\n */\n durationMs?: number\n failureSummary?: string\n retryCount?: number\n recording?: RecordingEntry\n // 2026-10-19 (444.1-15, D-24): set only on a skipped member, which has no testStarted to name it.\n name?: string\n filePath?: string\n readonly steps?: never\n}\n\n// --- Step lifecycle payloads ------------------------------------------------\n\n/** `stepStarted`: the owning `testIndex`, `stepIndex`, and `stepText`. */\nexport interface StepStartedPayload {\n testIndex: number\n stepIndex: number\n stepText: string\n}\n\n/**\n * `stepFinalized`: the {@link StepEvidence} projection — the full `ServedBrief` body is\n * structurally excluded (only its `briefDigest` travels). D-10/D-11.\n */\nexport interface StepFinalizedPayload {\n testIndex: number\n stepIndex: number\n cacheStatus: 'hit' | 'miss' | 'bypass'\n verifierVerdict: VerifierVerdict\n selfHealOccurred: boolean\n briefDigest: string\n /**\n * Phase 363 D-01 additive-optional appends (§2.2, RESEARCH Q1). Sourced from the runner\n * `StepResult` at projection time — NOT new fields on the §A8 `StepEvidence` DTO\n * (Pitfall 2). `error` is masked at the sink.\n */\n status?: 'passed' | 'failed' | 'healed' | 'skipped' | 'cancelled'\n durationMs?: number\n error?: string\n /**\n * 2026-08-27 (Phase 405 plan 04, D-05): the step's measured model-call usage, on the same\n * 363 D-01 additive-optional footing as the three fields above — the frozen envelope and the\n * event NAME are untouched. Summed by the runner loop over the calls IT made for this step\n * (planner + verifier; heal turns ride the planner path), never re-derived downstream.\n *\n * ABSENT when no call was measured — a cache hit, a bypass, or a provider that reports no\n * usage. Never zero-filled: a `{0,0,0}` here would be a measurement nobody made, and every\n * consumer downstream (the NULL step columns, the omitted `runs.detail` sum, the omitted\n * analytics fields) reads absence as \"unmeasured\" rather than \"free\".\n */\n tokenUsage?: ModelTokenUsage\n /** 423 D-09/D-10: selected profiles and authoritative provider observations, never backfilled. */\n modelUsage?: ModelUsage\n /** 423 D-01/D-05/D-07: capture facts only; record bodies stay in evidence blobs. */\n evidence?: StepEvidenceEntries\n variableSnapshot?: VariableSnapshot\n /**\n * 2026-08-29 (Phase 407 plan 03, D-14): the host's retrieval rung at the moment this step's\n * brief was served, on the same 363 D-01 additive-optional footing as the fields above — the\n * frozen envelope and the event NAME are untouched.\n *\n * Unlike the 363 extras this fact is NOT sourced from the runner `StepResult`: it IS a\n * `StepEvidence` field (407 D-13), so the projection reads it off the evidence. ABSENT when the\n * evidence carries none — a pre-407 run, or a run that bound no knowledge reader (D-16). Both\n * members are closed enum words, so `maskPayloadStrings` walks them unchanged in meaning.\n */\n retrievalRung?: RecordedRetrievalRung\n readonly servedBrief?: never\n}\n\n// --- Sub-action evidence tick payload ----------------------------------------\n\n/**\n * `subActionRecorded`: the {@link SubActionEvidence} projection with states collapsed to\n * `screenStateHash` identity (D-10). Raw `stateBefore`/`screenshot` are structural\n * compile errors — the 356 `NonCacheableStepInput` `?: never` idiom enforces payload\n * discipline at the type level (D-11), not a runtime strip.\n */\nexport interface SubActionRecordedPayload {\n testIndex: number\n stepIndex: number\n subActionIndex: number\n plan: string\n plannedAction: Action\n grounding?: GroundingEvidence\n result: RecordedActionResult\n /**\n * The `stateBefore` identity — the full {@link ScreenState} collapsed to a\n * `screenStateHash` string (D-10). This is the sub-action's primary state hash;\n * `screenStateHashAfter` is present only when the action recorded a distinct\n * post-action state.\n */\n screenStateHash: string\n screenStateHashAfter?: string\n artifactRefs?: readonly ArtifactRef[]\n /** 423 D-02: before-tree capture state; its present ref also rides artifactRefs. */\n ariaEvidence?: AriaEvidenceEntry\n recordingOffsetMs?: number\n readonly stateBefore?: never\n readonly screenshot?: never\n}\n\n// --- Hook lifecycle payloads (Phase 363 D-01 parity appends) ----------------\n\n/**\n * `hookStarted`: the hook identity fields (mirrors core `HookEvent`, reporter/types.ts\n * lines 25-32). `phase` distinguishes suite/test setup·teardown from `inline` hooks;\n * `scope`/`testIndex`/`stepIndex` locate the hook in the run tree when present.\n */\nexport interface HookStartedPayload {\n hookName: string\n phase: 'setup' | 'teardown' | 'inline'\n hookExecutionId: string\n hookId?: string\n scope?: 'suite' | 'test' | 'step'\n testIndex?: number\n stepIndex?: number\n}\n\n/**\n * `hookFinished`: the identity fields plus the hook result (mirrors core `HookResultEvent`,\n * reporter/types.ts lines 47-52). `stdout`/`stderr`/`error` and each `variables` VALUE are\n * masked at projection (T-363-01); `variables` keys pass through. `kind` distinguishes a\n * plain hook from an appium-script / runjs inline body.\n */\nexport interface HookFinishedPayload extends HookStartedPayload {\n status: 'passed' | 'failed' | 'skipped'\n durationMs: number\n stdout: string\n stderr: string\n variables: Record<string, string>\n error?: string\n kind?: 'hook' | 'appium-script' | 'runjs'\n}\n\n/**\n * `testRetryScheduled` (resolves RESEARCH Open Q-3): emitted when the member-runner retry\n * loop schedules another attempt. Only the FINAL attempt emits the authoritative\n * `testFinished`; this event marks a per-test accumulation reset for subscribers so\n * repeated `stepStarted` sequences mid-member don't corrupt counts/durations.\n */\nexport interface TestRetryScheduledPayload {\n testId: string\n testIndex: number\n attempt: number\n maxAttempts: number\n reason?: string\n}\n\n// --- Post-processing / status chip payloads (defined-never-emitted in M1) -----\n\n/**\n * The shared post-processing chip payload shape (spec §2.2: `{ runId, error, willRetry }`).\n * DEFINED in bus schema v1; the producer lands in Phase 388 (D-13) — appended to\n * `events.jsonl` by the in-process post-run tail, continuing `runFinished.finalSeq`.\n *\n * The shape is UNCHANGED by 388 and that is a decision rather than an omission: `live-view.md`\n * §4.3 ratifies richer per-chip summaries, and the bus enum is append-only (§2.2), so those\n * fields are additive later at no cost. What 388 emits is the minimal honest envelope, because\n * anything richer would be a second place chip semantics are stated — and the one place they\n * are stated is `projectPostProcessingChips`, over durable rows a surface can re-read.\n */\nexport interface ChipEventPayload {\n runId: string\n error?: string\n willRetry?: boolean\n}\n\nexport type AnalysisStartedPayload = ChipEventPayload\nexport type AnalysisCompletedPayload = ChipEventPayload\nexport type AnalysisFailedPayload = ChipEventPayload\nexport type CurationStartedPayload = ChipEventPayload\nexport type CurationCompletedPayload = ChipEventPayload\nexport type CurationFailedPayload = ChipEventPayload\n\n// --- Envelope + event union --------------------------------------------------\n\n/** The union of every §2.2 payload projection an envelope can carry. */\nexport type RunEventPayload =\n | RunStartedPayload\n | RunFinishedPayload\n | VerdictPayload\n | RunWarningPayload\n | RunErrorPayload\n | HeartbeatPayload\n | TestStartedPayload\n | TestFinishedPayload\n | StepStartedPayload\n | StepFinalizedPayload\n | SubActionRecordedPayload\n | HookStartedPayload\n | HookFinishedPayload\n | TestRetryScheduledPayload\n | ChipEventPayload\n\n/**\n * The frozen bus envelope (spec §2.2): `{ seq, ts, runId, type, payload }`. This is a\n * TYPE ONLY — the runner bus stamps `seq`/`ts` at publish (schema bans host time/hash APIs, D-05).\n * `seq` is a per-run gap-free monotonic integer (the total order; `lastEventId ≡ seq`);\n * `ts` is wall-clock, audit only. `runId` is a plain string here (the envelope crosses to\n * the browser/JSONL, so it carries the un-branded id).\n */\nexport interface RunEventEnvelope {\n seq: number\n ts: number\n runId: string\n type: RunEventType\n payload: RunEventPayload\n}\n\n/** A per-type envelope binding each event `type` to its payload projection. */\ninterface RunEventOf<T extends RunEventType, P extends RunEventPayload> {\n seq: number\n ts: number\n runId: string\n type: T\n payload: P\n}\n\n/**\n * The discriminated bus-event union: each event `type` mapped to its payload. M5 replay\n * tooling and M1b eval consume this to narrow on `type`. The six chip events are members\n * of the union (defined-never-emitted in M1; the reserved `issues*` triple was removed\n * 2026-08-26 — see the {@link RUN_EVENT_TYPES} header).\n */\nexport type RunEvent =\n | RunEventOf<'runStarted', RunStartedPayload>\n | RunEventOf<'runFinished', RunFinishedPayload>\n | RunEventOf<'verdict', VerdictPayload>\n | RunEventOf<'runWarning', RunWarningPayload>\n | RunEventOf<'runError', RunErrorPayload>\n | RunEventOf<'heartbeat', HeartbeatPayload>\n | RunEventOf<'testStarted', TestStartedPayload>\n | RunEventOf<'testFinished', TestFinishedPayload>\n | RunEventOf<'stepStarted', StepStartedPayload>\n | RunEventOf<'stepFinalized', StepFinalizedPayload>\n | RunEventOf<'subActionRecorded', SubActionRecordedPayload>\n | RunEventOf<'hookStarted', HookStartedPayload>\n | RunEventOf<'hookFinished', HookFinishedPayload>\n | RunEventOf<'testRetryScheduled', TestRetryScheduledPayload>\n | RunEventOf<'analysisStarted', AnalysisStartedPayload>\n | RunEventOf<'analysisCompleted', AnalysisCompletedPayload>\n | RunEventOf<'analysisFailed', AnalysisFailedPayload>\n | RunEventOf<'curationStarted', CurationStartedPayload>\n | RunEventOf<'curationCompleted', CurationCompletedPayload>\n | RunEventOf<'curationFailed', CurationFailedPayload>\n","import { z } from 'zod'\nimport type { ModelIdentity } from '../handoff/model-call-profile'\n\n/** Configured profiles only; healing, assertions and extraction use the verifier lane. */\nexport type ModelUsageRole = 'planner' | 'verifier'\nexport const MODEL_USAGE_ROLES = ['planner', 'verifier'] as const satisfies readonly ModelUsageRole[]\nconst count = z.number().int().nonnegative()\nexport const ModelUsageRoleSchema = z.enum(MODEL_USAGE_ROLES)\nexport const ModelUsageIdentitySchema = z.object({\n provider: z.string(), modelId: z.string(),\n}).strict() satisfies z.ZodType<ModelIdentity>\nconst roleSchema = z.object({\n declared: ModelUsageIdentitySchema.optional(),\n respondingModelIds: z.array(z.string()).nonempty().optional(),\n}).strict()\nexport const ModelUsageSchema = z.object({\n roles: z.object({ planner: roleSchema.optional(), verifier: roleSchema.optional() }).strict(),\n calls: z.object({ started: count, succeeded: count, failed: count }).strict(),\n inputTokens: count.optional(),\n outputTokens: count.optional(),\n cachedInputTokens: count.optional(),\n}).strict()\nexport type ModelUsage = z.infer<typeof ModelUsageSchema>\n\n/** Shared bus/detail token shape. Inclusive input already contains cache reads. */\nexport interface ModelTokenUsage {\n promptTokens: number\n completionTokens: number\n totalTokens: number\n cachedInputTokens?: number\n}\n\n/** Structural input from the runner's finished scope, without an execution dependency. */\nexport interface ModelUsageObservations {\n attempts: readonly {\n role: ModelUsageRole\n kind: 'start' | 'success' | 'failure'\n report?: {\n inputTokens?: number\n outputTokens?: number\n cachedInputTokens?: number\n respondingModelId?: string\n }\n }[]\n roles: { planner: { declared?: ModelIdentity }; verifier: { declared?: ModelIdentity } }\n}\n\n/** Only observed attempts establish measurement; caller applies its live mask before egress. */\nexport function projectObservedModelUsage(observed: ModelUsageObservations): {\n modelUsage?: ModelUsage\n tokenUsage?: ModelTokenUsage\n} {\n const { attempts } = observed\n const roles: ModelUsage['roles'] = {}\n for (const role of MODEL_USAGE_ROLES) {\n const declared = observed.roles[role].declared\n const respondingModelIds = [...new Set(attempts.flatMap(attempt =>\n attempt.role === role && attempt.kind === 'success'\n && typeof attempt.report?.respondingModelId === 'string'\n && attempt.report.respondingModelId.length > 0 ? [attempt.report.respondingModelId] : []))]\n if (declared !== undefined || respondingModelIds.length > 0) {\n roles[role] = {\n ...(declared === undefined ? {} : { declared: { ...declared } }),\n ...(respondingModelIds.length === 0 ? {} : { respondingModelIds }),\n }\n }\n }\n if (attempts.length === 0 && Object.keys(roles).length === 0) return {}\n const valid = (value: unknown): value is number =>\n typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n // Both counts range over exactly the same complete attempt population. Failed, pending,\n // missing and invalid reports cannot certify a partial total as the step's measured spend.\n const complete = attempts.length > 0 && attempts.every(attempt =>\n attempt.kind === 'success' && valid(attempt.report?.inputTokens)\n && valid(attempt.report?.outputTokens))\n const input = complete ? attempts.reduce((sum, item) => sum + item.report!.inputTokens!, 0) : undefined\n const output = complete ? attempts.reduce((sum, item) => sum + item.report!.outputTokens!, 0) : undefined\n const measured = valid(input) && valid(output) && valid(input + output)\n const cached = measured && attempts.every(item => valid(item.report?.cachedInputTokens)\n && item.report.cachedInputTokens <= item.report.inputTokens!)\n ? attempts.reduce((sum, item) => sum + item.report!.cachedInputTokens!, 0) : undefined\n const cache = valid(cached) ? { cachedInputTokens: cached } : {}\n return {\n modelUsage: {\n roles,\n calls: { started: attempts.length,\n succeeded: attempts.filter(item => item.kind === 'success').length,\n failed: attempts.filter(item => item.kind === 'failure').length },\n ...(measured ? { inputTokens: input, outputTokens: output, ...cache } : {}),\n },\n ...(measured ? { tokenUsage: { promptTokens: input, completionTokens: output,\n totalTokens: input + output, ...cache } } : {}),\n }\n}\n","import { screenStateHash } from '../determinism/screen-hash'\nimport type { ArtifactRef } from '../ids/artifact-ref'\nimport type { PerTestOutcome } from '../handoff/per-test-outcome'\nimport type { StepEvidence } from '../handoff/step-evidence'\nimport type { SubActionEvidence } from '../handoff/sub-action-evidence'\nimport { projectObservedModelUsage } from './model-usage'\nimport type { ModelUsageObservations } from './model-usage'\nimport type {\n HookFinishedPayload,\n HookStartedPayload,\n StepFinalizedPayload,\n SubActionRecordedPayload,\n TestFinishedPayload,\n TestRetryScheduledPayload,\n} from './bus-events'\n\n/**\n * The masking seam (D-09). Every payload projection takes a `MaskFn` and routes every\n * string it produces through it. Pre-362 the CLI passes an identity function; 362's\n * masking-context seeding replaces it with the real redactor with ZERO further wiring —\n * the same discipline `StepEvidence.workingMemory` already follows.\n */\nexport type MaskFn = (text: string) => string\n\n/**\n * Structural walk that applies `mask` to every string value reachable from `value`.\n * Arrays and plain objects are walked; numbers/booleans/null pass through unchanged.\n * Pure — the input is never mutated (a fresh structure is returned). This is the\n * terminal pass every projection runs so no value-bearing string field can escape the\n * D-09 seam.\n */\nexport function maskPayloadStrings<T>(value: T, mask: MaskFn): T {\n return walk(value, mask) as T\n}\n\nfunction walk(value: unknown, mask: MaskFn): unknown {\n if (typeof value === 'string') {\n return mask(value)\n }\n if (Array.isArray(value)) {\n return value.map(entry => walk(entry, mask))\n }\n if (value !== null && typeof value === 'object') {\n // Define own properties even for a captured name such as __proto__.\n return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, walk(entry, mask)]))\n }\n return value\n}\n\n/**\n * Like {@link maskPayloadStrings}, but also masks every object key, for documents whose keys are\n * data (op results, chat payloads, CLI output). Two keys of one object that mask to one name throw\n * instead of silently dropping a member; the message carries no value.\n */\nexport function maskPayloadTree<T>(value: T, mask: MaskFn): T {\n return walkTree(value, mask) as T\n}\n\nfunction walkTree(value: unknown, mask: MaskFn): unknown {\n if (typeof value === 'string') {\n return mask(value)\n }\n if (Array.isArray(value)) {\n return value.map(entry => walkTree(entry, mask))\n }\n if (value !== null && typeof value === 'object') {\n const masked: Record<string, unknown> = {}\n for (const [key, entry] of Object.entries(value)) {\n const maskedKey = mask(key)\n if (Object.hasOwn(masked, maskedKey)) {\n throw new Error('two keys of one object mask to the same name')\n }\n Object.defineProperty(masked, maskedKey, {\n value: walkTree(entry, mask),\n enumerable: true,\n writable: true,\n configurable: true,\n })\n }\n return masked\n }\n return value\n}\n\n/**\n * `StepEvidence` → `stepFinalized` payload (D-10). Carries `cacheStatus`, the\n * `verifierVerdict`, a boolean `selfHealOccurred` FLAG (never the `selfHeal` body), and\n * the `briefDigest` — the `ServedBrief`'s own digest field travels, never its body.\n */\nexport function projectStepFinalized(\n evidence: StepEvidence,\n ids: { testIndex: number; stepIndex: number },\n mask: MaskFn,\n extra?: {\n status?: StepFinalizedPayload['status']\n durationMs?: number\n error?: string\n tokenUsage?: StepFinalizedPayload['tokenUsage']\n modelUsage?: StepFinalizedPayload['modelUsage']\n modelObservations?: ModelUsageObservations\n evidence?: StepFinalizedPayload['evidence']\n variableSnapshot?: StepFinalizedPayload['variableSnapshot']\n },\n): StepFinalizedPayload {\n const usage = extra?.modelObservations === undefined ? {\n ...(extra?.tokenUsage === undefined ? {} : { tokenUsage: extra.tokenUsage }),\n ...(extra?.modelUsage === undefined ? {} : { modelUsage: extra.modelUsage }),\n } : projectObservedModelUsage(extra.modelObservations)\n const payload: StepFinalizedPayload = {\n testIndex: ids.testIndex,\n stepIndex: ids.stepIndex,\n cacheStatus: evidence.cacheStatus,\n verifierVerdict: evidence.verifierVerdict,\n selfHealOccurred: evidence.selfHeal !== undefined,\n briefDigest: evidence.servedBrief.briefDigest,\n // Phase 363 D-01 additive-optional appends (RESEARCH Q1). These are plain extra inputs\n // sourced from the runner `StepResult` — NOT fields on the §A8 StepEvidence DTO\n // (Pitfall 2). Omitted when absent so no undefined-hole survives JSON round-trip.\n ...(extra?.status !== undefined ? { status: extra.status } : {}),\n ...(extra?.durationMs !== undefined ? { durationMs: extra.durationMs } : {}),\n ...(extra?.error !== undefined ? { error: extra.error } : {}),\n // 2026-08-27 (Phase 405 plan 04, D-05): same spread-when-defined rule, for the same\n // reason — an unmeasured step carries NO key rather than a zero triple. The three\n // members are numbers, so `maskPayloadStrings` walks past them untouched.\n ...usage,\n ...(extra?.evidence !== undefined ? { evidence: extra.evidence } : {}),\n // Snapshot names are data-bearing keys. The terminal walk below masks their values.\n ...(extra?.variableSnapshot !== undefined\n ? { variableSnapshot: Object.fromEntries(\n Object.entries(extra.variableSnapshot).map(([name, value]) => [mask(name), value]),\n ) }\n : {}),\n // 2026-08-29 (Phase 407 plan 03, D-14): same spread-when-defined rule, read from the\n // EVIDENCE rather than from `extra` — unlike the 363 appends above, the rung IS a\n // `StepEvidence` field (D-13). A step whose evidence recorded no rung carries no key, so\n // absence on the wire keeps meaning \"no ladder was named\" and never \"the top rung\".\n ...(evidence.retrievalRung !== undefined ? { retrievalRung: evidence.retrievalRung } : {}),\n }\n const masked = maskPayloadStrings(payload, mask)\n // Distinctness is defined on published identities; a live masker may collapse raw aliases.\n for (const facts of Object.values(masked.modelUsage?.roles ?? {})) {\n if (facts.respondingModelIds !== undefined) {\n facts.respondingModelIds = [...new Set(facts.respondingModelIds)]\n }\n }\n return masked\n}\n\n/**\n * `SubActionEvidence` → `subActionRecorded` payload (D-10). The raw `stateBefore`/\n * `stateAfter` are collapsed to `screenStateHash` identity strings and destructured away\n * (the `toRecordedActionResult` idiom — never `delete`); `result` is already a\n * `RecordedActionResult` by evidence construction so no live screenshot bytes ride the bus.\n *\n * 2026-08-27 (Phase 405 plan 01, D-14 · RESEARCH D1): `decisionScreenshotRef` STOPS BEING\n * DISCARDED. Until this date it was destructured out and voided beside `stateBefore`, and the\n * consequence was measured rather than suspected: `artifactRefs` is declared on the payload,\n * no runner code sets `evidence.artifactRefs`, and the ONE ref the runner does mint per live\n * decision — the sha-keyed decision screenshot the v50 `FsEvidenceArtifactStore` already\n * writes — reached the handoff and the analysis jobs and never the wire. So the dashboard's\n * projection had nothing to persist and the run-detail page had no screenshot to render.\n *\n * THIS IS CONTENT ON A FROZEN SHAPE, not a shape change (the 363 D-01 class, and RESEARCH\n * Open Q1 recorded here as the dated decision it is). The payload TYPE, the envelope and the\n * event NAME are untouched; an existing optional field acquires its first producer. The ref\n * is APPENDED to whatever `artifactRefs` the evidence already carried rather than replacing\n * it, because the two are different claims — \"everything this sub-action produced\" and \"the\n * frame the planner decided from\" — and a decision screenshot that silently displaced a\n * store-written ref would lose evidence to gain evidence.\n *\n * The array is spread in only when NON-EMPTY (the absent-is-spread-away idiom every optional\n * on this payload follows): an empty array would be a second spelling of \"no artifacts\", and\n * a reader that had to tell `[]` from missing would be learning a distinction nothing means.\n */\nexport function projectSubActionRecorded(\n evidence: SubActionEvidence,\n ids: { testIndex: number; stepIndex: number; subActionIndex: number },\n mask: MaskFn,\n extra?: {\n ariaEvidence?: SubActionRecordedPayload['ariaEvidence']\n recordingOffsetMs?: number\n },\n): SubActionRecordedPayload {\n const { stateBefore, stateAfter, decisionScreenshotRef, localEffect, ...rest } = evidence\n void stateBefore\n void stateAfter\n void localEffect\n\n const artifactRefs: readonly ArtifactRef[] = [\n ...(rest.artifactRefs ?? []),\n ...(decisionScreenshotRef === undefined ? [] : [decisionScreenshotRef]),\n ...(extra?.ariaEvidence?.state === 'present' ? [extra.ariaEvidence.ref] : []),\n ]\n\n const payload: SubActionRecordedPayload = {\n testIndex: ids.testIndex,\n stepIndex: ids.stepIndex,\n subActionIndex: ids.subActionIndex,\n plan: rest.plan,\n plannedAction: rest.plannedAction,\n result: rest.result,\n screenStateHash: screenStateHash(evidence.stateBefore),\n ...(rest.grounding !== undefined ? { grounding: rest.grounding } : {}),\n ...(evidence.stateAfter !== undefined\n ? { screenStateHashAfter: screenStateHash(evidence.stateAfter) }\n : {}),\n ...(artifactRefs.length > 0 ? { artifactRefs } : {}),\n ...(extra?.ariaEvidence !== undefined ? { ariaEvidence: extra.ariaEvidence } : {}),\n ...(extra?.recordingOffsetMs !== undefined ? { recordingOffsetMs: extra.recordingOffsetMs } : {}),\n }\n return maskPayloadStrings(payload, mask)\n}\n\n/**\n * `PerTestOutcome` → `testFinished` payload (D-10). Identity + `outcome` only; the\n * embedded `steps` array is destructured away and never rides the bus.\n */\nexport function projectTestFinished(\n outcome: PerTestOutcome,\n mask: MaskFn,\n extra?: {\n durationMs?: number\n failureSummary?: string\n retryCount?: number\n recording?: TestFinishedPayload['recording']\n name?: string\n filePath?: string\n },\n): TestFinishedPayload {\n const { steps, ...rest } = outcome\n void steps\n\n const payload: TestFinishedPayload = {\n testId: rest.testId,\n testIndex: rest.testIndex,\n outcome: rest.outcome,\n // Phase 363 D-01 additive-optional appends (RESEARCH Q1). Plain extra inputs sourced\n // from the runner `TestResult` — NOT fields on the §A8 PerTestOutcome DTO (Pitfall 2).\n // `failureSummary` is a string so it routes through the mask like every payload string.\n ...(extra?.durationMs !== undefined ? { durationMs: extra.durationMs } : {}),\n ...(extra?.failureSummary !== undefined\n ? { failureSummary: extra.failureSummary }\n : {}),\n ...(extra?.retryCount !== undefined ? { retryCount: extra.retryCount } : {}),\n ...(extra?.recording !== undefined ? { recording: extra.recording } : {}),\n ...(extra?.name !== undefined ? { name: extra.name } : {}),\n ...(extra?.filePath !== undefined ? { filePath: extra.filePath } : {}),\n }\n return maskPayloadStrings(payload, mask)\n}\n\n// --- Hook lifecycle + retry projections (Phase 363 D-01 parity appends, spec §2.2) ----\n\n/**\n * Hook identity → `hookStarted` payload (D-01). Pure structural pass: absent optional\n * identity fields are omitted (no undefined holes), every string routes through the mask.\n */\nexport function projectHookStarted(\n input: HookStartedPayload,\n mask: MaskFn,\n): HookStartedPayload {\n const payload: HookStartedPayload = {\n hookName: input.hookName,\n phase: input.phase,\n hookExecutionId: input.hookExecutionId,\n ...(input.hookId !== undefined ? { hookId: input.hookId } : {}),\n ...(input.scope !== undefined ? { scope: input.scope } : {}),\n ...(input.testIndex !== undefined ? { testIndex: input.testIndex } : {}),\n ...(input.stepIndex !== undefined ? { stepIndex: input.stepIndex } : {}),\n }\n return maskPayloadStrings(payload, mask)\n}\n\n/**\n * Hook result → `hookFinished` payload (D-01, T-363-01). `stdout`/`stderr`/`error` and each\n * `variables` VALUE are routed through the mask by the terminal string walk — keys pass\n * through because {@link maskPayloadStrings} masks values only. Absent optionals are omitted.\n */\nexport function projectHookFinished(\n input: HookFinishedPayload,\n mask: MaskFn,\n): HookFinishedPayload {\n const payload: HookFinishedPayload = {\n hookName: input.hookName,\n phase: input.phase,\n hookExecutionId: input.hookExecutionId,\n status: input.status,\n durationMs: input.durationMs,\n stdout: input.stdout,\n stderr: input.stderr,\n variables: { ...input.variables },\n ...(input.hookId !== undefined ? { hookId: input.hookId } : {}),\n ...(input.scope !== undefined ? { scope: input.scope } : {}),\n ...(input.testIndex !== undefined ? { testIndex: input.testIndex } : {}),\n ...(input.stepIndex !== undefined ? { stepIndex: input.stepIndex } : {}),\n ...(input.error !== undefined ? { error: input.error } : {}),\n ...(input.kind !== undefined ? { kind: input.kind } : {}),\n }\n return maskPayloadStrings(payload, mask)\n}\n\n/**\n * Retry accounting → `testRetryScheduled` payload (resolves RESEARCH Open Q-3). No mask\n * param: the payload carries only identifiers and scheduling accounting (testId, indices,\n * attempt counts, a coarse reason) — no captured secret-bearing streams. Absent `reason`\n * is omitted so no undefined-hole survives JSON round-trip.\n */\nexport function projectTestRetryScheduled(\n input: TestRetryScheduledPayload,\n): TestRetryScheduledPayload {\n return {\n testId: input.testId,\n testIndex: input.testIndex,\n attempt: input.attempt,\n maxAttempts: input.maxAttempts,\n ...(input.reason !== undefined ? { reason: input.reason } : {}),\n }\n}\n","// Handle identity and the per-handle stream filter (Phase 402 plan 04, D-10 / D-14 · INVK-04).\n//\n// A HANDLE IS DERIVED ADDRESSING, NOT A NEW IDENTIFIER (D-10). A parallel run presents ONE run id\n// and N attachable per-member handles, and the identity a handle is spelled from is one the\n// payloads already carry: `testIndex`, bound at `createMemberEventSink` construction. Nothing is\n// minted here and nothing is added to the frozen envelope `{ seq, ts, runId, type, payload }` —\n// this module only says, for each event type, WHICH of the two things an envelope addresses.\n//\n// THE CLASSIFICATION IS TOTAL AND POSITIVE, AND ITS TOTALITY IS STRUCTURAL. `RUN_EVENT_SCOPE` is\n// declared `satisfies Record<RunEventType, RunEventScope>` over the frozen `RUN_EVENT_TYPES`, so a\n// type appended to that list without a classification is a COMPILE error and a key that is not a\n// member of it is an excess-property error. There is deliberately no default branch, no `??` and\n// no \"everything else is run-scoped\" arm: a fall-through would silently publish a future\n// member-scoped event to every handle, which is the exact cross-handle disclosure this filter\n// exists to prevent (T-402-13).\n//\n// WHY A THIRD SCOPE VALUE. The plan named two — member and run — and reading `HookStartedPayload`\n// at implementation time showed that hooks are neither. `testIndex` on that payload is OPTIONAL,\n// and `hooks/orchestrator.ts:buildStartedPayload` spreads it only when the hook's identity carries\n// one: a suite-level `setup` hook names no member, a per-test hook names exactly one. Scope is\n// therefore a property of the INSTANCE for hooks, and the honest classification says so\n// (`member-when-addressed`) rather than picking whichever of the two answers is wrong less often.\n// Forcing hooks into `run` would leak every member's hook output to every handle; forcing them\n// into `member` would drop suite-level hooks out of every handle's stream, including the handle\n// of the member the hook was setting up for.\n//\n// THE FILTER FAILS CLOSED. A member-scoped envelope carrying no usable `testIndex` is a defect,\n// and this predicate answers `false` for every handle rather than `true` for every handle. A\n// defect that reaches nobody is a bug; a defect that reaches everybody is a disclosure. The\n// unfiltered stream (no `handle` parameter) still carries it, which is where such an envelope\n// stays visible to whoever can debug it.\n\nimport { RUN_EVENT_TYPES, type RunEventEnvelope, type RunEventType } from './bus-events'\n\n/**\n * What an envelope addresses.\n *\n * - `run` — the whole run. ALWAYS passes a handle filter (D-14): a handle subscriber still has to\n * learn that the run ended, what the verdict was, and that the process is alive.\n * - `member` — exactly one member, named by a REQUIRED `payload.testIndex`.\n * - `member-when-addressed` — one member when the payload names it, the run when it does not.\n */\nexport type RunEventScope = 'run' | 'member' | 'member-when-addressed'\n\n/**\n * EVERY event type's scope, stated once.\n *\n * The rationale per group, so a later reader can check the reasoning rather than the verdict:\n *\n * - **Run lifecycle / diagnostics / liveness** (`runStarted`, `runFinished`, `verdict`,\n * `runWarning`, `runError`, `heartbeat`) — D-14's own list. `runStarted` joins it because it is\n * the run's header AND the roster announcement, so a handle subscriber must receive it to learn\n * which handles exist at all.\n * - **Member lifecycle / step / evidence** (`testStarted`, `testFinished`, `stepStarted`,\n * `stepFinalized`, `subActionRecorded`, `testRetryScheduled`) — every one of these payload types\n * declares `testIndex: number` REQUIRED, and the sink binds it at construction. The\n * classification is read off the payload types, not chosen.\n * - **Hooks** (`hookStarted`, `hookFinished`) — see the header note above.\n * - **The six post-run chip events** — run-scoped by nature: `ChipEventPayload` is\n * `{ runId, error?, willRetry? }`. There is no member producer and no field that could name one.\n * SIX since 404 D-02 (2026-08-26), not nine: the three never-emitted names for the third chain\n * member were removed from the frozen vocabulary, and this table lost the same three keys.\n */\nexport const RUN_EVENT_SCOPE = {\n // Run lifecycle\n runStarted: 'run',\n runFinished: 'run',\n // Verdict\n verdict: 'run',\n // Diagnostics\n runWarning: 'run',\n runError: 'run',\n // Liveness\n heartbeat: 'run',\n // Member-test lifecycle\n testStarted: 'member',\n testFinished: 'member',\n // Step lifecycle\n stepStarted: 'member',\n stepFinalized: 'member',\n // Sub-action evidence tick\n subActionRecorded: 'member',\n // Per-member attempt reset\n testRetryScheduled: 'member',\n // Hook lifecycle — scope is a property of the instance (see header)\n hookStarted: 'member-when-addressed',\n hookFinished: 'member-when-addressed',\n // Post-processing / status chips\n analysisStarted: 'run',\n analysisCompleted: 'run',\n analysisFailed: 'run',\n curationStarted: 'run',\n curationCompleted: 'run',\n curationFailed: 'run',\n} as const satisfies Record<RunEventType, RunEventScope>\n\n/** The frozen list, re-exported here so a consumer walking the table has the roster beside it. */\nexport const RUN_EVENT_SCOPE_TYPES: readonly RunEventType[] = RUN_EVENT_TYPES\n\n/**\n * The member an envelope names, or nothing.\n *\n * The ONE place a payload is asked which member it belongs to. A `testIndex` that is not a\n * non-negative safe integer is treated as absent rather than coerced — a filter that coerced\n * `'2'` to `2` would let a producer bug decide which reader sees which member's data.\n */\nexport function memberIndexOf(envelope: RunEventEnvelope): number | undefined {\n const value = (envelope.payload as { testIndex?: unknown }).testIndex\n if (typeof value !== 'number') return undefined\n if (!Number.isSafeInteger(value) || value < 0) return undefined\n return value\n}\n\n/**\n * D-14's filter: does this envelope belong on the stream of handle `handleIndex`?\n *\n * The ONE spelling of run-scoped-ness in the product. The run service's SSE route imports this\n * rather than re-deriving it, so there is no second place the answer could drift (T-402-15).\n *\n * Order matters: the CLASSIFICATION decides first. A run-scoped envelope passes even if its\n * payload happens to carry a `testIndex` — otherwise a run-scoped event that grew that field\n * tomorrow would silently disappear from every other handle's stream, and D-14's guarantee that a\n * handle subscriber learns the run ended would quietly stop holding.\n */\nexport function passesHandleFilter(envelope: RunEventEnvelope, handleIndex: number): boolean {\n const scope: RunEventScope | undefined = RUN_EVENT_SCOPE[envelope.type]\n if (scope === 'run') return true\n const memberIndex = memberIndexOf(envelope)\n if (memberIndex === undefined) {\n // Addressed-when-named hooks with no member are the run's; anything else member-scoped that\n // lost its identity — including an envelope whose `type` this build does not know — reaches\n // no handle. Fail closed.\n return scope === 'member-when-addressed'\n }\n return memberIndex === handleIndex\n}\n\n/** The separator in the composite handle spelling. One character, stated once. */\nexport const HANDLE_ID_SEPARATOR = '#'\n\n/**\n * The composite string spelling of a handle, for surfaces that need ONE id (a URL fragment, a\n * map key, a log line). The wire parameter is the bare integer (`?handle=2`) — this is the\n * convenience spelling, not a second identity: both are derived from the same `runId` +\n * `testIndex` pair and neither is minted.\n */\nexport function handleId(runId: string, testIndex: number): string {\n return `${runId}${HANDLE_ID_SEPARATOR}${String(testIndex)}`\n}\n\n/**\n * Parse a composite handle id, or nothing.\n *\n * Splits on the LAST separator so a run id that itself contains one still round-trips, and\n * refuses rather than guessing when either half is malformed.\n */\nexport function parseHandleId(value: string): { runId: string; testIndex: number } | undefined {\n const at = value.lastIndexOf(HANDLE_ID_SEPARATOR)\n if (at <= 0) return undefined\n const runId = value.slice(0, at)\n const parsed = parseHandleParam(value.slice(at + 1))\n if (parsed.kind !== 'handle') return undefined\n return { runId, testIndex: parsed.index }\n}\n\n/**\n * The outcome of reading a `handle` request parameter. THREE ARMS, and no permissive one: there\n * is no value of this type meaning \"it was malformed, serve them the firehose anyway\".\n */\nexport type HandleParamParse =\n | { readonly kind: 'absent' }\n | { readonly kind: 'invalid' }\n | { readonly kind: 'handle'; readonly index: number }\n\n/** Canonical non-negative decimal integers only — no sign, no leading zero, no exponent. */\nconst CANONICAL_HANDLE = /^(?:0|[1-9][0-9]*)$/\n\n/**\n * Read the `handle` parameter off an untrusted request.\n *\n * DELIBERATELY NOT `Number(raw)`: that accepts `' 7 '`, `'0x7'`, `'1e1'`, `''` (→ 0) and `'-0'`,\n * so a caller could reach a member through several spellings and an empty parameter would silently\n * become handle 0. The canonical form is the only accepted form (T-402-14).\n */\nexport function parseHandleParam(raw: string | null | undefined): HandleParamParse {\n if (raw === null || raw === undefined) return { kind: 'absent' }\n if (!CANONICAL_HANDLE.test(raw)) return { kind: 'invalid' }\n const index = Number(raw)\n if (!Number.isSafeInteger(index)) return { kind: 'invalid' }\n return { kind: 'handle', index }\n}\n\n/**\n * The handle roster a run announced, read off its `runStarted` envelope.\n *\n * The roster rides `runStarted.payload.handles` — an ADDITIVE payload field, never a new event\n * type (the `RUN_EVENT_TYPES` list is frozen/append-only and a second event vocabulary on the wire\n * is forbidden). Answers `undefined` when a run announced none, which a caller reads as \"this run\n * cannot answer a per-handle question\" rather than as an empty roster.\n *\n * (The wording above deliberately avoids the two-word sequence a raw source scan mistakes for an\n * import specifier: `validate:arch` reads every `<keyword> '…'` in this file as a declared\n * dependency, and a JSDoc sentence that happens to end in one is reported as a phantom external\n * dep. Measured live in 402-04; the same class of false positive 402-01 hit on a census.)\n */\nexport function handleRosterOf(envelope: RunEventEnvelope): readonly number[] | undefined {\n if (envelope.type !== 'runStarted') return undefined\n const value = (envelope.payload as { handles?: unknown }).handles\n if (!Array.isArray(value)) return undefined\n const handles: number[] = []\n for (const entry of value) {\n if (typeof entry !== 'number' || !Number.isSafeInteger(entry) || entry < 0) return undefined\n handles.push(entry)\n }\n return handles\n}\n","import { z } from 'zod'\n\nimport type { Action } from '../action/index'\n// 407 D-05: the `runs.knowledge` panel DTO composes three already-minted contracts — the rung\n// vocabulary, the serve-time trace and the record-change row — rather than respelling any of\n// them, so the panel and the verbs it sits beside can never disagree about one run.\nimport { RecordedRetrievalRungSchema } from '../brief/retrieval-rung'\nimport { ServedRetrievalTraceV1Schema } from '../brief/retrieval-trace'\nimport { BRIEF_WHY_NO_TRACE_REASONS } from '../knowledge/review-verbs'\nimport { RecordChangeSchema } from '../knowledge/maintenance-views'\nimport type { VerifierVerdict } from '../handoff/step-evidence'\nimport type { ArtifactRef } from '../ids/artifact-ref'\nimport type { PlannerLimitsRecord } from '../config/planner-limits'\nimport type { ScopeKey, ScopeTier } from '../identity/scope-key'\nimport {\n CURRENT_RUN_NOTIFICATION_SCHEMA_VERSION,\n RUN_NOTIFICATION_VIEW_STATUSES,\n} from '../notification/run-notification'\nimport type { RunNotificationView } from '../notification/run-notification'\nimport { CurationSnapshotSchema } from '../notification/curation-snapshot'\nimport {\n CurationSnapshotWithheldSchema,\n POST_PROCESSING_CHIP_STATUSES,\n POST_PROCESSING_DETAIL_STAGES,\n PostProcessingSkippedSchema,\n PostProcessingStageDetailSchema,\n} from '../notification/post-processing-status'\nimport type { PostProcessingChips, PostProcessingStatus } from '../notification/post-processing-status'\nimport { LiveStreamDeclarationSchema } from '../run/live-stream'\nimport { RUN_EVENT_TYPES } from '../run/bus-events'\nimport { ModelUsageSchema, ModelUsageIdentitySchema } from '../run/model-usage'\nimport type { ModelUsage, ModelTokenUsage } from '../run/model-usage'\nimport type { RunEventEnvelope, RunEventPayload } from '../run/bus-events'\nimport type { MemberTestOutcome } from '../run/member-outcome'\nimport {\n EvidenceEntrySchema, EvidenceKindSchema, EvidenceAbsenceReasonSchema, evidenceEntryOfKind,\n ConsoleEvidenceDocumentSchema, NetworkEvidenceDocumentSchema, A11yEvidenceDocumentSchema,\n AriaEvidenceDocumentSchema, VariablesEvidenceDocumentSchema, VariableSnapshotSchema,\n} from '../run/evidence'\nimport type { AriaEvidenceEntry, StepEvidenceEntries, VariableSnapshot } from '../run/evidence'\nimport { RecordingEntrySchema, type RecordingEntry } from '../run/recording'\nimport type { RecordedActionResult } from '../result/index'\nimport { runIdSchema } from '../run/run-id'\nimport type { GroundingEvidence } from '../screen/target-descriptor'\nimport type { RunId } from '../run/run-id'\nimport { EXECUTION_CONTEXT_VALUES } from '../run/run-status'\nimport type { ExecutionContext, RunStatus } from '../run/run-status'\nimport type { Verdict } from '../verdict/verdict'\nimport { RunDetailMemberMarkSchema, type RunDetailMemberMark } from './feedback'\nimport { wireOutputContract } from './output-contract'\nimport { oneJoinArm, recordJoinShape } from './record-join'\n\nexport const RUN_SUMMARY_SCHEMA_VERSION = 2\n\n/**\n * Surface-facing projection of one completed run (Phase 384, D-16).\n *\n * Minimal by construction: it carries the identity fields 387's run addressing\n * (`RUN-456`) resolves against, the build ordinal knowledge folds key on, and the\n * coarse outcome a listing renders. Step-level evidence stays in the handoff\n * document — 389's evidence links reach it through `runId`, not through this DTO.\n */\nexport interface RunSummary {\n runId: RunId\n scope: ScopeKey\n buildOrdinal: number\n executionContext: ExecutionContext\n aggregateVerdict: RunStatus\n startedAt: number\n endedAt: number\n /** Number of member tests the run recorded. */\n testCount: number\n /** Every member test the run recorded, in recorded order, whatever filter selected the run. */\n tests: RunSummaryTest[]\n recordedTargets: RecordedTargets\n}\n\nexport interface RunSummaryTest {\n testIndex: number\n testId: string\n testName: string\n}\n\n/**\n * The target names a run recorded when it happened (431 D-08), never read from current\n * configuration. `unknown` is its own arm so a run with no readable snapshot can never pass for a\n * run that recorded no targets.\n */\nexport type RecordedTargets =\n | { status: 'recorded'; names: string[] }\n | { status: 'unknown' }\n\nconst scopeTierValues = [\n 'global',\n 'product',\n 'suite',\n 'test',\n] as const satisfies readonly ScopeTier[]\n\nconst runStatusValues = [\n 'passed',\n 'failed',\n 'healed',\n 'timeout',\n 'cancelled',\n] as const satisfies readonly RunStatus[]\n\n// 393: hoisted to `run/run-status.ts` beside the type, so the analyze-run payload mirror\n// enumerates the same closed set rather than keeping a second copy of it.\nconst executionContextValues = EXECUTION_CONTEXT_VALUES\n\nconst scopeKeySchema = z.object({\n tier: z.enum(scopeTierValues),\n key: z.string(),\n}).strict()\n\nconst RunSummaryTestSchema = z.object({\n testIndex: z.number().int().nonnegative(),\n testId: z.string(),\n testName: z.string(),\n}).strict() satisfies z.ZodType<RunSummaryTest>\n\nconst RecordedTargetsSchema = z.discriminatedUnion('status', [\n z.object({ status: z.literal('recorded'), names: z.array(z.string().min(1)) }).strict(),\n z.object({ status: z.literal('unknown') }).strict(),\n]) satisfies z.ZodType<RecordedTargets>\n\nexport const RunSummarySchema = z.object({\n runId: runIdSchema,\n scope: scopeKeySchema,\n buildOrdinal: z.number().int().nonnegative(),\n executionContext: z.enum(executionContextValues),\n aggregateVerdict: z.enum(runStatusValues),\n startedAt: z.number().int().nonnegative(),\n endedAt: z.number().int().nonnegative(),\n testCount: z.number().int().nonnegative(),\n tests: z.array(RunSummaryTestSchema),\n recordedTargets: RecordedTargetsSchema,\n}).strict() satisfies z.ZodType<RunSummary>\n\nexport const RUNS_LIST_DEFAULT_LIMIT = 20\nexport const RUNS_LIST_MAX_LIMIT = 200\n\nconst listTextFilterSchema = z.string().refine((value) => value.trim().length > 0, {\n message: 'must name something: an empty or whitespace-only filter matches nothing',\n})\n\n// `.int()` is safe-integer bounded in zod 4, so an unrepresentable epoch or limit is refused\n// rather than rounded.\nconst epochMillisecondsSchema = z.number().int().nonnegative()\n\n/**\n * `runs.list` filters (431 D-08). Every filter selects completed runs BEFORE the limit caps them.\n * `test` matches a member's exact id or a case-insensitive substring of its title; `target`\n * matches a recorded target name exactly; `since` is inclusive epoch milliseconds on `endedAt`.\n */\nexport const RunsListInputSchema = z.object({\n verdict: z.enum(runStatusValues).optional(),\n test: listTextFilterSchema.optional(),\n target: listTextFilterSchema.optional(),\n since: epochMillisecondsSchema.optional(),\n limit: z.number().int().min(1).max(RUNS_LIST_MAX_LIMIT).optional(),\n}).strict()\n\nexport type RunsListInput = z.infer<typeof RunsListInputSchema>\n\n/**\n * `runs.list`'s OUTPUT contract, named (2026-08-16, Phase 396 plan 04 · D-16).\n *\n * The array used to be composed inline in the op — `output: z.array(RunSummarySchema)` — which is\n * correct for the op and unusable for anything else, because the composed object existed only\n * inside that spec literal. D-16's claim is that the schema a surface ADVERTISES and the schema\n * `invokeFunction` VALIDATES are the same object rather than two derivations of it, and a surface\n * cannot name an object that was never bound to a name. So it is bound here, beside the element\n * schema it wraps, and `runs-list.ts` imports it instead of rebuilding it.\n *\n * Note what it is NOT: a second contract. `packages/agent`'s spec now names this one, so there is\n * still exactly one array-of-summaries schema in the system and nothing to keep in step.\n */\nexport const RunsListOutputSchema = z.array(RunSummarySchema)\n\nexport type RunsListOutput = z.infer<typeof RunsListOutputSchema>\n\n/**\n * `runs.list`'s advertised output (431-03, D-03/D-07): the named schema above as the validator,\n * with a document in which each row's branded run id is the validated wire string it arrives as.\n */\nexport const RunsListOutputContract = wireOutputContract(RunsListOutputSchema)\n\nexport const RUN_DETAIL_SCHEMA_VERSION = 2\n\n/**\n * One member test as `runs.get` projects it (Phase 384, D-06/D-16).\n *\n * Carries the stable test identity (filePath + testName, ABRF-02) a review surface\n * addresses and renders, the member verdict, and the root-cause classification when the\n * run produced one. Step evidence itself is deliberately NOT projected — `stepCount` is\n * the only step-shaped field, and 389's evidence links reach the full step record through\n * the handoff document by `runId` + `testIndex`.\n */\nexport interface RunTestDetail {\n testId: string\n testName: string\n filePath: string\n testIndex: number\n outcome: MemberTestOutcome\n /** Number of recorded steps; the step evidence stays in the handoff document. */\n stepCount: number\n /**\n * Present iff the run classified a root cause for this member. Flattened to the three\n * fields a listing renders — the full `Verdict` (cited steps, anchors, artifacts) stays\n * in the handoff document rather than crossing every surface boundary by default.\n */\n rootCause?: {\n class: Verdict['class']\n producer: 'deterministic-classifier' | 'analyze-run'\n confidence: number\n rationale: string\n }\n}\n\n/**\n * The `runs.get` result: one completed run projected across the `CompletedRunHandoff`\n * surface a review UI needs (Phase 384, D-06/D-16).\n *\n * A superset of {@link RunSummary} — every listing field, plus the config digests a\n * reproduction needs, both durable run markers, and the per-member outcome rows.\n */\nexport interface RunDetail {\n runId: RunId\n scope: ScopeKey\n buildOrdinal: number\n executionContext: ExecutionContext\n aggregateVerdict: RunStatus\n configDigests: {\n suiteConfigDigest: string\n testConfigDigest: string\n }\n startedAt: number\n endedAt: number\n /**\n * D-10 verify-before-present gate-run marker, copied verbatim from the handoff.\n * Absent for an ordinary run; only the literal marker is meaningful.\n */\n gateRun?: true\n /**\n * D-14 §6 outcome-exclusion marker, copied verbatim from the handoff. A DISTINCT axis\n * from `gateRun` — neither implies the other.\n */\n excludedFromOutcomes?: true\n tests: RunTestDetail[]\n}\n\nconst verdictClassValues = [\n 'test_bug',\n 'app_bug',\n 'environment',\n 'flake',\n 'config_error',\n 'llm_error',\n 'unknown',\n 'timeout',\n] as const satisfies readonly Verdict['class'][]\n\nconst memberTestOutcomeValues = [\n ...runStatusValues,\n 'skipped',\n] as const satisfies readonly MemberTestOutcome[]\n\nconst configDigestsSchema = z.object({\n suiteConfigDigest: z.string(),\n testConfigDigest: z.string(),\n}).strict()\n\nexport const RunTestDetailSchema = z.object({\n testId: z.string(),\n testName: z.string(),\n filePath: z.string(),\n testIndex: z.number().int().nonnegative(),\n outcome: z.enum(memberTestOutcomeValues),\n stepCount: z.number().int().nonnegative(),\n rootCause: z.object({\n class: z.enum(verdictClassValues),\n producer: z.enum(['deterministic-classifier', 'analyze-run']),\n confidence: z.number(),\n rationale: z.string(),\n }).strict().optional(),\n}).strict() satisfies z.ZodType<RunTestDetail>\n\nexport const RunDetailSchema = z.object({\n runId: runIdSchema,\n scope: scopeKeySchema,\n buildOrdinal: z.number().int().nonnegative(),\n executionContext: z.enum(executionContextValues),\n aggregateVerdict: z.enum(runStatusValues),\n configDigests: configDigestsSchema,\n startedAt: z.number().int().nonnegative(),\n endedAt: z.number().int().nonnegative(),\n gateRun: z.literal(true).optional(),\n excludedFromOutcomes: z.literal(true).optional(),\n tests: z.array(RunTestDetailSchema),\n}).strict() satisfies z.ZodType<RunDetail>\n\n/** `runs.get` addresses exactly one completed run by id. */\nexport const RunsGetInputSchema = z.object({\n runId: runIdSchema,\n}).strict()\n\nexport type RunsGetInput = z.infer<typeof RunsGetInputSchema>\n\n/**\n * `runs.postProcessing` addresses one run's post-run chain (Phase 388, D-14).\n *\n * The same one-field shape `runs.get` takes, and deliberately so: chip truth is a fact about a\n * RUN, derived from that run's id alone (RESEARCH Pattern 2). A filter, a job id or a stage\n * name on this contract would be a second way to address a chain, and the whole projection\n * rests on there being exactly one.\n */\nexport const RunsPostProcessingInputSchema = z.object({\n runId: runIdSchema,\n}).strict()\n\nexport type RunsPostProcessingInput = z.infer<typeof RunsPostProcessingInputSchema>\n\n/**\n * The chain-terminal notification as a WIRE contract (Phase 388, D-09/D-11).\n *\n * `guardRunNotification` reads the BYTES another build may have written into a sqlite column;\n * this describes the shape a surface receives and the JSON-Schema projection a catalogue\n * publishes. 2026-10-17 (444-10, D-36): a surface receives `toRunNotificationView`'s words.\n */\nexport const RunNotificationViewSchema = z.object({\n schemaVersion: z.literal(CURRENT_RUN_NOTIFICATION_SCHEMA_VERSION),\n runId: z.string(),\n outcome: z.enum(RUN_NOTIFICATION_VIEW_STATUSES),\n verdictSummary: z.object({\n total: z.number().int().nonnegative(),\n // Partial on purpose (D-11): a class that did not occur is an ABSENT key, never a zero,\n // so \"this class did not happen\" and \"this build does not know that class\" stay different\n // bytes.\n byClass: z.partialRecord(z.enum(verdictClassValues), z.number().int().nonnegative()),\n }).strict(),\n stages: z.object({\n analysis: z.object({ status: z.enum(RUN_NOTIFICATION_VIEW_STATUSES) }).strict(),\n curation: z.object({\n status: z.enum(RUN_NOTIFICATION_VIEW_STATUSES),\n curated: z.number().int().nonnegative().optional(),\n deprecated: z.number().int().nonnegative().optional(),\n curationSnapshot: CurationSnapshotSchema.optional(),\n }).strict(),\n // 422 D-13: optional here for the same reason it is optional on the record — absent MEANS\n // not recorded. It has to be declared all the same: this object is `.strict()`, so a wire\n // contract that simply ignored the third stage would REFUSE every record that carries one.\n proposals: z.object({\n status: z.enum(RUN_NOTIFICATION_VIEW_STATUSES),\n proposed: z.number().int().nonnegative().optional(),\n skipped: z.number().int().nonnegative().optional(),\n }).strict().optional(),\n }).strict(),\n}).strict() satisfies z.ZodType<RunNotificationView>\n\nconst PostProcessingChipsSchema = z.object({\n analysis: z.enum(POST_PROCESSING_CHIP_STATUSES),\n curation: z.enum(POST_PROCESSING_CHIP_STATUSES),\n}).strict() satisfies z.ZodType<PostProcessingChips>\n\n/**\n * The `runs.postProcessing` result: the two chips, plus the chain's one record once it\n * exists (Phase 388, D-14/D-15; narrowed to two — Phase 404, D-01).\n *\n * `notification` is OPTIONAL rather than nullable because absence is the ordinary state of a\n * chain still in flight. A surface that had to distinguish `null` from missing would be\n * learning a second spelling of \"not yet\"; the chips already say what stage the run is at.\n */\nexport const PostProcessingStatusSchema = z.object({\n runId: z.string(),\n chips: PostProcessingChipsSchema,\n stageDetails: z.partialRecord(z.enum(POST_PROCESSING_DETAIL_STAGES), PostProcessingStageDetailSchema).optional(),\n curationSnapshot: CurationSnapshotSchema.optional(),\n /** A recorded snapshot that could not be projected safely (423 D-15); never beside curationSnapshot. */\n curationSnapshotWithheld: CurationSnapshotWithheldSchema.optional(),\n /** The run's chain was never enqueued (425 D-08, 444 D-39); folded from the durable handoff markers. */\n skipped: PostProcessingSkippedSchema.optional(),\n notification: RunNotificationViewSchema.optional(),\n}).strict() satisfies z.ZodType<PostProcessingStatus>\n\n/**\n * The `runs.start` input (D-09/D-10). The op registers with this full contract in 384 and\n * binds to a named not-bound-in-this-composition error until 386 relocates the composition\n * root — so this schema is the contract, not a description of what runs today.\n *\n * Every field is optional: an argument-less call means \"run the configured default set the\n * resolved config describes\". Fields are additive by construction (the object is strict, so\n * an unrecognized key is a typed refusal rather than a silently ignored request).\n */\nexport const RunsStartInputSchema = z.object({\n /** Test file paths or glob patterns to run; absent means the configured default set. */\n patterns: z.array(z.string()).optional(),\n /**\n * The run id to start under; absent means the composition mints one (Phase 401, D-02).\n *\n * ADDITIVE, and additive is what this object was built for: the strict shape refuses an\n * unrecognized key, so a field arrives as a contract change rather than as a silently ignored\n * request. Nothing about the acknowledgment law moves — every ack field is still read off the\n * durable record, and a run id nobody ran under still fails `RunNotRecordedError`.\n *\n * WHY A CALLER MAY NAME IT AT ALL. The retiring spawn port already let one: it minted the id and\n * handed it to the child through `AGENT_QA_RUN_ID`, so \"the door that starts the run chooses its\n * id\" is the shipped trust level, not a new one. Carrying it on the request is that same fact\n * with the child process removed from underneath it — which is the whole of D-01.\n */\n runId: runIdSchema.optional(),\n /** Scope the run addresses; absent resolves from the config. */\n scope: scopeKeySchema.optional(),\n /** Execution context to record on the run; absent resolves from the environment. */\n executionContext: z.enum(executionContextValues).optional(),\n /** Config file the composition root resolves the run against. */\n configPath: z.string().optional(),\n /**\n * D-10 verify-before-present gate-run marker. Surfaced here so 393 can set it and 388 can\n * propagate it onto the analyze-run job payload with no second schema break. Only the\n * literal marker is accepted, matching the handoff carrier exactly.\n */\n gateRun: z.literal(true).optional(),\n /** D-14 §6 outcome-exclusion marker; a DISTINCT axis from `gateRun`. */\n excludedFromOutcomes: z.literal(true).optional(),\n}).strict()\n\nexport type RunsStartInput = z.infer<typeof RunsStartInputSchema>\n\nexport const RUN_START_ACKNOWLEDGEMENT_SCHEMA_VERSION = 2\n\nconst plannerLimitSchema = z.number().int().positive().max(Number.MAX_SAFE_INTEGER)\n\n/**\n * 436 D-06: the effective planner limits a run recorded, as the acknowledgement carries them. The\n * handoff loader spells the same domain by hand (`hasPlannerLimitsRecordShape`); the two agree.\n */\nexport const PlannerLimitsRecordSchema = z.object({\n maxActions: plannerLimitSchema,\n maxPlanningTurns: plannerLimitSchema,\n perTest: z.array(z.object({\n testName: z.string(),\n filePath: z.string(),\n maxActions: plannerLimitSchema,\n maxPlanningTurns: plannerLimitSchema,\n }).strict()).optional(),\n}).strict() satisfies z.ZodType<PlannerLimitsRecord>\n\n/**\n * The `runs.start` result (Phase 384, D-09).\n *\n * Starting a run is ASYNCHRONOUS, so the acknowledgment names the run a caller may now\n * address — `runs.events` for the stream while it happens, `runs.get` for the outcome once\n * it exists — and deliberately not the outcome itself, which has not happened yet. Both\n * durable markers are echoed so a caller can confirm the run was accepted as the kind of\n * run it asked for rather than assuming its request survived resolution.\n */\nexport interface RunStartAcknowledgement {\n runId: RunId\n scope: ScopeKey\n executionContext: ExecutionContext\n buildOrdinal: number\n startedAt: number\n /** Member tests the resolved pattern set admitted. */\n testCount: number\n gateRun?: true\n excludedFromOutcomes?: true\n /** 436 D-06: the limits each step ran under, copied from the run's own record. */\n limits?: PlannerLimitsRecord\n}\n\nexport const RunStartAcknowledgementSchema = z.object({\n runId: runIdSchema,\n scope: scopeKeySchema,\n executionContext: z.enum(executionContextValues),\n buildOrdinal: z.number().int().nonnegative(),\n startedAt: z.number().int().nonnegative(),\n testCount: z.number().int().nonnegative(),\n gateRun: z.literal(true).optional(),\n excludedFromOutcomes: z.literal(true).optional(),\n limits: PlannerLimitsRecordSchema.optional(),\n}).strict() satisfies z.ZodType<RunStartAcknowledgement>\n\n/**\n * The `runs.events` stream input (D-08). `lastEventId` is the v49 bus resume token — the\n * gap-free `seq` of the last envelope the caller observed, so the stream resumes at\n * `lastEventId + 1`. Absent means replay from the beginning of the log.\n */\nexport const RunsEventsInputSchema = z.object({\n runId: runIdSchema,\n lastEventId: z.number().int().nonnegative().optional(),\n}).strict()\n\nexport type RunsEventsInput = z.infer<typeof RunsEventsInputSchema>\n\n/**\n * The `runs.liveurl` input (403 D-03). `handle` selects WHICH member of a parallel run the viewer\n * attaches to; absent means handle 0, the single-member case every non-suite run is.\n */\nexport const RunsLiveUrlInputSchema = z.object({\n runId: runIdSchema,\n handle: z.number().int().nonnegative().optional(),\n}).strict()\n\nexport type RunsLiveUrlInput = z.infer<typeof RunsLiveUrlInputSchema>\n\n/**\n * The `runs.liveurl` result (403 D-03/D-08). `liveUrl` carries the token in its FRAGMENT, so this\n * value is the one place the token exists outside the minting process's memory — which is why the\n * op's `classify` never interpolates it and no door logs this result.\n *\n * `stream` is the handle's DECLARED capability, echoed here so a caller can render the honest\n * no-preview state without opening a socket to find out.\n */\nexport const RunsLiveUrlResultSchema = z.object({\n liveUrl: z.string(),\n expiresAt: z.number().int(),\n handle: z.number().int().nonnegative(),\n stream: LiveStreamDeclarationSchema,\n}).strict()\n\nexport type RunsLiveUrlResult = z.infer<typeof RunsLiveUrlResultSchema>\n\n/** The editor subject's mint input (428 D-07), reachable only through the dashboard door. */\nexport const EditorLiveUrlInputSchema = z.object({\n sessionId: z.string().min(1),\n}).strict()\n\nexport type EditorLiveUrlInput = z.infer<typeof EditorLiveUrlInputSchema>\n\n/**\n * The editor subject's mint result (428 D-07). No `handle`: an editor session has exactly one\n * stream. `.strict()` is load-bearing because the composition parses this result, so a grown field\n * throws instead of leaking.\n */\nexport const EditorLiveUrlResultSchema = z.object({\n liveUrl: z.string(),\n expiresAt: z.number().int(),\n stream: LiveStreamDeclarationSchema,\n}).strict()\n\nexport type EditorLiveUrlResult = z.infer<typeof EditorLiveUrlResultSchema>\n\nexport const RUN_EVENT_ENVELOPE_SCHEMA_VERSION = 2\n\n/**\n * The `runs.events` stream ELEMENT contract (Phase 384, D-08).\n *\n * A stream op's declared output describes ONE element of the async iterable, never the\n * iterable itself — so this is the frozen v49 bus envelope as the JSONL event log records\n * it. `seq` is the per-run gap-free total order and doubles as the resume token: a caller\n * that observed seq N re-invokes with `lastEventId: N`.\n *\n * `payload` is projected as an OPEN record rather than the fifteen-member per-type union.\n * The envelope contract describes the frame; a consumer narrows the payload by `type`\n * against the exported `RunEvent` union. The `.transform` restoring the union rides the\n * same idiom as the branded-id schemas here, so JSON-Schema projection uses `io: 'input'`.\n */\nexport const RunEventEnvelopeSchema = z.object({\n seq: z.number().int().positive(),\n ts: z.number().int().nonnegative(),\n runId: z.string(),\n type: z.enum(RUN_EVENT_TYPES),\n payload: z.record(z.string(), z.unknown()).transform((value) => value as RunEventPayload),\n}).strict() satisfies z.ZodType<RunEventEnvelope>\n\n// ---- `runs.detail` — the durable run-detail projection (Phase 405 plan 01, D-03) ---------------\n//\n// THE WIRE MIRRORS THE BUS, FIELD FOR FIELD. Every name below is the name the producing payload\n// already uses (`testIndex`, `cacheStatus`, `verifierVerdict`, `selfHealOccurred`, `briefDigest`,\n// `screenStateHash`, `artifactRefs`), and that is D-01's \"no field is re-derived, renamed or\n// re-interpreted on the way in\" applied on the way OUT. A projection that renamed anything here\n// would be a second vocabulary for one run, free to drift from the events the same run recorded.\n\n/**\n * One member test of a run, as the dashboard projection persisted it (D-01, D-18).\n *\n * `testIndex` IS THE HANDLE (RESEARCH D4): `handleId(runId, testIndex)` is how the product spells\n * run-scoped member identity, and minting a second id here would be a second spelling of it.\n *\n * EVERY DESCRIPTIVE FIELD IS OPTIONAL AND `attempts` IS NOT, which is the D-18 thin-member shape\n * stated as a type: a member whose stream begins with a terminal event has an outcome and nothing\n * else, and it must still be renderable. `attempts` is an ordinal that starts at 1 and rises on\n * `testRetryScheduled` (D-17), so it is always known.\n */\nexport interface RunDetailMember {\n testIndex: number\n testId?: string\n name?: string\n filePath?: string\n suiteId?: string\n suiteName?: string\n suiteIndex?: number\n totalSteps?: number\n outcome?: MemberTestOutcome\n durationMs?: number\n failureSummary?: string\n retryCount?: number\n attempts: number\n recording?: RecordingEntry\n /**\n * 419 D-15: the LATEST mark per address on this member — the run-level entry\n * (no stepIndex) first, then step entries ascending. Absent when the host binds\n * no feedback dep or nothing was marked; a projection of the mark ledger,\n * nothing new is fetched by the block.\n */\n marks?: readonly RunDetailMemberMark[]\n}\n\n/**\n * The per-step model spend (D-05), ABSENT when nothing was measured.\n *\n * Three numbers rather than one, mirroring the additive-optional field 405-04 appends to\n * `stepFinalized`. A cache hit, a bypass or a provider that reports no usage carries NO\n * `tokenUsage` at all — never a zero, which would be a measurement nobody made.\n */\nexport interface RunStepTokenUsage extends ModelTokenUsage {}\n\n/** One finalized step, carrying the whole `StepFinalizedPayload` as persisted (D-01). */\nexport interface RunDetailStep {\n testIndex: number\n stepIndex: number\n /** The instruction text, cached from this step's own `stepStarted`. */\n stepText?: string\n cacheStatus: 'hit' | 'miss' | 'bypass'\n verifierVerdict: VerifierVerdict\n selfHealOccurred: boolean\n briefDigest: string\n status?: 'passed' | 'failed' | 'healed' | 'skipped' | 'cancelled'\n durationMs?: number\n error?: string\n tokenUsage?: RunStepTokenUsage\n modelUsage?: ModelUsage\n /** Capture-time entries; absence on historical rows is normalized by the read op. */\n evidence?: StepEvidenceEntries\n /** Finalized snapshot, with names and values masked by the bus producer. */\n variableSnapshot?: VariableSnapshot\n}\n\n/** One recorded sub-action, carrying the whole `SubActionRecordedPayload` as persisted (D-01). */\nexport interface RunDetailSubAction {\n testIndex: number\n stepIndex: number\n subActionIndex: number\n plan: string\n plannedAction: Action\n grounding?: GroundingEvidence\n result: RecordedActionResult\n screenStateHash: string\n screenStateHashAfter?: string\n artifactRefs?: readonly RunDetailArtifactRef[]\n /** Before-tree evidence belongs to this sub-action, never its parent step. */\n ariaEvidence?: AriaEvidenceEntry\n recordingOffsetMs?: number\n}\n\n/**\n * A projected artifact ref, annotated with read-time presence (Phase 406, D-17).\n *\n * A DETAIL-SIDE EXTENSION RATHER THAN A WIDER `ArtifactRef`, because `ArtifactRef` is the shape\n * the RUNNER mints when it writes a blob, and a producer has nothing to say about whether the\n * bytes survive to be read. Presence is a fact about the moment of the read, so it is added by\n * the read.\n *\n * `present === false || evidenceIncomplete === true` IS ONE PAGE STATE, and the two arms are kept\n * apart only so the page can say which side reported it: the producer knew at emit time, or the\n * reader found it gone since. `present` ABSENT is presence UNKNOWN — a host that cannot stat its\n * blobs — and the predicate is `=== false` precisely so it never renders as a claimed absence.\n */\nexport interface RunDetailArtifactRef extends ArtifactRef {\n present?: boolean\n}\n\n/**\n * The run-level token sum, computed at READ time from the step rows (D-06).\n *\n * THE THREE SUMS ARE ABSENT WHEN `measuredSteps === 0`, and that asymmetry is the whole point:\n * \"no step reported usage\" and \"every step reported zero\" are different facts about a run, and a\n * page that printed `0 tokens` for the first would be reporting a measurement nobody took. The two\n * counts are always present, so a surface can honestly render \"N tokens across M of K steps\".\n */\nexport interface RunTokenTotals {\n measuredSteps: number\n unmeasuredSteps: number\n promptTokens?: number\n completionTokens?: number\n totalTokens?: number\n cachedInputTokens?: number\n cachedMeasuredSteps?: number\n /** Inclusive input over precisely the steps contributing cachedInputTokens. */\n cachedInputMeasuredTokens?: number\n}\n\nexport const RunModelSummarySchema = z.object({\n declared: z.array(ModelUsageIdentitySchema.extend({ stepCount: z.number().int().positive() }))\n .nonempty().optional(),\n responding: z.array(z.object({ provider: z.string().optional(), modelId: z.string(),\n stepCount: z.number().int().positive() }).strict()).nonempty().optional(),\n}).strict()\nexport type RunModelSummary = z.infer<typeof RunModelSummarySchema>\n\n/**\n * What the run-detail READ PORT answers with — the rows and nothing derived (D-03).\n *\n * The token sum is DELIBERATELY NOT HERE. It is computed in the op by the exported pure\n * `projectRunTokenTotals`, so the sum has one producer in the layer that owns the contract rather\n * than one per composition root that happens to hold a database.\n */\nexport interface RunDetailRows {\n runId: string\n members: readonly RunDetailMember[]\n steps: readonly RunDetailStep[]\n subActions: readonly RunDetailSubAction[]\n}\n\n/** The `runs.detail` result: the rows plus the D-06 sum, in ONE unpaged answer. */\nexport interface RunDetailProjection extends RunDetailRows {\n tokens: RunTokenTotals\n models?: RunModelSummary\n}\n\n/**\n * `runs.detail` addresses exactly one run by id — the same one-field shape `runs.get` takes.\n *\n * Deliberately so: run detail is a fact about a RUN, derived from its id alone. A filter, a handle\n * or a page cursor on this contract would be a second way to address one page, and the projection\n * rests on there being exactly one.\n */\nexport const RunsDetailInputSchema = z.object({\n runId: runIdSchema,\n}).strict()\n\nexport type RunsDetailInput = z.infer<typeof RunsDetailInputSchema>\n\n/**\n * The bus's own nested objects, carried VERBATIM across the wire.\n *\n * An open record with a cast rather than a re-declaration of `Action` / `RecordedActionResult` /\n * `GroundingEvidence` in zod: those three unions are the runner's contracts, they are large, and a\n * second declaration here would be a second answer to what an action IS — free to fall behind the\n * type the runner actually emits. This is the `RunEventEnvelopeSchema.payload` idiom in this same\n * file, for the same reason: the envelope contract describes the frame, and a consumer narrows the\n * payload against the exported union.\n */\nconst opaqueBusObject = <T>(): z.ZodType<T> =>\n z.record(z.string(), z.unknown()).transform((value) => value as T) as unknown as z.ZodType<T>\n\nconst ArtifactRefSchema = z.object({\n id: z.string(),\n sha: z.string(),\n evidenceIncomplete: z.boolean().optional(),\n present: z.boolean().optional(),\n}).strict() satisfies z.ZodType<RunDetailArtifactRef>\n\nconst VerifierVerdictSchema = z.object({\n pass: z.boolean(),\n reasoning: z.string(),\n}).strict() satisfies z.ZodType<VerifierVerdict>\n\n/**\n * A WALL-CLOCK DURATION IS NOT AN INTEGER, and asserting that it is refuses every real run.\n *\n * Measured by 405-12 on the shipped binary: `runs.detail` answered `500 read_failed / ZodError` for\n * a populated run because both duration fields carried `.int()`, and the producer is a\n * `performance.now()` delta — the first real run through this contract reported\n * `227.4079999999999`. Every cell that had exercised these schemas built its rows by hand, and a\n * hand-written millisecond is a whole number, so the constraint held right up to the moment\n * somebody measured one.\n *\n * The interfaces beside these schemas type both fields as plain `number`; this is the schema\n * catching up to the type and to the producer, not a relaxation of either. `finite` stays because\n * a stored infinity is a real nonsense value and `nonnegative` because time does not run backwards.\n */\nconst durationMsSchema = z.number().finite().nonnegative()\n\nexport const RunDetailMemberSchema = z.object({\n testIndex: z.number().int().nonnegative(),\n testId: z.string().optional(),\n name: z.string().optional(),\n filePath: z.string().optional(),\n suiteId: z.string().optional(),\n suiteName: z.string().optional(),\n suiteIndex: z.number().int().nonnegative().optional(),\n totalSteps: z.number().int().nonnegative().optional(),\n outcome: z.enum(memberTestOutcomeValues).optional(),\n durationMs: durationMsSchema.optional(),\n failureSummary: z.string().optional(),\n retryCount: z.number().int().nonnegative().optional(),\n attempts: z.number().int().positive(),\n marks: z.array(RunDetailMemberMarkSchema).optional(),\n recording: RecordingEntrySchema.optional(),\n}).strict() satisfies z.ZodType<RunDetailMember>\n\nexport const RunStepTokenUsageSchema = z.object({\n promptTokens: z.number().int().nonnegative(),\n completionTokens: z.number().int().nonnegative(),\n totalTokens: z.number().int().nonnegative(),\n cachedInputTokens: z.number().int().nonnegative().optional(),\n}).strict() satisfies z.ZodType<RunStepTokenUsage>\n\nexport const RunDetailStepSchema = z.object({\n testIndex: z.number().int().nonnegative(),\n stepIndex: z.number().int().nonnegative(),\n stepText: z.string().optional(),\n cacheStatus: z.enum(['hit', 'miss', 'bypass']),\n verifierVerdict: VerifierVerdictSchema,\n selfHealOccurred: z.boolean(),\n briefDigest: z.string(),\n status: z.enum(['passed', 'failed', 'healed', 'skipped', 'cancelled']).optional(),\n durationMs: durationMsSchema.optional(),\n error: z.string().optional(),\n tokenUsage: RunStepTokenUsageSchema.optional(),\n modelUsage: ModelUsageSchema.optional(),\n evidence: z.strictObject({\n console: evidenceEntryOfKind('console'),\n network: evidenceEntryOfKind('network'),\n a11y: evidenceEntryOfKind('a11y'),\n variables: evidenceEntryOfKind('variables'),\n }).optional(),\n variableSnapshot: VariableSnapshotSchema.optional(),\n}).strict() satisfies z.ZodType<RunDetailStep>\n\nexport const RunDetailSubActionSchema = z.object({\n testIndex: z.number().int().nonnegative(),\n stepIndex: z.number().int().nonnegative(),\n subActionIndex: z.number().int().nonnegative(),\n plan: z.string(),\n plannedAction: opaqueBusObject<Action>(),\n grounding: opaqueBusObject<GroundingEvidence>().optional(),\n result: opaqueBusObject<RecordedActionResult>(),\n screenStateHash: z.string(),\n screenStateHashAfter: z.string().optional(),\n artifactRefs: z.array(ArtifactRefSchema).optional(),\n ariaEvidence: evidenceEntryOfKind('aria').optional(),\n recordingOffsetMs: z.number().finite().nonnegative().optional(),\n}).strict() satisfies z.ZodType<RunDetailSubAction>\n\nexport const RunTokenTotalsSchema = z.object({\n measuredSteps: z.number().int().nonnegative(),\n unmeasuredSteps: z.number().int().nonnegative(),\n promptTokens: z.number().int().nonnegative().optional(),\n completionTokens: z.number().int().nonnegative().optional(),\n totalTokens: z.number().int().nonnegative().optional(),\n cachedInputTokens: z.number().int().nonnegative().optional(),\n cachedMeasuredSteps: z.number().int().positive().optional(),\n cachedInputMeasuredTokens: z.number().int().nonnegative().optional(),\n}).strict() satisfies z.ZodType<RunTokenTotals>\n\nexport const RunDetailProjectionSchema = z.object({\n runId: z.string(),\n members: z.array(RunDetailMemberSchema),\n steps: z.array(RunDetailStepSchema),\n subActions: z.array(RunDetailSubActionSchema),\n tokens: RunTokenTotalsSchema,\n models: RunModelSummarySchema.optional(),\n}).strict() satisfies z.ZodType<RunDetailProjection>\n\n/**\n * `runs.artifact` addresses ONE content-addressed evidence blob, run-scoped (405 D-12/D-13).\n *\n * TWO FIELDS AND NO PATH, EVER. The sha is the whole of the artifact's address inside the run, and\n * the regex here is the CONTRACT rather than a route guard: a malformed sha is refused by this\n * schema at the door, so the op never receives one and `FsEvidenceArtifactStore.getBlob` — which\n * answers `undefined` for a malformed sha and for an absent file alike — is never asked to\n * distinguish the two. Lowercase only, because the store content-addresses with\n * `createHash('sha256').digest('hex')` and an uppercase spelling would name a file that does not\n * exist while looking like a legitimate miss.\n *\n * RUN-SCOPED BY CONSTRUCTION (D-12, T-405-16). There is no global `artifacts/:sha` shape here,\n * because the store keeps no sha→run index and a route that pretended otherwise would be reading\n * one run's evidence under another run's authority.\n */\nexport const RunsArtifactInputSchema = z.object({\n runId: runIdSchema,\n sha: z.string().regex(/^[0-9a-f]{64}$/),\n range: z.strictObject({\n start: z.number().int().nonnegative(),\n end: z.number().int().nonnegative().optional(),\n }).refine(range => range.end === undefined || range.end >= range.start, {\n message: 'Range end must not be below start',\n }).optional(),\n}).strict()\n\nexport type RunsArtifactInput = z.infer<typeof RunsArtifactInputSchema>\n\n/**\n * What `runs.artifact` answers with — the bytes, base64'd, under a SNIFFED content type.\n *\n * BASE64 AND UNARY rather than a stream, because a decision screenshot is bounded by the runner's\n * own capture and a stream kind would buy a few hundred kilobytes nothing at the cost of a second\n * result vocabulary (RESEARCH Pattern 2). The adapter decodes once and writes the bytes.\n *\n * `contentType` IS DERIVED FROM THE BYTES, not from a name, an extension or anything the caller\n * said: the store keeps no metadata, and the only honest source for \"what is this\" is the head of\n * the blob itself. The op's sniffer answers PNG, JPEG or the opaque default and NOTHING a browser\n * renders as markup (T-405-15).\n *\n * `byteLength` IS THE DECODED SIZE, DECLARED RATHER THAN DERIVABLE. It is here so that neither the\n * op's own receipt fold nor the route's `Content-Length` has to reach into `bytesBase64` to learn\n * how big the blob is — reading a payload's content to compose a receipt is exactly what the fold\n * census in `refusal-classifiers.test.ts` refuses, and a size a consumer must decode to discover is\n * a size two consumers will compute two ways.\n */\nexport const RunsArtifactResultSchema = z.object({\n runId: z.string(),\n sha: z.string(),\n contentType: z.string(),\n byteLength: z.number().int().nonnegative(),\n bytesBase64: z.string(),\n totalLength: z.number().int().nonnegative().optional(),\n range: z.strictObject({\n start: z.number().int().nonnegative(),\n end: z.number().int().nonnegative(),\n }).optional(),\n}).strict()\n\nexport type RunsArtifactResult = z.infer<typeof RunsArtifactResultSchema>\n\nexport const RunsArtifactOutputContract = wireOutputContract(RunsArtifactResultSchema)\n\n/** A recorded row address, never a caller-selected blob SHA or path. */\nexport const RunsEvidenceInputSchema = z.strictObject({\n runId: runIdSchema,\n testIndex: z.number().int().nonnegative(),\n stepIndex: z.number().int().nonnegative(),\n subActionIndex: z.number().int().nonnegative().optional(),\n kind: EvidenceKindSchema,\n}).refine(value => value.kind === 'aria' || value.subActionIndex === undefined, {\n message: 'Only ARIA evidence addresses a sub-action',\n})\nexport type RunsEvidenceInput = z.infer<typeof RunsEvidenceInputSchema>\n\nconst evidenceReady = <S extends z.ZodType>(document: S) => z.strictObject({\n address: RunsEvidenceInputSchema,\n outcome: z.literal('ready'),\n evidence: EvidenceEntrySchema,\n document,\n})\n\n/** Read failures are separate from the producer's capture-time presence/absence. */\nexport const RunsEvidenceResultSchema = z.union([\n evidenceReady(ConsoleEvidenceDocumentSchema),\n evidenceReady(NetworkEvidenceDocumentSchema),\n evidenceReady(A11yEvidenceDocumentSchema),\n evidenceReady(AriaEvidenceDocumentSchema),\n evidenceReady(VariablesEvidenceDocumentSchema),\n z.strictObject({\n address: RunsEvidenceInputSchema,\n outcome: z.literal('absent'),\n evidence: z.strictObject({\n kind: EvidenceKindSchema, state: z.literal('absent'), reason: EvidenceAbsenceReasonSchema,\n evidenceIncomplete: z.boolean().optional(),\n }),\n }),\n z.strictObject({\n address: RunsEvidenceInputSchema,\n outcome: z.literal('read-error'),\n code: z.enum(['address-not-found', 'ambiguous-address', 'invalid-entry', 'ref-not-owned',\n 'sha-mismatch', 'invalid-document', 'storage-read-failed', 'snapshot-missing', 'masking-unavailable']),\n capture: EvidenceEntrySchema.optional(),\n }),\n]).refine(value => {\n if (value.outcome === 'read-error') return value.capture === undefined || value.capture.kind === value.address.kind\n if (value.evidence.kind !== value.address.kind) return false\n return value.outcome !== 'ready' || (value.evidence.state === 'present' && value.document.kind === value.address.kind)\n}, { message: 'Evidence, document and address must describe the same captured kind' })\nexport type RunsEvidenceResult = z.infer<typeof RunsEvidenceResultSchema>\n\n/**\n * `runs.evidence`'s advertised output (431-03): every arm validates through the schema above, and\n * a captured variable map is published as the string-keyed entry map it is — own `__proto__`\n * included — rather than re-described through a record parser that skips that key.\n */\nexport const RunsEvidenceOutputContract = wireOutputContract(RunsEvidenceResultSchema)\n\n// ---- `runs.knowledge` — what one run USED and LEARNED (Phase 407, LERN-01/LERN-02 · D-05) -----\n//\n// ONE READ, ONE DTO, EVERY SURFACE. D-05's whole posture is that the Knowledge panel is a thin\n// client over a single registry verb rather than a page composing N `knowledge.brief.why` calls,\n// so this contract carries every fact the panel paints: per step the three served channels, the\n// serve-time trace arm, the procedure plan source and the recorded rung; per run the curation\n// word with its counts, the record changes attributable to this run, and the canary outcomes.\n//\n// THE SUBSTRATE IS THE RUN'S HANDOFF (D-06). Every field below is a projection of `StepEvidence`\n// or of a sibling op invoked with the same deps — nothing here is re-derived by querying today's\n// index, because a why-answer computed from the present would answer a different question than\n// the one asked (KREV-02's founding argument, applied to a whole run).\n\n/** `runs.knowledge` addresses exactly one recorded run, on `runs.postProcessing`'s one-field footing. */\nexport const RunsKnowledgeInputSchema = z.object({\n runId: runIdSchema,\n}).strict()\n\nexport type RunsKnowledgeInput = z.infer<typeof RunsKnowledgeInputSchema>\n\n/** A learned change with the read-time record join beside its unchanged historical fields. */\nexport const RunKnowledgeLearnedChangeSchema = RecordChangeSchema.safeExtend(recordJoinShape)\n .superRefine(oneJoinArm)\n\n/**\n * One channel-1 brief line as the panel renders it.\n *\n * PROJECTED FIELD BY FIELD rather than spread from `BriefLine`, so a field added to the serving\n * contract cannot silently reach a page. `servedAsCanary` rides along because it is the\n * serve-time half of D-08's attribution: the marker is always true of the line, the OUTCOME\n * arrives later on `learned.canaryAttributions`, and the two must stay separately readable.\n */\nexport const RunKnowledgeBriefLineSchema = z.object({\n id: z.string(),\n kind: z.string(),\n summary: z.string(),\n trust: z.number(),\n status: z.string(),\n servedAsCanary: z.boolean(),\n tier: z.string(),\n ...recordJoinShape,\n}).strict().superRefine(oneJoinArm)\n\n/** One channel-2 read trace as the panel renders it. */\nexport const RunKnowledgeReadTraceSchema = z.object({\n id: z.string(),\n detailLevel: z.string(),\n bodyDigest: z.string(),\n ...recordJoinShape,\n}).strict().superRefine(oneJoinArm)\n\n/**\n * One channel-3 caution as the panel renders it.\n *\n * `anchors` are DELIBERATELY NOT PROJECTED. The panel renders a caution's sentence and nothing\n * else, and an anchor list is structural routing detail that would arrive on the wire with no\n * reader — the projection carries what a surface paints, not everything the producer holds.\n */\nexport const RunKnowledgeCautionLineSchema = z.object({\n id: z.string(),\n summary: z.string(),\n ...recordJoinShape,\n}).strict().superRefine(oneJoinArm)\n\n/**\n * Why this step's brief said what it said — the trace, or a NAMED absence (D-04).\n *\n * The two arms are the `knowledge.brief.why` vocabulary applied per step, and they reuse that\n * verb's own reason enum rather than a second spelling of it: one run answered through this op\n * and the same run answered through `knowledge.brief.why` can never disagree about what a\n * missing trace is called.\n */\nexport const RunKnowledgeTraceSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('answered'),\n trace: ServedRetrievalTraceV1Schema,\n }).strict(),\n z.object({\n kind: z.literal('no-trace'),\n reason: z.enum(BRIEF_WHY_NO_TRACE_REASONS),\n }).strict(),\n])\n\nexport type RunKnowledgeTrace = z.infer<typeof RunKnowledgeTraceSchema>\n\n/**\n * The step's plan source, mirroring `StepPlanSource` MEMBER FOR MEMBER (D-07).\n *\n * A replay row and a hint row stay structurally distinct on the wire because G-381-4's whole\n * lesson is that a demoted replay recommendation and an ordinary served hint are byte-identical\n * unless something keeps them apart. The guard fold travels intact so the panel can say\n * \"replayed 5/5\" or \"broke at step 3: verifier rejection\" without a second read.\n *\n * MEMBER FOR MEMBER IS A LIST, NOT AN ADJECTIVE (407-12, CR-01). The replay arm names\n * `procedureId`, `guard` AND `flow`; the hint arm names `procedureId` and `demotion`. The claim\n * was made in prose here while `flow` was missing and the arm was `.strict()`, so every run that\n * really replayed a procedure — the only runs the \"replayed 5/5\" sentence exists for — failed\n * `spec.output.parse` with `unrecognized_keys` and the Knowledge tab rendered a read failure.\n * A member added to `StepPlanSource` belongs in this list on the same commit.\n */\nexport const RunKnowledgePlanSourceSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('procedure-replay'),\n procedureId: z.string(),\n guard: z.object({\n checksPassed: z.number().int().nonnegative(),\n total: z.number().int().nonnegative(),\n miss: z.object({\n procedureStepIndex: z.number().int().nonnegative(),\n reason: z.enum([\n 'descriptor-ambiguous',\n 'descriptor-missing',\n 'page-anchor-mismatch',\n 'gate-refused',\n 'parameter-unbound',\n 'non-replayable-action',\n ]),\n }).strict().optional(),\n executionFailure: z.object({\n procedureStepIndex: z.number().int().nonnegative(),\n }).strict().optional(),\n verifierRejection: z.object({\n procedureStepIndex: z.number().int().nonnegative(),\n }).strict().optional(),\n }).strict(),\n /**\n * The cross-flow position of this test step (407-12, CR-01), mirroring `StepPlanSource.flow`:\n * `cursor` = the committed body-step index this test step attempted, `length` = the committed\n * body's step count. The runner writes it UNCONDITIONALLY on every replay plan source it\n * records (`recordProcedureReplaySource` returns early when there is no cursor, and otherwise\n * always emits the member), so on disk it is present on every replay row a shipped build\n * wrote. Optional here only because pre-F-381-51-1 handoffs predate it.\n *\n * It rides BESIDE the guard fold and never inside it: the fold is per-step\n * (`checksPassed`/`total` over this step's attempted actions), and folding a cross-flow\n * cursor into it would make \"this step's replayed actions all passed\" mean two things.\n */\n flow: z.object({\n cursor: z.number().int().nonnegative(),\n length: z.number().int().nonnegative(),\n }).strict().optional(),\n }).strict(),\n z.object({\n kind: z.literal('procedure-hint'),\n procedureId: z.string(),\n demotion: z.enum(['body-unreadable', 'body-unparseable', 'body-empty']).optional(),\n }).strict(),\n])\n\nexport type RunKnowledgePlanSource = z.infer<typeof RunKnowledgePlanSourceSchema>\n\n/**\n * ONE STEP of one member test, with everything the panel shows for it.\n *\n * `testIndex` AND `stepIndex` both ride, because `stepIndex` is numbered PER MEMBER TEST — a run\n * with two tests has two step 0s, and a row keyed on `stepIndex` alone would address neither\n * (the `StepEvidenceAddress` never-guess contract, restated as a wire shape).\n */\nexport const RunKnowledgeStepSchema = z.object({\n testId: z.string(),\n testIndex: z.number().int().nonnegative(),\n stepIndex: z.number().int().nonnegative(),\n stepText: z.string(),\n served: z.object({\n channel1: z.array(RunKnowledgeBriefLineSchema),\n channel2: z.array(RunKnowledgeReadTraceSchema),\n channel3: z.array(RunKnowledgeCautionLineSchema),\n }).strict(),\n trace: RunKnowledgeTraceSchema,\n planSource: RunKnowledgePlanSourceSchema.optional(),\n retrievalRung: RecordedRetrievalRungSchema.optional(),\n}).strict()\n\nexport type RunKnowledgeStep = z.infer<typeof RunKnowledgeStepSchema>\n\n/**\n * One served canary line that curation later attributed an outcome to (D-08).\n *\n * `recordId` is the served line's own id — which IS the curation candidate id, the pin\n * `emit-canary-outcomes.ts` already relies on — and `observationId` is the sha-derived id the\n * outcome event carries, so a surface can trace a badge back to the exact event that justified\n * it. Rows appear ONLY for tuples with a surviving attributed outcome; a canary line with no\n * outcome yet is absent here and the panel reads \"attribution pending\" from the curation word.\n */\nexport const RunKnowledgeCanaryAttributionSchema = z.object({\n testIndex: z.number().int().nonnegative(),\n stepIndex: z.number().int().nonnegative(),\n recordId: z.string(),\n observationId: z.string(),\n outcome: z.enum(['confirmed', 'contradicted', 'helpful', 'harmful']),\n}).strict()\n\nexport type RunKnowledgeCanaryAttribution = z.infer<typeof RunKnowledgeCanaryAttributionSchema>\n\n/**\n * The whole panel projection — TWO ARMS, and the second one is the point (D-06).\n *\n * `evidence-incomplete` is a RESULT, not a throw. A run whose handoff has been pruned is the\n * ordinary \"go looking\" case 406 D-17 gave a component to, and a refusal would make a legible\n * page state indistinguishable from a broken read.\n *\n * `knowledgeStore` distinguishes \"this project has no knowledge store\" from \"retrieval ran and\n * served nothing\", derived from the durable {@link NO_KNOWLEDGE_READER_TRUNCATION} marker rather\n * than from a handoff version — a version says when a run happened, not what was bound to it.\n *\n * NO `null` ANYWHERE. Absence is an absent key throughout (the layer's own idiom): `counts` is\n * missing when the frozen notification row did not record both numbers, and does not read as a\n * zero somebody measured. 2026-09-30, 432-09 (D-25): the ready arm carries no pending-proposal\n * count; the tab shows what changed, never what awaits review.\n */\nexport const RunKnowledgeProjectionSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('evidence-incomplete'),\n runId: z.string(),\n }).strict(),\n z.object({\n kind: z.literal('ready'),\n runId: z.string(),\n buildOrdinal: z.number().int().nonnegative(),\n knowledgeStore: z.enum(['bound', 'unbound']),\n retrievalRung: RecordedRetrievalRungSchema.optional(),\n steps: z.array(RunKnowledgeStepSchema),\n curation: z.object({\n status: z.enum(POST_PROCESSING_CHIP_STATUSES),\n counts: z.object({\n curated: z.number().int().nonnegative(),\n deprecated: z.number().int().nonnegative(),\n }).strict().optional(),\n skipped: PostProcessingSkippedSchema.optional(),\n }).strict(),\n learned: z.object({\n changes: z.array(RunKnowledgeLearnedChangeSchema),\n canaryAttributions: z.array(RunKnowledgeCanaryAttributionSchema),\n /**\n * This run's curation as curation recorded it (423 D-15): the fixed checkpoint snapshot,\n * served verbatim so its rows reconcile exactly with its breakdown. Absent when curation\n * completed no snapshot (a failed or pre-423 chain) — never five zeros.\n */\n curationSnapshot: CurationSnapshotSchema.optional(),\n /**\n * The nested post-processing read withheld this run's snapshot (423 D-15): present beside an\n * absent {@link curationSnapshot} and an absent {@link sinceThen}; the learned rows stay served.\n */\n curationSnapshotWithheld: CurationSnapshotWithheldSchema.optional(),\n /**\n * Attributed changes whose recorded identity is not in {@link curationSnapshot}, such as a\n * later promotion of a record the snapshot already names. Present only beside a snapshot.\n */\n sinceThen: z.object({\n changes: z.array(RunKnowledgeLearnedChangeSchema),\n count: z.number().int().nonnegative(),\n }).strict().refine(section => section.count === section.changes.length, {\n message: 'sinceThen.count must equal its change rows', path: ['count'],\n }).optional(),\n /**\n * THE LEARNED HALF DEGRADED, AND SAYS SO (407-14, CR-03).\n *\n * Present iff a knowledge-store scan error — one malformed, truncated or tampered bundle,\n * quite possibly in a bundle this run never touched — folded one or both store enrichments\n * to an empty list. Before this member the same byte took down the WHOLE read: the reader\n * face threw, the op wrapped nothing, and the route rendered `read_failed` over a Used half\n * that was perfectly intact.\n *\n * `true` OR ABSENT, never `false` — the projection's no-null/no-zero-fill idiom applied to a\n * flag: a surface must not be able to read \"we checked and the scan was fine\" out of a build\n * that never had the concept. An empty `changes` list with this key is a DIFFERENT fact from\n * an empty one without it, which is the whole reason the marker is on the wire rather than\n * inferred from emptiness.\n */\n scanIncomplete: z.literal(true).optional(),\n }).strict(),\n }).strict(),\n])\n\nexport type RunKnowledgeProjection = z.infer<typeof RunKnowledgeProjectionSchema>\n\n/**\n * What the evidence-blob READ PORT answers with — three arms, and absence is TWO of them.\n *\n * THE SPLIT IS THE WHOLE POINT (D-15). `FsEvidenceArtifactStore.getBlob` returns `undefined` for a\n * run that never existed and for a run that exists and holds no such blob, and those are different\n * operator situations: the first is a bad link, the second is a GC'd or never-written artifact that\n * the page must render as a visible \"screenshot unavailable\" state. A port that answered one word\n * for both would make that distinction unrecoverable above it.\n *\n * NEITHER ABSENCE IS AN ERROR HERE. Turning an arm into the layer's typed refusal is the op's job,\n * so the \"not found\" vocabulary lives in one place rather than in every composition root.\n */\nexport type EvidenceBlobLookup =\n | { readonly status: 'found'; readonly bytes: Uint8Array }\n | { readonly status: 'blob_absent' }\n | { readonly status: 'unknown_run' }\n\n/**\n * The same three words, asked as a STAT rather than as a read (Phase 406, D-17).\n *\n * DERIVED FROM {@link EvidenceBlobLookup} RATHER THAN RESPELLED, because presence and the read\n * are one question asked at two costs: a durable read annotating every artifact ref on a run page\n * must not load a screenshot to decide whether to draw a link. A second literal union here would\n * be a second answer to which absences exist, free to fall behind the one the port already\n * serves — and the whole value of the split (D-15) is that the two arms stay distinguishable.\n */\nexport type EvidenceBlobPresence = EvidenceBlobLookup['status']\n","// The retrieval degradation rung, as a recorded fact about ONE run (Phase 407, TRST-01 · D-13/D-17).\n//\n// WHY A VOCABULARY AND NOT A STRING. The rung is what a banner PRINTS and what `doctor` grades,\n// and an open string would let a producer invent a fifth rung no reader has a rendering for —\n// the same reason `RETRIEVAL_TRACE_LEGS` next door is closed. Four names, folded once from the\n// two real axes the host exposes (the index face `'index' | 'scan'` and the embedder outcome\n// `native | floor | deferred | lexical-only`); the fold itself lives in `knowledge-local`, which\n// is the only package that can see either axis, and it hands the recorded value back as this\n// schema type. One vocabulary, three callers: the runner's evidence recorder, the run header's\n// banner, and `doctor`'s three rows.\n//\n// WHAT THE RUNG DESCRIBES, EXACTLY. It is the HOST's retrieval ladder at the moment this run was\n// served — not a claim about how any individual brief line was ranked. The run-brief serve path\n// reads index rows directly and attributes channels 1 and 3 to the `anchor` leg by construction;\n// the dense leg and the bundle-scan fallback live in the general `retrieve()` path used by the\n// curator, the entity resolver and the authoring reader. A surface must therefore never render\n// this value as \"this brief was dense-ranked\" — it renders \"retrieval was on rung X for this run\".\n//\n// RECORDED, NOT RE-DERIVED. A run served on the static floor stays labelled that way forever,\n// even after the host is fixed: the banner is about the run, not about the machine reading it\n// today. That is the same 387 D-13 posture the serve-time retrieval trace carries, and it is why\n// this value is persisted beside the evidence rather than recomputed at read time.\n\nimport { z } from 'zod'\n\n/**\n * The four rungs of the v51 degradation ladder, best first.\n *\n * `memidex` — the index is openable AND a native embedder is live: dense, lexical and anchor\n * legs all participate. `bundle-scan` — the index face degraded to `scan`, so no dense leg runs\n * regardless of the embedder (which is why the index axis is folded FIRST). `static-floor` — the\n * index is live but the embedder fell back to the static floor profile. `lexical-only` — the\n * index is live and no embedder resolved at all, so nothing dense participates.\n */\nexport const RETRIEVAL_RUNGS = ['memidex', 'bundle-scan', 'static-floor', 'lexical-only'] as const\n\nexport type RetrievalRung = (typeof RETRIEVAL_RUNGS)[number]\n\n/**\n * WHY the ladder degraded, as a closed enum recorded beside the rung (D-15, widened by 423 D-22).\n *\n * Closed rather than free prose lifted from an error, because this string is rendered to a\n * person in a one-line banner and graded by `doctor` — an error message would be neither\n * stable nor safe to print. `cold-artifact` and `load-failure` are real `DeferReason` arms in\n * `embedder-acquire.ts` and a `static` PREFERRED profile is a real configuration, so the enum\n * has a home for each rather than folding distinct operator situations into one wrong word.\n *\n * The mapping of record (fold owner: `knowledge-local/src/retrieval-rung.ts`):\n * `index-not-built` — the index file is absent (fresh store or clone); bundle scan is authoritative.\n * `index-locked` — another connection held the index; transient contention.\n * `index-corrupt` — the index would not open or carries the wrong schema version; rebuild requested.\n * `index-unavailable` — HISTORICAL ONLY: a pre-423 scan whose cause was not recorded. No current\n * fold mints it, and no reader may reinterpret it as one of the three causes above.\n * `native-runtime-unavailable` — the native ONNX runtime could not load; the floor took over.\n * `profile-static-configured` — the floor is serving because the PREFERRED profile is static.\n * `model-not-downloaded` — `DeferReason: 'cold-artifact'`.\n * `embedder-load-failed` — `DeferReason: 'load-failure'`.\n * `profile-unresolved` — `DeferReason: 'worker-unavailable'` (the 399 daemon posture).\n * `floor-disabled` — the floor factory itself refused, so retrieval is lexical by choice.\n */\nexport const RETRIEVAL_RUNG_REASONS = [\n 'native-runtime-unavailable',\n 'profile-unresolved',\n 'model-not-downloaded',\n 'embedder-load-failed',\n 'index-unavailable',\n 'floor-disabled',\n 'profile-static-configured',\n 'index-not-built',\n 'index-locked',\n 'index-corrupt',\n] as const\n\nexport type RetrievalRungReason = (typeof RETRIEVAL_RUNG_REASONS)[number]\n\n/** A recorded rung carries the current reason vocabulary. */\nexport const RecordedRetrievalRungSchema = z.object({\n schemaVersion: z.literal(2),\n rung: z.enum(RETRIEVAL_RUNGS),\n reason: z.enum(RETRIEVAL_RUNG_REASONS).optional(),\n}).strict()\n\nexport type RecordedRetrievalRung = z.infer<typeof RecordedRetrievalRungSchema>\n","// The serve-time retrieval trace (Phase 387, KREV-02 · D-13/D-14).\n//\n// What a brief SAID is already durable; what this contract makes durable is WHY it said it.\n// The serving path knows leg, rank, score and what the token budget cut at the moment it\n// assembles a brief, and every one of those facts is gone a millisecond later — a later\n// question answered by re-querying the index answers about *now*, which is precisely the\n// dishonesty KREV-02 exists to prevent. So the trace is captured at the seam and persisted\n// beside the evidence, and the why-verb reads only what was written down.\n//\n// TWO ledgers, not one. `servedLines` answers \"why did it say this\". `truncated` answers\n// \"why didn't it mention X\" — the question a QA engineer debugging a missed hint actually\n// asks, and the one that is unanswerable from the served brief alone because the cut\n// candidates leave no trace in it at all (D-14).\n//\n// This module deliberately does NOT touch the `ServedBrief` contract. That value feeds\n// `computeBriefDigest`, and every cassette and acceptance digest in the tree is keyed on its\n// exact bytes; a trace channel added there would have rewritten all of them (D-13).\n\nimport { z } from 'zod'\n\n/**\n * The retrieval legs a served line can be attributed to.\n *\n * VOCABULARY OF RECORD: `knowledge-local/src/retrieval/legs.ts`, whose `CandidateLeg` type\n * declares exactly these three names. That type is module-private and lives in a package\n * that sits ABOVE this one in the dependency order, so it cannot be imported here — which\n * makes this a second, independent spelling of one vocabulary with nothing holding the two\n * together. The cross-check belongs on the `knowledge-local` side (it depends on `schema`,\n * not the reverse) and is left for the plan that wires the serve seam.\n *\n * Closed on purpose: a leg is the ATTRIBUTION a why-answer prints, and an open string would\n * let a producer invent a fourth leg that no reader has a rendering for.\n */\nexport const RETRIEVAL_TRACE_LEGS = ['lexical', 'dense', 'anchor'] as const\n\nexport type RetrievalTraceLeg = (typeof RETRIEVAL_TRACE_LEGS)[number]\n\n/**\n * How many budget-cut candidates the truncation ledger carries.\n *\n * Bounded because the cut set is unbounded in principle — every admitted candidate that did\n * not fit is a cut candidate, and an unbounded ledger would make a step's evidence grow with\n * the size of the index rather than with what happened. Twenty is the depth at which \"why\n * didn't it mention X\" stops being answerable in practice: past it, X was not a near miss.\n * Retune from operational evidence — real why-questions whose answer fell off the end —\n * without adding config.\n */\nexport const TRACE_TRUNCATION_TOP_K = 20\n\n/**\n * One attributed candidate: which record, which leg matched it, where it ranked, and what it\n * scored.\n *\n * `rank` is 1-based, matching the in-tree convention the retrieval legs already use\n * (`index + 1` at their candidate-construction sites). A zero is rejected rather than\n * silently read as \"top result\", because the two conventions differ by exactly one and a\n * printed answer that is off by one rank is wrong in the least detectable way.\n *\n * `score` is finite but otherwise unbounded: fused RRF scores are sums of reciprocal-rank\n * contributions, not probabilities, and clamping them to [0,1] here would misreport them.\n */\nexport const TraceLineSchema = z.object({\n recordId: z.string().min(1),\n leg: z.enum(RETRIEVAL_TRACE_LEGS),\n rank: z.number().int().positive(),\n score: z.number().finite(),\n}).strict()\n\nexport type TraceLine = z.infer<typeof TraceLineSchema>\n\nexport const RETRIEVAL_TRACE_SCHEMA_VERSION = 2\n\n/**\n * The trace as persisted, stamped with `RETRIEVAL_TRACE_SCHEMA_VERSION`.\n *\n * `servedLines` is deliberately unbounded — the serving budget already bounds how many lines\n * can be served, so a second cap here would only ever disagree with the first.\n */\nexport const ServedRetrievalTraceV1Schema = z.object({\n schemaVersion: z.literal(RETRIEVAL_TRACE_SCHEMA_VERSION),\n servedLines: z.array(TraceLineSchema),\n truncated: z.array(TraceLineSchema).max(TRACE_TRUNCATION_TOP_K),\n}).strict()\n\nexport type ServedRetrievalTraceV1 = z.infer<typeof ServedRetrievalTraceV1Schema>\n","// The five knowledge review verbs' input and output contracts (Phase 387, KREV-01/KREV-02).\n//\n// Four of the five verbs are WIRING over functions the read-only reader entry already\n// exports (`inspectRecords`, `diffSince`, `listBundles`, the record read) — that is KREV-01's\n// own claim, and it only stays true if the DTOs here PROJECT those return shapes instead of\n// paraphrasing them. So the inspect and diff outputs carry the reader's own view schemas\n// verbatim; a paraphrase would have quietly become a second view to keep in step, and the\n// first field to drift would have been the one nobody looked at.\n//\n// The fifth verb — \"why did the brief say this\" — is the one with a real contract of its\n// own, and it is a contract about HONESTY rather than shape (D-15).\n\nimport { z } from 'zod'\n\nimport { ServedRetrievalTraceV1Schema } from '../brief/retrieval-trace'\nimport type { ServedBrief } from '../brief/served-brief'\nimport { ImprovementPlanKnowledgeSchema } from '../functions/feedback'\nimport { InspectFilterSchema, InspectRecordViewSchema, RecordChangeSchema } from './maintenance-views'\nimport { BundleProvenanceSchema } from './bundle-files'\nimport { KnowledgeTargetRefSchema, MarkChangeStampSchema } from './change'\n\n/**\n * WHY a why-question has no answer. Closed, and each member names a genuinely different\n * situation a surface has to phrase differently:\n *\n * `pre-trace-run` — the run predates trace capture. Nothing was lost; nothing was ever\n * written. This is permanent and no amount of retrying changes it.\n * `artifact-missing`— the run captured a trace and the artifact is gone (pruned, moved).\n * `step-not-found` — the run and its trace exist; the step being asked about does not.\n *\n * A bare \"no trace\" would have collapsed all three, and the only message a surface could\n * then print is one that tells the reader nothing about whether to go looking.\n */\nexport const BRIEF_WHY_NO_TRACE_REASONS = [\n 'pre-trace-run',\n 'artifact-missing',\n 'step-not-found',\n] as const\n\nexport type BriefWhyNoTraceReason = (typeof BRIEF_WHY_NO_TRACE_REASONS)[number]\n\n/**\n * The complete arm set of {@link BriefWhyResultSchema}, as a value.\n *\n * Exported so the closure can be asserted as an exact member set. \"No test exercises a\n * re-run arm\" is a claim about a test file; this is a claim about the contract — and the\n * absent arm is the whole design (D-15). Re-running retrieval would answer about the index\n * as it stands NOW, while the question asked is always about then.\n */\nexport const BRIEF_WHY_RESULT_KINDS = ['answered', 'no-trace'] as const\n\nexport type BriefWhyResultKind = (typeof BRIEF_WHY_RESULT_KINDS)[number]\n\n/**\n * Validates an offered `ServedBrief` at the §A11 three-channel depth.\n *\n * `ServedBrief` is a TypeScript interface whose only runtime schema in the tree requires the\n * acceptance-grade `proof` block, and a historical brief — exactly the kind offered on the\n * no-trace arm — has no proof. So the offering is checked against the closed channel set\n * §A11 fixes, which is the structure any consumer of this arm renders, and no deeper.\n *\n * STRUCTURAL, not `z.custom`. 2026-08-02 (387-06): the predicate form was correct and\n * unprojectable — `z.toJSONSchema` throws `Custom types cannot be represented in JSON Schema`\n * on it, and the function layer projects EVERY registered contract into an inert document at\n * registry-construction time (D-14). So the moment an op declared this union as its output,\n * building a registry threw and every capability in the process stopped listing, not just this\n * one. A predicate that cannot be described is a contract no catalog can publish, and 396's\n * MCP tool listing consumes exactly that description.\n *\n * `looseObject` rather than a strict one, because a real brief carries more than the three\n * channels (`proof`, and whatever §A11 adds next) and an offering is a value being PASSED ON,\n * not one being defined here. The acceptance and rejection behaviour is identical to the\n * predicate it replaces: an array carrying every channel as a named property is still refused,\n * a null is still refused, a missing digest is still refused, and a non-array channel is still\n * refused — measured against 387-02's nine-case rejection corpus, which is unchanged.\n */\nconst ServedBriefOfferingSchema = z.looseObject({\n channel1: z.array(z.unknown()),\n channel2: z.array(z.unknown()),\n channel3: z.array(z.unknown()),\n briefDigest: z.string(),\n}) as unknown as z.ZodType<ServedBrief>\n\n/**\n * The why-verb's answer: the trace that was written down, or a named reason there is none —\n * and never a third thing (D-15).\n *\n * The two arms are structurally incompatible on purpose. A trace on the absence arm is\n * exactly the shape a re-run would arrive in, so the schema refuses it rather than trusting\n * a future implementer to remember why the arm is empty.\n */\nexport const BriefWhyResultSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('answered'),\n trace: ServedRetrievalTraceV1Schema,\n /** Where the brief this trace explains lives, when the caller wants to read it too. */\n servedBriefRef: z.string().min(1).optional(),\n }).strict(),\n z.object({\n kind: z.literal('no-trace'),\n reason: z.enum(BRIEF_WHY_NO_TRACE_REASONS),\n /** Offered when the brief survived even though its trace did not. */\n servedBrief: ServedBriefOfferingSchema.optional(),\n }).strict(),\n])\n\nexport type BriefWhyResult = z.infer<typeof BriefWhyResultSchema>\n\n/**\n * Which step's brief is being asked about.\n *\n * `runId` + `stepIndex` is the primary key and `recordId` filters within it (RESEARCH open\n * question 3). `testId` is the disambiguator that key needs in practice and did not have:\n * `stepIndex` is per TEST, so a run with two tests has two step 0s. It is optional because a\n * single-test run needs no disambiguation — and under the never-guess contract the verb\n * refuses an ambiguous address rather than picking the first test.\n */\nexport const BriefWhyInputSchema = z.object({\n runId: z.string().min(1),\n testId: z.string().min(1).optional(),\n stepIndex: z.number().int().nonnegative(),\n recordId: z.string().min(1).optional(),\n}).strict()\n\nexport type BriefWhyInput = z.infer<typeof BriefWhyInputSchema>\n\n/**\n * 419 D-01: the knowledge fix a recorded user mark applies. 2026-10-01 (432-17): the accept, reject\n * and forget inputs and the direct change contracts live in `./change`; a mark is applied by\n * `runs.mark` in the same call (D-04).\n */\nexport const KnowledgeMarkInputSchema = z.object({\n target: KnowledgeTargetRefSchema,\n mark: MarkChangeStampSchema,\n plan: ImprovementPlanKnowledgeSchema,\n}).strict()\nexport type KnowledgeMarkInput = z.infer<typeof KnowledgeMarkInputSchema>\n\n/** `inspectRecords`' structural filter, unchanged — the verb is a client, not a rewrite. */\nexport const KnowledgeRecordsInspectInputSchema = z.object({\n filter: InspectFilterSchema,\n}).strict()\n\nexport type KnowledgeRecordsInspectInput = z.infer<typeof KnowledgeRecordsInspectInputSchema>\n\nexport const KnowledgeRecordsInspectOutputSchema = z.object({\n schemaVersion: z.literal(2),\n records: z.array(InspectRecordViewSchema),\n}).strict()\n\nexport type KnowledgeRecordsInspectOutput = z.infer<typeof KnowledgeRecordsInspectOutputSchema>\n\nexport const KnowledgeRecordsDiffInputSchema = z.object({\n sinceOrdinal: z.number().int().nonnegative(),\n}).strict()\n\nexport type KnowledgeRecordsDiffInput = z.infer<typeof KnowledgeRecordsDiffInputSchema>\n\n/**\n * The diff echoes the ordinal it was taken since. A change list with no baseline is a list\n * whose meaning depends on remembering the question, and these answers get pasted into\n * issues and CI logs where that context is gone.\n */\nexport const KnowledgeRecordsDiffOutputSchema = z.object({\n schemaVersion: z.literal(2),\n sinceOrdinal: z.number().int().nonnegative(),\n changes: z.array(RecordChangeSchema),\n}).strict()\n\nexport type KnowledgeRecordsDiffOutput = z.infer<typeof KnowledgeRecordsDiffOutputSchema>\n\nexport const KnowledgeRecordShowInputSchema = z.object({\n recordId: z.string().min(1),\n}).strict()\n\nexport type KnowledgeRecordShowInput = z.infer<typeof KnowledgeRecordShowInputSchema>\n\n/**\n * One record with the provenance that justifies it — the whole point of the verb. A record\n * shown without its provenance is an assertion; shown with it, it is evidence.\n */\nexport const KnowledgeRecordShowOutputSchema = z.object({\n schemaVersion: z.literal(2),\n record: InspectRecordViewSchema,\n provenance: BundleProvenanceSchema,\n summary: z.string(),\n body: z.string(),\n}).strict()\n\nexport type KnowledgeRecordShowOutput = z.infer<typeof KnowledgeRecordShowOutputSchema>\n\n/**\n * The show verb's answer: the record with its provenance, or a named absence (FUNC-04).\n *\n * A closed union rather than a throw, because asking about a record id that no bundle carries\n * is an ordinary thing for a reviewer to do — an id gets pasted out of a stale issue, or a\n * record was forgotten between two reads — and the caller has to be able to tell that apart\n * from a store that could not be read at all. A verb that threw on both would have made the\n * routine case indistinguishable from the broken one.\n *\n * The found arm SPREADS {@link KnowledgeRecordShowOutputSchema}'s own shape rather than\n * restating its fields, so the two cannot drift: there is one declaration of what showing a\n * record yields, and this union only adds the discriminant that makes absence expressible.\n */\nexport const KnowledgeRecordShowResultSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('found'),\n ...KnowledgeRecordShowOutputSchema.shape,\n }).strict(),\n z.object({\n kind: z.literal('not-found'),\n schemaVersion: z.literal(2),\n /** Echoed so an answer pasted into an issue still says what was asked about. */\n recordId: z.string().min(1),\n }).strict(),\n])\n\nexport type KnowledgeRecordShowResult = z.infer<typeof KnowledgeRecordShowResultSchema>\n","// 2026-09-08, 419 D-06/D-07/D-08/D-12: the Gate-3 neutral contracts.\nimport { z } from 'zod'\nimport type { Action } from '../action/index'\nimport { actionWireSchema } from '../action/wire-schema'\n\nimport { MARKS } from '../knowledge/gate-receipt'\nimport { DeltaSchema, KnowledgeChangeIdSchema, KnowledgeTargetRefSchema } from '../knowledge/change'\nimport { runIdSchema as runIdCodec, type RunId } from '../run/run-id'\nimport { VERDICT_CLASSES, type VerdictClass } from '../verdict/verdict'\nimport { oneJoinArm, recordJoinShape } from './record-join'\n\n// Reuse the canonical path validator before its type-only branding transform. The bytes\n// are unchanged; this structural schema also supports output JSON-schema projection.\nconst runIdSchema = runIdCodec.in as unknown as z.ZodType<RunId>\nconst markIdSchema = z.string().regex(/^mark_[0-9a-f]{12}$/)\nconst indexSchema = z.number().int().nonnegative()\nconst correctedActionSchema = actionWireSchema as unknown as z.ZodType<Action>\ntype ExactlyEqual<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false\n\n// prettier-ignore\nexport const MARK_QUARANTINE_CLASSES = ['flake', 'environment', 'timeout'] as const satisfies readonly VerdictClass[]\nexport type MarkQuarantineClass = (typeof MARK_QUARANTINE_CLASSES)[number]\n\nexport const MARK_FIX_KINDS = ['fact', 'caution', 'procedure-hint', 'test-edit'] as const\nexport type MarkFixKind = (typeof MARK_FIX_KINDS)[number]\n\n// 2026-09-30, 432-09 (D-04/D-22): a mark applies its fix in the call, so the writer's vocabulary is\n// `applied`. `drafted` is the pre-432 receipt that filed a proposal instead: it stays readable in an\n// existing ledger (430 D-08) and no writer produces it.\n// 2026-10-03 (quick 261003-mqc): `not-applied` closes a mark whose own planned fix was refused,\n// under the mark's own identity, so its gold and evidence count once and the run takes a new mark.\n// prettier-ignore\nexport const MARK_DISPOSITIONS = ['quarantined', 'applied', 'no-draftable-fix', 'confirmed-bug', 'not-applied'] as const\nexport const MARK_HISTORICAL_DISPOSITIONS = ['drafted'] as const\n\n/**\n * Why a mark's planned fix was not applied. Each comes from the plan itself, so retrying the same\n * plan could never apply it: the knowledge target is gone, the policy text is refused, or the test\n * file is outside the workspace.\n */\nexport const MARK_FIX_REFUSALS = [\n 'target-not-found',\n 'policy-materialize-refused',\n 'outside-workspace',\n] as const\nexport type MarkFixRefusal = (typeof MARK_FIX_REFUSALS)[number]\n\nexport const MARK_APPLIED_CHANGE_KINDS = ['knowledge', 'test-file'] as const\n\n/**\n * What an applied fix changed. A knowledge change names its stable change id and the records the\n * write read back; a test edit names the file it wrote and the digest of the exact bytes written.\n */\nexport const MarkAppliedChangeSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('knowledge'),\n changeId: KnowledgeChangeIdSchema,\n recordIds: z.array(z.string().min(1)),\n }).strict(),\n z.object({\n kind: z.literal('test-file'),\n filePath: z.string().min(1),\n contentDigest: z.string().min(1),\n }).strict(),\n])\nexport type MarkAppliedChange = z.infer<typeof MarkAppliedChangeSchema>\n\nexport const NoDraftableFixCheckedSchema = z.object({\n servedRecords: indexSchema,\n procedureReads: indexSchema,\n assertionDrift: z.boolean(),\n rootCause: z.enum(VERDICT_CLASSES).optional(),\n}).strict()\nexport type NoDraftableFixChecked = z.infer<typeof NoDraftableFixCheckedSchema>\n\nexport const MarkDispositionSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('quarantined'), class: z.enum(MARK_QUARANTINE_CLASSES) }).strict(),\n z.object({\n kind: z.literal('applied'),\n fix: z.enum(MARK_FIX_KINDS),\n change: MarkAppliedChangeSchema,\n }).strict().superRefine((value, ctx) => {\n if ((value.fix === 'test-edit') !== (value.change.kind === 'test-file')) {\n ctx.addIssue({ code: 'custom', path: ['change', 'kind'], message: 'a test edit writes a test file and every other fix changes knowledge' })\n }\n }),\n z.object({ kind: z.literal('no-draftable-fix'), checked: NoDraftableFixCheckedSchema }).strict(),\n z.object({ kind: z.literal('confirmed-bug'), confirmedRecords: indexSchema }).strict(),\n /** The mark's planned fix was refused, so nothing was changed; the mark itself stands. */\n z.object({\n kind: z.literal('not-applied'),\n fix: z.enum(MARK_FIX_KINDS),\n reason: z.enum(MARK_FIX_REFUSALS),\n }).strict(),\n /** Historical (read only): a pre-432 mark that filed a proposal. Its change was never recorded. */\n z.object({\n kind: z.literal('drafted'),\n fix: z.enum(MARK_FIX_KINDS),\n proposalId: z.string().min(1),\n proposalKind: z.enum(['knowledge', 'test-draft']),\n }).strict(),\n])\nexport type MarkDisposition = z.infer<typeof MarkDispositionSchema>\nconst _dispositionsCover: ExactlyEqual<\n (typeof MARK_DISPOSITIONS)[number] | (typeof MARK_HISTORICAL_DISPOSITIONS)[number], MarkDisposition['kind']> = true\nvoid _dispositionsCover\nconst _appliedChangeKindsCover: ExactlyEqual<(typeof MARK_APPLIED_CHANGE_KINDS)[number], MarkAppliedChange['kind']> = true\nvoid _appliedChangeKindsCover\n\nexport const MarkAddressSchema = z.object({\n runId: runIdSchema,\n testIndex: indexSchema,\n testId: z.string().min(1).optional(),\n stepIndex: indexSchema.optional(),\n}).strict()\nexport type MarkAddress = z.infer<typeof MarkAddressSchema>\n\nexport const MARK_RECEIPT_SCHEMA_VERSION = 2\nexport const MarkReceiptSchema = z.object({\n schemaVersion: z.literal(MARK_RECEIPT_SCHEMA_VERSION),\n markId: markIdSchema,\n ...MarkAddressSchema.shape,\n runSlug: z.string().min(1),\n kind: z.enum(MARKS),\n origin: z.literal('user'),\n /** The 1-based append position governs latest-wins, never markedAt (419 D-11). */\n ordinal: z.number().int().positive(),\n markedAt: indexSchema,\n note: z.string().max(2000).optional(),\n correctedExpectation: z.string().max(2000).optional(),\n correctedAction: correctedActionSchema.optional(),\n rootCause: z.object({ class: z.enum(VERDICT_CLASSES), producer: z.string().min(1) }).strict().optional(),\n isRerun: z.literal(true).optional(),\n disposition: MarkDispositionSchema,\n gold: z.array(z.object({\n cassetteId: z.string().min(1),\n sourceCassetteId: z.string().min(1),\n channel: z.enum(['user-mark', 'overturned-verdict']),\n }).strict()),\n evidence: z.object({ confirmed: indexSchema, overturned: indexSchema }).strict(),\n supersedes: markIdSchema.optional(),\n}).strict()\nexport type MarkReceipt = z.infer<typeof MarkReceiptSchema>\n\nexport const RunsMarkInputSchema = z.object({\n runId: runIdSchema,\n testId: z.string().min(1).optional(),\n stepIndex: indexSchema.optional(),\n kind: z.enum(MARKS),\n note: z.string().max(2000).optional(),\n correctedExpectation: z.string().max(2000).optional(),\n correctedAction: correctedActionSchema.optional(),\n}).strict()\nexport type RunsMarkInput = z.infer<typeof RunsMarkInputSchema>\n\nexport const RunsMarkOutcomeSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('marked'), receipt: MarkReceiptSchema }).strict(),\n z.object({ kind: z.literal('already-marked'), receipt: MarkReceiptSchema }).strict(),\n z.object({ kind: z.literal('run-not-found'), runId: runIdSchema }).strict(),\n z.object({ kind: z.literal('member-not-found'), runId: runIdSchema, testId: z.string().optional() }).strict(),\n z.object({\n kind: z.literal('step-not-found'), runId: runIdSchema,\n testIndex: indexSchema, stepIndex: indexSchema, stepCount: indexSchema,\n }).strict(),\n z.object({\n kind: z.literal('ambiguous-address'), runId: runIdSchema,\n candidates: z.array(z.object({ testIndex: indexSchema, testId: z.string().optional() }).strict()).min(2),\n }).strict(),\n z.object({ kind: z.literal('ambiguous-correction'), runId: runIdSchema,\n testIndex: indexSchema, decisionCount: indexSchema }).strict(),\n])\nexport type RunsMarkOutcome = z.infer<typeof RunsMarkOutcomeSchema>\n\nexport const IMPROVEMENT_PLAN_SCHEMA_VERSION = 2\nconst improvementPlanShape = {\n schemaVersion: z.literal(IMPROVEMENT_PLAN_SCHEMA_VERSION),\n markId: markIdSchema,\n feedbackSource: MarkAddressSchema.extend({ kind: z.enum(MARKS) }),\n runTraceRef: z.object({ runId: runIdSchema, runSlug: z.string().min(1) }).strict(),\n}\nconst wordingSchema = z.enum(['model', 'floor'])\nexport const ImprovementPlanKnowledgeSchema = z.object({\n kind: z.literal('knowledge'),\n ...improvementPlanShape,\n fix: z.enum(['fact', 'caution', 'procedure-hint']),\n target: KnowledgeTargetRefSchema,\n deltas: z.array(DeltaSchema).min(1),\n wording: wordingSchema,\n}).strict().superRefine((value, ctx) => {\n value.deltas.forEach((delta, index) => {\n if (delta.kind === 'MintUnknown') {\n ctx.addIssue({ code: 'custom', path: ['deltas', index, 'kind'], message: 'a mark never mints unknown knowledge (419 D-12)' })\n }\n })\n})\nexport type ImprovementPlanKnowledge = z.infer<typeof ImprovementPlanKnowledgeSchema>\n\nexport const ImprovementPlanSchema = z.discriminatedUnion('kind', [\n ImprovementPlanKnowledgeSchema,\n z.object({\n kind: z.literal('test-edit'), ...improvementPlanShape,\n fix: z.literal('test-edit'), testRef: z.string().min(1), intent: z.string().min(1), wording: wordingSchema,\n }).strict(),\n z.object({\n kind: z.literal('no-draftable-fix'), ...improvementPlanShape, checked: NoDraftableFixCheckedSchema,\n }).strict(),\n])\nexport type ImprovementPlan = z.infer<typeof ImprovementPlanSchema>\n\n// 2026-10-01, 432-17: the commit receipt is a direct change receipt and lives with the change\n// contracts; it is re-exported here so every existing import keeps its path.\nexport { COMMIT_RECEIPT_SCHEMA_VERSION, CommitReceiptSchema } from '../knowledge/change'\nexport type { CommitReceipt } from '../knowledge/change'\n\nexport const RunDetailMemberMarkSchema = z.object({\n markId: markIdSchema,\n kind: z.enum(MARKS),\n ordinal: z.number().int().positive(),\n stepIndex: indexSchema.optional(),\n disposition: MarkDispositionSchema,\n}).strict()\nexport type RunDetailMemberMark = z.infer<typeof RunDetailMemberMarkSchema>\n\n/** OQ5: gate3ArmSchema.stepId uses the same test:step spelling as DisplayStep addressing. */\nexport function deriveMarkStepId(testIndex: number, stepIndex: number): string {\n return `${testIndex}:${stepIndex}`\n}\n\n// 2026-10-02 (432-42, D-15): no mark refusal body. `MarkRefusalSchema` described the 403 the browser\n// door answered when the execution gate denied a mark; the gate is deleted (432-19), no route\n// answers that body, and the dashboard's branch that read it is deleted with it.\n\n/** Shared by runs.mark and runs.detail's ledger projection. */\nexport interface FeedbackPort {\n mark(input: RunsMarkInput): Promise<RunsMarkOutcome>\n marksFor(runId: RunId): Promise<readonly MarkReceipt[]>\n}\n\n/** The ledger's latest-wins address: member plus step, testId deliberately excluded (419 D-11). */\nexport function markAddressKey(address: Pick<MarkAddress, 'testIndex' | 'stepIndex'>): string {\n return `${address.testIndex}:${address.stepIndex ?? 'run'}`\n}\n\n// 2026-09-15, 423 D-19: marks history. 2026-09-30, 432-09 (D-04/D-25): each applied knowledge fix\n// joins the records it changed, read now; nothing is read from a proposal store.\n\nexport const RunsMarksHistoryInputSchema = z.object({ runId: runIdSchema }).strict()\nexport type RunsMarksHistoryInput = z.infer<typeof RunsMarksHistoryInputSchema>\n\n/** One record an applied fix changed: its id, then its content as the store shows it now, or why not. */\nexport const MarkHistoryChangedRecordSchema = z.object({\n recordId: z.string().min(1),\n ...recordJoinShape,\n}).strict().superRefine((record, ctx) => {\n oneJoinArm(record, ctx)\n if (record.recordContent === undefined && record.contentAbsence === undefined) {\n ctx.addIssue({ code: 'custom', path: ['recordContent'], message: 'a changed record leads with its content or the typed absence of it' })\n }\n})\nexport type MarkHistoryChangedRecord = z.infer<typeof MarkHistoryChangedRecordSchema>\n\nconst receiptFactShape = MarkReceiptSchema.omit({\n schemaVersion: true, runSlug: true, correctedExpectation: true, correctedAction: true, note: true,\n}).shape\n\nexport const MarkHistoryEntrySchema = z.object({\n ...receiptFactShape,\n // Masked free text can differ in length from the recorded note, so the writer's cap is not reapplied.\n note: z.string().optional(),\n /** Corrected fields are reported by presence; their content stays in the ledger. */\n corrected: z.object({ expectation: z.boolean(), action: z.boolean() }).strict(),\n active: z.boolean(),\n supersededBy: markIdSchema.optional(),\n /** The records an applied knowledge fix changed, in the receipt's order, joined at read time. */\n changedRecords: z.array(MarkHistoryChangedRecordSchema).optional(),\n}).strict().superRefine((entry, ctx) => {\n if (entry.active === (entry.supersededBy !== undefined)) {\n ctx.addIssue({ code: 'custom', path: ['active'], message: 'exactly the unsuperseded receipt on an address is active' })\n }\n const recordIds = entry.disposition.kind === 'applied' && entry.disposition.change.kind === 'knowledge'\n ? entry.disposition.change.recordIds : undefined\n if (recordIds === undefined ? entry.changedRecords !== undefined\n : entry.changedRecords?.map(record => record.recordId).join('\\n') !== recordIds.join('\\n')) {\n ctx.addIssue({ code: 'custom', path: ['changedRecords'], message: 'an applied knowledge fix joins exactly the records its receipt names' })\n }\n})\nexport type MarkHistoryEntry = z.infer<typeof MarkHistoryEntrySchema>\n\nexport const MARKS_HISTORY_OUTCOMES = ['history', 'run-not-found', 'ledger-corrupt', 'ledger-unavailable'] as const\n\nexport const RunsMarksHistoryResultSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('history'), runId: runIdSchema, entries: z.array(MarkHistoryEntrySchema) }).strict()\n .superRefine((value, ctx) => {\n value.entries.forEach((entry, index) => {\n if (entry.ordinal !== index + 1 || entry.runId !== value.runId) {\n ctx.addIssue({ code: 'custom', path: ['entries', index, 'ordinal'], message: 'history is this run ledger in ordinal order' })\n }\n })\n }),\n z.object({ kind: z.literal('run-not-found'), runId: runIdSchema }).strict(),\n z.object({ kind: z.literal('ledger-corrupt'), runId: runIdSchema, line: z.number().int().positive() }).strict(),\n z.object({ kind: z.literal('ledger-unavailable'), runId: runIdSchema }).strict(),\n])\nexport type RunsMarksHistoryResult = z.infer<typeof RunsMarksHistoryResultSchema>\nconst _historyOutcomesCover: ExactlyEqual<(typeof MARKS_HISTORY_OUTCOMES)[number], RunsMarksHistoryResult['kind']> = true\nvoid _historyOutcomesCover\n\n// 2026-09-15, 423 D-16/D-17: the consequence preview. Input is RunsMarkInputSchema itself; runs.mark\n// gains no field. Refusals are runs.mark's own arm objects, taken by position and type-pinned below.\nconst [, , markRunNotFoundArm, markMemberNotFoundArm, markStepNotFoundArm, markAmbiguousAddressArm,\n markAmbiguousCorrectionArm] = RunsMarkOutcomeSchema.options\n\nexport const MARK_PREVIEW_REFUSALS = ['run-not-found', 'member-not-found', 'step-not-found', 'ambiguous-address', 'ambiguous-correction'] as const\nexport const MARK_PREVIEW_OUTCOMES = ['consequences', 'quarantined', 'already-marked', ...MARK_PREVIEW_REFUSALS] as const\nexport const MARK_TARGET_REASONS = ['step-mark', 'failing-step', 'passing-verdict'] as const\nexport const MARK_GOLD_CHANNELS = ['user-mark', 'overturned-verdict'] as const\nexport const MARK_PREVIEW_LATEST_KINDS = ['first', 'supersedes'] as const\nexport const MARK_PREVIEW_DRAFT_KINDS = ['confirmed-bug', 'knowledge', 'test-edit', 'no-draftable-fix'] as const\n\nconst _refusalArmsInOrder: ExactlyEqual<\n [z.infer<typeof markRunNotFoundArm>['kind'], z.infer<typeof markMemberNotFoundArm>['kind'],\n z.infer<typeof markStepNotFoundArm>['kind'], z.infer<typeof markAmbiguousAddressArm>['kind'],\n z.infer<typeof markAmbiguousCorrectionArm>['kind']],\n [...typeof MARK_PREVIEW_REFUSALS]> = true\nvoid _refusalArmsInOrder\nconst _goldChannelsCover: ExactlyEqual<(typeof MARK_GOLD_CHANNELS)[number], MarkReceipt['gold'][number]['channel']> = true\nvoid _goldChannelsCover\n\nexport const MarkPreviewBasisSchema = z.object({\n ledgerOrdinal: indexSchema,\n /** The addressed prior mark's ordinal as observed. Not a lock: runs.mark re-plans under its transaction. */\n priorMarkOrdinal: z.number().int().positive().optional(),\n}).strict().refine(basis => basis.priorMarkOrdinal === undefined || basis.priorMarkOrdinal <= basis.ledgerOrdinal,\n { message: 'the prior mark lies inside the observed ledger', path: ['priorMarkOrdinal'] })\nexport type MarkPreviewBasis = z.infer<typeof MarkPreviewBasisSchema>\n\nexport const MarkPreviewLatestSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('first') }).strict(),\n z.object({ kind: z.literal('supersedes'), markId: markIdSchema, ordinal: z.number().int().positive() }).strict(),\n])\nexport type MarkPreviewLatest = z.infer<typeof MarkPreviewLatestSchema>\n\nconst previewMemberSchema = z.object({ testIndex: indexSchema, testId: z.string().min(1).optional() }).strict()\nconst resolvedStepSchema = z.object({ stepIndex: indexSchema, reason: z.enum(MARK_TARGET_REASONS) }).strict()\n\nexport const MarkPreviewGroundTruthSchema = z.object({\n testIndex: indexSchema,\n stepIndex: indexSchema,\n /** The verdict the mark asserts for this step. */\n verdict: z.enum(['pass', 'fail']),\n recordedVerdict: z.object({ pass: z.boolean(), reasoning: z.string() }).strict(),\n correctedExpectation: z.string().optional(),\n /** The corrected action is reported by presence; its content is the caller's own input. */\n correctedAction: z.boolean(),\n}).strict()\nexport type MarkPreviewGroundTruth = z.infer<typeof MarkPreviewGroundTruthSchema>\n\n/** A label a freeze would write. Gold cassette ids and ordinals are writer-minted and never appear. */\nexport const MarkPreviewLabelSchema = z.object({\n testIndex: indexSchema,\n stepIndex: indexSchema,\n decisionOrdinal: indexSchema,\n sourceCassetteId: z.string().min(1),\n channel: z.enum(MARK_GOLD_CHANNELS),\n correction: z.object({ verdict: z.enum(['pass', 'fail']) }).strict().optional(),\n}).strict()\nexport type MarkPreviewLabel = z.infer<typeof MarkPreviewLabelSchema>\n\nexport const MARK_PREVIEW_EVIDENCE_DIRECTIONS = ['confirm', 'overturn'] as const\nexport const MARK_PREVIEW_RECORD_EVIDENCE_KINDS = ['effects', 'unreadable'] as const\n\n/** One evidence event the writer's append would land; an overturn names the prior positive it reverses. */\nexport const MarkPreviewEvidenceEffectSchema = z.discriminatedUnion('direction', [\n z.object({ direction: z.literal('confirm') }).strict(),\n z.object({ direction: z.literal('overturn'), overturnsEvidenceToken: z.string(), overturnsCurationJobId: z.string().min(1) }).strict(),\n])\nexport type MarkPreviewEvidenceEffect = z.infer<typeof MarkPreviewEvidenceEffectSchema>\n\n/**\n * 2026-09-15, 423 D-17: one record the mark reaches, led by its joined content (or the typed reason\n * there is none) and followed by its complete planned effects. A record the store cannot read keeps\n * its id and is `unreadable`, exactly as the writer skips it.\n */\nexport const MarkPreviewKnowledgeRecordSchema = z.object({\n recordId: z.string().min(1),\n ...recordJoinShape,\n /** Served on a targeted step; otherwise reached only by false-pass correlation. */\n served: z.boolean(),\n evidence: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('effects'), effects: z.array(MarkPreviewEvidenceEffectSchema).min(1) }).strict(),\n z.object({ kind: z.literal('unreadable') }).strict(),\n ]),\n}).strict().superRefine((record, ctx) => {\n if ((record.recordContent === undefined) === (record.contentAbsence === undefined)) {\n ctx.addIssue({ code: 'custom', path: ['recordContent'], message: 'a reached record leads with its content or the typed absence of it' })\n }\n if (record.evidence.kind !== 'effects') return\n const confirms = record.evidence.effects.filter(effect => effect.direction === 'confirm').length\n if (confirms !== (record.served ? 1 : 0) || (record.served && record.evidence.effects[0]!.direction !== 'confirm')) {\n ctx.addIssue({ code: 'custom', path: ['evidence'], message: 'a served record is confirmed first and once; an unserved record is only overturned' })\n }\n})\nexport type MarkPreviewKnowledgeRecord = z.infer<typeof MarkPreviewKnowledgeRecordSchema>\nconst _evidenceDirectionsCover: ExactlyEqual<(typeof MARK_PREVIEW_EVIDENCE_DIRECTIONS)[number], MarkPreviewEvidenceEffect['direction']> = true\nvoid _evidenceDirectionsCover\nconst _recordEvidenceKindsCover: ExactlyEqual<(typeof MARK_PREVIEW_RECORD_EVIDENCE_KINDS)[number], MarkPreviewKnowledgeRecord['evidence']['kind']> = true\nvoid _recordEvidenceKindsCover\n\n/**\n * The knowledge the mark would reach: the writer's own evidence inputs, every reached record\n * (served targets first, then correlated unserved records) and the receipt evidence counts the\n * append would report. Effects are prospective; nothing is appended by a preview.\n */\nexport const MarkPreviewKnowledgeSchema = z.object({\n servedRecordIds: z.array(z.string().min(1)),\n appendsEvidence: z.boolean(),\n records: z.array(MarkPreviewKnowledgeRecordSchema),\n evidence: z.object({ confirmed: indexSchema, overturned: indexSchema }).strict(),\n}).strict().superRefine((knowledge, ctx) => {\n const ids = knowledge.records.map(record => record.recordId)\n if (new Set(ids).size !== ids.length) ctx.addIssue({ code: 'custom', path: ['records'], message: 'each reached record appears once' })\n const served = knowledge.records.filter(record => record.served).map(record => record.recordId)\n if (served.join('\\n') !== [...new Set(knowledge.servedRecordIds)].join('\\n')\n || knowledge.records.slice(0, served.length).some(record => !record.served)) {\n ctx.addIssue({ code: 'custom', path: ['records'], message: 'the served records lead, in served order, and no others are served' })\n }\n if (!knowledge.appendsEvidence && knowledge.records.length > 0) {\n ctx.addIssue({ code: 'custom', path: ['records'], message: 'a mark that appends no evidence reaches no record' })\n }\n const effects = knowledge.records.flatMap(record => record.evidence.kind === 'effects' ? record.evidence.effects : [])\n const confirmed = effects.filter(effect => effect.direction === 'confirm').length\n if (knowledge.evidence.confirmed !== confirmed || knowledge.evidence.overturned !== effects.length - confirmed) {\n ctx.addIssue({ code: 'custom', path: ['evidence'], message: 'the evidence counts are the planned effects' })\n }\n})\nexport type MarkPreviewKnowledge = z.infer<typeof MarkPreviewKnowledgeSchema>\n\n/** applyFeedback's plan kind and target: the fix runs.mark will apply. Its wording is a model call and is never previewed. */\nexport const MarkPreviewDraftSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('confirmed-bug') }).strict(),\n z.object({ kind: z.literal('knowledge'), fix: z.enum(['fact', 'caution', 'procedure-hint']), target: KnowledgeTargetRefSchema }).strict(),\n z.object({ kind: z.literal('test-edit'), testRef: z.string().min(1) }).strict(),\n z.object({ kind: z.literal('no-draftable-fix'), checked: NoDraftableFixCheckedSchema }).strict(),\n])\nexport type MarkPreviewDraft = z.infer<typeof MarkPreviewDraftSchema>\n\ntype LatestWithBasis = { latest: MarkPreviewLatest; basis: MarkPreviewBasis }\nfunction refineLatestBasis(value: LatestWithBasis, ctx: z.RefinementCtx) {\n const prior = value.latest.kind === 'supersedes' ? value.latest.ordinal : undefined\n if (prior !== value.basis.priorMarkOrdinal) {\n ctx.addIssue({ code: 'custom', path: ['basis', 'priorMarkOrdinal'], message: 'the basis names exactly the mark this one would supersede' })\n }\n}\n\nconst prospectiveShape = {\n runId: runIdSchema,\n /** Every effect below is what runs.mark would do now; nothing has been written. */\n prospective: z.literal(true),\n markKind: z.enum(MARKS),\n member: previewMemberSchema,\n resolvedStep: resolvedStepSchema,\n latest: MarkPreviewLatestSchema,\n basis: MarkPreviewBasisSchema,\n}\n\nexport const RunsMarkPreviewResultSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('consequences'),\n ...prospectiveShape,\n markedDecisionCount: indexSchema,\n groundTruth: z.array(MarkPreviewGroundTruthSchema),\n labels: z.array(MarkPreviewLabelSchema),\n knowledge: MarkPreviewKnowledgeSchema,\n draft: MarkPreviewDraftSchema,\n }).strict().superRefine((value, ctx) => {\n refineLatestBasis(value, ctx)\n if ((value.draft.kind === 'confirmed-bug') !== (value.markKind === 'confirmed-bug')) {\n ctx.addIssue({ code: 'custom', path: ['draft'], message: 'a confirmed bug drafts no fix and every other mark plans one' })\n }\n if (value.markKind !== 'false-pass' && value.labels.some(label => label.channel === 'overturned-verdict')) {\n ctx.addIssue({ code: 'custom', path: ['labels'], message: 'only a false-pass freezes an overturned verdict' })\n }\n if (value.markKind !== 'false-pass' && (value.knowledge.evidence.overturned > 0\n || value.knowledge.records.some(record => !record.served))) {\n ctx.addIssue({ code: 'custom', path: ['knowledge'], message: 'only a false-pass overturns or reaches an unserved record' })\n }\n const foreign = [...value.groundTruth, ...value.labels].some(item => item.testIndex !== value.member.testIndex)\n if (foreign) ctx.addIssue({ code: 'custom', path: ['member'], message: 'ground truth and labels belong to the resolved member' })\n }),\n z.object({\n kind: z.literal('quarantined'),\n ...prospectiveShape,\n class: z.enum(MARK_QUARANTINE_CLASSES),\n }).strict().superRefine(refineLatestBasis),\n z.object({\n kind: z.literal('already-marked'),\n runId: runIdSchema,\n /** The existing mark an identical repeat returns; a present fact, not a prospective one. */\n prior: RunDetailMemberMarkSchema.extend({ testIndex: indexSchema, testId: z.string().min(1).optional() }).strict(),\n basis: MarkPreviewBasisSchema,\n }).strict().superRefine((value, ctx) => {\n if (value.basis.priorMarkOrdinal !== value.prior.ordinal) {\n ctx.addIssue({ code: 'custom', path: ['basis', 'priorMarkOrdinal'], message: 'an identical repeat is computed against its prior mark' })\n }\n }),\n markRunNotFoundArm,\n markMemberNotFoundArm,\n markStepNotFoundArm,\n markAmbiguousAddressArm,\n markAmbiguousCorrectionArm,\n])\nexport type RunsMarkPreviewResult = z.infer<typeof RunsMarkPreviewResultSchema>\nconst _previewOutcomesCover: ExactlyEqual<(typeof MARK_PREVIEW_OUTCOMES)[number], RunsMarkPreviewResult['kind']> = true\nvoid _previewOutcomesCover\nconst _previewRefusalsAreMarkOutcomes: ExactlyEqual<\n Extract<RunsMarkPreviewResult, { kind: (typeof MARK_PREVIEW_REFUSALS)[number] }>,\n Extract<RunsMarkOutcome, { kind: (typeof MARK_PREVIEW_REFUSALS)[number] }>> = true\nvoid _previewRefusalsAreMarkOutcomes\n\n/** One ledger receipt with the records its applied knowledge fix changed, as the host read them. */\nexport interface MarkHistoryReadEntry {\n receipt: MarkReceipt\n changedRecords?: readonly MarkHistoryChangedRecord[]\n}\n\nexport type MarkHistoryRead =\n | { kind: 'history'; entries: readonly MarkHistoryReadEntry[] }\n | { kind: 'run-not-found' }\n | { kind: 'ledger-corrupt'; line: number }\n | { kind: 'ledger-unavailable' }\n\n/**\n * Read-only feedback observations. Separate from {@link FeedbackPort} so a host can grant history\n * without the mark writer; implementations never take the ledger lock, reap or write.\n */\nexport interface FeedbackReadsPort {\n history(runId: RunId): Promise<MarkHistoryRead>\n /**\n * 423 D-16: runs.mark's deterministic plan for this exact input, stopping before any intent,\n * lease, model call, id mint or write. Optional until a host implements it (423-19); a\n * feedbackReads binding without it leaves runs.mark.preview unbound by name.\n */\n preview?(input: RunsMarkInput): Promise<RunsMarkPreviewResult>\n}\n","import { z } from 'zod'\nimport { canonicalJson } from '../determinism/canonical-json'\nimport { sha256hex } from '../determinism/sha256'\nimport { PROMOTION_PATHS, strongerPromotionPath, type PromotionPath } from './promotion-path'\n\n// 2026-09-07, 417 D-19/D-20: additive optional fields; no persisted Gate-1 lines predate this widening.\n// 2026-09-07, 418: Gate-2 evidence widens additively; zero persisted Gate-2 lines predate this widening — reconciliation 2.\nexport const GATE_RECEIPT_SCHEMA_VERSION = 2\nexport type GateNumber = 1 | 2 | 3\nexport type GateVerdict = 'pass' | 'fail' | 'abstain'\n// prettier-ignore\nexport const GATE_NUMBERS = [1, 2, 3] as const satisfies readonly GateNumber[]\n// prettier-ignore\nexport const GATE_VERDICTS = ['pass', 'fail', 'abstain'] as const satisfies readonly GateVerdict[]\nexport type PerAxisScoreAxis = 'headline' | 'elementIdentity' | 'value' | 'opClass' | 'sideEffect' | 'loop'\n// 416 D-02: mirror the neutral axis names; schema never depends on eval.\n// prettier-ignore\nexport const PER_AXIS_SCORE_AXES = ['headline', 'elementIdentity', 'value', 'opClass', 'sideEffect', 'loop'] as const satisfies readonly PerAxisScoreAxis[]\nexport type CrossCheck = 'flipped' | 'held' | 'inconclusive' | 'not-run'\n// prettier-ignore\nexport const CROSS_CHECKS = ['flipped', 'held', 'inconclusive', 'not-run'] as const satisfies readonly CrossCheck[]\nexport type Degradation = 'replay-diff' | 'tier-not-implemented'\n// prettier-ignore\nexport const DEGRADATIONS = ['replay-diff', 'tier-not-implemented'] as const satisfies readonly Degradation[]\n// 2026-09-07, 417 D-02/D-06/D-09/D-13/D-19/D-20: declaration order is precedence.\n// The first applicable reason decides; same-family-refused is disclosure-only and never decides.\nexport type Gate1Reason = 'tier-not-implemented' | 'unprovenanced-candidate' | 'empty-gate-set' | 'target-unavailable' | 'baseline-uncached' | 'collateral-unscorable' | 'cap-exceeded' | 'no-positive-value' | 'collateral-harm' | 'target-not-reproduced' | 'inconclusive' | 'same-family-refused'\n// prettier-ignore\nexport const GATE1_REASONS = ['tier-not-implemented', 'unprovenanced-candidate', 'empty-gate-set', 'target-unavailable', 'baseline-uncached', 'collateral-unscorable', 'cap-exceeded', 'no-positive-value', 'collateral-harm', 'target-not-reproduced', 'inconclusive', 'same-family-refused'] as const satisfies readonly Gate1Reason[]\nexport type Gate1TargetSource = 'committed' | 'extracted'\n// prettier-ignore\nexport const GATE1_TARGET_SOURCES = ['committed', 'extracted'] as const satisfies readonly Gate1TargetSource[]\nexport type Gate1KSource = 'flag' | 'config' | 'default'\n// prettier-ignore\nexport const GATE1_K_SOURCES = ['flag', 'config', 'default'] as const satisfies readonly Gate1KSource[]\n// 417 D-01/D-03: post-exclusion collateral versus siblings at the target's step.\nexport type Gate1HarmOrigin = 'gate-set' | 'target-step'\n// prettier-ignore\nexport const GATE1_HARM_ORIGINS = ['gate-set', 'target-step'] as const satisfies readonly Gate1HarmOrigin[]\nexport type Benefit = 'exercised-benefited' | 'rode-along' | 'exercised-harmed'\n// prettier-ignore\nexport const BENEFITS = ['exercised-benefited', 'rode-along', 'exercised-harmed'] as const satisfies readonly Benefit[]\nexport type Mark = 'false-fail' | 'false-pass' | 'confirmed-bug'\n// prettier-ignore\nexport const MARKS = ['false-fail', 'false-pass', 'confirmed-bug'] as const satisfies readonly Mark[]\nexport type StateValidity = 'valid' | 'stale' | 'unknown'\n// prettier-ignore\nexport const STATE_VALIDITIES = ['valid', 'stale', 'unknown'] as const satisfies readonly StateValidity[]\nconst sha256 = z.string().regex(/^[0-9a-f]{64}$/)\nconst count = z.number().int().nonnegative()\nexport const gate1CapSchema = z.object({ maxScreens: z.number().int().min(1) }).strict()\nexport const gate1SpendSchema = z.object({\n screens: count, modelCalls: count, promptTokens: count, completionTokens: count, wallClockMs: count,\n}).strict()\nexport const gate2SpendSchema = z.object({\n modelCalls: count, screens: count, promptTokens: count, completionTokens: count,\n}).strict()\nexport const gate1TargetSchema = z.object({\n cassetteId: z.string().min(1), stepIndex: count, decisionOrdinal: count,\n runId: z.string().min(1), source: z.enum(GATE1_TARGET_SOURCES),\n baselineCorrect: z.boolean(), candidateCorrect: z.boolean(),\n baselineBriefSource: z.string(), candidateBriefSource: z.string(),\n}).strict()\n// Mirror LabelTier, LabelSourceChannel and CorpusEntry split/heldOutVisibility without importing eval.\n// Extracted target-step siblings have no CorpusEntry, so split and visibility are optional.\nexport const gate1HarmedSchema = z.object({\n cassetteId: z.string().min(1), stepIndex: count.optional(), decisionOrdinal: count,\n origin: z.enum(GATE1_HARM_ORIGINS), labelTier: z.string().optional(),\n sourceChannel: z.string().optional(), verdictPresent: z.boolean(), split: z.string().optional(),\n heldOutVisibility: z.string().optional(), axes: z.array(z.enum(PER_AXIS_SCORE_AXES)).min(1),\n softWeight: z.number().finite().min(0).max(1).optional(),\n}).strict()\nexport const axisScoreSchema = z.object({\n baseline: z.number(), candidate: z.number(), delta: z.number(), floor: z.number(),\n n: z.number().int().nonnegative(),\n}).strict()\nexport const perAxisScoreSchema = z.object({\n headline: axisScoreSchema, elementIdentity: axisScoreSchema, value: axisScoreSchema,\n opClass: axisScoreSchema, sideEffect: axisScoreSchema, loop: axisScoreSchema,\n}).strict()\nexport const corpusVersionSchema = z.object({\n corpusDigest: sha256,\n partitionVersion: z.number().int().nonnegative(),\n gateSetSize: z.number().int().nonnegative(),\n excludedCount: z.number().int().nonnegative(),\n minimumGateSet: z.number().int().min(1),\n}).strict()\nexport const samplesSchema = z.object({\n k: z.number().int().min(1), seeds: z.array(z.number().int()), seedHonored: z.boolean(),\n modelCalls: z.number().int().nonnegative(),\n detail: z.array(z.object({\n withRecord: z.boolean(), seed: z.number().int(), matchesGold: z.boolean(), kind: z.string(),\n }).strict()).optional(),\n}).strict()\nexport const noiseFloorRefSchema = z.object({\n profileKey: z.string().min(1), corpusDigest: sha256,\n}).strict()\nconst receiptCoreShape = {\n schemaVersion: z.literal(GATE_RECEIPT_SCHEMA_VERSION),\n candidateId: z.string().min(1),\n verdict: z.enum(GATE_VERDICTS),\n producedAtOrdinal: z.number().int().nonnegative(),\n producedBy: z.object({ jobId: z.string().optional(), opId: z.string().optional() }).strict(),\n receiptDigest: sha256,\n}\n// 416 D-01/D-02: each strict arm only accepts evidence that its gate measures.\nexport const gate1ArmSchema = z.object({\n ...receiptCoreShape, gate: z.literal(1), perAxisScore: perAxisScoreSchema,\n corpusVersion: corpusVersionSchema, samples: samplesSchema, crossCheck: z.enum(CROSS_CHECKS),\n judgeId: z.string().optional(), degradation: z.enum(DEGRADATIONS).optional(),\n noiseFloorRef: noiseFloorRefSchema.optional(),\n reasons: z.array(z.enum(GATE1_REASONS)).optional(),\n cap: gate1CapSchema.optional(),\n spend: gate1SpendSchema.optional(),\n kSource: z.enum(GATE1_K_SOURCES).optional(),\n targets: z.array(gate1TargetSchema).optional(),\n harmed: z.array(gate1HarmedSchema).optional(),\n unverifiedFlips: z.array(gate1HarmedSchema).optional(),\n population: z.object({\n proof: count, empty: count, rendered: count, refused: count, renderedExcluded: count,\n }).strict().optional(),\n floorAbsentAxes: z.array(z.enum(PER_AXIS_SCORE_AXES)).optional(),\n productFloor: z.object({\n product: z.string(), axes: z.array(z.object({\n axis: z.enum(PER_AXIS_SCORE_AXES), floor: z.number().nullable(), n: count,\n }).strict()),\n }).strict().optional(),\n generalization: z.object({\n ratio: z.number().optional(), ci: z.tuple([z.number(), z.number()]).optional(),\n liftDecisions: count, minimumLiftDecisions: count,\n }).strict().optional(),\n baselineSource: z.object({\n runRoot: z.string(), seed: z.number().int(), seedSource: z.string(),\n }).strict().optional(),\n judge: z.object({\n eligibility: z.string(), overrideConfigured: z.boolean(),\n panelSize: z.number().int().min(2).optional(),\n members: z.array(z.object({ judgeModelId: z.string().min(1), judgeFamily: z.string() }).strict()).optional(),\n }).strict().refine(judge => judge.panelSize === undefined\n ? judge.members === undefined : judge.members?.length === judge.panelSize,\n 'panel size and complete member metadata must appear together').optional(),\n}).strict()\nexport const gate2ArmSchema = z.object({\n ...receiptCoreShape, gate: z.literal(2), attributedObservationId: z.string().min(1),\n corpusVersion: z.object({ corpusDigest: sha256 }).strict(),\n benefit: z.enum(BENEFITS), stateValidity: z.enum(STATE_VALIDITIES),\n crossCheck: z.enum(CROSS_CHECKS).optional(),\n samples: samplesSchema.optional(),\n spend: gate2SpendSchema.optional(),\n runId: z.string().min(1).optional(),\n testIndex: count.optional(),\n stepIndex: count.optional(),\n observedStateDigest: sha256.optional(),\n attribution: z.string().optional(),\n}).strict()\nexport const gate3ArmSchema = z.object({\n ...receiptCoreShape, gate: z.literal(3), runId: z.string().min(1).optional(),\n stepId: z.string().optional(), mark: z.enum(MARKS).optional(),\n // 419 D-17: accepting a policy is not a run mark. Preserve its actual proposal identity.\n policyApproval: z.object({ proposalId: z.string().min(1), recordId: z.string().min(1) }).strict().optional(),\n}).strict().superRefine((value, ctx) => {\n if (value.policyApproval === undefined) {\n if (value.runId === undefined || value.mark === undefined) {\n ctx.addIssue({ code: 'custom', message: 'Gate 3 requires a complete run mark or policy approval' })\n }\n } else if (value.runId !== undefined || value.mark !== undefined || value.stepId !== undefined\n || value.policyApproval.recordId !== value.candidateId) {\n ctx.addIssue({ code: 'custom', message: 'policy approval must name this candidate and cannot carry a run mark' })\n }\n})\nexport const GateReceiptSchema = z.discriminatedUnion('gate', [\n gate1ArmSchema, gate2ArmSchema, gate3ArmSchema,\n])\nexport const PromotionReceiptSchema = z.object({\n schemaVersion: receiptCoreShape.schemaVersion,\n kind: z.literal('promotion'),\n candidateId: receiptCoreShape.candidateId,\n promotionPath: z.enum(PROMOTION_PATHS),\n citedReceiptDigests: z.array(sha256),\n producedAtOrdinal: receiptCoreShape.producedAtOrdinal,\n producedBy: receiptCoreShape.producedBy,\n receiptDigest: sha256,\n}).strict()\nexport const GateLineSchema = z.union([GateReceiptSchema, PromotionReceiptSchema])\nexport type GateReceipt = z.infer<typeof GateReceiptSchema>\nexport type Gate1Receipt = Extract<GateReceipt, { gate: 1 }>\nexport type Gate2Receipt = Extract<GateReceipt, { gate: 2 }>\nexport type Gate3Receipt = Extract<GateReceipt, { gate: 3 }>\nexport type PromotionReceipt = z.infer<typeof PromotionReceiptSchema>\nexport type GateLine = z.infer<typeof GateLineSchema>\ntype WithoutDigest<T> = T extends unknown ? Omit<T, 'receiptDigest'> : never\n\nexport function receiptDigestOf(line: GateLine): string {\n const { receiptDigest: _receiptDigest, ...rest } = line\n return sha256hex(canonicalJson(rest))\n}\nexport function stampReceiptDigest<T extends WithoutDigest<GateLine>>(line: T): T & { receiptDigest: string } {\n return { ...line, receiptDigest: sha256hex(canonicalJson(line)) }\n}\nexport function isPromotionReceipt(line: GateLine): line is PromotionReceipt {\n return 'kind' in line && line.kind === 'promotion'\n}\nexport function standingReceiptsByGate(receipts: readonly GateReceipt[]): GateReceipt[] {\n const standing = new Map<GateNumber, GateReceipt>()\n for (const receipt of receipts) {\n const previous = standing.get(receipt.gate)\n if (previous === undefined || receipt.producedAtOrdinal >= previous.producedAtOrdinal) {\n standing.set(receipt.gate, receipt)\n }\n }\n return GATE_NUMBERS.flatMap(gate => {\n const receipt = standing.get(gate)\n return receipt === undefined ? [] : [receipt]\n })\n}\nexport function strongestPromotionPath(lines: readonly GateLine[]): PromotionPath | undefined {\n let strongest: PromotionPath | undefined\n for (const line of lines) {\n if (isPromotionReceipt(line)) {\n strongest = strongest === undefined ? line.promotionPath\n : strongerPromotionPath(strongest, line.promotionPath)\n }\n }\n return strongest\n}\n","export type PromotionPath = 'deterministic-verdict-floor' | 'gate1-lower-trust' | 'gate1+gate2' | 'user-sovereign'\n// prettier-ignore\nexport const PROMOTION_PATHS = ['deterministic-verdict-floor', 'gate1-lower-trust', 'gate1+gate2', 'user-sovereign'] as const satisfies readonly PromotionPath[]\nexport const PROMOTION_PATH_STRENGTH: Record<PromotionPath, number> = {\n 'deterministic-verdict-floor': 0,\n 'gate1-lower-trust': 1,\n 'gate1+gate2': 2,\n 'user-sovereign': 3,\n}\nexport function strongerPromotionPath(a: PromotionPath, b: PromotionPath): PromotionPath {\n return PROMOTION_PATH_STRENGTH[a] >= PROMOTION_PATH_STRENGTH[b] ? a : b\n}\n\n","// The direct knowledge change contracts (432-17, D-02 / D-05 / D-09; introduced by 432-12).\n//\n// A knowledge change applies in the call. `knowledge.accept`, `knowledge.reject` and\n// `knowledge.forget` take the verb input plus an optional operation identity and answer what they\n// changed: the records, a typed absence, or a typed refusal. A mark changes knowledge through\n// `runs.mark` with the same review vocabulary. Nothing is filed for a second call to apply.\n//\n// MOVED HERE 2026-10-01 (432-17). These contracts lived beside the proposal they replaced\n// (`knowledge/proposal.ts`, `knowledge/review-verbs.ts`) while the proposal inbox still had readers.\n// The inbox, its envelope and the knowledge proposal payload are deleted, and old proposal files are\n// never parsed again (D-22), so this is the one module the direct change vocabulary lives in. The\n// commit receipt moved with it from `functions/feedback.ts` (which re-exports it), because the change\n// output carries it and the feedback contracts import this module's primitives: one direction only.\n//\n// THE CHANGE ID KEEPS ITS RECEIPT SHAPE. A change is identified by `prop_<operationId>`, and the\n// forget and commit receipts carry it in their `proposalId` field. The schema that refines the id is\n// named for what it identifies now.\n\nimport { z } from 'zod'\n\nimport { DELTA_KINDS } from '../delta/delta'\nimport { DELTA_ORIGINS } from '../delta/envelope'\nimport type { Delta } from '../delta/delta'\nimport { ENTITY_STATUSES } from '../entity/entity-card'\nimport { parseShortId } from '../entity/kinds'\nimport { BundleProvenanceSchema } from './bundle-files'\nimport { MARKS } from './gate-receipt'\nimport { PROMOTION_PATHS } from './promotion-path'\n\n/** 2026-09-08, 419 D-01: mark is the fourth — a user mark's fix, applied through the same writer. */\nexport const KNOWLEDGE_REVIEW_VERBS = ['accept', 'reject', 'forget', 'mark'] as const\n\nexport type KnowledgeReviewVerb = (typeof KNOWLEDGE_REVIEW_VERBS)[number]\n\n/**\n * The §7.7 projections a forget must scrub. Closed, and the closure is the point: \"scrub\n * every projection\" is only a checkable promise if the set of projections is enumerable.\n */\nexport const KNOWLEDGE_PROJECTIONS = ['fts', 'vec', 'graph', 'exemplar'] as const\n\nexport type KnowledgeProjection = (typeof KNOWLEDGE_PROJECTIONS)[number]\n\n/**\n * The id a knowledge change is recorded under, refined rather than a bare string.\n *\n * It is echoed into receipts and derived from a caller-supplied operation identity, so it is\n * attacker-reachable input. The pattern admits a hex mint and an `id-agent` word-id while refusing\n * whitespace, path separators and the empty body — the shapes that turn an identity into a path.\n */\nexport const KnowledgeChangeIdSchema = z\n .string()\n .min(10)\n .regex(/^prop_[a-z0-9]+(?:-[a-z0-9]+)*$/u, 'expected a prop_-prefixed lowercase change id')\n\n/**\n * 2026-09-30, 432-12 (D-05): the three knowledge changes a caller makes directly. A mark changes\n * knowledge through `runs.mark`, so it is a review verb and not one of these.\n */\nexport const KNOWLEDGE_CHANGE_VERBS = ['accept', 'reject', 'forget'] as const\n\nexport type KnowledgeChangeVerb = (typeof KNOWLEDGE_CHANGE_VERBS)[number]\n\n/**\n * A caller's stable identity for one knowledge change (432-12). Repeating it repeats the change,\n * which lands once. Letters, digits and single hyphens, so a UUID fits and the change id derived\n * from it keeps the receipt id shape.\n */\nexport const KnowledgeChangeOperationIdSchema = z\n .string()\n .min(5)\n .max(64)\n .regex(\n /^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/u,\n 'expected letters, digits and single hyphens, such as a UUID',\n )\n\n/**\n * WHAT a change is about, at either of the two grains D-19 pins: one record, or the `MEM-`\n * addressed bundle that contains records.\n *\n * The bundle arm refuses a well-formed short-ID of any other kind. `TST-001` parses and resolves to\n * a real entity — it is simply not a thing a knowledge change applies to, and a ref that reached\n * the store before anyone noticed would address by coincidence.\n */\nexport const KnowledgeTargetRefSchema = z.discriminatedUnion('grain', [\n z.object({\n grain: z.literal('record'),\n recordId: z.string().min(1),\n }).strict(),\n z.object({\n grain: z.literal('bundle'),\n shortId: z.string().refine(\n (value) => parseShortId(value)?.kind === 'MEM',\n 'expected a MEM- short-ID addressing a knowledge bundle',\n ),\n }).strict(),\n])\n\nexport type KnowledgeTargetRef = z.infer<typeof KnowledgeTargetRefSchema>\n\n/** {@link KnowledgeTargetRefSchema} under the name D-19 gives it. Deliberately the same value. */\nexport const ForgetTargetRefSchema = KnowledgeTargetRefSchema\n\nexport type ForgetTargetRef = KnowledgeTargetRef\n\n/**\n * Validates a change's deltas at ENVELOPE depth — the discriminant plus the three fields every arm\n * of the union carries — and no deeper.\n *\n * `Delta` is a type-only union, so a full arm-by-arm schema here would be a SECOND declaration of\n * the write vocabulary, free to drift from the one `commit()` actually applies. Arm interiors are\n * validated where they are applied; what this boundary owes is that an unrecognised kind or a delta\n * with no attributable origin never reaches that point looking well-formed.\n *\n * STRUCTURAL, not `z.custom` (387-08): a predicate is unprojectable, and the function layer projects\n * every declared contract into an inert JSON Schema document for its listing.\n */\nexport const DeltaSchema = z.looseObject({\n kind: z.enum(DELTA_KINDS),\n origin: z.enum(DELTA_ORIGINS),\n scope: z.looseObject({ tier: z.string(), key: z.string() }),\n citedIds: z.array(z.string()),\n}) as unknown as z.ZodType<Delta>\n\n/** One record a forget tombstones, with the provenance that survives it (D-19). */\nexport const TombstonedRecordSchema = z.object({\n recordId: z.string().min(1),\n provenance: BundleProvenanceSchema,\n}).strict()\n\nexport type TombstonedRecord = z.infer<typeof TombstonedRecordSchema>\n\nconst scrubSetSchema = z\n .array(z.enum(KNOWLEDGE_PROJECTIONS))\n .refine(\n (members) => new Set(members).size === members.length,\n 'projectionsScrubbed is a SUBSET of the scrub set, not a log of attempts',\n )\n\nexport const FORGET_RECEIPT_SCHEMA_VERSION = 2\n\n/**\n * What a forget DID: the value the change returns, and the content the forgotten entity's address\n * resolves to afterwards (D-19 + D-04). Every tombstoned record is enumerated with its provenance,\n * because a receipt that listed only what it happened to find is a receipt nobody can act on.\n *\n * `proposalId` carries the change id; the field name is the persisted receipt's (see the header).\n */\nexport const ForgetReceiptV1Schema = z.object({\n schemaVersion: z.literal(FORGET_RECEIPT_SCHEMA_VERSION),\n proposalId: KnowledgeChangeIdSchema,\n tombstonedRecords: z.array(TombstonedRecordSchema),\n projectionsScrubbed: scrubSetSchema,\n resultingBundleStatus: z.enum(ENTITY_STATUSES.MEM),\n forgottenAt: z.number().int().nonnegative(),\n}).strict()\n\nexport type ForgetReceiptV1 = z.infer<typeof ForgetReceiptV1Schema>\n\n/** The stamp binding a mark's knowledge fix to the mark that made it (419 D-01). */\nexport const MarkChangeStampSchema = z.object({\n markId: z.string().regex(/^mark_[0-9a-f]{12}$/),\n runId: z.string().min(1),\n testIndex: z.number().int().nonnegative(),\n stepIndex: z.number().int().nonnegative().optional(),\n kind: z.enum(MARKS),\n fix: z.enum(['fact', 'caution', 'procedure-hint']),\n}).strict()\n\nexport type MarkChangeStamp = z.infer<typeof MarkChangeStampSchema>\n\nexport const COMMIT_RECEIPT_SCHEMA_VERSION = 2\n\nconst ordinalSchema = z.number().int().nonnegative()\n\n/**\n * What a change that crossed a promotion gate, or wrote a policy record, committed (419 D-04/D-17).\n * `proposalId` carries the change id; the field name is the persisted receipt's (see the header).\n */\nexport const CommitReceiptSchema = z.object({\n schemaVersion: z.literal(COMMIT_RECEIPT_SCHEMA_VERSION),\n proposalId: KnowledgeChangeIdSchema,\n markId: z.string().optional(),\n committedAtOrdinal: ordinalSchema,\n recordIds: z.array(z.string().min(1)),\n gate3: z.array(z.object({ candidateId: z.string().min(1), receiptDigest: z.string().min(1) }).strict()),\n promoted: z.array(z.object({ candidateId: z.string().min(1), promotionPath: z.enum(PROMOTION_PATHS) }).strict()),\n held: z.array(z.object({ candidateId: z.string().min(1), reason: z.string().min(1) }).strict()),\n policy: z.object({\n recordId: z.string().min(1), scope: z.string().min(1), relPath: z.string().min(1),\n outcome: z.enum(['written', 'unchanged']),\n }).strict().optional(),\n}).strict()\n\nexport type CommitReceipt = z.infer<typeof CommitReceiptSchema>\n\n/** Accept a candidate: promote what the store already holds. */\nexport const KnowledgeAcceptInputSchema = z.object({\n target: KnowledgeTargetRefSchema,\n}).strict()\n\nexport type KnowledgeAcceptInput = z.infer<typeof KnowledgeAcceptInputSchema>\n\n/**\n * Reject a candidate. The reason is REQUIRED because the delta this becomes (`Deprecate`) requires\n * one — an input DTO that let it through empty would have handed the verb the job of inventing a\n * justification for a human decision.\n */\nexport const KnowledgeRejectInputSchema = z.object({\n target: KnowledgeTargetRefSchema,\n reason: z.string().min(1),\n}).strict()\n\nexport type KnowledgeRejectInput = z.infer<typeof KnowledgeRejectInputSchema>\n\n/** Forget a record or a whole bundle (D-19). */\nexport const KnowledgeForgetInputSchema = z.object({\n target: ForgetTargetRefSchema,\n}).strict()\n\nexport type KnowledgeForgetInput = z.infer<typeof KnowledgeForgetInputSchema>\n\n/**\n * 432-12 (D-05/D-09): what a CHANGE op takes on top of the verb it applies — an optional operation\n * identity. A caller that repeats the identity repeats the change, which lands once and answers the\n * same records; a caller that omits it gets a fresh identity back on the receipt.\n */\nconst CHANGE_IDENTITY = { operationId: KnowledgeChangeOperationIdSchema.optional() }\n\n/** {@link KnowledgeAcceptInputSchema} as `knowledge.accept` takes it. */\nexport const KnowledgeAcceptChangeInputSchema = z.object({\n ...KnowledgeAcceptInputSchema.shape,\n ...CHANGE_IDENTITY,\n}).strict()\n\nexport type KnowledgeAcceptChangeInput = z.infer<typeof KnowledgeAcceptChangeInputSchema>\n\n/** {@link KnowledgeRejectInputSchema} as `knowledge.reject` takes it. */\nexport const KnowledgeRejectChangeInputSchema = z.object({\n ...KnowledgeRejectInputSchema.shape,\n ...CHANGE_IDENTITY,\n}).strict()\n\nexport type KnowledgeRejectChangeInput = z.infer<typeof KnowledgeRejectChangeInputSchema>\n\n/** {@link KnowledgeForgetInputSchema} as `knowledge.forget` takes it. */\nexport const KnowledgeForgetChangeInputSchema = z.object({\n ...KnowledgeForgetInputSchema.shape,\n ...CHANGE_IDENTITY,\n}).strict()\n\nexport type KnowledgeForgetChangeInput = z.infer<typeof KnowledgeForgetChangeInputSchema>\n\n/** Why a direct change wrote nothing, when the store refused it by type rather than by absence. */\nexport const KNOWLEDGE_CHANGE_REFUSAL_REASONS = ['policy-materialize-refused'] as const\n\nexport type KnowledgeChangeRefusalReason = (typeof KNOWLEDGE_CHANGE_REFUSAL_REASONS)[number]\n\n/**\n * What a direct knowledge change DID (432-12, D-05): the records it changed, a typed absence, or a\n * typed refusal. Never a proposal: nothing waits for a second call.\n *\n * `recordIds` are read back after the write. A forget carries the tombstone receipt, and a change\n * that crossed a promotion gate carries its commit receipt. `operationId` is the identity the change\n * landed under, so a caller can retry it and land nothing twice.\n */\nexport const KnowledgeChangeOutputSchema = z.discriminatedUnion('outcome', [\n z.object({\n outcome: z.literal('applied'),\n verb: z.enum(KNOWLEDGE_CHANGE_VERBS),\n operationId: KnowledgeChangeOperationIdSchema,\n recordIds: z.array(z.string().min(1)),\n /** Present exactly when the change was a forget (D-19). */\n forgetReceipt: ForgetReceiptV1Schema.optional(),\n /** Present when the change passed a promotion gate or wrote a policy record. */\n commitReceipt: CommitReceiptSchema.optional(),\n }).strict(),\n z.object({\n outcome: z.literal('target-not-found'),\n verb: z.enum(KNOWLEDGE_CHANGE_VERBS),\n operationId: KnowledgeChangeOperationIdSchema,\n /** Echoed so an answer pasted into an issue still says what was asked about. */\n target: KnowledgeTargetRefSchema,\n }).strict(),\n z.object({\n outcome: z.literal('refused'),\n verb: z.enum(KNOWLEDGE_CHANGE_VERBS),\n operationId: KnowledgeChangeOperationIdSchema,\n reason: z.enum(KNOWLEDGE_CHANGE_REFUSAL_REASONS),\n }).strict(),\n]).superRefine((output, ctx) => {\n // 2026-10-03 (quick 261003-cpv, 432 review IN-21): \"present exactly when the change was a forget\",\n // enforced. Producer-parsed only (the op, the daemon answer the host re-parses, MCP).\n if (output.outcome !== 'applied') return\n if ((output.verb === 'forget') !== (output.forgetReceipt !== undefined)) {\n ctx.addIssue({\n code: 'custom',\n path: ['forgetReceipt'],\n message: 'an applied forget carries its forget receipt, and no other change carries one',\n })\n }\n})\n\nexport type KnowledgeChangeOutput = z.infer<typeof KnowledgeChangeOutputSchema>\n","import type { EvidenceToken, RecordId } from '../ids/record-id'\nimport type { BundleDraft, DeltaEnvelope } from './envelope'\n\ntype Add = DeltaEnvelope & {\n kind: 'Add'\n bundle: BundleDraft\n}\n\ntype Confirm = DeltaEnvelope & {\n kind: 'Confirm'\n targetId: RecordId\n evidenceToken: EvidenceToken\n}\n\ntype Supersede = DeltaEnvelope & {\n kind: 'Supersede'\n victimId: RecordId\n newBundle: BundleDraft\n evidenceToken: EvidenceToken\n}\n\ntype Deprecate = DeltaEnvelope & {\n kind: 'Deprecate'\n targetId: RecordId\n reason: string\n}\n\ntype MintUnknown = DeltaEnvelope & {\n kind: 'MintUnknown'\n conflict: {\n recordIds: RecordId[]\n kind: 'contradiction' | 'drift' | 'clarification'\n }\n}\n\ntype Noop = DeltaEnvelope & {\n kind: 'Noop'\n}\n\nexport type Delta = Add | Confirm | Supersede | Deprecate | MintUnknown | Noop\n\n/**\n * The §7.3 delta kinds as a RUNTIME value (387 D-17).\n *\n * `Delta` is a type-only union with no runtime declaration anywhere in the tree, because\n * until now nothing validated a delta at a boundary — deltas were constructed in-process and\n * handed straight to `commit()`. The 387 proposal DTO changes that: a proposal is a document\n * that crosses a process boundary between propose and apply, so its deltas arrive as\n * untrusted values and something has to be able to say which discriminants exist.\n *\n * This is a PROJECTION of the union above, not a second declaration of it: the `satisfies`\n * clause makes an entry that names no arm a compile error, and the reverse direction (an arm\n * that no entry names) is pinned in `__tests__/review-dtos.test-d.ts`. Adding a delta arm\n * without teaching this table about it therefore cannot be done silently.\n */\nexport const DELTA_KINDS = [\n 'Add',\n 'Confirm',\n 'Supersede',\n 'Deprecate',\n 'MintUnknown',\n 'Noop',\n] as const satisfies readonly Delta['kind'][]\n\nexport type DeltaKind = (typeof DELTA_KINDS)[number]\n","import type { ArtifactRef } from '../ids/artifact-ref'\nimport type { RecordId } from '../ids/record-id'\nimport type { Anchor } from '../identity/anchor'\nimport type { ScopeKey } from '../identity/scope-key'\nimport type { ExecutionContext } from '../run/run-status'\n\nexport type BundleKind = 'fact' | 'procedure' | 'caution' | 'unknown' | 'policy'\nexport type FactSubtype =\n | 'selector'\n | 'behavioral'\n | 'navigational'\n | 'measurement'\n | 'content'\n\n/** Phase 378 closes the producer vocabulary around the one-shot Curator drainer. */\nexport type OriginStage = 'run-curation'\n\nexport type CurationAuthorshipPath = 'llm' | 'llm-repaired' | 'deterministic-fallback'\n\n/**\n * 381-47: WHY the author fell back, threaded from AuthorOutcome's fallback arm so a\n * delta-noop drain report can name its cause (F-381-45-1 diagnosability).\n */\nexport type CurationFallbackReason = 'malformed' | 'no-model' | 'token-budget' | 'model-error'\n\n/**\n * D-04 raw Curator authorship facts with the SAFE-01 write-posture context that produced them.\n */\nexport interface CurationAuthorship {\n path: CurationAuthorshipPath\n model?: {\n id: string\n family?: string\n fingerprint?: string\n }\n executionContext: ExecutionContext\n /**\n * Stamped only on the deterministic-fallback path and consumed only for drain-noop\n * cause derivation — never a trust or tier input (D-06 folds `path` alone).\n */\n fallbackReason?: CurationFallbackReason\n}\n\nexport interface CompareAndSet {\n recordId: RecordId\n observedStatus: string\n observedOrdinal: number\n}\n\n/**\n * The delta-origin vocabulary as a RUNTIME value (387 D-17), projected from the envelope\n * declaration below by the same discipline `DELTA_KINDS` carries: `satisfies` makes an entry\n * naming no origin a compile error, and the reverse direction is pinned in the type-level\n * proof beside the review-DTO suite.\n *\n * It exists because the proposal boundary validates deltas at ENVELOPE depth — the fields\n * every arm carries — and `origin` is the one that decides whether a committed change is\n * attributable to a person or to the agent.\n */\nexport const DELTA_ORIGINS = ['agent', 'user', 'import', 'system'] as const\n\nexport type DeltaOrigin = (typeof DELTA_ORIGINS)[number]\n\nexport interface DeltaEnvelope {\n origin: DeltaOrigin\n scope: ScopeKey\n citedIds: RecordId[]\n precondition?: CompareAndSet[]\n authorship?: CurationAuthorship\n}\n\nexport interface BundleDraft {\n kind: BundleKind\n subtype?: FactSubtype\n anchors: Anchor[]\n scope: ScopeKey\n summary: string\n body: string\n distilledEvidenceRef: ArtifactRef\n originStage: OriginStage\n}\n","// The ONE entity card shape (Phase 387, ENTY-02 / D-10 / D-11 / D-12).\n//\n// `{ kind, id, uri, title, status, url?, keyFacts[], actions[] }`, verbatim per ENTY-02 — the\n// chat card, the MCP `structuredContent` and the M5 UI are all projections of this and never\n// of a per-surface variant. There is exactly one producer, and it lives in the function\n// layer; this file is the contract it renders INTO.\n//\n// `status` is a kind-DISCRIMINATED closed union (D-12). One flat status enum would have been\n// smaller and would have accepted `{ kind: 'MEM', status: 'passed' }` — a memory record that\n// claims a run verdict — which is precisely the class of nonsense a card must not be able to\n// carry into a verdict sentence. The per-kind vocabularies live in one exported table so a\n// test can walk the complete five-kind set rather than the three arms someone remembered.\n//\n// `url` is ABSENT by default (D-10). v52 configures no dashboard base URL, and a card that\n// carried a link to a route nothing serves would be a dead link shown with confidence. M5\n// turns it on by setting config — no schema change, no producer change.\n//\n// `actions[]` are registry op refs (D-11). A card can only advertise capabilities the\n// function registry already contains, so an advertised action is invokable identically over\n// chat, CLI and MCP, safe-mode listing filters apply to it automatically, and 397's parity\n// suite can assert every action a card offers actually resolves. A freeform action string\n// would have been a second capability vocabulary, which is the private-power drift L10\n// exists to prevent.\n\nimport { z } from 'zod'\n\nimport { parseShortId } from './kinds'\nimport type { EntityKind } from './kinds'\nimport { EntityUriSchema, parseEntityUri } from './uri'\n\n/**\n * The complete per-kind status vocabulary. The ONE table; every arm below reads its enum off\n * it, so there is no second place a status could be declared.\n */\nexport const ENTITY_STATUSES = {\n TST: ['active', 'quarantined'],\n RUN: ['passed', 'failed', 'running', 'unknown'],\n MEM: ['active', 'tombstoned', 'forgotten'],\n POL: ['active'],\n TGT: ['active', 'renamed', 'not-in-config'],\n} as const satisfies Record<EntityKind, readonly [string, ...string[]]>\n\nexport type EntityStatusFor<K extends EntityKind> = (typeof ENTITY_STATUSES)[K][number]\nexport type EntityStatus = EntityStatusFor<EntityKind>\n\n/**\n * Bounded, and the bound is the point rather than a performance guard: key facts are what a\n * reader actually reads, and a card that listed forty of them would be a data dump nobody\n * scans. Retune from what real cards need, not from a byte budget.\n */\nexport const ENTITY_CARD_MAX_KEY_FACTS = 12\n\n/** Same reasoning for the action row: a card offers a few next moves, not a menu. */\nexport const ENTITY_CARD_MAX_ACTIONS = 6\n\n/**\n * What each kind CALLS the machine id its address maps FROM — the label its FIRST key fact rides\n * under, on every card the one producer emits.\n *\n * IT LIVES IN THE CONTRACT RATHER THAN IN THE PRODUCER (moved here 400-08) because it is the only\n * thing that makes the machine id READABLE OFF A CARD. A card carries `{kind, id, uri, …}` and\n * deliberately no `machineId` field — the short-ID is the published address — but the identity fact\n * carries it, and a surface that has to route to a page keyed by machine id (the dashboard's\n * `/test/:t_id` and `/runs/:id`) needs to name that fact without guessing. With the table in the\n * producer's package a renderer had two ways to get there and both were wrong: read the label as a\n * literal (a second copy, free to drift the day a noun is retuned) or fish the id out of an\n * `actions[]` seed (addressing by coincidence, which `actions.ts`'s own header names as the thing\n * its seeds must never be). One declaration, imported by the producer that WRITES the fact and by\n * every surface that READS it, is what makes \"the identity fact carries the machine id\" a contract\n * instead of a convention.\n *\n * The label is per-kind and not cosmetic: `bundle id` and `run id` send a reader to different\n * places to correlate, and a card that said `machine id` for both would make the reader guess which\n * store to look in. A table rather than five literals so a kind cannot be added without answering\n * the question.\n */\nexport const ENTITY_IDENTITY_FACT_LABELS = {\n TST: 'test id',\n RUN: 'run id',\n MEM: 'bundle id',\n POL: 'policy id',\n TGT: 'target name',\n} as const satisfies Record<EntityKind, string>\n\n/**\n * One deterministic fact about the entity, computed by the producer from store data — never\n * LLM-authored (D-12). `ref` is an `agentqa://` URI so a fact can LINK another entity, which\n * is what lets a failing run's card point at the test it ran without inventing a second\n * cross-reference format.\n */\nexport const KeyFactSchema = z.object({\n label: z.string().min(1),\n value: z.string(),\n ref: EntityUriSchema.optional(),\n}).strict()\n\nexport type KeyFact = z.infer<typeof KeyFactSchema>\n\n/** A registry op reference (D-11): what to invoke, what to call it, and a seed input. */\nexport const ActionRefSchema = z.object({\n functionId: z.string().min(1),\n label: z.string().min(1),\n inputSeed: z.record(z.string(), z.unknown()),\n}).strict()\n\nexport type ActionRef = z.infer<typeof ActionRefSchema>\n\nconst cardBase = {\n id: z.string().min(1),\n uri: EntityUriSchema,\n title: z.string(),\n url: z.url().optional(),\n keyFacts: z.array(KeyFactSchema).max(ENTITY_CARD_MAX_KEY_FACTS),\n actions: z.array(ActionRefSchema).max(ENTITY_CARD_MAX_ACTIONS),\n}\n\n// Written out arm by arm rather than generated by a mapped helper. A helper would have kept\n// the five lines below in sync automatically and lost the inferred per-kind status type in\n// the process, and the inferred type is what makes `card.status` narrow to the right\n// vocabulary at every consumer. The completeness the helper would have guaranteed is instead\n// asserted directly against `ENTITY_KINDS` and `ENTITY_STATUSES` in this module's suite.\nconst entityCardUnion = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('TST'), status: z.enum(ENTITY_STATUSES.TST), ...cardBase }).strict(),\n z.object({ kind: z.literal('RUN'), status: z.enum(ENTITY_STATUSES.RUN), ...cardBase }).strict(),\n z.object({ kind: z.literal('MEM'), status: z.enum(ENTITY_STATUSES.MEM), ...cardBase }).strict(),\n z.object({ kind: z.literal('POL'), status: z.enum(ENTITY_STATUSES.POL), ...cardBase }).strict(),\n z.object({ kind: z.literal('TGT'), status: z.enum(ENTITY_STATUSES.TGT), ...cardBase }).strict(),\n])\n\n/**\n * The card contract, with the cross-field integrity the arms cannot express on their own.\n *\n * `kind`, `id` and `uri` are three spellings of ONE address, and a card whose three spellings\n * disagreed would resolve differently depending on which field a surface happened to read.\n * The refinement below is what makes them one address rather than three fields that usually\n * match.\n */\nexport const EntityCardSchema = entityCardUnion.superRefine((card, ctx) => {\n const parsedId = parseShortId(card.id)\n if (parsedId === undefined || parsedId.kind !== card.kind) {\n ctx.addIssue({\n code: 'custom',\n path: ['id'],\n message: `card id ${card.id} does not name a ${card.kind} entity`,\n })\n }\n const parsedUri = parseEntityUri(card.uri)\n if (parsedUri === undefined || parsedUri.kind !== card.kind || parsedUri.shortId !== card.id) {\n ctx.addIssue({\n code: 'custom',\n path: ['uri'],\n message: `card uri ${card.uri} does not address ${card.kind} ${card.id}`,\n })\n }\n})\n\nexport type EntityCard = z.infer<typeof entityCardUnion>\n","// The entity kind vocabulary and the `KIND-NNN` short-ID codec (Phase 387, ENTY-01 / D-03).\n//\n// Five kinds, closed, and the closure is load-bearing rather than tidy: a short-ID is a\n// PUBLISHED address that ends up in verdict sentences, receipts and CI logs, so the set of\n// things one can name has to be something a reader can enumerate — not whatever a regex\n// happened to accept that day. Every derived table below is built OVER the one array, and\n// the `satisfies Record<EntityKind, …>` on each of them is what makes \"you added a kind and\n// forgot to give it a URI segment\" a type error instead of a hole nobody notices until a\n// card renders a broken link.\n//\n// Two address FORMS, not one. Four kinds are ordinal-addressed (`MEM-001`) because their\n// machine ids are opaque digests and word-ids no human would type. `TGT` is slug-addressed\n// (`TGT-checkout`) because a target's machine id ALREADY is the human name the config gave\n// it (D-03) — minting an ordinal for it would invent a second name for something that\n// already had a good one, and every later surface would have to decide which one to print.\n\n/** The complete kind vocabulary (ENTY-01, spec §4.4). Order is the canonical listing order. */\nexport const ENTITY_KINDS = ['TST', 'RUN', 'MEM', 'POL', 'TGT'] as const\n\nexport type EntityKind = (typeof ENTITY_KINDS)[number]\n\n/**\n * The kind ↔ URI-segment table (`agentqa://memory/MEM-001`).\n *\n * A separate vocabulary on purpose: the prefix is what a human types in a sentence and the\n * segment is what a URI path reads like, and collapsing them would have produced\n * `agentqa://mem/MEM-001`. Both directions are derived below so the mapping cannot drift\n * apart into two half-maintained tables.\n */\nexport const ENTITY_URI_SEGMENTS = {\n TST: 'test',\n RUN: 'run',\n MEM: 'memory',\n POL: 'policy',\n TGT: 'target',\n} as const satisfies Record<EntityKind, string>\n\nexport type EntityUriSegment = (typeof ENTITY_URI_SEGMENTS)[EntityKind]\n\nconst SEGMENT_TO_KIND = new Map<string, EntityKind>(\n ENTITY_KINDS.map((kind) => [ENTITY_URI_SEGMENTS[kind], kind]),\n)\n\n/**\n * The kinds whose address body is a config-given slug rather than a minted ordinal (D-03).\n *\n * A table rather than a `kind === 'TGT'` test at each site, because the question \"is this\n * one of the irregular kinds\" is asked by the codec, the ledger and the resolver, and three\n * copies of a literal is three places a second slug-addressed kind would have to be\n * remembered.\n */\nexport const SLUG_ADDRESSED_ENTITY_KINDS = {\n TST: false,\n RUN: false,\n MEM: false,\n POL: false,\n TGT: true,\n} as const satisfies Record<EntityKind, boolean>\n\nexport function isSlugAddressedKind(kind: EntityKind): boolean {\n return SLUG_ADDRESSED_ENTITY_KINDS[kind]\n}\n\n/**\n * Ordinals RENDER zero-padded to three digits and PARSE at any width.\n *\n * Asymmetric on purpose. Padding is cosmetic — it makes a column of short-IDs line up and\n * makes `MEM-001` look like an identifier rather than a count — so the printed form is\n * pinned, while a human who typed `MEM-1` from memory gets the entity they meant instead of\n * a refusal that teaches them nothing. An ordinal past 999 simply renders at its natural\n * width; there is no wrap, no reflow, and no renumbering, because renumbering is exactly\n * what D-04 forbids.\n */\nexport const ENTITY_ORDINAL_MIN_DIGITS = 3\n\n/** The first ordinal a kind ever mints. Zero is not an address. */\nexport const ENTITY_FIRST_ORDINAL = 1\n\nexport function formatEntityOrdinal(ordinal: number): string {\n return String(ordinal).padStart(ENTITY_ORDINAL_MIN_DIGITS, '0')\n}\n\n/** `MEM-001`. Refuses a slug-addressed kind rather than inventing an ordinal for it. */\nexport function formatOrdinalShortId(kind: EntityKind, ordinal: number): string {\n if (isSlugAddressedKind(kind)) {\n throw new TypeError(`${kind} is slug-addressed (D-03); it has no ordinal short-ID`)\n }\n if (!Number.isSafeInteger(ordinal) || ordinal < ENTITY_FIRST_ORDINAL) {\n throw new TypeError(`entity ordinals start at ${String(ENTITY_FIRST_ORDINAL)}`)\n }\n return `${kind}-${formatEntityOrdinal(ordinal)}`\n}\n\n/** `TGT-checkout`. Refuses an ordinal-addressed kind for the same reason. */\nexport function formatSlugShortId(kind: EntityKind, slug: string): string {\n if (!isSlugAddressedKind(kind)) {\n throw new TypeError(`${kind} is ordinal-addressed (D-03); it has no slug short-ID`)\n }\n if (!ENTITY_SLUG_RE.test(slug)) {\n throw new TypeError(`not a well-formed entity slug: ${slug}`)\n }\n return `${kind}-${slug}`\n}\n\n/**\n * The two anchored bodies. Anchored at BOTH ends: an unanchored ordinal pattern accepts\n * `MEM-1 and also MEM-2`, and a resolver that took the first capture off that string would\n * silently answer about one of two entities the caller named.\n */\nconst ENTITY_ORDINAL_RE = /^[0-9]+$/u\nconst ENTITY_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/u\n\n/**\n * Built OVER `ENTITY_KINDS` rather than restating the five prefixes, so the parser and the\n * union cannot disagree about what a kind is. The body capture is deliberately loose — which\n * FORM is legal is a per-kind question the table above answers, not something a single\n * pattern should try to encode.\n */\nconst SHORT_ID_RE = new RegExp(`^(${ENTITY_KINDS.join('|')})-(.+)$`, 'u')\n\nexport type ParsedShortId =\n | { readonly kind: EntityKind; readonly form: 'ordinal'; readonly ordinal: number }\n | { readonly kind: EntityKind; readonly form: 'slug'; readonly slug: string }\n\n/**\n * Parse a short-ID, or `undefined` when the value is not one.\n *\n * Absence is a RESULT here, never a throw: the resolver hands this every free-text reference\n * a user types, and \"that bundle about checkout\" is an ordinary input, not an error\n * condition. The typed refusal belongs to the resolver, which knows whether a well-formed\n * address names an entity nobody minted or matches nothing at all.\n */\nexport function parseShortId(value: string): ParsedShortId | undefined {\n const match = SHORT_ID_RE.exec(value.trim())\n if (match === null) return undefined\n\n const kind = match[1] as EntityKind\n const body = match[2] ?? ''\n\n if (isSlugAddressedKind(kind)) {\n return ENTITY_SLUG_RE.test(body) ? { kind, form: 'slug', slug: body } : undefined\n }\n if (!ENTITY_ORDINAL_RE.test(body)) return undefined\n\n const ordinal = Number.parseInt(body, 10)\n if (!Number.isSafeInteger(ordinal) || ordinal < ENTITY_FIRST_ORDINAL) return undefined\n return { kind, form: 'ordinal', ordinal }\n}\n\n/**\n * The canonical spelling of whatever a caller typed — `MEM-1` and `MEM-001` are one address.\n *\n * The ledger is keyed on the canonical form, so this is what makes \"any digit width parses\"\n * a parsing convenience rather than a second set of rows.\n */\nexport function canonicalShortId(value: string): string | undefined {\n const parsed = parseShortId(value)\n if (parsed === undefined) return undefined\n return parsed.form === 'ordinal'\n ? formatOrdinalShortId(parsed.kind, parsed.ordinal)\n : formatSlugShortId(parsed.kind, parsed.slug)\n}\n\nexport function entityUriSegmentFor(kind: EntityKind): EntityUriSegment {\n return ENTITY_URI_SEGMENTS[kind]\n}\n\nexport function entityKindForUriSegment(segment: string): EntityKind | undefined {\n return SEGMENT_TO_KIND.get(segment)\n}\n\nexport function isEntityKind(value: string): value is EntityKind {\n return (ENTITY_KINDS as readonly string[]).includes(value)\n}\n","// The canonical `agentqa://<segment>/<short-id>` entity URI codec (Phase 387, ENTY-01).\n//\n// The URI is the machine-facing half of an address: a card's `keyFacts[]` link entities with\n// it, 389 will put it in verdict sentences, and 396 projects it as an MCP resource link. So\n// it is parsed with an anchored pattern and a closed segment vocabulary rather than with the\n// platform URL parser — `new URL()` accepts an unknown scheme, normalises case, and would\n// happily hand back `agentqa://MEMORY/mem-001` as a successful parse of something this\n// system has no address for.\n//\n// Round-tripping is the contract: `parseEntityUri(formatEntityUri(x)) === x` for every legal\n// address, and anything else parses to `undefined` rather than to a best guess.\n\nimport { z } from 'zod'\n\nimport {\n canonicalShortId,\n entityKindForUriSegment,\n entityUriSegmentFor,\n parseShortId,\n} from './kinds'\nimport type { EntityKind } from './kinds'\n\nexport const ENTITY_URI_SCHEME = 'agentqa'\n\nconst ENTITY_URI_PREFIX = `${ENTITY_URI_SCHEME}://`\n\n/**\n * Anchored, and with exactly two path segments.\n *\n * A pattern that allowed a trailing path would let `agentqa://memory/MEM-001/raw` resolve as\n * `MEM-001`, which is how a caller ends up believing a sub-resource exists because the thing\n * it hangs off resolved.\n */\nconst ENTITY_URI_RE = new RegExp(`^${ENTITY_URI_SCHEME}://([a-z]+)/([^/]+)$`, 'u')\n\nexport interface ParsedEntityUri {\n readonly kind: EntityKind\n /** Canonical spelling — `agentqa://memory/MEM-1` parses to `MEM-001`. */\n readonly shortId: string\n}\n\nexport function formatEntityUri(kind: EntityKind, shortId: string): string {\n const canonical = canonicalShortId(shortId)\n if (canonical === undefined) {\n throw new TypeError(`not a well-formed entity short-ID: ${shortId}`)\n }\n const parsed = parseShortId(canonical)\n if (parsed === undefined || parsed.kind !== kind) {\n throw new TypeError(`short-ID ${canonical} does not belong to kind ${kind}`)\n }\n return `${ENTITY_URI_PREFIX}${entityUriSegmentFor(kind)}/${canonical}`\n}\n\n/**\n * Parse an entity URI, or `undefined` when the value is not one.\n *\n * The two halves must AGREE: `agentqa://memory/TST-001` is refused rather than resolved as\n * the test it names, because a URI whose segment and prefix disagree is one that some\n * surface built by concatenation, and honouring it would make the segment decorative.\n */\nexport function parseEntityUri(value: string): ParsedEntityUri | undefined {\n const match = ENTITY_URI_RE.exec(value.trim())\n if (match === null) return undefined\n\n const kind = entityKindForUriSegment(match[1] ?? '')\n if (kind === undefined) return undefined\n\n const parsed = parseShortId(match[2] ?? '')\n if (parsed === undefined || parsed.kind !== kind) return undefined\n\n const canonical = canonicalShortId(match[2] ?? '')\n return canonical === undefined ? undefined : { kind, shortId: canonical }\n}\n\nexport function isEntityUri(value: string): boolean {\n return parseEntityUri(value) !== undefined\n}\n\n/** The refined-string codec cards and key facts validate their links against. */\nexport const EntityUriSchema = z\n .string()\n .refine(isEntityUri, `expected a canonical ${ENTITY_URI_SCHEME}:// entity URI`)\n","import { z } from 'zod'\n\nimport type { CurationAuthorship, CurationAuthorshipPath } from '../delta/envelope'\nimport type { BundleIdentityCore } from '../ids/content-address'\nimport { canonicalJson } from '../determinism/canonical-json'\nimport { sha256hex } from '../determinism/sha256'\nimport type { ExecutionContext } from '../run/run-status'\nimport { createVersionGuard } from '../versioning/create-version-guard'\nimport type { OriginClass } from './outcome-event'\n\n/** D-16: one version governs every committed JSON artifact in a bundle directory. */\nexport const BUNDLE_SCHEMA_VERSION = 2\n\nconst bundleKindSchema = z.enum(['fact', 'procedure', 'caution', 'unknown', 'policy'])\nconst factSubtypeSchema = z.enum([\n 'selector',\n 'behavioral',\n 'navigational',\n 'measurement',\n 'content',\n])\nconst originClassSchema: z.ZodType<OriginClass> = z.enum([\n 'user',\n 'agent-verified',\n 'agent-observed',\n 'import',\n])\nconst curationAuthorshipPaths = [\n 'llm',\n 'llm-repaired',\n 'deterministic-fallback',\n] as const satisfies readonly CurationAuthorshipPath[]\nconst executionContexts = [\n 'local-interactive',\n 'local-headless',\n 'ci',\n 'cloud',\n] as const satisfies readonly ExecutionContext[]\nconst curationAuthorshipSchema: z.ZodType<CurationAuthorship> = z.object({\n path: z.enum(curationAuthorshipPaths),\n model: z.object({\n id: z.string(),\n family: z.string().optional(),\n fingerprint: z.string().optional(),\n }).strict().optional(),\n executionContext: z.enum(executionContexts),\n // 381-47 additive-optional diagnostic; never a trust/tier input (D-06 folds path alone).\n fallbackReason: z\n .enum(['malformed', 'no-model', 'token-budget', 'model-error'])\n .optional(),\n}).strict()\nconst sha256Schema = z.string().regex(/^[0-9a-f]{64}$/, 'expected a lowercase SHA-256 hex digest')\n\nconst anchorSchema = z.discriminatedUnion('t', [\n z.object({ t: z.literal('page'), route: z.string() }).strict(),\n z.object({ t: z.literal('flow'), name: z.string() }).strict(),\n z.object({\n t: z.literal('el'),\n role: z.string(),\n name: z.string(),\n ordinal: z.number().int().optional(),\n }).strict(),\n z.object({\n t: z.literal('platform'),\n platform: z.enum(['web', 'android', 'ios']),\n }).strict(),\n z.object({ t: z.literal('selector'), literal: z.string() }).strict(),\n z.object({ t: z.literal('error'), message: z.string() }).strict(),\n])\n\nconst scopeKeySchema = z.object({\n tier: z.enum(['global', 'product', 'suite', 'test']),\n key: z.string(),\n}).strict()\n\nconst bundleIdentityCoreSchema: z.ZodType<BundleIdentityCore> = z.object({\n kind: bundleKindSchema,\n subtype: factSubtypeSchema.nullable(),\n primaryAnchor: anchorSchema,\n scope: scopeKeySchema,\n discriminantKey: z.string(),\n}).strict().superRefine((identity, ctx) => {\n if (identity.kind === 'fact' && identity.subtype === null) {\n ctx.addIssue({\n code: 'custom',\n path: ['subtype'],\n message: 'fact bundle identity requires a fact subtype (D-06)',\n })\n }\n if (identity.kind !== 'fact' && identity.subtype !== null) {\n ctx.addIssue({\n code: 'custom',\n path: ['subtype'],\n message: 'only fact bundle identity may carry a subtype (D-06)',\n })\n }\n})\n\nconst committedRelPathSchema = z.string().refine((value) => {\n if (value === '' || value.startsWith('/') || value.includes('\\\\')) return false\n const segments = value.split('/')\n return segments.every((segment) => segment !== '' && segment !== '.' && segment !== '..')\n}, 'expected a bundle-relative committed file path')\n\n/** The manifest is both the immutable identity echo and the mutable rebuild contract. */\nexport const BundleManifestSchema = z.object({\n schemaVersion: z.number().int().positive(),\n id: z.string(),\n identityHash: sha256Schema,\n identityCore: bundleIdentityCoreSchema,\n embeddingInput: z.string(),\n contentHashes: z.record(committedRelPathSchema, sha256Schema),\n mutableStateHash: sha256Schema,\n evidenceIncomplete: z.boolean(),\n complete: z.boolean(),\n createdAtOrdinal: z.number(),\n originClass: originClassSchema,\n}).strict().superRefine((manifest, ctx) => {\n if (Object.hasOwn(manifest.contentHashes, 'manifest.json')) {\n ctx.addIssue({\n code: 'custom',\n path: ['contentHashes', 'manifest.json'],\n message: 'manifest.json cannot hash itself',\n })\n }\n})\n\nexport type BundleManifest = z.infer<typeof BundleManifestSchema>\n\n/**\n * Graceful-degradation provenance: in-bundle evidence remains authoritative even when a\n * run-linked deep-audit reference is unavailable on the reading machine (§3.1).\n */\nexport const BundleProvenanceSchema = z.discriminatedUnion('mode', [\n z.object({\n schemaVersion: z.number().int().positive(),\n mode: z.literal('run-linked'),\n originClass: originClassSchema,\n runId: z.string(),\n testId: z.string(),\n stepIndex: z.number().int().nonnegative(),\n curationJobId: z.string().optional(),\n sourceBuildOrdinal: z.number().optional(),\n authorship: curationAuthorshipSchema.optional(),\n /** CUR-02: deterministic fallback output may request capable-model re-processing. */\n needsEnrichment: z.boolean().optional(),\n /**\n * SAFE-03: injection-flagged candidates stay out of brief serving and ordinary promotion\n * until a local-interactive re-review supersedes them.\n */\n withheld: z.boolean().optional(),\n }).strict(),\n z.object({\n schemaVersion: z.number().int().positive(),\n mode: z.literal('standalone'),\n originClass: originClassSchema,\n sourceDescription: z.string(),\n }).strict(),\n])\n\nexport type BundleProvenance = z.infer<typeof BundleProvenanceSchema>\n\nconst bundleRelationSchema = z.object({\n type: z.enum([\n 'supersedes',\n 'superseded-by',\n 'derived-from',\n 'conflicts-with',\n 'relates-to',\n 'renamed-from',\n 'equivalent-to',\n 'proposed-supersession-of',\n ]),\n targetId: z.string(),\n addedAtOrdinal: z.number(),\n curationJobId: z.string(),\n}).strict()\n\nexport const BundleRelationsSchema = z.object({\n schemaVersion: z.number().int().positive(),\n relations: z.array(bundleRelationSchema),\n}).strict()\n\nexport type BundleRelation = z.infer<typeof bundleRelationSchema>\nexport type BundleRelations = z.infer<typeof BundleRelationsSchema>\n\nconst artifactIndexEntrySchema = z.object({\n id: z.string(),\n sha: sha256Schema,\n bytes: z.number().int().nonnegative(),\n stepIndex: z.number().int().nonnegative(),\n relPath: z.string().regex(/^artifacts\\/[0-9a-f]{64}$/),\n role: z.string().optional(),\n originalName: z.string().optional(),\n evidenceIncomplete: z.boolean().optional(),\n}).strict().superRefine((artifact, ctx) => {\n if (artifact.relPath !== `artifacts/${artifact.sha}`) {\n ctx.addIssue({\n code: 'custom',\n path: ['relPath'],\n message: 'artifact relPath must match its content SHA',\n })\n }\n})\n\nconst skippedArtifactIndexEntrySchema = z.object({\n id: z.string(),\n sha: sha256Schema,\n stepIndex: z.number().int().nonnegative(),\n path: z.string(),\n reason: z.enum([\n 'step-cap',\n 'run-cap',\n 'pruned-source',\n 'sha-mismatch',\n ]),\n}).strict()\n\nexport const ArtifactsIndexSchema = z.object({\n schemaVersion: z.number().int().positive(),\n artifacts: z.array(artifactIndexEntrySchema),\n /** Skipped artifacts: bytes are intentionally absent and the refusal reason is durable. */\n skipped: z.array(skippedArtifactIndexEntrySchema).optional(),\n}).strict()\n\nexport type ArtifactsIndex = z.infer<typeof ArtifactsIndexSchema>\n\nconst guardBundleManifestVersion = createVersionGuard<BundleManifest>({\n name: 'BundleManifest',\n current: BUNDLE_SCHEMA_VERSION,\n migrations: {},\n})\nconst guardBundleProvenanceVersion = createVersionGuard<BundleProvenance>({\n name: 'BundleProvenance',\n current: BUNDLE_SCHEMA_VERSION,\n migrations: {},\n})\nconst guardBundleRelationsVersion = createVersionGuard<BundleRelations>({\n name: 'BundleRelations',\n current: BUNDLE_SCHEMA_VERSION,\n migrations: {},\n})\nconst guardArtifactsIndexVersion = createVersionGuard<ArtifactsIndex>({\n name: 'ArtifactsIndex',\n current: BUNDLE_SCHEMA_VERSION,\n migrations: {},\n})\n\nexport function guardBundleManifest(value: unknown): BundleManifest {\n return BundleManifestSchema.parse(guardBundleManifestVersion(value))\n}\n\nexport function guardBundleProvenance(value: unknown): BundleProvenance {\n return BundleProvenanceSchema.parse(guardBundleProvenanceVersion(value))\n}\n\nexport function guardBundleRelations(value: unknown): BundleRelations {\n return BundleRelationsSchema.parse(guardBundleRelationsVersion(value))\n}\n\nexport function guardArtifactsIndex(value: unknown): ArtifactsIndex {\n return ArtifactsIndexSchema.parse(guardArtifactsIndexVersion(value))\n}\n\nexport interface MutableStateHashInput {\n outcomes: string | null\n relations: string | null\n artifactsIndex: string | null\n /**\n * D-03 additive measurement stream digest. Optionality preserves the exact\n * mutable-state hash of bundles created before measurements.json exists.\n */\n measurements?: string | null\n /** 416 D-03: omitted until the lazy gate part exists, preserving prior bundle hashes. */\n gates?: string | null\n}\n\n/**\n * BNDL-02 anti-collapse law: only mutable-file content digests enter this hash. Identity,\n * embedding status, and prose are structurally absent so Phase 375 can diff rebuild state.\n */\nexport function computeMutableStateHash(input: MutableStateHashInput): string {\n return sha256hex(canonicalJson(input))\n}\n","import type { ArtifactRef } from '../ids/artifact-ref'\nimport type { RecordId } from '../ids/record-id'\nimport type { Anchor } from '../identity/anchor'\nimport type { MemoryOnPathEntry, MisdirectionEvidence } from './misdirection-evidence'\n\nexport interface VerdictEvidence {\n citedSteps: number[]\n citedAnchors: Anchor[]\n citedArtifacts: ArtifactRef[]\n rationale: string\n}\n\ninterface VerdictBase {\n /**\n * Which pipeline minted this verdict (D-03). M2 mints only\n * 'deterministic-classifier'; M4's analyze-run supersedes it via ordinary\n * supersession. Failure-side trust-keying switches on this field — it is a\n * different axis from VerdictSource (verb-evidence.ts), never reuse that union.\n */\n producer: 'deterministic-classifier' | 'analyze-run'\n confidence: number\n evidence: VerdictEvidence\n attribution?: {\n records: RecordId[]\n anchors: Anchor[]\n }\n memoryMisdirectionRuledOut: boolean\n /**\n * 422 D-17: the low-trust records the author says the run put on this verdict's failing\n * path. A DECLARATION, never the source of truth — `validateAnalysisAgainstHandoff`\n * recomputes the set from the run's own served briefs and rejects a declaration that\n * disagrees. Additive optional: absent on every verdict written before 422, and an absent\n * array exonerates nothing, because the gate keys on the recomputed set either way.\n */\n memoryOnPath?: MemoryOnPathEntry[]\n /**\n * 422 D-19/D-20: the complete per-record cross-check backing\n * {@link VerdictBase.memoryMisdirectionRuledOut}, or the `declared-only` absence marker a\n * run with no evaluation root carries instead. Additive optional BESIDE the frozen boolean,\n * which keeps its shape and meaning — historical bytes carrying the boolean alone stay\n * readable, while a current gated producer must ship this ledger.\n */\n misdirectionRuledOut?: MisdirectionEvidence\n perTest: number\n}\n\n/**\n * The closed verdict-class vocabulary, spelled once as data (388 C13). Minted here beside the\n * union it enumerates so consumers that must validate a stored class — the 390 quarantine ledger\n * guard keys entries on one — check membership against the same list the type declares, rather\n * than a fourth private copy. The three copies that predated it — the handoff guard, the\n * analysis-artifact guard and the analysis validator — were rewired to this export in 390 plan\n * 02, so the closed set is spelled exactly once (388 C13).\n *\n * Type agreement with `Verdict['class']` is pinned in `__tests__/quarantine-ledger.test.ts`.\n */\nexport const VERDICT_CLASSES = [\n 'test_bug',\n 'app_bug',\n 'environment',\n 'flake',\n 'config_error',\n 'llm_error',\n 'unknown',\n 'timeout',\n] as const\n\nexport type VerdictClass = (typeof VERDICT_CLASSES)[number]\n\nconst VERDICT_CLASS_SET: ReadonlySet<string> = new Set(VERDICT_CLASSES)\n\n/** True for exactly the eight closed classes — the membership check stored bytes must pass. */\nexport function isVerdictClass(value: unknown): value is VerdictClass {\n return typeof value === 'string' && VERDICT_CLASS_SET.has(value)\n}\n\nexport type Verdict =\n | (VerdictBase & {\n class: 'test_bug'\n subtype?: 'stale_selector' | 'outdated_flow' | 'bad_assertion' | 'wrong_expected_value'\n })\n | (VerdictBase & { class: 'app_bug' })\n | (VerdictBase & { class: 'environment' })\n | (VerdictBase & { class: 'flake' })\n | (VerdictBase & { class: 'config_error' })\n | (VerdictBase & { class: 'llm_error' })\n /** LLM-judge abstention / unclassifiable — noop for learning; never files an issue (§A9 routing). */\n | (VerdictBase & { class: 'unknown' })\n /** Routes with environment/flake (flake management); never the issue path (§A9 routing). */\n | (VerdictBase & { class: 'timeout' })\n","// 2026-09-15, 423 D-20/D-21: the read-time record join shared by runs.knowledge rows and the\n// runs.mark.preview knowledge records (D-17). Its own module so feedback.ts and runs.ts both use it.\nimport { z } from 'zod'\n\nimport type { KnowledgeRecordShowResult } from '../knowledge/review-verbs'\nimport { InspectRecordViewSchema } from '../knowledge/maintenance-views'\nimport type { MaskFn } from '../run/bus-projections'\n\n/**\n * Why a row carries no joined record content (423 D-20/D-21).\n *\n * `not-found` is the store's own answer for this identity (for example a purged record), while\n * `scan-incomplete` means the batch read could not finish and `not-bound` means this host binds no\n * batch record read. The row itself is always retained.\n */\nexport const RUN_KNOWLEDGE_CONTENT_ABSENCE_REASONS = [\n 'not-found',\n 'scan-incomplete',\n 'not-bound',\n] as const\n\nexport const RunKnowledgeContentAbsenceSchema = z.object({\n reason: z.enum(RUN_KNOWLEDGE_CONTENT_ABSENCE_REASONS),\n}).strict()\n\n/**\n * The record as the maintenance read shows it NOW (423 D-21). Every `current*` member is read-time\n * state; the row it rides on keeps its own historical `change`/`atOrdinal` or served trust/status.\n */\nexport const RunKnowledgeRecordContentSchema = z.object({\n content: z.string(),\n summary: z.string(),\n kind: InspectRecordViewSchema.shape.kind,\n applicability: z.object({\n product: z.string(),\n scope: z.string(),\n anchors: z.array(z.string()),\n openedAtOrdinal: z.number().int().nonnegative(),\n closedAtOrdinal: z.number().int().nonnegative().optional(),\n }).strict(),\n currentStatus: InspectRecordViewSchema.shape.status,\n currentTrust: z.object({\n confirmations: z.number().int().nonnegative(),\n contradictions: z.number().int().nonnegative(),\n evidenceTokens: z.array(z.string()),\n lastEventOrdinal: z.number().int().nonnegative(),\n trustNarrative: z.string().optional(),\n }).strict(),\n}).strict()\n\nexport type RunKnowledgeRecordContent = z.infer<typeof RunKnowledgeRecordContentSchema>\nexport type RunKnowledgeContentAbsence = z.infer<typeof RunKnowledgeContentAbsenceSchema>\n\nexport const recordJoinShape = {\n recordContent: RunKnowledgeRecordContentSchema.optional(),\n contentAbsence: RunKnowledgeContentAbsenceSchema.optional(),\n}\n\nexport function oneJoinArm(\n row: { recordContent?: unknown; contentAbsence?: unknown },\n ctx: z.RefinementCtx,\n) {\n if (row.recordContent !== undefined && row.contentAbsence !== undefined) {\n ctx.addIssue({ code: 'custom', path: ['contentAbsence'],\n message: 'a joined row carries record content or its absence, never both' })\n }\n}\n\n/**\n * The one record join (423 D-20): a found maintenance read, picked field by field. Trust and\n * status are `deriveBundleTrust`'s answer as shown, never recomputed; masking is a separate step.\n */\nexport function projectRecordContent(result: Extract<KnowledgeRecordShowResult, { kind: 'found' }>): RunKnowledgeRecordContent {\n const { record } = result\n return {\n content: result.body,\n summary: result.summary,\n kind: record.kind,\n applicability: {\n product: record.product,\n scope: record.scope,\n anchors: [...record.anchors],\n openedAtOrdinal: record.openedAtOrdinal,\n ...(record.closedAtOrdinal === undefined ? {} : { closedAtOrdinal: record.closedAtOrdinal }),\n },\n currentStatus: record.status,\n currentTrust: {\n confirmations: record.confirmations,\n contradictions: record.contradictions,\n evidenceTokens: [...record.evidenceTokens],\n lastEventOrdinal: record.lastEventOrdinal,\n ...(record.trustNarrative === undefined || record.trustNarrative === null\n ? {}\n : { trustNarrative: record.trustNarrative }),\n },\n }\n}\n\n/** Every free-text member of joined content crosses the mask; ordinals, kind and status stay structural. */\nexport function maskRecordContent(content: RunKnowledgeRecordContent, mask: MaskFn): RunKnowledgeRecordContent {\n return {\n ...content,\n content: mask(content.content),\n summary: mask(content.summary),\n applicability: {\n ...content.applicability,\n product: mask(content.applicability.product),\n scope: mask(content.applicability.scope),\n anchors: content.applicability.anchors.map(mask),\n },\n currentTrust: {\n ...content.currentTrust,\n evidenceTokens: content.currentTrust.evidenceTokens.map(mask),\n ...(content.currentTrust.trustNarrative === undefined ? {} : { trustNarrative: mask(content.currentTrust.trustNarrative) }),\n },\n }\n}\n","import { z } from 'zod'\n\nimport { createVersionGuard } from '../versioning/create-version-guard'\nimport { PROMOTION_PATHS } from './promotion-path'\n\nexport const RECORD_CHANGE_SCHEMA_VERSION = 2\nexport const INSPECT_RECORD_VIEW_SCHEMA_VERSION = 2\n\nconst knowledgeRecordKindSchema = z.enum([\n 'fact',\n 'procedure',\n 'caution',\n 'unknown',\n 'policy',\n])\n\nconst bundleStatusSchema = z.enum([\n 'active',\n 'candidate',\n 'superseded',\n 'deprecated',\n])\n\n/** Closed structural filter for deterministic maintenance inspection (D-06). */\nexport const InspectFilterSchema = z.object({\n product: z.string().optional(),\n scope: z.string().optional(),\n kind: knowledgeRecordKindSchema.optional(),\n status: bundleStatusSchema.optional(),\n anchor: z.string().optional(),\n recordId: z.string().optional(),\n asOfBuild: z.number().int().nonnegative().optional(),\n unresolvedOnly: z.boolean().optional(),\n}).strict()\n\nexport type InspectFilter = z.infer<typeof InspectFilterSchema>\n\n/** Stable machine-readable view of one record derived from committed bundle truth. */\nexport const InspectRecordViewSchema = z.object({\n schemaVersion: z.literal(INSPECT_RECORD_VIEW_SCHEMA_VERSION),\n recordId: z.string(),\n product: z.string(),\n scope: z.string(),\n kind: knowledgeRecordKindSchema,\n status: bundleStatusSchema,\n confirmations: z.number().int().nonnegative(),\n contradictions: z.number().int().nonnegative(),\n evidenceTokens: z.array(z.string()),\n lastEventOrdinal: z.number().int().nonnegative(),\n openedAtOrdinal: z.number().int().nonnegative(),\n closedAtOrdinal: z.number().int().nonnegative().optional(),\n anchors: z.array(z.string()),\n /** LLM-authored prose remains separate from code-computed evidence and counts. */\n trustNarrative: z.string().nullable().optional(),\n}).strict()\n\nexport type InspectRecordView = z.infer<typeof InspectRecordViewSchema>\n\nconst guardInspectRecordViewVersion = createVersionGuard<InspectRecordView>({\n name: 'InspectRecordView',\n current: INSPECT_RECORD_VIEW_SCHEMA_VERSION,\n migrations: {},\n})\n\nexport function guardInspectRecordView(value: unknown): InspectRecordView {\n return InspectRecordViewSchema.parse(guardInspectRecordViewVersion(value))\n}\n\nexport const RecordChangeSchema = z.object({\n schemaVersion: z.literal(RECORD_CHANGE_SCHEMA_VERSION),\n recordId: z.string(),\n change: z.enum([\n 'added',\n 'confirmed',\n 'superseded',\n 'deprecated',\n 'promoted',\n 'purged',\n ]),\n atOrdinal: z.number().int().nonnegative(),\n evidenceToken: z.string().optional(),\n byRecordId: z.string().optional(),\n /**\n * 419 D-19: present only when change === 'promoted' and the bundle's gate part\n * names a strongest path; numbers and digests are COPIED from the receipt line,\n * never derived at render.\n */\n promotionPath: z.enum(PROMOTION_PATHS).optional(),\n promotionReceiptDigest: z.string().regex(/^[0-9a-f]{64}$/).optional(),\n /**\n * The run whose curation produced this change (Phase 407, LERN-02 · D-10).\n *\n * ADDITIVE AND OPTIONAL, and `RECORD_CHANGE_SCHEMA_VERSION` deliberately does NOT move: every\n * change ever written stays valid, and a reader that ignores the field reads exactly what it\n * read before. Stamped by the reader entry's `diffSince` from the bundle's own\n * `provenance.runId` (`mode: 'run-linked'`) for commit and promotion events.\n *\n * WHY A FIELD AND NOT A JOIN ON `curationJobId`. There is no single \"this run's curation job\n * id\" to join on: commit stamps `curationJobId = candidateId`, promotion stamps\n * `promote:<candidateId>`, and a canary outcome stamps a sha-derived observation id — none of\n * which a `RecordChange` carries and none of which is the run. Absent when attribution is not\n * derivable, because a change attributed to the wrong run is worse than one attributed to no\n * run: a person reading \"this run deprecated that fact\" acts on it.\n */\n sourceRunId: z.string().min(1).optional(),\n /**\n * The attributed observation this change came from, when it came from one (Phase 407, D-10).\n *\n * The second half of the run link, and a DIFFERENT axis from `sourceRunId` rather than a\n * fallback for it. Canary outcomes are attributed by an observation id recomputed from the\n * run's served-canary tuples — `canaryOutcomeObservationId({ candidateId, runId, testId,\n * testIndex, stepIndex })` — so a consumer matches those changes by observation id while\n * matching commit/promotion changes by run id. Absent for a change no observation produced.\n */\n observationId: z.string().min(1).optional(),\n}).strict().superRefine((value, ctx) => {\n if (value.change === 'promoted') return\n for (const field of ['promotionPath', 'promotionReceiptDigest'] as const) {\n if (value[field] !== undefined) {\n ctx.addIssue({\n code: 'custom', path: [field],\n message: 'only a promoted change carries promotion receipt attribution (419 D-19)',\n })\n }\n }\n})\n\nexport type RecordChange = z.infer<typeof RecordChangeSchema>\n\nconst guardRecordChangeVersion = createVersionGuard<RecordChange>({\n name: 'RecordChange',\n current: RECORD_CHANGE_SCHEMA_VERSION,\n migrations: {},\n})\n\nexport function guardRecordChange(value: unknown): RecordChange {\n return RecordChangeSchema.parse(guardRecordChangeVersion(value))\n}\n","import { z } from 'zod'\n\nimport { RecordChangeSchema } from '../knowledge/maintenance-views'\nimport { canonicalJson } from '../determinism/index'\n\nexport type CurationBucket = 'added' | 'confirmed' | 'superseded' | 'deprecated' | 'proposed'\nexport const CURATION_BREAKDOWN_BUCKETS = [\n 'added', 'confirmed', 'superseded', 'deprecated', 'proposed',\n] as const satisfies readonly CurationBucket[]\nexport const CURATION_BUCKET_PRECEDENCE = [\n 'superseded', 'deprecated', 'proposed', 'added', 'confirmed',\n] as const satisfies readonly CurationBucket[]\nexport const CURATION_SNAPSHOT_SCHEMA_VERSION = 2\nexport const CurationBucketSchema = z.enum(CURATION_BREAKDOWN_BUCKETS)\n\n/** Classification is recorded by curation, not inferred from a record's current status. */\nexport const CurationSnapshotChangeSchema = z.discriminatedUnion('bucket', [\n z.object({\n bucket: z.literal('added'),\n change: RecordChangeSchema.safeExtend({ change: z.literal('added') }),\n }).strict(),\n z.object({\n bucket: z.literal('confirmed'),\n change: RecordChangeSchema.safeExtend({ change: z.enum(['confirmed', 'promoted']) }),\n }).strict(),\n z.object({\n bucket: z.literal('superseded'),\n change: RecordChangeSchema.safeExtend({\n change: z.literal('superseded'), byRecordId: z.string().min(1),\n }),\n }).strict(),\n z.object({\n bucket: z.literal('deprecated'),\n change: RecordChangeSchema.safeExtend({ change: z.literal('deprecated') }),\n }).strict(),\n z.object({\n bucket: z.literal('proposed'),\n // Both a newly held candidate and confirmation of an existing replacement\n // can be the successful effect of an original Supersede/Deprecate downgrade.\n change: RecordChangeSchema.safeExtend({ change: z.enum(['added', 'confirmed']) }),\n }).strict(),\n])\nexport type CurationSnapshotChange = z.infer<typeof CurationSnapshotChangeSchema>\n\n/**\n * One affected unit retains every historical identity used to classify it.\n * A supersession may retain its replacement's Add here for since-then exclusion;\n * that identity does not become a second affected-record membership.\n * This validator checks supplied facts; the committed-effect fold lives in knowledge-local.\n */\nexport const CurationSnapshotRowSchema = z.object({\n recordId: z.string().min(1),\n bucket: CurationBucketSchema,\n byRecordId: z.string().min(1).optional(),\n changes: z.array(CurationSnapshotChangeSchema).min(1),\n}).strict().superRefine((row, ctx) => {\n const ownChanges = row.changes.filter(({ change }) => change.recordId === row.recordId)\n const strongest = CURATION_BUCKET_PRECEDENCE.find((bucket) =>\n ownChanges.some((entry) => entry.bucket === bucket),\n )\n if (strongest !== row.bucket) {\n ctx.addIssue({ code: 'custom', path: ['bucket'], message: 'expected strongest affected bucket' })\n }\n const supersessions = ownChanges.filter((entry) => entry.bucket === 'superseded')\n const replacementIds = new Set(supersessions.map(({ change }) => change.byRecordId))\n const latestOrdinal = supersessions.reduce((latest, { change }) =>\n Math.max(latest, change.atOrdinal), -1)\n if (row.bucket === 'superseded'\n ? !supersessions.some(({ change }) =>\n change.atOrdinal === latestOrdinal && change.byRecordId === row.byRecordId)\n : row.byRecordId !== undefined) {\n ctx.addIssue({ code: 'custom', path: ['byRecordId'], message: 'expected recorded replacement' })\n }\n const identities = new Set<string>()\n for (const [index, { bucket, change }] of row.changes.entries()) {\n const path = ['changes', index]\n if (change.recordId !== row.recordId\n && !(bucket === 'added' && replacementIds.has(change.recordId))) {\n ctx.addIssue({ code: 'custom', path, message: 'change belongs to another affected unit' })\n }\n if (change.byRecordId !== undefined\n && (change.change !== 'superseded' || change.byRecordId === change.recordId)) {\n ctx.addIssue({ code: 'custom', path, message: 'invalid historical replacement' })\n }\n // Classification is deliberately excluded: two classifications of the same\n // historical identity are a conflict, not two pieces of history.\n const identity = canonicalJson(change)\n if (identities.has(identity)) {\n ctx.addIssue({ code: 'custom', path, message: 'duplicate historical change identity' })\n }\n identities.add(identity)\n }\n})\nexport type CurationSnapshotRow = z.infer<typeof CurationSnapshotRowSchema>\n\nexport const CurationBreakdownSchema = z.object({\n added: z.number().int().nonnegative(),\n confirmed: z.number().int().nonnegative(),\n superseded: z.number().int().nonnegative(),\n deprecated: z.number().int().nonnegative(),\n proposed: z.number().int().nonnegative(),\n}).strict()\nexport type CurationBreakdown = z.infer<typeof CurationBreakdownSchema>\n\n/** Fixed recorded snapshot; parsing never folds, reclassifies or repairs supplied rows/counts. */\nexport const CurationSnapshotSchema = z.object({\n schemaVersion: z.literal(CURATION_SNAPSHOT_SCHEMA_VERSION),\n rows: z.array(CurationSnapshotRowSchema),\n breakdown: CurationBreakdownSchema,\n}).strict().superRefine((snapshot, ctx) => {\n const records = new Set<string>()\n const replacements = new Set<string>()\n const counts: CurationBreakdown = {\n added: 0, confirmed: 0, superseded: 0, deprecated: 0, proposed: 0,\n }\n for (const [index, row] of snapshot.rows.entries()) {\n if (records.has(row.recordId)) {\n ctx.addIssue({ code: 'custom', path: ['rows', index, 'recordId'],\n message: 'duplicate affected-record membership' })\n } else {\n records.add(row.recordId)\n counts[row.bucket]++\n }\n for (const entry of row.changes) {\n if (entry.bucket === 'superseded') replacements.add(entry.change.byRecordId)\n }\n }\n for (const [index, row] of snapshot.rows.entries()) {\n if (row.bucket === 'added' && replacements.has(row.recordId)) {\n ctx.addIssue({ code: 'custom', path: ['rows', index],\n message: 'replacement Add is represented by its victim' })\n }\n }\n for (const bucket of CURATION_BREAKDOWN_BUCKETS) {\n if (snapshot.breakdown[bucket] !== counts[bucket]) {\n ctx.addIssue({ code: 'custom', path: ['breakdown', bucket],\n message: 'count must equal unique affected-record membership' })\n }\n }\n})\nexport type CurationSnapshot = z.infer<typeof CurationSnapshotSchema>\n","// The chain-terminal notification DTO (Phase 388, D-09 / D-11 / D-12).\n//\n// One record per run, written inside the transaction that lands the LAST job the post-run\n// chain enqueued. It is the thing 392's chat and M5's dashboard read, which is why it is\n// minted here rather than beside either of them: a payload shape that lived with one\n// consumer would be re-derived by the second, and the two spellings would drift on the first\n// field either of them wanted.\n//\n// What it deliberately does NOT carry (D-11; 385 D-01): no record content, no rationale\n// prose, no artifact bytes, no `agentqa://` refs. Counts, verdict classes and identifiers\n// only. The curation stage carries fixed curation event identities, which may contain\n// unconstrained strings. Public reads mask that snapshot through the same strict projection\n// as the early checkpoint snapshot; durable bytes remain the exact committed facts.\n//\n// `outcome` is a fact about the CHAIN, not about the run: a failed run whose analysis and\n// curation both succeeded notifies `done`. The run's own verdict is the exit code, frozen\n// long before anything here exists (JOBQ-06), and conflating the two would make this record\n// a second, later, quieter answer to a question already answered.\n\nimport type { Verdict } from '../verdict/verdict'\nimport { CurationSnapshotSchema } from './curation-snapshot'\nimport type { CurationSnapshot } from './curation-snapshot'\n\n/**\n * Stamped into every record and checked on every read.\n *\n * A literal type rather than `number` (the `CurationTailReceipt` idiom): a record built with\n * last version's shape then fails to typecheck at its construction site, which is where the\n * mistake is, instead of at the reader that could only report it as corrupt bytes.\n */\nexport const CURRENT_RUN_NOTIFICATION_SCHEMA_VERSION = 2\n\n/** Whether the chain as a whole finished clean. Every stage done ⇒ `done` (D-12). */\nexport type RunNotificationOutcome = 'done' | 'failed'\n\n/**\n * Declaration-order projection of `RunNotificationOutcome` (2026-09-12, 422-22; the D-22 bar).\n *\n * `satisfies` refuses a list member the union lacks and says NOTHING about a union that grew, so\n * the reverse direction is pinned by the independent oracles in\n * `../__tests__/422-notification-closed-sets.test.ts` and its `.test-d.ts` sibling — neither of\n * which builds its expectation from this list.\n */\nexport const RUN_NOTIFICATION_OUTCOMES = [\n 'done',\n 'failed',\n] as const satisfies readonly RunNotificationOutcome[]\n\n/** What became of one stage the chain actually ran. */\nexport type RunNotificationStageStatus = 'done' | 'failed'\n\n/**\n * Declaration-order projection of `RunNotificationStageStatus` (2026-09-12, 422-22).\n *\n * TWO WORDS, AND THE THIRD ONE IS AN ABSENCE RATHER THAN A WORD. A stage that was not recorded is\n * expressed by the member being MISSING (see `RunNotificationStages`), never by a `not-recorded`\n * status — because a status is a claim about a stage that ran. Widening this enum to carry a stage\n * that never ran would let a writer stamp an invented stage onto a row, and no reader can tell an\n * invented stage from a recorded one.\n */\nexport const RUN_NOTIFICATION_STAGE_STATUSES = [\n 'done',\n 'failed',\n] as const satisfies readonly RunNotificationStageStatus[]\n\n/**\n * Per-class counts over the verdicts the analysis stage authored.\n *\n * `byClass` is PARTIAL on purpose: a run with no environment failures omits the key rather\n * than carrying a zero. A dense record would make \"this class did not occur\" and \"this build\n * does not know that class yet\" the same bytes, and the second is the one a later verdict\n * class introduces.\n */\nexport interface RunNotificationVerdictSummary {\n total: number\n byClass: Partial<Record<Verdict['class'], number>>\n}\n\n/**\n * The stages the chain actually runs: two always, a third when the chain reached it.\n *\n * The optional third is the contract, not a convenience. `proposals` absent means the proposal\n * stage WAS NOT RECORDED — which is the truth for every chain that halted at a permanently failed\n * fold — and it is deliberately distinct from `{status: 'failed'}`, which claims a stage that ran\n * and did not finish. Synthesizing a successful stage would be this build inventing work nobody\n * did, and the read-side surfaces cannot tell an invented stage from a recorded one.\n *\n * A stage record carries its STATUS and, for curation, the counts it committed. It carries NO\n * failure text, and that absence is a decision rather than an omission (404 D-21, T-404-01):\n * this row is stamped by whichever process drains the chain, INCLUDING the daemon's pump, which\n * can fold with no declared mask bound (388 D-06's `no-masker` posture). A reason stored\n * here therefore could not be guaranteed masked at the moment it was written, and this row is\n * read by surfaces that render it directly — so a secret that reached the column would reach a\n * screen. The masked, bounded reason (`CHIP_ERROR_MAX_LENGTH`) lives instead on the in-process\n * `*Failed` chip envelope, which is itself durable (it is appended to the run's `events.jsonl`)\n * and reaches the page through the read route's `runs.events` fold. A `failed` chip with no\n * such envelope renders `failed` plus a posture-qualified \"reason not recorded\" line — never\n * blank. The job store's own per-job failure-reason column is a pump-internal field and is not\n * surfaced by this contract for the same masking reason.\n */\nexport interface RunNotificationStages {\n analysis: { status: RunNotificationStageStatus }\n /**\n * Counts are present only when the curation stage actually committed a bundle. A failed\n * curation reports its status and no counts at all — zeros would say it curated nothing,\n * which is a different claim from never having got that far.\n */\n curation: {\n status: RunNotificationStageStatus\n curated?: number\n deprecated?: number\n /** Exact bundle-committed facts. Missing on historical or uncommitted curation. */\n curationSnapshot?: CurationSnapshot\n }\n /**\n * The adversarial proposal stage (422 D-13). ABSENT means NOT RECORDED — see the interface\n * comment — and the counts follow curation's rule exactly: present only for a stage that got\n * far enough to have them, because zeros on a stage that never staged anything would claim it\n * proposed nothing, which is a different sentence from never having reached the port at all.\n */\n proposals?: {\n status: RunNotificationStageStatus\n proposed?: number\n skipped?: number\n }\n}\n\nexport interface RunNotification {\n schemaVersion: typeof CURRENT_RUN_NOTIFICATION_SCHEMA_VERSION\n runId: string\n outcome: RunNotificationOutcome\n verdictSummary: RunNotificationVerdictSummary\n stages: RunNotificationStages\n}\n\n// 2026-10-17 (444-10, D-36): agent-jobs.db keeps the stored words; every read serves this view.\nexport type RunNotificationViewStatus = 'complete' | 'failed'\n\nexport const RUN_NOTIFICATION_VIEW_STATUSES = [\n 'complete',\n 'failed',\n] as const satisfies readonly RunNotificationViewStatus[]\n\nexport interface RunNotificationViewStages {\n analysis: { status: RunNotificationViewStatus }\n curation: {\n status: RunNotificationViewStatus\n curated?: number\n deprecated?: number\n curationSnapshot?: CurationSnapshot\n }\n proposals?: {\n status: RunNotificationViewStatus\n proposed?: number\n skipped?: number\n }\n}\n\nexport interface RunNotificationView {\n schemaVersion: typeof CURRENT_RUN_NOTIFICATION_SCHEMA_VERSION\n runId: string\n outcome: RunNotificationViewStatus\n verdictSummary: RunNotificationVerdictSummary\n stages: RunNotificationViewStages\n}\n\nconst VIEW_WORD: Record<RunNotificationStageStatus, RunNotificationViewStatus> = {\n done: 'complete',\n failed: 'failed',\n}\n\nexport function toRunNotificationView(notification: RunNotification): RunNotificationView {\n const { analysis, curation, proposals } = notification.stages\n return {\n ...notification,\n outcome: VIEW_WORD[notification.outcome],\n stages: {\n analysis: { ...analysis, status: VIEW_WORD[analysis.status] },\n curation: { ...curation, status: VIEW_WORD[curation.status] },\n ...(proposals === undefined ? {} : { proposals: { ...proposals, status: VIEW_WORD[proposals.status] } }),\n },\n }\n}\n\n/**\n * The two admissible stage key sets, sorted and joined — declared as DATA (2026-09-12, 422-22).\n *\n * TWO SETS, never \"the declared ones plus anything\" (422 D-13). The optional third member widened\n * what a stage set may BE by exactly one shape; a presence check for `proposals` beside a subset\n * check for the rest would readmit the undeclared member this equality exists to refuse, which is\n * the failure the exact-key idiom was chosen against in the first place.\n *\n * Stated here rather than inline in the guard so the admissible shapes are a value an oracle can\n * read and a reviewer can count. The pair comes first, then the triple.\n */\nexport const RUN_NOTIFICATION_STAGE_KEY_SETS = [\n 'analysis,curation',\n 'analysis,curation,proposals',\n] as const\n\n/** The exact top-level field set, sorted and joined. The record carries these five and no more. */\nexport const RUN_NOTIFICATION_FIELD_KEYS = 'outcome,runId,schemaVersion,stages,verdictSummary'\n\n/** Refusal for bytes that do not describe a notification this build can read. */\nexport class RunNotificationSchemaError extends Error {\n override readonly name = 'RunNotificationSchemaError'\n\n constructor(readonly detail: string) {\n super(\n `a stored run notification cannot be read: ${detail}. The row is written inside the ` +\n 'chain-terminal transaction from a typed record, so bytes that fail this guard were ' +\n 'written by another build rather than by a caller that got a field wrong.',\n )\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isCount(value: unknown): boolean {\n return typeof value === 'number' && Number.isInteger(value) && value >= 0\n}\n\n/**\n * Membership against a declared closed list (2026-09-12, 422-22).\n *\n * The guard asks the CONSTANT rather than re-spelling its members in an `||` chain, so a word this\n * build reads and a word it admits cannot drift apart. An inline pair was fine while the words\n * were spelled once; they are now spelled beside their type, and two spellings is one too many.\n */\nfunction isMember<T extends string>(members: readonly T[], value: unknown): value is T {\n return typeof value === 'string' && (members as readonly string[]).includes(value)\n}\n\n/**\n * The migration seam, keyed by source version with one version step per entry, so a later bump\n * has a home instead of an `if` in the guard. It is empty, so every stamp but the current one is\n * refused.\n */\nexport const RUN_NOTIFICATION_MIGRATIONS: Record<number, (doc: unknown) => unknown> = {}\n\n/**\n * The full-shape guard, checked by EXACT key set rather than by presence, behind a forward walk\n * over the migration seam above.\n *\n * Presence checks admit a record carrying an extra field, and an extra field on a row several\n * surfaces render is exactly how a payload grows a member nobody declared. The sorted-key\n * comparison is the `CurationTailReceipt` idiom for the same reason.\n *\n * The walk runs FIRST and only forwards, and the record is then checked against the CURRENT shape\n * in full, so a step that produced something malformed is refused here rather than travelling. A\n * record whose stamp is not the current one after the walk is refused by name — this build cannot\n * know what another contract means, and guessing is how a reader renders a field it does not\n * understand.\n */\nexport function guardRunNotification(value: unknown): RunNotification {\n if (!isRecord(value)) {\n throw new RunNotificationSchemaError('it is not an object')\n }\n\n const declared = value.schemaVersion\n let migrated: Record<string, unknown> = value\n if (\n typeof declared === 'number' &&\n Number.isInteger(declared) &&\n declared < CURRENT_RUN_NOTIFICATION_SCHEMA_VERSION\n ) {\n for (let from = declared; from < CURRENT_RUN_NOTIFICATION_SCHEMA_VERSION; from += 1) {\n const step = RUN_NOTIFICATION_MIGRATIONS[from]\n if (step === undefined) break\n const next = step(migrated)\n if (!isRecord(next)) {\n throw new RunNotificationSchemaError(\n `migrating it from schemaVersion ${String(from)} produced no record`,\n )\n }\n migrated = next\n }\n }\n\n if (Object.keys(migrated).sort().join(',') !== RUN_NOTIFICATION_FIELD_KEYS) {\n throw new RunNotificationSchemaError(\n `its field set is ${JSON.stringify(Object.keys(migrated).sort())}`,\n )\n }\n if (migrated.schemaVersion !== CURRENT_RUN_NOTIFICATION_SCHEMA_VERSION) {\n throw new RunNotificationSchemaError(\n `it declares schemaVersion ${String(migrated.schemaVersion)}, and this build reads ` +\n String(CURRENT_RUN_NOTIFICATION_SCHEMA_VERSION),\n )\n }\n if (typeof migrated.runId !== 'string' || migrated.runId === '') {\n throw new RunNotificationSchemaError('it names no run')\n }\n if (!isMember(RUN_NOTIFICATION_OUTCOMES, migrated.outcome)) {\n throw new RunNotificationSchemaError(`${String(migrated.outcome)} is not a chain outcome`)\n }\n\n const summary = migrated.verdictSummary\n if (!isRecord(summary) || !isCount(summary.total) || !isRecord(summary.byClass)) {\n throw new RunNotificationSchemaError('its verdict summary is not a summary')\n }\n for (const [className, count] of Object.entries(summary.byClass)) {\n if (!isCount(count)) {\n throw new RunNotificationSchemaError(`its ${className} count is not a count`)\n }\n }\n\n const stages = migrated.stages\n if (!isRecord(stages)) {\n throw new RunNotificationSchemaError('it reports no stages')\n }\n // TWO admissible sets, never \"anything plus the declared ones\" (422 D-13). The optional third\n // member widened what a stage set may BE by exactly one shape; a presence check for `proposals`\n // beside a subset check for the rest would readmit the undeclared member this equality exists\n // to refuse, which is the failure the exact-key idiom was chosen against in the first place.\n const stageKeys = Object.keys(stages).sort().join(',')\n if (!(RUN_NOTIFICATION_STAGE_KEY_SETS as readonly string[]).includes(stageKeys)) {\n throw new RunNotificationSchemaError(\n `its stage set is ${JSON.stringify(Object.keys(stages).sort())}`,\n )\n }\n const analysis = stages.analysis\n if (!isRecord(analysis) || !isMember(RUN_NOTIFICATION_STAGE_STATUSES, analysis.status)) {\n throw new RunNotificationSchemaError('its analysis stage reports no outcome')\n }\n const curation = stages.curation\n if (!isRecord(curation) || !isMember(RUN_NOTIFICATION_STAGE_STATUSES, curation.status)) {\n throw new RunNotificationSchemaError('its curation stage reports no outcome')\n }\n if ('curated' in curation && !isCount(curation.curated)) {\n throw new RunNotificationSchemaError('its curated count is not a count')\n }\n if ('deprecated' in curation && !isCount(curation.deprecated)) {\n throw new RunNotificationSchemaError('its deprecated count is not a count')\n }\n if ('curationSnapshot' in curation &&\n !CurationSnapshotSchema.safeParse(curation.curationSnapshot).success) {\n // Never include untrusted snapshot keys or identity values in diagnostics.\n throw new RunNotificationSchemaError('its curation snapshot is invalid')\n }\n\n // Checked only when PRESENT, and then checked in full (422 D-13). An absent stage is the\n // not-recorded fact above and needs no validation; a present one is rendered, so a malformed\n // proposal stage is refused here rather than handed to a surface that would print `undefined`.\n if ('proposals' in stages) {\n const proposals = stages.proposals\n if (!isRecord(proposals) || !isMember(RUN_NOTIFICATION_STAGE_STATUSES, proposals.status)) {\n throw new RunNotificationSchemaError('its proposal stage reports no outcome')\n }\n if ('proposed' in proposals && !isCount(proposals.proposed)) {\n throw new RunNotificationSchemaError('its proposed count is not a count')\n }\n if ('skipped' in proposals && !isCount(proposals.skipped)) {\n throw new RunNotificationSchemaError('its skipped count is not a count')\n }\n }\n\n return migrated as unknown as RunNotification\n}\n","// THE post-processing chip vocabulary (Phase 388, D-14 / D-15; narrowed Phase 404, D-01).\n//\n// One exported closed union, in one place, because the vocabulary appears in three: the bus\n// chip events the in-process tail emits, the read op that projects durable job state, and\n// the CLI's exit summary line. Three spellings of four words is not a duplication a reviewer\n// catches — it is the state in which the dashboard says \"queued\" while the CLI says\n// \"pending\" about the same row, and nothing is wrong with either of them.\n//\n// 2026-08-26 (Phase 404, D-01): the chip set is exactly `{analysis, curation}` and the\n// vocabulary is exactly `pending · running · done · failed`. The Issue engine left the spec on\n// 2026-08-25, so the structural member that used to answer for the unfilled triage slot has no\n// slot left to answer for, and a word no producer can produce is a word every consumer still\n// has to render. The chip side stopped reading and rendering the third id then.\n// 2026-09-02 (Phase 412): the job-kind layer followed — the reserved sixth job kind, the chain's\n// third derived id, the retired entity kind and the retired proposal arm left with the\n// Issue-slot cleanup.\n// 2026-10-17 (444-10, D-13): the vocabulary is `pending · running · complete · failed`; a done job row reads `complete`.\n\nimport { z } from 'zod'\n\nimport { jobConclusionKindValues } from '../job/job'\nimport type { JobConclusionKind } from '../job/job'\nimport type { RunNotificationView } from './run-notification'\nimport type { CurationSnapshot } from './curation-snapshot'\n\n/**\n * Declared in the order a stage passes through them.\n *\n * A runtime array rather than a bare type, because the projection and its tests both need to\n * enumerate the vocabulary, and a union that only exists at compile time cannot be walked.\n */\nexport const POST_PROCESSING_CHIP_STATUSES = [\n 'pending',\n 'running',\n 'complete',\n 'failed',\n] as const\n\nexport type PostProcessingChipStatus = (typeof POST_PROCESSING_CHIP_STATUSES)[number]\n\n/**\n * The two chips, named rather than indexed.\n *\n * Fixed members instead of a record keyed by stage name: the chip set is ratified and closed\n * (spec §4.1 — notify is not a chip), so a surface that renders both should fail to compile\n * when a third arrives rather than silently render half the truth. That compile error is the\n * point: it is what walked this narrowing through every consumer in Phase 404.\n */\nexport interface PostProcessingChips {\n analysis: PostProcessingChipStatus\n curation: PostProcessingChipStatus\n}\n\n/** Detail stages include the chip-less proposals stage; this does not widen the chip set. */\nexport type PostProcessingDetailStage = 'analysis' | 'curation' | 'proposals'\n\nexport const POST_PROCESSING_DETAIL_STAGES = [\n 'analysis',\n 'curation',\n 'proposals',\n] as const satisfies readonly PostProcessingDetailStage[]\n\n/**\n * Recorded job facts only. Producers omit missing facts and mask failure text before\n * publishing; absence never asserts a zero attempt count or an unrecorded timestamp.\n *\n * Two instants, two different facts: `claimedAt` is the lease a drainer holds right now and is\n * absent on every settled row, because a terminal transition releases it; `startedAt` is when the\n * work first began, and it survives the lease.\n */\nexport interface PostProcessingStageDetail {\n attempts?: number\n createdAt?: string\n claimedAt?: string\n startedAt?: string\n updatedAt?: string\n conclusionKind?: JobConclusionKind\n lastFailureKind?: string\n lastFailureReason?: string\n}\n\nexport const PostProcessingStageDetailSchema = z.object({\n attempts: z.number().int().nonnegative().optional(),\n createdAt: z.string().min(1).optional(),\n claimedAt: z.string().min(1).optional(),\n startedAt: z.string().min(1).optional(),\n updatedAt: z.string().min(1).optional(),\n conclusionKind: z.enum(jobConclusionKindValues).optional(),\n lastFailureKind: z.string().optional(),\n lastFailureReason: z.string().optional(),\n}).strict() satisfies z.ZodType<PostProcessingStageDetail>\n\n/**\n * Why a recorded curation snapshot was not served (423 D-15, Gap 2). The read degrades the\n * snapshot, never itself: chips, stage details and the notification are served either way.\n */\nexport type CurationSnapshotWithheldReason = 'masking-unavailable' | 'projection-refused'\n\nexport const CURATION_SNAPSHOT_WITHHELD_REASONS = [\n 'masking-unavailable',\n 'projection-refused',\n] as const satisfies readonly CurationSnapshotWithheldReason[]\n\nexport const CurationSnapshotWithheldSchema = z.object({\n reason: z.enum(CURATION_SNAPSHOT_WITHHELD_REASONS),\n}).strict() satisfies z.ZodType<{ reason: CurationSnapshotWithheldReason }>\n\n/**\n * Why a run's post-run chain was never enqueued (425 D-08). A gate run and an\n * outcome-excluded run both skip the whole chain (404 D-08), so their chips would otherwise\n * read `pending` forever. The fact is a SIBLING of the chip words, never a fifth word: the\n * four-word vocabulary above stays closed, and a surface renders it beside the chips.\n * 2026-10-17 (444-11, D-39): renamed from the exclusion fact; every surface prints `skipped (<word>)`.\n * 2026-10-18 (444-12, D-14): `no-verdict` is a finished row with no handoff and no logged verdict.\n */\nexport type PostProcessingSkipReason = 'gate-run' | 'outcome-excluded' | 'no-verdict'\n\nexport const POST_PROCESSING_SKIP_REASONS = [\n 'gate-run',\n 'outcome-excluded',\n 'no-verdict',\n] as const satisfies readonly PostProcessingSkipReason[]\n\nexport const PostProcessingSkippedSchema = z.object({\n reason: z.enum(POST_PROCESSING_SKIP_REASONS),\n}).strict() satisfies z.ZodType<{ reason: PostProcessingSkipReason }>\n\n/** The one spelling of each reason every renderer prints inside `skipped (…)`. */\nexport const POST_PROCESSING_SKIP_REASON_WORDS: Readonly<Record<PostProcessingSkipReason, string>> = {\n 'gate-run': 'gate run',\n 'outcome-excluded': 'outcome-excluded',\n 'no-verdict': 'no verdict',\n}\n\nexport interface PostProcessingStatus {\n runId: string\n chips: PostProcessingChips\n /** A missing job row leaves its stage absent, including on historical payloads. */\n stageDetails?: Partial<Record<PostProcessingDetailStage, PostProcessingStageDetail>>\n /** Validated completed curation, available before the proposals stage reaches terminal. */\n curationSnapshot?: CurationSnapshot\n /**\n * Present iff a recorded snapshot exists and could not be projected safely; never beside\n * curationSnapshot. One flag governs both the checkpoint copy and the notification's nested copy.\n */\n curationSnapshotWithheld?: { reason: CurationSnapshotWithheldReason }\n /**\n * Present iff the run's durable record carries a gate-run or outcome-excluded marker; never\n * derived from missing job rows, from the run's status or from a pushed frame.\n */\n skipped?: { reason: PostProcessingSkipReason }\n /**\n * Present only once the chain reached its terminal and wrote its one row (D-09). Absent is\n * the ordinary state of a chain still in flight — never rendered as a failure.\n */\n notification?: RunNotificationView\n}\n\nexport function isPostProcessingChipStatus(value: unknown): value is PostProcessingChipStatus {\n return (\n typeof value === 'string' &&\n (POST_PROCESSING_CHIP_STATUSES as readonly string[]).includes(value)\n )\n}\n","import { z } from 'zod'\n\nimport { runIdSchema } from '../run/run-id'\nimport type { RunId } from '../run/run-id'\nimport { asJobId } from './job-id'\nimport type { JobId } from './job-id'\n\nexport type JobKind =\n | 'chat'\n | 'analyze-run'\n | 'curate-memory'\n | 'consolidate'\n | 'propose-improvements'\n\n// 385 C6 (JOBQ-01): `failed` and `cancelled` are the two TERMINAL statuses the agent job\n// queue needs and the v47 contract lacked — a bounded-retry queue that cannot record\n// exhaustion has no way to stop, and a cooperative cancel has no state to land in.\nexport type JobStatus =\n | 'queued'\n | 'authored'\n | 'bundling'\n | 'committing'\n | 'done'\n | 'failed'\n | 'cancelled'\n\n// 422 D-16 (ADV-03): `unreadable_kind` is the conclusion a row reaches when this build cannot\n// read the KIND it was written under — a kind an earlier build declared and this one has since\n// retired. It is a CONCLUSION and not a kind, which is the whole point: the five-kind vocabulary\n// below stays exactly as strict as it was, and the row that cannot join it gets an outcome\n// instead of an exemption. Nothing ever handles such a row; it is landed permanently at claim\n// with its attempt spent, so the queue neither loops on it nor pretends it never existed.\nexport type JobConclusionKind =\n | 'no_issue'\n | 'needs_user_input'\n | 'insufficient_evidence'\n | 'knowledge_skipped_draft'\n | 'model_capability_error'\n | 'provider_error'\n | 'insufficient_model_output'\n | 'unreadable_kind'\n\n// 385 C6 (JOBQ-01): `attempts` is incremented at CLAIM (D-18), so a job that kills its host\n// every time still exhausts its bound instead of crash-looping. `createdAt`/`updatedAt` are\n// ISO strings minted by the injected ClockPort — never the ambient wall clock and never a\n// SQL-side default, or the D-03 logical dump can never be compared across an interrupted\n// history. (This package's module-discipline guard forbids naming that ambient API here,\n// even in prose, so the rule is stated rather than quoted.)\nexport interface Job {\n id: JobId\n kind: JobKind\n status: JobStatus\n runRef?: RunId\n summary: string\n conclusionKind?: JobConclusionKind\n attempts: number\n createdAt: string\n updatedAt: string\n}\n\n// Exported for the sibling job DTO modules only (385 plan 02). They enumerate the same kind\n// set, and a second hand-written literal list is how one of them ends up admitting a kind the\n// other refuses. It is not on the package barrel: the kind vocabulary consumers need is the\n// `JobKind` type, and publishing the array as well would invite a caller to iterate it and\n// build a parallel registry beside the declared one.\nexport const jobKindValues = [\n 'chat',\n 'analyze-run',\n 'curate-memory',\n 'consolidate',\n 'propose-improvements',\n] as const satisfies readonly JobKind[]\n\nconst jobStatusValues = [\n 'queued',\n 'authored',\n 'bundling',\n 'committing',\n 'done',\n 'failed',\n 'cancelled',\n] as const satisfies readonly JobStatus[]\n\n// Exported on the same terms as `jobKindValues`: for sibling modules and for the contract tests\n// that pin this vocabulary EXACTLY, never on the package barrel. A consumer that needs to talk\n// about a conclusion has the `JobConclusionKind` type; publishing the array would invite the\n// parallel registry the comment above warns about.\nexport const jobConclusionKindValues = [\n 'no_issue',\n 'needs_user_input',\n 'insufficient_evidence',\n 'knowledge_skipped_draft',\n 'model_capability_error',\n 'provider_error',\n 'insufficient_model_output',\n 'unreadable_kind',\n] as const satisfies readonly JobConclusionKind[]\n\n/**\n * Whether this build reads `value` as a job kind (422 D-16).\n *\n * A PREDICATE rather than the array, so a caller can ask the question without gaining a list it\n * could iterate into a second registry. The store asks it of raw column bytes before those bytes\n * reach `jobSchema`, which is what lets a row written under a retired kind be recognised and\n * landed instead of throwing out of the transaction that had just spent its attempt.\n */\nexport function isJobKind(value: unknown): value is JobKind {\n return typeof value === 'string' && (jobKindValues as readonly string[]).includes(value)\n}\n\nconst jobIdSchema = z.string().transform(asJobId)\n\nexport const jobSchema = z.object({\n id: jobIdSchema,\n kind: z.enum(jobKindValues),\n status: z.enum(jobStatusValues),\n runRef: runIdSchema.optional(),\n summary: z.string(),\n conclusionKind: z.enum(jobConclusionKindValues).optional(),\n // REQUIRED, not optional. A store reads its rows back through this schema, so an optional\n // field here would let a row that never recorded an attempt or a timestamp parse clean —\n // and the C6 break exists precisely so that row cannot exist.\n attempts: z.number().int().nonnegative(),\n createdAt: z.string().min(1),\n updatedAt: z.string().min(1),\n}).strict()\n","declare const jobIdBrand: unique symbol\n\nexport type JobId = string & { readonly [jobIdBrand]: 'JobId' }\n\nexport const asJobId = (value: string): JobId => value as JobId\n","import { z } from 'zod'\nimport { EvidenceAbsenceReasonSchema } from './evidence'\n\nexport type RecordingState = 'present' | 'absent'\nexport const RECORDING_STATES = [\n 'present', 'absent',\n] as const satisfies readonly RecordingState[]\nexport type RecordingContentType = 'video/webm' | 'video/mp4'\nexport const RECORDING_CONTENT_TYPES = [\n 'video/webm', 'video/mp4',\n] as const satisfies readonly RecordingContentType[]\nexport const RECORDING_REF_PREFIX = 'recording:'\n\nexport const RecordingRefSchema = z.strictObject({\n id: z.templateLiteral([RECORDING_REF_PREFIX, z.string()]),\n sha: z.string().regex(/^[a-f0-9]{64}$/),\n evidenceIncomplete: z.boolean().optional(),\n}).refine(ref => ref.id === `${RECORDING_REF_PREFIX}${ref.sha}`, {\n message: 'Recording ref id must contain its exact SHA and the recording prefix',\n})\nexport type RecordingRef = z.infer<typeof RecordingRefSchema>\n\nexport const RecordingEntrySchema = z.union([\n z.strictObject({\n state: z.literal(RECORDING_STATES[0]),\n ref: RecordingRefSchema,\n contentType: z.enum(RECORDING_CONTENT_TYPES),\n byteLength: z.number().int().nonnegative(),\n durationMs: z.number().finite().nonnegative().optional(),\n }),\n z.strictObject({\n state: z.literal(RECORDING_STATES[1]),\n reason: EvidenceAbsenceReasonSchema,\n evidenceIncomplete: z.boolean().optional(),\n }),\n])\nexport type RecordingEntry = z.infer<typeof RecordingEntrySchema>\n","// The canonical output contract (2026-09-28, Phase 431 plan 03 · D-03/D-07 · research A1).\n//\n// WHY A COMPANION AND NOT THE SCHEMA ITSELF. A runtime contract that brands a run id\n// (`z.string().transform(asRunId)`) or preserves an own `__proto__` variable (a transform behind the\n// record) cannot be converted in zod's OUTPUT mode: the converter refuses any transform. Before 431\n// the only answers were to omit the advertised output (the 397 degradation) or to advertise the\n// INPUT-mode document as though it were the output. The first withholds a contract that exists; the\n// second is a second recipe presented as the first.\n//\n// An `OutputContract` is one Standard Schema object with two faces. `validate` IS the runtime\n// schema's own validation — the same object, never a re-parse through a wire schema, so no\n// transform, refinement or preserved key can be lost. `jsonSchema.output` is an explicit document\n// derived from the runtime schema's own output conversion, where exactly the declared WIRE TERMINALS\n// below are described by the wire half their transform consumes. Every other unrepresentable\n// construct fails the derivation by name, so the document can never be an any-valued stand-in.\n\nimport { z } from 'zod'\n\nimport { VariableSnapshotSchema } from '../run/evidence'\nimport { runIdSchema } from '../run/run-id'\n\nexport type JsonSchemaDocument = Readonly<Record<string, unknown>>\n\ninterface StandardIssue {\n readonly message: string\n readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined\n}\n\ntype StandardResult<Output> =\n | { readonly value: Output; readonly issues?: undefined }\n | { readonly issues: ReadonlyArray<StandardIssue> }\n\ninterface StandardJsonOptions {\n readonly target: string\n readonly libraryOptions?: Record<string, unknown> | undefined\n}\n\nexport interface OutputContractStandardProps<Input, Output> {\n readonly version: 1\n readonly vendor: string\n readonly types?: { readonly input: Input; readonly output: Output } | undefined\n readonly validate: (\n value: unknown,\n options?: { readonly libraryOptions?: Record<string, unknown> | undefined } | undefined,\n ) => StandardResult<Output> | Promise<StandardResult<Output>>\n readonly jsonSchema: {\n readonly input: (options: StandardJsonOptions) => Record<string, unknown>\n readonly output: (options: StandardJsonOptions) => Record<string, unknown>\n }\n}\n\nexport interface OutputContract<Schema extends z.ZodType = z.ZodType> {\n readonly runtimeSchema: Schema\n readonly outputRepresentation: JsonSchemaDocument\n readonly '~standard': OutputContractStandardProps<z.input<Schema>, z.output<Schema>>\n}\n\nconst PUBLISHED_TARGET = 'draft-2020-12'\n\n/**\n * Transform-bearing schemas whose output, on the wire, is exactly their wire half.\n *\n * `runIdSchema`'s transform is the `asRunId` brand cast: the value out is the validated string in.\n * `VariableSnapshotSchema`'s transform only re-attaches the own `__proto__` entry the record\n * parser skipped, after validating it as an entry, so its output is the string-keyed entry map the\n * record half describes. Nothing else is admitted by default.\n */\nconst WIRE_TERMINALS: ReadonlyMap<z.ZodType, z.ZodType> = new Map<z.ZodType, z.ZodType>([\n [runIdSchema, runIdSchema.in],\n [VariableSnapshotSchema, VariableSnapshotSchema.in._zod.def.left],\n])\n\nfunction deepFreeze<Value>(value: Value): Value {\n if (typeof value !== 'object' || value === null || Object.isFrozen(value)) return value\n for (const nested of Object.values(value)) deepFreeze(nested)\n return Object.freeze(value)\n}\n\nfunction withoutDialect(document: Record<string, unknown>): Record<string, unknown> {\n const { $schema: _dialect, ...rest } = document\n return rest\n}\n\nconst DATA_KEYWORDS = new Set(['const', 'enum', 'default', 'examples', 'required'])\nconst NAME_MAP_KEYWORDS = new Set(['properties', 'patternProperties', '$defs', 'dependentSchemas'])\n\nfunction unrepresentableAt(schema: unknown, at: string): string | undefined {\n if (typeof schema !== 'object' || schema === null) return undefined\n if (Array.isArray(schema)) {\n for (const [index, entry] of schema.entries()) {\n const found = unrepresentableAt(entry, `${at}/${index}`)\n if (found !== undefined) return found\n }\n return undefined\n }\n if (Object.keys(schema).length === 0) return at\n for (const [key, entry] of Object.entries(schema)) {\n if (DATA_KEYWORDS.has(key)) continue\n const members: [string, unknown][] = NAME_MAP_KEYWORDS.has(key)\n ? Object.entries(entry as object)\n : [['', entry]]\n for (const [name, member] of members) {\n const found = unrepresentableAt(member, name === '' ? `${at}/${key}` : `${at}/${key}/${name}`)\n if (found !== undefined) return found\n }\n }\n return undefined\n}\n\n/**\n * The output-mode document of a runtime schema, with its declared wire terminals described by\n * their wire halves.\n *\n * Converted with `unrepresentable: 'any'` only so the override can replace the terminals; any empty\n * schema left afterwards is an unrepresentable node nobody declared, and it throws rather than\n * shipping as \"anything\".\n */\nexport function deriveWireOutputRepresentation(\n runtimeSchema: z.ZodType,\n terminals: ReadonlyMap<z.ZodType, z.ZodType> = WIRE_TERMINALS,\n): JsonSchemaDocument {\n const document = z.toJSONSchema(runtimeSchema, {\n target: PUBLISHED_TARGET,\n io: 'output',\n unrepresentable: 'any',\n override: (context) => {\n const wire = terminals.get(context.zodSchema as unknown as z.ZodType)\n if (wire === undefined) return\n const replacement = withoutDialect(\n z.toJSONSchema(wire, { target: PUBLISHED_TARGET, io: 'output' }) as Record<string, unknown>,\n )\n for (const key of Object.keys(context.jsonSchema)) delete (context.jsonSchema as Record<string, unknown>)[key]\n Object.assign(context.jsonSchema, replacement)\n },\n }) as Record<string, unknown>\n\n const unrepresentable = unrepresentableAt(withoutDialect(document), '#')\n if (unrepresentable !== undefined) {\n throw new Error(\n `output contract has an unrepresentable construct at ${unrepresentable}; declare its wire `\n + 'terminal or give the runtime schema a representable output',\n )\n }\n return deepFreeze(document)\n}\n\n/**\n * Pair a runtime schema with its explicit output document, as one Standard Schema object.\n *\n * `validate` delegates to the runtime schema, so the advertised contract can never enforce less\n * than `invokeFunction` does. `jsonSchema.input` is the runtime schema's own input conversion;\n * `jsonSchema.output` returns a fresh copy of the document for the one target it is written in.\n */\nexport function createOutputContract<Schema extends z.ZodType>(\n runtimeSchema: Schema,\n outputRepresentation: Record<string, unknown>,\n): OutputContract<Schema> {\n const representation = deepFreeze(structuredClone(outputRepresentation))\n const runtime = runtimeSchema['~standard']\n return Object.freeze({\n runtimeSchema,\n outputRepresentation: representation,\n '~standard': Object.freeze({\n version: 1 as const,\n vendor: 'agent-qa',\n validate: (value: unknown, options?: { readonly libraryOptions?: Record<string, unknown> | undefined }) =>\n runtime.validate(value, options) as StandardResult<z.output<Schema>> | Promise<StandardResult<z.output<Schema>>>,\n jsonSchema: Object.freeze({\n input: (options: StandardJsonOptions) => runtime.jsonSchema.input(options),\n output: (options: StandardJsonOptions) => {\n if (options.target !== PUBLISHED_TARGET) {\n throw new Error(\n `output contract publishes ${PUBLISHED_TARGET} only; ${String(options.target)} was requested`,\n )\n }\n return structuredClone(representation) as Record<string, unknown>\n },\n }),\n }),\n })\n}\n\n/** A runtime schema's output contract, with its document derived from the wire terminals. */\nexport function wireOutputContract<Schema extends z.ZodType>(\n runtimeSchema: Schema,\n): OutputContract<Schema> {\n return createOutputContract(runtimeSchema, deriveWireOutputRepresentation(runtimeSchema))\n}\n","// `runs.overview` — one completed run as a compact address map (Phase 431, D-06).\n//\n// A MAP, NOT A DOCUMENT. Every field is either identity, a verdict, a count the run stored or the\n// literal address another read op takes. Bodies, traces, evidence documents and bytes stay behind\n// those addresses. Output ids are plain strings; the input keeps the branded run-id codec.\n//\n// Addresses, by the op that takes them:\n// runs.artifact { runId, sha } screenshots, recordings\n// runs.evidence { runId, testIndex, stepIndex, subActionIndex?, kind } step evidence, ARIA\n// knowledge.brief.why { runId, testId, stepIndex } served brief\n// knowledge.record.show { recordId } used and learned records\n\nimport { z } from 'zod'\n\nimport { BRIEF_WHY_NO_TRACE_REASONS } from '../knowledge/review-verbs'\nimport { RecordChangeSchema } from '../knowledge/maintenance-views'\nimport { CurationBreakdownSchema, CurationBucketSchema } from '../notification/curation-snapshot'\nimport {\n CurationSnapshotWithheldSchema,\n POST_PROCESSING_CHIP_STATUSES,\n PostProcessingSkippedSchema,\n} from '../notification/post-processing-status'\nimport { EvidenceAbsenceReasonSchema, EvidenceKindSchema } from '../run/evidence'\nimport { RECORDING_CONTENT_TYPES } from '../run/recording'\nimport { runIdSchema } from '../run/run-id'\nimport { RUN_KNOWLEDGE_CONTENT_ABSENCE_REASONS } from './record-join'\nimport { RunDetailStepSchema, RunSummarySchema, RunTestDetailSchema } from './runs'\n\n/** Labels and one-line summaries keep this many Unicode code points, then a visible `…`. */\nexport const RUN_OVERVIEW_TEXT_MAX_CODE_POINTS = 160\nexport const RUN_OVERVIEW_TRUNCATION_INDICATOR = '…'\n\nexport const RunsOverviewInputSchema = z.object({\n runId: runIdSchema,\n}).strict()\n\nexport type RunsOverviewInput = z.infer<typeof RunsOverviewInputSchema>\n\nconst index = z.number().int().nonnegative()\nconst count = z.number().int().nonnegative()\n/** Read-time presence of the addressed bytes. Absent means UNKNOWN, never absent bytes. */\nconst present = z.boolean().optional()\nconst incomplete = z.literal(true).optional()\n\nexport const RunOverviewTextSchema = z.object({\n text: z.string(),\n truncated: z.literal(true).optional(),\n}).strict()\n\nexport const RunOverviewArtifactAddressSchema = z.object({\n runId: z.string(),\n sha: z.string().regex(/^[0-9a-f]{64}$/),\n}).strict()\n\nexport const RunOverviewEvidenceAddressSchema = z.object({\n runId: z.string(),\n testIndex: index,\n stepIndex: index,\n subActionIndex: index.optional(),\n kind: EvidenceKindSchema,\n}).strict()\n\nexport const RunOverviewBriefAddressSchema = z.object({\n runId: z.string(),\n testId: z.string(),\n stepIndex: index,\n}).strict()\n\nconst address = RunOverviewEvidenceAddressSchema\n\nconst absentEvidence = <K extends 'console' | 'network' | 'a11y' | 'variables'>(kind: K) =>\n z.object({\n kind: z.literal(kind),\n state: z.literal('absent'),\n reason: EvidenceAbsenceReasonSchema,\n evidenceIncomplete: incomplete,\n address,\n }).strict()\n\nexport const RunOverviewStepEvidenceSchema = z.object({\n console: z.union([\n z.object({\n kind: z.literal('console'), state: z.literal('present'),\n counts: z.object({ total: count, errors: count, warnings: count }).strict(), present, address,\n }).strict(),\n absentEvidence('console'),\n ]),\n network: z.union([\n z.object({\n kind: z.literal('network'), state: z.literal('present'),\n counts: z.object({ total: count, failed: count, errored: count }).strict(), present, address,\n }).strict(),\n absentEvidence('network'),\n ]),\n a11y: z.union([\n z.object({\n kind: z.literal('a11y'), state: z.literal('present'),\n counts: z.object({ minor: count, moderate: count, serious: count, critical: count }).strict(),\n present, address,\n }).strict(),\n absentEvidence('a11y'),\n ]),\n variables: z.union([\n z.object({\n kind: z.literal('variables'), state: z.literal('present'),\n counts: z.object({ count }).strict(), address,\n }).strict(),\n absentEvidence('variables'),\n ]),\n}).strict()\n\n/** ARIA is sub-action addressed and stores no numeric count, so none is reported. */\nexport const RunOverviewAriaSchema = z.union([\n z.object({ subActionIndex: index, state: z.literal('present'), present, address }).strict(),\n z.object({\n subActionIndex: index, state: z.literal('absent'), reason: EvidenceAbsenceReasonSchema,\n evidenceIncomplete: incomplete, address,\n }).strict(),\n])\n\nexport const RunOverviewScreenshotSchema = z.object({\n subActionIndex: index,\n sha: z.string().regex(/^[0-9a-f]{64}$/),\n present,\n evidenceIncomplete: incomplete,\n address: RunOverviewArtifactAddressSchema,\n}).strict()\n\n/**\n * One record a step was served. `kind` and `summary` come from the served line or the current\n * record; whenever either is missing, `unavailable` names why, so nothing is inferred from an id.\n */\nexport const RunOverviewRecordSchema = z.object({\n recordId: z.string(),\n channel: z.enum(['brief', 'read', 'caution']),\n kind: z.string().optional(),\n summary: RunOverviewTextSchema.optional(),\n unavailable: z.object({ reason: z.enum(RUN_KNOWLEDGE_CONTENT_ABSENCE_REASONS) }).strict().optional(),\n}).strict().refine(\n (record) => (record.kind === undefined || record.summary === undefined)\n === (record.unavailable !== undefined),\n { message: 'a record lacking its kind or summary must say why, and only then' },\n)\n\nexport const RunOverviewBriefSchema = z.object({\n address: RunOverviewBriefAddressSchema,\n trace: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('answered') }).strict(),\n z.object({ kind: z.literal('no-trace'), reason: z.enum(BRIEF_WHY_NO_TRACE_REASONS) }).strict(),\n ]),\n}).strict()\n\nexport const RunOverviewStepSchema = z.object({\n stepIndex: index,\n label: RunOverviewTextSchema.optional(),\n status: RunDetailStepSchema.shape.status,\n /** What the run-detail projection recorded; `unavailable` when this host holds no row. */\n capture: z.discriminatedUnion('state', [\n z.object({\n state: z.literal('recorded'),\n screenshots: z.array(RunOverviewScreenshotSchema),\n evidence: RunOverviewStepEvidenceSchema,\n aria: z.array(RunOverviewAriaSchema),\n }).strict(),\n z.object({ state: z.literal('unavailable') }).strict(),\n ]),\n /** What the handoff recorded about the served brief; `unavailable` when it holds no step. */\n knowledge: z.discriminatedUnion('state', [\n z.object({\n state: z.literal('recorded'),\n records: z.array(RunOverviewRecordSchema),\n brief: RunOverviewBriefSchema,\n }).strict(),\n z.object({ state: z.literal('unavailable') }).strict(),\n ]),\n}).strict()\n\nexport const RunOverviewRecordingSchema = z.union([\n z.object({\n state: z.literal('present'),\n address: RunOverviewArtifactAddressSchema,\n contentType: z.enum(RECORDING_CONTENT_TYPES),\n byteLength: count,\n durationMs: z.number().finite().nonnegative().optional(),\n present,\n evidenceIncomplete: incomplete,\n }).strict(),\n z.object({\n state: z.literal('absent'),\n reason: EvidenceAbsenceReasonSchema,\n evidenceIncomplete: incomplete,\n }).strict(),\n])\n\nexport const RunOverviewTestSchema = z.object({\n testIndex: index,\n testId: z.string(),\n name: RunOverviewTextSchema,\n outcome: RunTestDetailSchema.shape.outcome,\n recording: RunOverviewRecordingSchema,\n steps: z.array(RunOverviewStepSchema),\n}).strict()\n\nexport const RunOverviewLearnedSchema = z.object({\n knowledgeStore: z.enum(['bound', 'unbound']),\n curation: z.object({\n status: z.enum(POST_PROCESSING_CHIP_STATUSES),\n counts: z.object({ curated: count, deprecated: count }).strict().optional(),\n skipped: PostProcessingSkippedSchema.optional(),\n }).strict(),\n snapshot: z.discriminatedUnion('state', [\n z.object({\n state: z.literal('recorded'),\n breakdown: CurationBreakdownSchema,\n rows: z.array(z.object({\n recordId: z.string(),\n bucket: CurationBucketSchema,\n byRecordId: z.string().optional(),\n }).strict()),\n }).strict(),\n z.object({\n state: z.literal('withheld'),\n reason: CurationSnapshotWithheldSchema.shape.reason,\n }).strict(),\n z.object({ state: z.literal('not-recorded') }).strict(),\n ]),\n changes: z.array(z.object({\n recordId: z.string(),\n change: RecordChangeSchema.shape.change,\n atOrdinal: count,\n }).strict()),\n scanIncomplete: z.literal(true).optional(),\n}).strict()\n\nexport const RunOverviewProjectionSchema = z.object({\n runId: z.string(),\n scope: RunSummarySchema.shape.scope,\n recordedTargets: RunSummarySchema.shape.recordedTargets,\n aggregateVerdict: RunSummarySchema.shape.aggregateVerdict,\n buildOrdinal: index,\n startedAt: index,\n endedAt: index,\n tests: z.array(RunOverviewTestSchema),\n learned: RunOverviewLearnedSchema,\n}).strict()\n\nexport type RunOverviewText = z.infer<typeof RunOverviewTextSchema>\nexport type RunOverviewArtifactAddress = z.infer<typeof RunOverviewArtifactAddressSchema>\nexport type RunOverviewEvidenceAddress = z.infer<typeof RunOverviewEvidenceAddressSchema>\nexport type RunOverviewBriefAddress = z.infer<typeof RunOverviewBriefAddressSchema>\nexport type RunOverviewStepEvidence = z.infer<typeof RunOverviewStepEvidenceSchema>\nexport type RunOverviewAria = z.infer<typeof RunOverviewAriaSchema>\nexport type RunOverviewScreenshot = z.infer<typeof RunOverviewScreenshotSchema>\nexport type RunOverviewRecord = z.infer<typeof RunOverviewRecordSchema>\nexport type RunOverviewStep = z.infer<typeof RunOverviewStepSchema>\nexport type RunOverviewRecording = z.infer<typeof RunOverviewRecordingSchema>\nexport type RunOverviewTest = z.infer<typeof RunOverviewTestSchema>\nexport type RunOverviewLearned = z.infer<typeof RunOverviewLearnedSchema>\nexport type RunOverviewProjection = z.infer<typeof RunOverviewProjectionSchema>\n","declare const recordIdBrand: unique symbol\ndeclare const evidenceTokenBrand: unique symbol\n\nexport type RecordId = string & { readonly [recordIdBrand]: 'RecordId' }\nexport type EvidenceToken = string & { readonly [evidenceTokenBrand]: 'EvidenceToken' }\n\nexport const asRecordId = (value: string): RecordId => value as RecordId\nexport const asEvidenceToken = (value: string): EvidenceToken => value as EvidenceToken\n","import { sha256hex16 } from '../determinism/sha256'\nimport type { EvidenceToken } from './record-id'\n\nexport interface EvidenceTokenInput {\n attributingObservationId: string\n anchor: string\n buildOrdinal: number\n}\n\nfunction text(input: string): string {\n return `${input.length}:${input}`\n}\n\nexport function computeEvidenceToken(input: EvidenceTokenInput): EvidenceToken {\n const preimage = [\n input.attributingObservationId,\n input.anchor,\n String(input.buildOrdinal),\n ].map(text).join('')\n\n return sha256hex16(preimage) as EvidenceToken\n}\n","/**\n * D-05/D-06/D-07 bundle identity: one immutable content address over normalized,\n * deterministic fields. Mutable bundle state belongs to the separate manifest hash; the two\n * hashes have two jobs and must never share inputs.\n */\nimport type { BundleKind, FactSubtype } from '../delta/envelope'\nimport { canonicalJson } from '../determinism/canonical-json'\nimport { sha256hex } from '../determinism/sha256'\nimport type { Anchor } from '../identity/anchor'\nimport { normalizeAnchor } from '../identity/normalize-anchor'\nimport type { ScopeKey } from '../identity/scope-key'\nimport { normalizeAccessibleName } from '../screen/normalize-name'\nimport { asRecordId, type RecordId } from './record-id'\nimport { slugBranch } from './slug'\n\nexport const BUNDLE_ID_HASH_SUFFIX_LENGTH = 16\nexport const BUNDLE_SLUG_MAX_LENGTH = 48\n\ntype ElementFactSubtype = Exclude<FactSubtype, 'measurement'>\n\nexport type BundleDiscriminant =\n | {\n kind: 'fact'\n subtype: ElementFactSubtype\n elementRef: { role: string; name: string }\n /** Real Supersede evidence identifies the replacement validity-window generation. */\n validityWindowEvidenceToken?: string\n }\n | { kind: 'fact'; subtype: 'measurement'; metricKey: string }\n | { kind: 'procedure'; flowName: string; stepSignature: string }\n | { kind: 'caution'; errorKey: string }\n | { kind: 'unknown'; conflictRecordIds: readonly string[] }\n | { kind: 'policy'; ruleKey: string; validityWindowEvidenceToken?: string }\n\n/**\n * Immutable bundle identity core. `primaryAnchor` is stored normalized. LLM-authored prose\n * (including title, summary, and body) must never enter this type or the BNDL-02 identity hash.\n */\nexport interface BundleIdentityCore {\n kind: BundleKind\n subtype: FactSubtype | null\n primaryAnchor: Anchor\n scope: ScopeKey\n discriminantKey: string\n}\n\nexport interface BundleIdentityInput {\n kind: BundleKind\n subtype?: FactSubtype\n primaryAnchor: Anchor\n scope: ScopeKey\n discriminantKey: string\n}\n\nfunction text(input: string): string {\n return `${input.length}:${input}`\n}\n\nfunction normalizeText(input: string): string {\n return input.trim().replace(/\\s+/g, ' ').toLowerCase()\n}\n\nfunction normalizedErrorKey(input: string): string {\n const normalized = normalizeAnchor({ t: 'error', message: input })\n return normalized.t === 'error' ? normalized.message : input\n}\n\n/** D-06 deterministic per-kind discriminant, independent of all authored prose. */\nexport function deriveDiscriminantKey(discriminant: BundleDiscriminant): string {\n switch (discriminant.kind) {\n case 'fact':\n if (discriminant.subtype === 'measurement') {\n return canonicalJson({\n kind: discriminant.kind,\n metricKey: normalizeText(discriminant.metricKey),\n subtype: discriminant.subtype,\n })\n }\n return canonicalJson({\n elementRef: {\n name: normalizeAccessibleName(discriminant.elementRef.name),\n role: normalizeText(discriminant.elementRef.role),\n },\n kind: discriminant.kind,\n subtype: discriminant.subtype,\n ...(discriminant.validityWindowEvidenceToken === undefined ? {} : {\n validityWindowEvidenceToken: discriminant.validityWindowEvidenceToken,\n }),\n })\n case 'procedure':\n return canonicalJson({\n flowName: normalizeAccessibleName(discriminant.flowName),\n kind: discriminant.kind,\n stepSignature: discriminant.stepSignature,\n })\n case 'caution':\n return canonicalJson({\n errorKey: normalizedErrorKey(discriminant.errorKey),\n kind: discriminant.kind,\n })\n case 'unknown':\n return canonicalJson({\n conflictRecordIds: [...new Set(discriminant.conflictRecordIds)].sort(),\n kind: discriminant.kind,\n })\n case 'policy':\n return canonicalJson({\n kind: discriminant.kind,\n ruleKey: normalizeText(discriminant.ruleKey),\n ...(discriminant.validityWindowEvidenceToken === undefined ? {} : {\n validityWindowEvidenceToken: discriminant.validityWindowEvidenceToken,\n }),\n })\n }\n}\n\n/** Ordered procedure-step identity; length framing prevents concatenation ambiguity. */\nexport function computeStepSequenceSignature(orderedStepKeys: readonly string[]): string {\n return sha256hex(orderedStepKeys.map(text).join(''))\n}\n\n/** D-07 normalize-then-hash by construction; callers may safely pass a raw anchor. */\nexport function computeBundleIdentityHash(core: BundleIdentityInput): string {\n const identityCore: BundleIdentityCore = {\n kind: core.kind,\n subtype: core.subtype ?? null,\n primaryAnchor: normalizeAnchor(core.primaryAnchor),\n scope: core.scope,\n discriminantKey: core.discriminantKey,\n }\n return sha256hex(canonicalJson(identityCore))\n}\n\nfunction anchorSlugText(anchor: Anchor): string {\n switch (anchor.t) {\n case 'el':\n return `el-${anchor.role}-${anchor.name}`\n case 'page':\n return `page-${anchor.route}`\n case 'flow':\n return `flow-${anchor.name}`\n case 'error':\n return `error-${anchor.message}`\n case 'selector':\n return `sel-${anchor.literal}`\n case 'platform':\n return `platform-${anchor.platform}`\n }\n}\n\n/** Human-reviewable, non-authoritative id prefix bounded to one safe path segment. */\nexport function bundleSlug(kind: BundleKind, primaryAnchor: Anchor): string {\n const raw = `${kind}-${anchorSlugText(normalizeAnchor(primaryAnchor))}`\n const kebab = raw\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n const bounded = kebab.slice(0, BUNDLE_SLUG_MAX_LENGTH).replace(/-+$/g, '')\n return slugBranch(bounded)\n}\n\n/**\n * D-05 bundle id. The hash suffix alone is authoritative identity; the slug exists solely for\n * human PR review ergonomics.\n */\nexport function mintBundleId(core: BundleIdentityInput): RecordId {\n const identityHash = computeBundleIdentityHash(core)\n return asRecordId(\n `${bundleSlug(core.kind, core.primaryAnchor)}-${identityHash.slice(0, BUNDLE_ID_HASH_SUFFIX_LENGTH)}`,\n )\n}\n","import { sha256hex } from '../determinism/sha256'\nimport type { Anchor } from '../identity/anchor'\nimport type {\n BriefLine,\n CautionLine,\n LosslessServedBriefProofV1,\n ReadTrace,\n ServedAdmissionEvent,\n ServedBrief,\n ServedPromptTurn,\n} from './served-brief'\n\nconst FIELD = '\\x1f'\nconst RECORD = '\\x01'\n\nfunction text(value: string): string {\n return `${value.length}:${value}`\n}\n\nfunction numberValue(value: number): string {\n return String(value)\n}\n\nfunction booleanValue(value: boolean): string {\n return value ? '1' : '0'\n}\n\nfunction optionalNumber(value: number | undefined): string {\n return value === undefined ? '0' : `1${FIELD}${numberValue(value)}`\n}\n\nfunction record(tag: string, fields: string[]): string {\n return [tag, ...fields].join(FIELD)\n}\n\nfunction arrayValue(values: string[]): string {\n return [numberValue(values.length), ...values].join(FIELD)\n}\n\nfunction v2Scalar(value: string | number | boolean): string {\n if (typeof value === 'boolean') return text(booleanValue(value))\n return text(String(value))\n}\n\nfunction v2Array(values: string[]): string {\n return [v2Scalar(values.length), ...values.map(text)].join('')\n}\n\nfunction v2Record(tag: string, fields: string[]): string {\n return `${v2Scalar(tag)}${v2Array(fields)}`\n}\n\nfunction v2OptionalNumber(value: number | undefined): string {\n return v2Record(\n 'optional-number',\n value === undefined ? [v2Scalar(false)] : [v2Scalar(true), v2Scalar(value)],\n )\n}\n\nfunction serializeScope(scope: ServedBrief['scope']): string {\n return record('scope', [\n text(scope.tier),\n text(scope.key),\n ])\n}\n\nfunction serializeScopeV2(scope: ServedBrief['scope']): string {\n return v2Record('scope', [v2Scalar(scope.tier), v2Scalar(scope.key)])\n}\n\nfunction serializeAnchor(anchor: Anchor): string {\n switch (anchor.t) {\n case 'page':\n return record('anchor:page', [\n text(anchor.route),\n ])\n case 'flow':\n return record('anchor:flow', [\n text(anchor.name),\n ])\n case 'el':\n return record('anchor:el', [\n text(anchor.role),\n text(anchor.name),\n optionalNumber(anchor.ordinal),\n ])\n case 'platform':\n return record('anchor:platform', [\n text(anchor.platform),\n ])\n case 'selector':\n return record('anchor:selector', [\n text(anchor.literal),\n ])\n case 'error':\n return record('anchor:error', [\n text(anchor.message),\n ])\n }\n}\n\nfunction serializeAnchorV2(anchor: Anchor): string {\n switch (anchor.t) {\n case 'page':\n return v2Record('anchor:page', [v2Scalar(anchor.route)])\n case 'flow':\n return v2Record('anchor:flow', [v2Scalar(anchor.name)])\n case 'el':\n return v2Record('anchor:el', [\n v2Scalar(anchor.role),\n v2Scalar(anchor.name),\n v2OptionalNumber(anchor.ordinal),\n ])\n case 'platform':\n return v2Record('anchor:platform', [v2Scalar(anchor.platform)])\n case 'selector':\n return v2Record('anchor:selector', [v2Scalar(anchor.literal)])\n case 'error':\n return v2Record('anchor:error', [v2Scalar(anchor.message)])\n }\n}\n\nfunction serializeBriefLine(line: BriefLine): string {\n return record('brief-line', [\n text(line.id),\n text(line.kind),\n text(line.summary),\n numberValue(line.trust),\n text(line.status),\n booleanValue(line.servedAsCanary),\n text(line.tier),\n ])\n}\n\nfunction serializeBriefLineV2(line: BriefLine): string {\n return v2Record('brief-line', [\n v2Scalar(line.id),\n v2Scalar(line.kind),\n v2Scalar(line.summary),\n v2Scalar(line.trust),\n v2Scalar(line.status),\n v2Scalar(line.servedAsCanary),\n v2Scalar(line.tier),\n ])\n}\n\nfunction serializeReadTrace(trace: ReadTrace): string {\n return record('read-trace', [\n text(trace.id),\n text(trace.detailLevel),\n text(trace.bodyDigest),\n ])\n}\n\nfunction serializeReadTraceV2(trace: ReadTrace): string {\n return v2Record('read-trace', [\n v2Scalar(trace.id),\n v2Scalar(trace.detailLevel),\n v2Scalar(trace.bodyDigest),\n ])\n}\n\nfunction serializeCautionLine(line: CautionLine): string {\n return record('caution-line', [\n text(line.id),\n arrayValue(line.anchors.map(serializeAnchor)),\n text(line.summary),\n ])\n}\n\nfunction serializeCautionLineV2(line: CautionLine): string {\n return v2Record('caution-line', [\n v2Scalar(line.id),\n v2Array(line.anchors.map(serializeAnchorV2)),\n v2Scalar(line.summary),\n ])\n}\n\nfunction serializeAdmissionEventV2(event: ServedAdmissionEvent): string {\n return v2Record('admission-event', [\n v2Scalar(event.ordinal),\n v2Scalar(event.turnOrdinal),\n v2Scalar(event.surface),\n v2Scalar(event.id),\n v2Scalar(event.sourceId),\n v2Scalar(event.clusterKey),\n v2Scalar(event.renderedCost),\n v2Scalar(event.chargeRepeated),\n ])\n}\n\nfunction serializePromptTurnV2(turn: ServedPromptTurn): string {\n return v2Record('prompt-turn', [\n v2Scalar(turn.ordinal),\n v2Scalar(turn.turnOrdinal),\n v2Scalar(turn.runDate),\n v2Scalar(turn.policyL0),\n v2Scalar(turn.learnedL1),\n v2Scalar(turn.learnedL2),\n v2Scalar(turn.contextTier),\n v2Scalar(turn.volatileTier),\n v2Scalar(turn.policyDigest),\n v2Scalar(turn.contextTierDigest),\n v2Scalar(turn.volatileTierDigest),\n ])\n}\n\nfunction serializeProofV2(proof: LosslessServedBriefProofV1): string {\n return v2Record('lossless-proof', [\n v2Scalar(proof.schemaVersion),\n v2Scalar(proof.completeness),\n v2Scalar(proof.recordCap),\n v2Scalar(proof.combinedBudget),\n v2Array(proof.admissionEvents.map(serializeAdmissionEventV2)),\n v2Array(proof.promptTurns.map(serializePromptTurnV2)),\n ])\n}\n\nfunction canonicalServedBriefV1(brief: ServedBrief): string {\n return [\n 'served-brief:v1',\n serializeScope(brief.scope),\n numberValue(brief.asOfBuild),\n numberValue(brief.budget),\n text(brief.truncation),\n arrayValue(brief.channel1.map(serializeBriefLine)),\n arrayValue(brief.channel2.map(serializeReadTrace)),\n arrayValue(brief.channel3.map(serializeCautionLine)),\n ].join(RECORD)\n}\n\nfunction canonicalServedBriefV2(\n brief: ServedBrief & { proof: LosslessServedBriefProofV1 },\n): string {\n return v2Record('served-brief:v2', [\n serializeScopeV2(brief.scope),\n v2Scalar(brief.asOfBuild),\n v2Scalar(brief.budget),\n v2Scalar(brief.truncation),\n v2Array(brief.channel1.map(serializeBriefLineV2)),\n v2Array(brief.channel2.map(serializeReadTraceV2)),\n v2Array(brief.channel3.map(serializeCautionLineV2)),\n serializeProofV2(brief.proof),\n ])\n}\n\nexport function computeBriefDigest(brief: ServedBrief): string {\n return sha256hex(\n brief.proof === undefined\n ? canonicalServedBriefV1(brief)\n : canonicalServedBriefV2(\n brief as ServedBrief & { proof: LosslessServedBriefProofV1 },\n ),\n )\n}\n","import { z } from 'zod'\n\nimport { sha256hex } from '../determinism/sha256'\nimport { asRecordId } from '../ids/record-id'\nimport { computeBriefDigest } from './compute-brief-digest'\nimport type { LosslessServedBriefProofV1, ServedBrief } from './served-brief'\n\nexport const SERVED_BRIEF_PROOF_SCHEMA_VERSION = 2\n\nexport type LosslessServedBrief = ServedBrief & {\n proof: LosslessServedBriefProofV1\n}\n\nconst finiteNumberSchema = z.number().finite()\nconst nonnegativeIntegerSchema = finiteNumberSchema.int().nonnegative()\nconst nonemptyStringSchema = z.string().min(1)\nconst digestSchema = z\n .string()\n .regex(/^[0-9a-f]{64}$/, 'expected a lowercase SHA-256 hex digest')\nconst recordIdSchema = nonemptyStringSchema.transform(asRecordId)\n\nconst scopeKeySchema = z\n .object({\n tier: z.enum(['global', 'product', 'suite', 'test']),\n key: nonemptyStringSchema,\n })\n .strict()\n\nconst anchorSchema = z.discriminatedUnion('t', [\n z.object({ t: z.literal('page'), route: z.string() }).strict(),\n z.object({ t: z.literal('flow'), name: z.string() }).strict(),\n z\n .object({\n t: z.literal('el'),\n role: z.string(),\n name: z.string(),\n ordinal: nonnegativeIntegerSchema.optional(),\n })\n .strict(),\n z\n .object({\n t: z.literal('platform'),\n platform: z.enum(['web', 'android', 'ios']),\n })\n .strict(),\n z.object({ t: z.literal('selector'), literal: z.string() }).strict(),\n z.object({ t: z.literal('error'), message: z.string() }).strict(),\n])\n\nexport const BriefLineSchema = z\n .object({\n id: recordIdSchema,\n kind: z.string(),\n summary: z.string(),\n trust: finiteNumberSchema.nonnegative(),\n status: z.string(),\n servedAsCanary: z.boolean(),\n tier: z.string(),\n })\n .strict()\n\nconst readTraceSchema = z\n .object({\n id: recordIdSchema,\n detailLevel: z.string(),\n bodyDigest: z.string(),\n })\n .strict()\n\nconst cautionLineSchema = z\n .object({\n id: recordIdSchema,\n anchors: z.array(anchorSchema),\n summary: z.string(),\n })\n .strict()\n\nconst servedAdmissionEventSchema = z\n .object({\n ordinal: nonnegativeIntegerSchema,\n turnOrdinal: nonnegativeIntegerSchema,\n surface: z.enum([\n 'brief-line',\n 'search-result',\n 'read-body',\n 'caution',\n 'procedure-hint',\n ]),\n id: recordIdSchema,\n sourceId: nonemptyStringSchema,\n clusterKey: nonemptyStringSchema,\n renderedCost: nonnegativeIntegerSchema,\n chargeRepeated: z.boolean(),\n })\n .strict()\n\nconst runDateSchema = z\n .string()\n .regex(\n /^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$/,\n 'expected a YYYY-MM-DD UTC date',\n )\n\nconst servedPromptTurnSchema = z\n .object({\n ordinal: nonnegativeIntegerSchema,\n turnOrdinal: nonnegativeIntegerSchema,\n runDate: runDateSchema,\n policyL0: z.string(),\n learnedL1: z.string(),\n learnedL2: z.string(),\n contextTier: nonemptyStringSchema,\n volatileTier: nonemptyStringSchema,\n policyDigest: digestSchema,\n contextTierDigest: digestSchema,\n volatileTierDigest: digestSchema,\n })\n .strict()\n\nconst losslessProofSchema = z\n .object({\n schemaVersion: z.literal(SERVED_BRIEF_PROOF_SCHEMA_VERSION),\n completeness: z.literal('lossless'),\n recordCap: nonnegativeIntegerSchema,\n combinedBudget: nonnegativeIntegerSchema,\n admissionEvents: z.array(servedAdmissionEventSchema),\n promptTurns: z.array(servedPromptTurnSchema).min(1),\n })\n .strict()\n\nexport const LosslessServedBriefSchema = z\n .object({\n scope: scopeKeySchema,\n asOfBuild: nonnegativeIntegerSchema,\n budget: nonnegativeIntegerSchema,\n truncation: z.string(),\n channel1: z.array(BriefLineSchema),\n channel2: z.array(readTraceSchema),\n channel3: z.array(cautionLineSchema),\n briefDigest: digestSchema,\n proof: losslessProofSchema,\n })\n .strict()\n .superRefine((brief, context) => {\n for (const [index, event] of brief.proof.admissionEvents.entries()) {\n if (event.ordinal !== index) {\n context.addIssue({\n code: 'custom',\n path: ['proof', 'admissionEvents', index, 'ordinal'],\n message: 'expected a contiguous zero-based ordinal',\n })\n }\n if (\n index > 0 &&\n event.turnOrdinal < brief.proof.admissionEvents[index - 1].turnOrdinal\n ) {\n context.addIssue({\n code: 'custom',\n path: ['proof', 'admissionEvents', index, 'turnOrdinal'],\n message: 'expected nondecreasing turn order',\n })\n }\n }\n\n for (const [index, turn] of brief.proof.promptTurns.entries()) {\n if (turn.ordinal !== index) {\n context.addIssue({\n code: 'custom',\n path: ['proof', 'promptTurns', index, 'ordinal'],\n message: 'expected a contiguous zero-based ordinal',\n })\n }\n if (\n index > 0 &&\n turn.turnOrdinal < brief.proof.promptTurns[index - 1].turnOrdinal\n ) {\n context.addIssue({\n code: 'custom',\n path: ['proof', 'promptTurns', index, 'turnOrdinal'],\n message: 'expected nondecreasing turn order',\n })\n }\n\n const promptDigests = [\n ['policyDigest', turn.policyDigest, sha256hex(turn.policyL0)],\n ['contextTierDigest', turn.contextTierDigest, sha256hex(turn.contextTier)],\n ['volatileTierDigest', turn.volatileTierDigest, sha256hex(turn.volatileTier)],\n ] as const\n for (const [field, actual, expected] of promptDigests) {\n if (actual !== expected) {\n context.addIssue({\n code: 'custom',\n path: ['proof', 'promptTurns', index, field],\n message: 'prompt tier digest does not match its exact bytes',\n })\n }\n }\n }\n\n if (computeBriefDigest(brief) !== brief.briefDigest) {\n context.addIssue({\n code: 'custom',\n path: ['briefDigest'],\n message: 'brief digest does not match the lossless proof',\n })\n }\n })\n\nfunction structuralPath(path: readonly PropertyKey[]): string {\n return path.length === 0 ? '$' : path.map(String).join('.')\n}\n\nexport class LosslessServedBriefError extends Error {\n readonly paths: readonly string[]\n\n constructor(paths: readonly (readonly PropertyKey[])[]) {\n const structuralPaths = [...new Set(paths.map(structuralPath))].sort()\n super(`Invalid lossless ServedBrief at ${structuralPaths.join(', ')}`)\n this.name = 'LosslessServedBriefError'\n this.paths = structuralPaths\n }\n}\n\n/** Parse untrusted persisted evidence without exposing prompt contents in diagnostics. */\nexport function guardLosslessServedBrief(value: unknown): LosslessServedBrief {\n const parsed = LosslessServedBriefSchema.safeParse(value)\n if (!parsed.success) {\n throw new LosslessServedBriefError(parsed.error.issues.map((issue) => issue.path))\n }\n return parsed.data\n}\n","import type { Anchor } from '../identity/anchor'\nimport type { ScopeKey } from '../identity/scope-key'\nimport type { RecordId } from '../ids/record-id'\nimport type { SERVED_BRIEF_PROOF_SCHEMA_VERSION } from './guard-lossless-served-brief'\n\n/**\n * The `truncation` string the runner writes when NO knowledge reader is bound (Phase 407, D-16).\n *\n * BYTE-IDENTICAL to the literal `makeEmptyServedBrief` has always written, lifted here so that\n * the producer and every reader import ONE constant instead of spelling the sentence twice. It\n * matters because this string is the ONLY durable marker distinguishing \"this project has no\n * knowledge store configured\" from \"retrieval ran and served nothing\" — a distinction the\n * Knowledge panel must make (no store → no banner and a stated absence; served nothing → an\n * honest empty brief), and one that cannot be recovered from an empty channel list.\n *\n * NOT A RUNG. \"No reader bound\" is deliberately outside the {@link RETRIEVAL_RUNGS} ladder: a\n * project that never configured a knowledge root did not degrade, so there is nothing to grade\n * and no cause to name (D-16; `doctor` reports `skip`).\n */\nexport const NO_KNOWLEDGE_READER_TRUNCATION = 'no brief served (no knowledge reader bound)'\n\nexport interface BriefLine {\n id: RecordId\n kind: string\n summary: string\n trust: number\n status: string\n servedAsCanary: boolean\n tier: string\n}\n\nexport interface ReadTrace {\n id: RecordId\n detailLevel: string\n bodyDigest: string\n}\n\nexport interface CautionLine {\n id: RecordId\n anchors: Anchor[]\n summary: string\n}\n\nexport type ServedAdmissionSurface =\n | 'brief-line'\n | 'search-result'\n | 'read-body'\n | 'caution'\n | 'procedure-hint'\n\n/** One chronological exposure evaluated by the production serving authority. */\nexport interface ServedAdmissionEvent {\n ordinal: number\n turnOrdinal: number\n surface: ServedAdmissionSurface\n id: RecordId\n sourceId: string\n clusterKey: string\n renderedCost: number\n chargeRepeated: boolean\n}\n\n/** Exact model-visible prompt material captured when a production turn is assembled. */\nexport interface ServedPromptTurn {\n ordinal: number\n turnOrdinal: number\n runDate: string\n policyL0: string\n learnedL1: string\n learnedL2: string\n contextTier: string\n volatileTier: string\n policyDigest: string\n contextTierDigest: string\n volatileTierDigest: string\n}\n\nexport interface LosslessServedBriefProofV1 {\n schemaVersion: typeof SERVED_BRIEF_PROOF_SCHEMA_VERSION\n completeness: 'lossless'\n recordCap: number\n combinedBudget: number\n admissionEvents: ServedAdmissionEvent[]\n promptTurns: ServedPromptTurn[]\n}\n\nexport interface ServedBrief {\n scope: ScopeKey\n asOfBuild: number\n budget: number\n truncation: string\n channel1: BriefLine[]\n channel2: ReadTrace[]\n channel3: CautionLine[]\n briefDigest: string\n /** Absent on historical values that predate acceptance-grade byte evidence. */\n proof?: LosslessServedBriefProofV1\n}\n","import type { ScopeKey } from '../identity/scope-key'\nimport type { RunId } from '../run/run-id'\nimport type { ExecutionContext, RunStatus } from '../run/run-status'\nimport type { QuarantineAppliedEntry } from '../quarantine/quarantine-ledger'\nimport type { PlannerLimitsRecord } from '../config/planner-limits'\nimport type { MisdirectionRecordResult } from '../verdict/misdirection-evidence'\nimport type { PerTestOutcome } from './per-test-outcome'\n\nexport const CURRENT_HANDOFF_SCHEMA_VERSION = 2\n\nexport interface CompletedRunHandoff {\n schemaVersion: number\n runId: RunId\n scope: ScopeKey\n buildOrdinal: number\n /**\n * D-14 §6 gate-run exclusion. Internal validation runs (including M4's\n * verify-before-present gate and eval cassette replays) contribute zero run-outcome\n * counter changes. The runner stamps this literal marker before persisting the handoff,\n * making the decision durable and identical for incremental folds and full rebuilds.\n * Absent means an ordinary counted run.\n */\n excludedFromOutcomes?: true\n /**\n * D-10 carrier for verify-before-present gate runs (Phase 384, 2026-07-28). Marks a run\n * as an M4 verification gate run so 388 can propagate it onto the `analyze-run` job\n * payload and 393 can set it, with no second breaking handoff-schema change.\n *\n * C8-ratified: gate runs DO feed curation. This is a DISTINCT axis from\n * `excludedFromOutcomes` above — neither marker implies the other, and v51's\n * run-outcome projection continues to read `excludedFromOutcomes` alone. The\n * exclusion semantics of a gate run land in 388/393; 384 mints only the carrier.\n *\n * Only the literal marker is meaningful; absence denotes an ordinary run.\n */\n gateRun?: true\n executionContext: ExecutionContext\n aggregateVerdict: RunStatus\n configDigests: {\n suiteConfigDigest: string\n testConfigDigest: string\n }\n startedAt: number\n endedAt: number\n tests: PerTestOutcome[]\n /**\n * Phase 390 D-16: which committed ledger entries this run applied, resolved ONCE at run start.\n * The set is folded before the first member executes, so a mid-run ledger edit can never\n * retroactively change a running build — and the run's own record says exactly which\n * dispositions it was operating under, and until when.\n *\n * Absent on runs that applied nothing (the overwhelmingly common case).\n */\n quarantineApplied?: readonly QuarantineAppliedEntry[]\n /**\n * The planner limits this run's steps ran under, copied verbatim from the resolved\n * RunConfig, with the members whose own limits differ. Absent on runs whose producer recorded\n * none.\n */\n plannerLimits?: PlannerLimitsRecord\n /**\n * Phase 422 D-17/D-18: the circularity arbiter's per-record cross-check rows, recorded BESIDE\n * the verdicts rather than only inside them, so a reader that never resolves a verdict can\n * still see what was checked and what was not.\n *\n * ABSENT means the arbiter never ran — true of every handoff written before 422 and of every\n * run with no low-trust memory to check. An EMPTY array means it ran and had nothing to\n * record. The two are deliberately distinguishable, and the loader may neither synthesize the\n * member nor drop it; `misdirectionEvidence: []` is not a synonym for silence.\n *\n * Each row binds the run's pre-execution IDENTITY through `handoffBaseDigest`\n * ({@link import('../verdict/misdirection-evidence').misdirectionSourceDigest}), never this\n * document's own digest — which now covers the sidecar, so digesting it here would hash a\n * value containing its own hash.\n *\n * Optional-additive, so no version bump or migration is owed.\n */\n misdirectionEvidence?: readonly MisdirectionRecordResult[]\n}\n","// The circularity guard's evidence contracts (Phase 422, plan 11 — D-17/D-19/D-20).\n//\n// A no-trust-change verdict says \"the served memory was not the problem\". That is exactly the\n// sentence a misdirected author would write to shield the record that misled it, so the claim\n// has never been allowed to stand on its own word. Phase 389 made the CLAIM checkable: a bare\n// boolean had to be `true` when candidate or low-trust memory sat on the failing path. This\n// module makes the EVIDENCE checkable, in three pieces that are deliberately separate:\n//\n// D-17 — MEMBERSHIP IS CODE-OWNED. `deriveMemoryOnPath` reads the run's OWN served briefs.\n// The verdict may DECLARE `memoryOnPath`, but the declaration is compared against\n// recomputation and never substituted for it: a forged array (naming fewer records,\n// or downgrading a pre-promotion candidate to a probation canary) and an omitted\n// array are both powerless, because the gate is keyed on what the briefs say.\n//\n// D-20 — THE CROSS-CHECK IS COMPLETE OR IT IS NOT AN EXONERATION.\n// `aggregateMisdirectionEvidence` folds per-record rows under one law: ANY flipped\n// row makes the memory suspect and takes precedence; only ALL relevant rows held\n// permits the authored no-trust-change class; anything else — inconclusive, not-run,\n// or a record with no row at all — answers `unknown` with the unresolved siblings\n// DISCLOSED by name rather than quietly folded into the held majority.\n//\n// D-19 — THE ONE EXEMPTION IS ABSENCE, NOT BREAKAGE. A run with no evaluation root cannot\n// cross-check anything, so it keeps the declared boolean under an explicit\n// `backing: 'declared-only'` marker. A run whose root is present-but-broken has the\n// same empty evidence and a completely different meaning: it is an unbacked gated\n// posture, and `declared-only` is refused there. Collapsing the two would let every\n// broken root borrow the BYOM exemption.\n//\n// WHY THE ROW CARRIES A SOURCE DIGEST AND NOT THE HANDOFF'S OWN. Each row binds the run,\n// member test, failing step, decision ordinal and record it describes, plus the corpus,\n// profile and brief identities the check ran under. It must also bind the HANDOFF it was\n// computed against — but the handoff's final digest covers the verdicts, and a verdict now\n// carries these rows, so digesting the finished document would hash a value that contains its\n// own hash. `misdirectionSourceDigest` is the way out: the run's IDENTITY (id, scope, build\n// ordinal, config digests) is fixed before the first member executes and cannot move when a\n// later member outcome is appended, so it identifies the source without a self-hash cycle.\n//\n// Pure-sync over DTOs, no host APIs — the schema-package law.\n\nimport { z } from 'zod'\n\nimport { canonicalJson } from '../determinism/canonical-json'\nimport { sha256hex } from '../determinism/sha256'\nimport type { BriefLine } from '../brief/served-brief'\nimport type { CompletedRunHandoff } from '../handoff/completed-run-handoff'\nimport type { StepEvidence } from '../handoff/step-evidence'\nimport type { RecordId } from '../ids/record-id'\nimport { CROSS_CHECKS } from '../knowledge/gate-receipt'\nimport type { CrossCheck } from '../knowledge/gate-receipt'\n\n/**\n * The two ways the store itself declares a served record's trust was not established when it\n * was put on a step's path — `'candidate'` is the pre-promotion fold status, and\n * `'low-trust-active'` is an active record served as a CANARY, deliberately on probation to\n * gather outcome evidence. No minted threshold and no second spelling of the trust fold: both\n * words read a marker the serving path already wrote.\n */\nexport type MemoryOnPathTrust = 'candidate' | 'low-trust-active'\n// prettier-ignore\nexport const MEMORY_ON_PATH_TRUSTS = ['candidate', 'low-trust-active'] as const satisfies readonly MemoryOnPathTrust[]\n\n/** One low-trust record the run's own briefs put on a verdict's failing path. */\nexport interface MemoryOnPathEntry {\n readonly recordId: RecordId\n readonly trust: MemoryOnPathTrust\n}\n\n/**\n * One EXPOSURE — the same record served on two steps is two sites, because the cross-check\n * that clears it on one step says nothing about the other.\n */\nexport interface MemoryOnPathSite extends MemoryOnPathEntry {\n readonly stepIndex: number\n}\n\n/**\n * The one backing word, and it is an ABSENCE claim: \"no evaluation root existed, so nothing\n * was measured and the author's declaration is all there is\". Never a quality grade.\n */\nexport type MisdirectionBacking = 'declared-only'\n// prettier-ignore\nexport const MISDIRECTION_BACKINGS = ['declared-only'] as const satisfies readonly MisdirectionBacking[]\n\n/** The evaluation-root posture a cross-check ran under (D-19). */\nexport type MisdirectionRootPosture = 'eval-root' | 'no-eval-root' | 'broken-eval-root'\n// prettier-ignore\nexport const MISDIRECTION_ROOT_POSTURES = ['eval-root', 'no-eval-root', 'broken-eval-root'] as const satisfies readonly MisdirectionRootPosture[]\n\n/** Disclosed sampling of one cross-check row; `seedHonored` sits on the row beside it. */\nexport interface MisdirectionSamples {\n readonly k: number\n readonly seeds: readonly number[]\n readonly modelCalls: number\n}\n\n/**\n * ONE record's cross-check at ONE exposure. Every identity the check depended on is bound\n * here, so a row cannot be lifted from another run, member, step or corpus generation and\n * replayed as this verdict's exoneration.\n */\nexport interface MisdirectionRecordResult {\n readonly runId: string\n /** The member test index — the phase's join key, same axis as `Verdict.perTest`. */\n readonly perTest: number\n /** The failing step this exposure happened on. */\n readonly stepIndex: number\n /** Decision identity within the step. */\n readonly decisionOrdinal: number\n readonly recordId: RecordId\n /** {@link misdirectionSourceDigest} of the handoff — the run's identity, not its bytes. */\n readonly handoffBaseDigest: string\n readonly briefDigest: string\n readonly corpusDigest: string\n readonly profileDigest: string\n readonly crossCheck: CrossCheck\n readonly seedHonored: boolean\n readonly reason?: string\n readonly samples?: MisdirectionSamples\n}\n\n/**\n * The optional evidence block a verdict carries beside the frozen boolean. `crossCheck`,\n * `recordId`, `reason` and `samples` are the single-record summary shape the gate receipts\n * already speak; `results` is the ADDITIVE complete per-record ledger this plan requires, and\n * `backing` is the D-19 absence marker.\n */\nexport interface MisdirectionEvidence {\n readonly crossCheck: CrossCheck\n readonly results: readonly MisdirectionRecordResult[]\n readonly recordId?: RecordId\n readonly reason?: string\n readonly samples?: MisdirectionSamples\n readonly backing?: MisdirectionBacking\n}\n\n/** What {@link aggregateMisdirectionEvidence} folds: the recomputed sites and the claimed rows. */\nexport interface MisdirectionAggregationInput {\n readonly runId: string\n readonly perTest: number\n readonly handoffBaseDigest: string\n readonly sites: readonly MemoryOnPathSite[]\n readonly results: readonly MisdirectionRecordResult[]\n}\n\n/**\n * The fold's answer. `'held'` is the ONLY arm that permits a no-trust-change class; every\n * other arm names what is unresolved so a reader can see it rather than infer it.\n */\nexport type MisdirectionAggregate =\n | { readonly outcome: 'held'; readonly records: readonly RecordId[] }\n | { readonly outcome: 'flipped'; readonly suspect: readonly RecordId[] }\n | {\n readonly outcome: 'unknown'\n readonly inconclusive: readonly RecordId[]\n readonly notRun: readonly RecordId[]\n readonly unchecked: readonly RecordId[]\n }\n | { readonly outcome: 'evidence-refused'; readonly problems: readonly string[] }\n\n/** Thrown by {@link guardMisdirectionEvidence} on bytes that are not a complete block. */\nexport class MisdirectionEvidenceError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'MisdirectionEvidenceError'\n }\n}\n\n/**\n * The trust word for one served brief line, or `undefined` when the store's own markers say\n * the record's trust WAS established. Pre-promotion status is checked first: a candidate that\n * also rode a canary slot is still a candidate, which is the stronger disclosure.\n */\nexport function memoryOnPathTrustOf(line: BriefLine): MemoryOnPathTrust | undefined {\n if (line.status === 'candidate') return 'candidate'\n if (line.servedAsCanary) return 'low-trust-active'\n return undefined\n}\n\n/**\n * Every low-trust EXPOSURE across the given steps, in step order then brief order. One record\n * served on two steps yields two sites; one record served twice within a single step's brief\n * yields one.\n */\nexport function deriveMemoryOnPathSites(steps: readonly StepEvidence[]): MemoryOnPathSite[] {\n const sites: MemoryOnPathSite[] = []\n const seen = new Set<string>()\n for (const step of steps) {\n for (const line of step.servedBrief.channel1) {\n const trust = memoryOnPathTrustOf(line)\n if (trust === undefined) continue\n const key = siteKey(step.stepIndex, line.id)\n if (seen.has(key)) continue\n seen.add(key)\n sites.push({ stepIndex: step.stepIndex, recordId: line.id, trust })\n }\n }\n return sites\n}\n\n/**\n * The record-level fold of {@link deriveMemoryOnPathSites} — the exact shape a verdict's\n * `memoryOnPath` declares, computed from the briefs so the declaration can be CHECKED. A\n * record exposed as both a candidate and a canary reads `'candidate'`: the stronger of the two\n * disclosures survives the fold, so folding can never soften what a site recorded.\n */\nexport function deriveMemoryOnPath(steps: readonly StepEvidence[]): MemoryOnPathEntry[] {\n const byRecord = new Map<RecordId, MemoryOnPathTrust>()\n for (const site of deriveMemoryOnPathSites(steps)) {\n const previous = byRecord.get(site.recordId)\n if (previous === 'candidate') continue\n byRecord.set(site.recordId, site.trust)\n }\n return [...byRecord].map(([recordId, trust]) => ({ recordId, trust }))\n}\n\n/**\n * The run IDENTITY digest a cross-check row binds (see the header): id, scope, build ordinal\n * and config digests — all fixed before the first member executes. Deliberately NOT the\n * handoff's own digest, which would cover the verdicts that carry these rows.\n */\nexport function misdirectionSourceDigest(handoff: CompletedRunHandoff): string {\n return sha256hex(\n canonicalJson({\n runId: handoff.runId,\n scope: handoff.scope,\n buildOrdinal: handoff.buildOrdinal,\n configDigests: handoff.configDigests,\n }),\n )\n}\n\n/** The one separator every composite key in this file joins on. */\nconst EVIDENCE_KEY_SEPARATOR = '\\u001f'\n\n/**\n * The evidence key: one EXPOSURE, not one record (see {@link MemoryOnPathSite}).\n *\n * U+001F BETWEEN THE COMPONENTS, and spelled as an escape so the separator survives a reformat.\n * `RecordId` is an unconstrained branded string and `stepIndex` is decimal, so bare\n * concatenation mints ONE key for `(1, '2abc')` and `(12, 'abc')`. This key gates memory\n * removal: a collision either hides a real exposure from `sites` — letting the fold reach\n * `held`, the only arm that exonerates — or reads two distinct rows as one conflicting pair.\n * `exposureKey` and `adversarialTupleKey` pin the same separator for the same reason.\n */\nfunction siteKey(stepIndex: number, recordId: RecordId): string {\n return `${String(stepIndex)}${EVIDENCE_KEY_SEPARATOR}${recordId}`\n}\n\n/**\n * Fold the claimed rows against the recomputed sites (D-20).\n *\n * THE KEY IS THE EXPOSURE, NOT THE RECORD. A record served on two steps is cross-checked\n * twice, and the run that cleared it on the first step says nothing about the second: keying\n * by record would read the second row as a duplicate of the first and REFUSE the pair, which\n * is how a real second-step flip disappears behind a first-step hold. Keying by exposure keeps\n * both rows, so the flip survives to the law below and a record covered on only one of its two\n * exposures reads `unchecked` rather than held.\n *\n * Key integrity runs FIRST and is fail-closed: a row minted against another run or member, a\n * row whose source-digest identity is not this handoff's, a row naming an exposure no brief\n * recorded, and two rows for one exposure are each `'evidence-refused'`. Only then does the\n * cross-check law apply — flipped takes precedence, all-held permits the class, and every\n * other shape answers `'unknown'` naming its unresolved records.\n *\n * Every answer is stated at RECORD level even though the fold is keyed per exposure, because\n * trust moves against a record. Harm names only the records a flip actually supports; a held\n * sibling of a flipped record is never labelled causal, and it stays visible in `memoryOnPath`\n * regardless — disclosed, not accused.\n */\nexport function aggregateMisdirectionEvidence(\n input: MisdirectionAggregationInput,\n): MisdirectionAggregate {\n const exposedRecords: RecordId[] = []\n for (const site of input.sites) {\n if (!exposedRecords.includes(site.recordId)) exposedRecords.push(site.recordId)\n }\n const requiredKeys = new Set(input.sites.map((site) => siteKey(site.stepIndex, site.recordId)))\n\n const problems: string[] = []\n const byKey = new Map<string, MisdirectionRecordResult>()\n for (const row of input.results) {\n const where = `${row.recordId} at step ${row.stepIndex}`\n if (row.runId !== input.runId) {\n problems.push(`row for ${where} was minted against run ${row.runId}`)\n continue\n }\n if (row.perTest !== input.perTest) {\n problems.push(`row for ${where} was minted against member test ${row.perTest}`)\n continue\n }\n if (row.handoffBaseDigest !== input.handoffBaseDigest) {\n problems.push(`row for ${where} names a source-digest identity from another run`)\n continue\n }\n const key = siteKey(row.stepIndex, row.recordId)\n if (!requiredKeys.has(key)) {\n problems.push(`row for ${where}, an exposure no served brief recorded on this path`)\n continue\n }\n if (byKey.has(key)) {\n problems.push(`a second, conflicting row for ${where}`)\n continue\n }\n byKey.set(key, row)\n }\n if (problems.length > 0) return { outcome: 'evidence-refused', problems }\n\n /** Records with at least one exposure whose row reads `check`. */\n const recordsWithCheck = (check: CrossCheck): RecordId[] =>\n exposedRecords.filter((recordId) =>\n input.sites.some(\n (site) =>\n site.recordId === recordId &&\n byKey.get(siteKey(site.stepIndex, site.recordId))?.crossCheck === check,\n ),\n )\n\n const suspect = recordsWithCheck('flipped')\n if (suspect.length > 0) return { outcome: 'flipped', suspect }\n\n const inconclusive = recordsWithCheck('inconclusive')\n const notRun = recordsWithCheck('not-run')\n const unchecked = exposedRecords.filter((recordId) =>\n input.sites.some(\n (site) => site.recordId === recordId && !byKey.has(siteKey(site.stepIndex, site.recordId)),\n ),\n )\n if (inconclusive.length > 0 || notRun.length > 0 || unchecked.length > 0) {\n return { outcome: 'unknown', inconclusive, notRun, unchecked }\n }\n\n return { outcome: 'held', records: exposedRecords }\n}\n\nconst recordIdSchema = z.custom<RecordId>(\n (value) => typeof value === 'string' && value.length > 0,\n { message: 'expected a non-empty RecordId' },\n)\nconst nonEmpty = z.string().min(1)\nconst samplesSchema = z\n .object({\n k: z.number().int().min(1),\n seeds: z.array(z.number().int()),\n modelCalls: z.number().int().nonnegative(),\n })\n .strict()\n\n/**\n * The wire shape of ONE declared on-path entry (422-12).\n *\n * Minted here rather than hand-rolled at each boundary: three readers now validate a PRESENT\n * `Verdict.memoryOnPath` — the handoff loader, the analysis-artifact guard and the strict\n * cassette parser — and three hand-rolled spellings of a two-field shape are three guards free\n * to drift from each other. The trust word is read from {@link MEMORY_ON_PATH_TRUSTS}, so the\n * closed vocabulary is still declared exactly once.\n */\nexport const MemoryOnPathEntrySchema = z\n .object({\n recordId: recordIdSchema,\n trust: z.enum(MEMORY_ON_PATH_TRUSTS),\n })\n .strict()\n\n/** The wire shape of one per-record row — every identity required, nothing extra tolerated. */\nexport const MisdirectionRecordResultSchema = z\n .object({\n runId: nonEmpty,\n perTest: z.number().int().nonnegative(),\n stepIndex: z.number().int().nonnegative(),\n decisionOrdinal: z.number().int().nonnegative(),\n recordId: recordIdSchema,\n handoffBaseDigest: nonEmpty,\n briefDigest: nonEmpty,\n corpusDigest: nonEmpty,\n profileDigest: nonEmpty,\n crossCheck: z.enum(CROSS_CHECKS),\n seedHonored: z.boolean(),\n reason: z.string().optional(),\n samples: samplesSchema.optional(),\n })\n .strict()\n\n/** The wire shape of the whole block. `results` is REQUIRED — an absent ledger is not a block. */\nexport const MisdirectionEvidenceSchema = z\n .object({\n crossCheck: z.enum(CROSS_CHECKS),\n results: z.array(MisdirectionRecordResultSchema),\n recordId: recordIdSchema.optional(),\n reason: z.string().optional(),\n samples: samplesSchema.optional(),\n backing: z.literal('declared-only').optional(),\n })\n .strict()\n\n/**\n * The one gate stored or foreign evidence bytes cross. Strict on purpose: an unrecognised\n * member is REFUSED rather than dropped, because a dropped member is a claim a reader never\n * sees, and this block exists to make a claim visible.\n */\n/**\n * Present-implies-valid for the two additive circularity members a stored verdict may carry\n * (422-12, D-17). ONE spelling for every reader that admits verdict bytes — the handoff loader's\n * `rootCause` predicate, the analysis-artifact guard, and any later reader of the same pair.\n *\n * A dropped member is a claim no reader ever sees, and these members exist to make a claim\n * visible, so a PRESENT-but-malformed member is refused rather than stripped. Absence stays\n * legal on every verdict written before 422, and a present `memoryOnPath` must be a real ARRAY\n * of complete entries: the declaration is what the validator recomputes against, so a\n * half-spelled one is a claim no gate can check.\n *\n * Deliberately NOT a total shape check for a verdict — each reader keeps its own rules about\n * class, producer and evidence depth. This answers only the circularity half.\n */\nexport function hasMisdirectionMemberShapes(value: Record<string, unknown>): boolean {\n if ('memoryOnPath' in value) {\n const declared = value.memoryOnPath\n if (!Array.isArray(declared)) return false\n if (!declared.every((entry) => MemoryOnPathEntrySchema.safeParse(entry).success)) return false\n }\n if (\n 'misdirectionRuledOut' in value &&\n !MisdirectionEvidenceSchema.safeParse(value.misdirectionRuledOut).success\n ) {\n return false\n }\n return true\n}\n\nexport function guardMisdirectionEvidence(value: unknown): MisdirectionEvidence {\n const parsed = MisdirectionEvidenceSchema.safeParse(value)\n if (!parsed.success) {\n throw new MisdirectionEvidenceError(\n `misdirectionRuledOut is not a complete evidence block: ${parsed.error.issues\n .map((issue) => `${issue.path.join('.') || '(root)'} ${issue.message}`)\n .join('; ')}`,\n )\n }\n return parsed.data as MisdirectionEvidence\n}\n","// The per-condition verdict block (439 D-02, D-07, D-10). Type-only DTOs plus their key sets and\n// one reader predicate; the runner computes the verdicts, readers keep reading whatever shipped.\n\nexport const CONDITION_VERDICTS = ['met', 'not-met', 'unverified', 'inconclusive'] as const\nexport type ConditionVerdict = (typeof CONDITION_VERDICTS)[number]\n\n/** The runner check that changed a condition's verdict, when one did. */\nexport const CONDITION_GUARDS = [\n 'quote-not-in-step',\n 'not-covered',\n 'citation-missing',\n 'admits-not-done',\n 'open-dialog',\n 'limit',\n 'narrowed',\n 'file',\n 'no-reload',\n 'visual-text-only',\n 'verifier-error',\n] as const\nexport type ConditionGuard = (typeof CONDITION_GUARDS)[number]\n\n/** What a condition needs beyond a cited line, as the verifier tagged it. */\nexport const CONDITION_NEEDS = ['visual', 'persistence', 'limit-max', 'limit-min', 'file'] as const\nexport type ConditionNeed = (typeof CONDITION_NEEDS)[number]\n\n/** The part of what the verifier was given that a citation points at. */\nexport const CITATION_SOURCES = [\n 'start-screen',\n 'final-screen',\n 'action',\n 'read',\n 'carried',\n 'screenshot',\n] as const\nexport type CitationSource = (typeof CITATION_SOURCES)[number]\n\n/** How the step ended when the block was recorded. */\nexport const CONDITION_ENDINGS = [\n 'completion',\n 'give-up',\n 'infeasible',\n 'limit-stop',\n 'timeout',\n 'cancelled',\n] as const\nexport type ConditionEnding = (typeof CONDITION_ENDINGS)[number]\n\n/**\n * One citation as checked by the runner. `found` is where the runner looked; a 'screenshot'\n * citation cannot be checked and is recorded 'unchecked'. `source` is where the quote was found.\n */\nexport interface ConditionCitation {\n source: CitationSource\n quote: string\n found: boolean | 'unchecked'\n}\n\n/** The runner's comparison of a saved file with the expected name and text. */\nexport interface ConditionFileCheck {\n name: 'match' | 'differs'\n content: 'match' | 'differs' | 'unverified'\n firstDifference?: string\n}\n\n/** One requested condition. Every text field is masked and bounded before record. */\nexport interface ConditionRecord {\n /** The step words this condition covers. */\n quote: string\n /** The runner's final verdict. */\n verdict: ConditionVerdict\n /** The model's verdict, present only when a guard changed it. */\n judged?: ConditionVerdict\n guard?: ConditionGuard\n needs?: ConditionNeed\n reason: string\n citations: ConditionCitation[]\n file?: ConditionFileCheck\n}\n\n/** An open dialog on the final screen and how the verifier accounted for it. */\nexport interface OpenDialogAccount {\n name: string\n account: 'bears-on-condition' | 'requested' | 'unrelated' | 'unaccounted'\n}\n\nexport interface ConditionVerdictsEvidence {\n ending: ConditionEnding\n conditions: ConditionRecord[]\n openDialogs?: OpenDialogAccount[]\n}\n\nexport const CONDITION_RECORD_KEYS = [\n 'quote',\n 'verdict',\n 'judged',\n 'guard',\n 'needs',\n 'reason',\n 'citations',\n 'file',\n] as const satisfies readonly (keyof ConditionRecord)[]\n\nexport const CONDITION_VERDICTS_EVIDENCE_KEYS = [\n 'ending',\n 'conditions',\n 'openDialogs',\n] as const satisfies readonly (keyof ConditionVerdictsEvidence)[]\n\nconst VERIFIER_ENDINGS: readonly ConditionEnding[] = [\n 'completion',\n 'give-up',\n 'infeasible',\n 'limit-stop',\n]\n\n/**\n * True when the verifier's judgment left the step unproven rather than failed: nothing is not met,\n * no open dialog bears on a condition, and something is unverified, inconclusive or unaccounted.\n * Timeout and cancelled blocks are recorded facts, not judgments, so they never count.\n */\nexport function stepOutcomeUnproven(step: {\n conditionVerdicts?: ConditionVerdictsEvidence\n}): boolean {\n const block = step.conditionVerdicts\n if (block === undefined || !VERIFIER_ENDINGS.includes(block.ending)) return false\n const dialogs = block.openDialogs ?? []\n if (block.conditions.some((condition) => condition.verdict === 'not-met')) return false\n if (dialogs.some((dialog) => dialog.account === 'bears-on-condition')) return false\n return (\n block.conditions.some(\n (condition) => condition.verdict === 'unverified' || condition.verdict === 'inconclusive',\n ) || dialogs.some((dialog) => dialog.account === 'unaccounted')\n )\n}\n","import { RecordedRetrievalRungSchema } from '../brief/retrieval-rung'\nimport { ServedRetrievalTraceV1Schema } from '../brief/retrieval-trace'\nimport { CURRENT_HANDOFF_SCHEMA_VERSION } from './completed-run-handoff'\nimport type { CompletedRunHandoff } from './completed-run-handoff'\nimport {\n createVersionGuard,\n VersionGuardError,\n} from '../versioning/create-version-guard'\nimport type { MigrationRegistry } from '../versioning/create-version-guard'\nimport { isVerdictClass } from '../verdict/verdict'\nimport {\n hasMisdirectionMemberShapes,\n MisdirectionRecordResultSchema,\n misdirectionSourceDigest,\n} from '../verdict/misdirection-evidence'\nimport { canonicalJson } from '../determinism/canonical-json'\nimport { sha256hex } from '../determinism/sha256'\nimport { screenStateHash } from '../determinism/screen-hash'\nimport type { StepEvidence } from './step-evidence'\nimport {\n CITATION_SOURCES,\n CONDITION_ENDINGS,\n CONDITION_GUARDS,\n CONDITION_NEEDS,\n CONDITION_VERDICTS,\n} from './condition-evidence'\n\n/** Thrown when a stored handoff's `schemaVersion` is not {@link CURRENT_HANDOFF_SCHEMA_VERSION}. */\nexport class HandoffVersionError extends VersionGuardError {\n constructor(found: number, supported: number) {\n super('CompletedRunHandoff', found, supported)\n this.name = 'HandoffVersionError'\n }\n}\n\nexport const HANDOFF_MIGRATIONS: MigrationRegistry = {}\n\nfunction isNonArrayObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/**\n * Validates an ElementInfo member of `stateBefore.elements` at the VALUE level the\n * load-boundary consumers operate on: locatorForElement applies `.trim()` to attribute\n * values and `.replaceAll()` to attribute/label values, and elementAnchor mints `el`\n * anchors from `role`/`nameNormalized` that normalizeAnchor string-normalizes\n * (normalizeHumanText). Rejects no honest document: `role` and `nameNormalized` are\n * required strings on ElementInfo, `attributes` is Record<string,string>, and every\n * ElementLabels member is an optional string.\n */\nfunction hasCompleteElementShape(value: unknown): boolean {\n if (!isNonArrayObject(value)) return false\n if (typeof value.role !== 'string') return false\n if (typeof value.nameNormalized !== 'string') return false\n const attributes = value.attributes\n const labels = value.labels\n return (\n isNonArrayObject(attributes) &&\n Object.values(attributes).every((member) => typeof member === 'string') &&\n isNonArrayObject(labels) &&\n Object.values(labels).every((member) => typeof member === 'string')\n )\n}\n\nfunction hasCompleteStateBeforeShape(stateBefore: unknown): boolean {\n if (!isNonArrayObject(stateBefore)) return false\n if ('url' in stateBefore && typeof stateBefore.url !== 'string') return false\n return Array.isArray(stateBefore.elements) && stateBefore.elements.every(hasCompleteElementShape)\n}\n\n/**\n * Validates a `subActions` element against the consumer-dereferenced surface: actionRefs\n * applies the `in` operator to `plannedAction`, resolvedElementEvidence walks\n * `stateBefore.elements`, and resolvedActionRefs flatMaps `grounding.attempts` for\n * EVERY subAction — so a present `grounding` must be a non-array object and present\n * `attempts` an array of non-array objects (absence stays legal: the consumer's `?? []`\n * handles it; attempt interiors stay unvalidated because the consumer's `outcome`\n * strict-equality and `resolvedRef` undefined-check reads are crash-safe on any\n * non-null object). classifySubActionRoute reads BOTH `stateBefore.url` and\n * `stateAfter?.url`, and when both are defined and differ it mints the AFTER leg as\n * the navigated `page` Anchor route normalizeAnchor trims — so both urls must be\n * strings when present. `stateAfter` absence stays legal (the consumer's optional\n * chain handles it); when present it must be a non-array object, and its interiors\n * beyond `url` stay unvalidated because no load-boundary consumer dereferences them.\n * `stateBefore.platform` stays unvalidated — its only read is an absence-safe\n * identity join.\n */\nfunction hasCompleteSubActionShape(value: unknown): boolean {\n if (!isNonArrayObject(value)) return false\n if (!isNonArrayObject(value.plannedAction)) return false\n if ('grounding' in value) {\n const grounding = value.grounding\n if (!isNonArrayObject(grounding)) return false\n if (\n 'attempts' in grounding &&\n (!Array.isArray(grounding.attempts) ||\n !grounding.attempts.every(isNonArrayObject))\n ) {\n return false\n }\n }\n if (!hasCompleteStateBeforeShape(value.stateBefore)) return false\n // 2026-10-19 (444.1-08, D-14): curation dereferences the dispatch pair as it does the planner's.\n if ('healedDispatch' in value) {\n const healed = value.healedDispatch\n if (!isNonArrayObject(healed) || !isNonArrayObject(healed.action)) return false\n if (!hasCompleteStateBeforeShape(healed.stateBefore)) return false\n }\n if ('stateAfter' in value) {\n const stateAfter = value.stateAfter\n if (!isNonArrayObject(stateAfter)) return false\n if ('url' in stateAfter && typeof stateAfter.url !== 'string') return false\n }\n return true\n}\n\n/**\n * Mirrors the six-kind Anchor union (discriminant `t` plus its payload) so every\n * guard-admitted `citedAnchors` member survives normalizeAnchor in the curator drain (WR-02).\n */\nfunction isAnchorShape(value: unknown): boolean {\n if (!isNonArrayObject(value)) return false\n switch (value.t) {\n case 'page':\n return typeof value.route === 'string'\n case 'flow':\n return typeof value.name === 'string'\n case 'el':\n return (\n typeof value.role === 'string' &&\n typeof value.name === 'string' &&\n (!('ordinal' in value) || typeof value.ordinal === 'number')\n )\n case 'platform':\n return (\n value.platform === 'web' ||\n value.platform === 'android' ||\n value.platform === 'ios'\n )\n case 'selector':\n return typeof value.literal === 'string'\n case 'error':\n return typeof value.message === 'string'\n default:\n return false\n }\n}\n\n/**\n * Requires string `id`/`sha` so artifact descriptor mapping is total (`ref.id.startsWith`\n * runs once the sha regex passes); hex-format enforcement stays the consumer's filter (WR-02).\n */\nfunction isArtifactRefShape(value: unknown): boolean {\n return (\n isNonArrayObject(value) &&\n typeof value.id === 'string' &&\n typeof value.sha === 'string'\n )\n}\n\nconst PLAN_SOURCE_MISS_REASONS = new Set<string>([\n 'descriptor-ambiguous',\n 'descriptor-missing',\n 'page-anchor-mismatch',\n 'gate-refused',\n 'parameter-unbound',\n 'non-replayable-action',\n])\n\n/**\n * The closed `StepPlanSource` procedure-hint demotion union (G-381-4 / D-12). Kept verbatim\n * beside the miss-reason set: a demotion outside it is a malformed document, never something\n * to loosen the predicate for.\n */\nconst PLAN_SOURCE_DEMOTIONS = new Set<string>([\n 'body-unreadable',\n 'body-unparseable',\n 'body-empty',\n])\n\nconst TEST_BUG_SUBTYPES = new Set<string>([\n 'stale_selector',\n 'outdated_flow',\n 'bad_assertion',\n 'wrong_expected_value',\n])\n\n/**\n * The loader's spelling of the wire's `z.number().int().nonnegative()` — the domain\n * `RunKnowledgePlanSourceSchema` (`../functions/runs`) declares for EVERY numeric member of a\n * replay plan source: `flow.cursor`, `flow.length`, `guard.checksPassed`, `guard.total` and the\n * three `procedureStepIndex` slots.\n *\n * The two predicates must never disagree. `planSourceOf` (agent `ops/runs-knowledge.ts`) picks an\n * admitted value straight onto that strict wire, so a member this loader admits and the wire\n * refuses reaches `spec.output.parse` as a thrown read and the Knowledge tab renders\n * `read_failed` for the run — REVIEW WR-04, structurally the CR-01 class (a producer value\n * reaching a stricter declaration) narrowed to \"declared with a narrower domain than the\n * admission predicate\". A handoff carrying a negative cursor is malformed, not historical: the\n * runner writes only indices and counts here (`recordProcedureReplaySource`, runner\n * `loop/index.ts`), so nothing already on disk is refused by reading the wire's domain.\n */\nfunction isOrdinal(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value >= 0\n}\n\nfunction hasProcedureStepIndexShape(value: unknown): boolean {\n return isNonArrayObject(value) && isOrdinal(value.procedureStepIndex)\n}\n\n/**\n * Validates a present `planSource` against the complete discriminated StepPlanSource\n * union (D-12): canary projection dereferences the replay guard's fold fields, so an\n * admitted procedure-replay source must carry them in full (CR-02).\n */\nfunction hasCompletePlanSourceShape(value: unknown): boolean {\n if (!isNonArrayObject(value)) return false\n if (typeof value.procedureId !== 'string' || value.procedureId.length === 0) {\n return false\n }\n if (value.kind === 'procedure-hint') {\n // Absence stays legal (an ordinary hint carries no demotion); a PRESENT demotion must\n // sit inside the closed union so demotion counts are trustworthy.\n if ('demotion' in value) {\n return typeof value.demotion === 'string' && PLAN_SOURCE_DEMOTIONS.has(value.demotion)\n }\n return true\n }\n if (value.kind !== 'procedure-replay') return false\n\n const guard = value.guard\n if (!isNonArrayObject(guard)) return false\n if (!isOrdinal(guard.checksPassed) || !isOrdinal(guard.total)) {\n return false\n }\n if ('miss' in guard) {\n const miss = guard.miss\n if (!isNonArrayObject(miss)) return false\n if (!isOrdinal(miss.procedureStepIndex)) return false\n if (\n typeof miss.reason !== 'string' ||\n !PLAN_SOURCE_MISS_REASONS.has(miss.reason)\n ) {\n return false\n }\n }\n if ('executionFailure' in guard && !hasProcedureStepIndexShape(guard.executionFailure)) {\n return false\n }\n if ('verifierRejection' in guard && !hasProcedureStepIndexShape(guard.verifierRejection)) {\n return false\n }\n if ('flow' in value) {\n // F-381-51-1 · D-09 / 407-12 / 407-20: the additive flow cursor is admitted only\n // well-formed — present ⇒ {cursor, length} both NON-NEGATIVE INTEGERS, the domain the wire\n // declares (`RunKnowledgePlanSourceSchema.flow`). Fail-closed on any other shape (the\n // CR-02/381-36 strictness is never loosened for a new member).\n const flow = value.flow\n if (!isNonArrayObject(flow)) return false\n if (!isOrdinal(flow.cursor) || !isOrdinal(flow.length)) return false\n }\n return true\n}\n\n/**\n * Validates a present `rootCause` against the complete Verdict shape: candidate\n * emission traverses `evidence.citedSteps`/`citedAnchors`/`citedArtifacts`/`rationale`,\n * so an admitted verdict must carry them in consumer-traversable form (CR-02).\n */\nfunction hasCompleteRootCauseShape(value: unknown): boolean {\n if (!isNonArrayObject(value)) return false\n if (!isVerdictClass(value.class)) return false\n if (\n value.producer !== 'deterministic-classifier' &&\n value.producer !== 'analyze-run'\n ) {\n return false\n }\n if (typeof value.confidence !== 'number') return false\n\n const evidence = value.evidence\n if (!isNonArrayObject(evidence)) return false\n if (\n !Array.isArray(evidence.citedSteps) ||\n !evidence.citedSteps.every((step) => typeof step === 'number')\n ) {\n return false\n }\n if (\n !Array.isArray(evidence.citedAnchors) ||\n !evidence.citedAnchors.every(isAnchorShape)\n ) {\n return false\n }\n if (\n !Array.isArray(evidence.citedArtifacts) ||\n !evidence.citedArtifacts.every(isArtifactRefShape)\n ) {\n return false\n }\n if (typeof evidence.rationale !== 'string') return false\n\n if (typeof value.memoryMisdirectionRuledOut !== 'boolean') return false\n if (typeof value.perTest !== 'number') return false\n\n // 422 D-17: the two additive evidence members are PRESENT-IMPLIES-VALID, delegated to the\n // schemas that declare them for the same reason `retrievalTrace` delegates next door — they\n // ship as zod contracts, and a second hand-rolled spelling here would be a guard free to\n // drift from the contract a producer composes evidence against. A malformed present member is\n // REFUSED rather than stripped: a dropped claim is a claim no reader ever sees, and this\n // block exists to make one visible. Absence stays legal on every pre-422 verdict.\n if (!hasMisdirectionMemberShapes(value)) return false\n\n if ('attribution' in value) {\n const attribution = value.attribution\n if (!isNonArrayObject(attribution)) return false\n if (!Array.isArray(attribution.records) || !Array.isArray(attribution.anchors)) {\n return false\n }\n }\n if ('subtype' in value) {\n if (value.class !== 'test_bug') return false\n if (\n typeof value.subtype !== 'string' ||\n !TEST_BUG_SUBTYPES.has(value.subtype)\n ) {\n return false\n }\n }\n return true\n}\n\n/**\n * Validates a present `interpolatedVariables` at the depth its one consumer dereferences\n * (381 G-381-3): the procedure-extraction emit fold applies exact string equality against\n * `value` to classify a trajectory value slot and copies `name` VERBATIM as the forced\n * parameter name — so every admitted member must be a non-array object carrying string\n * `name` AND string `value`, and nothing deeper exists to validate. Absence stays legal\n * (the field is additive-optional; a step that interpolated nothing omits it), and an\n * empty array is legal emptiness, distinct from malformed.\n */\nfunction hasCompleteInterpolatedVariablesShape(value: unknown): boolean {\n return (\n Array.isArray(value) &&\n value.every(\n (member) =>\n isNonArrayObject(member) &&\n typeof member.name === 'string' &&\n typeof member.value === 'string',\n )\n )\n}\n\n/**\n * Validates a present `retrievalTrace` (387 D-13/D-14) by DELEGATING to the one schema that\n * declares it, rather than restating its fields here.\n *\n * Every other predicate in this file is hand-rolled because its subject is a TypeScript\n * interface with no runtime declaration anywhere. The trace is not — it ships as a zod\n * schema — and a second hand-rolled spelling of it would be a guard patterned on what it\n * guards, free to drift from the contract the producer validates against.\n *\n * Present-implies-valid, and absence stays legal: a pre-387 run has no trace and never will\n * (that absence is what D-15's typed no-trace answer is FOR). Presence is admitted only in\n * consumer-traversable form because the why-verb dereferences every line's record, leg,\n * rank and score to answer with — the same discipline `planSource` and\n * `interpolatedVariables` carry.\n */\nfunction hasCompleteRetrievalTraceShape(value: unknown): boolean {\n return ServedRetrievalTraceV1Schema.safeParse(value).success\n}\n\n/**\n * Validates a present `retrievalRung` (407 D-13) by DELEGATING to the schema that declares it,\n * for the same reason the trace predicate above delegates: the rung ships as a zod schema, and a\n * second hand-rolled spelling here would be a guard free to drift from the contract its producer\n * validates against.\n *\n * Present-implies-valid, and absence stays legal: a pre-407 run has no rung and never will, and\n * neither does a run that bound no knowledge reader. Presence is admitted only in the closed\n * two-word form the banner renders and `doctor` grades — an open string here would reach a\n * surface that has no rendering for it.\n */\nfunction hasCompleteRetrievalRungShape(value: unknown): boolean {\n return RecordedRetrievalRungSchema.safeParse(value).success\n}\n\nfunction isOneOf(values: readonly string[], value: unknown): boolean {\n return typeof value === 'string' && values.includes(value)\n}\n\nfunction hasCompleteConditionRecordShape(value: unknown): boolean {\n if (!isNonArrayObject(value)) return false\n const file = value.file\n return (\n typeof value.quote === 'string' &&\n typeof value.reason === 'string' &&\n isOneOf(CONDITION_VERDICTS, value.verdict) &&\n (!('judged' in value) || isOneOf(CONDITION_VERDICTS, value.judged)) &&\n (!('guard' in value) || isOneOf(CONDITION_GUARDS, value.guard)) &&\n (!('needs' in value) || isOneOf(CONDITION_NEEDS, value.needs)) &&\n Array.isArray(value.citations) &&\n value.citations.every(\n (citation) =>\n isNonArrayObject(citation) &&\n isOneOf(CITATION_SOURCES, citation.source) &&\n typeof citation.quote === 'string' &&\n (typeof citation.found === 'boolean' || citation.found === 'unchecked'),\n ) &&\n (!('file' in value) ||\n (isNonArrayObject(file) &&\n isOneOf(['match', 'differs'], file.name) &&\n isOneOf(['match', 'differs', 'unverified'], file.content) &&\n (!('firstDifference' in file) || typeof file.firstDifference === 'string')))\n )\n}\n\n/**\n * Validates a present `conditionVerdicts` (439 D-07) by hand: the block is a TypeScript DTO with\n * no runtime schema, and every reader (the router, the root-cause classifier, analyze-run, the\n * evidence diet) walks its conditions, verdicts and dialogs through `stepOutcomeUnproven`.\n *\n * Present-implies-valid, and absence stays legal: a pre-439 run has no block, and neither does a\n * step that ended before any verifier judgment. Presence is admitted only in consumer-traversable\n * form, with every verdict, guard, need, citation source and dialog account one of its declared\n * literals, so no reader meets a value it has no reading for.\n */\nfunction hasCompleteConditionVerdictsShape(value: unknown): boolean {\n if (!isNonArrayObject(value)) return false\n const openDialogs = value.openDialogs\n return (\n isOneOf(CONDITION_ENDINGS, value.ending) &&\n Array.isArray(value.conditions) &&\n value.conditions.every(hasCompleteConditionRecordShape) &&\n (!('openDialogs' in value) ||\n (Array.isArray(openDialogs) &&\n openDialogs.every(\n (dialog) =>\n isNonArrayObject(dialog) &&\n typeof dialog.name === 'string' &&\n isOneOf(\n ['bears-on-condition', 'requested', 'unrelated', 'unaccounted'],\n dialog.account,\n ),\n )))\n )\n}\n\nfunction hasCompleteStepShape(value: unknown): boolean {\n if (!isNonArrayObject(value)) return false\n\n const servedBrief = value.servedBrief\n const verifierVerdict = value.verifierVerdict\n\n return (\n typeof value.stepIndex === 'number' &&\n typeof value.stepText === 'string' &&\n (value.cacheStatus === 'hit' ||\n value.cacheStatus === 'miss' ||\n value.cacheStatus === 'bypass') &&\n isNonArrayObject(servedBrief) &&\n Array.isArray(servedBrief.channel1) &&\n servedBrief.channel1.every(isNonArrayObject) &&\n Array.isArray(value.subActions) &&\n value.subActions.every(hasCompleteSubActionShape) &&\n isNonArrayObject(verifierVerdict) &&\n typeof verifierVerdict.pass === 'boolean' &&\n typeof verifierVerdict.reasoning === 'string' &&\n (!('planSource' in value) || hasCompletePlanSourceShape(value.planSource)) &&\n (!('interpolatedVariables' in value) ||\n hasCompleteInterpolatedVariablesShape(value.interpolatedVariables)) &&\n (!('retrievalTrace' in value) ||\n hasCompleteRetrievalTraceShape(value.retrievalTrace)) &&\n (!('retrievalRung' in value) || hasCompleteRetrievalRungShape(value.retrievalRung)) &&\n (!('conditionVerdicts' in value) ||\n hasCompleteConditionVerdictsShape(value.conditionVerdicts))\n )\n}\n\n/** Strict only for the new block: historical handoff shapes retain their existing rules. */\nfunction hasRerunOriginShape(value: unknown, member: Record<string, unknown>, runId: string): boolean {\n if (!isNonArrayObject(value)) return false\n const safeIndex = (index: unknown): index is number =>\n typeof index === 'number' && Number.isSafeInteger(index) && index >= 0\n const digest = (hash: unknown): hash is string =>\n typeof hash === 'string' && /^[a-f0-9]{64}$/.test(hash)\n if (Object.keys(value).some(key => !['attempt', 'outcome', 'rootCause', 'evidenceDigest', 'decisions'].includes(key))) return false\n if (member.isRerun !== true || !safeIndex(member.rerunAttempt) ||\n !safeIndex(value.attempt) || value.attempt >= member.rerunAttempt) return false\n if (value.outcome !== 'failed' && value.outcome !== 'timeout') return false\n if (!safeIndex(member.testIndex) || !digest(value.evidenceDigest) || !Array.isArray(value.decisions)) return false\n if ('rootCause' in value) {\n const root = value.rootCause\n if (!hasCompleteRootCauseShape(root) || !isNonArrayObject(root) ||\n root.producer !== 'deterministic-classifier' || root.perTest !== member.testIndex ||\n typeof root.confidence !== 'number' || !Number.isFinite(root.confidence) ||\n root.confidence < 0 || root.confidence > 1 ||\n !isNonArrayObject(root.evidence) || !Array.isArray(root.evidence.citedSteps) ||\n !root.evidence.citedSteps.every(safeIndex)) return false\n }\n const seen = new Set<string>()\n try {\n for (const decision of value.decisions) {\n if (!isNonArrayObject(decision) || Object.keys(decision).some(key =>\n !['runId', 'testId', 'testIndex', 'stepIndex', 'decisionOrdinal', 'screenStateHash', 'evidenceDigest', 'evidence'].includes(key))) return false\n if (decision.runId !== runId || decision.testId !== member.testId ||\n decision.testIndex !== member.testIndex || !safeIndex(decision.stepIndex) ||\n !safeIndex(decision.decisionOrdinal) || !digest(decision.screenStateHash) ||\n !digest(decision.evidenceDigest) || !hasCompleteStepShape(decision.evidence)) return false\n const step = decision.evidence as StepEvidence\n if (step.stepIndex !== decision.stepIndex || 'rerunOrigin' in step || 'firstFailedAttempt' in step) return false\n const action = step.subActions[decision.decisionOrdinal]\n if (action === undefined || typeof action.result?.success !== 'boolean' ||\n screenStateHash(action.stateBefore) !== decision.screenStateHash) return false\n const key = `${decision.stepIndex}:${decision.decisionOrdinal}`\n if (seen.has(key)) return false\n seen.add(key)\n const { screenStateHash: _stateHash, evidenceDigest, ...facts } = decision\n if (sha256hex(canonicalJson(facts)) !== evidenceDigest) return false\n }\n const { evidenceDigest, ...facts } = value\n return sha256hex(canonicalJson(facts)) === evidenceDigest\n } catch {\n // Malformed/cyclic observation facts cannot establish an evidence identity.\n return false\n }\n}\n\nfunction hasCompleteTestShape(value: unknown, runId: string): boolean {\n if (!isNonArrayObject(value)) return false\n\n return (\n typeof value.testId === 'string' &&\n typeof value.testName === 'string' &&\n value.testName.length > 0 &&\n typeof value.filePath === 'string' &&\n value.filePath.length > 0 &&\n typeof value.testIndex === 'number' &&\n (value.outcome === 'passed' ||\n value.outcome === 'failed' ||\n value.outcome === 'healed' ||\n value.outcome === 'timeout' ||\n value.outcome === 'cancelled' ||\n value.outcome === 'skipped') &&\n Array.isArray(value.steps) &&\n value.steps.every(hasCompleteStepShape) &&\n (!('rootCause' in value) || hasCompleteRootCauseShape(value.rootCause)) &&\n // 390 D-14: only the literal marker is legal. A truthy-but-not-true value would let a\n // hand-edited handoff read as quarantined at one consumer and not at another.\n (!('quarantined' in value) || value.quarantined === true) &&\n // 2026-09-07, 418 D-09: persisted rerun fields are present-implies-valid.\n (!('isRerun' in value) || value.isRerun === true) &&\n (!('rerunAttempt' in value) ||\n (typeof value.rerunAttempt === 'number' &&\n Number.isInteger(value.rerunAttempt) &&\n value.rerunAttempt >= 1)) &&\n (!('rerunOrigin' in value) || hasRerunOriginShape(value.rerunOrigin, value, runId))\n )\n}\n\n/**\n * 390 D-16: one applied-entry record, at the depth consumers traverse — the three identity legs\n * plus the expiry that says how long the disposition was licensed for. Every field is a required\n * non-empty string; an entry missing its identity could never be joined back to a test.\n */\nfunction isPositiveSafeInteger(value: unknown): boolean {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0\n}\n\nconst PLANNER_LIMITS_RECORD_KEYS = new Set(['maxActions', 'maxPlanningTurns', 'perTest'])\nconst PLANNER_LIMITS_PER_TEST_KEYS = new Set(['testName', 'filePath', 'maxActions', 'maxPlanningTurns'])\n\nfunction hasPlannerLimitsPerTestShape(value: unknown): boolean {\n if (!isNonArrayObject(value)) return false\n return (\n Object.keys(value).every((key) => PLANNER_LIMITS_PER_TEST_KEYS.has(key)) &&\n typeof value.testName === 'string' &&\n typeof value.filePath === 'string' &&\n isPositiveSafeInteger(value.maxActions) &&\n isPositiveSafeInteger(value.maxPlanningTurns)\n )\n}\n\n/**\n * 436 D-06: the loader's spelling of `PlannerLimitsRecordSchema` (`../functions/runs`). The\n * acknowledgement copies an admitted record onto that strict wire, so the two must never disagree.\n */\nfunction hasPlannerLimitsRecordShape(value: unknown): boolean {\n if (!isNonArrayObject(value)) return false\n return (\n Object.keys(value).every((key) => PLANNER_LIMITS_RECORD_KEYS.has(key)) &&\n isPositiveSafeInteger(value.maxActions) &&\n isPositiveSafeInteger(value.maxPlanningTurns) &&\n (!('perTest' in value) ||\n (Array.isArray(value.perTest) && value.perTest.every(hasPlannerLimitsPerTestShape)))\n )\n}\n\nfunction hasQuarantineAppliedShape(value: unknown): boolean {\n if (!isNonArrayObject(value)) return false\n return (\n typeof value.product === 'string' &&\n value.product.length > 0 &&\n typeof value.filePath === 'string' &&\n value.filePath.length > 0 &&\n typeof value.testName === 'string' &&\n value.testName.length > 0 &&\n typeof value.expiresAt === 'string' &&\n value.expiresAt.length > 0\n )\n}\n\n/**\n * 422 D-17/D-18: the run-level arbiter sidecar, admitted only when every row is a COMPLETE\n * cross-check row that belongs to THIS run.\n *\n * Three refusals beyond the row schema, each closing a way a row could be lifted from elsewhere\n * and replayed as this run's exoneration:\n *\n * - a foreign `runId` — the row was minted against another run;\n * - a `handoffBaseDigest` that is not {@link misdirectionSourceDigest} of this document — the\n * row names another run's identity even when it copied this run's id;\n * - two rows for one EXPOSURE `(perTest, stepIndex, recordId)` — a second answer to one check\n * is not a second check. `aggregateMisdirectionEvidence` refuses the same pair at fold\n * time; catching it at the load boundary means a document that reaches a reader cannot\n * already be one the fold is obliged to reject. The fold stays the authority — this is a\n * cheaper, earlier refusal of the same fact, never a replacement for it.\n *\n * The digest is computed from members this predicate's caller has already validated, so it is\n * never taken over an unchecked identity. An EMPTY array is legal and meaningful (see\n * `CompletedRunHandoff.misdirectionEvidence`); only the member's ABSENCE means silence.\n */\nfunction hasMisdirectionSidecarShape(value: unknown, handoff: Record<string, unknown>): boolean {\n if (!Array.isArray(value)) return false\n const baseDigest = misdirectionSourceDigest(handoff as unknown as CompletedRunHandoff)\n const exposures = new Set<string>()\n for (const candidate of value) {\n const parsed = MisdirectionRecordResultSchema.safeParse(candidate)\n if (!parsed.success) return false\n const row = parsed.data\n if (row.runId !== handoff.runId) return false\n if (row.handoffBaseDigest !== baseDigest) return false\n // Joined on U+001F, a separator no component can contain, so (1, '1x') and (11, 'x')\n // stay two exposures rather than colliding into one.\n const exposure = `${row.perTest}\u001f${row.stepIndex}\u001f${row.recordId}`\n if (exposures.has(exposure)) return false\n exposures.add(exposure)\n }\n return true\n}\n\n/**\n * Guarantees every required root field plus the required fields on each per-test outcome\n * and traversed step before a handoff reaches direct consumers, including the complete\n * discriminated shapes of the two traversed optional blocks — `planSource` and `rootCause`\n * (CR-02), including a present `planSource.demotion` on the procedure-hint arm, which must\n * sit inside the closed body-unreadable/body-unparseable/body-empty union while its absence\n * stays legal (G-381-4) — the string `name`/`value` of every present `interpolatedVariables` member, the\n * pair the emit fold value-matches and name-copies (G-381-3 capture half; absence and\n * emptiness both stay legal) — the element shapes of the consumer-traversed arrays — every `subActions` member\n * is dereferenceable through `plannedAction`, `grounding.attempts` (flatMapped by\n * resolvedActionRefs for every subAction), and `stateBefore.elements[]` down to the\n * string values consumers apply string operations to: string `role`/`nameNormalized`,\n * all-string `attributes`/`labels` member values, and string-if-present urls on BOTH\n * `stateBefore` and `stateAfter` — the two legs classifySubActionRoute reads\n * (CR-01/WR-01 grounding-depth and value-level closure; round-9 CR-01 stateAfter-url\n * closure); every `servedBrief.channel1`\n * member is a non-array object — and the `rootCause.evidence` members: `citedAnchors`\n * satisfy the six-kind Anchor union and `citedArtifacts` carry string id/sha (WR-02).\n * Only genuinely untraversed deep evidence — verified untraversed at the consumers'\n * dereference sites (handoff-anchors.ts, emit-candidates.ts, emit-canary-outcomes.ts,\n * normalize-anchor.ts) — stays unvalidated at this load boundary: workingMemory,\n * decision context, stagnation, cycle, planning failure, stateAfter interiors beyond\n * url, `grounding.descriptor` and attempt interiors (stage/outcome/resolvedRef value\n * types), and element state/bounds/hierarchy; element name/value stay unvalidated as\n * read-but-crash-safe reads (2026-10-15, 441-25: the curation capture copy that carried\n * them is gone).\n */\nfunction hasCompleteHandoffShape(value: unknown): boolean {\n if (!isNonArrayObject(value)) return false\n\n const scope = value.scope\n const configDigests = value.configDigests\n\n return (\n typeof value.schemaVersion === 'number' &&\n typeof value.runId === 'string' &&\n value.runId.length > 0 &&\n isNonArrayObject(scope) &&\n (scope.tier === 'global' ||\n scope.tier === 'product' ||\n scope.tier === 'suite' ||\n scope.tier === 'test') &&\n typeof scope.key === 'string' &&\n scope.key.length > 0 &&\n typeof value.buildOrdinal === 'number' &&\n (!('excludedFromOutcomes' in value) || value.excludedFromOutcomes === true) &&\n (!('gateRun' in value) || value.gateRun === true) &&\n (value.executionContext === 'local-interactive' ||\n value.executionContext === 'local-headless' ||\n value.executionContext === 'ci' ||\n value.executionContext === 'cloud') &&\n (value.aggregateVerdict === 'passed' ||\n value.aggregateVerdict === 'failed' ||\n value.aggregateVerdict === 'healed' ||\n value.aggregateVerdict === 'timeout' ||\n value.aggregateVerdict === 'cancelled') &&\n isNonArrayObject(configDigests) &&\n typeof configDigests.suiteConfigDigest === 'string' &&\n typeof configDigests.testConfigDigest === 'string' &&\n typeof value.startedAt === 'number' &&\n typeof value.endedAt === 'number' &&\n Array.isArray(value.tests) &&\n value.tests.every(test => hasCompleteTestShape(test, value.runId as string)) &&\n (!('quarantineApplied' in value) ||\n (Array.isArray(value.quarantineApplied) &&\n value.quarantineApplied.every(hasQuarantineAppliedShape))) &&\n (!('plannerLimits' in value) || hasPlannerLimitsRecordShape(value.plannerLimits)) &&\n // 422 D-17/D-18. Last in the chain on purpose: the row-identity check digests this\n // document's `runId`/`scope`/`buildOrdinal`/`configDigests`, and every one of those has\n // been validated by the clauses above before control reaches here.\n (!('misdirectionEvidence' in value) ||\n hasMisdirectionSidecarShape(value.misdirectionEvidence, value))\n )\n}\n\n/**\n * The read side of the handoff version discipline: parse → version check → refuse any stamp\n * other than {@link CURRENT_HANDOFF_SCHEMA_VERSION} with a typed {@link HandoffVersionError}.\n * Pure — no fs; the runner-local fs leg delegates here. Every handoff consumer routes through\n * this one guard.\n */\nexport const guardCompletedRunHandoff = createVersionGuard<CompletedRunHandoff>({\n name: 'CompletedRunHandoff',\n current: CURRENT_HANDOFF_SCHEMA_VERSION,\n migrations: HANDOFF_MIGRATIONS,\n error: HandoffVersionError,\n shape: hasCompleteHandoffShape,\n})\n","// The per-step limit evidence (436 D-11..D-13). Type-only DTOs plus their key sets and the one\n// reason formatter; the runner records them, readers keep reading whatever shipped.\n\nimport type { PlannerLimits } from '../config/planner-limits'\n\n/**\n * The typed limit stop (D-12). Present only when a limit refused the next dispatch of its kind.\n * It is never an application failure, a planning failure, a termination or a verdict.\n */\nexport interface LimitStopEvidence {\n limit: 'actions' | 'planning-turns'\n configured: number\n used: number\n reason: string\n /**\n * The step's requested outcome as a whole. Since 439 D-08 (superseding 436 D-13) the verifier\n * judges the stop once, and its per-condition verdicts sit beside this block in\n * `StepEvidence.conditionVerdicts`.\n */\n requestedOutcome: 'unverified'\n /** The last verifier rejection's reasoning, masked-before-record. */\n lastVerifierRejection?: string\n /** The planner's last stated reasoning, masked-before-record. */\n lastPlannerReasoning?: string\n}\n\n/** Inner inputs of one compound action, which count once against the action limit (D-07). */\nexport interface CompoundInputCount {\n subActionIndex: number\n kind: 'scroll' | 'fill'\n count: number\n}\n\n/** What a step execution used against its limits (D-11). */\nexport interface StepLimitUsage {\n limits: PlannerLimits\n actionsUsed: number\n planningCallsUsed: number\n verifierCalls: number\n judgeCalls: number\n compoundInputs?: CompoundInputCount[]\n}\n\nexport const LIMIT_STOP_EVIDENCE_KEYS = [\n 'limit',\n 'configured',\n 'used',\n 'reason',\n 'requestedOutcome',\n 'lastVerifierRejection',\n 'lastPlannerReasoning',\n] as const satisfies readonly (keyof LimitStopEvidence)[]\n\nexport const STEP_LIMIT_USAGE_KEYS = [\n 'limits',\n 'actionsUsed',\n 'planningCallsUsed',\n 'verifierCalls',\n 'judgeCalls',\n 'compoundInputs',\n] as const satisfies readonly (keyof StepLimitUsage)[]\n\n/** The plain reason a limit stop reads with, e.g. \"Stopped: action limit reached — 30 of 30 actions used\". */\nexport function formatLimitStopReason(\n limit: LimitStopEvidence['limit'],\n configured: number,\n used: number,\n): string {\n return limit === 'actions'\n ? `Stopped: action limit reached — ${used} of ${configured} actions used`\n : `Stopped: planning-turn limit reached — ${used} of ${configured} planner calls used`\n}\n","// Operation-specific evidence an action produced outside the page (436 D-19..D-23). Type-only\n// DTOs plus their key sets. No downloaded byte, file path or text preview is ever part of them.\n\n/** One download the action started, as the browser finished it (D-19). */\nexport interface DownloadEvidence {\n suggestedFilename: string\n /** The filename's extension including the dot, or '' when it has none. */\n extension: string\n /** Byte count of the completed file. */\n size?: number\n /** Lower-case hex sha-256 of the completed file's bytes. */\n sha256?: string\n /** Only 'completed' is evidence that the download happened; the rest never are. */\n state: 'completed' | 'failed' | 'canceled' | 'unfinished'\n /** The browser's failure text for 'failed' and 'canceled'. */\n failure?: string\n /** Started after the capture window of the action before it closed; no action is credited with starting it. */\n late?: true\n}\n\n/** One clipboard write the app made during the action (436-11). */\nexport interface ClipboardEvidence {\n source: 'writeText' | 'write' | 'copy-event'\n text: string\n truncated: boolean\n readBack: 'matched' | 'mismatched' | 'unavailable'\n}\n\n/** How a fill's read-back compared with the requested text (437 D-05). */\nexport type FillVerdict = 'exact' | 'normalized' | 'mismatch' | 'unverified'\n\n/** Which route delivered a fill's text (437 D-05). */\nexport type InputPath = 'native' | 'webview' | 'keyboard'\n\n/** What happened to a requested submit after a fill (437 D-05). */\nexport type SubmitOutcome = 'sent' | 'not-sent' | 'unavailable' | 'failed'\n\n/** Why a requested submit was not sent (437 D-05). */\nexport type SubmitReason = 'mismatch' | 'multi-line-field' | 'input-failed' | 'focus-lost'\n\n/** What one action's input actually delivered (437 D-05). `currentState` is masked. */\nexport interface InputEvidence {\n verb: string\n inputSent: boolean\n currentState?: string\n fillVerdict?: FillVerdict\n inputPath?: InputPath\n secure?: true\n submit?: SubmitOutcome\n submitReason?: SubmitReason\n unavailableReason?: string\n}\n\n/** Evidence that rides the action that produced it (D-22). */\nexport interface OperationEvidence {\n downloads?: DownloadEvidence[]\n clipboard?: ClipboardEvidence[]\n input?: InputEvidence[]\n}\n\n/** Whether the step's platform could capture each operation at all (D-23). */\nexport interface OperationCaptureAvailability {\n download: 'available' | 'unavailable'\n clipboard: 'available' | 'unavailable'\n reason?: string\n}\n\nexport const DOWNLOAD_EVIDENCE_KEYS = [\n 'suggestedFilename',\n 'extension',\n 'size',\n 'sha256',\n 'state',\n 'failure',\n 'late',\n] as const satisfies readonly (keyof DownloadEvidence)[]\n\nexport const CLIPBOARD_EVIDENCE_KEYS = [\n 'source',\n 'text',\n 'truncated',\n 'readBack',\n] as const satisfies readonly (keyof ClipboardEvidence)[]\n\nexport const INPUT_EVIDENCE_KEYS = [\n 'verb',\n 'inputSent',\n 'currentState',\n 'fillVerdict',\n 'inputPath',\n 'secure',\n 'submit',\n 'submitReason',\n 'unavailableReason',\n] as const satisfies readonly (keyof InputEvidence)[]\n\nexport const OPERATION_CAPTURE_AVAILABILITY_KEYS = [\n 'download',\n 'clipboard',\n 'reason',\n] as const satisfies readonly (keyof OperationCaptureAvailability)[]\n","// The per-run digest — a READ-TIME projection, never a record (Phase 391, D-16 / D-18).\n//\n// Minted here, beside `run-notification.ts`, and deliberately NOT inside it. The notification\n// row is the chain's one DURABLE artifact: counts-only, exact-key-guarded, read by chat and by\n// the dashboard, and frozen (388 D-11). The digest is what a HUMAN is shown once per run — the\n// sentences, the chain, the decisions waiting on them — composed live from four already-shipped\n// read paths every time somebody asks. Widening the row to carry any of that would have made\n// one payload answer two questions, and `guardRunNotification`'s sorted-key comparison would\n// hard-fail every reader on the first field. So the two shapes sit side by side in one\n// directory, and this one has no `schemaVersion`: nothing persists a digest, so there is no\n// build boundary for a version stamp to describe. A stamp here would be an invitation to store\n// one, which is precisely the second representation D-16 refuses.\n//\n// EXACTLY ONE DIGEST PER RUN IS STRUCTURAL, not a rule anyone enforces. The projection is keyed\n// by `runId`; a projection keyed by a run cannot fire per event, which is PROP-04's whole\n// complaint (\"an approval UX that fires 40 times per nightly run is a worse product than one\n// that fires once\") answered by a shape rather than by a throttle.\n//\n// REFS AND COUNTS ONLY (D-18, T-391-17). Nothing on this DTO carries evidence bytes, receipt\n// bytes, rationale prose or masked content: a mark change is its mark id, its fix and the ids or\n// workspace path it changed; candidates and quarantine are counts plus identity refs. 2026-09-30,\n// 432-09 (D-05/D-22): the digest reads applied mark changes from this run's own ledger and never\n// reads a proposal store. That is a privacy boundary rather than a size budget — this\n// value is rendered directly by a terminal, a chat and a dashboard, and a payload that COULD\n// carry a secret would need a masking boundary at each of them.\n\nimport { z } from 'zod'\n\nimport { AnalysisClusterViewSchema } from '../functions/analysis-get'\nimport type { AnalysisClusterView } from '../functions/analysis-get'\nimport { MARK_FIX_KINDS, MarkAppliedChangeSchema } from '../functions/feedback'\nimport type { MarkAppliedChange, MarkFixKind } from '../functions/feedback'\nimport { runIdSchema } from '../run/run-id'\nimport { POST_PROCESSING_CHIP_STATUSES, PostProcessingSkippedSchema } from './post-processing-status'\nimport type { PostProcessingChipStatus, PostProcessingSkipReason } from './post-processing-status'\nimport { RUN_NOTIFICATION_VIEW_STATUSES } from './run-notification'\nimport type { RunNotificationViewStatus } from './run-notification'\n\n/** `runs.digest` addresses exactly one run by id — the `runs.postprocessing` shape. */\nexport const RunsDigestInputSchema = z.object({\n runId: runIdSchema,\n}).strict()\n\nexport type RunsDigestInput = z.infer<typeof RunsDigestInputSchema>\n\n/**\n * One fix a mark on this run applied, read from the run's own mark ledger (432-09, D-04).\n *\n * The receipt's applied change VERBATIM: record ids for a knowledge fix, the written workspace path\n * and its byte digest for a test edit. In ledger order; a later mark on the same address does not\n * remove an earlier change, because the earlier fix was never retracted (D-11).\n */\nexport interface RunDigestMarkChange {\n markId: string\n ordinal: number\n fix: MarkFixKind\n change: MarkAppliedChange\n}\n\n/**\n * The chain's per-stage outcomes, in the ONE chip vocabulary (388 D-14/C13; narrowed to two —\n * Phase 404, D-01, 2026-08-26).\n *\n * The two chips are the `runs.postprocessing` values verbatim — not a synonym, not a\n * control-flow word — because two spellings of four words is the state in which the CLI and\n * the dashboard disagree about a row neither of them got wrong.\n *\n * `outcome` is present exactly once the chain wrote its terminal row, and it is a fact about\n * the CHAIN rather than about the run (the row's own note): a failed run whose analysis and\n * curation both succeeded reads `complete` (444 D-36: the served view's word, not the stored one).\n */\nexport interface RunDigestChainOutcomes {\n analysis: PostProcessingChipStatus\n curation: PostProcessingChipStatus\n outcome?: RunNotificationViewStatus\n /**\n * The `runs.postprocessing` skipped fact verbatim (425 D-08, 444 D-39), so a machine reader of the\n * digest never re-derives from `pending` chips what the read op already knows. A sibling of\n * the two chip arms rather than a fifth word on either of them.\n */\n skipped?: { reason: PostProcessingSkipReason }\n}\n\n/**\n * Curator candidates staged this run, as COUNTS (D-13).\n *\n * The digest REPORTS; the KREV verbs review. Candidates stay candidate-status truth inside\n * bundles and are never listed as proposals, so nothing here addresses one for a decision.\n *\n * NO REFS, and the absence is measured rather than an omission: the only run-scoped, durable\n * record of what a run curated is the chain-terminal notification row, which is counts-only BY\n * CONSTRUCTION (388 D-11) and may not be widened (D-18, T-391-18). A ref list would therefore\n * have had to come from somewhere else — a new port over the run directory's curation receipt —\n * and inventing one so a field could be populated is a larger change than the field is worth.\n * Stated here so a later reader does not read the gap as a bug.\n */\nexport interface RunDigestCandidateReport {\n curated: number\n deprecated: number\n}\n\n/**\n * Quarantine as counts + identity refs.\n *\n * STATE, NOT TRANSITIONS, and the difference is a fact about the ledger rather than a shortcut.\n * A quarantine entry records the test's three identity legs, its window and its history; it\n * carries NO run attribution, because auto-quarantine is code-authored operational state keyed\n * by a failure fingerprint and not by whoever happened to be running (390 C15). So there is no\n * honest way to compute \"transitions caused by this run\" from what is committed, and a number\n * presented as one would be a fabrication. What the digest can say truthfully is what the\n * ledger holds when the digest is read, which is also what a person acts on.\n *\n * `refs` are `product/filePath::testName` — the durable identity legs, never `testId`, which is\n * per-run and would address nothing tomorrow.\n */\nexport interface RunDigestQuarantineReport {\n quarantined: number\n expired: number\n refs: string[]\n}\n\n/**\n * The whole digest: structured sections, plus the bytes a surface prints.\n *\n * `lines` exists so that no surface composes a sentence. The tail, the CLI verb, 392's chat and\n * M5 all print these strings; the structured sections are for a surface that wants to lay the\n * same facts out differently (a dashboard card, a chat block) without re-deriving any of them.\n * Carrying both is what keeps \"one renderer\" true for the terminal without making every other\n * surface parse strings.\n *\n * `verdictClusters` are the `analysis.get` cluster views VERBATIM — the same value, the same\n * type, the same already-composed representative sentence. The digest re-renders nothing: 389\n * D-05/D-10 put one renderer and one accessor behind that op, and a second composition here\n * would be exactly the drift those decisions exist to prevent.\n */\nexport interface RunDigest {\n runId: string\n verdictClusters: AnalysisClusterView[]\n chain: RunDigestChainOutcomes\n /**\n * The fixes this run's marks applied, in ledger order. ABSENT where this host reads no mark\n * ledger or the ledger could not be read — an empty list is a measurement (\"no mark changed\n * anything\"), and an unread ledger is not.\n */\n markChanges?: RunDigestMarkChange[]\n candidates: RunDigestCandidateReport\n quarantine: RunDigestQuarantineReport\n lines: string[]\n}\n\nexport const RunDigestMarkChangeSchema = z.object({\n markId: z.string().min(1),\n ordinal: z.number().int().positive(),\n fix: z.enum(MARK_FIX_KINDS),\n change: MarkAppliedChangeSchema,\n}).strict().superRefine((value, ctx) => {\n // 2026-10-03 (quick 261003-cpv, 432 review IN-21): the same pairing `MarkDispositionSchema`'s\n // applied arm enforces on the ledger these rows are projected from. The digest is computed per\n // call and not stored, so no stored row is read through this.\n if ((value.fix === 'test-edit') !== (value.change.kind === 'test-file')) {\n ctx.addIssue({\n code: 'custom',\n path: ['change', 'kind'],\n message: 'a test edit writes a test file and every other fix changes knowledge',\n })\n }\n}) satisfies z.ZodType<RunDigestMarkChange>\n\n/**\n * The chip enums are CONSTRUCTED from the exported vocabulary rather than respelled (C13), so a\n * fifth chip status cannot arrive with this contract still admitting four.\n */\nexport const RunDigestChainOutcomesSchema = z.object({\n analysis: z.enum(POST_PROCESSING_CHIP_STATUSES),\n curation: z.enum(POST_PROCESSING_CHIP_STATUSES),\n outcome: z.enum(RUN_NOTIFICATION_VIEW_STATUSES).optional(),\n skipped: PostProcessingSkippedSchema.optional(),\n}).strict() satisfies z.ZodType<RunDigestChainOutcomes>\n\nexport const RunDigestCandidateReportSchema = z.object({\n curated: z.number().int().nonnegative(),\n deprecated: z.number().int().nonnegative(),\n}).strict() satisfies z.ZodType<RunDigestCandidateReport>\n\nexport const RunDigestQuarantineReportSchema = z.object({\n quarantined: z.number().int().nonnegative(),\n expired: z.number().int().nonnegative(),\n refs: z.array(z.string().min(1)),\n}).strict() satisfies z.ZodType<RunDigestQuarantineReport>\n\n/**\n * The `runs.digest` result.\n *\n * `AnalysisClusterViewSchema` is IMPORTED, not restated: the digest's verdict section is the\n * analysis op's cluster view, and a second declaration of that shape here would be free to\n * agree today and drop `members` after the first change to either.\n */\nexport const RunDigestSchema = z.object({\n runId: z.string(),\n verdictClusters: z.array(AnalysisClusterViewSchema),\n chain: RunDigestChainOutcomesSchema,\n markChanges: z.array(RunDigestMarkChangeSchema).optional(),\n candidates: RunDigestCandidateReportSchema,\n quarantine: RunDigestQuarantineReportSchema,\n lines: z.array(z.string()),\n}).strict() satisfies z.ZodType<RunDigest>\n","import { z } from 'zod'\n\nimport { CROSS_CHECKS } from '../knowledge/gate-receipt'\nimport type { CrossCheck } from '../knowledge/gate-receipt'\nimport { runIdSchema } from '../run/run-id'\nimport { MEMORY_ON_PATH_TRUSTS } from '../verdict/misdirection-evidence'\nimport type { MemoryOnPathTrust } from '../verdict/misdirection-evidence'\nimport { resolveVerdictMisdirection } from '../verdict/resolved-verdicts'\nimport type { Verdict } from '../verdict/verdict'\n\n// The `analysis.get` op contracts (Phase 389, D-11/D-15 — minted in schema per 384 D-16).\n//\n// THE one producer of a run's full analysis: resolved verdicts (through the D-10 accessor),\n// rendered sentences (the one renderer, live recurrence joins applied), and render-time\n// clusters. The DTO carries clusters AND the full per-test sentences so a run page can\n// expand a cluster (D-15) — every verdict still carries its sentence (ANLZ-03), the\n// presentation dedupes (ANLZ-04).\n//\n// Clusters mint NO identity (D-16): fingerprint value, count, member refs and a representative —\n// a cluster or verdict has no short-ID and no `agentqa://` address.\n// 2026-09-02 (Phase 410): the sixth entity kind left with the Issue-slot cleanup.\n//\n// EVIDENCE ON THE WIRE (Phase 406, D-01). A verdict said what it CONCLUDED and never what it\n// READ, so a page wanting \"jump to the step this is about\" or \"open the screenshot it looked at\"\n// had to open `analysis.json` itself and re-join — a second producer of the same refs, which is\n// the one thing this op exists to prevent. Each resolved verdict now carries the cited steps and\n// cited artifacts it already held, ADDITIVELY: the field is optional in the type so a reader\n// compiled against the older DTO is unaffected, while the op always emits it.\n//\n// THE CITED ANCHORS AND THE RATIONALE ARE DELIBERATELY OFF IT. The anchor list is an identity\n// vocabulary no surface binds, and the rationale is the model's own prose about a run — it\n// belongs to the artifact and to the rendered sentence, not to a link target. Widening later is\n// additive; unpublishing is not.\n\nconst verdictClassValues = [\n 'test_bug',\n 'app_bug',\n 'environment',\n 'flake',\n 'config_error',\n 'llm_error',\n 'unknown',\n 'timeout',\n] as const satisfies readonly Verdict['class'][]\n\n/** `analysis.get` addresses exactly one completed run by id — the `runs.get` shape. */\nexport const AnalysisGetInputSchema = z.object({\n runId: runIdSchema,\n}).strict()\n\nexport type AnalysisGetInput = z.infer<typeof AnalysisGetInputSchema>\n\n/**\n * One resolved verdict as the analysis surface lists it: the three classification fields a\n * reader triages on, joined to the member test by `perTest` (D-07's join key) and named by\n * its per-run `testId`. The full `Verdict` (evidence arrays, attribution) stays in the\n * artifact/handoff documents rather than crossing every surface boundary by default.\n */\n/**\n * One artifact a verdict cited, as the analysis surface links it (D-01/D-17).\n *\n * TWO ABSENCE FACTS, KEPT APART. `evidenceIncomplete` is the PRODUCER's — it knew at emit time\n * it could not attach these bytes — and `present` is the READER's, a stat taken when this DTO was\n * built. A page renders one `evidence-incomplete` state from either, but collapsing them here\n * would lose which side reported it, and only one of them can be fixed by re-running.\n *\n * `present` ABSENT IS NOT `present: false`. A host that cannot cheaply stat its blobs omits the\n * key, and a page's predicate is `present === false` so that presence-unknown never renders as a\n * claimed absence.\n */\nexport interface AnalysisCitedArtifact {\n id: string\n sha: string\n evidenceIncomplete?: boolean\n present?: boolean\n}\n\n/** What one verdict read, projected from its own `Verdict.evidence` — never re-derived (D-01). */\nexport interface AnalysisVerdictEvidence {\n citedSteps: number[]\n citedArtifacts: AnalysisCitedArtifact[]\n}\n\n/**\n * The not-run words the circularity arbiter is allowed to DISCLOSE on this DTO (422 D-19/D-20).\n *\n * A CLOSED ALLOW-LIST AND NOT A PASSTHROUGH, which is the whole reason it exists.\n * `MisdirectionRecordResult.reason` is an open `string` on the durable row: the arbiter writes one\n * of the four words `curation/misdirection-tail.ts` publishes (`cap-exceeded`, `interrupted`,\n * `no-eval-root`, `posture-unavailable`), but a root read failure or a validator refusal can put\n * arbitrary producer text there, and this DTO crosses the browser boundary. 422-17 held the same\n * line on the CLI close-out line for the same reason: the closed WORDS carry the whole disclosure,\n * and a reason outside this set is OMITTED rather than forwarded.\n *\n * Omission is safe because the word is a REFINEMENT of a row that already says `not-run`: a reader\n * that gets no word still knows the check did not run, it simply is not told why.\n */\nexport type AnalysisMisdirectionReason =\n | 'cap-exceeded'\n | 'interrupted'\n | 'no-eval-root'\n | 'posture-unavailable'\n// prettier-ignore\nexport const ANALYSIS_MISDIRECTION_REASONS = ['cap-exceeded', 'interrupted', 'no-eval-root', 'posture-unavailable'] as const satisfies readonly AnalysisMisdirectionReason[]\n\n/**\n * One record's cross-check, thinned to what a surface may show (422 D-20).\n *\n * NO DIGESTS AND NO SAMPLES. The durable row binds run, member, step, decision, brief, corpus and\n * profile identities so it cannot be replayed as another verdict's exoneration; none of that is a\n * fact a reader acts on, and every one of them is a value a page would put in a text node.\n */\nexport interface AnalysisMisdirectionRecord {\n recordId: string\n crossCheck: CrossCheck\n /** Present only when the row disclosed one of the closed words above. */\n reason?: AnalysisMisdirectionReason\n}\n\n/** One record the verdict DECLARED on its failing path, with the store's own trust marker. */\nexport interface AnalysisMemoryOnPathEntry {\n recordId: string\n trust: MemoryOnPathTrust\n}\n\n/**\n * What one resolved verdict says about circularity, as a surface may read it (422 D-17/D-19/D-20).\n *\n * `state` is {@link resolveVerdictMisdirection}'s three-arm reading, carried across the wire rather\n * than re-derived: `not-recorded` is a verdict that made no claim, `declared-only` is D-19's\n * absent-evaluation-root exemption, and `measured` is a real ledger. A surface that folded\n * `not-recorded` into either of the others would invent a backing nobody ever claimed.\n *\n * `memoryOnPath` is the verdict's own DECLARATION and stays exactly as absent or as empty as the\n * producer left it: \"the author declared no records\" and \"the author declared nothing\" are\n * different claims, and this member is the only place a page can tell them apart.\n */\nexport interface AnalysisVerdictMisdirection {\n state: 'not-recorded' | 'declared-only' | 'measured'\n /** The block's own summary word. Present exactly when `state` is not `not-recorded`. */\n crossCheck?: CrossCheck\n /** The complete per-record ledger, thinned. Present exactly when `crossCheck` is. */\n results?: AnalysisMisdirectionRecord[]\n /** D-19's absence marker, forwarded only when the producer actually wrote it. */\n backing?: 'declared-only'\n /** ABSENT stays absent; `[]` stays empty. Never synthesized from the ledger. */\n memoryOnPath?: AnalysisMemoryOnPathEntry[]\n}\n\nexport interface AnalysisResolvedVerdict {\n perTest: number\n testId: string\n class: Verdict['class']\n producer: 'deterministic-classifier' | 'analyze-run'\n confidence: number\n /** OPTIONAL for readers compiled before 406; the op always emits it (D-01). */\n evidence?: AnalysisVerdictEvidence\n /**\n * What this verdict says about circularity (422 D-17/D-19/D-20), or NOTHING.\n *\n * ABSENT MEANS THE VERDICT SAID NOTHING AT ALL — no ledger, no declaration — which is every\n * verdict written before 422 and the deterministic floor's minted `unknown`. It is emitted\n * exactly when the verdict carries `misdirectionRuledOut` or `memoryOnPath`, so a run whose\n * arbiter never ran reaches a surface with no circularity member and renders as it always did.\n */\n misdirection?: AnalysisVerdictMisdirection\n}\n\n/** One member test's composed sentence — the ONE renderer's output, verbatim (D-05). */\nexport interface AnalysisSentence {\n perTest: number\n testId: string\n sentence: string\n}\n\n/** A cluster member ref: the join keys a surface needs to expand, nothing more (D-16). */\nexport interface AnalysisClusterMemberRef {\n testIndex: number\n testId: string\n}\n\n/**\n * One cluster as the op serves it (D-15/D-16): the fingerprint VALUE (never hashed, never\n * given an id), occurrence count, member refs ordered by testIndex, and the representative\n * member with its composed sentence.\n */\nexport interface AnalysisClusterView {\n fingerprint: string\n count: number\n members: AnalysisClusterMemberRef[]\n representative: {\n testIndex: number\n sentence: string\n }\n}\n\n/** The `analysis.get` result (D-11): verdicts + sentences + clusters, one producer. */\nexport interface AnalysisGetOutput {\n runId: string\n verdicts: AnalysisResolvedVerdict[]\n sentences: AnalysisSentence[]\n clusters: AnalysisClusterView[]\n}\n\nexport const AnalysisCitedArtifactSchema = z.object({\n id: z.string(),\n sha: z.string(),\n evidenceIncomplete: z.boolean().optional(),\n present: z.boolean().optional(),\n}).strict() satisfies z.ZodType<AnalysisCitedArtifact>\n\nexport const AnalysisVerdictEvidenceSchema = z.object({\n citedSteps: z.array(z.number().int().nonnegative()),\n citedArtifacts: z.array(AnalysisCitedArtifactSchema),\n}).strict() satisfies z.ZodType<AnalysisVerdictEvidence>\n\nexport const AnalysisMisdirectionRecordSchema = z.object({\n recordId: z.string().min(1),\n crossCheck: z.enum(CROSS_CHECKS),\n reason: z.enum(ANALYSIS_MISDIRECTION_REASONS).optional(),\n}).strict() satisfies z.ZodType<AnalysisMisdirectionRecord>\n\nexport const AnalysisMemoryOnPathEntrySchema = z.object({\n recordId: z.string().min(1),\n trust: z.enum(MEMORY_ON_PATH_TRUSTS),\n}).strict() satisfies z.ZodType<AnalysisMemoryOnPathEntry>\n\nexport const AnalysisVerdictMisdirectionSchema = z.object({\n state: z.enum(['not-recorded', 'declared-only', 'measured']),\n crossCheck: z.enum(CROSS_CHECKS).optional(),\n results: z.array(AnalysisMisdirectionRecordSchema).optional(),\n backing: z.literal('declared-only').optional(),\n memoryOnPath: z.array(AnalysisMemoryOnPathEntrySchema).optional(),\n}).strict() satisfies z.ZodType<AnalysisVerdictMisdirection>\n\nexport const AnalysisResolvedVerdictSchema = z.object({\n perTest: z.number().int().nonnegative(),\n testId: z.string(),\n class: z.enum(verdictClassValues),\n producer: z.enum(['deterministic-classifier', 'analyze-run']),\n confidence: z.number(),\n evidence: AnalysisVerdictEvidenceSchema.optional(),\n misdirection: AnalysisVerdictMisdirectionSchema.optional(),\n}).strict() satisfies z.ZodType<AnalysisResolvedVerdict>\n\n/**\n * THE one projection of a verdict's circularity evidence onto this DTO (422 D-17/D-19/D-20).\n *\n * It lives beside the shape it produces and is called by `analysis.get` and by nobody else, which\n * is the point: a second spelling at the op, at the door or at the page would be a second answer to\n * \"what did this verdict say about the memory it was served\", and the three would agree only on the\n * day they were written. The three refusals it inherits from {@link resolveVerdictMisdirection} are\n * not restated here — the function is CALLED, never re-derived.\n *\n * THREE THINGS IT REFUSES TO DO ITSELF:\n *\n * - It does not synthesize a member. A verdict with no ledger AND no declaration answers\n * `undefined`, so an older run's failure view is byte-identical to what it rendered before 422.\n * - It does not recompute a cross-check, soften a `flipped` row or count a majority. The block's\n * own word and the complete per-record ledger are carried; the reading is the reader's.\n * - It does not forward a `reason` outside {@link ANALYSIS_MISDIRECTION_REASONS}, a digest, a\n * sample record or the row's identity bindings. See {@link AnalysisMisdirectionRecord}.\n */\nexport function projectVerdictMisdirection(\n verdict: Verdict,\n): AnalysisVerdictMisdirection | undefined {\n if (verdict.misdirectionRuledOut === undefined && verdict.memoryOnPath === undefined) {\n return undefined\n }\n // ABSENT STAYS ABSENT. `?? []` here would tell every reader the author declared an empty set.\n const declaration = verdict.memoryOnPath === undefined\n ? {}\n : {\n memoryOnPath: verdict.memoryOnPath.map((entry) => ({\n recordId: String(entry.recordId),\n trust: entry.trust,\n })),\n }\n const resolved = resolveVerdictMisdirection(verdict)\n if (resolved.state === 'not-recorded') return { state: 'not-recorded', ...declaration }\n const { evidence } = resolved\n return {\n state: resolved.state,\n crossCheck: evidence.crossCheck,\n results: evidence.results.map((row) => ({\n recordId: String(row.recordId),\n crossCheck: row.crossCheck,\n ...(disclosableReason(row.reason) === undefined\n ? {}\n : { reason: row.reason as AnalysisMisdirectionReason }),\n })),\n ...(evidence.backing === undefined ? {} : { backing: evidence.backing }),\n ...declaration,\n }\n}\n\n/** The allow-list read, spelled once. `undefined` for a word this DTO may not carry. */\nfunction disclosableReason(reason: string | undefined): AnalysisMisdirectionReason | undefined {\n return ANALYSIS_MISDIRECTION_REASONS.find((word) => word === reason)\n}\n\nexport const AnalysisSentenceSchema = z.object({\n perTest: z.number().int().nonnegative(),\n testId: z.string(),\n sentence: z.string(),\n}).strict() satisfies z.ZodType<AnalysisSentence>\n\nconst analysisClusterMemberRefSchema = z.object({\n testIndex: z.number().int().nonnegative(),\n testId: z.string(),\n}).strict() satisfies z.ZodType<AnalysisClusterMemberRef>\n\nexport const AnalysisClusterViewSchema = z.object({\n fingerprint: z.string(),\n count: z.number().int().positive(),\n members: z.array(analysisClusterMemberRefSchema),\n representative: z.object({\n testIndex: z.number().int().nonnegative(),\n sentence: z.string(),\n }).strict(),\n}).strict() satisfies z.ZodType<AnalysisClusterView>\n\nexport const AnalysisGetOutputSchema = z.object({\n runId: z.string(),\n verdicts: z.array(AnalysisResolvedVerdictSchema),\n sentences: z.array(AnalysisSentenceSchema),\n clusters: z.array(AnalysisClusterViewSchema),\n}).strict() satisfies z.ZodType<AnalysisGetOutput>\n","// The one verdict read path (Phase 389, D-10).\n//\n// Two producers now exist for one `(runId, testId)` verdict — the runner's deterministic\n// classifier persisted on the handoff, and analyze-run's authored artifact. THE resolved\n// verdict is served by this accessor and nowhere else: artifact verdicts when the artifact\n// is present, the handoff's deterministic floor when it is absent. The supersession-as-\n// upgrade law lives HERE — a consumer that read `rootCause` off the handoff directly would\n// be re-deriving the supersession rule, and the SC2 \"second independent observation\" defect\n// class returns the day two consumers derive it differently.\n\nimport type { CompletedRunHandoff } from '../handoff/completed-run-handoff'\nimport type { PerTestOutcome } from '../handoff/per-test-outcome'\nimport type { RunAnalysisArtifact } from './analysis-artifact'\nimport type {\n MemoryOnPathEntry,\n MisdirectionEvidence,\n} from './misdirection-evidence'\nimport type { Verdict } from './verdict'\n\n/**\n * What a RESOLVED verdict says about circularity (422 D-17/D-19) — three arms, not two.\n *\n * `not-recorded` is every verdict written before 422 and every verdict from a producer that\n * shipped no ledger. It is NOT `declared-only`: that word is D-19's specific claim that an\n * evaluation root was ABSENT, and handing it to a verdict that never made it would be the\n * reader inventing a backing. It is certainly not `held`.\n */\nexport type ResolvedMisdirection =\n | { readonly state: 'not-recorded' }\n | {\n readonly state: 'declared-only'\n readonly evidence: MisdirectionEvidence\n readonly memoryOnPath?: readonly MemoryOnPathEntry[]\n }\n | {\n readonly state: 'measured'\n readonly evidence: MisdirectionEvidence\n readonly memoryOnPath?: readonly MemoryOnPathEntry[]\n }\n\n/**\n * Read a resolved verdict's circularity evidence without inventing any (422 D-17/D-19).\n *\n * Pure projection, three refusals to invent:\n *\n * - No `misdirectionRuledOut` answers `not-recorded`, whatever else the verdict carries. A\n * declared `memoryOnPath` with no ledger beside it is a list of records nobody cross-checked\n * — reporting it as anything but \"not recorded\" would read a declaration as a result.\n * - The `declared-only` marker is reported as its own state, never folded into `measured`.\n * D-19 admits it only under a genuinely ABSENT evaluation root, and a surface that showed it\n * as a measurement would present the author's own word as the check on the author's word.\n * - An ABSENT `memoryOnPath` stays absent rather than becoming `[]`. \"The author declared no\n * records\" and \"the author declared nothing\" are different claims, and this phase keeps them\n * apart everywhere else.\n *\n * The evidence object is passed through by reference and never rebuilt, so a `flipped` row\n * cannot be softened on the way to a reader.\n */\nexport function resolveVerdictMisdirection(verdict: Verdict): ResolvedMisdirection {\n const evidence = verdict.misdirectionRuledOut\n if (evidence === undefined) return { state: 'not-recorded' }\n const declaration =\n verdict.memoryOnPath === undefined ? {} : { memoryOnPath: verdict.memoryOnPath }\n if (evidence.backing === 'declared-only') {\n return { state: 'declared-only', evidence, ...declaration }\n }\n return { state: 'measured', evidence, ...declaration }\n}\n\n/**\n * Members whose outcome is worth a root-cause verdict — the complement of the runner's own\n * presence rule (373-07): clean passes, skipped and cancelled members are not failures to\n * explain. Mirrors the agent handler's floor projection member-for-member.\n */\nfunction needsVerdict(test: PerTestOutcome): boolean {\n return test.outcome !== 'passed' && test.outcome !== 'skipped' && test.outcome !== 'cancelled'\n}\n\n/**\n * The floor's minted `unknown`, byte-identical to the runner's `deterministicVerdict`\n * output for an absent signal (confidence 0, the fixed rationale template, empty evidence\n * arrays). Minted here rather than imported because the dependency points the other way —\n * the runner consumes schema — and the two spellings are pinned equal by test.\n */\nfunction mintedUnknown(perTest: number): Verdict {\n return {\n class: 'unknown',\n producer: 'deterministic-classifier',\n confidence: 0,\n evidence: {\n citedSteps: [],\n citedAnchors: [],\n citedArtifacts: [],\n rationale: 'no deterministic signal matched',\n },\n memoryMisdirectionRuledOut: true,\n perTest,\n }\n}\n\n/**\n * THE only way any consumer obtains a run's verdicts (D-10).\n *\n * Artifact present → the authored verdicts, whole. Artifact absent → the deterministic\n * floor: each member needing a verdict answers its persisted `rootCause`, and a failed\n * member that carries none resolves to the minted `unknown` — the same fill the\n * classifier itself would have minted, so the array covers every failure either way.\n *\n * Pure over its two arguments. Whoever loads the artifact loads it through\n * `guardRunAnalysisArtifact`; this function never touches a byte of storage.\n *\n * 422 D-17 — WHAT THIS FUNCTION MUST NOT DO. Both paths hand back the verdict OBJECT it found,\n * so a per-record cross-check ledger, a `declared-only` backing marker and an attribution block\n * all survive resolution byte-for-byte; a projection that rebuilt a verdict field-by-field would\n * silently drop every member added after it was written. And the floor's {@link mintedUnknown}\n * carries NO circularity evidence, because it is minted precisely for a member nobody authored\n * anything about — minting `held` there would be the build asserting a cross-check that never\n * ran, on the one population where nothing is known.\n */\nexport function resolveRunVerdicts(\n artifact: RunAnalysisArtifact | undefined,\n handoff: CompletedRunHandoff,\n): Verdict[] {\n if (artifact !== undefined) return [...artifact.verdicts]\n return handoff.tests\n .filter(needsVerdict)\n .map((test) => test.rootCause ?? mintedUnknown(test.testIndex))\n}\n","// The authored sentence parts a run analysis carries BESIDE its verdicts (Phase 389, D-05/D-07).\n//\n// Parts live BESIDE `Verdict`, joined by `perTest`, and never inside it — the §A9 union is\n// frozen and the 387 beside-never-widening law applies here exactly as it did to the entity\n// vocabulary: widening `Verdict` would ripple through every guard, every persisted handoff and\n// every consumer that pattern-matches the union, for a field only the analysis surface reads.\n// `Verdict.evidence.rationale` stays what it always was — the classifier's advisory self-trace —\n// and is never the product sentence; the sentence a human reads is assembled from THESE parts.\n\nimport { z } from 'zod'\n\nimport { EntityUriSchema } from '../entity/uri'\n\n/**\n * Where the sentence's grounding quote came from, as a discriminated pair.\n *\n * The step arm names the captured step the quote was lifted from. The `test-outcome` arm is\n * the typed alternative for tests that captured ZERO steps (a suite-bootstrap failure, a\n * session that never opened): those failures still get a sentence, and a fabricated\n * `stepIndex` pointing at a step that does not exist is exactly the overstatement this\n * discriminant makes unrepresentable.\n */\nexport type VerdictGroundingQuote =\n | { stepIndex: number; quote: string }\n | { source: 'test-outcome'; quote: string }\n\n/**\n * One verdict's authored sentence parts (D-05).\n *\n * `perTest` is the join key to `Verdict.perTest` (D-07) — one parts record per authored\n * verdict, matched by number, never by array position. `links` carry `agentqa://` entity\n * URIs only, validated through the one URI codec rather than a bare string check.\n */\nexport interface VerdictSentenceParts {\n perTest: number\n /** A verbatim quote of captured evidence — never paraphrase, never fabrication. */\n groundingQuote: VerdictGroundingQuote\n /** What distinguishes THIS failure from its neighbours — the sentence's middle. */\n discriminator: string\n /** The one concrete thing to do next — the sentence's end. */\n nextAction: string\n /** `agentqa://` entity references the sentence surfaces as navigable links. */\n links: string[]\n}\n\n/** The runtime half of the contract — the artifact guard parses every part through this. */\nexport const VerdictSentencePartsSchema = z.object({\n perTest: z.number(),\n groundingQuote: z.union([\n z.object({ stepIndex: z.number(), quote: z.string() }),\n z.object({ source: z.literal('test-outcome'), quote: z.string() }),\n ]),\n discriminator: z.string(),\n nextAction: z.string(),\n links: z.array(EntityUriSchema),\n})\n","// The run-directory analysis artifact (Phase 389, D-09).\n//\n// `analysis.json` is the analysis job's own receipt and the durable truth home for a run's\n// authored verdicts and sentence parts — the document M5's run page, 392's chat and eval will\n// consume. It is a NEW file beside `handoff.json` and `events.jsonl`, never a mutation of\n// either (386 D-16's two-receipt law): the handoff records what the run observed, this file\n// records what the analysis authored, and each job writes only its own receipt.\n//\n// The guard is pure — no fs in schema. The host adapter that puts these bytes on disk lives\n// in `agent-local` (`writeAnalysisArtifact`), behind the `persistAnalysis` capability.\n\nimport {\n createVersionGuard,\n VersionGuardError,\n} from '../versioning/create-version-guard'\nimport type { MigrationRegistry } from '../versioning/create-version-guard'\nimport { hasMisdirectionMemberShapes } from './misdirection-evidence'\nimport { VerdictSentencePartsSchema } from './sentence-parts'\nimport type { VerdictSentenceParts } from './sentence-parts'\nimport { isVerdictClass } from './verdict'\nimport type { Verdict } from './verdict'\n\nexport const CURRENT_ANALYSIS_SCHEMA_VERSION = 2\n\n/** The artifact's file name inside a run directory: `runs/<slug(runId)>/analysis.json`. */\nexport const ANALYSIS_FILE = 'analysis.json'\n\n/**\n * What one analysis run durably authored (D-09).\n *\n * `verdicts` is the complete authored array — floor members and upgraded members alike —\n * and `parts` carries one sentence-parts record per verdict, joined by `perTest` (D-07).\n * The `verdicts-authored` checkpoint value stays byte-shape `{runId, verdicts}` exactly as\n * 388 froze it (388 D-02); parts live HERE and nowhere else.\n */\nexport interface RunAnalysisArtifact {\n schemaVersion: number\n runId: string\n verdicts: Verdict[]\n parts: VerdictSentenceParts[]\n}\n\n/**\n * Thrown when a stored artifact declares a `schemaVersion` this build cannot consume:\n * newer than {@link CURRENT_ANALYSIS_SCHEMA_VERSION}, or older with no registered\n * migration (the D-19 / §A8 version discipline the handoff guard set).\n */\nexport class AnalysisVersionError extends VersionGuardError {\n constructor(found: number, supported: number) {\n super('RunAnalysisArtifact', found, supported)\n this.name = 'AnalysisVersionError'\n }\n}\n\nexport const ANALYSIS_MIGRATIONS: MigrationRegistry = {}\n\nfunction isNonArrayObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/**\n * Structural check on one stored verdict, at the depth the artifact's consumers traverse:\n * class inside the closed union, a declared producer, and consumer-traversable evidence\n * arrays — the same discipline the handoff guard applies to a present `rootCause`.\n */\nfunction hasVerdictShape(value: unknown): boolean {\n if (!isNonArrayObject(value)) return false\n if (!isVerdictClass(value.class)) return false\n if (\n value.producer !== 'deterministic-classifier' &&\n value.producer !== 'analyze-run'\n ) {\n return false\n }\n if (typeof value.confidence !== 'number') return false\n const evidence = value.evidence\n if (!isNonArrayObject(evidence)) return false\n if (!Array.isArray(evidence.citedSteps)) return false\n if (!Array.isArray(evidence.citedAnchors)) return false\n if (!Array.isArray(evidence.citedArtifacts)) return false\n if (typeof evidence.rationale !== 'string') return false\n if (typeof value.memoryMisdirectionRuledOut !== 'boolean') return false\n if (typeof value.perTest !== 'number') return false\n // 422 D-17: the two additive circularity members are present-implies-valid, through the same\n // predicate the handoff loader applies to a persisted `rootCause` — one spelling, both\n // boundaries. A malformed present block is REFUSED here rather than dropped: this artifact is\n // the durable home a reader consults, and a stripped claim reads exactly like a claim that\n // was never made. Absence stays legal, so every pre-422 artifact keeps loading and none of\n // them is handed a backing it never declared.\n if (!hasMisdirectionMemberShapes(value)) return false\n return true\n}\n\n/**\n * The artifact's fail-closed shape: root fields, every verdict structurally complete, and\n * every parts record parsed through the ONE zod contract — which is what routes each\n * `links` member through `EntityUriSchema` (T-389-02) rather than a bare string check.\n *\n * `perTest` is the phase's one join key (D-07), and its uniqueness over BOTH arrays is a\n * one-document structural property enforced HERE for every stored/foreign artifact — this\n * guard is the one gate those bytes cross (G-389-3B / WR-02). The author path needs no\n * second gate: `evaluateAttempt` is first-entry-wins per testIndex (measured in plan 04),\n * so the shipped author cannot produce duplicates; the threat is foreign/stored bytes only.\n */\nfunction hasCompleteArtifactShape(value: unknown): boolean {\n if (!isNonArrayObject(value)) return false\n return (\n typeof value.schemaVersion === 'number' &&\n typeof value.runId === 'string' &&\n value.runId.length > 0 &&\n Array.isArray(value.verdicts) &&\n value.verdicts.every(hasVerdictShape) &&\n new Set(value.verdicts.map((verdict) => (verdict as { perTest: number }).perTest))\n .size === value.verdicts.length &&\n Array.isArray(value.parts) &&\n value.parts.every((part) => VerdictSentencePartsSchema.safeParse(part).success) &&\n new Set(value.parts.map((part) => (part as { perTest: number }).perTest)).size ===\n value.parts.length\n )\n}\n\n/**\n * The read side of the artifact version discipline: parse → refuse any stamp other than the\n * current one with a typed {@link AnalysisVersionError} → structural check. Every future artifact\n * consumer routes through this one guard.\n */\nexport const guardRunAnalysisArtifact = createVersionGuard<RunAnalysisArtifact>({\n name: 'RunAnalysisArtifact',\n current: CURRENT_ANALYSIS_SCHEMA_VERSION,\n migrations: ANALYSIS_MIGRATIONS,\n error: AnalysisVersionError,\n shape: hasCompleteArtifactShape,\n})\n\n/**\n * The typed answer of {@link admitAnalysisArtifactForRun}: the artifact by identity when\n * its recorded `runId` is the run being resolved, or a `run-mismatch` refusal carrying\n * both ids — the shape a consumer folds to the deterministic floor, never adopts.\n */\nexport type AnalysisArtifactAdmission =\n | { kind: 'admitted'; artifact: RunAnalysisArtifact }\n | { kind: 'run-mismatch'; recordedRunId: string; resolvingRunId: string }\n\n/**\n * The read half of the two-sided run-identity contract (G-389-3A, the 388 class).\n *\n * The write half derives the artifact's path FROM `artifact.runId` (the `persistAnalysis`\n * binding), so on an intact directory the recorded id and the resolved run agree by\n * construction. A copied, restored or foreign-written run directory breaks that agreement,\n * and this is the ONE place the comparison is spelled: both byte boundaries (the\n * agent-local artifact reader serving `analysis.get`/`runs.get`, and the canary fold's\n * loader) call it immediately after {@link guardRunAnalysisArtifact}.\n *\n * Consumers fold `run-mismatch` to `undefined` — the run's own deterministic floor. Never\n * adoption (the refusal exists so another run's verdicts and parts stay invisible whole),\n * and never a hard failure (the run's deterministic answer is intact; a mismatch is not\n * the version guard's corruption posture).\n */\nexport function admitAnalysisArtifactForRun(\n artifact: RunAnalysisArtifact,\n resolvingRunId: string,\n): AnalysisArtifactAdmission {\n if (artifact.runId === resolvingRunId) return { kind: 'admitted', artifact }\n return { kind: 'run-mismatch', recordedRunId: artifact.runId, resolvingRunId }\n}\n","// The failure fingerprint: one exported vocabulary (Phase 389, D-13).\n//\n// 390's FLAK-01 windows recurrence over this key and the cluster function groups over it,\n// so it is exported ONCE, from here, and the recipe below is part of the contract — changing\n// it later re-keys every accumulated fingerprint history. Deliberately a readable\n// deterministic string rather than a hash: the cluster DTO carries the fingerprint value\n// (D-16), and a reader owed an explanation should be able to see what the key says.\n//\n// THE RECIPE (contract, not implementation detail):\n// 1. Select one anchor deterministically — the FIRST element-kind anchor in `anchors`,\n// else the FIRST page-kind anchor, else mint `{t: 'error', message: errorText ?? ''}`.\n// 2. Normalize the selection through `normalizeAnchor` — the shape-locked contract whose\n// 'error' arm already collapses digit runs to '#', which is what makes two timeouts\n// differing only in milliseconds one recurrence.\n// 3. Key = `canonicalJson(normalized)` joined to the verdict class with `::` — the\n// emit-canary-outcomes normalizedKey idiom, extended by the class because the same\n// anchor failing as a flake and failing as an app bug are two facts, not one.\n\nimport { canonicalJson } from '../determinism/canonical-json'\nimport type { Anchor } from '../identity/anchor'\nimport { normalizeAnchor } from '../identity/normalize-anchor'\nimport type { Verdict } from './verdict'\n\n/** What a failure offers the fingerprint: its exercised anchors, and its error text. */\nexport interface FailureFingerprintInput {\n readonly anchors: readonly Anchor[]\n /** The error-signature fallback source for anchorless failures. Absent means ''. */\n readonly errorText?: string\n}\n\n/**\n * Deterministic, byte-stable fingerprint for one failure (D-13).\n *\n * Total: every failure keys, including anchorless ones — an empty anchor list with no error\n * text still yields the normalized empty-message error key rather than a refusal. Two\n * identical `(anchors, class)` inputs produce byte-identical keys across processes, because\n * every step of the recipe is pure over its arguments.\n */\nexport function failureFingerprint(\n input: FailureFingerprintInput,\n verdictClass: Verdict['class'],\n): string {\n const selected =\n input.anchors.find((anchor) => anchor.t === 'el')\n ?? input.anchors.find((anchor) => anchor.t === 'page')\n ?? { t: 'error' as const, message: input.errorText ?? '' }\n return `${canonicalJson(normalizeAnchor(selected))}::${verdictClass}`\n}\n","/** A skipped tap's block, keyed `idempotentNoop`. `inputSent: false` marks the 437 shape (D-05). */\nexport interface IdempotentNoopMeta {\n currentState: string\n inputSent?: false\n}\n\n// Reads the pre-437 `{ currentState }` block too (436 D-17).\nexport function readIdempotentNoopMeta(\n result?: { metadata?: Record<string, unknown> },\n): IdempotentNoopMeta | undefined {\n const raw = result?.metadata?.['idempotentNoop']\n if (raw && typeof raw === 'object' && 'currentState' in raw) {\n const { currentState, inputSent } = raw as Record<string, unknown>\n if (typeof currentState !== 'string') return undefined\n if (inputSent === undefined) return { currentState }\n if (inputSent === false) return { currentState, inputSent }\n }\n return undefined\n}\n\n// A skipped tap sent no input and did not fail (D-05), whichever shape recorded it.\nexport function actionDidNotFail(result?: {\n success?: boolean\n metadata?: Record<string, unknown>\n}): boolean {\n return result?.success === true || readIdempotentNoopMeta(result)?.inputSent === false\n}\n","// The action-anchor fingerprint: gate 3's v1 coverage recipe (Phase 393, D-13).\n//\n// A SIBLING of `failure-fingerprint.ts`, never an extension of it. That file is FROZEN\n// (389 D-13) because 390's recurrence windows key off its bytes; this one answers a different\n// question — what surface does a test EXERCISE, rather than how did it FAIL — and the two must\n// be free to move independently. What they share is their building blocks: `normalizeAnchor`\n// and `canonicalJson`, imported here rather than re-derived, so \"near-same anchors are the\n// same anchor\" has exactly one definition in the codebase.\n//\n// THE RECIPE (contract, not implementation detail):\n// 1. An element is `{ kind, type, anchor }`, plus `route` only when the step carries one.\n// `kind` separates the two vocabularies: an action contributes its action type, an\n// assertion contributes its assert-kind. Asserting a value on a field and typing into it\n// are different coverage facts about the same anchor, so they must key apart.\n// 2. The anchor passes through `normalizeAnchor` — the shape-locked contract that casefolds\n// roles, runs names through `normalizeAccessibleName`, and collapses route hashes and\n// trailing slashes. A route context is normalized through the SAME contract's page arm,\n// so `/Form.html/#thanks` and `/form.html` are one route here exactly as they are there.\n// 3. The element is `canonicalJson` of that object — keys sorted, so a caller building the\n// input in a different order cannot mint a second key for the same fact. Readable rather\n// than hashed, matching the frozen sibling: a receipt NAMES the uncovered element (D-14),\n// and a reader owed an explanation should be able to see what the key says.\n//\n// SET SEMANTICS LIVE AT THE CONSUMER. Gate 3's value test is \"at least one element absent from\n// the union of the suite's elements\" (D-14, spec §6.3 verbatim) — no similarity threshold, no\n// magic constant. This module mints elements and preserves order; it deliberately does NOT\n// deduplicate, because the sequence is what a later §4.1 enrichment builds on.\n\nimport { canonicalJson } from '../determinism/canonical-json'\nimport type { StepEvidence } from '../handoff/step-evidence'\nimport type { SubActionEvidence } from '../handoff/sub-action-evidence'\nimport type { Anchor } from '../identity/anchor'\nimport {\n classifySubActionRoute,\n elementAnchor,\n resolvedElementEvidence,\n} from '../identity/exercised-anchors'\nimport { normalizeAnchor } from '../identity/normalize-anchor'\nimport { actionDidNotFail } from '../result/no-input'\n\n/**\n * The recipe version. Bumping it RE-KEYS every accumulated fingerprint: the derived suite\n * table has to refold, and receipts already citing uncovered elements no longer line up with\n * what the table holds, so accrued coverage comparison resets. That is the costly-reversibility\n * note in D-13, and it is the reason the goldens in `__tests__` exist.\n */\nexport const ACTION_ANCHOR_FINGERPRINT_VERSION = 1\n\n/** One exercised step, reduced to what coverage cares about. */\nexport interface ActionAnchorElementInput {\n /** Which vocabulary `type` is drawn from: an action type, or an assert-kind. */\n readonly kind: 'action' | 'assert'\n /** The action type (`click`, `fill`, …) or the assert-kind (`assertValue`, `assertAI`, …). */\n readonly type: string\n /** The step's target, in the frozen anchor union `normalizeAnchor` accepts. */\n readonly anchor: Anchor\n /** Route the step carried, where it carried one. Absent means no route context. */\n readonly route?: string\n}\n\n/**\n * Normalize a route through the frozen anchor contract's page arm.\n *\n * `normalizeRoute` is private to `normalize-anchor.ts` and stays that way — reaching it through\n * the public `normalizeAnchor` reuses the contract instead of copying its body, which is what\n * keeps route normalization single-sourced when 377-era extensions move it.\n */\nfunction normalizedRoute(route: string): string {\n const normalized = normalizeAnchor({ t: 'page', route })\n return normalized.t === 'page' ? normalized.route : route\n}\n\n/**\n * One fingerprint element (D-13). Pure, total, and byte-stable across processes: every step of\n * the recipe is a pure function of its arguments.\n */\nexport function actionAnchorElement(input: ActionAnchorElementInput): string {\n const base = {\n kind: input.kind,\n type: input.type,\n anchor: normalizeAnchor(input.anchor),\n }\n return canonicalJson(\n input.route === undefined ? base : { ...base, route: normalizedRoute(input.route) },\n )\n}\n\n/**\n * The ordered element sequence for one test (D-13).\n *\n * Order and repeats are preserved deliberately — see the SET SEMANTICS note above.\n */\nexport function actionAnchorSequence(\n inputs: readonly ActionAnchorElementInput[],\n): string[] {\n return inputs.map((input) => actionAnchorElement(input))\n}\n\n/**\n * Which action types contribute an ASSERT element rather than an ACTION element (D-13).\n *\n * `kind` is the recipe's vocabulary discriminator: asserting a value on a field and typing into\n * it are different coverage facts about the same anchor, so they must key apart. The members are\n * the assert arms of `CommonAction` — the only action shapes whose purpose is a claim about the\n * app rather than a change to it. `extractAI` is deliberately absent: an extraction reads state\n * without asserting anything about it, so it covers surface the way an action does.\n *\n * Hoisted here from `knowledge-local`'s fold in 393-06, on the trigger its own doc comment named:\n * \"a second reader is the trigger to hoist it beside `actionAnchorElement`, not before.\" Gate 3's\n * draft side is that second reader.\n */\nexport const ASSERT_ACTION_TYPES: ReadonlySet<string> = new Set(['assertAI', 'assertValue'])\n\n/**\n * The anchor one sub-action exercised, or `undefined` when it exercised nothing nameable.\n *\n * Both arms route through the shipped exercised-anchors walk rather than re-deriving element\n * resolution: `resolvedElementEvidence` is the ONE implementation of \"which element did this ref\n * resolve to on the pre-action screen\" (389 D-13's promotion), reached here by handing it a step\n * narrowed to a single sub-action — the same reach-the-contract-through-its-public-door idiom\n * `normalizedRoute` above uses for routes.\n *\n * Falling back to the page anchor is what lets an assertion with no element target — `assertValue`\n * over the URL, the canonical case — still contribute coverage. A sub-action with neither an\n * element nor a route contributes nothing, which is the evidence-less case D-16's text lane\n * catches at the consumer.\n */\nfunction subActionAnchor(step: StepEvidence, subAction: SubActionEvidence): Anchor | undefined {\n const [resolved] = resolvedElementEvidence({ ...step, subActions: [subAction] })\n if (resolved !== undefined) return elementAnchor(resolved)\n const { route } = classifySubActionRoute(subAction)\n return route === undefined ? undefined : { t: 'page', route }\n}\n\n/**\n * The evidence `testFingerprintElements` reads, and nothing more.\n *\n * A `PerTestOutcome` is assignable unchanged — the suite side passes one straight out of the\n * fold. Declared as its own structural shape rather than as `PerTestOutcome` because the DRAFT\n * side passes the draft's own member out of a gate-run document and the identity fields play no\n * part in the recipe: naming only `steps` says which facts the elements are a function of, so a\n * reader cannot suspect the file path or the test name of leaking into the bytes.\n */\nexport interface FingerprintEvidenceLike {\n readonly steps?: readonly StepEvidence[]\n}\n\n/**\n * The ordered elements one test exercised, or `[]` when its evidence yields none (D-13).\n *\n * ONE FUNCTION, BOTH SIDES OF GATE 3. The suite union is folded from these bytes\n * (`knowledge-local`'s `suite_fingerprints`), and the draft's own elements are computed by this\n * same function from the draft's member outcome inside its gate-run document. That is what makes\n * the comparison a comparison: an asymmetric derivation — a draft measured one way against a\n * suite measured another — would compare two recipes rather than two tests, and would answer\n * \"does this draft add value\" with an artifact of the derivation. Living in `schema` is what lets\n * both readers reach it; `agent` names neither `core` nor `knowledge-local` and never will.\n *\n * ONLY SUB-ACTIONS THAT DID NOT FAIL COUNT (`actionDidNotFail`). A failed sub-action did not run\n * to an accepted result, and a surface an action failed to reach is not surface the test covers.\n * A skipped tap did not fail: it found its target already in the desired state and sent no input\n * (437 D-05), so its anchor counts, as it did before 437 recorded the skip `success: false`.\n * Retuning that rule is a measurement, not a preference, and it must move on both sides at once —\n * which is now structurally guaranteed rather than merely intended.\n *\n * A route is attached as CONTEXT only to element anchors. A page anchor already IS its route, so\n * repeating it would mint two spellings of one fact.\n */\nexport function testFingerprintElements(test: FingerprintEvidenceLike): string[] {\n const elements: string[] = []\n for (const step of test.steps ?? []) {\n for (const subAction of step.subActions ?? []) {\n if (!actionDidNotFail(subAction.result)) continue\n const anchor = subActionAnchor(step, subAction)\n if (anchor === undefined) continue\n const type = subAction.plannedAction.type\n const { route } = classifySubActionRoute(subAction)\n elements.push(actionAnchorElement({\n kind: ASSERT_ACTION_TYPES.has(type) ? 'assert' : 'action',\n type,\n anchor,\n ...(anchor.t === 'el' && route !== undefined ? { route } : {}),\n }))\n }\n }\n return elements\n}\n","// What FEEDS the failure fingerprint: one exported derivation (Phase 390, FLAK-01).\n//\n// The recipe itself lives next door in `failure-fingerprint.ts` and is FROZEN (389 D-13).\n// This module is its INPUT stage — the rule that decides which step a failure is about, and\n// which recorded bytes describe it — and it changes nothing about the recipe.\n//\n// THE RULE (contract, not implementation detail):\n// failing step = the FIRST step whose verifier verdict failed, else the LAST recorded step\n// (the timeout-after-all-verified anchor); a zero-step test has none.\n// error text = the failing step's FIRST non-empty sub-action error, else the verifier's\n// reasoning; a step-less test answers its recorded outcome.\n//\n// It lives HERE, in schema, rather than beside its first caller, because three consumers now\n// need one spelling and they cannot all reach each other: `analysis/cluster.ts` (the render-time\n// presentation), `jobs/kinds.ts`'s `templateGroundingQuote` (the floor sentence's quote), and —\n// the reason for the hoist — knowledge-local's fingerprint-keyed recurrence windows, which\n// cannot import agent. Two spellings of \"which step failed\" would be two fingerprints for one\n// failure, so SC1's window and the cluster presentation would eventually disagree about what\n// \"the same failure\" means (388 C13: one exported vocabulary).\n//\n// Pure-sync over DTOs, no host APIs — the schema-package law.\n\nimport type { PerTestOutcome } from '../handoff/per-test-outcome'\nimport type { StepEvidence } from '../handoff/step-evidence'\n\n/**\n * THE failing-step selection rule: the FIRST step whose verifier verdict failed, else the LAST\n * recorded step (the timeout-after-all-verified anchor). A zero-step test has no failing step\n * and keys through the error-signature fallback below.\n */\nexport function failingStepOf(test: PerTestOutcome): StepEvidence | undefined {\n if (test.steps.length === 0) return undefined\n return (\n test.steps.find((step) => !step.verifierVerdict.pass)\n ?? test.steps[test.steps.length - 1]\n )\n}\n\n/**\n * The error-signature fallback source for anchorless failures (D-13's total-function leg):\n * the failing step's first sub-action error text, else the verifier's reasoning; a step-less\n * test answers its recorded outcome. Every branch quotes bytes the run recorded.\n */\nexport function errorTextOf(step: StepEvidence | undefined, test: PerTestOutcome): string {\n if (step === undefined) return test.outcome\n const subActionError = step.subActions\n .map((subAction) => subAction.result.error)\n .find((error): error is string => typeof error === 'string' && error !== '')\n return subActionError ?? step.verifierVerdict.reasoning\n}\n","// The cross-document analysis validation boundary (Phase 389, plan 04 — D-05/D-07).\n//\n// An authored `RunAnalysisArtifact` is UNTRUSTED input: it crosses from model output into a\n// durable artifact, and this function is the one gate on that crossing. It validates the\n// artifact AGAINST the run's own handoff — a check zod cannot express, because a refinement\n// sees one document and this boundary needs two. Hence a pure FUNCTION over both documents,\n// not a schema: every cited step must exist in the test it is cited for, every grounding\n// quote must be verbatim-present in the cited step's captured evidence (an invented\n// observation cannot validate — the D-05 anti-hallucination pin), every class must belong to\n// the closed §A9 union, confidence must sit inside [0,1] exactly (a reject, never a clamp),\n// every link must parse through the one `agentqa://` codec, and a no-trust-change class must\n// have honestly ruled memory misdirection out when candidate or low-trust memory was served\n// on the failing path (spec §A9 / memory.md §7.2).\n//\n// Rejects are PER TEST — `perTest` is the join key — so one confused answer never fails its\n// siblings, and each reason string names the test's specific failure because those strings\n// feed the D-03 repair round-trip verbatim.\n//\n// Link RESOLUTION is deliberately not here: `parseEntityUri` is the pure codec half of the\n// check; resolving a parsed address against the entity directory is a host concern that\n// happens at read time (plan 05), never inside schema.\n\nimport { canonicalJson } from '../determinism/canonical-json'\nimport { parseEntityUri } from '../entity/uri'\nimport type { CompletedRunHandoff } from '../handoff/completed-run-handoff'\nimport type { PerTestOutcome } from '../handoff/per-test-outcome'\nimport type { StepEvidence } from '../handoff/step-evidence'\nimport type { RunAnalysisArtifact } from './analysis-artifact'\nimport { failingStepOf } from './fingerprint-input'\nimport {\n aggregateMisdirectionEvidence,\n deriveMemoryOnPath,\n deriveMemoryOnPathSites,\n misdirectionSourceDigest,\n} from './misdirection-evidence'\nimport type {\n MemoryOnPathEntry,\n MemoryOnPathSite,\n MisdirectionRootPosture,\n} from './misdirection-evidence'\nimport type { VerdictSentenceParts } from './sentence-parts'\nimport { isVerdictClass, VERDICT_CLASSES } from './verdict'\nimport type { Verdict } from './verdict'\n\n/**\n * The verbatim-presence searched set for a step-cited grounding quote (RESEARCH A5).\n *\n * PINNED as the exact list — too narrow churns the D-03 repair loop on honest quotes, too\n * wide weakens the anti-hallucination check. A quote must be a contiguous substring of at\n * least one of these fields of the CITED step:\n *\n * - `stepText` — the authored step instruction\n * - `verifierVerdict.reasoning` — the verifier's own words\n * - any `subActions[i].plan` — a planning turn's stated intent\n * - any `subActions[i].result.error` — a captured failure message\n * - the `canonicalJson` rendering of the step's `reportedValue`, `aiJudgment`,\n * `assertOutcome` or `termination` block, when present\n *\n * The canonicalJson members exist because those blocks are structured evidence: quoting\n * `\"passed\":false` out of an assertValue outcome is quoting captured bytes, and the\n * canonical rendering is the one deterministic spelling of them. Retune from operational\n * evidence only — a field joins this list when real repair transcripts show honest quotes\n * drawn from it being rejected; never widen it to make a failing author pass.\n */\nexport const QUOTE_SEARCHED_STEP_FIELDS = [\n 'stepText',\n 'verifierVerdict.reasoning',\n 'subActions[].plan',\n 'subActions[].result.error',\n 'canonicalJson(reportedValue)',\n 'canonicalJson(aiJudgment)',\n 'canonicalJson(assertOutcome)',\n 'canonicalJson(termination)',\n] as const\n\n/**\n * The searched set for the zero-step (`source: 'test-outcome'`) quote variant: a test that\n * captured no steps has exactly its recorded outcome to quote — the same field the\n * deterministic template quotes — and nothing is fabricated beyond it.\n */\nexport const QUOTE_SEARCHED_TEST_OUTCOME_FIELDS = ['outcome'] as const\n\n/** One per-test reject; `reason` feeds the D-03 repair message verbatim. */\nexport interface AnalysisValidationReject {\n readonly perTest: number\n readonly reason: string\n}\n\nexport type AnalysisValidationResult =\n | { readonly ok: true }\n | { readonly ok: false; readonly rejects: readonly AnalysisValidationReject[] }\n\n/**\n * The caller-declared posture this validation runs under (422 D-19/D-20). Both members are\n * FAIL-CLOSED by default: an unstated root posture is an ordinary `'eval-root'` (so the BYOM\n * exemption is never granted by silence), and an unstated producer is HISTORICAL (so bytes\n * written before 422 keep their boolean-only acceptance exactly as Phase 389 wrote it).\n */\nexport interface AnalysisValidationOptions {\n /**\n * D-19. `'no-eval-root'` — the run had no evaluation root, so nothing COULD be\n * cross-checked and `backing: 'declared-only'` is admitted. `'broken-eval-root'` — a root\n * existed but could not be used; the evidence is equally empty and the posture is unbacked,\n * so `declared-only` is refused. `'eval-root'` (default) — an ordinary gated run.\n */\n readonly rootPosture?: MisdirectionRootPosture\n /**\n * D-20. True when the artifact was authored by a CURRENT gated producer, which must ship a\n * complete per-record cross-check for every record the run put on the failing path. False\n * (default) preserves historical boolean-only wire acceptance.\n */\n readonly gatedProducerEvidence?: boolean\n}\n\n/**\n * The classes whose §A9 routing moves NO trust: app_bug/flake/environment/config_error all\n * mean \"the memory was not the problem\" — which is exactly the claim a misdirected author\n * would make to shield the record that misled it, so these are the classes the\n * `memoryMisdirectionRuledOut` obligation guards (memory.md §7.2).\n */\nconst NO_TRUST_CHANGE_CLASSES: ReadonlySet<string> = new Set([\n 'app_bug',\n 'flake',\n 'environment',\n 'config_error',\n])\n\n/**\n * The searched texts of one step, in {@link QUOTE_SEARCHED_STEP_FIELDS} order. Exported so\n * the author can restate the honest quote sources in a repair message and the tests can pin\n * the set member-for-member.\n */\nexport function searchedQuoteTexts(step: StepEvidence): string[] {\n const texts: string[] = [step.stepText, step.verifierVerdict.reasoning]\n for (const subAction of step.subActions) texts.push(subAction.plan)\n for (const subAction of step.subActions) {\n if (typeof subAction.result.error === 'string') texts.push(subAction.result.error)\n }\n if (step.reportedValue !== undefined) texts.push(canonicalJson(step.reportedValue))\n if (step.aiJudgment !== undefined) texts.push(canonicalJson(step.aiJudgment))\n if (step.assertOutcome !== undefined) texts.push(canonicalJson(step.assertOutcome))\n if (step.termination !== undefined) texts.push(canonicalJson(step.termination))\n return texts\n}\n\n/** The zero-step searched texts, in {@link QUOTE_SEARCHED_TEST_OUTCOME_FIELDS} order. */\nexport function searchedTestOutcomeTexts(test: PerTestOutcome): string[] {\n return [test.outcome]\n}\n\n/** Bound a quoted string for a reject reason — the reason names the quote, not reprints it. */\nfunction quoteForReason(quote: string): string {\n return quote.length <= 80 ? quote : `${quote.slice(0, 80)}…`\n}\n\n/**\n * The steps a verdict's evidence touches: `citedSteps`, the grounding quote's own step, and —\n * the 422 D-17 widening — the run's ACTUAL failing step, whether or not the author cited it.\n *\n * The widening is the whole point. Before it, an author could dodge the misdirection gate by\n * citing a clean neighbouring step and never mentioning the step that actually failed with a\n * candidate record in its brief. `failingStepOf` is the one exported spelling of \"which step\n * this failure is about\" (390 FLAK-01), so the gate and the failure fingerprint agree about\n * the step by construction rather than by coincidence.\n *\n * Returned in the test's own step order, deduplicated — steps, not indexes, because every\n * caller below needs the served brief.\n */\nfunction pathStepsOf(\n verdict: Verdict,\n parts: VerdictSentenceParts | undefined,\n test: PerTestOutcome,\n): StepEvidence[] {\n const indexes = new Set<number>(verdict.evidence.citedSteps)\n if (parts !== undefined && 'stepIndex' in parts.groundingQuote) {\n indexes.add(parts.groundingQuote.stepIndex)\n }\n const failing = failingStepOf(test)\n if (failing !== undefined) indexes.add(failing.stepIndex)\n return test.steps.filter((step) => indexes.has(step.stepIndex))\n}\n\n/** Render an on-path set for a reject reason: `rec_a(candidate), rec_b(low-trust-active)`. */\nfunction renderMemoryOnPath(entries: readonly MemoryOnPathEntry[]): string {\n if (entries.length === 0) return 'no low-trust record'\n return entries.map((entry) => `${entry.recordId}(${entry.trust})`).join(', ')\n}\n\n/** Order-insensitive equality of a declared `memoryOnPath` against the recomputed set. */\nfunction sameMemoryOnPath(\n declared: readonly MemoryOnPathEntry[],\n recomputed: readonly MemoryOnPathEntry[],\n): boolean {\n const key = (entries: readonly MemoryOnPathEntry[]): string =>\n entries\n .map((entry) => `${entry.recordId}\u0000${entry.trust}`)\n .slice()\n .sort()\n .join('\u0001')\n return declared.length === recomputed.length && key(declared) === key(recomputed)\n}\n\n/** What the per-test walk needs beyond the two documents' per-test slices. */\ninterface ValidationContext {\n readonly runId: string\n readonly handoffBaseDigest: string\n readonly options: AnalysisValidationOptions\n}\n\n/**\n * The 422 circularity gate, applied once the class is known to move no trust AND the run's own\n * briefs put at least one low-trust record on the verdict's failing path.\n *\n * The order is the law's order: the D-19 absence exemption is decided FIRST (a run with no\n * evaluation root never had rows to ship, so demanding them would refuse the only honest\n * answer it can give), historical bytes then keep Phase 389's boolean-only acceptance, and\n * only a declared CURRENT gated producer is held to the complete D-20 ledger.\n */\nfunction validateMisdirectionEvidence(\n verdict: Verdict,\n perTest: number,\n verdictClass: string,\n sites: readonly MemoryOnPathSite[],\n context: ValidationContext,\n reject: (reason: string) => void,\n): void {\n const block = verdict.misdirectionRuledOut\n const posture = context.options.rootPosture ?? 'eval-root'\n\n if (block?.backing === 'declared-only') {\n if (posture !== 'no-eval-root') {\n reject(\n 'misdirectionRuledOut.backing \"declared-only\" is available only to a run with no ' +\n `evaluation root; this run's posture is \"${posture}\", so the claim is unbacked — ` +\n 'cross-check every record on the failing path or answer unknown',\n )\n }\n return\n }\n\n if (context.options.gatedProducerEvidence !== true) return\n\n if (block === undefined) {\n reject(\n `class \"${verdictClass}\" claims no trust change while candidate/low-trust memory was ` +\n 'served on the failing path, but no misdirectionRuledOut evidence accompanies the ' +\n 'claim — cross-check every record this run put on that path',\n )\n return\n }\n\n const aggregate = aggregateMisdirectionEvidence({\n runId: context.runId,\n perTest,\n handoffBaseDigest: context.handoffBaseDigest,\n sites,\n results: block.results,\n })\n switch (aggregate.outcome) {\n case 'held':\n return\n case 'flipped':\n reject(\n `the misdirection cross-check FLIPPED for ${aggregate.suspect.join(', ')} — the ` +\n `served memory is suspect, so class \"${verdictClass}\" cannot claim no trust ` +\n 'change; answer unknown and let the record take the harm',\n )\n return\n case 'unknown':\n reject(\n 'the misdirection cross-check did not resolve for every record on the failing path ' +\n `(inconclusive: ${aggregate.inconclusive.join(', ') || 'none'}; not-run: ` +\n `${aggregate.notRun.join(', ') || 'none'}; unchecked: ` +\n `${aggregate.unchecked.join(', ') || 'none'}) — an unresolved sibling is not a held ` +\n 'exoneration',\n )\n return\n case 'evidence-refused':\n reject(\n 'misdirectionRuledOut evidence failed key integrity: ' + aggregate.problems.join('; '),\n )\n }\n}\n\nfunction validateOneTest(\n verdict: Verdict,\n parts: VerdictSentenceParts | undefined,\n test: PerTestOutcome | undefined,\n context: ValidationContext,\n rejects: AnalysisValidationReject[],\n): void {\n const perTest = verdict.perTest\n const reject = (reason: string): void => {\n rejects.push({ perTest, reason })\n }\n\n if (test === undefined) {\n reject(`no member test with testIndex ${perTest} exists in the handoff`)\n return\n }\n\n const verdictClass: string = verdict.class\n if (!isVerdictClass(verdictClass)) {\n reject(\n `class \"${verdictClass}\" is not a member of the closed verdict union ` +\n `(${VERDICT_CLASSES.join(', ')})`,\n )\n }\n\n if (!(verdict.confidence >= 0 && verdict.confidence <= 1)) {\n reject(\n `confidence ${String(verdict.confidence)} is outside [0, 1] — answer a value inside ` +\n 'the interval, it is never clamped',\n )\n }\n\n const stepIndexes = new Set(test.steps.map((step) => step.stepIndex))\n for (const cited of verdict.evidence.citedSteps) {\n if (!stepIndexes.has(cited)) {\n reject(\n `citedSteps names step ${cited}, which does not exist in this test's captured steps`,\n )\n }\n }\n\n if (parts === undefined) {\n reject('no sentence-parts record joins this verdict by perTest')\n } else {\n validateGroundingQuote(parts, test, reject)\n for (const link of parts.links) {\n if (parseEntityUri(link) === undefined) {\n reject(`link \"${link}\" is not a parseable agentqa:// entity URI`)\n }\n }\n }\n\n // 422 D-17: membership is RECOMPUTED from the run's own served briefs, over the cited\n // steps, the grounding step AND the actual failing step. A declared `memoryOnPath` is\n // compared against it and never substituted for it.\n const pathSteps = pathStepsOf(verdict, parts, test)\n const sites = deriveMemoryOnPathSites(pathSteps)\n const recomputed = deriveMemoryOnPath(pathSteps)\n\n if (verdict.memoryOnPath !== undefined && !sameMemoryOnPath(verdict.memoryOnPath, recomputed)) {\n reject(\n `memoryOnPath declares ${renderMemoryOnPath(verdict.memoryOnPath)} but this run's own ` +\n `served briefs put ${renderMemoryOnPath(recomputed)} on the failing path — ` +\n 'membership is recomputed from the briefs, never taken from the verdict',\n )\n }\n\n if (NO_TRUST_CHANGE_CLASSES.has(verdictClass) && sites.length > 0) {\n if (verdict.memoryMisdirectionRuledOut !== true) {\n reject(\n `class \"${verdictClass}\" claims no trust change while candidate/low-trust memory ` +\n 'was served on the failing path, but memoryMisdirectionRuledOut is not true — ' +\n 'rule misdirection out explicitly or answer unknown',\n )\n } else {\n validateMisdirectionEvidence(verdict, perTest, verdictClass, sites, context, reject)\n }\n }\n}\n\nfunction validateGroundingQuote(\n parts: VerdictSentenceParts,\n test: PerTestOutcome,\n reject: (reason: string) => void,\n): void {\n const quote = parts.groundingQuote\n if (quote.quote === '') {\n reject('groundingQuote is empty — a sentence must quote captured evidence verbatim')\n return\n }\n\n if ('stepIndex' in quote) {\n if (test.steps.length === 0) {\n reject(\n `groundingQuote cites step ${quote.stepIndex} but this test captured zero steps — ` +\n 'use the test-outcome quote variant',\n )\n return\n }\n const step = test.steps.find((candidate) => candidate.stepIndex === quote.stepIndex)\n if (step === undefined) {\n reject(\n `groundingQuote cites step ${quote.stepIndex}, which does not exist in this test's ` +\n 'captured steps',\n )\n return\n }\n if (!searchedQuoteTexts(step).some((text) => text.includes(quote.quote))) {\n reject(\n `quote not found: \"${quoteForReason(quote.quote)}\" is not verbatim-present in any ` +\n `searched field of step ${quote.stepIndex} ` +\n `(${QUOTE_SEARCHED_STEP_FIELDS.join(', ')})`,\n )\n }\n return\n }\n\n if (!searchedTestOutcomeTexts(test).some((text) => text.includes(quote.quote))) {\n reject(\n `quote not found: \"${quoteForReason(quote.quote)}\" is not verbatim-present in the ` +\n \"test's outcome fields\",\n )\n }\n}\n\n/**\n * Validate an analysis artifact against the run's handoff — pure and synchronous over its\n * arguments, per-test granular, reject reasons shaped for the repair loop.\n *\n * `options` is additive and fail-closed (422): omitting it reproduces the pre-422 acceptance\n * surface exactly, so every existing caller keeps compiling and keeps its answers.\n */\nexport function validateAnalysisAgainstHandoff(\n artifact: RunAnalysisArtifact,\n handoff: CompletedRunHandoff,\n options: AnalysisValidationOptions = {},\n): AnalysisValidationResult {\n const rejects: AnalysisValidationReject[] = []\n const context: ValidationContext = {\n runId: handoff.runId,\n handoffBaseDigest: misdirectionSourceDigest(handoff),\n options,\n }\n const testsByIndex = new Map(handoff.tests.map((test) => [test.testIndex, test]))\n // Duplicate perTest entries are refused upstream by `guardRunAnalysisArtifact` — the\n // rule's one owner (G-389-3B / WR-02). This two-document boundary deliberately does not\n // re-spell uniqueness (a Map here silently keeps the last duplicate, and that is fine);\n // the executable non-owner pin lives in this module's test suite.\n const partsByPerTest = new Map(artifact.parts.map((parts) => [parts.perTest, parts]))\n\n for (const verdict of artifact.verdicts) {\n validateOneTest(\n verdict,\n partsByPerTest.get(verdict.perTest),\n testsByIndex.get(verdict.perTest),\n context,\n rejects,\n )\n }\n\n return rejects.length === 0 ? { ok: true } : { ok: false, rejects }\n}\n","// The committed quarantine ledger's event contract and state vocabulary (Phase 390, D-01/D-03).\n//\n// `quarantine.jsonl` is a COMMITTED append-only event log at the knowledge root — its own\n// top-level artifact beside memory/ and policies/ — so a fresh CI checkout inherits quarantine\n// state and FLAK-02's non-failing disposition holds on every machine. Every line carries its own\n// `schemaVersion` (headerless, the outcomes.jsonl idiom) and crosses this one guard.\n//\n// THREE THINGS ARE DELIBERATE HERE:\n//\n// 1. The event list is append-only LIFECYCLE ACTIONS only. `'expired'` is NOT an event: it is a\n// COMPUTED state derived from an entry's `expiresAt` against the caller's `now` (D-11). Wall\n// clock enters the fold as an argument and is stamped into events at write time — this module\n// reads no clock at all, and neither does the fold that consumes it.\n// 2. Stable test identity is `(product, filePath, testName)`, never `testId` (a per-run explicit\n// id, not a durable identity). Every event and every folded entry is keyed that way.\n// 3. The `filePath` leg is the WORKSPACE-RELATIVE source path — rooted at the config directory,\n// forward-slashed, no leading `./` — which is the same bytes on every checkout (390-08 / D-01).\n// This is what makes the inheritance claim above TRUE rather than asserted: the match at\n// `quarantineAppliesToTest` is an exact string compare, so an absolute path (the version-1\n// shape) could only ever match on the one machine that wrote it. The absolute form is refused\n// structurally by {@link hasQuarantineEventShape}, so a hand-edited machine-local line cannot\n// silently re-enter the committed file.\n//\n// Consumers: the knowledge-local ledger read/fold (`readQuarantineLedger`/\n// `foldQuarantineLedgerState`), the CLI run-start snapshot (D-16), the quarantine list/add/release\n// verbs, and the recurrence clause's ladder arms (D-17).\n\nimport {\n createVersionGuard,\n VersionGuardError,\n} from '../versioning/create-version-guard'\nimport type { MigrationRegistry } from '../versioning/create-version-guard'\nimport { isVerdictClass } from '../verdict/verdict'\nimport type { VerdictClass } from '../verdict/verdict'\n\n/**\n * Version 2 (390-08 / CR-02): the `filePath` identity leg is workspace-relative. Version 1 stamped\n * a machine-local ABSOLUTE path, which no other checkout can interpret — the bump moves the\n * contract while it is still FREE (zero `quarantine.jsonl` files exist in the wild, verified\n * 2026-08-05) rather than after entries start circulating through PRs and CI checkouts.\n */\nexport const CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION = 2\n\n/**\n * The closed lifecycle-action union, spelled ONCE (388 C13). `entered` opens a window,\n * `renewed` extends it (and may claim the owner), and the two `released-*` kinds close it —\n * `released-auto` from the M-consecutive-passes exit, `released-manual` from the human half of\n * the exit path. There is deliberately no `expired` member (see the module head).\n */\nexport const QUARANTINE_EVENT_KINDS = [\n 'entered',\n 'renewed',\n 'released-manual',\n 'released-auto',\n] as const\n\nexport type QuarantineEventKind = (typeof QUARANTINE_EVENT_KINDS)[number]\n\nconst QUARANTINE_EVENT_KIND_SET: ReadonlySet<string> = new Set(QUARANTINE_EVENT_KINDS)\n\n/** True for exactly the four closed lifecycle actions. */\nexport function isQuarantineEventKind(value: unknown): value is QuarantineEventKind {\n return typeof value === 'string' && QUARANTINE_EVENT_KIND_SET.has(value)\n}\n\n/**\n * The typed literal every auto-entry carries until a human claims it (D-12): honest absence over\n * invented attribution — no git-identity stamping, no CODEOWNERS guessing. The list verb surfaces\n * unassigned entries FIRST because they are the triage queue.\n */\nexport const QUARANTINE_UNASSIGNED_OWNER = 'unassigned'\n\n/** An entry's owner: the unassigned literal, or whatever name a human claimed it under. */\nexport type QuarantineOwner = typeof QUARANTINE_UNASSIGNED_OWNER | (string & {})\n\n/**\n * Every event carries the version stamp, its kind, the ISO instant it was authored at, and the\n * three legs of stable test identity. Kind-specific fields hang off the arms below.\n */\ninterface QuarantineEventBase {\n /**\n * The CURRENT version literal, not `number` — and the literal is load-bearing rather than\n * decorative. It closes the one producer no runtime check on the write path can reach: an\n * in-tree TypeScript author hand-stamping a superseded version. That producer is not\n * hypothetical — it got this wrong TWICE during phase 390, after the 390-08 bump\n * (`cli/src/__tests__/curation-tail.test.ts:1789` and `:1804`, both `schemaVersion: 1`), and\n * both survived review because of where those objects happened to go rather than because\n * anything stopped them. Measured cost of the narrowing: those two fixtures, and nothing else —\n * all five production mint sites already spell {@link CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION}\n * literally.\n *\n * The literal is free only while {@link QUARANTINE_LEDGER_MIGRATIONS} stays empty by the stated\n * decision below. If that decision is ever reversed, this type becomes a UNION of the current\n * version plus every version carrying a registered migration — i.e. exactly the rule\n * {@link guardQuarantineLedgerEvent} already enforces on the read — and the append's version\n * pre-check widens the same way.\n */\n schemaVersion: typeof CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION\n kind: QuarantineEventKind\n /** ISO-8601 instant, stamped by the CALLER at write time (this module reads no clock). */\n at: string\n /** The slugged product partition, matching the run-outcome projection's own key. */\n product: string\n /**\n * The WORKSPACE-RELATIVE source path: rooted at the config directory, forward-slashed, no\n * leading `./` — minted once by the CLI through `workspaceRelativeIdentityPath` (390-08). These\n * are the same bytes on every checkout, which is the whole reason the committed ledger can hand\n * a disposition to a machine that never saw the run that wrote it. An absolute path is refused\n * by {@link hasQuarantineEventShape}; it is never used for file access, only for identity.\n */\n filePath: string\n testName: string\n}\n\n/** A window opens: the fingerprint that crossed, its resolved class, an owner, and a deadline. */\nexport interface QuarantineEnteredEvent extends QuarantineEventBase {\n kind: 'entered'\n fingerprint: string\n verdictClass: VerdictClass\n owner: QuarantineOwner\n /** ISO-8601 deadline, stamped at write time. On lapse, suppression STOPS (D-11). */\n expiresAt: string\n}\n\n/** A window extends, and optionally gets claimed out of `unassigned` (D-13's renew-on-re-add). */\nexport interface QuarantineRenewedEvent extends QuarantineEventBase {\n kind: 'renewed'\n expiresAt: string\n owner?: QuarantineOwner\n}\n\n/** A window closes. Identity only — the reason lives in which of the two kinds it is. */\nexport interface QuarantineReleasedEvent extends QuarantineEventBase {\n kind: 'released-manual' | 'released-auto'\n}\n\nexport type QuarantineLedgerEvent =\n | QuarantineEnteredEvent\n | QuarantineRenewedEvent\n | QuarantineReleasedEvent\n\n/**\n * Thrown when a stored ledger line declares a `schemaVersion` this build cannot consume: newer\n * than {@link CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION}, or older with no registered migration.\n *\n * The ledger is COMMITTED truth, so this is a hard failure rather than a skipped line — only\n * derived projections heal. A skipped line would silently un-quarantine a test.\n */\nexport class QuarantineLedgerVersionError extends VersionGuardError {\n constructor(found: number, supported: number) {\n super('QuarantineLedgerEvent', found, supported)\n this.name = 'QuarantineLedgerVersionError'\n }\n}\n\n/**\n * The older-version migration seam — DELIBERATELY EMPTY, registered so growth is additive.\n *\n * There is no `1 -> 2` entry and there will never be one. A version-1 line's `filePath` is a\n * machine-local absolute path; migrating it to the workspace-relative identity would require\n * GUESSING the checkout root it was written under, and a wrong guess produces an entry that\n * silently suppresses the wrong test (or nothing at all) forever. Refusal through\n * {@link QuarantineLedgerVersionError} is the honest arm: the read fails loudly, the run-start\n * snapshot degrades to empty with a printed warning, and the human deletes three lines of a file\n * that — by construction — no repository actually has (zero v1 ledgers exist, verified 2026-08-05).\n */\nexport const QUARANTINE_LEDGER_MIGRATIONS: MigrationRegistry = {}\n\nfunction isNonArrayObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0\n}\n\n/** A POSIX root, a Windows drive root (either slash direction), or a UNC/backslash root. */\nconst ABSOLUTE_PATH_PREFIX = /^([/\\\\]|[A-Za-z]:[/\\\\])/\n\n/**\n * A Windows DRIVE-RELATIVE prefix (`C:foo\\bar`) — a per-drive cwd-relative path, which\n * {@link ABSOLUTE_PATH_PREFIX} deliberately misses because it carries no root separator. It is not\n * absolute, and it is not the mint's output either.\n */\nconst DRIVE_RELATIVE_PREFIX = /^[A-Za-z]:/\n\n/**\n * Is this `filePath` the identity the mint PRODUCES (390-08 / CR-02, 390-11 / WR-01)?\n *\n * Positive domain, not merely \"not absolute\": `workspaceRelativeIdentityPath` emits a\n * configDir-rooted, forward-slashed, `./`-trimmed, `..`-free path, and that is exactly the set\n * admitted here — root-free, backslash-free, drive-prefix-free, and carrying no `.` or `..`\n * segment. The predicate previously enumerated only the NEGATIVE (absolute) domain, which is a\n * strictly weaker claim: `./tests/a.yaml`, `tests\\a.yaml` and `../outside.yaml` all passed it,\n * folded, and listed as `quarantined` while `quarantineAppliesToTest` compares `===` against the\n * mint's output and could never match one of them. That is silent suppression theater — the\n * loudest failure mode this phase exists to prevent — so those forms are now refused too.\n *\n * String predicates only, on purpose: this package bans host APIs, so the platform path module is\n * unavailable and the Windows forms have to be spelled here rather than delegated to\n * `isAbsolute` (which on a POSIX host would happily call `C:\\repo\\x.yaml` relative anyway).\n */\nfunction isWorkspaceRelativeIdentity(value: string): boolean {\n if (ABSOLUTE_PATH_PREFIX.test(value)) return false\n if (DRIVE_RELATIVE_PREFIX.test(value)) return false\n if (value.includes('\\\\')) return false\n return value.split('/').every((segment) => segment !== '.' && segment !== '..')\n}\n\n/**\n * Fail-closed structural check on one stored event, at the depth the fold traverses: the kind\n * inside the closed union, all three identity legs present and non-empty, the `filePath` leg\n * inside the mint's own positive domain — forward-slashed, root-free, `./`-trimmed, `..`-free —\n * and every kind-specific field the arm declares. An `entered` event with no `expiresAt` would\n * fold to a forever suppression, so its absence is refused rather than defaulted; a `filePath` no\n * other checkout can match is refused rather than normalized (this module cannot know the checkout\n * root, so any normalization here would be a guess).\n *\n * The read-side consequence is deliberate and worth naming: a hand-edited relative-but-unmatchable\n * line now lands in `refusedLines` as LINE-LEVEL DAMAGE the human can see and fix, instead of\n * folding into an entry that lists as `quarantined` while suppressing nothing. Refusal stays DATA\n * — never a run abort (the T-390-04 posture is unchanged), and never healing to absence.\n *\n * This is also the predicate the WRITE side ranges: the knowledge-local ledger append pre-checks\n * every event with it, so no caller can commit bytes THIS guard will refuse (390-11 / WR-07). Note\n * the scope — this is the STRUCTURAL leg only, and its version clause asks merely that\n * `schemaVersion` be a number. {@link guardQuarantineLedgerEvent} wraps it in a version identity\n * check, which the append ranges SEPARATELY against\n * {@link CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION} (390-14 / G-390-1) rather than through this\n * predicate.\n */\nexport function hasQuarantineEventShape(value: unknown): boolean {\n if (!isNonArrayObject(value)) return false\n if (typeof value.schemaVersion !== 'number') return false\n if (!isQuarantineEventKind(value.kind)) return false\n if (!isNonEmptyString(value.at)) return false\n if (!isNonEmptyString(value.product)) return false\n if (!isNonEmptyString(value.filePath)) return false\n if (!isWorkspaceRelativeIdentity(value.filePath)) return false\n if (!isNonEmptyString(value.testName)) return false\n\n switch (value.kind) {\n case 'entered':\n return (\n isNonEmptyString(value.fingerprint) &&\n isVerdictClass(value.verdictClass) &&\n isNonEmptyString(value.owner) &&\n isNonEmptyString(value.expiresAt)\n )\n case 'renewed':\n return (\n isNonEmptyString(value.expiresAt) &&\n (!('owner' in value) || isNonEmptyString(value.owner))\n )\n case 'released-manual':\n case 'released-auto':\n return true\n }\n}\n\n/**\n * The read side of the ledger version discipline: parse → reject-newer with a typed\n * {@link QuarantineLedgerVersionError} → migrate-older through\n * {@link QUARANTINE_LEDGER_MIGRATIONS} → structural check. Every ledger consumer routes here.\n */\nexport const guardQuarantineLedgerEvent = createVersionGuard<QuarantineLedgerEvent>({\n name: 'QuarantineLedgerEvent',\n current: CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION,\n migrations: QUARANTINE_LEDGER_MIGRATIONS,\n error: QuarantineLedgerVersionError,\n shape: hasQuarantineEventShape,\n})\n\n/**\n * The state vocabulary, minted ONCE (388 C13) so the fold, the list verb, the entity card and the\n * sentence clause all speak the same three words.\n *\n * `'quarantined'` suppresses; `'expired'` does NOT (the entry stays listed, renewable and\n * releasable — a lapsed window, not a closed one: a still-recurring fingerprint re-enters, D-11);\n * `'released'` is a closed window kept for the history the event log answers for free.\n */\nexport const QUARANTINE_ENTRY_STATE_NAMES = ['quarantined', 'expired', 'released'] as const\n\nexport type QuarantineEntryStateName = (typeof QUARANTINE_ENTRY_STATE_NAMES)[number]\n\n/**\n * One folded entry: the durable identity, the entry's own facts, its accumulated history, and its\n * computed state.\n *\n * TWO INSTANTS, TWO QUESTIONS (390-18). `enteredAt` is when the CURRENT window opened — the fact\n * `expiresAt` and `state` are relative to. `firstEnteredAt` is when this test's quarantine history\n * began, which is the fact a human triaging it is actually deciding about, and the key the triage\n * queue sorts on. For a first entry they coincide; for a test that has been here before they do\n * not, and reading one where the other was meant is the drift this docstring exists to prevent.\n *\n * `enteredCount` and `firstEnteredAt` are DERIVED by the fold from `entered` events already\n * committed — no event kind carries them, {@link CURRENT_QUARANTINE_LEDGER_SCHEMA_VERSION} is\n * unmoved and no migration exists for them. Every ledger already written answers both correctly on\n * its next fold.\n */\nexport interface QuarantineEntryState {\n product: string\n filePath: string\n testName: string\n fingerprint: string\n verdictClass: VerdictClass\n owner: QuarantineOwner\n enteredAt: string\n expiresAt: string\n /** How many `entered` events this identity has accumulated. A renewal is not one; minimum 1. */\n enteredCount: number\n /** The `at` of this identity's FIRST `entered` event — when its history began. */\n firstEnteredAt: string\n state: QuarantineEntryStateName\n}\n\n/**\n * The detection ladder's visible rungs (D-06/D-17). `'flagged'` is detection-layer visibility only\n * — one build of warning before action — and NEVER appears in the ledger; it exists in this union\n * because the recurrence answer renders all three arms from one vocabulary.\n */\nexport type QuarantineLadderState = 'flagged' | 'quarantined' | 'expired'\n\n/**\n * What a run records about the ledger entries it applied at run start (D-16, Open Q2): minimal\n * identity plus the expiry that says how long the disposition was licensed for. The handoff is\n * schema-versioned and every field on it is forever, so this stays deliberately small — owner,\n * fingerprint and history live in the ledger, which is the durable truth.\n */\nexport interface QuarantineAppliedEntry {\n product: string\n filePath: string\n testName: string\n expiresAt: string\n}\n\n/**\n * The STABLE test identity a snapshot entry is matched against — `(filePath, testName)`, never\n * `testId`, which is a per-run explicit id that does not survive to the next build.\n */\nexport interface QuarantineSnapshotMatch {\n filePath: string\n testName: string\n}\n\n/**\n * Does the run-start snapshot license this test's failure (390 D-14/D-16)?\n *\n * ONE spelling of the match, consumed by everything that has to agree about it: the runner's\n * aggregate verdict rule (which decides the exit code) and both CLI reporters (which tell the human\n * and the CI parser why a red row did not fail the build). Two spellings could disagree without\n * failing to compile, and the disagreement would surface as a reporter announcing a suppression\n * that never happened — precisely the un-quarantine evidence FLAK-02 exists to keep flowing.\n *\n * `product` is deliberately NOT compared: the composition layer filters the snapshot to the run's\n * product before handing it over (D-16), so re-deriving product bytes downstream would be a second,\n * drift-prone spelling of that rule.\n */\nexport function quarantineAppliesToTest(\n applied: readonly QuarantineAppliedEntry[] | undefined,\n test: QuarantineSnapshotMatch,\n): boolean {\n if (applied === undefined) return false\n return applied.some(\n (entry) => entry.filePath === test.filePath && entry.testName === test.testName,\n )\n}\n","// The three quarantine verbs' wire contract, and the port the ops dispatch through\n// (Phase 390, D-12/D-13).\n//\n// MINTED IN SCHEMA, not in `agent` (384 D-16). Two packages consume this contract and neither\n// may import the other: `agent` declares the op specs against these validators, and\n// knowledge-local implements {@link QuarantineOperationsPort} over the committed ledger. A\n// port type declared beside the ops would have made the implementing package depend on the\n// function layer, which is precisely the dependency the storage-neutral split forbids.\n//\n// THREE THINGS ARE DELIBERATE HERE:\n//\n// 1. THE VOCABULARIES ARE IMPORTED (388 C13). The entry DTO's `state` enum is constructed out\n// of the ledger's own {@link QUARANTINE_ENTRY_STATE_NAMES}, and its class enum out of the\n// canonical `VERDICT_CLASSES`. There is no second spelling of either union in this file,\n// so a fourth ledger state cannot arrive with the wire contract still admitting three.\n// 2. ABSENCE AND RE-ENTRY ARE RESULT ARMS, NEVER THROWS (D-13). `release` on a test that is\n// not quarantined answers `no-entry`; `add` on one that already is answers `renewed`,\n// having extended the expiry and claimed the owner when one was supplied. Both are\n// ordinary states of the world an operator asks about, and a rejected promise would say\n// \"that failed\" while discarding the entry the caller asked to see. Same reasoning the\n// knowledge apply outcome records for its already-applied arm.\n// 3. NO CLOCK CROSSES THIS CONTRACT. `add` may carry an explicit `expiresAt`, but an ABSENT\n// one is not defaulted here — the implementation stamps the pinned default lifetime at\n// write time, exactly as 390-01's fold takes `now` as an argument rather than reading it.\n// A caller-supplied \"now\" would let the caller forge the deadline the ledger records.\n\nimport { z } from 'zod'\n\nimport { VERDICT_CLASSES } from '../verdict/verdict'\nimport { QUARANTINE_ENTRY_STATE_NAMES } from './quarantine-ledger'\nimport type { QuarantineEntryState } from './quarantine-ledger'\n\n/**\n * One folded ledger entry as every surface lists it — D-13's enumeration contract in full:\n * the three legs of stable test identity, the fingerprint that keyed the window, the resolved\n * class, the owner (D-12's `unassigned` literal until a human claims it), the entry instant,\n * the accumulated re-entry history, the deadline, and the computed state.\n *\n * The owner leg is a non-empty string rather than an enum on purpose: the ledger's own owner\n * type is the unassigned literal widened by whatever name a human claimed it under, so an\n * enum here would be a closed set the ledger deliberately does not have.\n *\n * `enteredCount` and `firstEnteredAt` (390-18) are the ledger's own DERIVATIONS, not stored\n * bytes — the fold computes them over `entered` events already committed, so nothing about the\n * ledger's version or its migrations moves to carry them. They are on the wire because\n * \"this test has re-entered quarantine 7 times, and its history began 214 days ago\" is the fact\n * that prompts a human decision, and a surface cannot say it from a row that has no past. HOW a\n * surface phrases that is the surface's decision; this contract only carries the two numbers.\n *\n * The `satisfies` below is this widening's COMPLETENESS ORACLE: `QuarantineEntryState` gaining a\n * leg that this strict object does not carry is a compile error, so the wire contract cannot\n * silently answer less than the fold knows.\n */\nexport const QuarantineEntrySchema = z.object({\n product: z.string().min(1),\n filePath: z.string().min(1),\n testName: z.string().min(1),\n fingerprint: z.string().min(1),\n verdictClass: z.enum(VERDICT_CLASSES),\n owner: z.string().min(1),\n enteredAt: z.string().min(1),\n expiresAt: z.string().min(1),\n enteredCount: z.number().int().positive(),\n firstEnteredAt: z.string().min(1),\n state: z.enum(QUARANTINE_ENTRY_STATE_NAMES),\n}).strict() satisfies z.ZodType<QuarantineEntryState>\n\n/**\n * `quarantine.list` enumerates EVERYTHING the ledger folds to — no filter members.\n *\n * Owner and state filtering are reader concerns downstream (a dashboard column, a CLI flag\n * over the returned rows), and putting them here would have made the verb's answer depend on\n * how it was asked. The triage-queue ordering D-12 requires — unassigned owners first — is\n * the implementation's law, pinned where the implementation lands, never re-sorted by a\n * caller that received the rows.\n */\nexport const QuarantineListInputSchema = z.object({}).strict()\n\nexport type QuarantineListInput = z.infer<typeof QuarantineListInputSchema>\n\n/** Every entry the ledger folds to, in the implementation's stable order. */\nexport const QuarantineListOutputSchema = z.object({\n entries: z.array(QuarantineEntrySchema),\n}).strict()\n\nexport type QuarantineListOutput = z.infer<typeof QuarantineListOutputSchema>\n\n/**\n * The three legs of stable test identity — never `testId`, which is per-run and not durable.\n *\n * TWO of the three are accepted RAW here and normalized by the implementation, for one reason: a\n * leg the ledger's READERS transform needs a matching writer-side transform, and a schema that\n * demanded pre-transformed bytes would put the rule in two places and refuse the exact input the\n * human half of the exit path exists to accept. One rule, one home — and the home is\n * `createQuarantineOperations`, at the boundary of both write verbs.\n *\n * `product` lands in the slugged partition every reader compares (WR-01 / 390-09):\n * `createQuarantineOperations` runs it through `slugBranch`, so a human typing `My Product` reaches\n * the `My-Product` partition `resolveRunQuarantineSnapshot` filters on.\n *\n * `filePath` lands as the durable workspace-relative IDENTITY every reader compares with `===`\n * (390-12 / D-01): the same boundary mints it through core's `workspaceRelativeIdentityPath`,\n * pre-bound by the host to its own config directory — which is why the rule cannot live here, in a\n * package that knows no checkout root. A path that cannot be canonicalized for this checkout is\n * refused typed by the implementation rather than stored. Before that mint existed, an absolute\n * path from a failure report became a permanently unreadable line in a COMMITTED artifact.\n *\n * `testName` is the leg no reader transforms, so nothing normalizes it anywhere.\n */\nconst identityShape = {\n product: z.string().min(1),\n filePath: z.string().min(1),\n testName: z.string().min(1),\n} as const\n\n/** `quarantine.release` addresses exactly one quarantined test — the human half of the exit path. */\nexport const QuarantineReleaseInputSchema = z.object({ ...identityShape }).strict()\n\nexport type QuarantineReleaseInput = z.infer<typeof QuarantineReleaseInputSchema>\n\n/**\n * What a release did: the window it closed, or the named absence.\n *\n * `no-entry` is an ARM rather than a refusal because \"that test is not quarantined\" is an\n * ordinary answer to an ordinary question — a stale entry in someone's notes, a release that\n * already happened, an auto-exit that beat the human to it — and none of those is a broken\n * store. The released arm carries the entry so a surface can say WHAT it released without a\n * second read.\n *\n * The `released` discriminant is THIS VERB's outcome vocabulary and not the ledger's entry\n * state union — the two share a word and nothing else. An entry's state is read off\n * {@link QuarantineEntrySchema}, whose enum is constructed out of the ledger's own const.\n */\nexport const QuarantineReleaseOutputSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('released'), entry: QuarantineEntrySchema }).strict(),\n z.object({ kind: z.literal('no-entry') }).strict(),\n])\n\nexport type QuarantineReleaseOutput = z.infer<typeof QuarantineReleaseOutputSchema>\n\n/**\n * `quarantine.add` is manual ENTRY, renewal and the owner claim in one verb (D-13).\n *\n * Not three verbs, because in an append-only event log they are one gesture with different\n * prior state: re-adding an already-quarantined identity is a `renewed` event that extends\n * the deadline and claims the owner when one was supplied. Splitting them would have made a\n * caller ask the ledger what state a test is in before it could pick a verb — a read whose\n * answer can change between the two calls.\n *\n * `owner` absent leaves an auto-entry's `unassigned` in place (D-12: honest absence over\n * invented attribution — nothing here stamps a git identity). `expiresAt` absent takes the\n * pinned default lifetime at the implementation (D-11).\n */\nexport const QuarantineAddInputSchema = z.object({\n ...identityShape,\n owner: z.string().min(1).optional(),\n expiresAt: z.string().min(1).optional(),\n}).strict()\n\nexport type QuarantineAddInput = z.infer<typeof QuarantineAddInputSchema>\n\n/**\n * What an add did: opened a window, or extended one that was already open.\n *\n * Both arms carry the resulting entry, so a caller reading `renewed` learns the new deadline\n * and the owner in the same answer that told it the entry already existed. The discriminant is\n * the whole point — \"already quarantined\" is information an operator acts on, not an error.\n */\nexport const QuarantineAddOutputSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('entered'), entry: QuarantineEntrySchema }).strict(),\n z.object({ kind: z.literal('renewed'), entry: QuarantineEntrySchema }).strict(),\n])\n\nexport type QuarantineAddOutput = z.infer<typeof QuarantineAddOutputSchema>\n\n/**\n * The injected capability the three ops dispatch through — one OPTIONAL dep, three verbs.\n *\n * One port and not two (a reader plus a writer) because all three verbs need the same\n * substrate: the committed ledger under the knowledge root, folded through the one state fold.\n * The read/write asymmetry that matters is already stated where it is ENFORCED — `list`\n * declares read scopes and a read-only risk descriptor, `release` and `add` declare a write\n * scope and `readOnly: false` — so splitting the port would have restated at the composition\n * root a distinction the gate already makes at every call.\n *\n * `list` answers entries and NOT the wire envelope, so the ordering law and the envelope stay\n * separable: the op wraps, the implementation orders.\n *\n * Implementations own three things this contract deliberately does not: the D-12 triage-queue\n * ordering, the pinned default lifetime an absent `expiresAt` takes, and the wall clock every\n * event instant is stamped with. All three are host facts, and a port that accepted them as\n * arguments would let a caller decide them.\n */\nexport interface QuarantineOperationsPort {\n list(): Promise<readonly QuarantineEntryState[]>\n release(input: QuarantineReleaseInput): Promise<QuarantineReleaseOutput>\n add(input: QuarantineAddInput): Promise<QuarantineAddOutput>\n}\n","import { z } from 'zod'\n\n/**\n * The schema-owned run-scoped working-memory vocabulary (Phase 358, WM-01, D-14).\n * A `WorkingMemoryEntry` is one verbatim fact the planner captured mid-run via the\n * ratified `remember[]` plan-field (spec `tools-and-actions.md` §12.15, write channel\n * ratified 2026-07-05 — not a tool, no catalog change). The enums are CLOSED: the\n * planner cannot mint new categories, and unknown values are rejected at the plan-field\n * boundary (V5 input validation of untrusted model output).\n *\n * Pure DTO + zod validator only: no host or runtime IO APIs — the schema-package\n * ownership contract (pure sync types + zod).\n */\nexport interface WorkingMemoryEntry {\n /** Exact-recall key. Latest-wins on re-capture (D-12); one key ⇒ one current value. */\n key: string\n /** The verbatim captured value, kept masked in snapshots/flush (never unmasked). */\n value: string\n /** Closed category of the captured fact. */\n kind: 'code' | 'filename' | 'extracted-value' | 'progress-marker'\n /** Closed provenance of how the planner obtained the value. */\n provenance: 'observation' | 'toolResult' | 'plannerInference'\n /**\n * Optional capture-location context (D-11): the whole run set is served every turn,\n * so the planner weighs relevance itself — these carry where the entry was captured,\n * not a filter rule.\n */\n testIndex?: number\n stepIndex?: number\n}\n\nconst workingMemoryKindValues = [\n 'code',\n 'filename',\n 'extracted-value',\n 'progress-marker',\n] as const satisfies readonly WorkingMemoryEntry['kind'][]\n\nconst workingMemoryProvenanceValues = [\n 'observation',\n 'toolResult',\n 'plannerInference',\n] as const satisfies readonly WorkingMemoryEntry['provenance'][]\n\nexport const workingMemoryEntrySchema = z\n .object({\n key: z.string(),\n value: z.string(),\n kind: z.enum(workingMemoryKindValues),\n provenance: z.enum(workingMemoryProvenanceValues),\n testIndex: z.number().optional(),\n stepIndex: z.number().optional(),\n })\n .strict()\n","// What a caller asks the agent job queue for (Phase 385, D-08 / D-17 / JOBQ-05).\n//\n// This is the REQUEST vocabulary: the three facts a caller actually knows. It is deliberately\n// not the row the store inserts — the job's id is derived from the kind and the key by an\n// injected id source at the engine boundary, and its summary is composed there too, so a\n// caller that had to supply either could make the same logical job carry two identities.\n// The port's insert type is that resolved shape and extends this one; keeping the two apart\n// is what lets a handler ask for a successor without minting ids on the store's behalf.\n//\n// The idempotency key is MANDATORY here and nowhere is it optional. Dedupe rests on a\n// `(kind, idempotencyKey)` unique index, so a missing key leaves the index nothing to match\n// on and an EMPTY key matches everything — one shared row for every job of the kind. The\n// type forbids the first and the min-length rule forbids the second; neither alone is\n// enough, because a runtime schema cannot police a compile-time caller and a type cannot\n// police bytes arriving from another process.\n\nimport { z } from 'zod'\n\nimport { jobKindValues } from './job'\nimport type { JobKind } from './job'\n\nexport interface JobEnqueueRequest {\n kind: JobKind\n payload: unknown\n idempotencyKey: string\n}\n\n/**\n * A successor a handler's deterministic tail asks for (D-17).\n *\n * Structurally an enqueue request, and named separately because the ROLE differs: the\n * topology of what may chain to what is declared once on the kind, while the instances come\n * back from the handler as ordinary data. An outcome-dependent chain is then a value, not a\n * special case in the engine.\n */\nexport type ChainedJobRequest = JobEnqueueRequest\n\nexport const jobEnqueueRequestSchema = z\n .object({\n kind: z.enum(jobKindValues),\n payload: z.unknown(),\n idempotencyKey: z.string().min(1),\n })\n .strict()\n\n/**\n * The same rules, under the successor's name.\n *\n * Deliberately the identical schema value rather than a copy: two schemas would be free to\n * drift, and the direction that drift would take is obvious — a chained enqueue quietly\n * accepting a key a root enqueue refuses.\n */\nexport const chainedJobRequestSchema = jobEnqueueRequestSchema\n","// The on-disk contract for one agent job checkpoint (Phase 385, D-01 / D-04 / JOBQ-05).\n//\n// Under the hybrid split each checkpoint is its own committed artifact, and every committed\n// artifact in this repo carries a literal version stamp with no migration machinery behind\n// it (the v51 convention). Literal, not a number range: a build that read a stamp it did not\n// write would be guessing at the layout of bytes it is about to resume from, and a wrong\n// guess about a resume point is indistinguishable from progress that never happened. On a\n// mismatch the reader refuses and the operator clears queue state.\n//\n// The ENVELOPE is what this module owns; the payload stays `unknown` on purpose. What a\n// checkpoint means belongs to the engine that publishes it, and pinning a payload shape here\n// would make every new job kind a change to the shared contract.\n//\n// A note on the name. The store's own `PRAGMA user_version` is a DIFFERENT version with a\n// different lifetime — it describes table layout, this describes file layout — so this\n// constant is named for the checkpoint rather than for the store, and the two must not be\n// collapsed into one number just because both currently read 1.\n\nimport { z } from 'zod'\n\nimport { asJobId } from './job-id'\nimport type { JobId } from './job-id'\n\nexport const JOB_CHECKPOINT_SCHEMA_VERSION = 2\n\nexport interface JobCheckpointEnvelope {\n schemaVersion: typeof JOB_CHECKPOINT_SCHEMA_VERSION\n jobId: JobId\n checkpointId: string\n payload: unknown\n}\n\nconst jobIdSchema = z.string().min(1).transform(asJobId)\n\nexport const jobCheckpointEnvelopeSchema = z\n .object({\n schemaVersion: z.literal(JOB_CHECKPOINT_SCHEMA_VERSION),\n jobId: jobIdSchema,\n // Both ids become path segments in the local store, so neither may be empty here even\n // before the store applies its own stricter segment rule.\n checkpointId: z.string().min(1),\n payload: z.unknown(),\n })\n .strict()\n","// What a job handler reports when it returns (Phase 385, D-17 / D-18 / D-20).\n//\n// Three arms, discriminated. Without the discriminant, \"the work finished and chains\n// nothing\" and \"the work failed\" are the same shape, and the engine would have to infer\n// failure from an absence — which is how a handler that threw halfway lands as a clean\n// completion. The split between `retryable` and `permanent` is D-18's: the handler knows\n// whether the thing that went wrong could go right next time; only the engine knows whether\n// any attempts remain. So this type is the handler's REPORT, and the disposition the store\n// records is the engine's DECISION over it — a retryable report on the last permitted\n// attempt still becomes a permanent disposition. Collapsing the two would delete that\n// distinction and with it the bound on retries.\n//\n// Successors ride on the completion arm alone. A failed attempt that could still enqueue\n// follow-on work would leave the chain half-built with no record of which half.\n\nimport { z } from 'zod'\n\nimport { chainedJobRequestSchema } from './job-enqueue'\nimport type { ChainedJobRequest } from './job-enqueue'\n\nexport type JobHandlerOutcome =\n | { status: 'complete'; next: ChainedJobRequest[] }\n | { status: 'retryable'; reason: string }\n | { status: 'permanent'; reason: string }\n\nexport const jobHandlerOutcomeSchema = z.discriminatedUnion('status', [\n z\n .object({\n status: z.literal('complete'),\n // The successor list is the request schema itself, so a successor that could not be\n // enqueued on its own cannot arrive through a completion either. An array of anything\n // looser would let a chain smuggle in the empty key the enqueue rules exist to refuse.\n next: z.array(chainedJobRequestSchema),\n })\n .strict(),\n z.object({ status: z.literal('retryable'), reason: z.string().min(1) }).strict(),\n z.object({ status: z.literal('permanent'), reason: z.string().min(1) }).strict(),\n])\n","// The `analyze-run` job payload, mirrored as a schema (Phase 393, D-20).\n//\n// TWO READERS, DELIBERATELY ASYMMETRIC. The hand-rolled reader in `agent/src/jobs/kinds.ts`\n// stays additive-tolerant: it reads a payload written by an earlier build off a durable queue,\n// where an unknown key means \"a newer producer wrote this\" and refusing it would strand jobs.\n// This schema validates the PRODUCER side, at the enqueue site, where the shape is fully\n// controlled and a stray key means a bug in the code that just built it. Strictness belongs on\n// the half that can act on the refusal — putting it on the reader would be a regression\n// generator, and putting it nowhere is how a silently-dropped field ships.\n//\n// THE TWO FLAGS ARE QUEUE-LEVEL VISIBILITY, NOT INTEGRITY. `gateRun` and `excludedFromOutcomes`\n// already live inside the handoff, and `handoffDigest` already covers the handoff's bytes — so\n// copying them here adds no integrity guarantee whatsoever. What it adds is the ability to see\n// what a queued job IS without loading the handoff it points at, which is WTST-06's ratified\n// sentence taken literally. Anyone tempted to treat these copies as authoritative should read\n// the digest instead.\n\nimport { z } from 'zod'\n\nimport { EXECUTION_CONTEXT_VALUES } from '../run/run-status'\nimport { MisdirectionRecordResultSchema } from '../verdict/misdirection-evidence'\n\nexport const AnalyzeRunPayloadSchema = z.object({\n /** The run to analyse. */\n runId: z.string().min(1),\n /**\n * Digest of the handoff bytes being analysed, minted ONCE per run and shared with the\n * receipt — a second mint would be a second answer to \"which bytes were analysed\".\n */\n handoffDigest: z.string().min(1),\n handoffSchemaVersion: z.number().int().nonnegative(),\n /**\n * Optional because the hand-rolled reader has always treated it as optional; the enqueue\n * site does in practice always carry it.\n */\n executionContext: z.enum(EXECUTION_CONTEXT_VALUES).optional(),\n /**\n * D-10 verify-before-present gate-run marker, copied from the handoff carrier.\n *\n * A DISTINCT axis from `excludedFromOutcomes` below — neither marker implies the other, and\n * C8 ratified that gate runs DO feed curation. Only the literal marker is meaningful, exactly\n * as on `completed-run-handoff.ts`: `false` is a refusal rather than a synonym for absence,\n * so a producer cannot half-express the flag.\n */\n gateRun: z.literal(true).optional(),\n /** D-14 §6 outcome-exclusion marker, copied from the handoff carrier. Same literal-only rule. */\n excludedFromOutcomes: z.literal(true).optional(),\n /**\n * 422 D-17/D-18: the circularity arbiter's per-record rows, carried so the analysis job can\n * consider them WITHOUT a second read of the handoff — the same \"see what a queued job IS\"\n * reasoning as the two flags above, and with the same disclaimer: `handoffDigest` remains the\n * integrity answer for the analysed bytes.\n *\n * ABSENT means the arbiter never ran; an EMPTY array means it ran and recorded nothing. The\n * `.strict()` object preserves both, and `superRefine` below keeps a carried row from naming\n * an identity this payload is not about.\n */\n misdirectionEvidence: z.array(MisdirectionRecordResultSchema).optional(),\n}).strict().superRefine((payload, context) => {\n const rows = payload.misdirectionEvidence\n if (rows === undefined) return\n const baseDigests = new Set<string>()\n for (const row of rows) {\n baseDigests.add(row.handoffBaseDigest)\n if (row.runId !== payload.runId) {\n context.addIssue({\n code: 'custom',\n path: ['misdirectionEvidence'],\n message: `a cross-check row was minted against run ${row.runId}, not ${payload.runId}`,\n })\n }\n if (row.handoffBaseDigest === payload.handoffDigest) {\n // The row's base digest is the run's pre-execution IDENTITY; `handoffDigest` covers the\n // finished document, which now contains these rows. A producer that stamped the final\n // digest into a row has built the self-hash cycle the source digest exists to avoid, and\n // the two values can never legitimately be equal.\n context.addIssue({\n code: 'custom',\n path: ['misdirectionEvidence'],\n message:\n 'a cross-check row names the FINAL handoff digest as its source identity; the source digest binds the run, never the finished document',\n })\n }\n }\n if (baseDigests.size > 1) {\n context.addIssue({\n code: 'custom',\n path: ['misdirectionEvidence'],\n message: 'cross-check rows name more than one source-digest identity for one run',\n })\n }\n})\n\nexport type AnalyzeRunPayload = z.infer<typeof AnalyzeRunPayloadSchema>\n","import { z } from 'zod'\n\nimport { asPatchId } from './patch-id'\nimport type { PatchId } from './patch-id'\n\nexport type PatchStatus = 'proposed' | 'approved' | 'applied' | 'rejected' | 'failed'\n\nexport interface Hunk {\n header: string\n lines: string[]\n}\n\nexport interface FileChange {\n path: string\n changeKind: 'add' | 'modify' | 'delete'\n hunks: Hunk[]\n}\n\nexport interface Patch {\n id: PatchId\n status: PatchStatus\n summary: string\n changes: FileChange[]\n payloadHash?: `sha256:${string}`\n}\n\nconst patchStatusValues = [\n 'proposed',\n 'approved',\n 'applied',\n 'rejected',\n 'failed',\n] as const satisfies readonly PatchStatus[]\n\nconst changeKindValues = ['add', 'modify', 'delete'] as const satisfies readonly FileChange['changeKind'][]\n\nconst patchIdSchema = z.string().transform(asPatchId)\n\nconst payloadHashSchema = z\n .string()\n .regex(/^sha256:/)\n .transform((value) => value as `sha256:${string}`)\n\nconst hunkSchema = z.object({\n header: z.string(),\n lines: z.array(z.string()),\n}).strict()\n\nconst fileChangeSchema = z.object({\n path: z.string(),\n changeKind: z.enum(changeKindValues),\n hunks: z.array(hunkSchema),\n}).strict()\n\nexport const patchSchema = z.object({\n id: patchIdSchema,\n status: z.enum(patchStatusValues),\n summary: z.string(),\n changes: z.array(fileChangeSchema),\n payloadHash: payloadHashSchema.optional(),\n}).strict()\n","declare const patchIdBrand: unique symbol\n\nexport type PatchId = string & { readonly [patchIdBrand]: 'PatchId' }\n\nexport const asPatchId = (value: string): PatchId => value as PatchId\n","// The vendored base64 codec (Phase 395, D-17).\n//\n// A CONFIG PROPOSAL PERSISTS BYTES, and a proposal record is JSON. The platform's own base64 pair\n// and `Buffer` are host APIs this package may not name, so the byte<->text transport is vendored\n// here for the same reason `utf8.ts` beside it is.\n//\n// IT IS TRANSPORT, NOT REPRESENTATION. The digest a freshness check compares is taken over the raw\n// bytes BEFORE they are encoded and AFTER they are decoded, never over this text — base64 is how\n// the bytes survive a JSON file, not what they are.\n\nconst ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n\nconst REVERSE: ReadonlyMap<string, number> = new Map(\n [...ALPHABET].map((character, index) => [character, index]),\n)\n\nexport function base64Encode(bytes: Uint8Array): string {\n let out = ''\n\n for (let index = 0; index < bytes.length; index += 3) {\n const first = bytes[index]!\n const second = bytes[index + 1]\n const third = bytes[index + 2]\n\n out += ALPHABET[first >>> 2]\n out += ALPHABET[((first & 0x03) << 4) | ((second ?? 0) >>> 4)]\n out += second === undefined ? '=' : ALPHABET[((second & 0x0f) << 2) | ((third ?? 0) >>> 6)]\n out += third === undefined ? '=' : ALPHABET[third & 0x3f]\n }\n\n return out\n}\n\n/**\n * Bytes back from base64, REFUSING anything that is not base64 rather than skipping it.\n *\n * A permissive decoder is the wrong shape here: the value being decoded is about to be written to\n * a person's config file and compared against a digest, so a character this codec cannot read is a\n * corrupted record and must say so where it is read — not silently become shorter content that\n * then fails a digest comparison nobody can explain.\n */\nexport function base64Decode(text: string): Uint8Array {\n const body = text.endsWith('==') ? text.slice(0, -2) : text.endsWith('=') ? text.slice(0, -1) : text\n const padding = text.length - body.length\n if (text.length % 4 !== 0 || padding > 2) {\n throw new TypeError(`base64Decode was handed a value whose length is not a base64 length`)\n }\n\n const bytes: number[] = []\n let accumulator = 0\n let bits = 0\n\n for (const character of body) {\n const value = REVERSE.get(character)\n if (value === undefined) {\n throw new TypeError(\n `base64Decode was handed ${JSON.stringify(character)}, which is not a base64 character`,\n )\n }\n accumulator = (accumulator << 6) | value\n bits += 6\n if (bits >= 8) {\n bits -= 8\n bytes.push((accumulator >>> bits) & 0xff)\n }\n }\n\n return Uint8Array.from(bytes)\n}\n","// The vendored line differ (Phase 395, D-17).\n//\n// VENDORED RATHER THAN DEPENDED ON, and the reason is a running test rather than a preference.\n// `__tests__/package-class.test.ts` allow-lists this package's runtime dependencies at exactly\n// `{zod}`, and `__tests__/module-discipline.test.ts` refuses host APIs — the same law that made\n// `determinism/sha256.ts` a vendored implementation instead of a Web Crypto call. Adding `diff`\n// (jsdiff) here was the plan's written route and it reds `package-class.test.ts`; widening that\n// allow-list to admit the dependency would have resolved the refusal by opening the boundary the\n// refusal is about. 395-RESEARCH named this alternative as the house pattern: more work here, zero\n// new supply-chain surface, and T-395-SC ceases to exist.\n//\n// WHAT IT MUST NOT DO, because a hand-rolled diff's failure mode is silent: render a diff that\n// disagrees with the change it describes. So the OBLIGATION is checkable rather than claimed —\n// {@link reconstructSides} rebuilds both sides from the emitted lines, and the corpus asserts the\n// rebuild equals the inputs. A dropped line, a wrong hunk header or an off-by-one start reds there\n// rather than reaching a person as a diff that reads correctly and is not what would be committed.\n//\n// COMMON PREFIX/SUFFIX FIRST, THEN LCS ON WHAT IS LEFT. A config edit changes one or two lines in a\n// file of a hundred, so the trimmed middle is nearly always tiny and the table below is nearly\n// always trivial. The cap exists for the case that is not.\n\n/** How many unchanged lines surround each hunk. Unified diff's own default. */\nexport const DIFF_CONTEXT_LINES = 3\n\n/**\n * The largest LCS table this differ will build, in cells.\n *\n * RETUNE: raise it if a real config file set is being rendered as one whole-file replacement when a\n * line-level diff would have been reviewable. It exists because the table is O(old × new) and the\n * inputs are caller-supplied bytes: 4,000,000 cells is roughly a 2,000-line change against a\n * 2,000-line file, which is far outside anything the pinned config SET can be, and beyond it a\n * reviewer is not reading a line diff anyway. The fallback is honest rather than degraded — every\n * old line removed and every new line added, which is exactly what the change is.\n */\nexport const MAX_DIFF_TABLE_CELLS = 4_000_000\n\nexport type LineOp = 'equal' | 'delete' | 'insert'\n\nexport interface LineEdit {\n readonly op: LineOp\n readonly text: string\n}\n\n/** One unified-diff hunk: its four coordinates and its prefixed lines. */\nexport interface UnifiedHunk {\n readonly oldStart: number\n readonly oldLines: number\n readonly newStart: number\n readonly newLines: number\n /** Each line already carries its `' '`, `'-'` or `'+'` prefix. */\n readonly lines: readonly string[]\n}\n\n/**\n * Split text into lines, remembering whether the last one was terminated.\n *\n * The distinction is not cosmetic: a file that ends without a newline and one that ends with one\n * are different bytes, and a differ that collapsed them would render \"no change\" for a change, or\n * a change for none. Unified diff spells the difference `\`, and this is\n * where that marker's truth is decided.\n */\nfunction splitLines(text: string): { lines: string[]; terminated: boolean } {\n if (text === '') return { lines: [], terminated: true }\n const terminated = text.endsWith('\\n')\n const body = terminated ? text.slice(0, -1) : text\n return { lines: body.split('\\n'), terminated }\n}\n\n/**\n * The edit script, as one flat list in output order.\n *\n * Deletes precede inserts at a given position, which is the order unified diff prints and the order\n * a reader expects: the line that was there, then the line that replaced it.\n */\nexport function diffLines(oldText: string, newText: string): readonly LineEdit[] {\n const oldSide = splitLines(oldText).lines\n const newSide = splitLines(newText).lines\n\n let prefix = 0\n while (prefix < oldSide.length && prefix < newSide.length && oldSide[prefix] === newSide[prefix]) {\n prefix++\n }\n\n let suffix = 0\n while (\n suffix < oldSide.length - prefix\n && suffix < newSide.length - prefix\n && oldSide[oldSide.length - 1 - suffix] === newSide[newSide.length - 1 - suffix]\n ) {\n suffix++\n }\n\n const oldMiddle = oldSide.slice(prefix, oldSide.length - suffix)\n const newMiddle = newSide.slice(prefix, newSide.length - suffix)\n\n const edits: LineEdit[] = []\n for (let index = 0; index < prefix; index++) edits.push({ op: 'equal', text: oldSide[index]! })\n edits.push(...middleEdits(oldMiddle, newMiddle))\n for (let index = oldSide.length - suffix; index < oldSide.length; index++) {\n edits.push({ op: 'equal', text: oldSide[index]! })\n }\n return edits\n}\n\nfunction middleEdits(oldSide: readonly string[], newSide: readonly string[]): LineEdit[] {\n if (oldSide.length === 0 && newSide.length === 0) return []\n if (oldSide.length === 0) return newSide.map((text) => ({ op: 'insert' as const, text }))\n if (newSide.length === 0) return oldSide.map((text) => ({ op: 'delete' as const, text }))\n\n if ((oldSide.length + 1) * (newSide.length + 1) > MAX_DIFF_TABLE_CELLS) {\n // The honest fallback: the whole middle replaced. See MAX_DIFF_TABLE_CELLS.\n return [\n ...oldSide.map((text) => ({ op: 'delete' as const, text })),\n ...newSide.map((text) => ({ op: 'insert' as const, text })),\n ]\n }\n\n // Longest common subsequence by length table, then one backward walk. The table is\n // `lengths[i][j]` = LCS of `oldSide[i..]` and `newSide[j..]`, which makes the walk forward and\n // therefore the output order the printing order.\n const rows = oldSide.length + 1\n const columns = newSide.length + 1\n const lengths = new Uint32Array(rows * columns)\n\n for (let i = oldSide.length - 1; i >= 0; i--) {\n for (let j = newSide.length - 1; j >= 0; j--) {\n lengths[i * columns + j] = oldSide[i] === newSide[j]\n ? lengths[(i + 1) * columns + (j + 1)]! + 1\n : Math.max(lengths[(i + 1) * columns + j]!, lengths[i * columns + (j + 1)]!)\n }\n }\n\n const edits: LineEdit[] = []\n let i = 0\n let j = 0\n while (i < oldSide.length && j < newSide.length) {\n if (oldSide[i] === newSide[j]) {\n edits.push({ op: 'equal', text: oldSide[i]! })\n i++\n j++\n } else if (lengths[(i + 1) * columns + j]! >= lengths[i * columns + (j + 1)]!) {\n edits.push({ op: 'delete', text: oldSide[i]! })\n i++\n } else {\n edits.push({ op: 'insert', text: newSide[j]! })\n j++\n }\n }\n while (i < oldSide.length) edits.push({ op: 'delete', text: oldSide[i++]! })\n while (j < newSide.length) edits.push({ op: 'insert', text: newSide[j++]! })\n return edits\n}\n\nconst NO_NEWLINE_MARKER = '\\\'\n\n/**\n * Group the edit script into unified-diff hunks with {@link DIFF_CONTEXT_LINES} of context.\n *\n * Two changes closer together than twice the context share a hunk rather than producing two that\n * overlap — overlapping hunks are the classic hand-rolled-diff defect, and a patch carrying them\n * cannot be applied by anything that reads unified diff.\n */\nexport function toUnifiedHunks(\n oldText: string,\n newText: string,\n context: number = DIFF_CONTEXT_LINES,\n): readonly UnifiedHunk[] {\n const edits = diffLines(oldText, newText)\n if (!edits.some((edit) => edit.op !== 'equal')) return []\n\n const oldTerminated = splitLines(oldText).terminated\n const newTerminated = splitLines(newText).terminated\n\n const changedIndexes = edits.flatMap((edit, index) => (edit.op === 'equal' ? [] : [index]))\n const groups: { start: number; end: number }[] = []\n for (const index of changedIndexes) {\n const start = Math.max(0, index - context)\n const end = Math.min(edits.length - 1, index + context)\n const last = groups[groups.length - 1]\n if (last !== undefined && start <= last.end + 1) last.end = Math.max(last.end, end)\n else groups.push({ start, end })\n }\n\n // Line numbers are 1-based and counted over the SIDES, not over the edit script, so they are\n // accumulated as the script is walked rather than derived from an index.\n const oldLineAt: number[] = []\n const newLineAt: number[] = []\n let oldCursor = 1\n let newCursor = 1\n for (const edit of edits) {\n oldLineAt.push(oldCursor)\n newLineAt.push(newCursor)\n if (edit.op !== 'insert') oldCursor++\n if (edit.op !== 'delete') newCursor++\n }\n\n const lastOldIndex = edits.reduce((found, edit, index) => (edit.op === 'insert' ? found : index), -1)\n const lastNewIndex = edits.reduce((found, edit, index) => (edit.op === 'delete' ? found : index), -1)\n\n return groups.map((group) => {\n const lines: string[] = []\n let oldCount = 0\n let newCount = 0\n\n for (let index = group.start; index <= group.end; index++) {\n const edit = edits[index]!\n const prefix = edit.op === 'equal' ? ' ' : edit.op === 'delete' ? '-' : '+'\n lines.push(`${prefix}${edit.text}`)\n if (edit.op !== 'insert') oldCount++\n if (edit.op !== 'delete') newCount++\n if (index === lastOldIndex && !oldTerminated && edit.op !== 'insert') {\n lines.push(NO_NEWLINE_MARKER)\n } else if (index === lastNewIndex && !newTerminated && edit.op === 'insert') {\n lines.push(NO_NEWLINE_MARKER)\n }\n }\n\n return {\n // A zero-length side starts at 0, which is what unified diff means by \"before the first line\".\n oldStart: oldCount === 0 ? 0 : oldLineAt[group.start]!,\n oldLines: oldCount,\n newStart: newCount === 0 ? 0 : newLineAt[group.start]!,\n newLines: newCount,\n lines,\n }\n })\n}\n\n/**\n * Rebuild both sides from the emitted hunk lines — the differ's own acceptance bar.\n *\n * It exists so the corpus can assert the rendered diff describes the change it was rendered from,\n * rather than asserting that a differ produced some plausible-looking text. What reds it: a dropped\n * line, a prefix on the wrong side, a hunk whose header disagrees with its content, a group whose\n * context ran off an end. Only usable where the hunks cover the whole file (context = Infinity),\n * which is exactly how the corpus drives it.\n */\nexport function reconstructSides(hunks: readonly UnifiedHunk[]): { oldText: string; newText: string } {\n const oldLines: string[] = []\n const newLines: string[] = []\n let oldTerminated = true\n let newTerminated = true\n\n for (const hunk of hunks) {\n let previous: string | undefined\n for (const line of hunk.lines) {\n if (line === NO_NEWLINE_MARKER) {\n if (previous?.startsWith('+') === true) newTerminated = false\n else if (previous?.startsWith('-') === true) oldTerminated = false\n else {\n oldTerminated = false\n newTerminated = false\n }\n continue\n }\n const body = line.slice(1)\n if (line.startsWith(' ')) {\n oldLines.push(body)\n newLines.push(body)\n } else if (line.startsWith('-')) {\n oldLines.push(body)\n } else if (line.startsWith('+')) {\n newLines.push(body)\n }\n previous = line\n }\n }\n\n const join = (lines: readonly string[], terminated: boolean): string =>\n lines.length === 0 ? '' : `${lines.join('\\n')}${terminated ? '\\n' : ''}`\n\n return { oldText: join(oldLines, oldTerminated), newText: join(newLines, newTerminated) }\n}\n","// THE ONE diff/digest primitive both halves of a config proposal call (Phase 395, D-17 / D-19).\n//\n// RAW BYTES IN, RENDERED BYTES OUT. Construction (in `agent`) renders the diff a person reads and\n// records the digests a later apply will re-check; the apply (in `cli`) recomputes both from the\n// file as it stands and byte-compares. Those are two halves of ONE contract, and the whole reason\n// this is a single exported function rather than a shared convention is the history written into\n// `local-agent-host.ts:1650-1657`:\n//\n// BYTES, NOT TEXT — ON BOTH SIDES (394-23 WR-04, completed by 394-29 CR-02). … at the base BOTH\n// halves hashed the UTF-8 decoding and therefore AGREED … what the round-trip genuinely destroyed\n// was the rollback, which wrote U+FFFD back over every sequence the decoder could not read.\n//\n// WHERE THE DECODE IS, AND WHERE IT IS NOT. Every digest here is taken over the `Uint8Array` the\n// caller handed in, untouched. The decode happens ONLY on the rendering path, because a unified\n// diff is text by definition and there is nothing else it could be — a person cannot review bytes.\n// So a file whose bytes are not valid UTF-8 renders with replacement characters and still digests,\n// compares and applies as itself. The two claims stay separate, which is what CR-02 cost.\n//\n// SORTED BY PATH, ALWAYS, AND BY THE PATH'S UTF-8 BYTES. The rendered bytes are compared for\n// equality across two processes and two moments, so their order may not depend on the order a\n// caller happened to enumerate a file set in. The comparison is over the UTF-8 encoding rather than\n// over JavaScript's own string ordering because those two disagree: `<` compares UTF-16 code units,\n// which sorts every astral character BELOW U+E000–U+FFFF (its surrogates start at 0xD800) while its\n// UTF-8 encoding sorts ABOVE them (four-byte sequences start at 0xF0). One of those orders is a\n// property of a path; the other is a property of a language's string representation, and the thing\n// being compared here is a path.\n//\n// NOTHING CHANGED IS AN ANSWER, NOT AN EMPTY ONE (CFGM-01's empty edge). The result is discriminated\n// on `outcome`, and the `unchanged` arm structurally has no `diffBytes` — a caller cannot mistake\n// \"there is nothing to propose\" for \"here is a diff that happens to be zero bytes long\", because\n// there is no zero-length array to interpret. `unchanged` is decided from the BYTES, never from the\n// rendered line count, for the reason the refusal below exists.\n//\n// THE HUNK VOCABULARY IS `schema/src/patch/`'s (394 D-06 reserved it for this phase). The renderer\n// emits `FileChange`/`Hunk` values and then serializes THOSE, so the structure a surface can read\n// and the bytes a person reads are one artifact rather than two renderings of one change.\n\nimport { sha256hexBytes } from '../determinism/sha256'\nimport type { FileChange, Hunk } from '../patch/patch'\nimport { DIFF_CONTEXT_LINES, toUnifiedHunks } from './line-diff'\nimport { utf8Decode, utf8Encode } from './utf8'\n\n/** One file's before/after RAW bytes. Absent `oldBytes` is an add; absent `newBytes` is a delete. */\nexport interface ConfigDiffFileInput {\n readonly path: string\n readonly oldBytes?: Uint8Array\n readonly newBytes?: Uint8Array\n}\n\n/** What one file hashed to on each side. Absent where that side has no file at all. */\nexport interface ConfigFileDigest {\n readonly path: string\n readonly oldDigest?: string\n readonly newDigest?: string\n}\n\n/** What the primitive found: bytes that differ somewhere, or bytes that do not. */\nexport const CONFIG_DIFF_OUTCOMES = ['changed', 'unchanged'] as const\n\nexport type ConfigDiffOutcome = (typeof CONFIG_DIFF_OUTCOMES)[number]\n\nexport interface ConfigDiffChanged {\n readonly outcome: 'changed'\n /** The rendered unified diff, as the exact bytes a proposal stores and an apply compares. */\n readonly diffBytes: Uint8Array\n /** sha256 over exactly {@link ConfigDiffChanged.diffBytes}. */\n readonly diffDigest: string\n readonly perFileDigests: readonly ConfigFileDigest[]\n /** The same change in the reserved `patch/` vocabulary, for surfaces that read structure. */\n readonly changes: readonly FileChange[]\n}\n\n/**\n * Every file's two sides held the same bytes. There is nothing to show and nothing to decide.\n *\n * THE DIGESTS SURVIVE, THE DIFF DOES NOT. An apply that re-reads and finds no change still wants to\n * know what the files hashed to — that is how it says which file it looked at — but there is no\n * diff for it to compare against a stored one, and a zero-byte `diffBytes` here would be a value\n * whose digest an unwary caller could compare against a real proposal's and find unequal, reporting\n * a tampering refusal for a file nobody touched.\n */\nexport interface ConfigDiffUnchanged {\n readonly outcome: 'unchanged'\n readonly perFileDigests: readonly ConfigFileDigest[]\n readonly changes: readonly FileChange[]\n}\n\nexport type ConfigDiffResult = ConfigDiffChanged | ConfigDiffUnchanged\n\n/**\n * A file with no bytes on either side is not a change and must not be one.\n *\n * Refused BY NAME rather than rendered as an empty section: a caller that handed neither side is\n * either enumerating a file set it cannot read or has lost a byte payload somewhere upstream, and a\n * proposal listing a file with no content on either side would be a decision about nothing.\n */\nexport class EmptyConfigDiffFileError extends TypeError {\n constructor(readonly path: string) {\n super(\n `refusing to diff ${JSON.stringify(path)}: neither old nor new bytes were supplied, so there `\n + 'is no change to render and nothing to digest.',\n )\n this.name = 'EmptyConfigDiffFileError'\n }\n}\n\n/**\n * The bytes differ, but the diff renders as nothing. Refuse rather than show a person an empty page.\n *\n * THE HAZARD IS THE DECODE, AND IT IS THE ONE PLACE THE TWO CLAIMS THIS FILE KEEPS SEPARATE CAN\n * COLLIDE. A unified diff is text, so rendering decodes; a decode maps every byte sequence it\n * cannot read onto U+FFFD, and that map is many-to-one. Two files differing only in bytes no\n * decoding round-trips — `0x80` against `0xFF` — therefore decode to the SAME text and produce zero\n * hunks, while their digests differ and their content differs.\n *\n * Left alone, that is a proposal a person is shown as an empty diff and approves, which writes\n * bytes they never saw; and D-19's shown==applied comparison would agree with itself the whole way,\n * because both halves render the same nothing. So this is not a rendering nicety — it is the one\n * gap through which the byte-level guarantee could be satisfied while the human-level one was not.\n * The change is refused at construction, before any record of it can exist.\n */\nexport class UnrenderableConfigDiffError extends TypeError {\n constructor(readonly paths: readonly string[]) {\n super(\n `refusing to render a change to ${paths.map((path) => JSON.stringify(path)).join(', ')}: the `\n + 'bytes differ but the unified diff of them is empty, which means the difference is in byte '\n + 'sequences that are not text and a person would be asked to approve a blank page. Nothing '\n + 'has been proposed.',\n )\n this.name = 'UnrenderableConfigDiffError'\n }\n}\n\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n if (left.length !== right.length) return false\n for (let index = 0; index < left.length; index++) {\n if (left[index] !== right[index]) return false\n }\n return true\n}\n\n/** Byte-wise on the UTF-8 encoding of the path — see the file header for why not `<`. */\nfunction comparePaths(left: string, right: string): number {\n const leftBytes = utf8Encode(left)\n const rightBytes = utf8Encode(right)\n const shared = Math.min(leftBytes.length, rightBytes.length)\n for (let index = 0; index < shared; index++) {\n const difference = leftBytes[index]! - rightBytes[index]!\n if (difference !== 0) return difference\n }\n return leftBytes.length - rightBytes.length\n}\n\nfunction changeKindFor(file: ConfigDiffFileInput): FileChange['changeKind'] {\n if (file.oldBytes === undefined && file.newBytes === undefined) {\n throw new EmptyConfigDiffFileError(file.path)\n }\n if (file.oldBytes === undefined) return 'add'\n if (file.newBytes === undefined) return 'delete'\n return 'modify'\n}\n\nfunction hunksFor(file: ConfigDiffFileInput, context: number): Hunk[] {\n const oldText = file.oldBytes === undefined ? '' : utf8Decode(file.oldBytes)\n const newText = file.newBytes === undefined ? '' : utf8Decode(file.newBytes)\n return toUnifiedHunks(oldText, newText, context).map((hunk) => ({\n header: `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`,\n lines: [...hunk.lines],\n }))\n}\n\n/**\n * The `---`/`+++` pair, with `/dev/null` on the side that has no file — git's own spelling.\n *\n * The prefixes are `a/` and `b/` for the same reason: the bytes this renders are what a person\n * reviews in a chat window before saying yes, and a diff that did not look like a diff would be a\n * new artifact class for them to learn.\n */\nfunction fileHeaderLines(file: ConfigDiffFileInput, changeKind: FileChange['changeKind']): string[] {\n return [\n changeKind === 'add' ? '--- /dev/null' : `--- a/${file.path}`,\n changeKind === 'delete' ? '+++ /dev/null' : `+++ b/${file.path}`,\n ]\n}\n\n/**\n * Render the diff and take the digests, for one file set, in one pass.\n *\n * The `perFileDigests` and the `diffBytes` come out of the SAME call because they are one claim:\n * \"this diff is what these bytes produce\". A caller that could ask for one without the other would\n * be able to store a digest taken at one moment beside a diff rendered at another, which is the\n * disagreement the whole freshness contract exists to make impossible.\n */\nexport function renderConfigDiff(\n files: readonly ConfigDiffFileInput[],\n options: { readonly context?: number } = {},\n): ConfigDiffResult {\n const context = options.context ?? DIFF_CONTEXT_LINES\n const ordered = [...files].sort((left, right) => comparePaths(left.path, right.path))\n\n const changes: FileChange[] = []\n const perFileDigests: ConfigFileDigest[] = []\n const lines: string[] = []\n // DECIDED FROM THE BYTES, ONE FILE AT A TIME, and collected rather than short-circuited so the\n // refusal below can name every path it applies to instead of the first one it met.\n const changedButUnrendered: string[] = []\n let anyBytesDiffer = false\n\n for (const file of ordered) {\n const changeKind = changeKindFor(file)\n const hunks = hunksFor(file, context)\n changes.push({ path: file.path, changeKind, hunks })\n perFileDigests.push({\n path: file.path,\n // RAW BYTES, NEVER THE DECODING ABOVE. The decode two lines up feeds the render and nothing\n // else; these two digests are the values an apply re-checks against a file on disk.\n ...(file.oldBytes === undefined ? {} : { oldDigest: sha256hexBytes(file.oldBytes) }),\n ...(file.newBytes === undefined ? {} : { newDigest: sha256hexBytes(file.newBytes) }),\n })\n\n const bytesDiffer = file.oldBytes === undefined\n || file.newBytes === undefined\n || !bytesEqual(file.oldBytes, file.newBytes)\n if (bytesDiffer) anyBytesDiffer = true\n if (bytesDiffer && hunks.length === 0) changedButUnrendered.push(file.path)\n\n if (hunks.length === 0) continue\n lines.push(...fileHeaderLines(file, changeKind))\n for (const hunk of hunks) {\n lines.push(hunk.header)\n lines.push(...hunk.lines)\n }\n }\n\n if (changedButUnrendered.length > 0) throw new UnrenderableConfigDiffError(changedButUnrendered)\n\n if (!anyBytesDiffer) return { outcome: 'unchanged', perFileDigests, changes }\n\n // A trailing newline closes the last line, which every line before it already has. The zero-line\n // case cannot reach here: no byte differs (answered above) or the difference did not render\n // (refused above), so an empty rendering is never something this function returns.\n const diffBytes = utf8Encode(`${lines.join('\\n')}\\n`)\n\n return {\n outcome: 'changed',\n diffBytes,\n diffDigest: sha256hexBytes(diffBytes),\n perFileDigests,\n changes,\n }\n}\n","// The two closed vocabularies D-02 and D-03 bound (Phase 395, CFGM-01 / CFGM-02).\n//\n// PINNED CONSTANTS, NEVER CONFIGURATION (386 D-15). Both values below are JUDGEMENTS about what a\n// person must be asked about before a machine edits their repository, and a judgement a project can\n// switch off is not a guard — it is a default. They live in `schema` because the classifier that\n// reads them (395-04), the surfaces that render their consequences, and the grant machinery that\n// refuses on them are three packages, and three spellings of one vocabulary is the sibling-input\n// failure this project keeps rediscovering.\n//\n// EACH CONSTANT CARRIES A RETUNE COMMENT stating the judgement and naming who owns changing it,\n// because a pinned value with no stated owner is a value the next person guesses at.\n\n/**\n * The named classes of \"this crosses a boundary a standing approval may not cover\" (D-02).\n *\n * CLOSED AT THE CLASSES D-02 BOUNDS, and closed is the point. Cross-boundary-ness is computed per\n * VALUE — a base URL edited to point at a new origin is cross-boundary, the same edit to the same\n * origin is not — so what is pinned here is the set of REASONS a classifier may give, never a map\n * from ops to answers. A static per-op map could not see the origin change at all, which is why\n * D-02 put the flag on the proposal.\n *\n * The members, and what each one is a fact about:\n *\n * secret-adjacent-field — the edited path is at or under {@link SECRET_ADJACENT_CONFIG_FIELDS}.\n * new-origin — a URL value whose scheme/host/port differ from the one it replaces.\n * hook-added — a hook is code this project will EXECUTE; adding one is not a setting.\n * out-of-set-path — the change writes a file outside the enumerated config file set.\n * production-opt-in — top-level `allowProduction` is turned on, so production targets run.\n * production-declassified — a target declared `environment: production` moves to another class,\n * so the production refusal no longer reads it as production.\n *\n * 2026-10-03 (quick 261003-cpv, 432 review WR-01/WR-10): the two production members are added. D-18\n * makes production a config declaration that any door may write (D-01/D-12), so they are\n * provenance on the applied receipt, never a gate; before them the one change that turns off the\n * production refusal answered `crossBoundary: false`.\n *\n * RETUNE: adding a fifth member is a decision about what a person is asked to look at, and it is\n * owned by whoever owns D-02 — the phase that discovers a boundary these four cannot name, with the\n * case that showed it. Removing a member is a stronger claim than adding one: it says a class of\n * change stopped being worth a fresh ask, and the grant machinery's refusal rests on that. Do not\n * widen this by pattern; the classifier's job is to produce one of these words or nothing.\n */\nexport const CROSS_BOUNDARY_REASONS = [\n 'secret-adjacent-field',\n 'new-origin',\n 'hook-added',\n 'out-of-set-path',\n 'production-opt-in',\n 'production-declassified',\n] as const\n\nexport type CrossBoundaryReason = (typeof CROSS_BOUNDARY_REASONS)[number]\n\n/**\n * The config paths whose edit is secret-adjacent, as SUBTREE ROOTS rather than as leaves.\n *\n * ROOTS, NOT LEAVES, AND THAT IS THE ANTI-DOOR-ENUMERATION HALF. D-03 removed the settable-field\n * whitelist because a rule that can only refuse what it can NAME cannot be driven to zero by naming\n * more things. The same reasoning applies here in the other direction: this list names the ROOT of\n * each region, and everything under a root is secret-adjacent whether or not anybody enumerated it,\n * so a key added to the auth plugin declaration next year is covered on the day it is added.\n *\n * A `*` segment matches exactly one path segment — the record keys (target names, plugin indices)\n * that the config schema itself leaves open.\n *\n * Each entry, and why it is here:\n *\n * workspace.envFile — names the file the environment values are read from; repointing\n * it changes which values resolve into a run.\n * workspace.secretsFile — names the untracked secrets file; same argument, one step closer.\n * services.authState — the directory captured auth state (session cookies, bearer\n * tokens) is written to and loaded from.\n * plugins.auth — declares the plugin that RESOLVES credentials; it loads in-process.\n * plugins.providers — provider plugins load in-process with full host access and carry\n * provider credentials.\n * registry.providers — device-farm provider entries; the shape whose fields are a\n * username and an access key.\n * registry.targets.*.authState — binds one target to a stored auth state, i.e. decides which\n * identity a run acts as.\n * use.authState — the SAME fact, at the path the committed configuration actually\n * spells it (395-05, added with the field that showed it).\n *\n * `use.authState` WAS MISSING, AND FINDING OUT WHY IS WORTH THE PARAGRAPH. 395-02 listed\n * `registry.targets.*.authState` from `WebPlatformConfig`, which is the RESOLVED platform\n * configuration a run computes — `core`'s `TargetSchema` is `.strict()` and has no `authState` key,\n * so nothing can ever be committed at that path. The committed configuration binds an auth state at\n * `use.authState` (`AuthStateUseSchema`: a name, or `{ name, load, capture }`), and that path was\n * unflagged: every op that binds an identity would have produced an unflagged proposal a standing\n * grant could cover. The listed root is KEPT rather than corrected away — this list may not shrink to\n * make a proposal grantable, and a root that matches nothing costs nothing — but the reason it was\n * wrong is recorded here so the next reader does not read a resolved-config path as a committed one.\n *\n * RETUNE: this list is owned by whoever owns D-02/D-03 — a phase that finds a secret-bearing region\n * of the config schema these roots do not cover adds the ROOT, with the field that showed it. It may\n * not shrink to make a proposal grantable: a value here being flagged is the whole reason the\n * standing-grant refusal has anything to refuse. It is deliberately not derived from the config\n * schema by pattern (a name-matching heuristic over field names is exactly the enumeration this\n * avoids); it is a short list of places, stated once.\n */\nexport const SECRET_ADJACENT_CONFIG_FIELDS = [\n 'workspace.envFile',\n 'workspace.secretsFile',\n 'services.authState',\n 'plugins.auth',\n 'plugins.providers',\n 'registry.providers',\n 'registry.targets.*.authState',\n 'use.authState',\n] as const\n\nexport type SecretAdjacentConfigField = (typeof SECRET_ADJACENT_CONFIG_FIELDS)[number]\n\n/**\n * Does an edit at this dotted config path reach one of the secret-adjacent roots?\n *\n * SHIPPED BESIDE THE CONSTANT because the rule below is not obvious from the strings, and a caller\n * that re-derived it would be the second spelling of a judgement the file header says must have\n * exactly one. 395-04's classifier calls this; so does anything that wants to explain a flag.\n *\n * IT MATCHES IN BOTH DIRECTIONS, and the second one is the half that is easy to miss. A path AT or\n * UNDER a root is the obvious case: `plugins.auth.0.package` is inside `plugins.auth`. But a path\n * ABOVE a root reaches it too — `config.field.set` at `plugins` REPLACES the whole subtree,\n * including the auth declarations, so an ancestor edit is a secret-adjacent edit even though the\n * path a person typed does not appear on the list. A matcher that only walked downwards would let\n * the widest possible edit through as unflagged, which is the reverse of the risk ordering.\n */\nexport function isSecretAdjacentConfigField(path: string): boolean {\n const segments = path.split('.')\n return SECRET_ADJACENT_CONFIG_FIELDS.some((root) => {\n const rootSegments = root.split('.')\n const shared = Math.min(segments.length, rootSegments.length)\n for (let index = 0; index < shared; index++) {\n if (rootSegments[index] === '*') continue\n if (rootSegments[index] !== segments[index]) return false\n }\n return true\n })\n}\n","// The pinned config file SET, enumerated once for every consumer (Phase 395, D-02/D-05 · CFGM-01).\n//\n// A SET AND NOT A GLOB (394-39's population lesson). `*.yaml` would answer differently on the first\n// repository whose layout nobody anticipated — silently, and in the direction that matters, because\n// this answer is what a porcelain check scopes to, what the out-of-set classifier compares against,\n// and what a commit's pathspec names. Every member is a file the CONFIG ITSELF names: the config\n// yaml, the hooks file `workspace.hooksFile` points at, and the `.gitignore` whose managed block\n// `init` maintains.\n//\n// IT LIVES IN `schema` FOR THE REASON THE TWO VOCABULARIES BESIDE IT DO: three packages read this\n// one answer. `cli`'s config-files port enumerates the set it reads bytes for; `agent`'s\n// cross-boundary classifier decides `out-of-set-path` against it; 395-06's apply porcelain scopes\n// its check to it. Three spellings of one enumeration is the sibling-input failure this project\n// keeps rediscovering — and the failure mode here is silent in the permissive direction, because a\n// consumer whose copy is missing a member simply stops flagging changes to it.\n//\n// PURE, AND DELIBERATELY IGNORANT OF THE FILESYSTEM. The set is what the config NAMES, not what\n// happens to exist: a hooks file the config names and the repository does not have is still a\n// member, because \"the file is absent\" is a fact the reader reports, never a reason to stop\n// considering the path config-owned.\n//\n// RETUNE: add a member here when the config grows a new file it OWNS — not when a project happens\n// to keep another yaml beside it. The test is authorship: this product writes these files. Owned by\n// whoever owns D-02/D-05.\n\n/** The managed-block file `init` maintains. Not named by the config, but written by this product. */\nexport const CONFIG_SET_GITIGNORE = '.gitignore'\n\n/** What `workspace.hooksFile` defaults to when the config does not name one. */\nexport const CONFIG_SET_DEFAULT_HOOKS_FILE = 'hooks.yaml'\n\n/**\n * The closed set of workspace-relative paths this product's configuration owns.\n *\n * DEDUPLICATED AND SORTED, so two reads of one project answer in one order and a project whose\n * `hooksFile` IS its config file is enumerated once rather than digested twice under one path.\n */\nexport function enumerateConfigFileSet(input: {\n /** The config yaml's workspace-relative path, as the host's own identity mint spells it. */\n readonly configFile: string\n /** `workspace.hooksFile` as the committed config names it, or absent for the default. */\n readonly hooksFile?: string\n}): readonly string[] {\n const hooksFile = input.hooksFile === undefined || input.hooksFile === ''\n ? CONFIG_SET_DEFAULT_HOOKS_FILE\n : input.hooksFile\n return [...new Set([input.configFile, hooksFile, CONFIG_SET_GITIGNORE])].sort()\n}\n","// The closed action class, as input DTOs (Phase 395, D-01 / D-11 / D-13 · CFGM-01, CFGM-05).\n//\n// ONE DTO PER OP, NAMED FOR ITS OP ID, MINTED HERE (384 D-16). The registry op that carries each of\n// these lives in `packages/agent`, the MCP projection that will publish them lives in 396, and the\n// parity walk that enumerates them lives in 397 — three consumers, so the shapes live in `schema`\n// where none of them owns the vocabulary. A per-op sibling shape would be three spellings whose\n// disagreement is only visible at runtime.\n//\n// EVERY SCHEMA IS `.strict()`, AND THAT IS THE SECURITY PROPERTY RATHER THAN A STYLE. These inputs\n// are filled by a language model, so an unrecognised key is not a typo to forgive: it is either a\n// hallucinated field the op would silently ignore, or an attempt to smuggle a value past the shape\n// the guard reasons about. `.strict()` makes both a refusal at the boundary.\n//\n// `ConfigAuthSetInputSchema` IS THE ONE TO READ TWICE. D-11 ratified set_auth as REFS-ONLY as law:\n// it writes the NAME of an auth state, the NAME of a plugin package, the NAME of an environment\n// variable — never a credential. That is enforced here by the absence of any field a credential\n// could be assigned to, which is a property of the shape rather than a rule somebody remembers, and\n// `__tests__/proposal.test.ts` enumerates the keyset so adding one would be a visible edit. The\n// behavioural half — a value in one of the REFERENCE fields that is not shaped like a reference is\n// refused `refs-only` at construction — is defence in depth on top of this, not instead of it.\n\nimport { z } from 'zod'\n\nimport { CROSS_BOUNDARY_REASONS } from './constants'\n\n/**\n * The runtimes a hook may declare.\n *\n * SPELLED HERE rather than imported because the hooks file schema lives in `@vostride/agent-qa-core`\n * and this package may not import a first-party package (its package-class boundary). The words are\n * identical to `core`'s `HookDefinitionSchema.runtime` on purpose: a reader comparing them is\n * comparing one vocabulary seen from two layers, and a proposal that offered a fifth runtime would\n * be refused by the whole-file validation this phase runs before anything surfaces (CFGM-01).\n */\nexport const CONFIG_HOOK_RUNTIMES = ['node', 'bun', 'python', 'bash'] as const\n\nexport type ConfigHookRuntime = (typeof CONFIG_HOOK_RUNTIMES)[number]\n\n/**\n * The classes a target may declare at creation (432 D-19).\n *\n * Spelled here for the reason {@link CONFIG_HOOK_RUNTIMES} is: the words match `core`'s\n * `TargetSchema.environment`, and whole-config validation refuses any drift before the change is\n * written. Absent means undeclared, which is non-production (D-18).\n */\nexport const CONFIG_TARGET_ENVIRONMENTS = ['local', 'shared', 'production'] as const\n\nexport type ConfigTargetEnvironment = (typeof CONFIG_TARGET_ENVIRONMENTS)[number]\n\n/**\n * `config.target.create` — add a web target to `registry.targets`.\n *\n * `platform` IS A LITERAL, NOT AN ENUM OF THREE. The mobile platforms need a device profile, an app\n * package or a bundle id and a running Appium — facts a chat utterance does not carry and this\n * phase's scaffold cannot derive. A target class this op cannot honestly build is better refused by\n * the type than half-built by the op.\n */\nexport const ConfigTargetCreateInputSchema = z.object({\n /** The registry key. Also what a test's `target:` names. */\n name: z.string().min(1),\n platform: z.literal('web'),\n /** The base URL, absolute. D-15's hostname gate runs before this op is reached. */\n url: z.string().min(1),\n // 2026-10-02 (quick 261002-ctr): no `authStateName`. See `ConfigAuthSetInputSchema`.\n /** The target's class (432 D-19). Omitted means undeclared; production runs need allowProduction. */\n environment: z.enum(CONFIG_TARGET_ENVIRONMENTS).optional(),\n}).strict()\n\nexport type ConfigTargetCreateInput = z.infer<typeof ConfigTargetCreateInputSchema>\n\n/**\n * `config.target.edit` — change an existing target's URL.\n *\n * THE CHANGES ARE NESTED rather than flattened beside `name`, so \"which target\" and \"what about it\"\n * cannot be confused by a model filling the shape, and so an empty `changes` object is a\n * distinguishable input rather than an edit of nothing that looks like an edit of everything.\n * `platform` is absent deliberately: changing a target's platform is creating a different target.\n */\nexport const ConfigTargetEditInputSchema = z.object({\n name: z.string().min(1),\n changes: z.object({\n url: z.string().min(1).optional(),\n }).strict(),\n}).strict()\n\nexport type ConfigTargetEditInput = z.infer<typeof ConfigTargetEditInputSchema>\n\n/**\n * `config.auth.set` — declare an auth plugin for a target, or ask where an environment variable goes.\n *\n * REFS ONLY, AND THERE IS NO FIELD TO PUT A SECRET IN (D-11, ratified as law). Every field below\n * names WHERE a value lives; none of them holds one. The committed configuration therefore stays\n * secret-free by construction, which is what makes masking-at-resolution sound — a masker can only\n * mask values it can see, and the reason it can see all of them is that they never enter this file.\n *\n * 2026-10-02 (quick 261002-ctr): NO `authStateName`, here or on `config.target.create` /\n * `config.target.edit`. The three ops wrote it to `use.authState`, and the committed configuration\n * has no such key: `core`'s `UseSchema` and `TargetSchema` are both `.strict()` without one, so\n * whole-config validation answered every such call `blocked / schema-fail`. An auth state is bound\n * where the schema accepts it, in a test's or a suite's own `use.authState`.\n */\nexport const ConfigAuthSetInputSchema = z.object({\n /** Which target this auth applies to, by registry name. */\n target: z.string().min(1),\n /** The NAME of an auth plugin package to declare under `plugins.auth`. */\n pluginPackage: z.string().min(1).optional(),\n /** The NAME of an environment variable the plugin reads. Never its value. */\n envVarName: z.string().min(1).optional(),\n}).strict()\n\nexport type ConfigAuthSetInput = z.infer<typeof ConfigAuthSetInputSchema>\n\n/**\n * `config.hook.add` — declare a hook in the hooks file.\n *\n * A HOOK IS CODE THIS PROJECT WILL RUN, which is why `hook-added` is one of the four cross-boundary\n * reasons and why this input names a FILE rather than carrying a body: the script is a thing a\n * person writes and reviews in their editor, and a proposal that carried executable text would be\n * asking for approval of two artifacts in one decision.\n */\nexport const ConfigHookAddInputSchema = z.object({\n /** The human-facing hook name; the hook id is minted host-side. */\n name: z.string().min(1),\n runtime: z.enum(CONFIG_HOOK_RUNTIMES),\n /** Workspace-relative path to the script. */\n file: z.string().min(1),\n /** A duration string as the hooks file spells them, e.g. `30s`. Host default when absent. */\n timeout: z.string().min(1).optional(),\n network: z.boolean().optional(),\n}).strict()\n\nexport type ConfigHookAddInput = z.infer<typeof ConfigHookAddInputSchema>\n\n/**\n * `config.field.set` — set any schema-addressable path (D-03).\n *\n * ANY PATH, and the absence of a settable-field whitelist is the decision rather than an omission —\n * a whitelist is the door-enumeration failure this project has measured twice: a rule that can only\n * refuse what it can NAME cannot be driven to zero by naming more things. The guards here are\n * whole-input by construction instead: post-mutation validation of the ENTIRE config (CFGM-01) for\n * correctness, and D-02's per-value classifier for safety.\n *\n * Relocated from `proposal.ts` by 395-02 so the seven action inputs are one file a reader can read\n * as the closed class it is. The shape is byte-unchanged.\n */\nexport const ConfigFieldSetInputSchema = z.object({\n /** A dotted config path, e.g. `use.timeout` — split on `.` by the yaml Document mutation. */\n path: z.string().min(1),\n value: z.union([z.string(), z.number(), z.boolean()]),\n}).strict()\n\nexport type ConfigFieldSetInput = z.infer<typeof ConfigFieldSetInputSchema>\n\n/**\n * `config.project.scaffold` — configure a project from zero (D-13, CFGM-05).\n *\n * ONE FIELD, AND THE MODEL FILLS ONLY THAT ONE. D-13 is explicit: the LLM picks the DOMAIN token\n * from the utterance and deterministic host code derives everything else — the scheme, the target\n * name, the file set. Every field this shape does not have is a field a model could otherwise\n * invent, and `booking.com` versus `booking.de` is a coin flip review should not have to catch.\n */\nexport const ConfigProjectScaffoldInputSchema = z.object({\n /** The bare domain from the utterance, e.g. `booking.com`. D-15's hostname gate ran already. */\n domain: z.string().min(1),\n}).strict()\n\nexport type ConfigProjectScaffoldInput = z.infer<typeof ConfigProjectScaffoldInputSchema>\n\n// 2026-10-01, 432-17 (D-05/D-07/D-09): `config.undo.propose` and `config.proposal.apply` are deleted\n// with the proposal inbox, and so are their inputs and the git-commit apply receipts. A change is\n// written in its own call and reverted with git (D-07); there is no undo op (D-09).\n\n/** How one file of a config change is written: added, replaced, or removed. */\nexport const CONFIG_FILE_CHANGE_KINDS = ['add', 'modify', 'delete'] as const\n\nexport type ConfigFileChangeKind = (typeof CONFIG_FILE_CHANGE_KINDS)[number]\n\n/**\n * One file a config change writes: its workspace-relative path, the kind of write, the digest of\n * the bytes the change was computed against (absent for an add), and the new bytes. The writer\n * refuses when the file no longer holds the bytes `baseDigest` names, so a change never lands over\n * an edit it did not see.\n */\nexport const ConfigChangeFileSchema = z.object({\n path: z.string().min(1),\n changeKind: z.enum(CONFIG_FILE_CHANGE_KINDS),\n baseDigest: z.string().min(1).optional(),\n newContentBase64: z.string(),\n}).strict()\n\nexport type ConfigChangeFile = z.infer<typeof ConfigChangeFileSchema>\n\n// ---- 2026-09-30, 432-11 D-05/D-07: what a config change did, answered in the call ------------------\n//\n// The six config operations write their change before they answer. There is no proposal, no\n// inbox record and no second call to apply it: the answer is either what was written, a refusal\n// that wrote nothing, or an interruption that names exactly the files already written.\n\n/**\n * Why a change was blocked: the resulting configuration would not validate. The report names the\n * issues and never the value. Nothing is written or kept. A config change is not scanned for\n * secrets (441 D-15).\n */\nexport const CONFIG_BLOCKED_REASONS = ['schema-fail'] as const\n\nexport type ConfigBlockedReason = (typeof CONFIG_BLOCKED_REASONS)[number]\n\n/**\n * Why a config change was refused with nothing written.\n *\n * The first seven are facts about the request, decided before any file is touched:\n *\n * target-exists — a create names a target the registry already holds; a create never\n * replaces one.\n * target-not-found — an edit or an auth binding names a target that is not configured; the\n * refusal lists the configured names.\n * refs-only — the input carried something that is not a reference (a credential);\n * the value is never quoted.\n * unsupported-reference — a legal reference this configuration has nowhere to record.\n * not-a-hostname — the scaffold's token does not parse as a hostname.\n * already-configured — the scaffold would replace targets the project already declares.\n * unrenderable-diff — the change's bytes differ but render as nothing a person could read.\n *\n * The last three are facts about the files at the moment of writing:\n *\n * file-changed — a whole file differs from the bytes the change was built from.\n * field-changed — a field the change depends on changed since the call read it (a\n * target created meanwhile under the same name).\n * write-refused — the config transaction refused the change on the file as it now\n * stands (it no longer validates, parses or resolves).\n */\nexport const CONFIG_CHANGE_REFUSAL_REASONS = [\n 'target-exists',\n 'target-not-found',\n 'refs-only',\n 'unsupported-reference',\n 'not-a-hostname',\n 'already-configured',\n 'unrenderable-diff',\n 'file-changed',\n 'field-changed',\n 'write-refused',\n] as const\n\nexport type ConfigChangeRefusalReason = (typeof CONFIG_CHANGE_REFUSAL_REASONS)[number]\n\n/**\n * What one config operation did, answered after it wrote (432-11 D-05/D-07).\n *\n * applied — the change is on disk. `files` are the workspace-relative files written, in write\n * order; `fields` are the config fields the change set; `shownDiff` is the diff of\n * the change against the files as this call read them. An outside edit to another\n * field, merged in the write's own turn, is kept and is not part of this diff.\n * blocked — the change would not validate. It carries the report and never the change;\n * nothing was written and nothing was kept.\n * no-change — the configuration already holds the value.\n * refused — the request or the files at write time refused the change; nothing was written.\n * interrupted — a multi-file change stopped part way. `written` hold their new bytes, `failed`\n * did not, `unwritten` were never reached. Nothing is rolled back: the files are\n * plain edits a person reverts with git.\n */\nexport const ConfigChangeOutputSchema = z.discriminatedUnion('outcome', [\n z.object({\n outcome: z.literal('applied'),\n summaryLine: z.string().min(1),\n files: z.array(z.string().min(1)).min(1),\n fields: z.array(z.string().min(1)).min(1),\n /**\n * Whether the change adds a hook, a new origin, a secret-adjacent field or an out-of-set file,\n * turns `allowProduction` on, or moves a production target to another class (261003-cpv).\n */\n crossBoundary: z.boolean(),\n crossBoundaryReasons: z.array(z.enum(CROSS_BOUNDARY_REASONS)),\n shownDiff: z.string().min(1),\n }).strict(),\n z.object({\n outcome: z.literal('blocked'),\n /** What was attempted, never what was found. */\n summaryLine: z.string().min(1),\n blockedReason: z.enum(CONFIG_BLOCKED_REASONS),\n paths: z.array(z.string().min(1)).min(1),\n /** Whole-config validation issues, in the validator's own words, reduced to position for YAML. */\n validationIssues: z.array(z.string().min(1)).optional(),\n }).strict(),\n z.object({ outcome: z.literal('no-change'), path: z.string().min(1) }).strict(),\n z.object({\n outcome: z.literal('refused'),\n reason: z.enum(CONFIG_CHANGE_REFUSAL_REASONS),\n /** What was refused and what to do instead. Names fields and files, never a value. */\n detail: z.string().min(1),\n /** The configured names a caller could have meant. */\n candidates: z.array(z.string().min(1)).optional(),\n }).strict(),\n z.object({\n outcome: z.literal('interrupted'),\n summaryLine: z.string().min(1),\n written: z.array(z.string().min(1)),\n failed: z.object({\n path: z.string().min(1),\n reason: z.enum(['file-changed', 'write-failed']),\n }).strict(),\n unwritten: z.array(z.string().min(1)),\n detail: z.string().min(1),\n }).strict(),\n])\n\nexport type ConfigChangeOutput = z.infer<typeof ConfigChangeOutputSchema>\n","// What a REFERENCE looks like, stated positively (Phase 395-05, D-11 · CFGM-02).\n//\n// D-11 RATIFIED `set_auth` AS REFS-ONLY AS LAW: the committed configuration names WHERE a value\n// lives — an auth state, a plugin package, an environment variable — and never holds one. 395-02\n// enforced half of that with the SHAPE of the input DTO: `ConfigAuthSetInputSchema` has no field a\n// credential could be assigned to. This file is the other half, and it exists because the first half\n// is not enough: a model that wants to be helpful will put a bearer token in `pluginPackage`, and\n// the field it arrived in says nothing about what it holds.\n//\n// THE RULE IS PHRASED OVER WHAT IT ADMITS, NEVER OVER WHAT IT REFUSES, and that is the whole design.\n// The tempting implementation is a credential lexicon — \"refuse anything that looks like an AWS key,\n// a bearer token, a PEM block\" — and this project has measured that shape failing twice under its\n// own name: A RULE THAT CAN ONLY REFUSE WHAT IT CAN NAME CANNOT BE DRIVEN TO ZERO BY NAMING MORE\n// THINGS. Every credential family nobody thought of walks through it. The rule below names nothing\n// it refuses. It names what an auth-state name IS, what a package name IS, what an environment\n// variable name IS — three small closed shapes the configuration schema already imposes — and\n// refuses the complement. A credential family invented tomorrow is refused on the day it is invented\n// unless it happens to be spelled like a reference, and THAT residue is a bound this phase records\n// rather than a hole it pretends to have closed (see the KNOWN BOUND cell in `config-ops.test.ts`).\n//\n// THIS IS AN ADMISSION GATE, NOT THE ONLY GATE. Values that pass here still travel D-09's detector\n// scan and the seeded known-secret half, and the artifact they end up in is scanned again before\n// anything surfaces. The three do not overlap by accident: the shape rule refuses what a reference\n// cannot be, the detector half refuses named credential families, and the seeded half refuses values\n// the masker already knows — which is the only one of the three that catches a family nobody named.\n//\n// THE PATTERNS ARE RESTATED HERE ON `CONFIG_HOOK_RUNTIMES`' PRECEDENT, one file over: the config\n// schema lives in `@vostride/agent-qa-core` and this package may not import a first-party package.\n// `AUTH_STATE_SLUG_PATTERN` in `core/src/auth-state/schema.ts` is the same expression, deliberately.\n// The layering makes the direction of any drift safe rather than merely unlikely: whole-config\n// validation runs on every proposal, so a name this gate admits and `core` refuses becomes a\n// schema-fail blocked record — a worse message, never a worse outcome.\n\n/**\n * The reference kinds the config editor can be asked to write.\n *\n * RETUNE: a kind is added here when an op learns to write a new class of reference, together with\n * the shape the configuration schema already imposes on it. It is NOT a place to add a shape because\n * a value was refused: the question a new member answers is \"what does this reference look like\",\n * and if the answer is \"anything\", the field is not a reference and D-11 does not cover it.\n */\n// 2026-10-02 (quick 261002-ctr): no op writes an `auth-state-name` today — the three that did lost\n// the field, because the committed configuration has no key for it. The kind and its shape stay: a\n// member of a closed public set, matching `core`'s auth-state slug, for the op that next binds one.\nexport const CONFIG_REFERENCE_KINDS = [\n 'auth-state-name',\n 'plugin-package',\n 'env-var-name',\n] as const\n\nexport type ConfigReferenceKind = (typeof CONFIG_REFERENCE_KINDS)[number]\n\n/**\n * The admitted shape of each kind.\n *\n * `auth-state-name` — `core`'s `AUTH_STATE_SLUG_PATTERN`, which `TargetNameSchema` and\n * `AuthStateNameSchema` both are. Lowercase letters, digits and hyphens, starting with a letter\n * and ending with a letter or digit. No uppercase, no underscore, no dot, no slash, no `=`, no\n * whitespace — which is most of what a credential encoding needs.\n * `plugin-package` — an npm package name, optionally scoped. Lowercase by npm's own rule since 2017.\n * `env-var-name` — the POSIX-portable shape a shell will export. Deliberately the LOOSEST of the\n * three, and the one whose residue the recorded bound is about.\n */\nconst REFERENCE_SHAPES: Readonly<Record<ConfigReferenceKind, RegExp>> = {\n 'auth-state-name': /^[a-z][a-z0-9-]*[a-z0-9]$/,\n 'plugin-package': /^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*$/,\n 'env-var-name': /^[A-Za-z_][A-Za-z0-9_]*$/,\n}\n\n/**\n * The longest a reference of any kind may be.\n *\n * A LENGTH BOUND IS PART OF THE SHAPE, not a separate defence. npm's own limit is 214 characters and\n * an auth-state name is a path segment; nothing legitimate approaches either. A long value that also\n * satisfies one of the character classes above is the shape a base64 or hex-encoded secret takes,\n * and 214 is short enough to refuse the ones that are while being longer than any real name.\n */\nexport const MAX_CONFIG_REFERENCE_LENGTH = 214\n\n/**\n * Is this value shaped like a reference of this kind?\n *\n * ONE FUNCTION, EVERY CALLER. The ops that write references ask this rather than each carrying its\n * own idea of the shape, because three spellings of one judgement is the sibling-input failure this\n * project keeps rediscovering. The check is keyed on the reference KIND,\n * so an op added later that writes an auth-state name inherits the refusal by naming the kind.\n */\nexport function isLegalConfigReference(kind: ConfigReferenceKind, value: string): boolean {\n if (value.length === 0 || value.length > MAX_CONFIG_REFERENCE_LENGTH) return false\n return REFERENCE_SHAPES[kind].test(value)\n}\n","import type { BoundingBox } from '../primitives/bounding-box'\nimport type { Point } from '../primitives/point'\nimport type { Viewport } from '../primitives/viewport'\n\n/** An execution interval on the recorded page, in media milliseconds. No URLs or page IDs. */\nexport interface RecordingAnnotationWitness {\n startMs: number\n endMs: number\n scene: 'recorded-page'\n transform: 'identity'\n width: number\n height: number\n}\n\nexport function validRecordingAnnotation(witness: RecordingAnnotationWitness | undefined, viewport: Viewport): boolean {\n return !!witness && witness.scene === 'recorded-page' && witness.transform === 'identity'\n && [witness.startMs, witness.endMs, witness.width, witness.height].every(Number.isFinite)\n && witness.startMs >= 0 && witness.endMs > witness.startMs\n && witness.width > 0 && witness.height > 0\n && witness.width === viewport.width && witness.height === viewport.height\n}\n\nexport interface ActionAnnotationBase {\n viewport: Viewport\n direction?: 'up' | 'down' | 'left' | 'right'\n failureHighlight?: BoundingBox\n recording?: RecordingAnnotationWitness\n}\n\nexport type ActionAnnotation =\n | (ActionAnnotationBase & { kind: 'point'; point: Point & { boundingBox?: BoundingBox } })\n | (ActionAnnotationBase & { kind: 'path'; path: { start: Point; end: Point } })\n | (ActionAnnotationBase & { kind: 'pinch'; pinch: { center: Point; scale: number } })\n | (ActionAnnotationBase & { kind: 'region'; region: { boundingBox: BoundingBox } })\n\nexport function validRecordedAnnotation(annotation: ActionAnnotation): boolean {\n if (!validRecordingAnnotation(annotation.recording, annotation.viewport)) return false\n const point = (p: Point) => Number.isFinite(p.x) && Number.isFinite(p.y)\n && p.x >= 0 && p.y >= 0 && p.x <= annotation.viewport.width && p.y <= annotation.viewport.height\n const box = (b: BoundingBox) => point(b) && Number.isFinite(b.width) && Number.isFinite(b.height)\n && b.width > 0 && b.height > 0 && b.x + b.width <= annotation.viewport.width\n && b.y + b.height <= annotation.viewport.height\n if (annotation.failureHighlight && !box(annotation.failureHighlight)) return false\n switch (annotation.kind) {\n case 'point': return point(annotation.point) && (!annotation.point.boundingBox || box(annotation.point.boundingBox))\n case 'path': return point(annotation.path.start) && point(annotation.path.end)\n case 'pinch': return point(annotation.pinch.center) && Number.isFinite(annotation.pinch.scale) && annotation.pinch.scale > 0\n case 'region': return box(annotation.region.boundingBox)\n }\n}\n","import type { ActionAnnotation } from './annotation'\n\nexport interface ActionResult {\n success: boolean\n error?: string\n screenshot?: Uint8Array\n data?: unknown\n metadata?: Record<string, unknown>\n annotation?: ActionAnnotation\n}\n\nexport type RecordedActionResult = Omit<ActionResult, 'screenshot'> & {\n readonly screenshot?: never\n}\n\nexport function toRecordedActionResult(result: ActionResult): RecordedActionResult {\n const { screenshot: _screenshot, ...recorded } = result\n void _screenshot\n\n return recorded as RecordedActionResult\n}\n","/** One identity in a target refusal: the element's role, exact name and row words (438 D-02). */\nexport interface TargetIdentity {\n /** Absent only on a stated target that named no role; the observed identity always has one. */\n role?: string\n name: string\n row?: string\n}\n\nexport type TargetMismatchReason = 'role-kind' | 'name-no-shared-word' | 'name-number' | 'row'\n\n/**\n * A refused element action's block, keyed `targetRefusal` (438 D-05): the stated and observed\n * identities disagree, nothing was sent and nothing was substituted. Both identities are redacted\n * before record. A refusal is a planning decision, never an application failure.\n */\nexport interface TargetRefusalMeta {\n kind: 'target-mismatch'\n lane: 'ref' | 'fromRef' | 'toRef'\n path: 'live' | 'heal'\n stated: TargetIdentity\n observed: TargetIdentity\n reasons: TargetMismatchReason[]\n rowStated: boolean\n inputSent: false\n}\n\nexport const TARGET_REFUSAL_KEYS = [\n 'kind',\n 'lane',\n 'path',\n 'stated',\n 'observed',\n 'reasons',\n 'rowStated',\n 'inputSent',\n] as const\n\nexport const TARGET_IDENTITY_KEYS = ['role', 'name', 'row'] as const\n\nconst LANES: ReadonlySet<unknown> = new Set(['ref', 'fromRef', 'toRef'])\nconst PATHS: ReadonlySet<unknown> = new Set(['live', 'heal'])\nconst REASONS: ReadonlySet<unknown> = new Set([\n 'role-kind',\n 'name-no-shared-word',\n 'name-number',\n 'row',\n])\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction readIdentity(raw: unknown): TargetIdentity | undefined {\n if (!isRecord(raw)) return undefined\n const { role, name, row } = raw\n if (typeof name !== 'string') return undefined\n if (role !== undefined && typeof role !== 'string') return undefined\n if (row !== undefined && typeof row !== 'string') return undefined\n return {\n ...(role !== undefined ? { role } : {}),\n name,\n ...(row !== undefined ? { row } : {}),\n }\n}\n\n// Narrows field by field; a hand-edited or partial block reads as undefined (436 D-17).\nexport function readTargetRefusalMeta(\n result?: { metadata?: Record<string, unknown> },\n): TargetRefusalMeta | undefined {\n const raw = result?.metadata?.['targetRefusal']\n if (!isRecord(raw)) return undefined\n const { kind, lane, path, reasons, rowStated, inputSent } = raw\n if (kind !== 'target-mismatch' || inputSent !== false) return undefined\n if (!LANES.has(lane) || !PATHS.has(path) || typeof rowStated !== 'boolean') return undefined\n if (!Array.isArray(reasons) || reasons.length === 0) return undefined\n if (!reasons.every((reason) => REASONS.has(reason))) return undefined\n const stated = readIdentity(raw['stated'])\n const observed = readIdentity(raw['observed'])\n if (stated === undefined || observed === undefined) return undefined\n return {\n kind,\n lane: lane as TargetRefusalMeta['lane'],\n path: path as TargetRefusalMeta['path'],\n stated,\n observed,\n reasons: [...reasons] as TargetMismatchReason[],\n rowStated,\n inputSent,\n }\n}\n","/** Why a bound element could not be acted on (438 D-09). */\nexport type BindingOutcome =\n | 'stale-observation'\n | 'frame-detached'\n | 'binding-lost'\n | 'binding-changed'\n\n/**\n * A refused dispatch's block, keyed `binding` (438 D-07, D-09): the element observed under `ref` is\n * no longer the one on the page, so nothing was sent. `heal` records why a re-find found no single\n * replacement (438-07).\n */\nexport interface BindingOutcomeMeta {\n outcome: BindingOutcome\n ref: string\n inputSent: false\n heal?: 'absent' | 'not-unique'\n}\n\nexport const BINDING_OUTCOME_KEYS = ['outcome', 'ref', 'inputSent', 'heal'] as const\n\nconst OUTCOMES: ReadonlySet<unknown> = new Set([\n 'stale-observation',\n 'frame-detached',\n 'binding-lost',\n 'binding-changed',\n])\nconst HEALS: ReadonlySet<unknown> = new Set(['absent', 'not-unique'])\n\n// Narrows field by field; a hand-edited or partial block reads as undefined (436 D-17).\nexport function readBindingOutcomeMeta(\n result?: { metadata?: Record<string, unknown> },\n): BindingOutcomeMeta | undefined {\n const raw = result?.metadata?.['binding']\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined\n const { outcome, ref, inputSent, heal } = raw as Record<string, unknown>\n if (!OUTCOMES.has(outcome) || typeof ref !== 'string' || inputSent !== false) return undefined\n if (heal !== undefined && !HEALS.has(heal)) return undefined\n return {\n outcome: outcome as BindingOutcome,\n ref,\n inputSent,\n ...(heal !== undefined ? { heal: heal as NonNullable<BindingOutcomeMeta['heal']> } : {}),\n }\n}\n","import { canonicalJson } from '../determinism/canonical-json'\nimport type { Anchor } from '../identity/anchor'\nimport { normalizeAnchor } from '../identity/normalize-anchor'\nimport type { RecordId } from '../ids/record-id'\n\n/**\n * Exact per-record material required to enforce serving-volume and poisoning limits after a\n * reader selection crosses a package boundary. `renderedCost` is the cost of the bytes exposed\n * on that channel, not the source record body.\n */\nexport interface ServingRecordMetadata {\n readonly id: RecordId\n readonly sourceId: string\n readonly clusterKey: string\n readonly renderedCost: number\n}\n\n/**\n * PROVISIONAL Phase-380 Pin 2 identity. M3 may retune this grouping from field evidence, but\n * every serving channel must use this precise-first definition until then.\n */\nexport function servingClusterKey(anchors: readonly Anchor[]): string {\n const element = anchors.find((anchor) => anchor.t === 'el')\n if (element !== undefined) {\n const { ordinal: _ordinal, ...identity } = normalizeAnchor(element) as Extract<\n Anchor,\n { t: 'el' }\n >\n return canonicalJson(identity)\n }\n\n const flow = anchors.find((anchor) => anchor.t === 'flow')\n if (flow !== undefined) return canonicalJson(normalizeAnchor(flow))\n\n const page = anchors.find((anchor) => anchor.t === 'page')\n if (page !== undefined) {\n return (normalizeAnchor(page) as Extract<Anchor, { t: 'page' }>).route\n }\n\n // Records without a Pin-2 identity anchor deliberately share one conservative cluster.\n return canonicalJson([])\n}\n\nexport function servingRecordMetadata(input: {\n id: RecordId\n anchors: readonly Anchor[]\n renderedCost: number\n sourceId?: string\n}): ServingRecordMetadata {\n return {\n id: input.id,\n sourceId: input.sourceId ?? String(input.id),\n clusterKey: servingClusterKey(input.anchors),\n renderedCost: input.renderedCost,\n }\n}\n\nexport type ServingAdmissionRejectionReason =\n | 'volume-cap'\n | 'budget-cap'\n | 'source-dominance'\n | 'cluster-dominance'\n\nexport type ServingAdmissionDecision =\n | { admitted: true }\n | { admitted: false; reason: ServingAdmissionRejectionReason }\n\nexport interface ServingAdmissionState {\n readonly selectedIds: Set<string>\n readonly sourceCosts: Map<string, number>\n readonly clusterCosts: Map<string, number>\n selectedCount: number\n usedBudget: number\n}\n\nexport interface ServingAdmissionInput {\n readonly record: ServingRecordMetadata\n readonly budget: number\n readonly recordCap: number\n /** Charge a repeated cross-channel exposure while keeping its distinct-record slot free. */\n readonly chargeRepeated?: boolean\n}\n\nfunction normalizeLimit(value: number): number {\n if (value === Number.POSITIVE_INFINITY) return Number.MAX_SAFE_INTEGER\n return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0\n}\n\nexport function createServingAdmissionState(\n seeds: readonly ServingRecordMetadata[] = [],\n): ServingAdmissionState {\n const state: ServingAdmissionState = {\n selectedIds: new Set<string>(),\n sourceCosts: new Map<string, number>(),\n clusterCosts: new Map<string, number>(),\n selectedCount: 0,\n usedBudget: 0,\n }\n\n // Seeds have already crossed a serving boundary (the frozen brief), so retain their exact\n // material even if an upstream bug handed us an over-limit set. Later admissions still fail\n // closed against the accumulated costs.\n for (const seed of seeds) commitServingRecord(seed, state, true)\n return state\n}\n\n/** Pure preview used when channel-local and combined-turn authorities must commit atomically. */\nexport function inspectServingRecord(\n input: ServingAdmissionInput,\n state: ServingAdmissionState,\n): ServingAdmissionDecision {\n const budget = normalizeLimit(input.budget)\n const recordCap = normalizeLimit(input.recordCap)\n const cost = normalizeLimit(input.record.renderedCost)\n const id = String(input.record.id)\n const repeated = state.selectedIds.has(id)\n const chargeCost = !repeated || input.chargeRepeated === true\n\n if (!repeated && state.selectedCount >= recordCap) {\n return { admitted: false, reason: 'volume-cap' }\n }\n if (!chargeCost) return { admitted: true }\n if (cost === 0 || state.usedBudget + cost > budget) {\n return { admitted: false, reason: 'budget-cap' }\n }\n\n const nextSourceCost = (state.sourceCosts.get(input.record.sourceId) ?? 0) + cost\n const nextClusterCost = (state.clusterCosts.get(input.record.clusterKey) ?? 0) + cost\n // The ratified boundary is integer-only: equality is admitted; strictly above is refused.\n if (2 * nextSourceCost > budget) {\n return { admitted: false, reason: 'source-dominance' }\n }\n if (2 * nextClusterCost > budget) {\n return { admitted: false, reason: 'cluster-dominance' }\n }\n return { admitted: true }\n}\n\nfunction commitServingRecord(\n record: ServingRecordMetadata,\n state: ServingAdmissionState,\n chargeRepeated = false,\n): void {\n const id = String(record.id)\n const repeated = state.selectedIds.has(id)\n if (!repeated) {\n state.selectedIds.add(id)\n state.selectedCount += 1\n }\n if (repeated && !chargeRepeated) return\n\n const cost = normalizeLimit(record.renderedCost)\n state.sourceCosts.set(record.sourceId, (state.sourceCosts.get(record.sourceId) ?? 0) + cost)\n state.clusterCosts.set(record.clusterKey, (state.clusterCosts.get(record.clusterKey) ?? 0) + cost)\n state.usedBudget += cost\n}\n\n/** Shared greedy admission authority for brief, caution, search, and combined-turn ledgers. */\nexport function tryAdmitServingRecord(\n input: ServingAdmissionInput,\n state: ServingAdmissionState,\n): ServingAdmissionDecision {\n const decision = inspectServingRecord(input, state)\n if (decision.admitted) {\n commitServingRecord(input.record, state, input.chargeRepeated === true)\n }\n return decision\n}\n","import { z } from 'zod'\n\nimport { asEvidenceToken, asRecordId } from '../ids/record-id'\n\n/**\n * The §7.5 trust-prior origin classes. This vocabulary is deliberately separate\n * from DeltaEnvelope.origin, which records producer-stage provenance rather than\n * the strength of the evidence source used by the Beta fold.\n */\nexport type OriginClass = 'user' | 'agent-verified' | 'agent-observed' | 'import'\n\nconst originClassValues = [\n 'user',\n 'agent-verified',\n 'agent-observed',\n 'import',\n] as const satisfies readonly OriginClass[]\n\nconst commonEventShape = {\n evidenceToken: z.string().transform(asEvidenceToken),\n curationJobId: z.string(),\n buildOrdinal: z.number(),\n observationOrdinal: z.number().optional(),\n observationId: z.string().optional(),\n}\n\nconst originClassSchema = z.enum(originClassValues)\nexport const OVERTURNED_EVENT_TYPE = 'overturned' as const\nconst observationVariant = <T extends 'confirmed' | 'contradicted' | 'helpful' | 'harmful'>(\n type: T,\n) => z.object({\n ...commonEventShape,\n type: z.literal(type),\n origin: originClassSchema.optional(),\n}).strict()\n\n/**\n * The ONE canonical outcomes log carries attributed observations and explicit\n * lifecycle events. Helpful/harmful are minted now for Phase 380 attribution but\n * have no producer yet (D-10). Every line is real evidence or an explicit lifecycle\n * transition: evidence-incomplete is a prior discount, never a synthetic event\n * (D-08). Lines are append-only and never rewritten after commit (D-09).\n *\n * Event lines intentionally carry no schemaVersion; the containing bundle manifest\n * governs their format version.\n */\nexport const BundleOutcomeEventSchema = z.discriminatedUnion('type', [\n observationVariant('confirmed'),\n observationVariant('contradicted'),\n observationVariant('helpful'),\n observationVariant('harmful'),\n z.object({\n ...commonEventShape,\n type: z.literal('superseded'),\n byRecordId: z.string().transform(asRecordId),\n }).strict(),\n /**\n * 379 D-15 RATIFICATION: one retracted event replaces a bespoke window-reopen\n * event. Matching the retracted evidence/job identity inverts confirmed,\n * deprecated, superseded, and window-close effects through one fold rule, so\n * retracting a victim's superseded and window-close events is the typed\n * restoration that both reopens its window and re-derives its prior status.\n */\n z.object({\n ...commonEventShape,\n type: z.literal('retracted'),\n retractsEvidenceToken: z.string().transform(asEvidenceToken),\n retractsCurationJobId: z.string(),\n rollbackReceiptId: z.string(),\n }).strict(),\n z.object({\n ...commonEventShape,\n type: z.literal('deprecated'),\n reason: z.string(),\n }).strict(),\n z.object({\n ...commonEventShape,\n type: z.literal('promoted'),\n }).strict(),\n z.object({\n ...commonEventShape,\n type: z.literal('window-close'),\n closedAtOrdinal: z.number(),\n }).strict(),\n /**\n * 2026-09-08, 419 D-09: a compensating line beside the evidence a user mark\n * overturned — evidence only; no status moves here.\n */\n z.object({\n ...commonEventShape,\n type: z.literal(OVERTURNED_EVENT_TYPE),\n overturnsEvidenceToken: z.string().transform(asEvidenceToken),\n overturnsCurationJobId: z.string(),\n markId: z.string().regex(/^mark_[0-9a-f]{12}$/),\n }).strict(),\n])\n\nexport type BundleOutcomeEvent = z.infer<typeof BundleOutcomeEventSchema>\n\n/**\n * Derivation-level replay identity within one bundle. The record id is implicit\n * because a fold never spans bundle directories.\n */\nexport function eventDedupKey(event: BundleOutcomeEvent): string {\n return `${event.evidenceToken}:${event.curationJobId}`\n}\n\n/** First-wins, order-preserving defense against replayed outcome lines (BNDL-03). */\nexport function dedupeEvents(events: readonly BundleOutcomeEvent[]): BundleOutcomeEvent[] {\n const keys = new Set<string>()\n const deduped: BundleOutcomeEvent[] = []\n\n for (const event of events) {\n const key = eventDedupKey(event)\n if (keys.has(key)) continue\n keys.add(key)\n deduped.push(event)\n }\n\n return deduped\n}\n\n/**\n * Canonical lifecycle-effect sequence after append replay and rollback are\n * interpreted. Retraction audit lines remain in the input log but never become\n * effects themselves. Dedupe must run before target collection so a replayed\n * retraction identity retains the same first-wins law as every other event.\n */\nexport function survivingOutcomeEvents(\n events: readonly BundleOutcomeEvent[],\n): BundleOutcomeEvent[] {\n const dedupedEvents = dedupeEvents(events)\n const retractedEventKeys = new Set<string>()\n const overturnedEventKeys = new Set<string>()\n\n for (const event of dedupedEvents) {\n if (event.type === 'overturned') {\n overturnedEventKeys.add(`${event.overturnsEvidenceToken}:${event.overturnsCurationJobId}`)\n continue\n }\n if (event.type !== 'retracted') continue\n retractedEventKeys.add(eventDedupKey({\n ...event,\n evidenceToken: event.retractsEvidenceToken,\n curationJobId: event.retractsCurationJobId,\n }))\n }\n\n return dedupedEvents.filter(\n (event) => {\n if (event.type === 'retracted' || event.type === 'overturned') return false\n if (retractedEventKeys.has(eventDedupKey(event))) return false\n // 419 D-09: even a malformed citation cannot cancel a lifecycle transition.\n const isObservation = event.type === 'confirmed' || event.type === 'contradicted'\n || event.type === 'helpful' || event.type === 'harmful'\n return !isObservation || !overturnedEventKeys.has(eventDedupKey(event))\n },\n )\n}\n","import {\n survivingOutcomeEvents,\n type BundleOutcomeEvent,\n type OriginClass,\n} from './outcome-event'\n\n/**\n * PROVISIONAL origin priors for §7.5. M3 owns calibration once real attributed\n * outcomes exist. These are internal constitution values, never config keys.\n */\nexport const ORIGIN_PRIORS = {\n user: { alpha: 3, beta: 1 },\n 'agent-verified': { alpha: 2, beta: 1 },\n 'agent-observed': { alpha: 1, beta: 1 },\n import: { alpha: 0.5, beta: 1 },\n} as const satisfies Record<OriginClass, { alpha: number; beta: number }>\n\n/** Neutral pseudo-count data. Zero components are valid endpoint priors. */\nexport type TrustPriorTable = Partial<Record<OriginClass, { alpha: number; beta: number }>>\n\nfunction priorDataObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)\n}\n\n/** Reject the whole supplied table, including unused rows, without exposing input bytes. */\nexport function guardTrustPriorTable(value: unknown): TrustPriorTable {\n try {\n if (!priorDataObject(value)) throw new TypeError()\n const table: TrustPriorTable = {}\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== 'string' || !Object.hasOwn(ORIGIN_PRIORS, key)) throw new TypeError()\n const row: unknown = Object.getOwnPropertyDescriptor(value, key)?.value\n if (!priorDataObject(row) || Reflect.ownKeys(row).length !== 2) throw new TypeError()\n const alpha: unknown = Object.getOwnPropertyDescriptor(row, 'alpha')?.value\n const beta: unknown = Object.getOwnPropertyDescriptor(row, 'beta')?.value\n if (typeof alpha !== 'number' || typeof beta !== 'number'\n || !Number.isFinite(alpha) || !Number.isFinite(beta) || alpha < 0 || beta < 0\n || !Number.isFinite(alpha + beta) || alpha + beta <= 0) throw new TypeError()\n table[key as OriginClass] = { alpha, beta }\n }\n return table\n } catch {\n throw new TypeError('Invalid trust prior table')\n }\n}\n\n/**\n * PROVISIONAL D-08 prior discount; M3 owns calibration against evidence-complete\n * outcomes. It multiplies alpha only and is an internal constant, never a config key.\n */\nexport const EVIDENCE_INCOMPLETE_ALPHA_DISCOUNT = 0.5\n\n/**\n * PROVISIONAL D-10 serving-attribution weight. Phase 380 mints the first real\n * helpful/harmful events and M3 owns calibration; this is never a config key.\n */\nexport const SERVING_ATTRIBUTION_WEIGHT = 0.25\n\nexport type BundleStatus = 'active' | 'candidate' | 'superseded' | 'deprecated'\n\nexport interface DerivedTrustState {\n trust: number\n counters: {\n confirmed: number\n contradicted: number\n helpful: number\n harmful: number\n }\n status: BundleStatus\n validity: {\n openedAtOrdinal: number\n closedAtOrdinal?: number\n }\n /**\n * 379 D-05 RATIFICATION: the latest surviving real confirmation. Retraction and\n * window restoration never refresh this ordinal; staleness is derived as\n * asOfBuild minus this value. Index projections must bump their schema version\n * when adding this field so every existing bundle is re-projected (Plan 379-05).\n */\n lastConfirmedOrdinal: number\n}\n\nconst STATUS_PRECEDENCE: Record<BundleStatus, number> = {\n active: 4,\n candidate: 3,\n superseded: 2,\n deprecated: 1,\n}\n\nfunction lifecycleStatus(event: BundleOutcomeEvent): BundleStatus | undefined {\n switch (event.type) {\n case 'promoted':\n return 'active'\n case 'superseded':\n return 'superseded'\n case 'deprecated':\n return 'deprecated'\n default:\n return undefined\n }\n}\n\n/**\n * Pure BNDL-03 derivation shared by bundle reads and Phase 375 rebuilds. Events\n * are deduplicated inside the fold, counters/status/validity are derived rather\n * than stored as frontmatter scalars, and the LLM never supplies the trust number.\n * Event-level origin is audit metadata only; the immutable bundle provenance\n * selects the origin-class prior through opts.\n */\nexport function foldBundleTrust(\n events: readonly BundleOutcomeEvent[],\n opts: {\n originClass: OriginClass\n evidenceIncomplete: boolean\n createdAtOrdinal: number\n },\n priors?: TrustPriorTable,\n): DerivedTrustState {\n const suppliedPriors = priors === undefined ? undefined : guardTrustPriorTable(priors)\n const survivingEvents = survivingOutcomeEvents(events)\n\n const counters = {\n confirmed: 0,\n contradicted: 0,\n helpful: 0,\n harmful: 0,\n }\n let status: BundleStatus = 'candidate'\n let statusBuildOrdinal = opts.createdAtOrdinal\n let latestClose: { buildOrdinal: number; closedAtOrdinal: number } | undefined\n let lastConfirmedOrdinal: number | undefined\n\n for (const event of survivingEvents) {\n switch (event.type) {\n case 'overturned':\n // 419 D-09: overturnsEvidenceToken is interpreted by survivingOutcomeEvents;\n // the compensating audit line supplies no positive or harmful count.\n break\n case 'confirmed':\n counters.confirmed += 1\n lastConfirmedOrdinal = Math.max(\n lastConfirmedOrdinal ?? event.buildOrdinal,\n event.buildOrdinal,\n )\n break\n case 'contradicted':\n counters.contradicted += 1\n break\n case 'helpful':\n counters.helpful += 1\n break\n case 'harmful':\n counters.harmful += 1\n break\n case 'window-close':\n if (\n latestClose === undefined\n || event.buildOrdinal > latestClose.buildOrdinal\n || (\n event.buildOrdinal === latestClose.buildOrdinal\n && event.closedAtOrdinal > latestClose.closedAtOrdinal\n )\n ) {\n latestClose = {\n buildOrdinal: event.buildOrdinal,\n closedAtOrdinal: event.closedAtOrdinal,\n }\n }\n break\n }\n\n const nextStatus = lifecycleStatus(event)\n if (\n nextStatus !== undefined\n && (\n event.buildOrdinal > statusBuildOrdinal\n || (\n event.buildOrdinal === statusBuildOrdinal\n && STATUS_PRECEDENCE[nextStatus] > STATUS_PRECEDENCE[status]\n )\n )\n ) {\n status = nextStatus\n statusBuildOrdinal = event.buildOrdinal\n }\n }\n\n const prior = suppliedPriors?.[opts.originClass] ?? ORIGIN_PRIORS[opts.originClass]\n const alpha = prior.alpha * (\n opts.evidenceIncomplete ? EVIDENCE_INCOMPLETE_ALPHA_DISCOUNT : 1\n )\n const positiveEvidence = counters.confirmed + SERVING_ATTRIBUTION_WEIGHT * counters.helpful\n const negativeEvidence = counters.contradicted + SERVING_ATTRIBUTION_WEIGHT * counters.harmful\n // Discounting the smallest positive alpha can underflow. With no negative mass or\n // observations the exact positive endpoint is still one; do not invent epsilon mass.\n const trust = alpha === 0 && prior.beta === 0\n && positiveEvidence === 0 && negativeEvidence === 0\n ? 1\n : (positiveEvidence + alpha) / (\n positiveEvidence + negativeEvidence + alpha + prior.beta\n )\n\n return {\n trust,\n counters,\n status,\n validity: latestClose === undefined\n ? { openedAtOrdinal: opts.createdAtOrdinal }\n : {\n openedAtOrdinal: opts.createdAtOrdinal,\n closedAtOrdinal: latestClose.closedAtOrdinal,\n },\n lastConfirmedOrdinal: lastConfirmedOrdinal ?? opts.createdAtOrdinal,\n }\n}\n","/**\n * Phase 377 D-09 distilled graph evidence contract (memory.md §6.1).\n * observations.jsonl stores one guarded observation object per line; the file reader lives at the\n * knowledge-local boundary, while this browser-safe module owns each line's strict validation.\n */\nimport { z } from 'zod'\n\nimport { createVersionGuard } from '../versioning/create-version-guard'\n\nexport const DISTILLED_OBSERVATION_SCHEMA_VERSION = 2\n\nconst stepSchema = z.object({\n naturalKey: z.string(),\n ordinal: z.number().int().nonnegative(),\n}).strict()\n\nconst testSchema = z.object({ id: z.string() }).strict()\nconst procedureSchema = z.object({ id: z.string() }).strict()\nconst flowSchema = z.object({\n name: z.string(),\n precedes: z.string().optional(),\n}).strict()\nconst surfaceSchema = z.object({\n kind: z.enum(['page', 'screen']),\n naturalKey: z.string(),\n}).strict()\nconst elementSchema = z.object({ naturalKey: z.string() }).strict()\nconst locatorSchema = z.object({ selector: z.string() }).strict()\nexport const cautionRootCauseClassSchema = z.enum(['environment', 'timeout', 'flake'])\nexport type CautionRootCauseClass = z.infer<typeof cautionRootCauseClassSchema>\nconst errorSchema = z.object({\n naturalKey: z.string(),\n /**\n * 379 D-16 typed caution evidence. When present, this is identity-bearing evidence and joins\n * the candidate content address; Plan 379-04 plumbs it from the deterministic emit pre-pass.\n */\n rootCauseClass: cautionRootCauseClassSchema.optional(),\n}).strict()\n\nexport const distilledObservationSchema = z.object({\n schemaVersion: z.number().int().positive(),\n step: stepSchema,\n platform: z.enum(['web', 'mobile']).optional(),\n test: testSchema.optional(),\n procedure: procedureSchema.optional(),\n flow: flowSchema.optional(),\n surface: surfaceSchema.optional(),\n element: elementSchema.optional(),\n locator: locatorSchema.optional(),\n error: errorSchema.optional(),\n observedAtOrdinal: z.number().int().nonnegative(),\n}).strict().superRefine((observation, ctx) => {\n if (\n (observation.element !== undefined || observation.locator !== undefined)\n && observation.platform === undefined\n ) {\n ctx.addIssue({\n code: 'custom',\n path: ['platform'],\n message: 'element or locator requires platform (377 D-09; Pitfall 8)',\n })\n }\n\n if (observation.locator !== undefined && observation.element === undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['element'],\n message: 'locator requires element (377 D-09)',\n })\n }\n\n if (\n observation.platform !== undefined\n && observation.surface !== undefined\n && (\n (observation.platform === 'web' && observation.surface.kind !== 'page')\n || (observation.platform === 'mobile' && observation.surface.kind !== 'screen')\n )\n ) {\n ctx.addIssue({\n code: 'custom',\n path: ['surface', 'kind'],\n message: 'surface kind must agree with platform (377 D-09)',\n })\n }\n})\n\nexport type DistilledObservation = z.infer<typeof distilledObservationSchema>\n\nconst guardDistilledObservationVersion = createVersionGuard<DistilledObservation>({\n name: 'DistilledObservation',\n current: DISTILLED_OBSERVATION_SCHEMA_VERSION,\n migrations: {},\n})\n\n/** Guards and parses one untrusted observations.jsonl line. */\nexport function guardDistilledObservation(value: unknown): DistilledObservation {\n return distilledObservationSchema.parse(guardDistilledObservationVersion(value))\n}\n","import type { BundleKind, FactSubtype } from '../delta/envelope'\nimport type { Anchor } from '../identity/anchor'\nimport type { EvidenceToken } from '../ids/record-id'\nimport type { DistilledObservation } from './distilled-observation'\nimport type { OriginClass } from './outcome-event'\nimport type { BundleStatus } from './trust-fold'\nimport type { ScopeKey } from '../identity/scope-key'\nimport type { PromotionPath } from './promotion-path'\nimport { standingReceiptsByGate, type GateReceipt } from './gate-receipt'\nexport { PROMOTION_PATHS, PROMOTION_PATH_STRENGTH, strongerPromotionPath } from './promotion-path'\nexport type { PromotionPath } from './promotion-path'\n\nexport type PromotionOutcome =\n | { kind: 'promoted'; promotionPath: PromotionPath; citedReceiptDigests: readonly string[] }\n | { kind: 'already-active'; promotionPath?: PromotionPath }\nexport type GateReceiptRecordOutcome = { kind: 'appended' } | { kind: 'duplicate' }\nexport interface PromotionCandidateProvenance {\n runIds: readonly string[]\n receiptDigests: readonly string[]\n capturedAtOrdinals: readonly number[]\n}\nexport interface PromotionPostureCandidate {\n id: string\n product: string\n scope: ScopeKey\n provenance: PromotionCandidateProvenance\n}\nexport type ResolvePromotionPosture = (\n candidate: PromotionPostureCandidate,\n) => PromotionGatePosture | undefined\n\nexport type PromotionGateObservation = Pick<DistilledObservation, 'element' | 'error'>\n\nexport const GATE_SET_VERDICT_WORDS = ['ok', 'empty-gate-set', 'unprovenanced-candidate'] as const\nexport type GateSetVerdictWord = (typeof GATE_SET_VERDICT_WORDS)[number]\nexport interface PromotionJudgePosture {\n capable: boolean\n reason: 'eligible' | 'no-judge-configured' | 'no-eligible-judge'\n judgeFamily?: string\n /** Composite-only disclosure, copied from the gate's capability assessment. */\n judgeModelId?: string\n panelSize?: number\n members?: readonly { judgeModelId: string; judgeFamily: string }[]\n families?: {\n judge?: string\n replayed?: string\n recorded?: string\n members?: readonly { judgeModelId: string; judgeFamily?: string }[]\n offendingPair?: readonly [string, string]\n }\n}\n// 2026-09-30, 432-10 D-05/D-22: the pending-review marker left with the proposal inbox; the\n// gate-inconsistent hold is read from standing receipts alone.\nexport interface PromotionCanaryPosture {\n kind: 'provided' | 'not-provided'\n attributedRows?: number\n rarePathEligible: boolean\n}\nexport interface PromotionPostureScope {\n partition: string\n resolution: 'product-key' | 'default-fallback'\n}\ninterface PromotionSplitCounts {\n natural: number\n heldOutShared: number\n heldOutPrivate: number\n adversarial: number\n}\nexport interface PromotionGateSetCounts extends PromotionSplitCounts {\n excludedCount: number\n remaining?: { before: PromotionSplitCounts; after: PromotionSplitCounts }\n}\nexport interface ResolvedPromotionGatePosture {\n kind: 'resolved'\n replayGateAvailable: boolean\n gateSetNonEmpty: boolean\n gateSetVerdict: GateSetVerdictWord\n corpusDigest: string\n minimumGateSet: number\n counts: PromotionGateSetCounts\n scope: PromotionPostureScope\n judge: PromotionJudgePosture\n canary: PromotionCanaryPosture\n}\nexport interface UnavailablePromotionGatePosture {\n kind: 'unavailable'\n replayGateAvailable: boolean\n refusals: readonly string[]\n /** Declared panel capability remains knowable without a measured floor. */\n judge?: PromotionJudgePosture\n}\nexport type PromotionGatePosture = ResolvedPromotionGatePosture | UnavailablePromotionGatePosture\n\n/** Bundle-derivable evidence only; callers assemble this view from canonical bundle truth. */\nexport interface PromotionGateInput {\n kind: BundleKind\n subtype?: FactSubtype\n status: BundleStatus\n validityOpen: boolean\n anchors: readonly Anchor[]\n originClass: OriginClass\n withheld: boolean\n needsEnrichment: boolean\n evidenceIncomplete: boolean\n distilledObservations: readonly PromotionGateObservation[]\n /** V4: surviving code-derived confirmation identities from canonical outcome truth. */\n confirmedOutcomeEvidenceTokens: readonly EvidenceToken[]\n hasUserDeprecateInLineage: boolean\n memoryOffForAnchorGroup: boolean\n /**\n * 414 D-14: OPTIONAL and additive. Absent means \"no replay gate exists on this host\" — the\n * v51 BYOM floor of `spec/v2/memory.md` §12.2, whose verdicts must stay byte-identical — so\n * a caller that knows nothing about gate sets keeps the pre-414 answer for every input.\n */\n gatePosture?: PromotionGatePosture\n gateReceipts?: readonly GateReceipt[]\n}\n\nexport type PromotionGateHoldReason =\n | 'kind-excluded'\n | 'not-candidate'\n | 'window-closed'\n | 'withheld'\n | 'needs-enrichment'\n | 'evidence-incomplete'\n | 'no-confirmed-evidence'\n | 'no-element-observation'\n | 'missing-root-cause'\n | 'memory-off-anchor'\n | 'user-deprecated'\n | 'empty-gate-set'\n | 'gate1-receipt-required'\n | 'gate2-receipt-required'\n | 'gate-failed'\n | 'gate-abstained'\n | 'receipt-stale'\n | 'unprovenanced-candidate'\n | 'posture-unavailable'\n // 2026-09-07, 418 D-17 / ATTR-04: cross-signal contradiction; precedes gate-failed\n | 'gate-inconsistent'\n\n/**\n * The v54 deletion bar on the hold-reason vocabulary (414 D-14 / D-22).\n *\n * This is a PROJECTION of the union above, not a second declaration of it: the `satisfies`\n * clause makes an entry that names no member a compile error, and the reverse direction (a\n * member no entry names) is pinned by the never-bar in `__tests__/promotion-gate.test-d.ts`.\n * The hand-spelled runtime cell in `__tests__/promotion-gate-hold-reasons.test.ts` catches the\n * third case — a member widened in through a cast, which satisfies both compile-time halves.\n *\n * `promotionHoldReason` is a PERSISTED value in knowledge-local commit outcomes and in CLI\n * output, so a member joining or leaving this list is a coordinated change, never a local\n * edit. Phase 416 (PROM-04) extends the vocabulary THROUGH this bar rather than creating it.\n */\nexport const PROMOTION_GATE_HOLD_REASONS = [\n 'kind-excluded',\n 'not-candidate',\n 'window-closed',\n 'withheld',\n 'needs-enrichment',\n 'evidence-incomplete',\n 'no-confirmed-evidence',\n 'no-element-observation',\n 'missing-root-cause',\n 'memory-off-anchor',\n 'user-deprecated',\n 'empty-gate-set',\n 'gate1-receipt-required',\n 'gate2-receipt-required',\n 'gate-failed',\n 'gate-abstained',\n 'receipt-stale',\n 'unprovenanced-candidate',\n 'posture-unavailable',\n // 2026-09-07, 418 D-17 / ATTR-04: cross-signal contradiction; precedes gate-failed\n 'gate-inconsistent',\n] as const satisfies readonly PromotionGateHoldReason[]\n\nexport type GateInconsistencyShape = 'gate1-pass-gate2-fail' | 'gate2-pass-gate1-heldout-fail'\n// prettier-ignore\nexport const GATE_INCONSISTENCY_SHAPES = ['gate1-pass-gate2-fail', 'gate2-pass-gate1-heldout-fail'] as const satisfies readonly GateInconsistencyShape[]\nexport interface GateInconsistency {\n shape: GateInconsistencyShape\n gate1Digest: string\n gate2Digest: string\n}\n\n/**\n * 2026-09-07, 418 D-18: same digest means Gate-1 versus Gate-2, independently of the\n * posture's current digest. A contradiction on an older digest precedes staleness.\n * Fold to standing receipts first: historical contradictions do not override newer evidence.\n */\nexport function detectGateInconsistency(standing: readonly GateReceipt[]): GateInconsistency | undefined {\n const receipts = standingReceiptsByGate(standing)\n const g1 = receipts.find(receipt => receipt.gate === 1)\n const g2 = receipts.find(receipt => receipt.gate === 2)\n if (g1 === undefined || g2 === undefined ||\n g1.corpusVersion.corpusDigest !== g2.corpusVersion.corpusDigest) return undefined\n let shape: GateInconsistencyShape\n if (g1.verdict === 'pass' && g2.verdict === 'fail') {\n shape = 'gate1-pass-gate2-fail'\n } else if (g2.verdict === 'pass' && g1.verdict === 'fail' &&\n (g1.harmed ?? []).some(row => row.split === 'held-out')) {\n shape = 'gate2-pass-gate1-heldout-fail'\n } else {\n return undefined\n }\n return { shape, gate1Digest: g1.receiptDigest, gate2Digest: g2.receiptDigest }\n}\n\nexport type PromotionGateVerdict =\n | { verdict: 'promote'; promotionPath: PromotionPath; citedReceiptDigests: readonly string[] }\n | { verdict: 'hold'; reason: PromotionGateHoldReason }\n\nfunction hold(reason: PromotionGateHoldReason): PromotionGateVerdict {\n return { verdict: 'hold', reason }\n}\n\nfunction promoteVia(input: PromotionGateInput): PromotionGateVerdict {\n const posture = input.gatePosture\n if (posture === undefined || posture.kind !== 'resolved' || !posture.replayGateAvailable) {\n return { verdict: 'promote', promotionPath: 'deterministic-verdict-floor', citedReceiptDigests: [] }\n }\n const standing = standingReceiptsByGate(input.gateReceipts ?? [])\n const g1 = standing.find(receipt => receipt.gate === 1)\n if (g1 === undefined) return hold('gate1-receipt-required')\n if (g1.verdict === 'fail') return hold('gate-failed')\n if (g1.verdict === 'abstain') return hold('gate-abstained')\n if (g1.corpusVersion.corpusDigest !== posture.corpusDigest) return hold('receipt-stale')\n\n const g2 = standing.find(receipt => receipt.gate === 2)\n if (g2 !== undefined) {\n if (g2.verdict === 'fail') return hold('gate-failed')\n if (g2.verdict === 'abstain') return hold('gate-abstained')\n if (g2.corpusVersion.corpusDigest !== posture.corpusDigest) return hold('receipt-stale')\n if (g2.producedAtOrdinal >= g1.producedAtOrdinal) {\n return { verdict: 'promote', promotionPath: 'gate1+gate2',\n citedReceiptDigests: [g1.receiptDigest, g2.receiptDigest] }\n }\n }\n if (posture.canary.rarePathEligible === true) {\n return { verdict: 'promote', promotionPath: 'gate1-lower-trust',\n citedReceiptDigests: [g1.receiptDigest] }\n }\n return hold('gate2-receipt-required')\n}\n\nfunction promotionElementAnchor(\n input: PromotionGateInput,\n): Extract<Anchor, { t: 'el' }> | undefined {\n const primary = input.anchors[0]\n if (primary?.t === 'el') return primary\n if (primary?.t !== 'page' || input.subtype !== 'navigational') return undefined\n return input.anchors.find(\n (anchor): anchor is Extract<Anchor, { t: 'el' }> => anchor.t === 'el',\n )\n}\n\nfunction hasMatchingElementObservation(input: PromotionGateInput): boolean {\n const anchor = promotionElementAnchor(input)\n if (anchor?.ordinal === undefined) return false\n const naturalKey = `${anchor.role}:${anchor.name}:${anchor.ordinal}`\n const elements = input.distilledObservations.flatMap((observation) =>\n observation.element === undefined ? [] : [observation.element],\n )\n return elements.length === 1 && elements[0]?.naturalKey === naturalKey\n}\n\n/**\n * 379 A2 / D-16 / D-18 RATIFICATION: promotion keys on durable evidence, not the authorship\n * path. An evidence-complete deterministic-fallback fact promotes; a fallback Add lacking the\n * gate evidence (for example, needs-enrichment or ambiguous element evidence) remains candidate.\n * This pure predicate performs no loading and has no provider, port, or model dependency.\n */\nexport function evaluatePromotionGate(input: PromotionGateInput): PromotionGateVerdict {\n if (input.kind !== 'fact' && input.kind !== 'caution') return hold('kind-excluded')\n if (input.status !== 'candidate') return hold('not-candidate')\n if (!input.validityOpen) return hold('window-closed')\n const posture = input.gatePosture\n if (posture?.kind === 'unavailable') return hold('posture-unavailable')\n if (posture?.replayGateAvailable === true && posture.gateSetVerdict === 'unprovenanced-candidate') {\n return hold('unprovenanced-candidate')\n }\n if (posture?.replayGateAvailable === true && posture.gateSetNonEmpty === false) {\n return hold('empty-gate-set')\n }\n const standing = standingReceiptsByGate(input.gateReceipts ?? [])\n const g3 = standing.find(receipt => receipt.gate === 3)\n if (g3?.verdict === 'pass') {\n return { verdict: 'promote', promotionPath: 'user-sovereign',\n citedReceiptDigests: [g3.receiptDigest] }\n }\n // 2026-09-07, 418 D-17/D-20: directly after sovereign is the earliest slot allowed\n // by 416's kind/status/window and gate-set precedence. Fourteen holds precede\n // promoteVia, which also floors without posture: a never-confirmed candidate's first\n // live harm must report its contradiction before no-confirmed-evidence can mask it.\n // 2026-09-30, 432-10 D-05/D-22: the pending-proposal hold left with the inbox (thirteen holds\n // now); this evidence check is the one gate-inconsistent hold.\n if (detectGateInconsistency(standing) !== undefined) return hold('gate-inconsistent')\n if (input.withheld) return hold('withheld')\n if (input.needsEnrichment) return hold('needs-enrichment')\n if (input.evidenceIncomplete) return hold('evidence-incomplete')\n if (!input.confirmedOutcomeEvidenceTokens.some((token) => token.length > 0)) {\n return hold('no-confirmed-evidence')\n }\n if (input.memoryOffForAnchorGroup) return hold('memory-off-anchor')\n if (input.hasUserDeprecateInLineage) return hold('user-deprecated')\n\n if (input.kind === 'fact') {\n return hasMatchingElementObservation(input)\n ? promoteVia(input)\n : hold('no-element-observation')\n }\n\n return input.distilledObservations.some(\n (observation) => observation.error?.rootCauseClass !== undefined,\n )\n ? promoteVia(input)\n : hold('missing-root-cause')\n}\n","import type { EvidenceToken } from '../ids/record-id'\nimport type { PromotionGateInput } from './promotion-gate'\n\n/** LOCKED D-19 maximum for the always-on organic canary reservation. */\nexport const COLD_START_MAX_RECORDS = 2\n\n/**\n * 2026-09-07, 418 D-14: absolute active gate1-lower-trust count per product-tier scope.\n * Sized like the cold-start reservation so a three-record product can still hold two\n * rare-path records; a fraction would round to zero. Override: eval.gate2.maxLowerTrustPerScope.\n */\nexport const GATE2_DEFAULT_MAX_LOWER_TRUST_PER_SCOPE = 2\n\n/** LOCKED D-19 maximum share of the caller-supplied brief budget. */\nexport const COLD_START_MAX_BUDGET_FRACTION = 0.2\n\n/**\n * PROVISIONAL D-20 candidate trust discount. M3 owns calibration from attributed outcomes;\n * this remains an internal constitution value, never a config key.\n */\nexport const COLD_START_TRUST_DISCOUNT = 0.5\n\n/**\n * 2026-09-07, 418 D-15: a passed offline Gate-1 receipt warrants more trust than the\n * cold-start unverified discount, but less than full trust without attributed live benefit.\n * Lifts on the gate1+gate2 upgrade; internal constitution value, never a config key.\n */\nexport const LOWER_TRUST_PATH_DISCOUNT = 0.75\n\n/**\n * 2026-09-07, 418 D-12: two samples from different runs inside the validity window\n * confirm stale-state harm — the smallest count beyond one run's environment.\n * Internal constitution value, never a config key.\n */\nexport const GATE2_DEFAULT_STALE_CONFIRMATIONS = 2\n\nexport interface VettedCandidateInput extends Pick<\n PromotionGateInput,\n | 'kind'\n | 'status'\n | 'validityOpen'\n | 'anchors'\n | 'originClass'\n | 'withheld'\n | 'needsEnrichment'\n | 'evidenceIncomplete'\n | 'hasUserDeprecateInLineage'\n | 'memoryOffForAnchorGroup'\n> {\n /** Branded tokens projected from confirmed canonical outcome events. */\n confirmedOutcomeEvidenceTokens: readonly EvidenceToken[]\n}\n\n/**\n * Implements the researcher-pinned V1-V9 positive predicate. D-21's LOCKED hard exclusions are\n * evaluated first: candidacy/open validity, withheld provenance, a memory-off anchor group, and\n * user-deprecated lineage can never become eligible through a trust discount. The remaining\n * positive checks are provisional until M3 calibrates real attributed outcomes.\n */\nexport function isVettedCandidate(input: VettedCandidateInput): boolean {\n const candidacyPasses = input.status === 'candidate' && input.validityOpen\n if (\n !candidacyPasses\n || input.withheld\n || input.memoryOffForAnchorGroup\n || input.hasUserDeprecateInLineage\n ) {\n return false\n }\n\n return (\n (input.originClass === 'agent-verified' || input.originClass === 'user')\n && !input.evidenceIncomplete\n && input.confirmedOutcomeEvidenceTokens.some((token) => token.length > 0)\n && !input.needsEnrichment\n && (input.kind === 'fact' || input.kind === 'caution')\n )\n}\n\nexport interface ColdStartBudgetEntry {\n readonly tokenEstimate: number\n}\n\n/**\n * D-19's ALWAYS-ON organic canary channel, not a bootstrapping state machine. Warm stores keep\n * this reservation available so attributed candidate outcomes remain reachable. Selection is\n * pure, deterministic, and order-preserving; callers provide discounted-trust order and the real\n * brief budget, then the LOCKED two-record and twenty-percent walls apply, whichever is smaller.\n */\nexport function applyColdStartSubCap<T extends ColdStartBudgetEntry>(\n vetted: readonly T[],\n budgetShareTokens: number,\n): T[] {\n const tokenCap = Math.max(0, budgetShareTokens) * COLD_START_MAX_BUDGET_FRACTION\n const selected: T[] = []\n let usedTokens = 0\n\n for (const entry of vetted) {\n if (selected.length >= COLD_START_MAX_RECORDS) break\n if (!Number.isFinite(entry.tokenEstimate) || entry.tokenEstimate < 0) break\n if (usedTokens + entry.tokenEstimate > tokenCap) break\n\n selected.push(entry)\n usedTokens += entry.tokenEstimate\n }\n\n return selected\n}\n","import { z } from 'zod'\n\n/**\n * PROVISIONAL D-04 CUSUM allowance and decision interval in baseline-sigma\n * units. M3 owns calibration; these are internal constitution values, never\n * config keys.\n */\nexport const CUSUM_SLACK_K = 0.5\nexport const CUSUM_DECISION_H = 5\n\n/**\n * PROVISIONAL D-03 EWMA smoothing factor. The moving average is descriptive\n * distribution output only; it is never detector authority or a config key.\n */\nexport const MEASUREMENT_EWMA_ALPHA = 0.2\n\n/**\n * PROVISIONAL D-04 weighted-gap significance and minimum mode size. M3 owns\n * calibration; these are internal constitution values, never config keys.\n */\nexport const BIMODAL_GAP_THRESHOLD = 2.25\nexport const BIMODAL_MIN_MODE_N = 3\n\n/** Locked §9.2 evidence and drift thresholds; these are laws, not knobs. */\nexport const MEASUREMENT_MIN_N = 5\nexport const DRIFT_SIGMA_K = 3\nexport const DRIFT_RELATIVE_THRESHOLD = 0.5\n\n/**\n * PROVISIONAL D-04 confidence and kind-variance prior values. Measurement\n * metrics have no common absolute scale, so the kind prior is coefficient-of-\n * variation based. M3 owns calibration; these are never config keys.\n */\nexport const CI_SEPARATION_Z = 1.96\nexport const KIND_DEFAULT_CV = 0.3\nexport const KIND_CV_FLOOR = 1\nexport const SHRINKAGE_PSEUDO_N = 5\n\n/** PROVISIONAL D-04 revisit window for the stable-multimodal discriminator. */\nexport const MULTIMODAL_TRAILING_BUILDS = 5\n\nconst finiteNumberSchema = z.number().refine(Number.isFinite, 'Expected a finite number')\n\n/**\n * D-03's only stored detector input. The snapshot is written once when the\n * validity window opens; all current distribution and detector state is folded.\n */\nexport const measurementBaselineSchema = z.object({\n mu0: finiteNumberSchema,\n sigma0: finiteNumberSchema.nonnegative(),\n n0: z.number().int().positive(),\n openedAtOrdinal: z.number().int().nonnegative(),\n}).strict()\n\nexport type MeasurementBaseline = z.infer<typeof measurementBaselineSchema>\n\n/** Append-only numeric evidence line; ordinals replace wall-clock decisions. */\nexport const measurementObservationSchema = z.object({\n value: finiteNumberSchema,\n buildOrdinal: z.number().int().nonnegative(),\n evidenceToken: z.string(),\n curationJobId: z.string(),\n}).strict()\n\nexport type MeasurementObservation = z.infer<typeof measurementObservationSchema>\n\nexport interface MeasurementFoldState {\n n: number\n mean: number\n ewma: number\n /** Welford sum of squared deviations. */\n m2: number\n values: number[]\n cusumPos: number\n cusumNeg: number\n}\n\nexport interface MeasurementBand {\n lo: number\n hi: number\n n: number\n mean: number\n}\n\nexport interface DerivedMeasurementState {\n n: number\n mean: number\n /** Baseline-seeded descriptive EWMA; drift decisions never read this field. */\n ewma: number\n /** Population sigma over the fresh observation window. */\n sigma: number\n /** Nearest-rank pooled quantile; absent when the fresh window is empty. */\n p50: number | undefined\n /**\n * Nearest-rank pooled timeout ceiling consumed by Phase 380. Pooling all\n * modes makes a bimodal distribution safe by construction.\n */\n p95: number | undefined\n bands: MeasurementBand[]\n cusumPos: number\n cusumNeg: number\n}\n\nexport type MeasurementDriftDecision =\n | {\n decision: 'widen'\n reason: 'below-min-n' | 'ci-overlap' | 'within-threshold' | 'stable-multimodal'\n }\n | {\n decision: 'supersede'\n reason: 'threshold' | 'relative' | 'cusum' | 'regime-walk'\n }\n\nexport interface MeasurementDriftWindowBuilds {\n /** Ordered source lines used to distinguish revisited modes from a regime walk. */\n observations?: readonly MeasurementObservation[]\n /** Inclusive trailing build-ordinal width; defaults to the provisional M2 value. */\n trailingBuilds?: number\n /** Reserved for Plan 379-07's lineage/thrash fold without changing this seam. */\n lastSupersessionGapBuilds?: number\n}\n\nexport interface DecideMeasurementDriftInput {\n baseline: MeasurementBaseline\n state: DerivedMeasurementState\n windowBuilds?: MeasurementDriftWindowBuilds\n}\n\nexport interface CusumState {\n pos: number\n neg: number\n}\n\nexport interface CusumStepResult extends CusumState {\n tripped: boolean\n}\n\n/**\n * Ratified D-04 change-point step. Two-sided CUSUM references the fixed stored\n * baseline; Page-Hinkley is deliberately excluded because its running-mean\n * reference reintroduces the self-updating-reference failure banned by §9.2.\n */\nexport function cusumStep(\n state: Readonly<CusumState>,\n value: number,\n mu0: number,\n sigma0: number,\n): CusumStepResult {\n const pos = Math.max(0, state.pos + (value - mu0 - CUSUM_SLACK_K * sigma0))\n const neg = Math.max(0, state.neg - (value - mu0 + CUSUM_SLACK_K * sigma0))\n const decisionInterval = CUSUM_DECISION_H * sigma0\n\n return {\n pos,\n neg,\n tripped: pos > decisionInterval || neg > decisionInterval,\n }\n}\n\nexport interface BimodalSplit {\n /** Number of sorted values in the lower band. */\n splitIndex: number\n bands: [MeasurementBand, MeasurementBand]\n}\n\nfunction median(sorted: readonly number[]): number {\n const middle = Math.floor(sorted.length / 2)\n if (sorted.length % 2 === 1) return sorted[middle]!\n return (sorted[middle - 1]! + sorted[middle]!) / 2\n}\n\nfunction band(values: readonly number[]): MeasurementBand {\n let sum = 0\n for (const value of values) sum += value\n\n return {\n lo: values[0]!,\n hi: values[values.length - 1]!,\n n: values.length,\n mean: sum / values.length,\n }\n}\n\n/**\n * Ratified D-04 bimodality detector: a deterministic weighted largest-gap split\n * over an already sorted one-dimensional sample. At most two bands are emitted\n * in M2; recursive k-modal splitting is deferred.\n */\nexport function bimodalSplit(sorted: readonly number[]): BimodalSplit | undefined {\n const n = sorted.length\n if (n < 2 * BIMODAL_MIN_MODE_N) return undefined\n\n const weightedGaps: number[] = []\n for (let splitIndex = 1; splitIndex < n; splitIndex += 1) {\n const gap = sorted[splitIndex]! - sorted[splitIndex - 1]!\n weightedGaps.push(gap * Math.sqrt(splitIndex * (n - splitIndex)))\n }\n\n const scale = median([...weightedGaps].sort((left, right) => left - right))\n let best: { splitIndex: number; weightedGap: number } | undefined\n\n for (\n let splitIndex = BIMODAL_MIN_MODE_N;\n splitIndex <= n - BIMODAL_MIN_MODE_N;\n splitIndex += 1\n ) {\n const weightedGap = weightedGaps[splitIndex - 1]!\n if (best === undefined || weightedGap > best.weightedGap) {\n best = { splitIndex, weightedGap }\n }\n }\n\n if (best === undefined || best.weightedGap <= 0) return undefined\n if (scale > 0 && best.weightedGap / scale <= BIMODAL_GAP_THRESHOLD) return undefined\n\n const lower = sorted.slice(0, best.splitIndex)\n const upper = sorted.slice(best.splitIndex)\n return {\n splitIndex: best.splitIndex,\n bands: [band(lower), band(upper)],\n }\n}\n\n/**\n * Ratified D-04 weak variance prior. A scale-free kind CV is necessary because\n * measurement values are generic string-sourced metrics with no shared unit.\n */\nexport function shrunkSigma(sampleSigma: number, n: number, mu0: number): number {\n const evidenceN = Math.max(0, n)\n const kindSigma = KIND_DEFAULT_CV * Math.max(Math.abs(mu0), KIND_CV_FLOOR)\n const variance = (\n evidenceN * sampleSigma * sampleSigma\n + SHRINKAGE_PSEUDO_N * kindSigma * kindSigma\n ) / (evidenceN + SHRINKAGE_PSEUDO_N)\n\n return Math.sqrt(variance)\n}\n\nfunction trailingModeVisits(\n bands: readonly MeasurementBand[],\n windowBuilds: MeasurementDriftWindowBuilds | undefined,\n): { hasChronology: boolean; stable: boolean } {\n const observations = windowBuilds?.observations ?? []\n if (bands.length < 2 || observations.length === 0) {\n return { hasChronology: false, stable: false }\n }\n\n let latestBuildOrdinal = observations[0]!.buildOrdinal\n for (const line of observations) {\n latestBuildOrdinal = Math.max(latestBuildOrdinal, line.buildOrdinal)\n }\n\n const requestedWidth = windowBuilds?.trailingBuilds ?? MULTIMODAL_TRAILING_BUILDS\n const trailingBuilds = Math.max(1, Math.trunc(requestedWidth))\n const earliestBuildOrdinal = latestBuildOrdinal - trailingBuilds + 1\n const recent = observations.filter((line) => line.buildOrdinal >= earliestBuildOrdinal)\n const insideAnyBand = recent.every((line) =>\n bands.some((candidate) => line.value >= candidate.lo && line.value <= candidate.hi),\n )\n const everyBandRevisited = bands.every((candidate) =>\n recent.some((line) => line.value >= candidate.lo && line.value <= candidate.hi),\n )\n\n return {\n hasChronology: recent.length > 0,\n stable: insideAnyBand && everyBandRevisited,\n }\n}\n\n/**\n * The D-04 decision order is intentionally linear and locked: minimum evidence,\n * confidence separation, absolute/relative thresholds, fixed-baseline CUSUM,\n * then the multimodal discriminator before any supersession is minted. Widen\n * decisions append evidence only and must never count toward thrash depth.\n */\nexport function decideMeasurementDrift(\n input: Readonly<DecideMeasurementDriftInput>,\n): MeasurementDriftDecision {\n const { baseline, state } = input\n\n // Step 1: young distributions can only widen, regardless of poisoned outliers.\n if (state.n < MEASUREMENT_MIN_N) {\n return { decision: 'widen', reason: 'below-min-n' }\n }\n\n const baselineSigma = shrunkSigma(baseline.sigma0, baseline.n0, baseline.mu0)\n const windowSigma = shrunkSigma(state.sigma, state.n, baseline.mu0)\n const difference = Math.abs(state.mean - baseline.mu0)\n\n // Step 2: no downstream arm bypasses confidence-interval separation.\n const separation = CI_SEPARATION_Z * Math.sqrt(\n baselineSigma * baselineSigma / baseline.n0\n + windowSigma * windowSigma / state.n,\n )\n if (difference <= separation) {\n return { decision: 'widen', reason: 'ci-overlap' }\n }\n\n // Steps 3 and 4 arm supersession independently; reason precedence follows D-04.\n const sigmaThresholdPassed = difference > DRIFT_SIGMA_K * baselineSigma\n const relativeThresholdPassed = (\n difference > DRIFT_RELATIVE_THRESHOLD * Math.abs(baseline.mu0)\n )\n const cusumPassed = (\n state.cusumPos > CUSUM_DECISION_H * baselineSigma\n || state.cusumNeg > CUSUM_DECISION_H * baselineSigma\n )\n\n if (!sigmaThresholdPassed && !relativeThresholdPassed && !cusumPassed) {\n return { decision: 'widen', reason: 'within-threshold' }\n }\n\n // Step 5: revisiting both significant bands widens; abandoning one is a walk.\n const modeVisits = trailingModeVisits(state.bands, input.windowBuilds)\n if (modeVisits.stable) {\n return { decision: 'widen', reason: 'stable-multimodal' }\n }\n if (state.bands.length > 1 && modeVisits.hasChronology) {\n return { decision: 'supersede', reason: 'regime-walk' }\n }\n\n if (sigmaThresholdPassed) return { decision: 'supersede', reason: 'threshold' }\n if (relativeThresholdPassed) return { decision: 'supersede', reason: 'relative' }\n return { decision: 'supersede', reason: 'cusum' }\n}\n\nfunction nearestRank(sorted: readonly number[], quantile: number): number | undefined {\n if (sorted.length === 0) return undefined\n const index = Math.max(0, Math.ceil(quantile * sorted.length) - 1)\n return sorted[Math.min(index, sorted.length - 1)]\n}\n\n/**\n * Pure D-03 derivation over the append order supplied by measurements.json.\n * Welford and fixed-baseline CUSUM advance in one pass; values are then sorted\n * only for deterministic quantiles and the weighted-gap projection. No detector\n * state beyond the immutable baseline snapshot is persisted.\n */\nexport function foldMeasurements(\n baseline: MeasurementBaseline,\n lines: readonly MeasurementObservation[],\n): DerivedMeasurementState {\n const baselineSigma = shrunkSigma(baseline.sigma0, baseline.n0, baseline.mu0)\n const state: MeasurementFoldState = {\n n: 0,\n mean: 0,\n ewma: baseline.mu0,\n m2: 0,\n values: [],\n cusumPos: 0,\n cusumNeg: 0,\n }\n\n for (const line of lines) {\n state.ewma = (\n MEASUREMENT_EWMA_ALPHA * line.value\n + (1 - MEASUREMENT_EWMA_ALPHA) * state.ewma\n )\n state.n += 1\n const delta = line.value - state.mean\n state.mean += delta / state.n\n state.m2 += delta * (line.value - state.mean)\n state.values.push(line.value)\n\n const cusum = cusumStep(\n { pos: state.cusumPos, neg: state.cusumNeg },\n line.value,\n baseline.mu0,\n baselineSigma,\n )\n state.cusumPos = cusum.pos\n state.cusumNeg = cusum.neg\n }\n\n const sorted = [...state.values].sort((left, right) => left - right)\n const split = bimodalSplit(sorted)\n const sigma = state.n === 0 ? 0 : Math.sqrt(state.m2 / state.n)\n\n return {\n n: state.n,\n mean: state.mean,\n ewma: state.ewma,\n sigma,\n p50: nearestRank(sorted, 0.5),\n p95: nearestRank(sorted, 0.95),\n bands: split?.bands ?? (sorted.length === 0 ? [] : [band(sorted)]),\n cusumPos: state.cusumPos,\n cusumNeg: state.cusumNeg,\n }\n}\n","// Phase 374 gap closure: manifest identity is re-derived rather than trusted (BNDL-02,\n// D-03/D-07), keeping the read face authoritative over stored immutable semantics.\nimport { canonicalJson } from '../determinism/canonical-json'\nimport {\n computeBundleIdentityHash,\n mintBundleId,\n type BundleIdentityCore,\n type BundleIdentityInput,\n} from '../ids/content-address'\nimport { normalizeAnchor } from '../identity/normalize-anchor'\nimport type { BundleManifest } from './bundle-files'\n\nfunction identityCoreToInput(core: BundleIdentityCore): BundleIdentityInput {\n return {\n kind: core.kind,\n ...(core.subtype === null ? {} : { subtype: core.subtype }),\n primaryAnchor: core.primaryAnchor,\n scope: core.scope,\n discriminantKey: core.discriminantKey,\n }\n}\n\nexport function verifyManifestIdentity(\n manifest: Pick<BundleManifest, 'id' | 'identityHash' | 'identityCore'>,\n): string[] {\n const violations: string[] = []\n const normalizedAnchor = normalizeAnchor(manifest.identityCore.primaryAnchor)\n\n if (canonicalJson(normalizedAnchor) !== canonicalJson(manifest.identityCore.primaryAnchor)) {\n violations.push('identityCore.primaryAnchor is not stored normalized')\n }\n\n const identityInput = identityCoreToInput(manifest.identityCore)\n const recomputedIdentityHash = computeBundleIdentityHash(identityInput)\n if (recomputedIdentityHash !== manifest.identityHash) {\n violations.push(\n `identityHash mismatch: recomputed ${recomputedIdentityHash}, stored ${manifest.identityHash}`,\n )\n }\n\n const recomputedId = mintBundleId(identityInput)\n if (recomputedId !== manifest.id) {\n violations.push(`id mismatch: recomputed ${recomputedId}, stored ${manifest.id}`)\n }\n\n return violations\n}\n","import { z } from 'zod'\n\nimport type { BundleKind, FactSubtype } from '../delta/envelope'\nimport type { Anchor } from '../identity/anchor'\nimport type { ScopeKey } from '../identity/scope-key'\nimport { createVersionGuard } from '../versioning/create-version-guard'\nimport { BUNDLE_SCHEMA_VERSION } from './bundle-files'\nimport type { OriginClass } from './outcome-event'\n\nexport interface RecordFrontmatter {\n schemaVersion: number\n id: string\n kind: BundleKind\n subtype?: FactSubtype\n anchors: readonly { raw: Anchor; normalized: Anchor }[]\n scope: ScopeKey\n createdAtOrdinal: number\n originClass: OriginClass\n evidenceIncomplete: boolean\n}\n\nconst bundleKindSchema = z.enum(['fact', 'procedure', 'caution', 'unknown', 'policy'])\nconst factSubtypeSchema = z.enum([\n 'selector',\n 'behavioral',\n 'navigational',\n 'measurement',\n 'content',\n])\nconst anchorSchema = z.discriminatedUnion('t', [\n z.object({ t: z.literal('page'), route: z.string() }).strict(),\n z.object({ t: z.literal('flow'), name: z.string() }).strict(),\n z\n .object({\n t: z.literal('el'),\n role: z.string(),\n name: z.string(),\n ordinal: z.number().int().optional(),\n })\n .strict(),\n z\n .object({\n t: z.literal('platform'),\n platform: z.enum(['web', 'android', 'ios']),\n })\n .strict(),\n z.object({ t: z.literal('selector'), literal: z.string() }).strict(),\n z.object({ t: z.literal('error'), message: z.string() }).strict(),\n])\n\nexport const RecordAnchorsSchema = z.array(z.object({ raw: anchorSchema, normalized: anchorSchema }).strict())\nexport const RecordScopeSchema = z.object({\n tier: z.enum(['global', 'product', 'suite', 'test']),\n key: z.string(),\n}).strict()\n\nconst recordFrontmatterSchema: z.ZodType<RecordFrontmatter> = z\n .object({\n schemaVersion: z.literal(BUNDLE_SCHEMA_VERSION),\n id: z.string(),\n kind: bundleKindSchema,\n subtype: factSubtypeSchema.optional(),\n anchors: RecordAnchorsSchema,\n scope: RecordScopeSchema,\n createdAtOrdinal: z.number(),\n originClass: z.enum(['user', 'agent-verified', 'agent-observed', 'import']),\n evidenceIncomplete: z.boolean(),\n })\n .strict()\n .superRefine((frontmatter, ctx) => {\n if (frontmatter.kind === 'fact' && frontmatter.subtype === undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['subtype'],\n message: 'fact record frontmatter requires a fact subtype (D-06)',\n })\n }\n if (frontmatter.kind !== 'fact' && frontmatter.subtype !== undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['subtype'],\n message: 'only fact record frontmatter may carry a subtype (D-06)',\n })\n }\n })\n\nconst guardRecordFrontmatterVersion = createVersionGuard<RecordFrontmatter>({\n name: 'RecordFrontmatter',\n current: BUNDLE_SCHEMA_VERSION,\n migrations: {},\n})\n\nconst FRONTMATTER_KEY_ORDER = [\n 'schemaVersion',\n 'id',\n 'kind',\n 'subtype',\n 'anchors',\n 'scope',\n 'createdAtOrdinal',\n 'originClass',\n 'evidenceIncomplete',\n] as const satisfies readonly (keyof RecordFrontmatter)[]\n\nconst FRONTMATTER_KEYS = new Set<string>(FRONTMATTER_KEY_ORDER)\nconst REQUIRED_FRONTMATTER_KEYS = FRONTMATTER_KEY_ORDER.filter((key) => key !== 'subtype')\nconst FORBIDDEN_DERIVED_KEYS = new Set(['trust', 'counters', 'status', 'validity'])\nconst OPENING_FENCE = '---\\n'\nconst CLOSING_FENCE = '\\n---\\n\\n'\nconst SUMMARY_PREFIX = '## Summary\\n\\n'\nconst DETAIL_SEPARATOR = '\\n\\n## Detail\\n\\n'\n\nfunction validateFrontmatter(value: unknown): RecordFrontmatter {\n return recordFrontmatterSchema.parse(guardRecordFrontmatterVersion(value))\n}\n\n/** Deterministic record.md rendering over immutable-at-creation fields only (BNDL-03). */\nexport function emitRecordMarkdown(\n frontmatter: RecordFrontmatter,\n body: { summary: string; body: string },\n): string {\n const parsed = validateFrontmatter(frontmatter)\n const lines = FRONTMATTER_KEY_ORDER.flatMap((key) => {\n const value = parsed[key]\n if (value === undefined) return []\n const encoded = JSON.stringify(value)\n if (encoded === undefined) {\n throw new TypeError(`frontmatter key \"${key}\" is not JSON-serializable`)\n }\n return `${key}: ${encoded}`\n })\n\n return (\n `${OPENING_FENCE}${lines.join('\\n')}${CLOSING_FENCE}` +\n `${SUMMARY_PREFIX}${body.summary}${DETAIL_SEPARATOR}${body.body}`\n )\n}\n\nfunction parseFrontmatterLines(block: string): RecordFrontmatter {\n const values: Record<string, unknown> = {}\n\n for (const line of block.split('\\n')) {\n const separator = line.indexOf(': ')\n if (separator <= 0) {\n throw new TypeError(`malformed frontmatter line: ${JSON.stringify(line)}`)\n }\n\n const key = line.slice(0, separator)\n if (FORBIDDEN_DERIVED_KEYS.has(key)) {\n throw new TypeError(`BNDL-03 forbids derived frontmatter key \"${key}\"`)\n }\n if (!FRONTMATTER_KEYS.has(key)) {\n throw new TypeError(`unknown frontmatter key \"${key}\"`)\n }\n if (Object.hasOwn(values, key)) {\n throw new TypeError(`duplicate frontmatter key \"${key}\"`)\n }\n\n try {\n values[key] = JSON.parse(line.slice(separator + 2))\n } catch {\n throw new TypeError(`invalid JSON for frontmatter key \"${key}\"`)\n }\n }\n\n for (const key of REQUIRED_FRONTMATTER_KEYS) {\n if (!Object.hasOwn(values, key)) {\n throw new TypeError(`missing frontmatter key \"${key}\"`)\n }\n }\n\n return validateFrontmatter(values)\n}\n\n/** Strict parser for the writer-owned frontmatter and deterministic markdown section layout. */\nexport function parseRecordMarkdown(text: string): {\n frontmatter: RecordFrontmatter\n summary: string\n body: string\n} {\n if (!text.startsWith(OPENING_FENCE)) {\n throw new TypeError('record.md must start with a frontmatter fence')\n }\n\n const closingFence = text.indexOf(CLOSING_FENCE, OPENING_FENCE.length)\n if (closingFence < 0) {\n throw new TypeError('record.md is missing its closing frontmatter fence')\n }\n\n const frontmatter = parseFrontmatterLines(\n text.slice(OPENING_FENCE.length, closingFence),\n )\n const markdown = text.slice(closingFence + CLOSING_FENCE.length)\n if (!markdown.startsWith(SUMMARY_PREFIX)) {\n throw new TypeError('record.md body must start with the Summary section')\n }\n\n const sections = markdown.slice(SUMMARY_PREFIX.length)\n const detailSeparator = sections.indexOf(DETAIL_SEPARATOR)\n if (detailSeparator < 0) {\n throw new TypeError('record.md body is missing the Detail section')\n }\n\n return {\n frontmatter,\n summary: sections.slice(0, detailSeparator),\n body: sections.slice(detailSeparator + DETAIL_SEPARATOR.length),\n }\n}\n","// D-04 committed procedure step-sequence contract. The payload is embedded in record.md as ONE\n// canonicalJson fenced block (lean + PR-reviewable); parseProcedureBody is fail-closed — any\n// malformation returns undefined (downstream treats unparseable as no-match/hint, T-381-01),\n// never a throw, never eval/dynamic dispatch.\n\nimport { z } from 'zod'\n\nimport { canonicalJson } from '../determinism/canonical-json'\nimport type { Anchor } from '../identity/anchor'\nimport type { ProcedureParamType } from './curator-tier'\n\n/**\n * A descriptor-only element target (438 D-11). Replay re-finds it strictly: exactly one current\n * element with the same role, the exact observed `name` and, when stored, the `row` words. A\n * target without `name` cannot be judged strictly and is a guard miss. `nameNormalized` stays\n * for the readers that show it; `ordinal` is kept only so committed bodies still parse — nothing\n * new writes it and replay never reads it.\n */\nexport interface ProcedureGuardTarget {\n role: string\n nameNormalized: string\n name?: string\n row?: string\n ordinal?: number\n}\n\n/**\n * The per-step replay guard (D-05): the target the step is about to act on, the page anchor\n * the step was authored against, and optional stable landmark texts for the guard fold.\n */\nexport interface ProcedureGuardDescriptor {\n target: ProcedureGuardTarget\n pageAnchor: Extract<Anchor, { t: 'page' }>\n landmarks?: string[]\n}\n\nexport type ProcedureJsonValue =\n | string\n | number\n | boolean\n | null\n | ProcedureJsonValue[]\n | { [key: string]: ProcedureJsonValue }\n\nexport const procedureJsonValueSchema: z.ZodType<ProcedureJsonValue> = z.lazy(() =>\n z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(procedureJsonValueSchema),\n z.record(z.string(), procedureJsonValueSchema),\n ]),\n)\n\n/**\n * One action value slot: a JSON scalar literal, a `{ param }` ref into the payload's parameter\n * schema, or a tagged `{ json }` literal. Composite replay semantics such as fileUpload.files and\n * doubleClick/rightClick.relativePosition must survive byte-faithfully. The tag keeps object\n * literals unambiguous from `{ param }`; null, arrays, and objects ride the wrapper while scalars\n * stay bare so every pre-existing committed body remains parseable.\n */\nexport type ProcedureValueSlot =\n | string\n | number\n | boolean\n | { param: string }\n | { json: ProcedureJsonValue }\n\n/** One declared procedure parameter (D-03 closed type union). */\nexport interface ProcedureParameterSpec {\n name: string\n type: ProcedureParamType\n required: boolean\n}\n\n/**\n * One committed procedure step: the authored instruction prose, the replayable action shape\n * (targets keyed by ref lane, values keyed by field), and the D-05 guard descriptor.\n */\nexport interface ProcedureStepSpec {\n instruction: string\n action: {\n type: string\n targets: Record<string, ProcedureGuardTarget>\n values: Record<string, ProcedureValueSlot>\n }\n guard: ProcedureGuardDescriptor\n}\n\nexport const PROCEDURE_BODY_SCHEMA_VERSION = 2\n\n/** The one committed procedure body payload (stamped PROCEDURE_BODY_SCHEMA_VERSION). */\nexport interface ProcedureBodyPayload {\n schemaVersion: typeof PROCEDURE_BODY_SCHEMA_VERSION\n parameters: ProcedureParameterSpec[]\n steps: ProcedureStepSpec[]\n successAssertion: string\n}\n\nconst guardTargetSchema = z\n .object({\n role: z.string(),\n nameNormalized: z.string(),\n name: z.string().optional(),\n row: z.string().optional(),\n ordinal: z.number().int().optional(),\n })\n .strict()\n\nconst guardDescriptorSchema = z\n .object({\n target: guardTargetSchema,\n pageAnchor: z.object({ t: z.literal('page'), route: z.string() }).strict(),\n landmarks: z.array(z.string()).optional(),\n })\n .strict()\n\nconst valueSlotSchema: z.ZodType<ProcedureValueSlot> = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.object({ param: z.string() }).strict(),\n z.object({ json: procedureJsonValueSchema }).strict(),\n])\n\nconst stepSpecSchema = z\n .object({\n instruction: z.string(),\n action: z\n .object({\n type: z.string(),\n targets: z.record(z.string(), guardTargetSchema),\n values: z.record(z.string(), valueSlotSchema),\n })\n .strict(),\n guard: guardDescriptorSchema,\n })\n .strict()\n\nconst bodyPayloadSchema: z.ZodType<ProcedureBodyPayload> = z\n .object({\n schemaVersion: z.literal(PROCEDURE_BODY_SCHEMA_VERSION),\n parameters: z.array(\n z\n .object({\n name: z.string(),\n type: z.enum(['string', 'number', 'boolean', 'secret']),\n required: z.boolean(),\n })\n .strict(),\n ),\n steps: z.array(stepSpecSchema),\n successAssertion: z.string(),\n })\n .strict()\n .superRefine((payload, context) => {\n // WR-02: this committed codec is the fail-closed uniqueness AUTHORITY. Proposal-side\n // checks are advisory; rejecting duplicate names here makes an ambiguous body unservable\n // and unreplayable everywhere through parseProcedureBody's undefined-on-malformation law.\n if (!Array.isArray(payload.parameters)) return\n const names = new Set<string>()\n payload.parameters.forEach((parameter, index) => {\n if (typeof parameter?.name !== 'string') return\n if (names.has(parameter.name)) {\n context.addIssue({\n code: 'custom',\n message: `Duplicate procedure parameter name: ${parameter.name}`,\n path: ['parameters', index, 'name'],\n })\n }\n names.add(parameter.name)\n })\n })\n\nconst FENCE_OPEN = '```json agent-qa-procedure'\nconst FENCE_CLOSE = '```'\n\n/**\n * Serialize a payload into the ONE fenced canonicalJson block a record.md body carries.\n * Byte-stable across calls (canonicalJson sorts keys recursively).\n */\nexport function serializeProcedureBody(payload: ProcedureBodyPayload): string {\n return `${FENCE_OPEN}\\n${canonicalJson(payload)}\\n${FENCE_CLOSE}\\n`\n}\n\n/**\n * Fail-closed parse of a record.md body: locate the fenced block, JSON-parse it, and validate\n * structurally. ANY malformation — no fence, bad JSON, a param type outside the closed union,\n * an unknown key — returns undefined; this function never throws (T-381-01).\n */\nexport function parseProcedureBody(body: string): ProcedureBodyPayload | undefined {\n const fenceStart = body.indexOf(FENCE_OPEN)\n if (fenceStart === -1) return undefined\n const contentStart = fenceStart + FENCE_OPEN.length\n const fenceEnd = body.indexOf(`\\n${FENCE_CLOSE}`, contentStart)\n if (fenceEnd === -1) return undefined\n const raw = body.slice(contentStart, fenceEnd).trim()\n if (raw === '') return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return undefined\n }\n const result = bodyPayloadSchema.safeParse(parsed)\n return result.success ? result.data : undefined\n}\n\n/**\n * The ONE derivation of the ordered step keys feeding `computeStepSequenceSignature` for the\n * D-01 content address ({ kind: 'procedure', flowName, stepSignature }). Each key is the\n * canonicalJson of the step's structural shape — action type + descriptor targets + guard.\n * Authored prose (instruction/successAssertion) is EXCLUDED per the content-address prose ban,\n * and value slots are excluded so re-parameterization never forks procedure identity.\n */\nexport function procedureStepKeys(payload: ProcedureBodyPayload): string[] {\n return payload.steps.map((step) =>\n canonicalJson({\n action: { targets: step.action.targets, type: step.action.type },\n guard: step.guard,\n }),\n )\n}\n","import type { Anchor } from '../identity/anchor'\nimport { normalizeAnchor } from '../identity/normalize-anchor'\n\nfunction normalizedAnchorText(anchor: Anchor): string {\n const normalized = normalizeAnchor(anchor)\n switch (normalized.t) {\n case 'page':\n return normalized.route\n case 'flow':\n return normalized.name\n case 'el':\n return [normalized.role, normalized.name, normalized.ordinal]\n .filter((part) => part !== undefined)\n .join(':')\n case 'platform':\n return normalized.platform\n case 'selector':\n return normalized.literal\n case 'error':\n return normalized.message\n }\n}\n\n/**\n * PROVISIONAL Phase 374 rendering. Phase 376's embedding bench may refine this function, while\n * each manifest preserves the exact publish-time bytes for deterministic index rebuilds.\n */\nexport function renderEmbeddingInput(input: {\n summary: string\n body: string\n anchors: readonly Anchor[]\n}): string {\n return [\n input.summary,\n '',\n input.body,\n '',\n ...input.anchors.map(\n (anchor) => `anchor: ${anchor.t}:${normalizedAnchorText(anchor)}`,\n ),\n ].join('\\n')\n}\n\n/** D-02: one replay-consumable canonical JSON document per pre-action screen state. */\nexport function screenStateSnapshotRelPath(stepIndex: number): string {\n if (!Number.isInteger(stepIndex) || stepIndex < 0) {\n throw new RangeError('screen-state stepIndex must be a non-negative integer')\n }\n return `evidence/screenstates/step-${stepIndex}.json`\n}\n","import { canonicalJson } from '../determinism/canonical-json'\nimport { sha256hex } from '../determinism/sha256'\nimport { asEvidenceToken, type EvidenceToken } from '../ids/record-id'\nimport type { Anchor } from '../identity/anchor'\nimport { normalizeAnchor } from '../identity/normalize-anchor'\n\n/**\n * Pitfall 11: Confirm without a fresh token is a no-op. Tokens are derived by code at\n * emit-projection time, never accepted from model output, and downstream idempotency is keyed by\n * (recordId, evidenceToken, curationJobId).\n */\nexport function deriveEvidenceToken(input: {\n attributingObservationId: string\n anchor: Anchor\n buildOrdinal: number\n}): EvidenceToken {\n return asEvidenceToken(\n sha256hex(\n canonicalJson([\n input.attributingObservationId,\n normalizeAnchor(input.anchor),\n input.buildOrdinal,\n ]),\n ),\n )\n}\n","import { z } from 'zod'\nimport { BriefLineSchema } from '../brief/guard-lossless-served-brief'\nimport { BundleKindSchema, BundleStatusSchema } from '../functions/knowledge'\nimport { RecordAnchorsSchema, RecordScopeSchema } from './record-frontmatter'\n\n/**\n * 2026-09-07, 417 D-01, ARCHITECTURE §2.2: the DATA the cli bridge carries from\n * knowledge into eval-local. Declared here because agent and knowledge-local\n * both name it and neither may name eval. One brief line, never a prompt or code edit.\n */\nexport const CandidateInjectionSchema = z.object({\n candidateId: z.string().min(1),\n kind: BundleKindSchema,\n product: z.string().min(1),\n scope: RecordScopeSchema,\n anchors: RecordAnchorsSchema,\n status: BundleStatusSchema,\n line: BriefLineSchema,\n renderedLine: z.string().min(1),\n provenance: z.object({\n runIds: z.array(z.string()),\n receiptDigests: z.array(z.string()),\n capturedAtOrdinals: z.array(z.number().int()),\n }).strict(),\n target: z.object({\n runId: z.string().min(1),\n stepIndex: z.number().int().nonnegative(),\n testId: z.string().optional(),\n sourceBuildOrdinal: z.number().int().optional(),\n }).strict().optional(),\n latestOrdinal: z.number().int().nonnegative(),\n}).strict()\n\nexport const KnowledgeCandidateInjectionResultSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('not-found'), recordId: z.string() }).strict(),\n z.object({ kind: z.literal('found'), injection: CandidateInjectionSchema }).strict(),\n])\n\nexport type CandidateInjection = z.infer<typeof CandidateInjectionSchema>\nexport type KnowledgeCandidateInjectionResult = z.infer<typeof KnowledgeCandidateInjectionResultSchema>\n","import { z } from 'zod'\n\nimport type { BundleKind, FactSubtype } from '../delta/envelope'\nimport type { ScopeKey, ScopeTier } from '../identity/scope-key'\nimport type { BundleStatus, DerivedTrustState } from '../knowledge/trust-fold'\nimport { GateLineSchema, GateReceiptSchema } from '../knowledge/gate-receipt'\nimport { PROMOTION_PATHS } from '../knowledge/promotion-path'\nimport { PROMOTION_GATE_HOLD_REASONS, type PromotionGateVerdict } from '../knowledge/promotion-gate'\n\nexport const KNOWLEDGE_BUNDLE_SUMMARY_SCHEMA_VERSION = 2\n\n/**\n * One committed knowledge bundle as `knowledge.bundles.list` projects it\n * (Phase 384, D-06/D-16).\n *\n * Deliberately a LISTING row, not a record view: it carries bundle identity, product\n * qualification, the derived trust state a reviewer triages on, and the one-line summary —\n * never the record body, evidence, relations, or screen states. 387's five review verbs\n * extend this stub with the deeper projections they need; nothing here is meant to be the\n * final shape of a record inspection.\n *\n * All trust-shaped fields are DERIVED (the v51 trust fold), never authored: a surface\n * renders them and never recomputes them.\n */\nexport interface KnowledgeBundleSummary {\n /** The record id, which is also the bundle directory name. */\n bundleId: string\n /** Product the bundle is filed under; bundle ids are unique only per product. */\n product: string\n /** Bundle directory path relative to the knowledge root. */\n dir: string\n kind: BundleKind\n subtype?: FactSubtype\n scope: ScopeKey\n status: BundleStatus\n /** Derived trust score in [0, 1]. */\n trust: number\n counters: DerivedTrustState['counters']\n /** Build ordinal at which the record opened. */\n openedAtOrdinal: number\n /** Present iff the record has been closed (withdrawn or superseded). */\n closedAtOrdinal?: number\n /** Latest surviving real confirmation; staleness is asOfBuild minus this value. */\n lastConfirmedOrdinal: number\n /** The record's one-line human summary. */\n summary: string\n /** True when the record was folded with an incomplete evidence set (discounted prior). */\n evidenceIncomplete: boolean\n}\n\nconst scopeTierValues = [\n 'global',\n 'product',\n 'suite',\n 'test',\n] as const satisfies readonly ScopeTier[]\n\nconst bundleKindValues = [\n 'fact',\n 'procedure',\n 'caution',\n 'unknown',\n 'policy',\n] as const satisfies readonly BundleKind[]\n\nconst factSubtypeValues = [\n 'selector',\n 'behavioral',\n 'navigational',\n 'measurement',\n 'content',\n] as const satisfies readonly FactSubtype[]\n\nconst bundleStatusValues = [\n 'active',\n 'candidate',\n 'superseded',\n 'deprecated',\n] as const satisfies readonly BundleStatus[]\n\nexport const BundleKindSchema = z.enum(bundleKindValues)\nexport const BundleStatusSchema = z.enum(bundleStatusValues)\n\nconst scopeKeySchema = z.object({\n tier: z.enum(scopeTierValues),\n key: z.string(),\n}).strict()\n\nconst trustCountersSchema = z.object({\n confirmed: z.number().int().nonnegative(),\n contradicted: z.number().int().nonnegative(),\n helpful: z.number().nonnegative(),\n harmful: z.number().nonnegative(),\n}).strict() satisfies z.ZodType<DerivedTrustState['counters']>\n\nexport const KnowledgeBundleSummarySchema = z.object({\n bundleId: z.string(),\n product: z.string(),\n dir: z.string(),\n kind: BundleKindSchema,\n subtype: z.enum(factSubtypeValues).optional(),\n scope: scopeKeySchema,\n status: BundleStatusSchema,\n trust: z.number().min(0).max(1),\n counters: trustCountersSchema,\n openedAtOrdinal: z.number().int().nonnegative(),\n closedAtOrdinal: z.number().int().nonnegative().optional(),\n lastConfirmedOrdinal: z.number().int().nonnegative(),\n summary: z.string(),\n evidenceIncomplete: z.boolean(),\n}).strict() satisfies z.ZodType<KnowledgeBundleSummary>\n\n// 431 D-04: the listing's whole result, named so the op and the MCP tool share one object.\nexport const KnowledgeBundlesListOutputSchema = z.array(KnowledgeBundleSummarySchema)\n\n/**\n * `knowledge.bundles.list` takes no arguments in the seed slice. A `.strict()` empty object\n * rather than `z.void()` so product/status/trust filters become additive fields later\n * without changing the op's input contract shape.\n */\nexport const KnowledgeBundlesListInputSchema = z.object({}).strict()\n\nexport type KnowledgeBundlesListInput = z.infer<typeof KnowledgeBundlesListInputSchema>\n\n// 416 D-18: history, standing evidence and the live verdict are one schema-owned answer.\nexport const KnowledgeGatesListInputSchema = z.object({ recordId: z.string().min(1) }).strict()\nexport const PromotionGateVerdictSchema = z.discriminatedUnion('verdict', [\n z.object({\n verdict: z.literal('promote'),\n promotionPath: z.enum(PROMOTION_PATHS),\n citedReceiptDigests: z.array(z.string().regex(/^[0-9a-f]{64}$/)),\n }).strict(),\n z.object({\n verdict: z.literal('hold'),\n reason: z.enum(PROMOTION_GATE_HOLD_REASONS),\n }).strict(),\n]) satisfies z.ZodType<PromotionGateVerdict>\nexport const KnowledgeGatesListResultSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('not-found'), recordId: z.string() }).strict(),\n z.object({\n kind: z.literal('found'),\n recordId: z.string(),\n product: z.string(),\n recordKind: z.enum(bundleKindValues),\n status: z.enum(bundleStatusValues),\n strongestPromotionPath: z.enum(PROMOTION_PATHS).optional(),\n lines: z.array(GateLineSchema),\n standing: z.array(GateReceiptSchema),\n live: PromotionGateVerdictSchema,\n posture: z.enum(['absent', 'resolved', 'unavailable']),\n }).strict(),\n])\nexport type KnowledgeGatesListInput = z.infer<typeof KnowledgeGatesListInputSchema>\nexport type KnowledgeGatesListResult = z.infer<typeof KnowledgeGatesListResultSchema>\n","import type { CurationAuthorship } from '../delta/envelope'\n\n/**\n * D-06 curator capability tier. `full` = clean LLM authorship by a v46-capable family;\n * `degraded` = LLM authorship that needed repair, a weak/unknown family, or absent\n * authorship facts (conservative); `floor` = the deterministic fallback path.\n */\nexport type CuratorTier = 'full' | 'degraded' | 'floor'\n\n/**\n * D-03 closed procedure-parameter type union. `secret` exists so the extraction\n * disposition can structurally reject unparameterized secrets (T-381-02).\n */\nexport type ProcedureParamType = 'string' | 'number' | 'boolean' | 'secret'\n\n/**\n * PROVISIONAL v46-capable family prefixes: the tool-calling + structured-output rows of the\n * model package's family table. The list lives HERE (not in the model package) because schema\n * must never import from model — dependency direction. Matched case-insensitively at token\n * boundaries against `model.family ?? model.id` (RESEARCH A1: authorship stamps only\n * `model.id` today, so id is the fallback match key).\n */\nconst CAPABLE_FAMILY_PREFIXES: readonly string[] = [\n 'claude',\n 'gpt-4o',\n 'gpt-4.1',\n 'gpt-5',\n 'o1',\n 'o3',\n 'o4',\n 'gemini-1.5',\n 'gemini-2.5',\n 'gemini-3',\n]\n\n/** A prefix only matches when the next character is a token boundary (or the end). */\nexport function matchesCapableFamily(key: string): boolean {\n const normalized = key.trim().toLowerCase()\n return CAPABLE_FAMILY_PREFIXES.some((prefix) => {\n if (!normalized.startsWith(prefix)) return false\n const next = normalized.charAt(prefix.length)\n return next === '' || next === '-' || next === '.' || next === '_' || next === ':' || next === '/'\n })\n}\n\n/**\n * The ONE pure, total D-06 tier derivation over raw authorship facts. Absent authorship and\n * every unknown shape resolve to `degraded` — never a throw, never a widened string.\n */\nexport function curatorTier(authorship: CurationAuthorship | undefined): CuratorTier {\n if (authorship === undefined) return 'degraded'\n if (authorship.path === 'deterministic-fallback') return 'floor'\n if (authorship.path === 'llm-repaired') return 'degraded'\n const key = authorship.model?.family ?? authorship.model?.id\n if (key === undefined) return 'degraded'\n return matchesCapableFamily(key) ? 'full' : 'degraded'\n}\n","import type { ModelIdentity } from '../handoff/model-call-profile'\nimport { matchesCapableFamily, type CuratorTier } from './curator-tier'\n\n/** Evidence supplied by the recovering decision's producer, never another actor. */\nexport type PlannerCapabilityEvidence =\n | { kind: 'model-identity'; modelIdentity: ModelIdentity }\n | { kind: 'deterministic' }\n | { kind: 'missing' }\n\nexport interface PlannerCapability {\n tier: CuratorTier\n evidence: PlannerCapabilityEvidence\n}\n\n/**\n * Provisional capability from the recovering planner's own recorded identity (420 D-03).\n * The caller must establish that identity belongs to this decision. `deterministicPath`\n * means authentic recorded execution evidence; absence, a verifier or curator identity,\n * and a configured provider are never grounds to infer that flag. Family matching is\n * exactly the curator law, while curator repair/authorship rules remain curator-only.\n */\nexport function plannerCapabilityTier(\n modelIdentity: ModelIdentity | undefined,\n deterministicPath?: boolean,\n): PlannerCapability {\n if (deterministicPath === true) return { tier: 'floor', evidence: { kind: 'deterministic' } }\n if (!modelIdentity?.modelId?.trim() || !modelIdentity.provider?.trim()) {\n return { tier: 'degraded', evidence: { kind: 'missing' } }\n }\n const { provider, modelId } = modelIdentity\n return {\n tier: matchesCapableFamily(modelId) ? 'full' : 'degraded',\n evidence: { kind: 'model-identity', modelIdentity: { provider, modelId } },\n }\n}\n","import type { ProcedureSourceBinding } from './procedure-binding-coercion'\nimport type { ProcedureBodyPayload, ProcedureParameterSpec } from './procedure-steps'\n\n/**\n * Source-tagged binding capability available to procedure matching and replay binding.\n *\n * D-08 firewall: values never cross this contract in any form. Variables and memory carry\n * capability entries — a NAME plus per-type capability bits computed loop-side by\n * procedureSourceBinding over the same coercion the binder uses — and secrets carry names\n * only (the secret store binds solely as a string template). Keeping the three source sets\n * distinct lets the shared matcher apply the same source rules as the loop binder without\n * exposing a secret, test-variable value, or working-memory value to the knowledge layer.\n */\nexport interface ProcedureBindingAvailability {\n variables: readonly ProcedureSourceBinding[]\n memory: readonly ProcedureSourceBinding[]\n secrets: readonly string[]\n}\n\n/** Empty availability for screenless and absent-caller paths. */\nexport const EMPTY_PROCEDURE_BINDING_AVAILABILITY = {\n variables: [],\n memory: [],\n secrets: [],\n} as const satisfies ProcedureBindingAvailability\n\nfunction bindingsByName(\n entries: readonly ProcedureSourceBinding[],\n): ReadonlyMap<string, ProcedureSourceBinding> {\n const byName = new Map<string, ProcedureSourceBinding>()\n for (const entry of entries) {\n if (!byName.has(entry.name)) byName.set(entry.name, entry)\n }\n return byName\n}\n\nfunction isParameterAvailable(\n parameter: ProcedureParameterSpec,\n sources: {\n variables: ReadonlyMap<string, ProcedureSourceBinding>\n memory: ReadonlyMap<string, ProcedureSourceBinding>\n secrets: ReadonlySet<string>\n },\n): boolean {\n if (parameter.type === 'secret') return sources.secrets.has(parameter.name)\n\n // WR-01's authoritative source law, completed to value-typed capability: the matrix is\n // source x declared type x VALUE capability. Secret parameters use secrets only; strings\n // use variables, memory, then secrets (entry presence means a non-nullish value exists,\n // which is exactly string-bindability); numbers and booleans use a variables or memory\n // entry whose capability bit is true, per-source OR. The bits are computed loop-side by\n // procedureSourceBinding over the SAME coercion the binder uses\n // (coerceProcedureBindingValue), so admitting a source here is exactly binder success.\n // Name matching is exact code-unit Map-key equality — no trim, case fold, or unicode\n // normalization. Any binder coercion change must update coerceProcedureBindingValue\n // (one function, both sides), never this helper alone.\n const variable = sources.variables.get(parameter.name)\n const memory = sources.memory.get(parameter.name)\n if (parameter.type === 'string') {\n return variable !== undefined || memory !== undefined || sources.secrets.has(parameter.name)\n }\n if (parameter.type === 'number') {\n return variable?.canBindNumber === true || memory?.canBindNumber === true\n }\n return variable?.canBindBoolean === true || memory?.canBindBoolean === true\n}\n\n/**\n * The ONE fillability contract consumed by both procedure matching and the replay binder.\n *\n * Only referenced `{ param }` slots participate. A reference without a unique committed\n * declaration fails closed. `required` does not alter this verdict: once a slot references a\n * parameter it needs a binding because schema version 1 has no typed default. A future typed\n * `default` field on ProcedureParameterSpec would exempt that parameter here.\n */\nexport function procedureParameterFillability(\n payload: ProcedureBodyPayload,\n availability: ProcedureBindingAvailability,\n): { fillable: boolean; unfillable: readonly string[] } {\n const declarations = new Map(payload.parameters.map((parameter) => [parameter.name, parameter]))\n const referenced = new Set<string>()\n\n for (const step of payload.steps) {\n for (const slot of Object.values(step.action.values)) {\n if (typeof slot === 'object' && slot !== null && 'param' in slot) {\n referenced.add(slot.param)\n }\n }\n }\n\n const sources = {\n variables: bindingsByName(availability.variables),\n memory: bindingsByName(availability.memory),\n secrets: new Set(availability.secrets),\n }\n const unfillable = [...referenced]\n .filter((name) => {\n const declaration = declarations.get(name)\n return declaration === undefined || !isParameterAvailable(declaration, sources)\n })\n .sort()\n\n return { fillable: unfillable.length === 0, unfillable }\n}\n","import type { ProcedureParamType } from './curator-tier'\n\n/**\n * The ONE typed coercion law shared by the loop binder and capability computation.\n *\n * The runner's bindProcedureParam produces bound values through this function, and\n * procedureSourceBinding derives the capability bits that cross the reader port from it —\n * one function evaluated on the same raw value, so an input the binder would reject can\n * never be classified fillable for that type. Any binder coercion change lands HERE.\n *\n * Laws (deliberately pinned): nullish raw is absence for every type; 'string' is String(raw);\n * 'number' is the mechanical Number(raw) admitting only finite results ('' binds 0, no bespoke\n * emptiness carve-out); 'boolean' admits only true/false and the exact lowercase 'true'/'false'\n * strings. Secret parameters never coerce — they bind as secret-store templates only.\n */\nexport function coerceProcedureBindingValue(\n type: Exclude<ProcedureParamType, 'secret'>,\n raw: unknown,\n): string | number | boolean | undefined {\n if (raw === null || raw === undefined) return undefined\n if (type === 'string') return String(raw)\n if (type === 'number') {\n const number = Number(raw)\n return Number.isFinite(number) ? number : undefined\n }\n if (raw === true || raw === false) return raw\n if (raw === 'true') return true\n if (raw === 'false') return false\n return undefined\n}\n\n/**\n * One binding source entry on the availability contract: a NAME plus per-type capability\n * bits — never a value.\n *\n * D-08 firewall: raw values enter procedureSourceBinding as a pure function LOOP-SIDE; only\n * the name and the derived capability booleans exist on this contract. Presence of an entry\n * means a non-nullish value exists, which is exactly string-bindability, so no canBindString\n * member is needed.\n */\nexport interface ProcedureSourceBinding {\n readonly name: string\n readonly canBindNumber: boolean\n readonly canBindBoolean: boolean\n}\n\n/**\n * The sanitizer that keeps values loop-side: raw value in, name + capability bits out.\n * Nullish raw values are absence in every source — the name is simply not listed.\n */\nexport function procedureSourceBinding(\n name: string,\n raw: unknown,\n): ProcedureSourceBinding | undefined {\n if (raw === null || raw === undefined) return undefined\n return {\n name,\n canBindNumber: coerceProcedureBindingValue('number', raw) !== undefined,\n canBindBoolean: coerceProcedureBindingValue('boolean', raw) !== undefined,\n }\n}\n","// Pitfall 6: the ONE shared non-replayable action-class list. The runner's cache write guard,\n// the extraction disposition (381-03), and procedure replay (381-07) all consume THIS list —\n// it must never fork. Mirrors the runner's current exclusion lists member-for-member\n// (loop/index.ts COORDINATE_KEYS / COORDINATE_ACTION_TYPES + the setVariable/assertAI/extractAI\n// cache no-op guards); consumers swap their local copies for these in later plans.\n\n/**\n * Action types that are never replayable: `setVariable` (env provenance), `assertAI`/`extractAI`\n * (AI-judgment plans are never persisted, D-08), and `tapCoordinate` (inherently\n * coordinate-driven even after raw coordinates are sanitized out).\n */\nexport const NON_REPLAYABLE_ACTION_TYPES: readonly string[] = [\n 'setVariable',\n 'assertAI',\n 'extractAI',\n 'tapCoordinate',\n]\n\n/**\n * Raw-coordinate keys whose presence makes an action shape non-replayable (Pitfall 5b): a\n * coordinate binding cannot be re-grounded against a fresh observation.\n */\nexport const COORDINATE_ACTION_KEYS: readonly string[] = [\n 'x',\n 'y',\n 'coordinates',\n 'coords',\n 'startX',\n 'startY',\n 'endX',\n 'endY',\n]\n\n/**\n * Pure shape predicate: an action is replayable iff its type is outside\n * {@link NON_REPLAYABLE_ACTION_TYPES} AND none of its keys is a raw-coordinate key.\n */\nexport function isReplayableActionShape(type: string, keys: Iterable<string>): boolean {\n if (NON_REPLAYABLE_ACTION_TYPES.includes(type)) return false\n for (const key of keys) {\n if (COORDINATE_ACTION_KEYS.includes(key)) return false\n }\n return true\n}\n","/**\n * WHO is acting, as opposed to WHERE from (391 D-06). Closed, and spelled once (388 C13).\n *\n * `human` is a person taking an action directly; `agent` is a model-driven call, whether it\n * arrives over chat, MCP, or a background job the daemon started. The axis is deliberately NOT\n * {@link FunctionCaller.surface}: `cli` is a surface a human uses interactively AND the process a\n * scheduled job runs in, so a surface name cannot answer \"did a person decide this\". It is also\n * distinct from schema's TEST `Surface` (`web | mobile | android | ios | common`), which is about\n * what is under test rather than who is asking.\n *\n * There is no `unknown` member, and the absence is the fail-closed half of the design: a third\n * value would need a rule, every safe rule for it is \"treat it as agent\", and a vocabulary with a\n * member that always means another member is a vocabulary with two spellings for one thing.\n */\nexport const FUNCTION_CALLER_ORIGINS = ['human', 'agent'] as const\n\nexport type FunctionCallerOrigin = (typeof FUNCTION_CALLER_ORIGINS)[number]\n\n/**\n * The caller record every function invocation carries (Phase 384, FUNC-03).\n *\n * 2026-10-01 (432-20, D-10/D-12): NO FIELD HERE IS A PERMISSION INPUT. Every door can call every\n * operation, so `invokeFunction` and the registry read nothing on this record. `surface` and\n * `origin` survive for the receipts and presentation that already consume them, and no new label\n * is written. 2026-10-02 (432-39, D-02/D-10/D-12): the retired `grantedScopes`, `safeMode`,\n * `credential` and `sessionId` members are deleted, with the scope and trust-credential types they\n * named. An old caller record that still carries one is not migrated and nothing reads it. A branch\n * on `surface` remains an anti-pattern — it re-creates the per-surface private powers the function\n * layer abolished.\n */\nexport interface FunctionCaller {\n /**\n * Coded originating surface, e.g. 'cli' or 'mcp'. Attribution and diagnostics only;\n * never a permission input.\n */\n surface: string\n /**\n * WHO this call is on behalf of, MINTED by the composition root (391 D-06). The CLI mints\n * `human` because a person typed the command, the daemon and MCP mint `agent` because nobody\n * did.\n *\n * 2026-10-01 (432-20, D-10/D-12): presentation and receipts only. No dispatch check reads it\n * (the human-origin check is deleted), so it grants and withholds nothing. It stays required\n * because the existing receipt and planner consumers read it, and an optional field would need a\n * default nobody decides.\n */\n origin: FunctionCallerOrigin\n}\n\n","import { z } from 'zod'\n\nexport const MASKED_RESOLVED_CONFIG_SCHEMA_VERSION = 2\n\n/**\n * Which layer supplied the winning value for a resolved configuration key.\n *\n * A clean machine vocabulary rather than the CLI's existing human debug labels\n * (`global config` / `test yaml` / `cli flag`): those are display strings with spaces,\n * and this union crosses surface boundaries and projects into JSON Schema.\n */\nexport type ConfigValueSource =\n | 'default'\n | 'config-file'\n | 'env'\n | 'cli-flag'\n | 'test-file'\n\n/**\n * One resolved configuration key/value pair, rendered and passed through the declared-secret\n * mask while it is constructed (Phase 384, D-06/D-16; 441-20 and 441-40, D-29).\n *\n * The mask is applied at construction, so a surface holding a `MaskedResolvedConfig` never\n * holds a declared value to redact downstream: each one already reads as its\n * `[secret:<name>]` marker. Nothing else hides a value: no path, key name, placeholder or URL\n * reduction.\n *\n * `value` is always a rendered string (numbers, booleans, and nested values are stringified\n * at construction) so the mask applies to every value alike.\n */\nexport interface MaskedConfigEntry {\n /** Dot-path key into the resolved configuration tree. */\n key: string\n /** The rendered value through the declared mask. */\n value: string\n source: ConfigValueSource\n /** True when the declared mask changed the rendered value. */\n masked: boolean\n}\n\n/**\n * The `config.get` result: the masked, provenance-annotated resolved configuration read\n * that seeds 395's config class (Phase 384, D-06/D-16).\n *\n * A flat entry list rather than a nested tree — provenance is per-leaf, and a flat list is\n * the shape both a table renderer and a JSON-Schema projection want.\n */\nexport interface MaskedResolvedConfig {\n schemaVersion: typeof MASKED_RESOLVED_CONFIG_SCHEMA_VERSION\n /** The configuration file the read resolved against, as the caller addressed it. */\n configPath: string\n entries: MaskedConfigEntry[]\n}\n\nconst configValueSourceValues = [\n 'default',\n 'config-file',\n 'env',\n 'cli-flag',\n 'test-file',\n] as const satisfies readonly ConfigValueSource[]\n\nexport const MaskedConfigEntrySchema = z.object({\n key: z.string(),\n value: z.string(),\n source: z.enum(configValueSourceValues),\n masked: z.boolean(),\n}).strict() satisfies z.ZodType<MaskedConfigEntry>\n\nexport const MaskedResolvedConfigSchema = z.object({\n schemaVersion: z.literal(MASKED_RESOLVED_CONFIG_SCHEMA_VERSION),\n configPath: z.string(),\n entries: z.array(MaskedConfigEntrySchema),\n}).strict() satisfies z.ZodType<MaskedResolvedConfig>\n\n/**\n * `config.get` takes no arguments in the seed slice. A `.strict()` empty object rather than\n * `z.void()` so a key-path filter becomes an additive field later without changing the op's\n * input contract shape.\n */\nexport const ConfigGetInputSchema = z.object({}).strict()\n\nexport type ConfigGetInput = z.infer<typeof ConfigGetInputSchema>\n","// The `authoring.draft.verify` op contract (393, D-01).\n//\n// D-01 sketches the verb as `authoring.verify_draft`; that spelling is unrepresentable — the\n// parity taxonomy regex forbids underscores and the chat tool-name mapping refuses one (393-07).\n// The schema symbols keep the sketch's camel-case spelling; the dispatchable id does not.\n//\n// The planner binds ALL registry ops 1:1 (392 D-07), so this op is chat-reachable the moment\n// it registers — its input is crossing a trust boundary from an arbitrary caller, not being\n// handed over between two halves of the same program. `.strict()` plus a non-empty path is\n// therefore the refusal surface, not a formality. Path-boundary enforcement (is this draft\n// inside the workspace at all?) belongs at the op invoke where the resolved config exists;\n// this schema's job is to make sure the invoke is never handed a shape it must guess about.\n\nimport { z } from 'zod'\n\nimport { AuthoringFunnelSchema } from '../authoring/funnel'\nimport {\n DraftReceiptSchema,\n DraftRefSchema,\n TestFileWriteSchema,\n WrittenTestReceiptSchema,\n} from '../authoring/draft-receipt'\nimport { FanOutReportSchema } from '../authoring/fan-out'\nimport { PatchOpSchema } from '../authoring/patch-ops'\nimport { RunEvidenceRefSchema } from '../authoring/proposal-arms'\nimport type { ScopeTier } from '../identity/scope-key'\n\nexport const AuthoringVerifyDraftInputSchema = z.object({\n /** Path to the draft test file to evaluate. Resolved and boundary-checked at the invoke. */\n draftPath: z.string().min(1),\n /**\n * Draft mode: run the stability gate ONCE instead of the pinned N.\n *\n * D-18 makes this consequential rather than a speed knob — a draft-mode evaluation's\n * disposition is forced to `unverified` unconditionally, so nothing evaluated this way can\n * be auto-kept no matter how its four booleans read. Only the literal marker is accepted,\n * matching the `gateRun` / `excludedFromOutcomes` carrier idiom: `false` is a refusal, not a\n * synonym for absence, so a caller cannot half-express the intent.\n */\n draftMode: z.literal(true).optional(),\n /**\n * The invoking session, carried to the receipt this evaluation mints.\n *\n * Optional and never defaulted, under {@link DraftReceiptSchema}'s own absence-is-exclusion rule\n * — see the field's doc there for why a defaulted ref is the one shape that misattributes.\n */\n sessionRef: z.string().min(1).optional(),\n /**\n * The suite file this draft proposes to JOIN — the stability read's target (394-19, D-14).\n *\n * ABSENT MEANS THE DRAFT'S OWN FILE, which is the right answer for a standalone verify: a\n * committed suite file IS its own target. It is a CHOSEN contract rather than a derivation\n * because on the loop path the draft sits on a one-test-per-file shelf, so a target derived from\n * `draftPath` can never have neighbours and D-14's `neighbours-flaky` arm was unreachable from\n * `authoring.draft.write` for that reason alone. Only the caller knows which suite a draft would\n * join; the loop computes it through the same `authoredSuiteTargetPath` its accept arm uses.\n */\n targetSuitePath: z.string().min(1).optional(),\n}).strict()\n\nexport type AuthoringVerifyDraftInput = z.infer<typeof AuthoringVerifyDraftInputSchema>\n\n/**\n * The op returns the receipt it persisted — the same bytes, not a summary of them (D-19), so a\n * caller never has to re-read the store to learn what was just decided.\n */\nexport const AuthoringVerifyDraftOutputSchema = DraftReceiptSchema\n\nexport type AuthoringVerifyDraftOutput = z.infer<typeof AuthoringVerifyDraftOutputSchema>\n\n// ---- `authoring.draft.write`: the six-stage loop's one public entry (394, D-01 · WTST-01) ------\n\n/**\n * The scope the brief is read at and the draft is authored for.\n *\n * A module-private schema on the `functions/runs.ts` and `functions/knowledge.ts` idiom — each\n * file that has to validate a scope keeps its own, because there is no exported `ScopeKeySchema`\n * in this package and minting one now would publish a fourth spelling of a two-field object three\n * files already validate identically.\n */\nconst scopeKeySchema = z.object({\n tier: z.enum(['global', 'product', 'suite', 'test'] satisfies readonly ScopeTier[]),\n key: z.string().min(1),\n}).strict()\n\n/**\n * How one loop invocation ended — the CLOSED vocabulary, declared whole in 394-02 (D-01).\n *\n * All four members exist from the tracer onward and only `drafted` is reachable in it. That is\n * deliberate rather than premature: the loop is a six-stage pipeline whose stages land across\n * plans 04, 05 and 06, and a vocabulary that grew a member per plan would make each of those a\n * change to the SHAPE every consumer branches on — the op's output contract, 396's MCP\n * projection, 397's parity walk — instead of a new branch behind a discriminant they already\n * read. Declaring the whole set now costs one enum and buys three plans that add a case.\n *\n * `drafted` the draft was compiled, staged and verified; the receipt carries the verdict.\n * `refused` stage 2 found the intent already covered and ended the invocation (D-04, plan 04).\n * `repaired` stage 5 routed to bounded repair and a later iteration passed (D-08/D-10, plan 05).\n * `stopped` stage 5 routed to the stop arm: the gate run's verdict rides this result's `stop`\n * payload and the correctly-failing draft stays on the shelf with its receipt\n * (411 D-01/D-05).\n *\n * 2026-09-02 (Phase 411): the proposal arm for a correctly-failing draft left with the Issue-slot\n * cleanup.\n */\nexport const AUTHORING_LOOP_OUTCOMES = [\n 'drafted',\n 'refused',\n 'repaired',\n 'stopped',\n] as const\n\nexport type AuthoringLoopOutcomeKind = (typeof AUTHORING_LOOP_OUTCOMES)[number]\n\n/**\n * The two continuations a dedup refusal offers (394 D-04) — CLOSED, and minted here.\n *\n * It lives in `schema` rather than beside the lane that produces it because the op's output\n * validates it and chat renders it, and 384 D-16 puts a DTO's vocabulary where every surface\n * reading it can share one spelling. A second `as const` in `agent` would be the drift that law\n * exists to prevent, and would make \"which continuation did an author take\" — a question plan\n * 07's funnel asks — answerable two ways.\n *\n * TWO MEMBERS, and neither covers the other. An author whose intent really is the existing test\n * takes `extend-that-test`; an author whose intent is a DIFFERENT assertion about the same flow\n * has nothing to extend and takes `name-the-differing-assertion`, which is the honest question to\n * put to someone the screen may have over-flagged. Offering only the first would make an\n * over-flagging screen — the ratified safe direction — unappealable.\n */\nexport const AUTHORING_DEDUP_CONTINUATIONS = [\n 'extend-that-test',\n 'name-the-differing-assertion',\n] as const\n\nexport type AuthoringDedupContinuation = (typeof AUTHORING_DEDUP_CONTINUATIONS)[number]\n\n/**\n * What a stage-2 refusal NAMES (394 D-04).\n *\n * THE OUTPUT'S ONE PAYLOAD ARM, AND THE EXCEPTION IS PRINCIPLED. The output contract below states\n * that it carries no payload per outcome, because a draft's bytes are written to its test file and\n * named by `written`, and a second copy here would be a second place to read one artifact. A dedup\n * refusal has NO such home: nothing was authored, so there is no draft, no\n * receipt, no gate-run and no envelope, and D-04 makes the refusal a typed op RESULT that ends the\n * invocation and is rendered by chat. Omitting the payload would not avoid a second read path, it\n * would remove the only one — leaving a caller told `refused` with no way to learn what it\n * matched, which is precisely the refuse-and-LINK requirement.\n *\n * `matchedRef` is the reference a caller hands to `entities.resolve`, spelled\n * `<filePath>::<testName>`. It is deliberately NOT a `TST-###` short-ID: a short-ID exists only\n * once something has sighted the entity, sighting is what mints the permanent address, and no\n * `TST` sighting source is wired on any host in this build — so printing one would publish an\n * address that resolves to nothing (ENTY-01's never-guess law).\n *\n * `threshold` rides beside `score` because a refusal reporting 0.52 without saying what it was\n * compared against cannot tell an author whether their intent was borderline or identical.\n */\nexport const AuthoringDedupRefusalSchema = z.object({\n /** Workspace-relative path of the suite test the intent duplicates. */\n filePath: z.string().min(1),\n /** That test's display name — identity half two, never `testId`. */\n testName: z.string().min(1),\n /** The `entities.resolve` reference for it, in one spelling. */\n matchedRef: z.string().min(1),\n /** Token-set similarity, in [0,1]. */\n score: z.number().min(0).max(1),\n /** The pinned value it met or exceeded. */\n threshold: z.number().min(0).max(1),\n /** How many normalized tokens the intent and that test share — the score's numerator. */\n sharedTokens: z.number().int().min(0),\n /** How many suite tests were screened. The universe is the suite, not a covered subset. */\n comparedTests: z.number().int().min(0),\n /** Both continuations, always — see the vocabulary's own doc block. */\n continuations: z.array(z.enum(AUTHORING_DEDUP_CONTINUATIONS)).length(2),\n}).strict()\n\nexport type AuthoringDedupRefusal = z.infer<typeof AuthoringDedupRefusalSchema>\n\nexport const AUTHORING_STATED_VALUE_STAGES = ['compile', 'keep'] as const\n\nexport type AuthoringStatedValueStage = (typeof AUTHORING_STATED_VALUE_STAGES)[number]\n\n// 2026-10-12 (440-02, D-09): names the stage and the request's own missing values, never draft or\n// model text.\nexport const AuthoringStatedValueRefusalSchema = z.object({\n stage: z.enum(AUTHORING_STATED_VALUE_STAGES),\n missingValues: z.array(z.string().min(1)).min(1),\n}).strict()\n\nexport type AuthoringStatedValueRefusal = z.infer<typeof AuthoringStatedValueRefusalSchema>\n\n/**\n * The three classes the stop arm may carry — one definitive, two ambiguous (411 D-06).\n *\n * The schema spelling of the router's own `RouterStopSignalClass`. Two files, one vocabulary:\n * `loop.test-d.ts` pins the two equal by type so neither can drift from the other.\n */\nexport const AUTHORING_STOP_SIGNAL_CLASSES = [\n 'clean-definitive-assertion-fail',\n 'mixed-evidence',\n 'indefinitive-failure',\n] as const\n\nexport type AuthoringStopSignalClass = (typeof AUTHORING_STOP_SIGNAL_CLASSES)[number]\n\n/** How a bounded repair gave up, in the repair lane's own two words (411 D-08). */\nexport const AUTHORING_REPAIR_ABANDONMENTS = ['exhausted', 'prefix-regressed'] as const\n\nexport type AuthoringRepairAbandonment = (typeof AUTHORING_REPAIR_ABANDONMENTS)[number]\n\n/**\n * Where the failure was observed, in the run's own words.\n *\n * No `runId` here: it rides at the payload's top level (411 D-06) so a NULL failure point still\n * names the run stage 5 routed on.\n */\nexport const AuthoringStopFailurePointSchema = z.object({\n stepIndex: z.number().int().nonnegative(),\n /** Pre-interpolation step text — post-interpolation text can carry resolved secrets. */\n stepText: z.string(),\n /** The verifier's own reasoning for saying no. */\n reasoning: z.string(),\n /**\n * Which path produced the verdict. A free string rather than an enum: the run's own\n * `VerdictSource` vocabulary is owned by the handoff schema and grows there, and a second closed\n * copy here would refuse to report a real stop because the verdict came through a path this file\n * had not heard of.\n */\n verdictSource: z.string().min(1).optional(),\n}).strict()\n\nexport type AuthoringStopFailurePoint = z.infer<typeof AuthoringStopFailurePointSchema>\n\n/**\n * What a `stopped` invocation REPORTS — the gate run's verdict and the router's reading (411 D-05).\n *\n * NOTHING A MODEL WROTE IS ON IT. The payload is projected from the route the router derived and\n * from the receipt's own last gate run, both typed facts; there is no prose field for model output\n * to arrive through, which is the whole of \"the model never makes this decision\" expressed as a\n * shape rather than as an ordering. `.strict()` is the refusal surface for anything else.\n *\n * `repairAbandonment` AND `repairIterations` ARE PRESENT EXACTLY TOGETHER (411 D-08, 394-21/WR-09).\n * The loop carries the kind and the spend as ONE parameter and the op spreads both or neither, so\n * the two optionals here can never disagree — a kind with no spend, or a spend on a stop repair\n * never touched, are not states the loop can be in. They are two optionals rather than one nested\n * object for the reason the retired arm's were: a strict object with no effects, so the MCP\n * projection and the golden digest see a plain shape.\n */\nexport const AuthoringStopSchema = z.object({\n /** The LAST gate run on the receipt — the run stage 5 routed on. */\n runId: z.string().min(1),\n /** The draft's OWN member outcome, as the receipt's `GateRunRecord` spells it (411 D-06/D-17). */\n memberOutcome: z.string().min(1),\n /** The router's reading: which of the three stop classes this evidence was. */\n signalClass: z.enum(AUTHORING_STOP_SIGNAL_CLASSES),\n /** Null when the member failed at the member level with no step verdict to point at. */\n failurePoint: AuthoringStopFailurePointSchema.nullable(),\n /** Coordinates into the run's own durable records. Never a payload. */\n evidenceRefs: z.array(RunEvidenceRefSchema).readonly(),\n /** Present exactly with `repairIterations` — how a bounded repair gave up before this stop. */\n repairAbandonment: z.enum(AUTHORING_REPAIR_ABANDONMENTS).optional(),\n /**\n * Present exactly with `repairAbandonment` — `RepairOutcome.iterations`, INCLUDING iterations a\n * fence refused, which started nothing and are therefore not derivable from `fanOut`'s run ids.\n */\n repairIterations: z.number().int().min(0).optional(),\n}).strict()\n\nexport type AuthoringStop = z.infer<typeof AuthoringStopSchema>\n\n/**\n * What a caller hands the loop.\n *\n * `.strict()` and a non-empty intent for the reason the verify input states above, and here the\n * argument is sharper: `intent` is free text from an arbitrary caller that reaches an LLM and then\n * becomes bytes on this workspace's disk (T-394-06). The refusal surface a schema can hold is the\n * shape and the emptiness; what the model produces is validated again, by the parser, before a\n * single byte is written.\n */\nexport const AuthoringDraftWriteInputSchema = z.object({\n /** Plain-English description of the test to author. */\n intent: z.string().min(1),\n /**\n * Which scope the authoring brief is read at, and the draft is authored for.\n *\n * OPTIONAL, and absent resolves from the host's configured targets and committed tests — the\n * `RunsStartInputSchema.scope` law one op over, applied here for the reason that op adopted it:\n * a model cannot know this project's product keys, and a required field it can only guess at is\n * a field it refuses the whole call over (WINDOWS 110). A supplied scope always wins; the host\n * derives only on absence, and refuses by name rather than guessing when the answer is not\n * unique.\n *\n * THE `.describe()` BELOW IS THE HUMAN-FACING HALF, AND IT IS WHY IT IS A `.describe()` RATHER\n * THAN THIS DOC BLOCK (400-04, D-19). A JSDoc comment documents this field for whoever opens\n * this file; it reaches no reader of the product. The capability catalog is PRODUCED from the\n * declarations — `params` is the JSON-Schema projection of this very object — so a description\n * attached HERE is the single edit that documents `scope` on the surfaces that project `params`,\n * and a paragraph anywhere else is a paragraph the product never says.\n *\n * WHICH SURFACES THOSE ARE WAS MEASURED, NOT ASSUMED (400-12, WINDOWS #189). An earlier version\n * of this block claimed `/help`, `explain` and the chat type-ahead were \"all projections of that\n * ONE committed artifact\". They are not, and the claim was measured FALSE: `/help` and the\n * type-ahead render `row.description` (the op summary) rather than `params`, and `explain`\n * deliberately withholds params from its prompt (`explain-port.ts:17`, D-10-sanctioned charter\n * design). They project a different FIELD of the same artifact. The surfaces this `.describe()`\n * actually reaches are the committed capability catalog row, `init --agent` and MCP\n * `tools/list`; a person finds the op itself through `agent-qa fn --list` or the committed\n * catalog. 2026-09-28 (430 D-02): the dashboard's served catalog, the fourth surface in the D-19\n * letter RATIFIED on 2026-08-22, was deleted with its server door.\n * `packages/cli/src/__tests__/scope-doc-surfaces.test.ts` pins the committed leg and the served\n * leg's absence.\n * Projecting `params` into `/help` and the type-ahead stays open as a Rule-4 design question\n * (WINDOWS #189); it needs resolver-table surgery, not a wider sentence here.\n *\n * The 399 rehearsal measured what its absence costs: `/fn authoring.draft.write` ROUTES, meets\n * the confirm interactively, and then fails on `AuthoringScopeUnresolvableError` naming targets\n * the caller was never told they had to choose between — a field that is undocumented on every\n * surface a person reads is a field they can only learn about by being refused over it.\n *\n * IT DOES NOT RESTATE THE MODEL-FACING SENTENCE AND MUST NOT CONTRADICT IT.\n * `planner-tools.ts`'s `HOST_DERIVES_SCOPE` already tells the PLANNER who fills this field and\n * that the host never guesses; that sentence is load-bearing (it carries the 394-35 dist-gate\n * sentinel) and is untouched. This text says the same things in the same direction and adds the\n * half the planner has no use for: what a `/fn` caller typing JSON by hand has to pass.\n */\n scope: scopeKeySchema.optional().describe(\n 'Which product this test is authored for — the target key, e.g. `automation-exercise`. '\n + \"In chat the planner fills this from the person's own words: a request that names the page, \"\n + 'product or site it is for supplies the scope, and nothing needs to be typed. Calling '\n + '`/fn authoring.draft.write` directly, pass it explicitly — `{\"scope\":{\"tier\":\"product\",'\n + '\"key\":\"<target>\"}}` — whenever this project scaffolds more than one target. When it is '\n + 'omitted the host derives it ONLY where the project has exactly one candidate product; '\n + 'otherwise the call returns a typed refusal that names every candidate so you can choose '\n + 'one. It never guesses at a product, because authoring against a guessed product writes a '\n + 'test for the wrong application.',\n ),\n /**\n * Draft mode: the stability gate runs ONCE instead of the pinned N.\n *\n * Handed straight through to `authoring.draft.verify`, marker idiom and consequences intact —\n * a draft-mode evaluation's disposition is forced to `unverified`, so nothing authored this way\n * can be auto-kept. `z.literal(true)` for the same reason it is there: `false` is a refusal, not\n * a second spelling of absence.\n */\n draftMode: z.literal(true).optional(),\n /**\n * The invoking session, threaded to every receipt this invocation mints — the loop's own and the\n * one a repaired candidate earns.\n *\n * Optional and never defaulted, under {@link DraftReceiptSchema}'s absence-is-exclusion rule; a\n * session-owning surface stamps it at the invoke and a CLI supplies nothing.\n */\n sessionRef: z.string().min(1).optional(),\n}).strict()\n\nexport type AuthoringDraftWriteInput = z.infer<typeof AuthoringDraftWriteInputSchema>\n\n/**\n * What one loop invocation answers.\n *\n * The receipt is the WHOLE receipt the evaluator minted and persisted, not a summary of it — the\n * verify op's own rule, inherited because this op reaches that op rather than re-deciding\n * anything. `draftRef` is carried beside it even though the receipt already holds one, because it\n * is the answer to a different question: which draft this call produced, addressable without\n * knowing that a receipt is a thing that has a ref inside it.\n *\n * There is no payload arm per outcome. Since 432 (D-06) the final draft is written to its test file\n * in the call, and `written` is that write's file record (which file, or why none), not its bytes;\n * a stop's verdict rides THIS result, because nothing is written for it (411 D-05) — see `stop`\n * below.\n *\n * `fanOut` IS THE ONE RECORDED EXCEPTION (394-14 · WTST-08): the preview-versus-spent disclosure.\n * WTST-08's owner decision was preview plus honest reporting with NO enforced budget, so the number\n * previewed and the number actually spent are both reported, and `exceedsPreview` says when the\n * second outran the first. It is counts, run REFERENCES and one boolean — no draft body, no receipt\n * payload and no step evidence. (2026-10-03: the dispatch confirm that showed the preview and the\n * proposal inbox this paragraph used to contrast it with are deleted in 432.)\n *\n * BOTH ARE OPTIONAL, AND `outcome` SAYS WHICH TO EXPECT. A `drafted`, `repaired` or `stopped`\n * invocation carries both; a `refused` one ends at\n * stage 2 with no draft compiled and therefore no receipt to mint (D-04, plan 04). Requiring them\n * would have made plan 04's arrival a WIDENING of this op's output contract — the shape change the\n * whole-vocabulary-now discipline exists to avoid — and padding a refusal with an empty receipt\n * would be worse: a receipt is a durable record of gates that ran, and a synthetic one would be a\n * verdict about a draft that was never authored.\n */\nexport const AuthoringDraftWriteOutputSchema = z.object({\n draftRef: DraftRefSchema.optional(),\n receipt: DraftReceiptSchema.optional(),\n outcome: z.enum(AUTHORING_LOOP_OUTCOMES),\n /**\n * Present exactly on a stage-2 `refused` invocation. See {@link AuthoringDedupRefusalSchema}\n * for why this one payload arm exists where the paragraph above rules the others out.\n */\n refusal: AuthoringDedupRefusalSchema.optional(),\n statedValueRefusal: AuthoringStatedValueRefusalSchema.optional(),\n /**\n * Present exactly on a `stopped` invocation (411 D-05): the gate run's verdict, the router's\n * reading and the evidence coordinates — never a proposal of any class. Same rule as `refusal`:\n * `outcome` says which to expect.\n */\n stop: AuthoringStopSchema.optional(),\n /**\n * What this invocation previewed, beside what it actually spent.\n *\n * REQUIRED ON EVERY ARM, unlike `draftRef` and `receipt`. Those two are absent because a stage-2\n * refusal genuinely has neither. Cost is different in kind: \"this invocation ran nothing\" is a\n * true and useful answer, and `buildFanOutReport({ previewed: NO_RUNS_FAN_OUT_BOUND, runs: [] })`\n * is what the loop already answers with on that arm. An OPTIONAL field would make absent and\n * zero indistinguishable at a caller — \"nobody counted\" and \"nothing ran\" read the same — which\n * is the one ambiguity a disclosure may not have.\n */\n fanOut: FanOutReportSchema,\n /**\n * The final draft's written-test receipt (432 D-06): which file was written, or why none was,\n * with the disposition and the four gate booleans. Present exactly on `drafted` and `repaired`;\n * a `rejected` final draft is reported here as not written. Its disposition is the receipt's.\n */\n written: WrittenTestReceiptSchema.optional(),\n}).strict().superRefine((output, ctx) => {\n // 2026-10-03 (quick 261003-cpv, 432 review IN-21): the two rules above, enforced. Producer-parsed\n // only (the op's output validation and the MCP projection); no stored record is read through it.\n const writes = output.outcome === 'drafted' || output.outcome === 'repaired'\n if (writes !== (output.written !== undefined)) {\n ctx.addIssue({\n code: 'custom',\n path: ['written'],\n message: 'the written-test receipt is present exactly on a drafted or repaired invocation',\n })\n }\n if (output.written !== undefined && output.receipt !== undefined\n && output.written.disposition !== output.receipt.disposition) {\n ctx.addIssue({\n code: 'custom',\n path: ['written', 'disposition'],\n message: 'the written-test receipt carries the disposition of the receipt beside it',\n })\n }\n if (output.statedValueRefusal !== undefined && output.outcome !== 'refused') {\n ctx.addIssue({\n code: 'custom',\n path: ['statedValueRefusal'],\n message: 'the stated-value refusal is present only on a refused invocation',\n })\n }\n if (output.statedValueRefusal !== undefined && output.refusal !== undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['statedValueRefusal'],\n message: 'the stated-value refusal never rides beside the duplicate refusal',\n })\n }\n if (output.outcome === 'refused' && output.statedValueRefusal === undefined\n && output.refusal === undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['refusal'],\n message: 'a refused invocation carries the duplicate refusal or the stated-value refusal',\n })\n }\n})\n\nexport type AuthoringDraftWriteOutput = z.infer<typeof AuthoringDraftWriteOutputSchema>\n\n// ---- `authoring.funnel.get`: the honesty funnel's one read op (394, D-12/D-13 · WTST-05) -------\n\n/**\n * The window a funnel is computed over — a CLOSED, DISCRIMINATED three-arm scope.\n *\n * IT IS A SCOPE, NOT A FILTER, and the distinction is why it exists where `quarantine.list`\n * deliberately has none. That op's header refuses a filter because \"a filter here would make the\n * verb's answer depend on how it was asked\" — a reader concern over rows already in hand. This\n * parameter does something different in kind: it selects WHICH INVOCATIONS the projection is over,\n * which is the projection's denominator rather than a predicate applied after it. A funnel with no\n * scope would be forced to answer all-time, and \"how is this session doing\" — D-12's stated\n * default and the question WTST-05 asks — would be unanswerable from any surface.\n *\n * THE SESSION ARM CARRIES THE REF, because the op cannot know it. `FunctionSpec.invoke` receives\n * `(input, deps)` and nothing else — no caller — and `FunctionDeps` holds no session. D-12's\n * \"default scope = current session\" is therefore a SURFACE default, honoured where the session is\n * actually known, never a schema default that would have to guess. A defaulted session ref is the\n * one shape that could quietly report a different session's drafts as this one's.\n *\n * CHAT IS THE SURFACE THAT CONSTRUCTS ONE (394-19). It stamps its own session onto the two\n * `sessionRef`-carrying authoring ops, so receipts are ATTRIBUTED; and at the same invoke it\n * supplies THIS window — the session arm by default when a planner step carries none, and the\n * session arm's REF overwritten when the model emitted one — which is D-12's surface default\n * honoured exactly where the session is known. The all-time and last-n arms pass through\n * untouched. The CLI has no session, so it constructs nothing and asks all-time, which is the\n * honest answer for a caller that has none.\n *\n * `sessionRef` is compared by EXACT STRING EQUALITY and is opaque here: this package mints no\n * session ids and parses none, so any host's spelling round-trips unexamined.\n */\nexport const AuthoringFunnelWindowSchema = z.discriminatedUnion('scope', [\n z.object({\n scope: z.literal('session'),\n sessionRef: z.string().min(1),\n }).strict(),\n z.object({ scope: z.literal('all-time') }).strict(),\n z.object({\n scope: z.literal('last-n'),\n /** The N most recently EVALUATED drafts, newest first by `evaluatedAt`. */\n n: z.number().int().positive(),\n }).strict(),\n])\n\nexport type AuthoringFunnelWindow = z.infer<typeof AuthoringFunnelWindowSchema>\n\n/**\n * What a caller hands the funnel read. The window and nothing else.\n *\n * `.strict()` on the loop input's reasoning: 392 D-07 binds every registry op into the planner's\n * toolset, so this shape crosses a trust boundary from an arbitrary caller rather than being\n * handed between two halves of one program.\n */\nexport const AuthoringFunnelGetInputSchema = z.object({\n /**\n * ITS `scope` IS A HOMONYM, AND THAT IS EXACTLY WHY IT IS DOCUMENTED HERE (400-04, D-19).\n *\n * `authoring.draft.write.scope` names a PRODUCT to author for. This op's `window.scope` names a\n * SPAN OF HISTORY to count over — `session` / `all-time` / `last-n`. Two fields spelled the same\n * with nothing in common, sitting on two ops a person meets in the same breath. D-19's doc half\n * would have made that worse, not better, if this row had inherited the product-target sentence:\n * a catalog that documented this `scope` as \"the target product\" would be a produced artifact\n * confidently describing a capability the product does not have.\n *\n * AND THE HUMAN IS THE ONLY READER THIS TEXT HAS. `window` is host-stamped for the planner —\n * `WINDOW_STAMPED_FUNCTION_IDS` carries this op, so `modelFacingInput()` drops `window` from\n * `required` and the model is told it will be supplied. So this description is not planner\n * guidance at all; it exists for the human-facing surfaces D-19 says were undocumented — which,\n * as MEASURED by 400-12 (WINDOWS #189) and narrowed by 430 D-02, are the committed capability\n * catalog row, `init --agent` and MCP `tools/list`, with `agent-qa fn --list` and the committed\n * catalog as the way a person finds the op. NOT `/help`, `explain` or the type-ahead: those\n * render `row.description`, or withhold params by charter. See the `scope` field's doc block\n * above for the full measurement and the D-19 ratification.\n */\n window: AuthoringFunnelWindowSchema.describe(\n 'Which drafts to count — a span of history, NOT a product. `{\"scope\":\"session\",\"sessionRef\":'\n + '\"<id>\"}` counts only what this conversation authored; `{\"scope\":\"all-time\"}` counts every '\n + 'draft this workspace has evaluated; `{\"scope\":\"last-n\",\"n\":<count>}` counts the N most '\n + 'recently evaluated, newest first. In chat you never type this: the session supplies its own '\n + 'window, and asking about the current conversation is the default. Do not confuse it with '\n + '`authoring.draft.write`\\'s `scope`, which names the product a test is authored for.',\n ),\n}).strict()\n\nexport type AuthoringFunnelGetInput = z.infer<typeof AuthoringFunnelGetInputSchema>\n\n/**\n * The op answers the ONE computation's result, unchanged — see `authoring/funnel.ts`.\n *\n * Not a summary of it and not a re-shaping: the op re-derives nothing, so the contract IS the\n * DTO the derivation produces. The window is deliberately NOT echoed back; a caller knows what it\n * asked, and echoing it would invite a surface to render the scope off the answer rather than off\n * the request, which is two sources for one fact.\n */\nexport const AuthoringFunnelGetOutputSchema = AuthoringFunnelSchema\n\nexport type AuthoringFunnelGetOutput = z.infer<typeof AuthoringFunnelGetOutputSchema>\n\n// ---- `authoring.draft.edit`: the patch contract's second consumer (394-09, D-21 · WTST-07) ------\n\n/**\n * What a caller hands the edit op.\n *\n * TWO FIELDS, AND BOTH CROSS A TRUST BOUNDARY. `testRef` decides WHICH of a person's committed\n * tests is rewritten, and `intent` is free text that reaches a model and becomes a patch set. So\n * `.strict()` and non-empty are the shape refusal, and everything a schema cannot check is refused\n * downstream by a named error: the ref by the never-guess binder (D-19), the emitted patches by the\n * region fence, and the patched document by the parser before anything is proposed.\n *\n * `testRef` accepts the `<filePath>::<testName>` spelling this project already prints — the same\n * string a dedup refusal hands back — as well as free text, which is routed to the house resolver.\n * Which of the two arrived is not a caller's declaration but a fact about the string, decided in\n * one place; a `kind` discriminant here would let a caller assert an exact address for text that\n * is not one.\n */\nexport const AuthoringDraftEditInputSchema = z.object({\n /** The test to edit: `<filePath>::<testName>`, or a name to resolve. Never guessed at. */\n testRef: z.string().min(1),\n /** Plain-English description of the change. */\n intent: z.string().min(1),\n}).strict()\n\nexport type AuthoringDraftEditInput = z.infer<typeof AuthoringDraftEditInputSchema>\n\n/**\n * What one edit answers: the draft it points at, the diff that produced it, and what it wrote.\n *\n * THE DIFF RIDES THE OUTPUT. The patch set is a fact about THIS invocation, and this is the shape\n * that invocation's caller reads. 2026-10-01 (432-17, D-06): the `test-draft` proposal arm this output\n * used to carry is deleted with the inbox; `written` says which file the edit wrote.\n *\n * The ops are the diff in the contract's own vocabulary, and they are more precise than a line\n * range: a JSON Pointer names a node, and the guarantee that the rendered bytes changed only where\n * those pointers reach is 394-03's frozen corpus over the very applier this op reuses — which is\n * the whole argument for reusing it rather than writing a second one.\n */\nexport const AuthoringDraftEditOutputSchema = z.object({\n /**\n * The edited test. Since 432 D-06 the edit is written to the file it edited, and this ref points\n * at that file, so the verify arm reads the written test; it stays on the shelf copy only when\n * the write did not land (see `written`).\n */\n draftRef: DraftRefSchema,\n /** The committed test this edit was applied to, as the binder resolved it. */\n editedFrom: z.object({\n filePath: z.string().min(1),\n testName: z.string().min(1),\n /** How the ref bound: an exact address, or a unique high-confidence resolver hit (D-19). */\n boundBy: z.enum(['exact-ref', 'resolver']),\n }).strict(),\n /** The RFC-6902 ops that were applied — the diff. See the contract's doc block. */\n patches: z.array(PatchOpSchema),\n /** The model's own account of the change, stored as prose so nothing downstream parses it. */\n thoughts: z.string(),\n /**\n * What the edit did to the file it edited (432 D-06): written over the exact bytes it read, or\n * not written because that file changed, left the workspace, or could not be written.\n */\n written: TestFileWriteSchema,\n}).strict()\n\nexport type AuthoringDraftEditOutput = z.infer<typeof AuthoringDraftEditOutputSchema>\n","// The honesty funnel: Meta's four stages over drafts that reached authoring (394, D-13/D-15).\n//\n// THE DENOMINATOR IS FROZEN, AND THE FREEZE IS THE FEATURE. WTST-05 compares this project's\n// funnel against the published reference distribution — 75 built / 57 passed stably / 25 added\n// value / 73 accepted — and a comparison against a shape that drifts is a comparison against\n// nothing. So the four stages are a closed `as const` vocabulary, pinned by an exact key-set\n// assertion in `__tests__/funnel.test-d.ts` and by a runtime census beside it, and changing which\n// stages exist invalidates every recorded comparison rather than merely widening a type.\n//\n// THE ORDERED CONTRACT — which receipt field produces each count:\n//\n// 1. `built` one per receipt in the window. A receipt exists exactly when a\n// schema-valid draft was produced and evaluated.\n// 2. `passedStably` `gates.executesDefinitive.pass && gates.stableVerdict.pass` — gates 1+2.\n// 3. `addedValue` `gates.addsValue.pass` — gate 3.\n// 4. `writeEligible` a receipt whose stored disposition is one 432 D-06 writes to its test path\n// (`draftDispositionWritesTarget`: every disposition but `rejected`).\n//\n// 2026-10-02 (quick 261002-ctr): stage 4 was `accepted`, an `applied` human decision on a\n// test-draft proposal. 432 D-06 writes a final draft in the call that authored it and files no\n// proposal, and 432-17 deleted the inbox the decisions lived in, so `accepted` could only ever be\n// 0 and the flag below could never fire. The stage now counts what D-06 made the terminal step: a\n// draft the gates did not reject, which is a draft the authoring loop writes. It is named for the\n// disposition and not `written` because a receipt records the verification, not the file: a draft\n// verified on its own through `authoring.draft.verify` has a receipt and was never offered for a\n// write, and a write can still refuse at the target. Recorded comparisons against the reference\n// distribution's human `accepted` column are against a different measurement from here on. The\n// acceptance-failure flag keeps its name and is decided on `writeEligible`, so it can fire again.\n//\n// 2026-10-03 (quick 261003-cpv, 432 review WR-09): a draft-mode receipt whose gate 1, 3 or 4 said\n// no is now stored `rejected`, so it is no longer write-eligible and no longer raises the flag.\n// Receipts stored before this keep the disposition they were given and are counted as given.\n//\n// GATE 4 IS NOT A STAGE. There are four gates and four stages and they are not the same four:\n// `falsifiableAssertion` (gate 4) decides whether a draft asserts anything falsifiable, which is\n// a property of the draft rather than a step on the way from intent to suite. A draft rejected on\n// gate 4 alone still executed definitively, still ran stably and still added value, and counting\n// it out of those stages would report the funnel narrowing where it did not.\n//\n// THE STAGES ARE INDEPENDENT COUNTS OVER ONE DENOMINATOR, NOT NESTED SUBSETS. D-04 forbids\n// short-circuiting the gate evaluation — the corpus proves gate INDEPENDENCE, which is unprovable\n// if evaluation stops at the first `false` — so a receipt can carry `addsValue.pass` while gate 1\n// failed. `addedValue` therefore counts every receipt whose gate 3 passed, and may exceed\n// `passedStably`. Re-basing each stage on the previous one would hide exactly the independence\n// the gates were built to demonstrate.\n//\n// THE DEDUP REFUSAL IS A NAMED SIDE COUNTER, BESIDE THE FUNNEL AND NEVER FOLDED INTO A STAGE\n// (D-15). A stage-2 dedup refusal is the loop WORKING — the intent was already covered and\n// nothing was authored — so folding refusals into `built` and then into the filtered-out\n// remainder would let working-as-intended refusals inflate the filter rate, and the resulting\n// number could not be compared against the reference distribution at all. A draft the loop\n// stopped on because the application looks broken needs no counter of its own: it reached\n// authoring, so it is already a `built` nobody kept, counted in the stages themselves.\n//\n// THE FLAG IS COMPUTED ON EXACT INTEGERS, NEVER ON THE ROUNDED PERCENTAGE THE RENDER SHOWS. The\n// rendered percentage is a display concern computed separately and deliberately downstream of the\n// decision: a keep rate of 90.4% displays as \"90%\" and MUST still flag, and reading the rounded\n// value back is precisely how that gets silently lost. The comparison is the cross-multiplied\n// integer one — `writeEligible * den > num * built` — on the shipped `ceilingExceeded` precedent.\n//\n// BOUNDARY DIRECTIONS, STATED AND PINNED. The ceiling comparison is STRICTLY GREATER: a rate\n// exactly at the ceiling does not flag. The floor comparison is GREATER-OR-EQUAL: a draft count\n// exactly at the floor admits the flag. Below the floor the rate renders with an explicit\n// small-sample caveat and NEVER the flag.\n//\n// AN EMPTY WINDOW REPORTS AN ABSENT KEEP RATE, NOT 0%. `0/0` rendered as `0%` would report a loop\n// that filtered perfectly when in fact nothing happened — a wrong answer wearing a correct one's\n// clothes, about the one number this whole module exists to keep honest.\n\nimport { z } from 'zod'\n\nimport { draftDispositionWritesTarget } from './disposition'\nimport type { DraftReceipt } from './draft-receipt'\n\n/**\n * The CLOSED, ORDERED four-stage vocabulary (D-15).\n *\n * Ordered because the funnel is read top to bottom and the reference distribution is quoted in\n * this order. Closed because a fifth member is a new denominator, not a new column.\n */\nexport const AUTHORING_FUNNEL_STAGES = [\n 'built',\n 'passedStably',\n 'addedValue',\n 'writeEligible',\n] as const\n\nexport type AuthoringFunnelStage = (typeof AUTHORING_FUNNEL_STAGES)[number]\n\n/**\n * The keep rate above which the loop is reported as failing to filter — 9/10 (D-13).\n *\n * A RATIONAL PAIR AND NOT A DECIMAL, on the shipped `MARK_UNHANDLED_CEILING` precedent and for\n * its stated reason: it is published so no consumer re-derives the comparison as a rounded\n * percentage. `0.9` beside it would be a second spelling of one number, free to be the one a\n * caller reaches for.\n *\n * RETUNE: moving this changes what \"the loop is not filtering\" MEANS, so a retune is a\n * measurement and not a preference. Before moving it, report: (a) the observed keep rate over at\n * least one full milestone of REAL sessions — not corpus runs, whose outcomes are scripted —\n * broken down by disposition, so a rate driven by `keep-eligible` drafts is distinguishable from\n * one driven by `proposal-only` ones; (b) that rate set beside the reference distribution's 73%\n * accepted (73 of 75 built), which is the number this ceiling was chosen against; and (c) which\n * side of the PROPOSED ceiling the observed rate falls on, stated explicitly — a retune that\n * lands the observed rate just under its own new ceiling is a ceiling chosen to be satisfied. A\n * ceiling argued from intuition is the failure this block exists to prevent.\n */\nexport const KEEP_RATE_CEILING = { num: 9, den: 10 } as const\n\n/**\n * The fewest drafts a window must carry before the flag may be raised — 10 (D-13).\n *\n * RETUNE: a retune must report the FALSE-FLAG RATE at the current floor over real sessions —\n * how often a window of exactly 10..N drafts raised the acceptance-failure flag and a human\n * reading the drafts disagreed that the loop had stopped filtering. That number is what the\n * floor buys; a floor moved without it trades an unmeasured false-flag rate for an unmeasured\n * missed-flag rate. Report both directions: at a HIGHER floor, how many real windows would stop\n * being able to flag at all. A floor argued from intuition is the failure this block prevents.\n */\nexport const FUNNEL_MIN_DRAFTS_FLOOR = 10\n\n/**\n * The ONE counter that sits BESIDE the funnel (D-15). Never a stage; see the header.\n *\n * `dedupRefusals` is OPTIONAL, and its absence is a true statement rather than a gap. A stage-2\n * refusal ends the invocation with nothing authored — no draft, no receipt, no gate-run and no\n * envelope (D-04) — so on a host where nothing durably records one, the honest answer is that it\n * is not recorded. Reporting `0` would say \"no author was ever refused\" about something nothing\n * counts, which is the same wrong answer the absent keep rate exists to refuse.\n *\n * NOTHING ELSE SITS BESIDE THE FUNNEL, and the keep rate stays honest without it. A draft the\n * loop stopped on because the application looks broken reached authoring, so it is a `built`;\n * its gates rejected it, so it never reached `writeEligible`. It is already a built-but-not-kept draft in\n * the stages, over the same denominator — a second counter for it would describe the same event\n * twice and answer no question the stages do not.\n * 2026-09-02 (Phase 411): the proposal arm for a correctly-failing draft left with the Issue-slot\n * cleanup.\n */\nexport interface FunnelSideCounters {\n readonly dedupRefusals?: number\n}\n\n// 2026-10-02 (quick 261002-ctr): `AuthoringAcceptance` and the `acceptances` input are deleted\n// with the `accepted` stage. `writeEligible` is read off each receipt's own stored disposition.\n\nexport interface AuthoringFunnelInput {\n /** The receipts in the window. This IS the denominator. */\n readonly receipts: readonly DraftReceipt[]\n readonly sideCounters: FunnelSideCounters\n /**\n * Loop invocations the window covers, where the caller can count them.\n *\n * Receipts are addressed by content digest, so two byte-identical drafts collapse to ONE\n * receipt and one `built`. That is accepted rather than re-keyed — `receiptPath`'s recipe is\n * what `demo/init/scripts/drain-393-gates.sh` reads by — and it is DISCLOSED: when this number\n * exceeds the receipt count, the render carries the caveat rather than quietly under-reporting.\n */\n readonly invocationCount?: number\n}\n\nexport const AuthoringFunnelSchema = z.object({\n stages: z.object({\n built: z.number().int().nonnegative(),\n passedStably: z.number().int().nonnegative(),\n addedValue: z.number().int().nonnegative(),\n writeEligible: z.number().int().nonnegative(),\n }).strict(),\n sideCounters: z.object({\n dedupRefusals: z.number().int().nonnegative().optional(),\n }).strict(),\n /** The EXACT ratio, absent when nothing was built. Never the flag's input. */\n keepRate: z.number().min(0).max(1).optional(),\n acceptanceFailure: z.boolean(),\n smallSample: z.boolean(),\n undercounted: z.boolean(),\n /** The ONE rendered line every surface prints. See {@link renderFunnelLine}. */\n line: z.string().min(1),\n}).strict()\n\nexport type AuthoringFunnel = z.infer<typeof AuthoringFunnelSchema>\n\n/**\n * Phrasings a funnel render may never carry (the WTST-05 prohibition, made mechanical).\n *\n * A high keep rate is the loop failing to filter. Rendering it as an achievement, a score or a\n * percentage-complete is the exact misreading D-13 exists to prevent, and a prohibition nothing\n * checks is a comment. Every line this module composes is screened against these words before it\n * is returned, so the check runs on the SHIPPED wording rather than on a reviewer's attention.\n *\n * Matched on WORD BOUNDARIES, never as substrings: \"win\" inside \"window\" and \"star\" inside\n * \"started\" are the false positives a substring lexicon collects, and a screen that fires on its\n * own honest wording gets deleted rather than fixed.\n */\nexport const FUNNEL_SUCCESS_FRAMING_LEXICON: readonly string[] = [\n 'success',\n 'successful',\n 'succeeded',\n 'achievement',\n 'achieved',\n 'score',\n 'scored',\n 'grade',\n 'excellent',\n 'great',\n 'healthy',\n 'on track',\n 'milestone',\n 'well done',\n 'congratulations',\n 'complete',\n 'completed',\n 'progress',\n 'goal',\n '✅',\n '🎉',\n '👍',\n '⭐',\n]\n\n/** Raised when a composed funnel line carries a framing the prohibition forbids. */\nexport class FunnelSuccessFramingError extends Error {\n constructor(readonly violations: readonly string[]) {\n super(\n 'A funnel render may never present the keep rate as an achievement, a score or a '\n + `percentage-complete (WTST-05). Refusing a line carrying: ${violations.join(', ')}`,\n )\n this.name = 'FunnelSuccessFramingError'\n }\n}\n\n/** Which forbidden framings a string carries, in lexicon order. Empty is the clean answer. */\nexport function successFramingViolations(text: string): string[] {\n const lowered = text.toLowerCase()\n return FUNNEL_SUCCESS_FRAMING_LEXICON.filter((term) => (\n /^[a-z ]+$/.test(term)\n ? new RegExp(`(^|[^a-z])${term.replace(/ /g, '\\\\s+')}([^a-z]|$)`).test(lowered)\n : lowered.includes(term)\n ))\n}\n\n/**\n * The wording table every render composes from — the ONE place the funnel's words live.\n *\n * Pinned as a frozen record rather than inlined, so the prohibition above has something to screen\n * and a later editor changing a phrase edits it in the file that refuses a framed one.\n */\nexport const FUNNEL_PHRASES = {\n heading: 'Authoring funnel',\n built: 'built',\n passedStably: 'passed stably',\n addedValue: 'added value',\n writeEligible: 'write-eligible',\n noDrafts: 'No drafts reached authoring in this window, so there is no keep rate to report.',\n acceptanceFailure: 'ACCEPTANCE FAILURE',\n notFiltering: 'the loop is not filtering',\n smallSample: 'too few drafts to judge the filter',\n undercounted:\n 'fewer receipts than invocations — byte-identical drafts share one receipt, so `built` is a '\n + 'lower bound here',\n refusalsUnrecorded: 'dedup refusals not recorded on this host',\n} as const satisfies Readonly<Record<string, string>>\n\n/** What {@link renderFunnelLine} needs: the computed funnel minus the line it is about to make. */\nexport type FunnelRenderParts = Omit<AuthoringFunnel, 'line'>\n\n/**\n * Compose the ONE line every surface prints, and refuse it if it frames the rate as a success.\n *\n * The percentage is rounded HERE and nowhere else, and nothing downstream of this function reads\n * it back: `acceptanceFailure` was decided on integers before this ran.\n */\nexport function renderFunnelLine(parts: FunnelRenderParts): string {\n const { stages, sideCounters, keepRate } = parts\n const segments: string[] = [\n `${FUNNEL_PHRASES.heading} — ${stages.built} ${FUNNEL_PHRASES.built}`\n + ` · ${stages.passedStably} ${FUNNEL_PHRASES.passedStably}`\n + ` · ${stages.addedValue} ${FUNNEL_PHRASES.addedValue}`\n + ` · ${stages.writeEligible} ${FUNNEL_PHRASES.writeEligible}.`,\n ]\n\n if (keepRate === undefined) {\n segments.push(FUNNEL_PHRASES.noDrafts)\n } else {\n const percent = Math.round(keepRate * 100)\n const rate = `keep rate ${percent}% over ${stages.built} drafts`\n if (parts.acceptanceFailure) {\n segments.push(`${FUNNEL_PHRASES.acceptanceFailure}: ${rate} — ${FUNNEL_PHRASES.notFiltering}.`)\n } else if (parts.smallSample) {\n segments.push(\n `${rate} — ${FUNNEL_PHRASES.smallSample} (the floor is ${FUNNEL_MIN_DRAFTS_FLOOR} drafts).`,\n )\n } else {\n segments.push(`${rate}.`)\n }\n }\n\n if (parts.undercounted) segments.push(`Note: ${FUNNEL_PHRASES.undercounted}.`)\n\n const refusals = sideCounters.dedupRefusals === undefined\n ? FUNNEL_PHRASES.refusalsUnrecorded\n : `${sideCounters.dedupRefusals} dedup refusals`\n segments.push(`Beside the funnel: ${refusals}.`)\n\n const line = segments.join(' ')\n const violations = successFramingViolations(line)\n if (violations.length > 0) throw new FunnelSuccessFramingError(violations)\n return line\n}\n\n/**\n * THE ONE funnel computation (388 D-14's one-read-op law applied to the derivation).\n *\n * Pure and total. Every caller renders what this returns rather than deriving a number of its own,\n * which is what makes \"how many drafts did this session keep\" a question with one answer. What\n * calls it today is `authoring.funnel.get`, through the agent's projection; no surface computes a\n * funnel any other way, and none is permitted to.\n */\nexport function computeAuthoringFunnel(input: AuthoringFunnelInput): AuthoringFunnel {\n let passedStably = 0\n let addedValue = 0\n // Read off the receipt's STORED disposition, never recomputed from its gates: the stored value is\n // the answer that was given, and the one the loop's write decision read.\n let writeEligible = 0\n for (const receipt of input.receipts) {\n if (receipt.gates.executesDefinitive.pass && receipt.gates.stableVerdict.pass) passedStably += 1\n if (receipt.gates.addsValue.pass) addedValue += 1\n if (draftDispositionWritesTarget(receipt.disposition)) writeEligible += 1\n }\n\n const built = input.receipts.length\n const stages = { built, passedStably, addedValue, writeEligible }\n\n const smallSample = built < FUNNEL_MIN_DRAFTS_FLOOR\n // INTEGERS. Never `writeEligible / built > 0.9`, and never the rounded percentage the line shows.\n const aboveCeiling = writeEligible * KEEP_RATE_CEILING.den > KEEP_RATE_CEILING.num * built\n const acceptanceFailure = aboveCeiling && built >= FUNNEL_MIN_DRAFTS_FLOOR\n\n const parts: FunnelRenderParts = {\n stages,\n sideCounters: {\n ...(input.sideCounters.dedupRefusals === undefined\n ? {}\n : { dedupRefusals: input.sideCounters.dedupRefusals }),\n },\n // ABSENT rather than 0 when nothing was built — see the header.\n ...(built === 0 ? {} : { keepRate: writeEligible / built }),\n acceptanceFailure,\n smallSample,\n undercounted: input.invocationCount !== undefined && input.invocationCount > built,\n }\n\n return { ...parts, line: renderFunnelLine(parts) }\n}\n","// The draft disposition: ONE derivation site (Phase 393, D-18).\n//\n// A draft receipt reports four independent gate booleans (WTST-02). The disposition is what\n// those booleans plus the stability-run counts MEAN, and it is computed here — once — so that no\n// consumer can re-derive its own answer.\n//\n// 2026-09-30, 432 D-06: the never-auto-keep rule is superseded. The disposition stays as the\n// verification report, and what it now decides is whether the final draft is WRITTEN to its test\n// path: `keep-eligible`, `proposal-only` and `unverified` are written, `rejected` is not. That\n// decision is `draftDispositionWritesTarget` below, beside the table it reads.\n//\n// 2026-10-03 (quick 261003-cpv, 432 review WR-09): rule 1 now follows D-06 literally, \"writes the\n// test file unless a keep-gate rejected it\". One draft-mode run DECIDES gates 1, 3 and 4: gate 1\n// reads that run's own verdict, gate 3 that run's fingerprint against the suite plus the step text,\n// gate 4 the static assertion check (`verify-draft.ts` evaluates all four on every evaluation and\n// holds none at a constant). Only gate 2 needs more than one run: with one run it is true exactly\n// when a verdict was observed, so it can never report instability and never rejects in draft mode.\n// Before this, rule 1 answered 'unverified' unconditionally, so a draft-mode draft whose run\n// reached no verdict, or that added nothing or asserted nothing falsifiable, was written into the\n// suite. Stored receipts keep the disposition they were given (D-22).\n//\n// THE TABLE (contract, not implementation detail), evaluated in this order:\n// 1. `stabilityRunsRequested === 1` (draft mode): any of `executesDefinitive`, `addsValue` or\n// `falsifiableAssertion` false → 'rejected'; otherwise 'unverified', including when all four\n// gates passed. One run cannot observe stability, so a one-run evaluation never earns a\n// keep-shaped answer; 'unverified' rather than 'rejected' because no gate one run decides\n// said no.\n// 2. any gate boolean false → 'rejected'. Early-stopped stability runs (D-17 stops on the\n// first verdict flip) arrive here with `stabilityRunsCompleted` below N and must still\n// read 'rejected': the flip already proved instability, and the unrun runs would only\n// re-prove it. Letting the short count win would write a proven-unstable draft.\n// 3. all four true AND `stabilityRunsCompleted >= DRAFT_STABILITY_RUNS_N` → 'keep-eligible'.\n// 4. all four true with fewer completed runs → 'proposal-only'. The name is historical: a short\n// evaluation used to become a proposal. Since 432 D-06 it is written like the others, and\n// the name tells the reader the evaluation was short.\n\n/**\n * The closed disposition vocabulary. Stored receipts and the written-test receipt carry these\n * exact names; renaming one is a migration of durable records, not a rename.\n */\nexport const DRAFT_DISPOSITIONS = [\n 'keep-eligible',\n 'proposal-only',\n 'rejected',\n 'unverified',\n] as const\n\nexport type DraftDisposition = (typeof DRAFT_DISPOSITIONS)[number]\n\n/**\n * Stability runs a draft must complete before it can be keep-eligible. PINNED, never config.\n *\n * RETUNE: changing this number changes what the stability gate MEANS, so a retune is a\n * measurement, not a preference. Before moving it, re-measure on the frozen corpus: (a) the\n * gate-2 rejector's flip rate at the new N — the corpus rejector alternates on a pinned\n * per-request schedule, so a wrong N can make a proven-unstable draft read stable; (b) the\n * accept control's pass rate at the new N, since a higher N multiplies the chance that an\n * unrelated flake denies a good draft; (c) the wall-clock cost per draft (local-form runs are\n * ~22s each, so N is a direct multiplier on the authoring loop's latency budget). Record the\n * new numbers beside the frozen expectations table; a retune that only argues from intuition\n * is the failure this comment exists to prevent.\n */\nexport const DRAFT_STABILITY_RUNS_N = 3\n\n/**\n * The four keep-gates, reported separately and never collapsed (WTST-02, D-04).\n *\n * All four are always present: D-04 forbids short-circuiting, because the corpus proves gate\n * INDEPENDENCE — a draft whose only failing gate is 4 demonstrates that gate 4 is the sole\n * catcher, which is unprovable if evaluation stops at the first `false`.\n */\nexport interface DraftGateBooleans {\n /**\n * Gate 1: the draft reached a definitive verdict on every run.\n *\n * Definitive as `stability-gates.ts` enforces it (393-09, WR-04 doc arm): a `passed`, `failed`\n * or `healed` member outcome — a heal counts as a pass — with no planning failure, no cycle\n * flag and no recorded step termination on any step. A `failed` member carrying a termination\n * is indefinitive, and 9 of 9 failed members surveyed in the demo run store carry one, so on\n * current builds this gate effectively admits passing runs only. The app-broken branch — a\n * draft that fails because the application is wrong — ends the invocation as a reported stop:\n * the gate run's verdict on the op result, the draft retained on the shelf (411), rather than a\n * keep here.\n */\n readonly executesDefinitive: boolean\n /** Gate 2: the verdict did not flip across the stability runs. */\n readonly stableVerdict: boolean\n /** Gate 3: the draft exercises at least one element absent from the suite union (D-14). */\n readonly addsValue: boolean\n /** Gate 4: at least one assertion step references concrete, falsifiable content (D-09). */\n readonly falsifiableAssertion: boolean\n}\n\n/**\n * The gates one stability run decides (261003-cpv, WR-09): every gate except `stableVerdict`.\n * Draft mode rejects on these and only these.\n */\nexport const SINGLE_RUN_DRAFT_GATES = [\n 'executesDefinitive',\n 'addsValue',\n 'falsifiableAssertion',\n] as const satisfies readonly (keyof DraftGateBooleans)[]\n\n/** Whether every gate one run decides passed. */\nexport function singleRunGatesPass(gates: DraftGateBooleans): boolean {\n return SINGLE_RUN_DRAFT_GATES.every((gate) => gates[gate])\n}\n\nexport interface DraftDispositionInput {\n readonly gates: DraftGateBooleans\n /**\n * Stability runs the evaluation ASKED for. `1` is draft mode and is the only value with a\n * special meaning — rule 1 above, where only gates 1, 3 and 4 can reject.\n */\n readonly stabilityRunsRequested: number\n /**\n * Stability runs that actually completed. Below the requested count either because the\n * evaluation early-stopped on a verdict flip (D-17) or because a run could not be taken.\n */\n readonly stabilityRunsCompleted: number\n}\n\n/**\n * The ONE disposition derivation (D-18). Pure, total, and order-sensitive exactly as the\n * table above states; every branch is pinned by `__tests__/disposition.test.ts`.\n */\nexport function computeDraftDisposition(input: DraftDispositionInput): DraftDisposition {\n if (input.stabilityRunsRequested === 1) {\n return singleRunGatesPass(input.gates) ? 'unverified' : 'rejected'\n }\n\n const { executesDefinitive, stableVerdict, addsValue, falsifiableAssertion } = input.gates\n if (!(executesDefinitive && stableVerdict && addsValue && falsifiableAssertion)) {\n return 'rejected'\n }\n\n return input.stabilityRunsCompleted >= DRAFT_STABILITY_RUNS_N ? 'keep-eligible' : 'proposal-only'\n}\n\n/**\n * The dispositions whose final draft is written to its target (432 D-06, EDGE-09).\n *\n * Every disposition except `rejected`: the gates either said yes (`keep-eligible`), said yes over\n * too few runs (`proposal-only`), or said yes on every gate one run decides while stability was\n * not given enough runs (`unverified`; 261003-cpv, WR-09). Only `rejected` is a gate saying no,\n * and a rejected draft stays on the private shelf.\n */\nexport const DRAFT_WRITTEN_DISPOSITIONS = [\n 'keep-eligible',\n 'proposal-only',\n 'unverified',\n] as const satisfies readonly DraftDisposition[]\n\nexport type DraftWrittenDisposition = (typeof DRAFT_WRITTEN_DISPOSITIONS)[number]\n\n/** Whether a final draft with this disposition is written to its target. */\nexport function draftDispositionWritesTarget(\n disposition: DraftDisposition,\n): disposition is DraftWrittenDisposition {\n return (DRAFT_WRITTEN_DISPOSITIONS as readonly DraftDisposition[]).includes(disposition)\n}\n","// The draft receipt: what a keep-gate evaluation durably says about one draft (393, WTST-02).\n//\n// Two shape rules govern everything below.\n//\n// MAP, NOT TERRITORY (D-19 / 391 D-18). The receipt carries REFS to the runs it judged plus\n// the findings it derived — never run payloads, never resolved secrets, never post-interpolation\n// step text. Run bytes live in the run store, which is the only place that owns them. Every\n// object here is `.strict()`, so smuggling a payload in is a typed refusal rather than a field\n// nobody notices until it shows up in a durable file.\n//\n// KEYED, NOT POSITIONAL. `DraftGateResultsSchema` names its gates, so a later gate can join\n// without re-minting this DTO or renumbering anything a 394 consumer already reads.\n// 2026-09-02 (Phase 412): the bug-repro anchoring gate that was to join here left with the\n// Issue-slot cleanup.\n\nimport { z } from 'zod'\n\nimport { DRAFT_DISPOSITIONS, draftDispositionWritesTarget, singleRunGatesPass } from './disposition'\nimport type { DraftGateBooleans } from './disposition'\n\n/**\n * Bumping this is a breaking change to a durable store. The record schema pins the literal, so\n * a receipt written by an earlier build fails loudly at read time instead of being silently\n * reinterpreted under the new shape (the house stamp-and-hard-fail convention).\n */\nexport const CURRENT_DRAFT_RECEIPT_SCHEMA_VERSION = 2\n\n/**\n * Which draft this receipt is about.\n *\n * `filePath` + `testName` is the STABLE identity the suite comparison keys on — the ratified\n * project-wide rule, never `testId`. `testId` is carried anyway because it is what\n * `parseTestFile` mints for the draft and what the run's own evidence cites, so a reader\n * tracing a receipt back to a handoff needs it; it is provenance, not identity.\n */\nexport const DraftRefSchema = z.object({\n filePath: z.string().min(1),\n testId: z.string().min(1),\n testName: z.string().min(1),\n /** Digest of the draft bytes evaluated, so a later edit cannot inherit this receipt. */\n contentDigest: z.string().min(1),\n}).strict()\n\nexport type DraftRef = z.infer<typeof DraftRefSchema>\n\n/**\n * One parsed NL step, as gate 4's deterministic check classified it (D-11).\n *\n * Lands VERBATIM in the receipt: D-12 tunes ambiguity toward reject, which is only defensible\n * if the rejected author can read exactly which step was called what and why.\n */\nexport const StepClassificationRowSchema = z.object({\n /** Pre-interpolation step text. Post-interpolation text can carry resolved secrets. */\n stepText: z.string(),\n role: z.enum(['assertion', 'action']),\n /** Clause (ii) of D-09: references concrete expected content. Always false for actions. */\n falsifiable: z.boolean(),\n /** The vacuity-lexicon phrase this step matched, named so the author can see the term. */\n vacuityHit: z.string().optional(),\n /** Capture-signature pattern names hit by this step's expected value (D-10). */\n captureSignatureHits: z.array(z.string()),\n /** D-10 tautology detection: the assertion restates a prior action's own content. */\n tautologyHit: z.boolean().optional(),\n}).strict()\n\nexport type StepClassificationRow = z.infer<typeof StepClassificationRowSchema>\n\n/**\n * One stability run, as a REF plus the judgment made about it.\n *\n * `healed` is separable from `definitive` and from `memberOutcome` on purpose. Measured on the\n * frozen corpus (393-01, F3): the definitive-pass arm arrives as `healed`, not `passed` — the\n * accept control itself heals. A gate 1 that does not count a healed pass as a pass fails the\n * one draft it exists to accept. Recording the heal separately lets gate 1 count it as a pass\n * while 394 still reads the heal as the weak-grounding signal it is (D-17).\n *\n * `definitive` is a judgment, not a field copy. 393-01's F1 measured that\n * `termination.kind === 'infeasible'` does NOT separate gate 1 from gate 2 on this build — 19\n * of 21 failed members carry one — so no single terminal field decides definitiveness, and\n * `reason` is where the evaluator says what it actually read.\n */\nexport const GateRunRecordSchema = z.object({\n /** A ref into the run store. Deliberately not the run's contents. */\n runId: z.string().min(1),\n /** The draft's own MEMBER outcome, not the aggregate verdict (D-17). */\n memberOutcome: z.string().min(1),\n definitive: z.boolean(),\n healed: z.boolean(),\n /** Why this run was judged definitive or not — the F1 escape hatch. */\n reason: z.string().optional(),\n}).strict()\n\nexport type GateRunRecord = z.infer<typeof GateRunRecordSchema>\n\n/**\n * Gate 3's finding: which suite tests were compared, in which lane, and what was novel.\n *\n * `lane` is D-16's per-test disclosure. A suite test with run evidence is compared by anchor\n * fingerprint; an evidence-less one falls back to title/step-text similarity and over-flags\n * toward \"covered\" (the safe direction). Reporting the lane per test is what stops a\n * fingerprint-lane claim from being read into a text-lane guess.\n */\nexport const AddsValueFindingSchema = z.object({\n /**\n * Fingerprint elements absent from the suite union — NAMED, not counted (D-14). No\n * similarity threshold exists to defend, so the receipt shows the elements themselves.\n */\n novelElements: z.array(z.string()),\n comparedTests: z.array(z.object({\n filePath: z.string().min(1),\n testName: z.string().min(1),\n lane: z.enum(['fingerprint', 'text']),\n covered: z.boolean(),\n }).strict()),\n}).strict()\n\nexport type AddsValueFinding = z.infer<typeof AddsValueFindingSchema>\n\n/**\n * The four gate results, keyed by name (D-04: all four always evaluated, never short-circuited).\n *\n * Each carries `pass` plus a lean evidence sub-shape: counts and refs, with the rich tables\n * living once at the receipt level. Duplicating the tables inside each gate would create a\n * second answer to the same question, which is exactly what one-exported-vocabulary forbids.\n */\nexport const DraftGateResultsSchema = z.object({\n /**\n * Gate 1 (D-17): every run reached a DEFINITIVE verdict about the draft.\n *\n * THE ENFORCED RULE, as `stability-gates.ts` classifies it (393-09, WR-04 doc arm). The member\n * outcome must be `passed`, `failed` or `healed` — a healed pass IS a pass (393-01 F3) — AND no\n * step may carry a planning failure, a cycle flag, or ANY recorded termination. That last\n * conjunct is the one this doc used to omit: a `failed` member whose step evidence records a\n * termination is classified indefinitive, and the phase's survey of the demo run store found\n * 9 of 9 failed members carrying one. So on current builds a definitive verdict is effectively\n * a passing one — healed or clean — rather than the symmetric pass-or-fail this doc promised.\n * D-17's `error` class has no enum member here (`RunStatus` is\n * `passed | failed | healed | timeout | cancelled`); it arrives as a structural planning\n * failure or as a run record that cannot be read back at all.\n *\n * The app-broken branch — a draft that fails because the APPLICATION is wrong — is therefore\n * not a keep on this gate; it ends the invocation as a reported stop — the gate run's verdict on\n * the op result, the draft retained on the shelf (411). Read this field as \"the run answered\",\n * never as \"a failing draft can be kept\".\n */\n executesDefinitive: z.object({\n pass: z.boolean(),\n /** Refs into `gateRuns`. */\n runRefs: z.array(z.string()),\n /** The subset judged indefinitive, so \"why did gate 1 fail\" is answerable per run. */\n indefinitiveRunRefs: z.array(z.string()),\n reason: z.string().optional(),\n }).strict(),\n /** Gate 2 (D-17): the member outcome did not flip across the completed runs. */\n stableVerdict: z.object({\n pass: z.boolean(),\n runRefs: z.array(z.string()),\n /** Distinct member outcomes observed; length > 1 is the flip. */\n distinctOutcomes: z.array(z.string()),\n /** True when D-17's early-stop fired — the reason a completed count may be below N. */\n earlyStopped: z.boolean(),\n reason: z.string().optional(),\n }).strict(),\n /** Gate 3 (D-13/D-14/D-16): set semantics over anchor elements, no threshold. */\n addsValue: z.object({\n pass: z.boolean(),\n novelElementCount: z.number().int().nonnegative(),\n comparedTestCount: z.number().int().nonnegative(),\n reason: z.string().optional(),\n }).strict(),\n /** Gate 4 (D-09/D-10/D-12): the deterministic two-clause lexical check. */\n falsifiableAssertion: z.object({\n pass: z.boolean(),\n /** Clause (i): steps that classified as assertions at all. */\n assertionStepCount: z.number().int().nonnegative(),\n /** Clause (ii): of those, how many reference concrete expected content. */\n falsifiableAssertionCount: z.number().int().nonnegative(),\n reason: z.string().optional(),\n }).strict(),\n}).strict()\n\nexport type DraftGateResults = z.infer<typeof DraftGateResultsSchema>\n\n/** The gate names as a value, so a composition root can iterate them and a test can pin closure. */\nexport const DRAFT_GATE_NAMES = [\n 'executesDefinitive',\n 'stableVerdict',\n 'addsValue',\n 'falsifiableAssertion',\n] as const\n\nexport type DraftGateName = (typeof DRAFT_GATE_NAMES)[number]\n\n/**\n * The durable receipt (D-19). The op returns this AND persists it.\n *\n * `disposition` is the value `computeDraftDisposition` produced for this receipt's own gates\n * and counts. It is stored rather than recomputed at read time so the answer a consumer sees\n * is the answer that was actually given — a later retune of N must not silently rewrite the\n * history of decisions taken under the old one.\n */\nexport const DraftReceiptSchema = z.object({\n schemaVersion: z.literal(CURRENT_DRAFT_RECEIPT_SCHEMA_VERSION),\n draftRef: DraftRefSchema,\n gates: DraftGateResultsSchema,\n stepTable: z.array(StepClassificationRowSchema),\n gateRuns: z.array(GateRunRecordSchema),\n addsValueFinding: AddsValueFindingSchema,\n stabilityRunsRequested: z.number().int().nonnegative(),\n stabilityRunsCompleted: z.number().int().nonnegative(),\n disposition: z.enum(DRAFT_DISPOSITIONS),\n /** Epoch milliseconds. */\n evaluatedAt: z.number().int().nonnegative(),\n /**\n * The invoking session, as an OPAQUE string the caller supplied (394 D-12 · WTST-05).\n *\n * OPTIONAL AT THE CURRENT VERSION, AND THE VERSION IS DELIBERATELY NOT BUMPED. `parseReceipt`\n * throws `DraftReceiptSchemaVersionError` on any mismatch, so a bump would make `list()` throw\n * on every receipt already on a developer's or a CI runner's disk — which is precisely how a\n * funnel READ op becomes a crash. Optional-at-version-1 is the additive shape a stamp-and-\n * hard-fail store can actually absorb.\n *\n * ABSENCE IS EXCLUSION, NEVER A DEFAULT. A session-scoped funnel window compares this by exact\n * string equality; a receipt carrying no ref is left OUT rather than folded into whichever\n * session happens to be asking. Defaulting it in would attribute another session's drafts —\n * and, in the direction that matters, would inflate `built` under somebody else's keep rate.\n */\n sessionRef: z.string().min(1).optional(),\n}).strict()\n\nexport type DraftReceipt = z.infer<typeof DraftReceiptSchema>\n\n// ---- the written test (432 D-06/D-07) ----------------------------------------------------------\n//\n// A final draft is written straight to its test path unless its gates rejected it. What the\n// author is told is which file was written — or why none was — beside how well the draft was\n// verified: the disposition and the four gate booleans, never collapsed into one verdict.\n\n/** The four gate booleans on their own, as a written-test receipt carries them. */\nexport const DraftGateBooleansSchema = z.object({\n executesDefinitive: z.boolean(),\n stableVerdict: z.boolean(),\n addsValue: z.boolean(),\n falsifiableAssertion: z.boolean(),\n}).strict()\n\n/** The four booleans off a receipt's gate results, one per gate. */\nexport function draftGateBooleans(gates: DraftGateResults): DraftGateBooleans {\n return {\n executesDefinitive: gates.executesDefinitive.pass,\n stableVerdict: gates.stableVerdict.pass,\n addsValue: gates.addsValue.pass,\n falsifiableAssertion: gates.falsifiableAssertion.pass,\n }\n}\n\n/**\n * Why a writer left the target alone. `target-changed` covers both a new test whose path is now\n * taken and an edit whose file no longer holds the bytes it was built from.\n */\nexport const TEST_FILE_WRITE_REFUSALS = [\n 'outside-workspace',\n 'target-changed',\n 'write-failed',\n] as const\n\n/** Why no bytes reached the target: the gates rejected the draft, or the writer refused. */\nexport const TEST_FILE_NOT_WRITTEN_REASONS = ['rejected', ...TEST_FILE_WRITE_REFUSALS] as const\n\n/**\n * What happened at one test file: written (workspace-relative path and the digest of the exact\n * bytes written), or not written with the reason. A failed write is never reported as written.\n */\nexport const TestFileWriteSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('written'),\n filePath: z.string().min(1),\n contentDigest: z.string().min(1),\n }).strict(),\n z.object({\n kind: z.literal('not-written'),\n targetPath: z.string().min(1),\n reason: z.enum(TEST_FILE_NOT_WRITTEN_REASONS),\n /** The writer's own error text for `write-failed`; absent otherwise. */\n detail: z.string().optional(),\n }).strict(),\n])\n\nexport type TestFileWrite = z.infer<typeof TestFileWriteSchema>\n\n/**\n * The written-test receipt: the file, the disposition and the four gate booleans.\n *\n * A `rejected` disposition and a `rejected` not-written reason come together or not at all, and a\n * written file never carries a rejected disposition (EDGE-09).\n */\nexport const WrittenTestReceiptSchema = z.object({\n file: TestFileWriteSchema,\n disposition: z.enum(DRAFT_DISPOSITIONS),\n gates: DraftGateBooleansSchema,\n}).strict().superRefine((receipt, ctx) => {\n if (receipt.file.kind === 'written' && !draftDispositionWritesTarget(receipt.disposition)) {\n ctx.addIssue({\n code: 'custom',\n path: ['file'],\n message: `a ${receipt.disposition} draft is never written`,\n })\n }\n // 2026-10-03 (quick 261003-cpv, WR-09): an unverified draft is a draft-mode draft whose gates 1,\n // 3 and 4 passed; one of them false is a rejection. Producer-parsed only: nothing persists this\n // receipt, so the refinement reads no stored record.\n if (receipt.disposition === 'unverified' && !singleRunGatesPass(receipt.gates)) {\n ctx.addIssue({\n code: 'custom',\n path: ['disposition'],\n message: 'an unverified draft passed every gate one run decides; one that did not is rejected',\n })\n }\n const rejectedReason = receipt.file.kind === 'not-written' && receipt.file.reason === 'rejected'\n if (rejectedReason !== (receipt.disposition === 'rejected')) {\n ctx.addIssue({\n code: 'custom',\n path: ['file', 'reason'],\n message: 'only a rejected disposition leaves its draft unwritten as rejected',\n })\n }\n})\n\nexport type WrittenTestReceipt = z.infer<typeof WrittenTestReceiptSchema>\n","// The ONE fan-out arithmetic (Phase 394, D-03/D-10 · WTST-08).\n//\n// WHAT THIS NUMBER IS FOR. WTST-08's owner decision is preview and honest reporting with NO\n// enforced pre-dispatch budget. That decision moves the whole mitigation for an unbounded fan-out\n// onto DISCLOSURE — the number a person is shown at the dispatch confirm is the control, and the\n// number the finished proposal reports is what makes the disclosure falsifiable. A preview lower\n// than the loop's own worst case is therefore a consent defect and never a rounding choice: it is a\n// person having agreed to less compute than was actually taken from them.\n//\n// WHY IT LIVES IN `schema`. The dispatch confirm is composed in `agent` and the report rides a\n// proposal arm this package owns, so a bound spelled in `agent` and read by a receipt would be an\n// arithmetic each surface restates. One function in the one package both sides already depend on is\n// what makes \"the preview and the report cannot disagree\" a structural fact rather than a habit. It\n// is also why the terms arrive as INPUTS: `DRAFT_STABILITY_RUNS_N` lives here, but the repair cap K\n// lives in `agent` beside the loop that spends it, and a schema that reached for it would need a\n// dependency edge pointing the wrong way.\n//\n// THE ORDERED CONTRACT — where each term comes from, and what one costs:\n// initialN the first stability gate, `DRAFT_STABILITY_RUNS_N` (or 1 when the caller asked for\n// draft mode). EARLY-STOPPED: gate 2 stops on a verdict flip, so this term is an upper\n// bound on that gate and not a promise that it will be spent.\n// probeK one probe run per repair iteration, bounded by `REPAIR_ITERATION_CAP`. A fenced or\n// unparsable emission consumes an iteration WITHOUT starting a run, so this term is an\n// upper bound too.\n// finalN the full stability gate on the repaired candidate, `DRAFT_STABILITY_RUNS_N` again.\n// It is a SEPARATE quantity from `initialN` even when the two are numerically equal —\n// the first judges what the model wrote, the second judges what repair produced.\n// EVERY ONE OF THESE RUNS IS A FULL CHILD `agent-qa run` PROCESS against the user's application,\n// not a function call. That is what makes nine of them a number worth putting in front of a person.\n//\n// THE TWO N TERMS ARE NEVER COLLAPSED. A `FanOutBound` carrying only a sum, or a single doubled\n// term, would let a later reader re-derive `2N + K` and lose the distinction — and with the shipped\n// constants the collapse is invisible, because both terms are 3. The terms are separate keys, the\n// type pins the key set by equality, and the runtime cells that catch a collapse are the ones that\n// use draft mode, where the two terms differ.\n\n// THE SHAPES ARE ZOD SCHEMAS AND THE TYPES ARE DERIVED FROM THEM (394-14). Until this plan the\n// shapes here were hand-written interfaces, which was correct while nothing crossed a wire: the\n// report was an in-process value the loop handed its own caller. `authoring.draft.write` now\n// CARRIES the report on its `.strict()` output contract, so the shape is validated at a boundary —\n// and a validator written beside an interface is two declarations of one shape, free to drift in\n// the direction where the schema accepts a report the type forbids or strips one the type requires.\n// Deriving is what makes the mirror structural rather than a habit. `.readonly()` is on every one\n// of them because the interfaces it replaces were readonly throughout, and a derived type that\n// quietly dropped the modifier would be a widening nobody asked for.\n\nimport { z } from 'zod'\n\n/** The three terms, as the caller that knows all three supplies them. */\nconst fanOutBoundTerms = {\n /** The first stability gate's run count — `DRAFT_STABILITY_RUNS_N`, or 1 in draft mode. */\n initialN: z.number().int().min(0),\n /** One probe per repair iteration — `REPAIR_ITERATION_CAP`. */\n probeK: z.number().int().min(0),\n /** The final stability gate on the repaired candidate — `DRAFT_STABILITY_RUNS_N`. */\n finalN: z.number().int().min(0),\n}\n\nexport const FanOutBoundInputSchema = z.object(fanOutBoundTerms).strict().readonly()\n\nexport type FanOutBoundInput = z.infer<typeof FanOutBoundInputSchema>\n\n/**\n * The three terms and their total, all four separately readable.\n *\n * `total` IS NOT RE-DERIVED BY A REFINEMENT HERE, and the omission is deliberate. A\n * `.refine(b => b.total === b.initialN + b.probeK + b.finalN)` would be a SECOND assembly of the\n * three terms living one file away from `computeFanOutBound`, which is precisely the second\n * arithmetic this file's header forbids and mutation I of the phase's mutation driver (since\n * removed) existed to catch. The schema's job is the shape; the sum has exactly one site.\n */\nexport const FanOutBoundSchema = z.object({\n ...fanOutBoundTerms,\n total: z.number().int().min(0),\n}).strict().readonly()\n\nexport type FanOutBound = z.infer<typeof FanOutBoundSchema>\n\n/**\n * A term that would SUBTRACT from the disclosure.\n *\n * The one arithmetic error this number may never make, so it is refused at the input rather than\n * clamped: a negative term is a caller bug, and the safe-looking repair — treating it as zero —\n * would answer a smaller bound than the loop's worst case, which is the defect itself.\n */\nexport class FanOutBoundError extends Error {\n constructor(readonly term: keyof FanOutBoundInput, readonly value: number) {\n super(\n `fan-out bound: ${term} must be a non-negative integer, and it was ${value} — `\n + 'a term that subtracts would make the preview lower than the loop\\'s own worst case',\n )\n this.name = 'FanOutBoundError'\n }\n}\n\n/**\n * THE ONE fan-out arithmetic. `initialN + probeK + finalN`, with all three terms preserved.\n *\n * Pure and total: one argument, no clock, no store, no config. `schema`'s only runtime dependency\n * is `zod`, so there is nothing here for a later edit to reach for even if it wanted to.\n */\nexport function computeFanOutBound(input: FanOutBoundInput): FanOutBound {\n for (const term of ['initialN', 'probeK', 'finalN'] as const) {\n const value = input[term]\n if (!Number.isInteger(value) || value < 0) throw new FanOutBoundError(term, value)\n }\n return {\n initialN: input.initialN,\n probeK: input.probeK,\n finalN: input.finalN,\n total: input.initialN + input.probeK + input.finalN,\n }\n}\n\n/**\n * The bound of an invocation in which no draft ever reached verification.\n *\n * PRODUCED through the function rather than written as a literal `{initialN: 0, …, total: 0}`, so\n * it cannot pin a shape the function would not answer. A dedup refusal (D-04) ends the invocation\n * before a byte is authored, so all three terms really are zero — this is a true value, not a\n * placeholder standing in for a number nobody computed.\n */\nexport const NO_RUNS_FAN_OUT_BOUND: FanOutBound = computeFanOutBound({\n initialN: 0,\n probeK: 0,\n finalN: 0,\n})\n\n/** What a consumed run was STARTED for. Closed, and the two are not interchangeable. */\nexport const FAN_OUT_RUN_PURPOSES = ['gate', 'probe'] as const\n\nexport type FanOutRunPurpose = (typeof FAN_OUT_RUN_PURPOSES)[number]\n\n/**\n * One run the invocation actually spent — a ref and a role, never the run document.\n *\n * `completedAt` is OPTIONAL because a run whose record could not be read is a real posture: the run\n * happened and must be counted, and pretending to know when it finished would fabricate a position\n * in the sequence. See the ordering rule below for where such an entry lands.\n */\nexport const ConsumedRunSchema = z.object({\n runId: z.string().min(1),\n purpose: z.enum(FAN_OUT_RUN_PURPOSES),\n /** Epoch milliseconds, when the run's record says so. */\n completedAt: z.number().optional(),\n}).strict().readonly()\n\nexport type ConsumedRun = z.infer<typeof ConsumedRunSchema>\n\n/**\n * What was previewed, beside what was actually consumed.\n *\n * Both numbers ride ONE object so a reader cannot be handed either alone. The actual alone leaves\n * the disclosure unfalsifiable; the preview alone is the defect WTST-08 exists to prevent.\n */\nexport const FanOutReportSchema = z.object({\n previewed: FanOutBoundSchema,\n /** Distinct runs, in the order they finished, ties broken by run id. */\n consumed: z.array(ConsumedRunSchema).readonly(),\n consumedTotal: z.number().int().min(0),\n /**\n * The actual figure exceeded the previewed bound.\n *\n * REPORTED, NEVER CLAMPED AND NEVER THROWN. A clamp would turn a consent defect into a silent\n * correctness bug — the artifact would carry the number the preview promised rather than the\n * number that was spent — and a throw would destroy the receipt that holds the evidence for it.\n * The flag is a disclosure of the same kind the report itself is, and every path this phase\n * exercises asserts it is false.\n *\n * IT IS NOT RE-DERIVED HERE EITHER. `consumedTotal > previewed.total` spelled as a refinement\n * would be a second answer to the question `buildFanOutReport` already answered, and the two\n * could disagree only in the direction that hides an excess.\n */\n exceedsPreview: z.boolean(),\n}).strict().readonly()\n\nexport type FanOutReport = z.infer<typeof FanOutReportSchema>\n\n/**\n * Order the consumed runs into a sequence two renders of one report cannot disagree about.\n *\n * COMPLETION ORDER, TIES BROKEN BY RUN ID. Gate runs a fast local executor finishes inside the same\n * millisecond genuinely tie, so the id is what makes the order total rather than a fallback nobody\n * reaches. A run with NO known completion time sorts after every timed one, ordered by id among its\n * own kind: sorting it as `0` would place a run nothing timed ahead of runs that really did finish\n * first, which is a fabricated sequence rather than an unknown one.\n */\nfunction orderConsumedRuns(runs: readonly ConsumedRun[]): readonly ConsumedRun[] {\n return [...runs].sort((left, right) => {\n const leftTime = left.completedAt\n const rightTime = right.completedAt\n if (leftTime !== undefined && rightTime !== undefined && leftTime !== rightTime) {\n return leftTime - rightTime\n }\n if (leftTime === undefined && rightTime !== undefined) return 1\n if (leftTime !== undefined && rightTime === undefined) return -1\n return left.runId < right.runId ? -1 : left.runId > right.runId ? 1 : 0\n })\n}\n\n/**\n * Pair a previewed bound with the runs an invocation actually spent.\n *\n * DISTINCT BY RUN ID, and the first role wins. A run that served as the last repair probe and then\n * counted toward the final stability gate is ONE child process, and it was started as a probe —\n * counting it twice would inflate the actual figure in the safe-looking direction, which is exactly\n * how a real preview under-count would be masked by the report that exists to expose it.\n */\nexport function buildFanOutReport(input: {\n readonly previewed: FanOutBound\n readonly runs: readonly ConsumedRun[]\n}): FanOutReport {\n const distinct = new Map<string, ConsumedRun>()\n for (const run of input.runs) {\n if (!distinct.has(run.runId)) distinct.set(run.runId, run)\n }\n const consumed = orderConsumedRuns([...distinct.values()])\n return {\n previewed: input.previewed,\n consumed,\n consumedTotal: consumed.length,\n exceedsPreview: consumed.length > input.previewed.total,\n }\n}\n\n/** The wording table both renders compose from — the ONE place this plan's words live. */\nexport const FAN_OUT_PHRASES = {\n runCost: 'each run is a full `agent-qa run` process against your application',\n previewLead: 'This authoring invocation will execute up to',\n stability: 'stability runs',\n probes: 'repair probes',\n finalStability: 'final stability runs',\n reportLead: 'Runs consumed:',\n previewedWord: 'previewed',\n exceeded: 'THIS EXCEEDS THE PREVIEWED BOUND — report this, it is a defect in the bound',\n} as const\n\n/**\n * The disclosure the dispatch confirm renders — the sentence a person actually consents on.\n *\n * COMPOSED FROM THE BOUND'S OWN INTEGERS AND NOTHING ELSE. No caller text reaches this string: the\n * `intent` an arbitrary caller supplies is free text that already reaches a model, and a confirm\n * message it could write is a channel through which a caller could dress up what they are asking a\n * person to approve. Every token below is either a pinned phrase or a number this file computed.\n *\n * It names all three terms rather than only the total, because \"up to 9 runs\" is a number and\n * \"3 stability runs + up to 3 repair probes + 3 final stability runs\" is an explanation of it.\n */\nexport function renderFanOutPreview(bound: FanOutBound): string {\n return `${FAN_OUT_PHRASES.previewLead} ${bound.total} runs `\n + `(${bound.initialN} ${FAN_OUT_PHRASES.stability}, up to ${bound.probeK} `\n + `${FAN_OUT_PHRASES.probes}, ${bound.finalN} ${FAN_OUT_PHRASES.finalStability}). `\n + `${FAN_OUT_PHRASES.runCost}.`\n}\n\n/**\n * The honest half: what was actually spent, beside what was disclosed.\n *\n * The two figures are rendered in ONE line for the reason they ride one object — a reader handed\n * the actual alone cannot check the disclosure, and a reader handed the disclosure alone is being\n * told what was promised rather than what happened.\n */\nexport function renderFanOutReport(report: FanOutReport): string {\n const line = `${FAN_OUT_PHRASES.reportLead} ${report.consumedTotal} `\n + `(${FAN_OUT_PHRASES.previewedWord} up to ${report.previewed.total})`\n return report.exceedsPreview ? `${line} — ${FAN_OUT_PHRASES.exceeded}` : line\n}\n","// The RFC-6902 edit vocabulary for test documents (394, D-20 · WTST-07).\n//\n// THIS IS NOT THE UNIFIED-DIFF VOCABULARY. `packages/schema/src/patch/patch.ts` already carries\n// a `Hunk { header, lines }` / `FileChange { path, changeKind, hunks }` representation, and D-06\n// records deliberately that 394 does NOT reuse it. The two answer different questions: a hunk\n// describes bytes a human reviews before applying, and the ops below describe positions in a\n// PARSED document that a CST applier mutates so the untouched bytes never move. Unifying them\n// would force one of the two to lie about what it addresses. Read both headers before merging.\n//\n// The envelope is `{ thoughts, patches }` because WTST-07 names that shape: the model's reasoning\n// travels beside its edit rather than inside it, so nothing in `patches` has to be prose-parsed.\n\nimport { z } from 'zod'\n\n/**\n * The admitted ops — three of RFC-6902's six.\n *\n * `move` and `copy` are absent because each is expressible as an `add` plus a `remove`, and\n * admitting them would double the pointer-resolution surface the editable-region fence has to\n * cover: every `move` carries TWO pointers, and a fence that passes the destination while the\n * source addresses an excluded root is exactly the retarget T-394-10 exists to stop. `test` is\n * absent because it asserts something about the document rather than changing it, and the\n * post-render `TestDefinitionSchema` check already owns \"is this document still runnable\".\n *\n * A closed three-member vocabulary is also what lets the applier's `switch` be exhaustive, so a\n * fourth member cannot be added without the compiler naming every site that must handle it.\n */\nexport const PATCH_OP_KINDS = ['add', 'remove', 'replace'] as const\n\nexport type PatchOpKind = (typeof PATCH_OP_KINDS)[number]\n\n/**\n * A JSON Pointer (RFC-6901): the empty string, or a string beginning with `/`.\n *\n * The check is deliberately shape-only. Whether the pointer RESOLVES is a fact about a document,\n * which this package cannot see; whether it addresses a region a patch may touch is the fence\n * below. Refusing a malformed pointer here means the applier never has to guess whether `steps/1`\n * meant the root key `steps/1` or the path `/steps/1`.\n */\nconst JsonPointerSchema = z\n .string()\n .refine((value) => value === '' || value.startsWith('/'), {\n message: 'path must be a JSON Pointer: the empty string, or a string starting with \"/\"',\n })\n\n/**\n * The value an `add` or `replace` writes: a string, always.\n *\n * D-02 splits creation away from editing — a whole document is emitted whole and schema-validated,\n * and only subsequent MUTATIONS are patches. A patch that installs a nested collection is a\n * document rewrite wearing an op's clothes: the CST applier can preserve untouched bytes only\n * because every write it performs is one scalar token, so admitting object values here would\n * publish a contract the byte-preservation proof does not cover. A structured step (a `{step,\n * timeout}` mapping) is still editable field-by-field — `/steps/1/step` is a scalar pointer.\n */\nconst PatchValueSchema = z.string()\n\n/**\n * One RFC-6902 op, discriminated on `op`, every arm `.strict()`.\n *\n * `.strict()` is the refusal surface rather than a formality: these objects are authored by a\n * model and cross a trust boundary into a document that decides which app a test drives. An\n * unknown key is a signal the emitter is working from a different contract, and silently dropping\n * it would let that disagreement reach the applier.\n */\nexport const PatchOpSchema = z.discriminatedUnion('op', [\n z.object({\n op: z.literal('add'),\n path: JsonPointerSchema,\n value: PatchValueSchema,\n }).strict(),\n z.object({\n op: z.literal('remove'),\n path: JsonPointerSchema,\n }).strict(),\n z.object({\n op: z.literal('replace'),\n path: JsonPointerSchema,\n value: PatchValueSchema,\n }).strict(),\n])\n\nexport type PatchOp = z.infer<typeof PatchOpSchema>\n\n/**\n * The `{ thoughts, patches }` envelope WTST-07 names.\n *\n * `thoughts` is REQUIRED and may be empty. A set without the field is a different contract, and\n * making it optional would let two emitters disagree about whether the field exists while both\n * validate. An empty `patches` array is ACCEPTED and means \"nothing to change\" — a no-op that\n * renders byte-identical output, never an error, because \"the edit you asked for is already true\"\n * is a legitimate answer for a repair loop to reach.\n */\nexport const TestEditPatchSetSchema = z.object({\n thoughts: z.string(),\n patches: z.array(PatchOpSchema),\n}).strict()\n\nexport type TestEditPatchSet = z.infer<typeof TestEditPatchSetSchema>\n\n/**\n * The document roots a patch may address (T-394-10).\n *\n * `steps` is what a test DOES; `name` and `context` are what it says about itself. Everything\n * else a test document carries — `test-id`, `target`, `use`, `meta`, `setup`, `teardown` — is\n * identity or wiring, and a patch that can reach them is a patch that can silently change which\n * app a test hits or which credentials it runs under. That is a different power from editing what\n * the test does, and the whole point of a whitelist is that the two are not the same grant.\n *\n * RETUNE: admitting a new root widens what a model-emitted pointer can retarget, so a move here is\n * a measurement, not a preference. Before adding one, produce (a) a NAMED authoring case that\n * cannot be expressed inside the current roots — an actual intent the loop failed to satisfy, not\n * a hypothetical; (b) a re-run of the frozen byte-diff corpus with a new refusal cell proving the\n * fence still refuses everything OUTSIDE the widened set, since a fence that only ever passes is\n * unmeasurable; and (c) the answer to what a patch reaching the new root can change about which\n * app the test drives — if the answer is \"something\", the root belongs behind a different grant,\n * not behind this list. Record the case and the corpus numbers beside the frozen expectations.\n */\nexport const EDITABLE_POINTER_ROOTS = ['steps', 'name', 'context'] as const\n\nexport type EditablePointerRoot = (typeof EDITABLE_POINTER_ROOTS)[number]\n\n/**\n * Split a JSON Pointer into its decoded reference tokens (RFC-6901 §3).\n *\n * `~1` decodes to `/` and `~0` to `~`, in that order — reversing them turns `~01` into `/`\n * instead of `~1`. One decoder lives here so the fence below and the applier in `core` cannot\n * disagree about what a pointer addresses, which is the only way a whitelist can be bypassed\n * without anyone editing the whitelist.\n */\nexport function parseJsonPointer(path: string): string[] {\n if (path === '') return []\n return path\n .slice(1)\n .split('/')\n .map((segment) => segment.replaceAll('~1', '/').replaceAll('~0', '~'))\n}\n\n/**\n * The first reference token of a pointer, or `undefined` for the whole-document pointer.\n *\n * `undefined` is not \"no root\" — it is the root, all of it. The fence treats it as outside the\n * editable set for that reason: `` `` addresses the identity fields too.\n */\nexport function pointerRootOf(path: string): string | undefined {\n return parseJsonPointer(path)[0]\n}\n\n/** Whether a pointer addresses a region a patch may touch at all. */\nexport function isEditablePointer(path: string): boolean {\n const root = pointerRootOf(path)\n if (root === undefined) return false\n return (EDITABLE_POINTER_ROOTS as readonly string[]).includes(root)\n}\n","// Where an authored test is written, and the run-evidence coordinate vocabulary (394-06, D-05 · WTST-01).\n//\n// 2026-10-01 (432-17, D-06): the `test-draft` envelope arm this module was named for is deleted with\n// the proposal inbox. An authored test that a keep-gate did not reject is written to its test path in\n// the call that authored it, and the op answers which file it wrote (`TestFileWriteSchema`), so\n// nothing waits for a person to accept it. What survives here is what that write and the run\n// evidence still need: the target path derived from the draft shelf, and the evidence coordinates\n// an authoring result carries. The module keeps its name so its history stays addressable.\n//\n// THE SUITE DIRECTORY IS NOT GUESSED, it is read off the shelf path (see `authoredSuiteTargetPath`).\n\nimport { z } from 'zod'\n\nimport { slugBranch } from '../ids/slug'\n\n/**\n * How long a slugged test name may be before it is cut.\n *\n * RETUNE: raise it if real authored names are being truncated into collisions — the apply refuses\n * a target that already exists, so a collision costs a refusal rather than an overwrite, which is\n * the direction to fail in but not a direction to sit in. It may not become unbounded: this value\n * becomes a filename, and some filesystems still cap a component at 255 bytes.\n */\nexport const AUTHORED_SUITE_SLUG_MAX_LENGTH = 60\n\n/** The name a draft whose test name slugs to nothing at all is filed under. */\nconst AUTHORED_SUITE_FALLBACK_SLUG = 'authored-test'\n\n/**\n * Where an accepted draft is written, derived from where its DRAFT already lives.\n *\n * THE SUITE DIRECTORY IS NOT GUESSED, it is read off the shelf path. A draft is staged at\n * `<suiteDir>/<shelfDir>/<digest>.yaml`, so walking two segments up recovers the directory this\n * project's `workspace.testMatch` actually admits — and a project whose tests live under `e2e/`\n * gets `e2e/<slug>.yaml` without this function knowing that any such project exists. A hardcoded\n * `tests/` here would be a second spelling of a CONFIGURABLE fact, and the first project to\n * configure it differently would have every accepted draft written somewhere its own suite\n * discovery cannot see.\n *\n * The slug goes through {@link slugBranch}, which is the ONE security-reviewed path-segment\n * sanitizer — a model-authored test name reaches this function, so the value that becomes a\n * filename must not be able to name a separator, a parent directory or a hidden file.\n */\nexport function authoredSuiteTargetPath(draftShelfPath: string, testName: string): string {\n const segments = draftShelfPath.split('/').filter((segment) => segment.length > 0)\n const suiteDirectory = segments.slice(0, Math.max(segments.length - 2, 0)).join('/')\n const slug = slugBranch(testName)\n .toLowerCase()\n .slice(0, AUTHORED_SUITE_SLUG_MAX_LENGTH)\n .replace(/[.\\-]+$/, '')\n const name = `${slug.length > 0 ? slug : AUTHORED_SUITE_FALLBACK_SLUG}.yaml`\n return suiteDirectory.length > 0 ? `${suiteDirectory}/${name}` : name\n}\n\n/**\n * Which durable record an evidence coordinate addresses.\n *\n * THE ONE CHANNEL VOCABULARY. The router builds these coordinates and `authoring.draft.write`'s\n * `stop` arm carries them (411 D-07), and the two are the same thing seen from either side of the\n * result — so the words are spelled here, in `schema`, and the router imports them. A second\n * spelling inside `agent` would be free to drift from the one a caller was answered with, which is\n * the drift a wire projection can never detect because both halves would parse.\n */\nexport const RUN_EVIDENCE_CHANNELS = ['step-trace', 'state-before', 'state-after'] as const\n\nexport type RunEvidenceChannel = (typeof RUN_EVIDENCE_CHANNELS)[number]\n\n/**\n * A COORDINATE into a run's own durable records. Never a payload.\n *\n * `.strict()` is the refusal surface: a screen state, an element tree or a rendered snapshot\n * copied onto a stop payload fails to parse here rather than becoming a durable record nobody meant\n * to write. The key set is additionally pinned by equality in `router.test-d.ts`.\n */\nexport const RunEvidenceRefSchema = z.object({\n runId: z.string().min(1),\n filePath: z.string().min(1),\n testName: z.string().min(1),\n stepIndex: z.number().int().nonnegative(),\n /** Absent on the `step-trace` channel, which addresses the whole step. */\n subActionIndex: z.number().int().nonnegative().optional(),\n channel: z.enum(RUN_EVIDENCE_CHANNELS),\n}).strict()\n\nexport type RunEvidenceRef = z.infer<typeof RunEvidenceRefSchema>\n","// The declared fold contracts (2026-08-16, Phase 396 plan 04 — D-01 / D-16 · MCPS-02).\n//\n// WHY THIS FILE IS IN `schema` AND NOT IN `packages/mcp`. A fold is an MCP-surface idea: several\n// sibling registry ops arrive through ONE tool with a discriminated-union input, because the\n// registry is finer-grained than the workflow a caller is actually in (D-01). The natural home for\n// the composition is therefore the MCP package — and it cannot live there. That package's runtime\n// dependency allow-list is exactly the two protocol packages (D-20, enforced by `validate:arch`),\n// deliberately naming no validator library, and composing a discriminated union is a zod operation.\n// The alternative — composing at the JSON-Schema level inside `packages/mcp` — is worse than\n// inconvenient: every arm below is a `.strict()` object, so `additionalProperties: false` would\n// REJECT the discriminant key that a JSON-Schema-level composition had just added to it. A fold\n// built that way would advertise a contract that refuses every call made against it.\n//\n// So the composition happens where zod lives, which is also where this repository mints its DTOs\n// (384 D-16). Nothing here is a new shape: every arm is an op's OWN input DTO with one literal\n// property added, and every fold output is composed from the arms' own output contracts. No field\n// is re-declared, so an arm that gains a field gains it here on the next build.\n//\n// THE DISCRIMINANT VALUE IS THE OP ID. Not a short verb — `'config.field.set'`, not `'set_field'`.\n// That is what makes the tool handler's dispatch mechanical rather than a second lookup table: the\n// handler reads the discriminant, checks it against the tool's DECLARED op set, and invokes exactly\n// that op. A short verb would have needed a verb -> op map somewhere, and a map is a place two\n// spellings of one fact can disagree. The op ids are spelled as literals here because this package\n// may not import the function layer; `packages/mcp`'s bump guard reads them back OUT of the\n// composed schema and compares them against the registry's own enumeration, so the restatement is\n// pinned by a produced-not-literal check rather than trusted.\n\nimport { z } from 'zod'\n\nimport {\n ConfigAuthSetInputSchema,\n ConfigChangeOutputSchema,\n ConfigFieldSetInputSchema,\n ConfigHookAddInputSchema,\n ConfigProjectScaffoldInputSchema,\n ConfigTargetCreateInputSchema,\n ConfigTargetEditInputSchema,\n} from '../config-mutation/actions'\nimport {\n KnowledgeAcceptChangeInputSchema,\n KnowledgeChangeOutputSchema,\n KnowledgeForgetChangeInputSchema,\n KnowledgeRejectChangeInputSchema,\n} from '../knowledge/change'\nimport {\n AuthoringDraftEditInputSchema,\n AuthoringDraftEditOutputSchema,\n AuthoringVerifyDraftInputSchema,\n AuthoringVerifyDraftOutputSchema,\n} from './authoring'\nimport { createOutputContract } from './output-contract'\nimport type { OutputContract } from './output-contract'\nimport {\n RunsArtifactInputSchema,\n RunsArtifactOutputContract,\n RunsEvidenceInputSchema,\n RunsEvidenceOutputContract,\n} from './runs'\n\n/**\n * The key whose literal names which arm a fold call is about.\n *\n * A constant rather than the string `'action'` written at each of its call sites: the key the\n * union discriminates on, the key the tool handler strips, and the key the bump guard reads back\n * are THE SAME key, and two spellings of it would fail as a call that validates and then dispatches\n * nowhere.\n */\nexport const TOOL_FOLD_DISCRIMINANT = 'action'\n\n/**\n * The prose a caller reads about the discriminant, carried ON the schema.\n *\n * D-16's last clause is that human-facing descriptions live on the zod schemas so one source feeds\n * both surfaces. The discriminant is the one field of a fold that no arm DTO can describe — it does\n * not exist until the fold is composed — so if its meaning is not attached here it is attached\n * nowhere, and a caller is left inferring the vocabulary from a `const` list.\n */\nconst DISCRIMINANT_DESCRIPTION =\n 'Which registry operation this call is for. The value is the operation id itself; the rest of '\n + 'the object is that operation\\'s own input.'\n\n/** One arm's discriminant: the op id as a literal, carrying the shared prose. */\nfunction armLiteral<Id extends string>(opId: Id): z.ZodLiteral<Id> {\n return z.literal(opId).describe(DISCRIMINANT_DESCRIPTION)\n}\n\n/**\n * Compose the output a fold advertises from its arms' own output contracts.\n *\n * DEDUPED BY OBJECT IDENTITY, and the collapse is the point rather than an optimisation. The six\n * config actions and the three knowledge changes each answer with literally the same schema\n * object, so a `z.union` over them would advertise `anyOf: [X, X, X, …]` — a document that says\n * nothing the single member does not, while implying to a reader that the arms differ. When the\n * arms genuinely differ (the authoring fold), the union survives and is advertised.\n *\n * Identity and not deep equality: two structurally identical schemas built in two places are\n * exactly the drift D-16 exists to forbid, so collapsing them would hide it.\n */\nfunction foldOutput(arms: readonly z.ZodType[]): z.ZodType {\n const distinct: z.ZodType[] = []\n for (const arm of arms) if (!distinct.includes(arm)) distinct.push(arm)\n const [only] = distinct\n if (only !== undefined && distinct.length === 1) return only\n return z.union(distinct as [z.ZodType, z.ZodType, ...z.ZodType[]])\n}\n\n// ---- `agent_qa_refine_test`: edit an existing test, or verify a draft ---------------------------\n\nconst refineArms = [\n AuthoringDraftEditInputSchema.extend({\n [TOOL_FOLD_DISCRIMINANT]: armLiteral('authoring.draft.edit'),\n }),\n AuthoringVerifyDraftInputSchema.extend({\n [TOOL_FOLD_DISCRIMINANT]: armLiteral('authoring.draft.verify'),\n }),\n] as const\n\n/**\n * The one fold whose arms answer DIFFERENT shapes — an edit proposal on one side, a keep-gate\n * receipt on the other — so its advertised output is a real union rather than a collapsed one.\n */\nexport const AuthoringRefineFoldInputSchema = z.discriminatedUnion(\n TOOL_FOLD_DISCRIMINANT,\n refineArms,\n)\n\nexport type AuthoringRefineFoldInput = z.infer<typeof AuthoringRefineFoldInputSchema>\n\nexport const AuthoringRefineFoldOutputSchema = foldOutput([\n AuthoringDraftEditOutputSchema,\n AuthoringVerifyDraftOutputSchema,\n])\n\n// ---- `agent_qa_change_config`: the six direct config actions -------------------------------------\n\nconst configArms = [\n ConfigFieldSetInputSchema.extend({\n [TOOL_FOLD_DISCRIMINANT]: armLiteral('config.field.set'),\n }),\n ConfigTargetCreateInputSchema.extend({\n [TOOL_FOLD_DISCRIMINANT]: armLiteral('config.target.create'),\n }),\n ConfigTargetEditInputSchema.extend({\n [TOOL_FOLD_DISCRIMINANT]: armLiteral('config.target.edit'),\n }),\n ConfigAuthSetInputSchema.extend({\n [TOOL_FOLD_DISCRIMINANT]: armLiteral('config.auth.set'),\n }),\n ConfigHookAddInputSchema.extend({\n [TOOL_FOLD_DISCRIMINANT]: armLiteral('config.hook.add'),\n }),\n ConfigProjectScaffoldInputSchema.extend({\n [TOOL_FOLD_DISCRIMINANT]: armLiteral('config.project.scaffold'),\n }),\n] as const\n\n/**\n * D-01's own named example, and the reason `.extend()` on the shipped DTOs matters rather than a\n * fresh shape per arm: 395 made every one of these `.strict()` on a stated security argument (an\n * unrecognised key from a model is either a hallucination the op would ignore or a smuggling\n * attempt), and extending preserves that — a `bogus` key is still refused at the boundary, now\n * one layer earlier, by the SDK, before the handler runs.\n */\nexport const ConfigChangeFoldInputSchema = z.discriminatedUnion(\n TOOL_FOLD_DISCRIMINANT,\n configArms,\n)\n\nexport type ConfigChangeFoldInput = z.infer<typeof ConfigChangeFoldInputSchema>\n\n/**\n * 2026-09-30, 432-11 D-05: the six config operations answer what they wrote. 432-12 removed the\n * undo arm, so every arm answers the one change contract and the union collapses to it.\n */\nexport const ConfigChangeFoldOutputSchema = foldOutput(configArms.map(() => ConfigChangeOutputSchema))\n\n// ---- `agent_qa_change_knowledge`: accept, reject, forget, applied in the call (432-12) ------------\n\nconst knowledgeArms = [\n KnowledgeAcceptChangeInputSchema.extend({\n [TOOL_FOLD_DISCRIMINANT]: armLiteral('knowledge.accept'),\n }),\n KnowledgeRejectChangeInputSchema.extend({\n [TOOL_FOLD_DISCRIMINANT]: armLiteral('knowledge.reject'),\n }),\n KnowledgeForgetChangeInputSchema.extend({\n [TOOL_FOLD_DISCRIMINANT]: armLiteral('knowledge.forget'),\n }),\n] as const\n\nexport const KnowledgeChangeFoldInputSchema = z.discriminatedUnion(\n TOOL_FOLD_DISCRIMINANT,\n knowledgeArms,\n)\n\nexport type KnowledgeChangeFoldInput = z.infer<typeof KnowledgeChangeFoldInputSchema>\n\nexport const KnowledgeChangeFoldOutputSchema = foldOutput(\n knowledgeArms.map(() => KnowledgeChangeOutputSchema),\n)\n\n// ---- the run evidence read: a step's parsed evidence, or one of its blobs by sha ---------------\n\n/**\n * Compose a fold's output CONTRACT from its arms' canonical output contracts (431-03).\n *\n * The runtime side is `foldOutput` over the arms' own runtime schemas, so validation is still each\n * arm's exact schema. The document is the arms' own documents under one `anyOf`, in arm order, each\n * without its dialect marker; one distinct arm is simply that arm's contract.\n */\nfunction foldOutputContract(arms: readonly OutputContract[]): OutputContract {\n const distinct: OutputContract[] = []\n for (const arm of arms) if (!distinct.includes(arm)) distinct.push(arm)\n const [only] = distinct\n if (only !== undefined && distinct.length === 1) return only\n const members = distinct.map((arm) => {\n const { $schema: _dialect, ...document } = arm.outputRepresentation\n return document\n })\n return createOutputContract(foldOutput(distinct.map((arm) => arm.runtimeSchema)), {\n $schema: 'https://json-schema.org/draft/2020-12/schema',\n anyOf: members,\n })\n}\n\nconst evidenceArms = [\n // `safeExtend`, not a shape spread: the evidence address carries the ARIA-only sub-action\n // refinement, and a spread into a fresh object would silently drop it.\n RunsEvidenceInputSchema.safeExtend({\n [TOOL_FOLD_DISCRIMINANT]: armLiteral('runs.evidence'),\n }),\n RunsArtifactInputSchema.extend({\n [TOOL_FOLD_DISCRIMINANT]: armLiteral('runs.artifact'),\n }),\n] as const\n\n/**\n * D-07's one evidence read over two ops: a recorded row address answers the parsed, masked\n * document; a sha answers that run's blob. Both arms stay strict.\n */\nexport const RunsEvidenceFoldInputSchema = z.discriminatedUnion(\n TOOL_FOLD_DISCRIMINANT,\n evidenceArms,\n)\n\nexport type RunsEvidenceFoldInput = z.infer<typeof RunsEvidenceFoldInputSchema>\n\nexport const RunsEvidenceFoldOutputContract = foldOutputContract([\n RunsEvidenceOutputContract,\n RunsArtifactOutputContract,\n])\n","// The remote run service's wire vocabulary (Phase 402 plan 01, D-06 / D-13 / D-15 · INVK-03).\n//\n// WHAT LIVES HERE AND WHAT DELIBERATELY DOES NOT. This file holds the vocabulary the authed run\n// service speaks on the wire: the closed error-code set every refusal answers with, the readiness\n// DTO, the request shape, and the door's own contract version. 2026-10-01 (432-21, D-12): the\n// bearer header verdict and its three refusal reasons are deleted with the run-service tokens. It holds no\n// transport, no token, no route and no handler — the router that serves these words lives in\n// `packages/dashboard-server` and the composition that mints them lives in the CLI, because a\n// mountable module (D-02) can only be mountable if its vocabulary is reachable from a package\n// neither of them owns.\n//\n// THE EVENT VOCABULARY IS NOT HERE EITHER, AND THAT ABSENCE IS THE POINT (D-13). The stream serves\n// the frozen bus envelope verbatim — `RunEventEnvelopeSchema`, SSE `id` = `seq`, `event` = `type`.\n// A projection DTO in this file would be a second event vocabulary to drift against the first.\n\nimport { z } from 'zod'\n\n/**\n * The door's own contract version, bumped INDEPENDENTLY of the bus envelope's.\n *\n * Two versions because two contracts move for different reasons: `RUN_EVENT_ENVELOPE_SCHEMA_VERSION`\n * describes the frozen event frame, and this describes what routes exist and what they answer. 403\n * adds the attach contract to this door and will bump THIS constant without touching an envelope.\n *\n * 2026-10-02 (quick 261002-ctr): 2. Version 1 answered readiness with `authConfigured` and refused a\n * request with three bearer reasons; 432-21 deleted the bearer reasons (and added\n * `cross_site_refused`) and 432-22 deleted `authConfigured`. Both changed what these routes answer,\n * so the version moves once for the pair. The routes themselves, the start request and the stream\n * are unchanged.\n */\nexport const RUN_SERVICE_CONTRACT_VERSION = 2\n\n// 2026-10-01 (432-21, D-12): `SERVICE_BEARER_REFUSAL_REASONS`, `ServiceBearerRefusalReason` and the\n// two-arm `ServiceBearerVerdict` are deleted with `services.dashboard.runServiceTokens` and the door's\n// `verifyBearer` port. The door reads no `Authorization` header; what refuses a request before the\n// route table now is the dashboard's same-site guard (`cross_site_refused` below).\n\n/**\n * Every code any non-2xx answer on this door carries. Closed, and shared across all routes.\n *\n * 2026-10-01 (432-21, D-12/D-13): the three bearer refusal reasons left with the bearer, and\n * `cross_site_refused` took their place above the route table. The door answers a request a page on\n * another origin drove — or one naming a Host this loopback server never agreed to answer to — with\n * that word and nothing else, the same word the dashboard's other same-site doors use.\n */\nexport const RUN_SERVICE_ERROR_CODES = [\n 'cross_site_refused',\n 'refused_request_field',\n 'invalid_request_body',\n 'unknown_run',\n 'unknown_route',\n 'run_start_failed',\n 'replay_unavailable',\n // 402-04 (D-14, T-402-14): the `?handle=` parameter's two refusals, kept APART. `invalid_handle`\n // says the parameter was not a canonical non-negative integer — a fact about the caller's own\n // input, which it already has. `unknown_handle` says the parse succeeded and no member of this\n // run answers to it. Both are answered before any stream header, and neither echoes the value.\n 'invalid_handle',\n 'unknown_handle',\n // 403-03 (D-13, T-403-13 · INVK-05): the resume point's two refusals, kept APART on the\n // `invalid_handle`/`unknown_handle` reasoning one line up. `invalid_last_event_id` says the\n // `Last-Event-ID` header or the `?lastEventId=` parameter was not a canonical non-negative\n // integer — a fact about the caller's own input. `replay_floor` says the parse succeeded and the\n // requested point is BELOW what the bus can still replay; it is the one refusal on this door that\n // carries a second key, because the recovery point is the whole reason it exists (see\n // `RunServiceReplayFloorBodySchema`). Both are answered before any stream header.\n 'invalid_last_event_id',\n 'replay_floor',\n // 403-03 (D-03, Q3): the `liveUrl` mint's two host-fact refusals, so BOTH doors answer the same\n // words for the same situation. `live_view_unavailable` is a genuine host fact — no live-view\n // composition, or no origin to build a link against — refused by name rather than answered with\n // a URL that resolves to nothing. `live_url_mint_failed` is the mint's flattened 500, keeping its\n // words to itself exactly as `run_start_failed` does and for the same reason.\n 'live_view_unavailable',\n 'live_url_mint_failed',\n // 402-06 (D-01 discretion, T-402-22): the run was refused before it started — since 432 (D-18)\n // only the production refusal answers it, the policy gate being deleted. A member of the SAME\n // closed set so the code vocabulary stays one vocabulary, but the only code this door answers\n // with a body wider than one key — see `RunServiceDenialBodySchema` for why that widening is\n // sound exactly here and nowhere else.\n 'run_denied',\n] as const\n\nexport type RunServiceErrorCode = (typeof RUN_SERVICE_ERROR_CODES)[number]\n\n/**\n * The ONE error body this door writes — a single key carrying a closed code.\n *\n * ONE KEY, DELIBERATELY. A refusal body that varied its SHAPE by route or by reason would be a\n * fingerprinting surface: a caller refused at the door could learn which routes exist or whether a\n * run id is real by diffing the bodies it is refused with. With one key and a closed vocabulary the\n * only thing that varies is the word, and the word that can appear before the route table is\n * reached is `cross_site_refused` and nothing else.\n *\n * It is also why nothing here echoes the caller's input. Naming the offending field, the run id or\n * anything else would each put an attacker-chosen or a host-held string into a body served to a\n * caller this door has not yet admitted.\n */\nexport const RunServiceErrorBodySchema = z.object({\n error: z.enum(RUN_SERVICE_ERROR_CODES),\n}).strict()\n\nexport type RunServiceErrorBody = z.infer<typeof RunServiceErrorBodySchema>\n\n/**\n * What a RUN DENIAL answers with — the one body on this door wider than a single key (402-06).\n *\n * WHY THE ONE-KEY LAW DOES NOT GOVERN HERE, and this is the whole of the argument. That law exists\n * because a refusal shown to an UNAUTHENTICATED caller must not fingerprint the route map, a run\n * id's existence, or how many credentials are declared — every fact it could carry is a fact the\n * caller has not earned. A run denial is answered only AFTER the same-site guard admitted the\n * caller (since 432-21; before it, after a declared credential matched). The reader is a party this\n * process has already decided to talk to, and telling them nothing but a word turns a\n * decidable situation (\"this project's policy refuses runs of this class from this context\") into\n * an unexplained failure they will retry forever.\n *\n * WHAT IS ON IT, AND WHAT IS DELIBERATELY NOT.\n *\n * `neutralReason` — the run core's plain refusal sentence. Since 432 the only run denial is the\n * production refusal (D-18): it names the target and the one config line that allows it, and it\n * asks the reader to do nothing else.\n *\n * 2026-10-01 (432-19, D-15): there is no `remedies` list. The remedy vocabulary left with the\n * execution gate that minted it, and the production refusal never carried one.\n *\n * No `runId`. A denied run never started; publishing the id the core happened to mint would name\n * a run that does not exist and cannot be streamed.\n */\nexport const RunServiceDenialBodySchema = z.object({\n error: z.literal('run_denied'),\n neutralReason: z.string().min(1),\n}).strict()\n\nexport type RunServiceDenialBody = z.infer<typeof RunServiceDenialBodySchema>\n\n/**\n * What a REPLAY-FLOOR refusal answers with — the second body on this door wider than one key\n * (403-03, D-13 · INVK-05).\n *\n * WHY THE ONE-KEY LAW DOES NOT GOVERN HERE EITHER, on `RunServiceDenialBodySchema`'s exact\n * argument and with one addition of its own. A 410 is answered only AFTER the same-site guard\n * admitted the caller on the run-service door (a declared credential until 432-21), and only behind\n * the bind guard on the local one — the reader is a\n * party this process has already decided to talk to. And what the second key carries is not a host\n * secret: `earliestAvailableSeq` is a fact about the CALLER'S OWN request, namely the point at\n * which the replay it asked for could have been served.\n *\n * THE FIELD IS SPELLED EXACTLY AS `StreamReplayFloorError.earliestAvailableSeq` AND AS THE BUS'S\n * `ReplayIncompleteError.earliestAvailableSeq`, deliberately: the durable reader (`runs.events`)\n * and the live door name the SAME fact, so a client that learned the word once has learned it\n * everywhere.\n *\n * WITHOUT THE NUMBER THE REFUSAL WOULD BE WORSE THAN NOTHING. A caller told only \"gone\" can do one\n * of two things: give up, or retry the identical request forever. The number is what makes the\n * refusal actionable — re-attach with `lastEventId = earliestAvailableSeq - 1`, because the caller\n * names the last envelope it has ALREADY observed and this names the first one still available.\n * That subtraction is stated here, and pinned by a cell that reads the\n * floor out of a real refusal and re-attaches with it.\n */\nexport const RunServiceReplayFloorBodySchema = z.object({\n error: z.literal('replay_floor'),\n earliestAvailableSeq: z.number().int().nonnegative(),\n}).strict()\n\nexport type RunServiceReplayFloorBody = z.infer<typeof RunServiceReplayFloorBodySchema>\n\n/**\n * The request fields this door REFUSES outright (D-07 / D-12, 401's law carried to the wire).\n *\n * A caller may not name the terms of its own authorization, may not choose the identity its\n * run is addressed by, and may not turn up concurrency on a target whose config owner tuned it.\n * The core's own `REFUSED_RUN_REQUEST_FIELDS` refuses `scope` and `executionContext` a layer down;\n * `runId` joins them HERE because the local dashboard door legitimately supplies one (its queue\n * minted the row) and the remote door legitimately does not — the difference is a property of the\n * door, so it is stated at the door.\n */\nexport const RUN_SERVICE_REFUSED_REQUEST_FIELDS = ['runId', 'scope', 'executionContext'] as const\n\n/**\n * What a remote caller may say when starting a run: the pattern set, and nothing else.\n *\n * `.strict()`, so an unrecognised key is a typed refusal rather than a silently ignored request —\n * the same law `RunsStartInputSchema` is under. Absent `patterns` means \"the configured default\n * set\", which is what an argument-less `runs.start` already means.\n */\nexport const RunServiceStartRequestSchema = z.object({\n patterns: z.array(z.string()).optional(),\n}).strict()\n\nexport type RunServiceStartRequest = z.infer<typeof RunServiceStartRequestSchema>\n\n/**\n * What `/ok` reports (D-15): measured facts, and no prediction.\n *\n * SHALLOW BUT HONEST. Each field is something this process can observe about ITSELF right now —\n * the service answered, a host is composed, and which contract version these routes implement.\n * 2026-10-01 (432-22, D-12): `authConfigured` is deleted with `services.dashboard.runServiceTokens`.\n * No credential can be configured, so it had read `false` on every answer since 432-21, and a\n * fact that cannot vary is not a measurement. There is no `ready: true`, because a run's success depends on a\n * browser, a model, a network and a target, none of which this route touched. Deep diagnostics\n * (knowledge rungs, embedder health) belong to 407's `doctor` and are deliberately absent.\n *\n * `hostComposed` is measured off the SAME state the invoke path's guard throws on, so a `/ok` that\n * says the host is composed and a `POST /run` that says it is not cannot disagree.\n */\nexport const RunServiceReadinessSchema = z.object({\n service: z.literal('up'),\n hostComposed: z.boolean(),\n contractVersion: z.literal(RUN_SERVICE_CONTRACT_VERSION),\n}).strict()\n\nexport type RunServiceReadiness = z.infer<typeof RunServiceReadinessSchema>\n","// The mixed-verdict suite-stability read (394, D-14 · WTST-05).\n//\n// WHAT IT IS FOR. Gate 2 flips: the draft passed on one run and failed on another, so the keep\n// filter rejects it. The naive answer is to discard the draft silently, and it is the wrong one\n// often enough to matter — a target whose EXISTING tests are already flaky or quarantined is a\n// target where the application is unstable, and the honest message names that rather than telling\n// an author their test was no good. \"Your app is unstable here, and these are the neighbours that\n// say so\" and \"your draft did not pass\" are two different sentences, and the author can only act\n// on one of them.\n//\n// (That pair is spelled as two quoted clauses joined by `and`, never with the import keyword\n// between a word and a quoted phrase, because the arch dependency scan reads import specifiers\n// out of RAW BYTES with comments included, and prose shaped like a specifier is reported as an\n// undeclared external dependency. Fourth occurrence of that trap in this phase, all four in\n// prose — and the fifth was this very paragraph, when it first illustrated the shape verbatim.)\n//\n// IT STARTS ZERO RUNS, AND THAT IS THE WHOLE REASON D-14 IS READ-SIDE. WTST-08's fan-out preview\n// promises a bound before dispatch and the receipt reports what was spent; a stability check that\n// took its own runs would make the preview a number nobody could honour. Everything below is a\n// pure fold over evidence the project ALREADY has — the run-outcome projection and the quarantine\n// ledger — which is why it lives in `schema` and takes rows rather than ports.\n//\n// A DEGRADED POSTURE STATED IS NOT A CLEAN BILL OF HEALTH. A target with no history gets\n// `no-history` and says so. Returning `stable` for a target nothing has ever observed would be a\n// wrong answer wearing a correct one's clothes, and it is the one this vocabulary exists to make\n// unrepresentable: `stable` means evidence was read and it said stable.\n//\n// THE RESULT NAMES ITS EVIDENCE. `flakyNeighbours` carries identities, not a count and not a\n// boolean — an author told \"some neighbours are flaky\" cannot go and look, and the whole value of\n// this branch is that they can.\n\n/**\n * The CLOSED posture vocabulary. Three members, and none of them covers another.\n *\n * `stable` the target's existing tests were read and none is flaky or quarantined.\n * `neighbours-flaky` at least one existing test flips or sits in quarantine — the app is the\n * likelier explanation for the draft's own flip.\n * `no-history` nothing has ever been observed about this target. Honestly degraded.\n */\nexport const SUITE_STABILITY_POSTURES = ['stable', 'neighbours-flaky', 'no-history'] as const\n\nexport type SuiteStabilityPosture = (typeof SUITE_STABILITY_POSTURES)[number]\n\n/** Why one neighbour counts as unstable. Closed, because the message names the reason. */\nexport const NEIGHBOUR_INSTABILITY_REASONS = ['quarantined', 'verdict-flip'] as const\n\nexport type NeighbourInstabilityReason = (typeof NEIGHBOUR_INSTABILITY_REASONS)[number]\n\n/**\n * One existing test in the target suite, with what the project already knows about it.\n *\n * `outcomes` are recorded MEMBER outcomes, newest last, in the run store's own words — a free\n * string rather than an enum for the reason `GateRunRecord.memberOutcome` is one: the runner\n * owns that vocabulary and grows it, and a closed copy here would read a newer runner's outcome\n * as unknown. More than one DISTINCT value is a flip; the values themselves are never compared\n * against a member list this file maintains.\n *\n * An EMPTY `outcomes` array is \"nothing recorded\", never \"recorded as fine\".\n */\nexport interface SuiteNeighbourRow {\n readonly filePath: string\n readonly testName: string\n readonly outcomes: readonly string[]\n readonly quarantined: boolean\n}\n\n/** One named neighbour, with the reason and the evidence that produced it. */\nexport interface FlakyNeighbour {\n readonly filePath: string\n readonly testName: string\n /**\n * The `entities.resolve` reference, spelled `<filePath>::<testName>`.\n *\n * Deliberately NOT a `TST-###` short-ID: a short-ID exists only once something has sighted the\n * entity, and no `TST` sighting source is wired on any host in this build — so printing one\n * would publish an address that resolves to nothing (ENTY-01's never-guess law).\n */\n readonly ref: string\n readonly reason: NeighbourInstabilityReason\n /** The distinct outcomes observed, when the reason is a flip. Empty for a quarantine entry. */\n readonly distinctOutcomes: readonly string[]\n}\n\nexport interface SuiteStabilityAssessment {\n readonly posture: SuiteStabilityPosture\n /** NAMED, never counted. Empty for `stable` and for `no-history`. */\n readonly flakyNeighbours: readonly FlakyNeighbour[]\n /** The sentence a surface prints. One producer, so chat and the CLI say the same thing. */\n readonly message: string\n}\n\nexport interface SuiteStabilityInput {\n /** The suite file the draft targets — what the message names. */\n readonly targetFilePath: string\n /** The target's EXISTING tests. Empty means the target has no existing tests at all. */\n readonly neighbours: readonly SuiteNeighbourRow[]\n}\n\n/** `<filePath>::<testName>` — the one spelling, minted here so no surface invents a second. */\nexport function suiteTestRef(filePath: string, testName: string): string {\n return `${filePath}::${testName}`\n}\n\nfunction classify(row: SuiteNeighbourRow): FlakyNeighbour | undefined {\n const distinct = [...new Set(row.outcomes)]\n // QUARANTINE FIRST. A quarantined test may well have a single recorded outcome — that is what\n // quarantining it achieved — so reading the outcomes first would report it stable.\n if (row.quarantined) {\n return {\n filePath: row.filePath,\n testName: row.testName,\n ref: suiteTestRef(row.filePath, row.testName),\n reason: 'quarantined',\n distinctOutcomes: [],\n }\n }\n if (distinct.length > 1) {\n return {\n filePath: row.filePath,\n testName: row.testName,\n ref: suiteTestRef(row.filePath, row.testName),\n reason: 'verdict-flip',\n distinctOutcomes: distinct,\n }\n }\n return undefined\n}\n\n/**\n * Assess the target's existing tests. PURE, TOTAL, AND IT STARTS NOTHING.\n *\n * Order of decision, and it is order-sensitive exactly as written: any flaky neighbour wins,\n * because one unstable neighbour is enough to make the application the likelier explanation.\n * Only when nothing is flaky does the absence of evidence get to speak.\n */\nexport function assessSuiteStability(input: SuiteStabilityInput): SuiteStabilityAssessment {\n const flakyNeighbours = input.neighbours\n .map(classify)\n .filter((row): row is FlakyNeighbour => row !== undefined)\n\n if (flakyNeighbours.length > 0) {\n const named = flakyNeighbours\n .map((row) => `${row.ref} (${row.reason})`)\n .join(', ')\n return {\n posture: 'neighbours-flaky',\n flakyNeighbours,\n message:\n `Your app is unstable at ${input.targetFilePath}: ${flakyNeighbours.length} existing `\n + `test${flakyNeighbours.length === 1 ? '' : 's'} there already flip or sit in `\n + `quarantine — ${named}. The draft's own verdict flip is more likely the application `\n + 'than the draft.',\n }\n }\n\n const observed = input.neighbours.some((row) => row.outcomes.length > 0)\n if (!observed) {\n return {\n posture: 'no-history',\n flakyNeighbours: [],\n message:\n `No stability history for ${input.targetFilePath}: nothing here has a recorded outcome `\n + 'yet, so there is no evidence either way about whether the application is stable. This '\n + 'is a degraded read, not a clean bill of health.',\n }\n }\n\n return {\n posture: 'stable',\n flakyNeighbours: [],\n message:\n `The existing tests at ${input.targetFilePath} have stable recorded outcomes and none is `\n + 'quarantined, so the draft\\'s verdict flip is not explained by its neighbours.',\n }\n}\n","// Procedure-by-reference: the anchor vocabulary a compiled step is authored in (394, D-17).\n//\n// D-17 makes a procedure reference SEMANTIC rather than syntactic. The compiled draft carries an\n// ordinary natural-language step; at run time the shipped `getProcedure` seam matches that step\n// against the live procedure record and replays it. A later procedure fix therefore propagates,\n// because replay always reads the CURRENT record — and the committed test stays pure house-style\n// prose a person can read without knowing this mechanism exists. There is no `procedure:` literal\n// syntax, no parser change and no doc-model change: the whole reference is which WORDS the step\n// is written in.\n//\n// THE INPUT IS AN ANCHOR AND NOTHING ELSE, AND THAT IS THE MITIGATION (T-394-38). A served\n// procedure arrives as a `ProcedureMatch`, which carries `id` — a learned-shelf record id whose\n// supersession, withholding and garbage collection this project performs on its own schedule. An\n// authored test lives on the SOVEREIGN shelf and outlives every one of those events, so an id\n// embedded in it would rot: the record it names can be superseded or collected, and the committed\n// file would then point at something that is not there. Taking only the anchor makes that\n// structurally impossible rather than checked — there is no id in this function's argument to\n// leak, so no call site can leak one by accident.\n//\n// WHY THE ANCHOR IS ALSO THE RIGHT VOCABULARY, measured rather than assumed. `matchProcedure`\n// admits a candidate on anchor overlap and then folds the STEP TEXT in as a lexical term, so a\n// step written in the record's own words reaches a higher composed confidence than one written in\n// unrelated words — high enough, on a partially-matched anchor set, to cross the replay floor\n// instead of degrading to a hint. The knowledge-local suite drives both directions through the\n// real matcher.\n\nimport type { Anchor } from '../identity/anchor'\n\n/**\n * The words a compiled step should be authored in, for one anchor.\n *\n * An EXHAUSTIVE switch rather than a lookup with a fallback, on `renderResolution`'s precedent: a\n * seventh anchor arm is a compile error here instead of a silently unrendered case that would\n * degrade to an empty vocabulary — which reads, at the prompt, exactly like a procedure with\n * nothing to say about itself.\n *\n * Every arm renders the anchor's OWN words and adds none. A phrase invented here would be a\n * second vocabulary for one record, free to drift out of step with what the matcher scores.\n */\nexport function procedureStepVocabulary(anchor: Anchor): string {\n switch (anchor.t) {\n case 'flow':\n return anchor.name\n case 'page':\n return anchor.route\n case 'el':\n return `${anchor.role} ${anchor.name}`\n case 'platform':\n return anchor.platform\n case 'selector':\n return anchor.literal\n case 'error':\n return anchor.message\n }\n}\n","// The card ↔ dashboard-route contract (Phase 400 plan 08, DASH-03 · 387 ENTY-02 / D-10).\n//\n// WHY THIS IS IN `schema` AND NOT IN THE DASHBOARD. Verbatim `url.ts`'s reasoning for\n// `ENTITY_URL_ROUTE`: \"the M5 route table imports this constant, so 'the dashboard's routes and the\n// cards' links agree' is ONE declaration rather than two that were written from the same sentence.\"\n// The same sentence has three readers now — the dashboard's renderer, which mints hrefs from it;\n// the conformance scenario table, whose entity-card cases are built OVER it; and the parity cells\n// on both doors, which join against it. Three copies of a route table is three places a kind can\n// quietly acquire or lose a page, with nothing comparing them.\n//\n// AND IT IS A CONTRACT, NOT A FIXTURE. What a kind's card links to is a published fact about this\n// product's surfaces — the same class of fact as `ENTITY_URL_ROUTE` and `ENTITY_URI_SEGMENTS`, both\n// of which already live here. A test-only table would have made the parity suite's idea of the\n// routes the subject and left the shipped ones unmeasured.\n//\n// THE `null` ARM IS THE HONEST ONE (D-10). A kind with no page here says so, and every reader is\n// obliged to render nothing rather than a link — not a disabled anchor, not a `#`, not the card's\n// own `url`, which addresses `ENTITY_URL_ROUTE`'s M5 shape that no build serves yet. \"A card that\n// carried a link to a route nothing serves would be a dead link shown with confidence.\"\n\nimport type { EntityKind } from './kinds'\n\n/**\n * WHICH address fills a route's parameter — the grain a link is keyed by.\n *\n * Declared rather than left implicit because it is the whole of the dead-link question. A test's\n * page is keyed by its MACHINE ID (`/test/t-irish-vise-s`) while a card's `id` is its published\n * short-ID (`TST-001`) — a different address in a different namespace — so a table that said only\n * \"routed\" would be satisfied by a link that 404s. `no-parameter` is a real third answer and not a\n * degenerate one: a target's page is the config surface, which is why `TGT` can route from an\n * address alone where `TST` and `RUN` cannot.\n */\nexport const ENTITY_DASHBOARD_ROUTE_GRAINS = [\n 'machine-id',\n 'no-parameter',\n 'unrouted',\n] as const\n\nexport type EntityDashboardRouteGrain = (typeof ENTITY_DASHBOARD_ROUTE_GRAINS)[number]\n\nexport interface EntityDashboardRoute {\n /**\n * The route TEMPLATE, or `null` for a kind this dashboard has no page for.\n *\n * A template rather than a rendered path, on `ENTITY_URL_ROUTE`'s reasoning: a router consumes\n * the template and a card consumes the rendering, and both have to be able to name the same\n * thing.\n */\n readonly route: string | null\n readonly keyedBy: EntityDashboardRouteGrain\n}\n\n/**\n * THE per-kind table, total over `EntityKind`.\n *\n * `as const satisfies Record<EntityKind, …>` is the completeness guarantee every other per-kind\n * table in this directory carries: a sixth kind is a compile error here rather than a kind whose\n * card silently renders whichever arm a lookup happened to miss. There is deliberately no fallback.\n *\n * The three routed paths are the ones `dashboard-ui/src/app.tsx` registers today. The two `null`\n * arms are not placeholders: `MEM`/`POL` have no page in this build. They are also the arms that\n * matter most to measure —\n * a `MEM` card in dashboard chat DOES carry a `url` (400-01's D-16 overlays a base for any\n * conversation the dashboard serves) and must still offer nothing to click.\n */\nexport const ENTITY_DASHBOARD_ROUTES = {\n TST: { route: '/test/:t_id', keyedBy: 'machine-id' },\n RUN: { route: '/runs/:id', keyedBy: 'machine-id' },\n MEM: { route: null, keyedBy: 'unrouted' },\n POL: { route: null, keyedBy: 'unrouted' },\n TGT: { route: '/config', keyedBy: 'no-parameter' },\n} as const satisfies Record<EntityKind, EntityDashboardRoute>\n\n/** Does this build serve a page for that kind? The one predicate, so nobody re-derives it. */\nexport function isRoutedEntityKind(kind: EntityKind): boolean {\n return ENTITY_DASHBOARD_ROUTES[kind].route !== null\n}\n","// The card's `url` contract — the M5 route shape, pinned now (Phase 387, ENTY-02 / D-10).\n//\n// D-10 says the field is CONFIG-DERIVED and ABSENT by default, and that the shape is pinned\n// in v52 so M5 builds routes to match the cards rather than the other way round. Pinning it\n// here — in `schema`, beside the card contract the field lives on — rather than inside the\n// producer is what makes that promise reachable: the M5 route table imports this constant, so\n// \"the dashboard's routes and the cards' links agree\" is one declaration rather than two that\n// were written from the same sentence.\n//\n// The route is a TEMPLATE with named parameters rather than a formatting function's private\n// string, because a router consumes the template and a card consumes the rendering, and both\n// have to be able to name the same thing.\n\nimport { slugBranch } from '../ids/slug'\nimport { ENTITY_URI_SEGMENTS } from './kinds'\nimport type { EntityKind } from './kinds'\n\n/**\n * THE canonical entity route (D-10, spec `…/t/<ws>/<kind>/<short-id>/<slug>`).\n *\n * The `:kind` segment is the URI-SEGMENT word (`memory`, not `MEM`), the same vocabulary\n * `agentqa://` uses, so a reader who has seen one address form can read the other. `:slug` is\n * decorative — the address is `:kind` + `:shortId`, and the slug exists so a pasted link says\n * what it points at.\n */\nexport const ENTITY_URL_ROUTE = '/t/:workspace/:kind/:shortId/:slug'\n\n/** The route's parameters, in the order they appear. Exported so a router can check itself. */\nexport const ENTITY_URL_ROUTE_PARAMS = ['workspace', 'kind', 'shortId', 'slug'] as const\n\n/**\n * The slug's length cap.\n *\n * A cap rather than no cap because a title is free text and a bundle summary can be a\n * sentence; a link whose decorative tail is longer than the message it was pasted into is\n * worse than one that is truncated. Retune from what real titles look like.\n */\nexport const ENTITY_URL_SLUG_MAX_LENGTH = 60\n\n/**\n * The title → slug rendering.\n *\n * Delegates to `slugBranch`, which is the repo's ONE security-reviewed path-segment\n * sanitizer (D-07 / T-360-03). Writing a second one here would be a second answer to\n * \"what characters may appear in a segment\", and a URL segment is exactly the place a\n * traversal sequence would be worth smuggling. Its `default` fallback for an empty result is\n * kept verbatim for the same reason: one sanitizer, one fallback.\n *\n * Lower-cased after sanitising, and only after: case folding is a display convention for\n * links, while the sanitiser's job is which BYTES are legal, and doing them in one pass would\n * make the security rule depend on the cosmetic one.\n */\nexport function entityTitleSlug(title: string): string {\n return slugBranch(title).toLowerCase().slice(0, ENTITY_URL_SLUG_MAX_LENGTH)\n}\n\nexport interface EntityUrlInput {\n /** The configured dashboard base. An origin, or an origin with a path prefix. */\n readonly baseUrl: string\n readonly workspace: string\n readonly kind: EntityKind\n readonly shortId: string\n readonly title: string\n}\n\n/**\n * Render one entity's dashboard URL, or `undefined` when the inputs cannot produce an honest\n * one.\n *\n * ABSENCE IS A RESULT, never a throw and never a partial link. D-10's whole point is that a\n * card never shows a dead link, so a base that does not parse, a base with no host, and an\n * empty workspace all come back `undefined` — and the producer then omits the field, which is\n * the same state as \"no dashboard is configured\". A caller cannot tell the two apart, and\n * deliberately so: both mean \"there is no page to send you to\".\n *\n * The base's query and fragment are dropped rather than merged. A base carrying either is a\n * configuration mistake, and inheriting it onto every entity link would propagate the mistake\n * to every card instead of to the one place it was written.\n */\nexport function formatEntityUrl(input: EntityUrlInput): string | undefined {\n if (input.workspace.trim() === '') return undefined\n\n let base: URL\n try {\n base = new URL(input.baseUrl)\n } catch {\n return undefined\n }\n if (base.host === '') return undefined\n\n const path = ENTITY_URL_ROUTE\n .replace(':workspace', encodeURIComponent(input.workspace))\n .replace(':kind', ENTITY_URI_SEGMENTS[input.kind])\n .replace(':shortId', encodeURIComponent(input.shortId))\n .replace(':slug', encodeURIComponent(entityTitleSlug(input.title)))\n\n const prefix = base.pathname.replace(/\\/+$/u, '')\n base.pathname = `${prefix}${path}`\n base.search = ''\n base.hash = ''\n return base.toString()\n}\n","// Entity resolution results (Phase 387, ENTY-01 / ENTY-02 / D-09).\n//\n// TWO unions, and the split is what makes ENTY-02's one-producer claim testable rather than\n// aspirational.\n//\n// `EntityResolution` — DESCRIPTOR-level. What the store layer computes and what the\n// injected directory port returns. It carries the facts about an\n// entity and renders nothing.\n// `EntityCardResolution` — CARD-level. What `entities.resolve` answers with, produced by\n// the single card producer in the function layer.\n//\n// Collapsing them into one union would have put card construction inside `knowledge-local`,\n// and \"exactly one producer\" would then have meant \"one producer plus whatever the store\n// happened to build\", which is not a claim any test can pin. With the split, the store layer\n// has no vocabulary for a card at all.\n//\n// Three arms, closed, per D-09 — a hit, a small disambiguation set, or an honest miss. There\n// is deliberately no \"best effort\" arm: under ENTY-01's never-guess contract, weaker\n// retrieval may only produce MORE disambiguation, never a different silent answer, and an\n// arm that meant \"probably this one\" would be exactly the silent answer the contract forbids.\n\nimport { z } from 'zod'\n\nimport { EntityCardSchema } from './entity-card'\nimport { ENTITY_KINDS } from './kinds'\nimport { EntityUriSchema } from './uri'\n\n/**\n * The disambiguation set is small ON PURPOSE (D-09: \"top-3\").\n *\n * A long list is not disambiguation, it is a search result — and the moment a caller has to\n * scroll it, the surface has quietly handed the never-guess decision back to a human who has\n * less context than the resolver did. Retune from what real ambiguous references look like,\n * never to accommodate a weaker ranker.\n */\nexport const ENTITY_RESOLUTION_MAX_CANDIDATES = 3\n\n/** The score tier (a) answers with: an address that parsed and matched is not a guess. */\nexport const ENTITY_EXACT_MATCH_SCORE = 1\n\n/**\n * Why a reference resolved to nothing. A bare `none` would have collapsed two genuinely\n * different situations — a well-formed address for an entity that was never minted, and text\n * that matched no addressing rule at all — into one answer, and a surface cannot phrase a\n * useful message without knowing which one it holds.\n */\nexport const ENTITY_NO_MATCH_REASONS = [\n 'unknown-address',\n 'no-match',\n] as const\n\nexport type EntityNoMatchReason = (typeof ENTITY_NO_MATCH_REASONS)[number]\n\n/**\n * What the store layer knows about one entity: its address, the machine id that address maps\n * FROM, a human title, and the status the owning store reports.\n *\n * `statusSource` is a plain string rather than the card's closed per-kind union, and that is\n * the render-never-recompute boundary in type form: the store reports what it observed, and\n * the producer is where an unrecognised status is REFUSED by the schema (D-12) instead of\n * being silently mapped to something plausible.\n */\nexport const EntityDescriptorSchema = z.object({\n kind: z.enum(ENTITY_KINDS),\n shortId: z.string().min(1),\n uri: EntityUriSchema,\n machineId: z.string().min(1),\n title: z.string(),\n statusSource: z.string().min(1),\n /**\n * The machine id this entity was explicitly RENAMED to, when a rename was recorded (D-03).\n *\n * Present only for an address whose successor was written down — never inferred from two\n * similar names. The predecessor keeps its own permanent address and keeps resolving; this\n * field is what lets a card SHOW the rename rather than silently redirecting to the\n * successor, which would make an old CI log's reference quietly mean something else.\n */\n successorMachineId: z.string().min(1).optional(),\n /**\n * The DURABLE test identity a `TST` entity's store keyed it on (Phase 390, D-12).\n *\n * `(product, filePath, testName)` — the same three legs the run-outcome projection and the\n * quarantine ledger are keyed by, and never `testId`, which is a per-run explicit id. It is\n * reported BESIDE `machineId` rather than parsed out of it: the two answer different\n * questions, and a card that recovered an identity by splitting a machine id would be\n * guessing at a format no producer has agreed to.\n *\n * OPTIONAL because a store may not know it. A `TST` descriptor without it renders `active`,\n * which is the honest answer for a store that cannot say whether this test is quarantined —\n * matching it from the title instead would be exactly the plausible-but-wrong attribution\n * D-12 refuses. Absent for every other kind by construction: nothing else has a test identity.\n */\n testIdentity: z.object({\n product: z.string().min(1),\n filePath: z.string().min(1),\n testName: z.string().min(1),\n }).strict().optional(),\n}).strict()\n\nexport type EntityDescriptor = z.infer<typeof EntityDescriptorSchema>\n\nconst scoreSchema = z.number().min(0).max(1)\n\nconst noneArm = z.object({\n kind: z.literal('none'),\n reason: z.enum(ENTITY_NO_MATCH_REASONS),\n /** The nearest address worth offering, when one exists. Never auto-applied. */\n closestSuggestion: z.string().min(1).optional(),\n}).strict()\n\nexport const EntityResolutionSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('resolved'),\n descriptor: EntityDescriptorSchema,\n score: scoreSchema,\n }).strict(),\n z.object({\n kind: z.literal('ambiguous'),\n candidates: z.array(\n z.object({ descriptor: EntityDescriptorSchema, score: scoreSchema }).strict(),\n ).min(2).max(ENTITY_RESOLUTION_MAX_CANDIDATES),\n }).strict(),\n noneArm,\n])\n\nexport type EntityResolution = z.infer<typeof EntityResolutionSchema>\n\nexport const EntityCardResolutionSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('resolved'),\n card: EntityCardSchema,\n score: scoreSchema,\n }).strict(),\n z.object({\n kind: z.literal('ambiguous'),\n candidates: z.array(\n z.object({ card: EntityCardSchema, score: scoreSchema }).strict(),\n ).min(2).max(ENTITY_RESOLUTION_MAX_CANDIDATES),\n }).strict(),\n noneArm,\n])\n\nexport type EntityCardResolution = z.infer<typeof EntityCardResolutionSchema>\n\n/** `entities.resolve` input: any reference at all — short-ID, URI, or free text. */\nexport const EntitiesResolveInputSchema = z.object({\n ref: z.string().min(1),\n}).strict()\n\nexport type EntitiesResolveInput = z.infer<typeof EntitiesResolveInputSchema>\n\n/** `entities.get` input: an EXACT address. The simple read path 396 projects onto. */\nexport const EntitiesGetInputSchema = z.object({\n ref: z.string().min(1),\n}).strict()\n\nexport type EntitiesGetInput = z.infer<typeof EntitiesGetInputSchema>\n","// The chat session log's event grammar (Phase 392, CHAT-05 / D-14 / D-18).\n//\n// MINTED IN SCHEMA, on the `run-notification.ts` precedent and for its stated reason rather than\n// by analogy: several packages read these bytes and none may import another. `agent` emits them\n// from the turn engine, `agent-local` writes and re-reads them as JSONL, `cli` renders them, and\n// M5's dashboard will parse the same file. A grammar that lived beside any one consumer would be\n// re-derived by the next, and the two spellings would drift on the first field either wanted.\n//\n// THE EVENT KIND UNION IS CLOSED AND COMPLETE FROM DAY ONE, including the kinds nothing emits\n// yet. CHAT-05 names `model_change`, `active_tools_change`, `compaction` and `aborted` as members\n// of the log grammar; declaring them late would make \"this build does not know that kind\" and\n// \"that kind did not occur\" the same bytes for every reader written in between — which is exactly\n// the ambiguity a versioned, append-only log exists to avoid.\n//\n// MAP, NOT TERRITORY (D-18). An event carries REFS and one-line summaries, never payload bodies.\n// The one exception is chat's own content: a user message IS the thing chat is a record of, so its\n// text is logged. A knowledge record, a config file's contents, a tool result — those live in\n// their own stores and appear here as an id and a sentence. The rule is not about size. It is that\n// this file is read by surfaces that render it directly, so a field that could carry a secret\n// would need a masking boundary at every one of them.\n\n/**\n * Stamped into the header line and checked before any shape question on reopen.\n *\n * A literal type rather than `number` (the `RunNotification` idiom): a header built with last\n * version's shape fails to typecheck at its construction site, which is where the mistake is,\n * rather than at a reader that could only report it as corrupt bytes.\n */\nexport const CURRENT_CHAT_SESSION_SCHEMA_VERSION = 2\n\n/**\n * The first line of every session file, written and fsynced when the file is created.\n *\n * `model` and `toolsetHash` are the session's opening CONTEXT, not its running state: the log's\n * `model_change` and `active_tools_change` events carry drift from here onwards, so a reader\n * reconstructs \"what was in force at turn N\" by folding events over this header. Rewriting the\n * header on drift would make the file no longer append-only, which is the one property CHAT-05\n * asks for by name.\n */\nexport interface ChatSessionHeader {\n schemaVersion: typeof CURRENT_CHAT_SESSION_SCHEMA_VERSION\n sessionId: string\n createdAt: string\n model: string\n toolsetHash: string\n /**\n * WHICH DOOR OPENED THIS CONVERSATION (Phase 400, D-04) — optional, and on the HEADER.\n *\n * D-04 puts dashboard chat on this exact substrate \"tagged with their surface\". The obvious\n * spelling is a field on each event, and it is the one thing this grammar cannot have: the guard\n * below compares an EXACT key set per kind, so an extra field on any event kind makes every\n * session file written before it unreadable by the build that comes after. The header's own\n * guard is presence-based and tolerates keys it does not know, so the tag rides here, is written\n * ONCE at create with the rest of the opening context, and never rewritten.\n *\n * ABSENT IS A REAL VALUE AND IT IS THE DEFAULT: a session opened by a host that did not name its\n * surface. That is every file written before Phase 400 and every `agent-qa chat` session written\n * after it — one population, not two, which is what keeps the absence unambiguous. Only a host\n * that has a reason to distinguish itself supplies one, and `agent-qa dashboard` is the first.\n *\n * A PLAIN STRING RATHER THAN A CLOSED UNION, deliberately. The value is the surface's own name —\n * the same word `FunctionCaller.surface` carries for the same door — and the surface roster grows\n * by design (four doors today). A union here would make a session file written by a later build\n * fail to typecheck against an older one for a field no decision is taken on: nothing branches on\n * this value, it is a fact for a reader and a listing filter.\n */\n surface?: string\n}\n\n/**\n * Every kind of thing that can happen to a session, spelled ONCE (388 C13).\n *\n * Ordered by the turn they belong to rather than alphabetically, because the order is the shape\n * of a turn and a reader of this list should be able to see one.\n */\nexport const CHAT_SESSION_EVENT_KINDS = [\n 'user_message',\n 'stage_outcome',\n 'clause_receipt',\n 'clause_result',\n 'approval_decision',\n 'mark_unhandled',\n 'model_change',\n 'active_tools_change',\n 'compaction',\n 'aborted',\n 'turn_complete',\n] as const\n\nexport type ChatSessionEventKind = (typeof CHAT_SESSION_EVENT_KINDS)[number]\n\n/**\n * The four-stage routing contract's stages, named rather than numbered in the log.\n *\n * A number would be a position in a pipeline whose length is a design decision; a name survives\n * a stage being inserted, and a reader six months from now can tell which stage answered without\n * the contract in front of them.\n */\nexport const CHAT_TURN_STAGES = ['resolver', 'planner', 'reconcile', 'execute'] as const\n\nexport type ChatTurnStage = (typeof CHAT_TURN_STAGES)[number]\n\n/**\n * What a stage did with the turn.\n *\n * `skipped` is a first-class outcome and not an absence: a turn every clause of which the\n * deterministic table resolved does not consult the planner at all, and that is the tracer's whole\n * point (D-01/D-06 — the LLM is never touched). Logging nothing would make a skipped planner and\n * an unbound one identical in the record.\n */\nexport const CHAT_STAGE_OUTCOMES = ['resolved', 'skipped', 'unresolved'] as const\n\nexport type ChatStageOutcome = (typeof CHAT_STAGE_OUTCOMES)[number]\n\n/** How a turn ended (the value `turn_complete` carries, and the `agent.ask` result's status). */\nexport const CHAT_TURN_STATUSES = ['completed', 'failed', 'fail_closed'] as const\n\nexport type ChatTurnStatus = (typeof CHAT_TURN_STATUSES)[number]\n\n/**\n * The fields EVERY event carries, whatever its kind.\n *\n * `turnId` is on the base rather than per-kind because the log's primary read is \"show me that\n * turn\", and a kind that could omit it would be a hole in exactly that read. Session-scoped facts\n * that arrive between turns (a config re-read on open) carry the id of the turn they precede.\n */\nexport interface ChatSessionEventBase<K extends ChatSessionEventKind> {\n kind: K\n turnId: string\n at: string\n}\n\n/**\n * What the person typed, verbatim.\n *\n * The ONE payload body in this vocabulary, and the exception is principled: the utterance is not\n * a reference to content held elsewhere, it IS the content, and a session log that recorded\n * \"the user said something\" would not be the triage report D-18 asks for.\n */\nexport interface ChatUserMessageEvent extends ChatSessionEventBase<'user_message'> {\n text: string\n}\n\n/** Which stage answered, and how. One event per stage the turn actually reached. */\nexport interface ChatStageOutcomeEvent extends ChatSessionEventBase<'stage_outcome'> {\n stage: ChatTurnStage\n outcome: ChatStageOutcome\n}\n\n/**\n * One clause's trip through the function layer, as a REF and a sentence.\n *\n * `functionId` addresses the op; `outcome` is a ONE-LINE human summary; the result itself stays\n * wherever the op put it. `origin` records which caller the composition MINTED for this clause\n * (391 D-06, RESEARCH Pitfall 1) — a deterministic table hit is a person typing, a planner-planned\n * call is not, and the difference is a permission fact worth having in the record.\n */\nexport interface ChatClauseReceiptEvent extends ChatSessionEventBase<'clause_receipt'> {\n clause: string\n functionId: string\n origin: string\n status: string\n outcome: string\n}\n\n/**\n * WHAT ONE CLAUSE'S OP RETURNED — the turn's `results[]` entry, MASKED (399.1, D-05).\n *\n * THE SECOND PAYLOAD BODY IN THIS VOCABULARY, and like the first it is stated as an exception\n * rather than smuggled in. D-18's rule above is that an event carries REFS and one-line summaries,\n * because \"this file is read by surfaces that render it directly, so a field that could carry a\n * secret would need a masking boundary at every one of them\". That sentence is the REASON, and it\n * is satisfied here by the boundary being crossed BEFORE the bytes arrive rather than at each\n * reader: what rides this field is the function layer's masked payload, and nothing between the op\n * and this line restores a value. Each surface prints what the declared mask produced.\n *\n * VERBATIM-MASKED, NOT A DIGEST — the discretion D-05 left open, resolved. A digest would satisfy\n * the disclosure guard trivially and would also make the record unable to answer the question the\n * channel was minted for: 399's UAT rejected a chat surface that executed ops and could not say\n * what they returned, and a session log holding a hash of the answer reproduces that hole one\n * layer down. The result is the TURN'S OWN TERRITORY (392's receipt charter: the receipt is the\n * map, the territory travels beside it), so it is kept — as filed, masked.\n *\n * THE BINDING CONSTRAINT IS ON THE RECORD.\n * `.planning/phases/399.1-chat-render-contract/399.1-ADJUDICATION-transcript-cleartext.md`\n * § \"The load-bearing corollary for D-05\": op results can carry credentials, so persisting an\n * UNMASKED entry here would mint a second unadjudicated cleartext sink in this exact file — the\n * class that adjudication names — converting an inherited 392 posture gap into a 399.1 defect.\n * A repair of the two fields that DO carry cleartext today (`user_message.text`,\n * `clause_receipt.clause`) is filed separately as `T-399.1-04`; this kind must never become a\n * third.\n *\n * ONE EVENT PER CLAUSE THAT RAN, never per clause planned: a `not-run` clause has no result, and a\n * line claiming one would be the log asserting an op answered a call nobody made.\n *\n * `payload` IS `unknown` AND MUST BE JSON-REPRESENTABLE. The writer is a JSONL adapter, so an\n * `undefined` payload is written as `null` at the append site rather than omitted — an omitted key\n * would fail the exact-key guard below on reopen, turning an op that returns nothing into a corrupt\n * line.\n */\nexport interface ChatClauseResultEvent extends ChatSessionEventBase<'clause_result'> {\n functionId: string\n payload: unknown\n}\n\n/** The fsync boundary marker. Its presence is what makes the preceding turn non-dangling (D-19). */\nexport interface ChatTurnCompleteEvent extends ChatSessionEventBase<'turn_complete'> {\n status: ChatTurnStatus\n}\n\n/**\n * A person's answer at an ask-tier gate (D-03). HISTORICAL ONLY.\n *\n * 2026-10-01 (432-19, D-14/D-22): nothing writes this event any more. The chat confirm, the\n * `/pin` verb and the execution gate are deleted, so no build mints an `approval_decision`. The kind\n * and its exact key set stay so a session file a pre-432 build wrote keeps parsing: the session\n * guard throws on an unknown kind, and persisted history stays readable (430 D-08).\n */\nexport interface ChatApprovalDecisionEvent extends ChatSessionEventBase<'approval_decision'> {\n /** The `fn:`-prefixed risk name the gate classified, not the bare op id (391-05). */\n actionClass: string\n decision: 'accept' | 'accept-always' | 'deny'\n /**\n * WHICH DECISION THIS WAS, on `model_change.source`'s precedent and for its reason (plan 08).\n *\n * `gate` — a person answered the inline confirm when an ask-tier capability reached the gate.\n * `verb` — a person typed `/pin <class>`, pre-denying the class for the rest of the session.\n *\n * Both are a human decision about one action class, and collapsing them would leave a reviewer\n * unable to tell a refusal of a specific request from a standing rule the person set in advance.\n * The field is REQUIRED rather than defaulted: nothing had ever emitted an `approval_decision`\n * before this plan, so no session file on disk carries one, and an optional field would have\n * bought back-compatibility with a population of exactly zero lines at the cost of a defaulting\n * rule that then has to be right forever.\n */\n source: 'gate' | 'verb'\n}\n\n/**\n * A clause nothing in this build handles (D-08 / D-15).\n *\n * Logged on EVERY occurrence, in live sessions as well as scenario runs, which is what makes\n * CHAT-03's field rate a projection over logs rather than a new metric store. The gated ceiling\n * is computed over the frozen corpus; this event is what makes the ungated field number\n * observable at all.\n */\nexport interface ChatMarkUnhandledEvent extends ChatSessionEventBase<'mark_unhandled'> {\n clause: string\n reason: string\n}\n\n/**\n * The session model changed (D-04, CHAT-05's named config event).\n *\n * `source` distinguishes the two ways it happens, and they are genuinely different facts: a person\n * typed `/model`, or the configuration on disk drifted and the session re-read it (391's\n * human-edits-always-win echo). Collapsing them would leave a reader unable to tell a deliberate\n * switch from one that happened to them.\n */\nexport interface ChatModelChangeEvent extends ChatSessionEventBase<'model_change'> {\n from: string\n to: string\n source: 'verb' | 'config_reread'\n}\n\n/**\n * The reachable toolset changed (D-04, CHAT-05's second named config event).\n *\n * Deltas plus the new fingerprint, not the whole set: the header already carries the opening hash,\n * so a reader folds these to reconstruct what was reachable at turn N. Logging the full set each\n * time would put a copy of the catalogue in the log on every drift.\n *\n * There is no `/tools` toggle producing these (D-04) — the always-send-all law forbids one. What\n * produces them is a build or configuration that genuinely changed what exists.\n */\nexport interface ChatActiveToolsChangeEvent extends ChatSessionEventBase<'active_tools_change'> {\n addedIds: readonly string[]\n removedIds: readonly string[]\n toolsetHash: string\n}\n\n/**\n * ONE event for the whole degrade pass (CHAT-04).\n *\n * The stages of a degrade — hygiene, screenshot stripping, dedup, truncation — are FIELDS of one\n * pass and not sibling kinds, and that is a decision rather than a shorthand: they always run\n * together under one budget for one turn, so a reader asking \"what did compaction cost here\"\n * wants one row. Sibling kinds would make that question a join.\n *\n * `outcome` carries the substrate's own two answers verbatim (`degrade()`'s `DegradeOutcome`), so\n * the cannot-fit case is reported rather than folded into a success with smaller numbers.\n */\nexport interface ChatCompactionEvent extends ChatSessionEventBase<'compaction'> {\n beforeTokens: number\n afterTokens: number\n outcome: 'degraded' | 'pinned-content-exceeds-budget'\n}\n\n/**\n * A turn that ended without completing (D-19's two arms).\n *\n * `explicit` is a graceful Ctrl+C: the process was alive and wrote this itself. `synthesized` is\n * what the next-turn repair writes after a hard kill, where the dangling turn is inferred from a\n * tail that is not a boundary marker. Both are real and they are different — one says a person\n * stopped, the other says a machine died — and a single spelling would lose that.\n */\nexport interface ChatAbortedEvent extends ChatSessionEventBase<'aborted'> {\n source: 'explicit' | 'synthesized'\n}\n\n/** The complete event union: one member per declared kind. */\nexport type ChatSessionEvent =\n | ChatUserMessageEvent\n | ChatStageOutcomeEvent\n | ChatClauseReceiptEvent\n | ChatClauseResultEvent\n | ChatApprovalDecisionEvent\n | ChatMarkUnhandledEvent\n | ChatModelChangeEvent\n | ChatActiveToolsChangeEvent\n | ChatCompactionEvent\n | ChatAbortedEvent\n | ChatTurnCompleteEvent\n\n/** Bytes on a session line that do not describe an event this build can read. */\nexport class ChatSessionEventSchemaError extends Error {\n override readonly name = 'ChatSessionEventSchemaError'\n\n constructor(readonly detail: string) {\n super(\n `a stored chat session event cannot be read: ${detail}. Lines are written from typed `\n + 'records inside one process, so bytes that fail this guard were written by another '\n + 'build or damaged in place.',\n )\n }\n}\n\n/**\n * The EXACT key set each kind carries, spelled once and read by the guard below.\n *\n * A total `Record` over the kind union, which is the compile-time half of the double lock: an\n * twelfth kind cannot be declared without saying what its line looks like. The guard is the\n * runtime half, and the two catch different drifts (`jobs/kinds.ts:619-627`).\n *\n * Exact key sets rather than presence checks, for `run-notification.ts`'s stated reason: a\n * presence check admits a record carrying an EXTRA field, and an extra field on a line several\n * surfaces render is exactly how a payload body arrives in a log that promised refs (D-18).\n */\nconst EVENT_KEYS: Record<ChatSessionEventKind, readonly string[]> = {\n user_message: ['at', 'kind', 'text', 'turnId'],\n stage_outcome: ['at', 'kind', 'outcome', 'stage', 'turnId'],\n clause_receipt: ['at', 'clause', 'functionId', 'kind', 'origin', 'outcome', 'status', 'turnId'],\n clause_result: ['at', 'functionId', 'kind', 'payload', 'turnId'],\n approval_decision: ['actionClass', 'at', 'decision', 'kind', 'source', 'turnId'],\n mark_unhandled: ['at', 'clause', 'kind', 'reason', 'turnId'],\n model_change: ['at', 'from', 'kind', 'source', 'to', 'turnId'],\n active_tools_change: ['addedIds', 'at', 'kind', 'removedIds', 'toolsetHash', 'turnId'],\n compaction: ['afterTokens', 'at', 'beforeTokens', 'kind', 'outcome', 'turnId'],\n aborted: ['at', 'kind', 'source', 'turnId'],\n turn_complete: ['at', 'kind', 'status', 'turnId'],\n}\n\nfunction isChatSessionEventKind(value: unknown): value is ChatSessionEventKind {\n return CHAT_SESSION_EVENT_KINDS.some((kind) => kind === value)\n}\n\n/**\n * Guard one line off a session file.\n *\n * THE VERSION IS AN ARGUMENT, NOT A FIELD ON THE LINE, and that is a decision worth stating\n * because the obvious alternative looks safer. The file's version is declared ONCE, on the header\n * line, and the adapter refuses to open a session whose header this build does not read — so a\n * mixed-version file cannot come into existence by appending. Stamping every line as well would\n * be a second answer to the same question, free to disagree with the first, and would put a\n * constant in every line of an append-only file for a hazard the open path already closes.\n *\n * The version is nonetheless checked FIRST, before any shape question, for\n * `job-checkpoint-store.ts:231-237`'s reason: a version mismatch has a remedy an operator can act\n * on, and reporting it as a missing field sends them to repair a line whose real problem is that\n * another build wrote it.\n */\nexport function guardChatSessionEvent(\n value: unknown,\n declaredVersion: number,\n): ChatSessionEvent {\n if (declaredVersion !== CURRENT_CHAT_SESSION_SCHEMA_VERSION) {\n throw new ChatSessionEventSchemaError(\n `its session declares schemaVersion ${String(declaredVersion)}, and this build reads `\n + String(CURRENT_CHAT_SESSION_SCHEMA_VERSION),\n )\n }\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new ChatSessionEventSchemaError('it is not an object')\n }\n const record = value as Record<string, unknown>\n if (!isChatSessionEventKind(record.kind)) {\n throw new ChatSessionEventSchemaError(`${String(record.kind)} is not a session event kind`)\n }\n const expected = EVENT_KEYS[record.kind].join(',')\n const actual = Object.keys(record).sort().join(',')\n if (actual !== expected) {\n throw new ChatSessionEventSchemaError(\n `a ${record.kind} line carries ${JSON.stringify(Object.keys(record).sort())} and this `\n + `build writes ${JSON.stringify(EVENT_KEYS[record.kind])}`,\n )\n }\n if (typeof record.turnId !== 'string' || record.turnId === '') {\n throw new ChatSessionEventSchemaError('it names no turn')\n }\n if (typeof record.at !== 'string' || record.at === '') {\n throw new ChatSessionEventSchemaError('it carries no instant')\n }\n return record as unknown as ChatSessionEvent\n}\n","// Per-clause turn receipts (Phase 392, CHAT-01 / D-11).\n//\n// A turn reports what happened to EACH clause, not a single verdict, because D-11's execution rule\n// is sequential-and-stop-on-failure: a compound turn can legitimately end with one clause executed,\n// one failed and two never attempted, and a scalar answer cannot say that. The three statuses are\n// exactly those three facts.\n//\n// `not-run` is the member that earns the vocabulary. Without it a clause the engine deliberately\n// never attempted is indistinguishable from one that failed, and a person reading the receipt would\n// go looking for a failure that never happened.\n\n/**\n * What became of one clause. Closed, spelled once (388 C13).\n *\n * A DENIED confirm folds to `failed` rather than acquiring a fourth member (RESEARCH Pitfall 6):\n * the refusal name travels in `outcome`, so the fact is not lost, and a status a surface has to\n * special-case is a status every surface has to special-case.\n *\n * 2026-08-20 (Phase 399.1, D-02) — `refused` IS THAT FOURTH MEMBER, AND THE RULING ABOVE STANDS.\n * The 388 C13 ruling is about a PERSON declining a confirm, and a person who says no has not been\n * refused by anything: the turn asked, the answer was no, and folding that to `failed` costs a\n * reader nothing they cannot recover from `outcome`. This member is about the OTHER subject — a\n * GUARDRAIL declining an op. There the control WORKED and nothing failed, and both of the existing\n * members are actively wrong about it: `executed` asserts the change happened (measured G-399-2: a\n * credential-blocked config mutation rendered `executed` in green while the file was byte-unchanged,\n * and the reader's plausible next action was to paste the secret in by hand), while `failed` sends\n * them hunting a defect that does not exist. The specific reason — `schema-fail`, `refs-only`,\n * `duplicate-of:…` — still travels in `outcome` and in the rendered payload; what this member adds\n * is the one bit a surface must not get wrong, which is whether the thing was carried out.\n *\n * THE COST IS PAID DELIBERATELY, not overlooked: a status every surface has to special-case is\n * exactly what this is, and 399.1 pays it at every consumer in-phase (the receipt colour map becomes\n * exhaustive with a never-check, so a FIFTH member is a compile error rather than a silent `pc.dim`).\n * Widening the set is read-compatible for existing session logs — a status only ever appears in\n * entries written after it existed.\n */\nexport const CLAUSE_RECEIPT_STATUSES = ['executed', 'failed', 'not-run', 'refused'] as const\n\nexport type ClauseReceiptStatus = (typeof CLAUSE_RECEIPT_STATUSES)[number]\n\n/**\n * One clause's receipt.\n *\n * `outcome` is a ONE-LINE summary and never a payload body (D-18): for a failure it carries the\n * function layer's own refusal NAME (`UnknownFunctionError`, `FunctionInputError`, …), which is\n * the vocabulary `invokeFunction` already publishes, so a surface reporting a refused clause names\n * the same thing the audit row does.\n */\nexport interface ClauseReceipt {\n clause: string\n functionId: string\n origin: string\n status: ClauseReceiptStatus\n outcome: string\n}\n\n/**\n * Whether this status means the clause REACHED ITS CAPABILITY and came back (399.1-03).\n *\n * IT EXISTS BECAUSE THE FOURTH MEMBER PUT A HOLE IN EVERY ROLL-CALL SPELLED OVER `executed`. D-10's\n * atomicity claim — a fail-closed turn carried NOTHING out — was checked by both scenario runners as\n * \"no receipt says `executed`\", which was a complete statement of it for exactly as long as\n * `executed` was the only word for a clause that ran and returned. It is not any more: an op that\n * reached its capability and declined says `refused`, and some of them leave a durable trace on the\n * way (a blocked config proposal is FILED — that arm carries its `proposalId` precisely so a person\n * can find it). A roll-call that could not see that row would report \"nothing ran\" over a turn that\n * ran something and wrote a record.\n *\n * `failed` AND `not-run` ARE DELIBERATELY OUTSIDE IT, and they are outside for different reasons.\n * `not-run` is a clause the engine never attempted — the one member that is unambiguously nothing\n * happening. `failed` is the ambiguous one: it covers a clause the gate refused before dispatch AND\n * one that threw mid-flight, and the vocabulary cannot tell those apart, so a predicate that claimed\n * either answer for it would be inventing a fact. What this function answers is the question it can\n * answer: these two words mean the op RAN and RETURNED.\n *\n * SPELLED ONCE, BESIDE THE SET IT READS. Two runners in two packages ask this question, and a copy\n * in each is how one of them keeps a hole after somebody fixes the other.\n */\nexport function clauseReachedCapability(status: ClauseReceiptStatus): boolean {\n return status === 'executed' || status === 'refused'\n}\n","// The `agent.ask` op's input and output contracts (Phase 392, D-24).\n//\n// D-24 is why these are here at all: the turn entry is a REGISTERED function-layer op, and\n// the REPL, the one-shot `ask` verb, 396's MCP projection and 397's parity suite are all clients of\n// it. An op needs declared contracts, and a contract several surfaces render needs one spelling.\n//\n// `sessionId` IS OPAQUE TO THIS CONTRACT and validated where it becomes a path — the adapter checks\n// it against the same safe-segment class the job checkpoint store uses, and an unknown id is a\n// typed refusal rather than a silent create. A shape check here that looked like validation would\n// be the more dangerous kind of guard: it would make a reader believe the string had been\n// authorized when it had only been spelled acceptably.\n\nimport { z } from 'zod'\n\nimport { CLAUSE_RECEIPT_STATUSES } from './turn-receipts'\nimport { CHAT_TURN_STATUSES } from './session-events'\n\nexport const ClauseReceiptSchema = z.object({\n clause: z.string(),\n functionId: z.string(),\n origin: z.string(),\n status: z.enum(CLAUSE_RECEIPT_STATUSES),\n outcome: z.string(),\n})\n\n/**\n * What ONE executed clause produced, on its way to a person (Phase 399.1, D-05).\n *\n * THE RECEIPT IS THE MAP AND THIS IS THE TERRITORY. `ClauseReceiptSchema` above is a five-string\n * one-line record by charter (D-18), and 392's `explainAnswerLines` comment defends that seat at\n * length — so the op's own result could not travel on it, and for forty ops it travelled nowhere at\n * all: chat executed them and printed `<op> completed` (G-399-2). This member is that missing\n * channel made structural rather than a second carrier bolted onto the receipt.\n *\n * `payload` IS `unknown` BY INTENTION. Forty-three ops declare forty-three output contracts, and a\n * turn result that tried to name them would either enumerate them here — a second registry, free to\n * drift from the one that dispatches — or normalise them, which is the render defect this member\n * exists to close. The op that produced it is named by `functionId`, and the contract for those\n * bytes is that op's own declared output schema, which the registry already publishes.\n *\n * THE PAYLOAD IS MASKED, AND THAT IS A CONTRACT RATHER THAN AN OBSERVATION (D-04/D-05, and the\n * 2026-08-20 D-10 adjudication's binding corollary). It carries the value the function layer\n * returned, masked, and every path this contract travels — the prompt, the cache, the session event\n * log, any `agent.ask` client — keeps it that way. Each surface prints what the declared mask\n * produced, and nothing restores a value. An unmasked value here would put op-result credentials\n * into a persisted trail, minting a new instance of a cleartext-at-rest class that has already been\n * named.\n */\nexport const ClauseResultSchema = z.object({\n functionId: z.string().min(1),\n payload: z.unknown(),\n})\n\nexport type ClauseResult = z.infer<typeof ClauseResultSchema>\n\n\n/**\n * What a caller asks with.\n *\n * `message` is non-empty because an empty utterance has no clause to route and the honest refusal\n * is at the contract, before a turn id is minted and a session file is touched.\n */\nexport const AgentAskInputSchema = z.object({\n message: z.string().min(1),\n sessionId: z.string().optional(),\n})\n\nexport type AgentAskInput = z.infer<typeof AgentAskInputSchema>\n\n/**\n * What a turn answers with.\n *\n * `receipts` is present on EVERY status including `fail_closed`, where it is empty — and the\n * emptiness is the assertion D-10 asks for. A fail-closed turn that omitted the field would leave\n * \"nothing ran\" and \"the field is not reported here\" as the same bytes, and `executed == 0` is the\n * exact claim the compound scenarios make.\n *\n * `unhandled` names the clause the turn could not route. It is the message D-08 requires: a turn\n * that fails closed must say WHICH part of what the person asked for it could not do.\n */\nexport const AgentAskResultSchema = z.object({\n sessionId: z.string(),\n turnId: z.string(),\n status: z.enum(CHAT_TURN_STATUSES),\n answer: z.string().optional(),\n receipts: z.array(ClauseReceiptSchema),\n /**\n * What the clauses that RAN produced, in clause execution order (399.1, D-05).\n *\n * REQUIRED, AND A SIBLING OF `receipts` RATHER THAN A MEMBER OF ONE, on `receipts`' own argument:\n * a turn that omitted the field would leave \"nothing produced a result\" and \"this build does not\n * report results\" as the same bytes, and \"the refused turn ran nothing\" is precisely the claim a\n * fail-closed turn makes. So a fail-closed turn carries `[]` and says so.\n *\n * ONE ENTRY PER EXECUTED CLAUSE, so a compound turn's second op is not silently the first's. The\n * ORDER is the order the engine ran them in, which is the order the person typed them — the\n * property this whole engine preserves everywhere else.\n */\n results: z.array(ClauseResultSchema),\n // 2026-10-01 (432-19, D-15): no `denials` channel. It carried what the execution gate refused,\n // with the gate's remedies; there is no gate, so nothing is refused that way.\n unhandled: z.object({ clause: z.string(), reason: z.string() }).optional(),\n /**\n * Lines of this session's log the open path could not read (392 plan 08, discharging 392-03).\n *\n * SURFACED RATHER THAN SWALLOWED. A resumed session with permanent mid-file damage comes back\n * with a non-empty list, and a surface that ignored it would re-create exactly the swallow plan\n * 03 removed — a person continuing a conversation that is quietly missing part of itself. One\n * line of output is enough, which is why this is a COUNT of what could not be read rather than\n * the damage report: the report is the file, and `chat --list` is what names the file.\n *\n * OPTIONAL, and absent means the log had nothing to refuse — which every healthy session is, so\n * a required field would put a zero on every turn of every conversation forever.\n */\n refusedLineCount: z.number().int().positive().optional(),\n})\n\nexport type AgentAskResult = z.infer<typeof AgentAskResultSchema>\n","// The routing scenario contract (Phase 392, CHAT-02 / D-13 / D-15).\n//\n// Routing is a TESTED CONTRACT rather than reviewer discipline: each scenario is a file, the\n// corpus is versioned, and the `mark_unhandled` ceiling is computed over that frozen denominator.\n// This module is the vocabulary those files are written in, minted in schema because three\n// packages read it — the harness that runs a scenario, the meta-test that walks the resolver table\n// looking for one, and the ceiling computation over the manifest.\n//\n// EXACTLY TWO EXPECTATIONS EXIST, and the smallness is the design. A scenario either says \"this\n// must be carried out\" or \"this must be refused with nothing carried out\". There is no partial\n// arm, because D-10's atomicity means there is no partial OUTCOME: a turn that could not route\n// one clause executed zero of them.\n//\n// NO FRACTIONAL CONFIDENCE MEMBER EXISTS ANYWHERE IN THIS VOCABULARY, and its absence is load-\n// bearing rather than an omission. Stage-1 resolution is binary by construction (D-09): an exact\n// predicate hit, or nothing. A confidence field would be the first half of a threshold, and a\n// threshold is precisely how an OVERRIDING path — one whose verdict beats a model's — acquires a\n// false-positive rate. Precision 1.0 is a property of the mechanism, and a number here would make\n// it a property of a tuning value instead.\n\nimport { z } from 'zod'\n\nimport { CHAT_SESSION_EVENT_KINDS } from './session-events'\n\n/** What a scenario asserts about its turn. Closed, spelled once (388 C13). */\nexport const SCENARIO_EXPECTATIONS = ['should_execute', 'fail_closed'] as const\n\nexport type ScenarioExpectationKind = (typeof SCENARIO_EXPECTATIONS)[number]\n\n/**\n * The scenario classes (D-13's two lanes, three classes).\n *\n * `deterministic` scenarios never touch the LLM BY CONTRACT — which is why they need no mock, and\n * why \"no mocks in either lane\" is a true statement rather than an aspiration. `planner` and\n * `compound` run against a live model as a release gate.\n */\nexport const SCENARIO_CLASSES = ['deterministic', 'planner', 'compound'] as const\n\nexport type ScenarioClass = (typeof SCENARIO_CLASSES)[number]\n\n/** Where a scenario runs. `hermetic` is per-commit CI; `live` is the release gate (D-13). */\nexport const SCENARIO_LANES = ['hermetic', 'live'] as const\n\nexport type ScenarioLane = (typeof SCENARIO_LANES)[number]\n\n/**\n * What the turn must have done.\n *\n * `executed` is REQUIRED on both arms, and on the `fail_closed` arm it is the whole point: D-10's\n * claim is `executed == 0`, and an optional count would let a fail-closed scenario assert a\n * refusal while staying silent about whether anything ran on the way to it.\n *\n * `planned` is optional because it is only meaningful where a planner ran; `compound/` scenarios\n * that pin planned-equals-executed supply it, deterministic ones have nothing to say.\n *\n * `argsPin` is D-12's half: a scenario can pin the ARGUMENTS the executed op received, which is\n * how \"the mapper's binding beat the model's\" becomes an assertion rather than a hope.\n *\n * `namesClause` is D-08's: a fail-closed turn must name what it could not do, and a scenario that\n * only checked the status would pass against a silent drop.\n */\nexport const ScenarioExpectationSchema = z.object({\n kind: z.enum(SCENARIO_EXPECTATIONS),\n planned: z.number().int().nonnegative().optional(),\n executed: z.number().int().nonnegative(),\n ops: z.array(z.string()).optional(),\n argsPin: z.record(z.string(), z.unknown()).optional(),\n namesClause: z.string().optional(),\n /**\n * The session event this turn must leave behind (392 plan 08, widening 392-02's flagged gap).\n *\n * A DIRECTIVE'S PROOF IS AN EVENT, and until this field existed the vocabulary could not say so.\n * `/model` and `/pin` change what a SESSION is: they invoke nothing, so `ops` is empty and\n * `executed` is 0 on a turn that did exactly what was asked — the same numbers a turn that did\n * nothing at all would show. What tells them apart is the row in the log, and 392-02 recorded\n * that the alternative (asserting session events outside `expect`) would leave the corpus unable\n * to state its own claim. The enum is the log's own closed kind set, so a scenario cannot pin an\n * event kind this build does not write.\n */\n emitsSessionEvent: z.enum(CHAT_SESSION_EVENT_KINDS).optional(),\n /**\n * A fragment the turn's answer must contain (392 plan 08).\n *\n * The chrome directives' proof. `/help` and `/quit` produce prose and no event, so a scenario\n * for either has nothing else to assert — and a scenario that could only check the STATUS would\n * pass against a `/help` that printed an empty string. A fragment rather than the whole text,\n * because pinning the full help output would make every added alias a corpus edit.\n */\n answerContains: z.string().optional(),\n})\n\nexport const ChatScenarioSchema = z.object({\n id: z.string().min(1),\n class: z.enum(SCENARIO_CLASSES),\n lane: z.enum(SCENARIO_LANES),\n utterance: z.string().min(1),\n expect: ScenarioExpectationSchema,\n})\n\nexport type ScenarioExpectation = z.infer<typeof ScenarioExpectationSchema>\nexport type ChatScenario = z.infer<typeof ChatScenarioSchema>\n","// The capability-catalog row DTOs (Phase 398 plan 01 — XPLN-01, D-05 / D-06 / D-07 / D-08).\n//\n// WHAT THE CATALOG IS FOR. The golden ledger (397 D-05) is change control: it records what a\n// capability IS so a widened scope is a one-line diff. This artifact answers a different question —\n// what a PERSON or an external agent can reach, in the words they would read — and it is the one\n// data source behind `init --agent`, the chat `/` type-ahead, the starter prompts and the `explain`\n// op. Two committed projections of one registry could drift, so they do not: a census cell asserts\n// the op rows here and the golden's rows are the same set in both directions (D-01).\n//\n// THREE ROW KINDS, ONE DISCRIMINATED UNION (D-05). A registry op, a chat alias that resolves to\n// one, and a shipped skill are three different things a person can be told about, and a flat shape\n// that could describe any of them would be a shape every consumer has to defend against. `kind` is\n// the discriminant every consumer switches on. Capability count is the OP rows: adding an alias\n// does not add a capability.\n//\n// NOTHING HERE IS HAND-WRITTEN AT THE ARTIFACT (D-08). Descriptions come from the zod/FunctionSpec\n// summaries that already feed chat and MCP; `params` is the declaration's own inert input\n// projection, carried VERBATIM through the one shipped lens and never converted a second time. A\n// poorly-reading description is fixed at its zod source, where it improves every surface at once.\n//\n// PRESENCE RULES LIVE AT THE PRODUCER AND ITS CENSUS, NOT IN A REFINEMENT. `mcpTool` is present iff\n// the row claims the `mcp` surface, `docAbsentReason` iff `docPath` is null. Those are asserted by\n// named cells in `packages/cli/src/__tests__/conformance/catalog.test.ts` rather than by a\n// `superRefine` here, because a refined member cannot sit under `z.discriminatedUnion` and the\n// discriminant is the more load-bearing of the two properties.\n\nimport { z } from 'zod'\n\n/**\n * The surface vocabulary IS the pinned roster (D-06), not a superset of it.\n *\n * `chat` and `mcp` are the two surfaces 397's parity suite measures; the CLI's handlers are\n * deliberately absent (397 D-03's two-surface claim). The catalog never claims a surface nothing\n * measures — a third member arrives here only when a third roster row and its adapter do.\n */\nexport const CatalogSurfaceSchema = z.enum(['chat', 'mcp'])\nexport type CatalogSurface = z.infer<typeof CatalogSurfaceSchema>\n\n/**\n * One example call's arguments, DERIVED from the row's own params (spec §3.3, D-08).\n *\n * WHY IT IS AN OBJECT AND NOT A BARE RECORD. `\"exampleCall\": { \"arguments\": {} }` reads, in the\n * committed file, as \"call this with no arguments\" — which is a true and useful thing to say about\n * an op whose every property is optional. A bare `{}` in that position would read as a missing\n * value, and the distinction between \"nothing is required\" and \"nobody derived one\" is exactly what\n * the nullable arm plus {@link CatalogOpRowSchema.exampleCallAbsentReason} exists to keep apart.\n *\n * NOTHING HERE IS AUTHORED. The values come out of one pure function over the row's own JSON-Schema\n * projection; a hand-written example is a second contract that agrees with the schema until the day\n * the schema moves, and the agent that copied it is the one who finds out.\n */\nexport const CatalogExampleCallSchema = z.object({\n arguments: z.record(z.string(), z.unknown()),\n}).strict()\nexport type CatalogExampleCall = z.infer<typeof CatalogExampleCallSchema>\n\n/**\n * Which of the migration map's three closed answers a retired v1 tool name gets (D-13).\n *\n * THIS IS A SECOND SPELLING OF `V1MigrationArm`, AND IT IS TIED RATHER THAN TRUSTED. The arm\n * vocabulary is owned by `packages/mcp`'s migration map, which cannot be imported here: `mcp`\n * depends on `schema`, and a DTO package that imported a surface package would invert the workspace\n * (384 D-16). The two spellings are held together from both sides — the producer's projection\n * function takes a `V1ToolMigrationEntry` and returns this DTO, so an arm minted in `mcp` and\n * missing here fails to COMPILE; and a census cell asserts these options set-equal the arms the\n * shipped map actually carries, so an arm written here that nothing uses is a named RED.\n */\nexport const CatalogMigrationArmSchema = z.enum(['renamed-to', 'retired', 'pending'])\nexport type CatalogMigrationArm = z.infer<typeof CatalogMigrationArmSchema>\n\n/**\n * One v1 tool name and its ruled disposition, projected VERBATIM from the shipped map (D-14).\n *\n * `.strict()` for the reason every DTO here is strict, and one more: this section is what an\n * external agent still pinned to a v1 name reads, so a field that arrived by accident would be a\n * sentence the product did not mean to say to a caller it cannot see.\n */\nexport const CatalogMigrationEntrySchema = z.object({\n /** The v1 tool name, verbatim from the inventory's tool table. */\n v1Name: z.string().min(1),\n arm: CatalogMigrationArmSchema,\n /** The live v2 tool carrying the capability. Present only on `renamed-to`. */\n v2Tool: z.string().min(1).optional(),\n /** The inventory's ruled reason, dated. */\n note: z.string().min(1),\n /** What to call instead. Present on `retired` and `pending`. */\n route: z.string().min(1).optional(),\n /** The milestone owning the absence. Present only on `pending`. */\n owner: z.string().min(1).optional(),\n}).strict()\nexport type CatalogMigrationEntry = z.infer<typeof CatalogMigrationEntrySchema>\n\n/**\n * One registry op, as a person reads it.\n *\n * `mcpUnprojectedReasonKey` is the VISIBLE ABSENCE arm (D-06): an op with no MCP door carries the\n * class of the shipped `UNPROJECTED_OPS` reason rather than a blank column, so \"deliberately not\n * projected\" and \"nobody has looked at it\" are different values instead of the same hole.\n */\nexport const CatalogOpRowSchema = z.object({\n kind: z.literal('op'),\n /** The registry op id, under the dot taxonomy. */\n id: z.string().min(1),\n /** The declaration's own `summary` — the sentence every other surface already renders. */\n description: z.string().min(1),\n /** The declaration's inert input projection, verbatim. NEVER re-converted here. */\n params: z.record(z.string(), z.unknown()),\n surfaces: z.array(CatalogSurfaceSchema).min(1),\n /** Present iff `surfaces` contains `mcp`. */\n mcpTool: z.string().min(1).optional(),\n /** Present iff `surfaces` omits `mcp` — the visible-absence arm. */\n mcpUnprojectedReasonKey: z.string().min(1).optional(),\n /** Repo-relative path into a shipped doc, or an explicit null. Never a guessed URL (D-07). */\n docPath: z.string().min(1).nullable(),\n /** A heading within `docPath`, when the row deep-links rather than naming a whole file. */\n docAnchor: z.string().min(1).optional(),\n /** Present iff `docPath` is null — the dated reason there is no doc yet. */\n docAbsentReason: z.string().min(1).optional(),\n // 2026-10-02 (432-39, D-12): no `requiredScopes` column. Declarations carry no scopes, the\n // generator has written none since 432-20, and the strict row now refuses one.\n /**\n * A call an agent can copy, derived from `params` — or an explicit null (spec §3.3, D-08).\n *\n * NULL IS NOT \"no arguments\". An op whose properties are all optional gets\n * `{ \"arguments\": {} }`, because calling it with nothing is a real call. Null means the\n * derivation REFUSED to show a value it could not prove the shipped contract would accept, and\n * `exampleCallAbsentReason` says which construct it refused on. An example that would be\n * rejected on arrival is worse than none: the agent that copies it learns a shape the product\n * does not have, and learns it from the product's own manifest.\n */\n exampleCall: CatalogExampleCallSchema.nullable(),\n /** Present iff `exampleCall` is null — which construct the derivation would not guess at. */\n exampleCallAbsentReason: z.string().min(1).optional(),\n}).strict()\n\n/**\n * One chat alias, and the op it resolves to.\n *\n * `targetOpId` is joined to the registry in BOTH directions by the census cell: an alias naming a\n * non-registry target is a named RED, and an op-alias in the shipped resolver table with no row\n * here is the same RED from the other side (D-05).\n */\nexport const CatalogAliasRowSchema = z.object({\n kind: z.literal('alias'),\n /** The word a person types, exactly as the resolver table names it. */\n alias: z.string().min(1),\n targetOpId: z.string().min(1),\n /** The target op's own summary — an alias does not get a second description to drift from. */\n description: z.string().min(1),\n docPath: z.string().min(1).nullable(),\n docAnchor: z.string().min(1).optional(),\n docAbsentReason: z.string().min(1).optional(),\n}).strict()\n\n/** One shipped skill, from its own SKILL.md frontmatter. */\nexport const CatalogSkillRowSchema = z.object({\n kind: z.literal('skill'),\n name: z.string().min(1),\n description: z.string().min(1),\n shortDescription: z.string().min(1),\n /** The skill's own SKILL.md, repo-relative — a skill always has a doc, because it IS one. */\n docPath: z.string().min(1),\n}).strict()\n\nexport const CatalogRowSchema = z.discriminatedUnion('kind', [\n CatalogOpRowSchema,\n CatalogAliasRowSchema,\n CatalogSkillRowSchema,\n])\n\n/**\n * The committed artifact.\n *\n * `rowCount` and `rowsDigest` are the file's own mechanical self-check, on the golden's precedent:\n * a mint that produced a truncated document must not be able to reach the committed file, and a\n * reader must be able to tell a re-ordering from a re-content-ing without diffing every row. The\n * digest is sha256 over the ONE canonical serializer, so it is byte-level and locale-independent\n * (edge XPLN-01/encoding).\n */\nexport const CapabilityCatalogSchema = z.object({\n $note: z.array(z.string().min(1)).min(1),\n rowCount: z.number().int().nonnegative(),\n rowsDigest: z.string().min(1),\n rows: z.array(CatalogRowSchema),\n /**\n * The v1→v2 migration map, projected from `packages/mcp` (D-14, XPLN-03).\n *\n * It sits BESIDE the rows rather than among them because it is not a capability: an entry says\n * a name is gone and what answers the need instead, and a row kind for it would put retired\n * history into the set every consumer counts as \"what this product can do\".\n */\n migrationMap: z.array(CatalogMigrationEntrySchema),\n /**\n * The migration section's own count sentence.\n *\n * `rowCount` exists so a mint that produced a truncated document cannot reach the committed\n * file; this is the same mechanical self-check for the section `rowCount` does not cover. A new\n * section with no count is the hole `rowCount` was added to close, re-opened one field over.\n */\n migrationCount: z.number().int().nonnegative(),\n}).strict()\n\n// ---- The `init --agent` manifest (398-08, D-16 · XPLN-01) ----------------------------------------\n//\n// WHAT THE MANIFEST IS. One local, non-interactive, idempotent read: the committed catalog's rows\n// and migration map, verbatim and UNFILTERED, plus this workspace's posture. It is the machine entry\n// point spec §3.3 names — what an external agent reads instead of guessing — and because it is\n// produced by LOADING the committed artifact rather than by re-deriving anything, `manifest ≡\n// catalog` is a cell rather than a promise.\n//\n// IT IS UNFILTERED, AND THE SHAPE SAYS SO. The rows are every row, for every caller. 2026-10-02\n// (432-39, D-12): no door filters a listing per caller any more (432-20 deleted the MCP `tools/list`\n// visibility law), so there is no permission for a manifest to report either.\n\n// 2026-10-02 (432-39, D-02/D-12): `AgentManifestTokenRefSchema` is deleted with the posture's\n// `tokenEnvRefs`, `defaultScopes` and `safeMode` members. No MCP credential is declared or read\n// (432-21/22), no scope is granted and no composition hides an op, so each member could only ever\n// report the same constant. The strict posture now refuses all three.\n\n/**\n * Whether THIS workspace has a configuration, and whether it read — the local half of the\n * manifest (D-16).\n *\n * `configuration` has THREE arms and they are three different things to tell a person. `init --agent`\n * is the command an agent runs in a directory that may not be a project yet — that is what `init` is\n * for — so `absent` (no configuration file here) is an ordinary answer and not an error. `unresolved`\n * is the other one: a file IS here and it did not parse or validate, which is a thing to FIX rather\n * than a thing to run `init` for. Folding those two together would have an agent recommend the wrong\n * action.\n *\n * NO ARM CARRIES A REASON STRING, deliberately. A validation message quotes the input that failed to\n * validate, and the input here is the file an operator's credentials are declared beside (395-16:\n * Node's own printer walks a cause chain with `util.inspect`, which is how a config file's contents\n * once reached a terminal). The FACT is reportable; the text is not.\n */\nexport const AgentManifestPostureSchema = z.object({\n /** Whether this workspace has a configuration, and whether it read. */\n configuration: z.enum(['resolved', 'absent', 'unresolved']),\n}).strict()\nexport type AgentManifestPosture = z.infer<typeof AgentManifestPostureSchema>\n\n/** What `agent-qa init --agent` prints, in full. */\nexport const AgentManifestSchema = z.object({\n $note: z.array(z.string().min(1)).min(1),\n rows: z.array(CatalogRowSchema),\n migrationMap: z.array(CatalogMigrationEntrySchema),\n posture: AgentManifestPostureSchema,\n}).strict()\nexport type AgentManifest = z.infer<typeof AgentManifestSchema>\n\nexport type CatalogOpRow = z.infer<typeof CatalogOpRowSchema>\nexport type CatalogAliasRow = z.infer<typeof CatalogAliasRowSchema>\nexport type CatalogSkillRow = z.infer<typeof CatalogSkillRowSchema>\nexport type CatalogRow = z.infer<typeof CatalogRowSchema>\nexport type CapabilityCatalog = z.infer<typeof CapabilityCatalogSchema>\n\n/**\n * The row's identity within its kind — the key every census, sort and named RED uses.\n *\n * ONE SPELLING, because \"which row\" is asked by the producer's sort, the freshness comparator's\n * findings and three census cells; three spellings of it would be three answers on the day a kind\n * gains a field.\n */\nexport function catalogRowKey(row: CatalogRow): string {\n switch (row.kind) {\n case 'op':\n return row.id\n case 'alias':\n return row.alias\n case 'skill':\n return row.name\n }\n}\n","// The `explain` contract (Phase 398 plan 04 — XPLN-02, D-10 / D-11).\n//\n// THE UNION IS BINARY AND THERE IS NO CONFIDENCE MEMBER, and the absence is load-bearing. This is\n// the chat resolver table's own law, restated for the surface where it matters second-most:\n// `resolver-table.ts` says \"RESOLUTION IS BINARY … NO CONFIDENCE MEMBER … A confidence number\n// would be the first half of a threshold\". Here the reasoning is the same with a different\n// consequence: `explain` answers a person asking what the tool can do, and a 0.6-confidence answer\n// is an answer they will act on. There is exactly one honest split — the catalog grounds this, or\n// it does not — so the union has two arms and no number to tune between them (D-10, D-11).\n//\n// NO-INVENTION IS STRUCTURAL, NOT PROMPTED (D-10). `ExplainCitationSchema` is the LLM's whole\n// output contract, and it is `.strict()` with no field that can carry a command string: the model\n// selects catalog ROW IDS and nothing else. Every command a person reads is quoted out of a\n// catalog row by the deterministic renderer in `packages/agent/src/explain/renderer.ts`. A cited\n// id that no row answers to is therefore not a bad answer to sanitise — it is structurally an\n// abstention, because there is nothing for the renderer to quote.\n//\n// `query` IS THE ONE DELIBERATELY FREE-TEXT FIELD IN THIS FEATURE, and it never leaves the machine.\n// It flows to the local coverage log under `.agent-qa/` (D-11) and nowhere else; analytics may\n// carry at most a counter (D-14's no-free-text law). Nothing downstream of this file may put it in\n// an event payload.\n\nimport { z } from 'zod'\n\n/** What a person asked, verbatim. Local-only — see the header's free-text note. */\nexport const ExplainInputSchema = z.object({\n query: z.string().min(1),\n}).strict()\n\n/**\n * One run of model prose, or a pointer at one of the citations.\n *\n * A `citation` segment carries an INDEX and nothing else. Letting it carry its own text alongside\n * the index would be the field the header forbids arriving by the back door: the model would be\n * writing the words that stand where a command goes, which is exactly what \"the renderer quotes\n * the row\" means it must never do.\n */\nexport const ExplainProseSegmentSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('text'), text: z.string().min(1) }).strict(),\n z.object({ kind: z.literal('citation'), citationIndex: z.number().int().nonnegative() }).strict(),\n])\n\n/**\n * THE LLM'S ENTIRE OUTPUT CONTRACT (D-10).\n *\n * `segments` is admitted so the model is not forced to answer in a shape it cannot hold, and the\n * renderer treats it as INERT: the rendered output is a total function of the resolved rows and\n * the cited order, proven by the `renderer.test.ts` inertness cell. That cell is the guard on this\n * field — an author who later starts rendering model prose reds it, rather than discovering by\n * report that a made-up command reached a person.\n */\nexport const ExplainCitationSchema = z.object({\n /** Canonical catalog row ids — `op:<id>` / `alias:<alias>` / `skill:<name>`, in the model's order. */\n citedRowIds: z.array(z.string().min(1)),\n segments: z.array(ExplainProseSegmentSchema).optional(),\n}).strict()\n\n/** Which kind of catalog row a citation resolved to — the catalog's own discriminant. */\nexport const ExplainCitedRowKindSchema = z.enum(['op', 'alias', 'skill'])\n\n/**\n * One resolved citation: a catalog row, projected.\n *\n * Every member here is copied or derived from row data by the renderer. `invocation` is the row's\n * own reachable form (`/fn <id>`, `/<alias>`, the skill's name) — never a string the model wrote,\n * and never a literal in renderer code for an alias, whose names are compile-bound in the shipped\n * resolver table.\n */\nexport const ExplainCitedCapabilitySchema = z.object({\n rowId: z.string().min(1),\n rowKind: ExplainCitedRowKindSchema,\n invocation: z.string().min(1),\n description: z.string().min(1),\n /** The op row's declared required input names, verbatim from `params.required`. Empty otherwise. */\n requiredParams: z.array(z.string().min(1)),\n docPath: z.string().min(1).nullable(),\n}).strict()\n\n/** Grounded: every cited id resolved, and every line below was quoted out of a row. */\nexport const ExplainAnswerSchema = z.object({\n kind: z.literal('answer'),\n citations: z.array(ExplainCitedCapabilitySchema).min(1),\n renderedLines: z.array(z.string().min(1)).min(1),\n}).strict()\n\n/**\n * Not grounded — stated plainly, with the nearest thing the catalog does carry (D-11, XPLN-02).\n *\n * `closestRowIds` may be empty, and that is the honest arm rather than a hole: a query with no\n * lexical overlap with any row has no closest capability, and naming one anyway would be the\n * invention this whole contract exists to make impossible.\n *\n * `docsGap.logged` is the renderer's report of whether the host actually appended the coverage\n * record, not a request that it should — the renderer is storage-neutral and writes nothing.\n */\nexport const ExplainAbstentionSchema = z.object({\n kind: z.literal('abstention'),\n is_uncertain: z.literal(true),\n closestRowIds: z.array(z.string().min(1)),\n renderedLines: z.array(z.string().min(1)).min(1),\n docsGap: z.object({ logged: z.boolean() }).strict(),\n}).strict()\n\nexport const ExplainOutputSchema = z.discriminatedUnion('kind', [\n ExplainAnswerSchema,\n ExplainAbstentionSchema,\n])\n\nexport type ExplainInput = z.infer<typeof ExplainInputSchema>\nexport type ExplainProseSegment = z.infer<typeof ExplainProseSegmentSchema>\nexport type ExplainCitation = z.infer<typeof ExplainCitationSchema>\nexport type ExplainCitedRowKind = z.infer<typeof ExplainCitedRowKindSchema>\nexport type ExplainCitedCapability = z.infer<typeof ExplainCitedCapabilitySchema>\nexport type ExplainAnswer = z.infer<typeof ExplainAnswerSchema>\nexport type ExplainAbstention = z.infer<typeof ExplainAbstentionSchema>\nexport type ExplainOutput = z.infer<typeof ExplainOutputSchema>\n","// 2026-09-26, 429-04 D-18: the one provider-error classifier the CLI and the dashboard share.\n// Moved from `agent-qa auth test`: its regexes, their order and its six sentences are the\n// contract `auth-test.test.ts` pins, so the CLI's printed lines stay byte-identical.\n\n/** The class of a failed provider call, in the order the classifier tests them. */\nexport type ProviderErrorClass =\n | 'auth_error'\n | 'model_not_found'\n | 'rate_limit'\n | 'network_error'\n | 'invalid_request'\n | 'provider_error'\n// prettier-ignore\nexport const PROVIDER_ERROR_CLASSES = [\n 'auth_error',\n 'model_not_found',\n 'rate_limit',\n 'network_error',\n 'invalid_request',\n 'provider_error',\n] as const satisfies readonly ProviderErrorClass[]\n\nexport function extractProviderError(err: unknown): { message: string; statusCode?: number } {\n const errObj = err as Record<string, unknown>\n const statusCode = errObj?.statusCode as number | undefined\n const responseBody = errObj?.responseBody as string | undefined\n const data = errObj?.data as Record<string, unknown> | undefined\n const apiError = data?.error as Record<string, string> | undefined\n\n let message = err instanceof Error ? err.message : String(err)\n\n if (apiError?.message && apiError.message !== 'Error') {\n message = apiError.message\n } else if (typeof data?.detail === 'string') {\n message = data.detail\n } else if (responseBody) {\n try {\n const body = JSON.parse(responseBody)\n if (body?.detail) message = body.detail\n else if (body?.error?.message && body.error.message !== 'Error') message = body.error.message\n } catch {\n // Provider did not return JSON.\n }\n }\n\n return { message, statusCode }\n}\n\n/** The first class whose pattern matches wins, so a message naming two classes is stable. */\nexport function classifyProviderError(message: string, statusCode?: number): ProviderErrorClass {\n const fullContext = `${message} ${statusCode ?? ''}`\n if (/auth|unauthorized|401|invalid.*key|permission/i.test(fullContext)) return 'auth_error'\n if (/model.*not.*support|not found|404|does not exist/i.test(fullContext)) return 'model_not_found'\n if (/rate|429|quota|limit/i.test(fullContext)) return 'rate_limit'\n if (/ECONNREFUSED|ENOTFOUND|timeout|abort|fetch failed|network/i.test(fullContext)) {\n return 'network_error'\n }\n if (/invalid_request|400|bad request/i.test(fullContext)) return 'invalid_request'\n return 'provider_error'\n}\n\nexport function providerErrorSentence(errorClass: ProviderErrorClass, message: string): string {\n switch (errorClass) {\n case 'auth_error':\n return 'Authentication failed. Check the saved credential for this config.'\n case 'model_not_found':\n return 'Model not found. Check the model name.'\n case 'rate_limit':\n return 'Rate limited. Try again later.'\n case 'network_error':\n return 'Network error. Check the exact base URL and try again.'\n case 'invalid_request':\n return 'Invalid request. Check model and provider settings.'\n case 'provider_error':\n return `Connection failed. ${message}`\n }\n}\n","// 2026-09-26, 429-04 D-15/D-01: the draft model flow's DTOs. A draft is tested with the typed\n// credential inline and lands in the file only on a pass or an explicit skipTest, so nothing is\n// persisted before the person chooses to keep it.\nimport { z } from 'zod'\nimport type { ProviderErrorClass } from './provider-error'\n\n// The name rule itself is core's NameSlugSchema, applied by the route: schema cannot import core.\nexport const LlmConnectRequestSchema = z.object({\n name: z.string().min(1),\n provider: z.string().min(1),\n model: z.string().min(1),\n baseURL: z.string().optional(),\n providerHeaders: z.record(z.string(), z.string()).optional(),\n credential: z.object({\n type: z.enum(['api-key', 'bearer-token']),\n secret: z.string().min(1),\n }).strict().optional(),\n skipTest: z.boolean().optional(),\n}).strict()\n\nexport type LlmConnectRequest = z.infer<typeof LlmConnectRequestSchema>\n\nexport type LlmConnectResult =\n | { success: true; saved: true; becameDefault: boolean; usedCredential: boolean; revision: string }\n | { success: false; errorClass: ProviderErrorClass; message: string }\n\nexport type LlmCredentialSaveResult = { saved: true; created: boolean }\n\n/** Moves a saved credential to a renamed definition, so a rename never strands the secret. */\nexport const LlmCredentialMoveRequestSchema = z.object({\n from: z.string().min(1),\n to: z.string().min(1),\n provider: z.string().min(1),\n}).strict()\n\nexport type LlmCredentialMoveRequest = z.infer<typeof LlmCredentialMoveRequestSchema>\n\n/**\n * Why a model setup call was refused, as the route answers it.\n * - `invalid_setup_input`: the body is not a well-formed request.\n * - `name_invalid`: the name fails the name rule.\n * - `name_taken`: another definition already holds the name.\n * - `credential_provider_conflict`: a saved credential belongs to a different provider.\n * - `credential_not_accepted`: a key for a subscription provider, or a bearer token for a\n * provider other than anthropic-compatible.\n * - `credential_missing`: the provider needs a credential and none was typed or saved.\n * - `credential_exists`: a move target already holds a credential.\n * - `validation_failed`: the config with the definition added fails whole-config validation.\n */\nexport type LlmSetupRefusal =\n | 'invalid_setup_input'\n | 'name_invalid'\n | 'name_taken'\n | 'credential_provider_conflict'\n | 'credential_not_accepted'\n | 'credential_missing'\n | 'credential_exists'\n | 'validation_failed'\n// prettier-ignore\nexport const LLM_SETUP_REFUSALS = [\n 'invalid_setup_input',\n 'name_invalid',\n 'name_taken',\n 'credential_provider_conflict',\n 'credential_not_accepted',\n 'credential_missing',\n 'credential_exists',\n 'validation_failed',\n] as const satisfies readonly LlmSetupRefusal[]\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AO;AAAA,IACT,KAAK;AACH,aAAO,sBAAsB,OAAO;AAAA,EACxC;AACF;;;ACzEA,IAAAC,eAAkB;AAIX,IAAM,0BAA0B,eAAE,OAAO;AAAA,EAC9C,MAAM,eAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACtB,UAAU,eAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAC1B,OAAO,eAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACvB,SAAS,eAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,iBAAiB,eAAE,OAAO,eAAE,OAAO,GAAG,eAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EAC3D,YAAY,eAAE,OAAO;AAAA,IACnB,MAAM,eAAE,KAAK,CAAC,WAAW,cAAc,CAAC;AAAA,IACxC,QAAQ,eAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAC1B,CAAC,EAAE,OAAO,EAAE,SAAS;AAAA,EACrB,UAAU,eAAE,QAAQ,EAAE,SAAS;AACjC,CAAC,EAAE,OAAO;AAWH,IAAM,iCAAiC,eAAE,OAAO;AAAA,EACrD,MAAM,eAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACtB,IAAI,eAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACpB,UAAU,eAAE,OAAO,EAAE,IAAI,CAAC;AAC5B,CAAC,EAAE,OAAO;AA0BH,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":["import_zod","text","index","import_zod","import_zod","import_zod","text","import_zod","import_zod","import_zod","import_zod","text","text","text","import_zod","import_zod","import_zod","import_zod","import_zod","count","index","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","count","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","record","runIdSchema","runIdSchema","index","address","record","record","record","runIdSchema","import_zod","index","count","import_zod","import_zod","import_zod","import_zod","index","scopeKeySchema","import_zod","count","record","text","text","FIELD","RECORD","text","numberValue","booleanValue","record","arrayValue","import_zod","scopeKeySchema","anchorSchema","index","import_zod","recordIdSchema","samplesSchema","index","key","evidenceDigest","facts","import_zod","import_zod","verdictClassValues","import_zod","isNonArrayObject","text","isNonArrayObject","import_zod","import_zod","import_zod","import_zod","jobIdSchema","import_zod","import_zod","import_zod","index","text","text","index","i","j","index","index","import_zod","isRecord","record","import_zod","originClassSchema","import_zod","import_zod","finiteNumberSchema","index","import_zod","bundleKindSchema","factSubtypeSchema","anchorSchema","text","import_zod","index","import_zod","import_zod","scopeTierValues","scopeKeySchema","import_zod","import_zod","import_zod","text","import_zod","import_zod","import_zod","import_zod","scopeKeySchema","import_zod","import_zod","import_zod","record","import_zod","import_zod","import_zod","import_zod","import_zod"]}