import { P as ProjectProfile, D as DecisionCategory, I as IntelligenceConfig, E as EmbeddingProviderName, a as DecisionOptionEvidence, C as CompiledRule, B as BenchmarkGateConfig, b as DecisionPacket, c as PlanningManifest, d as DecisionIntent, S as SliceContext, e as DecisionOption, f as DecisionStatus, g as DecisionHumanResponse, h as PlanningCostEntry, i as PlanningLane, M as ManifestComplexity, j as PlanningCostLog, k as CoverageOverlayEntry, V as VerificationCriterion, l as ManifestDelta, m as ExecutionSlice, n as DocTarget, o as SliceFullSuiteCheck, p as ManifestClassification, q as IntelligenceContext, r as ModuleHealthMetrics, H as HealthTier, s as ModuleHealthProfile, t as PlanVsActualSnapshot, u as PlanVsActualDiff, R as RegressionEntry, v as CompiledRulesStore } from './project-profile-BiPq_e2T.js';
export { A as ActionRoutingConfig, w as AdaptiveRetrievalConfig, x as AppPreviewConfig, y as AutoResolveConfirmation, z as BenchmarkEvalConfig, F as CompliancePackConfig, G as CriterionSource, J as CriterionStatus, K as CustomClassificationDimension, L as DECISION_ASK_THRESHOLDS, N as DECISION_CARRY_OVER_SCOPES, O as DECISION_CATEGORIES, Q as DECISION_CATEGORY_DEFAULTS, T as DECISION_INTENTS, U as DECISION_STATUSES, W as DecisionAskThreshold, X as DecisionCarryOverScope, Y as DecisionCategoryTtlOverrides, Z as DecisionProfileConfig, _ as DecisionRecord, $ as DefectPatternSummary, a0 as DocTargetStatus, a1 as EMBEDDING_PROVIDER_NAMES, a2 as ESCALATION_MODES, a3 as EfficiencyConfig, a4 as EnterpriseConfig, a5 as EscalationConfig, a6 as EscalationMode, a7 as EscalationRuleConfig, a8 as ExecutionProgressTracker, a9 as ExecutionTrackerStatus, aa as ExistingImplementation, ab as FlakyProfileConfig, ac as ManifestRisk, ad as MetadataFiltersConfig, ae as ModelRoutingConfig, af as PaqadConfig, ag as PlanMode, ah as PriorSliceSummary, ai as ProjectCommands, aj as ProjectFeatureFlags, ak as ProjectMcpServer, al as ProjectMetadata, am as ProjectTesting, an as ProjectTestingParallel, ao as ProofType, ap as REQUIREMENT_PRIORITIES, aq as REQUIREMENT_RISKS, ar as RESEARCH_DEPTHS, as as RegressionStatus, at as RejectedAlternative, au as RequirementGraphDelta, av as RequirementNode, aw as RequirementPriority, ax as RequirementRisk, ay as RequirementType, az as RerankingConfig, aA as ResearchDepth, aB as RollbackClass, aC as SliceBudgetSummary, aD as SliceCheckpoint, aE as SliceCriteriaCheck, aF as SliceDocCheck, aG as SliceEscalationReason, aH as SliceEscalationReport, aI as SliceExecutionCancelledEvent, aJ as SliceExecutionCompletedEvent, aK as SliceExecutionEscalatedEvent, aL as SliceExecutionEvent, aM as SliceExecutionEventBase, aN as SliceExecutionEventKind, aO as SliceExecutionGateEvaluatedEvent, aP as SliceExecutionResumeAfterCrashEvent, aQ as SliceExecutionRetriedEvent, aR as SliceExecutionRunFinishedEvent, aS as SliceExecutionStartedEvent, aT as SliceExecutionStatus, aU as SliceFailingTest, aV as SliceFixAttempt, aW as SliceGateResult, aX as SliceProgressEntry, aY as SliceRegressionCheck, aZ as SliceScopeCheck, a_ as SliceScopeViolation, a$ as StrictnessConfig, b0 as TICKET_PROVIDER_KINDS, b1 as TicketProviderKind, b2 as TicketWriteBackMode, b3 as VerificationCase, b4 as VerificationPluginConfig, b5 as isDecisionPacket, b6 as isStrictDecisionId, b7 as toDecisionRecord, b8 as validateDecisionPacket } from './project-profile-BiPq_e2T.js';
import { D as Domain, S as Stack, C as Capability, A as ActiveCapability, R as RepositoryContext, T as ToolchainInfo, I as InstalledPackage, a as StackSourceReference, b as DetectedStackProfile, c as StackDriftReport, d as StackEcosystem, e as StackSnapshot } from './introspection-BvTZDzyc.js';
export { f as ACTIVE_CAPABILITIES, g as CAPABILITIES, h as DOMAINS, i as DOMAIN_STACK_MAP, j as DomainStackMapping, k as STACKS, l as STACK_CAPABILITIES_MAP, m as STACK_ECOSYSTEMS, n as StackDriftChange, o as StackProfileSourceKind, V as VersionBand } from './introspection-BvTZDzyc.js';
import { A as AnalyticsGateStatus, C as ClassificationResult, L as Lane, a as Complexity, R as Risk, b as ClassificationWorkflow, c as ClassificationScope, D as DatabaseImpact, d as ApiImpact, U as UiImpact, e as ComplianceSensitivity, f as CustomerFacingImpact, g as Reversibility, h as DataSensitivity, i as ContextBudgetHint, j as ResolutionMap, W as WorkflowSource, k as ResolutionSource, l as RoutingConfig } from './classification-vu8-PTr6.js';
export { m as API_IMPACTS, n as CLASSIFICATION_CERTAINTY, o as CLASSIFICATION_OUTPUT_TYPES, p as CLASSIFICATION_SCOPES, q as CLASSIFICATION_WORKFLOWS, r as COMPLEXITY_LEVELS, s as COMPLIANCE_SENSITIVITY_LEVELS, t as CONTEXT_BUDGET_HINTS, u as CUSTOMER_FACING_IMPACTS, v as ClassificationCertainty, w as ClassificationOutputType, x as DATABASE_IMPACTS, y as DATA_SENSITIVITY_LEVELS, z as LANES, P as PROCESS_DEPTHS, B as ProcessDepth, E as RESOLUTION_SOURCES, F as REVERSIBILITY_LEVELS, G as RISK_LEVELS, T as TARGET_CAPABILITIES, H as TargetCapability, I as UI_IMPACTS, J as WORKFLOW_SOURCES, K as selectLane } from './classification-vu8-PTr6.js';
export { HEURISTIC_TOKENIZER_VERSION, LoadedTokenizer, clearTokenizerCache, getOrLoad } from './context/tokenizer-cache.js';
export { f as findPackageRoot, g as getPackageRoot, a as getRuntimeRoot, b as getRuntimeTemplatesRoot } from './runtime-paths-D7pDu5IJ.js';
import { F as FeatureDevelopmentPolicy } from './feature-development-policy-CzhO1x0T.js';

declare const RESOLUTION_LAYERS: readonly [0, 1, 2, 3, 4, 5, 6];
type ResolutionLayer = (typeof RESOLUTION_LAYERS)[number];
interface ResolvedArtifact$1 {
    path: string;
    level: ResolutionLayer;
    source: string;
}
interface ResolvedArtifacts {
    rules: ResolvedArtifact$1[];
    skills: ResolvedArtifact$1[];
    agents: ResolvedArtifact$1[];
    hooks: ResolvedArtifact$1[];
    templates: ResolvedArtifact$1[];
    patterns: ResolvedArtifact$1[];
    antiPatterns: ResolvedArtifact$1[];
    checklists: ResolvedArtifact$1[];
    mcpConfigs: ResolvedArtifact$1[];
}

declare const ADAPTER_TYPES: readonly ["claude-code", "codex-cli", "antigravity", "gemini-cli", "junie", "cursor", "github-copilot", "windsurf", "continue", "aider", "aiassistant"];
type AdapterType = (typeof ADAPTER_TYPES)[number];
interface AdapterConfig {
    adapter: AdapterType;
    config_path: string;
    skills_root: string;
    agents_root: string;
    hooks_supported: boolean;
    mcp_supported: boolean;
}

interface AdapterCapabilities {
    skills: boolean;
    agents: boolean;
    hooks: boolean;
    mcp: boolean;
    caching: boolean;
    memory: boolean;
}
interface GeneratedFile {
    path: string;
    content: string;
    autoUpdate: boolean;
    executable?: boolean;
}
interface AdapterContext {
    frameworkPath: string;
    rulesPath: string;
    projectRoot: string;
}
interface AdapterInterface {
    readonly type: AdapterType;
    readonly capabilities: AdapterCapabilities;
    getConfigPath(): string;
    getMcpPath(): string;
    generateConfig(context: AdapterContext): Promise<GeneratedFile[]>;
    generateSkills(skills: ResolvedArtifact$1[]): Promise<GeneratedFile[]>;
    generateAgents(agents: ResolvedArtifact$1[]): Promise<GeneratedFile[]>;
    installHooks(hooks: ResolvedArtifact$1[]): Promise<GeneratedFile[]>;
    installMcp(mcpConfigs: ResolvedArtifact$1[], profile: ProjectProfile): Promise<GeneratedFile[]>;
    configureCaching(profile: ProjectProfile): Promise<GeneratedFile[]>;
    configureMemory(profile: ProjectProfile): Promise<GeneratedFile[]>;
}

/** The lifecycle point a live hook binds to, mapped per host to its native event
 *  name (e.g. Claude Code / Codex `PreToolUse` and `Stop`). */
type PaqadHookEvent = 'session-start' | 'prompt-submit' | 'pre-tool-mutation' | 'completion' | 'subagent-completion';
/**
 * The order the events are rendered into a host's hook config. Fixed so a
 * re-onboard is byte-stable and Claude's `.claude/settings.json` keeps the exact
 * key order it had before the shared renderer (PreToolUse, UserPromptSubmit,
 * SessionStart, Stop).
 */
declare const PAQAD_HOOK_EVENT_ORDER: readonly PaqadHookEvent[];
interface PaqadLiveHookSpec {
    id: string;
    event: PaqadHookEvent;
    /** Basename of the runtime hook file (e.g. `decision-pause-gate.mjs`). The
     *  renderer turns it into a cross-platform command via `hookCommand()`. */
    hookFile: string;
    /** When set, this hook is the capability-kernel seam: rendered via
     *  `capabilityGateCommand()` with this seam as the first argv. */
    capabilitySeam?: 'pre-mutation' | 'completion';
    /**
     * When true the host adapter type is appended to the command as an argv so the
     * one shared script knows which host invoked it (issue #566). The default host,
     * `claude-code`, is NEVER appended — its scripts default to `claude-code`, so
     * omitting it keeps Claude's generated config byte-identical to before this
     * change. Every non-default host (Codex) gets the argv.
     */
    hostArgv?: boolean;
    description: string;
}
/** The framework pointer prefix used in docs/diagnostics. Hook *commands* no
 *  longer embed this bare `~` form — Windows shells do not expand `~` — they use
 *  the absolute, interpreter-explicit `hookCommand()` form below (issue #240). */
declare const PAQAD_RUNTIME_PREFIX = "~/.paqad-ai/current";
/** The canonical mutating-tool matcher used by paqad's Claude pre-tool gates. */
declare const PAQAD_MUTATING_TOOL_MATCHER = "Edit|Write|NotebookEdit";
/**
 * The agent-type matcher for the `subagent-completion` hook (issue #567). paqad's stage
 * agents are all named `paqad-<stage>`, so this anchored prefix fires the hook only for
 * them and never for a user's own subagents (or the built-in `general-purpose`/`Explore`/
 * `Plan` agents).
 */
declare const PAQAD_STAGE_AGENT_MATCHER = "^paqad-";
/** The default host whose shared scripts run without a host argv (issue #566). */
declare const DEFAULT_HOOK_ADAPTER = "claude-code";
/**
 * A host that renders the full pre-and-completion hook chain. Each maps the
 * abstract lifecycle events to its own native event names and supplies the
 * mutating-tool matcher for its `pre-tool-mutation` seam. Verified against each
 * host's own hook documentation before wiring (RULE-18). Codex's mutating tool is
 * `apply_patch`; its matcher is a regex on `tool_name`, so it is anchored.
 */
interface HostHookEventMap {
    nativeEvent: Record<PaqadHookEvent, string>;
    /** The `pre-tool-mutation` event's matcher for this host. */
    mutatingMatcher: string;
    /**
     * The `subagent-completion` event's matcher for this host (issue #567). Both hosts match
     * on the subagent's agent type, so `^paqad-` restricts the hook to paqad's own stage
     * agents and never fires for a user's own subagents (Claude verified: `SubagentStop`
     * matches the same agent-type values as `SubagentStart`; Codex matches on `agent_type`).
     */
    subagentMatcher: string;
}
declare const NATIVE_HOOK_EVENTS: Readonly<Record<string, HostHookEventMap>>;
/** True iff the host renders the full `PAQAD_LIVE_HOOKS` chain (Claude or Codex). */
declare function rendersFullHookChain(adapterType: string): boolean;
/**
 * Absolute, POSIX-style path to the framework install dir (`~/.paqad-ai/current`),
 * resolved at onboard time. Mirrors `src/onboarding/manifest-writer.ts`. A hook
 * command cannot carry a bare `~` (Windows shells do not expand it) or rely on a
 * shebang / executable bit (Windows ignores both), so we bake an absolute path
 * and launch through the `node` interpreter (issue #240).
 */
declare function frameworkHomeAbsolute(env?: NodeJS.ProcessEnv): string;
/**
 * A cross-platform hook command: `node "<abs>/hooks/<file>"`. No `~`, no `.sh`,
 * no reliance on a shebang or the executable bit — it runs identically on Windows
 * (cmd/PowerShell), macOS, and Linux. `node` is always on PATH for a paqad-ai
 * install (it is a Node CLI). The path stays machine-agnostic across re-onboards
 * because it is recomputed from the local home dir each time the host config is
 * generated.
 */
declare function hookCommand(hookFile: string, env?: NodeJS.ProcessEnv): string;
/**
 * The Capability Kernel host-seam command (buildout F3). `capability-gate.mjs`
 * runs every kernel-bound capability registered at a seam; the seam is passed as
 * the first argv (`pre-mutation` for a PreToolUse mutation gate, `completion` for
 * a Stop/AfterAgent gate). `adapterType` (issue #566) is appended after the seam
 * for a non-default host so the gate attributes its recorded rows to the host that
 * ran; the default `claude-code` is omitted so Claude's command is unchanged.
 */
declare function capabilityGateCommand(seam: 'pre-mutation' | 'completion', adapterType?: string, env?: NodeJS.ProcessEnv): string;
/**
 * The record-only completion hook command Gemini CLI binds to (its `AfterAgent`).
 * It runs the same verification backstop as Claude's `Stop` hook — producing the
 * evidence ledger when enterprise evidence is on — but always exits 0 and stays
 * silent, so a non-Claude host's hook never halts, retries, or misreads it. See
 * `runtime/hooks/verification-record.mjs`.
 *
 * `adapterType` (issue #265) is passed to the hook as an argv so the per-stage
 * marker rows it records at completion are attributed to the host that actually
 * ran (`gemini-cli`), not a hard-coded `claude-code`. Omitted → the bare record
 * command (the hook then defaults attribution to `claude-code`).
 *
 * Codex no longer uses this hook — it renders the full blocking completion chain
 * (issue #566). It remains for Gemini, whose tier is unchanged.
 */
declare function completionRecordCommand(adapterType?: string, env?: NodeJS.ProcessEnv): string;
/**
 * The live hooks paqad generates for every host that renders the full chain
 * (issue #117, extended by #566). Listed in per-event order; the renderer walks
 * `PAQAD_HOOK_EVENT_ORDER` and, within each event, keeps this order — which is the
 * exact order Claude Code's `.claude/settings.json` carried before the shared
 * renderer, so that output is byte-identical.
 */
declare const PAQAD_LIVE_HOOKS: readonly PaqadLiveHookSpec[];
/** One rendered hook: the host's native event, an optional matcher, and the command. */
interface RenderedHook {
    nativeEvent: string;
    matcher?: string;
    command: string;
}
/** Render one spec's command for a host: the capability seam, plus the host argv for
 *  a non-default host (never for `claude-code`, so Claude stays byte-identical). */
declare function renderHookCommand(spec: PaqadLiveHookSpec, adapterType: string, env?: NodeJS.ProcessEnv): string;
/**
 * The full ordered hook chain a host renders, resolved to native event names,
 * matchers, and commands. Walks the fixed event order and, within each event,
 * `PAQAD_LIVE_HOOKS` order — so Claude's output is byte-identical to before the
 * shared renderer. Throws for a host that does not render the full chain (a caller
 * bug — Gemini uses the record-only completion helper, not this).
 */
declare function buildHostHookChain(adapterType: string, env?: NodeJS.ProcessEnv): RenderedHook[];
/**
 * How each adapter is ACTUALLY covered, grounded in which adapters wire an
 * executed native host hook. Two adapters now render the full pre-and-completion
 * chain: claude-code and codex-cli (issue #566). gemini-cli records at completion
 * only. Every other adapter ships an entry-file contract with no host seam, so it
 * is `advisory`.
 *
 *   - `live-pre-and-completion`: blocks before a mutating edit AND verifies at turn
 *     end (claude-code, codex-cli — the PreToolUse-capable hosts).
 *   - `live-completion-only`: at turn end records the stage-evidence ledger AND the
 *     agent's `paqad:stage` markers, then verifies — record-only (exit 0, silent),
 *     with NO in-turn pre-mutation block and NO in-chat verdict (gemini-cli).
 *   - `advisory`: no executed host hook; the entry-file contract only.
 */
type AdapterHookCoverage = 'live-pre-and-completion' | 'live-completion-only' | 'advisory';
declare const HOOK_COVERAGE_MATRIX: Readonly<Record<string, AdapterHookCoverage>>;
/** True iff the host exposes a native hook paqad actually wires (claude/codex/gemini). */
declare function isLiveHookCapable(adapterType: string): boolean;
/** True iff the host can BLOCK before a mutating edit (a PreToolUse seam) — claude/codex. */
declare function hasPreMutationBlock(adapterType: string): boolean;

declare class TemplateEngine {
    private readonly handlebars;
    constructor();
    render(templatePath: string, context: Record<string, unknown>): Promise<string>;
    private registerHelpers;
}

declare abstract class BaseAdapter implements AdapterInterface {
    protected readonly engine: TemplateEngine;
    readonly capabilities: AdapterCapabilities;
    abstract readonly type: AdapterInterface['type'];
    protected abstract configTemplateName(): string;
    protected abstract configOutputPath(): string;
    protected abstract skillsRoot(): string;
    protected abstract agentsRoot(): string;
    protected abstract hooksOutputPath(): string;
    protected abstract mcpOutputPath(): string;
    protected abstract cacheOutputPath(): string;
    protected abstract memoryOutputPath(): string;
    getConfigPath(): string;
    getMcpPath(): string;
    generateConfig(context: AdapterContext): Promise<GeneratedFile[]>;
    /**
     * Basenames of host-executed config files that carry machine-specific hook
     * commands (the absolute `node "<abs>"` invocation, issue #240). Overridden by
     * the adapters that actually wire executed hooks — Claude (`settings.json`),
     * Codex (`hooks.json`), Gemini (`settings.json`). Default: none.
     */
    protected executedHookConfigFiles(): string[];
    /**
     * A nested `.gitignore` in the host config dir that marks the paqad-generated
     * hook config files git-ignored (issue #240, the per-machine decision). Those
     * files now carry an absolute, machine-specific `node "<abs>"` hook command;
     * committing them would break a teammate or CI on a different home dir / OS.
     * Emitted ONLY for adapters that actually wire executed hooks (Claude, Codex,
     * Gemini) — every other adapter's generateConfig output is unchanged. Consistent
     * with the #184 nested-ignore approach (paqad owns a `.gitignore` inside the dir
     * it manages and never edits the project root `.gitignore`). The entry file, MCP
     * config, cache/memory, and skills/agents content are untouched.
     */
    protected hostConfigGitignore(): GeneratedFile | null;
    generateSkills(skills: ResolvedArtifact$1[]): Promise<GeneratedFile[]>;
    generateAgents(agents: ResolvedArtifact$1[]): Promise<GeneratedFile[]>;
    installHooks(hooks: ResolvedArtifact$1[]): Promise<GeneratedFile[]>;
    installMcp(mcpConfigs: ResolvedArtifact$1[], profile: ProjectProfile): Promise<GeneratedFile[]>;
    configureCaching(profile: ProjectProfile): Promise<GeneratedFile[]>;
    configureMemory(profile: ProjectProfile): Promise<GeneratedFile[]>;
}

/**
 * JetBrains AI Assistant (issue #219). AI Assistant auto-applies every `*.md`
 * under `.aiassistant/rules/` at the start of a conversation — the analog of
 * `CLAUDE.md` / `.junie/AGENTS.md`. It has no hook / lifecycle system, so the
 * `.paqad/.agent-entry-loaded` sentinel gate cannot bind here: this is a soft,
 * rules-only adapter (advisory hook coverage), exactly like `junie`.
 *
 * MCP is intentionally off. JetBrains AI Assistant configures MCP servers in the
 * IDE settings, not from a project file, so emitting a project-level `mcp.json`
 * would write an artifact no host reads. Modeled on `aider` (config-only).
 */
declare class AiAssistantAdapter extends BaseAdapter {
    readonly type: "aiassistant";
    readonly capabilities: AdapterCapabilities;
    protected configTemplateName(): string;
    protected configOutputPath(): string;
    protected skillsRoot(): string;
    protected agentsRoot(): string;
    protected hooksOutputPath(): string;
    protected mcpOutputPath(): string;
    protected cacheOutputPath(): string;
    protected memoryOutputPath(): string;
}

declare class AiderAdapter extends BaseAdapter {
    readonly type: "aider";
    readonly capabilities: AdapterCapabilities;
    protected configTemplateName(): string;
    protected configOutputPath(): string;
    protected skillsRoot(): string;
    protected agentsRoot(): string;
    protected hooksOutputPath(): string;
    protected mcpOutputPath(): string;
    protected cacheOutputPath(): string;
    protected memoryOutputPath(): string;
    generateConfig(context: AdapterContext): Promise<GeneratedFile[]>;
}

declare class AntigravityAdapter extends BaseAdapter {
    readonly type: "antigravity";
    protected configTemplateName(): string;
    protected configOutputPath(): string;
    protected skillsRoot(): string;
    protected agentsRoot(): string;
    protected hooksOutputPath(): string;
    protected mcpOutputPath(): string;
    protected cacheOutputPath(): string;
    protected memoryOutputPath(): string;
}

declare class ClaudeCodeAdapter extends BaseAdapter {
    readonly type: "claude-code";
    protected configTemplateName(): string;
    protected configOutputPath(): string;
    protected skillsRoot(): string;
    protected agentsRoot(): string;
    protected hooksOutputPath(): string;
    protected mcpOutputPath(): string;
    protected cacheOutputPath(): string;
    protected memoryOutputPath(): string;
    protected executedHookConfigFiles(): string[];
    generateConfig(context: AdapterContext): Promise<GeneratedFile[]>;
}

declare class CodexCliAdapter extends BaseAdapter {
    readonly type: "codex-cli";
    protected configTemplateName(): string;
    protected configOutputPath(): string;
    protected skillsRoot(): string;
    protected agentsRoot(): string;
    protected hooksOutputPath(): string;
    protected mcpOutputPath(): string;
    protected cacheOutputPath(): string;
    protected memoryOutputPath(): string;
    protected executedHookConfigFiles(): string[];
    generateConfig(context: AdapterContext): Promise<GeneratedFile[]>;
}

declare class ContinueAdapter extends BaseAdapter {
    readonly type: "continue";
    readonly capabilities: AdapterCapabilities;
    protected configTemplateName(): string;
    protected configOutputPath(): string;
    protected skillsRoot(): string;
    protected agentsRoot(): string;
    protected hooksOutputPath(): string;
    protected mcpOutputPath(): string;
    protected cacheOutputPath(): string;
    protected memoryOutputPath(): string;
}

declare class CursorAdapter extends BaseAdapter {
    readonly type: "cursor";
    readonly capabilities: AdapterCapabilities;
    protected configTemplateName(): string;
    protected configOutputPath(): string;
    protected skillsRoot(): string;
    protected agentsRoot(): string;
    protected hooksOutputPath(): string;
    protected mcpOutputPath(): string;
    protected cacheOutputPath(): string;
    protected memoryOutputPath(): string;
}

declare class AdapterFactory {
    static create(type: AdapterType): AdapterInterface;
}

declare class GeminiCliAdapter extends BaseAdapter {
    readonly type: "gemini-cli";
    protected configTemplateName(): string;
    protected configOutputPath(): string;
    protected skillsRoot(): string;
    protected agentsRoot(): string;
    protected hooksOutputPath(): string;
    protected mcpOutputPath(): string;
    protected cacheOutputPath(): string;
    protected memoryOutputPath(): string;
    protected executedHookConfigFiles(): string[];
    generateConfig(context: AdapterContext): Promise<GeneratedFile[]>;
}

declare class GithubCopilotAdapter extends BaseAdapter {
    readonly type: "github-copilot";
    readonly capabilities: AdapterCapabilities;
    protected configTemplateName(): string;
    protected configOutputPath(): string;
    protected skillsRoot(): string;
    protected agentsRoot(): string;
    protected hooksOutputPath(): string;
    protected mcpOutputPath(): string;
    protected cacheOutputPath(): string;
    protected memoryOutputPath(): string;
}

declare class JunieAdapter extends BaseAdapter {
    readonly type: "junie";
    readonly capabilities: AdapterCapabilities;
    protected configTemplateName(): string;
    protected configOutputPath(): string;
    protected skillsRoot(): string;
    protected agentsRoot(): string;
    protected hooksOutputPath(): string;
    protected mcpOutputPath(): string;
    protected cacheOutputPath(): string;
    protected memoryOutputPath(): string;
}

declare class WindsurfAdapter extends BaseAdapter {
    readonly type: "windsurf";
    readonly capabilities: AdapterCapabilities;
    protected configTemplateName(): string;
    protected configOutputPath(): string;
    protected skillsRoot(): string;
    protected agentsRoot(): string;
    protected hooksOutputPath(): string;
    protected mcpOutputPath(): string;
    protected cacheOutputPath(): string;
    protected memoryOutputPath(): string;
}

type AnalyticsProviderId = 'ga4' | 'gtm' | 'segment' | 'posthog' | 'mixpanel' | 'amplitude' | 'vercel' | 'plausible';
interface AnalyticsProvider {
    id: AnalyticsProviderId;
    displayName: string;
    /** npm dependency names that imply this provider. */
    packages: string[];
    /** Env-key name patterns (e.g. NEXT_PUBLIC_POSTHOG_KEY). */
    envKeyPatterns: RegExp[];
    /** HTML / entry-file host or URL fragments, matched as plain substrings. */
    entrySubstrings: string[];
    /** Measurement / container id shapes (e.g. G-XXXXXX). Anchored on both sides. */
    entryIdPatterns: RegExp[];
    /** Call-site patterns; capture group 1 is the event name. Stored WITHOUT the global
     *  flag — the extractor clones each with `g` so shared state is never mutated. */
    callSitePatterns: RegExp[];
}
declare const ANALYTICS_PROVIDERS: readonly AnalyticsProvider[];
/** Look up a provider by id. */
declare function findProvider(id: string): AnalyticsProvider | undefined;

interface AnalyticsCallSite {
    provider: AnalyticsProviderId;
    eventName: string;
}
/**
 * Every analytics event call found in `source`, in order, de-duplicated by (provider,event).
 * Pure and allocation-light: each provider pattern is cloned with the global flag so the
 * shared catalog regex is never mutated.
 */
declare function extractCallSites(source: string): AnalyticsCallSite[];
/** Infer a naming convention label from observed event names (e.g. `snake_case`). */
declare function inferNamingConvention(eventNames: readonly string[]): string | null;

declare const HEALTH_CHECK_STATUSES: readonly ["pass", "fail", "warning"];
type HealthCheckStatus = (typeof HEALTH_CHECK_STATUSES)[number];
interface HealthCheckResult {
    name: string;
    status: HealthCheckStatus;
    detail: string;
    remediation?: string;
}
interface HealthEfficiencySummary {
    context_hit_rate: number;
    skill_cache_hit_rate: number;
    mcp_usage_rate: number;
}
interface HealthReport {
    overall_status: HealthCheckStatus;
    checks: HealthCheckResult[];
    efficiency: HealthEfficiencySummary;
}
interface DetectionSignal {
    signal: string;
    file: string;
    implies: string;
    confidence: 'high' | 'medium' | 'low';
}
interface DetectionReport {
    detected_domain: Domain | null;
    detected_stack: Stack | null;
    detected_capabilities: Capability[];
    matched_packs?: string[];
    detected_traits?: string[];
    recommended_capabilities?: ActiveCapability[];
    detection_phase?: 'framework' | 'archetype' | 'none';
    confidence: 'high' | 'medium' | 'low';
    /**
     * PQD-423: numeric confidence in the inclusive range `[0, 1]`. Coexists with the
     * categorical `confidence` field (which the six internal callers still read) — it is
     * an additive surface for consumers that want a continuous score (e.g. `0.92`).
     */
    confidence_score?: number;
    /**
     * PQD-423: human-readable primary language derived from the primary toolchain
     * ecosystem (e.g. `'JavaScript/TypeScript'`, `'Python'`). `null` when no code
     * ecosystem was detected (empty, unknown, or content-only projects).
     */
    primary_language?: string | null;
    /**
     * PQD-423: which detection path produced this report — `'ai'` when the AI-first
     * path returned a confident result, `'static'` when the rule-based fallback ran.
     */
    source?: 'ai' | 'static';
    signals: DetectionSignal[];
    timestamp: string;
    repository?: RepositoryContext;
}

interface AnalyticsDetection {
    provider: AnalyticsProviderId;
    providerDisplay: string;
    /** Layer-2 naming convention observed at call sites, when any (e.g. `snake_case`). */
    convention: string | null;
    confidence: 'high' | 'medium' | 'low';
    signals: DetectionSignal[];
}
/**
 * Detect the wired analytics provider and its convention, or null when none is found.
 * Highest-confidence signal wins; call sites break ties and define the convention.
 */
declare function detectAnalyticsProvider(projectRoot: string): AnalyticsDetection | null;

/** Repo-relative path to the carry-forward sidecar the later stages read. */
declare const ANALYTICS_DECISION_PATH = ".paqad/planning/analytics-decision.json";
interface AnalyticsGateInput {
    projectRoot: string;
    /** `analytics_instrumentation` resolved from config. */
    flagEnabled: boolean;
    /** Whether the classifier judged this a feature / user-facing change. */
    changeIsFeatureShaped: boolean;
    now?: () => Date;
}
interface AnalyticsGateDecision {
    status: AnalyticsGateStatus;
    provider?: AnalyticsProviderId;
    providerDisplay?: string;
    convention?: string | null;
    confidence?: 'high' | 'medium' | 'low';
    resolved_at: string;
}
/**
 * Resolve the analytics gate without side effects. Detection runs ONLY when the flag is on
 * and the change is feature-shaped (cheapest checks first).
 */
declare function resolveAnalyticsGate(input: AnalyticsGateInput): AnalyticsGateDecision;
/**
 * Read the persisted analytics decision sidecar, or null when it is absent or unreadable. The
 * later feature-development stages read this instead of re-deriving the gate (issue #279).
 */
declare function readAnalyticsDecision(projectRoot: string): AnalyticsGateDecision | null;
/**
 * Resolve the gate and persist the decision sidecar (best-effort write). Returns the
 * decision either way. Called at planning/classify time so downstream stages just read the
 * sidecar instead of re-deriving.
 */
declare function resolveAndPersistAnalyticsGate(input: AnalyticsGateInput): AnalyticsGateDecision;

type AnalyticsConflictKind = 'provider_version_mismatch' | 'taxonomy_violation' | 'pii_consent' | 'no_provider_flag' | 'architecture_conflict';
interface AnalyticsConflict {
    category: DecisionCategory;
    /** Plain-language framing of what paqad caught (no jargon). */
    title: string;
}
declare const ANALYTICS_CONFLICTS: Record<AnalyticsConflictKind, AnalyticsConflict>;
/** The decision category for a conflict kind. */
declare function conflictCategory(kind: AnalyticsConflictKind): DecisionCategory;

/** Repo-relative root, module-owned so it never trips the top-level module-doc orphan walk. */
declare function analyticsFeatureDir(module: string, feature: string): string;
/** Repo-relative per-module analytics index path. */
declare function analyticsIndexPath(module: string): string;
/**
 * Normalize an event name to a stable filename slug. Casing and separators collapse, so
 * `Song Played`, `song played`, and `song_played` all map to `song-played` — one doc, with the
 * casing conflict caught at write time instead of silently splitting the data.
 */
declare function normalizeEventSlug(eventName: string): string;
/** Repo-relative per-event doc path. */
declare function analyticsEventDocPath(module: string, feature: string, eventName: string): string;
interface EventGroup {
    slug: string;
    /** Every exact event string seen for this slug; >1 means a casing/spelling conflict. */
    variants: string[];
    providers: AnalyticsProviderId[];
}
/**
 * Group call-sites into one entry per normalized slug, collecting every exact spelling and the
 * providers that fire it. `variants.length > 1` is the casing conflict a reviewer must resolve.
 */
declare function groupBySlug(callSites: readonly AnalyticsCallSite[]): EventGroup[];
/** Render the per-event doc: exact event string, a section per provider, PII/consent stub. */
declare function buildEventDoc(input: {
    module: string;
    feature: string;
    group: EventGroup;
}): string;
/** Render the per-module analytics index listing every event doc under it. */
declare function buildAnalyticsIndex(input: {
    module: string;
    entries: {
        feature: string;
        group: EventGroup;
    }[];
}): string;
interface AnalyticsSyncEntry {
    module: string;
    feature: string;
    callSites: AnalyticsCallSite[];
}
interface AnalyticsSyncResult {
    written: string[];
    skipped: string[];
    /** Repo-relative event docs whose slug collapsed >1 exact spelling. */
    conflicts: {
        path: string;
        variants: string[];
    }[];
}
/**
 * Generate or refresh the per-event docs + per-module index for the given attributed entries,
 * skipping any doc whose rendered content is byte-identical to what is already on disk. Returns
 * what was written, skipped, and which docs carry a casing conflict for the caller to surface.
 */
declare function syncAnalyticsDocs(projectRoot: string, entries: readonly AnalyticsSyncEntry[]): Promise<AnalyticsSyncResult>;

type AnalyticsStrictness = 'off' | 'warn' | 'strict';
/** Modes weakest → strictest, for the floor clamp. */
declare const ANALYTICS_STRICTNESS_MODES: readonly ["off", "warn", "strict"];
/** Analytics is coding-first: the default never blocks a correct build (confirmed 2026-07-02). */
declare const DEFAULT_ANALYTICS_STRICTNESS: AnalyticsStrictness;
/**
 * Resolve the analytics strictness mode with the team value as a floor. The tracked
 * `configs/.config.*` value is the floor; the local `.config` and `PAQAD_ANALYTICS_STRICTNESS`
 * env may only RAISE strictness above it. Nothing set ⇒ `warn`.
 */
declare function resolveAnalyticsStrictness(projectRoot: string, env?: NodeJS.ProcessEnv): AnalyticsStrictness;
interface InstrumentedEvent {
    module: string;
    feature: string;
    eventName: string;
}
interface AnalyticsCompletenessResult {
    mode: AnalyticsStrictness;
    /** `ok` — every event doc exists. `warn` — some missing, non-blocking. `block` — strict, missing. */
    verdict: 'ok' | 'warn' | 'block';
    /** Repo-relative event-doc paths that an instrumented event promised but that do not exist. */
    missingDocs: string[];
}
/**
 * Decide whether the instrumented events are completely documented. The gate is doc-existence:
 * strict requires the EVENT doc to exist (not each provider section — provider detection has
 * confidence, so blocking on a section would false-block). `off` is always `ok`.
 */
declare function evaluateAnalyticsCompleteness(input: {
    mode: AnalyticsStrictness;
    events: readonly InstrumentedEvent[];
    docExists: (repoRelPath: string) => boolean;
}): AnalyticsCompletenessResult;
/**
 * Convenience over {@link evaluateAnalyticsCompleteness} that checks the docs against the real
 * filesystem under `projectRoot` and resolves the strictness mode from config.
 */
declare function evaluateAnalyticsCompletenessForProject(projectRoot: string, events: readonly InstrumentedEvent[], env?: NodeJS.ProcessEnv): AnalyticsCompletenessResult;

interface TransitionEntry {
    timestamp: string;
    workflow: string;
    stack_key: string;
    from_skill: string;
    to_skill: string;
    from_outputs_hash: string;
}
interface TransitionLog {
    version: 1;
    entries: Record<string, TransitionEntry[]>;
    max_entries_per_key: number;
}
interface CacheMetrics {
    session_id: string;
    cache_hits: number;
    cache_misses: number;
    prewarm_hits: number;
    prewarm_misses: number;
    prewarm_skipped: number;
    total_token_savings_estimate: number;
}

declare class TransitionLogManager {
    private readonly projectRoot;
    private readonly maxPerKey;
    constructor(projectRoot: string, maxPerKey?: number);
    private get logPath();
    append(entry: TransitionEntry): Promise<void>;
    load(): Promise<TransitionLog>;
    computeProbabilities(stackKey: string, fromSkill: string): Promise<Array<{
        to_skill: string;
        probability: number;
    }>>;
    private save;
}

declare class CacheMetricsTracker {
    private readonly projectRoot;
    constructor(projectRoot: string);
    private metricsPath;
    record(sessionId: string, event: 'cache_hit' | 'cache_miss' | 'prewarm_hit' | 'prewarm_miss' | 'prewarm_skipped', tokenSavings?: number): Promise<void>;
    read(sessionId: string): Promise<CacheMetrics>;
    private write;
}

declare const CONTEXT_LEVELS: readonly [0, 1, 2, 3, 4];
type ContextLevel = (typeof CONTEXT_LEVELS)[number];
interface ContextHitEntry {
    session_id: string;
    phase: string;
    story?: string;
    files_loaded: number;
    files_referenced: number;
    hit_rate: number;
    unreferenced_files: string[];
    timestamp: string;
}
interface ContextBudgetConfig {
    config_tokens: number;
    skills_per_session: number;
    main_agent_max: number;
    compaction_trigger_pct: number;
}
interface SkillCacheEntry {
    skill_name: string;
    input_hash: string;
    result: unknown;
    created_at: string;
    files_hashed: string[];
}
type ContextHitLog = ContextHitEntry;
type ContextBudget = ContextBudgetConfig;
type BudgetTier = 'green' | 'yellow' | 'amber' | 'red';
interface ContextSegmentPriority {
    tier: 'critical' | 'high' | 'medium' | 'low';
    content_type: string;
    token_estimate: number;
}
interface SummarizedTurn {
    turn_index: number;
    timestamp: string;
    decisions: string[];
    files_touched: string[];
    blockers: string[];
    next_steps: string[];
    original_tokens: number;
    summary_tokens: number;
}
/**
 * A conversation turn handed to `TurnSummarizer.summarise`. Turns flagged
 * `decision_packet` or `approval_turn` are excluded from the collapsed span and
 * their ids are reported in `preserved_turn_ids` for the caller to re-insert.
 *
 * @since 1.10.0
 */
interface SummarisationMessage {
    role: 'user' | 'assistant';
    content: string;
    turn_id: string;
    decision_packet?: boolean;
    approval_turn?: boolean;
}
/**
 * Successful rolling-summary result. `summary_token_count` is a best-effort
 * estimate (character/4) and never exceeds the 2,000-token hard cap.
 *
 * @since 1.10.0
 */
interface SummariseSuccess {
    ok: true;
    summary_text: string;
    valid_through_turn_id: string;
    input_token_count: number;
    summary_token_count: number;
    truncated: boolean;
    preserved_turn_ids: string[];
}
/**
 * Failure result: an explicit, non-partial outcome so the caller can fall back
 * to drop-oldest without overwriting the last-known-good summary.
 *
 * @since 1.10.0
 */
interface SummariseFailure {
    ok: false;
    error: 'inference-failed' | 'timeout' | 'cancelled';
}
/**
 * Discriminated union on `ok` returned by `TurnSummarizer.summarise`.
 *
 * @since 1.10.0
 */
type SummariseResult = SummariseSuccess | SummariseFailure;
interface BudgetOptimizerState {
    tier: BudgetTier;
    tokens_used: number;
    max_tokens: number;
    last_evaluated_at: string;
    summarized_turn_count: number;
    evicted_segment_count: number;
    recommended_action?: 'continue' | 'warn' | 'compact';
    enforcement_reason?: 'healthy' | 'token-budget-tight' | 'context-hit-rate-below-target';
}
interface ContextSavingsEntry {
    session_id: string;
    timestamp: string;
    summarization_savings: number;
    eviction_savings: number;
    dedup_savings: number;
}
interface DeduplicationStats {
    total_artifacts: number;
    deduplicated: number;
    tokens_saved_estimate: number;
}
/**
 * Minimal model-catalog shape needed to size a context window. Aligns with the
 * desktop's `ModelMeta.contextWindowTokens` (spec 106) so the two repos agree on
 * the field name when they integrate.
 *
 * @since 1.10.0
 */
interface ModelCatalogEntry {
    /** Total tokens the model's context window can hold. */
    context_window_tokens: number;
    /** Maximum tokens the model may emit; caps `reserved_output_tokens` when set. */
    max_output_tokens?: number;
    /** Tokenizer identifier; selects (and is reported by) the tokenizer used. */
    tokenizer_version: string;
}
/**
 * Workspace `context_compression_aggression` policy. Separate from the
 * optimizer's `BudgetOptimizerConfig.strategy` (which uses `balanced`): the two
 * remain intentionally distinct so neither change drags the other.
 *
 * @since 1.10.0
 */
type WorkspaceCompressionPolicy = 'standard' | 'aggressive' | 'conservative';
/**
 * Usage band the breakdown falls into, derived from the active compression
 * policy's thresholds. Distinct from `BudgetTier` (`green/yellow/amber/red`).
 *
 * @since 1.10.0
 */
type BudgetBand = 'comfortable' | 'tightening' | 'compressed' | 'force-summary';
/**
 * Fully-assembled per-turn context slices plus the active model and policy.
 * Slices are raw strings; the engine tokenizes them.
 *
 * @since 1.10.0
 */
interface ComputeBudgetInput {
    system_prompt: string;
    project_knowledge: string;
    retrieved_chunks: string[];
    /** `null` when no rolling summary exists yet. */
    rolling_summary: string | null;
    recent_turns: string;
    new_user_message: string;
    /** Requested reserved output tokens; capped to `model.max_output_tokens`. */
    reserved_output_tokens: number;
    model: ModelCatalogEntry;
    compression_policy: WorkspaceCompressionPolicy;
}
/**
 * Audit record attached when one or more retrieved chunks were dropped because
 * a single chunk's token cost exceeded the remaining available budget.
 *
 * @since 1.10.0
 */
interface CompressionAuditRecord {
    event: 'context.compression_applied';
    reason: 'chunk_exceeds_budget';
    dropped_chunk_count: number;
}
/**
 * Successful budget breakdown: every slice's token cost, the total, the
 * percentage of the active window in use, and the band.
 *
 * @since 1.10.0
 */
interface BudgetBreakdownSuccess {
    ok: true;
    system_prompt_tokens: number;
    project_knowledge_tokens: number;
    retrieved_chunks_tokens: number;
    /** `"—"` sentinel when no rolling summary exists yet (see `ComputeBudgetInput`). */
    rolling_summary_tokens: number | '—';
    recent_turns_tokens: number;
    new_user_message_tokens: number;
    reserved_output_tokens: number;
    total_used: number;
    usage_pct: number;
    band: BudgetBand;
    tokenizer_version: string;
    dropped_chunk_count: number;
    compression_audit?: CompressionAuditRecord;
}
/**
 * Error breakdown returned when the model catalog entry has no
 * `context_window_tokens`; no default window is ever substituted.
 *
 * @since 1.10.0
 */
interface BudgetBreakdownError {
    ok: false;
    error: string;
    missing_field: 'context_window_tokens';
}
/**
 * Discriminated union on `ok` returned by `ContextBudgetEnforcer.computeBudget`.
 *
 * @since 1.10.0
 */
type BudgetBreakdown = BudgetBreakdownSuccess | BudgetBreakdownError;
/**
 * Priority tag assigned to a single conversation turn. Three values, distinct
 * from the four-value `ContextSegmentPriority.tier`: turns have no `critical`
 * band — protected turns occupy `high`.
 *
 * @since 1.10.0
 */
type TurnPriority = 'high' | 'normal' | 'low';
/**
 * A conversation turn handed to `PriorityClassifier.tag`. `decision_packet` and
 * `approval_turn` mark protected turns that must always resolve to `high`. An
 * incoming `priority` carries a tag from a prior pass so re-tagging a protected
 * turn that is already `high` is a silent no-op (the re-tag guard).
 *
 * @since 1.10.0
 */
interface TurnInput {
    turn_id: string;
    text: string;
    decision_packet?: boolean;
    approval_turn?: boolean;
    priority?: TurnPriority;
}
/**
 * A turn with its resolved priority. Same shape as `TurnInput` but `priority` is
 * required.
 *
 * @since 1.10.0
 */
interface TaggedTurn extends TurnInput {
    priority: TurnPriority;
}
/**
 * Audit record emitted when the classifier model returned a non-`high` tag for a
 * protected turn and the engine corrected it. The desktop surfaces these as
 * `context.context_health_warning` events.
 *
 * @since 1.10.0
 */
interface ContextHealthWarning {
    type: 'context.context_health_warning';
    reason: 'priority_invariant_breach';
    turn_id: string;
    classifier_returned: TurnPriority;
    corrected_to: 'high';
}
/**
 * Result of `PriorityClassifier.tag`: every input turn tagged, plus any
 * invariant-breach warnings raised while correcting protected turns.
 *
 * @since 1.10.0
 */
interface TurnTagResult {
    tagged: TaggedTurn[];
    warnings: ContextHealthWarning[];
}
/**
 * Caller-supplied policy snapshot for `PriorityClassifier.tag`. `all_normal`
 * (workspace priority-shaping disabled) flattens ordinary turns to `normal`
 * while protected turns still resolve to `high`. Absent means `false`.
 *
 * @since 1.10.0
 */
interface TurnTagPolicy {
    all_normal?: boolean;
}

declare const SKILL_MODEL_TIERS: readonly ["fast", "medium", "reasoning"];
type SkillModelTier = (typeof SKILL_MODEL_TIERS)[number];
declare const SKILL_OUTPUT_FORMATS: readonly ["markdown", "yaml", "json"];
type SkillOutputFormat = (typeof SKILL_OUTPUT_FORMATS)[number];
interface SkillTriggerCondition {
    [dimension: string]: string[];
}
interface SkillRequestRoutingRule {
    priority: number;
    patterns: string[];
    target_workflow: string;
}
interface SkillInputSchemaField {
    type: 'string' | 'string[]' | 'boolean' | 'path' | 'path[]' | 'object';
    required: boolean;
    description?: string;
}
interface SkillInputSchema {
    [name: string]: SkillInputSchemaField;
}
interface SkillCompletionTrigger {
    emit: string;
    triggers: string[];
}
interface SkillDefinition {
    name: string;
    description: string;
    file: string;
    model_tier: SkillModelTier;
    triggers: SkillTriggerCondition[];
    request_routing?: SkillRequestRoutingRule[];
    max_lines: number;
    cacheable: boolean;
    cache_key_inputs: string[];
    output_format: SkillOutputFormat;
    input_schema: SkillInputSchema;
    on_complete?: SkillCompletionTrigger;
    tools?: string[];
    max_output_tokens?: number;
}
interface LoadedSkill extends SkillDefinition {
    body: string;
    line_count: number;
}
/** Origin of a skill in a merged listing. */
type SkillSource = 'built-in' | 'runtime';
/** In-memory input shape for hot-registering a skill (no disk path required). */
interface RuntimeSkillDescriptor {
    /** Raw SKILL.md markdown content. */
    content: string;
    /** Optional label used to build the synthetic `file` value. */
    sourceLabel?: string;
}
/** A skill in a {@link RuntimeSkillRegistry} snapshot, tagged with its origin and id. */
interface RuntimeSkillListEntry extends LoadedSkill {
    /** Namespaced identifier: the skill name for built-ins, `runtime:<name>` for runtime entries. */
    id: string;
    source: SkillSource;
}
interface SkillResult {
    skill_name: string;
    findings: string[];
    output_paths: string[];
    cache_hit: boolean;
}
interface SkillCacheResult {
    hit: boolean;
    result?: unknown;
    input_hash?: string;
}
interface CacheStats {
    total_entries: number;
    total_size_bytes: number;
    hit_rate: number;
}

declare class SkillCacheManager {
    private readonly cacheDir;
    private readonly parser;
    private readonly cacheability;
    private cacheabilityLoaded;
    constructor(cacheDir: string);
    checkCache(skillName: string, inputFiles: string[]): Promise<SkillCacheResult>;
    writeCache(skillName: string, inputHash: string, result: unknown, filesHashed: string[]): Promise<void>;
    invalidateModule(moduleName: string): Promise<number>;
    getStats(): Promise<CacheStats>;
    computeInputHash(files: string[]): Promise<string>;
    private isCacheable;
    private updateMetrics;
    private readMetrics;
    private loadCacheability;
}

declare class CacheWarmer {
    private readonly cacheManager;
    constructor(cacheManager: SkillCacheManager);
    prewarm(skillName: string, predictedInputFiles: string[]): Promise<boolean>;
}

interface PredictiveCacheOptions {
    enabled: boolean;
    confidence_threshold: number;
    max_candidates: number;
}
declare const DEFAULT_PREDICTIVE_CACHE_OPTIONS: PredictiveCacheOptions;
declare class PredictiveCache {
    private readonly transitionLog;
    private readonly warmer;
    private readonly metrics;
    private readonly options;
    constructor(transitionLog: TransitionLogManager, warmer: CacheWarmer, metrics: CacheMetricsTracker, options?: PredictiveCacheOptions);
    onSkillComplete(sessionId: string, stackKey: string, workflow: string, completedSkill: string, outputHash: string, nextSkill?: string): Promise<void>;
    static computeOutputHash(output: string): string;
}

type BudgetVerdict = 'ok' | 'warning' | 'requires-justification' | 'blocked';
type BudgetDecision = 'allow' | 'warn' | 'require-justification' | 'block';
interface BudgetCheckResult {
    verdict: BudgetVerdict;
    usage_pct: number;
    budget: number;
    actual: number;
    message: string;
}
interface BudgetEvaluation {
    decision: BudgetDecision;
    usage_ratio: number;
}
declare class ContextBudgetEnforcer {
    private readonly budget;
    constructor(config?: Partial<ContextBudgetConfig>);
    static fromProfile(profile: Pick<ProjectProfile, 'model_routing'>, tier?: SkillModelTier, overrides?: Partial<ContextBudgetConfig>): ContextBudgetEnforcer;
    checkBudget(estimatedTokens: number): BudgetCheckResult;
    shouldCompact(currentTokens: number): boolean;
    evaluate(tokensUsed: number): BudgetEvaluation;
    /**
     * Compute an exact token-by-token breakdown of how the active model's context
     * window is consumed by a fully-assembled set of per-turn slices (PQD-167).
     *
     * Returns an error union (rather than substituting a default window) when the
     * model catalog entry has no `context_window_tokens`. Any single retrieved
     * chunk whose token cost exceeds the remaining available budget is excluded
     * from the total and reflected in `dropped_chunk_count` plus a
     * `context.compression_applied` audit record.
     *
     * @since 1.10.0
     */
    static computeBudget(input: ComputeBudgetInput): Promise<BudgetBreakdown>;
}

interface EvictionResult {
    evicted_count: number;
    tokens_reclaimed: number;
    evicted_sources: string[];
    evicted_segments: ContextSegmentPriority[];
    remaining_segments: ContextSegmentPriority[];
}
declare class ContextEvictor {
    evict(segments: ContextSegmentPriority[], tier: BudgetTier): EvictionResult;
}

/** A single chat message passed to {@link InferenceProvider.complete}. */
interface InferenceMessage {
    role: 'system' | 'user' | 'assistant';
    content: string;
}
/** Options for a single completion call. */
interface InferenceCompleteOptions {
    /** Soft deadline in milliseconds; the engine also enforces its own timeout. */
    timeoutMs?: number;
    /** Cancellation signal; aborted before/while running yields no result. */
    signal?: AbortSignal;
}
/** Minimal chat-completion provider the summariser calls. */
interface InferenceProvider {
    complete(messages: InferenceMessage[], opts?: InferenceCompleteOptions): Promise<string>;
}

/** Options for {@link TurnSummarizer.summarise}. */
interface SummariseOptions {
    /** Prior rolling summary to fold in (the summarise-the-summary path, AC3). */
    priorSummary?: {
        text: string;
        valid_through_turn_id: string;
    };
    /** Workspace model-tier preference forwarded to the provider's selection. */
    summaryModelPreference?: 'local' | 'cheapest' | 'default';
    /** Cancellation signal; already-aborted yields a `cancelled` failure. */
    signal?: AbortSignal;
    /** Provider that performs the actual inference; absent ⇒ graceful failure. */
    inferenceProvider?: InferenceProvider;
    /** Inference deadline; defaults to the 30-second contract. Mainly for tests. */
    timeoutMs?: number;
}
declare class TurnSummarizer {
    summarize(turnText: string, turnIndex: number, timestamp: string): SummarizedTurn;
    private extractDecisions;
    private extractFilesTouched;
    private extractBlockers;
    private extractNextSteps;
    estimateTokens(text: string): number;
    /**
     * Collapse older user+assistant turns into a single attributed rolling summary
     * via an injected {@link InferenceProvider} (PQD-169).
     *
     * Protected turns (`decision_packet`/`approval_turn`) are excluded from the
     * collapsed span and reported in `preserved_turn_ids`. A `priorSummary` is
     * folded in to summarise-the-summary. The result never exceeds the 2,000-token
     * cap: an over-length response is re-issued with a stricter prompt and, if
     * still over, truncated with `truncated: true`. An empty/malformed body is
     * retried once with an alternate template before failing. Timeouts (30 s),
     * cancellation, and a missing provider all return an explicit, non-partial
     * failure result so the caller can fall back without losing the prior summary.
     *
     * Token counts are best-effort (character/4); the cap is approximate.
     */
    summarise(messages: SummarisationMessage[], targetTokenCount: number, opts?: SummariseOptions): Promise<SummariseResult>;
    /** Slice text down to the token cap using the char/4 estimate. */
    private truncateToTokenCap;
    /**
     * Run one provider call under a merged timeout+cancellation signal. Classifies
     * the outcome so the caller only ever sees a typed success or failure.
     */
    private invoke;
}

type ContextPriorityTier = 'critical' | 'high' | 'medium' | 'low';
/**
 * Pluggable model that scores a single conversation turn. Injected into
 * `PriorityClassifier` so a test (or a future inference-backed model) can control
 * the raw tag a turn receives before the engine applies its invariants. The score
 * for a protected turn is advisory only — `tag` always overrides it to `high`.
 *
 * @since 1.10.0
 */
interface TurnClassifierModel {
    score(turn: TurnInput): TurnPriority;
}
/**
 * Default heuristic turn model. v1 has no signal that promotes an ordinary turn,
 * so every unprotected turn scores `normal` (matching the "default to normal" AC);
 * `high` is reserved for protected turns, which `tag` enforces separately. Richer
 * heuristics (e.g. error/blocker detection) are deferred to a future ticket.
 *
 * @since 1.10.0
 */
declare class InferredTurnClassifierModel implements TurnClassifierModel {
    score(): TurnPriority;
}
declare class PriorityClassifier {
    private readonly turnModel;
    constructor(turnModel?: TurnClassifierModel);
    /**
     * Tag every conversation turn `high`, `normal`, or `low` for the context-window
     * loop, enforcing the decision-packet/approval invariant: any protected turn
     * always resolves to `high`, whatever the model says and whatever the policy is.
     *
     * Batched per summarisation trigger: the caller invokes `tag` once with the
     * whole turn list, not once per message. The model is run in a single pass.
     *
     * @param turns  The turns to tag. A turn already carrying `priority: 'high'`
     *   that is protected is left untouched (the re-tag guard) and raises no warning.
     * @param policy Caller-supplied snapshot. `all_normal: true` flattens ordinary
     *   turns to `normal` while protected turns still resolve to `high`.
     * @returns The tagged turns plus any `priority_invariant_breach` warnings raised
     *   while correcting a protected turn the model scored below `high`.
     * @since 1.10.0
     */
    tag(turns: TurnInput[], policy?: TurnTagPolicy): TurnTagResult;
    classify(artifactSource: string, artifactType: string): ContextPriorityTier;
    classifyByContent(_content: string, phase: string): ContextPriorityTier;
}

interface BudgetOptimizerConfig {
    strategy: 'aggressive' | 'balanced' | 'conservative';
    summarize_after_turns: number;
}
declare class ContextBudgetOptimizer {
    private readonly summarizer;
    private readonly evictor;
    private readonly projectRoot;
    private readonly config;
    /** Reserved for priority-aware segment selection in future phases. */
    readonly classifier: PriorityClassifier;
    constructor(summarizer: TurnSummarizer, classifier: PriorityClassifier, evictor: ContextEvictor, projectRoot: string, config?: BudgetOptimizerConfig);
    static fromProfile(projectRoot: string, profile: Pick<ProjectProfile, 'efficiency' | 'model_routing'>, summarizer?: TurnSummarizer, classifier?: PriorityClassifier, evictor?: ContextEvictor): ContextBudgetOptimizer;
    evaluate(tokensUsed: number, maxTokens: number, metrics?: Partial<Pick<BudgetOptimizerState, 'summarized_turn_count' | 'evicted_segment_count'>> & {
        current_hit_rate?: number;
        target_hit_rate?: number;
    }): Promise<{
        action: 'continue' | 'warn' | 'compact';
        tier: BudgetTier;
    }>;
    /**
     * Follow-on (PQD-172): once turns carry a `PriorityClassifier.tag` priority, a
     * future pass should skip summarising turns where `priority === 'high'` so
     * decision-packet/approval turns survive compaction verbatim. The signature is
     * intentionally unchanged in this ticket — the AC does not require it.
     */
    summarizeTurns(turns: Array<{
        text: string;
        timestamp: string;
    }>, olderThanIndex: number): Promise<SummarizedTurn[]>;
    evictSegments(segments: ContextSegmentPriority[], tier: BudgetTier): EvictionResult;
    summarizeBeforeIndex(turnCount: number): number;
    resolveMaxTokens(profile: Pick<ProjectProfile, 'model_routing'>): number;
    saveState(state: BudgetOptimizerState): Promise<void>;
    private classifyTier;
}

declare class FileRegistryMapper {
    getAffectedRegistries(file: string): string[];
}

interface RefreshResult {
    total_registries: number;
    refreshed: number;
    skipped: number;
    registries: string[];
}
declare class DifferentialRefresh {
    private readonly mapper;
    constructor(mapper?: FileRegistryMapper);
    refresh(changedFiles: string[]): Promise<RefreshResult>;
}

interface HitTrackerInput {
    session_id: string;
    phase: string;
    story?: string;
}
declare class ContextHitTracker {
    private readonly loaded;
    private readonly referenced;
    private readonly input;
    constructor(sessionId: string, phase: string, story?: string);
    constructor(input: HitTrackerInput);
    recordLoaded(files: string[]): void;
    recordReferenced(file: string): void;
    computeHitRate(): ContextHitEntry;
    reset(): void;
}

/**
 * A persisted conversation message as the desktop stores it. A superset of the
 * minimal wire shape: the extra fields let the engine compute lineage (which
 * branch is active) and exclude stopped/discarded turns.
 *
 * `branchId`/`parentMessageId`/`discardedAt` are all optional so a flat history
 * (no branching, the current desktop shape) is a valid `DisplayMessage[]`.
 *
 * @since 1.10.0
 */
interface DisplayMessage {
    id: string;
    role: 'user' | 'assistant' | 'system';
    content: string;
    /** ISO-8601 creation timestamp; the sole chronological ordering key. */
    createdAt: string;
    /** A turn the user stopped mid-stream; excluded from the rebuild. */
    stopped?: boolean;
    /** ISO-8601 instant the turn was discarded by an edit; `null`/absent ⇒ live. */
    discardedAt?: string | null;
    /** Branch this message belongs to; `null`/absent ⇒ the main branch. */
    branchId?: string | null;
    /** Parent message id for lineage walking; `null`/absent ⇒ a root turn. */
    parentMessageId?: string | null;
}
/**
 * The clean wire shape handed to the LLM API: role and content only, plus an
 * optional `name` for tool/function attribution. Everything the model does not
 * need (ids, timestamps, branch metadata) is dropped.
 *
 * @since 1.10.0
 */
interface ApiMessage {
    role: 'user' | 'assistant' | 'system';
    content: string;
    name?: string;
}
/**
 * Where a retrieved chunk was inserted into the rebuilt conversation, for a
 * context inspector to render. `position` is the index of the inserted message
 * in the returned `ApiMessage[]`.
 *
 * @since 1.10.0
 */
interface RetrievedChunkRef {
    chunkId: string;
    position: number;
}
/**
 * The deterministic output of a rebuild. `messages` is the API conversation for
 * the next turn; `retrievedChunkIds` lists every chunk folded in (empty when no
 * retrieval ran); `truncated`/`truncatedTurnCount` report whether oldest turns
 * were dropped after summarisation could not fit history into the window.
 *
 * @since 1.10.0
 */
interface ConversationRebuildResult {
    messages: ApiMessage[];
    retrievedChunkIds: string[];
    truncated: boolean;
    truncatedTurnCount: number;
    /**
     * Issue #123 — SHA-256 over the canonical, versioned materials this rebuild
     * froze (lineage, classifier output, retrieved chunk digests, budget,
     * summariser mode, truncation). Proves the context is replayable from these
     * inputs; it does NOT assert bit-identical LLM regeneration. See
     * `computeContextHash`.
     *
     * @since 1.19.0
     */
    contextHash: string;
}
/**
 * SHA-256 hex digest of the serialised rebuild inputs (display conversation plus
 * classifier output). Used as the {@link DisplayMessage} cache key so an
 * unchanged turn is served without re-running the classifier or budget passes.
 *
 * @since 1.10.0
 */
type RebuildCacheKey = string;
/**
 * Structured failure thrown by `rebuildApiConversation` when the budget breakdown
 * is malformed (e.g. a non-positive window) or the summariser/optimizer throws.
 * The rebuild never auto-retries; it surfaces this so the desktop's catch block
 * can map it to a pending-error banner. The `kind` discriminant lets a consumer
 * route on it without an `instanceof` import.
 *
 * @since 1.10.0
 */
declare class RebuildFailedError extends Error {
    readonly kind: "rebuild_failed";
    readonly reason: string;
    constructor(reason: string);
}

/**
 * Resolve the active-branch lineage of a display conversation.
 *
 * - Excludes every message with `stopped === true` or `discardedAt` set.
 * - When parent pointers exist, walks back from the most-recent live message to
 *   its root, so a competing branch (not an ancestor of the leaf) is dropped.
 * - When no parent pointers exist (a flat history), keeps every live message on
 *   the leaf's branch — the current desktop shape, where the whole list is one
 *   linear conversation.
 * - Always returns messages in chronological order; pure and deterministic.
 */
declare function resolveActiveLineage(messages: DisplayMessage[]): DisplayMessage[];

/** Default entry cap; oldest entries are evicted past this (§5 safeguard). */
declare const DEFAULT_REBUILD_CACHE_MAX_SIZE = 50;
declare class RebuildCache {
    private readonly maxSize;
    private readonly entries;
    constructor(maxSize?: number);
    /** Hash the rebuild inputs into a stable key. Same inputs ⇒ same key. */
    computeKey(displayMessages: DisplayMessage[], classifierOutput: object): RebuildCacheKey;
    /** Return the cached result, refreshing its recency, or `undefined` on miss. */
    get(key: RebuildCacheKey): ConversationRebuildResult | undefined;
    /** Store a result, evicting the least-recently-used entry past the cap. */
    set(key: RebuildCacheKey, result: ConversationRebuildResult): void;
    /** Current entry count; primarily for tests and diagnostics. */
    get size(): number;
}

/** Inputs to {@link rebuildApiConversation}. */
interface RebuildInput {
    /** Full persisted conversation (stopped/edited/branched messages included). */
    displayMessages: DisplayMessage[];
    /** Classifier signals that drive retrieval and budgeting. */
    classifierOutput: Pick<ClassificationResult, 'retrieval_needed' | 'context_budget_hint'>;
    /** Chunks to fold in when `classifierOutput.retrieval_needed` is true. */
    retrievedChunks?: {
        chunkId: string;
        content: string;
    }[];
    /** Token budget for the next turn (the model window from the budget enforcer). */
    budgetTokens: number;
    /** Token estimator + (legacy) summariser; defaults to a fresh instance. */
    summarizer?: TurnSummarizer;
    /** Compresses older turns before truncation; absent ⇒ straight to truncation. */
    optimizer?: ContextBudgetOptimizer;
    /** When provided, a hit skips the classifier and budget passes entirely. */
    cache?: RebuildCache;
    /** When set, a truncation also writes a durable `context.truncated` event. */
    audit?: {
        projectRoot: string;
        sessionId: string;
    };
}
/**
 * Rebuild the API conversation for the next turn from a display conversation.
 *
 * Excludes stopped and discarded turns, follows only the active branch, and —
 * when the active branch plus retrieval exceeds `budgetTokens` — first compresses
 * older turns via the optimizer, then drops the oldest turns and reports
 * `truncated`. Retrieved chunks are inserted after any leading system context.
 *
 * Throws {@link RebuildFailedError} (no retry) when `budgetTokens` is malformed
 * or the optimizer throws.
 */
declare function rebuildApiConversation(input: RebuildInput): Promise<ConversationRebuildResult>;

type RetrievalDepth = 'none' | 'standard' | 'deep';
interface Chunk {
    id: string;
    source_file: string;
    ast_node_type: 'function' | 'class' | 'method' | 'import-block' | 'constant' | 'fallback';
    ast_node_path: string;
    exported_symbols: string[];
    content: string;
    char_count: number;
    content_hash: string;
    modified_at_ms?: number;
}
interface ChunkIndexEntry {
    source_file: string;
    source_file_hash: string;
    modified_at: string;
    chunks: Chunk[];
}
interface ChunkIndex {
    version: 1;
    generated_at: string;
    entries: ChunkIndexEntry[];
}
interface LoadStats {
    session_id: string;
    timestamp: string;
    tokens_before: number;
    tokens_after: number;
    reduction_pct: number;
    chunks_loaded: number;
    rag_chunks_retrieved?: number;
    rag_fallback_reason?: string;
    retrieval_depth?: RetrievalDepth;
    retrieval_escalated?: boolean;
    reranking?: {
        enabled: boolean;
        backend: string;
        model: string;
        candidate_pool_size: number;
        pre_rerank_chunk_ids: string[];
        post_rerank_chunk_ids: string[];
        latency_ms: number;
    };
    fusion_strategy?: FusionDiagnostic;
}
interface ActionRecommendation {
    action_type: 'workflow';
    confidence: number;
    evidence_chunk_ids: string[];
    workflow_id: string;
    explanation: string;
    requires_user_approval: true;
}
interface FusionDiagnostic {
    signals: string[];
    filters_applied: string[];
    filter_fallback?: boolean;
    filter_fallback_reason?: string;
}
interface SemanticLoadClassification {
    complexity?: 'trivial' | 'low' | 'medium' | 'high' | 'very-high';
    risk?: 'low' | 'medium' | 'high';
    scope?: 'single-file' | 'single-module' | 'multi-module' | 'system-wide';
    workflow?: string | null;
    affected_modules?: string[];
    file_extension?: string;
    frameworks?: string[];
    recency_cutoff_ms?: number;
}
interface SemanticLoadOptions {
    taskKeywords: string[];
    taskDescription?: string;
    taskTargetFile?: string;
    symbolReferences?: string[];
    tokenBudget: number;
    fullContextOverride?: boolean;
    classification?: SemanticLoadClassification;
}

/**
 * Identifies the chunking STRATEGY an index was built with (RAG buildout F22). It is
 * stamped into `RagIndexMeta.chunker_version` on every (re)build and compared on every
 * status check: an index built by a different chunker is treated as invalid, so it is
 * never incrementally synced (which would mix old and new chunk boundaries — corrupt)
 * and is fully rebuilt instead. Bump this whenever the chunking behaviour changes
 * (e.g. swapping the boundary detector for a tree-sitter parser).
 *
 * `cast-blurb-v1` = regex boundary detection + the cAST split-then-merge pass below
 * (F22) + deterministic contextual blurbs prepended before embedding/BM25 (F24). The
 * version covers the whole index-build strategy (how a file becomes index entries AND
 * what text those entries carry), so changing either half forces a clean rebuild.
 */
declare const CHUNKER_VERSION = "cast-blurb-v1";
declare class AstChunker {
    private readonly maxChunkChars;
    private readonly merge;
    /**
     * @param maxChunkChars per-chunk non-whitespace budget; also the cAST merge target.
     * @param merge when true (default) the cAST split-then-merge pass coalesces small
     *   adjacent same-file chunks up to the budget (RAG buildout F22). Disable for the
     *   raw boundary-only chunks (used by tests / the legacy `regex` strategy).
     */
    constructor(maxChunkChars?: number, merge?: boolean);
    /**
     * Chunk a file into AST-node-level slices, then (when enabled) apply the cAST
     * split-then-merge refinement so tiny adjacent symbols ride together up to the
     * budget instead of becoming one-line fragments. The boundary detection is the
     * "split"; {@link castMerge} is the "merge".
     */
    chunk(filePath: string, content: string): Chunk[];
    /** Boundary-only chunking (the "split" half of cAST), per detected language. */
    private chunkRaw;
    private detectLanguage;
    private parseTypeScript;
    private parsePhp;
    private parseDart;
    private splitLargeSegment;
    fallbackSplit(filePath: string, content: string): Chunk[];
    private makeChunk;
    private extractExportedSymbols;
}
/**
 * The cAST "merge" pass (RAG buildout F22). Boundary detection produces one chunk per
 * symbol, which leaves many tiny one-line chunks (a re-export, a small constant, a
 * two-line helper). cAST coalesces a run of ADJACENT chunks FROM THE SAME FILE into one
 * chunk as long as the combined non-whitespace size stays within `targetChars`, so the
 * model receives a coherent slice rather than a fragment, and the index holds fewer,
 * better-filled chunks.
 *
 * Safe-by-construction: it only ever joins chunks that were already adjacent within one
 * file, never crosses a file boundary, never drops or reorders content, and passes an
 * already-oversize chunk through untouched (the boundary splitter already shrank it as
 * far as it could). A single chunk is returned verbatim — no needless re-hash.
 */
declare function castMerge(chunks: readonly Chunk[], targetChars: number): Chunk[];

/**
 * Every stable error code the engine surfaces. Frozen runtime value; the
 * `EngineErrorCode` union below is derived from its keys so adding a code in
 * one place is enough.
 */
declare const ENGINE_ERROR_CODES: {
    readonly MISSING_POLICY_CONTEXT: "MISSING_POLICY_CONTEXT";
    readonly DUPLICATE_SKILL_IDENTIFIER: "DUPLICATE_SKILL_IDENTIFIER";
    readonly DECISION_PACKET_CORRUPT: "DECISION_PACKET_CORRUPT";
    readonly UNSUPPORTED_FILE_TYPE: "UNSUPPORTED_FILE_TYPE";
    readonly VERSION_INCOMPATIBLE: "VERSION_INCOMPATIBLE";
    readonly MANIFEST_PRODUCTION_TIMEOUT: "MANIFEST_PRODUCTION_TIMEOUT";
    readonly WORKFLOW_ALREADY_RUNNING: "WORKFLOW_ALREADY_RUNNING";
    readonly VECTOR_INDEX_STORAGE_ERROR: "VECTOR_INDEX_STORAGE_ERROR";
    readonly CANCELLED_BY_CONSUMER: "CANCELLED_BY_CONSUMER";
    readonly LOGGER_SINK_FAILED: "LOGGER_SINK_FAILED";
    readonly UNKNOWN_ENGINE_ERROR: "UNKNOWN_ENGINE_ERROR";
};
/** Stable error code surfaced on every typed engine error. */
type EngineErrorCode = (typeof ENGINE_ERROR_CODES)[keyof typeof ENGINE_ERROR_CODES];
/**
 * Fields common to every engine error payload. Individual payloads extend this
 * with the fields relevant to their code.
 */
interface EngineErrorPayloadBase extends Record<string, unknown> {
    /** Whether the consumer may safely retry the operation. */
    retryable?: boolean;
    /** Names of payload fields whose values were stripped before surfacing. */
    redacted_fields?: string[];
}
interface MissingPolicyContextPayload extends EngineErrorPayloadBase {
    /** Which policy lookup was attempted (e.g. workflow allow-list). */
    policy: string;
}
interface DuplicateSkillIdentifierPayload extends EngineErrorPayloadBase {
    /** The identifier that collided. */
    skill_id: string;
}
interface DecisionPacketCorruptPayload extends EngineErrorPayloadBase {
    decision_id: string;
    reason: string;
    /** Project-relative path to the offending packet, when known. */
    packet_path?: string;
}
interface UnsupportedFileTypePayload extends EngineErrorPayloadBase {
    /** The rejected file path (project-relative). */
    path: string;
    /** The extension or kind that was not supported. */
    extension: string;
}
interface VersionIncompatiblePayload extends EngineErrorPayloadBase {
    /** The version observed (engine or consumer, per `kind`). */
    found: string;
    /** The minimum/maximum version required. */
    required: string;
    /** Which side was incompatible. */
    kind: 'engine-too-new' | 'engine-too-old' | 'schema';
}
interface ManifestProductionTimeoutPayload extends EngineErrorPayloadBase {
    /** The configured timeout that elapsed, in milliseconds. */
    timeout_ms: number;
}
interface WorkflowAlreadyRunningPayload extends EngineErrorPayloadBase {
    /** The workflow or run already in flight. */
    workflow: string;
    /** The run id holding the lock, when known. */
    run_id?: string;
}
interface VectorIndexStorageErrorPayload extends EngineErrorPayloadBase {
    /** Index that failed to persist (e.g. `file`, `vision`). */
    index: string;
    /** The underlying failure reason. */
    reason: string;
}
interface CancelledByConsumerPayload extends EngineErrorPayloadBase {
    /** Resumable checkpoint left on disk, when the cancelled call wrote one. */
    checkpoint_path?: string;
}
interface LoggerSinkFailedPayload extends EngineErrorPayloadBase {
    /** The sink that failed (e.g. `stderr`, a consumer logger). */
    sink: string;
    reason: string;
}
interface UnknownEngineErrorPayload extends EngineErrorPayloadBase {
    /** Short, message-only description of the underlying failure. */
    message?: string;
}
/**
 * A single taxonomy entry, returned by `listErrorTaxonomy`. `payload_shape` is a
 * runtime-inspectable field→type-description map (e.g. `{ decision_id: 'string' }`)
 * so consumers and test harnesses can introspect the shape without TS reflection.
 */
interface TaxonomyEntry {
    code: EngineErrorCode;
    description: string;
    /** The canonical default for this code; individual instances may override. */
    retryable: boolean;
    payload_shape: Record<string, string>;
}
/**
 * Return every taxonomy entry. The result is computed only from the static
 * `TAXONOMY` table — it is identical before and after any engine operation and
 * is safe to call before any operation has run.
 */
declare function listErrorTaxonomy(): TaxonomyEntry[];
/**
 * Look up a single taxonomy entry by code, or `undefined` if the code is not in
 * the taxonomy (used to detect undocumented failures).
 */
declare function getTaxonomyEntry(code: string): TaxonomyEntry | undefined;

interface FrameworkErrorOptions {
    /**
     * Stable error code. New code should use an {@link EngineErrorCode} from the
     * taxonomy; the `(string & {})` arm keeps backward compatibility with
     * pre-taxonomy subclasses and arbitrary-string construction while preserving
     * literal autocomplete for the known codes.
     */
    code: EngineErrorCode | (string & {});
    cause?: unknown;
    details?: Record<string, unknown>;
    /** Whether the consumer may safely retry. Defaults to `false`. */
    retryable?: boolean;
    /**
     * When provided, string-valued `details` fields are run through the project's
     * secret redaction before the error is surfaced, and the stripped field names
     * are recorded in `details.redacted_fields`. Omitted ⇒ no fs access, details
     * pass through unchanged (the common path for existing subclasses).
     */
    projectRoot?: string;
}
declare class FrameworkError extends Error {
    readonly code: EngineErrorCode | (string & {});
    readonly details?: Record<string, unknown>;
    /** Whether the consumer may safely retry the operation that failed. */
    readonly retryable: boolean;
    constructor(message: string, options: FrameworkErrorOptions);
}

type EmbeddingProviderErrorCode = 'missing_api_key' | 'invalid_api_key' | 'rate_limited' | 'download_failed' | 'provider_error';
declare class EmbeddingProviderError extends Error {
    readonly provider: EmbeddingProviderName;
    readonly code: EmbeddingProviderErrorCode;
    readonly cause?: unknown | undefined;
    constructor(provider: EmbeddingProviderName, code: EmbeddingProviderErrorCode, message: string, cause?: unknown | undefined);
}
declare function isEmbeddingProviderError(error: unknown): error is EmbeddingProviderError;
interface RagIndexMeta {
    version: 1;
    provider: EmbeddingProviderName;
    model: string;
    built_at: string;
    chunk_count: number;
    embedding_dimensions: number;
    branch?: string;
    base_branch?: string;
    base_commit?: string;
    head_commit?: string;
    chunker_version?: string;
}
interface StoredVectorItem {
    id: string;
    vector: number[];
}
interface StoredVectorChunk extends Chunk, StoredVectorItem {
    vector: number[];
}
/**
 * The kinds of vision-derived text the engine accepts into the retrieval index.
 * Closed union: new kinds are additive, non-breaking changes. The engine does
 * not run the vision call itself — the consumer (desktop) performs OCR/captioning
 * and hands the engine the resulting plain text.
 */
type ExtractionKind = 'ocr' | 'caption';
declare const SUPPORTED_EXTRACTION_KINDS: readonly ["ocr", "caption"];
/**
 * Image extensions the engine accepts as a vision source path. The engine does
 * NOT read these files; it only validates that the caller's source path carries
 * an acceptable extension before keying chunks to it.
 */
declare const SUPPORTED_VISION_EXTENSIONS: readonly [".png", ".jpg", ".jpeg", ".gif", ".webp", ".tiff", ".bmp", ".avif", ".heic"];
interface VisionIngestInput {
    /** On-disk path of the image the text was extracted from; used as `source_file`. */
    sourcePath: string;
    /** The plain-text result of the consumer's vision call. */
    text: string;
    /** Which kind of extraction produced the text. */
    extractionKind: ExtractionKind;
}
interface VisionIngestResult {
    chunkCount: number;
    sourcePath: string;
    extractionKind: ExtractionKind;
}
/** A chunk derived from externally-supplied vision text rather than a source-file read. */
interface VisionChunk extends Chunk {
    extraction_kind: ExtractionKind;
    /** True when `source_file` no longer exists on disk (desktop owns path lifecycle). */
    source_missing?: boolean;
}
interface StoredVisionChunk extends VisionChunk, StoredVectorItem {
    vector: number[];
}
type RagIngestErrorCode = 'unsupported_file_type' | 'unknown_extraction_kind' | 'empty_extracted_text' | 'path_outside_project' | 'text_not_utf8';
/**
 * Stable, named failure for {@link VisionIngestInput} validation. The `code`
 * field is part of the public contract — consumers route UI behaviour off it.
 */
declare class RagIngestError extends FrameworkError {
    readonly code: RagIngestErrorCode;
    constructor(code: RagIngestErrorCode, message: string, details?: Record<string, unknown>);
}
declare function isRagIngestError(error: unknown): error is RagIngestError;
/**
 * A named, persistent vector collection addressable by id. Branded so a raw
 * string can't be passed by accident — construct one with {@link toCrsCollectionId}.
 */
type CrsCollectionId = string & {
    readonly __crsCollectionId: unique symbol;
};
/**
 * Brand a string as a {@link CrsCollectionId}. The only validation is
 * non-emptiness; filesystem-safety is handled at the path layer (`escapeCollectionId`).
 *
 * @throws {Error} when `id` is empty/whitespace.
 */
declare function toCrsCollectionId(id: string): CrsCollectionId;
/**
 * The write-side shape the desktop hands {@link RagService.writeChunks}: the raw
 * text to embed plus the session/workspace provenance. The engine produces the
 * `vector` and stamps `vector_timestamp`, yielding a stored {@link CrsChunk}.
 */
interface CrsChunkInput {
    id: string;
    content: string;
    source_session_id: string;
    source_workspace_id: string;
    created_at: string;
    project_id: string;
}
/** A persisted CRS chunk: a {@link CrsChunkInput} the engine has embedded and stamped. */
interface CrsChunk extends StoredVectorItem {
    content: string;
    source_session_id: string;
    source_workspace_id: string;
    created_at: string;
    project_id: string;
    /** ISO timestamp stamped by the engine when the vector was produced. */
    vector_timestamp: string;
}
/** A retrieval hit from a CRS collection, carrying its session/workspace provenance. */
interface CrsRetrievalResult {
    chunk: CrsChunk;
    sourceSessionId: string;
    sourceWorkspaceId: string;
    score: number;
}
/** Audit-grade payload emitted when a session's chunks are written into a collection. */
interface CrsIndexedSessionEvent {
    session_id: string;
    project_id: string;
    chunk_count: number;
}
/** Progress event emitted by {@link RagService.reindex} during a side-by-side rebuild. */
interface ReindexProgressEvent {
    status_percent: number;
    current_collection: string;
    est_time: number;
}
type ReindexProgressHandler = (event: ReindexProgressEvent) => void;
/**
 * Raised when the in-memory write backlog (used when the embedding provider is
 * unreachable) overflows its cap and the oldest pending chunks are dropped.
 *
 * The backlog is in-memory only: a host-process restart loses any queued chunks
 * silently. This error is the desktop's signal that data loss has occurred so it
 * can surface a degraded-mode notice. Mirrors {@link CorruptVectorIndexError} in
 * being a plain `Error` subclass (no `FrameworkError` inheritance).
 */
declare class EmbeddingBacklogOverflow extends Error {
    readonly dropped_count: number;
    constructor(dropped_count: number, message?: string);
}
declare function isEmbeddingBacklogOverflow(error: unknown): error is EmbeddingBacklogOverflow;
interface VectorIndexPayload<T extends StoredVectorItem = StoredVectorItem> {
    version: 1;
    dimensions: number;
    items: T[];
}
interface VectorQueryResult<T extends StoredVectorItem = StoredVectorItem> {
    score: number;
    item: T;
}
interface RagStatus {
    enabled: boolean;
    configured_provider?: EmbeddingProviderName;
    configured_model?: string;
    index_present: boolean;
    valid: boolean;
    /** True when the stored index was built with a different provider/model than currently configured. */
    stale_metadata?: boolean;
    built_at?: string;
    chunk_count: number;
    size_bytes: number;
    reason?: string;
    /** Number of vision-extracted chunks stored in the separate vision index (PQD-102). */
    vision_chunk_count?: number;
}
interface EmbeddingProvider {
    readonly name: EmbeddingProviderName;
    readonly model: string;
    validate(): Promise<void>;
    embed(input: string | string[]): Promise<number[][]>;
}
interface LocalEmbeddingProgress {
    loaded?: number;
    total?: number;
    status?: string;
}
interface LocalEmbeddingOutput {
    tolist?: () => number[] | number[][];
}
interface LocalEmbeddingExtractor {
    (input: string[], options: {
        pooling: 'mean';
        normalize: true;
    }): Promise<LocalEmbeddingOutput | number[] | number[][]>;
}
interface TransformersRuntimeEnv {
    cacheDir?: string;
    localModelPath?: string;
    allowLocalModels?: boolean;
    allowRemoteModels?: boolean;
}
interface OpenAiEmbeddingClient {
    embeddings: {
        create(input: {
            model: string;
            input: string | string[];
        }): Promise<{
            data: Array<{
                embedding: number[];
            }>;
        }>;
    };
}
interface VoyageEmbeddingClient {
    embed(input: {
        input: string | string[];
        model: string;
    }): Promise<{
        data: Array<{
            embedding: number[];
        }>;
    }>;
}
interface ProviderProgressUpdate {
    phase: 'download' | 'load' | 'build';
    message: string;
    loaded?: number;
    total?: number;
    percent?: number;
}
interface ChunkIndexSyncResult {
    index: ChunkIndex;
    changed_files: string[];
    added_files: string[];
    deleted_files: string[];
    updated: boolean;
}
interface RagRetrievalResult {
    vector_scores: Map<string, number>;
    chunks_retrieved: number;
    retrieved_chunk_ids: string[];
    retrieved_source_files: string[];
    retrieved_chunks: Array<Pick<StoredVectorChunk, 'id' | 'source_file' | 'content'>>;
    fallback_reason?: string;
    /**
     * Issue #354 — the top pre-floor fused score for the query, when any candidate
     * existed (before the similarity/relief floor was applied). Lets the consumer render
     * an honest "none above the floor (best 58%)" line instead of silently omitting the
     * retrieved-context section. Undefined when retrieval never scored anything (rag off,
     * no/stale index, error) — those keep the section omitted (disabled == today).
     */
    best_score?: number;
    /**
     * Issue #354 — true when the returned chunks came from the RELIEF band (nothing
     * cleared `rag_similarity_threshold`, so the top slices at or above `rag_relief_floor`
     * were delivered tagged low-confidence). The consumer tags these slices so the model
     * weighs them accordingly. Absent/false for high-confidence (above-floor) results.
     */
    low_confidence?: boolean;
}
/** A single scored candidate before the similarity/relief floor is applied (#354 probe). */
interface RagScoredCandidate {
    id: string;
    source_file: string;
    content: string;
    score: number;
}
interface BuildIndexOptions {
    intelligence?: IntelligenceConfig;
    onProgress?: (update: ProviderProgressUpdate) => void;
    /**
     * Optional consumer cancellation signal (PQD-104). When it aborts, `rebuild`
     * stops at the next chunk-batch boundary, writes the chunks embedded so far to
     * a resumable `.partial` index, emits a single `run.cancelled` event, and
     * throws a `CancelledError` whose `details.checkpoint_path` points at that
     * partial index. No full index file is written.
     */
    signal?: AbortSignal;
}
type ProviderFactory = (projectRoot: string, intelligence: IntelligenceConfig, onProgress?: (update: ProviderProgressUpdate) => void) => Promise<EmbeddingProvider>;
type ComparisonMode = 'lexical-vs-rag' | 'rag-vs-candidate' | 'feature-off-vs-on';
type EvalQueryClass = 'simple-lexical' | 'vocabulary-mismatch' | 'ambiguous' | 'multi-part' | 'workflow-triggering' | 'negative';
interface EvalDatasetItem {
    id: string;
    query_class: EvalQueryClass;
    task_description: string;
    keywords: string[];
    expected_file?: string;
    should_skip_retrieval?: boolean;
    workflow_trigger?: string;
}
interface EvalTrace {
    item_id: string;
    retrieval_depth?: string;
    first_stage_chunk_ids: string[];
    applied_metadata_filters?: string[];
    reranked_chunk_ids?: string[];
    packed_chunk_ids: string[];
    packed_token_count?: number;
    routed_workflow_id?: string;
    final_answer_or_recommendation?: string;
}
interface ModelGradedScores {
    retrieval_relevance: number;
    answer_faithfulness: number;
    action_recommendation_usefulness: number;
    routing_correctness: number;
}
interface EvalRunResult {
    mode: ComparisonMode;
    timestamp: string;
    dataset_size: number;
    traces: EvalTrace[];
    model_graded?: ModelGradedScores;
}

declare class ChunkIndexManager {
    private readonly projectRoot;
    constructor(projectRoot: string);
    get indexPath(): string;
    load(): Promise<ChunkIndex | null>;
    save(index: ChunkIndex): Promise<void>;
    rebuild(files: string[], chunker: AstChunker): Promise<ChunkIndex>;
    incrementalUpdate(changedFiles: string[], index: ChunkIndex, chunker: AstChunker): Promise<ChunkIndex>;
    isStale(index: ChunkIndex): Promise<{
        stale: boolean;
        changedFiles: string[];
    }>;
    sync(files: string[], chunker: AstChunker): Promise<ChunkIndexSyncResult>;
    private computeFileHash;
}

type MetadataFilterType = 'file_extension' | 'module_path_prefix' | 'framework' | 'recency_cutoff_ms';
interface MetadataFilter {
    type: MetadataFilterType;
    value: string | number;
}

interface ScoringContext {
    keywords: string[];
    targetFilePath?: string;
    symbolReferences?: string[];
    sessionStartMs: number;
    vectorScores?: Map<string, number>;
}
declare class RelevanceScorer {
    private readonly threshold;
    constructor(threshold?: number);
    score(chunk: Chunk, context: ScoringContext): number;
    filterAndRank(chunks: Chunk[], context: ScoringContext, filters?: MetadataFilter[]): {
        chunks: Chunk[];
        fusion_strategy: FusionDiagnostic;
    };
    private vectorSimilarityScore;
    private keywordOverlapScore;
    private symbolReferenceScore;
    private filePathProximityScore;
    private astDepthPenalty;
}

interface BudgetAllocation {
    critical_budget: number;
    task_relevant_budget: number;
    supporting_budget: number;
}
interface BudgetClassificationHints {
    complexity?: SemanticLoadClassification['complexity'];
    scope?: SemanticLoadClassification['scope'];
}
declare class BudgetAllocator {
    allocate(totalBudget: number, hints?: BudgetClassificationHints): BudgetAllocation;
    packChunks(chunks: Chunk[], budgetTokens: number, estimateTokens?: (text: string) => number): Chunk[];
}

interface SemanticLoaderOptions {
    projectRoot: string;
    fullContextOverride?: boolean;
    sessionId: string;
}
interface ResolvedArtifact {
    path: string;
    content?: string;
    type?: string;
}
declare class SemanticLoader {
    private readonly options;
    private readonly chunker;
    private readonly indexManager;
    private readonly scorer;
    private readonly allocator;
    private readonly rag;
    private readonly supportedExtensions;
    private readonly priorityClassifier;
    private reranker?;
    constructor(options: SemanticLoaderOptions);
    load(artifacts: ResolvedArtifact[], loadOptions: SemanticLoadOptions): Promise<{
        chunks: Chunk[];
        stats: LoadStats;
        action_recommendations?: ActionRecommendation[];
    }>;
    private isSupportedFile;
    private artifactToChunk;
    private persistStats;
    private packChunksByPriority;
    private classifyChunkPriority;
}

declare const COMPLIANCE_SCHEMA_VERSION: 1;
declare const SPEC_REVIEW_SCHEMA_VERSION: 1;
declare const DEFAULT_OBLIGATION_INDEX_PATH = ".paqad/compliance/obligation-index.json";
/**
 * Converts a spec file path to a filesystem-safe slug used as the compliance
 * subdirectory name (e.g. `docs/my-spec.md` → `my-spec`).
 */
declare function slugifySpec(specFile: string): string;
/** Returns the per-spec obligation index path (FR-2.1). */
declare function specIndexPath(specFile: string): string;
/** Returns the per-spec compliance report path (FR-3.5). */
declare function specReportPath(specFile: string): string;
/** Returns the per-spec spec-quality review path (FR-SQ2.1). */
declare function specReviewPath(specFile: string): string;

type ObligationCategory = 'functional' | 'edge-case' | 'acceptance' | 'non-functional' | 'unclassified';
type ComplianceState = 'covered' | 'partial' | 'uncovered' | 'indeterminate';
type SpecDefectSeverity = 'critical' | 'major' | 'minor';
type SpecReviewDefectCategory = 'contradiction' | 'formula_inconsistency' | 'boundary_gap' | 'goal_conflict' | 'dangling_reference' | 'missing_negative_case' | 'unresolvable_reference';
type SpecReviewDefectStatus = 'new' | 'existing' | 'resolved';
interface Obligation {
    obligation_id: string;
    category: ObligationCategory;
    description: string;
    pass_criteria: string | null;
    source_section: string;
    source_line: number | null;
    spec_file: string;
    affected_by_spec_defects?: string[];
}
interface ObligationIndexMetadata {
    spec_file: string;
    spec_hash: string;
    extracted_at: string;
    obligation_count: number;
    schema_version: number;
    warnings: string[];
}
interface ObligationIndex {
    metadata: ObligationIndexMetadata;
    obligations: Obligation[];
}
interface ComplianceReportObligation extends Obligation {
    state: ComplianceState;
    evidence: string[];
}
interface ComplianceReportSummary {
    total: number;
    covered: number;
    partial: number;
    uncovered: number;
    indeterminate: number;
    compliance_ratio: number;
}
interface ComplianceReport {
    metadata: {
        spec_file: string;
        spec_hash: string;
        generated_at: string;
        schema_version: number;
        /** SHA-256 of sorted test-file contents — used for incremental cache validation (FR-3.6). */
        test_files_hash: string;
        /** True when the report was returned from cache without re-scanning (FR-3.6). */
        cache_hit: boolean;
    };
    summary: ComplianceReportSummary;
    spec_review: {
        defect_count: number;
        critical_count: number;
        warning: string | null;
    } | null;
    obligations: ComplianceReportObligation[];
    /** Convenience list of obligation IDs whose state is `uncovered` (FR-3.3). */
    uncovered_obligations: string[];
}
interface SpecReviewLocation {
    section: string;
    line_range: [number, number];
    text_excerpt: string;
}
interface SpecReviewDefect {
    defect_id: string;
    category: SpecReviewDefectCategory;
    severity: SpecDefectSeverity;
    description: string;
    locations: SpecReviewLocation[];
    suggested_resolution: string;
    affected_obligation_ids: string[] | null;
    status: SpecReviewDefectStatus;
}
interface SpecPatternAdvisory {
    advisory_id: string;
    title: string;
    description: string;
}
interface SpecReviewReportMetadata {
    spec_file: string;
    spec_hash: string;
    reviewed_at: string;
    defect_count: number;
    schema_version: number;
}
interface SpecReviewReport {
    metadata: SpecReviewReportMetadata;
    defects: SpecReviewDefect[];
    pattern_advisories: SpecPatternAdvisory[];
}

interface ExtractObligationsOptions {
    spec_file: string;
    spec_markdown: string;
    extracted_at?: string;
    spec_review?: SpecReviewReport | null;
}
declare function extractObligationIndex(options: ExtractObligationsOptions): ObligationIndex;

interface LoadObligationIndexOptions {
    project_root: string;
    index_path?: string;
}
declare function loadObligationIndex(options: LoadObligationIndexOptions): Promise<ObligationIndex | null>;
interface SaveObligationIndexOptions {
    project_root: string;
    index: ObligationIndex;
    index_path?: string;
}
declare function saveObligationIndex(options: SaveObligationIndexOptions): Promise<string>;
declare function isEnoentError(error: unknown): boolean;

interface CheckComplianceOptions {
    project_root: string;
    index: ObligationIndex;
    test_globs?: string[];
    /**
     * Absolute or project-root-relative path where the report is loaded from (cache)
     * and written to after a fresh scan (FR-3.5, FR-3.6).  When omitted the report
     * is returned in memory only.
     */
    report_path?: string;
    spec_review?: SpecReviewReport | null;
    /**
     * Optional consumer cancellation signal (PQD-104). Checked before the test
     * file scan and before the report is written; an abort throws `CancelledError`
     * and writes no report.
     */
    signal?: AbortSignal;
}
declare function checkSpecCompliance(options: CheckComplianceOptions): Promise<ComplianceReport>;
declare function assertComplianceSummaryInvariants(summary: {
    total: number;
    covered: number;
    partial: number;
    uncovered: number;
    indeterminate: number;
    compliance_ratio: number;
}): void;

declare const BOUNDARY_SCHEMA_VERSION: 1;
/**
 * How each spec relates to the shared type (FR-BT1.3).
 */
type BoundaryRelationship = 'producer_consumer' | 'bidirectional' | 'shared_utility' | 'unanalyzable';
/**
 * A single shared type boundary detected via @boundary annotation or TypeScript
 * enum/union export (FR-BT1.2).
 */
interface BoundaryInterface {
    /** TypeScript type / enum name, e.g. "GateResult". */
    type_name: string;
    /** Source file where the type is declared. */
    file: string;
    /** Spec that produces instances of this type (null when unresolved). */
    producer_spec: string | null;
    /** Specs that consume instances of this type. */
    consumer_specs: string[];
    /** All possible states/values the producer can emit. */
    output_states: string[];
    relationship: BoundaryRelationship;
}
/** Unhandled variant — a state the producer emits that a consumer never references. */
interface UnhandledVariant {
    type_name: string;
    state: string;
    producer_spec: string | null;
    consumer_spec: string;
}
/** Persisted boundary manifest at .paqad/compliance/boundary-manifest.json. */
interface BoundaryManifest {
    metadata: {
        generated_at: string;
        schema_version: number;
    };
    boundaries: BoundaryInterface[];
}
/** Boundary coverage report at .paqad/compliance/boundary-report.json. */
interface BoundaryReport {
    metadata: {
        generated_at: string;
        schema_version: number;
    };
    total_interfaces: number;
    total_states: number;
    handled_count: number;
    unhandled_count: number;
    gate_result: 'pass' | 'warn' | 'skip';
    interfaces: BoundaryInterfaceReport[];
}
interface BoundaryInterfaceReport {
    type_name: string;
    file: string;
    producer_spec: string | null;
    consumer_specs: string[];
    total_states: number;
    unhandled_variants: UnhandledVariant[];
}

interface DoctorIssue {
    level: 'error' | 'warning';
    message: string;
}
interface DoctorResult {
    ok: boolean;
    issues: DoctorIssue[];
}
declare function doctorObligationIndex(index: ObligationIndex | null): DoctorResult;
declare function doctorBoundaryReport(report: BoundaryReport | null): DoctorResult;
declare function doctorSpecReview(review: SpecReviewReport | null, options?: {
    spec_is_newer?: boolean;
}): DoctorResult;

interface ReviewSpecOptions {
    spec_file: string;
    spec_markdown: string;
    reviewed_at?: string;
    previous_report?: SpecReviewReport | null;
}
declare function reviewSpecification(options: ReviewSpecOptions): SpecReviewReport;
declare function attachSpecDefectsToObligations(review: SpecReviewReport, obligations: Obligation[]): SpecReviewReport;
declare function compareDefects(left: SpecReviewDefect, right: SpecReviewDefect): number;

interface LoadSpecReviewOptions {
    project_root: string;
    review_path?: string;
    spec_file?: string;
}
declare function loadSpecReviewReport(options: LoadSpecReviewOptions): Promise<SpecReviewReport | null>;
interface SaveSpecReviewOptions {
    project_root: string;
    report: SpecReviewReport;
    review_path?: string;
    spec_file?: string;
}
declare function saveSpecReviewReport(options: SaveSpecReviewOptions): Promise<string>;

interface GenerateVitestSkeletonOptions {
    project_root: string;
    /** Obligations to scaffold. Pass only uncovered/partial to respect FR-5.5, or all for --all mode. */
    obligations: Obligation[];
    output_dir: string;
}
declare function generateVitestSkeletons(options: GenerateVitestSkeletonOptions): Promise<string[]>;
/**
 * Renders a failing Vitest test stub for a single obligation (FR-5.2).
 *
 * The generated file:
 * - Uses the obligation ID in the test name.
 * - Includes a comment block with obligation_id, description, pass_criteria, and source_section.
 * - Contains an inline `@obligation` annotation so compliance-checker can detect coverage.
 * - Fails when executed (explicit assertion that is always false).
 */
declare function renderVitestSkeleton(obligation: Obligation): string;

/**
 * FR-BT1: Interface Contract Detection (annotation-based path)
 *
 * Scans TypeScript source files for @boundary annotations and TypeScript
 * enum/union exports, and builds a BoundaryInterface list.
 *
 * Annotation format (one line comment before the type declaration):
 *   // @boundary <TypeName> [producer:<spec-slug>] [consumer:<spec-slug>,...] [states:<a>,<b>,...]
 *
 * If no explicit states are given, states are extracted from the TypeScript
 * enum or union type definition immediately following the annotation.
 */

/**
 * Parse a TypeScript source file's text and return all BoundaryInterface
 * declarations it contains.
 */
declare function detectBoundariesInSource(filePath: string, source: string): BoundaryInterface[];

/**
 * FR-BT2: State Set Extraction
 *
 * Given a BoundaryInterface, determines which states are "handled" by each
 * consumer spec by scanning the consumer spec's Markdown text for mentions
 * of each state value.
 *
 * Returns the set of unhandled variants — states in the producer's output set
 * that never appear in the consumer spec.
 */

interface ExtractionResult {
    boundary: BoundaryInterface;
    /** Per-consumer map from consumer_spec → array of unhandled states. */
    unhandled_by_consumer: Map<string, UnhandledVariant[]>;
}
/**
 * Compute unhandled variants for one BoundaryInterface.
 *
 * @param boundary   The detected boundary.
 * @param specTexts  Map from spec-slug to the spec's full Markdown text.
 */
declare function extractUnhandledVariants(boundary: BoundaryInterface, specTexts: Map<string, string>): ExtractionResult;

/**
 * FR-BT3: Boundary Test Generation
 *
 * Generates idempotent Vitest test stubs for every output state of a
 * BoundaryInterface. Unhandled variants get a comment flagging the gap.
 *
 * Output path: .paqad/compliance/boundary-tests/<producer>__<consumer>__<TypeName>.test.ts
 */

interface GenerateBoundaryTestsOptions {
    project_root: string;
    boundary: BoundaryInterface;
    unhandled: UnhandledVariant[];
    /** Override output directory (default: .paqad/compliance/boundary-tests). */
    output_dir?: string;
}
interface GeneratedBoundaryTest {
    file_path: string;
    written: boolean;
}
declare function generateBoundaryTests(options: GenerateBoundaryTestsOptions): Promise<GeneratedBoundaryTest[]>;

/**
 * FR-BT4: Gate and Report Integration
 *
 * Produces and persists the boundary coverage report from the extraction
 * results.  Gate behaviour (FR-BT4.3):
 *   - 'skip'  — no boundaries detected
 *   - 'warn'  — unhandled variants exist
 *   - 'pass'  — all variants handled
 */

declare const DEFAULT_BOUNDARY_REPORT_PATH = ".paqad/compliance/boundary-report.json";
declare function buildBoundaryReport(results: ExtractionResult[]): BoundaryReport;
declare function saveBoundaryReport(report: BoundaryReport, projectRoot: string, reportPath?: string): Promise<string>;
declare function loadBoundaryReport(projectRoot: string, reportPath?: string): Promise<BoundaryReport | null>;

/**
 * FR-BT1 + FR-BT2 orchestration: scan source files for @boundary annotations,
 * load referenced spec texts, and compute unhandled variants.
 */

interface ScanBoundariesOptions {
    project_root: string;
    /** Globs for TypeScript source files to scan (default: src/**\/*.ts). */
    source_globs?: string[];
    /**
     * Map from spec-slug to absolute path of the spec Markdown file.
     * When provided, spec texts are loaded from disk for handling-set extraction.
     */
    spec_paths?: Map<string, string>;
}
declare function scanBoundaries(options: ScanBoundariesOptions): Promise<ExtractionResult[]>;

declare const DEFECT_PATTERN_SCHEMA_VERSION: 1;
/** Which integrity-system component produced the raw finding. */
type DefectSource = 'compliance' | 'audit' | 'heuristic' | 'test_quality' | 'boundary' | 'spec_review';
/** Stack context from the project profile at recording time. */
interface StackContext {
    frameworks: string[];
    traits: string[];
}
/**
 * A single defect finding recorded from one integrity-system cycle.
 * Multiple findings of the same subcategory roll up into a DefectPatternEntry.
 */
interface DefectFinding {
    defect_id: string;
    source: DefectSource;
    /** D1–D10 broad category from the integrity defect taxonomy. */
    category: string;
    /** Refined label: "{D-category}.{pattern}", e.g. "D5.missing-cli-surface". */
    subcategory: string;
    spec_file: string;
    obligation_id: string | null;
    stack_context: StackContext;
    description: string;
    file_path: string | null;
    recorded_at: string;
    resolved: boolean;
    recurrence_count: number;
}
/** Lightweight entry in the pattern index for fast lookups. */
interface DefectPatternIndexEntry {
    pattern_id: string;
    subcategory: string;
    frequency: number;
    last_seen: string;
    stale: boolean;
}
/** Full aggregated pattern stored at entries/{id}.json. */
interface DefectPatternEntry {
    pattern_id: string;
    subcategory: string;
    description: string;
    frequency: number;
    recency: string;
    stack_contexts: StackContext[];
    /** Up to 5 representative obligation descriptions. */
    example_obligations: string[];
    /** Up to 5 representative implementation file paths. */
    example_files: string[];
    severity_distribution: {
        critical: number;
        major: number;
        minor: number;
        info: number;
    };
    first_seen: string;
    last_seen: string;
    stale: boolean;
}
interface DefectPatternIndex {
    schema_version: number;
    updated_at: string;
    entries: DefectPatternIndexEntry[];
}
/** Advisory surfaced in the spec quality review (FR-DP4). */
interface PatternAdvisory {
    advisory_id: string;
    title: string;
    description: string;
}
/** Options for querying relevant patterns. */
interface PatternQueryOptions {
    stack_context?: StackContext;
    /** Only return patterns with frequency >= this value (default 3 per FR-DP4.4). */
    min_frequency?: number;
    /** Only return patterns last seen within this many days (default 365). */
    max_age_days?: number;
    /** Maximum number of patterns to return (default 5 per FR-DP5.3). */
    limit?: number;
}

/**
 * FR-DP2: Subcategory Classification
 *
 * Rule-based classifier that maps raw defect descriptions to hierarchical
 * subcategories ("{D-category}.{pattern}"). New rules are added to
 * CLASSIFICATION_RULES — zero core changes required (NFR-DP4).
 */
interface ClassificationRule {
    /** Pattern matched against the normalised description. */
    pattern: RegExp;
    /** Resulting subcategory string. */
    subcategory: string;
}
/**
 * Rules are evaluated in order; the first match wins.
 * All rules must produce a subcategory in the form "{D-category}.{label}".
 */
declare const CLASSIFICATION_RULES: ClassificationRule[];
/**
 * Classify a defect description into a hierarchical subcategory.
 * When no rule matches, falls back to "{source_category}.unclassified".
 */
declare function classifyDefect(description: string, sourceCategory: string): string;

/**
 * FR-DP3: Defect Pattern Store
 *
 * File-based store at ~/.paqad/defect-patterns/ (parallel to the solution
 * pattern library at ~/.paqad/patterns/).
 *
 * Layout:
 *   ~/.paqad/defect-patterns/
 *     index.json           – lightweight metadata per pattern
 *     entries/{id}.json    – full pattern entry
 */

declare function defaultStoreRoot(): string;
/** Record a batch of findings into the store. Creates or updates pattern entries. */
declare function recordFindings(findings: DefectFinding[], storeRoot?: string): Promise<void>;
/** Query patterns relevant to a given stack context. */
declare function queryPatterns(options: {
    stack_context?: StackContext;
    min_frequency?: number;
    max_age_days?: number;
    limit?: number;
}, storeRoot?: string): Promise<DefectPatternEntry[]>;
/** Remove patterns last seen more than `olderThanDays` days ago. */
declare function prunePatterns(olderThanDays: number, storeRoot?: string): Promise<number>;
/** Load the full index, rebuilding from entry files if it is corrupt. */
declare function loadIndex(storeRoot?: string): Promise<DefectPatternIndex>;
/** Load a single pattern entry by ID. Returns null if it does not exist or is corrupt. */
declare function loadEntry(patternId: string, storeRoot?: string): Promise<DefectPatternEntry | null>;
declare function ensureStoreDir(storeRoot: string): Promise<void>;
/** Mark patterns older than STALENESS_DAYS as stale without removing them. */
declare function markStaleEntries(index: DefectPatternIndex): void;

/**
 * FR-DP1: Defect Recording
 *
 * Converts integrity-system outputs into DefectFinding records and persists
 * them via the pattern store. Recording is automatic and adds < 100ms latency
 * (NFR-DP1) because it fires after the gate/report has already returned.
 */

interface RecordFromComplianceOptions {
    report: ComplianceReport;
    stack_context?: StackContext;
    storeRoot?: string;
}
/**
 * Record uncovered obligation defects from a compliance report (FR-DP1.1 source: compliance).
 * Returns the number of findings recorded.
 */
declare function recordFromComplianceReport(options: RecordFromComplianceOptions): Promise<number>;

/**
 * FR-DP4: Feedback into Spec Quality Review
 * FR-DP5: Feedback into Agent Context
 *
 * Queries the pattern store for patterns relevant to the current spec or task
 * and formats them as advisories (review) or a warning block (agent context).
 */

/**
 * FR-DP4: Build pattern advisories for the spec quality review report.
 * Returns an empty array when no relevant patterns meet the thresholds —
 * producing no noise in the first-implementation scenario (EC-DP1).
 */
declare function buildPatternAdvisories(options: {
    stack_context?: StackContext;
    spec_keywords?: string[];
    storeRoot?: string;
} & Pick<PatternQueryOptions, 'min_frequency' | 'max_age_days'>): Promise<PatternAdvisory[]>;
/**
 * FR-DP5: Format relevant patterns as a concise agent-context warning block.
 * Returns an empty string when no patterns qualify (EC-DP1 — no block, no error).
 * Caps at 5 patterns, each as a single sentence (FR-DP5.3).
 */
declare function formatAgentContextWarnings(options: {
    stack_context?: StackContext;
    storeRoot?: string;
} & Pick<PatternQueryOptions, 'min_frequency' | 'max_age_days'>): Promise<string>;

declare const AGENT_ROLES: readonly ["context-curator", "solution-architect", "db-expert", "ux-ui-analyst", "product-owner", "market-researcher", "implementer", "reviewer", "verifier", "security-auditor", "test-planner", "gap-detector", "requirement-analyst", "devops-engineer", "doc-maintainer", "performance-analyst", "data-modeler", "integration-architect", "qa-engineer", "user-flow-writer", "chief-architect", "application-architect"];
type AgentRole = (typeof AGENT_ROLES)[number];
interface TokenBudget {
    analysis: number;
    implementation: number;
    review: number;
}
interface SubagentConfig {
    role: AgentRole;
    description: string;
    tools: string[];
    model?: string;
    token_budget: number;
    early_termination_allowed: boolean;
}

declare const DEFAULT_CONTEXT_BUDGET: ContextBudget;
declare function resolveContextBudgetForModel(modelName: string, baseBudget?: ContextBudget): ContextBudget;
declare function resolveContextBudgetForModelTier(models: Record<SkillModelTier, string>, tier: SkillModelTier, baseBudget?: ContextBudget): ContextBudget;
declare const CONTEXT_LEVEL_BUDGETS: Record<ContextLevel, number>;
declare const ROLE_TOKEN_BUDGETS: Record<AgentRole, number>;

declare const SUPPORTED_DOMAINS: readonly ["coding", "content"];
declare const SUPPORTED_STACKS: readonly ["laravel", "flutter", "react", "vue", "django", "fastapi", "rails", "spring-boot", "express", "angular", "svelte", "astro", "go-web", "rust-web", "dotnet", "nextjs", "flask", "nestjs", "kotlin-android", "node-cli", "node-library", "node-service", "short-video"];
declare const SUPPORTED_CAPABILITIES: readonly ["inertia", "vue", "react", "tailwind", "boost", "pest", "phpunit", "docker", "compose", "sail", "next", "remix", "vite-spa", "gatsby", "nuxt", "quasar", "blazor", "ef-core", "minimal-api", "mvc", "razor-pages", "signalr", "azure", "identity", "app-router", "pages-router", "prisma", "trpc", "next-auth", "sqlalchemy", "celery", "blueprints", "flask-login", "flask-restx", "gunicorn", "typeorm", "graphql", "microservices", "swagger", "passport", "fastify", "jetpack-compose", "room", "hilt", "retrofit", "coroutines", "navigation", "datastore"];

declare const HOOK_EXIT_CODES: {
    readonly ALLOW: 0;
    readonly ERROR: 1;
    readonly BLOCK: 2;
};

declare const PATHS: {
    readonly AGENCY_DIR: ".paqad";
    readonly AGENCY_CACHE_DIR: ".paqad/cache";
    readonly AGENCY_SESSION_DIR: ".paqad/session";
    readonly PROJECT_PROFILE: ".paqad/project-profile.yaml";
    readonly PROJECT_CONFIG: ".paqad/.config";
    readonly PROJECT_CONFIG_EXAMPLE: ".paqad/.config.example";
    readonly PROJECT_CONFIGS_DIR: ".paqad/configs";
    readonly PROJECT_CONFIGS_README: ".paqad/configs/README.md";
    readonly DETECTION_REPORT: ".paqad/detection-report.json";
    readonly ONBOARDING_MANIFEST: ".paqad/onboarding-manifest.json";
    readonly RAG_IGNORE_CONFIG: ".paqad/rag.ignore.yaml";
    readonly STACK_DRIFT: ".paqad/stack-drift.json";
    readonly STACK_SNAPSHOT: ".paqad/stack-snapshot.json";
    readonly DELIVERY_DETECTION: ".paqad/delivery-detection.json";
    readonly DELIVERY_PR_BODY_TEMPLATE: ".paqad/templates/pr-body.md";
    readonly FRAMEWORK_VERSION: ".paqad/framework-version.txt";
    readonly FRAMEWORK_PATH: ".paqad/framework-path.txt";
    readonly AGENT_ENTRY_SENTINEL: ".paqad/.agent-entry-loaded";
    readonly GLOSSARY: ".paqad/glossary.md";
    readonly HANDOFF: ".paqad/session/handoff.md";
    readonly CHANGED_FILES: ".paqad/session/changed-files.json";
    readonly ACTIVE_IMPLEMENTATION_SESSION: ".paqad/session/active-implementation.json";
    readonly CONTEXT_HIT_LOG: ".paqad/session/context-hit-log.json";
    readonly REVIEW_DIGEST: ".paqad/session/review-digest.md";
    readonly PROJECT_QUESTION_ANSWER: ".paqad/session/project-question-answer.json";
    readonly AUDIT_LOG: ".paqad/audit.log";
    readonly DECISIONS_DIR: ".paqad/decisions";
    readonly DECISIONS_PENDING_DIR: ".paqad/decisions/pending";
    readonly DECISIONS_RESOLVED_DIR: ".paqad/decisions/resolved";
    readonly DECISIONS_EXPIRED_DIR: ".paqad/decisions/expired";
    readonly DECISIONS_INDEX: ".paqad/decisions/index.json";
    readonly DECISIONS_AUDIT_LOG: ".paqad/decisions/audit.jsonl";
    readonly DECISIONS_EVENTS_LOG: ".paqad/decisions/events.jsonl";
    readonly DECISIONS_LOCK: ".paqad/decisions/.lock";
    readonly DECISION_PAUSE_CONTRACT: ".paqad/decision-pause-contract.md";
    readonly NARRATION_CONTRACT: ".paqad/narration-contract.md";
    readonly CHUNK_INDEX: ".paqad/context/chunk-index.json";
    readonly LOAD_STATS: ".paqad/context/load-stats.json";
    readonly VECTORS_DIR: ".paqad/vectors";
    readonly VECTOR_INDEX: ".paqad/vectors/index.json";
    readonly VECTOR_META: ".paqad/vectors/meta.json";
    readonly VISION_VECTOR_INDEX: ".paqad/vectors/vision-index.json";
    readonly VISION_VECTOR_META: ".paqad/vectors/vision-meta.json";
    readonly CRS_DIR: ".paqad/crs";
    readonly SECRETS_ENV: ".paqad/secrets.env";
    readonly SESSION_ATTACHMENT_COLLECTIONS_DIR: ".paqad/attachments";
    readonly SESSION_ATTACHMENT_REGISTRY: ".paqad/attachments/registry.json";
    readonly ATTACHMENT_EVENTS_LOG: ".paqad/attachment-events.jsonl";
    readonly GLOBAL_PATTERN_VECTORS_DIR: ".paqad/patterns/vectors";
    readonly GLOBAL_PATTERN_VECTOR_INDEX: ".paqad/patterns/vectors/index.json";
    readonly GLOBAL_PATTERN_VECTOR_META: ".paqad/patterns/vectors/meta.json";
    readonly TRANSITION_LOG: ".paqad/cache/transition-log.json";
    readonly CACHE_METRICS: ".paqad/cache/metrics.json";
    readonly PLANNING_MANIFESTS_DIR: ".paqad/planning/manifests";
    readonly CHECKS_DIR: ".paqad/checks";
    readonly CHECKS_REPORT: ".paqad/checks/last-run.json";
    readonly REGRESSION_GUARDS_DIR: ".paqad/regression-guards";
    readonly FLAKY_TESTS_DIR: ".paqad/flaky-tests";
    readonly FLAKY_REGISTRY: ".paqad/flaky-tests/registry.json";
    readonly FINDINGS_DIR: ".paqad/findings";
    readonly TRIAGE_LEDGER: ".paqad/findings/triage.json";
    readonly EVIDENCE_LEDGER_DIR: ".paqad/ledger";
    readonly EVIDENCE_LEDGER: ".paqad/ledger/evidence.jsonl";
    readonly FEATURE_EVIDENCE_DIR: ".paqad/ledger/feature-evidence";
    readonly FEATURE_EVIDENCE_SESSION_DIR: ".paqad/ledger/feature-evidence/_session";
    readonly CHAT_LEDGER_DIR: ".paqad/ledger/_chat";
    readonly LEDGER_SESSION_ID: ".paqad/session/ledger-session-id";
    readonly EVIDENCE_RECEIPT: ".paqad/ledger/receipt.dsse.json";
    readonly EVIDENCE_RECEIPT_CHAIN: ".paqad/ledger/receipts.jsonl";
    readonly EVIDENCE_AI_BOM: ".paqad/ledger/ai-bom.json";
    readonly EVIDENCE_CONTEXT_STAMP: ".paqad/session/context-stamp.json";
    readonly TRACEABILITY_DIR: ".paqad/traceability";
    readonly TRACEABILITY_MAP: ".paqad/traceability/map.json";
    readonly QUALITY_BASELINE: ".paqad/quality-baseline.json";
    readonly PLANNING_MODULE_HEALTH_DIR: ".paqad/module-health";
    readonly MODULE_HEALTH_EVIDENCE_DIR: ".paqad/module-health-evidence";
    readonly MODULE_HEALTH_CONSUMED_EVENTS: ".paqad/module-health-consumed-events.json";
    readonly MODULE_HEALTH_LOCK: ".paqad/locks/module-health.lock";
    readonly MODULE_HEALTH_LOG: ".paqad/logs/module-health.log";
    readonly COMPILED_RULES: ".paqad/compiled-rules.json";
    readonly PLANNING_COSTS: ".paqad/cache/planning-costs.json";
    readonly CONTEXT_SESSION_ARTIFACT: ".paqad/context/session-context.md";
    readonly CODEBASE_MEMORY: ".paqad/crs/codebase-memory.json";
    readonly BASE_DRIFT_STATE: ".paqad/session/base-drift.json";
    readonly BASE_DRIFT_MARKER: ".paqad/session/base-drift.marker";
    readonly BASE_DRIFT_LOCK: ".paqad/locks/base-drift.lock";
    readonly CONTEXT_BUDGET_STATE: ".paqad/session/context-budget.json";
    readonly CONTEXT_SAVINGS: ".paqad/session/context-savings.json";
    readonly DEDUP_STATS: ".paqad/session/dedup-stats.json";
    readonly HANDOFF_JSON: ".paqad/session/handoff.json";
    readonly HANDOFF_STATS: ".paqad/session/handoff-stats.json";
    readonly WORKFLOWS_DIR: "docs/instructions/workflows";
    readonly WORKFLOW_RUNS_DIR: ".paqad/workflows";
    readonly SKILL_CACHE_DIR: ".paqad/cache/skill-results";
    readonly SKILL_INDEX: ".paqad/skill-index.json";
    readonly SKILL_AUDIT_EVENTS_LOG: ".paqad/skills/events.jsonl";
    readonly DOC_PROGRESS: ".paqad/doc-progress.json";
    readonly DOC_RUN_SESSION: ".paqad/session/doc-run.json";
    readonly PENTEST_ROOT_DIR: ".paqad/pentest";
    readonly PENTEST_RUNS_DIR: ".paqad/pentest/runs";
    readonly HEALTH_ROOT_DIR: ".paqad/health";
    readonly HEALTH_RUNS_DIR: ".paqad/health/runs";
    readonly HEALTH_BASELINE: ".paqad/health/baseline.json";
    readonly SITE_MAP_ROOT_DIR: ".paqad/site-map";
    readonly SITE_MAP_RUNS_DIR: ".paqad/site-map/runs";
    readonly SITE_MAP_BASELINE: ".paqad/site-map/baseline.json";
    readonly SITE_MAP_PROGRESS: ".paqad/site-map/progress.json";
    readonly INDEXES_DIR: ".paqad/indexes";
    readonly CODE_KNOWLEDGE_INDEX: ".paqad/indexes/code-knowledge.json";
    readonly FRAMEWORK_API_INDEX: ".paqad/indexes/framework-api.json";
    readonly SITE_MAP_CANONICAL_DIR: "docs/site-map";
    readonly SITE_MAP_CANONICAL_APP_MAP: "docs/site-map/app-map.yaml";
    readonly SITE_MAP_CANONICAL_JOURNEYS_DIR: "docs/site-map/journeys";
    readonly SITE_MAP_CANONICAL_ANSWERS: "docs/site-map/answers.yaml";
    readonly SITE_MAP_CANONICAL_LAYOUT: "docs/site-map/layout.yaml";
    readonly DOCS_DIR: "docs";
    readonly FRAMEWORK_DOCS_DIR: "docs/framework";
    readonly FRAMEWORK_STACK_DIR: "docs/instructions/stack";
    readonly RCA_DIR: "docs/rca";
    readonly PENTEST_DIR: "docs/pentest";
    readonly PENTEST_RETEST_DIR: "docs/pentest/retests";
    readonly HEALTH_DIR: "docs/health";
    readonly RULES_DIR: "docs/instructions/rules";
    readonly MODULE_MAP: "docs/instructions/rules/module-map.yml";
    readonly TOOLS_DIR: "docs/instructions/tools";
    readonly INSTRUCTIONS_DIR: "docs/instructions";
    readonly ARCHITECTURE_DIR: "docs/instructions/architecture";
    readonly DESIGN_SYSTEM_DIR: "docs/instructions/design-system";
    readonly DESIGN_TOKENS_FILE: "docs/instructions/design-system/design-tokens.json";
    readonly MODULES_DIR: "docs/modules";
    readonly REGISTRIES_DIR: "docs/instructions/registries";
    readonly BENCHMARKS_DIR: "docs/instructions/benchmarks";
    readonly TECH_DEBT_DIR: "docs/instructions/tech-debt";
    readonly MODULE_DB_DIR: "database";
    readonly MODULE_API_DIR: "api";
    readonly MODULE_INTEGRATION_DIR: "integration";
    readonly MODULE_UI_DIR: "ui";
    readonly MODULE_FEATURES_DIR: "features";
    readonly MODULE_USER_FLOWS_DIR: "user-flows";
    readonly MODULE_RESEARCH_DIR: "research";
    readonly MODULE_DECISIONS_DIR: "decisions";
    readonly MODULE_ERROR_CATALOG: "error-catalog.md";
    readonly CLAUDE_MD: "CLAUDE.md";
    readonly AGENTS_MD: "AGENTS.md";
    readonly ANTIGRAVITY_MD: "ANTIGRAVITY.md";
    readonly GEMINI_MD: "GEMINI.md";
    readonly SCRIPTS_DIR: "scripts";
    readonly HOOKS_DIR: ".paqad/hooks";
    readonly LOGS_DIR: ".paqad/logs";
    readonly LOCKS_DIR: ".paqad/locks";
    readonly AUTO_UPDATE_LOG: ".paqad/logs/auto-update.log";
    readonly PROSPECTIVE_DECISIONS_DIR: ".paqad/decisions/module-decisions";
    readonly MODULE_MAP_HISTORY_DIR: ".paqad/module-map/history";
    readonly MODULE_MAP_EVENTS_LOG: ".paqad/module-map/events.jsonl";
    readonly MODULE_MAP_DRIFT: ".paqad/module-map/drift.json";
    readonly SCHEMA_MARKER: ".paqad/schema-version.json";
    readonly SCHEMA_MIGRATION_LOG: ".paqad/schema-migrations.jsonl";
    readonly SCHEMA_MIGRATION_LOCK: ".paqad/locks/schema-migration.lock";
    readonly ONBOARDING_CHECKPOINT: ".paqad/onboarding-checkpoint.json";
    readonly RULE_SCRIPT_MAP: "docs/instructions/rules/rule-script-map.yml";
    readonly RULE_SCRIPTS_DIR: ".paqad/scripts/rules";
    readonly RULE_SCRIPTS_CACHE_DIR: ".paqad/scripts/rules/.cache";
    readonly RULE_SCRIPTS_REPORT: ".paqad/scripts/rules/.cache/report.json";
    readonly RULE_SCRIPTS_DRIFT: ".paqad/scripts/rules/.cache/drift.json";
    readonly DUPLICATION_REPORT: ".paqad/scripts/rules/.cache/duplication.json";
    readonly RULE_SCRIPT_MAP_HISTORY_DIR: ".paqad/scripts/rules/.history";
    readonly RULE_SCRIPT_MAP_EVENTS_LOG: ".paqad/scripts/rules/.history/events.jsonl";
    readonly CAPABILITY_LOCK: ".paqad/capability-lock.json";
};
declare const REGISTRIES: readonly ["module-registry.md", "feature-registry.md", "model-registry.md", "api-registry.md", "job-event-registry.md", "component-registry.md", "screen-registry.md", "table-registry.md", "query-registry.md", "test-registry.md", "error-code-registry.md", "integration-registry.md", "reuse-catalog.md"];

declare const PLANNING_MANIFEST_VERSION: 1;
declare const PLAN_MODES: {
    readonly FULL: "full";
    readonly DELTA: "delta";
};
declare const PLANNING_LANES: {
    readonly FAST: "fast";
    readonly GRADUATED: "graduated";
    readonly FULL: "full";
};
declare const REQUIREMENT_TYPES: {
    readonly FUNCTIONAL: "functional";
    readonly NON_FUNCTIONAL: "non-functional";
    readonly CONSTRAINT: "constraint";
    readonly EDGE_CASE: "edge-case";
};
declare const PROOF_TYPES: {
    readonly AUTOMATED: "automated";
    readonly MANUAL: "manual";
    readonly VISUAL: "visual";
};
declare const CRITERION_STATUSES: {
    readonly UNCOVERED: "uncovered";
    readonly COVERED: "covered";
    readonly PARTIAL: "partial";
    readonly INDETERMINATE: "indeterminate";
};
declare const HEALTH_TIERS: {
    readonly STABLE: "stable";
    readonly MODERATE: "moderate";
    readonly FRAGILE: "fragile";
    readonly UNKNOWN: "unknown";
};
declare const ROLLBACK_CLASSES: {
    readonly SAFE: "safe";
    readonly NEEDS_MIGRATION: "needs-migration";
    readonly DESTRUCTIVE: "destructive";
};

declare const PAQAD_SCHEMA_VERSION = "1.1.0";

interface CancelledErrorDetails extends Record<string, unknown> {
    /**
     * When the cancelled call left a resumable partial state on disk, this points
     * at the checkpoint the consumer can resume from (e.g. a `.partial` index).
     */
    checkpoint_path?: string;
}
/**
 * Thrown internally when a long-running engine call is cancelled by the consumer
 * via an `AbortSignal` (PQD-104). Public-facing entry points either convert this
 * into a stable resolved outcome (e.g. `PipelineResult.cancelled`) or re-throw it
 * with `details.checkpoint_path` set so the consumer can resume.
 */
declare class CancelledError extends FrameworkError {
    readonly code: 'CANCELLED_BY_CONSUMER';
    constructor(message?: string, details?: CancelledErrorDetails);
}
declare function isCancelledError(error: unknown): error is CancelledError;

declare class MissingPolicyContextError extends FrameworkError {
    readonly code: 'MISSING_POLICY_CONTEXT';
    constructor(message: string, details: MissingPolicyContextPayload, projectRoot?: string);
}
declare class DuplicateSkillIdentifierError extends FrameworkError {
    readonly code: 'DUPLICATE_SKILL_IDENTIFIER';
    constructor(message: string, details: DuplicateSkillIdentifierPayload, projectRoot?: string);
}
declare class DecisionPacketCorruptError extends FrameworkError {
    readonly code: 'DECISION_PACKET_CORRUPT';
    constructor(message: string, details: DecisionPacketCorruptPayload, projectRoot?: string);
}
declare class UnsupportedFileTypeError extends FrameworkError {
    readonly code: 'UNSUPPORTED_FILE_TYPE';
    constructor(message: string, details: UnsupportedFileTypePayload, projectRoot?: string);
}
declare class VersionIncompatibleError extends FrameworkError {
    readonly code: 'VERSION_INCOMPATIBLE';
    constructor(message: string, details: VersionIncompatiblePayload, projectRoot?: string);
}
declare class ManifestProductionTimeoutError extends FrameworkError {
    readonly code: 'MANIFEST_PRODUCTION_TIMEOUT';
    constructor(message: string, details: ManifestProductionTimeoutPayload, projectRoot?: string);
}
declare class WorkflowAlreadyRunningError extends FrameworkError {
    readonly code: 'WORKFLOW_ALREADY_RUNNING';
    constructor(message: string, details: WorkflowAlreadyRunningPayload, projectRoot?: string);
}
declare class VectorIndexStorageError extends FrameworkError {
    readonly code: 'VECTOR_INDEX_STORAGE_ERROR';
    constructor(message: string, details: VectorIndexStorageErrorPayload, projectRoot?: string);
}
declare class LoggerSinkFailedError extends FrameworkError {
    readonly code: 'LOGGER_SINK_FAILED';
    constructor(message: string, details: LoggerSinkFailedPayload, projectRoot?: string);
}
declare class UnknownEngineError extends FrameworkError {
    readonly code: 'UNKNOWN_ENGINE_ERROR';
    constructor(message: string, details?: UnknownEngineErrorPayload, projectRoot?: string);
}
/**
 * Normalise any thrown value into an engine error carrying a taxonomy code.
 *
 * - A {@link FrameworkError} whose `code` is already in the taxonomy passes
 *   through unchanged.
 * - A {@link CancelledError} (or any framework error) is preserved.
 * - Anything else — including a `FrameworkError` with a code the taxonomy does
 *   not name — is wrapped in {@link UnknownEngineError}, and the engine emits an
 *   internal log naming the missing taxonomy entry (AC: undocumented failure).
 */
declare function toEngineError(error: unknown): FrameworkError;
/** True when `code` is a value the engine taxonomy defines. */
declare function isEngineErrorCode(code: string): code is EngineErrorCode;

interface RedactPayloadResult {
    redacted: Record<string, unknown>;
    /** Names of the fields whose values were altered by redaction. */
    redacted_fields: string[];
}
/**
 * Run every string-valued field of `payload` through {@link redactSecrets} and
 * report which fields were touched. Non-string fields pass through untouched.
 *
 * When `projectRoot` is omitted, or the project has no secrets configured,
 * `redactSecrets` is a no-op and the payload is returned unchanged with an empty
 * `redacted_fields` list — so error construction never fails on a missing
 * `.paqad/secrets.env` (the common case in tests and CI).
 */
declare function redactPayload(payload: Record<string, unknown>, projectRoot?: string): RedactPayloadResult;

declare class ResolutionError extends FrameworkError {
    constructor(message: string, details?: Record<string, unknown>);
}

interface SchemaVersionErrorOptions {
    code?: string;
    cause?: unknown;
    details?: Record<string, unknown>;
}
declare class SchemaVersionError extends FrameworkError {
    constructor(message: string, options?: SchemaVersionErrorOptions);
}

/** Why a runtime skill registration or removal was refused. */
type SkillRegistrationErrorKind = 'malformed' | 'duplicate' | 'not-found' | 'built-in-protected';
interface SkillRegistrationErrorOptions {
    kind: SkillRegistrationErrorKind;
    /** Built-in skill identifier involved in a `duplicate` collision. */
    builtInId?: string;
    /** Runtime skill identifier involved in a `duplicate` collision. */
    runtimeId?: string;
    cause?: unknown;
}
/**
 * Stable, named error for runtime skill registration/removal failures, so a
 * consumer (e.g. an in-app skill editor) can `instanceof`-check and branch on
 * `kind`. The `duplicate` case carries both colliding identifiers.
 */
declare class SkillRegistrationError extends FrameworkError {
    readonly kind: SkillRegistrationErrorKind;
    readonly builtInId?: string;
    readonly runtimeId?: string;
    constructor(message: string, options: SkillRegistrationErrorOptions);
}

declare class ValidationError extends FrameworkError {
    /**
     * Stable, machine-readable identifier for *which* validation rule fired,
     * narrower than the generic `code: 'VALIDATION_ERROR'`. Optional and
     * backward-compatible — existing two-argument construction leaves it
     * undefined. Consumers (e.g. the skill audit trail, PQD-194) key on this to
     * route a failure to a specific UI behaviour without parsing the message.
     */
    readonly subCode?: string;
    constructor(message: string, details?: Record<string, unknown>, subCode?: string);
}

/**
 * Canonical structured-logging contract shared across the three Paqad runtimes
 * (engine CLI, desktop Electron app, API). Defining these shapes in the engine
 * lets the desktop and API import a single source of truth for log records,
 * the redaction allowlist, and the correlation-id field rather than each
 * runtime maintaining its own copy.
 */
/** Severity levels, ordered debug < info < warn < error. */
type LogLevel = 'debug' | 'info' | 'warn' | 'error';
/**
 * One emitted log line. Always JSON-serialisable. `correlation_id` is present
 * whenever the line belongs to a request flow that crosses runtimes so a
 * support engineer can join the full flow by that identifier alone. The open
 * index signature carries any additional structured fields the caller passes.
 */
interface StructuredLogRecord {
    level: LogLevel;
    /** ISO-8601 timestamp. */
    timestamp: string;
    /** Runtime name, e.g. `'engine'`, `'desktop'`, `'api'`. */
    runtime: string;
    /** Stable event name, e.g. `'verification.started'`. */
    event: string;
    /** Shared identifier joining lines across runtimes, when one exists. */
    correlation_id?: string;
    [key: string]: unknown;
}
/** Field names whose values must be redacted before a line is emitted. */
type RedactionAllowlist = readonly string[];
/**
 * Record of a single redaction. Runtimes can implement their own operational
 * counter backed by this shape so redaction metrics stay consistent.
 */
interface RedactionEvent {
    field: string;
    placeholder: string;
    timestamp: string;
}

/**
 * Consumer-pluggable logger contract (PQD-105).
 *
 * A consumer of the `paqad-ai` package (e.g. the desktop app) can hand the
 * engine its own logger at init via {@link setEngineLogger}. Every structured
 * log the engine would otherwise drop into an internal `console.*` call is then
 * delivered to that logger so the consumer can surface engine activity in its
 * own UI without polling log files.
 *
 * This is distinct from the internal structured JSON logger in
 * `src/core/logging/` (PQD-96): that emits JSON lines for the engine's own
 * runtimes; this is a single injection seam the consumer owns. The shared
 * {@link LogLevel} union is reused so both contracts speak the same severities.
 */

/**
 * A single structured log the engine hands to the consumer's logger. `payload`
 * is an optional bag of structured fields; oversized payloads are truncated
 * with a `{ __truncated: true }` marker before delivery.
 */
interface EngineLogEntry {
    level: LogLevel;
    message: string;
    payload?: Record<string, unknown>;
}
/**
 * The contract a consumer implements and installs via {@link setEngineLogger}.
 *
 * `log` may return a promise (e.g. an async sink such as an HTTP endpoint), but
 * the engine never awaits it — calls are fire-and-forget so a slow or blocking
 * logger can never stall engine work. Log ordering is therefore not guaranteed
 * for async loggers. The engine catches any synchronous throw or rejected
 * promise and continues; it must not throw back to the caller.
 */
interface EngineLogger {
    log(entry: EngineLogEntry): void | Promise<void>;
}

/**
 * Consumer-pluggable logger registry (PQD-105).
 *
 * Holds the single consumer logger the engine delivers structured logs to, plus
 * the {@link engineLog} dispatch every library module calls instead of `console.*`.
 *
 * Design contract:
 * - Fire-and-forget: a consumer logger that blocks or returns a slow promise
 *   never stalls engine work — the engine never awaits {@link EngineLogger.log}.
 * - Fault isolation: a synchronous throw or a rejected promise from the consumer
 *   logger is caught here and never propagates to the caller. The first fault
 *   emits exactly one notice through the stderr default; after that the logger
 *   is treated as faulted and logs fall through to the stderr default silently.
 * - Replacement, not fan-out: installing a logger replaces the previous one,
 *   which receives no further entries (and the fault flag resets).
 * - Safe default: with no logger installed, `warn`/`error` go to `process.stderr`
 *   and `debug`/`info` are dropped, so engine warnings stay visible in dev
 *   without forcing the consumer to install a logger.
 */

/**
 * Install the consumer logger. Replaces any previously installed logger (the
 * previous logger receives no further entries) and resets the fault flag so the
 * new logger gets a clean slate.
 */
declare function setEngineLogger(logger: EngineLogger): void;
/** Revert to the safe stderr default. The previously installed logger is dropped. */
declare function clearEngineLogger(): void;
/**
 * The currently installed consumer logger, or `null` when the safe default is
 * active. Named `getConsumerLogger` (not `getEngineLogger`) because the engine
 * already exports a `getEngineLogger()` returning the internal structured JSON
 * logger (PQD-96) — a distinct concern from the consumer injection seam here.
 */
declare function getConsumerLogger(): EngineLogger | null;
/**
 * The single internal logging entry-point for library modules — call this
 * instead of `console.*`. Delivers to the installed consumer logger when one is
 * present and healthy, otherwise to the safe stderr default. Never throws.
 */
declare function engineLog(level: LogLevel, message: string, payload?: Record<string, unknown>): void;

/** Options for {@link createLogger}. */
interface CreateLoggerOptions {
    /** Runtime name stamped on every record, e.g. `'engine'`. */
    runtime: string;
    /** Minimum level to emit. Lines below this threshold are dropped. Default `'info'`. */
    level?: LogLevel;
    /** Field names to redact. Default {@link DEFAULT_REDACTION_ALLOWLIST}. */
    allowlist?: RedactionAllowlist;
    /** Correlation id stamped on every record from this logger, when set. */
    correlationId?: string;
    /** Sink for serialised lines. Default writes to `process.stdout`. Test seam. */
    writeLine?: (line: string) => void;
    /** Timestamp source. Default `() => new Date().toISOString()`. Test seam. */
    now?: () => string;
}
/** Structured logger emitting one JSON line per call. */
interface StructuredLogger {
    debug(event: string, fields?: Record<string, unknown>): void;
    info(event: string, fields?: Record<string, unknown>): void;
    warn(event: string, fields?: Record<string, unknown>): void;
    error(event: string, fields?: Record<string, unknown>): void;
    log(level: LogLevel, event: string, fields?: Record<string, unknown>): void;
    /** Number of values redacted since creation or the last reset. */
    getRedactionCount(): number;
    resetRedactionCount(): void;
    setLevel(level: LogLevel): void;
    setAllowlist(list: RedactionAllowlist): void;
    /**
     * Returns a logger that stamps `correlation_id` on every line and shares this
     * logger's mutable state (level, allowlist, redaction counter, sink), so a
     * correlation id injected at a run's entry point appears on every line of
     * that run without losing the shared configuration.
     */
    withCorrelation(correlationId: string): StructuredLogger;
}
/** Creates a structured logger. The `writeLine`/`now` seams keep tests off real I/O. */
declare function createLogger(options: CreateLoggerOptions): StructuredLogger;

/** Resolved logging configuration for a runtime. */
interface LoggingConfig {
    level: LogLevel;
    allowlist: RedactionAllowlist;
    runtime: string;
}
/**
 * Builds a logging config. The level threshold comes from `PAQAD_LOG_LEVEL`
 * (default `'info'`, invalid values ignored), then any explicit overrides win.
 */
declare function loadLoggingConfig(overrides?: Partial<LoggingConfig>): LoggingConfig;
/**
 * Applies a new config to an existing logger instance in place. The instance is
 * not replaced, so concurrent holders keep logging without dropping or
 * duplicating any line across the reload (AC4 — hot reload without loss).
 */
declare function reloadLoggingConfig(logger: StructuredLogger, config: LoggingConfig): void;
/** Lazy singleton logger for the engine runtime. */
declare function getEngineLogger(): StructuredLogger;

/** Literal token substituted for any allowlisted sensitive field value. */
declare const REDACTION_PLACEHOLDER = "[REDACTED]";
/**
 * Canonical, engine-authoritative list of sensitive field names. All three
 * runtimes import this rather than defining their own copy.
 */
declare const DEFAULT_REDACTION_ALLOWLIST: RedactionAllowlist;
/**
 * Returns a copy of `fields` with the value of any key that matches the
 * allowlist replaced by {@link REDACTION_PLACEHOLDER}. Redaction is applied at
 * the top level and one level deep inside plain nested objects. `count` is the
 * number of values replaced, so callers can drive an operational counter.
 */
declare function redactFields(fields: Record<string, unknown>, allowlist: RedactionAllowlist): {
    redacted: Record<string, unknown>;
    count: number;
};

/** Context handed to every migrator: the project and the version transition. */
interface SchemaMigrationContext {
    projectRoot: string;
    /** The project's current marker version (the version we migrate FROM). */
    fromVersion: string;
    /** The running engine's version (the version we migrate TO). */
    toVersion: string;
    /** The engine release performing the migration (for logging). */
    engineVersion: string;
}
/**
 * One forward migrator for a single `.paqad/` artifact or capability record.
 * Migrators MUST be idempotent: `checkAndMigrateSchema` re-checks under the lock,
 * and a migrator may legitimately see an already-partly-migrated tree on a retry.
 */
interface SchemaMigrator {
    /** Stable id (capability id or artifact name) — used for the migration log. */
    id: string;
    /**
     * Whether this migrator must run for a project moving `fromVersion -> toVersion`.
     * Keep it narrow (own only the transitions you actually change shape across) so
     * an unrelated marker bump never runs every migrator.
     */
    appliesTo(fromVersion: string, toVersion: string): boolean;
    /**
     * Idempotently migrate this artifact's on-disk rows forward. Returns a short
     * human note recorded alongside the migration record, or nothing.
     */
    migrate(context: SchemaMigrationContext): Promise<string | void>;
}

/**
 * The authoritative cross-artifact version stamp, written to
 * `PATHS.SCHEMA_MARKER` (`.paqad/schema-version.json`). Every consumer reads
 * this one file to learn whether the `.paqad/` layout is compatible with the
 * engine it is running.
 */
interface PaqadSchemaMarker {
    /** Semver of the `.paqad/` layout (see `PAQAD_SCHEMA_VERSION`). */
    paqad_schema_version: string;
    /** ISO-8601 timestamp of when this marker was last written. */
    written_at: string;
    /** The engine release version that last wrote the marker. */
    written_by_engine_version: string;
}
/**
 * One appended line in `PATHS.SCHEMA_MIGRATION_LOG`
 * (`.paqad/schema-migrations.jsonl`), recording a single forward migration.
 * `from_version` is `null` when a legacy/corrupt marker was reset to the
 * current baseline rather than migrated from a known earlier version.
 */
interface SchemaMigrationRecord {
    from_version: string | null;
    to_version: string;
    /** ISO-8601 timestamp of when the migration ran. */
    migrated_at: string;
    /** The engine release version that performed the migration. */
    engine_version: string;
    /** The `.paqad/`-relative path of the file that was migrated. */
    file: string;
    /**
     * One note per per-artifact migrator that ran during this migration (buildout
     * F1). Absent when no migrator applied to the transition — so a baseline
     * marker-only bump records exactly as it did before this field existed.
     */
    notes?: string[];
}
/** Outcome of comparing a marker's version against the running engine. */
type SchemaCompatibility = 'compatible' | 'needs-migration' | 'future';

declare function schemaMarkerPath(projectRoot: string): string;
declare function schemaMigrationLogPath(projectRoot: string): string;
/** Atomically writes the schema marker, creating `.paqad/` if absent. */
declare function writeSchemaMarker(projectRoot: string, engineVersion: string): Promise<PaqadSchemaMarker>;
/**
 * Synchronous sibling of `writeSchemaMarker`, for synchronous callers such as
 * `bootstrapFramework`. Same atomic temp-then-rename semantics.
 */
declare function writeSchemaMarkerSync(projectRoot: string, engineVersion: string): PaqadSchemaMarker;
/**
 * Reads and parses the marker. Returns `null` when the marker is absent (a
 * legacy project) or unreadable/corrupt — callers decide how to treat each via
 * the dedicated `checkAndMigrateSchema` flow, which distinguishes the two.
 */
declare function readSchemaMarker(projectRoot: string): Promise<PaqadSchemaMarker | null>;
/** Synchronous sibling of `readSchemaMarker`. */
declare function readSchemaMarkerSync(projectRoot: string): PaqadSchemaMarker | null;
/**
 * Stamps the schema marker only when a valid one is not already present, leaving
 * an existing marker (and its `written_at`) untouched. Used by `bootstrapFramework`
 * so repeated bootstraps/onboards are idempotent — re-stamping the layout that is
 * already current would otherwise churn the timestamp on every run. Reconciling a
 * marker for an *older* or *future* layout is the job of `checkAndMigrateSchema`.
 */
declare function ensureSchemaMarkerSync(projectRoot: string, engineVersion: string): PaqadSchemaMarker;
/**
 * Classifies a marker against the running engine's `PAQAD_SCHEMA_VERSION`:
 * equal → `compatible`, older → `needs-migration`, newer → `future`.
 */
declare function checkSchemaCompatibility(marker: PaqadSchemaMarker): SchemaCompatibility;
/** Appends one migration record as a newline-terminated JSON line. */
declare function appendMigrationRecord(projectRoot: string, record: SchemaMigrationRecord): Promise<void>;
/**
 * Runs `fn` while holding an exclusive migration lock for `projectRoot`. The
 * spin-wait yields the event loop between attempts so an in-process holder can
 * make progress; after `STALE_LOCK_TIMEOUT_MS` the lock is treated as stale and
 * stolen (consistent with the decision-store pattern).
 */
declare function withSchemaMigrationLock<T>(projectRoot: string, fn: () => Promise<T>): Promise<T>;
/**
 * The entry point callers run at the start of any engine run. Reads the marker
 * and reconciles it with the running engine:
 *
 *   - absent marker (legacy project) → stamp at the current version, no record.
 *   - corrupt/unparseable marker → overwrite at the current version and append a
 *     record with `from_version: null` (under the lock).
 *   - `future` → throw `SchemaVersionError` naming both versions; nothing mutated.
 *   - `needs-migration` → under the lock, re-check, migrate forward, append a
 *     record, and write the updated marker. The re-check makes concurrent runs
 *     converge to exactly one record.
 *   - `compatible` → no-op.
 *
 * Returns the marker the project is left with (`null` only for the `future`
 * branch, which throws before returning).
 */
declare function checkAndMigrateSchema(projectRoot: string, engineVersion: string, options?: {
    migrators?: readonly SchemaMigrator[];
}): Promise<PaqadSchemaMarker>;

declare const ACTIVE_CAPABILITY_ORDER: ActiveCapability[];
declare const MANAGEABLE_ACTIVE_CAPABILITIES: ActiveCapability[];
declare function listAvailableActiveCapabilities(): ActiveCapability[];
declare function isActiveCapability(value: string): value is ActiveCapability;
declare function isManageableActiveCapability(value: string): value is ActiveCapability;
declare function assertActiveCapability(value: string): ActiveCapability;
declare function normalizeActiveCapabilities(capabilities: Iterable<ActiveCapability>): ActiveCapability[];
declare function addActiveCapability(profile: ProjectProfile, capability: ActiveCapability): ProjectProfile;
declare function removeActiveCapability(profile: ProjectProfile, capability: ActiveCapability): ProjectProfile;

interface DesignTokenLeaf {
    $value: unknown;
    $type: string;
    $description?: string;
}
interface DesignTokenGroup {
    [key: string]: DesignTokenNode;
}
type DesignTokenNode = DesignTokenLeaf | DesignTokenGroup;
type DesignTokensDocument = DesignTokenGroup;
interface DesignTokenDocArtifact {
    path: string;
    content: string;
}
interface ThemeExportArtifact {
    path: string;
    content: string;
}

declare const DOC_TYPES: readonly ["stories", "spec", "user-flow", "schema", "query", "index", "registry", "ui", "api", "integration", "error-catalog", "glossary", "decision-record", "review-report", "sequence-plan"];
type DocType = (typeof DOC_TYPES)[number];
interface DocPath {
    type: DocType;
    path: string;
}
interface ApiEndpointDoc {
    method: string;
    route: string;
    auth: 'required' | 'public';
    permissions: string[];
    rate_limit?: string;
    description: string;
    request_schema_ref: string;
    response_schema_ref: string;
    error_codes_ref: string;
    added_in: string;
    last_updated: string;
}
interface ApiSchemaField {
    name: string;
    type: string;
    required: boolean;
    validation?: string;
    description: string;
}
interface IntegrationEventPayloadField {
    name: string;
    type: string;
    description: string;
}
interface IntegrationEvent {
    event_class: string;
    published_by: string;
    payload_fields: IntegrationEventPayloadField[];
    subscribers: string[];
    async: boolean;
    added_in: string;
}
interface IntegrationContract {
    type: 'event' | 'service-call' | 'shared-model' | 'job';
    interface_desc: string;
    contract_version: string;
    breaking_change_policy: string;
    fallback: string;
}
interface ErrorCatalogEntry {
    code: string;
    http_status?: number;
    user_message: string;
    internal_message: string;
    trigger: string;
    recovery_path: string;
    retry_safe: boolean;
    logged: boolean;
    alerted: boolean;
    added_in: string;
    last_updated: string;
}
interface IntegrationDoc {
    name: string;
    depends_on: string[];
    provides_to: string[];
}

type DocumentScope = 'ui' | 'api' | 'database' | 'architecture' | 'full';
type DocProgressState = 'not_started' | 'generating' | 'done' | 'failed';
interface DocProgressEntry {
    output_path: string;
    state: DocProgressState;
    started_at: string | null;
    completed_at: string | null;
    source_files: string[];
    source_hash: string | null;
    tokens_used: number | null;
    error: string | null;
    design_tokens?: {
        extraction_state: DocProgressState;
        total_tokens_found: number;
        placeholder_count: number;
        populated_count: number;
        placeholder_keys: string[];
    };
}
type ModuleDocStage = 'pending_map_review' | 'complete';
interface DocProgressFile {
    schema_version: '1';
    generated_by: 'paqad-ai';
    framework_version: string;
    modules: Record<string, Record<string, DocProgressEntry>>;
    global: Record<string, Record<string, DocProgressEntry>>;
    moduleDocStage?: ModuleDocStage;
}

declare const HOOK_TRIGGERS: readonly ["user-prompt-submit", "pre-tool-use", "post-tool-use", "stop", "subagent-stop", "pre-compact"];
type HookTrigger = (typeof HOOK_TRIGGERS)[number];
type ExitCode = 0 | 1 | 2;
interface HookDefinition {
    name: string;
    trigger: HookTrigger;
    command: string;
    blocking: boolean;
}
interface HookResult {
    hook: string;
    trigger: HookTrigger;
    exit_code: ExitCode;
    message?: string;
}

declare const MCP_SERVER_TYPES: readonly ["laravel-boost", "dart-mcp", "database-inspector", "figma", "vite-inspector", "react-router-mcp", "vue-router-mcp", "tailwind-mcp"];
type McpServerType = (typeof MCP_SERVER_TYPES)[number];
interface McpServerConfig {
    name: McpServerType | string;
    enabled: boolean;
    config: Record<string, unknown>;
}
interface McpServerDefinition {
    name: McpServerType;
    stacks: string[];
    capabilities: string[];
    provides: string[];
    replaces: string[];
}
interface McpConfigOutput {
    path: string;
    content: string;
}
type DataSourceType = 'mcp' | 'script' | 'cached-skill' | 'llm-read';
interface DataSource {
    type: DataSourceType;
    server?: string;
    script?: string;
    reason?: string;
    estimated_token_savings?: number;
}

interface OnboardingManifest {
    /**
     * Optional. No longer written into newly generated manifests: it is the one
     * field that churned the tracked manifest on every version bump, and its only
     * reader (graph extraction) null-guards a soft advisory. Kept in the type for
     * back-compat reading of manifests written before it was dropped.
     */
    framework_version?: string;
    adapter: AdapterType;
    project_root: string;
    profile: ProjectProfile;
    detected: DetectionReport | null;
    repository?: RepositoryContext;
    generated_at: string;
    generated_artifacts: Array<{
        path: string;
        auto_update: boolean;
        executable?: boolean;
    }>;
    planning_artifacts?: {
        compiled_rules_path: string;
        module_health_initialized: string[];
        classifier_config_path?: string;
    };
}
interface OnboardingOutput {
    adapter: AdapterType;
    decision_pause_supported_adapters: AdapterType[];
    generated_files: string[];
    detected_modules: string[];
    runtime_root: string;
    manifest_path: string;
    warnings: string[];
    /**
     * The no-migration safety net: framework knobs a legacy fat `project-profile.yaml`
     * carried at a non-default value that the hard-cutover strip reverted to the code
     * default (as `key=value` strings). Empty for a clean onboard. The CLI prints
     * these prominently so a revert is never silent.
     */
    reverted_framework_values: string[];
}
/**
 * One planned file in an onboarding preview.
 *
 * - `create` — the target does not exist and onboarding would write it.
 * - `overwrite` — the target exists, is auto-updatable, and its on-disk bytes differ
 *   from what onboarding would write. `mtimeMs` carries the existing file's last-changed
 *   time so the consumer can show "this will be replaced" without re-scanning disk.
 * - `skip` — onboarding would not change the file: either it already matches byte-for-byte,
 *   or it exists and is not auto-updatable (project-owned). `mtimeMs` is populated when the
 *   target exists.
 *
 * `templateError` annotates an entry whose on-disk state could not be classified (e.g. a
 * nested path that is unreadable); the preview records the reason and continues rather than
 * failing the whole tree.
 */
interface OnboardingFileTreeEntry {
    path: string;
    action: 'create' | 'overwrite' | 'skip';
    mtimeMs?: number;
    templateError?: string;
}
/**
 * Result of {@link OnboardingOrchestrator.preview} — a read-only description of every file
 * onboarding would create or change, computed without writing anything to disk.
 *
 * Determinism invariant: two calls with identical arguments and no disk change between them
 * return entry lists that are identical path-for-path and action-for-action. This holds only
 * if the generated content itself is deterministic, so onboarding templates must not embed
 * time- or randomness-dependent output.
 */
interface OnboardingPreviewResult {
    entries: OnboardingFileTreeEntry[];
    warnings: string[];
}

type PackInstallSource = 'built-in' | 'global' | 'project';
interface StackPackTraitManifest {
    name: string;
    display_name: string;
    detect_package?: string;
    detect_file?: string;
    detect_directory?: string;
    description: string;
}
interface StackPackFieldRule {
    name: string;
    presence?: 'required' | 'absent';
    value?: unknown;
}
interface StackPackDetectionRule {
    file?: string;
    packages?: string[];
    patterns?: string[];
    directory?: string;
    content_match?: string;
    fields?: StackPackFieldRule[];
    field_absent?: string[];
}
interface StackPackToolchainManifest {
    ecosystem: string;
    package_managers: string[];
    lockfiles: string[];
    audit_command?: string;
}
interface StackPackMcpDefault {
    name: string;
    when: 'always' | 'when_trait';
    trait?: string;
}
interface StackPackPentestCheckMap {
    glob: string;
    checks: string[];
}
interface StackPackAuditCommand {
    command: string;
    parser: string;
}
interface StackPackAstManifest {
    language: string;
    tree_sitter_grammar: string;
    file_extensions: string[];
}
interface StackPackTestingFramework {
    name: string;
    detect_package?: string;
    detect_file?: string;
    run_command?: string;
}
declare const STRUCTURED_TEST_FORMATS: readonly ["jest-json", "junit-xml", "pytest-json", "go-json", "rspec-json", "tap", "none"];
type StructuredTestFormat = (typeof STRUCTURED_TEST_FORMATS)[number];
declare const TEST_RUNNER_OUTPUT_SOURCES: readonly ["stdout", "file"];
type TestRunnerOutputSource = (typeof TEST_RUNNER_OUTPUT_SOURCES)[number];
/** How a runner parallelizes (issue #554). `native` already runs in parallel; `flag` needs the
 *  `parallel.flag` added to the command; `unavailable` has no parallel mode paqad can drive. */
declare const TEST_RUNNER_PARALLEL_MODES: readonly ["native", "flag", "unavailable"];
type TestRunnerParallelMode = (typeof TEST_RUNNER_PARALLEL_MODES)[number];
/** What replaces `<pattern>` in `commands.test_single` for the isolated re-run (issue #554). */
declare const SINGLE_TEST_SELECTORS: readonly ["test_id", "file"];
type SingleTestSelector = (typeof SINGLE_TEST_SELECTORS)[number];
/** A runner's parallel capability (issue #554, Part B.1). */
interface StackPackTestRunnerParallel {
    mode: TestRunnerParallelMode;
    /** The flag inserted after the runner invocation; required when `mode = flag`; carries
     *  `<processes>` exactly once. */
    flag?: string;
    /** An ecosystem package the parallel mode needs, looked up in the lockfile (e.g. paratest). */
    requires_package?: string;
    /** Human sentence shown when `mode = unavailable`. */
    reason?: string;
}
interface StackPackTestRunner {
    runner_id: string;
    structured_format: StructuredTestFormat;
    structured_flags?: string;
    default_command?: string;
    output_source?: TestRunnerOutputSource;
    output_path_pattern?: string;
    parallel?: StackPackTestRunnerParallel;
    /** Default `test_id`; what replaces `<pattern>` in `commands.test_single` (issue #554). */
    single_test_selector?: SingleTestSelector;
}
interface StackPackDocsManifest {
    overview_template?: string;
    conventions_template?: string;
}
interface StackPackRagManifest {
    exclude_directories?: string[];
    basename_includes?: string[];
}
interface StackPackModuleHealthManifest {
    source_roots: string[];
    source_globs?: string[];
    public_api_extractor?: string | null;
    test_command?: string;
    coverage_format?: string;
    coverage_path?: string;
    test_report_format?: string;
    test_report_path?: string;
    git_window_days?: number;
}
interface StackPackManifest {
    name: string;
    display_name: string;
    ecosystem: string;
    version: string;
    description: string;
    maintainer: string;
    tier?: 'framework' | 'archetype';
    detection: {
        manifests?: StackPackDetectionRule[];
        lockfiles?: StackPackDetectionRule[];
        heuristics?: StackPackDetectionRule[];
        priority?: number;
        excludes?: string[];
    };
    traits?: StackPackTraitManifest[];
    toolchains?: StackPackToolchainManifest[];
    mcp_defaults?: StackPackMcpDefault[];
    pentest?: {
        file_check_map?: StackPackPentestCheckMap[];
        audit_commands?: StackPackAuditCommand[];
    };
    ast?: StackPackAstManifest;
    testing?: {
        frameworks?: StackPackTestingFramework[];
    };
    test_runners?: StackPackTestRunner[];
    docs?: StackPackDocsManifest;
    rag?: StackPackRagManifest;
    module_health?: StackPackModuleHealthManifest;
    visual_evidence?: {
        frontend_globs?: string[];
    };
}
/**
 * OSCAL Control-Mapping set-theory relations
 * (https://pages.nist.gov/OSCAL/learn/concepts/layer/control/mapping/). A gate
 * is almost always a `subset-of` or `intersects-with` a legal clause — rarely
 * `equivalent-to`. Using the honest relation is the whole point: a mis-mapped
 * `equivalent-to` manufactures false assurance.
 */
declare const COMPLIANCE_RELATIONS: readonly ["equivalent-to", "equal-to", "subset-of", "superset-of", "intersects-with", "no-relationship"];
type ComplianceRelation = (typeof COMPLIANCE_RELATIONS)[number];
/** How strongly a clause's evidence is established. Never `full` — paqad does
 *  not perform conformity assessment, so a clause is at most `substantial`. */
declare const COMPLIANCE_EVIDENCE_STRENGTHS: readonly ["partial", "substantial"];
type ComplianceEvidenceStrength = (typeof COMPLIANCE_EVIDENCE_STRENGTHS)[number];
/** What a clause is satisfied *by*: a verification gate or an obligation
 *  category. `gate` is the primary, deterministic join key. */
type ComplianceSignalType = 'gate' | 'obligation_category';
interface ComplianceClause {
    id: string;
    title: string;
    url?: string;
}
interface ComplianceSignal {
    type: ComplianceSignalType;
    /** A `VERIFICATION_GATES` name (when `type: gate`) or an obligation category. */
    ref: string;
    relation: ComplianceRelation;
}
interface ComplianceMapping {
    clause: ComplianceClause;
    satisfied_by: ComplianceSignal[];
    evidence_strength: ComplianceEvidenceStrength;
    /** Provenance of the human/process that authored this opinion edge. */
    reviewed_by?: string;
}
interface ComplianceFramework {
    id: string;
    title: string;
    authority_url?: string;
    /** Standards amend live; pin the version so stale citations are detectable. */
    version?: string;
}
interface CompliancePackManifest {
    /** Discriminator selecting the `compliance-pack` schema. */
    kind: 'compliance-pack';
    name: string;
    description?: string;
    maintainer?: string;
    framework: ComplianceFramework;
    /** Verbatim, surfaced on every citation: evidence toward, not compliance. */
    disclaimer: string;
    mappings: ComplianceMapping[];
}
interface LoadedCompliancePack {
    manifest: CompliancePackManifest;
    root: string;
    manifestPath: string;
    source: PackInstallSource;
    validation: PackValidationResult;
}
interface CompliancePackRegistry {
    packs: Map<string, LoadedCompliancePack>;
    warnings: PackValidationIssue[];
}
interface PackValidationIssue {
    level: 'error' | 'warning';
    path: string;
    message: string;
}
interface PackValidationResult {
    valid: boolean;
    issues: PackValidationIssue[];
}
interface LoadedStackPack {
    manifest: StackPackManifest;
    root: string;
    manifestPath: string;
    source: PackInstallSource;
    validation: PackValidationResult;
}
interface PackRegistry {
    packs: Map<string, LoadedStackPack>;
    warnings: PackValidationIssue[];
}

declare const TOKEN_ARTIFACT_CLASSES: readonly ["test-output", "coverage-output", "json-report", "xml-report", "log-output", "grep-results", "route-dump", "inventory-scan-output"];
type TokenArtifactClass = (typeof TOKEN_ARTIFACT_CLASSES)[number];
declare const ESCALATION_REASONS: readonly ["structured-parse-failed-or-degraded", "summary-confidence-low", "compact-signals-contradict", "diagnosis-unresolved-after-compact-pass"];
type EscalationReason = (typeof ESCALATION_REASONS)[number];
interface TokenEfficiencyMetadata {
    original_size: number;
    compact_size: number;
    reduction_ratio: number;
    delta_mode_used: boolean;
    escalation_occurred: boolean;
}
interface CompactArtifactSummary {
    summary_counts: Record<string, number>;
    top_failures_or_errors: string[];
    affected_files: string[];
    severity_or_status: string;
    next_recommended_actions: string[];
}
interface CompactArtifactResult {
    artifact_class: TokenArtifactClass;
    summary: CompactArtifactSummary;
    targeted_excerpts: string[];
    confidence: number;
    raw_artifact_path: string | null;
    metadata: TokenEfficiencyMetadata;
}
interface BuildCompactArtifactInput {
    artifact_class: TokenArtifactClass;
    raw_content: string;
    raw_artifact_path?: string;
    max_excerpts?: number;
}
interface EscalationDecision {
    should_escalate: boolean;
    reason: EscalationReason | null;
    raw_slice: string | null;
    metadata: TokenEfficiencyMetadata;
}
interface EvaluateEscalationInput {
    compact: CompactArtifactResult;
    reason?: EscalationReason;
    unresolved_after_compact?: boolean;
    contradiction_detected?: boolean;
    confidence_threshold?: number;
    max_raw_slice_chars?: number;
    slice_hint?: string;
}
interface ReasoningInputPayload {
    compact_summary: CompactArtifactSummary;
    targeted_excerpts: string[];
    raw_slice: string | null;
    escalation_reason: EscalationReason | null;
    metadata: TokenEfficiencyMetadata;
}
interface DeltaReasoningPayload<TDelta> {
    delta: TDelta;
    payload: ReasoningInputPayload;
}
interface TestIssueSnapshot {
    test_id: string;
    message: string;
    status: 'passed' | 'failed' | 'errored';
}
interface TestDelta {
    newly_failing_tests: string[];
    newly_passing_tests: string[];
    newly_errored_tests: string[];
    changed_failure_messages: Array<{
        test_id: string;
        before: string;
        after: string;
    }>;
}
interface VerificationGateSnapshot {
    gate: string;
    passed: boolean;
    detail: string;
    remediation?: string;
}
interface VerificationDelta {
    changed_gate_outcomes: Array<{
        gate: string;
        before_passed: boolean;
        after_passed: boolean;
    }>;
    changed_evidence: Array<{
        gate: string;
        before_detail: string;
        after_detail: string;
    }>;
    changed_recommended_actions: Array<{
        gate: string;
        before: string;
        after: string;
    }>;
}
interface DriftFileSnapshot {
    file: string;
    status: string;
    conclusion: string;
}
interface DriftDelta {
    changed_files: string[];
    changed_statuses: Array<{
        file: string;
        before: string;
        after: string;
    }>;
    changed_conclusions: Array<{
        file: string;
        before: string;
        after: string;
    }>;
}
declare const DISCLOSURE_LEVELS: readonly ["summary", "compact", "excerpt", "raw"];
type DisclosureLevel = (typeof DISCLOSURE_LEVELS)[number];
declare const DISCLOSURE_ESCALATION_REASONS: readonly ["ambiguity-unresolved", "previous-layer-insufficient", "high-risk-or-cross-cutting"];
type DisclosureEscalationReason = (typeof DISCLOSURE_ESCALATION_REASONS)[number];
interface DisclosurePolicyInput {
    compact: CompactArtifactResult;
    escalation?: EscalationDecision;
    requested_level?: DisclosureLevel;
    escalation_reason?: DisclosureEscalationReason;
}
interface DisclosureAuditRecord {
    selected_level: DisclosureLevel;
    escalation_occurred: boolean;
    escalation_reason: DisclosureEscalationReason | null;
    skipped_intermediate: boolean;
}
interface DisclosurePolicyResult {
    level: DisclosureLevel;
    payload: string;
    escalation_reason: DisclosureEscalationReason | null;
    skipped_intermediate: boolean;
    audit: DisclosureAuditRecord;
}
declare const TASK_COMPLEXITIES: readonly ["trivial", "single-file", "single-module", "cross-cutting"];
type TaskComplexity = (typeof TASK_COMPLEXITIES)[number];
declare const RETRIEVAL_PATHS: readonly ["direct", "lexical", "rag-shallow", "rag-deep"];
type RetrievalPath = (typeof RETRIEVAL_PATHS)[number];
declare const RETRIEVAL_ESCALATION_SIGNALS: readonly ["insufficient-chunks", "conflicting-evidence", "unresolved-target-file-ambiguity"];
type RetrievalEscalationSignal = (typeof RETRIEVAL_ESCALATION_SIGNALS)[number];
interface RetrievalGateInput {
    task_complexity: TaskComplexity;
    ambiguity_detected?: boolean;
    chunk_count?: number;
    min_chunk_threshold?: number;
    conflicting_evidence?: boolean;
}
interface RetrievalAuditRecord {
    retrieval_depth: RetrievalPath;
    rag_skipped: boolean;
    escalation_signal: RetrievalEscalationSignal | null;
}
interface RetrievalGateResult {
    preferred_path: RetrievalPath;
    rag_skipped: boolean;
    escalation_signal: RetrievalEscalationSignal | null;
    audit: RetrievalAuditRecord;
}
declare const ROUTING_MECHANISMS: readonly ["deterministic-rule", "metadata-lookup", "cheap-model", "reasoning-model"];
type RoutingMechanism = (typeof ROUTING_MECHANISMS)[number];
interface RoutingInput {
    task_type: string;
    target_scope?: string;
    metadata?: Record<string, unknown>;
}
interface RoutingAuditRecord {
    routing_mechanism: RoutingMechanism;
    resolved_before_reasoning: boolean;
}
interface RoutingResult {
    needs_reasoning: boolean;
    mechanism_used: RoutingMechanism;
    resolved_task_type: string | null;
    audit: RoutingAuditRecord;
}
interface ControlLayerAuditRecord {
    disclosure: DisclosureAuditRecord;
    retrieval: RetrievalAuditRecord;
    routing: RoutingAuditRecord;
}

declare const TEST_OUTPUT_SCHEMA_VERSION = "1.0.0";
declare const UNKNOWN_TEST_OUTPUT_TIMESTAMP = "1970-01-01T00:00:00.000Z";
declare const TEST_ISSUE_CATEGORIES: readonly ["assertion", "error", "timeout", "unknown"];
type TestIssueCategory = (typeof TEST_ISSUE_CATEGORIES)[number];
declare const TEST_PARSE_STRATEGIES: readonly ["structured", "plain-text-fallback", "degraded"];
type TestParseStrategy = (typeof TEST_PARSE_STRATEGIES)[number];
interface StructuredTestSummary {
    total: number;
    passed: number;
    failed: number;
    skipped: number;
    errored: number;
    duration_ms: number;
    timestamp: string;
    runner_id: string;
}
interface StructuredTestIssue {
    test_id: string;
    suite: string | null;
    message: string;
    stack_trace: string | null;
    file_path: string | null;
    line_number: number | null;
    category: TestIssueCategory;
    duration_ms: number | null;
}
interface StructuredTestWarning {
    type: string;
    message: string;
    source_test_id: string | null;
}
interface StructuredTestParseMetadata {
    raw_byte_size: number;
    structured_byte_size: number;
    compression_ratio: number;
    original_size: number;
    compact_size: number;
    reduction_ratio: number;
    delta_mode_used: boolean;
    escalation_occurred: boolean;
    escalation_reason: EscalationReason | null;
    delta_summary: {
        newly_failing_tests: number;
        newly_passing_tests: number;
        newly_errored_tests: number;
        changed_failure_messages: number;
    } | null;
    parse_strategy: TestParseStrategy;
    parse_warnings: string[];
}
interface StructuredTestResult {
    schema_version: typeof TEST_OUTPUT_SCHEMA_VERSION;
    summary: StructuredTestSummary;
    failures: StructuredTestIssue[];
    warnings: StructuredTestWarning[];
    parse_metadata: StructuredTestParseMetadata;
    errors: StructuredTestIssue[];
    evidence_scope?: {
        related_paths?: string[];
        related_modules?: string[];
    };
}

declare const MUTATION_CONFIDENCE_LEVELS: readonly ["mature", "lower"];
type MutationConfidence = (typeof MUTATION_CONFIDENCE_LEVELS)[number];
declare const MUTATION_GATE_STATUSES: readonly ["killed-all", "survivors", "lower-confidence", "skipped", "unsafe-tree"];
type MutationGateStatus = (typeof MUTATION_GATE_STATUSES)[number];
declare const MUTATION_SKIP_REASONS: readonly ["fast-lane", "no-changed-code", "tool-not-configured", "tests-not-green", "run-failed"];
type MutationSkipReason = (typeof MUTATION_SKIP_REASONS)[number];
interface SurvivingMutant {
    file: string;
    line: number;
    operator: string;
    description?: string;
}
interface MutationResult {
    tool: string | null;
    language: string | null;
    confidence: MutationConfidence;
    scoped_files: string[];
    total_mutants: number;
    killed: number;
    survived: number;
    equivalent_set_aside: number;
    kill_rate: number | null;
    surviving_mutants: SurvivingMutant[];
    tree_clean: boolean;
    status: MutationGateStatus;
    skipped_reason: MutationSkipReason | null;
}

declare const QUALITY_MEASURES: readonly ["tangledness", "dead_code", "risky_patterns", "strictness"];
type QualityMeasure = (typeof QUALITY_MEASURES)[number];
declare const MEASURE_CONFIDENCE_LEVELS: readonly ["mature", "lower"];
type MeasureConfidence = (typeof MEASURE_CONFIDENCE_LEVELS)[number];
type RatchetMeasureOutcome = 'new' | 'unchanged' | 'tightened' | 'regressed' | 'blocked';
interface RatchetMeasureVerdict {
    measure: QualityMeasure;
    module: string;
    baseline_value: number | null;
    current_value: number | null;
    outcome: RatchetMeasureOutcome;
    confidence: MeasureConfidence;
    /**
     * The exception "kind" key — a regression of the same kind reuses an earlier
     * approval via the Decision Pause Contract (issue #110: approve once, reuse by
     * kind). Keyed by measure so "loosening strictness" reuses across modules.
     */
    kind: string;
    detail: string;
}
type QualityRatchetStatus = 'pass' | 'regressed' | 'captured' | 'skipped';
interface QualityRatchetResult {
    status: QualityRatchetStatus;
    lane: Lane;
    /** Every measure+module evaluated this run. */
    verdicts: RatchetMeasureVerdict[];
    /** Regressions with no approved exception — these block. */
    blocking_regressions: RatchetMeasureVerdict[];
    /** Regressions permitted by a reused/approved exception — recorded, not blocking. */
    excepted_regressions: RatchetMeasureVerdict[];
    /** Measures whose recorded level improved (baseline tightened). */
    tightened: RatchetMeasureVerdict[];
    /** True iff a baseline was captured (first run) or extended with new measures. */
    captured_baseline: boolean;
    skipped_reason: string | null;
}

declare const VERIFICATION_GATES: readonly ["change-completeness", "requirement-completeness", "story-quality", "ac-test-mapping", "spec-review", "architecture-compliance", "code-tests-lint", "implementation-review", "behavioral-correctness", "mutation-testing", "quality-ratchet", "database-quality", "module-docs-structure", "instructions-docs-structure", "documentation-freshness", "site-map-freshness", "extension-surface", "duplication"];
type VerificationGate = (typeof VERIFICATION_GATES)[number];
interface GateResult {
    gate: VerificationGate;
    passed: boolean;
    inconclusive?: boolean;
    detail: string;
    remediation?: string;
}
interface ImplementationReviewFinding {
    kind: 'decision-violation' | 'undeclared-decision';
    severity: 'error' | 'warning';
    detail: string;
    decision_id?: string;
    file?: string;
}
type CanonicalDocOwnershipKind = 'direct-doc-edit' | 'implementation-drift';
interface CanonicalDocTarget {
    target_path: string;
    ownership_kind: CanonicalDocOwnershipKind;
    owners: string[];
    reason: string;
}
/**
 * Where a verification run was fired from. `provider-workflow` is the in-session
 * path driven by the host agent following the feature-development workflow.
 *
 * Issue #117 adds the binding, agent-independent origins: a `Stop`/completion
 * hook (`hook-completion`) and the git/CI backstop (`git-backstop`,
 * `ci-backstop`). These let a run that fires automatically — not at the agent's
 * discretion — be told apart from the skippable in-workflow path.
 */
type VerificationOrigin = 'provider-workflow' | 'paqad-cli' | 'hook-completion' | 'git-backstop' | 'ci-backstop' | 'unknown';
/**
 * The set of {@link VerificationOrigin}s fired automatically by a hook or the
 * git/CI backstop (issue #117), as opposed to the in-session provider workflow.
 * A run with one of these origins evaluated the gates against repository
 * reality, independent of whether the agent chose to run the workflow phase.
 */
declare const BACKSTOP_VERIFICATION_ORIGINS: readonly ["hook-completion", "git-backstop", "ci-backstop"];
declare function isBackstopVerificationOrigin(origin: VerificationOrigin | undefined): origin is (typeof BACKSTOP_VERIFICATION_ORIGINS)[number];
interface VerificationContext {
    project_root: string;
    verification_origin?: VerificationOrigin;
    verification_stage?: 'provider-completion' | 'backstop-completion' | 'other';
    modules: string[];
    changed_files: string[];
    changed_files_source: 'session-artifact' | 'git-status' | 'none';
    /**
     * Issue #117 (C-4) — the path prefixes a change is allowed to touch, derived
     * from the frozen spec boundary and the attributed modules
     * (`classification.affected_modules` / `module-map.yml`). When set and
     * non-empty, the `change-completeness` gate flags `changed_files` outside the
     * boundary as a blocking scope-drift finding. Left undefined on the in-session
     * provider path, where scope is governed live by the workflow.
     */
    spec_boundary?: string[];
    code_changed: boolean;
    test_files_changed: boolean;
    documentation_files_changed: boolean;
    stale_doc_targets: CanonicalDocTarget[];
    requirements_complete: boolean;
    story_quality_passed: boolean;
    ac_test_mapping_passed: boolean;
    /**
     * Issue #117 (C-2) — the computed, specific detail behind
     * `ac_test_mapping_passed` (e.g. "Acceptance criteria with no proving check:
     * AC-2"). When set, the `ac-test-mapping` gate surfaces it so the trust
     * verdict names the exact unmapped criterion instead of a generic message.
     */
    ac_test_mapping_detail?: string;
    spec_review_passed: boolean;
    architecture_compliant: boolean;
    code_tests_lint_passed: boolean;
    implementation_review_passed: boolean;
    implementation_review_findings?: ImplementationReviewFinding[];
    behavioral_correctness_passed: boolean;
    database_quality_passed: boolean;
    structured_test_results?: StructuredTestResult[];
    mutation_result?: MutationResult;
    mutation_strict?: boolean;
    quality_ratchet_result?: QualityRatchetResult;
    lane?: Lane;
    expected_ui_modules: string[];
    expected_api_modules: string[];
    expected_integration_modules: string[];
    expected_error_catalog_modules: string[];
    registry_refreshed_at: string | null;
    glossary_updated: boolean;
}

declare const REVIEW_TIERS: readonly ["full", "standard", "spot-check"];
type ReviewTier = (typeof REVIEW_TIERS)[number];
declare const REVIEW_MODES: readonly ["fresh", "diff"];
type ReviewMode = (typeof REVIEW_MODES)[number];
declare const REVIEW_DIMENSIONS: readonly ["completeness", "assumption-safety", "security", "data-integrity", "performance", "failure-modes", "reuse-architecture", "database-quality", "ux-ui-quality", "test-quality", "observability", "rollback-safety"];
type ReviewDimension = (typeof REVIEW_DIMENSIONS)[number];
declare const TIER_DIMENSIONS: Record<ReviewTier, readonly ReviewDimension[]>;
declare const FINDING_SEVERITIES: readonly ["critical", "high", "medium", "low"];
type FindingSeverity$1 = (typeof FINDING_SEVERITIES)[number];
interface ReviewFinding {
    id: string;
    dimension: ReviewDimension;
    severity: FindingSeverity$1;
    finding: string;
    impact: string;
    required_action: string;
}
interface ReviewReport {
    point: 'after-spec' | 'after-implementation';
    tier: ReviewTier;
    mode: ReviewMode;
    verdict: 'pass' | 'fail';
    summary: string;
    findings: ReviewFinding[];
    dimensions_passed_clean: ReviewDimension[];
    dimensions_deferred: ReviewDimension[];
}

declare const PIPELINE_PHASES: readonly ["request-classification", "docs-first-load", "analysis", "question-answering", "root-cause-analysis", "pentest", "pentest-retest", "sequence-planning", "specification", "user-flow", "spec-review", "implementation", "implementation-review", "verification-gates", "documentation-update", "module-documentation"];
type PipelinePhase = (typeof PIPELINE_PHASES)[number];
interface PhaseResult {
    phase: PipelinePhase;
    status: 'pass' | 'fail' | 'warning';
    summary: string;
    artifacts: string[];
}
interface CompletedStorySummary {
    id: string;
    title: string;
    verification_status: 'passed' | 'failed' | 'partial';
}
interface ChangeClosureSummary {
    code_changed: boolean;
    test_evidence_changed: boolean;
    canonical_docs_changed: boolean;
    blocked: boolean;
    primary_blocking_reason: string | null;
    summary: string;
}
interface HandoffArtifact {
    framework_version: string;
    workflow: ClassificationResult['workflow'];
    current_phase: PipelinePhase;
    current_story: {
        id: string;
        title: string;
    } | null;
    completed_stories: CompletedStorySummary[];
    key_decisions: string[];
    verification_results: GateResult[];
    changed_files: string[];
    context_hit_rate: number;
    warnings: string[];
    unresolved_items: string[];
    closure_summary: ChangeClosureSummary;
    references: {
        spec: string;
        flow: string;
        review_report: string;
    };
}
interface PipelineRunContext {
    project_root: string;
    lane: Lane;
    classification: ClassificationResult;
    started_at: string;
    phases: PhaseResult[];
    feature_policy: FeatureDevelopmentPolicy | null;
    policy_warnings: string[];
    verification_context?: VerificationContext;
    verification_baseline_results?: GateResult[];
    verification_results?: GateResult[];
    /**
     * Optional consumer cancellation signal (PQD-104). The lane runner checks it
     * at each phase boundary; phases may also read it to cancel cooperatively.
     */
    signal?: AbortSignal;
}
interface PipelineAnalysisRole {
    name: string;
}
interface PipelineResult {
    lane: Lane | null;
    phases: PhaseResult[];
    blocked_at: PipelinePhase | null;
    handoff_path: string;
    analysisRoles: PipelineAnalysisRole[];
    reviewTier: ReviewTier;
    reviewMode?: ReviewMode;
    route_reason?: string | null;
    closure_summary: ChangeClosureSummary;
    /**
     * True when a consumer cancelled the run via an `AbortSignal` (PQD-104). When
     * set, `blocked_at` holds the phase that was interrupted and
     * `closure_summary.blocked` is true. The run resolves (does not throw) so the
     * consumer can dispatch it through a typed result envelope.
     */
    cancelled?: true;
    /** Path to a resumable partial-state checkpoint, when the cancelled run wrote one. */
    cancelled_checkpoint?: string;
}

declare const PENTEST_WORKFLOWS: readonly ["pentest", "pentest-retest"];
type PentestWorkflowName = (typeof PENTEST_WORKFLOWS)[number];
declare const PENTEST_SEVERITIES: readonly ["high", "medium", "low"];
type PentestSeverity = (typeof PENTEST_SEVERITIES)[number];
declare const PENTEST_EFFORTS: readonly ["low", "medium", "high"];
type PentestEffort = (typeof PENTEST_EFFORTS)[number];
declare const PENTEST_RETEST_STATUSES: readonly ["fixed", "still-open", "needs-manual-verification"];
type PentestRetestStatus = (typeof PENTEST_RETEST_STATUSES)[number];
declare const PENTEST_FINDING_STATUSES: readonly ["open", "coverage-gap", "fixed", "still-open", "needs-manual-verification", "potentially-fixed"];
type PentestFindingStatus = (typeof PENTEST_FINDING_STATUSES)[number];
declare const PENTEST_SOURCE_TYPES: readonly ["docs", "tests", "code", "runtime", "advisory"];
type PentestSourceType = (typeof PENTEST_SOURCE_TYPES)[number];
declare const PENTEST_RUN_STEP_STATUSES: readonly ["not_started", "running", "completed", "blocked", "failed"];
type PentestRunStepStatus = (typeof PENTEST_RUN_STEP_STATUSES)[number];
declare const PENTEST_RUN_STATUSES: readonly ["running", "completed", "blocked", "failed"];
type PentestRunStatus = (typeof PENTEST_RUN_STATUSES)[number];
interface PentestFinding {
    id: string;
    title: string;
    description: string;
    impact: PentestSeverity;
    effort: PentestEffort;
    possible_solution_direction: string;
    how_to_reproduce: string[];
    impact_area: string[];
    evidence: string[];
    category: string;
    status: PentestFindingStatus;
    confidence: number;
    source_types: PentestSourceType[];
    affected_modules: string[];
    affected_packages: string[];
    runtime_required: boolean;
    manual_follow_up: boolean;
}
interface PentestRetestFinding extends PentestFinding {
    retest_status: PentestRetestStatus;
}
interface PentestCoverageSummary {
    docs: boolean;
    tests: boolean;
    code: boolean;
    runtime: boolean;
    database: boolean;
    blocked_checks: string[];
}
interface PentestRuntimeStatus {
    target_url: string | null;
    status: 'reachable' | 'unreachable' | 'not-configured' | 'blocked';
    detail: string;
}
interface PentestReportIndex {
    schema_version: '1';
    generated_by: 'paqad-ai';
    framework_version: string;
    report_id: string;
    workflow: PentestWorkflowName;
    generated_at: string;
    report_path: string;
    sidecar_path: string;
    source_report_path: string | null;
    source_report_id: string | null;
    stack: {
        primary: string;
        traits: string[];
        toolchains: string[];
    };
    runtime: PentestRuntimeStatus;
    coverage: PentestCoverageSummary;
    findings: Array<PentestFinding | PentestRetestFinding>;
    blocked_checks: string[];
    sources_used: string[];
    methodology: string[];
    next_remediation_priorities: string[];
    raw_evidence_paths: string[];
}
interface PentestRunStep {
    id: string;
    title: string;
    status: PentestRunStepStatus;
    input_hash: string | null;
    artifact_paths: string[];
    skill_names: string[];
    error: string | null;
    started_at: string | null;
    completed_at: string | null;
}
interface PentestRunProgress {
    schema_version: '1';
    generated_by: 'paqad-ai';
    framework_version: string;
    run_id: string;
    workflow: PentestWorkflowName;
    status: PentestRunStatus;
    started_at: string;
    updated_at: string;
    report_path: string | null;
    sidecar_path: string | null;
    target_url: string | null;
    source_report_path: string | null;
    steps: PentestRunStep[];
    skill_invocations: string[];
    script_artifacts: string[];
    current_finding_ids: string[];
    incremental_type?: 'full' | 'incremental';
}

interface PostClassificationAdjustments {
    complexity: Complexity;
    risk: Risk;
    lane_before_override: string;
    lane_override_reason: string | null;
    risk_floor: Risk | null;
    risk_floor_reason: string | null;
    complexity_adjustment: number;
    complexity_adjustment_reason: string | null;
    resolution_updates: Record<string, string>;
    high_override_rate: boolean;
}

interface AffectedModule {
    path: string;
    source: 'explicit-path' | 'symbol-index' | 'rag' | 'stack-heuristic' | 'mcp' | 'import-graph';
    confidence: number;
}
interface ClassificationHint<TValue> {
    value: TValue;
    source: string;
    confidence: number;
    reason?: string;
}
interface PreClassificationResolved {
    workflow?: ClassificationWorkflow | null;
    scope?: ClassificationScope;
    affected_modules?: string[];
    database_impact?: DatabaseImpact;
    api_impact?: ApiImpact;
    ui_impact?: UiImpact;
    compliance_sensitivity?: ComplianceSensitivity;
    customer_facing_impact?: CustomerFacingImpact;
    reversibility?: Reversibility;
    data_sensitivity?: DataSensitivity;
    delta_candidate?: boolean;
    base_manifest_slug?: string | null;
    prior_requirement_count?: number | null;
    prior_criterion_count?: number | null;
    context_budget_hint?: ContextBudgetHint;
    affected_modules_source?: string;
    scope_graph_depth?: number;
    matched_rule_triggers?: string[];
    decision_category?: DecisionCategory;
}
interface PreClassificationResult {
    resolved: PreClassificationResolved;
    hints: Partial<Record<keyof PreClassificationResolved, ClassificationHint<unknown>>>;
    unresolved: string[];
    resolution_map: ResolutionMap;
    evidence: string[];
    detected_forks?: Array<{
        category: DecisionCategory;
        confidence: number;
        signal: string;
        matched_text: string;
    }>;
}

/**
 * Stability vocabulary for the engine extension surface contract (PQD-92).
 *
 * The extension-surface document (`docs/extension-surface.md`) enumerates every
 * engine API a downstream consumer (desktop, API layer, marketplace, coding-agent
 * adapters) depends on. Each entry carries a {@link StabilityLevel} so a breaking
 * change can be caught at design time rather than at integration. These types are
 * passive — exporting them lets future consumer-side tooling share the vocabulary.
 */
/** Stability guarantee grades, strongest to weakest. */
declare const STABILITY_LEVELS: readonly ["stable", "beta", "alpha", "internal"];
/**
 * The guarantee attached to a surface entry:
 * - `stable`   — covered by semver; removals/renames are breaking changes.
 * - `beta`     — usable, but may change in a minor release with notice.
 * - `alpha`    — experimental; may change or vanish without notice.
 * - `internal` — not part of the surface; consumers must not depend on it.
 */
type StabilityLevel = (typeof STABILITY_LEVELS)[number];
/**
 * One row of the extension surface contract: a single engine API as consumed by
 * one consumer, with enough metadata to detect drift.
 */
interface SurfaceEntry {
    /** The consumer that depends on this API (e.g. `desktop`, `claude-code`, `cli`). */
    consumer: string;
    /** The engine module path that owns the symbol (e.g. `src/adapters/adapter.interface.ts`). */
    engineModule: string;
    /** The exported symbol and its TypeScript signature. */
    functionSignature: string;
    /** The stability guarantee for this entry. */
    stabilityLevel: StabilityLevel;
    /** The semver in which the entry was introduced (e.g. `1.0.0`). */
    since: string;
    /**
     * When set, exempts the entry from the static orphan/drift checks with a
     * recorded reason — for call sites static analysis cannot reach (dynamically
     * constructed names, conditional imports, external consumers not in-tree).
     */
    exempt?: string;
}

interface TemplateDefinition {
    name: string;
    source: string;
    destination: string;
    partials?: string[];
}
type TemplateContext = Record<string, unknown>;

declare const VERIFICATION_EVIDENCE_SCHEMA_VERSION = "1.1.0";
declare const EVIDENCE_GATE_STATUSES: readonly ["pass", "fail", "inconclusive", "skipped"];
type EvidenceGateStatus = (typeof EVIDENCE_GATE_STATUSES)[number];
declare const EVIDENCE_OVERALL_STATUSES: readonly ["pass", "fail", "error"];
type EvidenceOverallStatus = (typeof EVIDENCE_OVERALL_STATUSES)[number];
declare const EVIDENCE_FAILURE_CATEGORIES: readonly ["test-failure", "test-error", "test-timeout", "gate-failure"];
type EvidenceFailureCategory = (typeof EVIDENCE_FAILURE_CATEGORIES)[number];
interface VerificationEvidenceFailure {
    category: EvidenceFailureCategory;
    file: string | null;
    line: number | null;
    test_id: string | null;
    suite: string | null;
    ac_id: string | null;
    message: string;
    stderr_excerpt: string | null;
}
interface VerificationEvidenceGate {
    name: VerificationGate;
    status: EvidenceGateStatus;
    detail: string;
    remediation: string | null;
    failures: VerificationEvidenceFailure[];
    /**
     * Issue #579 — a short reason for a `skipped` gate ("not-frontend", "no documented flow to
     * capture"), shown in the verdict summary's skip line when the gate's flag is on.
     */
    skip_reason?: string;
    confidence?: MutationConfidence;
}
interface VerificationEvidence {
    schema_version: typeof VERIFICATION_EVIDENCE_SCHEMA_VERSION;
    run_id: string;
    started_at: string;
    completed_at: string;
    overall_status: EvidenceOverallStatus;
    first_failure_gate: VerificationGate | null;
    gates: VerificationEvidenceGate[];
}

/**
 * Which dependency name means which framework. Exported so the framework-API index
 * (issue #397) selects the packages to index from THIS map rather than keeping a second,
 * divergent copy of the same knowledge (RULE-13).
 */
declare const FRAMEWORK_PACKAGE_MAP: Record<string, Stack>;
declare function buildDetectedStackProfile(input: {
    toolchains: ToolchainInfo[];
    packages: InstalledPackage[];
    sources: StackSourceReference[];
    detectedTraits?: string[];
    fallbackStack?: Stack | null;
    fallbackCapabilities?: string[];
}): DetectedStackProfile;
declare function getPrimaryStack(profile: Partial<Pick<ProjectProfile, 'active_capabilities' | 'routing' | 'stack_profile'>> | undefined): Stack;
declare function getLegacyCapabilities(profile: Partial<Pick<ProjectProfile, 'routing' | 'stack_profile'>> | undefined): Capability[];
declare function compareStackProfiles(previous: DetectedStackProfile | null, current: DetectedStackProfile): StackDriftReport;
declare function summarizeStack(profile: DetectedStackProfile): string;

/**
 * How a packet came to exist. Absent on a packet the agent opened by hand through
 * `paqad-ai decision create`; `evidence-armed` on one the machine minted from computed
 * evidence (issue #361), so a reader can tell an asked question from a detected one.
 */
type ContractDecisionOrigin = 'evidence-armed' | 'expert-conflict';
/**
 * A single option offered by a decision packet.
 *
 * `evidence` is optional and additive (issue #361): a hand-authored option carries none,
 * while an evidence-armed option carries the proof behind it (the matched file, when it
 * last changed, how many callers it has, how similar it is). It reuses the
 * {@link DecisionOptionEvidence} shape the automated `DecisionPacket` already defines
 * rather than introducing a second evidence representation.
 */
interface ContractDecisionOption {
    option_key: string;
    label: string;
    evidence?: DecisionOptionEvidence;
}
/** The pending form written by {@link createPendingDecision}. */
interface PendingContractDecision {
    id: string;
    category: string;
    title: string;
    context: string;
    options: ContractDecisionOption[];
    recommendation: string | null;
    created_at: string;
    status: 'pending';
    /** Set only on a machine-minted packet (issue #361); absent on a hand-opened one. */
    origin?: ContractDecisionOrigin;
    /**
     * The ULID of the change that was active when the packet was opened or resolved (issue #581),
     * so the change's `decisions.json` index can list it. Absent when no change was active, and on
     * packets written before the field existed.
     */
    change?: string;
}
/** The resolved form written by {@link resolvePendingDecision}. */
interface ResolvedContractDecision extends Omit<PendingContractDecision, 'status'> {
    status: 'resolved';
    chosen: string;
    rationale: string;
    resolved_at: string;
}
/** Fields the agent supplies to open a decision; the id/timestamps are minted. */
interface CreateDecisionInput {
    category: string;
    title: string;
    context: string;
    options: ContractDecisionOption[];
    recommendation?: string | null;
    /** Set by a machine minter (issue #361); omitted when the agent opens the packet. */
    origin?: ContractDecisionOrigin;
    /** The active change's ULID (issue #581); omitted when no change is active. */
    change?: string | null;
}
/** Mint a fresh, collision-free decision id (`D-<ULID>`). */
declare function mintDecisionId(): string;
/**
 * True when `id` is the collision-free `D-<ULID>` form (not legacy `D-{N}`). Delegates
 * to the single canonical write-time guard (`isStrictDecisionId`, issue #387) so the
 * contract-packet and automated-packet paths never carry divergent id regexes.
 */
declare function isContractDecisionId(id: string): boolean;
/**
 * Reject any id that is not the collision-free `D-<ULID>` form. A hand-written
 * sequential `D-4` (or any other shape) throws here, so a new packet can only
 * ever carry a minted ULID id — the guarantee issue #272 needs at creation time.
 */
declare function assertContractDecisionId(id: string): void;
/**
 * Open a decision: mint a `D-<ULID>` id, build the pending packet from the
 * supplied content, and write it atomically to `.paqad/decisions/pending/`.
 * Returns the minted id and the absolute path written.
 */
declare function createPendingDecision(projectRoot: string, input: CreateDecisionInput): {
    id: string;
    path: string;
};
/**
 * Resolve a pending decision: record the chosen option (and any free-text
 * rationale), move the packet from `pending/` to `resolved/`, and stamp
 * `resolved_at`. `chosen` must reference one of the packet's option keys. A packet opened with
 * no change is linked to `options.change` (the change active at resolve, issue #581); one that
 * already names a change keeps it. Returns the resolved packet and the absolute path written.
 */
declare function resolvePendingDecision(projectRoot: string, id: string, chosen: string, rationale?: string, options?: {
    change?: string | null;
}): {
    path: string;
    packet: ResolvedContractDecision;
};
/** A compact listing row for `paqad-ai decision list`. */
interface ContractDecisionListEntry {
    id: string;
    category: string;
    title: string;
    status: 'pending' | 'resolved';
}
/** A stored packet plus which directory it was read from. */
interface StoredContractDecision {
    packet: PendingContractDecision;
    status: 'pending' | 'resolved';
}
/**
 * Read every stored decision packet (pending first, then resolved, each id-sorted). The one
 * reader for the contract store: the CLI listing renders it, and the evidence-armed minter
 * (issue #361) scans the packets' contexts for its machine tokens. Tolerant by design — a
 * missing directory yields no rows and a malformed packet is skipped, so a partial store
 * never throws.
 */
declare function readContractDecisions(projectRoot: string): StoredContractDecision[];
/**
 * List every decision packet (pending first, then resolved), for `paqad-ai decision
 * list`.
 */
declare function listContractDecisions(projectRoot: string): ContractDecisionListEntry[];
/**
 * Append a write-in option to a pending packet and return its minted key. Honors the
 * Decision Pause Contract's "Other" flow without hand-editing the JSON: the user
 * picked a write-in answer, so the option is added to the packet before it resolves to
 * it. The key is `other` (or `other-2`, … on collision), never a duplicate.
 */
declare function addWriteInOption(projectRoot: string, id: string, label: string): string;

interface AIDetectorOptions {
    /**
     * Inference provider that performs the actual LLM call. When omitted the AI path
     * is considered unavailable and {@link AIDetector.detect} always returns `null`,
     * so the engine falls through to static detection (AC2).
     */
    provider?: InferenceProvider | null;
    /** Override the hard timeout (ms). Defaults to 10s. */
    timeoutMs?: number;
    /** Override the minimum accepted confidence. Defaults to 0.6. */
    minConfidence?: number;
}
/**
 * PQD-423: the AI-first stack detection path. Reads the project's top-level
 * manifests, asks an injected {@link InferenceProvider} to classify the stack, and
 * returns a {@link DetectionReport} tagged `source: 'ai'` — or `null` on any
 * failure (no provider, no manifests, call/parse error, timeout, or low
 * confidence), in which case the {@link Detector} runs its static fallback.
 *
 * Failure isolation is total: this class never throws. The static path therefore
 * remains the guaranteed last resort.
 */
declare class AIDetector {
    private readonly provider;
    private readonly timeoutMs;
    private readonly minConfidence;
    constructor(options?: AIDetectorOptions);
    detect(projectRoot: string): Promise<DetectionReport | null>;
    /**
     * Run the provider call under a hard timeout. If the provider ignores the
     * abort signal, the timer still rejects so the caller is never blocked past
     * {@link timeoutMs}.
     */
    private completeWithTimeout;
}

interface DetectorOptions {
    /**
     * PQD-423: the AI-first detection path. When omitted (the default), detection is
     * purely static — preserving the historical behaviour for every existing caller.
     * Inject an {@link AIDetector} backed by an inference provider to enable AI-first
     * detection with the static path as fallback.
     */
    aiDetector?: AIDetector | null;
}
declare class Detector {
    private readonly introspector;
    private readonly packLoader;
    private readonly aiDetector;
    /**
     * PQD-423 (AC4): in-flight detection promises keyed by `projectRoot` + persist
     * flag. Two concurrent `detect()` calls on the same unchanged folder share a
     * single promise, so they return identical results and do no redundant work.
     */
    private readonly inflight;
    constructor(options?: DetectorOptions);
    /**
     * @param options.persist When `false`, the underlying stack snapshot is not written to the
     *   on-disk cache (`.paqad/`). Defaults to `true`. Read-only callers such as the onboarding
     *   dry-run preview (PQD-103) pass `false` so detection touches no disk.
     */
    detect(projectRoot: string, options?: {
        persist?: boolean;
    }): Promise<DetectionReport>;
    private runDetect;
}

/**
 * Resolve the human-readable primary language for a detected ecosystem.
 *
 * @returns the language label, or `null` when no ecosystem was detected
 *   (`null`/`undefined`) or the ecosystem is not in the known map.
 */
declare function ecosystemToLanguage(ecosystem: StackEcosystem | null | undefined): string | null;

interface BuildDetectionReportInput {
    domain: Domain | null;
    stack: Stack | null;
    capabilities?: Capability[];
    matchedPacks?: string[];
    detectedTraits?: string[];
    recommendedCapabilities?: ActiveCapability[];
    detectionPhase?: DetectionReport['detection_phase'];
    signals: DetectionSignal[];
    confidence: DetectionReport['confidence'];
    /**
     * PQD-423: primary toolchain ecosystem; mapped to a `primary_language` label.
     * Omit/`null` for content-only, ambiguous, or unknown projects.
     */
    ecosystem?: StackEcosystem | null;
    /**
     * PQD-423: explicit numeric confidence in `[0, 1]`. When omitted it is derived
     * from the categorical `confidence`.
     */
    confidenceScore?: number;
    /** PQD-423: detection path that produced the report. Defaults to `'static'`. */
    source?: 'ai' | 'static';
    repository?: RepositoryContext;
}
declare function buildDetectionReport(input: BuildDetectionReportInput): DetectionReport;

/**
 * PQD-423: the `ModelResource` envelope permissions block. Kept at the IPC
 * boundary (this wrapper) rather than on the internal {@link DetectionReport}.
 */
interface StackDetectionPermissions {
    can_view: boolean;
    can_edit: boolean;
    can_delete: boolean;
}
/**
 * PQD-423: a {@link DetectionReport} wrapped in the seven mandatory `ModelResource`
 * envelope fields that every desktop/API response carries. This keeps the envelope
 * shape at the engine edge so internal detection types stay lean.
 */
interface StackDetectionResource {
    id: string;
    type: 'stack_detection';
    created_at: string;
    updated_at: string;
    created_at_human: string;
    updated_at_human: string;
    permissions: StackDetectionPermissions;
    report: DetectionReport;
}
interface ToStackDetectionResourceOptions {
    /** Project folder the report was produced for; folded into the stable `id`. */
    projectRoot?: string;
    /** Override any of the default permissions (view-only by default). */
    permissions?: Partial<StackDetectionPermissions>;
}
/**
 * Wrap a {@link DetectionReport} in the `ModelResource` envelope.
 *
 * The `id` is a deterministic SHA-256 of `projectRoot + report.timestamp`, so two
 * envelopes built from the same report (same folder, same detection run) share an
 * identical id. Human timestamps are formatted deterministically in UTC — no
 * locale or machine-timezone dependence — so the result is reproducible.
 */
declare function toStackDetectionResource(report: DetectionReport, options?: ToStackDetectionResourceOptions): StackDetectionResource;

declare function detectAnalyticsSignals(projectRoot: string): DetectionSignal[];

declare function detectFlutterSignals(projectRoot: string): DetectionSignal[];

interface LaravelDetectionResult {
    signals: DetectionSignal[];
    capabilities: Capability[];
}
declare function detectLaravelSignals(projectRoot: string): LaravelDetectionResult;

interface ReactDetectionResult {
    signals: DetectionSignal[];
    capabilities: Capability[];
}
declare function detectReactSignals(projectRoot: string): ReactDetectionResult;

declare function detectShortVideoSignals(projectRoot: string): DetectionSignal[];

interface SvelteDetectionResult {
    signals: DetectionSignal[];
    capabilities: Capability[];
}
declare function detectSvelteSignals(projectRoot: string): SvelteDetectionResult;

interface VueDetectionResult {
    signals: DetectionSignal[];
    capabilities: Capability[];
}
declare function detectVueSignals(projectRoot: string): VueDetectionResult;

/**
 * Engine event-stream contract (PQD-99).
 *
 * A single in-process subscription surface that delivers every event the engine
 * emits — slice execution, decision pauses, retrieval activity, workflow steps,
 * and registry changes — in occurrence order, without polling. Consumers
 * (the desktop app via its Electron preload bridge, the API layer) subscribe
 * once and receive a serialisable {@link EngineEvent} for every domain.
 *
 * Every variant carries:
 * - a `kind` discriminant (see {@link EngineEventKind}), and
 * - an `at` ISO-8601 timestamp stamped by the engine at emit time.
 *
 * Payloads are plain data only (no class instances, no circular references) so
 * the preload layer can forward them over IPC to the renderer untransformed.
 */
/** Fields shared by every engine event variant. */
interface EngineEventBase {
    /** ISO-8601 timestamp stamped by the engine when the event is emitted. */
    at: string;
    /**
     * Set when the event's string payload exceeded the bus's `maxPayloadBytes`
     * budget and was truncated to keep delivery cheap. The event is delivered
     * rather than rejected; consumers should treat truncated fields as elided.
     */
    truncated?: boolean;
}
/** A planning/agentic slice began executing. */
interface SliceStartedEvent extends EngineEventBase {
    kind: 'slice-started';
    runId: string;
    sliceId: string;
    index?: number;
}
/** A planning/agentic slice finished successfully. */
interface SliceCompletedEvent extends EngineEventBase {
    kind: 'slice-completed';
    runId: string;
    sliceId: string;
    durationMs?: number;
}
/** A planning/agentic slice failed. */
interface SliceFailedEvent extends EngineEventBase {
    kind: 'slice-failed';
    runId: string;
    sliceId: string;
    error: string;
}
/**
 * A single option carried on a {@link DecisionPausedEvent}. A serialisable
 * subset of the planning `DecisionOption` — enough for the desktop to render the
 * Decision Pause panel without a secondary filesystem read (PQD-101).
 */
interface DecisionEventOption {
    option_key: string;
    label: string;
    one_line_preview: string;
    trade_off: string;
    technical_detail?: string;
}
/**
 * The engine paused for a human decision (the Decision Pause contract).
 *
 * PQD-99 introduced the minimal `decisionId`/`category`/`prompt` shape; PQD-101
 * enriches it (additively, all optional) with the full packet content so a
 * consumer can pop the packet UI live without reading
 * `.paqad/decisions/pending/` itself.
 */
interface DecisionPausedEvent extends EngineEventBase {
    kind: 'decision-paused';
    decisionId: string;
    category?: string;
    prompt?: string;
    /** The packet question (the human-facing prompt text). */
    question?: string;
    /** The options offered, with their previews and trade-offs. */
    options?: DecisionEventOption[];
    /** The recommended option_key, if the packet carries one. */
    recommendation?: string | null;
    /** Why the recommendation was made, if provided. */
    recommendationReason?: string;
    /** Project-relative path to the on-disk pending packet JSON. */
    packetPath?: string;
    /** The slice this decision is linked to, if any. */
    linkedSliceId?: string;
}
/** A previously paused decision was resolved. */
interface DecisionResolvedEvent extends EngineEventBase {
    kind: 'decision-resolved';
    decisionId: string;
    resolution?: string;
    /** The chosen option_key (null when the resolution declined to choose). */
    chosenOptionKey?: string | null;
    /** Who/what resolved it: `human`, `rule`, `rag-confident`, `memoization`, … */
    resolver?: string;
    /** The recorded resolution intent (`explicit`, `safer-default`, …). */
    intent?: string;
}
/**
 * The engine read a pending packet and found it malformed (PQD-101). Lets a
 * consumer show a "decision was lost" notice instead of crashing.
 */
interface DecisionPacketCorruptEvent extends EngineEventBase {
    kind: 'decision-packet-corrupt';
    decisionId: string;
    reason: string;
}
/**
 * A new pause would exceed the per-project pending-packet cap, so the engine
 * refused to create the packet (PQD-101). Lets a consumer prompt the user to
 * triage the existing pending packets.
 */
interface DecisionCapExceededEvent extends EngineEventBase {
    kind: 'decision-cap-exceeded';
    pendingCount: number;
    cap: number;
}
/**
 * A consumer explicitly discarded a pending packet with a reason (PQD-101). No
 * fake resolution is written; the panel can close cleanly.
 */
interface DecisionDiscardedEvent extends EngineEventBase {
    kind: 'decision-discarded';
    decisionId: string;
    reason: string;
}
/** A retrieval (RAG) query started. */
interface RetrievalStartedEvent extends EngineEventBase {
    kind: 'retrieval-started';
    queryId: string;
    query?: string;
}
/** A retrieval (RAG) query completed. */
interface RetrievalCompletedEvent extends EngineEventBase {
    kind: 'retrieval-completed';
    queryId: string;
    resultCount?: number;
}
/** A workflow step began running. */
interface WorkflowStepStartedEvent extends EngineEventBase {
    kind: 'workflow-step-started';
    runId: string;
    stepIndex: number;
    skill: string | null;
}
/** A workflow step completed (or was skipped). */
interface WorkflowStepCompletedEvent extends EngineEventBase {
    kind: 'workflow-step-completed';
    runId: string;
    stepIndex: number;
    skill: string | null;
}
/** A workflow step failed. */
interface WorkflowStepFailedEvent extends EngineEventBase {
    kind: 'workflow-step-failed';
    runId: string;
    stepIndex: number;
    skill: string | null;
    error: string;
}
/** A runtime registry (skills, packs, tools, MCP servers) changed. */
interface RegistryChangedEvent extends EngineEventBase {
    kind: 'registry-changed';
    registry: string;
    change: 'added' | 'removed' | 'updated';
    id?: string;
}
/** A single gate's outcome carried on a {@link VerificationVerdictEvent}. */
interface VerificationGateVerdictEntry {
    gate: string;
    status: 'pass' | 'fail' | 'inconclusive' | 'skipped';
    detail: string;
}
/**
 * A verification run (issue #117) finished — fired by the completion hook / CI
 * backstop. Carries the one trust verdict so a desktop/UI subscriber renders
 * "did the agent obey?" without re-reading the diff. `ok` is the deterministic
 * pass/fail; `gates` carries per-gate specifics; `escalations` lists signals
 * that could not be proven and need a human.
 */
interface VerificationVerdictEvent extends EngineEventBase {
    kind: 'verification-verdict';
    origin: string;
    ok: boolean;
    summary: string;
    gates: VerificationGateVerdictEntry[];
    escalations: string[];
}
/**
 * Synthetic event delivered to a subscriber whose buffer overflowed: the bus
 * dropped `droppedCount` older non-critical events before this marker. It is
 * itself never dropped.
 */
interface EventsCoalescedEvent extends EngineEventBase {
    kind: 'events-coalesced';
    droppedCount: number;
}
/**
 * Discriminated union of every event the engine can emit. New domains add a
 * variant here and a `kind` literal; consumers switch on `kind`.
 */
type EngineEvent = SliceStartedEvent | SliceCompletedEvent | SliceFailedEvent | DecisionPausedEvent | DecisionResolvedEvent | DecisionPacketCorruptEvent | DecisionCapExceededEvent | DecisionDiscardedEvent | RetrievalStartedEvent | RetrievalCompletedEvent | WorkflowStepStartedEvent | WorkflowStepCompletedEvent | WorkflowStepFailedEvent | RegistryChangedEvent | VerificationVerdictEvent | EventsCoalescedEvent;
/** The set of `kind` discriminants, for use in {@link EngineEventFilter}. */
type EngineEventKind = EngineEvent['kind'];
/** A subscription filter: only events whose `kind` is listed are delivered. */
interface EngineEventFilter {
    kinds: readonly EngineEventKind[];
}
/** The lifecycle state of a subscription. */
type SubscriptionState = 'active' | 'faulted' | 'cancelled';
/**
 * Handle returned by `subscribe()`. `state` is a live view of the underlying
 * subscription; `unsubscribe()` stops delivery and releases backing resources.
 */
interface Subscription {
    readonly id: string;
    readonly state: SubscriptionState;
    unsubscribe(): void;
}
/**
 * A subscriber callback. Must be synchronous from the engine's perspective —
 * the bus never awaits it. The `void` return type discourages passing an async
 * function (whose Promise the bus would otherwise ignore).
 */
type EngineEventCallback = (event: EngineEvent) => void;

/** Tuning knobs for an {@link EngineEventBus} instance. */
interface EngineEventBusOptions {
    /**
     * Per-subscriber ring-buffer capacity. When a subscriber's buffer is full and
     * a new droppable event arrives, the oldest droppable event is discarded and
     * the subscriber receives an `events-coalesced` marker. Default 512.
     */
    bufferSize?: number;
    /**
     * Event kinds that must never be dropped when a buffer overflows. The
     * `events-coalesced` marker is always protected regardless of this set.
     * Default: decision events, which a UI must not miss.
     */
    neverDrop?: readonly EngineEventKind[];
    /**
     * Maximum serialised size (bytes) of an event payload before its string
     * fields are truncated and the event is tagged `truncated`. Default 65536.
     */
    maxPayloadBytes?: number;
}
/**
 * In-process, unified engine event bus (PQD-99).
 *
 * Subscribers register a callback and an optional kind filter; the engine calls
 * {@link emit} which enqueues to each subscriber's ring buffer and schedules a
 * microtask drain — `emit` itself never invokes a callback and never blocks
 * engine work. A slow subscriber's overflow is absorbed by dropping its oldest
 * non-critical events and tagging the next delivery with an `events-coalesced`
 * marker. A throwing callback faults only its own subscription; all others keep
 * receiving events. Deliberately does not extend Node's `EventEmitter` so the
 * surface stays exactly `subscribe`/`emit`/`unsubscribe`.
 */
declare class EngineEventBus {
    private readonly subscribers;
    private readonly bufferSize;
    private readonly neverDrop;
    private readonly maxPayloadBytes;
    private drainScheduled;
    constructor(options?: EngineEventBusOptions);
    /**
     * Register a subscriber. Without a filter, every kind is delivered. The
     * returned {@link Subscription} exposes live `state` and `unsubscribe()`.
     */
    subscribe(callback: EngineEventCallback, filter?: EngineEventFilter): Subscription;
    /**
     * Emit an event to every matching active subscriber. Enqueues only and
     * schedules an async drain — never invokes a callback inline, never blocks.
     */
    emit(event: EngineEvent): void;
    /** Stop delivery to a subscription and release its buffer. */
    unsubscribe(id: string): void;
    /** Total registered subscriptions (active + faulted; excludes cancelled). */
    subscriberCount(): number;
    /** Subscriptions currently in the `active` state. */
    activeSubscriberCount(): number;
    private enqueue;
    private scheduleDrain;
    private drain;
    private deliver;
    private truncateIfOversized;
}

declare const PLACEHOLDER_DESIGN_TOKENS: DesignTokensDocument;

interface SchemaValidationIssue {
    path: string;
    message: string;
    expected?: string;
    actual?: string;
}
interface ValidationResult {
    valid: boolean;
    errors: SchemaValidationIssue[];
}
declare class SchemaValidator {
    private readonly ajv;
    constructor();
    validate(schemaId: string, data: unknown): ValidationResult;
    private registerSchemas;
    private formatErrors;
}

declare const DESIGN_TOKENS_PLACEHOLDER_NOTE = "PLACEHOLDER design tokens seeded by paqad-ai. Replace these values with your project's real design tokens, then delete this \"$comment\". Until then, design-system docs (tokens.md, components.md, \u2026) are intentionally not generated, because they would describe a design system that does not exist.";
declare class DesignTokensMissingError extends Error {
    readonly path: string;
    constructor(path: string);
}
/**
 * Thrown when the tokens file is still the unedited placeholder scaffold. The
 * documentation workflow catches this and skips design-system doc generation
 * with a clear message rather than shipping docs built from placeholder values.
 */
declare class DesignTokensPlaceholderError extends Error {
    readonly path: string;
    constructor(path: string);
}
declare class DesignTokenService {
    private readonly validator;
    constructor(validator?: SchemaValidator);
    seed(projectRoot: string): Promise<void>;
    load(projectRoot: string): Promise<DesignTokensDocument>;
    generateDocs(projectRoot: string): Promise<DesignTokenDocArtifact[]>;
    writeDocs(projectRoot: string): Promise<string[]>;
    exportTheme(projectRoot: string, stack: Stack | null): Promise<ThemeExportArtifact[]>;
    writeThemeExports(projectRoot: string, stack: Stack | null): Promise<string[]>;
}

declare class HealthChecker {
    private readonly validator;
    run(projectRoot: string): Promise<HealthReport>;
    private readProfile;
    private detectModules;
    private checkFrameworkArtifacts;
    /**
     * Whether `relPath` (relative to the project root, e.g. `.paqad/vectors/`) is
     * git-ignored. Asks git, which honours the project root `.gitignore`, paqad's
     * nested `.paqad/.gitignore`, and any global excludes alike. Falls back to a
     * textual scan of both ignore files when git is unavailable or the project is
     * not a git repository (e.g. a freshly scaffolded test fixture), so the check
     * is meaningful before `git init`.
     */
    private isPathIgnored;
    private checkProfile;
    private checkDetectionReport;
    private checkOnboardingManifest;
    private checkStackSnapshot;
    private checkStackDrift;
    private checkDecisionWorkspace;
    private checkModuleHealthLedger;
    private checkInstructionCopies;
    private checkIndexesCurrent;
    private checkAdapterConfig;
    /**
     * Codex hooks wired (issue #566, AC-11). When a project carries a `.codex/` layer it is a
     * Codex project, so `.codex/hooks.json` must exist and wire paqad's hooks into all four
     * lifecycle events. A missing or partial file WARNS (never fails — a not-yet-onboarded or
     * not-yet-trusted project is not a fault) and names the `/hooks` trust step, because doctor
     * cannot confirm from disk whether Codex has TRUSTED the project hooks — that approval lives
     * in Codex, not the file. A non-Codex project (no `.codex/`) passes with nothing to check.
     */
    private checkCodexHooks;
    private checkProviderEntryBootstrapPointer;
    private checkProviderEntryFallbackClause;
    private checkStackCommands;
    /**
     * Warn when the recorded test-runner parallel mode is unavailable or unknown (issue #554), so a
     * team knows their suite runs sequentially and how to make it parallel. Pass on native/available.
     */
    private checkTestRunnerParallel;
    private checkStructuredTestOutput;
    private checkStableFrameworkPaths;
    private checkBrokenScaffold;
    private checkUiDocs;
    private checkApiDocs;
    private checkIntegrationDocs;
    private checkErrorCatalog;
    private checkMcp;
    private checkSkillCache;
    private checkContextHitRate;
    private buildEfficiencySummary;
    /**
     * Issue #284 — the resident rule-footprint readout. Reports how many bytes the lean
     * session-context artifact carries versus loading the full `docs/instructions/rules`
     * tree, computed per project (no hard-coded sizes). A present, smaller artifact is a
     * pass with the savings; an artifact that is not smaller than the full rule set warns
     * (lean loading is not paying off). A missing artifact is a pass: full-load is the
     * documented fallback and the artifact regenerates on the next refresh/onboard.
     */
    private checkLeanRuleFootprint;
    /**
     * S1 (defect D1) — the rule-store freshness gate. The per-turn refresh recomposes
     * the session-context artifact from `.paqad/compiled-rules.json`, so a store whose
     * `source_hash` no longer matches the authored rules under `docs/instructions/rules/`
     * means the agent is being served rule text that has drifted from the rules on disk.
     * That is a fault, not a warning, so this check FAILS when the store is stale and
     * names the command that rebuilds it. It passes when the store is current (or absent,
     * which {@link isCompiledRulesStale} reports as stale and the refresh then compiles).
     */
    private checkCompiledRulesCurrent;
    /**
     * Spec pipeline health (issue #512, FR-10): the S4 parser-parity corpus must pass BOTH the
     * S4 shape check and the real freeze parser (so the two can never drift, FR-10.2), and the
     * enforcement config must be coherent (no required gate on a disabled pipeline, FR-10-T4).
     */
    private checkSpecPipeline;
    /**
     * Visual-evidence coherence (issue #551, Part A.5). Warns (never fails) when the feature is
     * on but a prerequisite is missing, so a team that turned it on but cannot yet capture sees
     * exactly why. Fully silent when the flag is off.
     */
    private checkVisualEvidence;
    private checkExpertRoster;
    private checkClassificationOverrideRate;
    private documentationHasRun;
    private checkRag;
    private checkRagVectorPayloadConsistency;
    private checkJsonArtifact;
}

interface InstallResult {
    framework_home: string;
    project_root: string;
    version: string;
}
/** Options for {@link bootstrapFramework}. */
interface BootstrapOptions {
    /**
     * A consumer logger to install at init (PQD-105). When supplied, every
     * structured log the engine emits is routed to it. Equivalent to calling
     * {@link setEngineLogger} before bootstrapping; provided here so the consumer
     * has a single clean init surface.
     */
    logger?: EngineLogger;
}
/**
 * The HOME-ONLY half of the install: create the `~/.paqad-ai/current` framework symlink and
 * render the six stage-isolation agents under the user home. It writes NOTHING into the project,
 * so a caller that must not touch the tracked tree (issue #576, Finding 2 — `paqad-ai join`) can
 * set up a fresh machine's global install without producing a diff. {@link bootstrapFramework}
 * layers the project-side metadata writes on top for `onboard`/`install`.
 */
declare function bootstrapFrameworkHome(): {
    framework_home: string;
};
declare function bootstrapFramework(projectRoot: string, options?: BootstrapOptions): InstallResult;

/**
 * Sentinel returned for `engineVersion` when the engine was built without a
 * usable version string (AC5). A consumer can route this to a "broken engine
 * install" message instead of acting on an empty or invented version.
 */
declare const VERSION_UNKNOWN = "version unknown";
/**
 * The oldest consumer version the engine declares it is compatible with. The
 * comparison in {@link compareConsumerCompatibility} treats only a major-version
 * delta as breaking (semver), so this floor is enforced at the major level.
 */
declare const MIN_CONSUMER_VERSION = "1.0.0";
/** Immutable description of the engine's version and compatibility floor. */
interface EngineVersionReport {
    /** The engine's own version, or {@link VERSION_UNKNOWN} on a broken build. */
    readonly engineVersion: string;
    /** The oldest consumer version the engine supports ({@link MIN_CONSUMER_VERSION}). */
    readonly minConsumerVersion: string;
    /** The version at which the engine became deprecated, or `undefined`. */
    readonly deprecatedAsOf: string | undefined;
}
/**
 * Normalise a raw build-time version string into a reportable value. Returns
 * {@link VERSION_UNKNOWN} when the build-time injection produced an empty string,
 * the unreplaced `__PKG_VERSION__` placeholder, or a non-string (AC5).
 *
 * Exported as a pure helper so the "version unknown" path is testable: the
 * build-time `__PKG_VERSION__` define is replaced textually at compile time and
 * cannot be mocked at runtime.
 */
declare function normalizeEngineVersion(raw: unknown): string;
/**
 * Return the engine's version report. The result is a frozen object, computed
 * once and memoised for the process lifetime, so repeated calls return the
 * identical reference and perform no disk or network I/O (AC1, AC4). Calling it
 * forces no engine initialisation.
 */
declare function getEngineVersionReport(): EngineVersionReport;

/**
 * The outcome of comparing a consumer against an engine version report:
 * - `'ok'` — the consumer can run against this engine.
 * - `'engine-too-new'` — the consumer is older than the engine's required
 *   minimum consumer; the engine demands a newer consumer (AC2).
 * - `'engine-too-old'` — the consumer is on a newer major than the engine
 *   provides; the engine is below what the consumer requires (AC3).
 * - `'engine-version-unknown'` — the engine reported no usable version (AC5).
 */
type ConsumerCompatibility = 'ok' | 'engine-too-new' | 'engine-too-old' | 'engine-version-unknown';
/**
 * Compare a consumer version against the engine's version report.
 *
 * Returns `'engine-version-unknown'` when the engine has no usable version.
 * A consumer whose version cannot be parsed is treated conservatively as below
 * the floor (`'engine-too-new'`) so a broken consumer refuses to start rather
 * than proceeding silently.
 */
declare function compareConsumerCompatibility(consumerVersion: string, report: EngineVersionReport): ConsumerCompatibility;

/**
 * Synchronous read of the stack snapshot, for callers that cannot await (issue #357: the
 * plan-compile verb is sync all the way down). Same tolerance contract as
 * {@link StackSnapshotCache.read} — a missing or corrupt snapshot reads as `null`, never a
 * throw — and it resolves the path through `PATHS.STACK_SNAPSHOT` so there is one place
 * the snapshot location is known.
 */
declare function readStackSnapshotSync(projectRoot: string): StackSnapshot | null;
declare class StackSnapshotCache {
    read(projectRoot: string): Promise<StackSnapshot | null>;
    write(projectRoot: string, snapshot: StackSnapshot): Promise<void>;
    hashFiles(projectRoot: string, relativePaths: string[]): Promise<Record<string, string>>;
}

interface ParsedManifestPackage {
    name: string;
    constraint?: string;
    isDev?: boolean;
}
interface ParsedManifest {
    ecosystem: StackEcosystem;
    packages: ParsedManifestPackage[];
    scripts?: Record<string, string>;
}
interface ParsedLockfilePackage {
    name: string;
    version: string;
}
interface ParsedLockfile {
    ecosystem: StackEcosystem;
    packages: ParsedLockfilePackage[];
}
interface EcosystemParser {
    ecosystem: StackEcosystem;
    packageManager: string;
    manifestFiles: string[];
    lockfileFiles: string[];
    parseManifest(content: string, filename: string): ParsedManifest;
    parseLockfile(content: string, filename: string): ParsedLockfile;
}

interface ParsedProjectResult {
    toolchain: ToolchainInfo;
    packages: InstalledPackage[];
}
declare class EcosystemParserRegistry {
    private readonly parsers;
    constructor(parsers?: EcosystemParser[]);
    register(parser: EcosystemParser): void;
    list(): EcosystemParser[];
    getKnownFiles(): string[];
    parseProject(projectRoot: string): Promise<ParsedProjectResult[]>;
}
declare function createDefaultEcosystemParserRegistry(): EcosystemParserRegistry;

declare class StackIntrospector {
    private readonly cache;
    private readonly parserRegistry;
    /**
     * Build a stack snapshot for `projectRoot`.
     *
     * @param options.persist When `false`, the freshly computed snapshot is **not** written to
     *   the on-disk cache (`.paqad/`). Defaults to `true` (the historical behaviour). Read-only
     *   callers such as the onboarding dry-run preview (PQD-103) pass `false` so the snapshot can
     *   be computed without touching disk. The cache is still *read* either way.
     */
    snapshot(projectRoot: string, options?: {
        persist?: boolean;
    }): Promise<StackSnapshot>;
}

declare class McpConfigManager {
    private readonly registry;
    generate(profile: ProjectProfile, adapter: AdapterType): McpConfigOutput;
}

declare class DataRetrievalDecider {
    private readonly availableMcp;
    private readonly availableScripts;
    constructor(availableMcp?: string[], availableScripts?: string[]);
    decide(dataNeeded: string): DataSource;
    private findMcpProvider;
    private findScript;
}

declare const MCP_SERVERS: McpServerDefinition[];
declare function getServersForStack(stack: string, capabilities: string[]): McpServerDefinition[];
declare class McpServerRegistry {
    list(): McpServerDefinition[];
    forProfile(profile: Pick<ProjectProfile, 'routing' | 'stack_profile' | 'mcp' | 'active_capabilities'>): McpServerDefinition[];
}

type DocumentationWorkflowMode = 'foundation' | 'module-docs';
interface DocumentationWorkflowOptions {
    projectRoot: string;
    mode?: DocumentationWorkflowMode;
    request?: Pick<ClassificationResult, 'domain' | 'stack' | 'request_text'> & {
        output_path?: string;
    };
}
interface DocumentationWorkflowStep {
    id: string;
    summary: string;
    generated: string[];
    skipped: string[];
}
interface DocumentationWorkflowResult {
    generated: string[];
    skipped: string[];
    progress_path: string;
    handover_path: string;
    module_map_path: string | null;
    module_docs_pending_map_review: boolean;
    module_map_low_confidence_modules: string[];
    orphaned_module_dirs: string[];
    stack_snapshot: StackSnapshot;
    effective_routing: {
        domain: Domain;
        stack: Stack;
        capabilities: Capability[];
    };
    profile_updated: boolean;
    steps: DocumentationWorkflowStep[];
    /**
     * Issue #42 — delivery conventions detected during the repo scan and filled
     * into the `auto` sections of delivery-policy. Present only for the coding
     * domain. `connect_nudge` is the single combined "connect GitHub + Jira" card.
     */
    delivery_detection?: {
        summary: string[];
        connect_nudge: string | null;
        filled: boolean;
    };
}
declare class DocumentationWorkflow {
    private readonly tracker;
    private readonly detector;
    private readonly introspector;
    run(options: DocumentationWorkflowOptions): Promise<DocumentationWorkflowResult>;
    private runModuleDocs;
    private runFoundation;
}

interface DocumentPipelineOptions extends DocumentationWorkflowOptions {
    mode?: DocumentationWorkflowMode;
    request?: Pick<ClassificationResult, 'domain' | 'stack' | 'request_text'> & {
        output_path?: string;
    };
}
type DocumentRunResult = DocumentationWorkflowResult;
declare class DocumentPipeline {
    private readonly workflow;
    run(options: DocumentPipelineOptions): Promise<DocumentRunResult>;
}

declare class DocumentProgressTracker {
    private readonly validator;
    constructor(validator?: SchemaValidator);
    load(projectRoot: string): Promise<DocProgressFile>;
    save(projectRoot: string, progress: DocProgressFile): Promise<void>;
    resetGeneratingEntries(projectRoot: string, progress: DocProgressFile): Promise<void>;
    createEntry(output_path: string, source_files: string[]): DocProgressEntry;
    private createEmpty;
}
declare function resetGeneratingEntries(progress: DocProgressFile): DocProgressEntry[];

declare function hashSourceFiles(projectRoot: string, sourceFiles: string[]): Promise<string>;

interface FileWriteResult {
    written: string[];
    skipped: string[];
}
interface WriteGeneratedFilesOptions {
    /**
     * Write every file regardless of its `autoUpdate` flag or whether the target
     * already exists (PQD-424, AC2). The caller's explicit escape hatch for
     * "regenerate everything", overriding the default skip-if-present behaviour
     * that protects project-owned files.
     */
    forceOverwrite?: boolean;
}
declare function writeGeneratedFiles(projectRoot: string, files: GeneratedFile[], options?: WriteGeneratedFilesOptions): FileWriteResult;
/**
 * Classify what {@link writeGeneratedFiles} *would* do for each file, without touching disk.
 *
 * Pure read-only counterpart to `writeGeneratedFiles`: it performs no `mkdirSync`,
 * `writeFileSync`, or `chmodSync`. The action mirrors the write logic exactly —
 *
 * - target missing → `create`
 * - target exists, not auto-updatable → `skip` (project-owned; the writer leaves it alone)
 * - target exists, auto-updatable, bytes identical → `skip`
 * - target exists, auto-updatable, bytes differ → `overwrite`
 *
 * `mtimeMs` is populated whenever the target exists. If a target's on-disk state cannot be
 * read (e.g. a permission error on a nested path), the entry is recorded as `skip` with a
 * `templateError` annotation and the loop continues, so one bad path never fails the whole tree.
 */
declare function planGeneratedFiles(projectRoot: string, files: GeneratedFile[]): OnboardingFileTreeEntry[];

declare function generateFeatureDevelopmentPolicy(domain: 'coding' | 'content'): GeneratedFile[];

declare function writeProjectProfile(projectRoot: string, profile: ProjectProfile): string;
declare function writeDetectionReport(projectRoot: string, report: DetectionReport): string;
declare function writeFrameworkMetadata(projectRoot: string, version: string): void;
/**
 * Read the existing onboarding manifest before a re-run (PQD-424).
 *
 * Returns `null` when no manifest exists yet (a first-time onboarding). When a
 * manifest is present but cannot be parsed as JSON, the local registry is
 * corrupt: rather than silently overwriting it or skipping it with no signal,
 * this throws a {@link FrameworkError} (`REGISTRY_CORRUPTED`) so onboarding
 * blocks adoption cleanly and the consumer can surface a precise message.
 */
declare function readExistingOnboardingManifest(projectRoot: string): OnboardingManifest | null;
declare function writeOnboardingManifest(projectRoot: string, manifest: OnboardingManifest): string;
/**
 * Writes a JSON document but, if the destination already exists and the
 * payload is byte-equal except for the timestamp field, preserves the existing
 * timestamp. Makes re-runs idempotent when nothing meaningful changed.
 */
declare function writeJsonPreservingTimestamp<T extends object>(path: string, value: T, timestampFields: (keyof T & string) | readonly string[]): void;
declare function writeFrameworkVersionPreservingTimestamp(path: string, version: string, now: string): void;
declare function resolveFrameworkInstallPath(): string;
declare function sanitizeStackSnapshotRepository<T extends {
    repository?: RepositoryContext;
}>(projectRoot: string, snapshot: T): T;

interface RagSelection {
    enabled: boolean;
    provider?: EmbeddingProviderName;
    model?: string;
}

interface OnboardingOptions {
    projectRoot: string;
    runtimeRoot?: string;
    adapters?: AdapterType[];
    profileOverrides?: Partial<ProjectProfile>;
    selections?: {
        providers?: AdapterType[];
        /**
         * Programmatic escape hatch for non-CLI callers. The CLI intentionally does not expose a
         * direct `--domain` override because domain selection is inferred from stack choice.
         */
        domain?: 'coding' | 'content';
        stack_profile?: ProjectProfile['stack_profile'];
        stack?: Stack;
        capabilities?: Capability[];
        rag?: RagSelection;
    };
    /**
     * Invoked after the project is fully written to disk and before the optional RAG phase runs.
     * Lets the CLI print the success banner while RAG (which may prompt or hang) executes after.
     * Invariant: by the time this fires, every core `.paqad/**` artifact already exists. See #62.
     */
    onPhase1Complete?: (result: OnboardingOutput) => void;
    /**
     * PQD-424 (AC2) — when `true`, regenerate every artifact even if it already exists, including
     * the external-agent entry files (`CLAUDE.md`, `AGENTS.md`, …) that are otherwise left untouched
     * on a re-run. Defaults to `false`: existing files are not overwritten without this explicit opt-in.
     */
    forceOverwrite?: boolean;
    /**
     * PQD-424 — workspace governance applied before any disk write. When
     * `project_creation_disabled` is `true`, `run()` refuses cleanly (throws a `FrameworkError`
     * coded `PROJECT_CREATION_DISABLED`) without touching the filesystem.
     */
    workspacePolicy?: {
        project_creation_disabled?: boolean;
    };
}
declare class OnboardingOrchestrator {
    /**
     * Two-phase onboarding. Phase 1 generates and writes every core artifact deterministically,
     * with no inquirer prompts. Phase 2 is the optional RAG opt-in: it can prompt, fail, or hang
     * and the project is still fully onboarded. See issue #62 for the regression this protects.
     */
    run(options: OnboardingOptions): Promise<OnboardingOutput>;
    /**
     * Read-only preview of onboarding (PQD-103). Runs the same deterministic file-planning
     * pipeline as Phase 1 of {@link run} — detector, introspector, resolver, adapter loop, rule
     * generator, reference guides, hook script read — collecting `GeneratedFile[]` in memory, then
     * classifies each target with {@link planGeneratedFiles} instead of writing it.
     *
     * Nothing is written to disk: no `writeFileSync`, no `bootstrapFramework`, no
     * `DecisionStore.initialize`, and crucially no `checkAndMigrateSchema` (which would migrate
     * the `.paqad/` layout). The caller (the desktop UI) uses the returned tree to render a
     * "this is what will be created / overwritten / skipped" confirmation panel before committing.
     *
     * @throws {ValidationError} if `projectRoot` is missing, unreadable, or not a directory. No
     *   partial {@link OnboardingPreviewResult} is returned in that case.
     */
    preview(options: OnboardingOptions): Promise<OnboardingPreviewResult>;
    /**
     * Validate that a path exists, is readable, and is a directory. Throws a stable
     * {@link ValidationError} (code `VALIDATION_ERROR`) otherwise — the consumer distinguishes
     * this from a generic failure to show the right copy.
     */
    private assertReadableDirectory;
    /**
     * Build the in-memory `GeneratedFile[]` list exactly as Phase 1 of {@link run} does, with no
     * side effects. Kept separate from `run` so `run`'s write path stays untouched (PQD-103
     * additive-only safeguard). Returns any non-fatal warnings collected while planning.
     */
    private collectGeneratedFiles;
}

interface OnboardingSelections {
    providers: AdapterType[];
    domain: Domain;
    stack_profile: DetectedStackProfile;
    stack?: Stack;
    capabilities?: string[];
}
type SnapshotContext = {
    toolchains: ToolchainInfo[];
    packages: InstalledPackage[];
    profile: DetectedStackProfile;
};
declare function resolveSelections(detection: DetectionReport, snapshotOrOverrides?: SnapshotContext | Partial<OnboardingSelections>, maybeOverrides?: Partial<OnboardingSelections>): Promise<OnboardingSelections>;
declare function getStackPromptChoices(domain: Domain): Array<{
    name: string;
    value: Stack;
}>;
declare function renderStackConfirmationSummary(detection: DetectionReport, snapshot: SnapshotContext | undefined, selections: OnboardingSelections): string;

interface ModuleFeatureEntry {
    name: string;
    slug: string;
    auto_update_feature_name: boolean;
    derivation: 'user' | 'locked_manifest' | 'codebase_native' | 'inferred' | 'llm';
    confidence: 'high' | 'medium' | 'low';
    source_paths: string[];
}
interface ModuleMapEntry {
    name: string;
    slug: string;
    auto_update_module_name: boolean;
    derivation: 'user' | 'locked_manifest' | 'codebase_native' | 'inferred' | 'llm';
    confidence: 'high' | 'medium' | 'low';
    source_paths: string[];
    evidence: {
        routes?: string[];
        tables?: string[];
        symbols?: string[];
    };
    features: ModuleFeatureEntry[];
}
interface ModuleMap {
    version: number;
    last_updated_at: string;
    domain_glossary: {
        preferred_terms: string[];
        synonyms: Record<string, string>;
        notes: string;
    };
    modules: ModuleMapEntry[];
}
declare function generateInitialRegistries(projectRoot: string): Promise<GeneratedFile[]>;
declare function discoverModules(projectRoot: string): Promise<string[]>;
declare function discoverBusinessModules(projectRoot: string, 
/** Explicit module names extracted from the user's request text. These are added with
 *  high confidence before any directory or signal discovery runs. */
hintModuleNames?: string[]): Promise<ModuleMapEntry[]>;
declare function generateModuleMapYaml(projectRoot: string, hintModuleNames?: string[]): Promise<string>;
/**
 * Serialises a ModuleMap to YAML. Uses the `yaml` package so that all fields
 * (glossary synonyms, evidence, features) are written correctly and the output
 * is round-trippable through `loadModuleMap`.
 */
declare function serializeModuleMap(map: ModuleMap): string;
declare function loadModuleMap(projectRoot: string): Promise<ModuleMap | null>;
declare function writeModuleMap(projectRoot: string, yaml: string): Promise<void>;

declare function generateDocumentationScaffold(moduleNames?: string[]): Promise<GeneratedFile[]>;
declare function generateModuleScaffold(moduleName: string): Promise<GeneratedFile[]>;

type SkillAuditEventType = 'skill.load_failed' | 'skill.pack_load_failed';
/** Emitted when a single SKILL.md fails frontmatter validation and is excluded. */
interface SkillLoadFailedEvent {
    ts: string;
    type: 'skill.load_failed';
    /** Absolute path to the malformed SKILL.md file. */
    path: string;
    /** Stable sub-code identifying which validation rule fired. */
    validation_error_code: string;
    /** Human-readable summary (the ValidationError message). */
    message: string;
    /** Always null — a malformed file never enters the registry under an id. */
    skill_id: null;
    /** SHA-256 hex of the file bytes, for consumer-side de-duplication. */
    content_hash: string;
}
/** Emitted when a pack is quarantined (missing or invalid pack.yaml). */
interface SkillPackLoadFailedEvent {
    ts: string;
    type: 'skill.pack_load_failed';
    /** Manifest name, or the last path segment when the id is unrecoverable. */
    pack_id: string;
    /** Absolute path to the pack root directory. */
    pack_path: string;
    /** Stable code identifying the failure class. */
    validation_error_code: string;
    /** Count of error-level validation issues that caused the quarantine. */
    issue_count: number;
    /**
     * SHA-256 hex of the pack.yaml bytes, or of the pack-root path string when the
     * manifest is absent (nothing to hash), for consumer-side de-duplication.
     */
    content_hash: string;
}
type SkillAuditEvent = SkillLoadFailedEvent | SkillPackLoadFailedEvent;
/**
 * Default capacity of the bounded in-process buffer. No canonical "spec 10
 * event-bus contract" document was found in the engine repo (PQD-194 §8 Q1), so
 * the rule is established locally and documented here: hold at most this many
 * undelivered events, dropping the oldest when full.
 */
declare const DEFAULT_SKILL_AUDIT_BUFFER_CAPACITY = 50;
/**
 * Bounded, in-process buffer for audit events that could not be written to disk
 * (no `projectRoot` available, or a disk write failed). Oldest events are
 * dropped when capacity is exceeded; a later {@link flush} delivers the survivors
 * in emission order. A module-level singleton (see
 * {@link getSharedSkillAuditBuffer}) is used by both loaders so buffered events
 * survive across the short-lived loader instances callers create per load pass.
 */
declare class SkillAuditBuffer {
    private readonly capacity;
    private readonly events;
    constructor(capacity?: number);
    /** Number of events currently buffered (undelivered). */
    get size(): number;
    /** Add an event, dropping the oldest if at capacity. */
    add(event: SkillAuditEvent): void;
    /** A copy of the currently buffered events, oldest first. */
    snapshot(): SkillAuditEvent[];
    /**
     * Deliver every buffered event to disk in emission order, then clear them. An
     * event whose write throws is re-buffered (and may again drop the oldest) so a
     * transient disk fault never loses more than capacity allows.
     */
    flush(projectRoot: string): void;
}
/** The process-wide buffer shared by the skill and pack loaders. */
declare function getSharedSkillAuditBuffer(): SkillAuditBuffer;
/** Synchronously append one audit event as a JSONL line. */
declare function appendSkillAuditEvent(projectRoot: string, event: SkillAuditEvent): void;
/**
 * Emit an audit event: when a `projectRoot` is known, flush the buffer (so any
 * previously buffered events are delivered first, preserving order) and persist
 * this one; otherwise hold it in the buffer for a later flush. A disk fault
 * leaves the event safely buffered.
 */
declare function emitSkillAuditEvent(event: SkillAuditEvent, projectRoot: string | undefined, buffer?: SkillAuditBuffer): void;
/** Read all audit events from disk; malformed lines are skipped. */
declare function readSkillAuditEvents(projectRoot: string): SkillAuditEvent[];

interface StackPackLoaderOptions {
    runtimeRoot: string;
    globalPacksRoot?: string;
    projectRoot?: string;
}
declare class StackPackLoader {
    private readonly auditBuffer;
    private readonly validator;
    constructor(auditBuffer?: SkillAuditBuffer);
    load(options: StackPackLoaderOptions): PackRegistry;
    validatePack(packRoot: string, source?: PackInstallSource): LoadedStackPack;
    private resolvePacksRoot;
    private loadPacksFromRoot;
    private readPack;
}

interface PackManagerRoots {
    runtimeRoot: string;
    globalPacksRoot: string;
    projectPacksRoot: string;
    registryUrl?: string;
}
interface ListedPack {
    name: string;
    effective_source: PackInstallSource;
    available_sources: PackInstallSource[];
    override_active: boolean;
    matched_in_project: boolean;
    display_name: string;
    tier: 'framework' | 'archetype';
}
interface InstallPackOptions {
    projectRoot?: string;
    scope?: 'global' | 'project';
    roots?: Partial<PackManagerRoots>;
}
interface CreatePackOptions {
    destinationRoot?: string;
    ecosystem?: string;
    tier?: 'framework' | 'archetype';
}
declare function resolvePackManagerRoots(projectRoot?: string, overrides?: Partial<PackManagerRoots>): PackManagerRoots;
declare function listPacks(projectRoot?: string, overrides?: Partial<PackManagerRoots>): ListedPack[];
declare function installPack(source: string, options?: InstallPackOptions): Promise<LoadedStackPack>;
declare function removePack(name: string, projectRoot?: string, scope?: 'global' | 'project', overrides?: Partial<PackManagerRoots>): void;
declare function validatePackAt(path: string): LoadedStackPack;
declare function createPack(name: string, options?: CreatePackOptions): string;

declare function loadProjectPackRegistry(projectRoot?: string): PackRegistry;
declare function getPacksForFrameworks(frameworks: string[], projectRoot?: string): LoadedStackPack[];
declare function getPackManifestMap(frameworks: string[], projectRoot?: string): Map<string, StackPackManifest>;
declare function getPackTestRunners(frameworks: string[], projectRoot?: string): StackPackTestRunner[];

interface OsvVulnerabilityRecord {
    package_name: string;
    ecosystem: string;
    version: string;
    advisory_id: string;
    summary: string;
    details: string;
}
declare function queryOsv(packages: InstalledPackage[]): Promise<OsvVulnerabilityRecord[]>;

interface EnsurePentestRunOptions {
    projectRoot: string;
    workflow: PentestWorkflowName;
    sourceReportPath?: string | null;
    targetUrl?: string | null;
    steps: Array<Pick<PentestRunStep, 'id' | 'title'>>;
}
declare class PentestProgressTracker {
    private readonly validator;
    constructor(validator?: SchemaValidator);
    ensureRun(options: EnsurePentestRunOptions): Promise<PentestRunProgress>;
    load(projectRoot: string, runId: string): Promise<PentestRunProgress | null>;
    save(projectRoot: string, progress: PentestRunProgress): Promise<void>;
    markStepRunning(progress: PentestRunProgress, stepId: string, inputHash: string): void;
    markStepCompleted(progress: PentestRunProgress, stepId: string, artifactPaths: string[], skillNames: string[]): void;
    markStepBlocked(progress: PentestRunProgress, stepId: string, error: string, artifactPaths: string[], skillNames: string[]): void;
    markStepFailed(progress: PentestRunProgress, stepId: string, error: string, artifactPaths: string[], skillNames: string[]): void;
    markRunCompleted(progress: PentestRunProgress, reportPath: string, sidecarPath: string, findingIds: string[]): void;
    shouldSkipStep(progress: PentestRunProgress, stepId: string, inputHash: string): boolean;
    private findIncompleteRun;
    private resetRunningSteps;
    private findStep;
}
declare function runArtifactsDir(projectRoot: string, runId: string): string;
declare function runLogsDir(projectRoot: string, runId: string): string;
declare function runStatusForSteps(steps: PentestRunStep[]): PentestRunStatus;

interface ProjectScriptResult {
    script: string;
    status: 'completed' | 'blocked' | 'failed';
    artifact_paths: string[];
    exit_code: number | null;
    summary: string;
}
interface ModuleDocEvidence {
    module: string;
    paths: string[];
    content: string;
}
interface TestEvidence {
    path: string;
    content: string;
}
interface SuspiciousRoute {
    path: string;
    status: number;
    kind: string;
}
declare function toLocalTimestamp(date: Date): string;
declare function slugify(value: string): string;
declare function writeJson(target: string, data: unknown): Promise<void>;
declare function readJsonIfExists<T>(target: string): Promise<T | null>;
declare function hashRelevantInputs(projectRoot: string, workflow: PentestWorkflowName, extra?: Record<string, string | string[] | null | undefined>): Promise<string>;
declare function discoverTargetUrl(projectRoot: string, stack: string, explicit?: string): Promise<string | null>;
declare function runProjectScript(projectRoot: string, scriptName: string, env: Record<string, string>, logDir: string): Promise<ProjectScriptResult>;
declare function loadModuleDocs(projectRoot: string, focusModules?: string[]): Promise<ModuleDocEvidence[]>;
declare function loadTests(projectRoot: string, focusModules?: string[]): Promise<TestEvidence[]>;
declare function parseSuspiciousRoutes(runtimeChecks: Array<{
    path: string;
    status: number;
}>): SuspiciousRoute[];
declare function summarizeCommandAvailability(scriptResults: ProjectScriptResult[]): string[];
declare function inferSourceArtifacts(baseDir: string, scriptResults: ProjectScriptResult[]): string[];
declare function skillPath(name: string): string;
declare function toolReferencePath(stack: string): string;
declare function toReportId(prefix: 'PENTEST' | 'RETEST', date: Date): string;
declare function extractRelevantTestPaths(tests: TestEvidence[], moduleName: string, keywords: string[]): string[];
declare function parseSecretMatches(content: string): string[];
declare function safeBaseName(path: string): string;

interface ClassifierInput {
    request: string;
    profile?: Pick<ProjectProfile, 'active_capabilities' | 'intelligence' | 'stack_profile' | 'routing'>;
    resolved_workflow?: {
        workflow: ClassificationWorkflow | null;
        custom_workflow_name?: string | null;
        workflow_source?: WorkflowSource;
        workflow_reason?: string | null;
        matched_rule?: string | null;
    };
}
interface RequestClassifierOptions {
    projectRoot?: string;
}
declare class RequestClassifier {
    private readonly projectRoot?;
    constructor(options?: RequestClassifierOptions);
    classify(input: ClassifierInput): Promise<ClassificationResult>;
    /**
     * Resolve the analytics tag (issue #241). Returns undefined (no field, no fs scan) when
     * there is no project root or the `analytics_instrumentation` flag is off — the common
     * case. Only when the flag is on do we run the gate (which then detects a provider).
     * Best-effort: any config/detection failure yields undefined, never a thrown classify.
     */
    private resolveAnalyticsTag;
}

declare function computeClassificationConfidence(resolutionMap: ResolutionMap): number;

interface ContextBudgetEstimateInput {
    scope: ClassificationScope;
    delta_candidate: boolean;
    workflow: ClassificationWorkflow | null;
}
declare function estimateContextBudgetHint(input: ContextBudgetEstimateInput): ContextBudgetHint;

interface DeltaDetectionResult {
    delta_candidate: boolean;
    base_manifest_slug: string | null;
    prior_requirement_count: number | null;
    prior_criterion_count: number | null;
}
declare function detectDeltaCandidate(root: string, affectedModules: string[]): Promise<DeltaDetectionResult>;

interface ImpactResolutionInput {
    requestText: string;
    modulePaths: string[];
}
interface ImpactResolutionResult {
    database_impact: ClassificationResult['database_impact'];
    api_impact: ApiImpact;
    ui_impact: UiImpact;
    compliance_sensitivity: ComplianceSensitivity;
    customer_facing_impact: CustomerFacingImpact;
    reversibility: Reversibility;
    data_sensitivity: DataSensitivity;
    /** Tracks how each dimension was resolved so callers can populate ResolutionMap accurately. */
    resolution_sources: Record<'database_impact' | 'api_impact' | 'ui_impact' | 'compliance_sensitivity' | 'customer_facing_impact' | 'reversibility' | 'data_sensitivity', ResolutionSource>;
}
declare function resolveImpacts(input: ImpactResolutionInput): ImpactResolutionResult;

declare function shouldSkipLlm(preResult: PreClassificationResult, confidence: number, requestText: string, resolutionMap: ResolutionMap): boolean;

interface ModuleResolutionResult {
    modules: AffectedModule[];
    source: string;
}
declare class ModuleResolver {
    private readonly root;
    private readonly profile?;
    constructor(root: string, profile?: Pick<ProjectProfile, "intelligence" | "stack_profile"> | undefined);
    resolve(requestText: string): Promise<ModuleResolutionResult>;
    private resolveExplicitPaths;
    private tryResolveByBasename;
    private resolveSymbols;
    private resolveRagMatches;
    private resolveHeuristicModules;
}

declare class PostClassifier {
    private readonly projectRoot?;
    constructor(projectRoot?: string | undefined);
    adjust(classification: ClassificationResult, _preResult: PreClassificationResult, resolutionMap: ResolutionMap): Promise<PostClassificationAdjustments>;
    private computeRiskFloor;
    private readDefectStats;
    private computeComplexityAdjustment;
    private writeHistory;
}

interface PreClassifierInput {
    request: string;
    profile?: Pick<ProjectProfile, 'intelligence' | 'stack_profile'>;
    resolved_workflow?: {
        workflow: ClassificationWorkflow | null;
    };
    projectRoot?: string;
}
declare class PreClassifier {
    private readonly projectRoot;
    constructor(projectRoot?: string);
    classify(input: PreClassifierInput): Promise<PreClassificationResult>;
}

declare const LANE_PHASES: Record<Lane, PipelinePhase[]>;
declare class PipelineRouter {
    route(classification: ClassificationResult): {
        lane: Lane | null;
        phases: PipelinePhase[];
        route_reason?: string | null;
    };
}

declare function matchRuleTriggers(root: string, modulePaths: string[]): Promise<string[]>;
/**
 * A rule "always loads" when it declares no scoped trigger: an explicit `**`
 * pattern, or no patterns at all. These apply to every change regardless of which
 * files are in play (RAG buildout F5).
 */
declare function isAlwaysLoadRule(rule: Pick<CompiledRule, 'trigger_patterns'>): boolean;
/**
 * True when any of `paths` matches any of the rule's trigger patterns. Used to
 * decide whether a scoped rule's full text should be loaded for the files in
 * play. Always-load rules are handled separately by {@link isAlwaysLoadRule}.
 */
declare function ruleTriggersMatch(rule: Pick<CompiledRule, 'trigger_patterns'>, paths: readonly string[]): boolean;
declare function matchesGlobish(value: string, pattern: string): boolean;

interface ScopeResolutionResult {
    scope: ClassificationScope;
    scope_graph_depth: number;
}
declare function resolveScope(root: string, modulePaths: string[]): Promise<ScopeResolutionResult>;
declare function toProjectRelativeModule(root: string, filePath: string): string;

/**
 * In-memory registry of skills registered at runtime (e.g. from an in-app skill
 * editor or a marketplace install) without restarting the agent process. The
 * store is ephemeral — entries are lost on restart, matching the ticket's
 * "without restarting" intent.
 *
 * Built-in skills are passed at construction and never mutated. A runtime entry
 * whose name collides with a built-in is refused so the built-in remains the
 * default match; the runtime entry would otherwise live under a `runtime:<name>`
 * namespaced identifier.
 *
 * Snapshot isolation: {@link register} validates and stores in a single
 * synchronous turn with no `await` between parse and `Map.set`, and
 * {@link snapshot} returns a freshly composed array each call. A caller that
 * captured a snapshot before a later `register()` therefore sees a stable set.
 */
declare class RuntimeSkillRegistry {
    private readonly builtIns;
    private readonly builtInNames;
    private readonly runtime;
    private readonly parser;
    constructor(builtIns: readonly LoadedSkill[]);
    /**
     * Parses and registers a SKILL.md markdown string. Returns the stored
     * {@link LoadedSkill}. Throws {@link SkillRegistrationError} with
     * `kind: 'malformed'` on a parse failure, or `kind: 'duplicate'` when the
     * name collides with a built-in (carrying both ids) or an existing runtime
     * entry. Validation and storage happen synchronously with no async gap.
     */
    register(content: string, sourceLabel?: string): LoadedSkill;
    /**
     * Removes a runtime-registered skill by its `runtime:<name>` identifier.
     * Throws {@link SkillRegistrationError} with `kind: 'built-in-protected'` when
     * the identifier names a built-in, or `kind: 'not-found'` when no runtime
     * entry matches.
     */
    remove(runtimeId: string): void;
    /**
     * Returns an immutable, freshly composed listing of built-ins (first, sorted
     * by name) followed by runtime entries (sorted by name), each tagged with its
     * `id` and `source`.
     */
    snapshot(): readonly RuntimeSkillListEntry[];
}

interface WorkflowRouteResult {
    workflow: ClassificationWorkflow | null;
    custom_workflow_name?: string | null;
    workflow_source: WorkflowSource;
    workflow_reason?: string | null;
    matched_rule?: string | null;
}
interface WorkflowRouterServiceOptions {
    projectRoot?: string;
    runtimeRoot?: string;
    /** Optional registry of runtime-registered skills to merge into routing. */
    runtimeRegistry?: RuntimeSkillRegistry;
}
declare class WorkflowRouterService {
    private readonly projectRoot;
    private readonly runtimeRoot;
    private readonly runtimeRegistry?;
    private readonly parser;
    constructor(options?: WorkflowRouterServiceOptions);
    resolve(requestText: string, profile?: Pick<ProjectProfile, 'active_capabilities' | 'stack_profile' | 'routing'> | null): Promise<WorkflowRouteResult>;
    private loadRoutingSkills;
    private projectSkillArtifacts;
}

declare const TIER_TOKEN_LIMITS: Record<SkillModelTier, number>;
interface TruncationResult {
    output: string;
    truncated: boolean;
    original_token_estimate: number;
    final_token_estimate: number;
}
declare class StreamTruncator {
    private readonly projectRoot;
    constructor(projectRoot: string);
    truncate(output: string, tier: SkillModelTier, maxOutputTokensOverride?: number): TruncationResult;
    logTruncation(skillName: string, result: TruncationResult): Promise<void>;
    estimateTokens(text: string): number;
    private truncateAtSentenceBoundary;
}

declare const ARTIFACT_TYPES: readonly ["rules", "skills", "agents", "hooks", "templates", "patterns", "anti-patterns", "checklists", "mcp-configs"];
type ArtifactType = (typeof ARTIFACT_TYPES)[number];
type CollisionBehavior = 'most-specific-wins' | 'additive-merge';
declare const COLLISION_MAP: Record<ArtifactType, CollisionBehavior>;
declare const ARTIFACT_OUTPUT_KEYS: {
    readonly rules: "rules";
    readonly skills: "skills";
    readonly agents: "agents";
    readonly hooks: "hooks";
    readonly templates: "templates";
    readonly patterns: "patterns";
    readonly 'anti-patterns': "antiPatterns";
    readonly checklists: "checklists";
    readonly 'mcp-configs': "mcpConfigs";
};

declare function resolveCapabilityDirectories(runtimeRoot: string, stack: string, capabilities: string[], artifactType: ArtifactType): string[];

interface DeduplicatorArtifact {
    path: string;
    content?: string;
    type: string;
}
declare class ContextDeduplicator {
    private readonly contentHashMap;
    deduplicate(projectRoot: string, artifacts: DeduplicatorArtifact[]): Promise<{
        artifacts: DeduplicatorArtifact[];
        references: Map<string, string>;
        stats: DeduplicationStats;
    }>;
    reset(): void;
    private readContent;
    private computeHash;
    private persistStats;
}

interface InheritanceDirectory {
    path: string;
    level: 0 | 1 | 2 | 3 | 4 | 5 | 6;
    source: string;
}
declare function getInheritanceDirectories(runtimeRoot: string, routing: RoutingConfig, artifactType: ArtifactType): InheritanceDirectory[];

interface ResolverOptions {
    runtimeRoot: string;
}
declare class Resolver {
    readonly runtimeRoot: string;
    constructor(options: ResolverOptions);
    resolve(routing: RoutingConfig, deduplicator?: ContextDeduplicator): Promise<ResolvedArtifacts>;
    resolveArtifactType(routing: RoutingConfig, artifactType: ArtifactType): Promise<ResolvedArtifact$1[]>;
}

declare function appendRagAudit(projectRoot: string, level: 'INFO' | 'WARN', event: string, fields?: Record<string, unknown>): void;

interface RagBenchmarkSnapshot {
    hit_at_5: number;
    task_success_rate: number;
    correction_turns: number;
    prompt_tokens_sent: number;
    task_count: number;
    reranking?: {
        enabled: boolean;
        backend: string;
        candidate_pool_size: number;
        packed_size: number;
        latency_ms: number;
    };
    action_quality?: {
        workflow_correctness_pct: number;
        evidence_grounding_pct: number;
        noisy_suggestion_rate: number;
    };
}
interface RagBenchmarkMetricResult {
    passed: boolean;
    delta_pct: number;
    threshold_pct: number;
    summary: string;
    baseline_zero?: boolean;
}
interface RagPromptTokenGateResult extends RagBenchmarkMetricResult {
    override_passed: boolean;
    success_delta_pct: number;
}
interface RagBenchmarkEvaluation {
    passed: boolean;
    baseline: RagBenchmarkSnapshot;
    candidate: RagBenchmarkSnapshot;
    gates: BenchmarkGateConfig;
    metrics: {
        hit_at_5: RagBenchmarkMetricResult;
        task_success_rate: RagBenchmarkMetricResult;
        correction_turns: RagBenchmarkMetricResult;
        prompt_tokens_sent: RagPromptTokenGateResult;
    };
}
interface ConfigurationComparisonResult {
    mode: ComparisonMode;
    evaluation: RagBenchmarkEvaluation;
}
declare function compareConfigurations(baseline: RagBenchmarkSnapshot, candidate: RagBenchmarkSnapshot, mode: ComparisonMode, gates?: BenchmarkGateConfig): ConfigurationComparisonResult;
declare function evaluateBenchmarkGates(baseline: RagBenchmarkSnapshot, candidate: RagBenchmarkSnapshot, gates?: BenchmarkGateConfig): RagBenchmarkEvaluation;

interface RagIgnoreConfig {
    version: 1;
    exclude: string[];
    include: string[];
    additional_extensions: string[];
    additional_basename_includes: string[];
    additional_named_file_exclusions: string[];
    use_project_ignore_files: boolean;
    use_global_gitignore: boolean;
}
interface FilterDiagnostics {
    extensionAllowlist: string[];
    namedBasenameIncludes: string[];
    directoryExclusionSet: string[];
    hardNamedFileExclusionSet: string[];
}
interface FileProbeResult {
    path: string;
    excluded: boolean;
    layer?: 1 | 2 | 3 | 4;
    rule?: string;
}
interface FilterStats {
    total_discovered: number;
    excluded_layer1: number;
    excluded_layer2: number;
    excluded_layer3: number;
    excluded_layer4: number;
    passed: number;
}
interface RagFileFilterOptions {
    projectRoot: string;
    packs: LoadedStackPack[];
    intelligence?: Partial<IntelligenceConfig>;
}
declare class RagFileFilter {
    private readonly options;
    private readonly ragConfig;
    private readonly extensionAllowlist;
    private readonly namedBasenameIncludes;
    private readonly directoryExclusionSet;
    private readonly hardNamedFileExclusionSet;
    private readonly adapterFileExclusionSet;
    private readonly diagnosticsSnapshot;
    private _layer3RulesCache;
    constructor(options: RagFileFilterOptions);
    discoverFiles(onProgress?: (update: ProviderProgressUpdate) => void): Promise<string[]>;
    filterDiagnostics(): FilterDiagnostics;
    probeFile(absolutePath: string): Promise<FileProbeResult>;
    private getLayer3Rules;
    previewIndex(): Promise<string[]>;
    private evaluateFile;
    private evaluateLayer3;
    private evaluateLayer4;
}

declare class LocalEmbeddingProvider implements EmbeddingProvider {
    private readonly onProgress?;
    readonly name: "local";
    readonly model: string;
    private extractorPromise?;
    constructor(intelligence: IntelligenceConfig, onProgress?: ((update: ProviderProgressUpdate) => void) | undefined);
    validate(): Promise<void>;
    embed(input: string | string[]): Promise<number[][]>;
    private getExtractor;
    private loadExtractor;
}
declare class OpenAiEmbeddingProvider implements EmbeddingProvider {
    private readonly projectRoot;
    private readonly onProgress?;
    readonly name: "openai";
    readonly model: string;
    private clientPromise?;
    constructor(projectRoot: string, intelligence: IntelligenceConfig, onProgress?: ((update: ProviderProgressUpdate) => void) | undefined);
    validate(): Promise<void>;
    embed(input: string | string[]): Promise<number[][]>;
    private getClient;
    private createClient;
}
declare class VoyageEmbeddingProvider implements EmbeddingProvider {
    private readonly projectRoot;
    private readonly onProgress?;
    readonly name: "voyageai";
    readonly model: string;
    private clientPromise?;
    constructor(projectRoot: string, intelligence: IntelligenceConfig, onProgress?: ((update: ProviderProgressUpdate) => void) | undefined);
    validate(): Promise<void>;
    embed(input: string | string[]): Promise<number[][]>;
    private getClient;
    private createClient;
}
declare function createEmbeddingProvider(projectRoot: string, intelligence: IntelligenceConfig, onProgress?: (update: ProviderProgressUpdate) => void): Promise<EmbeddingProvider>;

declare function readProjectSecrets(projectRoot: string): Record<string, string>;
declare function getProjectSecret(projectRoot: string, key: string): string | undefined;
declare function writeProjectSecret(projectRoot: string, key: string, value: string): string;
declare function removeProjectSecrets(projectRoot: string): void;
declare function getSecretPermissionWarning(projectRoot: string): string | null;
declare function redactSecrets(input: string, projectRoot: string): string;

/** Default maximum number of chunks the backlog holds before dropping the oldest. */
declare const DEFAULT_CRS_BACKLOG_CAP = 1000;
/** Persist a batch of backlogged chunks for one collection (embed + write). */
type CrsBacklogPersist = (collectionId: CrsCollectionId, chunks: CrsChunkInput[]) => Promise<void>;
declare class CrsBacklogQueue {
    private readonly cap;
    private readonly entries;
    constructor(cap?: number);
    /** Number of chunks currently parked across all collections. */
    get size(): number;
    /**
     * Park `chunks` for `collectionId`. If the resulting size exceeds the cap, the
     * oldest entries are dropped to bring it back to the cap and an
     * {@link EmbeddingBacklogOverflow} is thrown carrying the number dropped.
     */
    enqueue(chunks: CrsChunkInput[], collectionId: CrsCollectionId): void;
    /**
     * Flush the backlog oldest-first, grouped per collection, through `persist`.
     * A group that persists successfully is removed; if `persist` throws, that
     * group (and the rest) stay queued and the error propagates so the caller can
     * retry on the next recovery.
     */
    drain(persist: CrsBacklogPersist): Promise<void>;
}

declare class RagService {
    private readonly projectRoot;
    private readonly providerFactory;
    /**
     * In-memory write backlog for CRS collections (PQD-415). Injectable so a
     * caller can size the cap or observe `.size`; defaults to a fresh queue at the
     * 1000-chunk cap.
     */
    private readonly crsBacklog;
    private readonly vectorIndex;
    private readonly visionVectorIndex;
    private readonly chunker;
    private readonly indexManager;
    private readonly patternVectors;
    private readonly resumeValidator;
    private resumeValidationPromise?;
    constructor(projectRoot: string, providerFactory?: ProviderFactory, 
    /**
     * In-memory write backlog for CRS collections (PQD-415). Injectable so a
     * caller can size the cap or observe `.size`; defaults to a fresh queue at the
     * 1000-chunk cap.
     */
    crsBacklog?: CrsBacklogQueue);
    getStatus(): Promise<RagStatus>;
    configureAndBuild(partial: Partial<BuildIndexOptions['intelligence']>, onProgress?: BuildIndexOptions['onProgress']): Promise<RagStatus>;
    /**
     * Rebuild the RAG index from the ALREADY-RESOLVED framework config WITHOUT persisting the
     * project profile or the local `.config` (issue #576, Finding 3). `paqad-ai join` uses this: a
     * teammate's machine must leave the tracked `project-profile.yaml` and the dev-local `.config`
     * exactly as the team committed them — configureAndBuild rewrites both, which produced a
     * "tracked files changed" diff and let a local `rag_*` key shadow a later team change. This runs
     * the same shared build core (rebuild + pattern vectors + audit); it only skips the two writes.
     */
    buildIndexOnly(partial: Partial<BuildIndexOptions['intelligence']>, onProgress?: BuildIndexOptions['onProgress']): Promise<RagStatus>;
    /** Shared build core for {@link configureAndBuild} and {@link buildIndexOnly}: normalize the
     *  config, rebuild the index, refresh the pattern vectors, and audit — no profile/config write. */
    private buildIndexCore;
    rebuild(options?: BuildIndexOptions): Promise<void>;
    /**
     * Write the chunks embedded before cancellation to a resumable `.partial`
     * index and return its project-relative path (PQD-104). Returns undefined when
     * nothing was embedded (e.g. aborted before the provider was ready), in which
     * case no partial file is written.
     */
    private writePartialIndex;
    clear(): Promise<void>;
    refreshContext(): Promise<ChunkIndexSyncResult>;
    retrieve(syncResult: ChunkIndexSyncResult, input: {
        taskDescription?: string;
        keywords: string[];
        targetFilePath?: string;
        symbolReferences?: string[];
    }, topN?: number): Promise<RagRetrievalResult>;
    private retrieveWithSyncPolicy;
    /**
     * Run a single retrieval query for eval purposes without requiring an
     * externally-managed ChunkIndexSyncResult. Refreshes the index internally.
     */
    retrieveForEval(input: {
        taskDescription?: string;
        keywords: string[];
        targetFilePath?: string;
        symbolReferences?: string[];
    }, topN?: number): Promise<RagRetrievalResult>;
    /**
     * Embed the query, query the file + vision indexes over a widened pool, fuse the
     * dense and lexical (BM25) legs, optionally rerank, and return the top-`limit`
     * candidates with their scores — BEFORE any similarity/relief floor is applied.
     *
     * This is the single canonical scoring path (RULE-04a1): both floor-with-relief
     * retrieval ({@link retrieveWithSyncPolicy}) and the `probe` diagnostic call it, so
     * a probe reports exactly the scores retrieval sees. Assumes the index is present
     * and valid — callers check {@link getStatus} first.
     */
    private scoreCandidates;
    /**
     * Issue #354 diagnostic — return the top-`limit` scored candidates for a query
     * BEFORE the similarity/relief floor, so `paqad-ai rag probe` can show how far real
     * scores sit from the floor on a live repo (the gap that made retrieval dark).
     * Refreshes the index internally like {@link retrieveForEval}. Returns `[]` when rag
     * is off or the index is missing/invalid.
     */
    probe(input: {
        taskDescription?: string;
        keywords: string[];
        targetFilePath?: string;
        symbolReferences?: string[];
    }, topN?: number): Promise<RagScoredCandidate[]>;
    /**
     * Accept plain text a consumer extracted from an image (via OCR, captioning,
     * etc.) into the retrieval index. The engine never reads the image itself; it
     * validates the input, embeds the text, and stores it in a separate vision
     * vector index keyed to the image's `sourcePath`. Re-ingesting the same path
     * replaces its prior chunks rather than duplicating them.
     *
     * @throws {RagIngestError} with a stable `code` for each rejection case.
     */
    ingestExtractedText(input: VisionIngestInput): Promise<VisionIngestResult>;
    resolveApiKeyName(provider: 'openai' | 'voyageai'): 'OPENAI_API_KEY' | 'VOYAGE_API_KEY';
    storeApiKey(provider: 'openai' | 'voyageai', value: string): string;
    hasApiKey(provider: 'openai' | 'voyageai'): boolean;
    localModelPath(): string;
    localModelCached(model?: string): boolean;
    /**
     * Embed and persist a session's chunks into the named CRS collection, returning
     * the audit-grade {@link CrsIndexedSessionEvent} (also appended to the audit log
     * as `crs.indexed_session`). The collection is created on demand. Every stored
     * chunk carries its `source_session_id`, `source_workspace_id`, `created_at`,
     * `project_id`, and an engine-stamped `vector_timestamp`.
     *
     * If the embedding provider is unreachable, the chunks are parked in the
     * in-memory backlog and the failure is surfaced: an {@link EmbeddingBacklogOverflow}
     * when the 1000-chunk cap is exceeded (oldest dropped), otherwise the provider
     * error. On the next successful call the parked backlog is drained first.
     */
    writeChunks(chunks: CrsChunkInput[], collectionId: CrsCollectionId): Promise<CrsIndexedSessionEvent>;
    /**
     * Retrieve from a CRS collection by raw query string. Returns only hits at or
     * above `confidenceThreshold` (default 0.5 cosine similarity), ranked by
     * descending score, each carrying its session/workspace provenance. Propagates
     * {@link CorruptVectorIndexError} on a corrupt on-disk index so the desktop can
     * fall back to file-RAG and trigger a rebuild.
     */
    retrieveCrs(query: string, collectionId: CrsCollectionId, topK: number, confidenceThreshold?: number): Promise<CrsRetrievalResult[]>;
    /**
     * Rebuild a CRS collection against a new embedding provider/model side by side,
     * with zero downtime: the new index is built in a sibling `.rebuilding` dir,
     * progress is reported via `onProgress`, then the live and new indexes are
     * swapped atomically. The old index is retained under a `.revert.<ms>` sibling
     * for 24 hours; expired reverts are swept on the next reindex.
     */
    reindex(provider: EmbeddingProviderName, model: string, collectionId: CrsCollectionId, onProgress?: ReindexProgressHandler): Promise<void>;
    private persistCrsChunks;
    private embedCrsChunks;
    private embedCrsForReindex;
    /** Delete `.revert.<ms>` siblings older than the 24-hour retention window. */
    private sweepExpiredCrsReverts;
    /**
     * Reorder the fused hits with the configured reranker (RAG buildout F18). A fast
     * path returns the hits untouched when reranking is disabled (the default), so no
     * cross-encoder model is loaded unless a team opts in. The reranker only reorders:
     * the original hit objects (and their cosine scores) are reattached via
     * {@link reorderByRankedIds}. Any reranker error falls back to the input order so
     * retrieval never blocks on it.
     */
    private applyReranking;
    private syncVectorIndex;
    /**
     * Split externally-supplied text into chunks bounded by non-whitespace size,
     * mirroring {@link AstChunker.fallbackSplit}'s paragraph-buffer strategy.
     * Always returns at least one chunk for non-empty input.
     */
    private splitTextIntoChunks;
    private throwIfAborted;
    /**
     * Build the F24 contextualiser: a function that prepends the deterministic blurb
     * (path + enclosing signature + exported symbols + module-map role) to a chunk's
     * content. The module-role resolver is built once from the module map here, so the
     * per-chunk cost is a lookup, not a parse.
     */
    private buildEmbedContextualizer;
    private embedChunks;
    private discoverSourceFiles;
    private validateResumeState;
}
/**
 * The text BM25 indexes for a candidate (RAG buildout F24): the deterministic blurb
 * (path + signature + exported symbols, no module-map lookup at query time) prepended to
 * the content, so exact identifiers and paths the bare body omits are matchable. Falls
 * back to bare content when the chunk carries no source path (e.g. a vision chunk).
 */
declare function lexicalDocumentText(item: {
    id: string;
    content: string;
    source_file?: string;
    ast_node_path?: string;
    exported_symbols?: string[];
}): string;

declare class CorruptVectorIndexError extends Error {
    readonly kind: 'index' | 'meta';
    readonly filePath: string;
    readonly cause?: unknown | undefined;
    constructor(kind: 'index' | 'meta', filePath: string, cause?: unknown | undefined);
}
declare class FileVectorIndex<T extends StoredVectorItem = StoredVectorItem> {
    private readonly indexPath;
    private readonly metaPath;
    constructor(indexPath?: string, metaPath?: string);
    load(projectRoot: string): Promise<VectorIndexPayload<T> | null>;
    loadMeta(projectRoot: string): Promise<RagIndexMeta | null>;
    save(projectRoot: string, payload: VectorIndexPayload<T>, meta: RagIndexMeta): Promise<void>;
    clear(projectRoot: string): Promise<void>;
    query(projectRoot: string, vector: number[], topN: number): Promise<VectorQueryResult<T>[]>;
    status(projectRoot: string): Promise<{
        present: boolean;
        sizeBytes: number;
        meta: RagIndexMeta | null;
        corrupt: boolean;
        reason?: string;
    }>;
    replaceAll(projectRoot: string, items: T[], metaInput: Omit<RagIndexMeta, 'version' | 'chunk_count' | 'built_at' | 'embedding_dimensions' | 'branch' | 'base_branch' | 'base_commit' | 'head_commit'>, baseBranch?: string): Promise<RagIndexMeta>;
    /**
     * Idempotently create a CRS collection under `.paqad/crs/<escaped-id>/`. Writes
     * an empty index + meta only when neither file exists yet; a second call for the
     * same id is a no-op rather than an error and never overwrites existing data.
     */
    static create(projectRoot: string, collectionId: CrsCollectionId): Promise<void>;
    /**
     * Remove chunks from a CRS collection atomically and return the count purged.
     * With `{ sourceSessionId }`, only that session's chunks are removed and the
     * filtered index is rewritten in place; without options the whole collection
     * directory is deleted. A non-existent collection or session purges nothing and
     * returns `0` rather than throwing.
     */
    static destroy(projectRoot: string, collectionId: CrsCollectionId, options?: {
        sourceSessionId?: string;
    }): Promise<number>;
    private resolve;
    private resolveExistingIndexPath;
    private resolveLegacyIndexPath;
}

/**
 * Identifier for a single session's ephemeral attachment collection. Branded so
 * a raw `sessionId` cannot be passed where a collection id is expected without
 * going through {@link toEphemeralCollectionId}. The value is the session id
 * itself — the collection is bound 1:1 to the session that owns it.
 */
type EphemeralCollectionId = string & {
    readonly __brand: 'EphemeralCollectionId';
};
/**
 * Brand a session id as its collection id. The collection is keyed directly by
 * the session id, so this is an identity cast that documents intent.
 */
declare function toEphemeralCollectionId(sessionId: string): EphemeralCollectionId;
/** Lifecycle state of a session's attachment collection. */
type AttachmentRecordStatus = 'indexed' | 'stale' | 'in-progress';
/**
 * Persisted registry row mapping a session to its collection. The registry is
 * the source of truth the orphan sweep enumerates to find collections whose
 * owning session no longer exists.
 */
interface AttachmentRecord {
    sessionId: string;
    collectionId: EphemeralCollectionId;
    filePaths: string[];
    status: AttachmentRecordStatus;
}
/** Successful completion shape returned by {@link SessionAttachmentIndexer.index}. */
interface AttachmentIndexingResult {
    collectionId: EphemeralCollectionId;
    chunkCount: number;
    durationMs: number;
}
/**
 * Discriminated-union member returned (rather than thrown) when the embedding
 * provider stays unreachable through the initial attempt plus both retries. The
 * desktop reads `kind` to show a degraded-indexing warning while still allowing
 * the message to send without retrieval.
 */
interface AttachmentIndexingDegradedSignal {
    kind: 'attachment_indexing_degraded';
    sessionId: string;
    reason: string;
    retriesExhausted: boolean;
}
/** The union an indexing call resolves to: success or a structured degrade. */
type AttachmentIndexingOutcome = AttachmentIndexingResult | AttachmentIndexingDegradedSignal;
/** Narrowing guard for the degraded outcome. */
declare function isAttachmentIndexingDegraded(outcome: AttachmentIndexingOutcome): outcome is AttachmentIndexingDegradedSignal;
/** One record per collection purged by the boot-time orphan sweep. */
interface AttachmentOrphanPurgeRecord {
    collectionId: EphemeralCollectionId;
    purgedAt: string;
}

/** A `sessionId` whose collection path would escape the attachments root. */
declare class AttachmentPathError extends Error {
    readonly sessionId: string;
    constructor(sessionId: string, message: string);
}
/** Absolute path of the attachments root for a given project/storage root. */
declare function attachmentCollectionsRoot(projectRoot: string): string;
/**
 * Resolve the absolute collection directory for a session, asserting it stays
 * inside the attachments root. Throws {@link AttachmentPathError} for an empty
 * id or one that resolves outside the root (path traversal).
 */
declare function resolveCollectionDir(projectRoot: string, sessionId: string): string;
/**
 * Project-relative `index.json` / `meta.json` paths for a session's collection,
 * suitable for {@link FileVectorIndex}, which joins them onto `projectRoot`.
 * Resolution is validated via {@link resolveCollectionDir} first.
 */
declare function collectionVectorPaths(projectRoot: string, sessionId: string): {
    indexPath: string;
    metaPath: string;
};
/**
 * Record (or overwrite) the collection a session owns. Re-registering the same
 * session replaces its row so a reindex never duplicates the mapping.
 */
declare function registerCollection(projectRoot: string, sessionId: string, collectionId: EphemeralCollectionId, filePaths?: string[], status?: AttachmentRecord['status']): Promise<void>;
/** Remove a session's registry row. A no-op when the session is unknown. */
declare function deregisterCollection(projectRoot: string, sessionId: string): Promise<void>;
/** Every registered (sessionId, collectionId) pair. */
declare function listCollections(projectRoot: string): Promise<{
    sessionId: string;
    collectionId: EphemeralCollectionId;
}[]>;
/** The collection id registered for a session, or null when none exists. */
declare function getCollectionId(projectRoot: string, sessionId: string): Promise<EphemeralCollectionId | null>;

/** The three terminal outcomes an attachment-index call can record. */
type AttachmentEventKind = 'attachment.indexed' | 'attachment.index_failed' | 'attachment.format_rejected';
/** Which collection the attachment was (or would have been) written into. */
type AttachmentCollectionScope = 'project' | 'session';
/**
 * One recorded attachment-indexing event. `chunk_count` and `provider` are
 * present only on `attachment.indexed`; `reason` is present only on the two
 * failure kinds. `at` is an ISO-8601 timestamp stamped at write time.
 */
interface AttachmentEvent {
    kind: AttachmentEventKind;
    file_name: string;
    at: string;
    collection_scope?: AttachmentCollectionScope;
    session_id?: string;
    chunk_count?: number;
    provider?: string;
    reason?: string;
}
/** Event payload accepted by {@link appendAttachmentEvent} (timestamp optional). */
type AttachmentEventInput = Omit<AttachmentEvent, 'at'> & {
    at?: string;
};
/** A live sink the indexer can push each event to in addition to the JSONL log. */
type AttachmentEventSink = (event: AttachmentEvent) => void;
/**
 * Append one attachment event as a JSON line to {@link PATHS.ATTACHMENT_EVENTS_LOG}
 * under `projectRoot`. Stamps `at` when the caller did not supply it and returns
 * the fully-formed record so callers can forward it to a live sink.
 */
declare function appendAttachmentEvent(projectRoot: string, event: AttachmentEventInput): AttachmentEvent;
/**
 * Read every attachment event recorded for `projectRoot`, oldest first. Returns
 * an empty array when the log does not exist yet; a malformed line is skipped
 * rather than aborting the read so a single bad write never wedges the consumer.
 */
declare function readAttachmentEvents(projectRoot: string): AttachmentEvent[];

/** Hard cap on PDF pages before the file is rejected (spec: 2,000 pages). */
declare const PDF_PAGE_CAP = 2000;
/** Decompressed-size ceiling for archives before zip-bomb rejection (500 MB). */
declare const ZIP_DECOMPRESSED_LIMIT_BYTES: number;
/**
 * Whether a rejection should surface as `attachment.index_failed` (the file is
 * broken or unreadable) or `attachment.format_rejected` (the file is well-formed
 * but its shape is disallowed — too many pages, zip-bomb, unsupported format).
 */
type AttachmentRejectionOutcome = 'index_failed' | 'format_rejected';
/** Stable, routable reason for a parse rejection. */
type AttachmentRejectionReason = 'parse-error' | 'encrypted-pdf' | 'mime-unrecognised' | 'page-cap' | 'zip-bomb' | 'unsupported-format' | 'empty-file';
/** The detected high-level kind of the attachment's content. */
type AttachmentContentKind = 'text' | 'pdf';
/** Successful parse: plain text ready for the chunker. */
interface ParsedAttachment {
    ok: true;
    content: string;
    detectedKind: AttachmentContentKind;
    pageCount?: number;
}
/** A parse that produced no indexable content, with a routable reason. */
interface AttachmentRejection {
    ok: false;
    outcome: AttachmentRejectionOutcome;
    reason: AttachmentRejectionReason;
    message: string;
}
type ParseAttachmentResult = ParsedAttachment | AttachmentRejection;
/** Text + page count a consumer-supplied PDF extractor returns. */
interface PdfExtraction {
    text: string;
    pageCount: number;
    /** Set true when the PDF is password-protected and could not be read. */
    encrypted?: boolean;
}
/** Consumer-supplied PDF text extractor. Throws or sets `encrypted` on failure. */
type PdfTextExtractor = (bytes: Buffer) => Promise<PdfExtraction>;
/** What a consumer-supplied archive inspector reports for zip-bomb defence. */
interface ArchiveInspection {
    /** Total bytes the archive expands to (measured during a guarded expansion). */
    decompressedBytes: number;
}
/** Consumer-supplied archive inspector. Used only to enforce the zip-bomb cap. */
type ArchiveInspector = (bytes: Buffer) => Promise<ArchiveInspection>;
interface ParseAttachmentOptions {
    /** Injected PDF extractor; PDFs are rejected as unsupported when absent. */
    pdfExtractor?: PdfTextExtractor;
    /** Injected archive inspector; archives are rejected as unsupported when absent. */
    archiveInspector?: ArchiveInspector;
    /** Supply the file bytes directly, skipping the disk read. */
    bytes?: Buffer;
    /** Override the PDF page cap (defaults to {@link PDF_PAGE_CAP}). */
    pageCap?: number;
    /** Override the zip-bomb ceiling (defaults to {@link ZIP_DECOMPRESSED_LIMIT_BYTES}). */
    zipDecompressedLimitBytes?: number;
}
/**
 * Parse `filePath` into plain text for the chunker, applying every format guard.
 * Returns a {@link ParsedAttachment} on success, or a {@link AttachmentRejection}
 * carrying a stable `outcome`/`reason` the indexer maps to an attachment event.
 * Never throws for a bad file — read/parse failures become typed rejections.
 */
declare function parseAttachment(filePath: string, options?: ParseAttachmentOptions): Promise<ParseAttachmentResult>;

type ProgressFn = (update: ProviderProgressUpdate) => void;
declare class SessionAttachmentIndexer {
    private readonly providerFactory;
    /** Injectable so tests need not wait the real 1 s / 2 s backoff. */
    private readonly retryDelaysMs;
    private readonly chunker;
    /** Sessions whose `index()` is in flight, keyed to their abort controller. */
    private readonly running;
    constructor(providerFactory?: ProviderFactory, 
    /** Injectable so tests need not wait the real 1 s / 2 s backoff. */
    retryDelaysMs?: readonly number[]);
    /**
     * Index `filePaths` into the session's collection. Resolves to a success
     * result, or to an {@link AttachmentIndexingDegradedSignal} when the provider
     * stays unreachable through every attempt. Throws {@link CancelledError} if
     * the run is aborted mid-flight (its partial collection is purged first), and
     * {@link AttachmentPathError} for a session id that escapes the attachments
     * root.
     */
    index(projectRoot: string, sessionId: string, filePaths: string[], intelligence: IntelligenceConfig, onProgress?: ProgressFn, signal?: AbortSignal): Promise<AttachmentIndexingOutcome>;
    /**
     * Abort the in-flight indexer for a session (if any) and purge its partial
     * collection immediately. Safe to call when nothing is running — it still
     * removes any collection directory left on disk for that session.
     */
    cancel(projectRoot: string, sessionId: string): Promise<void>;
    private chunkFiles;
    private embedWithRetry;
    private embedBatchWithRetry;
    private purgeCollection;
    private throwIfAborted;
    /** Wait `ms`, rejecting with {@link CancelledError} if `signal` aborts first. */
    private sleep;
}
/** Whether the attachment targets the project index or a session collection. */
type AttachmentSessionKind = 'project' | 'ephemeral';
/** Default wall-clock budget for retrying a rate-limited remote embed (spec: 30 s). */
declare const ATTACHMENT_RETRY_BUDGET_MS = 30000;
/** A stored attachment chunk, tagged with the source file's content hash for dedupe. */
interface AttachmentStoredChunk extends StoredVectorChunk {
    /** SHA-256 of the parsed file content; identical content is a no-op re-index. */
    file_content_hash: string;
}
interface IndexAttachmentParams {
    /** On-disk path of the attached file. */
    filePath: string;
    /** The owning session's id (also the ephemeral collection key). */
    sessionId: string;
    /** `project` → persistent project index; `ephemeral` → session-scoped collection. */
    sessionKind: AttachmentSessionKind;
    /** Workspace embedding configuration used to pick the provider. */
    intelligence: IntelligenceConfig;
    onProgress?: (update: ProviderProgressUpdate) => void;
    /** Live sink for the emitted attachment event (in addition to the JSONL log). */
    onEvent?: AttachmentEventSink;
    signal?: AbortSignal;
    /** Injected PDF/archive extractors and parse limits for {@link parseAttachment}. */
    parse?: ParseAttachmentOptions;
    /** Override the embedding provider factory (tests, custom providers). */
    providerFactory?: ProviderFactory;
    /** Wall-clock budget for rate-limit retries (defaults to {@link ATTACHMENT_RETRY_BUDGET_MS}). */
    retryBudgetMs?: number;
    /** Wait between rate-limit retries; injectable so tests need not really wait. */
    retryDelayMs?: number;
}
/** Successful index (or deduped no-op) outcome. */
interface IndexAttachmentResult {
    ok: true;
    chunkCount: number;
    provider: string;
    collectionScope: AttachmentCollectionScope;
    /** True when an identical file was already indexed and embedding was skipped. */
    deduped: boolean;
}
/** A failed index: parse rejection, format rejection, or embedding failure. */
interface IndexAttachmentFailure {
    ok: false;
    /** `format_rejected` for shape rejections; `index_failed` otherwise. */
    outcome: 'index_failed' | 'format_rejected';
    reason: string;
}
type IndexAttachmentOutcome = IndexAttachmentResult | IndexAttachmentFailure;
/** Narrowing guard for the failure outcome. */
declare function isIndexAttachmentFailure(outcome: IndexAttachmentOutcome): outcome is IndexAttachmentFailure;
/**
 * Chunk, embed, and write one attached file into the project index (when
 * `sessionKind` is `project`) or a session-scoped ephemeral collection (when
 * `ephemeral`), emitting exactly one `attachment.*` event for the outcome.
 *
 * - An unparseable/encrypted/oversized/zip-bomb file writes no chunks and
 *   returns a typed failure with `attachment.index_failed` or
 *   `attachment.format_rejected` (never throws for a bad file).
 * - Re-indexing identical content for the same path is a no-op: the existing
 *   chunk count is returned and the provider is never called again.
 * - A rate-limited remote provider is retried within `retryBudgetMs` before the
 *   call fails with `attachment.index_failed`.
 *
 * Throws {@link CancelledError} only when `signal` aborts mid-flight, and the
 * registry's path guard error for a traversal `sessionId` on the ephemeral path.
 */
declare function indexAttachment(projectRoot: string, params: IndexAttachmentParams): Promise<IndexAttachmentOutcome>;
/**
 * Remove a session's ephemeral attachment collection from disk and the registry.
 * Session-end callers invoke this to reclaim space. A no-op for an unknown or
 * traversal-unsafe session id.
 */
declare function clearEphemeralCollection(projectRoot: string, sessionId: string): Promise<void>;

/**
 * Purge every registered collection whose session id is absent from
 * `liveSessionIds`. Returns one record per purged collection. A collection whose
 * id would escape the attachments root is deregistered but never `rm`-ed, so a
 * crafted session id cannot turn the sweep into an arbitrary-path delete.
 */
declare function runOrphanSweep(projectRoot: string, liveSessionIds: string[]): Promise<AttachmentOrphanPurgeRecord[]>;

/**
 * Retrieve the top-N attachment chunks for `query` from a session's collection.
 * Returns an empty result with `fallback_reason: 'no-attachment-collection'`
 * when the session has no registered collection.
 */
declare function retrieveFromAttachments(projectRoot: string, sessionId: string, query: string, topN?: number, providerFactory?: ProviderFactory): Promise<RagRetrievalResult>;

/**
 * Map a {@link CrsCollectionId} to a deterministic, filesystem-safe directory
 * name. Any character outside `[A-Za-z0-9._-]` is replaced with `_`, and any run
 * of dots (which could otherwise form a `..` traversal) is collapsed to `_`.
 * Whenever escaping changed the string, a short content hash of the original id
 * is appended so two distinct ids can never collapse to the same directory.
 *
 * @throws {Error} when `id` is empty or escapes to nothing usable.
 */
declare function escapeCollectionId(id: CrsCollectionId): string;
/** Absolute path to a CRS collection's directory under `<projectRoot>/.paqad/crs/`. */
declare function crsCollectionDir(projectRoot: string, collectionId: CrsCollectionId): string;
/**
 * Project-relative index/meta paths for a CRS collection, in the shape
 * {@link FileVectorIndex} expects (it joins them onto `projectRoot` itself).
 */
declare function crsCollectionPaths(collectionId: CrsCollectionId): {
    indexPath: string;
    metaPath: string;
};
/**
 * Full on-disk layout for a CRS collection — both the project-relative paths
 * {@link FileVectorIndex} consumes and the absolute paths the side-by-side
 * reindex swap needs (it `rename`s sibling directories directly). `escaped` is
 * the directory name; `.revert.<ms>` siblings under `crsRootAbs` are retired
 * indexes awaiting their 24-hour cleanup.
 */
declare function crsCollectionLayout(projectRoot: string, collectionId: CrsCollectionId): {
    escaped: string;
    crsRootAbs: string;
    relDir: string;
    absDir: string;
    indexPath: string;
    metaPath: string;
};

declare class RunnerScriptGenerator {
    private readonly engine;
    generate(profile: ProjectProfile): Promise<GeneratedFile[]>;
    write(projectRoot: string, profile: ProjectProfile): Promise<string[]>;
}

/**
 * Processes skill body content and strips non-matching stack-conditional sections.
 *
 * Directive syntax:
 *   <!-- if:laravel -->...<!-- endif -->
 *   <!-- if:react -->...<!-- endif -->
 *   <!-- if:vue -->...<!-- endif -->
 *   <!-- if:flutter -->...<!-- endif -->
 */
declare class ConditionalSectionProcessor {
    process(body: string, frameworks: string[]): string;
}

interface ParsedSkillDocument {
    frontmatter: SkillDefinition;
    body: string;
    line_count: number;
}
declare class SkillFrontmatterParser {
    parse(content: string): ParsedSkillDocument;
}
declare function toLoadedSkill(file: string, parsed: ParsedSkillDocument, frameworks?: string[]): LoadedSkill;

interface GeneratedSkillIndexEntry {
    name: string;
    description: string;
    triggers: SkillDefinition['triggers'];
    request_routing?: SkillDefinition['request_routing'];
    model_tier: SkillDefinition['model_tier'];
    resolved_model: string;
    output_format: SkillDefinition['output_format'];
    cacheable: boolean;
    on_complete?: SkillDefinition['on_complete'];
    file: string;
}
declare function buildSkillIndex(profile: Pick<ProjectProfile, 'model_routing'>, files: string[], relativeTo?: string): Promise<GeneratedSkillIndexEntry[]>;
declare function generateSkillIndex(profile: Pick<ProjectProfile, 'model_routing'>, skillRoots: string[], relativeTo?: string): Promise<GeneratedSkillIndexEntry[]>;
declare function writeSkillIndexFromArtifacts(projectRoot: string, profile: Pick<ProjectProfile, 'model_routing'>, artifacts: ResolvedArtifact$1[]): Promise<string>;
declare function writeSkillIndex(projectRoot: string, index: GeneratedSkillIndexEntry[]): Promise<string>;

declare class SkillLoader {
    private readonly auditBuffer;
    private readonly parser;
    constructor(auditBuffer?: SkillAuditBuffer);
    /**
     * Load every SKILL.md among the resolved artifacts. A file whose frontmatter
     * fails validation is excluded from the result and recorded as a
     * `skill.load_failed` audit event (written to `.paqad/skills/events.jsonl`
     * when `projectRoot` is supplied, otherwise buffered) — it no longer crashes
     * the whole batch (PQD-194). Non-validation errors (e.g. an unreadable file)
     * still propagate.
     */
    load(artifacts: ResolvedArtifact$1[], projectRoot?: string): Promise<LoadedSkill[]>;
}

declare function selectModelForTier(profile: Pick<ProjectProfile, 'model_routing'>, tier: SkillModelTier): string;

declare class SkillTriggerEvaluator {
    shouldLoad(skill: Pick<LoadedSkill, 'triggers'>, classification: ClassificationResult): boolean;
}

declare function buildAgentConfigContext(input: {
    adapter: AdapterType;
    frameworkPath: string;
    rulesPath: string;
}): Record<string, unknown>;

declare function buildApiDocContext(moduleName: string): {
    moduleName: string;
};

declare function buildDesignSystemContext(projectName: string): {
    projectName: string;
};

declare function buildErrorCatalogContext(moduleName: string): {
    moduleName: string;
};

declare function buildIntegrationDocContext(moduleName: string): {
    moduleName: string;
};

declare function buildModuleScaffoldContext(moduleName: string): {
    moduleName: string;
    title: string;
};

declare function buildRegistryContext(name: string): {
    name: string;
};

declare function buildRunnerScriptContext(input: {
    projectName: string;
    commands: {
        test: string;
        lint: string;
        format: string;
    };
    stack?: string;
    routing?: {
        stack?: string;
    };
}): {
    routing: {
        stack: string;
    };
    projectName: string;
    commands: {
        test: string;
        lint: string;
        format: string;
    };
    stack?: string;
};

interface TemplateDescriptor {
    name: string;
    path: string;
    relativePath: string;
}
declare class TemplateRegistry {
    private readonly templatesRoot;
    constructor(templatesRoot: string);
    discover(): Promise<TemplateDescriptor[]>;
}

interface MutableParsedResult {
    summary: StructuredTestResult['summary'];
    failures: StructuredTestIssue[];
    warnings: StructuredTestWarning[];
    errors: StructuredTestIssue[];
}
interface ParseTestOutputOptions {
    runner: StackPackTestRunner;
    cwd?: string;
    stdout?: string | Buffer;
    stderr?: string | Buffer;
    baseline_result?: StructuredTestResult;
    include_full_issues_with_baseline?: boolean;
}
declare function parseTestOutput(options: ParseTestOutputOptions): Promise<StructuredTestResult>;
declare function parseSingleSource(rawSource: string, runner: StackPackTestRunner, parseWarnings: string[]): {
    result: MutableParsedResult;
    strategy: TestParseStrategy;
};
declare function collectRawSources(options: ParseTestOutputOptions): Promise<string[]>;
declare function parseStructuredByFormat(rawOutput: string, runner: StackPackTestRunner, parseWarnings?: string[]): MutableParsedResult;
declare function parseJestJson(rawOutput: string, runnerId: string): MutableParsedResult;
declare function parsePytestJson(rawOutput: string, runnerId: string): MutableParsedResult;
declare function parseRspecJson(rawOutput: string, runnerId: string): MutableParsedResult;
declare function parseGoJson(rawOutput: string, runnerId: string, parseWarnings?: string[]): MutableParsedResult;
declare function parseTap(rawOutput: string, runnerId: string): MutableParsedResult;
declare function parseJunitXml(rawOutput: string, runnerId: string): MutableParsedResult;
declare function parsePlainTextFallback(rawOutput: string, runnerId: string): MutableParsedResult;
declare function mergeParsedResults(results: MutableParsedResult[], runnerId: string): MutableParsedResult;
declare function finalizeParsedResult(result: MutableParsedResult, parseMetadata: StructuredTestParseMetadata): StructuredTestResult;
declare function createEmptyParsedResult(runnerId: string): MutableParsedResult;
declare function summarizeTestDelta(baseline: StructuredTestResult, current: MutableParsedResult): StructuredTestParseMetadata['delta_summary'];
declare function projectDeltaIssues(baseline: StructuredTestResult, current: MutableParsedResult): MutableParsedResult;
declare function createIssue(input: {
    testId: string;
    suite: string | null;
    message: string;
    stackTrace: string | null;
    filePath: string | null;
    lineNumber: number | null;
    category: TestIssueCategory;
    durationMs: number | null;
}): StructuredTestIssue;
declare function classifyIssue(message: string, fallback: TestIssueCategory): TestIssueCategory;
declare function normalizeRawOutput(rawOutput: string): string;
declare function extractSummaryCount(lines: string[], label: string): number;
declare function extractDurationMs(lines: string[]): number | null;
declare function isRunnerEnvelope(line: string): boolean;
declare function parseXmlAttributes(xmlFragment: string): Record<string, string>;
declare function extractTag(xmlFragment: string, tagName: string): {
    message: string | null;
    content: string;
} | null;
declare function decodeXmlEntities(value: string): string;
declare function toUtf8String(value: string | Buffer | undefined): string;
declare function toMilliseconds(value: unknown): number | null;
declare function toInteger(value: unknown): number | null;
declare function toIsoTimestamp(epochMs: number | undefined): string;
declare function normalizeTimestamp(value: string | undefined): string;
declare function dedupeWarnings(warnings: StructuredTestWarning[]): StructuredTestWarning[];
declare function dedupeStrings(values: string[]): string[];
declare function formatErrorMessage(error: unknown): string;
declare function selectDominantStrategy(current: TestParseStrategy, next: TestParseStrategy): TestParseStrategy;
declare const __testOutputInternals: {
    selectDominantStrategy: typeof selectDominantStrategy;
    parseSingleSource: typeof parseSingleSource;
    collectRawSources: typeof collectRawSources;
    parseStructuredByFormat: typeof parseStructuredByFormat;
    parseJestJson: typeof parseJestJson;
    parsePytestJson: typeof parsePytestJson;
    parseRspecJson: typeof parseRspecJson;
    parseGoJson: typeof parseGoJson;
    parseTap: typeof parseTap;
    parseJunitXml: typeof parseJunitXml;
    parsePlainTextFallback: typeof parsePlainTextFallback;
    mergeParsedResults: typeof mergeParsedResults;
    finalizeParsedResult: typeof finalizeParsedResult;
    createEmptyParsedResult: typeof createEmptyParsedResult;
    summarizeTestDelta: typeof summarizeTestDelta;
    projectDeltaIssues: typeof projectDeltaIssues;
    createIssue: typeof createIssue;
    classifyIssue: typeof classifyIssue;
    normalizeRawOutput: typeof normalizeRawOutput;
    extractSummaryCount: typeof extractSummaryCount;
    extractDurationMs: typeof extractDurationMs;
    isRunnerEnvelope: typeof isRunnerEnvelope;
    parseXmlAttributes: typeof parseXmlAttributes;
    extractTag: typeof extractTag;
    decodeXmlEntities: typeof decodeXmlEntities;
    toUtf8String: typeof toUtf8String;
    toMilliseconds: typeof toMilliseconds;
    toInteger: typeof toInteger;
    toIsoTimestamp: typeof toIsoTimestamp;
    normalizeTimestamp: typeof normalizeTimestamp;
    dedupeWarnings: typeof dedupeWarnings;
    dedupeStrings: typeof dedupeStrings;
    formatErrorMessage: typeof formatErrorMessage;
};

declare function buildCompactArtifact(input: BuildCompactArtifactInput): CompactArtifactResult;
declare function evaluateEscalation(input: EvaluateEscalationInput): EscalationDecision;
declare function buildReasoningInputPayload(compact: CompactArtifactResult, escalation: EscalationDecision): ReasoningInputPayload;
declare function applyDisclosurePolicy(input: DisclosurePolicyInput): DisclosurePolicyResult;
declare function evaluateRetrievalGate(input: RetrievalGateInput): RetrievalGateResult;
declare function runRoutingDecision(input: RoutingInput): RoutingResult;
declare function buildControlLayerAudit(disclosure: DisclosureAuditRecord, retrieval: RetrievalAuditRecord, routing: RoutingAuditRecord): ControlLayerAuditRecord;
declare function createTestDelta(baseline: TestIssueSnapshot[], current: TestIssueSnapshot[], options?: {
    treat_missing_as_passing?: boolean;
}): {
    delta: TestDelta;
    metadata: TokenEfficiencyMetadata;
};
declare function createVerificationDelta(baseline: VerificationGateSnapshot[], current: VerificationGateSnapshot[]): {
    delta: VerificationDelta;
    metadata: TokenEfficiencyMetadata;
};
declare function createDriftDelta(baseline: DriftFileSnapshot[], current: DriftFileSnapshot[]): {
    delta: DriftDelta;
    metadata: TokenEfficiencyMetadata;
};
declare function buildTestDeltaReasoningPayload(baseline: TestIssueSnapshot[], current: TestIssueSnapshot[], options?: {
    treat_missing_as_passing?: boolean;
}, escalationInput?: Omit<EvaluateEscalationInput, 'compact'>): DeltaReasoningPayload<TestDelta>;
declare function buildVerificationDeltaReasoningPayload(baseline: VerificationGateSnapshot[], current: VerificationGateSnapshot[], escalationInput?: Omit<EvaluateEscalationInput, 'compact'>): DeltaReasoningPayload<VerificationDelta>;
declare function buildDriftDeltaReasoningPayload(baseline: DriftFileSnapshot[], current: DriftFileSnapshot[], escalationInput?: Omit<EvaluateEscalationInput, 'compact'>): DeltaReasoningPayload<DriftDelta>;
declare function resolveEscalationReason(input: EvaluateEscalationInput, confidenceThreshold: number): EscalationReason | null;
declare function extractRawSlice(compact: CompactArtifactResult, maxChars: number, hint: string): string | null;
declare function summarizeByClass(artifactClass: BuildCompactArtifactInput['artifact_class'], raw: string, maxExcerpts: number): {
    summary: CompactArtifactSummary;
    excerpts: string[];
    confidence: number;
};
declare function summarizeTestOutput(raw: string, maxExcerpts: number): {
    summary: CompactArtifactSummary;
    excerpts: string[];
    confidence: number;
};
declare function summarizeCoverageOutput(raw: string, maxExcerpts: number): {
    summary: CompactArtifactSummary;
    excerpts: string[];
    confidence: number;
};
declare function summarizeJsonReport(raw: string, maxExcerpts: number): {
    summary: CompactArtifactSummary;
    excerpts: string[];
    confidence: number;
};
declare function summarizeXmlReport(raw: string, maxExcerpts: number): {
    summary: CompactArtifactSummary;
    excerpts: string[];
    confidence: number;
};
declare function summarizeLogOutput(raw: string, maxExcerpts: number): {
    summary: CompactArtifactSummary;
    excerpts: string[];
    confidence: number;
};
declare function summarizeGrepResults(raw: string, maxExcerpts: number): {
    summary: CompactArtifactSummary;
    excerpts: string[];
    confidence: number;
};
declare function summarizeRouteDump(raw: string, maxExcerpts: number): {
    summary: CompactArtifactSummary;
    excerpts: string[];
    confidence: number;
};
declare function summarizeInventoryScan(raw: string, maxExcerpts: number): {
    summary: CompactArtifactSummary;
    excerpts: string[];
    confidence: number;
};
declare function degradedSummary(artifactClass: BuildCompactArtifactInput['artifact_class'], raw: string, maxExcerpts: number, confidence: number): {
    summary: CompactArtifactSummary;
    excerpts: string[];
    confidence: number;
};
declare function minimizeCompactRepresentation(summaryResult: {
    summary: CompactArtifactSummary;
    excerpts: string[];
    confidence: number;
}, artifactClass: BuildCompactArtifactInput['artifact_class'], originalSize: number, maxExcerpts: number): {
    summary: CompactArtifactSummary;
    excerpts: string[];
    confidence: number;
};
declare function measureCompactRepresentation(summary: CompactArtifactSummary, excerpts: string[], confidence: number): number;
declare function createDeltaMetadata(fullState: unknown, delta: unknown): TokenEfficiencyMetadata;
declare function buildDeltaReasoningPayload<TDelta extends object>(delta: TDelta, deltaMetadata: TokenEfficiencyMetadata, escalationInput: Omit<EvaluateEscalationInput, 'compact'>): DeltaReasoningPayload<TDelta>;
declare function resolveDisclosureLevel(input: DisclosurePolicyInput): DisclosureLevel;
declare function buildDisclosurePayload(level: DisclosureLevel, compact: CompactArtifactResult, escalation?: EscalationDecision): string;
declare function resolveRetrievalPath(taskComplexity: RetrievalGateInput['task_complexity'], ambiguityDetected: boolean, chunkCount: number, threshold: number, conflictingEvidence: boolean): {
    path: RetrievalPath;
    rag_skipped: boolean;
    escalation_signal: RetrievalEscalationSignal | null;
};
declare function resolveRoutingMechanism(taskType: string, metadata?: Record<string, unknown>): {
    mechanism: RoutingMechanism;
    resolved: boolean;
    resolved_task_type: string | null;
};
declare function calculateReductionRatio(originalSize: number, compactSize: number): number;
declare function extractFileLikeSegments(lines: string[]): string[];
declare function flattenJson(value: unknown, prefix?: string): string[];
declare function normalizedIssueMessage(item: TestIssueSnapshot): string;
declare function tokenizeLines(raw: string): string[];
declare function normalizeLineEndings(raw: string): string;
declare function collapseWhitespace(input: string): string;
declare function sortUnique(values: string[]): string[];
declare const __tokenEfficiencyInternals: {
    summarizeByClass: typeof summarizeByClass;
    summarizeTestOutput: typeof summarizeTestOutput;
    summarizeCoverageOutput: typeof summarizeCoverageOutput;
    summarizeJsonReport: typeof summarizeJsonReport;
    summarizeXmlReport: typeof summarizeXmlReport;
    summarizeLogOutput: typeof summarizeLogOutput;
    summarizeGrepResults: typeof summarizeGrepResults;
    summarizeRouteDump: typeof summarizeRouteDump;
    summarizeInventoryScan: typeof summarizeInventoryScan;
    degradedSummary: typeof degradedSummary;
    minimizeCompactRepresentation: typeof minimizeCompactRepresentation;
    measureCompactRepresentation: typeof measureCompactRepresentation;
    resolveEscalationReason: typeof resolveEscalationReason;
    extractRawSlice: typeof extractRawSlice;
    createDeltaMetadata: typeof createDeltaMetadata;
    buildDeltaReasoningPayload: typeof buildDeltaReasoningPayload;
    resolveDisclosureLevel: typeof resolveDisclosureLevel;
    buildDisclosurePayload: typeof buildDisclosurePayload;
    resolveRetrievalPath: typeof resolveRetrievalPath;
    resolveRoutingMechanism: typeof resolveRoutingMechanism;
    extractFileLikeSegments: typeof extractFileLikeSegments;
    flattenJson: typeof flattenJson;
    normalizedIssueMessage: typeof normalizedIssueMessage;
    tokenizeLines: typeof tokenizeLines;
    normalizeLineEndings: typeof normalizeLineEndings;
    collapseWhitespace: typeof collapseWhitespace;
    sortUnique: typeof sortUnique;
    calculateReductionRatio: typeof calculateReductionRatio;
};

declare function appendAuditLog(projectRoot: string, previous: string | null, updated: string): void;
declare function appendAuditLogFailure(projectRoot: string, previous: string | null, target: string, error: string): void;

type UpdateCandidate = GeneratedFile;
interface UpdateDiff {
    path: string;
    before: string;
    after: string;
}
interface UpdateReport {
    previous_version: string | null;
    target_version: string;
    regenerated: string[];
    skipped: UpdateDiff[];
    deprecated: string[];
    new_mcp_servers: string[];
    new_scripts: string[];
    /** Obsolete config keys pruned from `.config` / `configs/.config.*` because
     *  this version's knob registry no longer knows them (never reset-to-default). */
    config_keys_pruned: string[];
}
interface FrameworkUpdaterOptions {
    generateCandidates?: (projectRoot: string) => Promise<UpdateCandidate[]>;
}
declare class FrameworkUpdater {
    private readonly options;
    constructor(options?: FrameworkUpdaterOptions);
    run(projectRoot: string): Promise<UpdateReport>;
    private getCandidates;
}

declare function toVerificationSnapshots(results: GateResult[]): VerificationGateSnapshot[];
declare function buildVerificationGateDeltaPayload(baselineResults: GateResult[], currentResults: GateResult[], escalationInput?: Omit<EvaluateEscalationInput, 'compact'>): DeltaReasoningPayload<VerificationDelta>;
declare function buildDocumentationDriftDeltaPayload(baseline: DriftFileSnapshot[], current: DriftFileSnapshot[], escalationInput?: Omit<EvaluateEscalationInput, 'compact'>): DeltaReasoningPayload<DriftDelta>;

declare const VERIFICATION_EVIDENCE_RELATIVE_PATH = ".paqad/session/verification-evidence.json";
declare const VERIFICATION_EVIDENCE_STDERR_BUDGET_BYTES = 2048;
interface BuildVerificationEvidenceInput {
    results: GateResult[];
    context: Pick<VerificationContext, 'structured_test_results' | 'mutation_result'>;
    run_id: string;
    started_at: string;
    completed_at: string;
}
declare function buildVerificationEvidence(input: BuildVerificationEvidenceInput): VerificationEvidence;
interface WriteVerificationEvidenceOptions {
    project_root: string;
}
declare function writeVerificationEvidence(evidence: VerificationEvidence, options: WriteVerificationEvidenceOptions): Promise<string>;

interface Gate {
    readonly gate: VerificationGate;
    check(context: VerificationContext): Promise<GateResult>;
}

declare class VerificationGateRunner {
    private readonly gates;
    constructor(gates?: Gate[]);
    run(context: VerificationContext): Promise<GateResult[]>;
    runWithDelta(context: VerificationContext, baselineResults: GateResult[], escalationInput?: Omit<EvaluateEscalationInput, 'compact'>): Promise<{
        results: GateResult[];
        delta_payload: DeltaReasoningPayload<VerificationDelta>;
    }>;
}

interface BuildRepositoryVerificationContextOptions {
    projectRoot: string;
    /** The agent-independent origin firing this run (issue #117). */
    origin: Extract<VerificationOrigin, 'hook-completion' | 'git-backstop' | 'ci-backstop'>;
}
interface RepositoryVerificationContextResult {
    context: VerificationContext;
    /**
     * Human-readable notes for signals that could not be proven either way and
     * escalate rather than block (e.g. "spec review: no frozen spec on record").
     * The trust verdict (issue #117 C-6) surfaces these so an inconclusive signal
     * is never *silently* passed.
     */
    escalations: string[];
}
/**
 * Build the verification context for a hook/backstop run. Loads every artifact
 * defensively — a missing or malformed artifact degrades to "nothing to prove"
 * for that signal rather than throwing, so a clean change in a freshly
 * onboarded project passes while a real contract violation blocks.
 */
declare function buildRepositoryVerificationContext(options: BuildRepositoryVerificationContextOptions): Promise<RepositoryVerificationContextResult>;

declare const TRACEABILITY_MAP_SCHEMA_VERSION: "1.0.0";
/** Where a promise comes from. Both are real promises; the source is recorded
 *  so the forward anchor is auditable. */
type PromiseSource = 'acceptance-criterion' | 'obligation';
/** Forward: promise → the code that delivers it → the check that proves it. */
interface ForwardLink {
    promise_id: string;
    source: PromiseSource;
    description: string;
    /** Project-relative files inferred to deliver this promise (change set +
     *  module map, optionally sharpened by explicit markers). */
    delivering_code: string[];
    /** Test files / gate ids that prove this promise (compliance evidence +
     *  verification-evidence `ac_id`). */
    proving_checks: string[];
    /** True iff at least one proving check exists. A false value is the
     *  "untested promise" signal. */
    proven: boolean;
}
/** How a code file relates to the promise set. */
type CodeRole = 'delivers-promise' | 'shared-groundwork' | 'orphan';
/** Backward: each code file → a promise, or to a promise-backed user. */
interface BackwardLink {
    file: string;
    /** Promises this file directly delivers (may be empty). */
    promise_ids: string[];
    /** True iff this file is reachable from a promise-delivering file via the
     *  import graph — i.e. something-with-a-promise actually uses it. */
    used_by_promise: boolean;
    /** Up to a few anchor files that reach this one (evidence of use). */
    reached_from: string[];
    role: CodeRole;
}
type TraceabilityFindingCode = 'TR-UNTESTED-PROMISE' | 'TR-CODE-ORPHAN';
interface TraceabilityFinding {
    code: TraceabilityFindingCode;
    /** The promise involved (TR-UNTESTED-PROMISE); null for orphan code. */
    promise_id: string | null;
    paths: string[];
    detail: string;
}
interface TraceabilityCounts {
    promises: number;
    untested_promises: number;
    delivers_promise: number;
    shared_groundwork: number;
    orphan_code: number;
}
interface TraceabilityMap {
    schema_version: typeof TRACEABILITY_MAP_SCHEMA_VERSION;
    generated_at: string;
    lane: Lane;
    /** `full` builds the whole two-way map; `light` (fast lane) checks only the
     *  change set — "did this trivial change add code with no promise/no user?" */
    mode: 'full' | 'light';
    /** When false, no promise anchors were discoverable this run, so orphan code
     *  cannot be told apart from shared groundwork — orphan flagging is suppressed
     *  rather than flagging the whole tree. The reason is recorded for honesty. */
    anchors_known: boolean;
    blocked_reason: string | null;
    forward: ForwardLink[];
    backward: BackwardLink[];
    findings: TraceabilityFinding[];
    counts: TraceabilityCounts;
}

/**
 * A computed judgment signal. `inconclusive` is distinct from `passed: false`:
 * it means "this could not be proven either way and must escalate", never
 * "assume fine".
 */
interface JudgmentSignal {
    passed: boolean;
    inconclusive: boolean;
    detail: string;
}
/**
 * `ac-test-mapping` from the traceability map (`.paqad/traceability/map.json`).
 * The map is the source of truth for which acceptance criteria exist and
 * whether each links to a proving check.
 *
 * - Map present, AC promises all proven → pass.
 * - Map present, one or more AC promises unproven → fail, naming the AC ids.
 * - Map present, no AC promises → pass (nothing to map — honest, not vacuous).
 * - Map absent → pass with a "no acceptance criteria on record" detail. The map
 *   carries the ACs; with no map there is nothing to prove, so a clean change in
 *   a project that never froze a spec is not blocked.
 */
declare function computeAcTestMapping(map: TraceabilityMap | null): JudgmentSignal;
/**
 * `implementation-review` from the decision store. A change that lands while a
 * decision packet is still unresolved violated the decision-pause contract: the
 * agent should have paused. Each unresolved pending packet becomes a blocking
 * `decision-violation` finding (issue #117 C-2/C-3).
 */
declare function computeImplementationReview(pendingDecisions: DecisionPacket[]): {
    passed: boolean;
    findings: ImplementationReviewFinding[];
};
/**
 * `spec-review` from the spec-review report
 * (`.paqad/spec-review/<slug>.json`, loaded by the compliance spec-review
 * store) plus the frozen-spec presence signal.
 *
 * - Report present with an unresolved critical defect → fail (the spec is not
 *   clean enough to freeze).
 * - Report present, clean → pass.
 * - No report but a frozen spec exists → pass (the spec was signed off).
 * - No report and no frozen spec, yet the change touches code → pass but
 *   `inconclusive` (escalate, do not block): "was the spec frozen and reviewed?"
 *   genuinely needs human/model judgment, so the verdict flags it rather than
 *   either silently asserting pass or blocking every spec-less change.
 * - No report, no frozen spec, no code change → pass (a docs-only/chore change).
 *
 * Note: `inconclusive` is reported with `passed: true` so the backstop does not
 * block a clean change that simply predates a frozen spec; the trust verdict
 * surfaces the inconclusive signal so it is never *silently* passed.
 */
declare function computeSpecReview(input: {
    specReview: SpecReviewReport | null;
    hasFrozenSpec: boolean;
    codeChanged: boolean;
}): JudgmentSignal;

/**
 * Returns the sorted, de-duplicated changed files that fall outside the spec
 * boundary. An empty boundary means "no boundary declared" and yields no drift
 * (the gate stays inert on the in-session provider path). A boundary entry is a
 * project-relative file or directory prefix; a changed file is in scope when it
 * equals, or sits under, any entry.
 */
declare function collectScopeDriftPaths(changedFiles: string[], specBoundary: string[]): string[];

interface RepositoryVerificationGateVerdict {
    gate: VerificationGate;
    status: EvidenceGateStatus;
    detail: string;
    remediation: string | null;
    /** Issue #579 — the short skip reason, carried from the evidence gate when present. */
    skip_reason?: string;
}
interface RepositoryVerificationVerdict {
    /** The agent-independent origin that fired this run. */
    origin: string;
    /** True iff no gate that ran failed (skipped/inconclusive-but-passed do not
     *  flip this; a hard `fail` does). This is the deterministic "did the agent
     *  obey?" signal. */
    ok: boolean;
    /** One-line trust verdict, the same text the hook prints and the event
     *  stream carries. */
    summary: string;
    /** The full end-of-change receipt (issue #325): the verdict headline + per-stage
     *  evidence + delivery state, composed at the completion seam. Falls back to
     *  `summary` when no stage fold is available. */
    receipt?: string;
    /** The model-facing narration advisory (issue #409): set when this change recorded
     *  stages the agent never spoke in visible text, empty otherwise. Advisory by
     *  contract — it never contributes to `ok`, because a silent turn is a voice defect,
     *  not a broken change. */
    narrationAdvisory?: string;
    /** Per-gate pass/fail/inconclusive/skipped with specifics. */
    gates: RepositoryVerificationGateVerdict[];
    /** Signals that could not be proven either way and escalate without blocking
     *  (e.g. "spec-review: no frozen spec on record"). */
    escalations: string[];
    /** Project path the evidence JSON was written to, or null if the write was
     *  skipped/failed. */
    evidence_path: string | null;
    /** Absolute path to the rendered per-feature `report.html` (issue #371), or null when
     *  no feature was active, the flag is off, or rendering failed. Best-effort — its
     *  absence never affects `ok`. */
    reportPath?: string | null;
    started_at: string;
    completed_at: string;
}
/**
 * Build the verdict from the evidence artifact. A run is `ok` when no gate
 * reports a hard `fail`; `skipped` gates (the model-judgment gates the backstop
 * does not re-judge) and inconclusive-but-passed signals never flip it.
 */
declare function buildRepositoryVerificationVerdict(input: {
    origin: string;
    evidence: VerificationEvidence;
    escalations: string[];
    evidencePath: string | null;
    /** Issue #579 — gates whose feature flag is on; a skip among them prints a skip line. */
    flagOnGates?: readonly VerificationGate[];
}): RepositoryVerificationVerdict;
/**
 * Render the branded trust verdict in paqad's own vocabulary (issue #325). The
 * headline is one of the contract's three verdict words — never an ad-hoc string —
 * led by the `**▸ paqad** ·` frame, and every status line pairs a fixed glyph with a
 * word so it stays legible with the emoji stripped. On a hard fail it names each
 * failing gate; when only inconclusive signals remain it reads "Inconclusive" (an
 * over-trust guard), and an all-clear reads "Safe to merge".
 *
 * Verdict vocabulary and glyphs come from `paqad-voice.ts`, fulfilling that file's
 * single-source claim so the chat verdict, the PR comment, and the dashboard all say
 * the same words.
 *
 * `unrecordedMandatoryStages` (issue #472) reconciles the headline with the per-stage
 * block: when the GATES all passed but a mandatory feature-development stage has no
 * evidence, "Safe to merge" over-claims relative to the stage block (which shows the
 * stage 🟡/🔴). In that case the word is downgraded to Inconclusive — the contract's
 * over-trust guard — while the true "N/N checks held" line is kept so the gates that
 * held are still credited. It never affects the caller's `ok` (exit/block) signal.
 */
declare function formatVerdictSummary(input: {
    ok: boolean;
    gates: RepositoryVerificationGateVerdict[];
    escalations: string[];
    unrecordedMandatoryStages?: string[];
    /**
     * Issue #579 — gates whose feature flag is on. A skipped gate in this list adds one
     * "⚪ <gate words>: skipped (<reason>)" line after the status lines and before the
     * escalations, so a flag-on gate that did nothing is visible. Skips never move the counts.
     */
    flagOnGates?: readonly VerificationGate[];
}): string;

/**
 * The gates the backstop runs. It deliberately omits the pure model-judgment
 * gates — requirement-completeness, story-quality, architecture-compliance,
 * behavioral-correctness, database-quality, code-tests-lint — because those are
 * provider-workflow concerns the backstop cannot re-judge from artifacts (and
 * CI runs lint/test/typecheck as separate steps). The omitted gates report
 * `skipped` in the evidence rather than passing vacuously.
 *
 * Order matters: the specific computed gates (ac-test-mapping, spec-review,
 * implementation-review) run *before* the change-completeness roll-up so that
 * when one fails, the verdict names the precise cause (which AC, which decision)
 * rather than the roll-up's generic "blocked". The runner short-circuits after
 * the first failure, so the first failing gate is the one the developer reads.
 */
declare function backstopGates(): Gate[];
interface RunRepositoryVerificationOptions extends BuildRepositoryVerificationContextOptions {
    /** When supplied, the verdict is streamed as a `verification-verdict` event
     *  (issue #117 C-6) so the desktop/UI sees the same data the hook prints. */
    eventBus?: EngineEventBus;
    /** Pre-built context, for tests/callers that already have one. When omitted
     *  the context is built from repository reality. */
    prebuiltContext?: {
        context: VerificationContext;
        escalations: string[];
    };
    /** The host session id (Claude passes one on the Stop-hook stdin). Threaded to
     *  stage-evidence finalization so the completion seam writes under the SAME id
     *  as the live session's other ledgers — instead of falling back to a stale
     *  single-slot cache and fragmenting one session into two subdirs (buildout F5b,
     *  bug #5). Absent on hosts that supply no id (the cached/minted id is used). */
    hostSessionId?: string | null;
    /** The turn transcript (issue #409). When supplied, the verdict carries a
     *  `narrationAdvisory` naming any stage this change recorded that the agent never
     *  spoke in visible text — the mirror of the narrated-but-unrecorded gap (#389).
     *  Absent/empty reads as "cannot tell" and produces no advisory. */
    transcriptText?: string | null;
    now?: () => string;
}
/**
 * Run the verification backstop against repository reality and return the trust
 * verdict. Never throws on a gate failure — a failure is reported as
 * `verdict.ok === false`; the caller (hook/CI) decides the exit code.
 */
declare function runRepositoryVerification(options: RunRepositoryVerificationOptions): Promise<RepositoryVerificationVerdict>;

declare const AC_ID_PATTERN: RegExp;
declare function extractAcIdFromIssue(issue: StructuredTestIssue): string | null;
declare function collectObservedAcIds(structuredResults: StructuredTestResult[]): string[];
declare class AcTestMappingGate implements Gate {
    readonly gate: "ac-test-mapping";
    check(context: Parameters<Gate['check']>[0]): Promise<GateResult>;
}

declare class ArchitectureComplianceGate implements Gate {
    readonly gate: "architecture-compliance";
    check(context: Parameters<Gate['check']>[0]): Promise<GateResult>;
}

declare class BehavioralCorrectnessGate implements Gate {
    readonly gate: "behavioral-correctness";
    check(context: Parameters<Gate['check']>[0]): Promise<GateResult>;
}

declare class ChangeCompletenessGate implements Gate {
    readonly gate: "change-completeness";
    check(context: Parameters<Gate['check']>[0]): Promise<GateResult>;
}

declare class CodeTestsLintGate implements Gate {
    readonly gate: "code-tests-lint";
    check(context: Parameters<Gate['check']>[0]): Promise<GateResult>;
}

declare class DatabaseQualityGate implements Gate {
    readonly gate: "database-quality";
    check(context: Parameters<Gate['check']>[0]): Promise<GateResult>;
}

declare class DocumentationFreshnessGate implements Gate {
    readonly gate: "documentation-freshness";
    check(context: Parameters<Gate['check']>[0]): Promise<GateResult>;
}

/**
 * Extension-surface gate (PQD-92).
 *
 * Backs AC2/AC3 inside the verification pipeline: when a public export barrel is
 * changed, the canonical surface document (`docs/extension-surface.md`) must be
 * amended in the same change set. The gate is *inert* (passes) when the document
 * is absent, so it stays backward-compatible for projects that predate the
 * contract — an inconclusive result would otherwise fail overall verification
 * (see `verification/evidence.ts`).
 */
declare const SURFACE_DOC_PATH = "docs/extension-surface.md";
declare class ExtensionSurfaceGate implements Gate {
    readonly gate: "extension-surface";
    check(context: Parameters<Gate['check']>[0]): Promise<GateResult>;
}

declare class ImplementationReviewGate implements Gate {
    readonly gate: "implementation-review";
    check(context: Parameters<Gate['check']>[0]): Promise<GateResult>;
}

declare class InstructionsDocsStructureGate implements Gate {
    readonly gate: "instructions-docs-structure";
    check(context: Parameters<Gate['check']>[0]): Promise<GateResult>;
}

declare class ModuleDocsStructureGate implements Gate {
    readonly gate: "module-docs-structure";
    check(context: Parameters<Gate['check']>[0]): Promise<GateResult>;
}

declare class RequirementCompletenessGate implements Gate {
    readonly gate: "requirement-completeness";
    check(context: Parameters<Gate['check']>[0]): Promise<GateResult>;
}

/**
 * Keep the stored site map honest: a code change that drifts the map cannot reach
 * "Safe to merge" while the map is stale. Mirror of {@link DocumentationFreshnessGate}, but
 * over the site map instead of the canonical docs. One deterministic signal fires, behind the
 * code-change guard: the stored canonical map carries a stamped {@link AppFreshness} whose
 * cited `file:line` anchors no longer all resolve (recorded map-vs-code drift, issue #466
 * Part G). It is read STATICALLY from the stored map — no evidence resolution at gate time
 * (NFR-4) — and stamped by the live run's trust + freshness restamp (C8), so the gate only
 * ever grades earned proof. (The old progress-ledger published-view signal is retired with the
 * report machinery, ART-3.)
 *
 * Inert unless the `site_map` capability is enabled (INV-1): with the flag off — the default —
 * the gate always passes and changes nothing, so it is fully additive.
 */
declare class SiteMapFreshnessGate implements Gate {
    readonly gate: "site-map-freshness";
    check(context: Parameters<Gate['check']>[0]): Promise<GateResult>;
}

declare class SpecReviewGate implements Gate {
    readonly gate: "spec-review";
    check(context: Parameters<Gate['check']>[0]): Promise<GateResult>;
}

declare class StoryQualityGate implements Gate {
    readonly gate: "story-quality";
    check(context: Parameters<Gate['check']>[0]): Promise<GateResult>;
}

interface MarkdownValidationResult {
    valid: boolean;
    errors: string[];
}

declare function validateApiDoc(markdown: string): MarkdownValidationResult;

declare function validateErrorCatalogMarkdown(markdown: string): MarkdownValidationResult;

declare function validateSpecDocument(markdown: string): {
    valid: boolean;
    errors: string[];
};

declare function validateUserFlow(markdown: string): MarkdownValidationResult;

interface Pattern {
    id: string;
    created_at: string;
    source_project: string;
    stack_filter: {
        domain: string;
        frameworks: string[];
        traits: string[];
    };
    category: string;
    problem: string;
    solution: string;
    files_involved: string[];
    verification: {
        tests_passed: boolean;
        build_passed: boolean;
    };
    tags: string[];
}
interface PatternIndexEntry {
    id: string;
    category: string;
    stack_filter: Pattern['stack_filter'];
    tags: string[];
    created_at: string;
    problem_preview: string;
}
interface PatternIndex {
    version: 1;
    entries: PatternIndexEntry[];
}
interface PatternFilter {
    domain?: string;
    frameworks?: string[];
    keywords?: string[];
    category?: string;
}
interface PatternMatch {
    pattern: Pattern;
    score: number;
    is_stale: boolean;
}

declare class PatternStore {
    get indexPath(): string;
    get entriesDir(): string;
    save(pattern: Pattern): Promise<void>;
    load(id: string): Promise<Pattern | null>;
    loadIndex(): Promise<PatternIndex>;
    updateIndex(pattern: Pattern): Promise<void>;
    delete(id: string): Promise<void>;
    list(filter?: PatternFilter): Promise<Pattern[]>;
}

type PatternSemanticScorer = (pattern: Pattern, keywords: string[]) => Promise<number> | number;
declare class PatternSuggester {
    private readonly store;
    private readonly relevanceThreshold;
    private readonly semanticScorer?;
    constructor(store: PatternStore, relevanceThreshold?: number, semanticScorer?: PatternSemanticScorer | undefined);
    suggest(keywords: string[], domain: string, frameworks: string[], limit?: number): Promise<PatternMatch[]>;
    private score;
    private isStale;
}

interface StoredPatternVector extends StoredVectorItem {
    fingerprint: string;
    category: string;
    tags: string[];
    problem_preview: string;
}
declare function getGlobalPatternVectorPaths(provider?: string, model?: string): {
    index: string;
    meta: string;
};
declare class PatternVectorService {
    private readonly store;
    private readonly providerFactory;
    constructor(store?: PatternStore, providerFactory?: ProviderFactory);
    private getIndex;
    getStatus(projectRoot: string): Promise<{
        present: boolean;
        valid: boolean;
        chunk_count: number;
        reason?: string;
    }>;
    rebuild(projectRoot: string, onProgress?: (message: string) => void): Promise<void>;
    refresh(projectRoot: string, onProgress?: (message: string) => void): Promise<void>;
    createSemanticScorer(projectRoot: string, onProgress?: (message: string) => void): Promise<PatternSemanticScorer | undefined>;
    createSuggester(projectRoot: string, relevanceThreshold?: number): Promise<PatternSuggester>;
    private embedPatterns;
}
declare function suggestPatternsForProject(projectRoot: string, keywords: string[], domain: string, frameworks: string[], limit?: number): Promise<PatternMatch[]>;

interface RecordPatternInput {
    classification: {
        workflow?: string;
        description?: string;
        category?: string;
    };
    projectDirName: string;
    domain: string;
    frameworks: string[];
    traits: string[];
    filesInvolved: string[];
    problem: string;
    solution: string;
    tags?: string[];
    verification: {
        tests_passed: boolean;
        build_passed: boolean;
    };
}
declare class PatternRecorder {
    private readonly store;
    constructor(store: PatternStore);
    record(input: RecordPatternInput): Promise<Pattern>;
}

declare class PatternCli {
    private readonly store;
    constructor(store: PatternStore);
    list(filter?: PatternFilter): Promise<void>;
    prune(olderThanDays?: number): Promise<void>;
    exportPatterns(outputPath: string, format: 'json' | 'markdown'): Promise<void>;
}

declare const ANSWER_GROUNDING_STATES: readonly ["observed", "inferred", "missing-evidence"];
type AnswerGroundingState = (typeof ANSWER_GROUNDING_STATES)[number];
declare const ANSWER_MODES: readonly ["quick", "explain", "trace"];
type AnswerMode = (typeof ANSWER_MODES)[number];
declare const CITATION_SOURCE_CLASSES: readonly ["canonical-doc", "generated-instruction", "framework-state", "manifest", "workflow", "code"];
type CitationSourceClass = (typeof CITATION_SOURCE_CLASSES)[number];
interface Citation {
    path: string;
    source_class: CitationSourceClass;
    excerpt?: string;
}
interface FreshnessMetadata {
    stale_sources: string[];
    drift_detected: boolean;
    generated_at?: string;
    note?: string;
}
interface Contradiction {
    source_a: string;
    source_b: string;
    description: string;
}
interface KnowledgeAnswer {
    answer: string;
    grounding_state: AnswerGroundingState;
    citations: Citation[];
    freshness: FreshnessMetadata | null;
    contradictions: Contradiction[];
    next_actions: string[];
    mode: AnswerMode;
    confidence_basis: string;
}
interface AnswerQuery {
    question: string;
    mode: AnswerMode;
    project_root: string;
    mcp_first?: boolean;
}

interface EvidenceFile {
    path: string;
    source_class: CitationSourceClass;
    excerpt: string;
    score: number;
}
declare function extractKeywords(question: string): string[];
declare function scoreFile(filePath: string, excerpt: string, keywords: string[]): number;
declare class EvidenceRetriever {
    retrieve(query: AnswerQuery): Promise<EvidenceFile[]>;
    private retrieveSemanticEvidence;
    private retrieveLexicalEvidence;
}

declare class FreshnessChecker {
    check(projectRoot: string, evidencePaths: string[]): Promise<FreshnessMetadata>;
}

declare class ContradictionDetector {
    detect(files: EvidenceFile[]): Contradiction[];
}

declare class ProjectKnowledgeAnswerer {
    private readonly retriever;
    private readonly freshnessChecker;
    private readonly contradictionDetector;
    constructor(retriever?: EvidenceRetriever, freshnessChecker?: FreshnessChecker, contradictionDetector?: ContradictionDetector);
    answer(query: AnswerQuery): Promise<KnowledgeAnswer>;
}

interface ContractBoundary {
    file: string;
    symbol: string;
    importers: string[];
}
declare function detectContractBoundaries(root: string, touchedFiles: string[]): Promise<ContractBoundary[]>;
declare function injectContractBoundaryCriteria(manifest: PlanningManifest, boundaries: ContractBoundary[]): PlanningManifest;

declare function appendPlanningAudit(projectRoot: string, level: 'INFO' | 'WARN', event: string, fields?: Record<string, unknown>): void;

declare const DECISION_AUDIT_EVENTS: readonly ["decision-pending-written", "decision-resolved-by-human", "decision-resolved-by-rule", "decision-resolved-by-memoization", "decision-resolved-by-rag-confident", "decision-reused", "decision-expired", "decision-superseded", "decision-delegated", "undeclared-decision-flagged", "decision-discarded"];
type DecisionAuditEventType = (typeof DECISION_AUDIT_EVENTS)[number];
interface DecisionAuditEvent {
    event: DecisionAuditEventType;
    decision_id: string;
    fingerprint: string;
    task_session_id: string;
    provider: string;
    timestamp: string;
    category?: DecisionCategory;
    responded_by?: string;
    chosen_option_key?: string | null;
    intent?: DecisionIntent;
}
declare function appendDecisionAuditEvent(projectRoot: string, event: DecisionAuditEvent): string;
declare function ensureDecisionAuditLog(projectRoot: string): string;
declare function readDecisionAuditEvents(projectRoot: string): DecisionAuditEvent[];

interface DecisionCopyIssue {
    field: string;
    message: string;
}
declare function lintDecisionCopy(packet: DecisionPacket): DecisionCopyIssue[];

/**
 * Decision-pause event family (PQD-101).
 *
 * The engine streams named, typed events whenever a decision packet is
 * persisted, resolved, found corrupt, refused for exceeding the pending cap, or
 * discarded — so a consumer (the desktop Decision Pause panel) can react live
 * without ever polling `.paqad/decisions/pending/`.
 *
 * The event *shapes* live in the unified engine event union (PQD-99,
 * {@link EngineEvent}) so every decision event is multiplexed into the single
 * stream a consumer already subscribes to. This module owns the planning-domain
 * concerns: the discriminant set, a narrowed {@link DecisionPauseEvent} alias,
 * and the builder functions {@link DecisionStore} uses to assemble each event.
 */

/** The `kind` discriminants that make up the decision-pause event family. */
declare const DECISION_PAUSE_EVENT_TYPES: readonly ["decision-paused", "decision-resolved", "decision-packet-corrupt", "decision-cap-exceeded", "decision-discarded"];
/** Union of the decision-pause event discriminants. */
type DecisionPauseEventType = (typeof DECISION_PAUSE_EVENT_TYPES)[number];
/** The subset of {@link EngineEvent} that belongs to the decision-pause family. */
type DecisionPauseEvent = Extract<EngineEvent, {
    kind: DecisionPauseEventType;
}>;
/** A sink that receives decision-pause events as they occur. */
type DecisionEventSink = (event: DecisionPauseEvent) => void;
/**
 * Build a `decision-paused` event from a freshly persisted packet. `packetPath`
 * is project-relative so streamed payloads never leak the user's home path.
 */
declare function decisionPausedEvent(packet: DecisionPacket, packetPath: string): DecisionPausedEvent;
/** Build a `decision-resolved` event from a resolved packet. */
declare function decisionResolvedEvent(packet: DecisionPacket, resolver: string): DecisionResolvedEvent;
/** Build a `decision-packet-corrupt` event for a malformed pending packet. */
declare function decisionPacketCorruptEvent(decisionId: string, reason: string): DecisionPacketCorruptEvent;
/** Build a `decision-cap-exceeded` event when a new pause is refused. */
declare function decisionCapExceededEvent(pendingCount: number, cap: number): DecisionCapExceededEvent;
/** Build a `decision-discarded` event for an explicitly dropped packet. */
declare function decisionDiscardedEvent(decisionId: string, reason: string): DecisionDiscardedEvent;

interface DetectedDecisionFork {
    category: DecisionCategory;
    confidence: number;
    signal: string;
    matched_text: string;
}
declare function detectDecisionForks(request: string): DetectedDecisionFork[];

interface EvidenceInput {
    projectRoot: string;
    file: string;
    category: DecisionCategory;
    similarity?: number;
}
declare function assembleDecisionEvidence(input: EvidenceInput): DecisionOptionEvidence;
declare function countFileReferences(projectRoot: string, file: string): number;
declare function defaultSimilarityFor(category: DecisionCategory, fileExists: boolean, callers: number): number;

interface RepoStateSignatureInput {
    active_capabilities?: ActiveCapability[];
    stack?: string | null;
    packs?: string[];
}
interface DecisionFingerprintInput {
    category: DecisionCategory;
    question: string;
    option_keys: string[];
    repo_state: RepoStateSignatureInput;
}
declare function computeDecisionFingerprint(input: DecisionFingerprintInput): string;
declare function normalizeDecisionQuestion(value: string): string;
declare function buildRepoStateSignature(input: RepoStateSignatureInput): string;
declare function scoreDecisionOptionOverlap(left: string[], right: string[]): number;

interface BuildDecisionPacketInput {
    projectRoot: string;
    requestedBy: string;
    taskSessionId: string;
    decisionId: string;
    category: DecisionCategory;
    detectorConfidence: number;
    context: SliceContext;
    manifest: PlanningManifest;
}
declare function buildDecisionPacket(input: BuildDecisionPacketInput): DecisionPacket;
declare function computePacketConfidence(options: DecisionOption[], recommendation: string | null, detectorConfidence: number): number;
declare function decisionQuestionForCategory(category: DecisionCategory): string;
declare function decisionOptionsForCategory(projectRoot: string, category: DecisionCategory, targetFile: string): {
    options: DecisionOption[];
};
declare function selectViableDecisionOptions(projectRoot: string, options: DecisionOption[]): DecisionOption[];

type DecisionResolutionSource = 'rule' | 'design-system' | 'profile' | 'rag-confident' | 'ask';
interface DecisionResolutionResult {
    source: DecisionResolutionSource;
    option_key?: string;
    reason?: string;
}
declare function resolveDecisionPacket(projectRoot: string, packet: DecisionPacket): Promise<DecisionResolutionResult>;
declare function askThresholdForProject(projectRoot: string): number;

interface DecisionIndexEntry {
    decision_id: string;
    fingerprint: string;
    category: string;
    chosen_option_key: string | null;
    responded_at: string;
    status: DecisionStatus;
    option_keys: string[];
}
interface DecisionIndexFile {
    fingerprints: Record<string, string>;
    decisions: Record<string, DecisionIndexEntry>;
}
interface ResolveDecisionInput {
    decisionId: string;
    humanResponse: DecisionHumanResponse;
    respondedByProvider?: string;
}
interface ResolveExistingDecisionInput {
    packet: DecisionPacket;
    humanResponse: DecisionHumanResponse;
    event: DecisionAuditEventType;
    respondedByProvider?: string;
}
interface ReadPendingResult {
    packet: DecisionPacket | null;
    error?: string;
}
interface DeferUndeclaredDecisionInput {
    packet: DecisionPacket;
    provider?: string;
}
interface DiscardDecisionInput {
    decisionId: string;
    reason: string;
}
/**
 * Default per-project cap on simultaneously pending decision packets (PQD-101).
 * Overridable via `custom.decisions.max_pending` in `.paqad/project-profile.yaml`.
 */
declare const MAX_PENDING_DECISIONS = 20;
/**
 * Thrown by {@link DecisionStore.writePending} when creating a new pending
 * packet would meet or exceed the per-project pending cap. Carries the counts
 * so a caller can emit a `decision-cap-exceeded` event and prompt the user to
 * triage.
 */
declare class DecisionCapExceededError extends Error {
    readonly pendingCount: number;
    readonly cap: number;
    constructor(pendingCount: number, cap: number);
}
/** Optional hooks supplied when constructing a {@link DecisionStore}. */
interface DecisionStoreOptions {
    /**
     * PQD-101 — live decision-event sink. When supplied, the store fires a
     * decision-pause event at each persistence boundary (paused on `writePending`,
     * resolved on any resolution, cap-exceeded on refusal, discarded on
     * `discard`). When omitted the store behaves exactly as before.
     */
    onEvent?: DecisionEventSink;
}
declare class DecisionStore {
    private readonly projectRoot;
    private readonly onEvent?;
    constructor(projectRoot: string, options?: DecisionStoreOptions);
    initialize(): void;
    /**
     * Mint a fresh decision id. Issue #184: ids are now `D-<ULID>` rather than a
     * monotonic `D-{N}`. ULIDs are timestamp-sortable and collision-free across
     * machines, so two developers on parallel branches never allocate the same
     * id (the old `max + 1` walk produced identical ids and hard merge conflicts
     * on real, non-regenerable decision packets). Allocation no longer reads the
     * filesystem, so the per-machine decision lock is gone — it only ever
     * serialised the now-removed directory walk.
     */
    nextDecisionId(): string;
    writePending(packet: DecisionPacket): string;
    /**
     * RAG buildout F25 — surface the top similar prior resolved decisions in the packet's
     * context, so the developer sees the precedents they already set when answering. Pure
     * deterministic ranking (same category + question/context token overlap), capped and
     * best-effort: any failure (or no precedents) returns the packet unchanged, and the
     * block is appended at most once.
     */
    private enrichWithPrecedents;
    /**
     * Refuse a *new* pending packet once the project's pending cap is reached.
     * Re-writing an already-pending packet (same `decisionId`) never trips the
     * cap, since it is excluded from the count. Emits `decision-cap-exceeded`
     * before throwing so a consumer learns of the refusal even though the throw
     * is caught upstream.
     */
    private enforcePendingCap;
    private maxPendingDecisions;
    /**
     * Discard a pending packet with a reason (PQD-101): remove the pending file
     * (never copying it to the resolved directory), record a `decision-discarded`
     * audit entry, emit a `decision-discarded` event, and return the removed
     * packet so a caller has the full context. Throws when no valid pending
     * packet exists for the id.
     */
    discard(input: DiscardDecisionInput): DecisionPacket;
    private emit;
    private relativePendingPath;
    resolve(input: ResolveDecisionInput): string;
    resolveExisting(input: ResolveExistingDecisionInput): string;
    deferUndeclaredDecision(input: DeferUndeclaredDecisionInput): string;
    findReusableDecision(packet: Pick<DecisionPacket, 'fingerprint' | 'category' | 'options'>): string | null;
    /**
     * Mirror a reuse into the git-ignored decision-reuse ledger (the same substrate
     * as the rag/stage evidence ledgers). Best-effort — the recorder swallows its own
     * errors, so a ledger failure can never disrupt decision resolution.
     */
    private recordReuseToLedger;
    readPending(decisionId: string): DecisionPacket | null;
    readPendingResult(decisionId: string): ReadPendingResult;
    readResolved(decisionId: string): DecisionPacket | null;
    deletePending(decisionId: string): void;
    listPendingDecisionIds(): string[];
    findPendingDecisionForTask(taskSessionId: string): string | null;
    expireResolvedDecision(decisionId: string): string;
    hasInvalidation(packet: DecisionPacket): boolean;
    private readPacket;
    private readReusableDecision;
    private assertWritablePacket;
    private appendAudit;
    private readIndex;
    private writeIndex;
    private indexPath;
    private packetPath;
    private listDirectoryIds;
    private writeResolvedPacket;
    private supersedeConflictingDecision;
}

declare function predictTokenCeiling(root: string, options: {
    lane: PlanningLane;
    complexity: ManifestComplexity;
    scope?: string;
}): Promise<number>;
declare function appendCostEntry(root: string, entry: PlanningCostEntry): Promise<void>;
declare function readCostLog(root: string): Promise<PlanningCostLog>;

declare function buildCoverageOverlay(root: string, modules: string[]): Promise<CoverageOverlayEntry[]>;
declare function markCriteriaFromOverlay(criteria: VerificationCriterion[], overlay: CoverageOverlayEntry[]): VerificationCriterion[];

declare function queryMatchingDefectPatterns(options: {
    stack: string;
    affectedModules: string[];
}): Promise<DefectPatternEntry[]>;
declare function injectDefectAdvisoryCriteria(manifest: PlanningManifest, patterns: DefectPatternEntry[]): PlanningManifest;

declare function mergeDeltaManifest(base: PlanningManifest, delta: PlanningManifest): PlanningManifest;
declare function computeDelta(base: PlanningManifest, updated: PlanningManifest): ManifestDelta;

declare function resolveDocTargets(root: string, executionSlices: ExecutionSlice[], apiImpact?: string | null, uiImpact?: string | null): Promise<DocTarget[]>;

interface FullSuiteRunResult {
    total_tests: number;
    passing: number;
    failing: number;
    failing_tests: string[];
    duration_ms: number;
}
type FullSuiteRunner = () => Promise<FullSuiteRunResult>;
declare function verifyFullSuite(runFullSuite: FullSuiteRunner, baselineFailingTests?: string[]): Promise<SliceFullSuiteCheck>;

declare function assembleIntelligence(root: string, classification: ManifestClassification): Promise<IntelligenceContext>;

declare function loadManifest(root: string, slug: string): Promise<PlanningManifest>;
declare function saveManifest(root: string, manifest: PlanningManifest): Promise<string>;
declare function manifestExists(root: string, slug: string): Promise<boolean>;
declare function listManifestSlugs(root: string): Promise<string[]>;
declare function computeManifestHash(manifest: PlanningManifest): string;

interface ValidationIssue {
    code: string;
    message: string;
    path?: string;
}
interface ManifestValidationError extends ValidationIssue {
    severity: 'error';
}
interface ValidationReport {
    valid: boolean;
    errors: ManifestValidationError[];
    warnings: ValidationIssue[];
}

declare function deriveHealthTier(metrics: ModuleHealthMetrics): HealthTier;
declare function readModuleHealth(root: string, moduleName: string): Promise<ModuleHealthProfile | null>;
declare function writeModuleHealth(root: string, moduleName: string, metrics: ModuleHealthMetrics): Promise<ModuleHealthProfile>;
declare function writeModuleHealthProfile(root: string, profile: ModuleHealthProfile): Promise<ModuleHealthProfile>;
declare function readAllModuleHealth(root: string): Promise<ModuleHealthProfile[]>;
declare function initializeModuleHealth(root: string, moduleName: string): Promise<ModuleHealthProfile>;
declare function moduleHealthPath(root: string, moduleName: string): string;

interface ModuleHealthEvidence {
    schema_version: 1;
    event_id: string;
    source: 'provider-hook' | 'workflow-phase' | 'verification-gate' | 'preflight' | 'session-artifact';
    provider?: string;
    session_id?: string;
    created_at: string;
    affected_files: string[];
    affected_modules: string[];
    signals: {
        tests?: {
            status?: 'pass' | 'fail' | 'partial' | 'unknown';
            passed?: number;
            failed?: number;
            errored?: number;
            coverage_pct?: number;
        };
        verification?: {
            status?: 'pass' | 'fail' | 'partial' | 'unknown';
            gates_passed?: string[];
            gates_failed?: string[];
        };
        compliance?: {
            covered_obligations?: number;
            total_obligations?: number;
            uncovered_critical?: number;
        };
        defects?: {
            new?: number;
            recurring?: number;
            resolved?: number;
        };
        mutation?: {
            kill_rate?: number;
            confidence?: 'mature' | 'lower';
        };
        docs?: {
            doc_targets_total?: number;
            doc_targets_updated?: number;
            doc_targets_missing?: number;
        };
        scope?: {
            scope_clean?: boolean;
            scope_violations?: number;
        };
    };
}
interface ModuleHealthSyncOptions {
    projectRoot: string;
    source?: ModuleHealthEvidence['source'];
    provider?: string;
    sessionId?: string;
    silent?: boolean;
    preflight?: boolean;
}
interface ModuleHealthSyncResult {
    processed_events: number;
    updated_profiles: string[];
    skipped: boolean;
    reason?: string;
}
declare function syncModuleHealth(options: ModuleHealthSyncOptions): Promise<ModuleHealthSyncResult>;
declare function syncModuleHealthFromVerification(input: {
    projectRoot: string;
    provider?: string;
    sessionId?: string;
    verificationContext: VerificationContext;
    results: GateResult[];
}): Promise<ModuleHealthSyncResult>;
declare function createEvidence(input: {
    source: ModuleHealthEvidence['source'];
    provider?: string;
    sessionId?: string;
    affectedFiles?: string[];
    affectedModules?: string[];
    signals?: ModuleHealthEvidence['signals'];
}): ModuleHealthEvidence;
declare function persistEvidence(projectRoot: string, evidence: ModuleHealthEvidence): Promise<void>;
declare function toProjectRelative(projectRoot: string, path: string): string;

declare function computePlanVsActual(manifest: PlanningManifest, actual: PlanVsActualSnapshot): PlanVsActualDiff;
declare function writePlanVsActual(root: string, slug: string, diff: PlanVsActualDiff): Promise<string>;

/** A switchable gate level (issue #512 B.3): off | advisory (warn) | required (strict). */
type GateMode = 'off' | 'warn' | 'strict';
/**
 * How firmly the specification stage adopts the pipeline once it is enabled (issue #547, FR-1.1):
 * `warn` (default) tells the agent to use the pipeline but still freezes a hand-written spec,
 * recording `pipeline.produced=false`; `strict` refuses a non-pipeline spec at freeze unless
 * `--manual --reason` is given. No effect while the pipeline is off.
 */
type AdoptionMode = 'warn' | 'strict';
interface PipelineConfig {
    /** Master switch. Off by default ⇒ feature-development is byte-identical to today (FR-11). */
    enabled: boolean;
    /** The switchable clarification (question-round) gate. */
    clarification: GateMode;
    /** The switchable final-review gate before freeze. */
    final_review: GateMode;
    /** Per-run model-token ceiling; exceeding it is a recorded warning, never a block. */
    token_ceiling: number;
    /**
     * Phase 2 expert roster (issue #521). Off by default ⇒ zero Phase 2 code runs and a run is
     * byte-identical to v1 (P2-INV-1). Only meaningful when {@link PipelineConfig.enabled} is on.
     */
    experts_enabled: boolean;
    /**
     * How firmly the specification stage adopts the pipeline (issue #547). `warn` by default; only
     * meaningful when {@link PipelineConfig.enabled} is on.
     */
    adoption: AdoptionMode;
    /**
     * The experts that sit at the table on every run (issue #558). Defaults to the four
     * {@link DEFAULT_STANDING_EXPERTS}; a team may override with `spec_pipeline_standing_experts`.
     * Unknown or non-expert ids are dropped (see {@link PipelineConfig.standing_experts_dropped}).
     * An empty string means no standing experts — the detector alone decides, as before.
     */
    standing_experts: AgentRole[];
    /** The ids in the knob that were dropped because they are not expert roles (the recorded warning). */
    standing_experts_dropped: string[];
}

/** The clarity label S1 produces, judged against the S0 grounding. */
type ClarityLabel = 'vague' | 'okay' | 'clear';
/** A reference pulled during grounding — a pointer, never a copy (FR-2.2). */
interface GroundingReference {
    kind: 'doc' | 'glossary' | 'rule';
    ref: string;
}
/** Which grounding source produced the artifact — recorded so a run is honest (#520, FR-2.1). */
type GroundingPath = 'rag' | 'docs-fallback';
/** S0 output — `grounding.json`. References plus the vocabulary terms S1/S2 ground on. */
/**
 * One vocabulary entry the project already uses (issue #558, FR-3.1). `term` is the word to say;
 * `definition` is the one-line gloss when the source carried one; `kind` is where it came from;
 * `source` is the doc path it was read from. These are what an expert must name things in.
 */
interface VocabularyEntry {
    term: string;
    definition?: string;
    kind: 'glossary' | 'role' | 'flow' | 'rule' | 'technical';
    source: string;
}

/**
 * How a finding maps onto a spec line (issue #547, FR-4.3). `requirement` → FR/NFR,
 * `invariant` → INV, `acceptance` → AC, `risk` → an NFR or a failure-path AC, `non-goal` →
 * the `## Non-goals` section.
 */
type FindingKind = 'requirement' | 'invariant' | 'acceptance' | 'risk' | 'non-goal';
/** How strongly the expert holds a finding (issue #547, FR-4.3). */
type FindingSeverity = 'must' | 'should' | 'could';

type FinishOutcome = 'freeze' | 'non-blocking-review' | 'await-human-approval';
/** Question counts recorded for provenance/metrics (FR-7.6). */
interface QuestionCounts {
    asked: number;
    answered: number;
    auto_answered: number;
    deferred: number;
}

/** A requirement kind — the id prefix. */
type RequirementKind = 'FR' | 'NFR' | 'AC' | 'INV';
/** One trace row: a stable id, its kind, and the source it derives from. */
interface TraceEntry {
    id: string;
    kind: RequirementKind;
    source: string;
}
/** The `trace.json` artifact. */
interface TraceArtifact {
    entries: TraceEntry[];
}

/**
 * How a spec frozen before issue #581 recorded that it was produced (issue #547, FR-9.1). No
 * writer produces it any more: a record frozen since #581 carries the `task`, `grounding`,
 * `pipeline` and `trace` sections instead, and no `run_dir` (D6). Readers still accept it on an
 * old record (INV-8).
 */
interface SpecProvenance {
    /** Whether the spec pipeline crafted this spec. */
    pipeline_produced: boolean;
    /** The run scratch directory the provenance was read from. */
    run_dir?: string;
    /** The S1 clarity label the run recorded. */
    label?: ClarityLabel;
    /** The grounding shape: whether the touched area was sparse, and which path grounded it. */
    grounding?: {
        sparse: boolean;
        path: GroundingPath;
    };
    /** The S2 question counts (asked / answered / auto-answered / deferred). */
    questions?: QuestionCounts;
    /** The experts consulted and how their notes fared. */
    experts?: {
        roles: AgentRole[];
        accepted: number;
        declined: number;
        conflicts: number;
        auto_resolved: number;
        /** How many of the seated experts were standing (issue #558, FR-8.2). Additive, optional. */
        standing?: number;
        /** How many findings the chief renamed to the project's word (issue #558, FR-8.2). */
        renamed?: number;
    };
    /**
     * A durable snapshot of every accepted finding, copied at freeze so the expert's own words
     * survive the scratch cleanup (issue #558, FR-13.1). Additive and optional; absent when the
     * pipeline is off or no expert fired.
     */
    findings?: AcceptedFinding[];
    /** The traceability artifact tying every spec line to its source (issue #547, FR-8.2). */
    trace?: TraceArtifact;
    /** Why the spec was frozen without the pipeline, under strict adoption (FR-9.3). */
    manual_reason?: string;
}
/** One accepted expert finding, snapshotted onto the frozen spec (issue #558, FR-13.1). */
interface AcceptedFinding {
    id: string;
    role: AgentRole;
    kind: FindingKind;
    severity: FindingSeverity;
    target: string;
    claim: string;
}
/** The `task` section: what the pipeline's task step said the change is for (issue #581). */
interface SpecTaskSection {
    intent: string;
    scope: Record<string, unknown>;
}
/**
 * The `grounding` section: which path grounded the request, whether the area was thin, and the
 * references it read. The terms the plain-language checks use stay in staging (issue #581).
 */
interface SpecGroundingSection {
    path: GroundingPath;
    sparse: boolean;
    references: GroundingReference[];
    /**
     * The project vocabulary (issue #558, FR-3.1), persisted so a brief's Project voice section is
     * reproducible after freeze and the brief hash stays stable (AC-8). Absent on a pre-#558 record.
     */
    vocabulary?: VocabularyEntry[];
}
/**
 * The `pipeline` section (issue #581, D4): whether the spec pipeline produced the spec, and how
 * its run finished. The enforcement settings are stored here once and nowhere else in the bundle.
 * A spec frozen without the pipeline while it was enabled records `produced: false`, with
 * `manual_reason` when it was frozen with `--manual --reason`.
 */
interface SpecPipelineSection {
    produced: boolean;
    outcome?: FinishOutcome;
    reason?: string;
    a5_live?: boolean;
    enforcement?: Omit<PipelineConfig, 'enabled'>;
    manual_reason?: string;
    /** The experts consulted and how their notes fared (issue #558, FR-8.2 / FR-13). */
    experts?: {
        roles: AgentRole[];
        accepted: number;
        declined: number;
        conflicts: number;
        auto_resolved: number;
        standing: number;
        on_call: string[];
        renamed: number;
    };
    /**
     * A durable snapshot of every accepted finding (after the chief's renames), so the expert's own
     * words survive the scratch cleanup (issue #558, FR-13.1). Absent when no expert fired.
     */
    findings?: AcceptedFinding[];
}
/**
 * The `trace` map (issue #581, owner decision D-01M3BJWGYHMZ6JHSEE09QTS4FM): every requirement
 * id (`FR-n`, `NFR-n`, `AC-n`, `INV-n`) mapped to where it came from, `ticket:<section>` or an
 * `EX-*` finding id in `experts.json`.
 */
type SpecTraceMap = Record<string, string>;
/**
 * Where an invariant ("a rule the feature must never break") came from. Compiled
 * rules and module business rules are auto-suggested at spec-build time; the
 * human can also author one directly. Every invariant must be human-confirmed
 * before the spec can be frozen (issue #102, Open Decision 2).
 */
type FeatureSpecInvariantSource = 'compiled-rule' | 'module-rule' | 'authored';
interface FeatureSpecInvariant {
    invariant_id: string;
    statement: string;
    source: FeatureSpecInvariantSource;
    rule_id?: string;
    confirmed: boolean;
}
/**
 * Snapshot written when a spec is frozen. `spec_hash` pins the exact source
 * markdown the freeze signed off on, so any later edit to the markdown is
 * detectable as drift.
 */
interface FrozenSpecMetadata {
    frozen_at: string;
    spec_hash: string;
    signed_off_by: string;
}
/**
 * What the spec-quality review found at freeze time, folded into the frozen record
 * (issue #401). Freeze runs the review itself and blocks on a critical defect, so this
 * summary is the evidence that it ran — it travels with the spec of record instead of
 * living in a separate `.paqad/compliance/<slug>/spec-review.json` the feature-development
 * flow had to produce by hand. Counts are of OPEN defects; a resolved defect is excluded,
 * matching the freeze evaluation's own semantics.
 */
interface SpecReviewSummary {
    reviewed_at: string;
    defect_count: number;
    by_severity: {
        critical: number;
        major: number;
        minor: number;
    };
}
/**
 * The structured, machine-checkable sidecar generated from a human-readable
 * `.paqad/specs/S-<id>-<slug>.md`. It is rebuilt from the markdown on every
 * freeze (never hand-maintained) so it cannot drift from the source of truth.
 */
interface FeatureSpec {
    /**
     * `'1'` on the builder's output and on a pre-#581 `specification.json`; the bundle record
     * written since issue #581 carries the envelope header, whose `schema_version` is the number 2.
     */
    schema_version: string | number;
    spec_id: string;
    /**
     * The source the spec was built from. In a bundle record written since issue #581 it is
     * always the bundle-relative `spec.md`; an older record names the project-relative source.
     */
    spec_file: string;
    spec_hash: string;
    behaviour: string[];
    acceptance_criteria: VerificationCriterion[];
    invariants: FeatureSpecInvariant[];
    open_questions: string[];
    frozen: FrozenSpecMetadata | null;
    /**
     * Set by `freezeSpec` when a spec-quality review was run for the freeze. Absent on
     * records frozen before issue #401, so readers must tolerate its absence.
     */
    spec_review?: SpecReviewSummary;
    /**
     * Things the change deliberately does NOT do, parsed tolerantly from a `## Non-goals`
     * section of the spec markdown (issue #512, Part B FR-6.4). Optional and additive: a
     * spec authored without the section simply omits it, so pre-#512 records still read and
     * freeze unchanged.
     */
    non_goals?: string[];
    /** The pipeline's task section (issue #581). Only on a spec the pipeline produced. */
    task?: SpecTaskSection;
    /** The pipeline's grounding section (issue #581). Only on a spec the pipeline produced. */
    grounding?: SpecGroundingSection;
    /** How the spec was produced (issue #581). Set only while the spec pipeline is enabled. */
    pipeline?: SpecPipelineSection;
    /** Where each requirement came from (issue #581). Only on a spec the pipeline produced. */
    trace?: SpecTraceMap;
    /** Read-only: a record frozen before issue #581. Never written any more. */
    provenance?: SpecProvenance;
}

/**
 * A cross-slice seam that the assembled work left unwired (issue #104). A slice
 * either depends on another that is absent from the assembly (`dangling`), or it
 * was wired onto an upstream slice whose own frozen criterion was never proven
 * (`upstream-unproven`).
 */
interface ReconnectSeam {
    slice_id: string;
    depends_on: string;
    kind: 'dangling' | 'upstream-unproven';
    detail: string;
}
/**
 * Two slices disagree about the assembly (issue #104): the same frozen
 * criterion is owned by more than one slice (`double-owned`), or a slice claims
 * a criterion that is not in the frozen spec at all (`off-spec`).
 */
interface ReconnectContradiction {
    kind: 'double-owned' | 'off-spec';
    criterion_id: string;
    slice_ids: string[];
    detail: string;
}
interface ReconnectReport {
    coherent: boolean;
    /** False when the spec was never frozen — the check has no written anchor to read. */
    anchored: boolean;
    /** How the reconnect was judged: structural by default, agent re-read on the full lane. */
    review: 'structural' | 'agent-re-read';
    frozen_criteria_total: number;
    /** Frozen criteria no slice covers — coverage gaps against the whole-feature spec. */
    uncovered_criteria: string[];
    /** Frozen criteria a slice covers but whose proof did not pass — built, not proven. */
    unproven_criteria: string[];
    unwired_seams: ReconnectSeam[];
    contradictions: ReconnectContradiction[];
}
interface ReconnectInput {
    spec: FeatureSpec;
    slices: ExecutionSlice[];
    snapshot: PlanVsActualSnapshot;
    lane: PlanningLane;
}
/**
 * The reconnect-to-whole check (issue #104). After the thin slices are built,
 * this confirms the assembled pieces satisfy the **frozen** whole-feature spec —
 * not merely that each slice passed alone. It is a real check, not a stamp: it
 * fails on a coverage gap, an unproven criterion, an unwired cross-slice seam,
 * or two slices that contradict each other.
 *
 * It anchors on the written frozen spec, never on the agent's memory of the
 * feature (the brief's core point — an agent's grip on the whole fades on long
 * jobs). An unfrozen spec yields `anchored: false` and is never coherent.
 *
 * Strength scales with lane (Open Decision 1): structural AC-coverage + seam
 * checks by default, escalating to an agent re-read of the spec on the `full`
 * lane.
 */
declare function computeReconnect(input: ReconnectInput): ReconnectReport;
/**
 * Renders the reconnect result as a human-readable checklist that names exactly
 * what does not fit the whole-feature spec, mirroring the Definition-of-Done
 * checklist (issue #102) so a reader sees the specific gap, not a vague verdict.
 */
declare function renderReconnectReport(report: ReconnectReport): string;

declare function buildRegressionWatchList(root: string, executionSlices: ExecutionSlice[]): Promise<RegressionEntry[]>;

declare function compileRules(root: string): Promise<CompiledRulesStore>;
declare function writeCompiledRules(root: string, store: CompiledRulesStore): Promise<string>;
declare function readCompiledRules(root: string): Promise<CompiledRulesStore | null>;
declare function isCompiledRulesStale(root: string): Promise<boolean>;
declare function computeSourceHash(root: string): Promise<string>;
/**
 * Whether a candidate string looks like a file path / glob trigger, as opposed to prose
 * or a code fragment. A trigger is a single path-shaped token: no whitespace, drawn from
 * the path/glob charset, length-bounded, and carrying a path signal — a separator (`/`),
 * a glob wildcard (`*` / `?`), or a file-extension dot. This is the gate that keeps the
 * inline-code fallback from scooping up arbitrary backtick spans (identifiers, prose, and
 * multi-line code-fence contents) as "triggers", which previously exploded the manifest
 * and produced the `` `, ` `` corruption when those junk patterns were comma-joined.
 */
declare function looksLikeTriggerPattern(candidate: string): boolean;

declare function injectRuleCriteria(manifest: PlanningManifest, compiledRules: CompiledRulesStore | null): PlanningManifest;

declare function emitTestSkeletons(root: string, criteria: VerificationCriterion[], stack: string): Promise<string[]>;

declare function deriveSlug(featureId: string, requestText?: string | null): string;
declare function isSlugSafe(slug: string): boolean;

interface PentestRetestWorkflowOptions {
    projectRoot: string;
    classification: ClassificationResult;
    sourceReportPath?: string;
    targetUrl?: string;
    focusModules?: string[];
    dbConnectionName?: string;
}
interface PentestRetestWorkflowResult {
    run_id: string;
    report_id: string;
    report_path: string;
    sidecar_path: string;
}
declare class PentestRetestWorkflow {
    private readonly introspector;
    private readonly tracker;
    run(options: PentestRetestWorkflowOptions): Promise<PentestRetestWorkflowResult>;
}

interface PentestWorkflowOptions {
    projectRoot: string;
    classification: ClassificationResult;
    targetUrl?: string;
    focusModules?: string[];
    dbConnectionName?: string;
    incremental?: boolean;
    lastRunId?: string;
}
interface PentestWorkflowResult {
    run_id: string;
    report_id: string;
    report_path: string;
    sidecar_path: string;
}
declare class PentestWorkflow {
    private readonly introspector;
    private readonly tracker;
    run(options: PentestWorkflowOptions): Promise<PentestWorkflowResult>;
}
declare function buildCurrentPentestReport(input: {
    projectRoot: string;
    classification: ClassificationResult;
    snapshot: Awaited<ReturnType<StackIntrospector['snapshot']>>;
    targetUrl: string | null;
    focusModules: string[];
    blockedChecks: string[];
    artifactsDir: string;
    progressRunId: string;
    reportTimestamp: Date;
}): Promise<PentestReportIndex>;

interface RootCauseAnalysisWorkflowOptions {
    projectRoot: string;
    classification: ClassificationResult;
}
interface RootCauseAnalysisWorkflowResult {
    output_path: string;
    title: string;
}
declare class RootCauseAnalysisWorkflow {
    run(options: RootCauseAnalysisWorkflowOptions): Promise<RootCauseAnalysisWorkflowResult>;
}

interface StepCondition {
    complexity?: string[];
    risk?: string[];
    workflow?: string[];
}
type OnFailureDirective = 'skip' | 'abort' | 'retry';
interface WorkflowStep {
    skill: string;
    condition?: StepCondition;
    on_failure?: OnFailureDirective;
}
interface ParallelGroup {
    parallel: WorkflowStep[];
    on_failure?: OnFailureDirective;
}
type TemplateStep = WorkflowStep | ParallelGroup;
interface WorkflowTemplate {
    name: string;
    description: string;
    triggers?: {
        workflow?: string[];
        complexity?: string[];
        risk?: string[];
    };
    steps: TemplateStep[];
}
interface WorkflowStepProgress {
    index: number;
    skill: string | null;
    type: 'sequential' | 'parallel';
    status: 'not_started' | 'running' | 'completed' | 'skipped' | 'failed' | 'aborted' | 'cancelled';
    started_at: string | null;
    completed_at: string | null;
    error: string | null;
}
interface WorkflowRunProgress {
    schema_version: '1';
    run_id: string;
    template_name: string;
    status: 'running' | 'completed' | 'failed' | 'aborted' | 'cancelled';
    started_at: string;
    updated_at: string;
    steps: WorkflowStepProgress[];
    /**
     * Number of steps that completed before a consumer cancellation (PQD-104).
     * Set only when `status === 'cancelled'`; lets the consumer resume from the
     * first not-yet-completed step.
     */
    cancelled_steps_completed?: number;
}

declare class WorkflowTemplateLoader {
    private readonly projectRoot;
    constructor(projectRoot: string);
    get workflowsDir(): string;
    load(workflowName: string): Promise<WorkflowTemplate>;
    list(): Promise<string[]>;
}

declare class WorkflowTemplateValidator {
    validate(template: WorkflowTemplate, availableSkills: Set<string>): {
        valid: boolean;
        errors: string[];
    };
    isParallelGroup(step: TemplateStep): step is ParallelGroup;
}

interface StepExecutionContext {
    classification: {
        complexity?: string;
        risk?: string;
        workflow?: string;
        [key: string]: unknown;
    };
}
interface StepExecutionResult {
    status: 'completed' | 'skipped' | 'failed';
    error?: string;
}
interface WorkflowStepRunner {
    execute(step: WorkflowStep, signal?: AbortSignal): Promise<StepExecutionResult>;
}
interface StepExecutorOptions {
    sessionId?: string;
    stackKey?: string;
    predictiveCache?: PredictiveCache;
    skillCacheManager?: SkillCacheManager;
}
declare class StepExecutor implements WorkflowStepRunner {
    private readonly context;
    private readonly sessionId;
    private readonly stackKey;
    private readonly predictiveCache;
    private readonly skillCacheManager;
    private lastSkill;
    constructor(context: StepExecutionContext, options?: StepExecutorOptions);
    shouldExecute(step: WorkflowStep): boolean;
    execute(step: WorkflowStep, signal?: AbortSignal): Promise<StepExecutionResult>;
    /** Exposed for testing only. */
    getLastSkill(): string | undefined;
    protected runStep(payload: WorkflowStep): Promise<void>;
    private evaluateCondition;
}

interface ParallelResult {
    results: Array<{
        skill: string;
        status: 'completed' | 'skipped' | 'failed';
        error?: string;
    }>;
    overall: 'completed' | 'failed' | 'skipped' | 'cancelled';
}
declare class ParallelExecutor {
    private readonly stepExecutor;
    constructor(stepExecutor: WorkflowStepRunner);
    execute(group: ParallelGroup, signal?: AbortSignal): Promise<ParallelResult>;
    /**
     * Resolve as soon as either the group settles or the consumer aborts, so a
     * cancellation returns control within a bounded delay even if some in-flight
     * branch is slow (PQD-104).
     */
    private raceAgainstAbort;
    private executeGroup;
}

/** Per-call options for cancellable workflow runs (PQD-104). */
interface WorkflowRunOptions {
    /**
     * Optional consumer cancellation signal. When it aborts, the run settles at
     * the next step boundary with `status: 'cancelled'`, emits a single
     * `run.cancelled` event, and persists progress atomically so the consumer can
     * resume from the first not-yet-completed step.
     */
    signal?: AbortSignal;
}
interface WorkflowEngineOptions {
    projectRoot: string;
    availableSkills: Set<string>;
    createStepExecutor?: (context: StepExecutionContext) => WorkflowStepRunner;
    /**
     * Optional engine event bus (PQD-99). When provided, the engine emits
     * `workflow-step-started` before each step and `workflow-step-completed` /
     * `workflow-step-failed` after it, so consumers can render progress live.
     * Omitting it leaves behaviour unchanged.
     */
    eventBus?: EngineEventBus;
}
declare class WorkflowEngine {
    private readonly options;
    private readonly loader;
    private readonly validator;
    constructor(options: WorkflowEngineOptions);
    getRegisteredWorkflowIds(): Promise<string[]>;
    run(templateName: string, context: StepExecutionContext, options?: WorkflowRunOptions): Promise<WorkflowRunProgress>;
    resume(runId: string, templateName: string, context: StepExecutionContext, options?: WorkflowRunOptions): Promise<WorkflowRunProgress>;
    private executeSteps;
    private initProgress;
    private progressPath;
    private saveProgress;
    /**
     * Settle the run as cancelled-by-consumer (PQD-104): record how many steps
     * finished, persist atomically, and emit exactly one `run.cancelled` event.
     * Callers return immediately afterward so no further events for this run follow.
     */
    private cancelRun;
    private loadProgress;
    private loadAndValidateTemplate;
    private executeSequentialStep;
}

declare const VERSION: string;
declare function getFrameworkName(): string;

export { ACTIVE_CAPABILITY_ORDER, AC_ID_PATTERN, ADAPTER_TYPES, AGENT_ROLES, AIDetector, type AIDetectorOptions, ANALYTICS_CONFLICTS, ANALYTICS_DECISION_PATH, ANALYTICS_PROVIDERS, ANALYTICS_STRICTNESS_MODES, ANSWER_GROUNDING_STATES, ANSWER_MODES, ARTIFACT_OUTPUT_KEYS, ARTIFACT_TYPES, ATTACHMENT_RETRY_BUDGET_MS, AcTestMappingGate, type ActionRecommendation, ActiveCapability, type AdapterCapabilities, type AdapterConfig, type AdapterContext, AdapterFactory, type AdapterHookCoverage, type AdapterInterface, type AdapterType, type AffectedModule, type AgentRole, AiAssistantAdapter, AiderAdapter, type AnalyticsCallSite, type AnalyticsCompletenessResult, type AnalyticsConflict, type AnalyticsConflictKind, type AnalyticsDetection, type AnalyticsGateDecision, type AnalyticsGateInput, AnalyticsGateStatus, type AnalyticsProvider, type AnalyticsProviderId, type AnalyticsStrictness, type AnalyticsSyncEntry, type AnalyticsSyncResult, type AnswerGroundingState, type AnswerMode, type AnswerQuery, AntigravityAdapter, type ApiEndpointDoc, ApiImpact, type ApiMessage, type ApiSchemaField, ArchitectureComplianceGate, type ArchiveInspection, type ArchiveInspector, type ArtifactType, AstChunker, type AttachmentCollectionScope, type AttachmentContentKind, type AttachmentEvent, type AttachmentEventInput, type AttachmentEventKind, type AttachmentEventSink, type AttachmentIndexingDegradedSignal, type AttachmentIndexingOutcome, type AttachmentIndexingResult, type AttachmentOrphanPurgeRecord, AttachmentPathError, type AttachmentRecord, type AttachmentRecordStatus, type AttachmentRejection, type AttachmentRejectionOutcome, type AttachmentRejectionReason, type AttachmentSessionKind, type AttachmentStoredChunk, BACKSTOP_VERIFICATION_ORIGINS, BOUNDARY_SCHEMA_VERSION, BehavioralCorrectnessGate, BenchmarkGateConfig, type BootstrapOptions, type BoundaryInterface, type BoundaryInterfaceReport, type BoundaryManifest, type BoundaryRelationship, type BoundaryReport, type BudgetAllocation, BudgetAllocator, type BudgetBand, type BudgetBreakdown, type BudgetBreakdownError, type BudgetBreakdownSuccess, type BudgetCheckResult, type BudgetClassificationHints, type BudgetDecision, type BudgetEvaluation, type BudgetOptimizerConfig, type BudgetOptimizerState, type BudgetTier, type BudgetVerdict, type BuildCompactArtifactInput, type BuildDecisionPacketInput, type BuildIndexOptions, type BuildRepositoryVerificationContextOptions, type BuildVerificationEvidenceInput, CHUNKER_VERSION, CITATION_SOURCE_CLASSES, CLASSIFICATION_RULES, COLLISION_MAP, COMPLIANCE_EVIDENCE_STRENGTHS, COMPLIANCE_RELATIONS, COMPLIANCE_SCHEMA_VERSION, CONTEXT_LEVELS, CONTEXT_LEVEL_BUDGETS, CRITERION_STATUSES, type CacheMetrics, CacheMetricsTracker, type CacheStats, CacheWarmer, type CancelledByConsumerPayload, CancelledError, type CancelledErrorDetails, type CanonicalDocOwnershipKind, type CanonicalDocTarget, Capability, type ChangeClosureSummary, ChangeCompletenessGate, type CheckComplianceOptions, type Chunk, type ChunkIndex, type ChunkIndexEntry, ChunkIndexManager, type ChunkIndexSyncResult, type Citation, type CitationSourceClass, type ClassificationHint, ClassificationResult, type ClassificationRule, ClassificationScope, ClassificationWorkflow, type ClassifierInput, ClaudeCodeAdapter, CodeTestsLintGate, CodexCliAdapter, type CollisionBehavior, type CompactArtifactResult, type CompactArtifactSummary, type ComparisonMode, CompiledRule, CompiledRulesStore, type CompletedStorySummary, Complexity, type ComplianceClause, type ComplianceEvidenceStrength, type ComplianceFramework, type ComplianceMapping, type CompliancePackManifest, type CompliancePackRegistry, type ComplianceRelation, type ComplianceReport, type ComplianceReportObligation, type ComplianceReportSummary, ComplianceSensitivity, type ComplianceSignal, type ComplianceSignalType, type ComplianceState, type CompressionAuditRecord, type ComputeBudgetInput, ConditionalSectionProcessor, type ConfigurationComparisonResult, type ConsumerCompatibility, type ContextBudget, type ContextBudgetConfig, ContextBudgetEnforcer, type ContextBudgetEstimateInput, ContextBudgetHint, ContextBudgetOptimizer, ContextDeduplicator, ContextEvictor, type ContextHealthWarning, type ContextHitEntry, type ContextHitLog, ContextHitTracker, type ContextLevel, type ContextPriorityTier, type ContextSavingsEntry, type ContextSegmentPriority, ContinueAdapter, type ContractBoundary, type ContractDecisionListEntry, type ContractDecisionOption, type ContractDecisionOrigin, type Contradiction, ContradictionDetector, type ControlLayerAuditRecord, type ConversationRebuildResult, CorruptVectorIndexError, CoverageOverlayEntry, type CreateDecisionInput, type CreateLoggerOptions, type CreatePackOptions, type CrsBacklogPersist, CrsBacklogQueue, type CrsChunk, type CrsChunkInput, type CrsCollectionId, type CrsIndexedSessionEvent, type CrsRetrievalResult, CursorAdapter, CustomerFacingImpact, DECISION_AUDIT_EVENTS, DECISION_PAUSE_EVENT_TYPES, DEFAULT_ANALYTICS_STRICTNESS, DEFAULT_BOUNDARY_REPORT_PATH, DEFAULT_CONTEXT_BUDGET, DEFAULT_CRS_BACKLOG_CAP, DEFAULT_HOOK_ADAPTER, DEFAULT_OBLIGATION_INDEX_PATH, DEFAULT_PREDICTIVE_CACHE_OPTIONS, DEFAULT_REBUILD_CACHE_MAX_SIZE, DEFAULT_REDACTION_ALLOWLIST, DEFAULT_SKILL_AUDIT_BUFFER_CAPACITY, DEFECT_PATTERN_SCHEMA_VERSION, DESIGN_TOKENS_PLACEHOLDER_NOTE, DISCLOSURE_ESCALATION_REASONS, DISCLOSURE_LEVELS, DOC_TYPES, DataRetrievalDecider, DataSensitivity, type DataSource, type DataSourceType, DatabaseImpact, DatabaseQualityGate, type DecisionAuditEvent, type DecisionAuditEventType, DecisionCapExceededError, type DecisionCapExceededEvent, DecisionCategory, type DecisionCopyIssue, type DecisionDiscardedEvent, type DecisionEventOption, type DecisionEventSink, type DecisionFingerprintInput, DecisionHumanResponse, type DecisionIndexFile, DecisionIntent, DecisionOption, DecisionOptionEvidence, DecisionPacket, DecisionPacketCorruptError, type DecisionPacketCorruptEvent, type DecisionPacketCorruptPayload, type DecisionPauseEvent, type DecisionPauseEventType, type DecisionPausedEvent, type DecisionResolutionResult, type DecisionResolutionSource, type DecisionResolvedEvent, DecisionStatus, DecisionStore, type DecisionStoreOptions, type DeduplicationStats, type DeduplicatorArtifact, type DefectFinding, type DefectPatternEntry, type DefectPatternIndex, type DefectPatternIndexEntry, type DefectSource, type DeferUndeclaredDecisionInput, type DeltaDetectionResult, type DeltaReasoningPayload, type DesignTokenDocArtifact, type DesignTokenGroup, type DesignTokenLeaf, type DesignTokenNode, DesignTokenService, type DesignTokensDocument, DesignTokensMissingError, DesignTokensPlaceholderError, type DetectedDecisionFork, DetectedStackProfile, type DetectionReport, type DetectionSignal, Detector, type DetectorOptions, DifferentialRefresh, type DiscardDecisionInput, type DisclosureAuditRecord, type DisclosureEscalationReason, type DisclosureLevel, type DisclosurePolicyInput, type DisclosurePolicyResult, type DisplayMessage, type DocPath, type DocProgressEntry, type DocProgressFile, type DocProgressState, DocTarget, type DocType, type DoctorIssue, type DoctorResult, DocumentPipeline, type DocumentPipelineOptions, DocumentProgressTracker, type DocumentRunResult, type DocumentScope, DocumentationFreshnessGate, DocumentationWorkflow, type DocumentationWorkflowMode, type DocumentationWorkflowOptions, type DocumentationWorkflowResult, type DocumentationWorkflowStep, Domain, type DriftDelta, type DriftFileSnapshot, DuplicateSkillIdentifierError, type DuplicateSkillIdentifierPayload, ENGINE_ERROR_CODES, ESCALATION_REASONS, EVIDENCE_FAILURE_CATEGORIES, EVIDENCE_GATE_STATUSES, EVIDENCE_OVERALL_STATUSES, type EcosystemParser, EcosystemParserRegistry, EmbeddingBacklogOverflow, type EmbeddingProvider, EmbeddingProviderError, type EmbeddingProviderErrorCode, EmbeddingProviderName, type EngineErrorCode, type EngineErrorPayloadBase, type EngineEvent, type EngineEventBase, EngineEventBus, type EngineEventBusOptions, type EngineEventCallback, type EngineEventFilter, type EngineEventKind, type EngineLogEntry, type EngineLogger, type EngineVersionReport, type EnsurePentestRunOptions, type EphemeralCollectionId, type ErrorCatalogEntry, type EscalationDecision, type EscalationReason, type EvalDatasetItem, type EvalQueryClass, type EvalRunResult, type EvalTrace, type EvaluateEscalationInput, type EventGroup, type EventsCoalescedEvent, type EvictionResult, type EvidenceFailureCategory, type EvidenceFile, type EvidenceGateStatus, type EvidenceOverallStatus, EvidenceRetriever, ExecutionSlice, type ExitCode, ExtensionSurfaceGate, type ExtractObligationsOptions, type ExtractionKind, type ExtractionResult, FINDING_SEVERITIES, FRAMEWORK_PACKAGE_MAP, type FileProbeResult, FileRegistryMapper, FileVectorIndex, type FileWriteResult, type FilterDiagnostics, type FilterStats, type FindingSeverity$1 as FindingSeverity, FrameworkError, type FrameworkErrorOptions, FrameworkUpdater, type FrameworkUpdaterOptions, FreshnessChecker, type FreshnessMetadata, type FullSuiteRunResult, type FullSuiteRunner, type FusionDiagnostic, type Gate, type GateResult, GeminiCliAdapter, type GenerateBoundaryTestsOptions, type GenerateVitestSkeletonOptions, type GeneratedBoundaryTest, type GeneratedFile, type GeneratedSkillIndexEntry, GithubCopilotAdapter, HEALTH_CHECK_STATUSES, HEALTH_TIERS, HOOK_COVERAGE_MATRIX, HOOK_EXIT_CODES, HOOK_TRIGGERS, type HandoffArtifact, type HealthCheckResult, type HealthCheckStatus, HealthChecker, type HealthEfficiencySummary, type HealthReport, HealthTier, type HitTrackerInput, type HookDefinition, type HookResult, type HookTrigger, type HostHookEventMap, type ImpactResolutionInput, type ImpactResolutionResult, type ImplementationReviewFinding, ImplementationReviewGate, type IndexAttachmentFailure, type IndexAttachmentOutcome, type IndexAttachmentParams, type IndexAttachmentResult, type InferenceCompleteOptions, type InferenceMessage, type InferenceProvider, InferredTurnClassifierModel, type InheritanceDirectory, type InstallPackOptions, type InstallResult, InstalledPackage, InstructionsDocsStructureGate, type InstrumentedEvent, type IntegrationContract, type IntegrationDoc, type IntegrationEvent, type IntegrationEventPayloadField, IntelligenceConfig, IntelligenceContext, type JudgmentSignal, JunieAdapter, type KnowledgeAnswer, LANE_PHASES, Lane, type LaravelDetectionResult, type ListedPack, type LoadObligationIndexOptions, type LoadSpecReviewOptions, type LoadStats, type LoadedCompliancePack, type LoadedSkill, type LoadedStackPack, type LocalEmbeddingExtractor, type LocalEmbeddingOutput, type LocalEmbeddingProgress, LocalEmbeddingProvider, type LogLevel, LoggerSinkFailedError, type LoggerSinkFailedPayload, type LoggingConfig, MANAGEABLE_ACTIVE_CAPABILITIES, MAX_PENDING_DECISIONS, MCP_SERVERS, MCP_SERVER_TYPES, MIN_CONSUMER_VERSION, ManifestClassification, ManifestComplexity, ManifestDelta, ManifestProductionTimeoutError, type ManifestProductionTimeoutPayload, type ManifestValidationError, McpConfigManager, type McpConfigOutput, type McpServerConfig, type McpServerDefinition, McpServerRegistry, type McpServerType, MissingPolicyContextError, type MissingPolicyContextPayload, type ModelCatalogEntry, type ModelGradedScores, type ModuleDocEvidence, type ModuleDocStage, ModuleDocsStructureGate, type ModuleFeatureEntry, type ModuleHealthEvidence, ModuleHealthMetrics, ModuleHealthProfile, type ModuleHealthSyncOptions, type ModuleHealthSyncResult, type ModuleMap, type ModuleMapEntry, type ModuleResolutionResult, ModuleResolver, NATIVE_HOOK_EVENTS, type Obligation, type ObligationCategory, type ObligationIndex, type ObligationIndexMetadata, type OnFailureDirective, type OnboardingFileTreeEntry, type OnboardingManifest, type OnboardingOptions, OnboardingOrchestrator, type OnboardingOutput, type OnboardingPreviewResult, type OnboardingSelections, type OpenAiEmbeddingClient, OpenAiEmbeddingProvider, type OsvVulnerabilityRecord, PAQAD_HOOK_EVENT_ORDER, PAQAD_LIVE_HOOKS, PAQAD_MUTATING_TOOL_MATCHER, PAQAD_RUNTIME_PREFIX, PAQAD_SCHEMA_VERSION, PAQAD_STAGE_AGENT_MATCHER, PATHS, PDF_PAGE_CAP, PENTEST_EFFORTS, PENTEST_FINDING_STATUSES, PENTEST_RETEST_STATUSES, PENTEST_RUN_STATUSES, PENTEST_RUN_STEP_STATUSES, PENTEST_SEVERITIES, PENTEST_SOURCE_TYPES, PENTEST_WORKFLOWS, PIPELINE_PHASES, PLACEHOLDER_DESIGN_TOKENS, PLANNING_LANES, PLANNING_MANIFEST_VERSION, PLAN_MODES, PROOF_TYPES, type PackInstallSource, type PackManagerRoots, type PackRegistry, type PackValidationIssue, type PackValidationResult, type PaqadHookEvent, type PaqadLiveHookSpec, type PaqadSchemaMarker, ParallelExecutor, type ParallelGroup, type ParallelResult, type ParseAttachmentOptions, type ParseAttachmentResult, type ParseTestOutputOptions, type ParsedAttachment, type ParsedLockfile, type ParsedLockfilePackage, type ParsedManifest, type ParsedManifestPackage, type ParsedProjectResult, type ParsedSkillDocument, type Pattern, type PatternAdvisory, PatternCli, type PatternFilter, type PatternIndex, type PatternIndexEntry, type PatternMatch, type PatternQueryOptions, PatternRecorder, type PatternSemanticScorer, PatternStore, PatternSuggester, PatternVectorService, type PdfExtraction, type PdfTextExtractor, type PendingContractDecision, type PentestCoverageSummary, type PentestEffort, type PentestFinding, type PentestFindingStatus, PentestProgressTracker, type PentestReportIndex, type PentestRetestFinding, type PentestRetestStatus, PentestRetestWorkflow, type PentestRetestWorkflowOptions, type PentestRetestWorkflowResult, type PentestRunProgress, type PentestRunStatus, type PentestRunStep, type PentestRunStepStatus, type PentestRuntimeStatus, type PentestSeverity, type PentestSourceType, PentestWorkflow, type PentestWorkflowName, type PentestWorkflowOptions, type PentestWorkflowResult, type PhaseResult, type PipelineAnalysisRole, type PipelinePhase, type PipelineResult, PipelineRouter, type PipelineRunContext, PlanVsActualDiff, PlanVsActualSnapshot, PlanningCostEntry, PlanningCostLog, PlanningLane, PlanningManifest, type PostClassificationAdjustments, PostClassifier, type PreClassificationResolved, type PreClassificationResult, PreClassifier, type PreClassifierInput, PredictiveCache, type PredictiveCacheOptions, PriorityClassifier, ProjectKnowledgeAnswerer, ProjectProfile, type ProjectScriptResult, type ProviderFactory, type ProviderProgressUpdate, REDACTION_PLACEHOLDER, REGISTRIES, REQUIREMENT_TYPES, RESOLUTION_LAYERS, RETRIEVAL_ESCALATION_SIGNALS, RETRIEVAL_PATHS, REVIEW_DIMENSIONS, REVIEW_MODES, REVIEW_TIERS, ROLE_TOKEN_BUDGETS, ROLLBACK_CLASSES, ROUTING_MECHANISMS, type RagBenchmarkEvaluation, type RagBenchmarkMetricResult, type RagBenchmarkSnapshot, RagFileFilter, type RagFileFilterOptions, type RagIgnoreConfig, type RagIndexMeta, RagIngestError, type RagIngestErrorCode, type RagPromptTokenGateResult, type RagRetrievalResult, type RagScoredCandidate, RagService, type RagStatus, type ReactDetectionResult, type ReadPendingResult, type ReasoningInputPayload, RebuildCache, type RebuildCacheKey, RebuildFailedError, type RebuildInput, type ReconnectContradiction, type ReconnectInput, type ReconnectReport, type ReconnectSeam, type RecordFromComplianceOptions, type RecordPatternInput, type RedactPayloadResult, type RedactionAllowlist, type RedactionEvent, type RefreshResult, type RegistryChangedEvent, RegressionEntry, type ReindexProgressEvent, type ReindexProgressHandler, RelevanceScorer, type RenderedHook, type RepoStateSignatureInput, type RepositoryVerificationContextResult, type RepositoryVerificationGateVerdict, type RepositoryVerificationVerdict, RequestClassifier, type RequestClassifierOptions, RequirementCompletenessGate, ResolutionError, type ResolutionLayer, ResolutionMap, ResolutionSource, type ResolveDecisionInput, type ResolveExistingDecisionInput, type ResolvedArtifact$1 as ResolvedArtifact, type ResolvedArtifacts, type ResolvedContractDecision, Resolver, type ResolverOptions, type RetrievalAuditRecord, type RetrievalCompletedEvent, type RetrievalDepth, type RetrievalEscalationSignal, type RetrievalGateInput, type RetrievalGateResult, type RetrievalPath, type RetrievalStartedEvent, type RetrievedChunkRef, Reversibility, type ReviewDimension, type ReviewFinding, type ReviewMode, type ReviewReport, type ReviewSpecOptions, type ReviewTier, Risk, RootCauseAnalysisWorkflow, type RootCauseAnalysisWorkflowOptions, type RootCauseAnalysisWorkflowResult, type RoutingAuditRecord, RoutingConfig, type RoutingInput, type RoutingMechanism, type RoutingResult, type RunRepositoryVerificationOptions, RunnerScriptGenerator, type RuntimeSkillDescriptor, type RuntimeSkillListEntry, RuntimeSkillRegistry, SINGLE_TEST_SELECTORS, SKILL_MODEL_TIERS, SKILL_OUTPUT_FORMATS, SPEC_REVIEW_SCHEMA_VERSION, STABILITY_LEVELS, STRUCTURED_TEST_FORMATS, SUPPORTED_CAPABILITIES, SUPPORTED_DOMAINS, SUPPORTED_EXTRACTION_KINDS, SUPPORTED_STACKS, SUPPORTED_VISION_EXTENSIONS, SURFACE_DOC_PATH, type SaveObligationIndexOptions, type SaveSpecReviewOptions, type ScanBoundariesOptions, type SchemaCompatibility, type SchemaMigrationRecord, type SchemaValidationIssue, SchemaValidator, SchemaVersionError, type SchemaVersionErrorOptions, type ScopeResolutionResult, type ScoringContext, type SemanticLoadClassification, type SemanticLoadOptions, SemanticLoader, type SemanticLoaderOptions, SessionAttachmentIndexer, type SingleTestSelector, SiteMapFreshnessGate, SkillAuditBuffer, type SkillAuditEvent, type SkillAuditEventType, type SkillCacheEntry, SkillCacheManager, type SkillCacheResult, type SkillCompletionTrigger, type SkillDefinition, SkillFrontmatterParser, type SkillInputSchema, type SkillInputSchemaField, type SkillLoadFailedEvent, SkillLoader, type SkillModelTier, type SkillOutputFormat, type SkillPackLoadFailedEvent, SkillRegistrationError, type SkillRegistrationErrorKind, type SkillRegistrationErrorOptions, type SkillRequestRoutingRule, type SkillResult, type SkillSource, type SkillTriggerCondition, SkillTriggerEvaluator, type SliceCompletedEvent, SliceContext, type SliceFailedEvent, SliceFullSuiteCheck, type SliceStartedEvent, type SpecDefectSeverity, type SpecPatternAdvisory, type SpecReviewDefect, type SpecReviewDefectCategory, type SpecReviewDefectStatus, SpecReviewGate, type SpecReviewLocation, type SpecReviewReport, type SpecReviewReportMetadata, type StabilityLevel, Stack, type StackContext, type StackDetectionPermissions, type StackDetectionResource, StackDriftReport, StackEcosystem, StackIntrospector, type StackPackAstManifest, type StackPackAuditCommand, type StackPackDetectionRule, type StackPackDocsManifest, type StackPackFieldRule, StackPackLoader, type StackPackLoaderOptions, type StackPackManifest, type StackPackMcpDefault, type StackPackModuleHealthManifest, type StackPackPentestCheckMap, type StackPackRagManifest, type StackPackTestRunner, type StackPackTestRunnerParallel, type StackPackTestingFramework, type StackPackToolchainManifest, type StackPackTraitManifest, StackSnapshot, StackSnapshotCache, StackSourceReference, type StepCondition, type StepExecutionContext, type StepExecutionResult, StepExecutor, type StepExecutorOptions, type StoredContractDecision, type StoredPatternVector, type StoredVectorChunk, type StoredVectorItem, type StoredVisionChunk, StoryQualityGate, StreamTruncator, type StructuredLogRecord, type StructuredLogger, type StructuredTestFormat, type StructuredTestIssue, type StructuredTestParseMetadata, type StructuredTestResult, type StructuredTestSummary, type StructuredTestWarning, type SubagentConfig, type Subscription, type SubscriptionState, type SummarisationMessage, type SummariseFailure, type SummariseOptions, type SummariseResult, type SummariseSuccess, type SummarizedTurn, type SurfaceEntry, type SuspiciousRoute, type SvelteDetectionResult, TASK_COMPLEXITIES, TEST_ISSUE_CATEGORIES, TEST_OUTPUT_SCHEMA_VERSION, TEST_PARSE_STRATEGIES, TEST_RUNNER_OUTPUT_SOURCES, TEST_RUNNER_PARALLEL_MODES, TIER_DIMENSIONS, TIER_TOKEN_LIMITS, TOKEN_ARTIFACT_CLASSES, type TaggedTurn, type TaskComplexity, type TaxonomyEntry, type TemplateContext, type TemplateDefinition, type TemplateDescriptor, TemplateEngine, TemplateRegistry, type TemplateStep, type TestDelta, type TestEvidence, type TestIssueCategory, type TestIssueSnapshot, type TestParseStrategy, type TestRunnerOutputSource, type TestRunnerParallelMode, type ThemeExportArtifact, type ToStackDetectionResourceOptions, type TokenArtifactClass, type TokenBudget, type TokenEfficiencyMetadata, ToolchainInfo, type TransformersRuntimeEnv, type TransitionEntry, type TransitionLog, TransitionLogManager, type TruncationResult, type TurnClassifierModel, type TurnInput, type TurnPriority, TurnSummarizer, type TurnTagPolicy, type TurnTagResult, UNKNOWN_TEST_OUTPUT_TIMESTAMP, UiImpact, type UnhandledVariant, UnknownEngineError, type UnknownEngineErrorPayload, UnsupportedFileTypeError, type UnsupportedFileTypePayload, type UpdateCandidate, type UpdateDiff, type UpdateReport, VERIFICATION_EVIDENCE_RELATIVE_PATH, VERIFICATION_EVIDENCE_SCHEMA_VERSION, VERIFICATION_EVIDENCE_STDERR_BUDGET_BYTES, VERIFICATION_GATES, VERSION, VERSION_UNKNOWN, ValidationError, type ValidationIssue, type ValidationReport, type ValidationResult, type VectorIndexPayload, VectorIndexStorageError, type VectorIndexStorageErrorPayload, type VectorQueryResult, type VerificationContext, VerificationCriterion, type VerificationDelta, type VerificationEvidence, type VerificationEvidenceFailure, type VerificationEvidenceGate, type VerificationGate, VerificationGateRunner, type VerificationGateSnapshot, type VerificationGateVerdictEntry, type VerificationOrigin, type VerificationVerdictEvent, VersionIncompatibleError, type VersionIncompatiblePayload, type VisionChunk, type VisionIngestInput, type VisionIngestResult, type VoyageEmbeddingClient, VoyageEmbeddingProvider, type VueDetectionResult, WindsurfAdapter, WorkflowAlreadyRunningError, type WorkflowAlreadyRunningPayload, WorkflowEngine, type WorkflowEngineOptions, type WorkflowRouteResult, WorkflowRouterService, type WorkflowRouterServiceOptions, type WorkflowRunOptions, type WorkflowRunProgress, WorkflowSource, type WorkflowStep, type WorkflowStepCompletedEvent, type WorkflowStepFailedEvent, type WorkflowStepProgress, type WorkflowStepRunner, type WorkflowStepStartedEvent, type WorkflowTemplate, WorkflowTemplateLoader, WorkflowTemplateValidator, type WorkspaceCompressionPolicy, type WriteGeneratedFilesOptions, type WriteVerificationEvidenceOptions, ZIP_DECOMPRESSED_LIMIT_BYTES, __testOutputInternals, __tokenEfficiencyInternals, addActiveCapability, addWriteInOption, analyticsEventDocPath, analyticsFeatureDir, analyticsIndexPath, appendAttachmentEvent, appendAuditLog, appendAuditLogFailure, appendCostEntry, appendDecisionAuditEvent, appendMigrationRecord, appendPlanningAudit, appendRagAudit, appendSkillAuditEvent, applyDisclosurePolicy, askThresholdForProject, assembleDecisionEvidence, assembleIntelligence, assertActiveCapability, assertComplianceSummaryInvariants, assertContractDecisionId, attachSpecDefectsToObligations, attachmentCollectionsRoot, backstopGates, bootstrapFramework, bootstrapFrameworkHome, buildAgentConfigContext, buildAnalyticsIndex, buildApiDocContext, buildBoundaryReport, buildCompactArtifact, buildControlLayerAudit, buildCoverageOverlay, buildCurrentPentestReport, buildDecisionPacket, buildDesignSystemContext, buildDetectedStackProfile, buildDetectionReport, buildDocumentationDriftDeltaPayload, buildDriftDeltaReasoningPayload, buildErrorCatalogContext, buildEventDoc, buildHostHookChain, buildIntegrationDocContext, buildModuleScaffoldContext, buildPatternAdvisories, buildReasoningInputPayload, buildRegistryContext, buildRegressionWatchList, buildRepoStateSignature, buildRepositoryVerificationContext, buildRepositoryVerificationVerdict, buildRunnerScriptContext, buildSkillIndex, buildTestDeltaReasoningPayload, buildVerificationDeltaReasoningPayload, buildVerificationEvidence, buildVerificationGateDeltaPayload, capabilityGateCommand, castMerge, checkAndMigrateSchema, checkSchemaCompatibility, checkSpecCompliance, classifyDefect, clearEngineLogger, clearEphemeralCollection, collectObservedAcIds, collectScopeDriftPaths, collectionVectorPaths, compareConfigurations, compareConsumerCompatibility, compareDefects, compareStackProfiles, compileRules, completionRecordCommand, computeAcTestMapping, computeClassificationConfidence, computeDecisionFingerprint, computeDelta, computeImplementationReview, computeManifestHash, computePacketConfidence, computePlanVsActual, computeReconnect, computeSourceHash, computeSpecReview, conflictCategory, countFileReferences, createDefaultEcosystemParserRegistry, createDriftDelta, createEmbeddingProvider, createEvidence, createLogger, createPack, createPendingDecision, createTestDelta, createVerificationDelta, crsCollectionDir, crsCollectionLayout, crsCollectionPaths, decisionCapExceededEvent, decisionDiscardedEvent, decisionOptionsForCategory, decisionPacketCorruptEvent, decisionPausedEvent, decisionQuestionForCategory, decisionResolvedEvent, defaultSimilarityFor, defaultStoreRoot, deregisterCollection, deriveHealthTier, deriveSlug, detectAnalyticsProvider, detectAnalyticsSignals, detectBoundariesInSource, detectContractBoundaries, detectDecisionForks, detectDeltaCandidate, detectFlutterSignals, detectLaravelSignals, detectReactSignals, detectShortVideoSignals, detectSvelteSignals, detectVueSignals, discoverBusinessModules, discoverModules, discoverTargetUrl, doctorBoundaryReport, doctorObligationIndex, doctorSpecReview, ecosystemToLanguage, emitSkillAuditEvent, emitTestSkeletons, engineLog, ensureDecisionAuditLog, ensureSchemaMarkerSync, ensureStoreDir, escapeCollectionId, estimateContextBudgetHint, evaluateAnalyticsCompleteness, evaluateAnalyticsCompletenessForProject, evaluateBenchmarkGates, evaluateEscalation, evaluateRetrievalGate, extractAcIdFromIssue, extractCallSites, extractKeywords, extractObligationIndex, extractRelevantTestPaths, extractUnhandledVariants, findProvider, formatAgentContextWarnings, formatVerdictSummary, frameworkHomeAbsolute, generateBoundaryTests, generateDocumentationScaffold, generateFeatureDevelopmentPolicy, generateInitialRegistries, generateModuleMapYaml, generateModuleScaffold, generateSkillIndex, generateVitestSkeletons, getCollectionId, getConsumerLogger, getEngineLogger, getEngineVersionReport, getFrameworkName, getGlobalPatternVectorPaths, getInheritanceDirectories, getLegacyCapabilities, getPackManifestMap, getPackTestRunners, getPacksForFrameworks, getPrimaryStack, getProjectSecret, getSecretPermissionWarning, getServersForStack, getSharedSkillAuditBuffer, getStackPromptChoices, getTaxonomyEntry, groupBySlug, hasPreMutationBlock, hashRelevantInputs, hashSourceFiles, hookCommand, indexAttachment, inferNamingConvention, inferSourceArtifacts, initializeModuleHealth, injectContractBoundaryCriteria, injectDefectAdvisoryCriteria, injectRuleCriteria, installPack, isActiveCapability, isAlwaysLoadRule, isAttachmentIndexingDegraded, isBackstopVerificationOrigin, isCancelledError, isCompiledRulesStale, isContractDecisionId, isEmbeddingBacklogOverflow, isEmbeddingProviderError, isEngineErrorCode, isEnoentError, isIndexAttachmentFailure, isLiveHookCapable, isManageableActiveCapability, isRagIngestError, isSlugSafe, lexicalDocumentText, lintDecisionCopy, listAvailableActiveCapabilities, listCollections, listContractDecisions, listErrorTaxonomy, listManifestSlugs, listPacks, loadBoundaryReport, loadEntry, loadIndex, loadLoggingConfig, loadManifest, loadModuleDocs, loadModuleMap, loadObligationIndex, loadProjectPackRegistry, loadSpecReviewReport, loadTests, looksLikeTriggerPattern, manifestExists, markCriteriaFromOverlay, markStaleEntries, matchRuleTriggers, matchesGlobish, mergeDeltaManifest, mintDecisionId, moduleHealthPath, normalizeActiveCapabilities, normalizeDecisionQuestion, normalizeEngineVersion, normalizeEventSlug, parseAttachment, parseSecretMatches, parseSuspiciousRoutes, parseTestOutput, persistEvidence, planGeneratedFiles, predictTokenCeiling, prunePatterns, queryMatchingDefectPatterns, queryOsv, queryPatterns, readAllModuleHealth, readAnalyticsDecision, readAttachmentEvents, readCompiledRules, readContractDecisions, readCostLog, readDecisionAuditEvents, readExistingOnboardingManifest, readJsonIfExists, readModuleHealth, readProjectSecrets, readSchemaMarker, readSchemaMarkerSync, readSkillAuditEvents, readStackSnapshotSync, rebuildApiConversation, recordFindings, recordFromComplianceReport, redactFields, redactPayload, redactSecrets, registerCollection, reloadLoggingConfig, removeActiveCapability, removePack, removeProjectSecrets, renderHookCommand, renderReconnectReport, renderStackConfirmationSummary, renderVitestSkeleton, rendersFullHookChain, resetGeneratingEntries, resolveActiveLineage, resolveAnalyticsGate, resolveAnalyticsStrictness, resolveAndPersistAnalyticsGate, resolveCapabilityDirectories, resolveCollectionDir, resolveContextBudgetForModel, resolveContextBudgetForModelTier, resolveDecisionPacket, resolveDocTargets, resolveFrameworkInstallPath, resolveImpacts, resolvePackManagerRoots, resolvePendingDecision, resolveScope, resolveSelections, retrieveFromAttachments, reviewSpecification, ruleTriggersMatch, runArtifactsDir, runLogsDir, runOrphanSweep, runProjectScript, runRepositoryVerification, runRoutingDecision, runStatusForSteps, safeBaseName, sanitizeStackSnapshotRepository, saveBoundaryReport, saveManifest, saveObligationIndex, saveSpecReviewReport, scanBoundaries, schemaMarkerPath, schemaMigrationLogPath, scoreDecisionOptionOverlap, scoreFile, selectModelForTier, selectViableDecisionOptions, serializeModuleMap, setEngineLogger, shouldSkipLlm, skillPath, slugify, slugifySpec, specIndexPath, specReportPath, specReviewPath, suggestPatternsForProject, summarizeCommandAvailability, summarizeStack, syncAnalyticsDocs, syncModuleHealth, syncModuleHealthFromVerification, toCrsCollectionId, toEngineError, toEphemeralCollectionId, toLoadedSkill, toLocalTimestamp, toProjectRelative, toProjectRelativeModule, toReportId, toStackDetectionResource, toVerificationSnapshots, toolReferencePath, validateApiDoc, validateErrorCatalogMarkdown, validatePackAt, validateSpecDocument, validateUserFlow, verifyFullSuite, withSchemaMigrationLock, writeCompiledRules, writeDetectionReport, writeFrameworkMetadata, writeFrameworkVersionPreservingTimestamp, writeGeneratedFiles, writeJson, writeJsonPreservingTimestamp, writeModuleHealth, writeModuleHealthProfile, writeModuleMap, writeOnboardingManifest, writePlanVsActual, writeProjectProfile, writeProjectSecret, writeSchemaMarker, writeSchemaMarkerSync, writeSkillIndex, writeSkillIndexFromArtifacts, writeVerificationEvidence };
