2. Architecture
codeknife arch is the architecture blade. It flags shallow modules, oversized files and functions, complex or deeply nested functions, long parameter lists, boolean flag parameters, wide directories, low-cohesion types, helper chains that split one function into steps, tangled items, module dependency cycles, fields used outside their owning module, and imports that break the layer rules in arch.toml. Use it when you want structural feedback on a repository, or to enforce which directories may import which.
Quick example
Section titled “Quick example”This demo crate has a domain module and an infra module that import each other, and an arch.toml that forbids domain from importing infra:
archdemo/ Cargo.toml arch.toml src/lib.rs pub mod app; pub mod domain; pub mod infra; src/domain/mod.rs use crate::infra::Db; ... db.pool_size + 1 src/infra/mod.rs use crate::domain::run_domain; pub struct Db { pub pool_size: usize } ... src/app/mod.rs pub fn configure(verbose: bool, dry_run: bool, a: u32, b: u32, c: u32, d: u32) -> u32 { ... }[[layers]]name = "domain"paths = ["src/domain/**"]
[[layers]]name = "infra"paths = ["src/infra/**"]
[[deny]]from = "domain"to = "infra"reason = "Domain must not depend on infrastructure"codeknife arch --no-cache --format humanerror[CK_ARCH_MODULE_CYCLE]: module dependency cycle across 2 modules: archdemo::domain <-> archdemo::infra --> src/domain/mod.rs:1 (archdemo::domain -> archdemo::infra) = note: src/domain/mod.rs:1 — imports `crate::infra::Db` = note: src/infra/mod.rs:1 — imports `crate::domain::run_domain` ┌─▶ archdemo::domain │ ┃ src/domain/mod.rs:1 imports `crate::infra::Db` │ ▼ │ archdemo::infra │ │ src/infra/mod.rs:1 imports `crate::domain::run_domain` └─────┘ = fix: Invert the dependency or extract shared types/traits into a lower-layer module so imports form a DAG. Cheapest cut: `archdemo::domain` -> `archdemo::infra` (1 site(s)).
warning[CK_ARCH_FIELD_LEAK]: `Db::pool_size` is accessed outside its owning module (1 places across 1 modules) --> src/infra/mod.rs:4 (Db::pool_size) = note: src/domain/mod.rs:4 — accesses `Db.pool_size` Db pool_size ◀━━ 1 archdemo::domain = fix: Encapsulate internal representation behind behavior-level methods on the owning type (deep module).
warning[CK_ARCH_DEEP_NESTING]: `configure` nesting depth is 6 (limit 4) --> src/app/mod.rs:9-29 (archdemo::app::configure) = fix: Use guard clauses / early returns to reduce nesting depth.
warning[CK_ARCH_COGNITIVE_COMPLEXITY]: `configure` cognitive complexity is 23 (limit 15) --> src/app/mod.rs:9-29 (archdemo::app::configure) = fix: Flatten nested conditionals using early returns, match tables, or domain helpers.
warning[CK_ARCH_TOO_MANY_PARAMS]: `configure` takes 6 parameters (limit 5) --> src/app/mod.rs:9-29 (archdemo::app::configure) = fix: Group cohesive parameters into an options or domain context struct.
warning[CK_ARCH_BOOL_TRAP]: `configure` has 2 boolean flag parameters --> src/app/mod.rs:9-29 (archdemo::app::configure) = fix: Replace boolean flags with explicit enum variants or separate named functions.
error[CK_ARCH_LAYER_VIOLATION]: forbidden dependency `src/domain/mod.rs` -> `src/infra/mod.rs` (Domain must not depend on infrastructure) --> src/domain/mod.rs:1 (crate::infra::Db) = fix: Invert dependency or respect arch.toml rule (`domain -> infra`).
codeknife arch: FAIL (4 files, 2 errors, 5 warnings, 0 info, 2ms)The exit code is 1 because there are errors and warnings. The same run in agent format:
codeknife arch --no-cache --format agentCODEKNIFE arch status=fail files=4 errors=2 warnings=5 infos=0 elapsed_ms=6[1] ERROR CK_ARCH_MODULE_CYCLE src/domain/mod.rs:1-1 sym=archdemo::domain -> archdemo::infra impact=85 | module dependency cycle across 2 modules: archdemo::domain <-> archdemo::infra | fix: Invert the dependency or extract shared types/traits into a lower-layer module so imports form a DAG. Cheapest cut: `archdemo::domain` -> `archdemo::infra` (1 site(s)).[2] ERROR CK_ARCH_LAYER_VIOLATION src/domain/mod.rs:1-1 sym=crate::infra::Db impact=85 | forbidden dependency `src/domain/mod.rs` -> `src/infra/mod.rs` (Domain must not depend on infrastructure) | fix: Invert dependency or respect arch.toml rule (`domain -> infra`).[3] WARNING CK_ARCH_COGNITIVE_COMPLEXITY src/app/mod.rs:9-29 sym=archdemo::app::configure impact=70 | `configure` cognitive complexity is 23 (limit 15) | fix: Flatten nested conditionals using early returns, match tables, or domain helpers....| Flag | Effect |
|---|---|
--layers <PATH> |
Read layer rules from this TOML file instead of arch.toml. The file fully replaces arch.toml for this run. |
--infer |
Infer [[layers]] and [[deny]] rules from the current import graph and print them as TOML. No findings are produced. See Inferring layers. |
--write |
With --infer, also write the inferred TOML to arch.toml (or to the --layers path). Has no effect without --infer. |
The global flags --path, --format, --strict, --changed, --since, --no-cache and --max-items also apply. See the CLI Reference and Paths, Excludes & Changed Scope.
--strict lowers some thresholds (see the rule table). With --changed, only findings that touch changed files are kept; each check below says what “touch” means for it.
The [blades] arch = false switch in codeknife.toml only affects codeknife check and the other commands that run the whole static suite. codeknife arch always runs the blade. Threshold keys under [thresholds] apply to both.
Every rule in this blade has blade arch. The full catalogue across blades is in the Rule Catalogue.
| Rule ID | Severity | Triggers when | Config key (default) | --strict |
|---|---|---|---|---|
CK_ARCH_MODULE_CYCLE |
error | Two or more modules form a dependency cycle | none | no change |
CK_ARCH_TANGLE |
warning | Two or more items depend on each other in a cycle, across 2+ modules or with more than held_in_mind items |
held_in_mind (7) |
no change |
CK_ARCH_LAYER_VIOLATION |
error | An import breaks a deny, allow_only or private_internals rule |
arch.toml |
no change |
CK_ARCH_FIELD_LEAK |
warning | A field is read or written from outside its owning module | none | no change |
CK_ARCH_SHALLOW_MODULE |
warning | A module exposes more than held_in_mind functions to other modules and exposes at least as many as it hides |
held_in_mind (7) |
no change |
CK_ARCH_WIDE_DIR |
warning | A directory has more than max_dir_members entries |
max_dir_members (15) |
no change |
CK_ARCH_LONG_FILE |
error | Production lines exceed max_file_lines |
max_file_lines (1000) |
400 |
CK_ARCH_LONG_FILE |
warning | Production lines exceed warn_file_lines (but not max_file_lines) |
warn_file_lines (500) |
no change |
CK_ARCH_LONG_FN |
warning | Function lines exceed max_fn_lines |
max_fn_lines (60) |
40 |
CK_ARCH_DEEP_NESTING |
warning | Nesting depth exceeds max_nesting |
max_nesting (4) |
3 |
CK_ARCH_COGNITIVE_COMPLEXITY |
warning | Cognitive complexity exceeds max_cognitive_complexity |
max_cognitive_complexity (15) |
10 |
CK_ARCH_TOO_MANY_PARAMS |
warning | Parameter count exceeds max_params |
max_params (5) |
4 |
CK_ARCH_BOOL_TRAP |
warning | Boolean parameter count is at least max_bool_params |
max_bool_params (2) |
no change |
CK_ARCH_LOW_COHESION |
warning | A type’s methods split into disjoint LCOM4 clusters | none (gated by warn_file_lines) |
no change |
CK_ARCH_FAKE_SPLIT |
warning | Three or more private 4+ parameter helpers call each other in a single-caller chain | none | no change |
All config keys live under [thresholds] in codeknife.toml (see codeknife.toml). --strict takes the smaller of your configured value and the strict value, so it never loosens a threshold.
No rule in this blade has an autofixer. The Autofix Engine does not change any CK_ARCH_* finding.
How each check works
Section titled “How each check works”The function-level metrics (lines, cognitive complexity, nesting, parameter and boolean parameter counts) come from the language adapters. How Metrics Are Computed explains them. It also covers two counting errors that affect CK_ARCH_TOO_MANY_PARAMS: Python * and / markers are counted as parameters, and Go variadic parameters are not counted. The module graph, imports and references come from Import Resolution.
Module depth (CK_ARCH_SHALLOW_MODULE)
Section titled “Module depth (CK_ARCH_SHALLOW_MODULE)”The depth check compares what a module shows to other modules with what it hides. It does not compute a ratio.
- For each module, count its working callables: functions and methods that are not tests, not trait implementations and not thin wrappers. A thin wrapper is a function whose body is a single field access or a single call that forwards to another function.
- shown is the number of distinct working callables in the module that some other module uses. Uses go through wrappers, so a call to a wrapper counts as a use of the function it forwards to.
- hidden is the total minus shown.
- The module is flagged when
shown > held_in_mindandshown >= hidden.
With the default held_in_mind = 7, a module whose 8 functions are all called from elsewhere is flagged:
warning[CK_ARCH_SHALLOW_MODULE]: shallow module `shapedemo::util` exposes 8 working functions while hiding only 0 (limit 7) --> src/util/mod.rs:1 (shapedemo::util) shows │ 8 ████████████████████████████████████ hides │ 0 free_functions │ 8 ████████████████████████████████████ = fix: Consolidate narrow single-purpose exports into deeper operations that hide internal sequencing.The bars below shows and hides count the uses from other modules, grouped by the owning type of the function used, with free_functions for functions that have no owner. They count every use, so a function called from three places adds 3. The finding points at line 1 of the first file of the module. The metric value is the shown count. Workspace nodes are never flagged. With --changed, a module is checked only if one of its files changed.
File size (CK_ARCH_LONG_FILE)
Section titled “File size (CK_ARCH_LONG_FILE)”Test files are skipped. For Rust files, production lines stop at the first line whose trimmed text is exactly #[cfg(test)]; the count is the number of lines above it. For every other file, it is the file’s total line count.
- More than
max_file_linesproduction lines: error, impact 75, message(limit N). - Otherwise more than
warn_file_lines: warning, impact 45, message(recommended <= N).
warning[CK_ARCH_LONG_FILE]: file `src/big.rs` has 506 production lines (recommended <= 500) --> src/big.rs:1-506 (src/big.rs) src/big.rs │ 506 ████████████████████████████████████ = fix: Consider splitting independent responsibilities before this file becomes monolithic.The same file under --strict:
[1] ERROR CK_ARCH_LONG_FILE src/big.rs:1-506 sym=src/big.rs impact=75 | file `src/big.rs` has 506 production lines (limit 400) | fix: Split this file along domain boundaries into cohesive modules.Function checks
Section titled “Function checks”Each function or method that is not a test is compared with five thresholds. Each one that is crossed produces its own warning on the function’s span.
| Rule | Comparison | Impact |
|---|---|---|
CK_ARCH_LONG_FN |
lines > max_fn_lines |
60 |
CK_ARCH_DEEP_NESTING |
max nesting > max_nesting |
50 |
CK_ARCH_COGNITIVE_COMPLEXITY |
cognitive complexity > max_cognitive_complexity |
70 |
CK_ARCH_TOO_MANY_PARAMS |
parameter count > max_params |
45 |
CK_ARCH_BOOL_TRAP |
boolean parameter count >= max_bool_params |
40 |
Note that CK_ARCH_BOOL_TRAP uses “at least”, while the others use “more than”. With the default of 2, a function with two bool parameters is flagged. With --changed, only functions in changed files are checked.
warning[CK_ARCH_LONG_FN]: `long_one` is 66 lines (limit 60) --> src/big.rs:1-66 (shapedemo::big::long_one) = fix: Extract meaningful phase-level abstractions rather than mechanical line cuts.Directory fan-out (CK_ARCH_WIDE_DIR)
Section titled “Directory fan-out (CK_ARCH_WIDE_DIR)”For each directory, CodeKnife counts the analysed source files directly inside it plus the subdirectories that contain analysed files. Other files (Markdown, config, images) do not count. A directory with more than max_dir_members entries is flagged at line 1 of the directory path, with impact 35. The repository root is shown as ., and only files directly in the root count toward it. With --changed, a directory is checked only if a changed file lies under it.
warning[CK_ARCH_WIDE_DIR]: wide directory `src/wide` has 17 items (limit 15) --> src/wide:1 (src/wide) src/wide │ 17 ████████████████████████████████████ = fix: Group related files into cohesive domain subdirectories so each directory stays scannable.Cohesion (CK_ARCH_LOW_COHESION, LCOM4)
Section titled “Cohesion (CK_ARCH_LOW_COHESION, LCOM4)”For each type, CodeKnife collects its methods, skipping trait implementations, tests, and builder or accessor names: new, default, from, into, and names starting with with_, set_, get_ or is_.
The type is checked only when all of these hold:
- it has at least 2 fields,
- it has at least 4 such methods,
- its file has more than
warn_file_linestotal lines, or the type has at least 6 such methods.
Two methods are connected when they access the same field or when one calls the other. Each connected group is one LCOM4 cluster. The type is flagged when there are at least 4 clusters, or when at least 2 clusters contain two or more methods. The metric value is the cluster count, impact 65. The fix hint lists every cluster:
warning[CK_ARCH_LOW_COHESION]: `Service` has LCOM4 = 4 disjoint method/field clusters --> src/svc/mod.rs:1-6 (shapedemo::svc::Service) = fix: Split along natural cohesion seams: Cluster 1: methods=[load, save] fields=[cache, conn] | Cluster 2: methods=[paint, render] fields=[template] | Cluster 3: methods=[audit] fields=[] | Cluster 4: methods=[purge] fields=[]With --changed, a type is checked only if its file changed.
Anti-gaming: helper chains (CK_ARCH_FAKE_SPLIT)
Section titled “Anti-gaming: helper chains (CK_ARCH_FAKE_SPLIT)”This check targets functions that were cut into sequential steps to get under the length limit. A function is a suspicious helper when it is a free function (not a method), private, not a test, takes 4 or more parameters, and has exactly one caller. Starting from each suspicious helper, CodeKnife follows calls to the next suspicious helper in the same module, up to 8 steps. A chain of 3 or more is reported once, on its first function, with impact 55.
warning[CK_ARCH_FAKE_SPLIT]: suspicious sequential private helper chain (step_one -> step_two -> step_three) each passing >= 4 params --> src/chain.rs:5-8 (shapedemo::chain::step_one) = fix: Do not evade function-length limits with step_1->step_2 wrappers; introduce a real cohesive type or inline trivial steps.Two other parts of the blade also resist simple workarounds:
- Thin wrappers do not count as working callables in the depth check, so adding forwarding functions does not raise the hidden count.
- The dependency graph looks through wrappers. A call to a getter that only returns a field counts as a read of that field, so the field leak check still sees it (see below).
Dependency cycles (CK_ARCH_MODULE_CYCLE)
Section titled “Dependency cycles (CK_ARCH_MODULE_CYCLE)”CodeKnife builds a module graph from two sources: every import, and every non-test reference that resolves to a symbol in another module. It ignores edges between a module and itself, and edges between a parent and a child module (by module tree ancestry or by qualified name prefix, such as demo and demo::a). Each strongly connected component with 2 or more modules is one cycle finding, with impact 85.
For the report, CodeKnife finds the shortest cycle inside the component and shows the first import or use site for each step. These sites are also listed as related spans (evidence in JSON). The fix hint names the cheapest edge to cut: the edge inside the component with the fewest import statements (or, for an edge with no imports, the fewest use sites), with ties broken by internal module order. The count is shown as (N site(s)). A three-module cycle:
error[CK_ARCH_MODULE_CYCLE]: module dependency cycle across 3 modules: layersdemo::a <-> layersdemo::b::internal <-> layersdemo::c --> src/a/mod.rs:1 (layersdemo::a -> layersdemo::b::internal -> layersdemo::c) = note: src/a/mod.rs:1 — imports `crate::b::internal::secret` = note: src/b/internal/mod.rs:1 — imports `crate::c::fc` = note: src/c/mod.rs:1 — imports `crate::a::fa` ┌─▶ layersdemo::a │ ┃ src/a/mod.rs:1 imports `crate::b::internal::secret` │ ▼ │ layersdemo::b::internal │ │ src/b/internal/mod.rs:1 imports `crate::c::fc` │ ▼ │ layersdemo::c │ │ src/c/mod.rs:1 imports `crate::a::fa` └─────┘ = fix: Invert the dependency or extract shared types/traits into a lower-layer module so imports form a DAG. Cheapest cut: `layersdemo::a` -> `layersdemo::b::internal` (1 site(s)).With --changed, a cycle is reported if any of its modules has a changed file.
Tangles (CK_ARCH_TANGLE)
Section titled “Tangles (CK_ARCH_TANGLE)”A tangle is a cycle between individual items rather than modules. CodeKnife groups each type with its methods and fields into one node, and makes a separate node for each free function, constant and route. Two nodes are linked when one uses the other (call, field access, type reference or trait implementation) outside tests. Each strongly connected component with 2 or more nodes is a candidate. It is reported when it spans more than one module, or when it has more than held_in_mind nodes. The picture lists at most held_in_mind members, followed by ... and N more coupled items.
warning[CK_ARCH_TANGLE]: tangled component: 3 items mutually depend on each other across 3 module(s) --> src/a/mod.rs:3-5 (layersdemo::a::fa) ┌─▶ layersdemo::a::fa │ ┃ src/a/mod.rs:3 mutually coupled │ ▼ │ layersdemo::b::internal::secret │ │ src/b/internal/mod.rs:3 mutually coupled │ ▼ │ layersdemo::c::fc │ │ src/c/mod.rs:3 mutually coupled └─────┘ = fix: Break mutual dependencies by introducing an orchestrator above them or decoupling shared state.With --changed, a tangle is reported if any member is in a changed file.
Field leaks (CK_ARCH_FIELD_LEAK)
Section titled “Field leaks (CK_ARCH_FIELD_LEAK)”CodeKnife looks at every non-test field read and field write whose owning type lives in a different module from the code that accesses it. Calls to field accessor wrappers count: a method whose body only returns self.field (or &mut self.field, which counts as a write) is treated as a read of that field.
An access is ignored when:
- the field is private and is accessed directly, not through an accessor wrapper,
- it is a read through an accessor whose name looks like a data utility. Exact names:
new,default,from,into,get,len,is_empty,iter,fmt,clone,eq,cmp,hash,to_string,String,Error, and any__dunder__name. Prefixes:with_,set_,get_,is_,load,parse,save,write,render,build,rebuild,create,apply,add_,from_,lookup,record,filter_,merge_.
If a field has no external write, it is also skipped when its owner is a passive data carrier:
- the owner name ends with one of
Opts,Options,Config,Args,Cli,Params,Limits,Settings,Metrics,Report,Summary,Result,Entry,Node,Span,Edge,Info,Ctx,Context,Model,Ir,Graph,Tree,Spec,Schema,Snapshot,BrieforDto, or - the owner has no non-public fields and either has fewer than 2 behaviour methods (methods whose names are not data-utility names), or has no mutating methods and at least 2 fields.
One finding is emitted per field, on the field’s declaration line, with impact 55. The metric is the number of access sites. Up to 5 sites are listed as related spans. In this example, balance is private, but the getter balance() is called from another module, so it is reported. A second getter named get_balance() is not, because get_ is a data-utility prefix:
warning[CK_ARCH_FIELD_LEAK]: `Ledger::balance` is accessed outside its owning module (1 places across 1 modules) --> src/store/mod.rs:2 (Ledger::balance) = note: src/api/mod.rs:4 — accesses `Ledger.balance` Ledger balance ◀━━ 1 leakdemo::api = fix: Encapsulate internal representation behind behavior-level methods on the owning type (deep module).With --changed, an access counts if either the accessing file or the field’s file changed.
Layer rules (CK_ARCH_LAYER_VIOLATION)
Section titled “Layer rules (CK_ARCH_LAYER_VIOLATION)”Layer rules are checked only when an arch.toml exists at the repository root, or when you pass --layers. Only import statements are checked, not other references. For each import, CodeKnife takes the importing file’s repo-relative path (from_file) and the path of the first file of the imported module (to_file). It then tests the rules in this order and stops at the first match:
[[deny]]:from_filematchesfromandto_filematchesto. The message uses the rule’sreason, orClean Architecture layer boundary violationif there is none.[[allow_only]]:from_filematchesfrom, the import is to a different module, andto_filematches none of theallowentries. The message readsoutside allow_only list for <from>.private_internals: for an import to a different module,to_filematches aprivate_internalsglob andfrom_fileis outside that glob’s owner directory. The message readscrosses into private_internals of another module.
Each violation is an error on the import line, with impact 85. With --changed, only imports in changed files are checked.
Using this arch.toml on the three-module demo above:
private_internals = ["src/b/internal/**"]
[[layers]]name = "core"paths = ["src/c/**"]
[[layers]]name = "edge"paths = ["src/a/**"]
[[deny]]from = "core"to = "edge"reason = "Core must not import edge"
[[allow_only]]from = "src/b/**"allow = ["core", "src/b/**"][2] ERROR CK_ARCH_LAYER_VIOLATION src/a/mod.rs:1-1 sym=crate::b::internal::secret impact=85 | forbidden dependency `src/a/mod.rs` -> `src/b/internal/mod.rs` (crosses into `private_internals` of another module) | fix: Depend on the owning module's public facade instead of `src/b/internal/mod.rs`.[3] ERROR CK_ARCH_LAYER_VIOLATION src/c/mod.rs:1-1 sym=crate::a::fa impact=85 | forbidden dependency `src/c/mod.rs` -> `src/a/mod.rs` (Core must not import edge) | fix: Invert dependency or respect arch.toml rule (`core -> edge`).The arch.toml format
Section titled “The arch.toml format”CodeKnife reads arch.toml from the repository root (--path). Every top-level key is optional. Unknown keys are ignored.
| Key | Type | Meaning |
|---|---|---|
layers |
array of tables | Named groups of path globs. Each needs name (string) and paths (array of glob strings). A layer does nothing on its own; it is a name you can use in deny and allow_only. |
deny |
array of tables | Forbidden import directions. Each needs from and to, and may have reason. |
allow_only |
array of tables | Import allow lists. Each needs from (string) and allow (array of strings). |
private_internals |
array of strings | Globs for directories that only their parent directory may import. |
In deny.from, deny.to, allow_only.from and each allow_only.allow entry, a value that exactly equals a layer name expands to that layer’s paths. Any other value is used as a glob. Globs are matched against repo-relative file paths such as src/domain/mod.rs, so domain/** does not match files under src/domain/. Invalid globs are skipped without an error.
For a private_internals glob, CodeKnife strips a trailing /**, /* or /, then takes the parent directory as the owner. For src/b/internal/** the owner is src/b, and only files whose path starts with src/b/ may import into it. If the owner is empty or contains *, the check compares the first path segment of both files instead.
A complete example:
private_internals = ["src/storage/internal/**"]
[[layers]]name = "domain"paths = ["src/domain/**"]
[[layers]]name = "infra"paths = ["src/infra/**", "src/storage/**"]
[[deny]]from = "domain"to = "infra"reason = "Domain must not depend on infrastructure"
[[allow_only]]from = "src/app/**"allow = ["domain", "src/app/**"]A missing required field stops every command that loads the repository, not only arch, with exit code 2:
codeknife error: parsing arch.toml: TOML parse error at line 1, column 1 |1 | [[deny]] | ^^^^^^^^missing field `to`codeknife init writes a starter arch.toml that contains only comments when none exists. See Init, Skill & Usage Spec.
Inferring layers
Section titled “Inferring layers”codeknife arch --infer proposes an arch.toml from the imports the repository already has. It prints TOML and exits with code 0. It produces no findings, and it does not look at --changed.
inferdemo/ src/lib.rs pub mod app; pub mod domain; pub mod infra; src/domain/mod.rs pub fn id() -> usize { 1 } src/infra/mod.rs use crate::domain::id; ... src/app/mod.rs use crate::infra::load; ...codeknife arch --infer --no-cache --format human# Generated by `codeknife arch --infer`
allow_only = []private_internals = []
[[layers]]name = "domain"paths = ["src/domain/**"]
[[layers]]name = "infra"paths = ["src/infra/**"]
[[layers]]name = "app"paths = ["src/app/**"]
[[deny]]from = "domain"to = "app"reason = "Inferred layer `domain` (rank 0) must not depend on `app` (rank 2)"
[[deny]]from = "domain"to = "infra"reason = "Inferred layer `domain` (rank 0) must not depend on `infra` (rank 1)"
[[deny]]from = "infra"to = "app"reason = "Inferred layer `infra` (rank 1) must not depend on `app` (rank 2)"How layers are inferred
Section titled “How layers are inferred”- Buckets. Each non-test file is put in a bucket by its path:
crates/<name>/...(at least three path segments) goes in bucket<name>with globcrates/<name>/**.src/<name>/...(at least three path segments) goes in bucket<name>with globsrc/<name>/**.- Any other path with a directory goes in a bucket named after its top-level directory, with glob
<top>/**. - Files at the repository root, and files directly in
src/orcrates/, are not bucketed. If two paths give the same bucket name (for examplecrates/core/andsrc/core/), the first glob seen is kept.
- Edges. Each import from a file in one bucket to a module in another bucket is an edge. Other references are not used.
- Ranks. Buckets with no outgoing edges get rank 0 and are removed. This repeats with rank 1, 2 and so on. Buckets left over when no bucket can be removed are given the next rank together. That includes buckets in a cycle and any bucket that depends on one.
- Layers. One
[[layers]]entry per bucket, sorted by rank and then by name. - Deny rules. For every pair of buckets where one has a lower rank than the other, a
[[deny]]forbids the lower-ranked bucket from depending on the higher-ranked one. Buckets with the same rank get no deny rule between them.
The output always contains allow_only = [] and private_internals = []. When the repository has cycles, the header carries # NOTE: lines. In this run, app only depends on infra, but it is still listed among the cyclic buckets because it depends on the domain and infra cycle:
# Generated by `codeknife arch --infer`# NOTE: cyclic buckets placed at top rank without inter-cycle deny rules: app, domain, infra# NOTE: repository currently has 1 intra-module cycle(s); inspect `codeknife arch`
deny = []allow_only = []private_internals = []
[[layers]]name = "app"paths = ["src/app/**"]...JSON output
Section titled “JSON output”With --format json or --format sarif, --infer prints a JSON object instead of TOML. It has the fields config (the inferred rules), toml (the same text as the TOML output), layers_count, deny_count and notes. When no buckets are found, notes contains fewer than two multi-file directories detected for layering. That note appears only in this JSON, not in the TOML header, and only when there are zero layers.
{ ... "layers_count": 3, "deny_count": 3, "notes": []}Writing the file
Section titled “Writing the file”--infer --write writes the TOML to arch.toml in the repository root, or to the --layers path resolved against --path. An existing file is overwritten without a prompt or backup. The command prints wrote <path> to standard error and still prints the TOML (or JSON) to standard output.
codeknife arch --path inferdemo --infer --write --no-cache --format agent > /dev/nullwrote .../inferdemo/arch.tomlOn a repository with no cycles, the inferred rules match the current imports, so a following codeknife arch run reports no layer violations:
codeknife arch --path inferdemo --no-cache --format agentCODEKNIFE arch status=pass files=4 errors=0 warnings=0 infos=0 elapsed_ms=9Exit codes
Section titled “Exit codes”| Code | When |
|---|---|
0 |
No error or warning findings remain after the baseline filter. Always 0 with --infer. |
1 |
At least one error or warning finding remains. |
2 |
CodeKnife could not run: for example, arch.toml or the --layers file does not parse, or the --layers file does not exist. |
See Output Formats & Exit Codes for the report formats.
Also available via
Section titled “Also available via”codeknife checkruns this blade (without--infer) as part of the quality gate, usingarch.tomlfrom the repository root. Thecodeknife_checkMCP tool does the same. See MCP Tools.codeknife map --proposalshows the layer violations of a proposedarch.tomlin the Garden Map.