@ai-sdlc/orchestrator 0.6.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. package/dist/admission-composite.d.ts +67 -0
  2. package/dist/admission-composite.js +158 -0
  3. package/dist/admission-enrichment.d.ts +142 -0
  4. package/dist/admission-enrichment.js +331 -0
  5. package/dist/admission-hc.d.ts +62 -0
  6. package/dist/admission-hc.js +83 -0
  7. package/dist/admission-score.d.ts +95 -5
  8. package/dist/admission-score.js +84 -11
  9. package/dist/analysis/analyzer.js +3 -2
  10. package/dist/analysis/convention-detector.d.ts +85 -2
  11. package/dist/analysis/convention-detector.js +375 -70
  12. package/dist/analysis/diff-analyzer.d.ts +33 -0
  13. package/dist/analysis/diff-analyzer.js +122 -0
  14. package/dist/analysis/hotspot-analyzer.js +3 -1
  15. package/dist/analysis/index.d.ts +2 -1
  16. package/dist/analysis/index.js +2 -1
  17. package/dist/artifacts/index.d.ts +65 -0
  18. package/dist/artifacts/index.js +142 -0
  19. package/dist/backlog-adapter.d.ts +121 -0
  20. package/dist/backlog-adapter.js +438 -0
  21. package/dist/calibration.d.ts +43 -0
  22. package/dist/calibration.js +76 -0
  23. package/dist/cli/commands/agents.d.ts +24 -0
  24. package/dist/cli/commands/agents.js +66 -1
  25. package/dist/cli/commands/git-remote.d.ts +49 -0
  26. package/dist/cli/commands/git-remote.js +91 -0
  27. package/dist/cli/commands/health.d.ts +4 -0
  28. package/dist/cli/commands/health.js +13 -1
  29. package/dist/cli/commands/init.d.ts +26 -0
  30. package/dist/cli/commands/init.js +164 -22
  31. package/dist/cli/commands/mcp-setup.d.ts +31 -0
  32. package/dist/cli/commands/mcp-setup.js +78 -8
  33. package/dist/cli/formatters/table.js +15 -2
  34. package/dist/cli/index.d.ts +14 -1
  35. package/dist/cli/index.js +81 -20
  36. package/dist/cli/versions.d.ts +57 -0
  37. package/dist/cli/versions.js +128 -0
  38. package/dist/code-area-classifier.d.ts +21 -0
  39. package/dist/code-area-classifier.js +48 -0
  40. package/dist/config.d.ts +33 -1
  41. package/dist/config.js +78 -8
  42. package/dist/database/adapters/external.d.ts +24 -0
  43. package/dist/database/adapters/external.js +80 -0
  44. package/dist/database/adapters/neon.d.ts +41 -0
  45. package/dist/database/adapters/neon.js +98 -0
  46. package/dist/database/adapters/pg-snapshot-restore.d.ts +28 -0
  47. package/dist/database/adapters/pg-snapshot-restore.js +68 -0
  48. package/dist/database/adapters/sqlite-copy.d.ts +32 -0
  49. package/dist/database/adapters/sqlite-copy.js +145 -0
  50. package/dist/database/connection-injection.d.ts +35 -0
  51. package/dist/database/connection-injection.js +93 -0
  52. package/dist/database/index.d.ts +12 -0
  53. package/dist/database/index.js +23 -0
  54. package/dist/database/registry.d.ts +13 -0
  55. package/dist/database/registry.js +27 -0
  56. package/dist/database/topology.d.ts +52 -0
  57. package/dist/database/topology.js +44 -0
  58. package/dist/database/types.d.ts +89 -0
  59. package/dist/database/types.js +26 -0
  60. package/dist/design-authority.d.ts +40 -0
  61. package/dist/design-authority.js +71 -0
  62. package/dist/design-lookahead.d.ts +64 -0
  63. package/dist/design-lookahead.js +86 -0
  64. package/dist/design-quality-trend.d.ts +87 -0
  65. package/dist/design-quality-trend.js +190 -0
  66. package/dist/design-system-context.d.ts +46 -0
  67. package/dist/design-system-context.js +80 -0
  68. package/dist/design-system-correction-loop.d.ts +64 -0
  69. package/dist/design-system-correction-loop.js +128 -0
  70. package/dist/design-system-metrics.d.ts +61 -0
  71. package/dist/design-system-metrics.js +104 -0
  72. package/dist/design-system-stewardship.d.ts +22 -0
  73. package/dist/design-system-stewardship.js +85 -0
  74. package/dist/design-system-validation.d.ts +37 -0
  75. package/dist/design-system-validation.js +88 -0
  76. package/dist/dispatch/index.d.ts +4 -0
  77. package/dist/dispatch/index.js +4 -0
  78. package/dist/dispatch/merge-gate.d.ts +46 -0
  79. package/dist/dispatch/merge-gate.js +90 -0
  80. package/dist/dispatch/requeue.d.ts +57 -0
  81. package/dist/dispatch/requeue.js +131 -0
  82. package/dist/dispatch/worker-pool.d.ts +62 -0
  83. package/dist/dispatch/worker-pool.js +60 -0
  84. package/dist/execute.d.ts +40 -0
  85. package/dist/execute.js +185 -15
  86. package/dist/fix-ci.js +8 -1
  87. package/dist/fix-review.js +8 -1
  88. package/dist/harness/adapters/claude-code.d.ts +29 -0
  89. package/dist/harness/adapters/claude-code.js +191 -0
  90. package/dist/harness/adapters/codex.d.ts +25 -0
  91. package/dist/harness/adapters/codex.js +61 -0
  92. package/dist/harness/independence.d.ts +51 -0
  93. package/dist/harness/independence.js +67 -0
  94. package/dist/harness/index.d.ts +14 -0
  95. package/dist/harness/index.js +20 -0
  96. package/dist/harness/registry.d.ts +17 -0
  97. package/dist/harness/registry.js +31 -0
  98. package/dist/harness/types.d.ts +123 -0
  99. package/dist/harness/types.js +8 -0
  100. package/dist/harness/version-probe.d.ts +14 -0
  101. package/dist/harness/version-probe.js +123 -0
  102. package/dist/index.d.ts +30 -4
  103. package/dist/index.js +35 -2
  104. package/dist/models/classifier.d.ts +76 -0
  105. package/dist/models/classifier.js +221 -0
  106. package/dist/models/index.d.ts +3 -0
  107. package/dist/models/index.js +3 -0
  108. package/dist/models/registry.d.ts +97 -0
  109. package/dist/models/registry.js +173 -0
  110. package/dist/pillar-breakdown.d.ts +63 -0
  111. package/dist/pillar-breakdown.js +153 -0
  112. package/dist/priority.d.ts +5 -0
  113. package/dist/priority.js +18 -5
  114. package/dist/review-meta.d.ts +65 -0
  115. package/dist/review-meta.js +149 -0
  116. package/dist/review.d.ts +4 -0
  117. package/dist/review.js +12 -2
  118. package/dist/runners/claude-code-sdk.d.ts +31 -0
  119. package/dist/runners/claude-code-sdk.js +238 -0
  120. package/dist/runners/claude-code.d.ts +3 -0
  121. package/dist/runners/claude-code.js +30 -66
  122. package/dist/runners/codex.js +4 -1
  123. package/dist/runners/copilot.js +4 -1
  124. package/dist/runners/cursor.js +4 -1
  125. package/dist/runners/git-utils.d.ts +81 -0
  126. package/dist/runners/git-utils.js +201 -0
  127. package/dist/runners/index.d.ts +3 -0
  128. package/dist/runners/index.js +3 -0
  129. package/dist/runners/review-agent.d.ts +20 -0
  130. package/dist/runners/review-agent.js +171 -41
  131. package/dist/runners/runner-registry.js +10 -0
  132. package/dist/runners/sdk-review-runner.d.ts +65 -0
  133. package/dist/runners/sdk-review-runner.js +185 -0
  134. package/dist/runners/security-triage.d.ts +20 -4
  135. package/dist/runners/security-triage.js +39 -15
  136. package/dist/runners/types.d.ts +6 -0
  137. package/dist/runtime/attestations.d.ts +274 -0
  138. package/dist/runtime/attestations.js +460 -0
  139. package/dist/runtime/git-env.d.ts +53 -0
  140. package/dist/runtime/git-env.js +60 -0
  141. package/dist/runtime/index.d.ts +7 -0
  142. package/dist/runtime/index.js +7 -0
  143. package/dist/runtime/parallelism-flag.d.ts +10 -0
  144. package/dist/runtime/parallelism-flag.js +18 -0
  145. package/dist/runtime/port-allocator.d.ts +21 -0
  146. package/dist/runtime/port-allocator.js +66 -0
  147. package/dist/runtime/worktree-pool.d.ts +86 -0
  148. package/dist/runtime/worktree-pool.js +204 -0
  149. package/dist/runtime/worktree.d.ts +25 -0
  150. package/dist/runtime/worktree.js +111 -0
  151. package/dist/sa-scoring/auto-calibrate.d.ts +69 -0
  152. package/dist/sa-scoring/auto-calibrate.js +107 -0
  153. package/dist/sa-scoring/c1-sa2-computable.d.ts +42 -0
  154. package/dist/sa-scoring/c1-sa2-computable.js +59 -0
  155. package/dist/sa-scoring/composite.d.ts +107 -0
  156. package/dist/sa-scoring/composite.js +139 -0
  157. package/dist/sa-scoring/depparse-client.d.ts +79 -0
  158. package/dist/sa-scoring/depparse-client.js +187 -0
  159. package/dist/sa-scoring/did-compiler.d.ts +122 -0
  160. package/dist/sa-scoring/did-compiler.js +286 -0
  161. package/dist/sa-scoring/drift-monitor.d.ts +84 -0
  162. package/dist/sa-scoring/drift-monitor.js +186 -0
  163. package/dist/sa-scoring/exemplar-bank.d.ts +78 -0
  164. package/dist/sa-scoring/exemplar-bank.js +154 -0
  165. package/dist/sa-scoring/feedback-store.d.ts +100 -0
  166. package/dist/sa-scoring/feedback-store.js +156 -0
  167. package/dist/sa-scoring/index.d.ts +71 -0
  168. package/dist/sa-scoring/index.js +158 -0
  169. package/dist/sa-scoring/layer1-deterministic.d.ts +115 -0
  170. package/dist/sa-scoring/layer1-deterministic.js +298 -0
  171. package/dist/sa-scoring/layer2-structural.d.ts +71 -0
  172. package/dist/sa-scoring/layer2-structural.js +151 -0
  173. package/dist/sa-scoring/layer3-llm.d.ts +86 -0
  174. package/dist/sa-scoring/layer3-llm.js +282 -0
  175. package/dist/sa-scoring/rescore-orchestrator.d.ts +52 -0
  176. package/dist/sa-scoring/rescore-orchestrator.js +47 -0
  177. package/dist/scheduling/burn-down.d.ts +27 -0
  178. package/dist/scheduling/burn-down.js +43 -0
  179. package/dist/scheduling/calibration.d.ts +42 -0
  180. package/dist/scheduling/calibration.js +150 -0
  181. package/dist/scheduling/index.d.ts +8 -0
  182. package/dist/scheduling/index.js +8 -0
  183. package/dist/scheduling/ledger.d.ts +59 -0
  184. package/dist/scheduling/ledger.js +216 -0
  185. package/dist/scheduling/off-peak.d.ts +27 -0
  186. package/dist/scheduling/off-peak.js +112 -0
  187. package/dist/scheduling/schedule-decision.d.ts +39 -0
  188. package/dist/scheduling/schedule-decision.js +89 -0
  189. package/dist/scheduling/tier-analysis.d.ts +47 -0
  190. package/dist/scheduling/tier-analysis.js +81 -0
  191. package/dist/scheduling/types.d.ts +140 -0
  192. package/dist/scheduling/types.js +11 -0
  193. package/dist/shared.d.ts +13 -0
  194. package/dist/shared.js +32 -0
  195. package/dist/state/schema.d.ts +5 -1
  196. package/dist/state/schema.js +223 -1
  197. package/dist/state/store.d.ts +55 -1
  198. package/dist/state/store.js +342 -7
  199. package/dist/state/types.d.ts +139 -0
  200. package/dist/types.d.ts +1 -1
  201. package/dist/validate-agent-output.js +4 -1
  202. package/dist/watch.js +6 -0
  203. package/package.json +2 -2
@@ -0,0 +1,123 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ const execFileAsync = promisify(execFile);
4
+ const PROBE_TIMEOUT_MS = 5000;
5
+ /**
6
+ * Run a harness's version probe and compare against its declared semver range.
7
+ * Per RFC §13.8: parse failures fall through to "available" (warning only) so undocumented
8
+ * vendor changes to --version output don't break every pipeline.
9
+ */
10
+ export async function probeVersion(requires) {
11
+ let stdout;
12
+ try {
13
+ const result = await execFileAsync(requires.binary, requires.versionProbe.args, {
14
+ timeout: PROBE_TIMEOUT_MS,
15
+ });
16
+ stdout = result.stdout;
17
+ }
18
+ catch (err) {
19
+ const code = err.code;
20
+ if (code === 'ENOENT') {
21
+ return {
22
+ available: false,
23
+ reason: 'binary-missing',
24
+ detail: `${requires.binary} not found on PATH`,
25
+ };
26
+ }
27
+ return {
28
+ available: false,
29
+ reason: 'probe-failed',
30
+ detail: `${requires.binary} ${requires.versionProbe.args.join(' ')} failed: ${err.message}`,
31
+ };
32
+ }
33
+ let installedVersion;
34
+ try {
35
+ installedVersion = requires.versionProbe.parse(stdout).trim();
36
+ }
37
+ catch (err) {
38
+ return {
39
+ available: true,
40
+ reason: 'probe-failed',
41
+ detail: `could not parse ${requires.binary} version output: ${err.message}`,
42
+ };
43
+ }
44
+ if (!installedVersion) {
45
+ return {
46
+ available: true,
47
+ reason: 'probe-failed',
48
+ detail: `parser returned empty version from ${requires.binary} output`,
49
+ };
50
+ }
51
+ if (!matchesRange(installedVersion, requires.versionRange)) {
52
+ return {
53
+ available: false,
54
+ reason: 'version-out-of-range',
55
+ detail: `${requires.binary} ${installedVersion} installed, adapter requires ${requires.versionRange}`,
56
+ installedVersion,
57
+ };
58
+ }
59
+ return { available: true, installedVersion };
60
+ }
61
+ /**
62
+ * Minimal semver-range matcher supporting `>=X.Y.Z` and `>=X.Y.Z <A.B.C`.
63
+ * v1 ships only the cases the RFC's default policy uses (open-ended upper bound by
64
+ * default; explicit upper bound only when a known-incompatible upstream version exists).
65
+ */
66
+ export function matchesRange(version, range) {
67
+ const v = parseSemver(version);
68
+ if (!v)
69
+ return false;
70
+ const constraints = range
71
+ .split(/\s+/)
72
+ .map((c) => c.trim())
73
+ .filter((c) => c.length > 0);
74
+ for (const constraint of constraints) {
75
+ const m = constraint.match(/^(>=|>|<=|<|=)(\d+)\.(\d+)\.(\d+)$/);
76
+ if (!m)
77
+ return false;
78
+ const op = m[1];
79
+ const target = [
80
+ Number.parseInt(m[2], 10),
81
+ Number.parseInt(m[3], 10),
82
+ Number.parseInt(m[4], 10),
83
+ ];
84
+ const cmp = compareSemver(v, target);
85
+ switch (op) {
86
+ case '>=':
87
+ if (cmp < 0)
88
+ return false;
89
+ break;
90
+ case '>':
91
+ if (cmp <= 0)
92
+ return false;
93
+ break;
94
+ case '<=':
95
+ if (cmp > 0)
96
+ return false;
97
+ break;
98
+ case '<':
99
+ if (cmp >= 0)
100
+ return false;
101
+ break;
102
+ case '=':
103
+ if (cmp !== 0)
104
+ return false;
105
+ break;
106
+ }
107
+ }
108
+ return true;
109
+ }
110
+ function parseSemver(s) {
111
+ const m = s.match(/^(\d+)\.(\d+)\.(\d+)/);
112
+ if (!m)
113
+ return null;
114
+ return [Number.parseInt(m[1], 10), Number.parseInt(m[2], 10), Number.parseInt(m[3], 10)];
115
+ }
116
+ function compareSemver(a, b) {
117
+ for (let i = 0; i < 3; i++) {
118
+ if (a[i] !== b[i])
119
+ return a[i] - b[i];
120
+ }
121
+ return 0;
122
+ }
123
+ //# sourceMappingURL=version-probe.js.map
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { loadConfig, loadConfigAsync, type AiSdlcConfig } from './config.js';
1
+ export { loadConfig, loadConfigAsync, type AiSdlcConfig, type ConfigLoadWarning, } from './config.js';
2
2
  export { validateIssue, validateIssueWithExtensions, parseComplexity } from './validate-issue.js';
3
3
  export { executePipeline, type ExecuteOptions, type PipelineResult, type PromotionResult, } from './execute.js';
4
4
  export { validateAgentOutput, type ValidationContext, type ValidationResult, type ValidationViolation, } from './validate-agent-output.js';
@@ -20,8 +20,27 @@ export { createStructuredConsoleLogger, createStructuredBufferLogger, } from './
20
20
  export { startWatch, type WatchOptions, type WatchHandle } from './watch.js';
21
21
  export { computePriority, rankWorkItems, type PriorityScore, type PriorityInput, type PriorityConfig, } from './priority.js';
22
22
  export { checkAction, enforceAction, DEFAULT_BLOCKED_ACTIONS, type ActionEnforcementResult, } from './action-enforcement.js';
23
- export { scoreIssueForAdmission, mapIssueToPriorityInput, type AdmissionInput, type AdmissionThresholds, type IssueAdmissionResult, type AuthorAssociation, } from './admission-score.js';
23
+ export { scoreIssueForAdmission, mapIssueToPriorityInput, type AdmissionInput, type AdmissionThresholds, type IssueAdmissionResult, type AuthorAssociation, type DesignSystemContext, type AutonomyContext, type CodeAreaQuality, type DesignAuthoritySignal, type DesignAuthoritySignalType, type DesignQualityMetrics, } from './admission-score.js';
24
+ export { enrichAdmissionInput, computeDesignSystemReadiness, computeReadinessFromDesignSystemContext, computeDefectRiskFactor, computeAutonomyFactor, computeDesignAuthorityWeight, complexityToAutonomyLevel, type EnrichmentContext, type LifecyclePhase, } from './admission-enrichment.js';
25
+ export { computeAdmissionComposite, type AdmissionComposite } from './admission-composite.js';
26
+ export { parseBacklogTask, loadBacklogTaskFromRoot, mapBacklogTaskToAdmissionInput, loadSoulTracks, loadMaintainers, type BacklogTaskSnapshot, type BacklogAcceptanceCriterion, type BacklogMappingOptions, type BacklogAdmissionMapping, } from './backlog-adapter.js';
27
+ export { computePillarBreakdown, detectTensions, pillarSignalScore, type PillarBreakdown, type PillarContribution, type PillarName, type SharedDimensions, type TensionFlag, type TensionFlagType, type HcChannelBreakdown, } from './pillar-breakdown.js';
28
+ export { compileDid, validatePhase2bReadiness, hashDidSpec, canonicalJson, tokenize, serializeForStore, deserializeFromStore, type CompiledDid, type CompiledScopeLists, type CompiledScopeEntry, type CompiledConstraintRule, type CompiledAntiPattern, type CompiledAntiPatternLists, type CompiledMeasurableSignal, type Bm25Corpus, type Bm25Document, type PrincipleCorpora, type ReadinessResult, } from './sa-scoring/did-compiler.js';
29
+ export { HttpDepparseClient, FakeDepparseClient, DepparseError, type DepparseClient, type DepparseMatch, type DepparseMatchRequest, type DepparseMatchResponse, type DepparseHealth, type DepparseErrorKind, } from './sa-scoring/depparse-client.js';
30
+ export { runLayer1, checkScopeGate, detectConstraintViolations, detectAntiPatterns, checkMeasurableSignals, renderPreVerifiedSummary, type DeterministicScoringResult, type ScopeGateResult, type ScopeGateMatch, type ConstraintViolation, type ConstraintViolationResult, type AntiPatternHit, type AntiPatternResult, type MeasurableSignalCheck, type MeasurableSignalResult, type Layer1Input, } from './sa-scoring/layer1-deterministic.js';
31
+ export { computeDomainRelevance, computePrincipleCoverage, type DomainRelevanceResult, type PrincipleCoverageVector, type PrincipleCoverageEntry, type ContributingTerm, } from './sa-scoring/layer2-structural.js';
32
+ export { runLayer3, buildSa1Prompt, buildSa2Prompt, extractJson, RecordedLLMClient, LayerLlmError, CONFIDENCE_THRESHOLD, type LLMClient, type LLMScoringResult, type SubtleConflict, type SubtleDesignConflict, type Layer3Input, type PromptContext, type LayerLlmErrorKind, } from './sa-scoring/layer3-llm.js';
33
+ export { computeSoulAlignment, computeSa1, computeSa2, getPhaseWeights, W_STRUCTURAL_FLOOR, type SoulAlignmentResult, type SoulAlignmentInput, type Sa1Inputs, type Sa2Inputs, type Sa1Result, type Sa2Result, type SaPhase, type PhaseWeights, } from './sa-scoring/composite.js';
34
+ export { computeSa2Computable, type Sa2ComputableResult } from './sa-scoring/c1-sa2-computable.js';
35
+ export { SAFeedbackStore, SA_FEEDBACK_LABELS, classifyLabel, recordOverrideFeedback, type RecordFeedbackInput, type PrecisionWindow, type PrecisionResult, type CategoryFalsePositive, type OverrideFeedbackInput, } from './sa-scoring/feedback-store.js';
36
+ export { computeCalibrationCoefficient, buildCategoryCoefficients, type CategoryFeedback, type BuildCategoryCoefficientsInput, } from './calibration.js';
37
+ export { autoCalibratePhaseWeights, computePhase3Weights, decideCalibrationDirection, renderCalibrationDiff, WEIGHT_FLOOR, WEIGHT_CEILING, DEFAULT_SHIFT_SIZE, DEFAULT_WINDOW_DAYS, PRECISION_DELTA_THRESHOLD, type PrecisionPair, type CalibrationDecision, type ComputePhase3WeightsInput, type AutoCalibrateDeps, type AutoCalibrateResult, type DimensionDiff, } from './sa-scoring/auto-calibrate.js';
38
+ export { detectSoulDrift, computeWindowStats, computeTrend, describeDriftSource, DEFAULT_MEAN_THRESHOLD, DEFAULT_STDDEV_THRESHOLD, DEFAULT_CONSECUTIVE_WINDOWS, DEFAULT_RECOVERY_MS, type SoulDriftDetectedEvent, type DriftTrend, type WindowStats, type DriftDetectorDeps, } from './sa-scoring/drift-monitor.js';
39
+ export { handleCoreIdentityChanged, type CoreIdentityChangedEvent, type BacklogReshuffledEvent, type SoulGraphStaleFlag, type RescoreDeps, type HandleResult, } from './sa-scoring/rescore-orchestrator.js';
40
+ export { scoreSoulAlignment, resolveSoulAlignmentOverride, type ScoreSoulAlignmentInput, type ScoreSoulAlignmentDeps, type SoulAlignmentScoringResult, } from './sa-scoring/index.js';
41
+ export type { SaDimension, FeedbackSignal } from './state/types.js';
24
42
  export { executeReview, type ReviewContext, type ReviewOptions } from './review.js';
43
+ export { metaReview, ReviewFeedbackStore, type MetaReviewDecision, type MetaReviewResult, type ReviewFeedback, } from './review-meta.js';
25
44
  export { createPipelineOrchestration, executePipelineOrchestration, validatePipelineHandoffs, sequential, parallel, hybrid, hierarchical, swarm, validateHandoff, simpleSchemaValidate, } from './orchestration.js';
26
45
  export { createPipelineRegoEvaluator, createPipelineCELEvaluator, createPipelineABACHook, createPipelineExpressionEvaluator, createPipelineLLMEvaluator, evaluatePipelineGate, scorePipelineComplexity, evaluatePipelineComplexityRouting, } from './policy-evaluators.js';
27
46
  export { createPipelineAdapterRegistry, createPipelineWebhookBridge, resolveAdapterFromGit, resolveInfrastructure, resolveIssueTrackerFromConfig, scanPipelineAdapters, } from './adapters.js';
@@ -55,8 +74,8 @@ export { createOTelBridge, isOTelAvailable } from './otel-exporter.js';
55
74
  export type { OTelBridge, OTelBridgeOptions, OTelSpanHandle } from './otel-exporter.js';
56
75
  export { renderDashboardFrame } from './cli/dashboard-renderer.js';
57
76
  export type { DashboardData } from './cli/dashboard-renderer.js';
58
- export { walkFiles, detectModules, parseImports, buildModuleGraph, detectConventions, detectPatterns, analyzeHotspots, computeComplexityScore, analyzeCodebase, buildCodebaseContext, formatContextForPrompt, } from './analysis/index.js';
59
- export type { CodebaseProfile, CodebaseContext, Hotspot, ArchitecturalPattern, DetectedConvention, ModuleInfo, ModuleGraph, DependencyEdge, AnalyzerOptions, FileInfo, ImportStatement, } from './analysis/index.js';
77
+ export { walkFiles, detectModules, parseImports, buildModuleGraph, detectConventions, detectReactProject, loadProjectAliases, parseTsConfigAliases, parseViteOrWebpackAliases, enumerateTestLocations, detectPatterns, analyzeHotspots, computeComplexityScore, analyzeCodebase, buildCodebaseContext, formatContextForPrompt, analyzeDiff, extractChangedFiles, } from './analysis/index.js';
78
+ export type { CodebaseProfile, CodebaseContext, Hotspot, ArchitecturalPattern, DetectedConvention, ModuleInfo, ModuleGraph, DependencyEdge, AnalyzerOptions, FileInfo, ImportStatement, DiffFinding, DiffAnalysisResult, DetectConventionsOptions, PathAliasMap, TestLocationSummary, } from './analysis/index.js';
60
79
  export { createCheckRun, updateCheckRun, reportGateCheckRuns } from './check-runs.js';
61
80
  export { detectMonorepoLayout, detectWorkspace, buildServiceMap, detectCycles, topologicalOrder, getTransitiveDependents, analyzeImpact, formatImpactSummary, getAffectedBuildOrder, } from './multi-repo/index.js';
62
81
  export type { ServiceNode, ServiceMap, ServiceEdge, MonorepoLayout, WorkspaceConfig, WorkspacePackage, ImpactResult, } from './multi-repo/index.js';
@@ -75,6 +94,13 @@ export type { ArchiveManifest, ArchivalOptions } from './audit-archival.js';
75
94
  export { Orchestrator, type OrchestratorConfig, type WebhookConfig } from './orchestrator.js';
76
95
  export type { OrchestratorPlugin, PluginContext, BeforeRunEvent, AfterRunEvent, RunErrorEvent, } from './plugin.js';
77
96
  export { CostGovernancePlugin } from './cost-governance.js';
97
+ export { WorktreePoolManager, WorktreePoolError, WorktreeOwnershipError, deterministicPort, allocatePort, allocateContiguousPorts, isPortFree, PortAllocationError, slugifyBranch, worktreePath, verifyOwnership, assertOwnership, isExistingWorktree, readParallelismMode, isParallelismEnabled, PARALLELISM_FLAG, DEFAULT_BASE_PORT, DEFAULT_POOL_ROOT, DEFAULT_STALE_THRESHOLD_DAYS, type WorktreePoolSpec, type WorktreePoolManagerDeps, type WorktreeHandle, type AllocateOptions, type AllocatePortOptions, type AllocateContiguousOptions, type OwnershipResult, type ParallelismMode, } from './runtime/index.js';
98
+ export { HarnessRegistry, UnknownHarnessError, ClaudeCodeAdapter, CodexAdapter, createDefaultHarnessRegistry, probeVersion, matchesRange, enforceIndependence, validateIndependenceGraph, CyclicIndependenceConstraintError, type HarnessAdapter, type HarnessAvailability, type HarnessCapabilities, type HarnessEvent, type HarnessInput, type HarnessName, type HarnessRequires, type HarnessResult, type HarnessResultStatus, type ClaudeCodeAdapterDeps, type CodexAdapterDeps, type IndependenceResult, type UpstreamRun, type ToolDefinition, } from './harness/index.js';
99
+ export { SubscriptionLedger, validateTenantShares, evaluateSchedule, CalibrationStore, COLD_START_DEFAULT, buildBurnDownReport, analyzeTier, PLAN_COSTS_USD, isOffPeakAt, nextOffPeakStart, ageInDays, freshnessLevel, DEFAULT_TENANT, COLD_START_DEFAULT_INPUT, COLD_START_DEFAULT_OUTPUT, ESTIMATE_VARIANCE_THRESHOLD, ROLLING_WINDOW_SIZE, type SubscriptionPlan, type Schedule, type TokenEstimate, type LedgerKey, type WindowState, type AdmissionDecision, type BurnDownReport, type LedgerEvent, type BillingMode, type QuotaSource, type OffPeakSchedule, type BurnDownInput, type CalibrationStoreDeps, type LedgerDeps, type ScheduleDecision, type ScheduleEvaluationContext, type Confidence, type ContentionEvent, type TierAnalysisInput, type TierAnalysisResult, type FreshnessLevel, } from './scheduling/index.js';
100
+ export { DatabaseAdapterRegistry, UnknownDatabaseAdapterError, SqliteCopyAdapter, NeonAdapter, PgSnapshotRestoreAdapter, ExternalAdapter, createDefaultDatabaseAdapterRegistry, buildInjectionOverrides, parsePostgresUrl, maskConnectionString, enforceTopologyGuard, buildMigrationDivergedEvent, DatabaseBranchAdapterError, BranchTopologyForbiddenError, type DatabaseBranchAdapter, type DatabaseBranchCapabilities, type DatabaseBranchHandle, type DatabaseAdapterName, type ResolvedDatabaseBranchPool, type DatabaseAccess, type SqliteCopyAdapterDeps, type NeonAdapterDeps, type PgSnapshotRestoreAdapterDeps, type ExternalAdapterDeps, type InjectedEnvOverrides, type KnownInFlightBranches, type MigrationDivergedEvent, } from './database/index.js';
101
+ export { StateWriter, appendEvent, readEvents, atomicWriteJson, listActiveStates, HEARTBEAT_INTERVAL_MS, HEARTBEAT_STALE_MS, type RuntimeState, type ArtifactEvent, type StageStatus, } from './artifacts/index.js';
102
+ export { runWorkerPool, withMergeGate, forceReleaseMergeGate, isBranchUpToDate, MergeGateLockTimeoutError, decideRequeue, appendTriageHistory, type WorkItem, type WorkerPoolDeps, type WorkerPoolEvent, type WorkerPoolResult, type FailureEvent, type RequeueTrigger, type RequeueDecision, type RequeueDecisionInput, type TriageHistoryEntry, type FailureClassification, type MergeGateDeps, } from './dispatch/index.js';
103
+ export { ModelRegistry, ModelRemovedError, UnknownAliasError, DEFAULT_REGISTRY, decideFromRawOutput, decideFromInvocationFailure, validateClassifierOutput, defaultRulesetDecision, appendCalibrationEntry, ALL_REVIEWERS, type ModelEntry, type ResolutionContext, type ResolutionResult, type ResolutionEvent, type ReviewerName, type ClassifierOutput, type ClassifierDecision, type FellOpenReason, type CalibrationLogEntry, type DiffSummary, } from './models/index.js';
78
104
  export { PipelineCycleDetector, createStageMarker, parseStageInvocations, DEFAULT_CYCLE_LIMITS, type PipelineStage, type CycleConfig, type CycleDetectionResult, } from './pipeline-cycle-detector.js';
79
105
  export { checkAndHandleCycle, createCycleDetectorFromConfig, type CycleHandlerOptions, type CycleCheckResult, } from './cycle-utils.js';
80
106
  export type { ApiVersion, Metadata, Condition, SecretRef, MetricCondition, Duration, Resource, TriggerFilter, Trigger, Provider, RoutingStrategy, ComplexityThreshold, Routing, Stage, PipelineSpec, PipelinePhase, PipelineStatus, Pipeline, AgentConstraints, HandoffContractRef, Handoff, SkillExample, Skill, AgentCard, AgentRoleSpec, AgentRoleStatus, AgentRole, GateScope, MetricRule, ToolRule, ReviewerRule, DocumentationRule, ProvenanceRule, ExpressionRule, GateRule, EnforcementLevel, Override, RetryPolicy, Evaluation, Gate, QualityGateSpec, QualityGateStatus, QualityGate, Permissions, ApprovalRequirement, Guardrails, MonitoringLevel, AutonomyLevel, PromotionCriteria, DemotionTrigger, AgentAutonomyStatus, AutonomyPolicySpec, AutonomyPolicyStatus, AutonomyPolicy, AdapterInterface, HealthCheck, AdapterBindingSpec, AdapterBindingStatus, AdapterBinding, AnyResource, ResourceKind, ValidationError, GateVerdict, DemotionResult, ComplexityFactor, AuthorizationContext, AuthorizationResult, AuthIdentity, AuthenticationResult, Authenticator, MutatingGateContext, ExpressionEvaluator, ExpressionVerdict, LLMEvaluationDimension, LLMEvaluationResult, LLMGateVerdict, AgentExecutionState, HandoffValidationError, SchemaResolver, SchemaValidationError, MemoryTier, MemoryEntry, WorkingMemory, ShortTermMemory, LongTermMemory, SharedMemory, EpisodicMemory, } from './types.js';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // ── Core orchestration ───────────────────────────────────────────────
2
- export { loadConfig, loadConfigAsync } from './config.js';
2
+ export { loadConfig, loadConfigAsync, } from './config.js';
3
3
  export { validateIssue, validateIssueWithExtensions, parseComplexity } from './validate-issue.js';
4
4
  export { executePipeline, } from './execute.js';
5
5
  export { validateAgentOutput, } from './validate-agent-output.js';
@@ -34,8 +34,27 @@ export { computePriority, rankWorkItems, } from './priority.js';
34
34
  export { checkAction, enforceAction, DEFAULT_BLOCKED_ACTIONS, } from './action-enforcement.js';
35
35
  // Issue admission scoring
36
36
  export { scoreIssueForAdmission, mapIssueToPriorityInput, } from './admission-score.js';
37
+ export { enrichAdmissionInput, computeDesignSystemReadiness, computeReadinessFromDesignSystemContext, computeDefectRiskFactor, computeAutonomyFactor, computeDesignAuthorityWeight, complexityToAutonomyLevel, } from './admission-enrichment.js';
38
+ export { computeAdmissionComposite } from './admission-composite.js';
39
+ export { parseBacklogTask, loadBacklogTaskFromRoot, mapBacklogTaskToAdmissionInput, loadSoulTracks, loadMaintainers, } from './backlog-adapter.js';
40
+ export { computePillarBreakdown, detectTensions, pillarSignalScore, } from './pillar-breakdown.js';
41
+ // RFC-0008 Addendum B — SA scoring (Layer 1/2/3 + composite)
42
+ export { compileDid, validatePhase2bReadiness, hashDidSpec, canonicalJson, tokenize, serializeForStore, deserializeFromStore, } from './sa-scoring/did-compiler.js';
43
+ export { HttpDepparseClient, FakeDepparseClient, DepparseError, } from './sa-scoring/depparse-client.js';
44
+ export { runLayer1, checkScopeGate, detectConstraintViolations, detectAntiPatterns, checkMeasurableSignals, renderPreVerifiedSummary, } from './sa-scoring/layer1-deterministic.js';
45
+ export { computeDomainRelevance, computePrincipleCoverage, } from './sa-scoring/layer2-structural.js';
46
+ export { runLayer3, buildSa1Prompt, buildSa2Prompt, extractJson, RecordedLLMClient, LayerLlmError, CONFIDENCE_THRESHOLD, } from './sa-scoring/layer3-llm.js';
47
+ export { computeSoulAlignment, computeSa1, computeSa2, getPhaseWeights, W_STRUCTURAL_FLOOR, } from './sa-scoring/composite.js';
48
+ export { computeSa2Computable } from './sa-scoring/c1-sa2-computable.js';
49
+ export { SAFeedbackStore, SA_FEEDBACK_LABELS, classifyLabel, recordOverrideFeedback, } from './sa-scoring/feedback-store.js';
50
+ export { computeCalibrationCoefficient, buildCategoryCoefficients, } from './calibration.js';
51
+ export { autoCalibratePhaseWeights, computePhase3Weights, decideCalibrationDirection, renderCalibrationDiff, WEIGHT_FLOOR, WEIGHT_CEILING, DEFAULT_SHIFT_SIZE, DEFAULT_WINDOW_DAYS, PRECISION_DELTA_THRESHOLD, } from './sa-scoring/auto-calibrate.js';
52
+ export { detectSoulDrift, computeWindowStats, computeTrend, describeDriftSource, DEFAULT_MEAN_THRESHOLD, DEFAULT_STDDEV_THRESHOLD, DEFAULT_CONSECUTIVE_WINDOWS, DEFAULT_RECOVERY_MS, } from './sa-scoring/drift-monitor.js';
53
+ export { handleCoreIdentityChanged, } from './sa-scoring/rescore-orchestrator.js';
54
+ export { scoreSoulAlignment, resolveSoulAlignmentOverride, } from './sa-scoring/index.js';
37
55
  // PR review orchestration
38
56
  export { executeReview } from './review.js';
57
+ export { metaReview, ReviewFeedbackStore, } from './review-meta.js';
39
58
  // Agent orchestration
40
59
  export { createPipelineOrchestration, executePipelineOrchestration, validatePipelineHandoffs, sequential, parallel, hybrid, hierarchical, swarm, validateHandoff, simpleSchemaValidate, } from './orchestration.js';
41
60
  // Policy evaluators
@@ -77,7 +96,7 @@ export { createOTelBridge, isOTelAvailable } from './otel-exporter.js';
77
96
  // Dashboard renderer
78
97
  export { renderDashboardFrame } from './cli/dashboard-renderer.js';
79
98
  // Codebase analysis
80
- export { walkFiles, detectModules, parseImports, buildModuleGraph, detectConventions, detectPatterns, analyzeHotspots, computeComplexityScore, analyzeCodebase, buildCodebaseContext, formatContextForPrompt, } from './analysis/index.js';
99
+ export { walkFiles, detectModules, parseImports, buildModuleGraph, detectConventions, detectReactProject, loadProjectAliases, parseTsConfigAliases, parseViteOrWebpackAliases, enumerateTestLocations, detectPatterns, analyzeHotspots, computeComplexityScore, analyzeCodebase, buildCodebaseContext, formatContextForPrompt, analyzeDiff, extractChangedFiles, } from './analysis/index.js';
81
100
  // Check runs
82
101
  export { createCheckRun, updateCheckRun, reportGateCheckRuns } from './check-runs.js';
83
102
  // Multi-repo orchestration
@@ -97,6 +116,20 @@ export { archiveEntries, loadArchivedEntries, verifyArchiveContinuity } from './
97
116
  export { Orchestrator } from './orchestrator.js';
98
117
  // Cost governance plugin
99
118
  export { CostGovernancePlugin } from './cost-governance.js';
119
+ // RFC-0010 runtime primitives
120
+ export { WorktreePoolManager, WorktreePoolError, WorktreeOwnershipError, deterministicPort, allocatePort, allocateContiguousPorts, isPortFree, PortAllocationError, slugifyBranch, worktreePath, verifyOwnership, assertOwnership, isExistingWorktree, readParallelismMode, isParallelismEnabled, PARALLELISM_FLAG, DEFAULT_BASE_PORT, DEFAULT_POOL_ROOT, DEFAULT_STALE_THRESHOLD_DAYS, } from './runtime/index.js';
121
+ // RFC-0010 harness adapters
122
+ export { HarnessRegistry, UnknownHarnessError, ClaudeCodeAdapter, CodexAdapter, createDefaultHarnessRegistry, probeVersion, matchesRange, enforceIndependence, validateIndependenceGraph, CyclicIndependenceConstraintError, } from './harness/index.js';
123
+ // RFC-0010 subscription scheduling
124
+ export { SubscriptionLedger, validateTenantShares, evaluateSchedule, CalibrationStore, COLD_START_DEFAULT, buildBurnDownReport, analyzeTier, PLAN_COSTS_USD, isOffPeakAt, nextOffPeakStart, ageInDays, freshnessLevel, DEFAULT_TENANT, COLD_START_DEFAULT_INPUT, COLD_START_DEFAULT_OUTPUT, ESTIMATE_VARIANCE_THRESHOLD, ROLLING_WINDOW_SIZE, } from './scheduling/index.js';
125
+ // RFC-0010 database branching (DatabaseBranchAdapter framework + 4 adapters)
126
+ export { DatabaseAdapterRegistry, UnknownDatabaseAdapterError, SqliteCopyAdapter, NeonAdapter, PgSnapshotRestoreAdapter, ExternalAdapter, createDefaultDatabaseAdapterRegistry, buildInjectionOverrides, parsePostgresUrl, maskConnectionString, enforceTopologyGuard, buildMigrationDivergedEvent, DatabaseBranchAdapterError, BranchTopologyForbiddenError, } from './database/index.js';
127
+ // RFC-0010 artifacts (heartbeat + event stream + atomic JSON + state listing)
128
+ export { StateWriter, appendEvent, readEvents, atomicWriteJson, listActiveStates, HEARTBEAT_INTERVAL_MS, HEARTBEAT_STALE_MS, } from './artifacts/index.js';
129
+ // RFC-0010 dispatch (worker pool + merge gate + requeue)
130
+ export { runWorkerPool, withMergeGate, forceReleaseMergeGate, isBranchUpToDate, MergeGateLockTimeoutError, decideRequeue, appendTriageHistory, } from './dispatch/index.js';
131
+ // RFC-0010 model registry + classifier
132
+ export { ModelRegistry, ModelRemovedError, UnknownAliasError, DEFAULT_REGISTRY, decideFromRawOutput, decideFromInvocationFailure, validateClassifierOutput, defaultRulesetDecision, appendCalibrationEntry, ALL_REVIEWERS, } from './models/index.js';
100
133
  // Pipeline cycle detection
101
134
  export { PipelineCycleDetector, createStageMarker, parseStageInvocations, DEFAULT_CYCLE_LIMITS, } from './pipeline-cycle-detector.js';
102
135
  export { checkAndHandleCycle, createCycleDetectorFromConfig, } from './cycle-utils.js';
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Conditional review classifier (RFC-0010 §12). The classifier reads a PR diff and emits a
3
+ * structured decision listing which downstream review agents to invoke. This module provides:
4
+ *
5
+ * - The output-schema validator (Q4 resolution: confident: bool + confidence: float with
6
+ * consistency rule confident: true REQUIRES confidence ≥ 0.7).
7
+ * - The default fall-open ruleset (RFC §12.3 baseline + the four fall-open triggers).
8
+ * - The calibration-log writer for $ARTIFACTS_DIR/_classifier/calibration.jsonl.
9
+ */
10
+ export type ReviewerName = 'testing' | 'critic' | 'security';
11
+ export declare const ALL_REVIEWERS: readonly ReviewerName[];
12
+ export interface ClassifierOutput {
13
+ reviewers: ReviewerName[];
14
+ rationale: Record<string, string>;
15
+ confident: boolean;
16
+ confidence: number;
17
+ modelOverride?: Partial<Record<ReviewerName, 'haiku' | 'sonnet' | 'opus' | 'opus[1m]'>>;
18
+ harnessOverride?: Partial<Record<ReviewerName, string>>;
19
+ }
20
+ export type FellOpenReason = 'parse-error' | 'schema-validation' | 'confident-false' | 'invocation-failed';
21
+ export interface ClassifierDecision {
22
+ reviewers: readonly ReviewerName[];
23
+ fellOpen: boolean;
24
+ fellOpenReason: FellOpenReason | null;
25
+ rawOutput: ClassifierOutput | null;
26
+ parseError: string | null;
27
+ }
28
+ /**
29
+ * Parse and validate raw JSON output from a classifier-LLM invocation. Returns a structured
30
+ * decision; on any validation failure the decision falls open to the full reviewer set per
31
+ * RFC §12.3 (failing open is a non-negotiable safety property).
32
+ */
33
+ export declare function decideFromRawOutput(rawJson: string): ClassifierDecision;
34
+ /** Decision used when the classifier invocation itself fails (timeout, harness exhausted). */
35
+ export declare function decideFromInvocationFailure(): ClassifierDecision;
36
+ type ValidationResult = {
37
+ ok: true;
38
+ value: ClassifierOutput;
39
+ } | {
40
+ ok: false;
41
+ error: string;
42
+ };
43
+ export declare function validateClassifierOutput(value: unknown): ValidationResult;
44
+ export interface DiffSummary {
45
+ filesChanged: number;
46
+ paths: string[];
47
+ linesAdded: number;
48
+ linesRemoved: number;
49
+ }
50
+ /**
51
+ * Apply the default classifier ruleset from RFC §12.3 to a diff summary. Used as the
52
+ * fallback when no LLM classifier is configured, and as the seed prompt for LLM-based
53
+ * classifiers. Always returns confident: true with confidence: 1.0 because these are
54
+ * deterministic rules.
55
+ */
56
+ export declare function defaultRulesetDecision(diff: DiffSummary): ClassifierOutput;
57
+ export interface CalibrationLogEntry {
58
+ timestamp: string;
59
+ issueId: string;
60
+ diffStats: DiffSummary;
61
+ classifierOutput: ClassifierOutput | null;
62
+ fellOpen: boolean;
63
+ fellOpenReason: FellOpenReason | null;
64
+ /** Back-filled later via cli-classifier-feedback when the operator attributes a miss. */
65
+ humanOverrideAfterMerge: {
66
+ addedReviewer: ReviewerName;
67
+ reason: string;
68
+ } | null;
69
+ }
70
+ /**
71
+ * Append one entry to $ARTIFACTS_DIR/_classifier/calibration.jsonl. Atomic per-line via
72
+ * appendFile. Creates the directory if missing.
73
+ */
74
+ export declare function appendCalibrationEntry(artifactsDir: string, entry: CalibrationLogEntry): Promise<void>;
75
+ export {};
76
+ //# sourceMappingURL=classifier.d.ts.map
@@ -0,0 +1,221 @@
1
+ /**
2
+ * Conditional review classifier (RFC-0010 §12). The classifier reads a PR diff and emits a
3
+ * structured decision listing which downstream review agents to invoke. This module provides:
4
+ *
5
+ * - The output-schema validator (Q4 resolution: confident: bool + confidence: float with
6
+ * consistency rule confident: true REQUIRES confidence ≥ 0.7).
7
+ * - The default fall-open ruleset (RFC §12.3 baseline + the four fall-open triggers).
8
+ * - The calibration-log writer for $ARTIFACTS_DIR/_classifier/calibration.jsonl.
9
+ */
10
+ import { appendFile, mkdir } from 'node:fs/promises';
11
+ import { dirname } from 'node:path';
12
+ export const ALL_REVIEWERS = ['testing', 'critic', 'security'];
13
+ const VALID_MODEL_OVERRIDES = new Set(['haiku', 'sonnet', 'opus', 'opus[1m]']);
14
+ const VALID_HARNESS_OVERRIDES = new Set([
15
+ 'claude-code',
16
+ 'codex',
17
+ 'gemini-cli',
18
+ 'opencode',
19
+ 'aider',
20
+ 'generic-api',
21
+ ]);
22
+ const CONFIDENCE_FLOOR_FOR_TRUE = 0.7;
23
+ /**
24
+ * Parse and validate raw JSON output from a classifier-LLM invocation. Returns a structured
25
+ * decision; on any validation failure the decision falls open to the full reviewer set per
26
+ * RFC §12.3 (failing open is a non-negotiable safety property).
27
+ */
28
+ export function decideFromRawOutput(rawJson) {
29
+ let parsed;
30
+ try {
31
+ parsed = JSON.parse(rawJson);
32
+ }
33
+ catch (err) {
34
+ return failOpen('parse-error', null, err.message);
35
+ }
36
+ const validation = validateClassifierOutput(parsed);
37
+ if (!validation.ok) {
38
+ return failOpen('schema-validation', null, validation.error);
39
+ }
40
+ if (!validation.value.confident) {
41
+ return failOpen('confident-false', validation.value, null);
42
+ }
43
+ return {
44
+ reviewers: validation.value.reviewers,
45
+ fellOpen: false,
46
+ fellOpenReason: null,
47
+ rawOutput: validation.value,
48
+ parseError: null,
49
+ };
50
+ }
51
+ /** Decision used when the classifier invocation itself fails (timeout, harness exhausted). */
52
+ export function decideFromInvocationFailure() {
53
+ return failOpen('invocation-failed', null, null);
54
+ }
55
+ function failOpen(reason, rawOutput, parseError) {
56
+ return {
57
+ reviewers: ALL_REVIEWERS,
58
+ fellOpen: true,
59
+ fellOpenReason: reason,
60
+ rawOutput,
61
+ parseError,
62
+ };
63
+ }
64
+ export function validateClassifierOutput(value) {
65
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
66
+ return { ok: false, error: 'output is not an object' };
67
+ }
68
+ const obj = value;
69
+ // reviewers: array of ReviewerName, unique
70
+ if (!Array.isArray(obj.reviewers)) {
71
+ return { ok: false, error: 'reviewers must be an array' };
72
+ }
73
+ const seen = new Set();
74
+ for (const r of obj.reviewers) {
75
+ if (typeof r !== 'string' || !ALL_REVIEWERS.includes(r)) {
76
+ return { ok: false, error: `reviewers contains invalid value: ${String(r)}` };
77
+ }
78
+ if (seen.has(r))
79
+ return { ok: false, error: `reviewers contains duplicate: ${r}` };
80
+ seen.add(r);
81
+ }
82
+ // rationale: object with string values
83
+ if (typeof obj.rationale !== 'object' || obj.rationale === null || Array.isArray(obj.rationale)) {
84
+ return { ok: false, error: 'rationale must be an object' };
85
+ }
86
+ for (const [k, v] of Object.entries(obj.rationale)) {
87
+ if (typeof v !== 'string') {
88
+ return { ok: false, error: `rationale.${k} must be a string` };
89
+ }
90
+ }
91
+ // confident: bool
92
+ if (typeof obj.confident !== 'boolean') {
93
+ return { ok: false, error: 'confident must be a boolean' };
94
+ }
95
+ // confidence: number in [0, 1]
96
+ if (typeof obj.confidence !== 'number' ||
97
+ !Number.isFinite(obj.confidence) ||
98
+ obj.confidence < 0 ||
99
+ obj.confidence > 1) {
100
+ return { ok: false, error: 'confidence must be a number in [0, 1]' };
101
+ }
102
+ // Consistency: confident: true REQUIRES confidence >= 0.7
103
+ if (obj.confident && obj.confidence < CONFIDENCE_FLOOR_FOR_TRUE) {
104
+ return {
105
+ ok: false,
106
+ error: `confident: true requires confidence >= ${CONFIDENCE_FLOOR_FOR_TRUE} (got ${obj.confidence})`,
107
+ };
108
+ }
109
+ // Optional modelOverride: { reviewerName?: alias }
110
+ if (obj.modelOverride !== undefined) {
111
+ if (typeof obj.modelOverride !== 'object' ||
112
+ obj.modelOverride === null ||
113
+ Array.isArray(obj.modelOverride)) {
114
+ return { ok: false, error: 'modelOverride must be an object' };
115
+ }
116
+ for (const [k, v] of Object.entries(obj.modelOverride)) {
117
+ if (!ALL_REVIEWERS.includes(k)) {
118
+ return { ok: false, error: `modelOverride contains unknown reviewer: ${k}` };
119
+ }
120
+ if (typeof v !== 'string' || !VALID_MODEL_OVERRIDES.has(v)) {
121
+ return {
122
+ ok: false,
123
+ error: `modelOverride.${k} must be one of ${[...VALID_MODEL_OVERRIDES].join('|')}`,
124
+ };
125
+ }
126
+ }
127
+ }
128
+ // Optional harnessOverride: { reviewerName?: harnessName }
129
+ if (obj.harnessOverride !== undefined) {
130
+ if (typeof obj.harnessOverride !== 'object' ||
131
+ obj.harnessOverride === null ||
132
+ Array.isArray(obj.harnessOverride)) {
133
+ return { ok: false, error: 'harnessOverride must be an object' };
134
+ }
135
+ for (const [k, v] of Object.entries(obj.harnessOverride)) {
136
+ if (!ALL_REVIEWERS.includes(k)) {
137
+ return { ok: false, error: `harnessOverride contains unknown reviewer: ${k}` };
138
+ }
139
+ if (typeof v !== 'string' || !VALID_HARNESS_OVERRIDES.has(v)) {
140
+ return {
141
+ ok: false,
142
+ error: `harnessOverride.${k} must be one of ${[...VALID_HARNESS_OVERRIDES].join('|')}`,
143
+ };
144
+ }
145
+ }
146
+ }
147
+ return { ok: true, value: obj };
148
+ }
149
+ /**
150
+ * Apply the default classifier ruleset from RFC §12.3 to a diff summary. Used as the
151
+ * fallback when no LLM classifier is configured, and as the seed prompt for LLM-based
152
+ * classifiers. Always returns confident: true with confidence: 1.0 because these are
153
+ * deterministic rules.
154
+ */
155
+ export function defaultRulesetDecision(diff) {
156
+ if (diff.filesChanged === 0) {
157
+ return {
158
+ reviewers: [],
159
+ rationale: { all: 'no files changed; no review needed' },
160
+ confident: true,
161
+ confidence: 1,
162
+ };
163
+ }
164
+ const allDocs = diff.paths.every((p) => /\.(md|rst|txt)$/i.test(p) || p.startsWith('docs/'));
165
+ if (allDocs) {
166
+ return {
167
+ reviewers: ['critic'],
168
+ rationale: { critic: 'documentation-only change; critic suffices' },
169
+ confident: true,
170
+ confidence: 0.95,
171
+ };
172
+ }
173
+ const touchesAuth = diff.paths.some((p) => /(?:^|\/)(auth|crypto|secrets?)\b/i.test(p));
174
+ const touchesLockfiles = diff.paths.some((p) => /(?:^|\/)(package(-lock)?\.json|requirements\.txt|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|poetry\.lock|Pipfile\.lock)$/i.test(p));
175
+ const touchesCi = diff.paths.some((p) => p.startsWith('.github/workflows/'));
176
+ if (touchesAuth) {
177
+ return {
178
+ reviewers: ['testing', 'critic', 'security'],
179
+ rationale: {
180
+ testing: 'auth touched; verify regression coverage',
181
+ critic: 'auth touched; verify approach',
182
+ security: 'auth-touching diff; mandatory security review',
183
+ },
184
+ modelOverride: { security: 'opus' },
185
+ confident: true,
186
+ confidence: 0.99,
187
+ };
188
+ }
189
+ if (touchesLockfiles || touchesCi) {
190
+ return {
191
+ reviewers: ['security', 'critic'],
192
+ rationale: {
193
+ security: touchesLockfiles ? 'supply-chain (lockfile) change' : 'CI workflow change',
194
+ critic: 'verify approach',
195
+ },
196
+ confident: true,
197
+ confidence: 0.9,
198
+ };
199
+ }
200
+ // Default: all three
201
+ return {
202
+ reviewers: ['testing', 'critic', 'security'],
203
+ rationale: {
204
+ testing: 'default fallback',
205
+ critic: 'default fallback',
206
+ security: 'default fallback',
207
+ },
208
+ confident: true,
209
+ confidence: 0.8,
210
+ };
211
+ }
212
+ /**
213
+ * Append one entry to $ARTIFACTS_DIR/_classifier/calibration.jsonl. Atomic per-line via
214
+ * appendFile. Creates the directory if missing.
215
+ */
216
+ export async function appendCalibrationEntry(artifactsDir, entry) {
217
+ const path = `${artifactsDir}/_classifier/calibration.jsonl`;
218
+ await mkdir(dirname(path), { recursive: true });
219
+ await appendFile(path, JSON.stringify(entry) + '\n', 'utf8');
220
+ }
221
+ //# sourceMappingURL=classifier.js.map
@@ -0,0 +1,3 @@
1
+ export { ModelRegistry, ModelRemovedError, UnknownAliasError, DEFAULT_REGISTRY, type ModelEntry, type ResolutionContext, type ResolutionResult, type ResolutionEvent, } from './registry.js';
2
+ export { decideFromRawOutput, decideFromInvocationFailure, validateClassifierOutput, defaultRulesetDecision, appendCalibrationEntry, ALL_REVIEWERS, type ReviewerName, type ClassifierOutput, type ClassifierDecision, type FellOpenReason, type CalibrationLogEntry, type DiffSummary, } from './classifier.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,3 @@
1
+ export { ModelRegistry, ModelRemovedError, UnknownAliasError, DEFAULT_REGISTRY, } from './registry.js';
2
+ export { decideFromRawOutput, decideFromInvocationFailure, validateClassifierOutput, defaultRulesetDecision, appendCalibrationEntry, ALL_REVIEWERS, } from './classifier.js';
3
+ //# sourceMappingURL=index.js.map