# 齐衡 QIHENG — Design Integrity Control Plane

Version: `1.1.17`

[中文](README.zh-CN.md) · [核心流程与术语](TERMINOLOGY.md) · [Commercial capability catalog](CAPABILITIES.md) · [Enterprise adoption](ENTERPRISE.md) · [Security](SECURITY.md) · [Support](SUPPORT.md) · [Brand standard](BRAND.md) · [Operating contract](INSTRUCTION.md) · [Ontology](docs/ONTOLOGY.md) · [FAQ](docs/FAQ.md) · [Changelog](CHANGELOG.md)

> **在璇玑玉衡，以齐七政。**
> *Zài xuán jī yù héng，yǐ qí qī zhèng。*

**Use evidence as the measure; align design, implementation, validation, and admission.**

The Chinese brand **齐衡** is inspired by the *Canon of Shun* in the
*Book of Documents*. **齐** means to align or calibrate; **衡** means to observe,
measure, and balance. See the canonical [brand standard](BRAND.md).

齐衡 QIHENG is a portable design integrity control plane for proving that code still matches
authoritative design intent. It supports Codex, Claude Code, OpenCode, MiMo Code,
BitFun, and generic Claude Code-compatible Coding Agents, with OpenSpec, design
documents, API contracts, schemas, product requirements, or Gherkin features
as design sources.

## What makes it different

- **An executable Harness, not a checklist.** A cryptographic Candidate
  Passport, typed gate graph, dependency closure, explicit applicability, and
  content-addressed evidence compute delivery readiness.
- **A shared ontology, not isolated Agent summaries.** Requirements, scenarios,
  implementation units, gaps, repairs, validations, and evidence form one
  traceable semantic graph.
- **Governed mutations.** Role-bounded Actions and action-specific patches are
  recorded in an append-only, SHA-256-linked Ledger before reconciliation.
- **Evidence that fails closed.** Source, implementation, and evidence artifacts
  are content-addressed; changed or missing bytes block PASS.
- **Validation causality.** A green result binds the exact DesignSource and
  ImplementationUnit hashes it consumed, so an old log cannot approve new code.
- **Portable final proof.** Reports and Attestations bind the terminal decision
  to the snapshot revision, Ledger, artifacts, invariants, and residual risks.
- **Executive visibility without evidence loss.** The Assurance Cockpit shows
  one decision, coverage, Digital Thread, risk blockers, and drill-down IDs
  derived directly from machine state.

The differentiator is therefore not the number of Agents. It is the governed,
inspectable evidence chain between design, implementation, validation, and the
final decision.

QIHENG groups roles by evidence responsibility, not by headcount:

- **Lens** establishes authority, obligations, semantic conflicts, and impact.
- **Forge** inspects, repairs, and validates source-backed gaps.
- **Tribunal** challenges high-risk claims, audits proof freshness, and makes
  candidate-bound consistency and admission decisions.

The orchestrator assembles the smallest applicable panel for the current risk.
Adding more Agents without a distinct hypothesis, artifact, consumer, and
decision right does not add assurance.

## Three-minute quick start

Requires Node.js 20 or later.

```text
npx dic-workflow-kit@1.1.17 install
```

The published package names remain `dic-workflow-kit` and
`@tonyclaw/dic-workflow-kit` for compatibility. A global install exposes the
preferred `qiheng` command as well as the legacy `dic-workflow-kit` command.
The default `full` capability pack installs all 21 Skills and 19 Subagents.
Enterprise teams can inspect or select dependency-closed capability packs:

```text
qiheng catalog
qiheng install --host coding-agent --pack design
```

Restart the Coding Agent in the target repository, then use the product entry:

```text
Use $qiheng to process the current Spec or Change in audit mode.
```

The equivalent CLI bootstrap is `qiheng start --root . --mode audit`. Use
`--change <id>` or `--spec <path>` when the entry is known, then use
`qiheng status`, `qiheng next`, or `qiheng resume`. The entry delegates to the
existing review orchestrator and Harness; users no longer need to memorize
their internal names.

Start with `reports/final-consistency-report.md`, `reports/FINAL_RESULT.json`,
and `reports/ontology-report.md`. A valid terminal result is `PASS`, `PARTIAL`,
`BLOCKED`, or `FAIL`; green tests alone do not imply PASS.

After the project profile exists, operate the executable Harness:

```text
qiheng harness-init --root .
qiheng harness-check --root . --json
qiheng harness-report --root .
```

Candidate files and gate evidence use bounded concurrent hashing and are
deduplicated by path within one verification run. Concurrency defaults to `8`
and can be tuned from `1` to `32` with `QIHENG_IO_CONCURRENCY` without changing
Candidate or evidence hash semantics.

The Harness computes runnable batches from gate dependencies. Read-only gates
are exposed as `PARALLEL_READ`; any batch containing source-repair authority is
isolated as `EXCLUSIVE_WRITE`. `qiheng next --json` returns `executionMode`,
`runnableGates`, and `remainingBatches`. Entry initialization, resume, and gate
recording share a repository control lock so concurrent processes cannot lose
Harness updates.

Successful gates are stored under `reports/.qiheng-cache/gates/`. A cache key
binds the complete gate definition, profile, and the input domains actually
consumed by that gate. An implementation-only Candidate change can therefore
reuse authority, cross-Spec, and Spec gates when design-source bytes are
unchanged, while implementation, test, and downstream admission gates remain
invalidated. Reuse still rereads evidence, recomputes SHA-256 hashes, and
verifies Subagent handoffs. Cross-Candidate results record
`reuseMode: UNCHANGED_INPUTS` and their source Candidate hash.

The generated `reports/harness-report.md` is the executive-facing Assurance
Cockpit: one decision, a cryptographic candidate passport, assurance coverage,
a visual design-to-delivery Digital Thread, gate decisions, and exact blockers.

## Documentation

| Document | Purpose |
| --- | --- |
| [Commercial capability catalog](CAPABILITIES.md) | Product boundary, capability packs, component responsibilities, installation controls, and acceptance baseline |
| [Operating contract](INSTRUCTION.md) | Full workflow, evidence, handoff, and terminal-state rules |
| [Ontology model](docs/ONTOLOGY.md) | Objects, links, Actions, Ledger, gates, and Attestations |
| [Delivery Assurance Harness](docs/HARNESS.md) | Candidate passport, executable gate graph, Digital Thread, evidence recording, and executive cockpit |
| [FAQ](docs/FAQ.md) | Multi-Agent communication, mounted knowledge, BDD, and product questions |
| [Enterprise adoption](ENTERPRISE.md) | Four-plane architecture, production checklist, pilot metrics, and 90-day rollout |
| [Security policy](SECURITY.md) | Trust boundaries, vulnerability reporting, threat model, and production baseline |
| [Support policy](SUPPORT.md) | Support tiers, compatibility, diagnostics, and upgrade boundaries |
| [Proprietary notice](NOTICE.md) | Boundary between public distribution and commercial production rights |
| [Release guide](docs/RELEASING.md) | Maintainer-only dual npm release procedure |
| [Changelog](CHANGELOG.md) | Version history |

## Enterprise adoption

The public package supports product evaluation and controlled pilots. Production
deployment also requires enterprise identity, permissions, approvals, key
management, immutable evidence storage, and a written commercial agreement.
Start with the [enterprise adoption guide](ENTERPRISE.md), then run:

```text
npm run release:check
```

A commercial production release must additionally pass
`npm run commercial:check`. The proprietary package currently remains
`UNLICENSED`, so that check intentionally blocks until legal approval is
recorded in the package metadata. A successful technical release is not a grant
of production rights.

QIHENG deliberately does not recreate enterprise identity, approval, signing,
compliance, or immutable-storage platforms. Repository-specific external
decisions can be attached as admission evidence; the enterprise system remains
their source of truth.

## Install with npm

Both `dic-workflow-kit` and `@tonyclaw/dic-workflow-kit` publish the same version
and runtime payload. The package contains all 21 Skills and all nineteen
Subagents and installs them with host-native directory layouts for Codex,
Claude Code, OpenCode, MiMo Code, BitFun, and generic Coding Agents that use
Claude Code-compatible files.

Codex remains the default, so the original command is backward compatible:

```text
npx dic-workflow-kit@1.1.17 install
```

Select another host explicitly:

```text
npx dic-workflow-kit@1.1.17 install --host claude-code
npx dic-workflow-kit@1.1.17 install --host opencode
npx dic-workflow-kit@1.1.17 install --host mimo-code
npx dic-workflow-kit@1.1.17 install --host bitfun
npx dic-workflow-kit@1.1.17 install --host coding-agent --dry-run
```

User scope is the default. To install into the current repository instead, use `--scope project`:

```text
npx dic-workflow-kit@1.1.17 install --host claude-code --scope project
npx dic-workflow-kit@1.1.17 install --host opencode --scope project
npx dic-workflow-kit@1.1.17 install --host mimo-code --scope project
npx dic-workflow-kit@1.1.17 install --host bitfun --scope project
npx dic-workflow-kit@1.1.17 install --host coding-agent --scope project
```

The host mappings are:

| Host | User scope | Project scope |
| --- | --- | --- |
| Codex | `~/.agents/plugins/plugins/dic-workflow-kit` plus marketplace registration | Not applicable to this plugin installer |
| Claude Code | `~/.claude/{skills,agents}` | `.claude/{skills,agents}` |
| OpenCode | `~/.config/opencode/{skills,agents}` | `.opencode/{skills,agents}` |
| MiMo Code | platform config root under `mimocode/{skills,agents}` | `.mimocode/{skills,agents}` |
| BitFun | platform-native BitFun data/config roots | `.bitfun/{skills,agents}` |
| Generic Coding Agent | discovers common CodeAgent roots, defaulting to `~/.codeagent/{skills,agents}` | discovers `.codeagent`, `.code-agent`, or `.coding-agent` |

On Windows, MiMo Code's user root resolves to `%LOCALAPPDATA%\mimocode`; `MIMOCODE_HOME` and `XDG_CONFIG_HOME` are honored where applicable. BitFun user Skills resolve to the platform data directory (`BitFun/skills`) and its Subagents resolve to the BitFun config root (`bitfun/agents`); project installation uses BitFun's native `.bitfun` directory. The generic Coding Agent adapter reuses Claude Code's Skill and Subagent metadata contract. It checks `CODING_AGENT_HOME`, `CODE_AGENT_HOME`, `CODEAGENT_HOME`, then common directories; if more than one candidate exists, it fails safely and asks for an explicit root. The installer adapts Subagent frontmatter per host while keeping `agents/` in the package as the single source of truth.

For BitFun, the installer emits its native custom-agent schema. Source-changing
authority is limited to `code-repairer`; `profile-builder` and
`validation-runner` may persist scoped artifacts. Evidence and gate roles receive
command execution only when their responsibilities require it.

You can also install the CLI globally:

```text
npm install --global @tonyclaw/dic-workflow-kit@1.1.17
qiheng install --host opencode
```

The same CLI can also be installed directly from the repository:

```text
npm install --global git+ssh://git@gitcode.com/TonyClaw/DICWorkflowKit.git
qiheng install
```

Use `--dry-run` to preview the resolved destination and `--install-root <path>` to set the host root. If the product stores the two resource types separately, use `--skills-root <path>` and `--agents-root <path>`. The backward-compatible `--marketplace-root <path>` remains Codex-only. The Codex installer preserves unrelated marketplace entries and replaces only the entry with the same plugin name. Restart or reload the target coding-agent session after its first Skills/agents directory is created.

When the directory convention is unknown, preview discovery first:

```text
npx dic-workflow-kit@1.1.17 install --host coding-agent --dry-run
```

Once the CodeAgent configuration root is known, install explicitly:

```text
npx dic-workflow-kit@1.1.17 install --host coding-agent --install-root <codeagent-home>
```

### What the Coding Agent installation contains

`--install-root` is QIHENG's root inside the target Coding Agent. It is neither
the project source directory nor npm's global package directory. User scope
defaults to `~/.codeagent`; project scope defaults to
`<project>/.codeagent`. An existing unique `.code-agent` or `.coding-agent`
directory is reused when discovered.

The default layout is:

```text
<Coding Agent root>/
├─ .dic-workflow-kit-install.json   # version, roots, managed files, SHA-256
├─ skills/                          # 21 reusable methods, including the product entry
└─ agents/                          # 19 dispatchable Subagents
```

`skills/` receives the complete Skill directories and their supporting assets:

```text
knowledge-bdd                    quality-evidence-audit
knowledge-change-impact          quality-repository-gate
knowledge-openspec               quality-review-orchestrator
knowledge-repair-distill         quality-spec-review
qiheng
quality-adversarial-challenge    quality-sr-ar-review
quality-ci-gate                  workflow-core
quality-code-review              workflow-harness
quality-consistency-gate         workflow-intake
quality-cross-spec-consistency   workflow-profile
quality-dt-review                workflow-repair
```

`agents/` receives these Subagents with Claude Code-compatible metadata:

```text
adversarial-challenger.md        impact-analyst.md
architecture-reviewer.md         impl-inspector.md
ci-gatekeeper.md                 profile-builder.md
code-quality-reviewer.md         repair-planner.md
code-repairer.md                 repository-gatekeeper.md
contract-oracle.md               semantic-conflict-auditor.md
evidence-auditor.md              spec-quality-reviewer.md
final-reviewer.md                spec-reader.md
flow-auditor.md                  test-quality-reviewer.md
                                 validation-runner.md
```

Skills define how work is performed, Subagents own bounded decisions and
deliverables, and the root manifest supports integrity checks and safe
uninstallation. If the target product separates the two resource types, use:

```text
qiheng install --host coding-agent \
  --install-root <qiheng-state-root> \
  --skills-root <target-skills-root> \
  --agents-root <target-agents-root>
```

The root then primarily stores the manifest while Skills and Subagents are
written to their explicit destinations. Pass the same three root options to
subsequent `doctor` or `uninstall` commands.

### Understand the flow immediately after installation

After an interactive installation succeeds, the console renders the QIHENG
flow: candidate freezing, the inspect-repair-validate feedback loop, specialist
assurance, consistency signing, and the two-stage
`READY_FOR_ADMISSION → repository admission → READY` closure. `--json` remains
pure machine-readable JSON and never includes the diagram.

Generate the high-density offline HTML swimlane for browsing, printing, or
sharing:

```text
npx dic-workflow-kit@1.1.17 guide
```

After a global CLI installation, the short form is `qiheng guide`. The default
output is `.qiheng/guide/index.html` under the current project. Choose another
location when needed:

```text
npx dic-workflow-kit@1.1.17 guide --output docs/qiheng-flow.html
```

The terminal and HTML views share one flow definition so their stages, roles,
evidence, and terminal states cannot drift apart.

### Verify, upgrade, and uninstall

Every successful installation writes `.dic-workflow-kit-install.json` with the package version, resolved host roots, managed files, and SHA-256 hashes. Use `doctor` to verify that no managed file is missing or modified:

```text
qiheng doctor --host bitfun --scope project
qiheng doctor --host opencode
```

Remove only files managed by this installation:

```text
qiheng uninstall --host bitfun --scope project
```

Install refuses to overwrite an unmanaged or locally modified file. Uninstall likewise refuses to remove a modified managed file. Install, upgrade, and uninstall use a cross-process lock and a durable on-disk transaction; after an interrupted process, the next lifecycle operation quarantines a stale lock, verifies backup hashes, and restores the unfinished transaction. Review the reported paths first; use `--force` only when those changes may be discarded. `--force` never disables canonical path-boundary checks. Use `--json` with `install`, `doctor`, or `uninstall` for machine-readable CI output.

## How to use it

### 1. Start the Coding Agent in your project root

After installation, enter the repository you want to inspect and restart Codex, Claude Code, OpenCode, MiMo Code, or BitFun. An existing session may not discover a newly created Skills/agents directory immediately.

```text
cd /path/to/your-project
```

### 2. Start the workflow with a prompt

This prompt works across all supported hosts:

```text
Use $qiheng to process the current Spec or Change in delivery mode.
Tell me the current stage, next gate, next Skill/Agent, blockers, and evidence.
```

The `$qiheng` Skill is the public entry. `quality-review-orchestrator` remains
the internal gate orchestrator and `workflow-harness` remains the executable
state authority.

For an audit that must not modify code:

```text
Use QIHENG to audit this project without modifying files.
Report design obligations, implementation gaps, evidence locations,
recommended repairs, and residual risks.
```

For an evidence-bounded repair:

```text
Use QIHENG to inspect and repair this project.
Repair only gaps traceable to authoritative design sources. Run relevant
validation after each change; stop expanding changes when validation fails
and record the blocker.
```

### 3. Check one OpenSpec Change

Provide the Change ID explicitly to reduce search scope and avoid treating historical changes as current truth:

```text
Use QIHENG to check the OpenSpec Change
2026-06-09-add-ts-local-skill-source.
Start from its proposal, design, tasks, and delta specs. Cross-check the current
stable specs, implementation, and tests. Produce an obligation matrix,
implementation gaps, and a validation conclusion.
```

For an archived Change, archived files remain historical context while the promoted current stable Spec becomes the authoritative baseline.

### 4. Invoke the core Skill explicitly

On hosts that expose slash Skills, start with:

```text
/workflow-core
```

You can also name the required Skills directly:

```text
Use workflow-core, workflow-intake, workflow-profile, and
knowledge-openspec to inspect the current OpenSpec change.
```

You do not need to start all nineteen Subagents manually. The primary Agent should select roles according to evidence dependencies and require every delegation to produce a standard handoff consumed by a downstream step.

### 5. Read the results

Start with these outputs:

| File | Purpose |
| --- | --- |
| `reports/qiheng-entry.json` | Product-entry intent: mode and repository/Spec/Change pointer; never a second gate-state store. |
| `reports/qiheng-entry.md` | Human-readable current stage and next-action projection. |
| `reports/intake-evidence.json` | Raw repository facts discovered before normalization |
| `reports/project-profile.json` | Project structure, design sources, protected paths, and validation commands |
| `reports/handoffs/` | Standard `dic.agent-handoff.v1` records consumed by Harness gates |
| `reports/contract-obligations.md` | Human-readable design obligations with source anchors |
| `reports/implementation-gaps.md` | Confirmed implementation gaps |
| `reports/repair-plan.md` | Source-backed repair plan with stop conditions |
| `reports/quality/` | Applicability plan, gate run history, invalidation reasons, and candidate-bound decisions |
| `reports/final-consistency-report.md` | Final consistency conclusion and residual risks |
| `reports/FINAL_RESULT.json` | Machine-readable terminal status |
| `logs/trace/` | Intake, delegation, change, and validation evidence |

DIC terminal status is `PASS`, `PARTIAL`, `BLOCKED`, or `FAIL`. Read it
separately from specialist quality and repository admission. A DIC `PASS`
means the consistency evidence chain is satisfied, not merely that visible
tests happen to pass and not that the candidate is automatically admitted.

### Troubleshooting

- **A Skill or Subagent is missing:** restart the Coding Agent and use `--dry-run` to confirm the resolved install root.
- **Check installation integrity:** run `doctor` with the same host, scope, and root options used for installation.
- **Install reports a collision:** inspect the reported file; preserve or rename user-owned content before considering `--force`.
- **Uninstall refuses a modified file:** keep the file by leaving the installation in place, or use `--force` only after backing up the modification.
- **Only this repository should use the kit:** add `--scope project` for Claude Code, OpenCode, MiMo Code, or BitFun.
- **The project does not use OpenSpec:** use design documents, APIs, schemas, READMEs, or product requirements as authoritative design sources.
- **A validation tool is unavailable:** record the missing command and environment evidence, and finish as `BLOCKED` or `PARTIAL`; do not claim success.
- **Do green tests prove consistency:** no. Requirements, branches, state transitions, side effects, and integration flows must also match the design.

Maintainers: see [the dual npm release guide](docs/RELEASING.md).

## Why This Exists

Coding Agents are good at changing code, but they often optimize for local green tests, visible examples, or the latest error message. In design-first projects, especially OpenSpec projects, the harder question is different:

> Does the implementation still match the design contract?

QIHENG answers that question with a repeatable workflow:

1. Identify authoritative design sources.
2. Build a project profile.
3. Map design requirements to implementation areas.
4. Inspect implementation gaps.
5. Plan small source-backed repair slices.
6. Validate with project-declared commands.
7. Record evidence, residual risks, and final artifacts.

## Repository Layout

| Path | Purpose |
| --- | --- |
| `INSTRUCTION.md` | Generic operating manual for autonomous design-implementation consistency work. |
| `skills/` | Installable Skills: workflow controls and reusable knowledge packs. |
| `agents/` | Installable Agent prompts: bounded roles for evidence production and repair flow. |
| `adapters/` | Optional adapters for OpenSpec, BDD, generic repositories, and supported coding-agent hosts. |
| `runtime/` | Source implementation of ontology evaluation, Actions, Ledger, integrity checks, reports, and Attestations. |
| `schemas/` | Stable JSON schemas for profiles, ontology state, Actions, handoffs, Attestations, and final results. |
| `scripts/` | Portable Python standard-library helpers. |
| `docs/` | Ontology reference, FAQ, release guide, and current product presentations. |
| `examples/` | Small examples showing how to apply the kit to different project styles. |

## Capability Activation Policy

The selection mechanism is universal; running every capability is not. QIHENG first builds a project profile from design sources, repository structure, change scope, and risk. Capabilities that do not match the profile are not loaded, executed, or added to the working context.

| Attribute | Meaning | Activation rule |
| --- | --- | --- |
| **Required（必需）** | Foundation of the design–implementation consistency path | Runs for every project to form the minimum traceable closed loop. |
| **On-demand（按需）** | Specialist capability for a particular structure, tool, or risk | Loaded only when the project profile matches its applicability conditions. |
| **Triggered（触发）** | Response capability for a change, problem, or exceptional event | Activated by input drift, a consistency gap, validation failure, or a disputed high-risk conclusion; only affected gates are rerun. |

## Skills by First Activation

This table is an index, not a mandatory serial pipeline. Skills are listed by their earliest normal activation point; decisions become stale when their consumed artifacts or candidate bytes change.

| Order | Skill | Attribute | Type | Workflow Position | Core Role |
| --- | --- | --- | --- | --- | --- |
| 00 | `qiheng` | **Required** | Product entry | User request through terminal delivery | Starts, queries and resumes the workflow while delegating orchestration and state to the existing controls. |
| 01 | `quality-review-orchestrator` | **Required** | Quality control | Imported Spec through pre-commit admission | Maintains the applicability plan, gate dependencies, invalidation, reruns, and distinct delivery outcomes. |
| 02 | `workflow-core` | **Required** | Workflow mechanism | Entire DIC run | Defines source priority, ontology, evidence rules, typed handoffs, final statuses, and durable outputs. |
| 03 | `workflow-harness` | **Required** | Executable control plane | Profile creation through admission | Freezes candidate identity, materializes the gate graph, records evidence-backed decisions, propagates invalidation, and computes readiness. |
| 04 | `workflow-intake` | **Required** | Workflow method | Before Subagents | Finds design sources, implementation roots, test roots, protected paths, validation commands, and adapter hints. |
| 05 | `workflow-profile` | **Required** | Workflow method | Before Subagents | Normalizes intake evidence into the project profile consumed by every downstream role. |
| 06 | `knowledge-openspec` | **On-demand** | Knowledge pack | When OpenSpec or a Change is detected | Interprets proposals, designs, specs, scenarios, tasks, active changes, and archived capabilities. |
| 07 | `knowledge-bdd` | **On-demand** | Knowledge pack | When `.feature` files or behavioral coverage are in scope | Interprets mounted Gherkin contracts or derives source-bounded Given-When-Then scenarios. |
| 08 | `knowledge-change-impact` | **Triggered** | Workflow method | After input drift, stale evidence, or repair | Traces semantic impact and invalidates only dependent evidence and gates. |
| 09 | `quality-cross-spec-consistency` | **On-demand** | Design quality gate | When multiple related Specs or baselines exist | Audits direct related baselines and ranked semantic candidates for incompatible current rules. |
| 10 | `quality-spec-review` | **On-demand** | Design quality gate | When independent Spec quality review is needed | Checks completeness, consistency, testability, traceability, and unsupported claims. |
| 11 | `quality-sr-ar-review` | **On-demand** | Architecture quality gate | When requirements, architecture, or domain boundaries change | Checks requirement-to-design coverage, ownership, interfaces, data/state, quality attributes, and realizability. |
| 12 | `quality-ci-gate` | **On-demand** | Delivery quality gate | When CI or delivery checks exist | Defines candidate checks, runtime/flake policy, evidence retention, and candidate-bound verification. |
| 13 | `workflow-repair` | **Triggered** | Workflow method | When design and implementation diverge | Controls source-backed consistency inspection, minimal repair, validation, and convergence. |
| 14 | `knowledge-repair-distill` | **Triggered** | Knowledge pack | When repairs repeat, validation fails, or execution drifts | Supplies gap taxonomy, convergence guidance, model-steering hints, and validation gates. |
| 15 | `quality-code-review` | **On-demand** | Implementation quality gate | When code changes or implementation risk is high | Reviews semantic contract impact, architecture, security, performance, reliability, and maintainability. |
| 16 | `quality-dt-review` | **On-demand** | Test quality gate | When test coverage, assertions, or defect detection need review | Checks requirement/risk coverage, negative paths, assertion strength, determinism, and mutation sensitivity. |
| 17 | `quality-adversarial-challenge` | **Triggered** | Independent challenge gate | When risk is high or a pass conclusion is disputed | Runs a minimal risk-selected challenge set and records reproducible counterexamples. |
| 18 | `quality-evidence-audit` | **On-demand** | Evidence integrity gate | When strict auditability or reproducible delivery is required | Verifies that claims are current, reproducible, content-addressed, and candidate-bound. |
| 19 | `quality-consistency-gate` | **Required** | DIC terminal gate | After evidence is ready; before repository admission | Independently signs the candidate-bound design, implementation, test, and evidence consistency state. |
| 20 | `quality-repository-gate` | **On-demand** | Pre-commit admission gate | When a commit, merge, or release decision is needed | Decides ADMIT, ADMIT WITH FOLLOW-UP, or REJECT, then closes the full Harness to `READY`. |

Skill total: **7 Required, 10 On-demand, and 4 Triggered; 21 in total**.

## Subagents in the DIC Consistency Loop

These Subagents implement the post-implementation consistency loop. Their
dependency order does not imply that the surrounding quality gates execute once
or that unrelated work must be serialized.

| Step | Subagent | Attribute | Phase | Consumes | Produces |
| --- | --- | --- | --- | --- | --- |
| 01 | `profile-builder` | **Required** | Project profile confirmation | Intake evidence and repository structure | `reports/project-profile.json`, authority scope, and semantic candidates |
| 02 | `spec-reader` | **Required** | Source truth | Project profile and authoritative design sources | Source-backed requirement brief, source anchors, protected paths, unresolved questions |
| 03 | `semantic-conflict-auditor` | **On-demand** | Cross-Spec challenge | Multiple related baselines, semantic candidates, and authority roots | Source-paired conflict and refinement findings; no edits |
| 04 | `contract-oracle` | **Required** | Requirement mapping | Confirmed requirements, scenarios, and conflict findings | Source-confirmed design requirement queue |
| 05 | `spec-quality-reviewer` | **On-demand** | Spec quality | Specs requiring independent quality review | Independent completeness, consistency, and testability decision |
| 06 | `architecture-reviewer` | **On-demand** | Architecture quality | Changed architecture, interfaces, data, dependencies, or domain boundaries | Independent architecture realization decision |
| 07 | `impact-analyst` | **Triggered** | Change impact | Changed design, implementation, or test inputs and their dependencies | Invalidated decisions and minimal safe rerun plan |
| 08 | `flow-auditor` | **On-demand** | Flow completeness | Requirements involving state machines, lifecycles, asynchronous work, or cross-system flows | Lifecycle, transition, branch, side-effect, and integration-flow audit |
| 09 | `impl-inspector` | **Required** | Implementation inspection | Confirmed requirements and applicable specialist audits | Source-backed implementation gap report; no code edits |
| 10 | `repair-planner` | **Triggered** | Repair planning | A discovered consistency gap, protected paths, and validation commands | Small repair slices with source anchors, stop conditions, and fallback routes |
| 11 | `code-repairer` | **Triggered** | Code repair | Approved repair slices | Minimal code changes, changed-file evidence, and repair notes |
| 12 | `code-quality-reviewer` | **On-demand** | Code quality | Code changes or elevated implementation risk | Independent correctness, security, and maintainability decision |
| 13 | `validation-runner` | **Required** | Validation execution | Project-declared commands and changed implementation | Content-addressed validation logs under `logs/trace/validation/` |
| 14 | `test-quality-reviewer` | **On-demand** | Test quality | Existing tests or changed test risk | Independent test coverage and strength decision |
| 15 | `adversarial-challenger` | **Triggered** | Independent challenge | High-risk or disputed pass conclusions, policies, and evidence | Falsifiable challenges and reproducible counterexamples; no edits |
| 16 | `ci-gatekeeper` | **On-demand** | Delivery gate | Projects with CI or delivery checks | CI plan and frozen-candidate verification decisions |
| 17 | `evidence-auditor` | **On-demand** | Evidence integrity | Claims and evidence requiring strict auditability or reproducibility | Claim-to-evidence matrix and stale or unsupported claim findings |
| 18 | `final-reviewer` | **Required** | DIC consistency gate | Current DIC evidence, conflicts, impact, validation, and output artifacts | Candidate-bound consistency decision and Attestation; not repository admission |
| 19 | `repository-gatekeeper` | **On-demand** | Repository admission | A candidate requiring a commit, merge, or release decision | ADMIT, ADMIT WITH FOLLOW-UP, or REJECT decision |

Subagent total: **6 Required, 9 On-demand, and 4 Triggered; 19 in total**.

## Default Gate Lifecycle

```text
IMPORT SPEC
-> Intake + Profile
-> Cross-Spec Consistency
-> Spec Review
-> [SR/AR Review when architecture or realization is affected]
-> CI Gate [PLAN]

IMPLEMENT
-> implementation from confirmed obligations
-> [risk-applicable specialist gates]*

DIC CONSISTENCY LOOP
-> inspect design-implementation gaps
-> [plan repair -> apply repair -> validate]*
-> analyze impact and stale dependent evidence
-> [invalidate and re-run affected gates]*

PRE-COMMIT
-> [Adversarial Challenge when material hypotheses apply]
-> CI Gate [VERIFY frozen candidate]
-> Evidence Audit [candidate-bound claim freshness]
-> Consistency Gate [DIC consistency + Attestation]
-> Harness [READY_FOR_ADMISSION]
-> Repository Gate [ADMIT / ADMIT WITH FOLLOW-UP / REJECT]
-> Harness [READY]
```

`*` means zero or more risk-driven iterations. This is a gate graph with
feedback loops, not a fixed one-pass Agent chain. A skipped gate needs an
applicability reason. A changed Spec, architecture, implementation, test,
fixture, pipeline, policy, or candidate invalidates dependent decisions, which
must be re-run from the earliest affected boundary.

Keep three outcomes distinct: DIC `consistencyStatus`, specialist
`qualityStatus`, and repository `admissionStatus`. DIC `PASS` proves
design-implementation consistency; it does not by itself prove every quality
domain or grant `ADMIT`. Retain the applicability plan, gate run history,
invalidation reasons, and decisions under `reports/quality/`.

## Ontology-Driven Consistency

DIC models the run as a portable semantic graph, not a collection of unrelated
agent summaries. `reports/ontology-snapshot.json` contains typed objects
(`DesignSource`, `Requirement`, `Scenario`, `ImplementationUnit`, `Gap`,
`RepairAction`, `Validation`, and `Evidence`) and explicit links between them.

Each object has a stable ID, lifecycle, and source provenance. Agents operate
through bounded actions defined by `schemas/ontology-action.schema.json`. The
final reviewer computes PASS from graph invariants: active obligations must be
source-backed, requirements must have implementation dispositions, obligations
must have current validation evidence, and blocking gaps must be closed.

This is file-backed by design. It works across Coding Agent hosts without
requiring a graph database; SQLite or a graph service can be added later as an
index without changing the semantic contract.

The published, bundled CLI validates and records actions without publishing the
runtime source. These ontology commands expect the workflow to have already
created `reports/ontology-snapshot.json`, `reports/project-profile.json`, and,
for Ledger operations, `reports/ontology-actions.jsonl`. They are integrity and
evidence commands, not a replacement for the initial Agent-driven intake:

```text
qiheng ontology-check --root . --status PASS
qiheng action-check --root . --action reports/actions/repair.json
qiheng action-record --root . --action reports/actions/repair.json
qiheng ontology-reconcile --root .
qiheng ontology-ledger-check --root . --json
qiheng ontology-evidence-check --root . --json
qiheng ontology-validation-check --root . --json
qiheng ontology-implementation-check --root . --json
qiheng ontology-query --root . --query impact --id <object-id>
qiheng ontology-drift --root .
qiheng ontology-plan --root . --json
qiheng ontology-explain --root . --id <object-id> --json
qiheng ontology-report --root . --status PASS
qiheng ontology-attest --root . --status PASS --summary "Verified"
qiheng ontology-attestation-check --root .
```

`action-record` writes an append-only, SHA-256-addressed audit entry to
`reports/ontology-actions.jsonl`. It rejects unauthorized Agent roles, missing
targets, invalid target types, incomplete terminal conditions, missing evidence,
protected-path overlap, and action-ID collisions.

New records use the v2 ledger format: each record has a sequence number,
previous-record hash, base Snapshot revision, action hash, and full-record hash.
This detects reordering, insertion, mutation, and stale-state recording while
retaining read compatibility with a contiguous v1 prefix. Run
`ontology-ledger-check` to inspect the chain head and complete-file hash.

Completed actions carry a declarative `ontologyPatch`. Action-specific rules
restrict which objects, links, and lifecycle transitions can be produced.
`ontology-reconcile` verifies ledger hashes, skips previously applied actions,
replays remaining patches, recomputes invariants, and replaces the snapshot only
after the complete candidate state is valid.

`ontology-query` provides four initial operational views:

- `uncovered`: active obligations missing implementation or validation
- `gaps`: unresolved Gap objects
- `unevidenced`: validations without durable evidence
- `impact --id`: the bounded dependency neighborhood of a changed source,
  requirement, implementation unit, validation, gap, or repair

`ontology-evidence-check` verifies that every Evidence object required by a
current Validation points to a real project-relative file whose bytes match its
recorded SHA-256. A `VERIFIED_BY` link counts toward PASS only when the target
Validation is current and reports `properties.status: PASS`.

`ontology-validation-check` closes the “old green log, new code” loophole.
Each Validation records `executedAt` and binds every consumed DesignSource and
ImplementationUnit through `{ objectId, contentHash }`. Missing or stale inputs
block PASS and invalidate the final Attestation.

`ontology-implementation-check` verifies every required ImplementationUnit
against its project-relative file and recorded SHA-256. Existing code is
recorded through `ObserveImplementation`; `ApplyRepair` is reserved for
implementation created or changed by an approved repair.

`ontology-drift` compares current design-source content with the SHA-256
provenance recorded in the snapshot. Changed or missing sources return a
non-zero status and their IDs can be passed directly to the impact query.

`ontology-plan` combines source drift, implementation drift, Evidence drift,
and impact traversal into a minimal rerun plan. Design changes restart intake
and contract confirmation; implementation drift restarts inspection and
validation; Evidence-only drift restarts validation and final review.

Every generated or reconciled snapshot has a canonical `snapshotRevision`.
Direct semantic edits invalidate it. Reconciliation also checks that the
on-disk snapshot did not change while replay was running, preventing a stale
writer from silently overwriting newer semantic state. Source drift is included
in the PASS gate, so old green evidence cannot approve a changed design.

`ontology-explain` returns an object's properties, provenance, direct
relations, and bounded evidence chains. It shows exactly which design source,
implementation unit, gap, repair, validation, and evidence support a claim.

`ontology-report` generates a high-density Markdown view directly from the
snapshot. `ontology-attest` creates a content-addressed terminal decision bound
to the snapshot revision, action-ledger hash, tracked source hashes, Evidence
artifact hashes, ImplementationUnit hashes, and gate results.
`ontology-attestation-check` recomputes those bindings so a source,
implementation file, evidence file, ledger, snapshot, or attestation edit makes
the artifact fail closed.
Store the emitted `contentHash` in CI or release metadata and supply it through
`--expected-hash` to add an external trust anchor; a self-contained digest alone
provides integrity, not authenticity.

## BDD as an Ontology Source

The source helper detects `.feature` files under conventional feature, BDD,
spec, and test roots. English and common Chinese Gherkin keywords are supported.

- Feature becomes a Requirement.
- Scenario and Scenario Outline become Scenario objects.
- Background clauses are inherited by every scenario.
- Examples tables, tags, source lines, and source hashes are preserved.
- `DERIVED_FROM` connects obligations to the feature file.
- `REFINES` connects each scenario to its Feature requirement.

Parsing a scenario does not prove it passed. Validation and durable evidence
must still be attached through `RunValidation` and `AttachEvidence`.

For an explicitly selected OpenSpec Change, only referenced Feature files are
mounted. Other detected files remain discoverable without silently widening the
Change's obligation scope.

## OpenSpec Focus

For OpenSpec projects, the kit treats these as first-class design sources:

| OpenSpec Source | How It Is Used |
| --- | --- |
| `openspec/specs/**/spec.md` | Stable capability requirements and scenarios. |
| `openspec/changes/**/proposal.md` | Intent behind a planned change. |
| `openspec/changes/**/design.md` | Technical design rationale and constraints. |
| `openspec/changes/**/tasks.md` | Implementation checklist and completion evidence. |
| `openspec/changes/**/specs/**/spec.md` | Delta requirements and scenarios for active changes. |
| Archived specs | Historical context, never stronger than current active specs. |

The kit checks whether proposals, specs, scenarios, and tasks were actually reflected in implementation and tests.

The source repository also contains a development helper for generating these profiles directly. It is intentionally excluded from the npm runtime package. From a source checkout, scope intake to one OpenSpec Change with:

```text
python scripts/dic_workflow.py \
  --root /path/to/project \
  --output-root /path/to/evidence \
  init --change 2026-06-09-add-ts-local-skill-source
```

The resulting profile records the Change lifecycle, proposal/design/tasks documents, delta specs, and matching promoted baseline specs. When `openspec/designs/spec-to-design-map.md` contains the capability, the profile also mounts its architecture designs, module designs, ADRs, validation summary, and executable command suggestions. Archived change-specific validation commands are omitted because their active Change target no longer exists.

## Output Contract

By default, a run should produce artifacts relative to the selected submission/workflow root:

```text
reports/project-profile.json
reports/contract-obligations.json
reports/contract-obligations.md
reports/ontology-snapshot.json
reports/ontology-actions.jsonl
reports/ontology-report.md
reports/ontology-attestation.json
reports/implementation-gaps.md
reports/repair-plan.md
reports/final-consistency-report.md
reports/FINAL_RESULT.json
result/output.md
logs/trace/
```

For an explicit OpenSpec Change, `init` generates the obligation artifacts and
ontology snapshot automatically. Requirements and Scenarios receive stable IDs,
source line references, authority labels, provenance hashes, parent
relationships, and structured Given/When/Then clauses. Active changes use delta
specs as authority; archived changes use the promoted current baseline so
historical text cannot override current design truth.

From a source checkout, evaluate the ontology structure or a requested PASS gate:

```text
python scripts/dic_workflow.py --root /path/to/evidence ontology-check
python scripts/dic_workflow.py --root /path/to/evidence ontology-check --status PASS
```

Adapters can extend this contract for a specification format or coding-agent
host without changing the core Skills/SubAgents responsibilities.

## Portability Rules

- Do not hardcode local absolute paths.
- Do not assume Windows, Linux, macOS, PowerShell, Bash, or `cmd`.
- Resolve paths from the active `INSTRUCTION.md`, project profile, or adapter configuration.
- Use Python standard library only for helper scripts.
- Resolve external tools such as `git`, `mvn`, `npm`, `pnpm`, `pytest`, or `openspec` from the target environment `PATH` only when needed.
- Treat missing external tools as environment evidence, not as design failure.

## Status

QIHENG is a released, cross-host workflow package with safe
installation lifecycle management, OpenSpec and BDD intake, ontology-governed
Actions, content-addressed validation, tamper-evident Ledgers, generated reports,
and final Attestations. New work should preserve these contracts while extending
adapters, storage backends, and CI trust anchors.
