arkgate 4.2.0 → 4.3.0

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 (46) hide show
  1. package/CHANGELOG.md +86 -4
  2. package/README.md +20 -6
  3. package/bin/ark-mcp-runtime.mjs +64 -0
  4. package/bin/ark-shared.mjs +16 -4
  5. package/bin/ark.mjs +55 -1
  6. package/bin/lib/adapter-contract.mjs +88 -5
  7. package/bin/lib/agent-projection-command.mjs +396 -0
  8. package/bin/lib/agent-projection.mjs +319 -0
  9. package/bin/lib/agent-skills-package.mjs +266 -0
  10. package/bin/lib/baseline-key.mjs +32 -0
  11. package/bin/lib/ci-and-commands.mjs +44 -0
  12. package/bin/lib/diagnostic-catalog.mjs +155 -0
  13. package/bin/lib/physical-cohesion.mjs +2 -1
  14. package/bin/lib/status-command.mjs +369 -0
  15. package/bin/lib/status-manifest.mjs +394 -0
  16. package/dist/eslint/index.cjs +3 -3
  17. package/dist/eslint/index.js +3 -3
  18. package/dist/index.cjs +46 -11
  19. package/dist/index.d.ts +729 -6
  20. package/dist/index.js +46 -11
  21. package/docs/README.md +6 -6
  22. package/docs/agent-guide.md +112 -14
  23. package/docs/configuration.md +7 -0
  24. package/docs/develop.md +8 -0
  25. package/docs/diagnostics.md +606 -0
  26. package/docs/package-surface.md +19 -8
  27. package/docs/product-voice.md +45 -0
  28. package/docs/use.md +23 -0
  29. package/package.json +11 -1
  30. package/schemas/ark.analysis-result.schema.json +14 -1
  31. package/schemas/ark.status-manifest.schema.json +244 -0
  32. package/server.json +2 -2
  33. package/templates/agent-skills/README.md +59 -0
  34. package/templates/agent-skills/ark-adopt/SKILL.md +171 -0
  35. package/templates/agent-skills/ark-architect/SKILL.md +175 -0
  36. package/templates/agent-skills/ark-autopilot/SKILL.md +242 -0
  37. package/templates/agent-skills/ark-contract/SKILL.md +136 -0
  38. package/templates/agent-skills/ark-coverage/SKILL.md +167 -0
  39. package/templates/agent-skills/ark-explain/SKILL.md +210 -0
  40. package/templates/agent-skills/ark-explore/SKILL.md +377 -0
  41. package/templates/agent-skills/ark-fix/SKILL.md +185 -0
  42. package/templates/agent-skills/ark-loop/SKILL.md +180 -0
  43. package/templates/agent-skills/ark-place/SKILL.md +162 -0
  44. package/templates/agent-skills/ark-runtime/SKILL.md +120 -0
  45. package/templates/agent-skills/ark-think/SKILL.md +133 -0
  46. package/templates/agent-skills/ark-upgrade/SKILL.md +218 -0
@@ -0,0 +1,377 @@
1
+ ---
2
+ name: ark-explore
3
+ description: Specialized map skill — decision-grade recon of layers + ArkRules opportunities + dual-plan seed (no apply). Primary post-green door when design-weak. Not the default day-to-day path (use doctor + place/gate; guided apply is /ark-autopilot). CLI is a sensor; you read the tree. No gate bypass.
4
+ ---
5
+
6
+ # /ark-explore — Recon the real project (map only)
7
+
8
+ **Specialized escape**, not the default curriculum. Use when you need a decision-grade map
9
+ or the post-green Shape door; hand off to `/ark-autopilot` to apply. Day-to-day place + gate
10
+ work does not require this skill.
11
+
12
+ You are a **staff engineer doing architecture reconnaissance** on *this* repository.
13
+ Ark’s CLI is a **sensor** (coverage, doctor, plan). **You** open source, entry points,
14
+ install hooks, examples/starters, and coupling evidence. Output is **decision-grade**:
15
+ ranked residual that changes the next command — **not** a celebration of ENFORCE and
16
+ **not** a paraphrase of README/ROADMAP.
17
+
18
+ ## When / not when
19
+
20
+ | Use `/ark-explore` when… | Do **not** use it when… |
21
+ |--------------------------|-------------------------|
22
+ | Map / “what next?” / residual after ENFORCE | User wants edits applied → `/ark-autopilot` or `/ark-fix` |
23
+ | **Primary post-green door (Q01):** messy / spaghetti / design-weak / “clarify for AI” | Skill-shopping coverage or think for the same residual |
24
+ | Spaghetti brownfield: patterns concurrent, design-weak under green check | Only “governed% + gates installed?” numbers → `/ark-coverage` |
25
+ | Dual-plan **seed** (A remediation + B pattern bets) without applying | One design trade-off between 2–3 options already mapped → `/ark-think` |
26
+ | Path-correct vs design-correct honesty | Plain-language tour / HTML report → `/ark-explain` |
27
+
28
+ **Q01 single path:** when doctor `postGreenPath` / ENFORCE · design-weak is active, **this skill
29
+ (shape-focus / dual-plan seed) is the map half of the one door** — then `/ark-autopilot` only
30
+ to apply B with user OK. Do not send the user to coverage or think as equal first choices.
31
+
32
+ ### Status lights (rank residual; not settings)
33
+
34
+ | Light | Explore role |
35
+ |-------|----------------|
36
+ | **Suggest** | Point at `ark start` → doctor; map only if user insists on recon before setup |
37
+ | **Adapt** | Map false-green / ungoverned / concentrated edge; hand off adopt/contract before Shape vanity |
38
+ | **Enforce** | Confirm edges; if residual smells/patterns appear, auto-upgrade to dual-plan seed / shape-focus |
39
+ | **Enforce · design-weak** | **Primary post-green map door** — shape-focus + dual-plan B + extraction cards. False-done forbidden. Never claim healthy because plan A is empty. |
40
+
41
+ `/ark-autopilot`, `/ark-adopt`, and `/ark-coverage` embed a **lighter** version of this pass.
42
+ **You** are the full recon + pattern-planning skill.
43
+
44
+ ## Related onboarding
45
+
46
+ - **Greenfield / thin tree:** `/ark-architect` or `ark-check --recommend` / `ark start`.
47
+ - **Brownfield action (write contract/baseline):** `/ark-adopt` after the map.
48
+ - **Execute dual plan:** `/ark-autopilot` (explore seeds; autopilot applies A, proposes B).
49
+ - **Default path:** `ark start` → `ark-check --doctor` → `/ark-autopilot` for guided apply; use this skill for map-only or post-green Shape residual.
50
+
51
+ ## Dual engine (mandatory)
52
+
53
+ | Engine | Role | Never confuse with |
54
+ |--------|------|--------------------|
55
+ | **Deterministic** | Contract truth: layers, rules, violations, `mechanical-safe` kinds, exit codes | Product vision or “good enough” |
56
+ | **Exploratory** | Judgment from **reading this tree**: product surface, field path, hotspots, false greens, **lived design patterns**, spaghetti residual | Only paraphrasing CLI JSON or docs |
57
+
58
+ **Incomplete:** doctor/coverage dump with no file paths you opened; or a long map that
59
+ only restates README; or a multi-week roadmap when the user only asked for a map;
60
+ or “healthy” because plan A is empty while design-weak smells remain unlisted.
61
+ **Complete:** dry headline + field evidence + ranked bets with **así te lo re-soluciono**
62
+ (real paths, concrete next step, **success signal**) + honest handoff when residual is
63
+ *not* layer debt.
64
+
65
+ **ENFORCE / 100% governed / empty plan is baseline, not a finding.** Lead with residual
66
+ that still matters (dogfood gaps, soft starters, identity drift, **semantic false-green**,
67
+ **design-weak under ENFORCE**, coupling that blocks evolution). If residual is truly none,
68
+ say so in one line and hand off `stop`.
69
+
70
+
71
+ ## MCP workspace binding (mandatory)
72
+
73
+ Before any `ark_*` MCP tool, call `ark_identity` with `project.expectedRoot` set to the exact
74
+ workspace root. Continue only when `binding.status === "matched"` and `authoritative === true`;
75
+ retain `projectIdentity.projectId`, then pass both `expectedRoot` and `expectedProjectId` under
76
+ `project` on every later MCP call. If identity is missing, mismatched, unverified, or the root is
77
+ uncertain, do not consume MCP analysis: use the workspace-local CLI and report that MCP
78
+ restart/retargeting is required. `ark://manifest` never satisfies this preflight.
79
+
80
+ ## Dual plane — layers + ArkRules (mandatory, except /ark-runtime)
81
+
82
+ ArkGate has **two opt-in planes**. The user chooses which to use; you **always label** findings so they never blur.
83
+
84
+ | Plane | What it protects | Where it lives | Sensors / tools |
85
+ |-------|------------------|----------------|-----------------|
86
+ | **Layers** (inter-layer) | Who may import whom, capabilities, pure/forbiddenGlobals, peerIsolation | `ark.config.json` → `layers[]`, `rules[]` | graph check, baseline edges, doctor coverage % |
87
+ | **ArkRules** (intra-layer) | Structure inside a layer + domain invariants as data | `arkRules` map + `arkrules/<ExactLayerName>.json` | structure sensors, invariant coverage, `--rules-inventory`, doctor `rulesUnderContract` |
88
+
89
+ **Rules for every report / answer:**
90
+ 1. Prefix each finding or next step with **`[Layer]`** or **`[ArkRules]`** (or a two-column table with those headers).
91
+ 2. Never call an import-edge violation an “invariant” or an aggregate sensor a “layer deny.”
92
+ 3. Absence of `arkRules` is **valid** — do not force ArkRules unless the user wants them or residual inventory clearly wants a pilot.
93
+ 4. Editing `arkrules/*` or promoting modes is **`/ark-contract`**; fixing code under a structure sensor is **`/ark-fix`** / **`/ark-loop`** (judgment, never invent mechanical-safe).
94
+ 5. CLI helpers: `ark-check --rules-inventory --json`, doctor JSON `rulesUnderContract`, sensors emit `ARKRULE_*` / `INVARIANT_UNCOVERED` with `evidence.arkruleId`.
95
+
96
+
97
+ ### Explore + ArkRules
98
+ - Always run sensors for **both** planes when present: coverage/doctor **and** `--rules-inventory` if `arkRules` exists or brownfield may hide spaghetti rules.
99
+ - Ranked table kinds may include `arkrules-opportunity` and `invariant-gap`.
100
+ - Dual-plan **B** may include: place advisory structure rules, extract one inventory candidate to Domain + `arkrules` entry, promote one covered invariant.
101
+ - Field path: note whether starters emit `arkrules/*`.
102
+
103
+ ## Output mode (pick one — do not invent a fourth)
104
+
105
+ | Mode | When | Deliverable |
106
+ |------|------|-------------|
107
+ | **Recon (default)** | map / residual / “what next?” / bare `/ark-explore` | Headline → map → ranked table → **Top 3** → residue → Completion |
108
+ | **Dual-plan seed** | user asks for a **plan**, mejora, roadmap, “Ark + patrón”, **or** spaghetti signals fire (§G) | Same recon **plus** **§ Dual-plan seed** (A + B). **Cap 3–5 B bets.** |
109
+ | **Shape-focus** | plan A already empty / ENFORCE, `plan.completeness` is `complete`, user wants **pattern** depth only | Abbreviated map + **mandatory** concurrent-patterns table + B bets only (A = “goal.met / empty”) |
110
+
111
+ **Auto-upgrade:** if §G spaghetti signals fire, you **must** use dual-plan seed or shape-focus
112
+ — never end on recon-only with “layers are clean.”
113
+
114
+ **Forbidden in every mode:**
115
+ - A 6-phase / multi-week implementation roadmap as the default explore product.
116
+ - Phases with week estimates, long PR stacks, or vanity “Domain ≥ N files” as done criteria.
117
+ - Auto-applying anything (explore does not edit the contract or product code unless the user
118
+ separately asks to execute a bet).
119
+
120
+ **Dual-plan seed shape (mode dual-plan seed | shape-focus):**
121
+
122
+ | Section | Content |
123
+ |---------|---------|
124
+ | **A. Remediation** | From `--plan` — usually empty when ENFORCE; one line if so. Empty counts only when `plan.completeness === "complete"` |
125
+ | **B. Pattern / evolution** | **3–5** bets max; each: evidence · así te lo re-soluciono · **success signal** · next skill · **pilot** · **kill-switch** if new layer/big move |
126
+ | **Phase ladder** | Name which of Align / Stabilize / **Shape** the repo is in (§G) |
127
+
128
+ Long multi-PR execution belongs to **`/ark-autopilot`**. If residual spans sessions/PRs,
129
+ optionally point the user at a durable Shape plan (e.g. `docs/plans/shape-<pilot>/`) seeded
130
+ from patternBets + extraction cards — **optional**, not a gate requirement
131
+ (see `docs/brownfield-adoption.md` §6).
132
+
133
+ ## Subagent fan-out (optional, host-dependent)
134
+
135
+ When the user asks to go faster **or** the work naturally splits (multiple packages,
136
+ feature dirs, plan clusters), you **may** dispatch **subagents**:
137
+
138
+ | Host capability | Behavior |
139
+ |-----------------|----------|
140
+ | **Parallel subagents supported** (e.g. multi-agent / `spawn_subagent` / concurrent Agent tools) | Launch **2–N** agents in **one wave** with **disjoint path scopes**. Prefer **read-only** explore agents for mapping; at most **one writer** unless the host gives isolated worktrees. Parent merges findings, then runs `ark-check` once. |
141
+ | **Not supported** (single agent only) | **Fall back to sequential** — same checklist, one cluster/step at a time. Never claim parallel work you did not run. |
142
+
143
+ **Rules:**
144
+ 1. Give each subagent a **tight brief**: paths in scope, sensor commands allowed, deliverable shape (paths opened + findings JSON or bullets).
145
+ 2. **No shared mutable files** across parallel writers.
146
+ 3. STOP handoffs and dual-engine rules still apply in every agent.
147
+ 4. Parent owns the **### Completion** block (union of **Opened**, single **Handoff**).
148
+ 5. Do **not** use subagents to weaken the gate or invent `mechanical-safe` kinds.
149
+
150
+ Useful split: **core product tree** | **field path** (`examples/`, starters) | **agent install surfaces** (hooks vs templates).
151
+
152
+ ## Anti-wrapper rule
153
+
154
+ **Forbidden:**
155
+ - Only `ark-check --json` / `--coverage` / `--doctor` paraphrase.
156
+ - Echoing README / ROADMAP / marketing as if it were recon.
157
+ - Padding the ranked table with “architecture is clean” rows when the sensor already said that.
158
+ - Ranking debt by **LOC alone** without fan-in, exports, or call-site evidence.
159
+ - **Vanity success metrics** as bet done criteria (e.g. “Domain ≥ 20 files”) without multi-surface proof or a kill-switch.
160
+ - Multi-week roadmaps when mode is recon-only.
161
+ - Claiming “nothing to do” because plan A is empty while §G design smells remain.
162
+
163
+ **Required:**
164
+ 1. Sensor: `--coverage --json`, `--doctor`, optional `--plan --json` / normal check.
165
+ 2. **Product + code pass** — min **12 source files** across **≥4 directories** that matter for *this* product (apps, packages, features, domain, adapters, API routes, CLIs).
166
+ 3. **Field path** when scaffolds exist (see §E); for pure apps, **internal field path** (see §E).
167
+ 4. **Coupling evidence** beyond “large file” (see §C).
168
+ 5. **Path-correct vs design-correct** pass (see §B) — always on brownfield or when plan is empty.
169
+ 6. **§G spaghetti / design-depth** when signals fire (or always on brownfield).
170
+ 7. Ranked rows that **change a decision**; each bet has a **success signal** (not a file count).
171
+ 8. Hard lines: never weaken the contract; never invent mechanical-safe kinds; never claim ENFORCE from type-only cleanup while false-green doctor ids are active.
172
+ 9. **Parse honesty:** require `plan.completeness === "complete"` before accepting `goal.met`. If `doctor.parseHealth.affectedFiles > 0`, open and name those paths; never describe them as clean or successfully inspected. Doctor alone does not change the gate verdict, but check/plan completeness is `partial`, plan goal is false, and strict merge fails.
173
+
174
+ ## Reconnaissance pass (do all that apply)
175
+
176
+ ### A. Product surface (what the system is)
177
+ - README / package.json `description` / scripts / monorepo workspace roots — **skim for entry points**, do not restate the pitch.
178
+ - User-facing entry: Next/Nest/Express routes, CLIs, workers, public APIs, package exports.
179
+ - Deploy shape if obvious (apps/, packages/, services/).
180
+ - One dry line: **what a real user/agent gets** (not the slogan).
181
+
182
+ ### B. Architecture as lived — path-correct vs design-correct
183
+ - Map top dirs → intended layer vs what code *actually* does (UI, use-cases, I/O, pure domain).
184
+ - Classic false-green: empty Domain / Persistence while Application owns `airtable|supabase|prisma|repositories` → doctor id `contract-false-green-io-under-application`.
185
+ - **Semantic false-green** (edges green, names lie) — flag when you see it:
186
+ - HTTP handlers / route bodies living under `repositories/` or Persistence globs.
187
+ - Presentation/routes defaulting to a data facade (`platform/*`, raw db) while “repos exist”.
188
+ - Domain layer thin while pure business rules sit in Application with no I/O (should be Domain).
189
+ - Layer labels that match globs but not role (gate path-correct, design wrong).
190
+ - Framework guts vs product code (Nest modules, Next app router, generated clients).
191
+ - **Identity risk:** which layer owns the product *wedge* vs file-count / public barrel.
192
+ - **Concurrent design patterns** (short table when ≥2 styles coexist **or** when spaghetti signals fire):
193
+
194
+ | Pattern name | Example path | Quality |
195
+ |--------------|--------------|---------|
196
+ | … | `src/…` | `canonical` / `gate-green design-weak` / `legacy` |
197
+
198
+ Mark the **golden** pattern to copy. Do not only list layer file counts.
199
+
200
+ When `doctor.physicalCohesion` includes `reshapeDecisions`, treat current rejected/deferred
201
+ targets as explicit adopter decisions, not residual to re-fight. Keep their mirror facts in the
202
+ map. When the user accepts, defers, or rejects a live `reshapePilot.nextPilot`, record the card's
203
+ exact `decisionTarget` with a reason (and optional `reviewBy`) in
204
+ `.ark/reshape-decisions.json`. Never infer or suppress from free-form golden-pattern prose.
205
+
206
+ ### C. Coupling & debt (measure, don’t guess)
207
+ Prefer evidence over aesthetics:
208
+ - **Fan-in / importers** of hot modules (who imports the suspect file?).
209
+ - **Export surface** (how many public symbols does the orchestration module re-export?).
210
+ - Import cycles, cross-feature leaks (`peerIsolation` candidates).
211
+ - Business rules in UI/hooks (`can*`, `calculate*`, policy constants) → Domain / intents.
212
+ - Dead or aspirational globs; layers with files but no rules; **starter/preset rules weaker than sibling archetypes** (soft green).
213
+ - LOC is a **hint** only — pair it with fan-in or export count before calling something a god module.
214
+
215
+ ### D. Agent / gate reality (installed vs generated)
216
+ - Write gate + CI + `/ark-*` skills present? Stale skills? Global vs pinned `arkgate`?
217
+ - **Installed hooks vs install templates:** compare project PreToolUse / write-hook commands to what `--install-agent-gates` would emit. Doctor `writePath` / adoption gaps are leads — **verify on disk**.
218
+ - MCP config present and pointing at a real binary? `prepare-write` / autoPatch surface vs hook mode.
219
+ - Baseline: real debt or hiding contract smell?
220
+ - CI: is architecture check required on the default branch path this repo actually uses?
221
+ - **Origin:** is `.ark/reports/origin.json` present? (Day-zero picture; missing → agent-dx / adopt gap, not a layer violation.)
222
+
223
+ ### E. Field path (consumer promise or internal)
224
+ When `examples/`, `templates/`, gallery starters, eval fixtures, or docs claim “copy this and stay green”:
225
+ 1. Open **≥2** scaffolds (prefer one minimal gallery + one “deep” / runnable demo).
226
+ 2. **Run** their documented check script when cheap; record pass/fail — do not trust README alone.
227
+ 3. Diff **rule strength** across archetypes (missing denies = soft false-green for consumers).
228
+ 4. Note import style vs package surface docs (`arkgate` root barrel vs preferred subpath).
229
+ 5. Flag **false promises**: demo fails under its own check, or green with a hollow contract.
230
+
231
+ If the repo is a **pure app** (no examples): state **Field path: internal** and do one of:
232
+ - Name the **norm for new code** that the residual implies (e.g. “no new `platform/db` in routes”), or
233
+ - Point at one **smoke** the team could add — do not invent a full CI system.
234
+
235
+ ### F. Suggestive bets (not commits yet)
236
+ For each opportunity: **impact × effort × enforceability** (can the gate hold it after?).
237
+
238
+ **Success signal (required per bet)** — observable, not vanity:
239
+ - Good: `doctor.writePath = repair`; `ark-check` green after promote; API + UI import same pure `computeX`; 0 new routes with facade SQL; pilot cluster migrated + kill-switch decision recorded.
240
+ - Bad: “Domain has ≥ N files”; “add layer X”; “more documentation”.
241
+
242
+ **Kill-switch (required if the bet adds a layer, peerIsolation wall, or big-bang move):**
243
+ - Name a **pilot** (one cluster) and a **stop condition** (e.g. “if pilot does not reduce confusion in 2 real PRs → prefer handlers-under-domain without a new layer”).
244
+ - Prefer **forward-only + migrate-on-touch** over big-bang.
245
+
246
+ Prefer bets the user can run next (`command` / skill), not vague “improve DX”.
247
+
248
+ ### G. Spaghetti / design-depth ladder (non-deterministic path — mandatory when signals fire)
249
+
250
+ **Signals (any one → dual-plan seed or shape-focus):**
251
+ - Plan A empty / `goal.met` with `completeness: complete` **and** you still see design-weak / concurrent patterns / god modules.
252
+ - Brownfield with mixed layouts (flat services + “hex” folders + feature dumps).
253
+ - Semantic false-green (path-correct, design-wrong).
254
+ - User words: spaghetti, monstruo, legacy, “está enforce pero horrible”, pattern, refactor shape.
255
+
256
+ **Phase ladder (name exactly one current phase):**
257
+
258
+ | Phase | Goal | Done when (falsifiable) |
259
+ |-------|------|-------------------------|
260
+ | **Align** | Contract matches reality (path-correct); no false-green freeze | Governed high; false-green closed; concentrated edge fixed via contract |
261
+ | **Stabilize** | ENFORCE + honest baseline only for real debt | 0 new edges; doctor not lying about write path/CI |
262
+ | **Shape** | One **golden** pattern + pilot cluster | Pilot smells cleared; rest is migrate-on-touch; B bets have success signals |
263
+
264
+ ENFORCE without Shape progress is **`ENFORCE · design-weak`** — say that out loud. It is **not** “healthy finished.”
265
+
266
+ **Agent-detected design smells** (list any that apply; paths required — these may predate doctor IDs):
267
+
268
+ | Smell id (label) | How you detect it in source |
269
+ |------------------|-----------------------------|
270
+ | `io-under-application` | I/O clients under Application; empty Domain/Persistence (also doctor when present) |
271
+ | `handler-in-persistence` | Static framework HTTP imports, `defineRoute` calls, or route bodies under Persistence-role repo/db globs (**envelope:** first 800 sorted candidates; absence of smell ≠ full-tree proof above that cap; incomplete/partial analysis is never “no smells”) |
272
+ | `god-module` | High fan-in + wide export surface + mixed concerns |
273
+ | `domain-logic-in-ui` | `can*` / `calculate*` / policy constants in hooks/pages |
274
+ | `mixed-pattern-cluster` | Same feature area uses ≥2 incompatible layouts |
275
+ | `soft-contract` | Layers without denies / peerIsolation off where peers leak |
276
+ | `facade-sql-in-routes` | Routes import raw ORM/SQL while “repositories exist” elsewhere |
277
+
278
+ **Extraction card** (for each I/O / god-module B bet — judgment, never mechanical-safe).
279
+ Canonical productized template also in `docs/brownfield-adoption.md` §6.
280
+
281
+ **Q04 pilot loop:** when doctor/plan JSON is available, use **`pilotLoop.nextPilot`** as the
282
+ **single** next extraction card (one pilot at a time → re-doctor). Do not open five B bets
283
+ in parallel. When `pilotLoop.queuedBets > 0`, those bets stay **queued**, not concurrent.
284
+ `multiPilotBatchForbidden` / `autoApplyForbidden` (alias `autoApplyPlanBForbidden`) are hard
285
+ lines — never silent codemod of plan B. After the pilot lands, re-run doctor; success =
286
+ reduced evidence on pilot paths.
287
+
288
+ ### Plan B one-pilot checklist (mandatory before any B apply)
289
+
290
+ Empty plan A + design-weak is **not** architecture finished. Plan B is judgment only.
291
+
292
+ | Step | Gate | Fail closed if… |
293
+ |------|------|-----------------|
294
+ | 1. Confirm residual | `designFitness.designWeak` **or** non-empty `patternBets` / `designSmells` | You would claim healthy finished because plan A is empty |
295
+ | 2. Pick **one** pilot | `pilotLoop.nextPilot` (preferred) **or** one ranked B bet with a path scope | Multi-pilot batch / “fix all smells this PR” |
296
+ | 3. Write extraction card | Pilot · Smell · Move · Do not · Success · **Kill-switch** · Next | Missing kill-switch or success signal |
297
+ | 4. User OK | Explicit approval before edit (or stay map-only) | Silent auto-apply of plan B |
298
+ | 5. Apply **only** that pilot | Via `/ark-autopilot` (apply B) or `/ark-fix` (one cluster) | Opening a second pilot before re-doctor |
299
+ | 6. Re-doctor | Success = reduced evidence on pilot paths; residual outside pilot may remain | Declaring whole-tree done from one pilot |
300
+
301
+ **Hard lines (never break):**
302
+ - `killSwitch` / kill-switch is **required** on every B card (stop condition if pilot does not reduce confusion).
303
+ - `multiPilotBatchForbidden` — never multi-batch Shape extractions.
304
+ - `autoApplyPlanBForbidden` / `neverMechanicalSafe: true` — never invent mechanical-safe for B.
305
+ - `healthyFinishedForbidden` while design-weak — empty plan A is baseline, not done.
306
+
307
+ ```text
308
+ ### Extraction card
309
+ Pilot: <one dir or feature — or pilotLoop.nextPilot.pilotTarget>
310
+ Smell: <doctor designSmells[].id when present, else agent-detected id>
311
+ Move: <verbatim I/O or rule → port/adapter or Domain file>
312
+ Do not:
313
+ - rewrite queries / touch schema / migrations
314
+ - weaken ark.config.json
315
+ - auto-apply as mechanical-safe or invent new mechanical-safe kinds
316
+ - big-bang the monorepo
317
+ - open a second pilot before re-doctor
318
+ Success: <observable / falsifiable — re-doctor>
319
+ Kill-switch: <stop condition — e.g. if pilot does not clear smell evidence in 1 PR → stop / re-map>
320
+ Next: /ark-autopilot (apply with user ok) | /ark-fix (one cluster) | re-doctor
321
+ ```
322
+
323
+ When doctor JSON is available, prefer smell `id`s from `designSmells` / `patternBets[].smellId`
324
+ and the ranked **`pilotLoop.nextPilot`**.
325
+
326
+ ## Output format (keep tight)
327
+
328
+ State **Mode: recon | dual-plan seed | shape-focus** and **Phase: Align | Stabilize | Shape** in the first lines.
329
+
330
+ 1. **Headline** — product one sentence + honesty (mode, governed%, false-green / semantic false-green / **ENFORCE·design-weak** / false-promise risk). ENFORCE is context, not the story.
331
+ 2. **Map** — entry points, major dirs, shape name (or “no honest shape yet”). One screen. **Patterns concurrent** table when §B/§G requires it.
332
+ 3. **What I opened** — paths + sensors (include field/hook/origin when used).
333
+ 4. **Ranked table** — **only rows that change a decision**. Prefer **3–6** hard rows.
334
+
335
+ | # | Kind | Finding | Evidence (path) | Así te lo re-soluciono | Success signal | Next skill / command |
336
+
337
+ Kinds: `risk` | `false-green` | `debt` | `opportunity` | `shape` | `manifiesto` | `agent-dx` | `design-weak`
338
+
339
+ **Así te lo re-soluciono** must be concrete: files to touch, command to run.
340
+ **Success signal** must be falsifiable (see §F).
341
+
342
+ 5. **Field path summary**.
343
+ 6. **Top 3 bets** — first bet = highest leverage residual, even when plan A is empty (design-correct / agent-dx / field honesty — **not** “run loop on zero steps”).
344
+ On false-green dominant: **STOP — do not continue this skill as complete.** **STOP — false-green: invoke /ark-adopt or /ark-contract before claiming ENFORCE.** Do not claim goal.met / ENFORCE from type-only cleanup while doctor reports `contract-false-green-io-under-application`.
345
+ On concentrated edge dominant: **STOP — do not continue this skill as complete.** **STOP — concentrated edge: invoke /ark-contract with source evidence** (do not freeze a wrong contract or grind N freezes).
346
+ 7. **Dual-plan seed** — required in dual-plan seed / shape-focus (and when §G auto-upgrades); A + B cap 3–5; extraction cards for I/O bets.
347
+ 8. **Deterministic residue** — plan completeness, steps, violations, doctor top action. Point to `/ark-loop` / `/ark-fix` **only when A steps exist**; never call a `partial`/`unavailable` plan met, and never pretend loop is the architecture story when a complete goal is already met.
348
+
349
+ Optional: **Diff vs naive sensor-only read** (what reading the tree changed).
350
+
351
+ ## Done criteria
352
+
353
+ - ≥12 source files read and cited across ≥4 directories.
354
+ - Field path: scaffolds run/opened **or** pure-app internal norm stated.
355
+ - At least **3 decision-grade** rows (not “fix violation X” and not “layers are clean”).
356
+ - Coupling claims backed by fan-in / exports / importers (or clearly marked as LOC-only hint).
357
+ - Path vs design called out when concurrent patterns, semantic false-green, or §G signals exist.
358
+ - When §G fires: phase named, design smells listed with paths, dual-plan B or shape-focus B present.
359
+ - Every Top-3 / B bet has a **success signal**; new-layer bets have a **kill-switch** + pilot.
360
+ - Mode respected: no multi-week roadmap in recon mode; dual-plan seed capped at 3–5 B bets.
361
+ - Clear handoff: `/ark-adopt` | `/ark-contract` | `/ark-autopilot` | `/ark-loop` | `/ark-fix` | CLI | `stop`.
362
+ - No gate weakening; no false ENFORCE claim; no README echo as primary content.
363
+
364
+ ## Completion contract (skill incomplete if missing)
365
+
366
+ End with **exactly** these headings (markdown `###`):
367
+
368
+ ### Completion
369
+ - **Sensor:** commands/tools run
370
+ - **Opened:** real paths read (or `n/a` only if pure install/upgrade with no source analysis)
371
+ - **Result:** one-line outcome
372
+ - **Planes:** one-line split of residual **[Layer]** vs **[ArkRules]** (or `n/a` if unused)
373
+ - **Handoff:** `/ark-…` / CLI / `none`
374
+ - **Incomplete?** `no` | `yes — <what is missing>`
375
+
376
+ If a **STOP** handoff applies and you continued as if done, set **Incomplete?** to `yes`.
377
+ **Skill incomplete if missing** any of the bullets above.
@@ -0,0 +1,185 @@
1
+ ---
2
+ name: ark-fix
3
+ description: Resolve Ark architecture violations at the root cause — read importers and product context, design ports/adapters/moves/intent alignment. Never weaken the contract. CLI only validates.
4
+ ---
5
+
6
+ # /ark-fix — Fix architecture violations at the root
7
+
8
+ You fix violations Ark reports. Prefer structural fixes over silencing the gate.
9
+ **Read the surrounding product code** (callers, package role, feature ownership) — not only
10
+ the two files on the violation edge.
11
+
12
+ ## When / not when
13
+
14
+ | Use `/ark-fix` when… | Do **not** use it when… |
15
+ |----------------------|-------------------------|
16
+ | One change / small cluster just failed the gate | Bulk residual / many edges → `/ark-loop` or `/ark-autopilot` |
17
+ | Need a structural fix (port, move, intent rename) | Map residual / pattern Shape plan → `/ark-explore` |
18
+ | Judgment design for a known violation | Contract wrong / false-green → STOP to `/ark-contract` / `/ark-adopt` |
19
+
20
+ When the fix is really a **Shape** extraction (I/O out of routes, god module split), write an
21
+ **extraction card** before editing — same template as `docs/brownfield-adoption.md`
22
+ §6 and explore §G. Fixed fields (never mechanical-safe, never silent B apply).
23
+
24
+ ### Plan B one-pilot checklist (when Shape residual, not a single edge fix)
25
+
26
+ Empty plan A + `designWeak` is **not** architecture finished. One pilot only:
27
+
28
+ 1. **Confirm** doctor `designFitness.designWeak` / non-empty `patternBets` (or agent-detected smell).
29
+ 2. **One pilot** — prefer `pilotLoop.nextPilot`; never multi-batch concurrent Shape extractions.
30
+ 3. **Extraction card** with **Kill-switch** + falsifiable Success (required).
31
+ 4. **User OK** before apply — `autoApplyPlanBForbidden` / never mechanical-safe.
32
+ 5. **Edit only that pilot scope** — then `ark-check` / re-doctor; residual outside pilot may remain.
33
+ 6. **Stop** if kill-switch fires; do not open pilot #2 in the same batch.
34
+
35
+ ```text
36
+ ### Extraction card
37
+ Pilot: <one directory or feature path — or pilotLoop.nextPilot.pilotTarget>
38
+ Smell: <doctor designSmells id if present>
39
+ Move: <verbatim relocate / split>
40
+ Do not: rewrite queries; weaken ark.config; invent mechanical-safe kinds; big-bang; multi-pilot batch
41
+ Success: <falsifiable — re-doctor on pilot paths>
42
+ Kill-switch: <stop condition — required>
43
+ Next: re-run ark-check; shrink baseline if applicable
44
+ ```
45
+
46
+ ## Dual engine (mandatory)
47
+
48
+ | Engine | Role |
49
+ |--------|------|
50
+ | **Deterministic** | Violation list, plan kinds, post-edit `ark-check` |
51
+ | **Exploratory** | Why this edge exists in *this* product; better home; manifiesto if the rule is business |
52
+
53
+
54
+
55
+ ## MCP workspace binding (mandatory)
56
+
57
+ Before any `ark_*` MCP tool, call `ark_identity` with `project.expectedRoot` set to the exact
58
+ workspace root. Continue only when `binding.status === "matched"` and `authoritative === true`;
59
+ retain `projectIdentity.projectId`, then pass both `expectedRoot` and `expectedProjectId` under
60
+ `project` on every later MCP call. If identity is missing, mismatched, unverified, or the root is
61
+ uncertain, do not consume MCP analysis: use the workspace-local CLI and report that MCP
62
+ restart/retargeting is required. `ark://manifest` never satisfies this preflight.
63
+
64
+ ## Dual plane — layers + ArkRules (mandatory, except /ark-runtime)
65
+
66
+ ArkGate has **two opt-in planes**. The user chooses which to use; you **always label** findings so they never blur.
67
+
68
+ | Plane | What it protects | Where it lives | Sensors / tools |
69
+ |-------|------------------|----------------|-----------------|
70
+ | **Layers** (inter-layer) | Who may import whom, capabilities, pure/forbiddenGlobals, peerIsolation | `ark.config.json` → `layers[]`, `rules[]` | graph check, baseline edges, doctor coverage % |
71
+ | **ArkRules** (intra-layer) | Structure inside a layer + domain invariants as data | `arkRules` map + `arkrules/<ExactLayerName>.json` | structure sensors, invariant coverage, `--rules-inventory`, doctor `rulesUnderContract` |
72
+
73
+ **Rules for every report / answer:**
74
+ 1. Prefix each finding or next step with **`[Layer]`** or **`[ArkRules]`** (or a two-column table with those headers).
75
+ 2. Never call an import-edge violation an “invariant” or an aggregate sensor a “layer deny.”
76
+ 3. Absence of `arkRules` is **valid** — do not force ArkRules unless the user wants them or residual inventory clearly wants a pilot.
77
+ 4. Editing `arkrules/*` or promoting modes is **`/ark-contract`**; fixing code under a structure sensor is **`/ark-fix`** / **`/ark-loop`** (judgment, never invent mechanical-safe).
78
+ 5. CLI helpers: `ark-check --rules-inventory --json`, doctor JSON `rulesUnderContract`, sensors emit `ARKRULE_*` / `INVARIANT_UNCOVERED` with `evidence.arkruleId`.
79
+
80
+
81
+ ### Fix + ArkRules
82
+ - Classify each violation: `LAYER_*` / capability → **[Layer]**; `ARKRULE_*` / `INVARIANT_*` → **[ArkRules]**.
83
+ - Structure sensor fixes are judgment (ports, factories, private state) — not mechanical-safe.
84
+
85
+ ## Subagent fan-out (optional, host-dependent)
86
+
87
+ When the user asks to go faster **or** the work naturally splits (multiple packages,
88
+ feature dirs, plan clusters), you **may** dispatch **subagents**:
89
+
90
+ | Host capability | Behavior |
91
+ |-----------------|----------|
92
+ | **Parallel subagents supported** (e.g. multi-agent / `spawn_subagent` / concurrent Agent tools) | Launch **2–N** agents in **one wave** with **disjoint path scopes**. Prefer **read-only** explore agents for mapping; at most **one writer** unless the host gives isolated worktrees. Parent merges findings, then runs `ark-check` once. |
93
+ | **Not supported** (single agent only) | **Fall back to sequential** — same checklist, one cluster/step at a time. Never claim parallel work you did not run. |
94
+
95
+ **Rules:**
96
+ 1. Give each subagent a **tight brief**: paths in scope, sensor commands allowed, deliverable shape (paths opened + findings JSON or bullets).
97
+ 2. **No shared mutable files** across parallel writers.
98
+ 3. STOP handoffs and dual-engine rules still apply in every agent.
99
+ 4. Parent owns the **### Completion** block (union of **Opened**, single **Handoff**).
100
+ 5. Do **not** use subagents to weaken the gate or invent `mechanical-safe` kinds.
101
+
102
+ ## Related onboarding
103
+
104
+ - **Greenfield:** `/ark-architect` or `ark-check --recommend` / `ark start`.
105
+ - **Brownfield:** `/ark-adopt` — match contract to reality; do not force a starter preset.
106
+ - **Map first:** `/ark-explore` when the violation is one of many structural smells.
107
+ - **peerIsolation / cross-slice:** always **judgment** — extract to shared, events/ports, or redesign ownership. Never auto-apply cross-feature or cross-context moves.
108
+ - **`vertical-slice` ownership:** feature code stays under `src/features/<slice>/…` (no sibling-slice imports); shared primitives in `src/shared/`; infra in `src/lib/`; shell in `src/app/`. Cross-feature edges are peerIsolation — extract shared or use events/ports.
109
+ - **`ddd-bounded-contexts` ownership:** code under `src/contexts/<context>/{domain,application,infrastructure,presentation}/`; shared kernel only under `src/shared/kernel/`. Cross-context imports (same or cross technical layer) are peerIsolation — integrate via application APIs/events, not peer technical layers.
110
+ - **Default path:** `ark start` → `/ark-autopilot` → `ark-check --doctor`.
111
+
112
+ ## Anti-wrapper rule (mandatory)
113
+
114
+ **Forbidden:** only listing violations from JSON without reading importers/targets.
115
+
116
+ **Required:**
117
+ 1. Run `ark-check` as **sensor** (and `--plan --json` if multi-step) — CLI validates; you remediate.
118
+ 2. **Read** each violated file and its import target (plus callers that explain product role).
119
+ If the wall is a concentrated contract smell: **STOP — do not continue this skill as complete.** **STOP — concentrated edge: invoke /ark-contract with source evidence** (do not freeze a wrong contract or grind N freezes).
120
+ If false-green cores: **STOP — do not continue this skill as complete.** **STOP — false-green: invoke /ark-adopt or /ark-contract before claiming ENFORCE.** Do not claim goal.met / ENFORCE from type-only cleanup while doctor reports `contract-false-green-io-under-application`.
121
+ If many residuals: **STOP — do not continue this skill as complete.** **STOP — bulk residual debt: invoke /ark-loop or /ark-autopilot** instead of ad-hoc multi-file grinding without a plan.
122
+ 3. **“Así te lo re-soluciono”** — concrete change before editing.
123
+ 4. After edits: `ark-check --strict-config` (and baseline if configured).
124
+
125
+ ## Common fix patterns
126
+
127
+ | Symptom | Fix |
128
+ |---------|-----|
129
+ | App → Presentation type-only | Extract type to application/core; re-export from UI |
130
+ | App → Presentation value (UI in core) | Move component wrappers to presentation |
131
+ | Domain → outer layer | Port/interface in Domain; adapter outside; or relocate false Domain file (`**/types.ts` trap) |
132
+ | Intent prefix mismatch | Rename intent to layer’s `intentPrefixes` or fix prefix in config via `/ark-contract` |
133
+ | Forbidden global in Domain | Inject a port (Clock, Id, Http) — don’t allow `Date.now` in Domain |
134
+ | Concentrated edge wall | Stop grinding; `/ark-contract` facade/surface split |
135
+
136
+ ## Manifiesto
137
+
138
+ If the “fix” is really a missing business intent or Domain home for a rule:
139
+
140
+ - Propose intent name + layer placement.
141
+ - Register / place code so `ark_manifest` / config can enforce it.
142
+ - Do not only delete the import.
143
+
144
+ ## Rules
145
+
146
+ - No `ark-*-disable`, no allowing a bad edge “to finish”, no baselining a **new** violation you introduced.
147
+ - Prefer mechanical-safe kinds when the plan tags them; otherwise design judgment carefully.
148
+ - Code only — no DB migrations unless user asked.
149
+
150
+ ## Mechanical-edit hygiene (Y04 — outcome gate)
151
+
152
+ - Header injection must **merge into the existing doc comment**; the kept result has one `/**`, not stacked headers.
153
+ - Route completion or movement must **preserve the original typed `defineRoute<…>(opts, handler)` call**; reconstruct that call instead of extracting untyped opts/handler constants that drop generics or contextual typing.
154
+ - A convention-only `*-data.ts` stub is not a fix: move the real code or **leave the placeholder file uncreated**; never write `import "server-only"; export {}` as an empty naming token.
155
+ - Keep the edit only when the **previously clean file stays typecheck-clean**. Otherwise roll it back and treat the change as judgment.
156
+
157
+ ## Reshape findings (X04 — never mechanical)
158
+
159
+ If `doctor.physicalCohesion` fires while you fix: do **not** fold reshape moves into your fix
160
+ batch. Physical moves run only through `/ark-loop`'s one-pilot loop; merge decisions only as
161
+ `/ark-architect` merge cards. A cohesion finding is context for your fix, never a license to
162
+ reorganize. Respect `physicalCohesion.reshapeDecisions`: never revive a current rejected/deferred
163
+ target from the still-visible facts. If the user makes a verdict while reviewing the finding,
164
+ record its exact `decisionTarget` + reason in `.ark/reshape-decisions.json`; never infer one from
165
+ golden-pattern prose.
166
+
167
+ ## Done
168
+
169
+ - Targeted violations gone; no new ones.
170
+ - Report: what moved, what was intentional default, what needs user decision.
171
+
172
+ ## Completion contract (skill incomplete if missing)
173
+
174
+ End with **exactly** these headings (markdown `###`):
175
+
176
+ ### Completion
177
+ - **Sensor:** commands/tools run
178
+ - **Opened:** real paths read (or `n/a` only if pure install/upgrade with no source analysis)
179
+ - **Result:** one-line outcome
180
+ - **Planes:** one-line split of residual **[Layer]** vs **[ArkRules]** (or `n/a` if unused)
181
+ - **Handoff:** `/ark-…` / CLI / `none`
182
+ - **Incomplete?** `no` | `yes — <what is missing>`
183
+
184
+ If a **STOP** handoff applies and you continued as if done, set **Incomplete?** to `yes`.
185
+ **Skill incomplete if missing** any of the bullets above.