arkgate 4.8.26 → 4.8.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +2 -2
  3. package/bin/ark-layer-match.mjs +23 -0
  4. package/bin/ark-mcp-runtime.mjs +45 -4
  5. package/bin/ark-mcp.mjs +9 -3
  6. package/bin/ark.mjs +27 -1
  7. package/bin/lib/analysis-engine.mjs +10 -10
  8. package/bin/lib/arkrules-sensors.mjs +9 -4
  9. package/bin/lib/class-source-scan.mjs +1 -1
  10. package/bin/lib/config-contract.mjs +5 -0
  11. package/bin/lib/prepare-change.mjs +10 -6
  12. package/bin/lib/prepare-write.mjs +7 -0
  13. package/bin/lib/remediation.mjs +84 -0
  14. package/bin/lib/resolved-candidate-facts.mjs +19 -2
  15. package/bin/lib/snippet-analysis.mjs +82 -1
  16. package/dist/chunk-A5EIY3HI.cjs +3 -3
  17. package/dist/chunk-H5I3GARV.js +16 -0
  18. package/dist/chunk-QQ4SJEJ7.cjs +16 -0
  19. package/dist/chunk-SVSQVGFJ.js +3 -3
  20. package/dist/{configTypes-GPvvdleM.d.cts → configTypes-D1oxws6x.d.cts} +6 -0
  21. package/dist/{configTypes-GPvvdleM.d.ts → configTypes-D1oxws6x.d.ts} +6 -0
  22. package/dist/eslint/index.cjs +11 -12
  23. package/dist/eslint/index.d.cts +7 -1
  24. package/dist/eslint/index.d.ts +7 -1
  25. package/dist/eslint/index.js +11 -11
  26. package/dist/index.cjs +32 -32
  27. package/dist/index.d.cts +13 -2
  28. package/dist/index.d.ts +13 -2
  29. package/dist/index.js +32 -32
  30. package/dist/inspectorListen-6DQVJ4DC.js +2 -1
  31. package/dist/inspectorListen-KGMIQ2TF.cjs +2 -1
  32. package/dist/nestjs/index.cjs +1 -1
  33. package/dist/nestjs/index.d.cts +1 -1
  34. package/dist/nestjs/index.d.ts +1 -1
  35. package/dist/nestjs/index.js +1 -1
  36. package/dist/order/index.cjs +1 -1
  37. package/dist/order/index.js +1 -1
  38. package/dist/runtime/index.cjs +10 -10
  39. package/dist/runtime/index.d.cts +4 -3
  40. package/dist/runtime/index.d.ts +4 -3
  41. package/dist/runtime/index.js +10 -10
  42. package/dist/{types-CnauMQQL.d.cts → types-DBiqlOWZ.d.cts} +6 -0
  43. package/dist/{types-CnauMQQL.d.ts → types-DBiqlOWZ.d.ts} +6 -0
  44. package/docs/README.md +2 -1
  45. package/docs/agent-guide.md +3 -2
  46. package/docs/ai-gates.md +1 -1
  47. package/docs/configuration.md +11 -0
  48. package/docs/package-surface.md +2 -1
  49. package/docs/product-voice.md +1 -1
  50. package/package.json +1 -1
  51. package/schemas/ark.config.schema.json +10 -0
  52. package/server.json +2 -2
  53. package/templates/agent-skills/README.md +1 -1
  54. package/templates/agent-skills/ark-adopt/SKILL.md +6 -0
  55. package/templates/agent-skills/ark-autopilot/SKILL.md +1 -1
  56. package/templates/agent-skills/ark-place/SKILL.md +4 -0
  57. package/templates/skills/ark-adopt.md +6 -0
  58. package/templates/skills/ark-autopilot.md +1 -1
  59. package/templates/skills/ark-place.md +4 -0
  60. package/dist/chunk-G3JRBJGH.js +0 -16
  61. package/dist/chunk-R3AJ5RSZ.cjs +0 -16
@@ -78,6 +78,12 @@ type ArkConfigLayer = {
78
78
  name: string;
79
79
  patterns: string[];
80
80
  exclude?: string[];
81
+ /**
82
+ * Optional public surface globs for this layer. When non-empty, cross-layer
83
+ * imports into this layer must target a file matching one of these globs;
84
+ * deep imports into internal layer files are denied.
85
+ */
86
+ entrypoints?: string[];
81
87
  intentPrefixes?: string[];
82
88
  /**
83
89
  * App-context caption for this layer.
@@ -78,6 +78,12 @@ type ArkConfigLayer = {
78
78
  name: string;
79
79
  patterns: string[];
80
80
  exclude?: string[];
81
+ /**
82
+ * Optional public surface globs for this layer. When non-empty, cross-layer
83
+ * imports into this layer must target a file matching one of these globs;
84
+ * deep imports into internal layer files are denied.
85
+ */
86
+ entrypoints?: string[];
81
87
  intentPrefixes?: string[];
82
88
  /**
83
89
  * App-context caption for this layer.
package/docs/README.md CHANGED
@@ -73,7 +73,8 @@ These are **not** the day-to-day product path. They stay in the repo for evidenc
73
73
  | Field adoption kit (scaffolding, not closed) | [field/](field/) |
74
74
  | Runtime hardening (experimental) | [production-hardening.md](production-hardening.md) |
75
75
 
76
- Current release: [CHANGELOG](../CHANGELOG.md) (`arkgate@4.8.26`; confirm npm with `npm view arkgate@4.8.26 version`; does not close `K01`).
76
+ Current release: [CHANGELOG](../CHANGELOG.md) (`arkgate@4.8.27`; confirm npm with `npm view arkgate@4.8.27 version`; does not close `K01`).
77
+ Prior published: [CHANGELOG](../CHANGELOG.md) (`arkgate@4.8.26`).
77
78
  Prior published: [CHANGELOG](../CHANGELOG.md) (`arkgate@4.8.25`).
78
79
  Prior published: [CHANGELOG](../CHANGELOG.md) (`arkgate@4.8.24`).
79
80
  Prior published: [CHANGELOG](../CHANGELOG.md) (`arkgate@4.8.23`).
@@ -315,6 +315,7 @@ MCP `ark_recommend` and the `/ark-adopt` skill (leftover name `/ark-architect` i
315
315
  npx ark start --yes # preferred read-only preview: shape → contract → host → CI
316
316
  npx ark start --yes --apply # apply exactly the previewed compact setup
317
317
  npx ark init --archetype crud-product --yes # non-interactive: shape → preset → origin → gates
318
+ npx ark init --baseline --yes # brownfield: freeze existing debt into .ark-baseline.json + wire --baseline in CI
318
319
  npx ark init # TTY wizard: pick application shape (1–8), not a framework
319
320
  npx ark-check --doctor # includes "New here?" when coverage is low or config is fresh
320
321
  npx ark-check --report beginner.html --beginner # simplified HTML for enthusiasts
@@ -1557,8 +1558,8 @@ The server exposes these thirteen tools. Every tool accepts the additive
1557
1558
  | `ark_check` | `{ strict?, baseline? }`: run the full project architecture check. `verdict` separates `identity`, `completeness`, `graph`, `coverage`, `gates`, and `overallOk`; no individual green fact substitutes for the combined verdict. |
1558
1559
  | `ark_policy_delta` | `{ baseConfig, candidateConfig?, baseArkRuleFiles?, candidateArkRuleFiles?, acknowledgement? }`: classify a complete contract transition, ArkRules included; never edits the contract. `baseArkRuleFiles` (`{ "<path from baseConfig.arkRules>": <file JSON> }`) is required when `baseConfig` maps `arkRules`. Include each `childSlices.arkRulesFile` path in that map when the wall discovers one. Weakening / new layer / new allow edge needs `adrPath` on the acknowledgement. |
1559
1560
  | `ark_coverage` | No args: report per-layer counts, every unclassified file, unmatched layers, and missing rule edges. |
1560
- | `ark_place` | `{ filePath, description? }`: resolve the governed home for `filePath` (fail-closed without it; never invents a path) and return its import/global constraints. |
1561
- | `ark_prepare_write` | `{ source, filePath, description?, layer? }`: compose placement and snippet validation, with hashes and a mechanical-safe patch when available. `filePath` is required (fail-closed). Partial like `validate_code`: read `lexicalValid`. |
1561
+ | `ark_place` | `{ filePath, description? }`: resolve the governed home for `filePath` (fail-closed without it; never invents a path) and return its import/global constraints, plus `entrypoints` and `targetEntrypoints` when layers declare public entrypoints. |
1562
+ | `ark_prepare_write` | `{ source, filePath, description?, layer? }`: compose placement (`entrypoints`, `targetEntrypoints`) and snippet validation (including immediate 2-hop cycle checks under `cyclePolicy: "strict"`), with hashes, a mechanical-safe patch when available, and `judgmentBrief.blueprint` (ready-to-paste TypeScript port/entrypoint/valve/kernel code on rejection). `filePath` is required (fail-closed). Partial like `validate_code`: read `lexicalValid`. |
1562
1563
  | `ark_prepare_change` | `{ changes, changeMap? }`: preflight one complete create/update/delete batch in memory against the same Effective Contract as `ark-check` (ArkRules included: same `policyHash`, structure/invariant findings; a missing referenced ArkRules file fails closed); ArkRules-plane findings the base tree already has are returned as `preExisting: true` warnings and do not block, so baselined brownfield debt does not reject an unrelated batch; never writes files. |
1563
1564
  | `ark_recommend` | No args: return the deterministic application-shape plan used by `ark-check --recommend --json`. |
1564
1565
  | `ark_suggest_include` | No args: propose TypeScript/JavaScript include roots from workspaces and nested packages. |
package/docs/ai-gates.md CHANGED
@@ -961,7 +961,7 @@ checker from the ref you pin, so an older ref runs an older checker, and that ch
961
961
  config keys (for example `schemaVersion` 1.3, `childSlices`, `sliceIdentity`) with exit 2:
962
962
 
963
963
  ```yaml
964
- - uses: pedroknigge/arkgate@v4.8.26 # same version as the arkgate devDependency
964
+ - uses: pedroknigge/arkgate@v4.8.27 # same version as the arkgate devDependency
965
965
  with:
966
966
  root: .
967
967
  config: ark.config.json
@@ -263,6 +263,17 @@ That sentence is product copy. Not “Rich domain model, business rules, and dom
263
263
  ]
264
264
  ```
265
265
 
266
+ - **`layers[].entrypoints`** (optional) — public entrypoints for the layer (for
267
+ example `["src/infrastructure/index.ts"]`). When present and non-empty, external
268
+ layers that are permitted to import this layer may only import files matching
269
+ `entrypoints`; importing an internal file outside `entrypoints` is rejected as
270
+ `LAYER_IMPORT_VIOLATION` across `ark-check`, `arkgate/eslint`, `AICodeGate`, and
271
+ `ark-mcp`. Same-layer imports remain allowed. Enabling or narrowing `entrypoints`
272
+ is a `strengthening` policy delta; removing or widening `entrypoints` is a
273
+ `weakening` policy delta. Invalid or zero-match globs emit
274
+ `CONFIG_INVALID_LAYER_PATTERN` / `CONFIG_LAYER_PATTERN_NO_MATCHES`. `ark_place`
275
+ and `ark_prepare_write` project `entrypoints` and `targetEntrypoints` so agents
276
+ know which public surface to import before writing.
266
277
  - `intentPrefixes`, `forbiddenGlobals`, `mayImportInfrastructure`, `optional`
267
278
  — `intentPrefixes` is how the ArkRun kernel maps an intent name to a layer at runtime.
268
279
  A layer with a canonical 11-layer name (`DomainModel`, `ApplicationOrchestration`,
@@ -69,10 +69,11 @@ hardening guide remains repository-hosted rather than duplicated in the gate tar
69
69
  | **Report parity and snapshot evidence (4.2)** | `ark-check --report` → advisory sections (`data-advisory="contractHealth\|ambientState\|parseHealth\|arkRun"`, nested `governanceWeight`) + layer wall badges; `.ark/reports/*.json` | The report is a rendering of doctor truth. **Standing rule:** every doctor advisory ships with its report section — enforced by the `reportParity` guard, which enumerates the doctor's advisory keys and fails on any missing section. Snapshots add best-effort Git `HEAD`/branch/dirty provenance without a shell; unavailable Git is explicit. Evolution renders the Ark score delta only when both snapshots name the same ArkGate version, while retaining raw facts across versions. Thin `arkRun` on `latest.json` is `notAScore` residual honesty for `ark status`. |
70
70
  | **MCP project identity (4.2)** | `ark_identity`; `arkgate/schema/project-identity` or `arkgate/schema/ark.project-identity.schema.json`; root API constants/helpers/types | Schema `1.0`. `projectId` hashes canonical root + config path and stays stable across contract edits/restarts; runtime id/start time are separate. Every project-bound tool result and error carries `projectIdentity`, `binding` (`matched` / `unverified` / `mismatch`), and `authoritative`. Canonical out-of-root config/file evidence fails before project data. |
71
71
  | **MCP tools and compatibility resource** | `arkgate-mcp`; `ark_manifest`; `ark_status`; `ark://manifest` | Tool names and primary argument shapes are stable within a major. Every tool accepts additive `project.expectedRoot` / optional `expectedProjectId`. The initial handshake requires the exact project root; a contained descendant is authoritative only together with the matching project id. Legacy tool calls remain callable but `unverified` and non-authoritative. `ark_manifest` is the authoritative contract surface after binding. **`ark_status`** returns the status manifest envelope (parity with `ark status --json`). Standard `resources/read` cannot portably carry the expectation, so `ark://manifest` remains compatibility-only and always unverified/non-authoritative. The server never retargets from input. Every published `outputSchema` has top-level `type: "object"` and the returned `structuredContent` validates against it (MCP SDK clients check both). A contract edit after startup makes project tools return `CONTRACT_STALE` until restart. `arkgate-mcp --help` / `--version` print and exit. |
72
- | **`ark.config.json`** | Layer globs, optional `layers[].description`, optional `layers[].trustBoundary`, optional `layers[].owners`, optional `requireLayerOwners`, rules, include/exclude, forbiddenGlobals, intent prefixes, `peerIsolation`, `dynamicImportAllowlist`, `safety` thresholds; optional **`coverage`** controls (`testGlobs`, `maxFiles`); optional **`arkRules`** map of one path or a list of paths (schema `1.1+`), plus optional `childSlices.arkRulesFile` and `sliceAliases.pinned`; optional **`arkRun`** extra (schema `1.2+`); optional **`arkOrder`** extra (schema `1.3+`) | Versioned by `schemaVersion`; unknown fields fail closed and migrations preserve the previous supported major. Absence of `coverage`, `arkRules`, `arkRun`, or `arkOrder` is byte-for-byte silent on Layers / ArkRules verdicts. Enforced extra teeth share the CLI / MCP / hook / preflight / CI verdict and arm only when the layer plane is classified (same ArkRules floor). |
72
+ | **`ark.config.json`** | Layer globs, optional `layers[].description`, optional `layers[].trustBoundary`, optional `layers[].owners`, optional `layers[].entrypoints`, optional `requireLayerOwners`, rules, include/exclude, forbiddenGlobals, intent prefixes, `peerIsolation`, `dynamicImportAllowlist`, `safety` thresholds; optional **`coverage`** controls (`testGlobs`, `maxFiles`); optional **`arkRules`** map of one path or a list of paths (schema `1.1+`), plus optional `childSlices.arkRulesFile` and `sliceAliases.pinned`; optional **`arkRun`** extra (schema `1.2+`); optional **`arkOrder`** extra (schema `1.3+`) | Versioned by `schemaVersion`; unknown fields fail closed and migrations preserve the previous supported major. Absence of `coverage`, `arkRules`, `arkRun`, or `arkOrder` is byte-for-byte silent on Layers / ArkRules verdicts. Enforced extra teeth share the CLI / MCP / hook / preflight / CI verdict and arm only when the layer plane is classified (same ArkRules floor). |
73
73
  | **Layer caption (`layers[].description`, 4.8.7)** | Optional string on each layer. Projected onto `ark_place` / prepare-write / MCP place JSON, doctor JSON + human, coverage JSON, and the HTML Purpose column when present. `/ark-adopt` writes it from the product map or glossary; `/ark-place` prints it next to layer name + globs. | Existing optional field — **no `schemaVersion` bump**, no new key, no 14th skill. Copy is **app context** (a product sentence such as `Purchase requests — from asked to received.`), not architecture jargon. Stripped from `policyHash` like `stewards`; caption-only edits are neutral. Absence is silent: never a residual, never a score, never `--strict-config` fail, never flips `valid`. Compact starters may omit. |
74
74
  | **Layer trust (`layers[].trustBoundary`)** | Optional closed tag on each layer: `public` \| `auth` \| `admin` \| `internal`. Projected onto `ark_place` / prepare-write / MCP place JSON, doctor JSON + human, coverage JSON, and the HTML report when present. `/ark-adopt` writes it when the product map names that door; `/ark-place` prints `trust: public`. | Additive optional field — **no `schemaVersion` bump**, no new skill. Stripped from `policyHash` like `stewards` and `layers[].description`; tag-only edits are neutral. Absence is silent: never a residual, never a score, never `--strict-config` fail, never flips `valid`. Invalid values fail the schema. Compact starters may omit. Not host/CI TLS. Not an import-rule matrix. |
75
75
  | **Layer owners (`layers[].owners` + `requireLayerOwners`)** | Optional GitHub handles or emails on each layer. Projected onto place / prepare-write / MCP / doctor / coverage / HTML when present. `requireLayerOwners: true` asks for owners on every live (non-reserved) layer: doctor names the first missing house, `--strict-config` refuses, and the write gate denies a write into that house. | Additive optional fields — **no `schemaVersion` bump**, no new skill. Owners are stripped from `policyHash` like captions; owner-only edits are neutral. The require flag stays in the hash. Absence of owners is silent unless the require flag is on. Invalid identity (display name) fails the schema. Compact starters may omit. Not import-rule teeth. No `/ark-owners`. |
76
+ | **Layer entrypoints (`layers[].entrypoints`, 4.8.27)** | Optional non-empty glob array on each layer declaring its public entrypoints. Projected onto `ark_place` / `ark_prepare_write` (`entrypoints`, `targetEntrypoints`). External layers allowed to import the target layer must import via `entrypoints`; internal files outside `entrypoints` fail with `LAYER_IMPORT_VIOLATION` across CLI, ESLint, `AICodeGate`, and MCP, with a deterministic `blueprint` snippet on rejection. | Additive optional field — **no `schemaVersion` bump**, no new skill. Enforced at the single `findDeniedEdgeDecision` waist. Policy-delta classifies enabling/narrowing as `strengthening` and removing/widening as `weakening`. Absence changes no verdict. |
76
77
  | **ArkRules inventory / under-contract (4.0; layer context 4.2)** | `ark-check --rules-inventory [--json]`; doctor `rulesUnderContract` + `rulesMigration`; MCP `ark_rules_inventory` | Additive. Honest counts (inventoried / under-contract / frozen) — **never a score**. Structure candidates count as under contract by declared (layer, sensor); frozen counts `ARKRULE_*` / `INVARIANT_*` baseline keys. CLI and MCP payloads share one builder (same keys, incl. `coverageEvidence`). When configured layer evidence exists it overrides filename role guesses: a Domain file named `handler` is not a controller candidate. Test/fixture/seed/migration/exclusion surfaces plus narrow development-identity, PostgreSQL OID, and technical I/O constants are silent. Without layer evidence, backward-compatible path/content heuristics remain. Structure/invariant diagnostics use adapter `1.4` provenance. |
77
78
  | **`arkgate/schema/project-identity`** or **`arkgate/schema/ark.project-identity.schema.json`** | MCP canonical project, contract, runtime, expectation, and binding envelope | Schema `1.0`. Initial `expectedRoot` must be the exact project root. A contained descendant can match only when `expectedProjectId` is also present and correct; id-only matching stays non-authoritative. Mismatch codes are `PROJECT_ROOT_MISMATCH`, `PROJECT_ID_MISMATCH`, and `INVALID_PROJECT_EXPECTATION`. |
78
79
  | **Package pin dual-truth (4.0)** | doctor JSON `packageVersionTruth`; upgrade JSON/human note when pin behind CLI | Additive, advisory. Surfaces after `upgrade --no-install` when managed CLI is ahead of package.json. |
@@ -80,7 +80,7 @@ On the seven lane openings — `docs/use.md`, `docs/develop.md`, `docs/README.md
80
80
  `README.md` is the first-contact module. Its first screen is four beats: what
81
81
  (**Contener · Guiar · Ordenar**), why (design the boundary before you implement;
82
82
  a green check is **needs a refactor** when leftover mess remains), one command
83
- (`npx arkgate@4.8.26 start`), and one honest red result (fail-open named; required
83
+ (`npx arkgate@4.8.27 start`), and one honest red result (fail-open named; required
84
84
  CI is the hard line). The four paragraphs, the not-that line, the host matrix,
85
85
  and the release index sit below `## Appendix`. The not-that line does not lead
86
86
  the README.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arkgate",
3
- "version": "4.8.26",
3
+ "version": "4.8.27",
4
4
  "description": "When the agent writes a bad import, the write doesn’t land. The same check fails the pull request.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -699,6 +699,16 @@
699
699
  },
700
700
  "uniqueItems": true
701
701
  },
702
+ "entrypoints": {
703
+ "type": "array",
704
+ "items": {
705
+ "type": "string",
706
+ "minLength": 1
707
+ },
708
+ "uniqueItems": true,
709
+ "minItems": 1,
710
+ "description": "Optional public surface globs for this layer. When non-empty, cross-layer imports into this layer must target a file matching one of these globs; deep imports into internal layer files are denied."
711
+ },
702
712
  "intentPrefixes": {
703
713
  "type": "array",
704
714
  "items": {
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/pedroknigge/arkgate",
7
7
  "source": "github"
8
8
  },
9
- "version": "4.8.26",
9
+ "version": "4.8.27",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "arkgate",
14
- "version": "4.8.26",
14
+ "version": "4.8.27",
15
15
  "runtimeHint": "npx",
16
16
  "transport": {
17
17
  "type": "stdio"
@@ -9,7 +9,7 @@ closed `/ark-*` catalog shipped as flat templates for Ark install.
9
9
  **Closed catalog** (`ARK_SKILL_NAMES`) — first-class doors plus one-release
10
10
  redirect stubs. Add a name only with a live ROADMAP item.
11
11
 
12
- Package version when last generated context: **arkgate@4.8.26**
12
+ Package version when last generated context: **arkgate@4.8.27**
13
13
  Schema: agent-skills package contract `1.0`
14
14
 
15
15
  ## Skills (closed catalog)
@@ -35,6 +35,12 @@ has honest houses. Skills never enforce — CLI / hooks / CI do.
35
35
  (GitHub handle or email). Compact starter may omit. Do not invent people.
36
36
  Absence is silent unless the user asked for required owners — then write
37
37
  `requireLayerOwners: true` after the live houses have names. No `/ark-owners`.
38
+ - When a layer exposes a deliberate public barrel or facade (e.g. `src/domain/index.ts`),
39
+ optional `layers[].entrypoints` restricts cross-layer imports into that layer to matching
40
+ globs. Intra-layer imports stay unrestricted. Absence is silent. No `/ark-entrypoints`.
41
+ - On brownfield trees with genuine pre-existing debt, `ark init --baseline` (or
42
+ `arkgate-check --write-baseline`) freezes `.ark-baseline.json` so `--strict-merge`
43
+ blocks only new regressions.
38
44
  - When the user wants required gates (`--require-gates` / `--strict-merge` /
39
45
  required GitHub check) and there is no `docs/adr/` (or `docs/decisions/`),
40
46
  leave a short decision note there — only if they loosen a rule or add a real
@@ -258,7 +258,7 @@ Status lights from doctor — not settings you choose. Rank residual honestly:
258
258
  **STOP — do not continue this skill as complete.** **STOP — concentrated edge:** rewrite `ark.config.json` **in this turn** with source evidence (do not freeze a wrong config or grind N freezes).
259
259
  6. **Worktree preferred** — discardable git worktree when possible.
260
260
  7. **Mechanical-safe (A only)** — kinds from `/ark-loop` table; one step, validate, rollback.
261
- 8. **Judgment (A)** — implement with full “así te lo re-soluciono”; validate; rollback on fail.
261
+ 8. **Judgment (A)** — implement with full “así te lo re-soluciono” (use the deterministic `blueprint` / `judgmentBrief.blueprint` TypeScript skeleton when present for `FORBIDDEN_GLOBAL`, `CAPABILITY_VIOLATION`, `LAYER_IMPORT_VIOLATION`, `ARKORDER_*`, or `ARKRUN_DIRECT_NEW`); validate; rollback on fail.
262
262
  9. **Pattern bets (B)** — apply **one** extraction-card pilot this turn; leave the rest queued. Never weaken the gate to clear B.
263
263
  10. **Manifiesto** — loose business rules → Domain placement + `intentPrefixes` / intents; write config here if the path is still dishonest.
264
264
  11. **Final report** — re-`--report`; evolution vs origin; A applied vs open; B proposed/deferred; gates on.
@@ -49,6 +49,10 @@ right house. Skills never enforce — CLI / hooks / CI do.
49
49
  to the layer name and globs. Omit when absent — do not invent a person or `/ark-owners`.
50
50
  When `requireLayerOwners` is on and the house has no owners, send that gap to
51
51
  `/ark-adopt` before writing.
52
+ - When `ark_place` / `ark_prepare_write` returns `entrypoints` or `targetEntrypoints`,
53
+ import allowed layers through their listed public entrypoints (barrels/facades) rather
54
+ than deep internal paths. When `ark_prepare_write` returns `judgmentBrief.blueprint`,
55
+ use that TypeScript Port/valve/entrypoint skeleton to satisfy the boundary before writing.
52
56
  - When `arkRun` is on: scaffold through the kernel (no `new` of managed types; declare
53
57
  `uses` / `reactsTo` / `raises` / `sends`; factory only in `arkRun.kernelRoots`,
54
58
  `compositionRoots` alias). Extra off → do not introduce the kernel. Enable it
@@ -35,6 +35,12 @@ has honest houses. Skills never enforce — CLI / hooks / CI do.
35
35
  (GitHub handle or email). Compact starter may omit. Do not invent people.
36
36
  Absence is silent unless the user asked for required owners — then write
37
37
  `requireLayerOwners: true` after the live houses have names. No `/ark-owners`.
38
+ - When a layer exposes a deliberate public barrel or facade (e.g. `src/domain/index.ts`),
39
+ optional `layers[].entrypoints` restricts cross-layer imports into that layer to matching
40
+ globs. Intra-layer imports stay unrestricted. Absence is silent. No `/ark-entrypoints`.
41
+ - On brownfield trees with genuine pre-existing debt, `ark init --baseline` (or
42
+ `arkgate-check --write-baseline`) freezes `.ark-baseline.json` so `--strict-merge`
43
+ blocks only new regressions.
38
44
  - When the user wants required gates (`--require-gates` / `--strict-merge` /
39
45
  required GitHub check) and there is no `docs/adr/` (or `docs/decisions/`),
40
46
  leave a short decision note there — only if they loosen a rule or add a real
@@ -258,7 +258,7 @@ Status lights from doctor — not settings you choose. Rank residual honestly:
258
258
  **STOP — do not continue this skill as complete.** **STOP — concentrated edge:** rewrite `ark.config.json` **in this turn** with source evidence (do not freeze a wrong config or grind N freezes).
259
259
  6. **Worktree preferred** — discardable git worktree when possible.
260
260
  7. **Mechanical-safe (A only)** — kinds from `/ark-loop` table; one step, validate, rollback.
261
- 8. **Judgment (A)** — implement with full “así te lo re-soluciono”; validate; rollback on fail.
261
+ 8. **Judgment (A)** — implement with full “así te lo re-soluciono” (use the deterministic `blueprint` / `judgmentBrief.blueprint` TypeScript skeleton when present for `FORBIDDEN_GLOBAL`, `CAPABILITY_VIOLATION`, `LAYER_IMPORT_VIOLATION`, `ARKORDER_*`, or `ARKRUN_DIRECT_NEW`); validate; rollback on fail.
262
262
  9. **Pattern bets (B)** — apply **one** extraction-card pilot this turn; leave the rest queued. Never weaken the gate to clear B.
263
263
  10. **Manifiesto** — loose business rules → Domain placement + `intentPrefixes` / intents; write config here if the path is still dishonest.
264
264
  11. **Final report** — re-`--report`; evolution vs origin; A applied vs open; B proposed/deferred; gates on.
@@ -49,6 +49,10 @@ right house. Skills never enforce — CLI / hooks / CI do.
49
49
  to the layer name and globs. Omit when absent — do not invent a person or `/ark-owners`.
50
50
  When `requireLayerOwners` is on and the house has no owners, send that gap to
51
51
  `/ark-adopt` before writing.
52
+ - When `ark_place` / `ark_prepare_write` returns `entrypoints` or `targetEntrypoints`,
53
+ import allowed layers through their listed public entrypoints (barrels/facades) rather
54
+ than deep internal paths. When `ark_prepare_write` returns `judgmentBrief.blueprint`,
55
+ use that TypeScript Port/valve/entrypoint skeleton to satisfy the boundary before writing.
52
56
  - When `arkRun` is on: scaffold through the kernel (no `new` of managed types; declare
53
57
  `uses` / `reactsTo` / `raises` / `sends`; factory only in `arkRun.kernelRoots`,
54
58
  `compositionRoots` alias). Extra off → do not introduce the kernel. Enable it
@@ -1,16 +0,0 @@
1
- import{I as Le,N as At,P as ce,Q as kt,R as Et,T as Rt,V as Pt,a,e as St,f as wt,r as It,t as vt,x as bt}from"./chunk-SVSQVGFJ.js";var Ct="4.8.26";var C={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},xt={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...C,default:[]},kernelRoots:{...C},managedLayers:{...C,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Lt={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...C,default:[]},managedLayers:{...C,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...C,default:[]},appliesTo:{...C,default:[]}}};function z(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}a(z,"isObject");function er(t){let e=new Set;if(!Array.isArray(t.layers))return e;for(let n of t.layers)z(n)&&typeof n.name=="string"&&n.name.length>0&&e.add(n.name);return e}a(er,"declaredLayerNames");function Ot(t){if(!z(t))return t;let e={mode:t.mode===void 0?"advisory":t.mode,compositionRoots:t.compositionRoots===void 0?[]:t.compositionRoots,managedLayers:t.managedLayers===void 0?[]:t.managedLayers,requireDeclarations:t.requireDeclarations===void 0?!0:t.requireDeclarations};return t.kernelRoots!==void 0&&(e.kernelRoots=t.kernelRoots),t.ignoreDirectNewForErrors!==void 0&&(e.ignoreDirectNewForErrors=t.ignoreDirectNewForErrors),{...t,...e}}a(Ot,"defaultedArkRun");function $t(t){if(!z(t))return t;let e=typeof t.maxXiKeys=="number"&&t.maxXiKeys>0?t.maxXiKeys:7;return{...t,mode:t.mode===void 0?"advisory":t.mode,planeRoots:t.planeRoots===void 0?[]:t.planeRoots,managedLayers:t.managedLayers===void 0?[]:t.managedLayers,maxXiKeys:e,xiKeys:t.xiKeys===void 0?[]:t.xiKeys}}a($t,"defaultedArkOrder");function Dt(t,e,n,r){if(!Array.isArray(e))return;let o=er(t);e.forEach((i,s)=>{typeof i=="string"&&i.length>0&&!o.has(i)&&r.push({path:`$.${n}.managedLayers[${s}]`,message:`layer ${JSON.stringify(i)} is not declared in layers[]`})})}a(Dt,"validateManagedLayersDeclared");function Nt(t,e){let n=t.arkRun;if(n===void 0||!z(n))return;let r=n.managedLayers;if(Dt(t,r,"arkRun",e),n.mode==="enforced"){let o=n.kernelRoots??n.compositionRoots;(!Array.isArray(o)||o.length===0)&&e.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(r)||r.length===0)&&e.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Nt,"validateArkRunExtra");function Tt(t,e){let n=t.arkOrder;if(n===void 0||!z(n))return;let r=n.managedLayers;if(Dt(t,r,"arkOrder",e),n.mode==="enforced"){let o=n.planeRoots;(!Array.isArray(o)||o.length===0)&&e.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(r)||r.length===0)&&e.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Tt,"validateArkOrderExtra");var ue={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ht={description:'deny blocks every shared-root import of a slice. deny-cross-parent leaves that hop as a warning and, in ark-check and CI only, reports a slice that reaches another universe through a shared root. The write hook and ESLint see one edge and do not block it. The object form { mode: "deny-cross-parent", stopAt } names composition roots (bootstrap, DI registrations) the whole-graph walk never starts at or passes through; a stop file must still sit under sharedRoots, and stopAt does not silence the direct SHARED_IMPORTS_SLICE warning. arkgate 4.8.22 and older reject deny-cross-parent. arkgate 4.8.23 and older reject the object form (must be one of deny, deny-cross-parent).',oneOf:[{type:"string",enum:["deny","deny-cross-parent"]},{type:"object",additionalProperties:!1,required:["mode","stopAt"],properties:{mode:{type:"string",enum:["deny-cross-parent"]},stopAt:{...ue,minItems:1}}}]},Kt={type:"object",additionalProperties:!1,required:["sliceFolders"],description:`Optional inner wall under this rule. Runs only on a rule with peerIsolation: true and allowed: false; elsewhere it is inert and ark-check warns CONFIG_CHILD_SLICES_INERT (config load still accepts it, as 4.8.23 did). Absent keeps today's universe wall. sliceFolders names children. Flat files are universe common, and so is a commonFolders directory directly under the universe (a folder of that name inside a child belongs to that child). siblings is "deny" (default), "advisory", or { default, enforce, ratchet }. parentMayImportChild defaults to false. message is the text for inner-wall findings. allowedCrossSlice may use a whole-segment *. It clears only a sibling crossing. Cross-parent has no advisory knob. arkgate 4.8.22 and older reject this key. A build that still rejects unknown childSlices fields rejects allowedCrossSlice at config load. A build that still types siblings as a string enum rejects the object at config load.`,properties:{sliceFolders:{...ue,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"]},commonFolders:{...ue,minItems:1},siblings:{description:'"deny" or "advisory", or { default, enforce, ratchet } so listed subtrees are errors while the default stays advisory. ratchet absent: a new advisory crossing fails only when the baseline in use already records an advisory crossing of this rule. ratchet true: any unrecorded advisory crossing fails when a baseline is in use. ratchet false: measure only, never fails. A string-enum build rejects the object at config load (must be one of deny, advisory). arkgate 4.8.23 and older reject ratchet (unknown field).',oneOf:[{type:"string",enum:["deny","advisory"]},{type:"object",additionalProperties:!1,required:["default"],properties:{default:{type:"string",enum:["deny","advisory"]},enforce:{...ue},ratchet:{type:"boolean"}}}]},parentMayImportChild:{type:"boolean"},message:{type:"string",minLength:1,description:"Text for inner-wall findings (CROSS_SIBLING_SLICE and universe common importing a child). The rule message stays the universe-wall text (CROSS_PARENT_SLICE and fail-closed denies). Absent: ArkGate default text, never the rule message. arkgate 4.8.23 and older reject this field (unknown field)."},arkRulesFile:{type:"string",minLength:1,description:"Filename read at each child slice root this wall already resolved. The only token is <Layer>, replaced with a declared layer name (arkrules.<Layer>.json). No slash and no wildcard. A discovered file that omits appliesTo is scoped to that slice directory. Explicit appliesTo outside the slice fails config load (ARKRULE_SCOPE_ESCAPES_SLICE). The effective id is <childId>#<localId>. A build that rejects unknown childSlices fields fails at config load (unknown field)."},sliceAliases:{type:"array",minItems:1,description:"Maps a source path glob onto a child slice id (universe id plus one child segment) so files outside the slice trees take that universe and child for both walls. A path without a wildcard also covers everything under it, as sharedRoots does. A bare name, a universe id alone, a target outside every universe shape, and a wildcard in to are rejected. Under stars identity a target written against the 4.8.23 stars id (star bindings before the last literal dropped, e.g. api/v1/x for modules/*/api/*) still loads when it maps to one universe shape, and ark-check warns CONFIG_SLICE_LEGACY_STARS_ID with the new id; it is rejected only when it maps to more than one shape. Config load checks only the shape; doctor reports a target universe no file belongs to. The glob may not overlap a slice folder, and two aliases may not match the same file. Doctor lists each unpinned alias as an owed move. pinned true lists the alias separately and does not count it as debt. reason is a doctor label and does not pin by itself. A build that rejects unknown childSlices fields fails at config load (unknown field). arkgate 4.8.22 and older reject childSlices.",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},pinned:{type:"boolean",description:"True when a framework forces the path to stay. The alias is not an owed move and does not clear other honesty debt."},reason:{type:"string",minLength:1,description:"Doctor label, such as framework-route. A label alone does not pin."}}}},allowedCrossSlice:{type:"array",minItems:1,description:"Directed child-slice allowances. * matches one whole path segment (features/projects/*). ** and a partial segment are rejected. A bare name is rejected. This list clears only CROSS_SIBLING_SLICE. It cannot clear CROSS_PARENT_SLICE or CROSS_PARENT_VIA_SHARED. The universe allowedCrossSlice still treats * as a literal. A build that rejects unknown childSlices fields fails at config load (unknown field).",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}};function I(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}a(I,"isObject");function fe(t,e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?`${t}.${e}`:`${t}[${JSON.stringify(e)}]`}a(fe,"propertyPath");function P(t){let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)}a(P,"trimTrailingSlashes");function Vt(t,e){ir(t,e),ar(t,e),ur(t,e),Rr(t,e),Er(t,e)}a(Vt,"validateSliceContract");var Mt='must be "deny", "deny-cross-parent", or { "mode": "deny-cross-parent", "stopAt": ["<composition root path or glob>"] }',Ft="must not cover the whole tree. Name the composition root itself (bootstrap file, DI registrations folder).";function tr(t){return t==="*"||t==="**"}a(tr,"isWildcardSegment");function Wt(t){let e=t.toLowerCase().split("/").filter(o=>o.length>0&&o!==".");(e[0]==="src"||e[0]==="app")&&(e=e.slice(1));let n=e.length;for(;n>0&&tr(e[n-1]??"");)n-=1;let r=e.slice(0,n);return r.some(o=>o.includes("*"))?null:r}a(Wt,"coveredFolder");function nr(t,e){return t.length<=e.length&&t.every((n,r)=>e[r]===n)}a(nr,"isPrefixOf");function rr(t,e){let n=t.layers;if(!Array.isArray(n))return[];let r=new Set([e.from,e.to].filter(i=>typeof i=="string")),o=[];for(let i of n){if(!I(i)||typeof i.name!="string"||!r.has(i.name))continue;let s=Array.isArray(i.patterns)?i.patterns:[];for(let l of s){if(typeof l!="string")continue;let c=l.replace(/\\/g,"/").split("/"),d=c.findIndex(m=>m.includes("*")),f=d===-1?c:c.slice(0,d),p=Wt(f.join("/"));p&&o.push(p)}}return o}a(rr,"ruleLayerFolders");function or(t,e){let n=P(t.trim().replace(/\\/g,"/"));if(n.length===0)return"must be a non-empty path or glob";let r=n.replace(/^[./]+/,"");if(r===""||r==="*"||r==="**")return Ft;for(let i of n.split("/"))if(i.length===0||i==="."||i==="..")return"must be a path or glob without empty, . or .. segments";let o=Wt(n);return o===null?null:o.length===0?Ft:e.some(i=>nr(o,i))?"must not cover a whole layer root of this rule. Name the composition root itself (bootstrap file, DI registrations folder).":null}a(or,"stopAtEntryIssue");function ir(t,e){let n=t.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!I(r)||r.sharedImportsSlice===void 0)return;let i=r.sharedImportsSlice,s=`$.rules[${o}].sharedImportsSlice`;if(typeof i=="string"){i!=="deny"&&i!=="deny-cross-parent"&&e.push({path:s,message:Mt});return}if(!I(i)){e.push({path:s,message:Mt});return}for(let f of Object.keys(i))f!=="mode"&&f!=="stopAt"&&e.push({path:fe(s,f),message:"unknown field"});i.mode===void 0?e.push({path:`${s}.mode`,message:"is required"}):i.mode!=="deny-cross-parent"&&e.push({path:`${s}.mode`,message:'must be deny-cross-parent. stopAt has no meaning for deny; use the string "deny".'});let l=i.stopAt;if(l===void 0){e.push({path:`${s}.stopAt`,message:"is required"});return}if(!Array.isArray(l)||l.length===0){e.push({path:`${s}.stopAt`,message:"must be a non-empty array of paths or globs"});return}let c=new Set,d=rr(t,r);l.forEach((f,p)=>{let m=`${s}.stopAt[${p}]`;if(typeof f!="string"){e.push({path:m,message:"must be a non-empty path or glob"});return}let h=or(f,d);if(h){e.push({path:m,message:h});return}let S=P(f.trim().replace(/\\/g,"/")).toLowerCase();if(c.has(S)){e.push({path:m,message:"duplicate stopAt entry"});return}c.add(S)})})}a(ir,"validateSharedImportsSlice");var sr=["deny","advisory"],_t='must be "deny", "advisory", or { "default": "deny" | "advisory", "enforce": ["<child id or subtree path>"], "ratchet": true | false }';function ar(t,e){let n=t.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!I(r))return;let i=r.childSlices;if(!I(i)||i.siblings===void 0)return;let s=i.siblings,l=`$.rules[${o}].childSlices.siblings`;if(typeof s=="string"){sr.includes(s)||e.push({path:l,message:_t});return}if(!I(s)){e.push({path:l,message:_t});return}for(let d of Object.keys(s))d!=="default"&&d!=="enforce"&&d!=="ratchet"&&e.push({path:fe(l,d),message:"unknown field"});if(s.ratchet!==void 0&&typeof s.ratchet!="boolean"&&e.push({path:`${l}.ratchet`,message:"must be a boolean"}),s.default===void 0?e.push({path:`${l}.default`,message:"is required"}):s.default!=="deny"&&s.default!=="advisory"&&e.push({path:`${l}.default`,message:"must be deny or advisory"}),s.enforce===void 0)return;if(!Array.isArray(s.enforce)){e.push({path:`${l}.enforce`,message:"must be an array of child slice ids or subtree paths"});return}let c=new Set;s.enforce.forEach((d,f)=>{let p=`${l}.enforce[${f}]`;if(typeof d!="string"||d.trim().length===0){e.push({path:p,message:"must be a non-empty child slice id or subtree path"});return}let m=P(d.trim().replace(/\\/g,"/"));if(m.split("/").some(h=>h.length===0||h==="."||h==="..")){e.push({path:p,message:"must be a child slice id or subtree path without . or .."});return}if(m.includes("*")){e.push({path:p,message:"must be a child slice id or subtree path. * is not a wildcard on siblings.enforce"});return}if(c.has(m)){e.push({path:p,message:"duplicate enforce entry"});return}c.add(m)})})}a(ar,"validateChildSliceSiblings");var lr="must be a slice id with a slash. A bare name is ambiguous across universes.",cr="* matches one whole path segment. ** and a partial segment are not wildcards.";function dr(t){let e=P(t.trim().replace(/\\/g,"/"));if(e.length===0)return"must be a non-empty slice id";if(!e.includes("/"))return lr;let n=e.split("/");for(let r of n){if(r.length===0||r==="."||r==="..")return"must be a slice id without empty, . or .. segments";if(r.includes("*")&&r!=="*")return cr}return null}a(dr,"childCrossSlicePatternIssue");function Bt(t){return P(t.trim().replace(/\\/g,"/")).toLowerCase()}a(Bt,"childCrossSlicePatternKey");function ur(t,e){let n=t.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!I(r))return;let i=r.childSlices;if(!I(i)||i.allowedCrossSlice===void 0)return;let s=i.allowedCrossSlice,l=`$.rules[${o}].childSlices.allowedCrossSlice`;if(!Array.isArray(s)){e.push({path:l,message:"must be an array of { from, to } child slice ids"});return}let c=new Set;s.forEach((d,f)=>{let p=`${l}[${f}]`;if(!I(d)){e.push({path:p,message:"must be an object with from and to"});return}for(let h of Object.keys(d))h!=="from"&&h!=="to"&&e.push({path:fe(p,h),message:"unknown field"});for(let h of["from","to"]){let S=d[h],u=`${p}.${h}`;if(typeof S!="string"||S.trim().length===0){e.push({path:u,message:"must be a non-empty slice id"});continue}let y=dr(S);y&&e.push({path:u,message:y})}if(typeof d.from!="string"||typeof d.to!="string")return;let m=`${Bt(d.from)}\0${Bt(d.to)}`;if(!m.startsWith("\0")&&!m.endsWith("\0")){if(c.has(m)){e.push({path:p,message:"duplicate child slice allowance"});return}c.add(m)}})})}a(ur,"validateChildSliceAllowedCrossSlice");var M="must be a child of a universe shape this rule names (its universe sliceFolders shape plus one child segment). A bare name, a universe id alone, a target outside every universe shape, and a wildcard are rejected. Config load checks the shape only; doctor reports a target universe no file belongs to.",fr="is a 4.8.23 stars id (star bindings before the last literal dropped) that maps to more than one universe shape of this rule. Write the new stars id, which keeps every star binding (e.g. orders/api/v1/x for modules/*/api/*).",pr="overlaps a slice folder. An alias covers only files outside the slice trees.",gr="two slice aliases match the same file";function mr(t){return P(t.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(e=>e.length>0)}a(mr,"aliasPathSegments");function hr(t){let e=t[t.length-1];return e===void 0||e.includes("*")?[...t]:[...t,"**"]}a(hr,"aliasSegmentsWithSubtree");function Ut(t){let e=[];for(let n of t){if(n.includes("*"))break;e.push(n)}return e}a(Ut,"concreteGlobPrefix");function J(t,e){if(t.length>e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return!1;return!0}a(J,"segmentsArePrefix");function yr(t){let e=t.split(/[/\\]/).filter(Boolean).map(r=>r.toLowerCase());if(e.length<2||e[0]==="*"||e[0]==="**"||!e.some(r=>r==="*"))return null;let n=[];for(let r of e){if(r==="*"||r==="**")break;if(r.includes("*"))return null;n.push(r)}return n.length>0?n:null}a(yr,"anchoredSlicePrefix");function Sr(t,e){let n=Ut(t),r=n.length<t.length,o=n[0]==="src"||n[0]==="app"?n.slice(1):n;return J(e,n)||J(e,o)?!0:r?J(n,e)&&n.length<e.length||J(n,["src",...e])&&n.length<e.length+1||J(n,["app",...e])&&n.length<e.length+1:!1}a(Sr,"globOverlapsAnchored");function wr(t,e){for(let r=0;r<t.length;r+=1){if(t[r]!==e&&t[r]!=="*")continue;let o=t.slice(r+1);if(o.length>=2||o.some(i=>i==="*"||i==="**"))return!0}let n=Ut(t);return n.length<t.length&&(n.length===0||n.length===1&&(n[0]==="src"||n[0]==="app"))}a(wr,"globOverlapsBare");function Ir(t,e){let n=e.split(/[/\\]/).filter(Boolean).map(o=>o.toLowerCase());if(n.length===1&&n[0]&&!n[0].includes("*"))return wr(t,n[0]);let r=yr(e);return r?Sr(t,r):!1}a(Ir,"globOverlapsSliceEntry");function vr(t){let e=P(t.trim().replace(/\\/g,"/"));if(e.length===0)return"must be a non-empty path glob";if(e==="*"||e==="**")return"must not cover the whole tree";for(let n of e.split("/")){if(n.length===0||n==="."||n==="..")return"must be a path glob without empty, . or .. segments";if(!(n==="*"||n==="**")&&(n.includes("*")||n.includes("?")||n.includes("{")||n.includes("[")))return"* matches one whole path segment. ** is a whole segment. A partial segment is not a wildcard."}return null}a(vr,"aliasGlobIssue");function br(t,e){let n=[];if(!Array.isArray(t))return n;let r=e==="stars";for(let o of t){if(typeof o!="string"||o.length===0)continue;let i=o.split(/[/\\]/).filter(Boolean).map(s=>s.toLowerCase());if(i.length===1&&i[0]&&!i[0].includes("*")){n.push({literals:[i[0],null]});continue}if(!i.some(s=>s==="**"||s.includes("*")&&s!=="*")&&i.includes("*")){if(r){let s=-1;for(let d=0;d<i.length;d+=1)i[d]!=="*"&&(s=d);if(s<0)continue;let l=i.filter((d,f)=>f>=s||d==="*").map(d=>d==="*"?null:d),c=i.slice(s).map(d=>d==="*"?null:d);n.push(c.length===l.length?{literals:l}:{literals:l,legacy:c});continue}n.push({literals:i.map(s=>s==="*"?null:s)})}}return n}a(br,"universeShapes");function de(t,e){return t.literals.length!==e.length?!1:t.literals.every((n,r)=>n===null||n===e[r])}a(de,"shapeMatches");function Ar(t,e){let n=P(t.trim().replace(/\\/g,"/"));if(n.length===0||n.split("/").some(i=>i.length===0||i==="."||i==="..")||n.includes("*")||!n.includes("/"))return M;let r=n.split("/").map(i=>i.toLowerCase());if(e.length===0||e.some(i=>de(i,r)))return M;if(e.some(i=>de(i,r.slice(0,-1))))return null;let o=new Set(e.filter(i=>i.legacy!==void 0&&!de({literals:i.legacy},r)&&de({literals:i.legacy},r.slice(0,-1))).map(i=>i.literals.map(s=>s??"*").join("/")));return o.size===1?null:o.size>1?fr:M}a(Ar,"aliasTargetIssue");function jt(t){let e=t[0];return(e==="src"||e==="app")&&t.length>1?[t,t.slice(1)]:[t]}a(jt,"aliasGlobVariants");function kr(t,e){let n=jt(t),r=jt(e);for(let o of n)if(x(o,e,0,0,new Map))return!0;for(let o of r)if(x(t,o,0,0,new Map))return!0;return!1}a(kr,"aliasesCanMatchSameFile");function x(t,e,n,r,o){let i=`${n}:${r}`,s=o.get(i);if(s!==void 0)return s;let l=!1;if(n===t.length&&r===e.length)l=!0;else if(n<t.length&&t[n]==="**")l=x(t,e,n+1,r,o)||r<e.length&&x(t,e,n,r+1,o);else if(r<e.length&&e[r]==="**")l=x(t,e,n,r+1,o)||n<t.length&&x(t,e,n+1,r,o);else if(n<t.length&&r<e.length){let c=t[n],d=e[r];(c===d||c==="*"||d==="*")&&(l=x(t,e,n+1,r+1,o))}return o.set(i,l),l}a(x,"globsCanMatchSame");var Gt="must be a filename with exactly one <Layer> token and no slash or wildcard (arkrules.<Layer>.json)";function Er(t,e){let n=t.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!I(r))return;let i=r.childSlices;if(!I(i)||i.arkRulesFile===void 0)return;let s=`$.rules[${o}].childSlices.arkRulesFile`,l=i.arkRulesFile;if(typeof l!="string"||l.length===0){e.push({path:s,message:Gt});return}(l.split("<Layer>").length!==2||/[*\\/]/.test(l)||l.includes(".."))&&e.push({path:s,message:Gt})})}a(Er,"validateChildSliceArkRulesFile");function Rr(t,e){let n=t.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!I(r))return;let i=r.childSlices;if(!I(i)||i.sliceAliases===void 0)return;let s=i.sliceAliases,l=`$.rules[${o}].childSlices.sliceAliases`;if(!Array.isArray(s)){e.push({path:l,message:"must be an array of { from, to } slice aliases"});return}let c=br(r.sliceFolders,r.sliceIdentity),d=[...Array.isArray(r.sliceFolders)?r.sliceFolders:[],...Array.isArray(i.sliceFolders)?i.sliceFolders:[]].filter(p=>typeof p=="string"&&p.length>0),f=[];s.forEach((p,m)=>{let h=`${l}[${m}]`;if(!I(p)){e.push({path:h,message:"must be an object with from and to"});return}for(let y of Object.keys(p))y!=="from"&&y!=="to"&&y!=="pinned"&&y!=="reason"&&e.push({path:fe(h,y),message:"unknown field"});let S=p.from,u=p.to;if(typeof S!="string"||S.trim().length===0)e.push({path:`${h}.from`,message:"must be a non-empty path glob"});else{let y=vr(S);if(y)e.push({path:`${h}.from`,message:y});else{let g=hr(mr(S));d.some(v=>Ir(g,v))&&e.push({path:`${h}.from`,message:pr});for(let v of f)if(kr(v,g)){e.push({path:h,message:gr});break}f.push(g)}}if(typeof u!="string"||u.trim().length===0)e.push({path:`${h}.to`,message:M});else{let y=Ar(u,c);y&&e.push({path:`${h}.to`,message:y})}})})}a(Rr,"validateChildSliceAliases");function pe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}a(pe,"isObject");function F(t,e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?`${t}.${e}`:`${t}[${JSON.stringify(e)}]`}a(F,"propertyPath");function L(t){return t===null?"null":Array.isArray(t)?"array":typeof t}a(L,"valueType");function Pr(t,e){let n="#/$defs/";if(t.startsWith(n))return e.$defs[t.slice(n.length)]}a(Pr,"resolveSchemaRef");function _(t,e,n,r,o){if(e.$ref){let i=Pr(e.$ref,r);if(!i){o.push({path:n,message:`schema reference ${e.$ref} cannot be resolved`});return}_(t,i,n,r,o);return}if(e.const!==void 0&&!Object.is(t,e.const)){o.push({path:n,message:`must equal ${JSON.stringify(e.const)}`});return}if(e.enum&&!e.enum.some(i=>Object.is(i,t))){o.push({path:n,message:`must be one of ${e.enum.map(String).join(", ")}`});return}if(e.type==="object"){if(!pe(t)){o.push({path:n,message:`must be an object; received ${L(t)}`});return}let i=e.properties??{};for(let s of e.required??[])t[s]===void 0&&o.push({path:F(n,s),message:"is required"});if(e.additionalProperties===!1)for(let s of Object.keys(t))s in i||o.push({path:F(n,s),message:"unknown field"});else if(e.additionalProperties!==void 0&&e.additionalProperties!==!0&&typeof e.additionalProperties=="object"){let s=e.additionalProperties;for(let l of Object.keys(t))l in i||_(t[l],s,F(n,l),r,o)}for(let[s,l]of Object.entries(i))t[s]!==void 0&&_(t[s],l,F(n,s),r,o);return}if(e.type==="array"){if(!Array.isArray(t)){o.push({path:n,message:`must be an array; received ${L(t)}`});return}if(e.minItems!==void 0&&t.length<e.minItems&&o.push({path:n,message:`must contain at least ${e.minItems} item(s)`}),e.uniqueItems){let i=t.map(s=>JSON.stringify(s));new Set(i).size!==i.length&&o.push({path:n,message:"must not contain duplicate items"})}e.items&&t.forEach((i,s)=>_(i,e.items,`${n}[${s}]`,r,o));return}if(e.type==="string"){if(typeof t!="string"){o.push({path:n,message:`must be a string; received ${L(t)}`});return}e.minLength!==void 0&&t.length<e.minLength&&o.push({path:n,message:`must contain at least ${e.minLength} character(s)`});return}if(e.type==="boolean"){typeof t!="boolean"&&o.push({path:n,message:`must be a boolean; received ${L(t)}`});return}if(e.type==="integer"){if(!Number.isInteger(t)){o.push({path:n,message:`must be an integer; received ${L(t)}`});return}e.minimum!==void 0&&t<e.minimum&&o.push({path:n,message:`must be at least ${e.minimum}`})}}a(_,"validateSchemaNode");function ge(t){if(typeof t!="string")return null;let e=t.trim().replace(/^@/,"").toLowerCase();return e.length>0?e:null}a(ge,"normalizeStewardId");function qt(t){let e=ge(t);return!e||Oe(e)||e.includes(" ")||e.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(e)}a(qt,"isGitHubHandle");function Cr(t){if(typeof t!="string")return!1;let e=t.trim().toLowerCase();if(!e.includes("@")||e.includes(" ")||Oe(e))return!1;let n=e.split("@");if(n.length!==2||!n[0]||/\s/.test(e))return!1;let r=n[1].lastIndexOf(".");return r>0&&r<n[1].length-1}a(Cr,"isGitHubEmail");function xr(t){if(typeof t!="string")return null;let e=t.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return e&&qt(e[1])?ge(e[1]):null}a(xr,"githubHandleFromEmail");function zt(t){let e=xr(t);if(e)return e;let n=ge(t);return!n||Oe(n)?null:qt(n)||Cr(n)?n:null}a(zt,"canonicalStewardId");var Lr=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function Oe(t){let e=ge(t);return!e||Lr.test(e)}a(Oe,"isAutomationAuthor");var A="1.3",Or=["public","auth","admin","internal"];function $r(t){return t?.optional===!0||t?.reserved===!0||t?.allowEmpty===!0}a($r,"isFutureHouseLayer");function Dr(t){let e=t&&typeof t=="object"?t.owners:void 0;if(!Array.isArray(e)||e.length===0)return;let n=e.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}a(Dr,"layerOwnersList");function yi(t){return t?.requireLayerOwners!==!0||!Array.isArray(t.layers)?[]:t.layers.filter(e=>!$r(e)&&!Dr(e)).map(e=>e.name)}a(yi,"layersMissingRequiredOwners");function Si(t){return`Add a GitHub handle or email to ${t}'s owners in ark.config.json (/ark-adopt).`}a(Si,"missingLayerOwnersNextAction");var me="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",Jt=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Nr=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Tr(){let t=[];for(let e of Jt)for(let n of Jt)e===n||Nr.has(`${e}->${n}`)||t.push({from:e,to:n,allowed:!1});return t}a(Tr,"createDefaultRules");var he=Tr(),$e=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],b={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Yt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:me,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:me,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:A,default:A},name:{type:"string",minLength:1},include:{...b,minItems:1,default:["src"]},exclude:{...b,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:he,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...b,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{description:"A project-relative ArkRules path, or a list of paths merged into one catalog for this layer. A string keeps today's behaviour. An older build that types this value as a string rejects an array at config load.",oneOf:[{type:"string",minLength:1},{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",minLength:1}}]},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...b,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...b,minItems:1},exclude:b,intentPrefixes:b,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...Or]},owners:{...b,minItems:1},forbiddenGlobals:b,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...b,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"],description:"How a starred sliceFolders prefix is named. Absent and path keep today's ids (every literal and star binding). stars keeps the last literal plus every star binding (a star before the last literal is kept too), so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...b,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:Ht,childSlices:Kt}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...b,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...b,minItems:1}}},arkRun:xt,arkOrder:Lt}},R=class extends Error{static{a(this,"ArkConfigValidationError")}issues;source;constructor(e,n){super(`Invalid ArkGate config (${e}):
2
- ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
3
- `)}`),this.name="ArkConfigValidationError",this.source=e,this.issues=n}};function Mr(t,e){let n=t.arkRules;if(!(n===void 0||!pe(n)))for(let[r,o]of Object.entries(n)){let i=F("$.arkRules",r);if(typeof o=="string"){o.length===0&&e.push({path:i,message:"must be a non-empty relative path string"});continue}if(!Array.isArray(o)||o.length===0){e.push({path:i,message:"must be a non-empty path string or an array of paths"});continue}let s=new Set;o.forEach((l,c)=>{let d=`${i}[${c}]`;if(typeof l!="string"||l.length===0){e.push({path:d,message:"must be a non-empty relative path string"});return}s.has(l)&&e.push({path:d,message:"duplicate path"}),s.add(l)})}}a(Mr,"validateArkRulesRefs");function Fr(t,e){let n=t.layers;Array.isArray(n)&&n.forEach((r,o)=>{if(!r||typeof r!="object"||Array.isArray(r)||!("owners"in r))return;let i=r.owners;Array.isArray(i)&&i.forEach((s,l)=>{typeof s=="string"&&(zt(s)||e.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a(Fr,"validateLayerOwners");function _r(t){let e={...t,$schema:t.$schema===void 0?me:t.$schema,schemaVersion:t.schemaVersion===void 0?A:t.schemaVersion,include:t.include===void 0?["src"]:t.include,layers:t.layers===void 0?[]:t.layers,rules:t.rules===void 0?he.map(n=>({...n})):t.rules};return t.arkRun!==void 0&&(e.arkRun=Ot(t.arkRun)),t.arkOrder!==void 0&&(e.arkOrder=$t(t.arkOrder)),e}a(_r,"defaultedConfig");function Br(t){return t===A?null:t==="unversioned"?"unversioned":t==="1.0"||t==="1.1"||t==="1.2"?t:null}a(Br,"migratedFromOf");function jr(){let t=new Set([A]);for(let e of $e)e.from!=="unversioned"&&t.add(e.from),t.add(e.to);return t}a(jr,"knownInputVersions");function Gr(t,e="ark.config.json"){if(!pe(t))throw new R(e,[{path:"$",message:`must be an object; received ${L(t)}`}]);let n=jr(),r=t.schemaVersion===void 0?"unversioned":typeof t.schemaVersion=="string"?t.schemaVersion:null;if(r===null)throw new R(e,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(t.schemaVersion)}; expected ${A}`}]);if(r!=="unversioned"&&!n.has(r))throw new R(e,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${A}`}]);let o=r,i={...t},s=0;for(;o!==A&&s<$e.length+1;){s+=1;let l=$e.find(c=>c.from===o);if(!l)throw new R(e,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${A}`}]);o=l.to,i.schemaVersion=o}if(o!==A)throw new R(e,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${A}`}]);return{candidate:_r(i),migratedFrom:Br(r)}}a(Gr,"migrateArkConfig");function Hr(t,e="ark.config.json"){let{candidate:n,migratedFrom:r}=Gr(t,e),o=[];if(_(n,Yt,"$",Yt,o),Nt(n,o),Tt(n,o),Fr(n,o),Vt(n,o),Mr(n,o),o.length>0)throw new R(e,o);return{config:n,migratedFrom:r}}a(Hr,"loadArkConfigContract");function wi(t,e="ark.config.json"){let n;try{n=JSON.parse(t)}catch(r){throw new R(e,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Hr(n,e)}a(wi,"parseArkConfigJson");function Xt(t){let e={$schema:typeof t.$schema=="string"&&t.$schema.length>0?t.$schema:me,schemaVersion:A};for(let[n,r]of Object.entries(t))n!=="$schema"&&n!=="schemaVersion"&&(e[n]=r);return e}a(Xt,"withArkConfigMetadata");var Zt={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},Kr=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function De(t){let e=(t.intentPrefixes??[]).filter(n=>n.trim().length>0);return e.length>0?e:Kr.find(n=>n.layer===t.name)?.prefixes??[]}a(De,"effectiveIntentPrefixes");function Qt(t){let e=new Set(t.layers.filter(r=>De(r).length>0).map(r=>r.name)),n=new Set;for(let r of t.rules??[])if(!(r.allowed!==!1||r.peerIsolation===!0))for(let o of[r.from,r.to])e.has(o)||n.add(o);return[...n].sort()}a(Qt,"unresolvableLayerFlowLayers");function bi(t,e){return e.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(i=>({layer:r.name,layerIndex:o,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:r})=>t.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}a(bi,"resolveIntentLayer");function Vr(t){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(t)}a(Vr,"looksLikeArkIntent");function Ai(t){if(!t.publishCall)return[];let e=[];return(t.rawIntentName!==void 0&&Vr(t.rawIntentName)||t.objectHasIntent)&&e.push({ruleId:"RAW_EVENT_PUBLISH",message:Zt.RAW_EVENT_PUBLISH}),t.arkPublishCandidate&&!t.hasSource&&e.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Zt.PUBLISH_MISSING_SOURCE}),e}a(Ai,"classifyPublishFacts");function Wr(t){return t.endsWith(".")?t:`${t}.`}a(Wr,"normalizePrefix");function Ur(t,e){let n=t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0;return(e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0)-n}a(Ur,"byLongestPrefix");function Ne(t){let e=t.layers.map(o=>({...o,prefixes:o.prefixes.map(Wr)})),n=[...e].sort(Ur),r=[...t.rules??[]];return{name:t.name,layers:e,rules:r,resolveLayer(o){return e.find(i=>i.match?.(o))?.name??n.find(i=>i.prefixes.some(s=>o.startsWith(s)))?.name}}}a(Ne,"createArchitectureProfile");function Te(t,e={}){return Ne({name:e.name??t.name??"ark.config.json",layers:t.layers.map((n,r)=>({name:n.name,prefixes:[...De(n)],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:t.rules??[]})}a(Te,"createArchitectureProfileFromArkConfig");var qr=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],Y=Ne({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:qr,rules:he.map(t=>({...t}))}),zr={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function Jr(t={}){let e=t.rootDir??"src",n=t.optionalLayers??!0,r=e==="."?"":`${e}/`;return Xt({include:t.include??[e],layers:Y.layers.map(o=>({name:o.name,patterns:(zr[o.name]??[o.name]).map(i=>`${r}${i}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...Y.rules]})}a(Jr,"createElevenLayerArkConfig");var X=class{static{a(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(e,n){if(this.intents.has(e))throw new Error(`Intent "${e}" is already registered. Intent names must be unique within a registry.`);let r=a(i=>({intent:e,payload:i,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:e,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(e,o),n?.dependsOn)for(let i of n.dependsOn)this.declareDependency(e,i);if(n?.produces)for(let i of n.produces)this.declareProduction(e,i);return o}declareDependency(e,n){this.dependencies.has(e)||this.dependencies.set(e,new Set),this.dependencies.get(e).add(n)}declareProduction(e,n){this.productions.has(e)||this.productions.set(e,new Set),this.productions.get(e).add(n)}get(e){return this.intents.get(e)}list(){return Array.from(this.intents.values())}getDependencies(e){let n=this.dependencies.get(e);return n?Array.from(n):[]}getProductions(e){let n=this.productions.get(e);return n?Array.from(n):[]}getAllRelationships(){let e=[];for(let[n,r]of this.dependencies.entries())for(let o of r)e.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)e.push({from:n,to:o,kind:"produces"});return e}has(e){return this.intents.has(e)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var en=new X;function Yr(t,e){return en.define(t,e)}a(Yr,"defineIntent");function Me(){return new X}a(Me,"createIntentRegistry");var Xr=en;var tn=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Fe(t){if(!t||typeof t!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!tn.some(n=>t.startsWith(n)))return{valid:!1,reason:`Intent "${t}" must start with one of: ${tn.join(", ")}`};let e=t.slice(t.indexOf(".")+1);return!e||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(e)?{valid:!1,reason:`Intent "${t}" has an invalid segment after the layer prefix`}:{valid:!0}}a(Fe,"validateIntentName");var O=class extends Error{static{a(this,"PolicyViolationError")}violations;constructor(e){let n=e.map(r=>`- ${r.policyName}: ${r.message}`).join(`
4
- `);super(`Hard policy violation(s) detected:
5
- ${n}`),this.name="PolicyViolationError",this.violations=e}};var B=class{static{a(this,"PolicyEngine")}policies=[];constructor(e=[]){for(let n of e)this.add(n)}add(e){if(this.policies.some(n=>n.name===e.name))throw new Error(`Policy "${e.name}" is already registered in this engine.`);this.policies.push(e)}getPolicies(){return[...this.policies]}evaluate(e){let n=[];for(let i of this.policies){let s=i.check(e);if(s!==!0){if(s===!1){n.push({policyName:i.name,severity:i.severity,message:`Policy "${i.name}" was violated.`});continue}if(Array.isArray(s))for(let l of s)n.push({policyName:i.name,severity:i.severity,message:l.message,details:l.details});else n.push({policyName:i.name,severity:i.severity,message:s.message,details:s.details})}}let r=n.filter(i=>i.severity==="hard"),o=n.filter(i=>i.severity==="soft");return{passed:n.length===0,violations:n,hardViolations:r,softViolations:o}}enforce(e){let n=this.evaluate(e);if(n.hardViolations.length>0)throw new O(n.hardViolations);return n}clear(){this.policies.length=0}};function Z(t){let e=t.severity??"soft";return{name:t.name,severity:e,tags:t.tags,owner:t.owner,version:t.version,rationale:t.rationale,enforcementMode:t.enforcementMode,deprecated:t.deprecated,replacedBy:t.replacedBy,check:t.check}}a(Z,"definePolicy");function Zr(t){let e=t.indexOf(".");return e>=0?t.slice(0,e):t}a(Zr,"defaultLayerOf");function nn(t,e){return e.resolveLayer?.(t)??Zr(t)}a(nn,"resolveLayer");function Qr(t,e,n){return t===n.from&&e===n.to}a(Qr,"matchesRule");function _e(t){let e=t.name??"Layer isolation",n=t.severity??"hard";return Z({name:e,severity:n,tags:["layer"],check:a(r=>{let o=[...(r.edges??[]).filter(s=>s.kind==="declared"||s.kind==="produces").map(s=>({from:s.from,to:s.to})),...(r.relationships??[]).filter(s=>s.kind==="dependsOn").map(s=>({from:s.from,to:s.to}))],i=[];for(let s of o){let l=nn(s.from,t),c=nn(s.to,t);for(let d of t.rules)!d.allowed&&Qr(l,c,d)&&i.push({policyName:e,severity:n,message:d.message??`Layer violation: ${s.from} (${l}) must not relate to ${s.to} (${c})`})}return i.length>0?i:!0},"check")})}a(_e,"defineLayerPolicy");function Be(t){return t.tags?.includes("layer")??!1}a(Be,"isLayerPolicy");var rn={layerIsolation(){return rn.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return _e({name:"Clean architecture matrix",severity:"hard",rules:[{from:"Domain",to:"Adapter",allowed:!1},{from:"Domain",to:"Application",allowed:!1},{from:"Adapter",to:"Application",allowed:!1},{from:"Adapter",to:"Domain",allowed:!1}]})}};function je(t,e={}){return _e({name:e.name??`${t.name} layer policy`,severity:e.severity??"hard",rules:t.rules,resolveLayer:t.resolveLayer})}a(je,"defineArchitectureProfilePolicy");function Ge(t){return e=>({event:e,relationships:t.intentRegistry?.getAllRelationships(),edges:t.dependencyGraph?.getEdges()})}a(Ge,"buildPublishPolicyContext");function eo(t){return Z(t)}a(eo,"definePublishPolicy");var Q=class extends Error{static{a(this,"UnregisteredIntentError")}intentName;constructor(e){super(`Intent "${e}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=e}},ee=class extends Error{static{a(this,"InvalidIntentNameError")}intentName;reason;constructor(e,n){super(`Invalid intent name "${e}": ${n}`),this.name="InvalidIntentNameError",this.intentName=e,this.reason=n}},te=class extends Error{static{a(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},ne=class extends Error{static{a(this,"EventContractViolationError")}intentName;issues;constructor(e,n){super(`Event contract violation for "${e}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=e,this.issues=n}},j=class extends Error{static{a(this,"UnknownEventSourceError")}intentName;source;constructor(e,n){super(n?`Event "${e}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${e}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=e,this.source=n}},$=class extends Error{static{a(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(e,n){super(`Source-bound publisher for "${e}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=e,this.attemptedSource=n}},re=class extends Error{static{a(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(e,n,r,o,i){super(i??`Observed layer violation: "${e}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=e,this.intentName=n,this.fromLayer=r,this.toLayer=o}},G=class extends Error{static{a(this,"ArkKernelConfigError")}code;layers;constructor(e){super(`Hard observed-layer-flow enforcement cannot resolve layer(s) ${e.map(n=>`"${n}"`).join(", ")}: they appear in a deny rule but declare no intentPrefixes (and are not canonical 11-layer names), so no intent maps to them and the rule would never fire. Add intentPrefixes to those layers in ark.config.json, or pass enforceObservedLayerFlow: 'soft' | 'off' explicitly.`),this.name="ArkKernelConfigError",this.code="ARKRUN_LAYER_FLOW_UNRESOLVABLE",this.layers=e}};function oe(t,e){if(!(!e.strictRegistry&&!e.validateIntentNaming)){if(e.validateIntentNaming){let n=Fe(t);if(!n.valid)throw new ee(t,n.reason)}if(e.strictRegistry&&e.intentRegistry&&!e.intentRegistry.has(t))throw new Q(t)}}a(oe,"assertIntentAllowed");function on(t,e){if(e.requireKnownSource){if(!t.metadata.source||t.metadata.source==="unknown")throw new j(t.intent);if(e.intentRegistry&&!e.intentRegistry.has(t.metadata.source))throw new j(t.intent,t.metadata.source)}}a(on,"assertSourceAllowed");function ie(t,e){if(!e.eventContracts)return;let n=e.eventContracts.validate(t);if(!n.ok&&(e.strictEventContracts||n.contract))throw new ne(t.intent,n.issues)}a(ie,"assertContractAllowed");function H(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}a(H,"isPlainRecord");function K(t){return Array.isArray(t)?t.map(K):H(t)?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,K(n)])):t}a(K,"clonePatchValue");function He(t,e,n="payload"){let r={...t};for(let[o,i]of Object.entries(e)){let s=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=K(i);continue}if(H(r[o])&&H(i)){r[o]=He(r[o],i,s);continue}if(Array.isArray(r[o])&&Array.isArray(i)){r[o]=Ke(r[o],i,s);continue}throw new Error(`Interceptor patch cannot overwrite existing ${s}.`)}return r}a(He,"mergeRecordPatch");function Ke(t,e,n="payload"){let r=[...t];return e.forEach((o,i)=>{let s=`${n}[${i}]`;if(i>=r.length||r[i]===void 0){r[i]=K(o);return}if(H(r[i])&&H(o)){r[i]=He(r[i],o,s);return}if(Array.isArray(r[i])&&Array.isArray(o)){r[i]=Ke(r[i],o,s);return}throw new Error(`Interceptor patch cannot overwrite existing ${s}.`)}),r}a(Ke,"mergeArrayPatch");function sn(t,e){if(Array.isArray(e)){if(t===void 0)return K(e);if(!Array.isArray(t))throw new Error("Array interceptor patch requires an array payload.");return Ke(t,e)}if(t===void 0)return K(e);if(!H(t))throw new Error("Object interceptor patch requires an object payload.");return He(t,e)}a(sn,"applyPayloadPatch");async function an(t,e){if(t.metadata.allowInterception===!1)return t;let n=[...e.interceptorsForIntent(t.intent)],r=t;for(let o of n){let i=[];try{if(await Promise.resolve(o.interceptor({event:r,intercept:a(c=>{i.push(c)},"intercept")})),i.length===0)continue;let s=new Date().toISOString(),l={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:s}]}};for(let c of i)l={...l,payload:sn(l.payload,c),metadata:{...l.metadata}};ie(l,{eventContracts:e.eventContracts,strictEventContracts:e.strictEventContracts}),r=l,o.lastInterceptedAt=s,e.appendTrace({type:"event.intercepted",timestamp:s,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:i.length}}),await e.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:i.length})}catch(s){await to(o,r,s,e)}}return r}a(an,"applyInterceptors");async function to(t,e,n,r){let o=n instanceof Error?n.message:String(n);r.appendTrace({type:"interceptor.error",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{registrationId:t.registrationId,interceptorId:t.interceptorId,error:o}}),await r.recordAudit("interceptor.error",e,{registrationId:t.registrationId,interceptorId:t.interceptorId,error:o})}a(to,"recordInterceptorError");function Sn(t){if(t==="deny"||t==="deny-cross-parent")return t;if(t!==null&&typeof t=="object"){let e=t.mode;if(e==="deny-cross-parent")return e}}a(Sn,"sharedImportsSliceMode");function bs(t){if(t===null||typeof t!="object")return[];let e=t.stopAt;return Array.isArray(e)?e.filter(n=>typeof n=="string"&&n.length>0):[]}a(bs,"sharedImportsSliceStopAt");var ln=new Map;function cn(t){return/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t}a(cn,"escapeLiteral");function ve(t){let e="";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="\\"&&n+1<t.length){let o=t[n+1];if("*?{}[],".includes(o)||o==="\\"){e+="\\"+o,n+=1;continue}e+="/";continue}e+=r}return e}a(ve,"normalizeGlobSeparators");function no(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="\\"){n+=1;continue}if(r==="{")e+=1;else if(r==="}"&&(e-=1,e<0))return!1}return e===0}a(no,"bracesBalanced");function W(t){let e=ln.get(t);if(e)return e;let n=ve(t),r=no(n),o="",i=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=cn(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",i+=1):c==="}"&&r&&i>0?(o+=")",i-=1):c===","&&r&&i>0?o+="|":o+=cn(c)}let s=new RegExp(`^${o}$`);return ln.set(t,s),s}a(W,"globToRegExp");function ro(t){return ve(String(t)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(ro,"concreteGlobSegments");function oo(t,e){let n=ve(String(t)),r=ro(n),o=n.replace(/\*/g,"").length,i=r.length*1e4+o;if(e==null||e==="")return i;let s=String(e).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let d of r){let f=-1;for(let p=l;p<s.length;p+=1)if(s[p]===d){f=p;break}if(f<0)return i;c=f,l=f+1}return(c+1)*1e6+r.length*1e4+o}a(oo,"patternSpecificity");function As(t,e){let n=String(t).split(/[/\\]/).join("/"),r,o=-1;for(let i of e??[])if(!(i.exclude??[]).some(s=>W(s).test(n))){for(let s of i.patterns??[])if(W(s).test(n)){let l=oo(s,n);l>o&&(o=l,r=i.name)}}return r}a(As,"layerForRelativePath");function se(t,e,n){return In(t,e,n==="stars"?"stars":"path")}a(se,"sliceIdForPath");function We(t,e){return In(t,e?[...e]:void 0,wn)}a(We,"legacyStarsSliceIdForPath");var wn="stars-4.8.23";function In(t,e,n){if(!e?.length)return;let r=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return;let o=new Set;for(let i of e){if(typeof i!="string"||i.length===0)continue;let s=io(i);if(s.anchored){let l=ao(r,s.anchored,n);if(l)return l;continue}s.bare!==void 0&&o.add(s.bare)}return fo(r,o)}a(In,"sliceIdWithBinding");var ye=new Map;function io(t){let e=ye.get(t);if(e)return e;let n={};return vn(t)?n={anchored:so(t)}:!t.includes("/")&&!t.includes("\\")&&!t.includes("*")&&(n={bare:t.toLowerCase()}),ye.size>=1024&&ye.clear(),ye.set(t,n),n}a(io,"parsedSliceFolder");function vn(t){let e=t.split(/[/\\]/).filter(n=>n.length>0);return e.length<2||e[0]==="*"||e[0]==="**"?!1:e.some(n=>n==="*")}a(vn,"isAnchoredSliceEntry");function so(t){return t.split(/[/\\]/).filter(e=>e.length>0).map(e=>e.toLowerCase())}a(so,"anchoredSlicePattern");function ao(t,e,n){let r=An(t,e[0]??"");for(let o of r){let i=lo(t,e,o,n);if(i)return i}}a(ao,"anchoredSliceIdFromPattern");function lo(t,e,n,r="path"){let o=[],i=[],s=-1,l=n;for(let c=0;c<e.length;c+=1){let d=e[c];if(d==="*"){if(l>=t.length-1){for(let f=c;f<e.length;f+=1)if(e[f]!=="*")return;break}o.push(t[l].toLowerCase()),i.push(!0),l+=1;continue}if(d==="**"||l>=t.length||t[l].toLowerCase()!==d)return;o.push(t[l].toLowerCase()),i.push(!1),s=o.length-1,l+=1}if(o.length!==0)return r===wn?s<0?void 0:o.slice(s).join("/"):r==="stars"?s<0?void 0:o.filter((c,d)=>d>=s||i[d]).join("/"):o.join("/")}a(lo,"bindAnchoredSlice");function bn(t){let e=-1;for(let r=0;r<t.length;r+=1)t[r]!=="*"&&(e=r);if(e<0)return null;let n=[];for(let r=0;r<t.length;r+=1)(r>=e||t[r]==="*")&&n.push(r);return n}a(bn,"starsKeptSegmentIndexes");function ks(t){let e=[];for(let n of t??[]){if(!n||n.sliceIdentity!=="stars")continue;let r=new Map,o=new Map;for(let i of n.sliceFolders??[]){if(typeof i!="string"||i.length===0)continue;let s=co(i);if(!s)continue;let l=i.split(/[/\\]/).filter(f=>f.length>0).join("/").toLowerCase(),c=o.get(s)??new Set;if(c.has(l))continue;c.add(l),o.set(s,c);let d=r.get(s)??[];d.push(i),r.set(s,d)}for(let[i,s]of r)s.length<2||e.push({from:n.from,to:n.to,stem:i,paths:s,message:uo(n.from,n.to,s,i)})}return e}a(ks,"sliceIdentityCollisions");function co(t){if(!vn(t))return;let e=t.split(/[/\\]/).filter(r=>r.length>0).map(r=>r.toLowerCase());if(e.some(r=>r==="**"))return;let n=bn(e);if(n)return n.map(r=>e[r]).join("/")}a(co,"starsIdentityStem");function uo(t,e,n,r){let o=n.length===2?`${n[0]} and ${n[1]}`:`${n.slice(0,-1).join(", ")}, and ${n[n.length-1]}`;return`${t} \u2192 ${e}: sliceIdentity "stars" gives one slice id to ${o}. They bind as ${r}.`}a(uo,"formatSliceIdentityCollision");function fo(t,e){if(e.size!==0){for(let n=0;n<t.length-1;n+=1)if(e.has(t[n].toLowerCase())&&!(n+1>=t.length-1))return`${t[n].toLowerCase()}/${t[n+1].toLowerCase()}`}}a(fo,"bareSliceId");function po(t){let e=new Set;for(let n of t??[]){let o=ve(String(n)).split("/").filter(Boolean);for(let i=0;i<o.length;i+=1){let s=o[i];if((s==="**"||s==="*")&&i>0){let l=o[i-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&e.add(l)}}}return[...e]}a(po,"inferSliceFoldersFromPatterns");function ze(t,e,n){if(Array.isArray(t.sliceFolders)&&t.sliceFolders.length>0)return t.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===e);return po(r?.patterns)}a(ze,"resolveSliceFolders");function dn(t){return String(t).split(/[/\\]/).filter(e=>!!e&&e!==".").map(e=>e.toLowerCase())}a(dn,"normalizeSegments");function ae(t){let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)}a(ae,"trimTrailingSlashes");var go=["src","app"];function An(t,e){let n=(t[0]??"").toLowerCase(),r=e.toLowerCase();return go.includes(n)&&r!==n?[0,1]:[0]}a(An,"anchorOffsets");function mo(t){let e=ae(t.replace(/^[./]+/,""));return e==="*"||e==="**"}a(mo,"isBlanketRoot");function Se(t,e){if(!t||!e?.length)return!1;let n=String(t).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=dn(n);for(let i of e){if(typeof i!="string"||i.length===0||mo(i))continue;if(i.includes("*")){let c=ae(i.toLowerCase());if(W(c).test(r)||W(`${c}/**`).test(r))return!0;continue}let s=dn(i);if(s.length===0)continue;let l=An(o,s[0]??"");for(let c of l){if(c+s.length>o.length)continue;let d=!0;for(let f=0;f<s.length;f+=1)if(o[c+f]!==s[f]){d=!1;break}if(d)return!0}}return!1}a(Se,"pathUnderSharedRoot");function un(t,e){let n=String(t).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=e.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}a(un,"sliceMatchesDeclaration");function fn(t,e,n){return!t?.length||!e||!n?!1:t.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&un(r.from,e)&&un(r.to,n))}a(fn,"crossSliceEdgeAllowed");function ho(t){if(!t.fromPath)return{denied:!0,reason:"missing-path"};if(t.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let e=!!t.fromSlice||t.fromShared===!0;if(!t.toPath)return e?t.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!t.toSlice||t.toShared===!0;return!e||!n?{denied:!0,reason:"unclassifiable-path"}:t.sharedImportsSlice==="deny"&&t.fromShared===!0&&t.toSlice&&!t.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!t.fromSlice||!t.toSlice?{denied:!1}:t.fromSlice===t.toSlice?{denied:!1}:t.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}a(ho,"peerIsolationDecision");function kn(t){return ae(t.trim().replace(/\\/g,"/")).toLowerCase()}a(kn,"aliasGlobPattern");function En(t,e){let n=kn(t);if(!n||n==="*"||n==="**")return!1;let r=String(e).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),o=qe(r),i=W(n),l=(n.split("/").pop()??"").includes("*")?null:W(`${n}/**`),c=a(d=>i.test(d)||l!==null&&l.test(d),"hit");return c(r)||o!==r&&c(o)}a(En,"aliasGlobMatches");function Es(t,e){return!t||!e?.length?!1:Se(t,[...e])?!0:e.some(n=>typeof n=="string"&&En(n,t))}a(Es,"pathMatchesSharedWalkStop");function Je(t){let e=kn(t).split("/").filter(Boolean);return e.length<2||e.some(n=>n.includes("*")||n==="."||n==="..")?null:{universeId:e.slice(0,-1).join("/"),childId:e.join("/")}}a(Je,"splitAliasTarget");function Rn(t,e){for(let n of e.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&En(n.from,t))return n;return null}a(Rn,"firstSliceAliasEntry");function yo(t,e){let n=Rn(t,e);return n?Je(n.to):null}a(yo,"firstSliceAlias");function Ue(t,e,n){if(!t)return{};let r=n??e.sliceFolders,o=se(t,r?[...r]:void 0,e.sliceIdentity),i=we(t,o,e.childSlices);if(o||i.childId||i.mismatched)return i.childId?{universeId:o,childId:i.childId}:{universeId:o};let s=yo(t,e);return s?{universeId:s.universeId,childId:s.childId}:{}}a(Ue,"resolveGovernedSlice");function So(t){let e=[];for(let n of t??[]){if(typeof n!="string"||n.length===0)continue;let r=n.split(/[/\\]/).filter(Boolean).map(l=>l.toLowerCase());if(r.length===1&&r[0]&&!r[0].includes("*")){e.push({literals:[r[0],null],legacy:[r[0],null]});continue}if(r.some(l=>l==="**"||l.includes("*")&&l!=="*"))continue;let o=bn(r);if(!o||!r.includes("*"))continue;let i=a(l=>l==="*"?null:l,"star"),s=o.find(l=>r[l]!=="*")??0;e.push({literals:o.map(l=>i(r[l]??"")),legacy:r.slice(s).map(i)})}return e}a(So,"starsUniverseShapes");function pn(t,e){return t.length===e.length&&t.every((n,r)=>n===null||e[r]==="*"||n===e[r])}a(pn,"literalsMatch");function V(t,e){let n=e.split("/").filter(Boolean).map(i=>i.toLowerCase()),r=So(t);if(n.length===0||r.some(i=>pn(i.literals,n)))return[];let o=new Set;for(let i of r)if(i.legacy.length!==i.literals.length&&pn(i.legacy,n)){let s=[...n],l=i.literals.length-i.legacy.length;o.add([...i.literals.slice(0,l).map(()=>"*"),...s].join("/"))}return[...o].sort()}a(V,"legacyStarsIdTargets");function Pn(t,e){if(t.sliceIdentity!=="stars")return;let n=Je(e);if(n)return V(t.sliceFolders,n.universeId).length===1?n.universeId:void 0}a(Pn,"legacyAliasUniverse");function gn(t,e,n){let r=Ue(t,e,n);if(!t||e.sliceIdentity!=="stars")return r;if(r.universeId){let o=Rn(t,e);if(!se(t,[...n],e.sliceIdentity)&&o&&Pn(e,o.to)!==void 0)return{...r,legacyAlias:!0,legacyUniverse:r.universeId,legacyChild:r.childId};let s=We(t,n),l=e.childSlices,c=l?.sliceIdentity==="stars"?We(t,l.sliceFolders):void 0;return{...r,...s?{legacyUniverse:s}:{},...c&&r.childId?{legacyChild:c}:{}}}return r}a(gn,"placeForPair");function wo(t,e,n,r){let o=gn(n,t,e),i=gn(r,t,e),s=o.legacyUniverse,l=i.legacyUniverse,c=a((S,u)=>{if(!S.legacyAlias||u.legacyAlias||!u.universeId||u.legacyUniverse?.toLowerCase()!==S.universeId?.toLowerCase())return S;let y=S.childId?.split("/").pop();return{...S,universeId:u.universeId,...y?{childId:`${u.universeId}/${y}`}:{}}},"adopt"),d=c(o,i),f=c(i,o),p=fn(t.allowedCrossSlice,d.universeId,f.universeId)||t.sliceIdentity==="stars"&&(s!==d.universeId||l!==f.universeId)&&fn(t.allowedCrossSlice,s,l),m=t.childSlices?.sliceIdentity==="stars"&&o.legacyChild!==void 0&&i.legacyChild!==void 0&&o.legacyChild!==i.legacyChild&&Cn(t.childSlices.allowedCrossSlice,o.legacyChild,i.legacyChild),h=a(S=>({...S.universeId?{universeId:S.universeId}:{},...S.childId?{childId:S.childId}:{}}),"strip");return{from:h(d),to:h(f),crossSliceAllowed:p,legacyChildAllowed:m}}a(wo,"resolveGovernedSlicePair");function Io(t,e){switch(t){case"cross-slice":return`cross-slice edge ${e.fromSlice??"?"} \u2192 ${e.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"shared-imports-slice":return`shared root imports slice ${e.toSlice??"?"} (${e.fromPath??"?"} \u2192 ${e.toPath??"?"}). The wall is direct-only.`;case"unclassifiable-path":{let n=[e.fromSlice?void 0:e.fromPath,e.toSlice?void 0:e.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}a(Io,"peerIsolationDenyExplanation");function vo(t,e){return`cross-parent slice ${t??"?"} \u2192 ${e??"?"}. The child wall cannot allow another universe.`}a(vo,"crossParentExplanation");function bo(t,e,n){return`cross-sibling slice ${t} \u2192 ${e} inside ${n}.`}a(bo,"crossSiblingExplanation");function Ao(t){return`universe common imports child ${t}. parentMayImportChild is off.`}a(Ao,"parentImportsChildExplanation");function mn(t){if(!t)return;let e=t.split("/").filter(Boolean);return e.length>0?e[e.length-1]:void 0}a(mn,"universePairLabel");function ko(t,e){if(!t||!e?.length)return!1;let n=t.toLowerCase();return e.some(r=>typeof r=="string"&&r.length>0&&r.toLowerCase()===n)}a(ko,"isCommonFolderName");function we(t,e,n){if(!t||!n?.sliceFolders?.length)return{};let r=se(t,n.sliceFolders,n.sliceIdentity);if(!r||!e)return{};let o=r.toLowerCase(),i=e.toLowerCase();if(o===i)return{};if(!o.startsWith(`${i}/`))return{mismatched:{childId:r,universeId:e}};let s=o.slice(i.length+1).split("/")[0];return ko(s,n.commonFolders)?{}:{childId:r}}a(we,"resolveChildSliceId");function Eo(t){return ae(t.trim().replace(/\\/g,"/")).toLowerCase()}a(Eo,"siblingEntryKey");function qe(t){return t.replace(/^(?:src|app)\//,"")}a(qe,"stripSrcOrApp");function Ro(t,e){let n=t.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=qe(e);if(!r)return!1;let o=qe(n);return n===r||n.startsWith(`${r}/`)||o===r||o.startsWith(`${r}/`)}a(Ro,"pathUnderSubtree");function Po(t,e,n){if(!e||!n?.length)return!1;let r=e.toLowerCase();for(let o of n){if(typeof o!="string")continue;let i=Eo(o);if(!(!i||i.includes("*"))&&(r===i||t&&Ro(t,i)))return!0}return!1}a(Po,"importerInEnforcedSubtree");function Co(t,e,n){return t==null||t==="deny"?!1:t==="advisory"?!0:t.default==="deny"?!1:!Po(e,n,t.enforce)}a(Co,"siblingCrossingAdvisory");function Ie(t){if(typeof t!="string")return null;let e=ae(t.trim().replace(/\\/g,"/")).toLowerCase();if(!e.includes("/"))return null;let n=e.split("/");for(let r of n)if(r.length===0||r==="."||r===".."||r.includes("*")&&r!=="*")return null;return n}a(Ie,"childSlicePatternSegments");function hn(t,e){let n=Ie(t),r=Ie(e);if(!n||!r||n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let i=n[o];if(i!=="*"&&i!==r[o])return!1}return!0}a(hn,"childSlicePatternMatches");function Cn(t,e,n){if(!t?.length)return!1;for(let r of t)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&hn(r.from,e)&&hn(r.to,n))return!0;return!1}a(Cn,"childCrossSliceAllowed");function xo(t,e){let n=Ie(t),r=Ie(e);if(!n||!r)return!1;let o=n.slice(0,-1),i=r.slice(0,-1);if(o.length!==i.length)return!0;for(let s=0;s<o.length;s+=1){let l=o[s],c=i[s];if(l==="*"||c==="*"||l!==c)return!0}return!1}a(xo,"childAllowanceSpansUniverses");function Lo(t){let e=ho({fromPath:t.fromPath,toPath:t.toPath,folderCount:t.folderCount,fromSlice:t.fromSlice,toSlice:t.toSlice,fromShared:t.fromShared,toShared:t.toShared,crossSliceAllowed:t.crossSliceAllowed,sharedImportsSlice:Sn(t.rule.sharedImportsSlice)});if(e.denied){let s=!!t.rule.childSlices&&e.reason==="cross-slice";return{crossing:e.reason==="cross-slice"?"cross-parent":"fail-closed",decision:"deny",...s?{reasonId:"CROSS_PARENT_SLICE"}:{},explanation:s?vo(t.fromSlice,t.toSlice):Io(e.reason??"missing-path",{fromPath:t.fromPath,toPath:t.toPath,fromSlice:t.fromSlice,toSlice:t.toSlice}),peerIsolationReason:e.reason,fromUniverse:t.fromSlice,toUniverse:t.toSlice}}let n=t.rule.childSlices;if(!n||!t.fromSlice||!t.toSlice||t.fromSlice!==t.toSlice||!t.toPath)return{crossing:"none",decision:"allow",fromUniverse:t.fromSlice,toUniverse:t.toSlice};let r=t.fromChild??we(t.fromPath,t.fromSlice,n).childId,o=t.toChild??we(t.toPath,t.toSlice,n).childId,i={crossing:"none",decision:"allow",fromUniverse:t.fromSlice,toUniverse:t.toSlice};return r&&o&&r!==o?t.legacyChildAllowed||Cn(n.allowedCrossSlice,r,o)?i:{crossing:"cross-sibling",decision:Co(n.siblings,t.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:bo(r,o,t.fromSlice),fromUniverse:t.fromSlice,toUniverse:t.toSlice}:!r&&o&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:Ao(o),fromUniverse:t.fromSlice,toUniverse:t.toSlice}:i}a(Lo,"evaluateNestedSliceWall");function xn(t){return t?.crossing==="cross-sibling"||t?.crossing==="parent-imports-child"}a(xn,"isChildWallCrossing");function Rs(t,e){return xn(e)?t?.childSlices?.message:t?.message}a(Rs,"sliceConsumerMessage");function Ps(t){let e=t.verdict.explanation,n=xn(t.verdict),r=n?t.childMessage:t.ruleMessage;if(t.surface==="intent"){let o=t.defaultMessage??`${t.fromLayer} must not reference ${t.toLayer} intent.`;return n&&e?`${t.childMessage??o} ${e}`:t.verdict.reasonId&&e?`${o} ${e}`:e&&t.verdict.peerIsolationReason!=="cross-slice"?`${o} ${e}`:r?e?`${r} (${e})`:r:o}if(r)return e?`${r} (${e})`:r;if(e){let o=t.kind??"import";return`${t.fromLayer} must not ${o} another slice of ${t.toLayer} (${t.fromPath} \u2192 ${t.toPath}): ${e}`}return`${t.fromLayer} must not ${t.kind??"import"} ${t.toLayer}.`}a(Ps,"composeSliceDenialMessage");function Cs(t){if(!t||t.decision==="allow")return{};let e=mn(t.fromUniverse),n=mn(t.toUniverse);return{...t.reasonId?{reasonId:t.reasonId}:{},...t.reasonId&&e&&n?{universeFrom:e,universeTo:n}:{},...t.decision==="advisory"?{failsStrict:!1,severity:"warning"}:{}}}a(Cs,"sliceFindingExtras");function xs(t,e){let n=[],r=new Set,o=new Set;for(let i of t??[])if(i?.peerIsolation&&i.allowed===!1&&n.push(...Oo(i,e)),!!i?.childSlices){if(!i.peerIsolation||i.allowed!==!1){n.push({ruleId:"CONFIG_CHILD_SLICES_INERT",failsStrict:!1,fromLayer:i.from,toLayer:i.to,message:`${i.from} \u2192 ${i.to}: childSlices is inert on this rule and enforces nothing. The child wall runs only inside a universe wall. Add "peerIsolation": true and "allowed": false to the same rule, or remove childSlices.`});continue}for(let s of e){let l=se(s,i.sliceFolders,i.sliceIdentity),c=we(s,l,i.childSlices);if(!c.mismatched)continue;let d=`${i.from}\0${i.to}\0${c.mismatched.universeId}\0${c.mismatched.childId}`;r.has(d)||(r.add(d),n.push({ruleId:"CONFIG_CHILD_SLICE_EXTENDS",failsStrict:!1,fromLayer:i.from,toLayer:i.to,path:s,message:`${i.from} \u2192 ${i.to}: child id ${c.mismatched.childId} does not extend universe id ${c.mismatched.universeId} (${s}).`}))}for(let s of i.childSlices.allowedCrossSlice??[]){if(!s||typeof s.from!="string"||typeof s.to!="string"||!xo(s.from,s.to))continue;let l=`${s.from.trim().toLowerCase()}\0${s.to.trim().toLowerCase()}`;o.has(l)||(o.add(l),n.push({ruleId:"CONFIG_CHILD_SLICE_CROSS_UNIVERSE",failsStrict:!1,fromLayer:i.from,toLayer:i.to,message:`childSlices.allowedCrossSlice ${s.from} \u2192 ${s.to} cannot cross the universe wall. The universe wall still denies that edge.`}))}}return n}a(xs,"childSliceConfigFindings");function yn(t,e){let n=new Map;if(!t?.length)return n;for(let r of e){if(typeof r!="string")continue;let o=se(r,[...t],"stars"),i=We(r,t);if(!o||!i||o===i)continue;let s=n.get(i)??new Set;s.add(o),n.set(i,s)}return n}a(yn,"observedIdsByLegacy");function Ve(t,e,n,r){let o=r?`/${r}`:"",i=`${e[0]??t}${o}`,s=[...n.get(t.toLowerCase())??[]].sort().map(l=>`${l}${o}`);return s.length===1?`${s[0]}`:s.length>1?`${i} (one entry per module: ${s.join(", ")})`:i}a(Ve,"newIdHint");function Oo(t,e){let n=[],r=a(i=>n.push({ruleId:"CONFIG_SLICE_LEGACY_STARS_ID",failsStrict:!1,fromLayer:t.from,toLayer:t.to,message:`${t.from} \u2192 ${t.to}: ${i} It keeps its 4.8.23 meaning for this release only.`}),"push"),o=t.childSlices;if(t.sliceIdentity==="stars"){let i=yn(t.sliceFolders,e);for(let s of o?.sliceAliases??[]){if(!s||typeof s.to!="string")continue;let l=Je(s.to);if(!l||Pn(t,s.to)===void 0)continue;let c=V(t.sliceFolders,l.universeId),d=l.childId.split("/").pop();r(`sliceAliases to "${s.to}" is a 4.8.23 stars id (the star before the last literal was dropped). The id is now ${Ve(l.universeId,c,i,d)}; write that instead.`)}for(let s of t.allowedCrossSlice??[]){if(!s||typeof s.from!="string"||typeof s.to!="string")continue;let l=[s.from,s.to].filter(d=>d.includes("/")&&V(t.sliceFolders,d).length>0);if(l.length===0)continue;let c=a(d=>l.includes(d)?Ve(d,V(t.sliceFolders,d),i):d,"rename");r(`allowedCrossSlice ${s.from} \u2192 ${s.to} names a 4.8.23 stars id. The ids are now ${c(s.from)} \u2192 ${c(s.to)}; write those instead.`)}}if(o?.sliceIdentity==="stars"){let i=yn(o.sliceFolders,e);for(let s of o.allowedCrossSlice??[]){if(!s||typeof s.from!="string"||typeof s.to!="string")continue;let l=[s.from,s.to].filter(d=>V(o.sliceFolders,d).length>0);if(l.length===0)continue;let c=a(d=>l.includes(d)?Ve(d,V(o.sliceFolders,d),i):d,"rename");r(`childSlices.allowedCrossSlice ${s.from} \u2192 ${s.to} names a 4.8.23 stars id. The ids are now ${c(s.from)} \u2192 ${c(s.to)}; write those instead.`)}}return n}a(Oo,"legacyStarsIdFindings");function Ls(t){if(t!==null&&typeof t=="object"){let e=t.ratchet;if(e===!0)return"always";if(e===!1)return"never"}return"auto"}a(Ls,"siblingRatchetMode");function Ln(t,e,n,r){return $o(t,e,n,r)?.rule}a(Ln,"findDeniedEdgeRule");function $o(t,e,n,r){for(let o of t??[])if(!(o.from!==e||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let i=r?.fromPath,s=r?.toPath,l=ze(o,e,r?.layers),c=wo(o,l,i,s),d=c.from,f=c.to,p=d.universeId,m=f.universeId,h=Lo({rule:o,fromPath:i,toPath:s,folderCount:l.length,fromSlice:p,toSlice:m,fromChild:d.childId,toChild:f.childId,fromShared:!p&&Se(i,o.sharedRoots),toShared:!m&&Se(s,o.sharedRoots),crossSliceAllowed:c.crossSliceAllowed,legacyChildAllowed:c.legacyChildAllowed});if(h.decision!=="allow")return{rule:o,peerIsolationReason:h.peerIsolationReason,fromSlice:p,toSlice:m,sliceVerdict:h};continue}if(e!==n)return{rule:o}}}a($o,"findDeniedEdgeDecision");function Os(t,e,n,r){let o=r?.fromPath,i=r?.toPath;if(!(!o||!i))for(let s of t??[]){if(s.from!==e||s.to!==n||s.allowed!==!1||!s.peerIsolation||Sn(s.sharedImportsSlice)==="deny")continue;let l=ze(s,e,r?.layers),c=Ue(o,s,l).universeId,d=Ue(i,s,l).universeId;if(!(c||!d)&&Se(o,s.sharedRoots))return{fromPath:o,toPath:i,toSlice:d}}}a(Os,"findSharedImportsSliceBridge");function $s(t,e,n){return ze(t,e,n)}a($s,"peerSliceFolders");async function On(t,e){if(e.mode==="off"||!e.architectureProfile)return;let n=t.metadata.source;if(!n||n==="unknown")return;let r=e.architectureProfile,o=r.resolveLayer(n),i=r.resolveLayer(t.intent);if(!o||!i)return;let s=Ln(r.rules.filter(f=>f.peerIsolation!==!0),o,i);if(!s)return;let l=e.mode,c=s.message??`Observed layer violation: "${n}" (${o}) must not produce "${t.intent}" (${i}).`,d={source:n,intent:t.intent,fromLayer:o,toLayer:i,severity:l,message:c,rule:s};if(e.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:d}),await e.recordAudit("layer.observedViolation",t,d),l==="hard")throw new re(n,t.intent,o,i,c)}a(On,"assertObservedLayerFlowAllowed");async function $n(t,e){let n=e.getPolicyContext(t),r;try{r=e.policyEngine.enforce(n)}catch(o){throw o instanceof O&&(e.appendTrace({type:"policy.hardViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{violations:o.violations}}),await e.recordAudit("policy.hardViolation",t,{violations:o.violations})),o}r.softViolations.length>0&&(e.appendTrace({type:"policy.softViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{violations:r.softViolations}}),await e.recordAudit("policy.softViolation",t,{violations:r.softViolations}),e.onSoftViolation&&await e.safeHook(()=>e.onSoftViolation(r,t),"onSoftViolation",t))}a($n,"enforcePublishPolicy");function Do(t,e){t.history.push(e),t.maxHistorySize!==void 0&&t.history.length>t.maxHistorySize&&t.history.splice(0,t.history.length-t.maxHistorySize)}a(Do,"appendHistory");function D(t,e){t.trace.push(e),t.maxHistorySize!==void 0&&t.trace.length>t.maxHistorySize&&t.trace.splice(0,t.trace.length-t.maxHistorySize);for(let n of t.traceSinks)try{n(e)}catch{}}a(D,"appendTrace");async function le(t,e,n,r){if(t.auditTrail)try{await t.auditTrail.record({type:e,source:n.metadata.source,intent:n.intent,correlationId:n.metadata.correlationId,causationId:n.metadata.causationId,subject:n.intent,details:r})}catch(o){D(t,{type:"hook.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{hook:"auditTrail",error:o instanceof Error?o.message:String(o)}})}}a(le,"recordAudit");async function Dn(t,e){let n={intent:e.intent,source:e.metadata.source,suggestion:"Publish through a registered intent creator so strict registry, contracts, and agent tooling share one source of truth."};D(t,{type:"event.rawPublish",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:n}),await le(t,"event.rawPublish",e,n)}a(Dn,"recordRawPublishDiagnostic");async function Nn(t,e,n,r){let o={event:e,publishedAt:new Date().toISOString(),subscribersNotified:n};Do(t,o);let i=await t.eventBuffer?.enqueue(e,r);return D(t,{type:"event.published",timestamp:o.publishedAt,intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{subscribersNotified:n}}),await le(t,"event.published",e,{subscribersNotified:n}),{record:o,bufferRecord:i??void 0}}a(Nn,"recordSuccessfulPublish");async function Tn(t,e,n,r){let o=t.eventBuffer;if(o)try{r.ok?await o.markDispatched(n):await o.markFailed(n,r.error)}catch(i){D(t,{type:"hook.error",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{hook:"eventBuffer",error:i instanceof Error?i.message:String(i)}})}}a(Tn,"settleBufferRecord");async function Mn(t,e,n,r){let o={transport:r,error:n instanceof Error?n.message:String(n)};D(t,{type:"event.handoffFailed",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:o}),await le(t,"event.handoffFailed",e,o)}a(Mn,"recordHandoffFailure");function Ye(t,e,n){return{...t,...e,occurredAt:e.occurredAt||t.occurredAt||new Date().toISOString(),source:e.source||t.source||"unknown",kernelInstanceId:e.kernelInstanceId??t.kernelInstanceId??n,eventVersion:e.eventVersion??t.eventVersion,schemaVersion:e.schemaVersion??t.schemaVersion,allowInterception:e.allowInterception??t.allowInterception,interceptions:e.interceptions??t.interceptions,correlationId:e.correlationId??t.correlationId,causationId:e.causationId??t.causationId,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}}a(Ye,"enrichMetadata");function No(){let t=globalThis.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID().replace(/-/g,"").slice(0,10):Math.random().toString(36).slice(2,12).padEnd(10,"0")}a(No,"randomNonce");var To=No(),Fn=new Map;function k(t){let e=(Fn.get(t)??0)+1;return Fn.set(t,e),`${t}-${Date.now()}-${To}-${e}`}a(k,"nextRuntimeId");function Mo(){return k("interceptor")}a(Mo,"nextInterceptorRegistrationId");var U=class{static{a(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;settleBufferOnLocalDelivery;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(e={}){if(this.onPublish=e.onPublish,this.onSoftViolation=e.onSoftViolation,this.onHandlerError=e.onHandlerError,this.eventContracts=e.eventContracts,this.strictEventContracts=e.strictEventContracts??!1,this.requireKnownSource=e.requireKnownSource??!1,this.architectureProfile=e.architectureProfile,this.enforceObservedLayerFlowMode=e.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=e.rethrowHandlerErrors??!1,this.settleBufferOnLocalDelivery=e.settleBufferOnLocalDelivery??!1,this.intentRegistry=e.intentRegistry,this.dependencyGraph=e.dependencyGraph,this.strictRegistry=e.strictRegistry??e.intentRegistry!==void 0,this.validateIntentNaming=e.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:e.maxHistorySize,traceSinks:[...e.traceSinks??[]],auditTrail:e.auditTrail,eventBuffer:e.eventBuffer??e.outbox,instanceId:e.instanceId},e.policyEngine?this.policyEngine=e.policyEngine:e.policies&&e.policies.length>0&&(this.policyEngine=new B(e.policies)),(this.policyEngine?.getPolicies()??e.policies??[]).some(Be)&&!e.intentRegistry&&!e.dependencyGraph&&!e.getPolicyContext)throw new te;e.getPolicyContext?this.getPolicyContext=e.getPolicyContext:e.intentRegistry||e.dependencyGraph?this.getPolicyContext=Ge({intentRegistry:e.intentRegistry,dependencyGraph:e.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(e,n,r,o){await this.dispatch(e,n,r,o)}async dispatch(e,n,r,o={}){let i=o.notifySubscribers!==!1,s=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,d=typeof e!="function";if(d){let u=e,y=r??n??{};c={...u,metadata:Ye(u.metadata,y,this.recording.instanceId)}}else{let u=e,y=n,g=r??{},v=u(y);c={...v,metadata:Ye(v.metadata,g,this.recording.instanceId)}}d&&this.strictRegistry&&await Dn(this.recording,c),oe(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),on(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),ie(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await an(c,{interceptorsForIntent:a(u=>this.interceptorsByIntent.get(u)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:a(u=>this.appendTrace(u),"appendTrace"),recordAudit:a((u,y,g)=>this.recordAudit(u,y,g),"recordAudit")}),ie(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await On(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:a(u=>this.appendTrace(u),"appendTrace"),recordAudit:a((u,y,g)=>this.recordAudit(u,y,g),"recordAudit")}),this.dependencyGraph?.registerEventFlow(c.metadata.source,c.intent);let f=[...this.subscriptionsByIntent.get(c.intent)??[]];this.policyEngine&&await $n(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:a(u=>this.appendTrace(u),"appendTrace"),recordAudit:a((u,y,g)=>this.recordAudit(u,y,g),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:a((u,y,g)=>this.safeHook(u,y,g),"safeHook")});let{bufferRecord:p}=await Nn(this.recording,c,i?f.length:0,o.tx);p&&o.onBufferRecord?.(p);let m=p!==void 0&&(o.settleBufferOnLocalDelivery??this.settleBufferOnLocalDelivery),h=(async()=>{i&&await Promise.all(f.map(u=>this.invokeHandler(u,c))),l&&this.onPublish&&await this.safeHook(()=>this.onPublish(c),"onPublish",c)})(),S=m?h.then(()=>this.settleBufferRecord(c,p.id,{ok:!0}),async u=>{throw await this.settleBufferRecord(c,p.id,{ok:!1,error:u}),u}):h;return s?await S:S.then(void 0,()=>{}),c}async settleBufferRecord(e,n,r){await Tn(this.recording,e,n,r)}async recordHandoffFailure(e,n,r){await Mn(this.recording,e,n,r)}createPublisher(e){let n=typeof e=="string"?e:e.name;return oe(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:a(async(r,o,i={},s)=>{if(i.source&&i.source!==n)throw new $(n,i.source);await this.publish(r,o,{...i,source:n},s)},"publish")}}subscribe(e,n){let r=typeof e=="string"?e:e.name;oe(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let i=this.subscriptionsByIntent.get(r)??[];return i.push(o),this.subscriptionsByIntent.set(r,i),()=>{let s=this.subscriptions.indexOf(o);s>=0&&this.subscriptions.splice(s,1);let l=this.subscriptionsByIntent.get(r);if(!l)return;let c=l.indexOf(o);c>=0&&l.splice(c,1),l.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(e,n,r){let o=typeof e=="string"?e:e.name;oe(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let i={registrationId:Mo(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(i);let s=this.interceptorsByIntent.get(o)??[];return s.push(i),this.interceptorsByIntent.set(o,s),i.registrationId}unregisterInterceptor(e){let n=this.interceptors.find(i=>i.registrationId===e);if(!n)return!1;let r=this.interceptors.indexOf(n);r>=0&&this.interceptors.splice(r,1);let o=this.interceptorsByIntent.get(n.intentName);if(o){let i=o.indexOf(n);i>=0&&o.splice(i,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(e){return this.interceptors.filter(n=>!e||n.intentName===e).map(n=>({registrationId:n.registrationId,interceptorId:n.interceptorId,intent:n.intentName,createdAt:n.createdAt,lastInterceptedAt:n.lastInterceptedAt}))}getHistory(){return[...this.recording.history]}clearHistory(){this.recording.history.length=0}getTrace(){return[...this.recording.trace]}clearTrace(){this.recording.trace.length=0}appendTrace(e){D(this.recording,e)}async recordAudit(e,n,r){await le(this.recording,e,n,r)}async invokeHandler(e,n){try{await Promise.resolve(e.handler(n))}catch(r){if(this.appendTrace({type:"handler.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{error:r instanceof Error?r.message:String(r)}}),await this.recordAudit("handler.error",n,{handlerIntent:e.intentName,error:r instanceof Error?r.message:String(r)}),this.onHandlerError&&await this.safeHook(()=>this.onHandlerError(r,n,e.intentName),"onHandlerError",n),this.rethrowHandlerErrors)throw r}}async safeHook(e,n,r){try{await Promise.resolve(e())}catch(o){this.appendTrace({type:"hook.error",timestamp:new Date().toISOString(),intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{hook:n,error:o instanceof Error?o.message:String(o)}}),await this.recordAudit("hook.error",r,{hook:n,error:o instanceof Error?o.message:String(o)})}}};function Fo(t){return new U(t)}a(Fo,"createEventBus");function _o(t){if(!(!t||t.length===0))return t.map(e=>typeof e=="object"&&e!==null&&"key"in e?String(e.key):String(e)).join(".")}a(_o,"formatStandardSchemaPath");function Bo(t){if(Array.isArray(t))return"array";if(t===null)return"object";let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="object"?e:"unknown"}a(Bo,"actualType");function jo(t,e){return t?`${t}.${e}`:e}a(jo,"formatPath");function _n(t,e,n,r,o){let i=Bo(t);if(e.type!=="unknown"&&i!==e.type){o.push({intent:r.intent,version:r.version,field:n,message:`Expected ${e.type}, received ${i}.`});return}if(e.enum&&!e.enum.some(s=>Object.is(s,t))&&o.push({intent:r.intent,version:r.version,field:n,message:"Value is not allowed by event contract enum."}),e.type==="object"&&e.fields){if(t===null||typeof t!="object"||Array.isArray(t)){o.push({intent:r.intent,version:r.version,field:n,message:"Nested object field must be a non-array object."});return}Bn(t,e.fields,r,o,n)}e.type==="array"&&e.items&&Array.isArray(t)&&t.forEach((s,l)=>{_n(s,e.items,`${n}[${l}]`,r,o)})}a(_n,"validateSchemaField");function Bn(t,e,n,r,o){for(let[i,s]of Object.entries(e)){let l=jo(o,i),c=t[i];if(c===void 0){s.required&&r.push({intent:n.intent,version:n.version,field:l,message:"Required field is missing."});continue}_n(c,s,l,n,r)}}a(Bn,"validateObjectSchema");var be=class{static{a(this,"EventContractRegistryImpl")}contracts=new Map;register(e){let n=this.key(e.intent,e.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...e})}get(e,n){return n?this.contracts.get(this.key(e,n)):this.list(e).at(-1)}list(e){return Array.from(this.contracts.values()).filter(n=>!e||n.intent===e)}validate(e){let n=e.metadata.eventVersion,r=this.get(e.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:e.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:e.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let i=e.payload!=null&&typeof e.payload=="object"?e.payload:void 0;if(r.schema){if(!i)o.push({intent:e.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(Bn(i,r.schema,r,o),r.allowAdditionalFields===!1)for(let s of Object.keys(i))r.schema[s]||o.push({intent:e.intent,version:r.version,field:s,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let s=r.standardSchema["~standard"].validate(e.payload);if(s instanceof Promise)o.push({intent:e.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(s.issues)for(let l of s.issues)o.push({intent:e.intent,version:r.version,field:_o(l.path),message:l.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(e,n){return`${e}@${n}`}};function Xe(){return new be}a(Xe,"createEventContractRegistry");function Go(){return k("outbox")}a(Go,"nextOutboxId");function jn(t){return{...t,event:{...t.event,metadata:{...t.event.metadata}}}}a(jn,"cloneRecord");var Ho=1e4,q=class{static{a(this,"InMemoryEventBuffer")}records=new Map;maxRecords;evictedPendingIds=new Set;evictedPendingCount=0;constructor(e={}){let n=e.maxRecords;this.maxRecords=typeof n=="number"&&!Number.isNaN(n)&&n>=0?n:1/0}get evictedPending(){return this.evictedPendingCount}trackEvictedPending(e){for(this.evictedPendingCount+=1,this.evictedPendingIds.add(e);this.evictedPendingIds.size>Ho;){let n=this.evictedPendingIds.values().next().value;this.evictedPendingIds.delete(n)}}settleEvicted(e){this.evictedPendingIds.delete(e)&&(this.evictedPendingCount-=1)}evictOverflow(){for(;this.records.size>this.maxRecords;){let e;for(let[n,r]of this.records)if(r.status!=="pending"){e=n;break}e===void 0&&(e=this.records.keys().next().value,this.trackEvictedPending(e)),this.records.delete(e)}}async enqueue(e){let n=new Date().toISOString(),r={id:Go(),event:e,status:"pending",attempts:0,createdAt:n,updatedAt:n};this.records.set(r.id,r);let o=jn(r);return this.evictOverflow(),o}async markDispatched(e){let n=this.records.get(e);if(!n){this.settleEvicted(e);return}n.status="dispatched",n.updatedAt=new Date().toISOString()}async markFailed(e,n){let r=this.records.get(e);if(!r){this.settleEvicted(e);return}r.status="failed",r.attempts+=1,r.error=n instanceof Error?n.message:String(n),r.updatedAt=new Date().toISOString()}async list(e){return Array.from(this.records.values()).filter(n=>!e||n.status===e).map(jn)}async clear(){this.records.clear(),this.evictedPendingIds.clear()}},Ko=q;function Ze(t){return`${t.from}->${t.to}`}a(Ze,"flowKey");function Gn(t){let e=new Set,n=[];for(let r of t){let o=Ze(r);e.has(o)||(e.add(o),n.push(r))}return n}a(Gn,"uniqueFlows");function Hn(t,e){let n=new Set(e.map(Ze));return t.filter(r=>!n.has(Ze(r)))}a(Hn,"difference");function Qe(t){let e=t.registry,n=t.eventBus,r=t.graph;return{report(){let o=e?e.getAllRelationships().filter(u=>u.kind==="produces").map(u=>({from:u.from,to:u.to})):[],i=o.length>0||!r?[]:r.getEdges().filter(u=>u.kind==="produces").map(u=>({from:u.from,to:u.to})),s=n?.getHistory().map(u=>({from:u.event.metadata.source,to:u.event.intent}))??[],l=s.length>0||!r?[]:r.getEdges().filter(u=>u.kind==="observed").map(u=>({from:u.from,to:u.to})),c=Gn([...o,...i]),d=Gn([...s,...l]),f=d.filter(u=>!u.from||u.from==="unknown"),p=e?Array.from(new Set(d.map(u=>u.from).filter(u=>u&&u!=="unknown"&&!e.has(u)))):[],m=e?Array.from(new Set(d.map(u=>u.to).filter(u=>!e.has(u)))):[],h=new Set(d.flatMap(u=>[u.from,u.to])),S=e?e.list().map(u=>u.name).filter(u=>!h.has(u)):[];return{generatedAt:new Date().toISOString(),declaredProductions:c,observedProductions:d,declaredButUnobserved:Hn(c,d),observedButUndeclared:Hn(d.filter(u=>u.from!=="unknown"),c),unknownSources:f,unregisteredObservedSources:p,unregisteredObservedIntents:m,registeredButNeverObserved:S}}}}a(Qe,"createObservabilityReporter");function Vo(){return k("audit")}a(Vo,"createAuditId");function Wo(t,e){return!(e.type&&t.type!==e.type||e.intent&&t.intent!==e.intent||e.correlationId&&t.correlationId!==e.correlationId||e.subject&&t.subject!==e.subject||e.since&&t.timestamp<e.since||e.until&&t.timestamp>e.until)}a(Wo,"matchesQuery");var Ae=class{constructor(e){this.maxRecords=e}maxRecords;static{a(this,"InMemoryAuditStore")}records=[];append(e){this.records.push(e),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(e={}){let n=this.records.filter(r=>Wo(r,e));return e.limit===void 0?[...n]:n.slice(-e.limit)}clear(){this.records.length=0}},et=class{constructor(e){this.store=e}store;static{a(this,"AuditTrailImpl")}async record(e){let n={id:Vo(),timestamp:e.timestamp??new Date().toISOString(),type:e.type,source:e.source,actor:e.actor,intent:e.intent,correlationId:e.correlationId,causationId:e.causationId,subject:e.subject,details:e.details};return await this.store.append(n),n}async query(e){return this.store.query(e)}async clear(){await this.store.clear()}};function tt(t={}){return new et(t.store??new Ae(t.maxRecords))}a(tt,"createAuditTrail");var nt=class{static{a(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(e,n,r="declared"){this.ensureNode(e),this.ensureNode(n),this.addEdge({from:e,to:n,kind:r})}registerEventFlow(e,n){this.ensureNode(e),this.ensureNode(n),this.addEdge({from:e,to:n,kind:"observed"})}getNodes(){return Array.from(this.nodes.values())}getEdges(){return[...this.edges]}toJSON(){return{nodes:this.getNodes(),edges:this.getEdges()}}toMermaid(){let e=`flowchart TD
6
- `;for(let r of this.edges){let o=r.kind?`|${r.kind}|`:"";e+=` ${this.safeId(r.from)} -->${o} ${this.safeId(r.to)}
7
- `}let n=new Set(this.edges.flatMap(r=>[r.from,r.to]));for(let r of this.nodes.keys())n.has(r)||(e+=` ${this.safeId(r)}
8
- `);return e.trim()}toLayerMermaid(e){let n=new Map;for(let i of this.nodes.keys()){let s=e.resolveLayer(i)??"Unclassified",l=n.get(s)??[];l.push(i),n.set(s,l)}let r=`flowchart TD
9
- `;for(let i of e.layers){let s=n.get(i.name)??[];if(s.length!==0){r+=` subgraph ${this.safeId(i.name)}[${i.name}]
10
- `;for(let l of s)r+=` ${this.safeId(l)}[${l}]
11
- `;r+=` end
12
- `}}let o=n.get("Unclassified")??[];if(o.length>0){r+=` subgraph Unclassified[Unclassified]
13
- `;for(let i of o)r+=` ${this.safeId(i)}[${i}]
14
- `;r+=` end
15
- `}for(let i of this.edges){let s=i.kind?`|${i.kind}|`:"";r+=` ${this.safeId(i.from)} -->${s} ${this.safeId(i.to)}
16
- `}return r.trim()}detectViolations(e=[]){let n=[],r=this.findSimpleCycles();r.length>0&&n.push(`Cycle detected: ${r.map(o=>o.join("->")).join(", ")}`);for(let o of e)try{let i=o(this.edges);i&&i.length&&n.push(...i)}catch(i){n.push(`Rule error: ${i.message}`)}return n}ensureNode(e){this.nodes.has(e)||this.nodes.set(e,{id:e})}addEdge(e){this.edges.some(r=>r.from===e.from&&r.to===e.to&&r.kind===e.kind)||this.edges.push(e)}findSimpleCycles(){let e=new Map;for(let l of this.edges)e.has(l.from)||e.set(l.from,[]),e.get(l.from).push(l.to);let n=[],r=new Set,o=[],i=a(l=>{r.add(l),o.push(l);for(let c of e.get(l)||[])if(!r.has(c))i(c);else if(o.includes(c)){let d=o.indexOf(c),f=o.slice(d).concat(c);n.push(f)}o.pop()},"dfs");for(let l of e.keys())r.has(l)||i(l);let s=new Set(n.map(l=>l.join("->")));return Array.from(s).map(l=>l.split("->"))}safeId(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}};function rt(){return new nt}a(rt,"createDependencyGraph");function ot(t,e,n={}){let r=n.requireRegisteredTargets??!1;for(let o of t.getAllRelationships())r&&!t.has(o.to)||(o.kind==="dependsOn"?e.registerDependency(o.from,o.to,"declared"):e.registerDependency(o.from,o.to,"produces"))}a(ot,"syncRegistryToGraph");var it=class{static{a(this,"MetadataRegistryImpl")}entities=new Map;entity(e,n,r={}){if(this.entities.has(e)&&!r.allowOverwrite)throw new Error(`Entity metadata "${e}" is already registered.`);let o={name:e,fields:{},...n};return this.entities.set(e,o),o}getEntity(e){return this.entities.get(e)}listEntities(){return Array.from(this.entities.values())}findEntitiesByIntent(e){return this.listEntities().filter(n=>n.emits?.includes(e)||n.consumes?.includes(e))}validate(){let e=[];for(let n of this.entities.values()){n.name.trim()||e.push({entity:n.name,message:"Entity name is required."});for(let[r,o]of Object.entries(n.fields))r.trim()||e.push({entity:n.name,field:r,message:"Field name is required."}),(!o.type||typeof o.type!="string")&&e.push({entity:n.name,field:r,message:"Field type must be a non-empty string."}),o.relation&&!this.entities.has(o.relation.entity)&&e.push({entity:n.name,field:r,message:`Related entity "${o.relation.entity}" is not registered.`})}return{ok:e.length===0,issues:e}}toJSON(){return this.listEntities()}};function st(){return new it}a(st,"createMetadataRegistry");var ke=class{static{a(this,"InMemoryReadModelStore")}states=new Map;load(e){return this.states.get(e)}save(e,n){this.states.set(e,n)}clear(e){e?this.states.delete(e):this.states.clear()}};function Uo(t){return typeof t.initialState=="function"?t.initialState():t.initialState}a(Uo,"initialState");var at=class{static{a(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(e={}){this.store=e.store??new ke,this.auditTrail=e.auditTrail}register(e){if(this.definitions.has(e.name))throw new Error(`Projection "${e.name}" is already registered.`);this.definitions.set(e.name,e),this.checkpoints.set(e.name,{projection:e.name,appliedCount:0})}list(){return Array.from(this.definitions.values())}async apply(e){let n=[];for(let r of this.definitions.values()){if(!r.sourceIntents.includes(e.intent))continue;let o=await this.store.load(r.name)??Uo(r),i=await r.project(e,o);await this.store.save(r.name,i);let s=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(s?.appliedCount??0)+1,lastIntent:e.intent,lastCorrelationId:e.metadata.correlationId,updatedAt:new Date().toISOString()}),await this.auditTrail?.record({type:"projection.applied",source:"Kernel.ProjectionRegistry",intent:e.intent,correlationId:e.metadata.correlationId,causationId:e.metadata.causationId,subject:r.name,details:{projection:r.name}}),n.push(r.name)}return n}async getState(e){return this.store.load(e)}getCheckpoint(e){return this.checkpoints.get(e)}getCheckpoints(){return Array.from(this.checkpoints.values())}async clear(){await this.store.clear();for(let e of this.definitions.values())this.checkpoints.set(e.name,{projection:e.name,appliedCount:0})}};function lt(t){return new at(t)}a(lt,"createProjectionRegistry");var ct="1.0";function qo(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}a(qo,"policyId");var dt=class{constructor(e){this.data=e}data;static{a(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function ut(t={}){let e=t.registry,n=t.policyEngine,r=t.metadata,o=t.graph,i=t.profile,s=t.projections,l=t.eventContracts,c=t.observability,d=e?e.list().map(g=>({name:g.name,dependencies:e.getDependencies(g.name),productions:e.getProductions(g.name)})):[],f=e?e.getAllRelationships():[],p=n?n.getPolicies().map(g=>({id:qo(g.name),name:g.name,severity:g.severity,tags:g.tags?[...g.tags]:void 0,owner:g.owner,version:g.version,rationale:g.rationale,enforcementMode:g.enforcementMode,deprecated:g.deprecated,replacedBy:g.replacedBy,description:g.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],m=r?r.toJSON():[],h=o?o.toJSON():{nodes:[],edges:[]},S=m.filter(g=>(g.emits?.length??0)>0||(g.consumes?.length??0)>0).map(g=>({entity:g.name,emits:g.emits,consumes:g.consumes})),u=s?s.list().map(g=>({name:g.name,sourceIntents:g.sourceIntents,checkpoint:s.getCheckpoint(g.name)})):[],y={schemaVersion:"1.0",version:Ct,exportedAt:new Date().toISOString(),intents:d,relationships:f,policies:p,entities:m,graph:h,architecture:i?{profile:i.name,layers:i.layers,rules:i.rules}:void 0,projections:u,eventContracts:l?.list()??[],observability:c?.report(),links:{entityIntents:S}};return new dt(y)}a(ut,"createArkManifest");function Kn(t){return k(t)}a(Kn,"createWorkflowId");function ft(t){return t instanceof Error?t.message:String(t)}a(ft,"errorMessage");function zo(t){return new Promise(e=>{setTimeout(e,t)})}a(zo,"sleep");async function Jo(t,e,n){let r=new AbortController;if(e===void 0)return t(r.signal);let o,i=new Promise((s,l)=>{o=setTimeout(()=>{let c=new Error(`Workflow step "${n}" timed out after ${e}ms.`);r.abort(c),l(c)},e)});try{return await Promise.race([t(r.signal),i])}finally{o&&clearTimeout(o)}}a(Jo,"withTimeout");var Ee=class{static{a(this,"InMemoryWorkflowStore")}snapshots=new Map;save(e,n){let r=this.snapshots.get(e.id);if(r&&r.version!==e.version)throw new Error(`Optimistic concurrency conflict for workflow ${e.id}`);let o=(e.version??0)+1;this.snapshots.set(e.id,{...e,version:o,context:{...e.context}}),e.version=o}get(e,n){let r=this.snapshots.get(e);return r?{...r,context:{...r.context}}:void 0}list(e){return Array.from(this.snapshots.values()).filter(n=>!e||n.workflowName===e).map(n=>({...n,context:{...n.context}}))}claim(e,n,r){let o=Date.now();for(let i of this.snapshots.values()){if(r&&i.workflowName!==r||i.status!=="running"&&i.status!=="compensating")continue;let s=i.expiresAt?new Date(i.expiresAt).getTime()<o:!0;if(!i.ownerId||s){i.ownerId=e,i.expiresAt=new Date(o+n).toISOString();let l=(i.version??0)+1;return i.version=l,this.snapshots.set(i.id,{...i,context:{...i.context}}),{...i,context:{...i.context}}}}}clear(){this.snapshots.clear()}},pt=class{constructor(e,n={}){this.bus=e;this.options=n;this.store=n.store??new Ee}bus;options;static{a(this,"WorkflowEngineImpl")}definitions=new Map;store;register(e){if(this.definitions.has(e.name))throw new Error(`Workflow "${e.name}" is already registered.`);let n=new Set;for(let r of e.steps){if(n.has(r.name))throw new Error(`Workflow "${e.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(e.name,e),e.startOn){let r=e.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(e.name,r.mapEventToPayload(o))})}}async start(e,n,r={}){let o=this.definitions.get(e);if(!o)throw new Error(`Workflow "${e}" is not registered.`);let i=new Date().toISOString(),s={id:r.id??Kn(e),version:0,workflowName:e,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:i,updatedAt:i};return await this.store.save(s,r.tx),await this.audit("workflow.started",s,{workflowName:e}),this.executeSnapshot(s,o,r.tx)}async resume(e,n={}){let r=await this.get(e,n.tx);if(!r)return;if(r.status!=="running"&&r.status!=="compensating")return r;let o=this.definitions.get(r.workflowName);if(!o)throw new Error(`Workflow "${r.workflowName}" is not registered.`);return this.executeSnapshot(r,o,n.tx)}async executeSnapshot(e,n,r){try{let o=n.steps.filter(i=>!e.completedSteps.includes(i.name));for(let i of o)await this.runStep(e,i,r);return e.status="completed",e.currentStep=void 0,e.completedAt=new Date().toISOString(),e.updatedAt=e.completedAt,await this.store.save(e,r),await this.audit("workflow.completed",e,{workflowName:e.workflowName}),{...e,context:{...e.context}}}catch(o){throw await this.compensate(e,n.steps,o,r),e.status="failed",e.currentStep=void 0,e.error=ft(o),e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.failed",e,{workflowName:e.workflowName,error:e.error,failedStep:e.failedStep}),o}}async get(e,n){return this.store.get(e,n)}async list(e){return this.store.list(e)}async runStep(e,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},i=Math.max(1,o.attempts);e.currentStep=n.name,e.updatedAt=new Date().toISOString(),await this.store.save(e,r);for(let s=1;s<=i;s+=1){e.attempts[n.name]=s,await this.store.save(e,r);let l;try{l=await Jo(c=>Promise.resolve(n.execute(e.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(s<i){o.delayMs&&await zo(o.delayMs);continue}throw e.failedStep=n.name,e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.step.failed",e,{step:n.name,attempt:s,error:ft(c)}),c}l&&Object.assign(e.context,l),e.completedSteps.push(n.name),e.currentStep=void 0,e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.step.completed",e,{step:n.name,attempt:s});return}throw new Error(`Workflow step "${n.name}" did not complete.`)}async compensate(e,n,r,o){e.status="compensating",e.updatedAt=new Date().toISOString(),await this.store.save(e,o);let i=n.filter(s=>e.completedSteps.includes(s.name));for(let s=i.length-1;s>=0;s-=1){let l=i[s];if(l.compensate)try{await Promise.resolve(l.compensate(e.context,this.bus,r)),await this.audit("workflow.compensation.completed",e,{step:l.name})}catch(c){await this.audit("workflow.step.failed",e,{step:l.name,compensation:!0,error:ft(c)})}}}async audit(e,n,r){await this.options.auditTrail?.record({type:e,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function Re(t,e){return new pt(t,e)}a(Re,"createWorkflowEngine");function Yo(t,e,n={}){let r=Re(e,n),o={name:t.name,steps:t.steps};r.register(o);let i=n.id??Kn(t.name),s="idle",l=[];return{id:i,definition:t,get status(){return s},get completedSteps(){return[...l]},async run(c){s="running",l=[];try{let d=await r.start(t.name,c,{id:i});s=d.status==="waiting"?"idle":d.status,l=[...d.completedSteps]}catch(d){let f=await r.get(i);throw s=f?.status==="waiting"?"idle":f?.status??"failed",l=f?.completedSteps??[],d}}}}a(Yo,"createSaga");async function Vn(t,e={}){let n=At({host:e.host,port:e.port,nodeEnv:e.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await import("./inspectorListen-6DQVJ4DC.js");return r(t,{bind:n,sseIntervalMs:e.sseIntervalMs})}a(Vn,"startArkRunInspector");var Xo=new Set(["singleton","transient"]);function Wn(t){let e={id:t.id,lifetime:t.lifetime,uses:[...t.uses],reactsTo:[...t.reactsTo],raises:[...t.raises],sends:[...t.sends]};if(t.extendedInfo){let n=t.extendedInfo;e.extendedInfo={...n.label?{label:n.label}:{},...n.architectureKind?{architectureKind:n.architectureKind}:{},...n.tags?{tags:[...n.tags]}:{},...n.group?{group:n.group}:{},...n.metadata?{metadata:{...n.metadata}}:{}}}return e}a(Wn,"cloneComponent");function Zo(t){if(t===void 0)return"singleton";if(typeof t=="string"&&Xo.has(t))return t;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}a(Zo,"closedLifetime");function Un(){let t=new Map,e=new Map,n=new Set;function r(s){let l=t.get(s);if(!l)throw new Error(`ArkRun component "${s}" is not registered.`);return l}a(r,"mustRecord");function o(s,l){if(!l.factory)throw new Error(`ArkRun component "${s}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(s))throw new Error(`ArkRun component "${s}" has a circular resolve.`);n.add(s);try{return l.factory()}finally{n.delete(s)}}a(o,"instantiate");function i(s,l){if(e.has(s))return e.get(s);let c=o(s,l);return e.set(s,c),c}return a(i,"singleton"),{register(s){let l=typeof s?.id=="string"?s.id.trim():"";if(!l)throw new Error("ArkRun component id must be a non-empty string.");if(t.has(l))throw new Error(`ArkRun component "${l}" is already registered.`);let c=Zo(s.lifetime),d=St({id:l,lifetime:c,uses:s.uses,reactsTo:s.reactsTo,raises:s.raises,sends:s.sends,extendedInfo:s.extendedInfo});if(!d)throw new Error("ArkRun component id must be a non-empty string.");let f=typeof s.factory=="function"?s.factory:void 0;return t.set(l,{component:d,factory:f}),Wn(d)},resolve(s){let l=r(s);return l.component.lifetime==="transient"?o(s,l):i(s,l)},resolveSingleton(s){let l=r(s);if(l.component.lifetime==="transient")throw new Error(`ArkRun component "${s}" is transient; resolveSingleton requires lifetime "singleton".`);return i(s,l)},snapshotComponents(){return[...t.values()].map(s=>Wn(s.component))}}}a(Un,"createComponentRegistry");function Qo(t){let e={...t.metadata??{}};if(t.source===void 0)return e;if(e.source&&e.source!==t.source)throw new $(t.source,e.source);return e.source=t.source,e}a(Qo,"stampMetadata");async function gt(t,e,n,r={}){let o=bt({transport:r.transport,ephemeral:r.ephemeral??t.defaultEphemeral,brokerBound:typeof t.broker?.send=="function"}),i=Qo(r),s=o.deliveredVia==="broker"&&t.broker!==void 0,l,c=await t.eventBus.dispatch(e,n,i,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers,...s?{settleBufferOnLocalDelivery:!1}:{},onBufferRecord:a(d=>{l=d.id},"onBufferRecord")});if(s&&t.broker){let d=t.eventBus,f=t.broker,p=(async()=>{try{await f.send(c)}catch(m){throw l!==void 0&&await d.settleBufferRecord(c,l,{ok:!1,error:m}),await d.recordHandoffFailure(c,m,"broker"),m}l!==void 0&&await d.settleBufferRecord(c,l,{ok:!0})})();o.awaitHandoff?await p:p.then(void 0,()=>{})}return o}a(gt,"sendOnArkRunTransport");var ei=1e3;function ti(){return k("ark-kernel")}a(ti,"nextKernelInstanceId");function qn(t,e){let n=t.constructor?.name;return typeof n=="string"&&n.length>0?n:e}a(qn,"portConstructorId");function mt(t={}){let e=t.strict??!0,n=t.instanceId??ti(),r=t.profile??Y,o=t.maxHistorySize??ei,i=Me(),s=rt(),l=t.metadata??st(),c=t.auditTrail===void 0,d=t.auditTrail??tt({maxRecords:o}),f=t.eventContracts??Xe(),p=t.eventBuffer===void 0&&t.outbox===void 0,m=t.eventBuffer??t.outbox??new q({maxRecords:o}),h=t.projections??lt({auditTrail:d}),S=new B([je(r),...t.policies??[]]),u=a(()=>{ot(i,s,{requireRegisteredTargets:!0})},"syncGraph"),y=t.ephemeral??!0,g=t.broker,v=new U({intentRegistry:i,dependencyGraph:s,policyEngine:S,strictRegistry:!0,validateIntentNaming:!0,auditTrail:d,eventContracts:f,strictEventContracts:t.strictEventContracts??e,requireKnownSource:t.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:t.enforceObservedLayerFlow??(e?"hard":"off"),eventBuffer:m,settleBufferOnLocalDelivery:p,instanceId:n,maxHistorySize:o,onPublish:t.autoApplyProjections===!1?void 0:async w=>{await h.apply(w)}}),yt=Re(v,{auditTrail:d}),Pe=Qe({registry:i,eventBus:v,graph:s}),N=Un(),Jn=typeof g?.send=="function",Yn=p?"InMemoryEventBuffer":qn(m,"EventBufferStore"),Xn=c?"InMemoryAuditStore":qn(d,"AuditTrail"),Zn=kt({stores:[ce(Yn,"outbox"),ce(Xn,"audit"),ce("InMemoryWorkflowStore","workflow")]}),Ce={instanceId:n,profile:r,registry:i,graph:s,metadata:l,auditTrail:d,eventContracts:f,eventBuffer:m,outbox:m,projections:h,policyEngine:S,eventBus:v,workflowEngine:yt,observability:Pe,publisher(w){let T=v.createPublisher(w);return{source:T.source,publish:T.publish,send(E,xe,Qn={}){return gt({eventBus:v,broker:g,defaultEphemeral:y},E,xe,{...Qn,source:T.source})}}},send(w,T,E={}){return gt({eventBus:v,broker:g,defaultEphemeral:y},w,T,E)},register(w){return N.register(w)},resolve(w){return N.resolve(w)},resolveSingleton(w){return N.resolveSingleton(w)},getDependencyInformationPackage(){return wt({kernelInstanceId:n,components:N.snapshotComponents()})},requestGraph(w){return It({kernelInstanceId:n,components:N.snapshotComponents()},w)},getInspectorSnapshot(w){return Pt({kernelInstanceId:n,host:w?.host,port:w?.port,package:{kernelInstanceId:n,components:N.snapshotComponents()},observability:Pe.report(),ephemeralDefault:y,brokerBound:Jn,hardening:Zn})},startInspector(w){return Vn({getInspectorSnapshot:a(E=>Ce.getInspectorSnapshot(E),"getInspectorSnapshot"),requestGraph:a(E=>Ce.requestGraph(E),"requestGraph"),async listInspectorOutbox(){let[E,xe]=await Promise.all([m.list("pending"),m.list("failed")]);return Et([...E,...xe],{sampleLimit:Le})},async listInspectorWorkflows(){return Rt(await yt.list(),{sampleLimit:Le})}},w)},syncGraph:u,manifest(){return u(),ut({registry:i,policyEngine:S,metadata:l,graph:s,profile:r,projections:h,eventContracts:f,observability:Pe})}};return Ce}a(mt,"createArkKernel");function ni(t={}){return mt({...t,strict:!0,strictEventContracts:t.strictEventContracts??!0,requireKnownSource:t.requireKnownSource??!0,enforceObservedLayerFlow:t.enforceObservedLayerFlow??"hard"})}a(ni,"createStrictArkKernel");function ht(t,e,n){let{profileName:r,...o}=e,i=e.enforceObservedLayerFlow,s=(i??n)==="hard"?Qt(t):[];if(i==="hard"&&s.length>0)throw new G(s);return{options:{...o,profile:Te(t,{name:r})},unresolvable:s}}a(ht,"planKernelFromConfig");function zn(t,e){return e.length===0||Promise.resolve().then(()=>t.auditTrail.record({type:"layer.observedFlowUnresolvable",subject:e.join(","),details:{code:"ARKRUN_LAYER_FLOW_UNRESOLVABLE",layers:e,message:new G(e).message}})).catch(()=>{}),t}a(zn,"withUnresolvableNotice");function Gl(t,e={}){let n=e.strict??!0,r=ht(t,e,n?"hard":"off");return zn(mt(r.options),r.unresolvable)}a(Gl,"createArkKernelFromConfig");function Hl(t,e={}){let n=ht(t,e,"hard");return zn(ni(n.options),n.unresolvable)}a(Hl,"createStrictArkKernelFromConfig");function Kl(t,e={}){return ri(ht(t,e,"off").options)}a(Kl,"createLenientArkKernelFromConfig");function ri(t={}){return mt({...t,strict:!1,strictEventContracts:t.strictEventContracts??!1,enforceObservedLayerFlow:t.enforceObservedLayerFlow??"off"})}a(ri,"createLenientArkKernel");export{Ct as a,yi as b,Si as c,Hr as d,wi as e,Kr as f,bi as g,Vr as h,Ai as i,Ne as j,Te as k,Y as l,Jr as m,Sn as n,bs as o,W as p,oo as q,As as r,ks as s,Se as t,fn as u,Es as v,Ue as w,wo as x,mn as y,Rs as z,Ps as A,Cs as B,xs as C,Ls as D,$o as E,Os as F,$s as G,X as H,Yr as I,Me as J,Xr as K,Fe as L,O as M,B as N,Z as O,_e as P,Be as Q,rn as R,je as S,Ge as T,eo as U,Q as V,ee as W,te as X,ne as Y,j as Z,$ as _,re as $,G as aa,Fo as ba,be as ca,Xe as da,q as ea,Ko as fa,Qe as ga,Ae as ha,tt as ia,rt as ja,ot as ka,st as la,ke as ma,lt as na,ct as oa,ut as pa,Ee as qa,Re as ra,Yo as sa,Vn as ta,ei as ua,mt as va,ni as wa,Gl as xa,Hl as ya,Kl as za,ri as Aa};