# @harness-engineering/intelligence 中文文档

规范地址：https://npmcn.com/package/%40harness-engineering/intelligence/

版本：0\.15\.1
npm 元数据更新时间：2026-11-17T01:35:55.476Z
中文译文更新时间：2026-11-17T10:50:15.283Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40harness-engineering/intelligence
原文对照：https://npmcn.com/package/%40harness-engineering/intelligence/?lang=original
项目主页：https://github.com/Intense-Visions/harness-engineering/tree/main/packages/intelligence#readme
源码仓库：https://github.com/Intense-Visions/harness-engineering

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：604 kB，7 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：5 个
- 首次发布：2026-04-19T01:33:09.504Z
- 最新版本发布：2026-11-17T01:35:55.098Z
- 近 30 天下载量：9465（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：42（近 12 个月 42 个）

## 中文简介

用于光谱浓缩、复杂模拟和执行前模拟的情报管道

## 安装

```sh
npm install @harness-engineering/intelligence
```

也可以使用：`pnpm add @harness-engineering/intelligence`、`yarn add @harness-engineering/intelligence`、`bun add @harness-engineering/intelligence`

## README

# @ harness- engineering/ 情报

用于光谱浓缩,复杂建模,以及执行前模拟的情报管道. 增强混合管弦乐手的路由,并用相图后置分析和分层模拟.

## 建筑

```
                         ┌─────────────────────┐
                         │    Work Item Input   │
                         │  Roadmap · JIRA ·    │
                         │  GitHub · Linear ·   │
                         │  Manual text         │
                         └──────────┬──────────┘
                                    ▼
                         ┌─────────────────────┐
                         │      Adapters        │
                         │  toRawWorkItem()     │
                         │  jiraToRawWorkItem() │
                         │  githubToRawWorkItem │
                         │  linearToRawWorkItem │
                         │  manualToRawWorkItem │
                         └──────────┬──────────┘
                                    ▼
┌────────────────────────────────────────────────────────────────┐
│                    IntelligencePipeline                        │
│                                                                │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  SEL — Spec Enrichment Layer                             │  │
│  │  LLM analysis + graph-validated system discovery         │  │
│  │  → EnrichedSpec (intent, affected systems, unknowns)     │  │
│  └──────────────────────┬───────────────────────────────────┘  │
│                         ▼                                      │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  CML — Complexity Modeling Layer                         │  │
│  │  Structural (graph blast radius) + Semantic (ambiguity)  │  │
│  │  + Historical (past outcome failure rate)                │  │
│  │  → ComplexityScore → ConcernSignal[]                     │  │
│  └──────────────────────┬───────────────────────────────────┘  │
│                         ▼                                      │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  PESL — Pre-Execution Simulation Layer                   │  │
│  │  Graph-only checks (quick-fix) or full LLM simulation    │  │
│  │  (guided-change) with abort on low confidence            │  │
│  │  → SimulationResult (confidence, abort flag)             │  │
│  └──────────────────────────────────────────────────────────┘  │
│                                                                │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  Outcome Recording                                       │  │
│  │  ExecutionOutcomeConnector → graph nodes + edges         │  │
│  │  Feeds back into CML historical dimension                │  │
│  └──────────────────────────────────────────────────────────┘  │
└────────────────────────────────────────────────────────────────┘
```

## 快速启动

```ts
import {
  IntelligencePipeline,
  AnthropicAnalysisProvider,
  toRawWorkItem,
} from '@harness-engineering/intelligence';
import { GraphStore } from '@harness-engineering/graph';

// 1. Create the pipeline
const provider = new AnthropicAnalysisProvider({
  apiKey: process.env.ANTHROPIC_API_KEY!,
});
const store = new GraphStore();
await store.load('.harness/graph');

const pipeline = new IntelligencePipeline(provider, store);

// 2. Preprocess an issue (SEL → CML → signals)
const result = await pipeline.preprocessIssue(issue, scopeTier, escalationConfig);
// result.spec    — EnrichedSpec with intent, affected systems, unknowns
// result.score   — ComplexityScore with overall 0-1, risk level, reasoning
// result.signals — ConcernSignal[] for routeIssue()

// 3. Simulate before dispatch (PESL)
if (result.spec && result.score) {
  const simulation = await pipeline.simulate(result.spec, result.score, scopeTier);
  // simulation.abort — true if confidence too low
  // simulation.predictedFailures — what might go wrong
  // simulation.testGaps — missing test coverage
}

// 4. Record execution outcomes (feedback loop)
await pipeline.recordOutcome({
  issueId: 'CORE-42',
  result: 'success',
  retryCount: 0,
  failureReasons: [],
  durationMs: 45000,
  affectedSystemNodeIds: ['node-abc'],
});
```

## 等级行为

管道根据管弦乐手的视野级调整其行为:

| 范围 | 自己 | CML 数据 | 萨尔瓦多 | 路线 |
| --- | --- | --- | --- | --- |
| `autoExecute` (快速修复,诊断) | 跳过 | 跳过 | 仅图 | 总是在本地发送 |
| `signalGated` (修改指南) | 运行 | 运行 | 完全 LLM 模拟 | 无关切信号的发送 |
| `alwaysHuman` (全面探索) | 运行 | 跳过 | 跳过 | 总是升级( 浓缩为上下文) |

## 层

### SEL — 光谱浓缩层

将原始工作项目转换为结构化 `EnrichedSpec` 对象通过 LLM 分析和图表验证.

```ts
import { enrich, GraphValidator } from '@harness-engineering/intelligence';

const validator = new GraphValidator(store);
const spec = await enrich(rawWorkItem, provider, validator);
// spec.intent — what the task is trying to accomplish
// spec.affectedSystems — graph-validated system references
// spec.unknowns — explicitly identified knowledge gaps
// spec.ambiguities — areas needing clarification
```

### CML — 复杂模拟层

三个方面的任务复杂性:

-   **结构** - 图像爆炸半径通过 `CascadeSimulator`,正态为 0-1
-   **语义** ——来自SEL浓缩的不明、模糊和风险信号
-   **历史** ——同一受影响系统过去执行结果的平稳故障率

```ts
import { scoreCML, scoreToConcernSignals } from '@harness-engineering/intelligence';

const score = scoreCML(enrichedSpec, store);
// score.overall — 0-1 weighted composite
// score.riskLevel — 'low' | 'medium' | 'high' | 'critical'
// score.recommendedRoute — 'local' | 'human' | 'simulation-required'

const signals = scoreToConcernSignals(score);
// signals fed into existing routeIssue() for signalGated tiers
```

### PESL — 执行前模拟层

在写入代码前模拟执行 。 按成本划分:

-   **仅图** (快速固定/诊断) - `CascadeSimulator` 爆炸半径+测试漏洞检测. 快 (<2s),无 LLM 成本.
-   **完全模拟** (指向变化)——LLM辅助计划扩展,故障注入,测试投影. 与图表基线合并.

```ts
import { PeslSimulator } from '@harness-engineering/intelligence';

const simulator = new PeslSimulator(provider, store);
const result = await simulator.simulate(spec, score, scopeTier);

if (result.abort) {
  // Confidence too low — escalate to human instead of dispatching
  console.log('Predicted failures:', result.predictedFailures);
  console.log('Test gaps:', result.testGaps);
}
```

### 适配器

将外部数据转换为纯映射函数 `RawWorkItem`数字 :

```ts
import {
  toRawWorkItem, // Roadmap Issue → RawWorkItem
  jiraToRawWorkItem, // JIRA issue → RawWorkItem
  githubToRawWorkItem, // GitHub issue/PR → RawWorkItem
  linearToRawWorkItem, // Linear issue → RawWorkItem
  manualToRawWorkItem, // Free text → RawWorkItem
} from '@harness-engineering/intelligence';
```

每个适配器接受前置数据对象并生成一个 `RawWorkItem`。不包括 API 客户端 — 适配器是纯函数 .

### 有效性——代理性能回顾

属性分析 `execution_outcome` 在图中的节点可以对每个人的准确度进行分分,检测出盲点,并推荐哪个人物将新问题引导到.

```ts
import {
  computePersonaEffectiveness,
  detectBlindSpots,
  recommendPersona,
} from '@harness-engineering/intelligence';

// Per-(persona, system) success rates with Laplace smoothing
const scores = computePersonaEffectiveness(store, { persona: 'backend-dev' });
// scores[0].successRate — smoothed success rate in [0, 1]
// scores[0].sampleSize  — total observations

// Blind spots: (persona, system) pairs with high failure rates
const spots = detectBlindSpots(store, { minFailures: 2, minFailureRate: 0.5 });
// spots[0].failureRate — raw failure rate
// spots[0].failures    — absolute failure count

// Recommend personas for an issue given its affected systems
const recs = recommendPersona(store, {
  systemNodeIds: ['module-auth', 'module-db'],
  candidatePersonas: ['backend-dev', 'fullstack'],
  minSamples: 3,
});
// recs[0].persona — best candidate
// recs[0].score   — mean smoothed success rate across requested systems
```

### 专门性——长期代理专家追踪

以时间衰变、任务类型分类、一致性评分、专门知识水平和持续配置存储来扩大效力。 最近的结果通过指数衰减而比起旧的结果更重地加权.

```ts
import {
  computeSpecialization,
  computeExpertiseLevel,
  buildSpecializationProfile,
  weightedRecommendPersona,
  decayWeight,
  temporalSuccessRate,
  loadProfiles,
  saveProfiles,
  refreshProfiles,
} from '@harness-engineering/intelligence';

// Compute specialization entries for (persona, system, taskType) tuples
const entries = computeSpecialization(store, {
  persona: 'backend-dev',
  taskType: 'bug-fix',
  temporal: { halfLifeDays: 30 },
});
// entries[0].score.composite         — weighted combination of temporal, consistency, volume
// entries[0].expertiseLevel          — 'novice' | 'competent' | 'proficient' | 'expert'

// Classify expertise from raw numbers
const level = computeExpertiseLevel(25, 0.8); // → 'proficient'

// Build a full profile for a persona (strengths, weaknesses, overall level)
const profile = buildSpecializationProfile(store, 'backend-dev', {
  temporal: { halfLifeDays: 30 },
});
// profile.strengths   — top 3 entries by composite score
// profile.weaknesses  — entries with temporal success rate < 0.5
// profile.overallLevel — median expertise across all entries

// Weighted recommendation incorporating specialization multipliers
const weighted = weightedRecommendPersona(store, {
  systemNodeIds: ['module-auth'],
  taskType: 'bug-fix',
});
// weighted[0].weightedScore — baseScore * specializationMultiplier

// Temporal decay helpers
const weight = decayWeight(15, 30); // weight at 15 days with 30-day half-life
const rate = temporalSuccessRate([{ result: 'success', timestamp: '2026-04-01T00:00:00Z' }], {
  halfLifeDays: 30,
});

// Persist profiles to .harness/specialization-profiles.json
const profiles = loadProfiles('/path/to/project');
saveProfiles('/path/to/project', profiles);

// Recompute and persist profiles for all personas with outcomes
const refreshed = refreshProfiles('/path/to/project', store);
```

### 结果记录

执行结果反馈到图表中, 用于未来的 CML 评分 :

```ts
import { ExecutionOutcomeConnector } from '@harness-engineering/intelligence';

const connector = new ExecutionOutcomeConnector(store);
await connector.ingest({
  issueId: 'CORE-42',
  result: 'failure',
  retryCount: 2,
  failureReasons: ['Migration script failed'],
  durationMs: 120000,
  affectedSystemNodeIds: ['module-auth'],
});
// Creates execution_outcome node with outcome_of edges to affected systems
// Future CML scoring queries these outcomes for historical failure rates
```

## 整形器整合

情报管道在两点上融入了管弦乐手的滴答循环:

1.  **预线** (单位:千美元) `asyncTick`(b) —— `preprocessIssue()` 运行 SEL + CML,生成反馈到 `routeIssue()`用于 `alwaysHuman` 中,浓缩光谱附于 `EscalateEffect` 作为人类评论员的背景.
    
2.  **后路线** (单位:千美元) `asyncTick`(b) —— `simulate()` 管理地方发行的PESL。 如果模拟建议中止( I)`confidence < 0.3`),将调度转换为 `EscalateEffect` 换句话说.
    
3.  **执行后** (单位:千美元) `emitWorkerExit`(b) —— `recordOutcome()` 将执行结果输入到图中,将CML的历史维度反馈给未来的评分.
    

### 盘子

仪表板的 **请注意** 页面显示升级互动。 当情报管道启用时,升级包括内容更丰富:

-   **丰富光谱摘要** ——意向,受影响系统,未知数
-   **关注信号** 导致升级的原因(高度复杂、爆炸半径大、模糊不清)
-   **PESL 流产原因** ——预测的故障和测试缺口(当模拟建议中止时)

这种背景有助于人类审查人员就升级的工作项目做出更快,更知情的决定.

## 配置

管道使用与管弦乐手的代理后端——Anthropic API,OpenAI API,或本地LLM(Ollama,LM Studio等)相同的LLM连接:

```yaml
intelligence:
  enabled: true
```

不需要单独的 API 密钥 。 管道的提供者来自现有的代理人配置:

| 代理后端 | 情报用途 |
| --- | --- |
| `anthropic` 编号 : `claude` | Anthropic 信件 API( 相同的密钥) |
| `openai` | OpenAI Chat API( 相同的密钥) |
| `localBackend: openai-compatible` | 本地端点( 相同的 URL) |

覆盖每层模型 :

```yaml
intelligence:
  enabled: true
  models:
    sel: llama3.2 # fast model for enrichment
    pesl: deepseek-r1 # reasoning model for simulation
```

对于思维模型(Quen3, Deepseek-R1),对结构化输出的禁用推理:

```yaml
intelligence:
  enabled: true
  promptSuffix: '/no_think' # Qwen3 — disable thinking for structured output
  jsonMode: false # Qwen3 hangs with Ollama's JSON grammar constraint
  requestTimeoutMs: 90000 # fail fast instead of waiting 10 min
  failureCacheTtlMs: 300000 # don't retry failed analyses for 5 min
```

何时 `enabled: false` (默认),管道完全跳过. 见 [智能管道指南](https://npmcn.com/package/docs/guides/intelligence-pipeline.md) 用于完整配置参考.

## 依赖关系

```
@harness-engineering/types  → shared type definitions
@harness-engineering/graph  → GraphStore, CascadeSimulator, node/edge types
@anthropic-ai/sdk           → LLM calls via AnalysisProvider
openai                      → OpenAI-compatible analysis provider
zod                         → response schema validation
```

情报包 **无依赖** 打开 `@harness-engineering/orchestrator`。依赖性流动的方式如下: `orchestrator → intelligence → graph → types`。 。 。 .

## API 参考

### 管道

| 导出 | 说明 |
| --- | --- |
| `IntelligencePipeline` | SEL、CML、PESL的主要管道类别 |
| `PreprocessResult` | 返回类型 `preprocessIssue()` |

### 适配器

| 导出 | 说明 |
| --- | --- |
| `toRawWorkItem` | 路线图 `Issue` → `RawWorkItem` |
| `jiraToRawWorkItem` | JIRA问题 `RawWorkItem` |
| `githubToRawWorkItem` | GitHub 问题/PR + `RawWorkItem` |
| `linearToRawWorkItem` | 线性问题 `RawWorkItem` |
| `manualToRawWorkItem` | 自由文本 − `RawWorkItem` |

### 类型

| 导出 | 说明 |
| --- | --- |
| `RawWorkItem` | 一般工作项目投入 |
| `EnrichedSpec` | SEL 输出意图, 受影响的系统, 未知 |
| `ComplexityScore` | CML 输出总分, 风险水平, 推理 |
| `SimulationResult` | PESL 输出有自信, 中止旗, 预测 |
| `ExecutionOutcome` | 图摄入的结果数据 |

### 有效性

| 导出 | 说明 |
| --- | --- |
| `computePersonaEffectiveness` | 人均(人,系统) 平地平地成功率 |
| `detectBlindSpots` | 查找故障率高的对( persona, system) |
| `recommendPersona` | 给某个问题提供个人建议 |
| `PersonaEffectivenessScore` | 类型:对一对(人,系统)的平滑成功率 |
| `BlindSpot` | 类型 :( persona, system) 有相容失败的配对 |
| `PersonaRecommendation` | 类型:有分数和覆盖面的推荐人 |

### 专业

| 导出 | 说明 |
| --- | --- |
| `computeSpecialization` | 计算( persona, system, taskType) tuple 的专业条目 |
| `computeExpertiseLevel` | 从样本规模和成功率对专门知识级别进行分类 |
| `buildSpecializationProfile` | 构建完整的人物简介a(实力、弱点、总体水平) |
| `weightedRecommendPersona` | 专门化乘数建议 |
| `decayWeight` | 特定年龄结果的指数衰减加权数 |
| `temporalSuccessRate` | 按时间标记的结果计算的临时加权成功率 |
| `loadProfiles` | 从磁盘装入持续的专业配置 |
| `saveProfiles` | 将专业配置保存到 `.harness/specialization-profiles.json` |
| `refreshProfiles` | 调整和坚持所有个人的简介,使其符合成果 |
| `SpecializationScore` | 类型:综合分数(时间,一致性,体积,复合) |
| `SpecializationEntry` | 类型: 单项( persona, system, taskType) 桶 |
| `SpecializationProfile` | 类型:具有长处、弱点的完整人物简介,总体水平 |
| `WeightedRecommendation` | 类型:有基准分数、专业乘数、加权分数的推荐 |
| `ExpertiseLevel` | 类型 : `'novice' | 'competent' | 'proficient' | 'expert'` |
| `TaskType` | 类型:任务类型分类 |
| `TemporalConfig` | 类型:时间衰变配置(半衰期,参考时间) |
| `ProfileStore` | 类型:长期保存专业简介 |

### 分析

| 导出 | 说明 |
| --- | --- |
| `AnthropicAnalysisProvider` | 反动支持 `AnalysisProvider` |
| `OpenAICompatibleAnalysisProvider` | OpenAI/ 本地 LLM 支持 `AnalysisProvider` |
| `enrich` | SEL 浓缩功能 |
| `GraphValidator` | 基于图表的系统解析器 |
| `scoreCML` | CML 评分函数 |
| `scoreToConcernSignals` | 得分 + `ConcernSignal[]` 转换 |
| `PeslSimulator` | 分层模拟外观 |
| `ExecutionOutcomeConnector` | 结果图摄入量 |
| `computeHistoricalComplexity` | CML 历史维度 |

## 许可证

麻省理工学院

## 常见问题

### @harness-engineering/intelligence 是什么？

用于光谱浓缩、复杂模拟和执行前模拟的情报管道

### 如何安装 @harness-engineering/intelligence？

在项目目录运行 npm install @harness-engineering/intelligence，或使用 pnpm add / yarn add / bun add。

### @harness-engineering/intelligence 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @harness-engineering/intelligence 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @harness-engineering/intelligence 可以商用吗？

@harness-engineering/intelligence 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @harness-engineering/intelligence 的下载量有多少？

根据 npm 官方下载统计，@harness-engineering/intelligence 在 2026/10/17 – 2026/11/15 这 30 天内被下载 9,465 次，日均约 316 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @harness-engineering/intelligence 还在维护吗？

最新版本 0\.15\.1 发布于 2026/11/17（今天）；至今共发布 42 个版本，其中过去 12 个月发布了 42 个；首次发布于 2026/04/19。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

