@harness-engineering/intelligence 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Intense Visions, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,441 @@
1
+ # @harness-engineering/intelligence
2
+
3
+ Intelligence pipeline for spec enrichment, complexity modeling, and pre-execution simulation. Augments the hybrid orchestrator's routing with graph-backed analysis and tiered simulation.
4
+
5
+ ## Architecture
6
+
7
+ ```
8
+ ┌─────────────────────┐
9
+ │ Work Item Input │
10
+ │ Roadmap · JIRA · │
11
+ │ GitHub · Linear · │
12
+ │ Manual text │
13
+ └──────────┬──────────┘
14
+
15
+ ┌─────────────────────┐
16
+ │ Adapters │
17
+ │ toRawWorkItem() │
18
+ │ jiraToRawWorkItem() │
19
+ │ githubToRawWorkItem │
20
+ │ linearToRawWorkItem │
21
+ │ manualToRawWorkItem │
22
+ └──────────┬──────────┘
23
+
24
+ ┌────────────────────────────────────────────────────────────────┐
25
+ │ IntelligencePipeline │
26
+ │ │
27
+ │ ┌──────────────────────────────────────────────────────────┐ │
28
+ │ │ SEL — Spec Enrichment Layer │ │
29
+ │ │ LLM analysis + graph-validated system discovery │ │
30
+ │ │ → EnrichedSpec (intent, affected systems, unknowns) │ │
31
+ │ └──────────────────────┬───────────────────────────────────┘ │
32
+ │ ▼ │
33
+ │ ┌──────────────────────────────────────────────────────────┐ │
34
+ │ │ CML — Complexity Modeling Layer │ │
35
+ │ │ Structural (graph blast radius) + Semantic (ambiguity) │ │
36
+ │ │ + Historical (past outcome failure rate) │ │
37
+ │ │ → ComplexityScore → ConcernSignal[] │ │
38
+ │ └──────────────────────┬───────────────────────────────────┘ │
39
+ │ ▼ │
40
+ │ ┌──────────────────────────────────────────────────────────┐ │
41
+ │ │ PESL — Pre-Execution Simulation Layer │ │
42
+ │ │ Graph-only checks (quick-fix) or full LLM simulation │ │
43
+ │ │ (guided-change) with abort on low confidence │ │
44
+ │ │ → SimulationResult (confidence, abort flag) │ │
45
+ │ └──────────────────────────────────────────────────────────┘ │
46
+ │ │
47
+ │ ┌──────────────────────────────────────────────────────────┐ │
48
+ │ │ Outcome Recording │ │
49
+ │ │ ExecutionOutcomeConnector → graph nodes + edges │ │
50
+ │ │ Feeds back into CML historical dimension │ │
51
+ │ └──────────────────────────────────────────────────────────┘ │
52
+ └────────────────────────────────────────────────────────────────┘
53
+ ```
54
+
55
+ ## Quick Start
56
+
57
+ ```ts
58
+ import {
59
+ IntelligencePipeline,
60
+ AnthropicAnalysisProvider,
61
+ toRawWorkItem,
62
+ } from '@harness-engineering/intelligence';
63
+ import { GraphStore } from '@harness-engineering/graph';
64
+
65
+ // 1. Create the pipeline
66
+ const provider = new AnthropicAnalysisProvider({
67
+ apiKey: process.env.ANTHROPIC_API_KEY!,
68
+ });
69
+ const store = new GraphStore();
70
+ await store.load('.harness/graph');
71
+
72
+ const pipeline = new IntelligencePipeline(provider, store);
73
+
74
+ // 2. Preprocess an issue (SEL → CML → signals)
75
+ const result = await pipeline.preprocessIssue(issue, scopeTier, escalationConfig);
76
+ // result.spec — EnrichedSpec with intent, affected systems, unknowns
77
+ // result.score — ComplexityScore with overall 0-1, risk level, reasoning
78
+ // result.signals — ConcernSignal[] for routeIssue()
79
+
80
+ // 3. Simulate before dispatch (PESL)
81
+ if (result.spec && result.score) {
82
+ const simulation = await pipeline.simulate(result.spec, result.score, scopeTier);
83
+ // simulation.abort — true if confidence too low
84
+ // simulation.predictedFailures — what might go wrong
85
+ // simulation.testGaps — missing test coverage
86
+ }
87
+
88
+ // 4. Record execution outcomes (feedback loop)
89
+ await pipeline.recordOutcome({
90
+ issueId: 'CORE-42',
91
+ result: 'success',
92
+ retryCount: 0,
93
+ failureReasons: [],
94
+ durationMs: 45000,
95
+ affectedSystemNodeIds: ['node-abc'],
96
+ });
97
+ ```
98
+
99
+ ## Tier-Based Behavior
100
+
101
+ The pipeline adapts its behavior based on the orchestrator's scope tier:
102
+
103
+ | Scope Tier | SEL | CML | PESL | Routing |
104
+ | ------------------------------------- | ---- | ---- | ------------------- | --------------------------------------- |
105
+ | `autoExecute` (quick-fix, diagnostic) | Skip | Skip | Graph-only | Always dispatch locally |
106
+ | `signalGated` (guided-change) | Run | Run | Full LLM simulation | Dispatch if no concern signals |
107
+ | `alwaysHuman` (full-exploration) | Run | Skip | Skip | Always escalate (enrichment as context) |
108
+
109
+ ## Layers
110
+
111
+ ### SEL — Spec Enrichment Layer
112
+
113
+ Converts raw work items into structured `EnrichedSpec` objects via LLM analysis and graph validation.
114
+
115
+ ```ts
116
+ import { enrich, GraphValidator } from '@harness-engineering/intelligence';
117
+
118
+ const validator = new GraphValidator(store);
119
+ const spec = await enrich(rawWorkItem, provider, validator);
120
+ // spec.intent — what the task is trying to accomplish
121
+ // spec.affectedSystems — graph-validated system references
122
+ // spec.unknowns — explicitly identified knowledge gaps
123
+ // spec.ambiguities — areas needing clarification
124
+ ```
125
+
126
+ ### CML — Complexity Modeling Layer
127
+
128
+ Scores task complexity across three dimensions:
129
+
130
+ - **Structural** — Graph blast radius via `CascadeSimulator`, normalized to 0-1
131
+ - **Semantic** — Unknowns, ambiguities, and risk signals from SEL enrichment
132
+ - **Historical** — Smoothed failure rate from past execution outcomes on the same affected systems
133
+
134
+ ```ts
135
+ import { scoreCML, scoreToConcernSignals } from '@harness-engineering/intelligence';
136
+
137
+ const score = scoreCML(enrichedSpec, store);
138
+ // score.overall — 0-1 weighted composite
139
+ // score.riskLevel — 'low' | 'medium' | 'high' | 'critical'
140
+ // score.recommendedRoute — 'local' | 'human' | 'simulation-required'
141
+
142
+ const signals = scoreToConcernSignals(score);
143
+ // signals fed into existing routeIssue() for signalGated tiers
144
+ ```
145
+
146
+ ### PESL — Pre-Execution Simulation Layer
147
+
148
+ Simulates execution before code is written. Tiered by cost:
149
+
150
+ - **Graph-only** (quick-fix/diagnostic) — `CascadeSimulator` blast radius + test gap detection. Fast (<2s), no LLM cost.
151
+ - **Full simulation** (guided-change) — LLM-assisted plan expansion, failure injection, test projection. Merged with graph baseline.
152
+
153
+ ```ts
154
+ import { PeslSimulator } from '@harness-engineering/intelligence';
155
+
156
+ const simulator = new PeslSimulator(provider, store);
157
+ const result = await simulator.simulate(spec, score, scopeTier);
158
+
159
+ if (result.abort) {
160
+ // Confidence too low — escalate to human instead of dispatching
161
+ console.log('Predicted failures:', result.predictedFailures);
162
+ console.log('Test gaps:', result.testGaps);
163
+ }
164
+ ```
165
+
166
+ ### Adapters
167
+
168
+ Pure mapping functions for converting external data into `RawWorkItem`:
169
+
170
+ ```ts
171
+ import {
172
+ toRawWorkItem, // Roadmap Issue → RawWorkItem
173
+ jiraToRawWorkItem, // JIRA issue → RawWorkItem
174
+ githubToRawWorkItem, // GitHub issue/PR → RawWorkItem
175
+ linearToRawWorkItem, // Linear issue → RawWorkItem
176
+ manualToRawWorkItem, // Free text → RawWorkItem
177
+ } from '@harness-engineering/intelligence';
178
+ ```
179
+
180
+ Each adapter accepts a pre-fetched data object and produces a `RawWorkItem`. No API clients are included — adapters are pure functions.
181
+
182
+ ### Effectiveness — Agent Performance Introspection
183
+
184
+ Analyzes persona-attributed `execution_outcome` nodes in the graph to score per-persona accuracy, detect blind spots, and recommend which persona to route new issues to.
185
+
186
+ ```ts
187
+ import {
188
+ computePersonaEffectiveness,
189
+ detectBlindSpots,
190
+ recommendPersona,
191
+ } from '@harness-engineering/intelligence';
192
+
193
+ // Per-(persona, system) success rates with Laplace smoothing
194
+ const scores = computePersonaEffectiveness(store, { persona: 'backend-dev' });
195
+ // scores[0].successRate — smoothed success rate in [0, 1]
196
+ // scores[0].sampleSize — total observations
197
+
198
+ // Blind spots: (persona, system) pairs with high failure rates
199
+ const spots = detectBlindSpots(store, { minFailures: 2, minFailureRate: 0.5 });
200
+ // spots[0].failureRate — raw failure rate
201
+ // spots[0].failures — absolute failure count
202
+
203
+ // Recommend personas for an issue given its affected systems
204
+ const recs = recommendPersona(store, {
205
+ systemNodeIds: ['module-auth', 'module-db'],
206
+ candidatePersonas: ['backend-dev', 'fullstack'],
207
+ minSamples: 3,
208
+ });
209
+ // recs[0].persona — best candidate
210
+ // recs[0].score — mean smoothed success rate across requested systems
211
+ ```
212
+
213
+ ### Specialization — Persistent Agent Expertise Tracking
214
+
215
+ Extends effectiveness with temporal decay, task-type categorization, consistency scoring, expertise levels, and persistent profile storage. Recent outcomes are weighted more heavily than old ones via exponential decay.
216
+
217
+ ```ts
218
+ import {
219
+ computeSpecialization,
220
+ computeExpertiseLevel,
221
+ buildSpecializationProfile,
222
+ weightedRecommendPersona,
223
+ decayWeight,
224
+ temporalSuccessRate,
225
+ loadProfiles,
226
+ saveProfiles,
227
+ refreshProfiles,
228
+ } from '@harness-engineering/intelligence';
229
+
230
+ // Compute specialization entries for (persona, system, taskType) tuples
231
+ const entries = computeSpecialization(store, {
232
+ persona: 'backend-dev',
233
+ taskType: 'bug-fix',
234
+ temporal: { halfLifeDays: 30 },
235
+ });
236
+ // entries[0].score.composite — weighted combination of temporal, consistency, volume
237
+ // entries[0].expertiseLevel — 'novice' | 'competent' | 'proficient' | 'expert'
238
+
239
+ // Classify expertise from raw numbers
240
+ const level = computeExpertiseLevel(25, 0.8); // → 'proficient'
241
+
242
+ // Build a full profile for a persona (strengths, weaknesses, overall level)
243
+ const profile = buildSpecializationProfile(store, 'backend-dev', {
244
+ temporal: { halfLifeDays: 30 },
245
+ });
246
+ // profile.strengths — top 3 entries by composite score
247
+ // profile.weaknesses — entries with temporal success rate < 0.5
248
+ // profile.overallLevel — median expertise across all entries
249
+
250
+ // Weighted recommendation incorporating specialization multipliers
251
+ const weighted = weightedRecommendPersona(store, {
252
+ systemNodeIds: ['module-auth'],
253
+ taskType: 'bug-fix',
254
+ });
255
+ // weighted[0].weightedScore — baseScore * specializationMultiplier
256
+
257
+ // Temporal decay helpers
258
+ const weight = decayWeight(15, 30); // weight at 15 days with 30-day half-life
259
+ const rate = temporalSuccessRate([{ result: 'success', timestamp: '2026-04-01T00:00:00Z' }], {
260
+ halfLifeDays: 30,
261
+ });
262
+
263
+ // Persist profiles to .harness/specialization-profiles.json
264
+ const profiles = loadProfiles('/path/to/project');
265
+ saveProfiles('/path/to/project', profiles);
266
+
267
+ // Recompute and persist profiles for all personas with outcomes
268
+ const refreshed = refreshProfiles('/path/to/project', store);
269
+ ```
270
+
271
+ ### Outcome Recording
272
+
273
+ Execution results feed back into the graph for future CML scoring:
274
+
275
+ ```ts
276
+ import { ExecutionOutcomeConnector } from '@harness-engineering/intelligence';
277
+
278
+ const connector = new ExecutionOutcomeConnector(store);
279
+ await connector.ingest({
280
+ issueId: 'CORE-42',
281
+ result: 'failure',
282
+ retryCount: 2,
283
+ failureReasons: ['Migration script failed'],
284
+ durationMs: 120000,
285
+ affectedSystemNodeIds: ['module-auth'],
286
+ });
287
+ // Creates execution_outcome node with outcome_of edges to affected systems
288
+ // Future CML scoring queries these outcomes for historical failure rates
289
+ ```
290
+
291
+ ## Orchestrator Integration
292
+
293
+ The intelligence pipeline integrates into the orchestrator's tick cycle at two points:
294
+
295
+ 1. **Pre-routing** (in `asyncTick`) — `preprocessIssue()` runs SEL + CML, producing concern signals that feed into `routeIssue()`. For `alwaysHuman` tiers, the enriched spec is attached to the `EscalateEffect` as context for the human reviewer.
296
+
297
+ 2. **Post-routing** (in `asyncTick`) — `simulate()` runs PESL for locally-routed issues. If simulation recommends abort (`confidence < 0.3`), the dispatch is converted to an `EscalateEffect` instead.
298
+
299
+ 3. **Post-execution** (in `emitWorkerExit`) — `recordOutcome()` ingests the execution result into the graph, feeding the CML historical dimension for future scoring.
300
+
301
+ ### Dashboard
302
+
303
+ The dashboard's **Attention** page displays escalated interactions. When the intelligence pipeline is enabled, escalations include enriched context:
304
+
305
+ - **Enriched spec summary** — Intent, affected systems, unknowns
306
+ - **Concern signals** — What triggered the escalation (high complexity, large blast radius, high ambiguity)
307
+ - **PESL abort reasons** — Predicted failures and test gaps (when simulation recommends abort)
308
+
309
+ This context helps human reviewers make faster, more informed decisions about escalated work items.
310
+
311
+ ## Configuration
312
+
313
+ The pipeline uses the same LLM connection as the orchestrator's agent backend — Anthropic API, OpenAI API, or a local LLM (Ollama, LM Studio, etc.):
314
+
315
+ ```yaml
316
+ intelligence:
317
+ enabled: true
318
+ ```
319
+
320
+ No separate API key needed. The pipeline derives its provider from the existing agent config:
321
+
322
+ | Agent Backend | Intelligence Uses |
323
+ | --------------------------------- | --------------------------------- |
324
+ | `anthropic` / `claude` | Anthropic Messages API (same key) |
325
+ | `openai` | OpenAI Chat API (same key) |
326
+ | `localBackend: openai-compatible` | Local endpoint (same URL) |
327
+
328
+ Override models per-layer:
329
+
330
+ ```yaml
331
+ intelligence:
332
+ enabled: true
333
+ models:
334
+ sel: llama3.2 # fast model for enrichment
335
+ pesl: deepseek-r1 # reasoning model for simulation
336
+ ```
337
+
338
+ For thinking models (Qwen3, DeepSeek-R1), disable reasoning for structured output:
339
+
340
+ ```yaml
341
+ intelligence:
342
+ enabled: true
343
+ promptSuffix: '/no_think' # Qwen3 — disable thinking for structured output
344
+ jsonMode: false # Qwen3 hangs with Ollama's JSON grammar constraint
345
+ requestTimeoutMs: 90000 # fail fast instead of waiting 10 min
346
+ failureCacheTtlMs: 300000 # don't retry failed analyses for 5 min
347
+ ```
348
+
349
+ When `enabled: false` (default), the pipeline is completely skipped. See the [Intelligence Pipeline Guide](../../docs/guides/intelligence-pipeline.md) for full configuration reference.
350
+
351
+ ## Dependencies
352
+
353
+ ```
354
+ @harness-engineering/types → shared type definitions
355
+ @harness-engineering/graph → GraphStore, CascadeSimulator, node/edge types
356
+ @anthropic-ai/sdk → LLM calls via AnalysisProvider
357
+ openai → OpenAI-compatible analysis provider
358
+ zod → response schema validation
359
+ ```
360
+
361
+ The intelligence package has **no dependency** on `@harness-engineering/orchestrator`. The dependency flows one way: `orchestrator → intelligence → graph → types`.
362
+
363
+ ## API Reference
364
+
365
+ ### Pipeline
366
+
367
+ | Export | Description |
368
+ | ---------------------- | -------------------------------------------- |
369
+ | `IntelligencePipeline` | Main pipeline class composing SEL, CML, PESL |
370
+ | `PreprocessResult` | Return type of `preprocessIssue()` |
371
+
372
+ ### Adapters
373
+
374
+ | Export | Description |
375
+ | --------------------- | ------------------------------- |
376
+ | `toRawWorkItem` | Roadmap `Issue` → `RawWorkItem` |
377
+ | `jiraToRawWorkItem` | JIRA issue → `RawWorkItem` |
378
+ | `githubToRawWorkItem` | GitHub issue/PR → `RawWorkItem` |
379
+ | `linearToRawWorkItem` | Linear issue → `RawWorkItem` |
380
+ | `manualToRawWorkItem` | Free text → `RawWorkItem` |
381
+
382
+ ### Types
383
+
384
+ | Export | Description |
385
+ | ------------------ | ---------------------------------------------------- |
386
+ | `RawWorkItem` | Generic work item input |
387
+ | `EnrichedSpec` | SEL output with intent, affected systems, unknowns |
388
+ | `ComplexityScore` | CML output with overall score, risk level, reasoning |
389
+ | `SimulationResult` | PESL output with confidence, abort flag, predictions |
390
+ | `ExecutionOutcome` | Outcome data for graph ingestion |
391
+
392
+ ### Effectiveness
393
+
394
+ | Export | Description |
395
+ | ----------------------------- | -------------------------------------------------------------- |
396
+ | `computePersonaEffectiveness` | Per-(persona, system) Laplace-smoothed success rates |
397
+ | `detectBlindSpots` | Find (persona, system) pairs with high failure rates |
398
+ | `recommendPersona` | Recommend personas for an issue given affected system node IDs |
399
+ | `PersonaEffectivenessScore` | Type: smoothed success rate for a (persona, system) pair |
400
+ | `BlindSpot` | Type: (persona, system) pair with consistent failures |
401
+ | `PersonaRecommendation` | Type: persona recommendation with score and coverage stats |
402
+
403
+ ### Specialization
404
+
405
+ | Export | Description |
406
+ | ---------------------------- | ------------------------------------------------------------------------------- |
407
+ | `computeSpecialization` | Compute specialization entries for (persona, system, taskType) tuples |
408
+ | `computeExpertiseLevel` | Classify expertise level from sample size and success rate |
409
+ | `buildSpecializationProfile` | Build a full profile for a persona (strengths, weaknesses, overall level) |
410
+ | `weightedRecommendPersona` | Persona recommendation with specialization multipliers |
411
+ | `decayWeight` | Exponential decay weight for an outcome at a given age |
412
+ | `temporalSuccessRate` | Temporally-weighted success rate from timestamped outcomes |
413
+ | `loadProfiles` | Load persisted specialization profiles from disk |
414
+ | `saveProfiles` | Save specialization profiles to `.harness/specialization-profiles.json` |
415
+ | `refreshProfiles` | Recompute and persist profiles for all personas with outcomes |
416
+ | `SpecializationScore` | Type: composite score (temporal, consistency, volume, composite) |
417
+ | `SpecializationEntry` | Type: single entry for a (persona, system, taskType) bucket |
418
+ | `SpecializationProfile` | Type: full persona profile with strengths, weaknesses, overall level |
419
+ | `WeightedRecommendation` | Type: recommendation with base score, specialization multiplier, weighted score |
420
+ | `ExpertiseLevel` | Type: `'novice' \| 'competent' \| 'proficient' \| 'expert'` |
421
+ | `TaskType` | Type: task type categorization |
422
+ | `TemporalConfig` | Type: temporal decay configuration (half-life, reference time) |
423
+ | `ProfileStore` | Type: persisted store of specialization profiles |
424
+
425
+ ### Analysis
426
+
427
+ | Export | Description |
428
+ | ---------------------------------- | ------------------------------------------ |
429
+ | `AnthropicAnalysisProvider` | Anthropic-backed `AnalysisProvider` |
430
+ | `OpenAICompatibleAnalysisProvider` | OpenAI/local LLM-backed `AnalysisProvider` |
431
+ | `enrich` | SEL enrichment function |
432
+ | `GraphValidator` | Graph-based affected system resolver |
433
+ | `scoreCML` | CML scoring function |
434
+ | `scoreToConcernSignals` | Score → `ConcernSignal[]` conversion |
435
+ | `PeslSimulator` | Tiered simulation facade |
436
+ | `ExecutionOutcomeConnector` | Outcome graph ingestion |
437
+ | `computeHistoricalComplexity` | CML historical dimension |
438
+
439
+ ## License
440
+
441
+ MIT