Metadata-Version: 2.5
Name: code-constraints
Version: 0.1.1
Summary: Enforce architectural and implementation constraints on a codebase: UML models, drift checks, conformance rules, and implementation locks.
Project-URL: Homepage, https://github.com/fleskovar/code-constraints
Project-URL: Repository, https://github.com/fleskovar/code-constraints
Project-URL: Issues, https://github.com/fleskovar/code-constraints/issues
Project-URL: Documentation, https://github.com/fleskovar/code-constraints/blob/main/docs/TUTORIAL.md
Author: Francisco Leskovar
License-Expression: MIT
License-File: LICENSE
Keywords: architecture,ci,code-review,constraints,governance,lint,uml
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Documentation
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: fastapi>=0.115
Requires-Dist: gitpython>=3.1
Requires-Dist: lxml>=5.0
Requires-Dist: python-multipart>=0.0.20
Requires-Dist: pyyaml>=6.0
Requires-Dist: questionary>=2.0
Requires-Dist: rich>=13.0
Requires-Dist: tree-sitter-c-sharp>=0.23
Requires-Dist: tree-sitter-julia>=0.23
Requires-Dist: tree-sitter-lua>=0.4
Requires-Dist: tree-sitter-odin>=1.2
Requires-Dist: tree-sitter-typescript>=0.23
Requires-Dist: tree-sitter>=0.23
Requires-Dist: typer>=0.12
Requires-Dist: uvicorn[standard]>=0.30
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: hatchling>=1.27; extra == 'dev'
Requires-Dist: httpx2>=0.1; extra == 'dev'
Requires-Dist: httpx>=0.27; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Provides-Extra: mcp
Requires-Dist: mcp>=2.0; extra == 'mcp'
Description-Content-Type: text/markdown

# code-constraints (`cdec`)

**Constrain what changes in a codebase.** `cdec` turns your architectural decisions into
checks that a machine can run. It parses your code into a UML model, shows it as an
interactive class diagram, and fails the build when the code breaks a rule that the team
agreed on. Junior developers, external contributors and coding agents then work inside
those boundaries, not around them.

It supports Python, C#, Odin, Lua, Julia, TypeScript and Svelte 5. It needs Python only —
there is no external binary to install.

## Install

```bash
pip install code-constraints
cdec --help
```

This requires Python 3.11 or later. The package includes the web viewer.
For the MCP server that coding agents use, install `pip install "code-constraints[mcp]"`.

To install from a clone or from git (`pip install .`, `pipx install .`,
`pip install git+https://github.com/fleskovar/code-constraints`), you also need Node.js 20
or later and npm. The build compiles the web viewer and puts it in the package. Without npm,
the build stops with an error. To build a package with no web viewer on purpose, set
`CDEC_SKIP_UI_BUILD=1`.

## Quick start

The steps below use a Python project with its code in `src/`. Run every command from the
root of the repository. For other languages, change `--lang` and see the
[per-language guides](docs/languages/README.md).

### Start with the viewer

Start the viewer in the folder of your project:

```bash
cdec ui
```

The browser opens on the home page. Select **Open this folder**, or choose another folder
with **Browse…**. The viewer detects the language. You do not need another command: every
task has a page or a wizard. Read the [user manual](docs/USER_MANUAL.md) for each step.

A project has five pages:

| Page | What it holds |
|---|---|
| **Project** | The codebase, the next step of the journey, and one card for each task. |
| **Diagrams** | The class diagrams: the code, the target, each snapshot. Show one, compare two, or edit one. |
| **Rules** | The rules of `rules.yaml`, the constraint tags in the code, and the locks. |
| **Checks** | The report of the check: the rules on a model, against a baseline. |
| **Timeline** | The start, each goal, each checkpoint and each rule change, in order. |

A folder with no `.cdec/` folder opens on the **Project** page. Choose a journey there:

- **Start a new design** (greenfield). The folder has little or no code. You draw the
  target model first, set it as the goal, and turn on the rules that keep the code in the
  plan.
- **Adopt an existing codebase** (brownfield). The code exists. You record it as it is,
  then turn rules on one at a time.

A page names a model in one of five ways: the code of today, the target (the reference
model), a step of the timeline, a git revision, or a model file (`.xmi` or `.json`). The
**Diagrams** page shows one model, or the change between two. The **Checks** page runs the
rules on one model against another.

Each task of the CLI has a place in the viewer:

| Task | Where | The command it runs |
|---|---|---|
| Open a project | Home: **This folder**, **Open a folder** (with **Browse…**), **Recent folders** | `cdec ui parse PATH` |
| Open a model file, or compare two model files | Home: **Open a model file** | `cdec diff-xmi` |
| Set up a project | **Project** | `cdec init` |
| Fold the files of an older cdec into `rules.yaml` | **Project** | `cdec init --migrate` |
| Add a rule | **Add a rule** wizard: choose, fill in a form, try it on the code of today, turn it on | an edit of `rules:`, then `cdec exceptions allow` for the issues that you accept |
| Change or remove a rule, change a severity | **Rules** | an edit of `rules:` |
| See the constraint tags of the code | **Rules**, **Constraints in the code** | none: the tags are in the model |
| Put a constraint tag on a class or a method | **Put a constraint on a class** wizard | none: it gives the line to paste, then parses the code again to confirm the tag |
| Copy the shim file | the tag wizard | `cdec update-assets --no-agents` |
| Record new locks, accept a change to locked code | **Rules**, **Locks** | `cdec check -A locks`, `cdec check -A locks --force --target …` |
| Run the check, see why it fails | **Checks**, **▶ Run cdec check** | `cdec check`, `--fail-on`, `--rules-file`, `--bypass-locks` |
| Check the code against a snapshot or a git revision | **Checks**, **More options**, **against** | `cdec check --reference FILE`, `cdec check --base-ref REV` |
| Check a target model or a snapshot with the rules | **Checks**, **More options**, **Check** | none: only the viewer does this |
| Accept one issue, or all open issues | **Checks** | `cdec exceptions allow`, `cdec check -A rules` |
| Withdraw an accepted issue, remove the stale ones | **Checks**, **Accepted issues** | `cdec exceptions remove`, `cdec exceptions prune` |
| Plan a change | **Diagrams**, **Edit**, **Set as goal…** | `cdec reference set` |
| Show a model, or compare two models | **Diagrams**, **Show** and **compared with** | `cdec diff`, `cdec diff-vs-xmi`, `cdec diff-xmi`, `cdec reference show` |
| See the code against the goal | **Timeline**, **The code of today** | `cdec reference show` |
| See the rules that were on at each step | **Timeline** | `cdec history` |
| Record progress | **Timeline**, **Record a checkpoint…** | `cdec history add` |
| Accept the code as the reference | **Accept the code as the reference** wizard | `cdec check -A reference` |
| Run the check in CI, set up a coding agent | **Run the check automatically** wizard | writes `cdec-ci.sh` / `cdec-ci.bat`; shows the CI, pre-commit, hcm and MCP texts |

A wizard writes nothing before its last step. The **Add a rule** wizard shows what the rule
reports before it turns the rule on, and can accept those issues in the same step. `cdec`
does not change source code: the tag wizard gives the exact line for your language and
opens the file.

The steps below do the same work from the command line.

### 1. Look at the class diagram

```bash
cdec ui parse src
```

This parses `src/`, starts the viewer at http://127.0.0.1:8765, and opens the class
diagram in your browser. `cdec` detects the language. To set it, add `--lang python`.

In the viewer, use the class list to search, show, hide and isolate classes. Click a class
to centre the canvas on it. Press `Ctrl+C` in the terminal to stop the server.

### 2. Create the project config

```bash
cdec init --lang python --source src
```

This writes `.cdec/rules.yaml` (the settings and the rules) and `.cdec/reference.xmi` (a
snapshot of the current architecture). Commit the `.cdec/` folder. The rule list is empty,
so `cdec check` enforces nothing yet.

### 3. Propose a new constraint on the diagram

Export the architecture as a JSON model that you can edit:

```bash
cdec parse src --lang python --out target.json
```

Open `target.json`, find the class, and add a constraint tag to its `rules` list. This
example declares that nothing may subclass `Invoice`:

```json
{
  "name": "Invoice",
  "qualified_name": "myapp.domain.Invoice",
  "rules": [{ "name": "sealed" }],
  ...
}
```

You can also edit the model in the browser. Click **Edit**, open the **Code** panel,
edit the JSON, and click **Save .json**.

Show the proposal in the viewer, as a diff against the current code:

```bash
cdec propose target.json --focus myapp.domain.Invoice
```

Green shows what the code must add. Red shows what the code must remove. Edit
`target.json` again and run `cdec propose` again: the open browser tab refreshes in place.
When the team agrees, lock the proposal as the target architecture:

```bash
cdec reference set target.json      # writes .cdec/reference.xmi
```

To make the tags in the reference binding, add this rule to `.cdec/rules.yaml`:

```yaml
rules:
  - id: agreed-tags
    type: frozen-rules
    severity: error
```

### 4. Run the check

```bash
cdec check
```

The code does not carry the `@sealed` tag yet, so the check fails with exit code 1:

```
[agreed-tags] (error)
  - [V-34FFDDA4] myapp.domain.Invoice — myapp/domain/invoice.py:12: architectural tag @sealed on 'myapp.domain.Invoice' was removed.

Summary: 1 error(s), 0 warning(s).
```

Every issue starts with a stable key. To accept one issue, give the key and a reason:

```bash
cdec exceptions allow V-34FFDDA4 --reason "agreed in ARCH-42"
```

Put `cdec check` in CI or in a pre-commit hook. A non-zero exit code stops the build.

### 5. Add rules in the config file

Rules that describe the architecture as a whole go in `.cdec/rules.yaml`. Each rule has
an `id`, a `type` and a `severity`. Add a `message` that tells the developer why the rule
exists and how to fix a violation:

```yaml
rules:
  - id: agreed-tags
    type: frozen-rules
    severity: error

  - id: domain-does-not-depend-on-ui
    type: forbidden-package-references
    severity: error
    from: ["myapp.domain.**"]
    to:   ["myapp.ui.**"]
    message: |
      Layering violation: '{source}' must not depend on '{target}'.
      Move the reference to the package that owns the workflow.

  - id: layering
    type: layer-dependencies     # reads the @layer tags from step 6
    severity: error
    allow:
      ui:     [domain]
      domain: []

  - id: tags-must-be-honoured
    type: tag-conformance        # checks the code against its own tags
    severity: error
```

Run `cdec check` again after each change. On an existing codebase, run
`cdec check --automatic-exceptions rules` once to accept the current violations. After
that, only new violations fail. The **Rules** page of the viewer does this for one rule at
a time: it shows what a rule reports before you turn it on. The [rules catalogue](docs/RULES_CATALOGUE.md) lists every
rule type, with its options and a passing and a failing example.

### 6. Add rules in the code with the shims

Rules about one class or one method go in the code, as tags. The tags come from a small
shim module that does nothing at run time. Copy it into the project:

```bash
cdec update-assets --lang python --no-agents     # writes cdec_rules.py
```

Put `cdec_rules.py` where your code can import it. Then tag the code:

```python
from cdec_rules import layer, sealed

@sealed
@layer("domain")
class Invoice:
    ...
```

Run `cdec check` again. The `agreed-tags` rule passes, because the code now carries the
tag from the reference. The `tag-conformance` rule now enforces the tag itself. If a class
subclasses `Invoice`, the check fails:

```
[tags-must-be-honoured] (error)
  - [F-5A5D24E3] myapp.domain.SpecialInvoice — myapp/domain/invoice.py:40: 'myapp.domain.SpecialInvoice' subclasses sealed class 'Invoice'; sealed types may not be subclassed.
```

C# uses attributes (`[Sealed]`), Julia uses macros (`@sealed`), and Lua and Odin use
comments (`---@cdec sealed`, `//@cdec sealed`). See
[the tag table](#architectural-rule-tags) for all tags in all languages.

### Next steps

- Read the [tutorial](docs/TUTORIAL.md) for the full path from the first parse to a
  gated CI pipeline.
- Freeze a function body with `@locked`. See [Implementation locks](#implementation-locks).
- Teach a coding agent the workflow. See [Agent skills (hcm bundle)](#agent-skills-hcm-bundle).
- Let a coding agent run the checks. See [Use it from a coding agent](#use-it-from-a-coding-agent-mcp).

---

## How the check works

`cdec check` is the whole gate, and `.cdec/rules.yaml` is the whole contract. Four kinds
of rule run inside it. Each kind answers a different question:

| Rule kind | `type:` | Question it answers |
| --- | --- | --- |
| **Model rules** | `no-new-classes`, `forbidden-references`, `layer-dependencies`, `frozen-rules`, … | Did the *architecture* change? (new or removed classes, forbidden dependencies, cycles, layer violations, weakened tags) |
| **Conformance** | `tag-conformance` | Does the *implementation* obey its tags? (`@no_instantiation`, `@factory`, `@immutable`, `@sealed`) |
| **Freeze** | `implementation-locks` | Did this body change **at all**? (AST digests: reformatted or moved code never trips a lock; a semantic edit does) |
| **Reference gate** | `reference-architecture` | Did *anything* structural change against the committed snapshot? |

Each kind is opt-in. They share the rule catalogue but no logic.

The `rules:` list can also go in `.cdec/rules/*.yaml`, one file per rule set. Then
`cdec check --rules-file NAME` runs a subset — for example, a fast set on every commit and
the full set before a release. Use one layout or the other, not both.

## Architectural rule tags

Python, C# and Julia tags are no-op decorators, attributes and macros from the shim. `cdec`
recognises a tag only when the shim is in scope (`from cdec_rules import …`,
`using CodeConstraints.Rules;`, `using CdecRules`), so unrelated decorators never match.

Lua has no declaration modifiers, and the Odin compiler rejects unknown `@(...)`
attributes. Both languages therefore put the tag in a comment where a decorator would go.
The `@cdec` prefix does the job of the import.

| Tag | Python | C# | Julia | Lua / Odin | Meaning |
| --- | --- | --- | --- | --- | --- |
| no-instantiation | `@no_instantiation(allow=[...])` | `[NoInstantiation(Allow = ...)]` | `@no_instantiation allow=[...]` | `@cdec no_instantiation(allow = [...])` | the body may not construct objects (except the `allow` types) |
| factory | `@factory(creates=[...])` | `[Factory(Creates = ...)]` | `@factory creates=[...]` | `@cdec factory(creates = [...])` | the only place that may build the listed types |
| immutable | `@immutable` | `[Immutable]` | `@immutable` | `@cdec immutable` | fields may not change after construction |
| sealed | `@sealed` | `[Sealed]` | `@sealed` | `@cdec sealed` | the class may not be subclassed |
| layer | `@layer("name")` | `[Layer("name")]` | `@layer "name"` | `@cdec layer("name")` | puts the class in an architectural layer |
| no-side-effects | `@no_side_effects` | `[NoSideEffects]` | `@no_side_effects` | `@cdec no_side_effects` | shown and drift-frozen (body analysis is not implemented yet) |
| locked | `@locked(reason="...")` | `[Locked(Reason = "...")]` | `@locked reason="..."` | `@cdec locked(reason = "...")` | the implementation is frozen — see [Implementation locks](#implementation-locks) |

Lua writes the comment as `---@cdec …` and Odin as `//@cdec …`. ⚠️ Julia macro arguments
are **space-separated**: `@layer "orders"` is correct, and `@layer("orders")` is a syntax
error.

The tags are part of the model. They round-trip through XMI, show as badges on the class
diagram, and take part in the diff. Three decoupled engines enforce them:

- **Model rules.** They read the model and the baseline, never the method bodies.
  `frozen-rules` fails when a tag in the baseline is removed or weakened.
  `layer-dependencies` flags forbidden references between `@layer` tags.
- **`tag-conformance`.** It re-parses the source and inspects method bodies. Detection is
  precise in C# and Odin, heuristic in Python (`allow` is the escape hatch), name-based in
  Julia, and idiom-based in Lua.
- **`implementation-locks`.** It digests the normalised AST of a `@locked` element and
  fails when that AST changes.

To see all of them in one run, try the bundled demo. Its model rules pass, and
`tag-conformance` flags one seeded body violation, so the command exits 1 on purpose:

```bash
cdec check --config examples/python_demo/.cdec --source examples/python_demo
```

## Implementation locks

A locked class or function may not change **at all**. This is stronger than the
architectural rules. Use it to pin down test logic, or an agreed sequence of steps that
nobody may quietly reorder. The rest of the codebase then adapts to the locked code.

The lock applies to the **syntax tree**, not to a range of lines. New code above a locked
function, reformatted code and edited comments change nothing. A renamed local, a swapped
operator, a new statement or two reordered steps fail the check.

**1. Declare the lock in the code.**

```python
from cdec_rules import locked

class Invoice:
    @locked(reason="settlement order agreed with finance")
    def settle(self, amount):
        tax = amount * 0.2
        return amount + tax
```

```csharp
using CodeConstraints.Rules;

[Locked(Reason = "settlement order agreed with finance")]
public decimal Settle(decimal amount) { ... }
```

**2. Turn on the rule** in `.cdec/rules.yaml`:

```yaml
  - id: frozen-implementations
    type: implementation-locks
    severity: error
```

**3. Record the digest.** `cdec check --automatic-exceptions locks` writes the digest to the
`locks:` section of the same file. Commit it.

**4. `cdec check` now enforces the lock.** There is no new CI step:

```
[frozen-implementations] (error)
  NOT EXCEPTABLE: a frozen implementation changes only via
  `cdec check --automatic-exceptions locks --force`.
  - [L-3D246C33] Invoice.settle — billing.py:6: 'Invoice.settle' is a frozen
      method and its implementation changed.
      Lock reason: settlement order agreed with finance
      Locked by: alice on 2026-08-02T10:15:00+00:00
      Revert the change, or ask a lead to approve a re-baseline with
      `cdec check --automatic-exceptions locks --force`.
```

Five conditions fail the check: the body **changed**, the element was **removed**, the
`@locked` tag was deleted (**unlocked**), a tag has no recorded digest (**missing**), or the
digest algorithm changed (**algo-mismatch**). The last one is reported separately, so an
upgrade never looks like tampering.

### Lock code without a tag

To freeze code that you cannot tag, such as a whole test package, give the rule
qualified-name globs:

```yaml
  - id: frozen-implementations
    type: implementation-locks
    severity: error
    include_docstrings: false    # true: docstrings and /// comments count as implementation
    targets:
      - "tests.**"               # every class and function under tests/ is frozen
```

### Keep re-baselining a lead-only action

Anybody can safely run `cdec check --automatic-exceptions locks`. It **adds** locks for new
tags. It never overwrites the digest of a changed implementation, and it never drops an
entry whose tag was deleted. To accept a change, add `--force`:

```bash
cdec check --automatic-exceptions locks --force
cdec check --automatic-exceptions locks --target Invoice.settle --force   # one element only
```

Without `--target`, `--force` accepts each lock that changed. With it, one approval
accepts one change. Only this command rewrites the `locks:` section of `.cdec/rules.yaml`. Put the file behind
a CODEOWNERS entry, and a change to frozen code becomes a reviewed, lead-approved event.
For the same reason, `cdec exceptions allow` refuses an `L-` key, and
`--automatic-exceptions rules` does not accept one.

To ship without a re-baseline, bypass the locks explicitly:

```bash
cdec check --bypass-locks --bypass-reason "hotfix #42"   # or CDEC_LOCK_BYPASS=1
```

A bypassed run prints a banner, still collects every violation, and sets
`summary.bypassed` in `--json-out`. Reject that flag in CI, so that a bypass is always a
deliberate and visible act.

## The review loop: accept known violations

A rule that can only say no gets switched off. `cdec` gives a recorded, reviewable and
revocable way to say "this one is fine":

```bash
cdec check --log-out check.log
#   [no-new-classes] (error)
#     - [V-DD3EA5B2] animals.Cat — animals/cat.py:1: New class 'animals.Cat' was added.

#  …add [ALLOW: agreed in ARCH-42] to the lines that you accept…
cdec exceptions patch --file check.log     # writes .cdec/rules.yaml, with the reason

# or, for one known key:
cdec exceptions allow V-DD3EA5B2 --reason "agreed in ARCH-42"
```

A key is a hash of *what* the issue is (engine, rule, element, detail), never of *where*
it is. An exception therefore survives reformatted and moved code, and the same code
always gives the same key. An agent can run `cdec check --format json`, decide, and call
`cdec exceptions allow <key>` without parsing prose.

Other subcommands: `review`, `remove`, `list`, `prune`. See
[Accepting known violations](docs/CLI_REFERENCE.md#24-accepting-known-violations-cdec-exceptions).

## The project history

`cdec` records the journey of the architecture in `.cdec/history/`. Commit the folder. Each
entry is a model file (`.xmi`) and a note file (`.yaml`) with the title, the reason, the
author, the commit, and the rules in force.

| Entry | Meaning | Written by |
|---|---|---|
| `start` | The architecture when the journey began. | `cdec init` |
| `goal` | A target model that the team agreed on. | `cdec reference set`, **Set as goal** in the viewer |
| `checkpoint` | The code at one moment. | `cdec history add`, `cdec check --automatic-exceptions reference` |

```bash
cdec reference set target.json --title "Split billing from orders" -m "Orders must not know tax rules."
# …work…
cdec history add "Receipt moved to billing" -m "Tax rules are next."
cdec history                                   # list the entries
```

While a goal is open, each checkpoint records the distance to it: the classes to build, the
classes to change, and the classes that are not in the plan. The **Timeline** page of the
viewer shows each entry on the diagram and plays the entries in order. A rule that the
viewer turns on, changes or removes is an entry too. To turn the history
off, set `history: false` in `.cdec/rules.yaml`.

## Agent skills (hcm bundle)

`cdec` ships a bundle for [hcm](https://github.com/fleskovar/harness_config_manager), the
harness config manager. The bundle tells a coding agent how to work in a project that
`cdec` gates. hcm installs it into Claude Code, GitHub Copilot, OpenCode, Reasonix and Pi.

With the bundle, the agent plans the architecture first. Each work plan starts with an
analysis of the class hierarchy and of its constraints. The agent then proposes the
changes as a UML JSON model and shows it with `cdec propose`. It writes the implementation
only after a senior developer approves the proposal.

| Resource | Name | What it gives the agent |
| --- | --- | --- |
| Context section | `code-constraints` | The rules that apply in each session: plan first, run the gate, do not weaken a constraint. |
| Skill | `cdec-architecture-first` | The work-plan procedure: analyse, model, propose, wait for approval, lock, implement. It includes a plan template. |
| Skill | `cdec-architecture-loop` | The propose → review → lock loop, and the JSON model format. |
| Skill | `cdec-guardrails` | Each rule type and each tag from the [rules catalogue](docs/RULES_CATALOGUE.md), with a cookbook of patterns: layers, ports and adapters, factory, value object, frozen implementation. |
| Skill | `cdec-gate` | How to run `cdec check`, read its report, and resolve a failure without a weaker rule. |
| Subagent | `cdec-architect` | An architect that writes the proposal and its guardrails. It does not approve its own proposal. |
| Command | `/cdec-plan` | Writes an architecture-first work plan for a change, and stops for the review. |

### Install the bundle

**1. Install hcm.** This needs Node.js:

```bash
npm install -g harness-config-manager
```

**2. Register the bundle.** `cdec` gives hcm the bundle that ships in the package:

```bash
cdec hcm init
```

**3. Install it into a project.** Run this in the root of the project:

```bash
hcm install code-constraints -t claude-code
```

For a different harness, change `-t`. `hcm targets` lists the harnesses, and `-t all`
installs into each one. To install the bundle for all your projects, add `-s user`.

The bundle does not copy the language shim. To get the shim, run
`cdec update-assets --lang python --no-agents`. See
[step 6 of the quick start](#6-add-rules-in-the-code-with-the-shims).

### Update the bundle

After you upgrade `code-constraints`, run this in each project that has the bundle:

```bash
cdec hcm update
```

The command registers the new bundle, then runs `hcm update code-constraints` in the
current folder. It sends its options to `hcm update`, for example
`cdec hcm update -t claude-code --no-prompt`.

To remove the bundle, run `hcm uninstall code-constraints -t claude-code` in the project,
then `hcm registry remove code-constraints`.

### Develop the bundle

The bundle is in `src/code_constraints/cli/_assets/hcm_bundle/`. From an editable install
(`pip install -e .`), register the working copy:

```bash
cdec hcm init --dev
```

hcm then reads the folder in place. After each edit, run `hcm update code-constraints` in
a test project. Check the bundle with `hcm validate` and `hcm refs check --path`. Keep the
`version` in `hcm.yaml` equal to the package version.

## Use it from a coding agent (MCP)

Any MCP-capable harness (Claude Code, Cursor, VS Code, Windsurf, Zed) can run `cdec` as a
stdio server. The agent then calls the engines as tools and reads structured JSON:

```bash
pip install "code-constraints[mcp]"
```

```json
{
  "mcpServers": {
    "code-constraints": { "type": "stdio", "command": "cdec-mcp", "args": [] }
  }
}
```

Put this in `.mcp.json` at the repository root, or in the equivalent file for your harness
(see the [MCP guide](docs/MCP.md)). The agent gets `cdec_check` for the gate,
`cdec_issues` and `cdec_allow` for the review loop, and `cdec_propose` and
`cdec_reference_set` for the design loop. The issue keys are the same as the keys that the
CLI prints, so an agent and a person can share one workflow.

## Interactive viewer

`cdec ui` starts the viewer at http://127.0.0.1:8765 and opens it in the browser. The home
page offers the folder that the command ran in, the recent folders, a folder browser and
a model file. `cdec ui parse [PATH]` opens the class diagram of a codebase directly. Add
`--no-browser` to start the viewer only.

The viewer keeps your work in a `.cdec_cache/` folder. It creates the folder in the
directory where you start `cdec ui`, and the folder ignores itself in git.

- **Recent paths**: the first section of the home page lists the paths you opened from this
  folder, most recently used first. You do not have to type a path again.
- **Views**: each path has views. A view is the state of the canvas: the diagram, the
  visible elements, their positions and the display options. Open a view to continue it,
  or select **New view** to start `Untitled 1`, `Untitled 2`, and so on.
- **Automatic save**: the viewer saves the open view while you work. You do not have to
  name it first. To give it a name, select the pencil next to the view name in the header,
  type the name in place, and press Enter or select **OK**. Escape cancels. The home page
  list has the same pencil.
- **Language**: when you type a path, the viewer finds the language from the files and
  sets the dropdown. You can change it.

`cdec ui parse [PATH]` continues the view that the path was last seen in.

A view in `.cdec_cache/` is local to your machine. The **Shared views** in the left panel
are a different thing: you save them by name to `.cdec/views/`, and you commit them for
the team.

The class diagram gives you:

- **Class tree**: classes grouped by package and by kind, with search and a visibility
  checkbox on each package, kind and class. Click a class to centre the canvas on it.
- **Inspector**: a floating panel with the details and the related classes of the
  selected class.
- **Toolbar**, in three groups:
  - **Visibility**: the **Display** menu (members, relationship lines, level of detail),
    and **Show all** / **Hide all** for the classes or for one kind of line.
  - **Explore**: **Isolate** shows only the selected class. **↑ upstream** and
    **↓ downstream** reveal one ring of neighbours of the selection, and **−** hides it
    again. Press **a** first to reveal from every visible class. The arrows
    follow the canvas: **↓ downstream** reveals the derived classes and the referenced
    classes, **↑ upstream** reveals the base classes and the classes that hold a
    reference. Each reveal runs the auto-layout again. **Step back**
    undoes the last ring. **Inspect edge** opens the two classes of the selected line.
  - **Layout**: **Re-layout** runs the auto-layout again over the visible classes.
- **Right click** on an element opens a menu:
  - **Hide** and **Focus** do the same as the **h** and **f** keys. They work on the whole
    selection when the element is part of it.
  - **Reveal in file explorer** opens the file manager on the file that declares the class.
  - **Open in editor** opens that file in VS Code, at the line of the class, when VS Code
    is installed. Without VS Code, it uses the application your desktop has for the file
    type. On Windows the viewer does not open a file that Windows would run (a `.py` file,
    for example) unless an editor is registered for it. To use a different editor, set
    `CDEC_EDITOR` before you start `cdec ui`, for example `vim +{line} {file}`.

  The two file actions run on the machine that runs `cdec ui`, and only for a request
  from that machine.
- **Keyboard**, on the class and package canvas. The **Keys** menu of the toolbar shows
  this list. A click on a canvas element selects it and does not move the view.
  - **Shift + click** adds an element to the selection, or takes it out. **↑ upstream**,
    **↓ downstream** and the keys below then work on every selected element.
  - **a** selects every visible element. **Esc** clears the selection.
  - **Tab** selects the next element on the same level: the visible elements that have the
    same parent. **Shift + Tab** selects the previous one. Hold **Tab** and press **a** to
    select the whole level.
  - A double tap on **Tab** changes "follow": Inheritance, References, All.
  - **w** moves the selection upstream and **s** moves it downstream. They first reveal the
    elements that are hidden there. With one element selected, the selection moves to one
    element. With many elements selected, it moves to the whole next level.
  - **f** fits the view on the selection.
  - **h** hides the selection. Press **a** and then **h** to clear the canvas.
  - **l** runs the automatic layout again.
  - **Ctrl + c** copies the selection as text for a document. One element gives
    `Namespace.Class (path/to/File.cs)`. Many elements give a Markdown list in the order
    of the canvas, left to right. While "follow" is Inheritance, the list is nested: each
    class is four spaces below its base type.

    ```
    - billing.Invoice (billing/invoice.py)
        - billing.CreditNote (billing/credit_note.py)
    - billing.Receipt (billing/receipt.py)
    ```

    Only a line between two selected classes makes a level. A class with two selected
    base types is in the list below each of them.
  - **Space** moves to the search box of the left panel.

  While an element is selected, **Tab** belongs to the canvas. Press **Esc** first to move
  the keyboard focus with **Tab**.
- **Architecture** menu: **Layers & rules** shows the layers and their allowed
  dependencies. **Set as reference** saves the current diagram as `.cdec/reference.xmi`
  after a confirmation.
- **Saved views**: export the visible set, positions and selection to a `.cdecview.json`
  file, and import it later.
- **Diff walkthrough**: for a diff, a Prev/Next change list moves the camera to each
  changed class.
- **Rule badges** on tagged classes and operations. Hover a badge to see the rule and its
  parameters.

Package, activity and sequence diagrams use the same interactive canvas.

The **editor** (click **Edit**) keeps the classes that you filtered in the view. It
supports:

- **Visual edits**: add classes, drag between nodes to draw inheritance and associations,
  add attributes and methods, double-click to edit, and press **Delete** to remove a class.
- **Code panel**: the model as editable JSON beside the canvas. An edit on one side updates
  the other. This is the same JSON that `cdec convert` and `cdec propose` use.
- **Live diff**: load a baseline (**Baseline…**, or **Architecture ▸ Compare with
  reference**), and the canvas shows added, removed and changed elements while you edit.
- **Open and save** as `.xmi` or `.json`.

## Embedded diagram tags

Mark code regions for activity and sequence diagrams with XML-style comment tags. This
works in Python and C# only:

```python
# <uml-activity name="checkout" granularity="control-flow">
def checkout(cart):
    if cart.is_empty():
        return
    pay(cart)
# </uml-activity>
```

```csharp
// <uml-sequence name="login" root="HandleLogin">
public void HandleLogin(User u) {
    _auth.Verify(u);
    _session.Start(u);
}
// </uml-sequence>
```

Supported tags: `<uml-class />`, `<uml-activity name="..." granularity="control-flow|statement|calls">`,
`<uml-sequence name="..." root="...">`.

## Supported languages

| Language   | `--lang`     | Class / package | Rule tags | `tag-conformance` | `implementation-locks` | Activity / sequence |
| ---------- | ------------ | --------------- | --------- | ----------------- | ---------------------- | ------------------- |
| Python     | `python`     | ✅ | decorators          | ✅ | ✅ | ✅ |
| C#         | `csharp`     | ✅ | attributes          | ✅ | ✅ | ✅ |
| Odin       | `odin`       | ✅ | `//@cdec` comments  | ✅ | ✅ | — |
| Lua        | `lua`        | ✅ | `---@cdec` comments | ✅ | ✅ | — |
| Julia      | `julia`      | ✅ | macros              | ✅ | ✅ | — |
| TypeScript | `typescript` | ✅ | —                   | — | — | — |
| Svelte 5   | `svelte`     | ✅ | —                   | — | — | — |

## Command overview

Each command also runs as `python -m code_constraints.cli <command>`. The
[CLI reference](docs/CLI_REFERENCE.md) documents every option.

| Command | What it does |
| --- | --- |
| `cdec` | Interactive session: setup, viewer, checks, CI scripts. |
| `cdec init` | Scaffold `.cdec/rules.yaml` and a reference snapshot. `--migrate` converts the old per-concern files. |
| `cdec check` | The gate: run every rule and exit non-zero on a violation. |
| `cdec check -A rules\|locks\|reference\|all` | Accept the current state instead of a failure (`--automatic-exceptions`). `--target GLOB` limits `-A locks` to the named elements. |
| `cdec exceptions …` | Accept, list, remove and prune individual issues by key. |
| `cdec locks` | Show what is lockable and what is locked (read-only). |
| `cdec ui` / `cdec ui parse` | Start the web viewer / open the class diagram of a codebase. |
| `cdec parse` | Parse source into a model file (`.xmi` or `.json`). |
| `cdec convert` | Convert a model between XMI 2.1 and editor JSON. |
| `cdec propose` | Show a proposed model in the viewer, as a diff. `--against source\|reference\|none`. |
| `cdec reference set` / `show` | Lock a model as the reference / show the code against it. |
| `cdec diff` / `diff-vs-xmi` / `diff-xmi` | Diff two git revisions / source against a model / two models. |
| `cdec update-assets` | Copy the language shim and the bundled Claude agents into a project. |
| `cdec hcm init` / `cdec hcm update` | Register the agent bundle with hcm / refresh it after an upgrade. |
| `cdec update` | Update a standalone install in place. |

The agent configuration ships as an hcm bundle. See
[Agent skills (hcm bundle)](#agent-skills-hcm-bundle). `cdec update-assets` can also copy
an earlier set of Claude Code agents (`cdec-architect`, `oop-refactor-architect`) and a
skill (`cdec-architecture-loop`) into `.claude/`. If you use the bundle, pass `--no-agents`,
because two of those files have the same names as files of the bundle.

## Documentation

| Document | What it is |
| --- | --- |
| **[Tutorial](docs/TUTORIAL.md)** | **Start here.** From the first parse to a gated CI pipeline, with runnable examples against the bundled demos. |
| **[User manual](docs/USER_MANUAL.md)** | How to use the web app, step by step, for a greenfield project and for a brownfield project. |
| **[Rules & constraints catalogue](docs/RULES_CATALOGUE.md)** | Every rule type and every source tag, with options, a sample configuration, and a passing and a failing example. |
| [CLI reference](docs/CLI_REFERENCE.md) | Every command and option, the `.cdec/` files, exit codes and CI/CD recipes. |
| [MCP server](docs/MCP.md) | Install, per-harness configuration and the tool list. |
| **[Per-language guides](docs/languages/README.md)** | [Python](docs/languages/PYTHON.md) · [C#](docs/languages/CSHARP.md) · [Odin](docs/languages/ODIN.md) · [Lua](docs/languages/LUA.md) · [Julia](docs/languages/JULIA.md) · [TypeScript & Svelte](docs/languages/TYPESCRIPT-SVELTE.md) |
| [Examples](examples/README.md) | The demo projects for every language. |
| [Installers](install/README.md) | Standalone install scripts, configuration and uninstall steps. |

---

## Other ways to install

**Standalone installer.** This clones the repository with `git`, manages its own virtualenv,
builds the web frontend, and puts `cdec` on your `PATH`. It requires `git`, Python 3.11+
and Node 20+. To update later, run `cdec update` or run the installer again.

```bash
# Linux / macOS
curl -fsSL https://raw.githubusercontent.com/fleskovar/code_constraints/main/install/install.sh | bash
```

```powershell
# Windows (PowerShell)
irm https://raw.githubusercontent.com/fleskovar/code_constraints/main/install/install.ps1 | iex
```

**From a built wheel:**

```bash
make dist
pip install dist/code_constraints-0.1.0-py3-none-any.whl
```

The build hook (`hatch_build.py`) builds the web viewer during `make dist`, `pip install .`
and every other build, so each wheel has the viewer. This needs Node.js 20 or later.

## Development

The `Makefile` is the front door. `make help` lists every target.

```bash
make setup      # venv + editable install with dev extras + frontend build
make test       # full test suite
make verify     # ruff + mypy + pytest — run before a push
make demo       # run `cdec check` against the bundled examples
make serve      # http://127.0.0.1:8765
```

| Target | What it does |
| --- | --- |
| `make install-dev` | Editable install with dev extras. Code edits take effect immediately. |
| `make install` | Non-editable install from source into the venv. |
| `make install-pipx` | Install the `cdec` CLI globally from this checkout with `pipx`. |
| `make dist` / `make package` | Build the frontend, then the wheel and sdist in `dist/`. The wheel includes the web viewer. |
| `make check-dist` | Build, then validate the artifacts with `twine`. |
| `make frontend-check` | `svelte-check` (TypeScript). |
| `make clean` / `make distclean` | Remove build artifacts and caches / everything generated, `node_modules` included. |

To change the interpreter, the venv or the port, set them on the command line:

```bash
make setup BASE_PYTHON=python3.12 VENV=/tmp/cdec-venv
make serve PORT=9000
```

The recipes run through `sh`. On Windows, use Git Bash or another shell that has `sh` on
`PATH`.

### Frontend

```bash
cd frontend
npm install
npm run dev      # Vite dev server with HMR, proxies /api to :8765
npm run build    # production build into frontend/dist/
npm run check    # svelte-check (TypeScript)
```

Run `cdec ui` and `npm run dev` together. Vite sends `/api/*` to the backend.
`cdec ui` serves the built bundle in `frontend/dist/`. After a frontend edit, run
`npm run build` again, or the server continues to show the old build.
