# 齐衡 QIHENG Design Integrity Workflow

齐衡 QIHENG is the Design Integrity Control Plane: use evidence as the measure
to align design, implementation, validation, and admission. The name is inspired
by 《尚书·舜典》“在璇玑玉衡，以齐七政”
(*Zài xuán jī yù héng，yǐ qí qī zhèng。*). DIC remains the technical
consistency protocol used by the workflow.

Use this workflow when a Coding Agent must check or repair whether implementation matches design intent.

This instruction is generic. It must not assume a contest, language, framework, directory name, agent host, or operating system.

## Core Contract

- Work autonomously when invoked by an automated runner.
- Resolve the workflow root from the directory containing this `INSTRUCTION.md`.
- Resolve the project root from the workflow root, adapter config, or repository evidence.
- Treat design/spec/API/schema/config/README sources as stronger than existing implementation.
- Treat public examples and tests as smoke signals, not the full design surface.
- Do not edit protected design sources unless explicitly instructed.
- Write intermediate evidence under `logs/trace/`.
- Write final evidence under `reports/` and `result/`.
- Treat `reports/ontology-snapshot.json` as the machine-readable semantic state.
- Change semantic state through typed, evidence-backed actions rather than untracked prose.

When workflow evidence is stored outside the repository, use the workflow root
to locate `reports/` and the Snapshot `projectRoot` to resolve design,
implementation, and Evidence paths. Do not conflate these roots.

## Ontology Contract

The workflow models design consistency as typed objects and links:

```text
Change -> PROPOSES -> Requirement
Requirement -> DERIVED_FROM -> DesignSource
Scenario -> REFINES -> Requirement
Requirement -> IMPLEMENTED_BY -> ImplementationUnit
Requirement/Scenario -> VERIFIED_BY -> Validation
Gap -> VIOLATES -> Requirement
RepairAction -> RESOLVES -> Gap
Validation -> PRODUCES -> Evidence
```

Every object must have a stable ID, lifecycle, properties, and provenance. Every
link endpoint must resolve. Reports are views over this semantic state; they are
not independent sources of truth.

Agents may only perform actions within their role:

- readers propose or confirm source-backed objects
- inspectors add observed implementation and gap links
- planners propose repair actions without editing code
- repairers execute approved, path-bounded actions
- validators attach validation and evidence objects
- final reviewers evaluate DIC invariants and transition consistency status

Before executing or recording a mutation, validate it with the installed runtime:

```text
qiheng action-check --root <project> --action <action.json>
qiheng action-record --root <project> --action <action.json>
qiheng ontology-reconcile --root <project>
qiheng ontology-ledger-check --root <project>
qiheng ontology-evidence-check --root <project>
qiheng ontology-validation-check --root <project>
qiheng ontology-implementation-check --root <project>
```

`action-record` appends an immutable, content-hashed entry to
`reports/ontology-actions.jsonl`. Reusing an action ID with different content is
an error. `ontology-reconcile` replays authorized `ontologyPatch` effects and
atomically replaces the snapshot only when structural invariants still pass.
Use `ontology-check --status PASS` before producing a terminal PASS.

Set `expectedSnapshotRevision` on authored actions. Newly recorded ledger
entries bind the current Snapshot revision and form a sequence-numbered hash
chain. Reconcile before recording the next action; otherwise recording fails.

A completed action must declare `parameters.ontologyPatch`. Its permitted
object types, link types, and lifecycle transitions are derived from the action
type. Agents must not edit `ontology-snapshot.json` directly to bypass these
rules.

Useful machine-readable queries:

```text
qiheng ontology-query --root <project> --query uncovered
qiheng ontology-query --root <project> --query gaps
qiheng ontology-query --root <project> --query unevidenced
qiheng ontology-query --root <project> --query impact --id <object-id>
qiheng ontology-drift --root <project>
qiheng ontology-plan --root <project> --json
qiheng ontology-explain --root <project> --id <object-id> --json
qiheng ontology-report --root <project> --status <status>
```

Snapshots carry a canonical `snapshotRevision`. Direct semantic edits invalidate
the revision and must fail structural review. Reconciliation uses optimistic
concurrency and refuses to replace a snapshot that changed after replay began.

A PASS gate includes source-drift evaluation. A changed, missing, or
out-of-project tracked source blocks PASS even when older implementation and
validation links are still present.

A `VERIFIED_BY` relation counts only when its Validation has a current lifecycle
and `properties.status: PASS`. The Validation must record `executedAt` and bind
every consumed DesignSource and ImplementationUnit as
`properties.inputs[] = { objectId, contentHash }`; otherwise an earlier run
could incorrectly approve newer design or code. Every Evidence produced by such a Validation
must reference a project-relative artifact, record its SHA-256
`provenance.contentHash`, and implement `ContentAddressed`.

An `IMPLEMENTED_BY` relation counts only when its ImplementationUnit has a
current lifecycle. The implementation must reference a project-relative regular
file, record its SHA-256 `provenance.contentHash`, and implement
`ContentAddressed`. Use `ObserveImplementation` for existing code and
`ApplyRepair` for approved repair output.

The portable schemas are:

```text
schemas/ontology-snapshot.schema.json
schemas/ontology-action.schema.json
schemas/ontology-action-record.schema.json
schemas/ontology-attestation.schema.json
```

## Quality Review Boundaries

Use `quality-review-orchestrator` to maintain a candidate-bound gate graph. It
selects only the specialist quality Skills justified by the imported Spec,
architecture, implementation, test, pipeline, and admission risk. The graph may
contain repeated gates and feedback edges; it is not a one-pass checklist.

Operate through these lifecycle boundaries:

1. **Import and design clearance.** Intake resolves the imported Spec/change
   and governing baseline. Run `quality-cross-spec-consistency` when the
   profile requires semantic cross-Spec search, then run `quality-spec-review`
   before implementation.
   Add `quality-sr-ar-review` when architecture or realization is affected.
2. **Gate planning.** Run `quality-ci-gate` with `phase: PLAN` to declare the
   checks, evidence, runtime budgets, and failure policy expected for the
   planned change surface.
3. **Implementation.** Advance implementation only from confirmed obligations.
   Trigger code, DT, security, performance, and other specialist gates when
   their risk becomes applicable; do not assume one fixed invocation.
4. **DIC consistency repair.** After implementation, compare the current
   candidate with confirmed design, repair source-backed inconsistencies,
   validate them, and repeat until invariants converge or a blocker is recorded.
5. **Affected-gate re-entry.** Any Spec, architecture, code, test, fixture,
   pipeline, policy, or candidate change marks its dependent decisions `STALE`.
   Run `knowledge-change-impact` and re-run only those affected gates against
   the new candidate.
6. **Pre-commit admission.** Freeze the candidate, run `quality-ci-gate` with
   `phase: VERIFY`. When high-risk claims apply, run
   `quality-adversarial-challenge`; always audit terminal claim freshness with
   `quality-evidence-audit`. Let `final-reviewer` compute DIC consistency and
   verify the Attestation, then run `quality-repository-gate`.

Skipped specialist reviews require an applicability reason. `STALE` and
`SKIPPED` are lifecycle states, not successful quality decisions. Quality
findings must reference existing ontology objects and Evidence where possible
instead of creating a parallel truth model.

DIC consistency, specialist quality, and repository admission are separate
outcomes. DIC `PASS` proves design-implementation consistency; it does not by
itself prove all quality domains or grant admission. Preserve the applicability
plan, run history, invalidation reasons, and specialist outputs under
`reports/quality/` so the Repository Gate consumes only current evidence for
the same frozen candidate.

## Enterprise Integration Boundary

QIHENG owns the Skills/SubAgents workflow, candidate binding, evidence
freshness, consistency decision, and repository admission contract. Enterprise
identity, approval, key management, compliance, immutable storage, and release
authorization remain external systems.

When repository policy requires one of those external decisions, record a
current, verifiable reference as admission evidence. Do not recreate a partial
identity, signing, or compliance platform inside QIHENG, and do not claim that
a local hash proves an external control was enforced.

## Default Lifecycle

```text
qiheng [START / STATUS / NEXT / RESUME]
-> quality-review-orchestrator [OPEN]
-> workflow-core
-> workflow-intake
-> workflow-profile
-> profile-builder
-> workflow-harness [freeze candidate + materialize gate graph]
-> spec-reader
-> semantic-conflict-auditor [uses quality-cross-spec-consistency]
-> contract-oracle [confirms implementation obligations]
-> spec-quality-reviewer [uses quality-spec-review]
-> architecture-reviewer [uses quality-sr-ar-review when applicable]
-> impact-analyst [uses knowledge-change-impact]
-> ci-gatekeeper [uses quality-ci-gate to PLAN required gates]
-> IMPLEMENT FROM CONFIRMED OBLIGATIONS
-> flow-auditor
-> impl-inspector
-> [repair-planner -> code-repairer -> validation-runner]*
-> [code-quality-reviewer / test-quality-reviewer / affected specialist reviewers]*
-> impact-analyst [uses knowledge-change-impact after drift or repair]
-> [invalidate and re-enter earliest affected gate]*
-> adversarial-challenger [uses quality-adversarial-challenge when applicable]
-> ci-gatekeeper [uses quality-ci-gate to VERIFY frozen candidate]
-> evidence-auditor [uses quality-evidence-audit]
-> final-reviewer [uses quality-consistency-gate; DIC consistency + Attestation]
-> workflow-harness [check READY_FOR_ADMISSION]
-> repository-gatekeeper [uses quality-repository-gate]
-> workflow-harness [check READY + generate executive cockpit]
-> quality-review-orchestrator [CLOSE]
-> qiheng [REPORT TERMINAL STATE]
```

`*` means zero or more risk-driven iterations. Dependencies constrain execution;
the textual layout does not require every conditional gate or force unrelated
gates into serial execution.

## Required Evidence

At minimum, produce:

```text
reports/qiheng-entry.json
reports/qiheng-entry.md
reports/intake-evidence.json
reports/project-profile.json
reports/harness-plan.json
reports/harness-run.json
reports/harness-report.md
reports/handoffs/*.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/final-consistency-report.md
reports/FINAL_RESULT.json
reports/quality/
result/output.md
logs/trace/
```

If a helper or external tool is unavailable, record the exact blocker and continue with the smallest source-backed fallback.

## Subagent Economy

Subagents are useful only when they produce bounded, auditable artifacts. Before delegating, record:

- why the subagent is needed
- bounded inputs
- expected artifact
- local budget
- fallback route
- acceptance check

Do not launch a subagent only to produce chat summaries. If a handoff has no trace artifact, output, decision, validation summary, repair queue item, or terminal blocker, treat it as ineffective delegation and recover locally.

## OpenSpec Rule

If OpenSpec files are present, use `knowledge-openspec` before repair planning. Confirm:

- proposal intent is reflected in specs
- spec scenarios are mapped to implementation and tests
- tasks are completed or terminally classified
- archived specs do not override current specs
- implementation does not silently exceed or contradict the accepted design

## BDD Rule

If `.feature` files are present, use `knowledge-bdd`. Preserve Feature,
Background, Scenario, Scenario Outline, Examples, tags, normalized steps, and
source lines. BDD acceptance contracts become ontology obligations, but they do
not become validation evidence until current executable checks are recorded.

## DIC Consistency Status

Use one of:

- `PASS`
- `PARTIAL`
- `BLOCKED`
- `FAIL`

Do not use `SUCCESS`, `DONE`, or informal labels for machine-readable DIC
consistency. Record specialist quality and repository admission in their
separate fields.

`PASS` is valid only when ontology invariants pass. At minimum:

- every active obligation has a source
- every active scenario refines a requirement
- every active requirement has an implementation disposition
- every required ImplementationUnit exists and matches its recorded SHA-256
- every active obligation is linked to validation
- every referenced Validation is current and successful
- every referenced Validation binds the current design and implementation hashes
- every required Evidence artifact exists and matches its recorded SHA-256
- no blocking gap remains open

Before publishing any terminal status, generate the ontology report, create a
content-addressed attestation, and verify it against the current snapshot,
action ledger, design sources, and gate:

```text
qiheng ontology-report --root <project> --status <status>
qiheng ontology-attest --root <project> --status <status> --summary "<summary>"
qiheng ontology-attestation-check --root <project>
```

If the final verification fails, the result is stale and must not be published.
Persist the emitted Attestation `contentHash` in external CI or release
metadata when available, then verify it with
`ontology-attestation-check --expected-hash <sha256>`.
