@agentskit/harness 0.12.0 → 0.13.0

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.
package/dist/index.d.ts CHANGED
@@ -2240,9 +2240,10 @@ declare const modelFor: (policy: ModelPolicy, role: ModelRole) => ModelBinding;
2240
2240
  * PR/issue comment — a segment lifted from an issue description or a code-review finding can carry a secret that
2241
2241
  * was never meant to leave the private context it came from. Pure and kernel-safe: no adapters, no network, no
2242
2242
  * state. Pattern-based, not a claim of completeness — it catches the shapes that show up in practice (emails,
2243
- * common provider API-key prefixes, phone numbers, card-number-shaped digit runs), not every possible secret.
2243
+ * common provider API-key prefixes, PEM private-key blocks, phone numbers, card-number-shaped digit runs), not
2244
+ * every possible secret.
2244
2245
  */
2245
- type PiiKind = 'email' | 'api-key' | 'phone' | 'credit-card';
2246
+ type PiiKind = 'email' | 'api-key' | 'phone' | 'credit-card' | 'private-key';
2246
2247
  interface PiiMatch {
2247
2248
  readonly kind: PiiKind;
2248
2249
  readonly index: number;
@@ -2370,8 +2371,16 @@ declare const exportEvidenceBundle: ({ configPath, runId, outputPath, privateKey
2370
2371
  readonly privateKeyPath: string;
2371
2372
  readonly keyId: string;
2372
2373
  }) => Promise<EvidenceBundle>;
2373
- declare const verifyEvidenceBundle: (path: string, { trustedKeys }?: {
2374
+ /** Per-file and total caps on decoded evidence content: without them, a corrupted or hostile bundle could carry
2375
+ * arbitrarily large (or arbitrarily many) `contentBase64` blobs and exhaust memory during verification, before
2376
+ * any hash or signature check ever runs. The base64-length pre-check happens before `Buffer.from` decodes
2377
+ * anything, so an oversized single file is rejected without allocating its decoded buffer at all. */
2378
+ declare const EVIDENCE_MAX_FILE_BYTES: number;
2379
+ declare const EVIDENCE_MAX_TOTAL_BYTES: number;
2380
+ declare const verifyEvidenceBundle: (path: string, { trustedKeys, maxFileBytes, maxTotalBytes }?: {
2374
2381
  readonly trustedKeys?: readonly TrustedEvidenceKey[];
2382
+ readonly maxFileBytes?: number;
2383
+ readonly maxTotalBytes?: number;
2375
2384
  }) => EvidenceBundleVerification;
2376
2385
  declare const readEvidenceTrustStore: (path: string) => readonly TrustedEvidenceKey[];
2377
2386
 
@@ -4595,4 +4604,4 @@ declare const discoverIntake: (runner: CommandRunner, input: {
4595
4604
  readonly now: () => Date;
4596
4605
  }, options?: GitHubCliOptions) => Promise<readonly IntakeRecord[]>;
4597
4606
 
4598
- export { AGENT_REGISTRY_SCHEMA_VERSION, ARTIFACT_SCHEMA_VERSION, ARTIFACT_TYPES, ASSURANCE_LEVELS, type AdapterMetadata, type AdapterTelemetry, type AdversarialReviewResult, type AgentAdapter, type AgentEvalCase, type AgentEvalReport, type AgentEvalSuite, type AgentMemoryAdapter, type AgentMemoryHit, type AgentMemoryKvStore, type AgentMemoryRecord, type AgentRegistry, type AgentRegistryEntry, AgentRegistryEntrySchema, AgentRegistrySchema, type AgentSessionOptions, type AgentUsage, type ApprovedAssumption, type ArgvRagContextProviderOptions, type ArtifactBinding, type ArtifactEnvelope, type ArtifactEnvelopeInput, type ArtifactType, type ArtificialAnalysisModel, type AssuranceLevel, type AutomationStatus, type AutonomyMode, BENCHMARK_SCHEMA_VERSION, BLOCK_STATUSES, type BenchmarkBinding, type BenchmarkComparison, type BenchmarkImprovementDirection, type BenchmarkManifest, type BenchmarkObservation, type BenchmarkObservationEvidence, type BenchmarkObservationInput, type BenchmarkObservationStatus, type BenchmarkReport, type BenchmarkRun, type BenchmarkSummary, type BenchmarkTask, type BlockAssessment, type BlockManifest, type BlockStatus, CAPABILITY_KINDS, CAPABILITY_MANIFEST_SCHEMA_VERSION, CHECK_CATEGORIES, COMPATIBILITY_COMPONENTS, COMPATIBILITY_SCHEMA_VERSION, CONTEXT_PROVIDER_SLOT, CONTRACT_CLOSE, CONTRACT_OPEN, CONTRACT_SCHEMA_VERSION, type CacheUsage, type CapabilityDescriptor, type CapabilityKind, type CapabilityManifest, type CapabilityManifestInput, type CatalogModel, type ChangedFile, type CheckCategory, type CheckOutcome, type CheckResult, type ChecksAssessment, type ClaimResult, type CodeReviewInput, type CodeReviewOutcome, type CodingAgentAdapter, type CodingAgentHandlerResult, type CodingAgentRequest, type CodingAgentResult, type CommandResult, type CommandRunOptions, type CommandRunner, type CompatibilityComponent, type CompatibilityComponentId, type CompatibilityManifest, type CompatibilityObservation, type CompatibilityReport, type CompatibilityStatus, type ContextProvider, type ContextQuery, type ContextReference, type ContextSnapshot, type ContractAssessment, type ContractOutcome, ContractOutcomeSchema, type ContractScope, type CooldownEntry, type CooldownState, type CoordinationIdentity, type CriterionStatus, type CycleIterationMetrics, type CycleMatrixRow, type CycleStepResult, type CycleStepStatus, type DebriefInput, type DebriefIssueRow, type DebriefReport, type DecisionPacket, type DeliverInput, type DeliverOutcome, type DeliverReport, type DeliverResult, type DeliveryState, type DetectProvidersInput, type DiscoveryAmbiguity, type DiscoveryCurrentInput, type DiscoveryCurrentResult, type DiscoveryDecisionLogEntry, type DiscoveryInput, type DiscoveryOption, type DiscoveryResult, type DispatchLease, type DispatchLedger, type DispatchRecord, type DispatchRecordFile, type Disposer, type DocBridgeIndexInspection, type DockerMount, type DockerRuntimeEvidence, type DockerToolDefinition, type DoctorCheck, type DoctorCheckStatus, EVAL_COMPONENTS, EVAL_LAYERS, EVAL_MANIFEST_SCHEMA_VERSION, EVENT_LOG_GENESIS, EVIDENCE_BUNDLE_SCHEMA_VERSION, type EffortLevel, type EvalBatteryReport, type EvalCaseDefinition, type EvalCaseReport, type EvalComponent, type EvalExpectation, type EvalLayer, type EvalManifest, type EvalObservation, type EvalObservationStatus, type EventLogLock, type EventLogLockRecovery, type EventLogLockStatus, type EventLogVerification, type EventStore, type EvidenceArtifact, type EvidenceBundle, type EvidenceBundleFile, type EvidenceBundleSignature, type EvidenceBundleVerification, type EvidenceReference, type ExecutePhaseProfileOptions, type FailureClass, type FailureClassification, type FetchQueueInput, FileArtifactStore, FileEventStore, type FilePreflightPlan, type GateAssessment, type GateBinding, type GateCriterion, type GenerateContractInput, type GitHubCliOptions, type GuidedInstallIO, type GuidedInstallInput, type GuidedInstallReport, HARNESS_ERROR_CATALOG, HARNESS_ERROR_CODES, HARNESS_EVENT_ENVELOPE_SCHEMA_VERSION, HARNESS_EVENT_SCHEMA_VERSION, HARNESS_EVENT_TYPES, HARNESS_PLUGIN_API_VERSION, HARNESS_REPO_URL, type HandoffBriefInput, HarnessError, type HarnessErrorClassification, type HarnessErrorDisposition, type HarnessEvent, type HarnessEventContext, type HarnessEventEnvelope, type HarnessEventEnvelopeInput, type HarnessEventInput, type HarnessEventListener, type HarnessEventPayloads, type HarnessEventProvenance, type HarnessEventType, type HarnessPlugin, type HarnessPluginContext, IMPROVEMENT_CYCLE_STEPS, type ImprovementCycleAssessment, type ImprovementCycleInput, type ImprovementCycleIteration, type ImprovementCycleStep, type InstallAction, type InstallInput, type InstallReport, type IntakeRecord, type IssueFailureRecord, type IssueFailureState, LEARNING_STATUSES, LEGAL_TRANSITIONS, LOOP_CONFIG_FILE, LOOP_CONFIG_SCHEMA_VERSION, LOOP_LOCAL_CONFIG_FILE, LOOP_STAGES, type LearningRecord, type LearningStatus, type LearningsLedger, type LinearIssueDetail, type LinearListInput, type LinearQueueFilter, type LinearWriteOptions, type LlmCache, type LlmCacheKeyInput, type LlmCacheStats, type LoadedConfig, type LoadedLoopConfig, type LocalConfigAnswers, type LocalConfigPrompter, type LoopConfig, type LoopConfigInput, LoopConfigSchema, type LoopDoctorInput, type LoopDoctorReport, type LoopEvent, type LoopEventBus, type LoopEventListener, type LoopEventPayload, type LoopHookListener, type LoopHookName, type LoopHookPayload, type LoopHookResult, type LoopIssue, type LoopPluginModule, type LoopProviderConfig, type LoopStage, type LoopStageName, type LoopState, type LoopStatusReport, MEMORY_SCOPES, MODEL_ROLES, type MachineMetrics, type MachineSample, type MachineThresholds, type McpPolicy, type McpToolBridge, type McpToolBridgeOptions, type McpToolCallInput, type McpToolCallResult, type MemoryContextPlan, type MemoryPromptSelection, type MemoryScope, type MemoryUsage, type MetricStatus, type ModelBinding, type ModelPolicy, type ModelQuality, type ModelReference, type ModelRole, type NormalizedPhaseProfile, type ObservabilityAnomaly, type ObservabilityMetrics, type ObservabilityReport, type ObservabilitySeverity, type ObservabilitySnapshot, type ObservabilityTerminal, type OptimizationComparison, type OptimizationObservation, type OrcaAgentHookState, type OrcaAutomation, type OrcaAutomationSpec, type OrcaCliOptions, type OrcaCreatedWorktree, type OrcaDispatchInput, type OrcaDispatchPlan, type OrcaLeaseState, type OrcaLifecycleInput, type OrcaLifecycleProjection, type OrcaMemorySample, type OrcaStatus as OrcaRuntimeStatus, type OrcaSendReceipt, type OrcaTerminal, type OrcaWorktree, type OutcomeProgress, type OutcomeProgressStatus, PHASE_DECISIONS, PHASE_EFFECTS, PHASE_EFFECT_ACTIONS, PHASE_MODES, PR_FIELDS, type ParallelismUsage, type PhaseAmbiguity, type PhaseContext, type PhaseDecision, type PhaseDecisionPacket, type PhaseDefinition, type PhaseEffect, type PhaseEffectAction, type PhaseEffectPolicy, type PhaseExecution, type PhaseExecutionReport, type PhaseGateEvaluator, type PhaseGateResult, type PhaseHandler, type PhaseHandlerResult, type PhaseMachineMetrics, type PhaseMode, type PhasePreflight, type PhasePreflightResult, type PhaseProfile, type PhaseResumeState, type PhaseRetryPolicy, type PhaseRoutePlan, type PhaseTelemetry, type PhaseTokenMetrics, type PiiKind, type PiiMatch, type PiiScanResult, type PilotAssessment, type PilotEntry, type PilotManifest, type PinnedSkill, type PinnedSkillRef, type PluginContribution, type PluginRegistry, type PluginSlot, type PolicyDecision, type PolicyGate, type PolicyRequest, type PolicyRule, type ProcessToolDefinition, type ProductionEvidence, type ProviderAuthStatus, type ProviderAvailability, type ProviderCatalog, type ProviderFailure, type ProviderSpec, type ProviderUsage, type PullRequestApproval, type PullRequestCheck, type PullRequestDraft, type PullRequestSnapshot, QUALITY_DIMENSIONS, type QaTransitionAssessment, type QualityDimension, type QualityDimensionScore, type QualityMatrix, REVIEW_SEVERITIES, RUN_STATES, type RagContextProviderOptions, type RagQueryResult, type RankedModel, type RecoveryObservation, type RecoveryPolicy, type RecoveryResult, type RepositoryProfile, type ResolvedAgent, type RetroInput, type RetroIssueRow, type RetroReport, type RetroStageReport, type RetroSuggestion, type RetroTarget, type RetroWindow, type ReviewFinding, type ReviewLens, type ReviewSeverity, type ReviewVerdict, type RichIO, type RoutingDecision, type RoutingSkip, type RunOutcome, type RunReconciliation, type RunState, type RuntimeConfig, type RuntimeExperimentCandidate, type RuntimeExperimentResult, STATES, SURFACE_NAMES, type SessionRecorder, type SlotAssessment, type SlotInput, type SourceSnapshot, type StagePauseEntry, type StagePauseState, type StateTransition, type StatusBlock, type StatusSnapshot, type StoredContract, type StructuredEvidence, type SurfaceName, type SurfaceRequirement, type TaskContract, TaskContractSchema, type TeamMember, type TickCandidateResult, type TickInput, type TickOutcome, type TickReport, type TokenUsage, type ToolDefinition, type ToolExecutionRequest, type ToolExecutionResult, type ToolRuntime, type TrackingAdapter, type TrackingConfig, type TrackingTransition, type TrustedEvidenceKey, type UsageMetric, type UsageWindow, type VerificationCheck, type VerificationConfig, type VerificationRun, WIP_STATES, type WatchEvent, type WatchEventKind, type WatchInput, type WatchReport, type WatchTargetSnapshot, type WatchdogBlocker, type WatchdogBudget, type WatchdogResult, type WipAssessment, type WipAssessmentInput, type WipEntry, type WipState, type WorkerBriefInput, type WorkflowNode, type WorkflowResult, activeCooldowns, adaptiveConcurrency, advanceQueueOwner, appendLoopEvent, approveRun, approvedDecision, artifactDigest, artifactFilePath, artifactIsFresh, artifactMarkdownPath, assertHuman, assessAcceptance, assessAgentEval, assessBlock, assessChecks, assessCompatibility, assessContract, assessDiscovery, assessImprovementCycle, assessIntegration, assessObservability, assessPilot, assessPreflight, assessProduction, assessQaTransition, assessSlots, assessWip, assessWorktreeCleanup, atLeast, authStatusFor, authorizeRun, automationName, automationPrompt, automationSpecs, availableMemoryBytes, benchmarkRuns, branchFor, briefPath, buildDebriefReport, buildListIssuesArgv, buildRetroReport, buildReviewArgv, buildSuggestions, busyIssues, cancelRun, classifyFailure, classifyHarnessError, classifyProviderFailure, classifyWatchEvent, classifyWatchPhase, cleanTaskArtifacts, clearIssueFailures, clearProviderCooldown, compareOptimization, compareVersions, composePullRequest, contractIsFresh, contractPath, cooldownPath, cooldownUntil, countRotationBlockingLeases, countRunningWorkers, createArgvRagContextProvider, createArtifactEnvelope, createCapabilityManifest, createCodingAgentAdapter, createCompatibilityManifest, createConfiguredToolRuntime, createDispatchLedger, createDocBridgeContextProvider, createDockerToolRuntime, createEvalManifest, createFileMemoryAdapter, createFileMemoryKvStore, createHarnessEventEnvelope, createInMemoryMemoryAdapter, createKvMemoryAdapter, createLinearTrackingAdapter, createLlmCache, createLlmCacheKey, createLoopEventBus, createMachineMonitor, createMcpToolBridge, createModelPolicy, createOrcaDispatchPlan, createOrcaLifecycleProjection, createPhaseArtifact, createPhaseProfile, createPluginRegistry, createPluginSlot, createPolicyGate, createProcessRunner, createProcessToolRuntime, createPullRequestApproval, createQualityMatrix, createRagContextProvider, createRichIO, createSessionRecorder, createStatusSnapshot, createToolRuntime, createTrackingAdapter, createTrackingTransition, deliveryStatePath, detectProviders, discoverIntake, dispatchRecordPath, evaluateWatchdog, executePhaseProfile, exportEvidenceBundle, extractResetsAt, fetchArtificialAnalysisModels, fetchLinearIssue, fetchLinearQueue, fetchTeamMembers, filterAndOrderQueue, findExecutable, formatWatchEvent, gatherLoopState, generateContract, githubComment, githubCommentArgv, githubCommentExists, githubLabelRemove, githubMerge, githubMergeArgv, githubOpenPullRequests, githubPullRequest, githubPullRequestsForBranch, hasLocalConfig, hashContextSnapshot, hashContextSnapshots, hashMcpArgs, inspectDocBridgeIndex, inspectEventLogLock, installLoopAutomations, installPreflight, intakeIssueId, intakePath, isDiscoveryCurrent, isIssuePaused, isStagePaused, isWsl, issueFailurePath, launchWorkerTerminal, learningToMemoryRecord, learningsPath, linearAttach, linearAttachArgv, linearCommentAdd, linearCommentAddArgv, linearLabelAdd, linearLabelArgv, linearLabelRemove, linearStatusSet, linearStatusSetArgv, listCliModels, listCliModelsCached, listDispatched, listIntake, listPausedIssues, loadAgentRegistry, loadAliases, loadBenchmarkManifest, loadBuiltinCatalog, loadConfig, loadLatestRun, loadLoopConfig, loadLoopPlugins, loadPinnedSkills, localConfigPath, loopStatus, markProviderExhausted, memoryDigestOf, mergeLoopConfig, modelFor, normalizeReason, openLoopMemory, orcaAccountList, orcaAgentHooks, orcaAutomationCreateArgv, orcaAutomationEditArgv, orcaAutomationRemove, orcaAutomationRun, orcaAutomationRuns, orcaAutomationsList, orcaDiagnosticsMemory, orcaJson, orcaStatus, orcaTerminalCreate, orcaTerminalList, orcaTerminalScreen, orcaTerminalSend, orcaTerminalWait, orcaVersion, orcaWorktreeCreate, orcaWorktreeRemove, orcaWorktreeSet, orcaWorktreeSetArgv, orcaWorktrees, parseAgentRegistryText, parseArtificialAnalysisPayload, parseAutomationRuns, parseContractOutput, parseGrokModelsOutput, parseJsonEnvelope, parseLinearIssueDetail, parseLinearIssues, parseLoopConfigText, parseMemInfo, parseModelRef, parseOrcaAgentHooks, parseOrcaAutomations, parseOrcaSendReceipt, parseOrcaStatus, parseOrcaTerminals, parseOrcaVersion, parseOrcaWorktreeCreate, parseOrcaWorktrees, parseProviderUsage, parsePullRequest, parseRagQueryOutput, parseRetro, parseReviewResult, parseSince, parseTeamMembers, parseUsageWindows, parseVmStat, pauseIssue, planFilePreflight, planMemoryContext, planPhaseProfile, planRun, precheckCommand, precheckDeliver, precheckTick, preferMemoryOverDocBridge, promoteLearnings, promoteLearningsToMemory, promptLocalConfig, providerIdentity, providerSpecs, queueOwner, rankModels, readAaCache, readArtifactFile, readCliModelsCache, readContextSnapshots, readCooldowns, readDeliveryState, readDispatchRecord, readEvidenceTrustStore, readIntake, readIssueFailures, readLearningsLedger, readLoopEvents, readOutcomeProgress, readStagePause, readStoredContract, reconcileRun, recordBenchmarkObservation, recordIssueFailure, recordStageRunResult, recoverEventLogLock, recoveryDelayMs, remainingUsagePercent, renderArtifactMarkdown, renderContractPrompt, renderDebriefMarkdown, renderFindingsForWorker, renderHandoffBrief, renderHeadlessArgv, renderLocalConfig, renderObservabilityMarkdown, renderPinnedSkills, renderRetroMarkdown, renderTuiCommand, renderWorkerBrief, resolveAgentForRole, resolveAlias, resolveCatalogCandidates, resolveDocContext, resumeIssue, resumeStage, resumeStateFromArtifacts, retroLearnings, retryRun, rotationStatePath, routeAllRoles, runAdversarialReview, runAgentEval, runCodeReview, runDeliver, runEvalBattery, runGuidedInstall, runLoopDoctor, runObservability, runRetroStage, runTick, runWithRecovery, runWorkflow, sampleMachine, scanForPii, selectMemoryForPrompt, selectModel, selectRuntime, severityRank, shellQuote, skillDigest, skillRefs, snapshotWatchTargets, stageEntry, stagePausePath, startRun, summarizeMachine, tiersFor, touchesProtectedPaths, transition, undeclaredOrcaProviders, uninstallLoopAutomations, unknownTelemetry, untrusted, upsertProposedLearnings, usageRankTuple, validateAdapterMetadata, validateArtifactEnvelope, validateBenchmarkManifest, validateBlockManifest, validateCacheableOperation, validateCapabilityManifest, validateCompatibilityManifest, validateConfig, validateContextSnapshot, validateContextSnapshots, validateEvalManifest, validateHarnessErrorClassification, validateHarnessEventEnvelope, validateLoopConfig, validateMemoryRecord, validateOptimizationObservation, validatePhaseTelemetry, validateSafeCommand, validateStatusSnapshot, verifyEvidenceBundle, verifyPullRequestApproval, verifyRun, watchDeliveries, worktreeNameFor, writeAaCache, writeCliModelsCache, writeDispatchRecord, writeIdFor, writeLearningsLedger, writeLocalConfig, writeStoredContract };
4607
+ export { AGENT_REGISTRY_SCHEMA_VERSION, ARTIFACT_SCHEMA_VERSION, ARTIFACT_TYPES, ASSURANCE_LEVELS, type AdapterMetadata, type AdapterTelemetry, type AdversarialReviewResult, type AgentAdapter, type AgentEvalCase, type AgentEvalReport, type AgentEvalSuite, type AgentMemoryAdapter, type AgentMemoryHit, type AgentMemoryKvStore, type AgentMemoryRecord, type AgentRegistry, type AgentRegistryEntry, AgentRegistryEntrySchema, AgentRegistrySchema, type AgentSessionOptions, type AgentUsage, type ApprovedAssumption, type ArgvRagContextProviderOptions, type ArtifactBinding, type ArtifactEnvelope, type ArtifactEnvelopeInput, type ArtifactType, type ArtificialAnalysisModel, type AssuranceLevel, type AutomationStatus, type AutonomyMode, BENCHMARK_SCHEMA_VERSION, BLOCK_STATUSES, type BenchmarkBinding, type BenchmarkComparison, type BenchmarkImprovementDirection, type BenchmarkManifest, type BenchmarkObservation, type BenchmarkObservationEvidence, type BenchmarkObservationInput, type BenchmarkObservationStatus, type BenchmarkReport, type BenchmarkRun, type BenchmarkSummary, type BenchmarkTask, type BlockAssessment, type BlockManifest, type BlockStatus, CAPABILITY_KINDS, CAPABILITY_MANIFEST_SCHEMA_VERSION, CHECK_CATEGORIES, COMPATIBILITY_COMPONENTS, COMPATIBILITY_SCHEMA_VERSION, CONTEXT_PROVIDER_SLOT, CONTRACT_CLOSE, CONTRACT_OPEN, CONTRACT_SCHEMA_VERSION, type CacheUsage, type CapabilityDescriptor, type CapabilityKind, type CapabilityManifest, type CapabilityManifestInput, type CatalogModel, type ChangedFile, type CheckCategory, type CheckOutcome, type CheckResult, type ChecksAssessment, type ClaimResult, type CodeReviewInput, type CodeReviewOutcome, type CodingAgentAdapter, type CodingAgentHandlerResult, type CodingAgentRequest, type CodingAgentResult, type CommandResult, type CommandRunOptions, type CommandRunner, type CompatibilityComponent, type CompatibilityComponentId, type CompatibilityManifest, type CompatibilityObservation, type CompatibilityReport, type CompatibilityStatus, type ContextProvider, type ContextQuery, type ContextReference, type ContextSnapshot, type ContractAssessment, type ContractOutcome, ContractOutcomeSchema, type ContractScope, type CooldownEntry, type CooldownState, type CoordinationIdentity, type CriterionStatus, type CycleIterationMetrics, type CycleMatrixRow, type CycleStepResult, type CycleStepStatus, type DebriefInput, type DebriefIssueRow, type DebriefReport, type DecisionPacket, type DeliverInput, type DeliverOutcome, type DeliverReport, type DeliverResult, type DeliveryState, type DetectProvidersInput, type DiscoveryAmbiguity, type DiscoveryCurrentInput, type DiscoveryCurrentResult, type DiscoveryDecisionLogEntry, type DiscoveryInput, type DiscoveryOption, type DiscoveryResult, type DispatchLease, type DispatchLedger, type DispatchRecord, type DispatchRecordFile, type Disposer, type DocBridgeIndexInspection, type DockerMount, type DockerRuntimeEvidence, type DockerToolDefinition, type DoctorCheck, type DoctorCheckStatus, EVAL_COMPONENTS, EVAL_LAYERS, EVAL_MANIFEST_SCHEMA_VERSION, EVENT_LOG_GENESIS, EVIDENCE_BUNDLE_SCHEMA_VERSION, EVIDENCE_MAX_FILE_BYTES, EVIDENCE_MAX_TOTAL_BYTES, type EffortLevel, type EvalBatteryReport, type EvalCaseDefinition, type EvalCaseReport, type EvalComponent, type EvalExpectation, type EvalLayer, type EvalManifest, type EvalObservation, type EvalObservationStatus, type EventLogLock, type EventLogLockRecovery, type EventLogLockStatus, type EventLogVerification, type EventStore, type EvidenceArtifact, type EvidenceBundle, type EvidenceBundleFile, type EvidenceBundleSignature, type EvidenceBundleVerification, type EvidenceReference, type ExecutePhaseProfileOptions, type FailureClass, type FailureClassification, type FetchQueueInput, FileArtifactStore, FileEventStore, type FilePreflightPlan, type GateAssessment, type GateBinding, type GateCriterion, type GenerateContractInput, type GitHubCliOptions, type GuidedInstallIO, type GuidedInstallInput, type GuidedInstallReport, HARNESS_ERROR_CATALOG, HARNESS_ERROR_CODES, HARNESS_EVENT_ENVELOPE_SCHEMA_VERSION, HARNESS_EVENT_SCHEMA_VERSION, HARNESS_EVENT_TYPES, HARNESS_PLUGIN_API_VERSION, HARNESS_REPO_URL, type HandoffBriefInput, HarnessError, type HarnessErrorClassification, type HarnessErrorDisposition, type HarnessEvent, type HarnessEventContext, type HarnessEventEnvelope, type HarnessEventEnvelopeInput, type HarnessEventInput, type HarnessEventListener, type HarnessEventPayloads, type HarnessEventProvenance, type HarnessEventType, type HarnessPlugin, type HarnessPluginContext, IMPROVEMENT_CYCLE_STEPS, type ImprovementCycleAssessment, type ImprovementCycleInput, type ImprovementCycleIteration, type ImprovementCycleStep, type InstallAction, type InstallInput, type InstallReport, type IntakeRecord, type IssueFailureRecord, type IssueFailureState, LEARNING_STATUSES, LEGAL_TRANSITIONS, LOOP_CONFIG_FILE, LOOP_CONFIG_SCHEMA_VERSION, LOOP_LOCAL_CONFIG_FILE, LOOP_STAGES, type LearningRecord, type LearningStatus, type LearningsLedger, type LinearIssueDetail, type LinearListInput, type LinearQueueFilter, type LinearWriteOptions, type LlmCache, type LlmCacheKeyInput, type LlmCacheStats, type LoadedConfig, type LoadedLoopConfig, type LocalConfigAnswers, type LocalConfigPrompter, type LoopConfig, type LoopConfigInput, LoopConfigSchema, type LoopDoctorInput, type LoopDoctorReport, type LoopEvent, type LoopEventBus, type LoopEventListener, type LoopEventPayload, type LoopHookListener, type LoopHookName, type LoopHookPayload, type LoopHookResult, type LoopIssue, type LoopPluginModule, type LoopProviderConfig, type LoopStage, type LoopStageName, type LoopState, type LoopStatusReport, MEMORY_SCOPES, MODEL_ROLES, type MachineMetrics, type MachineSample, type MachineThresholds, type McpPolicy, type McpToolBridge, type McpToolBridgeOptions, type McpToolCallInput, type McpToolCallResult, type MemoryContextPlan, type MemoryPromptSelection, type MemoryScope, type MemoryUsage, type MetricStatus, type ModelBinding, type ModelPolicy, type ModelQuality, type ModelReference, type ModelRole, type NormalizedPhaseProfile, type ObservabilityAnomaly, type ObservabilityMetrics, type ObservabilityReport, type ObservabilitySeverity, type ObservabilitySnapshot, type ObservabilityTerminal, type OptimizationComparison, type OptimizationObservation, type OrcaAgentHookState, type OrcaAutomation, type OrcaAutomationSpec, type OrcaCliOptions, type OrcaCreatedWorktree, type OrcaDispatchInput, type OrcaDispatchPlan, type OrcaLeaseState, type OrcaLifecycleInput, type OrcaLifecycleProjection, type OrcaMemorySample, type OrcaStatus as OrcaRuntimeStatus, type OrcaSendReceipt, type OrcaTerminal, type OrcaWorktree, type OutcomeProgress, type OutcomeProgressStatus, PHASE_DECISIONS, PHASE_EFFECTS, PHASE_EFFECT_ACTIONS, PHASE_MODES, PR_FIELDS, type ParallelismUsage, type PhaseAmbiguity, type PhaseContext, type PhaseDecision, type PhaseDecisionPacket, type PhaseDefinition, type PhaseEffect, type PhaseEffectAction, type PhaseEffectPolicy, type PhaseExecution, type PhaseExecutionReport, type PhaseGateEvaluator, type PhaseGateResult, type PhaseHandler, type PhaseHandlerResult, type PhaseMachineMetrics, type PhaseMode, type PhasePreflight, type PhasePreflightResult, type PhaseProfile, type PhaseResumeState, type PhaseRetryPolicy, type PhaseRoutePlan, type PhaseTelemetry, type PhaseTokenMetrics, type PiiKind, type PiiMatch, type PiiScanResult, type PilotAssessment, type PilotEntry, type PilotManifest, type PinnedSkill, type PinnedSkillRef, type PluginContribution, type PluginRegistry, type PluginSlot, type PolicyDecision, type PolicyGate, type PolicyRequest, type PolicyRule, type ProcessToolDefinition, type ProductionEvidence, type ProviderAuthStatus, type ProviderAvailability, type ProviderCatalog, type ProviderFailure, type ProviderSpec, type ProviderUsage, type PullRequestApproval, type PullRequestCheck, type PullRequestDraft, type PullRequestSnapshot, QUALITY_DIMENSIONS, type QaTransitionAssessment, type QualityDimension, type QualityDimensionScore, type QualityMatrix, REVIEW_SEVERITIES, RUN_STATES, type RagContextProviderOptions, type RagQueryResult, type RankedModel, type RecoveryObservation, type RecoveryPolicy, type RecoveryResult, type RepositoryProfile, type ResolvedAgent, type RetroInput, type RetroIssueRow, type RetroReport, type RetroStageReport, type RetroSuggestion, type RetroTarget, type RetroWindow, type ReviewFinding, type ReviewLens, type ReviewSeverity, type ReviewVerdict, type RichIO, type RoutingDecision, type RoutingSkip, type RunOutcome, type RunReconciliation, type RunState, type RuntimeConfig, type RuntimeExperimentCandidate, type RuntimeExperimentResult, STATES, SURFACE_NAMES, type SessionRecorder, type SlotAssessment, type SlotInput, type SourceSnapshot, type StagePauseEntry, type StagePauseState, type StateTransition, type StatusBlock, type StatusSnapshot, type StoredContract, type StructuredEvidence, type SurfaceName, type SurfaceRequirement, type TaskContract, TaskContractSchema, type TeamMember, type TickCandidateResult, type TickInput, type TickOutcome, type TickReport, type TokenUsage, type ToolDefinition, type ToolExecutionRequest, type ToolExecutionResult, type ToolRuntime, type TrackingAdapter, type TrackingConfig, type TrackingTransition, type TrustedEvidenceKey, type UsageMetric, type UsageWindow, type VerificationCheck, type VerificationConfig, type VerificationRun, WIP_STATES, type WatchEvent, type WatchEventKind, type WatchInput, type WatchReport, type WatchTargetSnapshot, type WatchdogBlocker, type WatchdogBudget, type WatchdogResult, type WipAssessment, type WipAssessmentInput, type WipEntry, type WipState, type WorkerBriefInput, type WorkflowNode, type WorkflowResult, activeCooldowns, adaptiveConcurrency, advanceQueueOwner, appendLoopEvent, approveRun, approvedDecision, artifactDigest, artifactFilePath, artifactIsFresh, artifactMarkdownPath, assertHuman, assessAcceptance, assessAgentEval, assessBlock, assessChecks, assessCompatibility, assessContract, assessDiscovery, assessImprovementCycle, assessIntegration, assessObservability, assessPilot, assessPreflight, assessProduction, assessQaTransition, assessSlots, assessWip, assessWorktreeCleanup, atLeast, authStatusFor, authorizeRun, automationName, automationPrompt, automationSpecs, availableMemoryBytes, benchmarkRuns, branchFor, briefPath, buildDebriefReport, buildListIssuesArgv, buildRetroReport, buildReviewArgv, buildSuggestions, busyIssues, cancelRun, classifyFailure, classifyHarnessError, classifyProviderFailure, classifyWatchEvent, classifyWatchPhase, cleanTaskArtifacts, clearIssueFailures, clearProviderCooldown, compareOptimization, compareVersions, composePullRequest, contractIsFresh, contractPath, cooldownPath, cooldownUntil, countRotationBlockingLeases, countRunningWorkers, createArgvRagContextProvider, createArtifactEnvelope, createCapabilityManifest, createCodingAgentAdapter, createCompatibilityManifest, createConfiguredToolRuntime, createDispatchLedger, createDocBridgeContextProvider, createDockerToolRuntime, createEvalManifest, createFileMemoryAdapter, createFileMemoryKvStore, createHarnessEventEnvelope, createInMemoryMemoryAdapter, createKvMemoryAdapter, createLinearTrackingAdapter, createLlmCache, createLlmCacheKey, createLoopEventBus, createMachineMonitor, createMcpToolBridge, createModelPolicy, createOrcaDispatchPlan, createOrcaLifecycleProjection, createPhaseArtifact, createPhaseProfile, createPluginRegistry, createPluginSlot, createPolicyGate, createProcessRunner, createProcessToolRuntime, createPullRequestApproval, createQualityMatrix, createRagContextProvider, createRichIO, createSessionRecorder, createStatusSnapshot, createToolRuntime, createTrackingAdapter, createTrackingTransition, deliveryStatePath, detectProviders, discoverIntake, dispatchRecordPath, evaluateWatchdog, executePhaseProfile, exportEvidenceBundle, extractResetsAt, fetchArtificialAnalysisModels, fetchLinearIssue, fetchLinearQueue, fetchTeamMembers, filterAndOrderQueue, findExecutable, formatWatchEvent, gatherLoopState, generateContract, githubComment, githubCommentArgv, githubCommentExists, githubLabelRemove, githubMerge, githubMergeArgv, githubOpenPullRequests, githubPullRequest, githubPullRequestsForBranch, hasLocalConfig, hashContextSnapshot, hashContextSnapshots, hashMcpArgs, inspectDocBridgeIndex, inspectEventLogLock, installLoopAutomations, installPreflight, intakeIssueId, intakePath, isDiscoveryCurrent, isIssuePaused, isStagePaused, isWsl, issueFailurePath, launchWorkerTerminal, learningToMemoryRecord, learningsPath, linearAttach, linearAttachArgv, linearCommentAdd, linearCommentAddArgv, linearLabelAdd, linearLabelArgv, linearLabelRemove, linearStatusSet, linearStatusSetArgv, listCliModels, listCliModelsCached, listDispatched, listIntake, listPausedIssues, loadAgentRegistry, loadAliases, loadBenchmarkManifest, loadBuiltinCatalog, loadConfig, loadLatestRun, loadLoopConfig, loadLoopPlugins, loadPinnedSkills, localConfigPath, loopStatus, markProviderExhausted, memoryDigestOf, mergeLoopConfig, modelFor, normalizeReason, openLoopMemory, orcaAccountList, orcaAgentHooks, orcaAutomationCreateArgv, orcaAutomationEditArgv, orcaAutomationRemove, orcaAutomationRun, orcaAutomationRuns, orcaAutomationsList, orcaDiagnosticsMemory, orcaJson, orcaStatus, orcaTerminalCreate, orcaTerminalList, orcaTerminalScreen, orcaTerminalSend, orcaTerminalWait, orcaVersion, orcaWorktreeCreate, orcaWorktreeRemove, orcaWorktreeSet, orcaWorktreeSetArgv, orcaWorktrees, parseAgentRegistryText, parseArtificialAnalysisPayload, parseAutomationRuns, parseContractOutput, parseGrokModelsOutput, parseJsonEnvelope, parseLinearIssueDetail, parseLinearIssues, parseLoopConfigText, parseMemInfo, parseModelRef, parseOrcaAgentHooks, parseOrcaAutomations, parseOrcaSendReceipt, parseOrcaStatus, parseOrcaTerminals, parseOrcaVersion, parseOrcaWorktreeCreate, parseOrcaWorktrees, parseProviderUsage, parsePullRequest, parseRagQueryOutput, parseRetro, parseReviewResult, parseSince, parseTeamMembers, parseUsageWindows, parseVmStat, pauseIssue, planFilePreflight, planMemoryContext, planPhaseProfile, planRun, precheckCommand, precheckDeliver, precheckTick, preferMemoryOverDocBridge, promoteLearnings, promoteLearningsToMemory, promptLocalConfig, providerIdentity, providerSpecs, queueOwner, rankModels, readAaCache, readArtifactFile, readCliModelsCache, readContextSnapshots, readCooldowns, readDeliveryState, readDispatchRecord, readEvidenceTrustStore, readIntake, readIssueFailures, readLearningsLedger, readLoopEvents, readOutcomeProgress, readStagePause, readStoredContract, reconcileRun, recordBenchmarkObservation, recordIssueFailure, recordStageRunResult, recoverEventLogLock, recoveryDelayMs, remainingUsagePercent, renderArtifactMarkdown, renderContractPrompt, renderDebriefMarkdown, renderFindingsForWorker, renderHandoffBrief, renderHeadlessArgv, renderLocalConfig, renderObservabilityMarkdown, renderPinnedSkills, renderRetroMarkdown, renderTuiCommand, renderWorkerBrief, resolveAgentForRole, resolveAlias, resolveCatalogCandidates, resolveDocContext, resumeIssue, resumeStage, resumeStateFromArtifacts, retroLearnings, retryRun, rotationStatePath, routeAllRoles, runAdversarialReview, runAgentEval, runCodeReview, runDeliver, runEvalBattery, runGuidedInstall, runLoopDoctor, runObservability, runRetroStage, runTick, runWithRecovery, runWorkflow, sampleMachine, scanForPii, selectMemoryForPrompt, selectModel, selectRuntime, severityRank, shellQuote, skillDigest, skillRefs, snapshotWatchTargets, stageEntry, stagePausePath, startRun, summarizeMachine, tiersFor, touchesProtectedPaths, transition, undeclaredOrcaProviders, uninstallLoopAutomations, unknownTelemetry, untrusted, upsertProposedLearnings, usageRankTuple, validateAdapterMetadata, validateArtifactEnvelope, validateBenchmarkManifest, validateBlockManifest, validateCacheableOperation, validateCapabilityManifest, validateCompatibilityManifest, validateConfig, validateContextSnapshot, validateContextSnapshots, validateEvalManifest, validateHarnessErrorClassification, validateHarnessEventEnvelope, validateLoopConfig, validateMemoryRecord, validateOptimizationObservation, validatePhaseTelemetry, validateSafeCommand, validateStatusSnapshot, verifyEvidenceBundle, verifyPullRequestApproval, verifyRun, watchDeliveries, worktreeNameFor, writeAaCache, writeCliModelsCache, writeDispatchRecord, writeIdFor, writeLearningsLedger, writeLocalConfig, writeStoredContract };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { resolve, dirname, join, relative, isAbsolute, delimiter, basename, extname, sep } from 'path';
2
2
  import { createHash, randomUUID, createPrivateKey, createPublicKey, sign, verify } from 'crypto';
3
- import { existsSync, mkdirSync, openSync, writeSync, appendFileSync, closeSync, unlinkSync, readFileSync, writeFileSync, statSync, readdirSync, mkdtempSync, renameSync, rmSync } from 'fs';
3
+ import { existsSync, mkdirSync, openSync, writeSync, appendFileSync, closeSync, unlinkSync, readFileSync, writeFileSync, statSync, readdirSync, mkdtempSync, renameSync, rmSync, accessSync, constants } from 'fs';
4
4
  import { execFile, spawn, execFileSync } from 'child_process';
5
5
  import { promisify } from 'util';
6
6
  import { cpus, loadavg, freemem, totalmem, tmpdir, release } from 'os';
@@ -1283,9 +1283,9 @@ var createDocBridgeContextProvider = ({ root, indexPath = ".doc-bridge/index.jso
1283
1283
  const started = Date.now();
1284
1284
  const ageBudget = maxAgeHours ?? 0;
1285
1285
  const inspection = ageBudget > 0 ? inspectDocBridgeIndex(root, indexPath, now4()) : null;
1286
- if (inspection?.error) throw new Error(`Doc Bridge index is unreadable: ${inspection.error}`);
1286
+ if (inspection?.error) fail(`Doc Bridge index is unreadable: ${inspection.error}`, "INVALID_STATE");
1287
1287
  if (inspection?.ageHours !== null && inspection?.ageHours !== void 0 && inspection.ageHours > ageBudget) {
1288
- throw new Error(`Doc Bridge index is ${inspection.ageHours.toFixed(1)}h old; refresh it before resolving context.`);
1288
+ fail(`Doc Bridge index is ${inspection.ageHours.toFixed(1)}h old; refresh it before resolving context.`, "STALE");
1289
1289
  }
1290
1290
  const document = index(root, indexPath);
1291
1291
  const contentHash = sourceHash(document);
@@ -1306,7 +1306,9 @@ var createDocBridgeContextProvider = ({ root, indexPath = ".doc-bridge/index.jso
1306
1306
  });
1307
1307
  var executable = (path) => {
1308
1308
  try {
1309
- return statSync(path).isFile();
1309
+ if (!statSync(path).isFile()) return false;
1310
+ accessSync(path, constants.X_OK);
1311
+ return true;
1310
1312
  } catch {
1311
1313
  return false;
1312
1314
  }
@@ -1963,7 +1965,7 @@ var validateIteration = (iteration, index2) => {
1963
1965
  if (typeof result !== "object" || result === null || Array.isArray(result)) return fail(`iterations[${index2}].steps[${stepIndex}] must be an object.`, "INVALID_INPUT");
1964
1966
  if (result.step !== IMPROVEMENT_CYCLE_STEPS[stepIndex]) return fail(`iterations[${index2}].steps[${stepIndex}] must be ${IMPROVEMENT_CYCLE_STEPS[stepIndex]}.`, "INVALID_INPUT");
1965
1967
  if (!["passed", "failed", "blocked", "pending"].includes(result.status)) return fail(`iterations[${index2}].steps[${stepIndex}].status is invalid.`, "INVALID_INPUT");
1966
- if (result.status !== "passed" && !nonEmpty3(result.reason, `iterations[${index2}].steps[${stepIndex}].reason`)) return fail(`iterations[${index2}].steps[${stepIndex}].reason is required when the step does not pass.`, "INVALID_INPUT");
1968
+ if (result.status !== "passed" && (typeof result.reason !== "string" || !result.reason.trim())) return fail(`iterations[${index2}].steps[${stepIndex}].reason is required when the step does not pass.`, "INVALID_INPUT");
1967
1969
  });
1968
1970
  if (iteration.adjustment !== void 0) nonEmpty3(iteration.adjustment, `iterations[${index2}].adjustment`);
1969
1971
  return { ...iteration, metrics: validateMetrics(iteration.metrics, index2) };
@@ -1977,8 +1979,10 @@ var assessImprovementCycle = (input) => {
1977
1979
  const iterations = input.iterations.map(validateIteration);
1978
1980
  iterations.forEach((iteration, index2) => {
1979
1981
  if (iteration.iteration !== index2 + 1) return fail("iterations must be sequential and start at 1.", "INVALID_INPUT");
1980
- if (index2 > 0 && iterations[index2 - 1]?.steps.every((step) => step.status === "passed")) return fail("a completed cycle cannot have later iterations.", "INVALID_INPUT");
1981
- if (index2 < iterations.length - 1 && !iteration.adjustment) return fail(`iterations[${index2}].adjustment is required before repeating.`, "INVALID_INPUT");
1982
+ const isLast = index2 === iterations.length - 1;
1983
+ const iterationComplete = iteration.steps.every((step) => step.status === "passed");
1984
+ if (iterationComplete && !isLast) return fail("a completed cycle cannot have later iterations.", "INVALID_INPUT");
1985
+ if (!isLast && !iteration.adjustment) return fail(`iterations[${index2}].adjustment is required before repeating.`, "INVALID_INPUT");
1982
1986
  });
1983
1987
  const matrix = iterations.map((iteration) => {
1984
1988
  const statuses = Object.fromEntries(iteration.steps.map((step) => [step.step, step.status]));
@@ -3230,7 +3234,6 @@ var createSessionRecorder = ({ stateDir, run, adapter, policy, runtime, sessionI
3230
3234
  const approvals = /* @__PURE__ */ new Map();
3231
3235
  const released = /* @__PURE__ */ new Map();
3232
3236
  const attempts = /* @__PURE__ */ new Map();
3233
- const executing = /* @__PURE__ */ new Set();
3234
3237
  let ended = false;
3235
3238
  if (resume) {
3236
3239
  const prior = store.read(run.runId).filter((event2) => event2.sessionId === id2);
@@ -3358,30 +3361,27 @@ var createSessionRecorder = ({ stateDir, run, adapter, policy, runtime, sessionI
3358
3361
  const actionId = required9(input.actionId, "actionId");
3359
3362
  const action = pending.get(actionId) ?? fail(`Tool action is not pending: ${actionId}.`, "INVALID_STATE");
3360
3363
  if (action.executionStarted) fail(`Tool action requires human recovery decision: ${actionId}.`, "HUMAN_APPROVAL_REQUIRED");
3361
- if (executing.has(actionId)) fail(`Tool action is already executing: ${actionId}.`, "INVALID_STATE");
3362
- executing.add(actionId);
3363
3364
  action.executionStarted = true;
3364
3365
  const attempt = (attempts.get(actionId) ?? 0) + 1;
3365
3366
  attempts.set(actionId, attempt);
3366
3367
  append("tool.execution.started", { actionId, turnId: action.turnId, toolId: action.toolId, attempt });
3368
+ let result;
3367
3369
  try {
3368
- const result = await runtime.execute({ actionId, turnId: action.turnId, toolId: action.toolId, argumentsHash: action.argumentsHash, arguments: input.arguments });
3369
- if (result.status === "completed") {
3370
- complete2({ actionId, resultHash: result.resultHash, durationMs: result.durationMs, runtimeEvidence: result.runtimeEvidence });
3371
- return result;
3372
- }
3373
- if (result.status === "failed") {
3374
- failAction({ actionId, errorCode: result.errorCode, retryable: result.retryable, durationMs: result.durationMs, runtimeEvidence: result.runtimeEvidence });
3375
- return result;
3376
- }
3377
- return fail("Runtime returned an invalid execution result.", "HARNESS_ERROR");
3370
+ result = await runtime.execute({ actionId, turnId: action.turnId, toolId: action.toolId, argumentsHash: action.argumentsHash, arguments: input.arguments });
3378
3371
  } catch {
3379
- const result = { status: "failed", errorCode: "RUNTIME_ERROR", retryable: true, durationMs: 0 };
3380
- if (pending.has(actionId)) failAction({ actionId, ...result });
3372
+ const failure = { status: "failed", errorCode: "RUNTIME_ERROR", retryable: true, durationMs: 0 };
3373
+ if (pending.has(actionId)) failAction({ actionId, ...failure });
3374
+ return failure;
3375
+ }
3376
+ if (result.status === "completed") {
3377
+ complete2({ actionId, resultHash: result.resultHash, durationMs: result.durationMs, runtimeEvidence: result.runtimeEvidence });
3381
3378
  return result;
3382
- } finally {
3383
- executing.delete(actionId);
3384
3379
  }
3380
+ if (result.status === "failed") {
3381
+ failAction({ actionId, errorCode: result.errorCode, retryable: result.retryable, durationMs: result.durationMs, runtimeEvidence: result.runtimeEvidence });
3382
+ return result;
3383
+ }
3384
+ return fail("Runtime returned an invalid execution result.", "HARNESS_ERROR");
3385
3385
  },
3386
3386
  end: (status) => {
3387
3387
  open();
@@ -3946,7 +3946,17 @@ var modelFor = (policy, role) => policy.bindings.find((binding2) => binding2.rol
3946
3946
 
3947
3947
  // src/kernel/pii.ts
3948
3948
  var PATTERNS = [
3949
- { kind: "api-key", regex: /\b(?:sk-[A-Za-z0-9]{16,}|gh[opsu]_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,})\b/g },
3949
+ // PEM key blocks first: large, unambiguous, and must claim their content before any narrower pattern below
3950
+ // could otherwise match a substring inside the base64 body (unlikely, but claimed-range order matters).
3951
+ { kind: "private-key", regex: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED |)PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |DSA |OPENSSH |ENCRYPTED |)PRIVATE KEY-----/g },
3952
+ // `sk-` body allows `-`/`_` (not just alnum) so a project/scoped key like `sk-proj-...`/`sk-live-...` matches
3953
+ // as one token instead of the hyphen splitting it into a too-short fragment. `github_pat_` (fine-grained PAT)
3954
+ // and `AIza…` (Google API key) are current real-world formats missing from the original list entirely.
3955
+ { kind: "api-key", regex: /\b(?:sk-[A-Za-z0-9_-]{16,}|sk_(?:live|test)_[A-Za-z0-9]{16,}|pk_(?:live|test)_[A-Za-z0-9]{16,}|gh[opsu]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|AIza[A-Za-z0-9_-]{30,}|xox[baprs]-[A-Za-z0-9-]{10,})\b/g },
3956
+ // The AWS *secret* half (as opposed to the `AKIA…` access-key id above) has no recognizable prefix — a bare
3957
+ // 40-char base64-shaped run is too generic to scan for on its own (matches hashes, tokens, arbitrary base64).
3958
+ // Anchoring on the conventional key name it's almost always assigned to/from keeps this pattern high-signal.
3959
+ { kind: "api-key", regex: /\b(?:aws_secret_access_key|AWS_SECRET_ACCESS_KEY|SecretAccessKey)\s*[:=]\s*["']?([A-Za-z0-9/+=]{40})["']?/g },
3950
3960
  { kind: "email", regex: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g },
3951
3961
  { kind: "credit-card", regex: /\b(?:\d[ -]?){13,16}\b/g },
3952
3962
  { kind: "phone", regex: /\b\+?\d{1,3}?[\s().-]?\(?\d{2,4}\)?[\s.-]?\d{3,4}[\s.-]?\d{4}\b/g }
@@ -4111,7 +4121,9 @@ var exportEvidenceBundle = async ({ configPath, runId, outputPath, privateKeyPat
4111
4121
  `, "utf8");
4112
4122
  return bundle;
4113
4123
  };
4114
- var verifyEvidenceBundle = (path, { trustedKeys = [] } = {}) => {
4124
+ var EVIDENCE_MAX_FILE_BYTES = 25 * 1048576;
4125
+ var EVIDENCE_MAX_TOTAL_BYTES = 200 * 1048576;
4126
+ var verifyEvidenceBundle = (path, { trustedKeys = [], maxFileBytes = EVIDENCE_MAX_FILE_BYTES, maxTotalBytes = EVIDENCE_MAX_TOTAL_BYTES } = {}) => {
4115
4127
  const bundle = parseBundle(path);
4116
4128
  if (bundle.type !== "agentskit-harness-evidence-bundle" || bundle.schemaVersion !== EVIDENCE_BUNDLE_SCHEMA_VERSION || !bundle.runId || !validKeyId(bundle.signerKeyId) || !validDigest(bundle.payloadHash) || bundle.signature?.algorithm !== "ed25519" || bundle.signature.keyId !== bundle.signerKeyId || typeof bundle.signature.publicKeyPem !== "string" || typeof bundle.signature.signatureBase64 !== "string" || !Array.isArray(bundle.files)) fail("Evidence bundle metadata is invalid.", "HARNESS_ERROR");
4117
4129
  if (trustedKeys.length) {
@@ -4121,10 +4133,14 @@ var verifyEvidenceBundle = (path, { trustedKeys = [] } = {}) => {
4121
4133
  if (trusted.publicKeyPem !== bundle.signature.publicKeyPem) fail(`Evidence bundle key does not match trust store: ${bundle.signerKeyId}`, "HARNESS_ERROR");
4122
4134
  }
4123
4135
  const paths = /* @__PURE__ */ new Set();
4136
+ let totalBytes = 0;
4124
4137
  for (const file of bundle.files) {
4125
4138
  if (!file || typeof file.path !== "string" || paths.has(file.path) || !validDigest(file.sha256) || typeof file.contentBase64 !== "string") fail("Evidence bundle file metadata is invalid.", "HARNESS_ERROR");
4126
4139
  paths.add(file.path);
4140
+ if (file.contentBase64.length > Math.ceil(maxFileBytes / 3) * 4) fail(`Evidence bundle file exceeds the maximum allowed size: ${file.path}`, "HARNESS_ERROR");
4127
4141
  const content = Buffer.from(file.contentBase64, "base64");
4142
+ totalBytes += content.length;
4143
+ if (totalBytes > maxTotalBytes) fail("Evidence bundle exceeds the maximum total allowed size.", "HARNESS_ERROR");
4128
4144
  if (sha256(content) !== file.sha256) fail(`Evidence bundle file hash mismatch: ${file.path}`, "HARNESS_ERROR");
4129
4145
  }
4130
4146
  if (!paths.has(`runs/${bundle.runId}/run.json`) || !paths.has(`runs/${bundle.runId}/events.ndjson`)) fail("Evidence bundle is missing the run projection or event log.", "HARNESS_ERROR");
@@ -5877,6 +5893,14 @@ var githubCommentExists = async (runner, input, options = {}) => {
5877
5893
  const list2 = await ghJson(runner, ["api", "--paginate", `repos/${input.repo}/issues/${input.number}/comments`, "--jq", "[.[].body]"], options);
5878
5894
  return Array.isArray(list2) && list2.some((body3) => typeof body3 === "string" && body3.includes(input.marker));
5879
5895
  };
5896
+ var writeJsonAtomic = (path, value) => {
5897
+ const dir = dirname(path);
5898
+ mkdirSync(dir, { recursive: true });
5899
+ const tmp = join(dir, `.${basename(path)}.${process.pid}.${Date.now()}.tmp`);
5900
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}
5901
+ `, "utf8");
5902
+ renameSync(tmp, path);
5903
+ };
5880
5904
  var clip = (text7, max) => text7.length <= max ? text7 : `${text7.slice(0, Math.max(0, max - 1))}\u2026`;
5881
5905
  var createFileMemoryKvStore = (dir) => {
5882
5906
  mkdirSync(dir, { recursive: true });
@@ -6086,9 +6110,7 @@ var readStoredContract = (stateDir, identifier) => {
6086
6110
  };
6087
6111
  var writeStoredContract = (stateDir, stored) => {
6088
6112
  const path = contractPath(stateDir, stored.issue);
6089
- mkdirSync(dirname(path), { recursive: true });
6090
- writeFileSync(path, `${JSON.stringify(stored, null, 2)}
6091
- `, "utf8");
6113
+ writeJsonAtomic(path, stored);
6092
6114
  return path;
6093
6115
  };
6094
6116
  var contractIsFresh = (stored, issue, reuseHours, now4, memoryDigest) => stored.issueUpdatedAt === issue.updatedAt && (reuseHours === 0 || now4.getTime() - Date.parse(stored.generatedAt) <= reuseHours * 36e5) && (memoryDigest === void 0 || (stored.memoryDigest ?? hashJson([])) === memoryDigest);
@@ -6523,26 +6545,56 @@ var readDispatchRecord = (stateDir, identifier) => {
6523
6545
  return null;
6524
6546
  }
6525
6547
  };
6526
- var writeJson2 = (path, value) => {
6527
- mkdirSync(dirname(path), { recursive: true });
6528
- writeFileSync(path, `${JSON.stringify(value, null, 2)}
6529
- `, "utf8");
6530
- };
6531
6548
  var writeDispatchRecord = (stateDir, record3) => {
6532
6549
  const path = dispatchRecordPath(stateDir, record3.issue);
6533
- writeJson2(path, record3);
6550
+ writeJsonAtomic(path, record3);
6534
6551
  return path;
6535
6552
  };
6536
6553
  var EVENTS_ROTATE_AT_BYTES = 10 * 1024 * 1024;
6554
+ var EVENTS_LOCK_STALE_MS = 5e3;
6555
+ var EVENTS_LOCK_MAX_ATTEMPTS = 100;
6556
+ var EVENTS_LOCK_RETRY_MS = 10;
6557
+ var acquireEventsLock = (lockFilePath) => {
6558
+ for (let attempt = 0; attempt < EVENTS_LOCK_MAX_ATTEMPTS; attempt += 1) {
6559
+ try {
6560
+ return openSync(lockFilePath, "wx");
6561
+ } catch (error) {
6562
+ if (error.code !== "EEXIST") throw error;
6563
+ try {
6564
+ if (Date.now() - statSync(lockFilePath).mtimeMs > EVENTS_LOCK_STALE_MS) unlinkSync(lockFilePath);
6565
+ } catch {
6566
+ }
6567
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, EVENTS_LOCK_RETRY_MS);
6568
+ }
6569
+ }
6570
+ return null;
6571
+ };
6537
6572
  var appendLoopEvent = (stateDir, event2, bus, now4 = () => /* @__PURE__ */ new Date()) => {
6538
6573
  const path = join(stateDir, "events.ndjson");
6539
6574
  mkdirSync(dirname(path), { recursive: true });
6575
+ const lockFilePath = `${path}.lock`;
6576
+ const lockFd = acquireEventsLock(lockFilePath);
6540
6577
  try {
6541
- if (statSync(path).size > EVENTS_ROTATE_AT_BYTES) renameSync(path, join(stateDir, `events-archive-${now4().getTime()}.ndjson`));
6542
- } catch {
6543
- }
6544
- appendFileSync(path, `${JSON.stringify(event2)}
6578
+ if (lockFd !== null) {
6579
+ try {
6580
+ if (statSync(path).size > EVENTS_ROTATE_AT_BYTES) renameSync(path, join(stateDir, `events-archive-${now4().getTime()}.ndjson`));
6581
+ } catch {
6582
+ }
6583
+ }
6584
+ appendFileSync(path, `${JSON.stringify(event2)}
6545
6585
  `, "utf8");
6586
+ } finally {
6587
+ if (lockFd !== null) {
6588
+ try {
6589
+ closeSync(lockFd);
6590
+ } catch {
6591
+ }
6592
+ try {
6593
+ unlinkSync(lockFilePath);
6594
+ } catch {
6595
+ }
6596
+ }
6597
+ }
6546
6598
  if (bus && typeof event2["type"] === "string") bus.emit(event2);
6547
6599
  };
6548
6600
  var gatherLoopState = async (input) => {
@@ -6838,7 +6890,7 @@ The loop will not retry this issue until you remove the \`${config.resilience.pa
6838
6890
  if (!launched.accepted) notes.push(`${detail.identifier}: terminal ${launched.terminal} did not confirm the brief; deliver will nudge it if it stays idle`);
6839
6891
  ledger.recordDispatch({ lease: claim.lease, idempotencyKey: plan.idempotencyKey, commandDigest: plan.commandDigest });
6840
6892
  const record3 = { issue: detail.identifier, worktreeId: created.id, worktree, branch: actualBranch, terminal: launched.terminal, provider: builder.provider, model: builder.model, contractDigest: stored.digest, leaseKey: claim.lease.key, leaseId: claim.lease.leaseId, dispatchedAt: now4().toISOString(), url: detail.url, briefDigest, skills: skillRefs(pinnedSkills), setup: setupResult, effort: builder.effort, initialRemainingPercent: builder.remainingPercent, worktreePath: created.path };
6841
- writeJson2(dispatchRecordPath(loaded.stateDir, detail.identifier), record3);
6893
+ writeJsonAtomic(dispatchRecordPath(loaded.stateDir, detail.identifier), record3);
6842
6894
  appendLoopEvent(loaded.stateDir, { at: record3.dispatchedAt, type: "worker.dispatched", ...record3, command: builder.tui, briefAccepted: launched.accepted, tuiIdle: launched.idle }, bus);
6843
6895
  await bus.runHook("afterDispatch", { issue: detail.identifier, provider: record3.provider, model: record3.model, branch: record3.branch, worktreeId: record3.worktreeId });
6844
6896
  clearIssueFailures(loaded.stateDir, detail.identifier);
@@ -6955,11 +7007,6 @@ var discoverIntake = async (runner, input, options = {}) => {
6955
7007
  // src/loop/deliver.ts
6956
7008
  var message3 = (error) => error instanceof HarnessError ? `${error.code}: ${error.message}` : error instanceof Error ? error.message : String(error);
6957
7009
  var isMissingOrcaWorktree = (error) => message3(error).includes("selector_not_found");
6958
- var writeJson3 = (path, value) => {
6959
- mkdirSync(dirname(path), { recursive: true });
6960
- writeFileSync(path, `${JSON.stringify(value, null, 2)}
6961
- `, "utf8");
6962
- };
6963
7010
  var deliveryStatePath = (stateDir, identifier) => join(stateDir, "issues", identifier, "delivery.json");
6964
7011
  var readDeliveryState = (stateDir, identifier) => {
6965
7012
  const path = deliveryStatePath(stateDir, identifier);
@@ -6986,7 +7033,7 @@ var minutesBetween = (later, earlier) => earlier === null ? Number.POSITIVE_INFI
6986
7033
  var orcaOptions = (config) => ({ bin: config.orca.bin, timeoutMs: config.orca.timeoutMs });
6987
7034
  var linearOptions = (config) => ({ bin: config.orca.bin, workspaceId: config.linear.workspaceId, orca: { timeoutMs: config.orca.timeoutMs } });
6988
7035
  var saveState = (ctx, state) => {
6989
- if (!ctx.dryRun) writeJson3(deliveryStatePath(ctx.loaded.stateDir, state.issue), state);
7036
+ if (!ctx.dryRun) writeJsonAtomic(deliveryStatePath(ctx.loaded.stateDir, state.issue), state);
6990
7037
  };
6991
7038
  var event = (ctx, payload) => {
6992
7039
  if (!ctx.dryRun) appendLoopEvent(ctx.loaded.stateDir, { at: ctx.now().toISOString(), ...payload }, ctx.bus);
@@ -7658,7 +7705,7 @@ var runDeliver = async (input) => {
7658
7705
  const candidates = (await githubOpenPullRequests(input.runner, { repo: config.project.repo, limit: 100 })).filter((item) => item.headRef === record3.branch || item.headRef.endsWith(`/${record3.worktree}`) || item.headRef === record3.worktree);
7659
7706
  if (candidates.length) {
7660
7707
  open = candidates;
7661
- if (!dryRun) writeJson3(dispatchRecordPath(loaded.stateDir, record3.issue), { ...record3, branch: candidates[0].headRef });
7708
+ if (!dryRun) writeJsonAtomic(dispatchRecordPath(loaded.stateDir, record3.issue), { ...record3, branch: candidates[0].headRef });
7662
7709
  notes.push(`${record3.issue}: PR found on branch ${candidates[0].headRef}; dispatch record updated`);
7663
7710
  }
7664
7711
  }
@@ -8267,7 +8314,7 @@ var parseSince = (value, now4) => {
8267
8314
  return new Date(now4.getTime() - amount * unit);
8268
8315
  }
8269
8316
  const parsed = Date.parse(value);
8270
- if (Number.isNaN(parsed)) throw new Error(`Unrecognised --since value: ${value} (use 7d, 12h, 30m or an ISO date)`);
8317
+ if (Number.isNaN(parsed)) fail(`Unrecognised --since value: ${value} (use 7d, 12h, 30m or an ISO date)`, "INVALID_INPUT");
8271
8318
  return new Date(parsed);
8272
8319
  };
8273
8320
  var median3 = (values) => {
@@ -8516,6 +8563,7 @@ var phaseOf = (dispatch, delivery) => {
8516
8563
  return "in-flight";
8517
8564
  };
8518
8565
  var summarize2 = (phase2, delivery, dispatch) => {
8566
+ if (phase2 === "idle") return "Not yet dispatched";
8519
8567
  if (phase2 === "merged") return `Merged PR #${delivery.prNumber ?? "?"}`;
8520
8568
  if (phase2 === "held" || phase2 === "held-incomplete-review") {
8521
8569
  if (delivery.heldFor) return `Held for a human (self-edit or protected path at ${delivery.heldFor.slice(0, 7)})`;
@@ -8602,7 +8650,7 @@ var buildDebriefReport = (input) => {
8602
8650
  });
8603
8651
  continue;
8604
8652
  }
8605
- continue;
8653
+ if (!input.issue) continue;
8606
8654
  }
8607
8655
  rows.push(rowFor({ issue, dispatch, delivery, intent, repo: config.project.repo, now: now4 }));
8608
8656
  }
@@ -8770,7 +8818,7 @@ var runObservability = async (input) => {
8770
8818
  const events = readLoopEvents(loaded.stateDir).filter((event2) => Date.parse(event2.at) >= since.getTime() && Date.parse(event2.at) <= at.getTime());
8771
8819
  const ledger = createDispatchLedger(loaded.stateDir);
8772
8820
  const active = ledger.active();
8773
- const missingDeliveryIssues = active.filter((lease) => !existsSync(deliveryStatePath(loaded.stateDir, lease.issue))).map((lease) => lease.issue);
8821
+ const missingDeliveryIssues = active.filter((lease) => !existsSync(deliveryStatePath(loaded.stateDir, lease.issue)) && !existsSync(dispatchRecordPath(loaded.stateDir, lease.issue))).map((lease) => lease.issue);
8774
8822
  const records = listDispatched(loaded.stateDir);
8775
8823
  const completed = records.map((record3) => ({ record: record3, state: readDeliveryState(loaded.stateDir, record3.issue) })).filter(({ state }) => state.finishedAt && Date.parse(state.finishedAt) >= since.getTime());
8776
8824
  const leadTimes = completed.map(({ record: record3, state }) => state.finishedAt ? (Date.parse(state.finishedAt) - Date.parse(record3.dispatchedAt)) / 6e4 : null).filter((value) => value !== null && Number.isFinite(value)).sort((a, b) => a - b);