@harness-engineering/core

中文文档
0.57.0发布于 2026/11/17MITTypeScriptESM + CJS构建来源已验证近 30 天下载 9556

Core library for Harness Engineering toolkit

原始使用文档
文档目录10 节
  1. Installation
  2. Modules
  3. Modules Overview
  4. Validation Module
  5. Context Engineering Module
  6. Architectural Constraints Module
  7. Entropy Management Module
  8. Error Handling
  9. Development
  10. License

@harness-engineering/core

Core library for Harness Engineering toolkit - provides runtime APIs for context engineering, architectural constraints, agent feedback, and entropy management.

Installation

pnpm add @harness-engineering/core

Modules

Modules Overview

ModuleDescription
validationCross-cutting validation for file structure, configuration, and commit messages
contextAGENTS.md knowledge maps, documentation coverage analysis, token budgets, and context filtering
constraintsArchitectural layer enforcement, circular dependency detection, and boundary validation
entropyDocumentation drift, dead code detection, pattern violations, and auto-fix
architectureMetric collection via multiple collectors (circular deps, layer violations, complexity, coupling, forbidden imports, module size, dependency depth)
reviewCode review pipeline with mechanical checks, fan-out agents (compliance, bugs, security, architecture), and deduplication
feedbackAgent feedback loops with self-review, peer review, telemetry, logging, and action tracking
performanceBenchmarking, baseline management, regression detection, and critical path analysis
securitySecurity scanning with secret detection, injection detection, XSS, crypto, path traversal, and stack-specific rules (Node.js, Express, React, Go)
ciCI/CD check orchestration for running automated checks in continuous integration pipelines
code-navCode navigation: file parsing, symbol extraction/outlines, symbol search, and code range unfolding by language
stateState persistence including learnings, failures, handoffs, gates, streams, sessions, and event logging
roadmapRoadmap parsing, serialization, and synchronization with codebase and issue tracking
pipelineSkill pipeline orchestration for sequential and multi-turn skill execution
workflowWorkflow execution engine for structured multi-step workflows
interactionTypes and schemas for agent-to-human interactions (questions, confirmations, transitions)
blueprintHTML documentation generation from module data using EJS templates
pricingLiteLLM-based model pricing lookup, disk cache with 24h TTL, bundled fallback, and microdollar cost calculation
sharedError types, Result pattern for error handling, file system utilities, and language parsers

Validation Module

Cross-cutting validation utilities used by all other modules.

File Structure Validation

Verify project follows file structure conventions:

import { validateFileStructure, type Convention } from '@harness-engineering/core';

const conventions: Convention[] = [
  {
    pattern: 'README.md',
    required: true,
    description: 'Project README',
    examples: ['README.md'],
  },
  {
    pattern: 'AGENTS.md',
    required: true,
    description: 'Knowledge map',
    examples: ['AGENTS.md'],
  },
];

const result = await validateFileStructure('./my-project', conventions);

if (result.ok) {
  console.log('Valid:', result.value.valid);
  console.log('Conformance:', result.value.conformance + '%');
  console.log('Missing:', result.value.missing);
} else {
  console.error('Error:', result.error.message);
}

Config Validation

Type-safe configuration validation with Zod:

import { validateConfig } from '@harness-engineering/core';
import { z } from 'zod';

const ConfigSchema = z.object({
  version: z.number(),
  layers: z.array(
    z.object({
      name: z.string(),
      allowedDependencies: z.array(z.string()),
    })
  ),
});

const result = validateConfig(userConfig, ConfigSchema);

if (result.ok) {
  // TypeScript knows result.value matches ConfigSchema
  console.log('Config version:', result.value.version);
} else {
  console.error('Validation failed:', result.error.message);
  console.error('Suggestions:', result.error.suggestions);
}

Commit Message Validation

Validate commit messages follow conventional format:

import { validateCommitMessage } from '@harness-engineering/core';

const result = validateCommitMessage('feat(core): add validation module', 'conventional');

if (result.ok) {
  if (result.value.valid) {
    console.log('Type:', result.value.type); // 'feat'
    console.log('Scope:', result.value.scope); // 'core'
    console.log('Breaking:', result.value.breaking); // false
  } else {
    console.log('Issues:', result.value.issues);
  }
}

Context Engineering Module

Tools for validating and generating AGENTS.md knowledge maps.

AGENTS.md Validation

Validate the structure and links in an AGENTS.md file:

import { validateAgentsMap } from '@harness-engineering/core';

const result = await validateAgentsMap('./AGENTS.md');

if (result.ok) {
  console.log('Valid:', result.value.valid);
  console.log('Sections:', result.value.sections.length);
  console.log('Broken links:', result.value.brokenLinks.length);
  console.log('Missing sections:', result.value.missingSections);
}

Documentation Coverage

Check how well your code is documented:

import { checkDocCoverage } from '@harness-engineering/core';

const result = await checkDocCoverage('src', {
  docsDir: './docs',
  sourceDir: './src',
  excludePatterns: ['**/*.test.ts'],
});

if (result.ok) {
  console.log('Coverage:', result.value.coveragePercentage + '%');
  console.log('Gaps:', result.value.gaps);
}

Knowledge Map Integrity

Verify all links in your AGENTS.md point to existing files:

import { validateKnowledgeMap } from '@harness-engineering/core';

const result = await validateKnowledgeMap('./');

if (result.ok) {
  console.log('Integrity:', result.value.integrity + '%');
  for (const broken of result.value.brokenLinks) {
    console.log(`Broken: ${broken.path} - ${broken.suggestion}`);
  }
}

AGENTS.md Generation

Auto-generate an AGENTS.md from your project structure:

import { generateAgentsMap } from '@harness-engineering/core';

const result = await generateAgentsMap({
  rootDir: './',
  includePaths: ['**/*.md', 'src/**/*.ts'],
  excludePaths: ['node_modules/**'],
  sections: [{ name: 'API Docs', pattern: 'docs/api/**/*.md', description: 'API documentation' }],
});

if (result.ok) {
  console.log(result.value); // Generated markdown content
}

Architectural Constraints Module

Tools for enforcing layered architecture and detecting dependency issues.

Layer Validation

Define and validate architectural layers:

import { validateDependencies, defineLayer, TypeScriptParser } from '@harness-engineering/core';

const result = await validateDependencies({
  layers: [
    defineLayer('domain', ['src/domain/**'], []),
    defineLayer('services', ['src/services/**'], ['domain']),
    defineLayer('api', ['src/api/**'], ['services', 'domain']),
  ],
  rootDir: './src',
  parser: new TypeScriptParser(),
});

if (result.ok && !result.value.valid) {
  for (const violation of result.value.violations) {
    console.log(`${violation.file}:${violation.line} - ${violation.reason}`);
    console.log(`  ${violation.fromLayer} cannot import from ${violation.toLayer}`);
  }
}

Circular Dependency Detection

Find cycles in your dependency graph:

import { detectCircularDepsInFiles, TypeScriptParser } from '@harness-engineering/core';

const result = await detectCircularDepsInFiles(
  ['src/a.ts', 'src/b.ts', 'src/c.ts'],
  new TypeScriptParser()
);

if (result.ok && result.value.hasCycles) {
  for (const cycle of result.value.cycles) {
    console.log('Cycle found:', cycle.cycle.join(' -> '));
  }
}

Boundary Validation

Validate data at module boundaries:

import { z } from 'zod';
import { createBoundaryValidator } from '@harness-engineering/core';

const UserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(1),
});

const validator = createBoundaryValidator(UserSchema, 'UserService.createUser');

const result = validator.parse(requestBody);
if (result.ok) {
  // result.value is typed as { email: string; name: string }
  createUser(result.value);
} else {
  console.error(result.error.suggestions);
}

Entropy Management Module

Detect and fix codebase entropy: documentation drift, dead code, and pattern violations.

Quick Analysis

import { EntropyAnalyzer } from '@harness-engineering/core';

const analyzer = new EntropyAnalyzer({
  rootDir: './src',
  analyze: {
    drift: true,
    deadCode: true,
    patterns: {
      patterns: [
        {
          name: 'max-exports',
          description: 'Limit exports per file',
          severity: 'warning',
          files: ['**/*.ts'],
          rule: { type: 'max-exports', count: 10 },
        },
      ],
    },
  },
  include: ['**/*.ts'],
  docPaths: ['docs/**/*.md'],
});

const result = await analyzer.analyze();

if (result.ok) {
  console.log(`Found ${result.value.summary.totalIssues} issues`);
  console.log(`${result.value.summary.fixableCount} can be auto-fixed`);
}

Full Analyzer Workflow

import { EntropyAnalyzer, createFixes, applyFixes } from '@harness-engineering/core';

const analyzer = new EntropyAnalyzer({
  rootDir: './src',
  analyze: { drift: true, deadCode: true },
});

// Run analysis
const report = await analyzer.analyze();
if (!report.ok) throw new Error(report.error.message);

// Get suggestions for manual fixes
const suggestions = analyzer.getSuggestions();
console.log(`${suggestions.suggestions.length} suggestions generated`);

// Auto-fix safe issues
if (report.value.deadCode) {
  const fixes = createFixes(report.value.deadCode, {
    fixTypes: ['unused-imports', 'dead-files'],
    dryRun: true, // Preview first
  });

  console.log(
    'Preview:',
    fixes.map((f) => f.description)
  );

  // Apply for real
  await applyFixes(fixes, { dryRun: false, createBackup: true });
}

Error Handling

All APIs use the Result<T, E> pattern for type-safe error handling:

import { type Result, Ok, Err } from '@harness-engineering/core';

const result: Result<string, Error> = Ok('success');

if (result.ok) {
  console.log(result.value); // TypeScript knows this is string
} else {
  console.error(result.error); // TypeScript knows this is Error
}

Development

# Install dependencies
pnpm install

# Run tests
pnpm test

# Run tests with coverage
pnpm test:coverage

# Type checking
pnpm typecheck

# Build
pnpm build

# Lint
pnpm lint

License

MIT

版本与发布记录

@harness-engineering/core 共发布 82 个版本,首次发布于 2026/03/17;过去 12 个月发布了 82 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.57.0latest2026/11/17今天
0.56.02026/11/125 天前
0.55.02026/10/2027 天前
0.54.12026/09/241 个月前
0.54.02026/09/181 个月前
0.53.02026/09/172 个月前

关于 @harness-engineering/core 的常见问题

@harness-engineering/core 是什么?

Core library for Harness Engineering toolkit

如何安装 @harness-engineering/core?

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

@harness-engineering/core 支持 TypeScript 吗?

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

@harness-engineering/core 支持 ESM 还是 CommonJS?

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

@harness-engineering/core 可以商用吗?

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

@harness-engineering/core 的下载量有多少?

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

@harness-engineering/core 还在维护吗?

最新版本 0.57.0 发布于 2026/11/17(今天);至今共发布 82 个版本,其中过去 12 个月发布了 82 个;首次发布于 2026/03/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。