arkgate 4.8.23 → 4.8.25

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 (201) hide show
  1. package/CHANGELOG.md +153 -0
  2. package/README.md +7 -5
  3. package/bin/ark-check-runtime.mjs +41 -91
  4. package/bin/ark-dashboard.mjs +56 -53
  5. package/bin/ark-layer-match.mjs +707 -121
  6. package/bin/ark-mcp-runtime.mjs +448 -169
  7. package/bin/ark-mcp.mjs +68 -4
  8. package/bin/ark-shared.mjs +42 -22
  9. package/bin/ark.mjs +65 -97
  10. package/bin/lib/adapter-contract-types.mjs +5 -0
  11. package/bin/lib/adapter-contract.mjs +15 -0
  12. package/bin/lib/adoption-stance.mjs +2 -2
  13. package/bin/lib/adr-path.mjs +3 -3
  14. package/bin/lib/agent-gates.mjs +0 -61
  15. package/bin/lib/agent-homes.mjs +12 -21
  16. package/bin/lib/agent-projection-command.mjs +9 -5
  17. package/bin/lib/ambient-state.mjs +9 -30
  18. package/bin/lib/analysis-engine.mjs +15 -11
  19. package/bin/lib/architecture-scan.mjs +61 -15
  20. package/bin/lib/ark-order-doctor.mjs +4 -29
  21. package/bin/lib/ark-order-facts.mjs +319 -17
  22. package/bin/lib/ark-order-sensors.mjs +28 -101
  23. package/bin/lib/ark-order-types.mjs +3 -2
  24. package/bin/lib/ark-run-doctor.mjs +17 -28
  25. package/bin/lib/ark-run-facts.mjs +461 -48
  26. package/bin/lib/ark-run-sensors.mjs +6 -4
  27. package/bin/lib/arkgate-pins.mjs +91 -0
  28. package/bin/lib/arkrule-file-hints.mjs +2 -47
  29. package/bin/lib/arkrules-contract.mjs +124 -133
  30. package/bin/lib/arkrules-sensors.mjs +55 -252
  31. package/bin/lib/check-args.mjs +85 -1
  32. package/bin/lib/ci-and-commands.mjs +24 -78
  33. package/bin/lib/ci-merge-boundary.mjs +1 -1
  34. package/bin/lib/class-source-scan.mjs +479 -0
  35. package/bin/lib/clone-detection.mjs +474 -0
  36. package/bin/lib/codex-home.mjs +5 -3
  37. package/bin/lib/config-contract-slices.mjs +739 -0
  38. package/bin/lib/config-contract.mjs +42 -607
  39. package/bin/lib/config-extras.mjs +16 -22
  40. package/bin/lib/config-warnings.mjs +32 -0
  41. package/bin/lib/contract-smells.mjs +33 -15
  42. package/bin/lib/core-ratchet.mjs +0 -2
  43. package/bin/lib/dashboard-cli.mjs +62 -0
  44. package/bin/lib/deep-module-coach.mjs +2 -4
  45. package/bin/lib/deploy-path.mjs +13 -38
  46. package/bin/lib/design-delta.mjs +1 -1
  47. package/bin/lib/design-smells.mjs +2 -2
  48. package/bin/lib/diagnostic-catalog.mjs +23 -9
  49. package/bin/lib/doctor-advisories.mjs +78 -8
  50. package/bin/lib/doctor-green-cite.mjs +1 -1
  51. package/bin/lib/doctor-human.mjs +1 -1
  52. package/bin/lib/doctor-next-actions.mjs +19 -4
  53. package/bin/lib/doctor-plan.mjs +9 -13
  54. package/bin/lib/duplication-io.mjs +572 -0
  55. package/bin/lib/effective-contract-load.mjs +282 -83
  56. package/bin/lib/enforcement-profiles.mjs +40 -4
  57. package/bin/lib/entry-points-io.mjs +424 -0
  58. package/bin/lib/extra-merge-teeth.mjs +36 -0
  59. package/bin/lib/field-install.mjs +38 -14
  60. package/bin/lib/first-run-help.mjs +10 -5
  61. package/bin/lib/flat-parent-importers.mjs +139 -0
  62. package/bin/lib/flat-parent-pilot.mjs +40 -100
  63. package/bin/lib/gate-files.mjs +58 -90
  64. package/bin/lib/git-change-scope.mjs +109 -0
  65. package/bin/lib/github-enforcement.mjs +166 -29
  66. package/bin/lib/golden-pattern.mjs +1 -1
  67. package/bin/lib/hook-templates.mjs +17 -15
  68. package/bin/lib/host-support-matrix.mjs +3 -1
  69. package/bin/lib/html-report-advisories.mjs +4 -0
  70. package/bin/lib/html-report-depth.mjs +2 -2
  71. package/bin/lib/html-report.mjs +2 -2
  72. package/bin/lib/import-graph-projection.mjs +112 -0
  73. package/bin/lib/import-resolve.mjs +13 -1
  74. package/bin/lib/improvement-compass-doctor.mjs +1 -24
  75. package/bin/lib/install-migrate.mjs +50 -73
  76. package/bin/lib/invariant-coverage-io.mjs +4 -3
  77. package/bin/lib/invariant-coverage.mjs +85 -11
  78. package/bin/lib/invariant-probe-cli.mjs +347 -0
  79. package/bin/lib/invariant-probe-io.mjs +165 -0
  80. package/bin/lib/invariant-probe-runner.mjs +268 -0
  81. package/bin/lib/invariant-probe-sites.mjs +174 -0
  82. package/bin/lib/invariant-probe-workspace.mjs +183 -0
  83. package/bin/lib/invariant-probe.mjs +461 -0
  84. package/bin/lib/invariant-tests-path.mjs +16 -22
  85. package/bin/lib/literal-path-drift.mjs +4 -2
  86. package/bin/lib/managed-upgrade.mjs +2 -8
  87. package/bin/lib/mcp-adoption.mjs +13 -6
  88. package/bin/lib/mcp-hook-payload.mjs +403 -63
  89. package/bin/lib/orphan-modules-io.mjs +458 -0
  90. package/bin/lib/orphan-modules.mjs +251 -0
  91. package/bin/lib/outside-importers.mjs +197 -0
  92. package/bin/lib/package-manager.mjs +60 -2
  93. package/bin/lib/parse-health.mjs +1 -1
  94. package/bin/lib/passthrough-commands.mjs +83 -0
  95. package/bin/lib/persistence-write-hint.mjs +106 -0
  96. package/bin/lib/pin-dependent-gates.mjs +117 -0
  97. package/bin/lib/policy-delta-io.mjs +219 -14
  98. package/bin/lib/post-green-path.mjs +1 -1
  99. package/bin/lib/prepare-change.mjs +115 -7
  100. package/bin/lib/prepare-write.mjs +2 -2
  101. package/bin/lib/presets.mjs +59 -73
  102. package/bin/lib/product-copy.mjs +1 -6
  103. package/bin/lib/project-root.mjs +31 -62
  104. package/bin/lib/remediation.mjs +23 -4
  105. package/bin/lib/resolved-candidate-facts.mjs +405 -117
  106. package/bin/lib/rules-inventory.mjs +22 -3
  107. package/bin/lib/rules-under-contract.mjs +247 -9
  108. package/bin/lib/scan-files.mjs +36 -4
  109. package/bin/lib/schema-validation.mjs +130 -0
  110. package/bin/lib/sensor-promote-cli.mjs +2 -11
  111. package/bin/lib/sensor-promote-io.mjs +33 -22
  112. package/bin/lib/sensor-promotion.mjs +1 -1
  113. package/bin/lib/skill-catalog-apply.mjs +1 -1
  114. package/bin/lib/skill-install.mjs +42 -38
  115. package/bin/lib/snippet-analysis.mjs +140 -6
  116. package/bin/lib/source-policy.mjs +34 -0
  117. package/bin/lib/start-install-recovery.mjs +72 -2
  118. package/bin/lib/start-preview.mjs +31 -1
  119. package/bin/lib/states-transitions-presence.mjs +3 -3
  120. package/bin/lib/status-command.mjs +35 -22
  121. package/bin/lib/status-manifest.mjs +50 -30
  122. package/bin/lib/status-transition-catalog.mjs +0 -6
  123. package/bin/lib/suggestions.mjs +3 -3
  124. package/bin/lib/team-parliament-io.mjs +76 -88
  125. package/bin/lib/team-parliament.mjs +21 -10
  126. package/bin/lib/upgrade-behavior-changes.mjs +2 -2
  127. package/bin/lib/upgrade-command.mjs +2 -24
  128. package/bin/lib/upgrade-outcome.mjs +1 -1
  129. package/bin/lib/upstream-report.mjs +21 -10
  130. package/bin/lib/violations.mjs +10 -9
  131. package/bin/lib/weakest-link.mjs +13 -0
  132. package/bin/lib/write-path-capabilities.mjs +6 -4
  133. package/dist/chunk-A5EIY3HI.cjs +5 -0
  134. package/dist/chunk-AHACEKSV.js +16 -0
  135. package/dist/chunk-SVSQVGFJ.js +5 -0
  136. package/dist/chunk-UN5EH4QV.cjs +16 -0
  137. package/dist/{configTypes-Bbf_MFGe.d.ts → configTypes-GPvvdleM.d.cts} +30 -4
  138. package/dist/configTypes-GPvvdleM.d.ts +257 -0
  139. package/dist/eslint/index.cjs +18 -5
  140. package/dist/eslint/index.d.cts +368 -0
  141. package/dist/eslint/index.d.ts +139 -156
  142. package/dist/eslint/index.js +11 -5
  143. package/dist/index.cjs +36 -35
  144. package/dist/index.d.cts +5547 -0
  145. package/dist/index.d.ts +3283 -198
  146. package/dist/index.js +36 -35
  147. package/dist/inspectorListen-6DQVJ4DC.js +1 -0
  148. package/dist/inspectorListen-KGMIQ2TF.cjs +1 -0
  149. package/dist/nestjs/index.cjs +1 -18
  150. package/dist/nestjs/index.d.cts +22 -0
  151. package/dist/nestjs/index.d.ts +1 -3
  152. package/dist/nestjs/index.js +1 -18
  153. package/dist/order/index.cjs +1 -1
  154. package/dist/order/index.d.cts +155 -0
  155. package/dist/order/index.d.ts +15 -3
  156. package/dist/order/index.js +1 -1
  157. package/dist/runtime/index.cjs +13 -30
  158. package/dist/{diagnosticCatalog-35mrwAHe.d.ts → runtime/index.d.cts} +828 -276
  159. package/dist/runtime/index.d.ts +2741 -133
  160. package/dist/runtime/index.js +13 -30
  161. package/dist/{types-Bdj32QwA.d.ts → types-CnauMQQL.d.cts} +607 -163
  162. package/dist/types-CnauMQQL.d.ts +1800 -0
  163. package/docs/README.md +3 -1
  164. package/docs/agent-guide.md +217 -16
  165. package/docs/ai-gates.md +174 -26
  166. package/docs/arkorder.md +32 -15
  167. package/docs/brownfield-adoption.md +5 -1
  168. package/docs/configuration.md +230 -31
  169. package/docs/develop.md +2 -1
  170. package/docs/diagnostics.md +212 -19
  171. package/docs/package-surface.md +35 -9
  172. package/docs/product-voice.md +7 -1
  173. package/package.json +69 -19
  174. package/schemas/ark.analysis-result.schema.json +15 -0
  175. package/schemas/ark.config.schema.json +77 -12
  176. package/schemas/ark.invariant-probe.schema.json +368 -0
  177. package/schemas/ark.resolved-candidate-facts.schema.json +1 -1
  178. package/schemas/ark.status-manifest.schema.json +22 -0
  179. package/server.json +3 -9
  180. package/templates/agent-skills/README.md +1 -1
  181. package/templates/agent-skills/ark-adopt/SKILL.md +5 -1
  182. package/templates/agent-skills/ark-contract/SKILL.md +17 -0
  183. package/templates/agent-skills/ark-coverage/SKILL.md +2 -0
  184. package/templates/agent-skills/ark-explore/SKILL.md +7 -0
  185. package/templates/agent-skills/ark-fix/SKILL.md +20 -0
  186. package/templates/agent-skills/ark-order/SKILL.md +4 -2
  187. package/templates/agent-skills/ark-place/SKILL.md +8 -0
  188. package/templates/agent-skills/ark-runtime/SKILL.md +6 -1
  189. package/templates/arkrules/PersistenceAdapters.json +1 -1
  190. package/templates/arkrules/PresentationAdapters.json +1 -1
  191. package/templates/skills/ark-adopt.md +5 -1
  192. package/templates/skills/ark-contract.md +17 -0
  193. package/templates/skills/ark-coverage.md +2 -0
  194. package/templates/skills/ark-explore.md +7 -0
  195. package/templates/skills/ark-fix.md +20 -0
  196. package/templates/skills/ark-order.md +4 -2
  197. package/templates/skills/ark-place.md +8 -0
  198. package/templates/skills/ark-runtime.md +6 -1
  199. package/bin/lib/ark-order-error.mjs +0 -18
  200. package/bin/lib/ark-order-invariants.mjs +0 -346
  201. package/dist/types-Ik_OakcI.d.ts +0 -183
@@ -88,22 +88,26 @@ export function defaultedArkOrder(value) {
88
88
  xiKeys: value.xiKeys === undefined ? [] : value.xiKeys,
89
89
  };
90
90
  }
91
+ /** Each named managed layer of an extra must be declared in `layers[]`. */
92
+ function validateManagedLayersDeclared(config, managed, extraKey, issues) {
93
+ if (!Array.isArray(managed))
94
+ return;
95
+ const layerNames = declaredLayerNames(config);
96
+ managed.forEach((name, index) => {
97
+ if (typeof name === 'string' && name.length > 0 && !layerNames.has(name)) {
98
+ issues.push({
99
+ path: `$.${extraKey}.managedLayers[${index}]`,
100
+ message: `layer ${JSON.stringify(name)} is not declared in layers[]`,
101
+ });
102
+ }
103
+ });
104
+ }
91
105
  export function validateArkRunExtra(config, issues) {
92
106
  const extra = config.arkRun;
93
107
  if (extra === undefined || !isObject(extra))
94
108
  return;
95
- const layerNames = declaredLayerNames(config);
96
109
  const managed = extra.managedLayers;
97
- if (Array.isArray(managed)) {
98
- managed.forEach((name, index) => {
99
- if (typeof name === 'string' && name.length > 0 && !layerNames.has(name)) {
100
- issues.push({
101
- path: `$.arkRun.managedLayers[${index}]`,
102
- message: `layer ${JSON.stringify(name)} is not declared in layers[]`,
103
- });
104
- }
105
- });
106
- }
110
+ validateManagedLayersDeclared(config, managed, 'arkRun', issues);
107
111
  if (extra.mode === 'enforced') {
108
112
  const roots = extra.kernelRoots ?? extra.compositionRoots;
109
113
  if (!Array.isArray(roots) || roots.length === 0) {
@@ -124,18 +128,8 @@ export function validateArkOrderExtra(config, issues) {
124
128
  const extra = config.arkOrder;
125
129
  if (extra === undefined || !isObject(extra))
126
130
  return;
127
- const layerNames = declaredLayerNames(config);
128
131
  const managed = extra.managedLayers;
129
- if (Array.isArray(managed)) {
130
- managed.forEach((name, index) => {
131
- if (typeof name === 'string' && name.length > 0 && !layerNames.has(name)) {
132
- issues.push({
133
- path: `$.arkOrder.managedLayers[${index}]`,
134
- message: `layer ${JSON.stringify(name)} is not declared in layers[]`,
135
- });
136
- }
137
- });
138
- }
132
+ validateManagedLayersDeclared(config, managed, 'arkOrder', issues);
139
133
  if (extra.mode === 'enforced') {
140
134
  const roots = extra.planeRoots;
141
135
  if (!Array.isArray(roots) || roots.length === 0) {
@@ -59,3 +59,35 @@ export function collectConfigWarnings(root, config, files, rules, manifest) {
59
59
  files: files.map((file) => normalize(path.relative(root, file))),
60
60
  });
61
61
  }
62
+
63
+ /**
64
+ * Machine-readable refusal for an invalid contract under `--json` / `--doctor --json`.
65
+ * The human message still goes to stderr; stdout must never be empty for JSON consumers.
66
+ */
67
+
68
+ /**
69
+ * @param {unknown} error
70
+ * @param {string[]} argv
71
+ * @returns {string|null} JSON line for stdout, or null when not a config-contract error / not --json
72
+ */
73
+ export function configInvalidJsonEnvelope(error, argv) {
74
+ if (!argv.includes('--json')) return null;
75
+ const e = /** @type {{ name?: string, issues?: Array<{path: string, message: string}>, source?: string }} */ (error);
76
+ if (e?.name !== 'ArkConfigValidationError' || !Array.isArray(e.issues)) {
77
+ // Any other fatal error still answers --json with JSON (exit 2 stays the caller's job),
78
+ // so a CI step that parses stdout never sees an empty or plain-text body.
79
+ const message = error instanceof Error ? error.message : String(error);
80
+ const policyBase = /^(Cannot (read|resolve) policy base|Policy base )/.test(message);
81
+ return JSON.stringify({
82
+ ok: false,
83
+ error: policyBase ? 'POLICY_BASE_UNREADABLE' : 'CHECK_ERROR',
84
+ message,
85
+ });
86
+ }
87
+ return JSON.stringify({
88
+ ok: false,
89
+ error: 'CONFIG_INVALID',
90
+ configPath: e.source,
91
+ messages: e.issues.map((issue) => `${issue.path}: ${issue.message}`),
92
+ });
93
+ }
@@ -102,15 +102,22 @@ function ackMatchable(...names) {
102
102
  }
103
103
 
104
104
  /**
105
- * Load the optional acknowledgment sidecar. Bounded and fail-loud:
106
- * non-file, oversized, unparsable, or wrong-shaped content → `invalid: true`
107
- * with `acks: []` (a broken file never suppresses anything).
105
+ * Bounded, fail-loud `.ark/` acknowledgment sidecar loader (contract-smell and
106
+ * ambient-state acks). Missing file → `exists: false`. Non-file, oversized,
107
+ * unparsable, over-long, or wrong-shaped content → `invalid: true` with
108
+ * `acks: []` (a broken file never suppresses anything).
108
109
  *
109
110
  * @param {string} root
110
- * @returns {{ path: string, exists: boolean, invalid?: boolean, error?: string, acks: Array<{id: string, edge: string, reason?: string}> }}
111
+ * @param {string} relPath
112
+ * @param {{
113
+ * shape: string,
114
+ * isWellFormed: (ack: any) => boolean,
115
+ * malformed: string,
116
+ * normalize?: (acks: any[]) => any[],
117
+ * }} spec
118
+ * @returns {{ path: string, exists: boolean, invalid?: boolean, error?: string, acks: any[] }}
111
119
  */
112
- export function loadContractSmellAcks(root) {
113
- const relPath = CONTRACT_SMELL_ACKS_PATH;
120
+ export function loadAckSidecar(root, relPath, spec) {
114
121
  const abs = path.join(root, relPath);
115
122
  let stats;
116
123
  try {
@@ -128,21 +135,32 @@ export function loadContractSmellAcks(root) {
128
135
  return invalid(error instanceof Error ? error.message : 'unreadable JSON');
129
136
  }
130
137
  const acks = Array.isArray(parsed?.acks) ? parsed.acks : null;
131
- if (!acks) return invalid('expected { acks: [{ id, edge, reason? }] }');
138
+ if (!acks) return invalid(`expected ${spec.shape}`);
132
139
  if (acks.length > MAX_ACK_ENTRIES) return invalid(`more than ${MAX_ACK_ENTRIES} entries`);
133
- const wellFormed = acks.every(
134
- (a) =>
140
+ if (!acks.every(spec.isWellFormed)) return invalid(spec.malformed);
141
+ return { path: relPath, exists: true, acks: spec.normalize ? spec.normalize(acks) : acks };
142
+ }
143
+
144
+ /**
145
+ * Load the optional acknowledgment sidecar. Bounded and fail-loud:
146
+ * non-file, oversized, unparsable, or wrong-shaped content → `invalid: true`
147
+ * with `acks: []` (a broken file never suppresses anything).
148
+ *
149
+ * @param {string} root
150
+ * @returns {{ path: string, exists: boolean, invalid?: boolean, error?: string, acks: Array<{id: string, edge: string, reason?: string}> }}
151
+ */
152
+ export function loadContractSmellAcks(root) {
153
+ return loadAckSidecar(root, CONTRACT_SMELL_ACKS_PATH, {
154
+ shape: '{ acks: [{ id, edge, reason? }] }',
155
+ isWellFormed: (a) =>
135
156
  a !== null &&
136
157
  typeof a === 'object' &&
137
158
  typeof a.id === 'string' &&
138
159
  typeof a.edge === 'string' &&
139
160
  a.edge.trim().length > 0 &&
140
- (a.reviewBy === undefined || typeof a.reviewBy === 'string')
141
- );
142
- if (!wellFormed) {
143
- return invalid('every ack needs string id, non-empty string edge, and string reviewBy when present');
144
- }
145
- return { path: relPath, exists: true, acks };
161
+ (a.reviewBy === undefined || typeof a.reviewBy === 'string'),
162
+ malformed: 'every ack needs string id, non-empty string edge, and string reviewBy when present',
163
+ });
146
164
  }
147
165
 
148
166
  /**
@@ -8,8 +8,6 @@ import { computeCoverage } from './doctor-plan.mjs';
8
8
  import { CORE_LAYER_NAMES } from './core-layers.mjs';
9
9
  import { resolveConfigPathWithinRoot } from './project-root.mjs';
10
10
 
11
- export { CORE_LAYER_NAMES } from './core-layers.mjs';
12
-
13
11
  /**
14
12
  * Core layers whose optionality matters once they match files (presets share these names).
15
13
  * Used by doctor adoption gaps and `--ratchet-cores`.
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Shared, pure helpers for the observability dashboard CLI (`ark-dashboard`,
3
+ * `arkgate-dashboard`, and the `ark dashboard` passthrough). No I/O here.
4
+ */
5
+
6
+ export const DASHBOARD_DEFAULT_INTERVAL_MS = 2000;
7
+ export const DASHBOARD_DEFAULT_TIMEOUT_MS = 5000;
8
+ export const DASHBOARD_DEFAULT_URL = 'http://127.0.0.1:3000/snapshot';
9
+ const DASHBOARD_MIN_MS = 200;
10
+ const DASHBOARD_MAX_MS = 60_000;
11
+
12
+ export const DASHBOARD_HELP = `arkgate-dashboard (alias ark-dashboard, ark dashboard) — observability TUI.
13
+ Usage: arkgate-dashboard [--url <inspector-url>] [--interval <ms>] [--timeout <ms>] [--once]
14
+ Polls an ArkRun inspector; it does not start the kernel.
15
+
16
+ -u, --url <url> Inspector URL: handle.url (root) or handle.snapshotUrl.
17
+ Default: $ARK_DASHBOARD_URL, else ${DASHBOARD_DEFAULT_URL}.
18
+ startInspector() binds a random port unless you pass
19
+ { port }, so pass the URL your app printed.
20
+ -i, --interval <ms> Poll interval, clamped to ${DASHBOARD_MIN_MS}-${DASHBOARD_MAX_MS} (default ${DASHBOARD_DEFAULT_INTERVAL_MS}).
21
+ -t, --timeout <ms> Fetch timeout, clamped to ${DASHBOARD_MIN_MS}-${DASHBOARD_MAX_MS} (default ${DASHBOARD_DEFAULT_TIMEOUT_MS}).
22
+ --once Render one frame and exit (non-zero when the kernel is unreachable).
23
+ -h, --help Show this help.
24
+ -v, --version Print the arkgate version.`;
25
+
26
+ export const DASHBOARD_EPHEMERAL_PORT_HINT =
27
+ 'Hint: startInspector() binds a random port by default (port 0). Pass --url <handle.url> ' +
28
+ '(printed by your app), set ARK_DASHBOARD_URL, or start the inspector with startInspector({ port: 3000 }).';
29
+
30
+ /**
31
+ * Clamp a millisecond flag into [min, max]. Non-numeric input uses the default.
32
+ * @param {string | undefined} raw
33
+ * @param {number} fallback
34
+ */
35
+ export function clampDashboardMs(raw, fallback) {
36
+ if (raw === undefined || raw === null || String(raw).trim() === '') return fallback;
37
+ const parsed = Number.parseInt(String(raw), 10);
38
+ if (!Number.isFinite(parsed)) return fallback;
39
+ return Math.min(DASHBOARD_MAX_MS, Math.max(DASHBOARD_MIN_MS, parsed));
40
+ }
41
+
42
+ /**
43
+ * Derive a sibling inspector route (`/outbox`, `/workflows`) from the URL the
44
+ * user passed. Accepts the inspector root (`handle.url`, with or without a
45
+ * trailing slash), `/snapshot`, `/snapshot/`, and prefix mounts (`/x/snapshot`).
46
+ * @param {string} inspectorUrl
47
+ * @param {string} suffix e.g. '/outbox'
48
+ * @returns {string | null}
49
+ */
50
+ export function dashboardSiblingUrl(inspectorUrl, suffix) {
51
+ try {
52
+ const u = new URL(inspectorUrl);
53
+ let basePath = u.pathname.replace(/\/+$/, '');
54
+ if (basePath.endsWith('/snapshot')) basePath = basePath.slice(0, -'/snapshot'.length);
55
+ u.pathname = `${basePath}${suffix}`;
56
+ u.search = '';
57
+ u.hash = '';
58
+ return u.toString();
59
+ } catch {
60
+ return null;
61
+ }
62
+ }
@@ -14,12 +14,10 @@ import {
14
14
  DEEPENING_CANDIDATE_CAP,
15
15
  } from './deepening-coach.mjs';
16
16
 
17
- export { buildDeepeningCandidates, ARK_DEEPENING_COACH_SCHEMA_VERSION, DEEPENING_CANDIDATE_CAP };
18
-
19
17
  /** Recent-window commit cap for hot-path heuristic (budget). */
20
- export const HOT_PATH_COMMIT_LIMIT = 200;
18
+ const HOT_PATH_COMMIT_LIMIT = 200;
21
19
  /** Max listed hot paths. */
22
- export const HOT_PATH_LIST_CAP = 8;
20
+ const HOT_PATH_LIST_CAP = 8;
23
21
  /** Minimum change hits before a path is “elevated”. */
24
22
  export const HOT_PATH_MIN_HITS = 3;
25
23
  /** Kill hung git instead of stalling CI. */
@@ -3,7 +3,7 @@
3
3
  */
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
- import { readPackageJson, packageScriptsHaveTypecheck } from './gate-files.mjs';
6
+ import { readPackageJson, packageScriptsHaveTypecheck, someNestedPackageJson } from './gate-files.mjs';
7
7
 
8
8
  /**
9
9
  * Production deploy path quality (universal — any consumer repo).
@@ -62,44 +62,19 @@ export function detectDeployPathQuality(root) {
62
62
  let hasTypecheckScript = packageScriptsHaveTypecheck(scripts);
63
63
  const packageLintScripts = [];
64
64
  // Monorepo: package-level scripts count (apps/web, packages/ui, …).
65
- try {
66
- for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
67
- if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === 'node_modules') continue;
68
- const candidates = [path.join(root, entry.name)];
69
- // one more level: packages/foo
70
- try {
71
- for (const child of fs.readdirSync(path.join(root, entry.name), { withFileTypes: true })) {
72
- if (child.isDirectory() && !child.name.startsWith('.')) {
73
- candidates.push(path.join(root, entry.name, child.name));
74
- }
75
- }
76
- } catch {
77
- /* ignore */
78
- }
79
- for (const dir of candidates) {
80
- const pj = path.join(dir, 'package.json');
81
- if (!fs.existsSync(pj)) continue;
82
- try {
83
- const nested = JSON.parse(fs.readFileSync(pj, 'utf8'));
84
- const ns = nested.scripts && typeof nested.scripts === 'object' ? nested.scripts : {};
85
- if (scriptHasLint(ns)) {
86
- hasLintScript = true;
87
- packageLintScripts.push(path.relative(root, dir).split(path.sep).join('/'));
88
- }
89
- if (packageScriptsHaveTypecheck(ns)) hasTypecheckScript = true;
90
- const nd = {
91
- ...(nested.dependencies || {}),
92
- ...(nested.devDependencies || {}),
93
- };
94
- if (nd.next && !engines.includes('next')) engines.push('next');
95
- } catch {
96
- /* ignore */
97
- }
98
- }
65
+ someNestedPackageJson(root, (nested, dir) => {
66
+ const ns = nested.scripts && typeof nested.scripts === 'object' ? nested.scripts : {};
67
+ if (scriptHasLint(ns)) {
68
+ hasLintScript = true;
69
+ packageLintScripts.push(path.relative(root, dir).split(path.sep).join('/'));
99
70
  }
100
- } catch {
101
- /* ignore */
102
- }
71
+ if (packageScriptsHaveTypecheck(ns)) hasTypecheckScript = true;
72
+ const nd = {
73
+ ...(nested.dependencies || {}),
74
+ ...(nested.devDependencies || {}),
75
+ };
76
+ if (nd.next && !engines.includes('next')) engines.push('next');
77
+ });
103
78
 
104
79
  const ciTexts = collectCiWorkflowTexts(root);
105
80
  const ciJoined = ciTexts.join('\n');
@@ -1,4 +1,4 @@
1
1
  // Generated from design-delta.source.mjs — run npm run generate:packaged-tooling.
2
- import{spawnSync as O}from"node:child_process";import B from"node:crypto";import j from"node:fs";import w from"node:path";import{layerForFile as T}from"../ark-shared.mjs";import{loadGoldenPattern as I}from"./golden-pattern.mjs";import{collectGovernedFiles as q}from"./scan-files.mjs";const P="1.0",_=Object.freeze(["domain-logic-in-ui"]),b=/\.[cm]?[jt]sx?$/i,W=/(?:^|\/)(?:components?|pages|hooks|ui|views|screens)(?:\/|$)|(?:^|\/)app\/(?!api\/)/i,U=/^(can|should|calculate|compute)[A-Z_]|policy/i,z=/^(can|should)[A-Z_]|policy/i,H=/^(calculate|compute)[A-Z_]/i,D=/(?:route|routing|path|label|className|style|render|display|view|modal|dialog|tooltip|navigate|navigation|href|tab|menu|component|toast|breadcrumb|sidebar|drawer|popover|layout|theme|icon)/i,G=/^(?:use[A-Z_]|render|navigate|redirect|push|replace|open|close|show|hide|setState|set[A-Z_]|toast|alert|confirm)/,J=new Set(["includes","some","every","has"]);function h(e){return String(e||"").replace(/\\/g,"/").replace(/^\.\//,"")}function $(e){return`sha256:${B.createHash("sha256").update(e,"utf8").digest("hex")}`}function C(e,t){const s=[...t].map(n=>[h(n.path),$(n.content)]).sort(([n],[i])=>n.localeCompare(i));return $(JSON.stringify({config:e,files:s}))}function V(e,t){const s=t.toLowerCase();return s.endsWith(".tsx")?e.ScriptKind.TSX:s.endsWith(".jsx")?e.ScriptKind.JSX:s.endsWith(".js")||s.endsWith(".mjs")||s.endsWith(".cjs")?e.ScriptKind.JS:e.ScriptKind.TS}function Z(e,t,s){const n=T(e,s,t?.layers??[]);return W.test(s)||/presentation|ui|view/i.test(n??"")}function Q(e,t){const s=[],n=i=>{if(e.isFunctionDeclaration(i)&&i.name&&i.body)s.push({name:i.name.text,body:i.body,node:i});else if(e.isVariableDeclaration(i)&&e.isIdentifier(i.name)){const a=i.initializer;a&&(e.isArrowFunction(a)||e.isFunctionExpression(a))&&s.push({name:i.name.text,body:a.body,node:i})}else e.isMethodDeclaration(i)&&i.name&&e.isIdentifier(i.name)&&i.body&&s.push({name:i.name.text,body:i.body,node:i});e.forEachChild(i,n)};return n(t),s}function X(e,t){if(!U.test(t.name)||D.test(t.name))return null;let s=0,n=0,i=0,a=0,r=!1,o=!1;const l=new Set([e.SyntaxKind.EqualsEqualsToken,e.SyntaxKind.EqualsEqualsEqualsToken,e.SyntaxKind.ExclamationEqualsToken,e.SyntaxKind.ExclamationEqualsEqualsToken,e.SyntaxKind.LessThanToken,e.SyntaxKind.LessThanEqualsToken,e.SyntaxKind.GreaterThanToken,e.SyntaxKind.GreaterThanEqualsToken,e.SyntaxKind.InKeyword,e.SyntaxKind.InstanceOfKeyword]),u=new Set([e.SyntaxKind.AmpersandAmpersandToken,e.SyntaxKind.BarBarToken,e.SyntaxKind.QuestionQuestionToken]),p=new Set([e.SyntaxKind.PlusToken,e.SyntaxKind.MinusToken,e.SyntaxKind.AsteriskToken,e.SyntaxKind.SlashToken,e.SyntaxKind.PercentToken,e.SyntaxKind.AsteriskAsteriskToken]),f=c=>{if(e.isJsxElement(c)||e.isJsxSelfClosingElement(c)||e.isJsxFragment(c)){o=!0;return}if(e.isBinaryExpression(c)&&(l.has(c.operatorToken.kind)&&(s+=1),u.has(c.operatorToken.kind)&&(n+=1),p.has(c.operatorToken.kind)&&(i+=1)),e.isCallExpression(c)){let g="";e.isIdentifier(c.expression)?g=c.expression.text:e.isPropertyAccessExpression(c.expression)&&(g=c.expression.name.text),J.has(g)&&(a+=1),(G.test(g)||D.test(g))&&(r=!0)}e.forEachChild(c,f)};if(f(t.body),o||r)return null;const m=s+n+a,v=i;let S,d;if(H.test(t.name)&&v>0)S="calculation-rule",d=v;else if(z.test(t.name)&&m>0)S="authorization-policy-rule",d=m;else return null;return{kind:S,magnitude:d,detail:`comparisons:${s};logical:${n};predicates:${a};arithmetic:${i}`}}function Y(e,t){return e?.present&&e.golden?.newCodeHome?`Move ${t} to ${e.golden.newCodeHome} following golden pattern "${e.golden.name}", then import the pure rule from the UI.`:`Move ${t} into the project's Domain/shared pure-rules home and import it from the UI; do not weaken ark.config.json.`}function E({root:e,config:t,records:s,ts:n,goldenPattern:i}){if(!n?.createSourceFile)throw new Error("TypeScript parser is required for design-delta analysis.");const a=[];for(const r of[...s].sort((o,l)=>h(o.path).localeCompare(h(l.path)))){const o=h(r.path);if(!b.test(o)||o.endsWith(".d.ts")||!Z(e,t,o))continue;const l=n.createSourceFile(o,String(r.content),n.ScriptTarget.Latest,!0,V(n,o));for(const u of Q(n,l)){const p=X(n,u);if(!p)continue;const f=`domain-logic-in-ui|${o}|${u.name}|${p.kind}`,m=l.getLineAndCharacterOfPosition(u.node.getStart(l)).line+1;a.push({smellId:"domain-logic-in-ui",fingerprint:$(f),identity:f,evidence:{kind:p.kind,path:o,line:m,symbol:u.name,detail:p.detail,magnitude:p.magnitude},repairHint:Y(i,u.name)})}}return a.sort((r,o)=>r.identity.localeCompare(o.identity))}function L({mode:e,baseIdentity:t,candidateIdentity:s,touchedPaths:n,baseFindings:i,candidateFindings:a,createdPathsOnly:r=!1,baseTreePaths:o=[]}){const l=new Set([...n].map(h)),u=new Set([...o].map(h)),p=new Map(i.map(d=>[d.identity,d])),f=new Set(i),m=[];let v=0;for(const d of a){let c=p.get(d.identity);if(!c){const y=[...f].filter(k=>k.smellId===d.smellId&&k.evidence.symbol===d.evidence.symbol&&k.evidence.kind===d.evidence.kind);y.length===1&&([c]=y)}c&&f.delete(c);const g=c?.evidence?.magnitude??0,x=d.evidence.magnitude;if(!l.has(d.evidence.path)){c&&(v+=1);continue}c?x>g?m.push({...d,classification:"worsened",baseMagnitude:g,candidateMagnitude:x}):v+=1:m.push({...d,classification:"new",baseMagnitude:0,candidateMagnitude:x})}const S=r?m.filter(d=>d.classification==="new"&&!u.has(h(d.evidence.path))):m;return{schemaVersion:P,mode:e,complete:!0,valid:S.length===0,base:t,candidate:s,supportedSmellIds:[..._],touchedPaths:[...l].sort(),changes:S,baseFindingCount:i.length,candidateFindingCount:a.length,historicalResidualCount:v,enforcementScope:r?"created-paths":"touched-new-or-worsened"}}function F(e,t){const s=[];for(const n of q(e,t)){const i=h(w.relative(e,n));!b.test(i)||i.endsWith(".d.ts")||s.push({path:i,content:j.readFileSync(n,"utf8")})}return s}function ee(e,t,s,n){const i=new Map(s.map(a=>[h(a.path),a.content]));for(const a of n){const r=h(a.path);!b.test(r)||r.endsWith(".d.ts")||!T(e,r,t?.layers??[])||(a.delete===!0?i.delete(r):typeof a.content=="string"&&i.set(r,a.content))}return[...i].map(([a,r])=>({path:a,content:r}))}function de({root:e,config:t,changes:s,ts:n}){const i=F(e,t),a=ee(e,t,i,s??[]),r=I(e),o=E({root:e,config:t,records:i,ts:n,goldenPattern:r}),l=E({root:e,config:t,records:a,ts:n,goldenPattern:r});return L({mode:"write-candidate",baseIdentity:{kind:"candidate-tree",value:C(t,i)},candidateIdentity:{kind:"candidate-tree",value:C(t,a)},touchedPaths:(s??[]).map(u=>u.path),baseFindings:o,candidateFindings:l})}function K(e,t,s={}){return O("git",t,{cwd:e,encoding:s.encoding??"utf8",maxBuffer:64*1024*1024,input:s.input})}function M(e,t,s){const n=K(e,t);if(n.status!==0)throw new Error(`${s}: ${(n.stderr||n.stdout||"git command failed").trim()}`);return n.stdout.trim()}function A(e,t,s){const n=K(e,t,{encoding:"buffer"});if(n.status!==0)throw new Error(`${s}: ${String(n.stderr||n.stdout||"git command failed").trim()}`);return n.stdout.toString("utf8").split("\0").map(h).filter(Boolean)}function R(e,t,s){const n=K(e,["show",`${t}:${s}`]);if(n.status!==0)throw new Error(`base file unavailable (${s}): ${(n.stderr||"").trim()}`);return n.stdout}function N(e,t){return{schemaVersion:P,mode:"git-base",complete:!1,valid:!1,base:{kind:"git-tree",value:String(e||"<missing>")},candidate:{kind:"candidate-tree",value:"<unavailable>"},supportedSmellIds:[..._],touchedPaths:[],changes:[],baseFindingCount:0,candidateFindingCount:0,historicalResidualCount:0,error:t}}function te({root:e,config:t,configPath:s="ark.config.json",baseRef:n,ts:i,createdPathsOnly:a=!1,missingBase:r="fail-closed"}){const o=r==="skip";if(typeof n!="string"||!n.trim())return N(n,o?"design-delta skipped: no resolvable Git base ref.":"--fail-on-new-smells requires --base-ref <git-ref>.");try{if(n.startsWith("-"))throw new Error('base ref must not start with "-".');const l=M(e,["rev-parse","--verify",`${n}^{commit}`],"base ref is unresolvable"),u=M(e,["rev-parse","--verify",`${l}^{tree}`],"base tree is unresolvable"),p=h(w.isAbsolute(s)?w.relative(e,s):s);if(!p||p.startsWith("../"))throw new Error("base config path must be inside the project root.");const f=JSON.parse(R(e,l,p)),m=A(e,["ls-tree","-r","--name-only","-z",l],"base tree listing failed").filter(y=>b.test(y)&&!y.endsWith(".d.ts")),v=m.filter(y=>T(e,y,f?.layers??[])).map(y=>({path:y,content:R(e,l,y)})),S=F(e,t),d=[...A(e,["diff","--name-only","-z",l,"--"],"candidate diff failed"),...A(e,["ls-files","--others","--exclude-standard","-z"],"untracked-file scan failed")],c=I(e),g=E({root:e,config:f,records:v,ts:i,goldenPattern:c}),x=E({root:e,config:t,records:S,ts:i,goldenPattern:c});return L({mode:"git-base",baseIdentity:{kind:"git-tree",value:u,commit:l},candidateIdentity:{kind:"candidate-tree",value:C(t,S)},touchedPaths:d,baseFindings:g,candidateFindings:x,createdPathsOnly:!!a,baseTreePaths:m})}catch(l){return N(n,l instanceof Error?l.message:String(l))}}function ne(e){return e?.complete?e.valid?`Design delta passed: 0 new/worsened supported smells across ${e.touchedPaths.length} touched path(s).`:[`Design delta blocked ${e.changes.length} new/worsened supported smell(s):`,...e.changes.map(t=>`- [${t.smellId}] ${t.evidence.path}:${t.evidence.line??1} ${t.evidence.symbol??""} (${t.classification})
2
+ import{spawnSync as O}from"node:child_process";import B from"node:crypto";import j from"node:fs";import w from"node:path";import{layerForFile as T}from"../ark-shared.mjs";import{loadGoldenPattern as I}from"./golden-pattern.mjs";import{collectGovernedFiles as q}from"./scan-files.mjs";const P="1.0",_=Object.freeze(["domain-logic-in-ui"]),b=/\.[cm]?[jt]sx?$/i,W=/(?:^|\/)(?:components?|pages|hooks|ui|views|screens)(?:\/|$)|(?:^|\/)app\/(?!api\/)/i,U=/^(can|should|calculate|compute)[A-Z_]|policy/i,z=/^(can|should)[A-Z_]|policy/i,H=/^(calculate|compute)[A-Z_]/i,D=/(?:route|routing|path|label|className|style|render|display|view|modal|dialog|tooltip|navigate|navigation|href|tab|menu|component|toast|breadcrumb|sidebar|drawer|popover|layout|theme|icon)/i,G=/^(?:use[A-Z_]|render|navigate|redirect|push|replace|open|close|show|hide|setState|set[A-Z_]|toast|alert|confirm)/,J=new Set(["includes","some","every","has"]);function h(e){return String(e||"").replace(/\\/g,"/").replace(/^\.\//,"")}function $(e){return`sha256:${B.createHash("sha256").update(e,"utf8").digest("hex")}`}function C(e,t){const s=[...t].map(n=>[h(n.path),$(n.content)]).sort(([n],[i])=>n.localeCompare(i));return $(JSON.stringify({config:e,files:s}))}function V(e,t){const s=t.toLowerCase();return s.endsWith(".tsx")?e.ScriptKind.TSX:s.endsWith(".jsx")?e.ScriptKind.JSX:s.endsWith(".js")||s.endsWith(".mjs")||s.endsWith(".cjs")?e.ScriptKind.JS:e.ScriptKind.TS}function Z(e,t,s){const n=T(e,s,t?.layers??[]);return W.test(s)||/presentation|ui|view/i.test(n??"")}function Q(e,t){const s=[],n=i=>{if(e.isFunctionDeclaration(i)&&i.name&&i.body)s.push({name:i.name.text,body:i.body,node:i});else if(e.isVariableDeclaration(i)&&e.isIdentifier(i.name)){const a=i.initializer;a&&(e.isArrowFunction(a)||e.isFunctionExpression(a))&&s.push({name:i.name.text,body:a.body,node:i})}else e.isMethodDeclaration(i)&&i.name&&e.isIdentifier(i.name)&&i.body&&s.push({name:i.name.text,body:i.body,node:i});e.forEachChild(i,n)};return n(t),s}function X(e,t){if(!U.test(t.name)||D.test(t.name))return null;let s=0,n=0,i=0,a=0,r=!1,o=!1;const l=new Set([e.SyntaxKind.EqualsEqualsToken,e.SyntaxKind.EqualsEqualsEqualsToken,e.SyntaxKind.ExclamationEqualsToken,e.SyntaxKind.ExclamationEqualsEqualsToken,e.SyntaxKind.LessThanToken,e.SyntaxKind.LessThanEqualsToken,e.SyntaxKind.GreaterThanToken,e.SyntaxKind.GreaterThanEqualsToken,e.SyntaxKind.InKeyword,e.SyntaxKind.InstanceOfKeyword]),u=new Set([e.SyntaxKind.AmpersandAmpersandToken,e.SyntaxKind.BarBarToken,e.SyntaxKind.QuestionQuestionToken]),p=new Set([e.SyntaxKind.PlusToken,e.SyntaxKind.MinusToken,e.SyntaxKind.AsteriskToken,e.SyntaxKind.SlashToken,e.SyntaxKind.PercentToken,e.SyntaxKind.AsteriskAsteriskToken]),f=c=>{if(e.isJsxElement(c)||e.isJsxSelfClosingElement(c)||e.isJsxFragment(c)){o=!0;return}if(e.isBinaryExpression(c)&&(l.has(c.operatorToken.kind)&&(s+=1),u.has(c.operatorToken.kind)&&(n+=1),p.has(c.operatorToken.kind)&&(i+=1)),e.isCallExpression(c)){let g="";e.isIdentifier(c.expression)?g=c.expression.text:e.isPropertyAccessExpression(c.expression)&&(g=c.expression.name.text),J.has(g)&&(a+=1),(G.test(g)||D.test(g))&&(r=!0)}e.forEachChild(c,f)};if(f(t.body),o||r)return null;const m=s+n+a,v=i;let S,d;if(H.test(t.name)&&v>0)S="calculation-rule",d=v;else if(z.test(t.name)&&m>0)S="authorization-policy-rule",d=m;else return null;return{kind:S,magnitude:d,detail:`comparisons:${s};logical:${n};predicates:${a};arithmetic:${i}`}}function Y(e,t){return e?.present&&e.golden?.newCodeHome?`Move ${t} to ${e.golden.newCodeHome} following golden pattern "${e.golden.name}", then import the pure rule from the UI.`:`Move ${t} into the project's Domain/shared pure-rules home and import it from the UI; do not weaken ark.config.json.`}function E({root:e,config:t,records:s,ts:n,goldenPattern:i}){if(!n?.createSourceFile)throw new Error("TypeScript parser is required for design-delta analysis.");const a=[];for(const r of[...s].sort((o,l)=>h(o.path).localeCompare(h(l.path)))){const o=h(r.path);if(!b.test(o)||o.endsWith(".d.ts")||!Z(e,t,o))continue;const l=n.createSourceFile(o,String(r.content),n.ScriptTarget.Latest,!0,V(n,o));for(const u of Q(n,l)){const p=X(n,u);if(!p)continue;const f=`domain-logic-in-ui|${o}|${u.name}|${p.kind}`,m=l.getLineAndCharacterOfPosition(u.node.getStart(l)).line+1;a.push({smellId:"domain-logic-in-ui",fingerprint:$(f),identity:f,evidence:{kind:p.kind,path:o,line:m,symbol:u.name,detail:p.detail,magnitude:p.magnitude},repairHint:Y(i,u.name)})}}return a.sort((r,o)=>r.identity.localeCompare(o.identity))}function L({mode:e,baseIdentity:t,candidateIdentity:s,touchedPaths:n,baseFindings:i,candidateFindings:a,createdPathsOnly:r=!1,baseTreePaths:o=[]}){const l=new Set([...n].map(h)),u=new Set([...o].map(h)),p=new Map(i.map(d=>[d.identity,d])),f=new Set(i),m=[];let v=0;for(const d of a){let c=p.get(d.identity);if(!c){const y=[...f].filter(k=>k.smellId===d.smellId&&k.evidence.symbol===d.evidence.symbol&&k.evidence.kind===d.evidence.kind);y.length===1&&([c]=y)}c&&f.delete(c);const g=c?.evidence?.magnitude??0,x=d.evidence.magnitude;if(!l.has(d.evidence.path)){c&&(v+=1);continue}c?x>g?m.push({...d,classification:"worsened",baseMagnitude:g,candidateMagnitude:x}):v+=1:m.push({...d,classification:"new",baseMagnitude:0,candidateMagnitude:x})}const S=r?m.filter(d=>d.classification==="new"&&!u.has(h(d.evidence.path))):m;return{schemaVersion:P,mode:e,complete:!0,valid:S.length===0,base:t,candidate:s,supportedSmellIds:[..._],touchedPaths:[...l].sort(),changes:S,baseFindingCount:i.length,candidateFindingCount:a.length,historicalResidualCount:v,enforcementScope:r?"created-paths":"touched-new-or-worsened"}}function F(e,t){const s=[];for(const n of q(e,t)){const i=h(w.relative(e,n));!b.test(i)||i.endsWith(".d.ts")||s.push({path:i,content:j.readFileSync(n,"utf8")})}return s}function ee(e,t,s,n){const i=new Map(s.map(a=>[h(a.path),a.content]));for(const a of n){const r=h(a.path);!b.test(r)||r.endsWith(".d.ts")||!T(e,r,t?.layers??[])||(a.delete===!0?i.delete(r):typeof a.content=="string"&&i.set(r,a.content))}return[...i].map(([a,r])=>({path:a,content:r}))}function de({root:e,config:t,changes:s,ts:n}){const i=F(e,t),a=ee(e,t,i,s??[]),r=I(e),o=E({root:e,config:t,records:i,ts:n,goldenPattern:r}),l=E({root:e,config:t,records:a,ts:n,goldenPattern:r});return L({mode:"write-candidate",baseIdentity:{kind:"candidate-tree",value:C(t,i)},candidateIdentity:{kind:"candidate-tree",value:C(t,a)},touchedPaths:(s??[]).map(u=>u.path),baseFindings:o,candidateFindings:l})}function K(e,t,s={}){return O("git",t,{cwd:e,encoding:s.encoding??"utf8",maxBuffer:64*1024*1024,input:s.input})}function M(e,t,s){const n=K(e,t);if(n.status!==0)throw new Error(`${s}: ${(n.stderr||n.stdout||"git command failed").trim()}`);return n.stdout.trim()}function A(e,t,s){const n=K(e,t,{encoding:"buffer"});if(n.status!==0)throw new Error(`${s}: ${String(n.stderr||n.stdout||"git command failed").trim()}`);return n.stdout.toString("utf8").split("\0").map(h).filter(Boolean)}function R(e,t,s){const n=K(e,["show",`${t}:./${s}`]);if(n.status!==0)throw new Error(`base file unavailable (${s}): ${(n.stderr||"").trim()}`);return n.stdout}function N(e,t){return{schemaVersion:P,mode:"git-base",complete:!1,valid:!1,base:{kind:"git-tree",value:String(e||"<missing>")},candidate:{kind:"candidate-tree",value:"<unavailable>"},supportedSmellIds:[..._],touchedPaths:[],changes:[],baseFindingCount:0,candidateFindingCount:0,historicalResidualCount:0,error:t}}function te({root:e,config:t,configPath:s="ark.config.json",baseRef:n,ts:i,createdPathsOnly:a=!1,missingBase:r="fail-closed"}){const o=r==="skip";if(typeof n!="string"||!n.trim())return N(n,o?"design-delta skipped: no resolvable Git base ref.":"--fail-on-new-smells requires --base-ref <git-ref>.");try{if(n.startsWith("-"))throw new Error('base ref must not start with "-".');const l=M(e,["rev-parse","--verify",`${n}^{commit}`],"base ref is unresolvable"),u=M(e,["rev-parse","--verify",`${l}^{tree}`],"base tree is unresolvable"),p=h(w.isAbsolute(s)?w.relative(e,s):s);if(!p||p.startsWith("../"))throw new Error("base config path must be inside the project root.");const f=JSON.parse(R(e,l,p)),m=A(e,["ls-tree","-r","--name-only","-z",l],"base tree listing failed").filter(y=>b.test(y)&&!y.endsWith(".d.ts")),v=m.filter(y=>T(e,y,f?.layers??[])).map(y=>({path:y,content:R(e,l,y)})),S=F(e,t),d=[...A(e,["diff","--relative","--name-only","-z",l,"--"],"candidate diff failed"),...A(e,["ls-files","--others","--exclude-standard","-z"],"untracked-file scan failed")],c=I(e),g=E({root:e,config:f,records:v,ts:i,goldenPattern:c}),x=E({root:e,config:t,records:S,ts:i,goldenPattern:c});return L({mode:"git-base",baseIdentity:{kind:"git-tree",value:u,commit:l},candidateIdentity:{kind:"candidate-tree",value:C(t,S)},touchedPaths:d,baseFindings:g,candidateFindings:x,createdPathsOnly:!!a,baseTreePaths:m})}catch(l){return N(n,l instanceof Error?l.message:String(l))}}function ne(e){return e?.complete?e.valid?`Design delta passed: 0 new/worsened supported smells across ${e.touchedPaths.length} touched path(s).`:[`Design delta blocked ${e.changes.length} new/worsened supported smell(s):`,...e.changes.map(t=>`- [${t.smellId}] ${t.evidence.path}:${t.evidence.line??1} ${t.evidence.symbol??""} (${t.classification})
3
3
  Next action: ${t.repairHint}`)].join(`
4
4
  `):`Design delta unavailable: ${e?.error||"unknown error"}`}function ue({enabled:e,createdPathsOnly:t,missingBase:s,...n}){const i=s==="skip",a=e?te({...n,createdPathsOnly:!!t,missingBase:i?"skip":"fail-closed"}):null,r=a&&i&&!a.complete?null:a;return{result:r,combineEdges:({activeViolationCount:o,strictConfig:l,strictWarningCount:u,policyValid:p})=>{const f=o===0&&(!l||u===0)&&p;return{edgeValid:f,observedOk:f&&(r?.valid??!0)}},exitCode:o=>r&&!r.complete?2:o,failureText:()=>r&&!r.valid?ne(r):null}}function pe(e){return e?e.complete?e.valid?[{level:"ok",text:`0 new/worsened supported smells across ${e.touchedPaths.length} touched path(s)`}]:[{level:"bad",text:`${e.changes.length} new/worsened supported smell(s) block this candidate`},...e.changes.slice(0,5).flatMap(t=>[{level:"plain",text:`[${t.smellId}] ${t.evidence.path}:${t.evidence.line??1} ${t.evidence.symbol??""}`},{level:"dim",text:`fix: ${t.repairHint}`}])]:[{level:"bad",text:`Unavailable \u2014 ${e.error||"base/candidate evidence incomplete"}`}]:[]}export{P as DESIGN_DELTA_SCHEMA_VERSION,_ as DESIGN_DELTA_SUPPORTED_SMELLS,E as analyzeDesignFindings,ue as createDesignDeltaCheck,pe as designDeltaDoctorLines,te as evaluateGitDesignDelta,de as evaluateWriteDesignDelta,ne as formatDesignDeltaBlock};
@@ -494,7 +494,7 @@ export function summarizeDesignFitness(smells, ctx = {}) {
494
494
  export const GREEN_PLAN_POINTER_MAX_IDS = 4;
495
495
 
496
496
  /** When a smell has no evidence path, say so — do not leave the reader hunting. */
497
- export const SMELL_UNATTRIBUTED =
497
+ const SMELL_UNATTRIBUTED =
498
498
  'no file — leftover design, not a specific line';
499
499
 
500
500
  /**
@@ -502,7 +502,7 @@ export const SMELL_UNATTRIBUTED =
502
502
  * The pointer used to print only the id, so "1 design smell (domain-logic-in-ui)"
503
503
  * could not answer "did my change cause this?"
504
504
  */
505
- export function formatSmellPointerName(id, smells) {
505
+ function formatSmellPointerName(id, smells) {
506
506
  const match = (smells || []).find((smell) => smell?.id === id);
507
507
  const evidence = Array.isArray(match?.evidence)
508
508
  ? match.evidence.filter((entry) => typeof entry === 'string' && entry.trim())
@@ -35,7 +35,10 @@ export const DIAGNOSTIC_CATALOG = Object.freeze([
35
35
  entry('LAYER_IMPORT_VIOLATION', 'layer', 'This import is not allowed', 'This file imported a folder it may not reach. The write doesn’t land. The same check fails the pull request.', 'Branch by import kind: constants/types/pure → adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence → inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement.'),
36
36
  entry('LAYER_INTENT_REFERENCE_VIOLATION', 'layer', 'Intent referenced across a blocked layer edge', 'A string intent (or intent-like reference) names a layer that the file’s layer may not reach under the contract rules — the same plane as import edges, for event/intent coupling.', 'Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference — then preflight again.'),
37
37
  entry('LAYER_REFERENCE_VIOLATION', 'layer', 'Layer reference blocked (snippet / AI gate)', 'Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.', 'Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate.'),
38
+ entry('SHARED_IMPORTS_SLICE', 'layer', 'A shared root imports a slice', 'A declared shared root imports a slice directly. That hop is allowed while sharedImportsSlice is unset or "deny-cross-parent", so this is advisory: the universe wall is direct-only.', 'Move the code the shared root needs into the shared root, or invert the dependency. Set sharedImportsSlice: "deny" to make these edges errors. With "deny-cross-parent", a slice that reaches another universe through a shared root is reported as LAYER_IMPORT_VIOLATION with reasonId CROSS_PARENT_VIA_SHARED. This warning does not fail the check.', { oftenAdvisory: true }),
38
39
  entry('CIRCULAR_DEPENDENCY', 'layer', 'Dependency cycle', 'Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.', 'Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one — then preflight again.'),
40
+ entry('CROSS_WALL_DUPLICATE', 'layer', 'Code copied across a wall', 'Near-identical code sits on two sides of a slice wall (or in two layers that may not import each other). The wall would deny the import, so the code was copied instead. Status details (`--doctor --all`) and the report list it from token fingerprints taken at status time; they never enter the check, so the verdict does not change. Same-slice copies are counted, never listed.', 'Move one copy to a shared home the wall allows — a declared shared root, the universe common folder, or a layer both sides may import — then import it from both sides. One move at a time, through the write gate (/ark-place names the destination). Advisory only — it never fails a run.', { oftenAdvisory: true }),
41
+ entry('CROSS_LAYER_DUPLICATE', 'layer', 'Code copied in two layers', 'Near-identical code sits in two layers, and at least one of them may import the other. Status details (`--doctor --all`) and the report list it from token fingerprints taken at status time; the verdict does not change.', 'Keep one copy in the lower layer both sides may import, and import it from the other. One move at a time, through the write gate. Advisory only — it never fails a run.', { oftenAdvisory: true }),
39
42
  // ── capability / ambient ─────────────────────────────────────────────────
40
43
  entry('FORBIDDEN_GLOBAL', 'capability', 'Forbidden ambient global or dual import', 'The file’s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.', 'Inject the capability through a small port (Clock, HttpPort, Config, …), bind the implementation outside the walled layer, then preflight again.'),
41
44
  entry('CAPABILITY_VIOLATION', 'capability', 'Denied effect capability', 'The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.', 'Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe — port shape is a design decision.'),
@@ -56,18 +59,22 @@ export const DIAGNOSTIC_CATALOG = Object.freeze([
56
59
  entry('ARKRULE_INVARIANT', 'arkrules', 'ArkRule invariant failed', 'Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).', 'Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement.'),
57
60
  entry('ARKRULE_SCOPE_EMPTY', 'arkrules', 'ArkRule appliesTo matched zero files', 'An ArkRule’s appliesTo globs matched no governed files — the rule cannot observe what it claims to protect.', 'Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.', { oftenAdvisory: true }),
58
61
  entry('ARKRULE_HINT_BUDGET_EXHAUSTED', 'arkrules', 'Structural-hint budget exhausted', 'orchestration-only, thin-adapter, and writes-via-aggregate only evaluate files the hint loader preloaded. When eligible governed files exceed that budget (coverage.maxFiles, default 400 — there is no arkrules.hintBudget), those sensors never saw the rest of their scope. Enforced + unreviewed is not green. The finding names exact hinted/governed counts and per-sensor reviewed N/M of scope.', 'Raise coverage.maxFiles in ark.config.json (this cap also bounds structural-hint preload; --doctor names the coupling) so hinted/governed counts match, then re-run with --strict-config. An enforced hint sensor that cannot see its scope fails strict.'),
62
+ entry('ARKRULE_FILE_UNREFERENCED', 'arkrules', 'ArkRules file not referenced', 'A JSON file under arkrules/, or a slice file named arkrules.<Layer>.json beside governed code, is not in the effective catalog, so none of its rules are enforced. Drift looks like governance until someone notices.', 'Reference a central file from arkRules, set childSlices.arkRulesFile so a slice file is discovered, or delete it. Advisory only: it never fails the check.', { oftenAdvisory: true }),
63
+ entry('ARKRULE_DUPLICATE_ID', 'arkrules', 'ArkRule id declared more than once', 'Two ArkRules files in one layer declare the same effective id. Central ids stay bare. A slice file is namespaced as <childId>#<localId>, so the same local id in two slices is not a duplicate.', 'Rename one id, or split the files onto different slices. Config load fails closed. The catalog is not enforced until the id is unique.'),
64
+ entry('ARKRULE_SCOPE_ESCAPES_SLICE', 'arkrules', 'Slice ArkRule appliesTo leaves its slice', 'A file discovered from childSlices.arkRulesFile set appliesTo to a glob that can match outside that child slice. The default, when appliesTo is omitted, is the slice directory.', 'Narrow appliesTo to the slice directory, or omit it. Config load fails closed. The escaping rule is not enforced.'),
59
65
  entry('INVARIANT_CATALOG_EMPTY', 'arkrules', 'Domain invariant catalog is empty', 'ArkRules is on and a Domain-role layer has code, but invariants[] has no phrases the code must preserve. Empty looks like “done” until someone fills the catalog.', 'Add 1–2 short phrases to invariants[] in arkrules/<Domain>.json (or the mapped file). Starters show the shape. Advisory unless a domain structure rule is already enforced — then --strict-merge can refuse. Do not freeze this finding.', { oftenAdvisory: true }),
60
66
  entry('INVARIANT_UNCOVERED', 'arkrules', 'Invariant without coverage evidence', 'An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).', 'Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial — never fake green. When the message reports an exhausted file budget, raise coverage.maxFiles (or narrow coverage.testGlobs) in ark.config.json.'),
61
67
  entry('INVARIANT_COVERAGE_OUTSIDE_ROOTS', 'arkrules', 'Covering test outside the declared coverage roots', 'The only test naming this invariant sits outside coverage.coverageRoots — the places the project declares its runner executes. ArkGate matches declared text and never executes tests, so it cannot tell whether that file is ever run: coverage there is a test that exists, not a test that runs.', 'Move the test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json. Advisory: it never fails strict, but promotion to enforced refuses on it.', { oftenAdvisory: true }),
68
+ entry('INVARIANT_PROBE_SURVIVED', 'arkrules', 'Covering tests do not pin the invariant', 'The committed invariant probe (.ark/invariant-probe.json, written by arkgate-check --probe-invariants --write) shows, for files that have not changed since, that the covering tests still pass with the invariant\'s symbol broken on purpose (survived) or never call it (not reached). The test names the rule but does not pin it. A status and inventory line only: it never enters the check, so the verdict does not change.', 'Add a test case that fails when the rule is broken (the line names the change that went unnoticed), then re-run arkgate-check --probe-invariants --write and commit the file. Promotion to enforced refuses while the fresh artifact says survived or not reached; a stale, killed, inconclusive or missing result changes nothing.', { oftenAdvisory: true }),
62
69
  entry('INVARIANT_TESTS_PATH_MISSING', 'arkrules', 'Domain-invariant tests path missing under adopted', 'The project is adopted (required CI or explicit advisory) and has domain invariants that want test evidence, but ark.config.json does not name where those tests live. Green coverage without a real tests path is an empty checkbox.', 'Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present. Not freezable.'),
63
70
  entry('INVARIANT_COVERAGE_ROOTS_MISSING', 'arkrules', 'Coverage roots missing while an invariant is enforced', 'A catalogued domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots — the folders where the project says its test runner actually goes. Without that declaration, INVARIANT_COVERAGE_OUTSIDE_ROOTS cannot fire and coverage can certify a test no runner runs.', 'Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. testGlobs alone is not enough. Fail-closed until that path is present. Not freezable.'),
64
71
  // ── ArkRun (opt-in extra; RN05 dual-depth nextAction) ────────────────────
65
- entry('ARKRUN_MISSING_ROOT', 'arkrun', 'No kernel factory in composition roots', 'The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.', 'Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe — factory placement is a design decision.'),
66
- entry('ARKRUN_KERNEL_IN_DOMAIN', 'arkrun', 'Domain-role layer imports the kernel', 'A Domain-role layer imports arkgate/runtime, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.', 'Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.'),
72
+ entry('ARKRUN_MISSING_ROOT', 'arkrun', 'No kernel factory in composition roots', 'The ArkRun extra is on but no kernel factory (createArkKernel / createStrictArkKernel / createLenientArkKernel, their *FromConfig variants, or ArkModule.forRoot / forRootAsync imported from arkgate/nestjs) was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.', 'Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe — factory placement is a design decision.'),
73
+ entry('ARKRUN_KERNEL_IN_DOMAIN', 'arkrun', 'Domain-role layer imports the kernel', 'A Domain-role layer imports arkgate/runtime, arkgate/nestjs, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.', 'Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.'),
67
74
  entry('ARKRUN_DIRECT_NEW', 'arkrun', 'Managed type constructed with new', 'A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.', 'Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe — rewiring construction is a design decision.'),
68
- entry('ARKRUN_UNDECLARED_EMIT', 'arkrun', 'Emit name not in raises/sends', 'A publisher / publish / raise / send call-site literal is not listed in the file’s raises or sends declaration.', 'Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.'),
69
- entry('ARKRUN_UNDECLARED_HANDLE', 'arkrun', 'Handle name not in reactsTo', 'A subscribe / registerHandler call-site literal is not listed in the file’s reactsTo declaration.', 'Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.'),
70
- entry('ARKRUN_UNDECLARED_DEPEND', 'arkrun', 'Depend name not in uses', 'A resolve / resolveSingleton call-site literal is not listed in the file’s uses declaration.', 'Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.'),
75
+ entry('ARKRUN_UNDECLARED_EMIT', 'arkrun', 'Emit name not in raises/sends', 'A publisher / publish / raise / send call on a receiver traced to the kernel names an intent (string literal or same-file define/defineIntent binding) that is not listed in the file’s raises or sends declaration.', 'Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.'),
76
+ entry('ARKRUN_UNDECLARED_HANDLE', 'arkrun', 'Handle name not in reactsTo', 'A subscribe / registerHandler call on a receiver traced to the kernel names an intent (string literal or same-file define/defineIntent binding) that is not listed in the file’s reactsTo declaration.', 'Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.'),
77
+ entry('ARKRUN_UNDECLARED_DEPEND', 'arkrun', 'Depend name not in uses', 'A resolve / resolveSingleton call on a receiver traced to the kernel names a component that is not listed in the file’s uses declaration.', 'Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.'),
71
78
  entry('ARKRUN_TRANSPORT_BYPASS', 'arkrun', 'Homemade broker or emitter import', 'A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, …) instead of the ArkRun kernel transport.', 'Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe — homemade buses stay judgment.'),
72
79
  entry('ARKORDER_MISSING_PLANE', 'arkorder', 'No createOrderPlane in plane roots', 'The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.', 'Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe — factory placement is a design decision.'),
73
80
  entry('ARKORDER_KERNEL_IN_DOMAIN', 'arkorder', 'Domain-role layer imports the order plane', 'A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.', 'Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.'),
@@ -79,6 +86,7 @@ export const DIAGNOSTIC_CATALOG = Object.freeze([
79
86
  entry('ARKORDER_XI_TTL', 'arkorder', 'Slow key carries a freshness field', 'ξ named ttl/freshUntil/maxAge. Freshness belongs on σ. A slow parameter that expires per transaction is not slow.', 'Move freshness onto σ (freshUntil) and keep ξ stable, then preflight again. Never mechanical-safe.'),
80
87
  entry('ARKORDER_STALE_SIGMA', 'arkorder', 'σ is stale', 'ingest ran after σ.freshUntil (or sigmaMaxAgeMs). ξ does not TTL.', 'Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe.'),
81
88
  entry('ARKORDER_UNVALVED_RELEASE', 'arkorder', 'Second freeze without the valve', 'release() already froze the big choice. A later release() with a different value does not land. First freeze is release(); later change is proposeRelease then apply.', 'Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.'),
89
+ entry('ARKORDER_STALE_PROPOSAL', 'arkorder', 'Proposal is not bound to the current Release', 'apply() got a ProposeResult computed against another Release (another apply landed first), one missing its base binding, or one whose reviewed blast radius is not the transition that would commit. The binding is data, not a capability: a proposal that states the current base and the exact transition applies whoever built it.', 'Run proposeRelease again against the current Release, review the new blast radius, then apply that proposal. Never mechanical-safe.'),
82
90
  // ── atomic preflight / change set ────────────────────────────────────────
83
91
  entry('INVALID_CHANGE_PATH', 'preflight', 'Unsafe change path', 'A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).', 'Use canonical project-relative paths only in the atomic change set, then preflight again.'),
84
92
  entry('DUPLICATE_CHANGE_PATH', 'preflight', 'Duplicate path in change set', 'The atomic change set lists more than one operation for the same path.', 'Collapse to one create/update/delete per path, then preflight again.'),
@@ -90,10 +98,11 @@ export const DIAGNOSTIC_CATALOG = Object.freeze([
90
98
  entry('CANDIDATE_CONTENT_HASH_MISMATCH', 'preflight', 'Candidate content hash mismatch', 'The candidate file content hash does not match the hash expected for the declared change.', 'Rebuild candidate facts from the exact proposed content, then preflight again.'),
91
99
  entry('UNDECLARED_CANDIDATE_CHANGE', 'preflight', 'Undeclared candidate change', 'Candidate facts differ from base for a path that was not listed in the explicit change set.', 'Declare every path that changes in the atomic change set, then preflight again.'),
92
100
  entry('ATOMIC_PREFLIGHT_UNAVAILABLE', 'preflight', 'Atomic preflight unavailable', 'The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).', 'Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green.'),
101
+ entry('WRITE_GATE_UNAVAILABLE', 'preflight', 'Write gate could not run', 'The write gate could not load its own inputs (ark.config.json missing, unreadable, or invalid; a referenced ArkRules file missing or invalid; or the built library missing), so it cannot judge this governed source write (existing files included), or a write would leave ark.config.json or a referenced ArkRules file unloadable. No checker, no write: the hook blocks instead of letting the write through unchecked.', 'Fix the reported input (repair ark.config.json or the ArkRules file, or run `npm run build` / reinstall arkgate from npm), then retry the same write. Do not remove the hook to get past it.'),
93
102
  entry('DESIGN_SMELL_REGRESSION', 'preflight', 'Design smell regression on base-relative ratchet', 'Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.', 'Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref.'),
94
103
  // ── analysis completeness / host ─────────────────────────────────────────
95
104
  entry('ANALYSIS_PARSE_INCOMPLETE', 'analysis', 'Parse incomplete', 'Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.', 'Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass.'),
96
- entry('LEXICAL_EVIDENCE_INCOMPLETE', 'analysis', 'Lexical evidence incomplete', 'This check only saw one file, so it cannot fully prove how the import resolves. The result is provisional — `ark-check` on the project is the authority.', 'Run `npx arkgate-check --root . --config ark.config.json` to confirm. Do not call ark_prepare_change from a hook deny.'),
105
+ entry('LEXICAL_EVIDENCE_INCOMPLETE', 'analysis', 'Lexical evidence incomplete', 'This check only saw one file, so it cannot fully prove how the import resolves. The result is provisional — `ark-check` on the project is the authority.', 'For a complete verdict, run `npx arkgate-check --root . --config ark.config.json` (or ark_prepare_change over MCP with the full candidate batch). Read lexicalValid for the one-file result.'),
97
106
  entry('ANALYSIS_COVERS_NO_FILES', 'analysis', 'Analysis covered no files', 'No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.', 'Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files — then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it.'),
98
107
  entry('ANALYSIS_HOST_UNAVAILABLE', 'analysis', 'Analysis host unavailable', 'No usable TypeScript / analysis host was available for this invocation.', 'Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed.'),
99
108
  entry('ADAPTER_NOT_ALLOWED_FOR_PORT', 'adapter', 'Adapter not allowed for port', 'Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.', 'Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision — then re-run.'),
@@ -121,12 +130,16 @@ export const DIAGNOSTIC_CATALOG = Object.freeze([
121
130
  entry('CONFIG_UNCLASSIFIED_FILES', 'config', 'Unclassified included files', 'Included source files match no layer pattern; import rules will not enforce on them.', 'Extend layer patterns or narrow include so every governed file is classified.', { oftenAdvisory: true }),
122
131
  entry('CONFIG_LAYER_MISSING_OWNER', 'config', 'Layer missing owner', 'requireLayerOwners is on and this layer has no owners. Writes to that house fail closed, like a folder with no name on the door.', 'Add a GitHub handle or email to that layer’s owners in ark.config.json (/ark-adopt), then re-run. Reserved/allowEmpty houses may stay unnamed. Turn the flag off only if you no longer want owners required.'),
123
132
  entry('CONFIG_SLICE_IDENTITY_COLLISION', 'config', 'Starred slice prefixes share one id', 'sliceIdentity is stars and two different sliceFolders prefixes bind as the same slice id. Parallel trees of one feature do that on purpose; unrelated trees that share the last folder name merge by accident.', 'Keep stars when those prefixes are one feature. Otherwise use path, or rename the last literal so the prefixes do not bind as the same id. Doctor names both paths.', { oftenAdvisory: true }),
124
- entry('CONFIG_CHILD_SLICES_VERSION', 'config', 'childSlices needs a newer arkgate', 'The rule schema sets additionalProperties to false. arkgate 4.8.22 and older reject a config that contains childSlices instead of ignoring the key.', 'Pin arkgate newer than 4.8.22 before shipping a config that sets childSlices. This warning does not fail the check.', { oftenAdvisory: true }),
133
+ entry('CONFIG_CHILD_SLICES_VERSION', 'config', 'Config needs a newer arkgate than a pinned copy', 'ark.config.json uses a slice key (childSlices, sharedImportsSlice "deny-cross-parent" or its object form, sliceIdentity, sharedImportsSlice, childSlices.message, siblings.ratchet) that an arkgate pinned in this repo rejects at config load. Emitted only with evidence of that pin: an exact package.json dependency, the installed node_modules/arkgate, package-lock.json, a scripts/*hook* or host hook command, or a CI workflow. Silent otherwise.', 'Bump the named file to the version the finding gives (or newer), then run Ark again. This warning does not fail the check.', { oftenAdvisory: true }),
125
134
  entry('CONFIG_CHILD_SLICE_EXTENDS', 'config', 'Child slice id does not extend its universe', 'A path resolved a child id that is not the universe id plus a further segment. The child wall does not treat that id as a child, so the edge is universe common until the folders line up.', 'Point childSlices.sliceFolders at children under the same universe id the outer sliceFolders already names. Doctor names the path.', { oftenAdvisory: true }),
126
135
  entry('CONFIG_CHILD_SLICE_CROSS_UNIVERSE', 'config', 'Child slice allowance cannot cross the universe wall', 'childSlices.allowedCrossSlice names a pattern that can match two universes. That list clears only a sibling crossing inside one universe. The universe wall still denies the edge.', 'Narrow the pattern so both sides share one universe prefix (features/projects/* to features/projects/d2d-item), or remove the entry. This warning does not fail the check.', { oftenAdvisory: true }),
136
+ entry('CONFIG_CHILD_SLICES_INERT', 'config', 'childSlices on a rule that cannot run it', 'A rule sets childSlices without peerIsolation: true and allowed: false. The child wall runs only inside a universe wall, so on this rule childSlices enforces nothing. Config load still accepts it (arkgate 4.8.23 did too).', 'Add "peerIsolation": true and "allowed": false to the same rule so the child wall runs, or remove childSlices. This warning does not fail the check.', { oftenAdvisory: true }),
137
+ entry('CONFIG_SLICE_LEGACY_STARS_ID', 'config', 'Slice id written in the 4.8.23 stars form', 'Under sliceIdentity "stars", a sliceAliases target or an allowedCrossSlice entry names the 4.8.23 stars id, which dropped a star binding before the last literal (modules/*/api/* bound api/v1). The id now keeps that binding (orders/api/v1). For one release the entry keeps its 4.8.23 meaning, so verdicts do not change.', 'Rewrite the entry with the new id the warning names (for example orders/api/v1/x instead of api/v1/x). A sliceAliases target that maps to more than one universe shape is rejected at config load. This warning does not fail the check.', { oftenAdvisory: true }),
127
138
  // ── literal path drift ───────────────────────────────────────────────────
128
139
  entry('LITERAL_PATH_DRIFT', 'drift', 'Literal path moved by a rename', 'A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms — the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose — and a hand sweep reliably covers one of them.', 'Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand.'),
129
140
  entry('LITERAL_PATH_UNRESOLVED', 'drift', 'Literal path does not resolve', 'A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.', 'Read the candidate and decide: fix the path, or leave it. Advisory only — it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.', { oftenAdvisory: true }),
141
+ entry('ORPHAN_MODULE', 'drift', 'File nothing imports', 'No governed file, test or entry point imports this module. It is the leftover an agent leaves when a rewrite lands next to the old file. Status reads it from the import facts the check already resolved, so it never changes the verdict. When a dynamic import, an unresolved import or an unmapped entry could reach the file, the item says so (maybe-dynamic, maybe-unresolved) and the list is partial.', 'Delete the file through the write gate, one file at a time. If a framework, a script or a runtime loader uses it, add a glob with a reason to .ark/entry-points.json (optional reviewBy) instead. Advisory only — it never fails a run.', { oftenAdvisory: true }),
142
+ entry('UNUSED_EXPORT', 'drift', 'Export nothing imports by name', 'An export no governed file or test imports by name. Listed only in status details (`--doctor --all`) and the report. Default, namespace, star, dynamic and require use count as using every export, so those files are skipped.', 'Drop the export keyword (or the code) if nothing outside the file needs it, or keep it when it is public API an entry point exposes. Advisory only — it never fails a run.', { oftenAdvisory: true }),
130
143
  // ── meta ─────────────────────────────────────────────────────────────────
131
144
  entry('ARK_UNKNOWN', 'meta', 'Unknown diagnostic', 'A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.', 'Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.'),
132
145
  ]);
@@ -199,14 +212,15 @@ export const SLICE_REASON_HINTS = Object.freeze([
199
212
  ruleId: 'LAYER_IMPORT_VIOLATION',
200
213
  title: 'Cross-sibling slice',
201
214
  why: 'This import crosses two feature slices inside one universe.',
202
- fix: 'Import universe-common code, or move the shared piece into the feature that owns it. An enforce list makes those importer subtrees errors. Other sibling crossings stay warnings, and a new one past the baseline still fails.',
215
+ fix: 'Import universe-common code, or move the shared piece into the feature that owns it.',
216
+ advisoryNote: 'This crossing is a warning (siblings advisory). With a baseline in use, a new one fails only when the baseline already records an advisory crossing of this rule and the count grows, or when siblings.ratchet is true; ratchet false measures only.',
203
217
  }),
204
218
  Object.freeze({
205
219
  reasonId: 'CROSS_PARENT_VIA_SHARED',
206
220
  ruleId: 'LAYER_IMPORT_VIOLATION',
207
221
  title: 'Cross-universe through a shared root',
208
222
  why: 'A slice reaches another universe only through a shared root. ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.',
209
- fix: 'Stop the shared root from importing the other universe, or move that import into the universe that owns it. A shared hop that stays inside one universe is allowed.',
223
+ fix: 'Stop the shared root from importing the other universe, or move that import into the universe that owns it. A shared hop that stays inside one universe is allowed. If the shared hop is a composition root (bootstrap, DI registrations), list it in sharedImportsSlice.stopAt; a path through a stop is not a crossing.',
210
224
  }),
211
225
  ]);
212
226
  const SLICE_REASON_BY_ID = new Map(SLICE_REASON_HINTS.map((hint) => [hint.reasonId, hint]));