import type { DispatchRequest, Intent, Level, TaskShape } from "../types.js"; const PATH_RE = /(?:^|[\s`"'])((?:[\w.-]+\/)*[\w.-]+\.(?:[cm]?[jt]sx?|py|go|rs|java|kt|json|ya?ml|md|sql|css|html?|sh))(?:$|[\s`"',:;])/gi; const HIGH_RISK = /\b(auth|security|credential|secret|token|payment|billing|migration|rollback|delete|destructive|production|race|concurren|transaction|integrity)/i; const HIGH_COUPLING = /\b(race|concurren|distributed|transaction|migration|state machine|cross[- ]module|rollback)/i; const RESEARCH = /\b(research|latest|current|compare|unknown|investigate|diagnos)/i; const VERIFY = /\b(test|tests|lint|build|verify|check|acceptance)/i; const MULTI = /\b([2-9]|several|multiple|all|each|packages?|modules?|services?)/i; const FIRST_PROVEN = /\b(reproduce (?:the )?root cause|first (?:proven|working) (?:result|path)|find (?:a )?working path)\b/i; const CHANGE_ACTION = /^(?:please\s+)?(?:add|implement|create|change|modify|update|apply|refactor|build|write)\b/i; const CHANGE = /\b(?:add|implement|create|change|modify|update|apply|refactor|build|write)\b/i; function intentFor(text: string): Intent { if (/\b(fix|bug|broken|error|regression)/i.test(text)) return "fix"; if (CHANGE_ACTION.test(text)) return "change"; if (RESEARCH.test(text)) return "investigate"; if (CHANGE.test(text)) return "change"; if (/\b(review|audit|inspect)/i.test(text)) return "review"; return "answer"; } function pathsIn(text: string, supplied: string[] = []): string[] { const found = new Set(supplied); for (const match of text.matchAll(PATH_RE)) if (match[1]) found.add(match[1]); return [...found].sort(); } const LEVEL_ORDER: Level[] = ["low", "medium", "high"]; const INTENT_ORDER: Intent[] = ["answer", "investigate", "review", "change", "fix"]; const SENSITIVE_PATH_SEGMENT = /(?:^|[/_.-])(auth|security|secret|credential|token|payment|billing|migration|migrations|crypto|session|permission|permissions)(?:$|[/_.-])/i; type ShapeSource = "declared" | "signal" | "keyword"; function escalateLevel(derived: Level, derivedSource: ShapeSource, declared: Level | undefined): { value: Level; source: ShapeSource } { if (declared && LEVEL_ORDER.indexOf(declared) > LEVEL_ORDER.indexOf(derived)) return { value: declared, source: "declared" }; return { value: derived, source: derivedSource }; } function escalateIntent(derived: Intent, derivedSource: ShapeSource, declared: Intent | undefined): { value: Intent; source: ShapeSource } { if (declared && INTENT_ORDER.indexOf(declared) > INTENT_ORDER.indexOf(derived)) return { value: declared, source: "declared" }; return { value: derived, source: derivedSource }; } function sensitivePathRisk(paths: readonly string[]): Level | undefined { return paths.some((path) => SENSITIVE_PATH_SEGMENT.test(path)) ? "high" : undefined; } export interface ShapeInput extends DispatchRequest { contextRatio?: number; repeatedFailureCount?: number; failureFingerprint?: string; priorDisagreement?: boolean; preflight?: { scopedDirtyFiles: number; scopedDiffStatFiles: number; affectedDirectories: number; explicitCommands: number; sessionCacheState: "cold-proxy" | "warm-proxy" | "unknown"; currentRunFailureCount: number; remainingCredits: number; providerState: string; }; } export function analyzeTask(input: ShapeInput): TaskShape { const text = input.objective.trim(); const mentionedPaths = pathsIn(text, input.paths); const declared = input.declaredShape; const highCoupling = HIGH_COUPLING.test(text); const highRisk = HIGH_RISK.test(text); const research = RESEARCH.test(text); const firstProven = FIRST_PROVEN.test(text); const declaredUnits = declared?.independentUnits; const units = Math.max( input.preflight?.affectedDirectories ?? 0, Number.isSafeInteger(declaredUnits) && declaredUnits! > 0 ? declaredUnits! : 0, MULTI.test(text) ? Math.max(2, mentionedPaths.length) : Math.max(1, mentionedPaths.length), ); const knownScope = mentionedPaths.length > 0 || /\b(this|that|single[- ]file|one[- ]file)/i.test(text); const breadth = units >= 6 || /\b(monorepo|entire|all packages|whole codebase)/i.test(text) ? "wide" : units >= 3 || /\b(cross[- ]module|several)/i.test(text) ? "cross-module" : knownScope ? (mentionedPaths.length <= 1 ? "tiny" : "local") : "local"; const intentPick = escalateIntent(intentFor(text), "keyword", declared?.intent); const intent = intentPick.value; const uncertaintyPick = escalateLevel(research || !knownScope ? "high" : /\b(maybe|possibly|seem)/i.test(text) ? "medium" : "low", "keyword", declared?.uncertainty); const uncertainty = uncertaintyPick.value; const pathRisk = sensitivePathRisk(mentionedPaths); const keywordRisk: Level = highRisk ? "high" : /\b(api|database|db|network|deploy)/i.test(text) ? "medium" : "low"; const riskFloor = escalateLevel(keywordRisk, "keyword", pathRisk); const riskPick = escalateLevel(riskFloor.value, pathRisk && riskFloor.value === pathRisk ? "signal" : riskFloor.source, declared?.risk); const risk = riskPick.value; const couplingSignal: Level = breadth === "wide" ? "medium" : "low"; const couplingKeyword: Level = highCoupling ? "high" : breadth === "cross-module" || breadth === "wide" ? "medium" : "low"; const couplingFloor = escalateLevel(couplingSignal, "signal", couplingKeyword); const couplingPick = escalateLevel(couplingFloor.value, couplingFloor.source, declared?.coupling); const coupling = couplingPick.value; const verifiability = input.acceptanceCommand || VERIFY.test(text) ? "strong" : intent === "answer" || intent === "investigate" ? "partial" : "weak"; const reasonCodes = [ `intent:${intent}`, `scope:${knownScope ? "known" : "unknown"}`, `breadth:${breadth}`, `coupling:${coupling}`, `risk:${risk}`, `uncertainty:${uncertainty}`, `shape:${intentPick.source}:intent`, `shape:${riskPick.source}:risk`, `shape:${couplingPick.source}:coupling`, `shape:${uncertaintyPick.source}:uncertainty`, ...(firstProven ? ["execution:first-proven"] : []), ]; if (input.contextRatio && input.contextRatio > 0.75) reasonCodes.push("context:wide-swarm-blocked"); if (input.preflight?.scopedDirtyFiles) reasonCodes.push(`checkout:dirty-${input.preflight.scopedDirtyFiles}`); if (input.preflight?.explicitCommands) reasonCodes.push(`commands:explicit-${input.preflight.explicitCommands}`); if (input.preflight) reasonCodes.push(`cache:${input.preflight.sessionCacheState}`); if (input.preflight && input.preflight.providerState !== "healthy") reasonCodes.push(`provider:${input.preflight.providerState}`); if (input.preflight && input.preflight.remainingCredits <= 0) reasonCodes.push("budget:exhausted"); const repeatedFailureCount = input.repeatedFailureCount ?? input.preflight?.currentRunFailureCount ?? 0; if (repeatedFailureCount) reasonCodes.push(`failure:repeated-${repeatedFailureCount}`); if (input.priorDisagreement) reasonCodes.push("agents:disagreement"); return { intent, knownScope, mentionedPaths, breadth, coupling, uncertainty, risk, verifiability, independentUnits: units, externalResearchRequired: research, writerOverlapRisk: /\b(same file|shared schema|overlap)/i.test(text), liveCrossAgentDependency: /\b(war room|live|interactive hypotheses)/i.test(text), repeatedFailureCount, failureFingerprint: input.failureFingerprint, priorDisagreement: input.priorDisagreement ?? false, confidence: knownScope && uncertainty === "low" ? 0.85 : uncertainty === "high" ? 0.45 : 0.65, reasonCodes, }; }