arkgate 4.8.14 → 4.8.16

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 (103) hide show
  1. package/CHANGELOG.md +172 -0
  2. package/README.md +17 -7
  3. package/bin/ark-check-runtime.mjs +17 -49
  4. package/bin/ark-mcp-runtime.mjs +111 -2
  5. package/bin/ark-shared.mjs +142 -11
  6. package/bin/ark.mjs +24 -33
  7. package/bin/lib/adr-presence.mjs +97 -0
  8. package/bin/lib/agent-skills-package.mjs +179 -1
  9. package/bin/lib/analysis-completeness.mjs +38 -2
  10. package/bin/lib/analysis-engine.mjs +6 -6
  11. package/bin/lib/architecture-scan.mjs +43 -4
  12. package/bin/lib/ark-run-doctor.mjs +6 -0
  13. package/bin/lib/ark-run-report.mjs +6 -2
  14. package/bin/lib/arkrules-sensors.mjs +81 -0
  15. package/bin/lib/baseline-key.mjs +6 -1
  16. package/bin/lib/check-args.mjs +52 -2
  17. package/bin/lib/config-contract.mjs +65 -2
  18. package/bin/lib/diagnostic-catalog.mjs +5 -1
  19. package/bin/lib/doctor-advisories.mjs +120 -10
  20. package/bin/lib/doctor-green-cite.mjs +139 -0
  21. package/bin/lib/doctor-human.mjs +115 -67
  22. package/bin/lib/doctor-next-actions.mjs +23 -0
  23. package/bin/lib/doctor-plan.mjs +35 -2
  24. package/bin/lib/enforcement-honesty.mjs +47 -2
  25. package/bin/lib/field-install.mjs +47 -7
  26. package/bin/lib/first-run-help.mjs +9 -1
  27. package/bin/lib/host-support-matrix.mjs +9 -1
  28. package/bin/lib/html-report-depth.mjs +2 -0
  29. package/bin/lib/html-report.mjs +13 -2
  30. package/bin/lib/import-resolve.mjs +74 -13
  31. package/bin/lib/improvement-compass-doctor.mjs +8 -1
  32. package/bin/lib/improvement-compass-map.mjs +5 -1
  33. package/bin/lib/invariant-coverage.mjs +121 -0
  34. package/bin/lib/invariant-tests-path.mjs +212 -0
  35. package/bin/lib/layer-description.mjs +90 -8
  36. package/bin/lib/mcp-hook-payload.mjs +56 -0
  37. package/bin/lib/no-domain-frontend.mjs +91 -0
  38. package/bin/lib/package-manager.mjs +8 -0
  39. package/bin/lib/presets.mjs +3 -4
  40. package/bin/lib/product-copy.mjs +15 -0
  41. package/bin/lib/projected-governed-coverage.mjs +114 -0
  42. package/bin/lib/prototype-shortcuts.mjs +224 -0
  43. package/bin/lib/recommend-cli.mjs +54 -0
  44. package/bin/lib/remediation.mjs +15 -0
  45. package/bin/lib/resolved-candidate-facts.mjs +83 -66
  46. package/bin/lib/rules-under-contract.mjs +117 -2
  47. package/bin/lib/snippet-analysis.mjs +14 -8
  48. package/bin/lib/start-preview.mjs +24 -2
  49. package/bin/lib/states-transitions-presence.mjs +212 -0
  50. package/bin/lib/status-command.mjs +2 -0
  51. package/bin/lib/status-transition-catalog.mjs +410 -0
  52. package/bin/lib/team-parliament-io.mjs +10 -0
  53. package/bin/lib/violations.mjs +13 -1
  54. package/bin/lib/write-path-capabilities.mjs +20 -5
  55. package/bin/lib/write-path-detect.mjs +27 -2
  56. package/dist/{configTypes-j7so8B4O.d.ts → configTypes-VD0qcubY.d.ts} +21 -1
  57. package/dist/{diagnosticCatalog-DVx_2RmF.d.ts → diagnosticCatalog-KWvGLI1U.d.ts} +24 -3
  58. package/dist/eslint/index.cjs +4 -4
  59. package/dist/eslint/index.d.ts +1 -1
  60. package/dist/eslint/index.js +4 -4
  61. package/dist/index.cjs +34 -34
  62. package/dist/index.d.ts +71 -10
  63. package/dist/index.js +34 -34
  64. package/dist/nestjs/index.cjs +5 -5
  65. package/dist/nestjs/index.d.ts +3 -3
  66. package/dist/nestjs/index.js +5 -5
  67. package/dist/runtime/index.cjs +15 -15
  68. package/dist/runtime/index.d.ts +6 -6
  69. package/dist/runtime/index.js +15 -15
  70. package/dist/{types-tGhZUiGX.d.ts → types-BSzRy2X1.d.ts} +1 -1
  71. package/dist/{types-Djbs3KjE.d.ts → types-D5GT5ZT8.d.ts} +3 -1
  72. package/docs/README.md +1 -1
  73. package/docs/agent-guide.md +8 -4
  74. package/docs/ai-gates.md +10 -3
  75. package/docs/brownfield-adoption.md +4 -1
  76. package/docs/configuration.md +66 -10
  77. package/docs/develop.md +4 -1
  78. package/docs/diagnostics.md +48 -4
  79. package/docs/enthusiast/how-to-agent-gates.md +5 -0
  80. package/docs/enthusiast/how-to-pick-shape.md +1 -1
  81. package/docs/package-surface.md +7 -5
  82. package/docs/use.md +10 -3
  83. package/package.json +1 -1
  84. package/schemas/ark.config.schema.json +24 -3
  85. package/server.json +2 -2
  86. package/templates/agent-skills/README.md +1 -1
  87. package/templates/agent-skills/ark-adopt/SKILL.md +97 -1
  88. package/templates/agent-skills/ark-autopilot/SKILL.md +12 -3
  89. package/templates/agent-skills/ark-coverage/SKILL.md +2 -2
  90. package/templates/agent-skills/ark-explain/SKILL.md +6 -3
  91. package/templates/agent-skills/ark-explore/SKILL.md +33 -1
  92. package/templates/agent-skills/ark-place/SKILL.md +42 -3
  93. package/templates/agent-skills/ark-runtime/SKILL.md +4 -2
  94. package/templates/agent-skills/ark-upgrade/SKILL.md +1 -1
  95. package/templates/arkrules/DomainModel.json +14 -1
  96. package/templates/skills/ark-adopt.md +97 -1
  97. package/templates/skills/ark-autopilot.md +12 -3
  98. package/templates/skills/ark-coverage.md +2 -2
  99. package/templates/skills/ark-explain.md +6 -3
  100. package/templates/skills/ark-explore.md +33 -1
  101. package/templates/skills/ark-place.md +42 -3
  102. package/templates/skills/ark-runtime.md +4 -2
  103. package/templates/skills/ark-upgrade.md +1 -1
@@ -16,7 +16,14 @@ import {
16
16
  invariantIdsFromCatalog,
17
17
  loadInvariantCoverageInputs,
18
18
  } from './invariant-coverage-io.mjs';
19
+ import { catalogHasEnforcedInvariant } from './invariant-coverage.mjs';
20
+ import {
21
+ declaredCoverageRootsPresent,
22
+ declaredInvariantTestsPathPresent,
23
+ scanDemandsInvariantTestsPath,
24
+ } from './invariant-tests-path.mjs';
19
25
  import { loadArkRuleFileHints } from './arkrule-file-hints.mjs';
26
+ import { collectGovernedFiles } from './scan-files.mjs';
20
27
 
21
28
  const HINT_CACHE_CAP = 16;
22
29
  /** Process-local hint map keyed by scoped path + content hash. Not a second engine. */
@@ -40,15 +47,34 @@ function normalizeScanRelPath(root, filePath) {
40
47
  return relative;
41
48
  }
42
49
 
43
- /** Empty / missing `files` stays unbounded (full governed set). */
44
- function fileLocalScope(root, files) {
50
+ /**
51
+ * Empty / missing `files` stays unbounded (full governed set).
52
+ * A complete governed list is also unbounded — doctor and check always pass
53
+ * that list, and treating it as `--changed` paid import-closure + a second
54
+ * `resolveModuleName` pass on every full-tree run (#212).
55
+ */
56
+ function fileLocalScope(root, files, config, { changed = false } = {}) {
45
57
  if (!Array.isArray(files) || files.length === 0) return null;
46
58
  const scoped = new Set();
47
59
  for (const file of files) {
48
60
  const rel = normalizeScanRelPath(root, file);
49
61
  if (rel) scoped.add(rel);
50
62
  }
51
- return scoped.size > 0 ? scoped : null;
63
+ if (scoped.size === 0) return null;
64
+ // `--changed` is already a bounded envelope — do not re-walk the include tree (#205).
65
+ if (!changed && config && coversGovernedSet(root, scoped, config)) return null;
66
+ return scoped;
67
+ }
68
+
69
+ function coversGovernedSet(root, scoped, config) {
70
+ const governed = collectGovernedFiles(root, config);
71
+ if (governed.length === 0) return false;
72
+ if (scoped.size < governed.length) return false;
73
+ for (const absolute of governed) {
74
+ const rel = normalizeScanRelPath(root, absolute);
75
+ if (rel && !scoped.has(rel)) return false;
76
+ }
77
+ return true;
52
78
  }
53
79
 
54
80
  function filterHintPreload(fileContents, scoped) {
@@ -126,7 +152,9 @@ export function resolveArchitectureSnapshot({
126
152
  { ...config, rules: rules ?? config.rules },
127
153
  manifest
128
154
  );
129
- const scoped = fileLocalScope(root, files);
155
+ const scoped = fileLocalScope(root, files, effectiveConfig, {
156
+ changed: args?.changed === true,
157
+ });
130
158
  const facts = resolveCandidateFacts({
131
159
  root,
132
160
  config: effectiveConfig,
@@ -176,9 +204,20 @@ export function resolveArchitectureSnapshot({
176
204
  filterHintPreload(coverageInputs?.fileContents, scoped),
177
205
  scoped
178
206
  );
207
+ const adopted = scanDemandsInvariantTestsPath(root, args);
208
+ const pathPresent = adopted
209
+ ? declaredInvariantTestsPathPresent(root, effectiveConfig.coverage)
210
+ : true;
211
+ // Silent when nothing is enforced — do not probe coverageRoots on that path.
212
+ const rootsPresent = catalogHasEnforcedInvariant(arkRulesLoad.arkRules?.invariants)
213
+ ? declaredCoverageRootsPresent(root, effectiveConfig.coverage)
214
+ : true;
179
215
  const analyzed = analyzeTrustedResolvedProject({
180
216
  contract: analysisContract,
181
217
  facts,
218
+ ...(adopted ? { adopted: true } : {}),
219
+ ...(adopted && pathPresent === false ? { invariantTestsPathPresent: false } : {}),
220
+ ...(rootsPresent === false ? { coverageRootsPresent: false } : {}),
182
221
  ...(coverageInputs ? { coverageInputs } : {}),
183
222
  ...(fileHints ? { fileHints } : {}),
184
223
  });
@@ -11,6 +11,10 @@
11
11
  import { composeMergePlanesHonesty, extraMergeTeethAllowed, isArkRunRuleId, } from './extra-merge-teeth.mjs';
12
12
  export const ARK_RUN_DOCTOR_SCHEMA_VERSION = '1.0';
13
13
  const RESIDUAL_RULE_CAP = 12;
14
+ /** Compact / details — only when `arkRun` is on. Absence stays silent. */
15
+ export const ARKRUN_ONE_BREATH = 'Layers stop a bad import. ArkRun is an optional experimental runtime — in-memory, not Postgres. Data is gone on restart.';
16
+ /** Next step when the extra is on and residual remains. */
17
+ export const ARKRUN_FIRST_CONTACT_NEXT = 'Next: /ark-runtime to wire one candidate.';
14
18
  function closedMode(value) {
15
19
  return value === 'enforced' || value === 'advisory' ? value : null;
16
20
  }
@@ -126,6 +130,7 @@ export function formatArkRunDoctorLines(section) {
126
130
  const mode = section.mode ?? 'unknown';
127
131
  const teeth = section.extraMergeTeeth === true ? 'armed' : 'not armed';
128
132
  const lines = [
133
+ ARKRUN_ONE_BREATH,
129
134
  `mode: ${mode} · extra merge teeth ${teeth} · not a score`,
130
135
  ];
131
136
  if (section.residual.count > 0) {
@@ -134,6 +139,7 @@ export function formatArkRunDoctorLines(section) {
134
139
  ? ` (+${section.residual.count - section.residual.ruleIds.length} more)`
135
140
  : '';
136
141
  lines.push(`Residual: ${shown}${more}`);
142
+ lines.push(ARKRUN_FIRST_CONTACT_NEXT);
137
143
  }
138
144
  else {
139
145
  lines.push('Residual: none on this scan (not a score — green extras ≠ finished kernel wiring).');
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * HTML for the doctor ArkRun advisory (report parity: data-advisory="arkRun").
3
3
  */
4
+ import { ARKRUN_FIRST_CONTACT_NEXT, ARKRUN_ONE_BREATH } from './ark-run-doctor.mjs';
5
+
4
6
  export function formatArkRunHtml(section, esc) {
5
7
  if (!section || typeof section !== 'object' || section.notAScore !== true) return '';
6
8
  const escape = typeof esc === 'function' ? esc : (v) => String(v);
@@ -17,6 +19,7 @@ export function formatArkRunHtml(section, esc) {
17
19
  }
18
20
  const residual = section.residual && typeof section.residual === 'object' ? section.residual : { count: 0, ruleIds: [] };
19
21
  const ids = Array.isArray(residual.ruleIds) ? residual.ruleIds : [];
22
+ const next = residual.count > 0 ? ` ${ARKRUN_FIRST_CONTACT_NEXT}` : '';
20
23
  const residualHtml =
21
24
  residual.count > 0
22
25
  ? `<p><span class="tag warn">residual</span> ${ids
@@ -40,8 +43,9 @@ export function formatArkRunHtml(section, esc) {
40
43
  <section class="section card" data-advisory="arkRun">
41
44
  <h2>ArkRun <span class="muted">(not a score)</span></h2>
42
45
  <p class="dim" style="margin:.15rem 0 .55rem;font-size:.88rem">
43
- <b>[ArkRun]</b> Kernel usage + declarations — separate from <b>[Layer]</b> imports and <b>[ArkRules]</b> shape.
44
- Advisory never flips <code>valid</code>. Enforced extra teeth only when the layer plane is classified.
46
+ <b>[ArkRun]</b> ${ARKRUN_ONE_BREATH}
47
+ Kernel usage + declarations separate from <b>[Layer]</b> imports and <b>[ArkRules]</b> shape.
48
+ Advisory never flips <code>valid</code>. Enforced extra teeth only when the layer plane is classified.${next}
45
49
  </p>
46
50
  ${merge}
47
51
  <div class="kpis" style="margin-bottom:.55rem">
@@ -378,6 +378,87 @@ export function collectEmptyAppliesToFindings(arkRules, files) {
378
378
  a.arkruleId.localeCompare(b.arkruleId) ||
379
379
  a.message.localeCompare(b.message));
380
380
  }
381
+ /** Intent prefixes are short tokens (`Domain.`, `Application.`). Bound the scan. */
382
+ const INTENT_PREFIX_SCAN_LIMIT = 64;
383
+ /**
384
+ * Strip trailing `.` without a regex. `\.+$` on config strings is CodeQL
385
+ * js/polynomial-redos (backtracking on long runs of `.`). Linear walk is enough.
386
+ */
387
+ function stripTrailingDots(value) {
388
+ let end = value.length;
389
+ while (end > 0 && value.charCodeAt(end - 1) === 46) {
390
+ end -= 1;
391
+ }
392
+ return end === value.length ? value : value.slice(0, end);
393
+ }
394
+ function normalizeIntentPrefix(prefix) {
395
+ const trimmed = prefix.trim();
396
+ const bounded = trimmed.length > INTENT_PREFIX_SCAN_LIMIT
397
+ ? trimmed.slice(0, INTENT_PREFIX_SCAN_LIMIT)
398
+ : trimmed;
399
+ return stripTrailingDots(bounded);
400
+ }
401
+ function layerNameLooksDomain(layer) {
402
+ const lower = layer.toLowerCase();
403
+ return (lower.includes('domain') ||
404
+ lower.includes('entity') ||
405
+ lower.includes('aggregate') ||
406
+ lower.includes('model'));
407
+ }
408
+ function ownsDomainIntent(intentPrefixes) {
409
+ return intentPrefixes.some((prefix) => {
410
+ const normalized = normalizeIntentPrefix(prefix);
411
+ return normalized === 'Domain' || normalized.startsWith('Domain.');
412
+ });
413
+ }
414
+ /** Domain-role house: name or intentPrefixes. Keep aligned with rulesInventory. */
415
+ export function isDomainRoleLayerName(layer, intentPrefixes = []) {
416
+ return layerNameLooksDomain(layer) || ownsDomainIntent(intentPrefixes);
417
+ }
418
+ /**
419
+ * §2 catalog residual — ArkRules is on, Domain has code, invariants[] is empty.
420
+ * Advisory by default. failsStrict only when a domain structure rule is already
421
+ * enforced (the project opted into ArkRules merge teeth). Not freezable.
422
+ */
423
+ export function collectEmptyInvariantCatalogFindings(input) {
424
+ if (input.arkRulesActive !== true)
425
+ return [];
426
+ const domainLayers = (input.layers ?? [])
427
+ .filter((layer) => isDomainRoleLayerName(layer.name, layer.intentPrefixes ?? []))
428
+ .map((layer) => layer.name);
429
+ if (domainLayers.length === 0)
430
+ return [];
431
+ const domainSet = new Set(domainLayers);
432
+ const domainPopulated = (input.files ?? []).some((file) => {
433
+ const layer = typeof file.layer === 'string' ? file.layer : '';
434
+ return layer.length > 0 && domainSet.has(layer);
435
+ });
436
+ if (!domainPopulated)
437
+ return [];
438
+ const domainInvariants = (input.arkRules.invariants ?? []).filter((inv) => domainSet.has(inv.provenance.layer));
439
+ if (domainInvariants.length > 0)
440
+ return [];
441
+ const fillLayer = domainLayers.find((name) => input.arkRules.byLayer?.[name]) ?? domainLayers[0];
442
+ const fillPath = input.arkRules.byLayer?.[fillLayer]?.sourceFile ?? `arkrules/${fillLayer}.json`;
443
+ const optedIntoTeeth = (input.arkRules.structure ?? []).some((rule) => rule.mode === 'enforced' &&
444
+ domainSet.has(rule.provenance.layer) &&
445
+ !isTier2(rule.sensor));
446
+ return [
447
+ {
448
+ ruleId: 'INVARIANT_CATALOG_EMPTY',
449
+ code: 'invariant-catalog-empty',
450
+ message: `ArkRules is on and ${fillLayer} has code, but invariants[] is empty — there are no phrases the code must preserve. Add 1–2 short phrases in ${fillPath}.`,
451
+ file: fillPath,
452
+ line: 1,
453
+ fromLayer: fillLayer,
454
+ arkruleId: 'invariant-catalog',
455
+ arkruleSource: fillPath,
456
+ severity: optedIntoTeeth ? 'error' : 'warning',
457
+ sensor: 'invariant-coverage',
458
+ failsStrict: optedIntoTeeth,
459
+ },
460
+ ];
461
+ }
381
462
  /** IO / ORM import evidence. postgres and drizzle-orm include package subpaths. Keep in lockstep with arkOrderFacts. */
382
463
  const IO_IMPORT_HINT_RE = /\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/;
383
464
  /**
@@ -9,7 +9,12 @@
9
9
  */
10
10
 
11
11
  /** Config diagnostics that are never code debt. Not a schema key. */
12
- export const NON_FREEZABLE_BASELINE_RULE_IDS = ['ARKRULE_SCOPE_EMPTY'];
12
+ export const NON_FREEZABLE_BASELINE_RULE_IDS = [
13
+ 'ARKRULE_SCOPE_EMPTY',
14
+ 'INVARIANT_CATALOG_EMPTY',
15
+ 'INVARIANT_TESTS_PATH_MISSING',
16
+ 'INVARIANT_COVERAGE_ROOTS_MISSING',
17
+ ];
13
18
  /**
14
19
  * STRUCTURE freeze `target`: sensor id, plus `:symbol` when a method/class is known.
15
20
  * V1 empty-target keys (`ARKRULE_STRUCTURE|file|layer||`) stay exact-match only —
@@ -14,7 +14,55 @@ export function resolveDesignDeltaBaseRef(root, explicit, env = process.env) {
14
14
  return discoverLocalBaseRef(root) || undefined;
15
15
  }
16
16
 
17
- export function parseArgs(argv) {
17
+ /** Opt-in local / multi-worktree cheap check. Ignored values: empty, 0, false, no, off. */
18
+ export function envFlagOn(value) {
19
+ return /^(1|true|yes)$/i.test(String(value ?? '').trim());
20
+ }
21
+
22
+ export const LOCAL_STRICT_MERGE_MESSAGE =
23
+ '--local cannot be combined with --strict-merge: CI stays the full fail-closed check. Use --local (or ARK_CHECK_LOCAL=1) only on the local / pre-push path.';
24
+
25
+ export const LOCAL_TREE_MODE_MESSAGE =
26
+ '--local cannot be combined with report modes that need the whole tree (--doctor, --coverage, --plan, --report, --promote). Use --local --base <ref> for the cheap local check.';
27
+
28
+ export function localCheckEnvelope(args, root) {
29
+ if (!args?.local) return {};
30
+ return {
31
+ local: true,
32
+ scope: 'changed',
33
+ analysisRoot: path.resolve(root),
34
+ };
35
+ }
36
+
37
+ /**
38
+ * `--local` / `ARK_CHECK_LOCAL=1` reuse `--changed`. Env is ignored under
39
+ * `--strict-merge` and under full-tree report modes so CI / doctor stay whole-tree.
40
+ */
41
+ export function applyLocalCheckMode(args, env = process.env) {
42
+ const explicit = args.local === true;
43
+ const fromEnv = envFlagOn(env.ARK_CHECK_LOCAL);
44
+ if (!explicit && !fromEnv) return args;
45
+ const treeModes = [
46
+ args.doctor && '--doctor',
47
+ args.coverage && '--coverage',
48
+ args.plan && '--plan',
49
+ args.report && '--report',
50
+ args.promote && '--promote',
51
+ ].filter(Boolean);
52
+ if (args.strictMerge) {
53
+ if (explicit) throw new Error(LOCAL_STRICT_MERGE_MESSAGE);
54
+ return args;
55
+ }
56
+ if (treeModes.length > 0) {
57
+ if (explicit) throw new Error(LOCAL_TREE_MODE_MESSAGE);
58
+ return args;
59
+ }
60
+ args.local = true;
61
+ args.changed = true;
62
+ return args;
63
+ }
64
+
65
+ export function parseArgs(argv, env = process.env) {
18
66
  const args = {
19
67
  root: process.cwd(),
20
68
  config: 'ark.config.json',
@@ -39,6 +87,7 @@ export function parseArgs(argv) {
39
87
  contractSession: false,
40
88
  contractDiff: false,
41
89
  changed: false,
90
+ local: false,
42
91
  against: undefined,
43
92
  base: undefined,
44
93
  persona: undefined,
@@ -180,6 +229,7 @@ export function parseArgs(argv) {
180
229
  else if (arg === '--contract-session') args.contractSession = true;
181
230
  else if (arg === '--contract-diff') args.contractDiff = true;
182
231
  else if (arg === '--changed') args.changed = true;
232
+ else if (arg === '--local') args.local = true;
183
233
  else if (arg === '--against') args.against = requireValue(arg, i++);
184
234
  else if (arg === '--base') args.base = requireValue(arg, i++);
185
235
  else if (arg === '--persona') args.persona = requireValue(arg, i++);
@@ -238,5 +288,5 @@ export function parseArgs(argv) {
238
288
  );
239
289
  }
240
290
  }
241
- return args;
291
+ return applyLocalCheckMode(args, env);
242
292
  }
@@ -9,9 +9,40 @@
9
9
  */
10
10
 
11
11
  import { ARK_ORDER_SCHEMA_DEF, ARK_RUN_SCHEMA_DEF, defaultedArkOrder, defaultedArkRun, validateArkOrderExtra, validateArkRunExtra, } from './config-extras.mjs';
12
+ import { canonicalStewardId } from './team-parliament.mjs';
12
13
  /** Current published ark.config.json schema version (ADR 0027: 1.3 adds optional arkOrder). */
13
14
  export const ARK_CONFIG_SCHEMA_VERSION = '1.3';
14
- export const ARK_CONFIG_SCHEMA_URL = 'https://unpkg.com/arkgate@2/schemas/ark.config.schema.json';
15
+ /** Closed layer trust tags. Optional; absence is silent. Not a schemaVersion bump. */
16
+ export const LAYER_TRUST_BOUNDARIES = ['public', 'auth', 'admin', 'internal'];
17
+ /** Future house: empty globs are expected; missing owners stay silent even when required. */
18
+ export function isFutureHouseLayer(layer) {
19
+ return layer?.optional === true || layer?.reserved === true || layer?.allowEmpty === true;
20
+ }
21
+ /**
22
+ * Present `layers[].owners` as non-empty strings. Absence / empty / wrong type → undefined.
23
+ */
24
+ export function layerOwnersList(layer) {
25
+ const raw = layer && typeof layer === 'object' ? layer.owners : undefined;
26
+ if (!Array.isArray(raw) || raw.length === 0)
27
+ return undefined;
28
+ const ids = raw.filter((entry) => typeof entry === 'string' && entry.length > 0);
29
+ return ids.length > 0 ? ids : undefined;
30
+ }
31
+ /**
32
+ * Layer names that must name owners when `requireLayerOwners` is on.
33
+ * Empty when the require flag is absent or false.
34
+ */
35
+ export function layersMissingRequiredOwners(config) {
36
+ if (config?.requireLayerOwners !== true || !Array.isArray(config.layers))
37
+ return [];
38
+ return config.layers
39
+ .filter((layer) => !isFutureHouseLayer(layer) && !layerOwnersList(layer))
40
+ .map((layer) => layer.name);
41
+ }
42
+ export function missingLayerOwnersNextAction(layerName) {
43
+ return `Add a GitHub handle or email to ${layerName}'s owners in ark.config.json (/ark-adopt).`;
44
+ }
45
+ export const ARK_CONFIG_SCHEMA_URL = 'https://unpkg.com/arkgate@4/schemas/ark.config.schema.json';
15
46
  const DEFAULT_LAYER_NAMES = [
16
47
  'DomainModel',
17
48
  'ApplicationOrchestration',
@@ -121,6 +152,11 @@ export const ARK_CONFIG_SCHEMA = {
121
152
  arkOrder: { $ref: '#/$defs/arkOrder' },
122
153
  /** Team parliament — GitHub handles or emails who may loosen the law (not part of policy hash). */
123
154
  stewards: { ...stringArraySchema, default: [] },
155
+ /**
156
+ * When true, every non-reserved layer must name owners. Absence/false is
157
+ * silent. Policy teeth — stays in policyHash. Owners stay metadata.
158
+ */
159
+ requireLayerOwners: { type: 'boolean' },
124
160
  },
125
161
  $defs: {
126
162
  layer: {
@@ -133,6 +169,8 @@ export const ARK_CONFIG_SCHEMA = {
133
169
  exclude: stringArraySchema,
134
170
  intentPrefixes: stringArraySchema,
135
171
  description: { type: 'string', minLength: 1 },
172
+ trustBoundary: { type: 'string', enum: [...LAYER_TRUST_BOUNDARIES] },
173
+ owners: { ...stringArraySchema, minItems: 1 },
136
174
  forbiddenGlobals: stringArraySchema,
137
175
  capabilities: {
138
176
  type: 'object',
@@ -205,7 +243,7 @@ export const ARK_CONFIG_SCHEMA = {
205
243
  coverage: {
206
244
  type: 'object',
207
245
  additionalProperties: false,
208
- description: 'Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant.',
246
+ description: 'Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.',
209
247
  properties: {
210
248
  testGlobs: { ...stringArraySchema, minItems: 1 },
211
249
  maxFiles: {
@@ -351,6 +389,30 @@ function validateNode(value, schema, path, root, issues) {
351
389
  }
352
390
  }
353
391
  }
392
+ function validateLayerOwners(candidate, issues) {
393
+ const layers = candidate.layers;
394
+ if (!Array.isArray(layers))
395
+ return;
396
+ layers.forEach((layer, index) => {
397
+ if (!layer || typeof layer !== 'object' || Array.isArray(layer))
398
+ return;
399
+ if (!('owners' in layer))
400
+ return;
401
+ const owners = layer.owners;
402
+ if (!Array.isArray(owners))
403
+ return;
404
+ owners.forEach((entry, ownerIndex) => {
405
+ if (typeof entry !== 'string')
406
+ return;
407
+ if (!canonicalStewardId(entry)) {
408
+ issues.push({
409
+ path: `$.layers[${index}].owners[${ownerIndex}]`,
410
+ message: 'must be a GitHub handle or email (not a display name)',
411
+ });
412
+ }
413
+ });
414
+ });
415
+ }
354
416
  function defaultedConfig(input) {
355
417
  const result = {
356
418
  ...input,
@@ -456,6 +518,7 @@ export function loadArkConfigContract(input, source = 'ark.config.json') {
456
518
  validateNode(candidate, ARK_CONFIG_SCHEMA, '$', ARK_CONFIG_SCHEMA, issues);
457
519
  validateArkRunExtra(candidate, issues);
458
520
  validateArkOrderExtra(candidate, issues);
521
+ validateLayerOwners(candidate, issues);
459
522
  if (issues.length > 0)
460
523
  throw new ArkConfigValidationError(source, issues);
461
524
  return { config: candidate, migratedFrom };
@@ -56,8 +56,11 @@ export const DIAGNOSTIC_CATALOG = Object.freeze([
56
56
  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
57
  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
58
  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.'),
59
+ 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 }),
59
60
  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.'),
60
61
  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 }),
62
+ 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
+ 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.'),
61
64
  // ── ArkRun (opt-in extra; RN05 dual-depth nextAction) ────────────────────
62
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.'),
63
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.'),
@@ -90,7 +93,7 @@ export const DIAGNOSTIC_CATALOG = Object.freeze([
90
93
  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.'),
91
94
  // ── analysis completeness / host ─────────────────────────────────────────
92
95
  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.'),
93
- entry('LEXICAL_EVIDENCE_INCOMPLETE', 'analysis', 'Lexical evidence incomplete', 'Single-file validation cannot prove project module resolution. The write hook is already the verdict.', 'Re-run `npx arkgate-check --root . --config ark.config.json`, or treat the hook deny as final. Do not call ark_prepare_change from a hook deny.'),
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.'),
94
97
  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.'),
95
98
  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.'),
96
99
  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.'),
@@ -116,6 +119,7 @@ export const DIAGNOSTIC_CATALOG = Object.freeze([
116
119
  entry('CONFIG_RULE_UNKNOWN_TO_LAYER', 'config', 'Rule unknown to layer', 'A dependency rule references a target layer name that is not declared.', 'Fix the rule’s to field to a declared layer name.', { oftenAdvisory: true }),
117
120
  entry('CONFIG_AMBIGUOUS_LAYERS', 'config', 'Ambiguous layer classification', 'Some files match multiple layers at equal specificity; classification falls back to declaration order.', 'Disambiguate overlapping patterns so each file has one clear layer owner.', { oftenAdvisory: true }),
118
121
  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
+ 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.'),
119
123
  // ── literal path drift ───────────────────────────────────────────────────
120
124
  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.'),
121
125
  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 }),
@@ -18,9 +18,17 @@ import {
18
18
  } from './reshape-decisions.mjs';
19
19
  import { printParseHealthSection, summarizeParseHealth } from './parse-health.mjs';
20
20
  import { detectGraphBlindSpots, printGraphBlindSection } from './graph-blind.mjs';
21
- import { summarizeRulesUnderContract } from './rules-under-contract.mjs';
21
+ import {
22
+ formatArkRulesDoctorLines,
23
+ summarizeRulesUnderContract,
24
+ } from './rules-under-contract.mjs';
22
25
  import { collectStewardNudge } from './team-parliament-io.mjs';
23
- import { formatArkRunDoctorLines, summarizeArkRunSection } from './ark-run-doctor.mjs';
26
+ import {
27
+ ARKRUN_FIRST_CONTACT_NEXT,
28
+ ARKRUN_ONE_BREATH,
29
+ formatArkRunDoctorLines,
30
+ summarizeArkRunSection,
31
+ } from './ark-run-doctor.mjs';
24
32
  import {
25
33
  ARKORDER_FIRST_CONTACT_NEXT,
26
34
  ARKORDER_ONE_BREATH,
@@ -28,6 +36,7 @@ import {
28
36
  summarizeArkOrderSection,
29
37
  } from './ark-order-doctor.mjs';
30
38
  import { composeMergePlanesHonesty } from './extra-merge-teeth.mjs';
39
+ import { collectPrototypeShortcutsResidual } from './prototype-shortcuts.mjs';
31
40
 
32
41
  export function attachExtraDoctorSections(rulesUnderContract, config, classification, findings) {
33
42
  const arkRulesMerge = {
@@ -80,12 +89,78 @@ export function attachExtraDoctorSections(rulesUnderContract, config, classifica
80
89
  return { arkRun, arkOrder, mergePlanes };
81
90
  }
82
91
 
92
+ function arkRulesDoctorMark(section, warn) {
93
+ if (Array.isArray(section?.loadErrors) && section.loadErrors.length > 0) return warn;
94
+ if (section?.emptyInvariantCatalog === true) return warn;
95
+ if ((Number(section?.uncoveredInvariants) || 0) > 0) return warn;
96
+ return ' ';
97
+ }
98
+
83
99
  export function printCompactExtraDoctorLines(advisories, io) {
100
+ const owners = advisories?.layerOwners;
101
+ if (owners?.required && owners.ask) {
102
+ console.log('');
103
+ io.line(io.warn, owners.ask);
104
+ if (owners.nextAction) io.line(' ', `Next: ${owners.nextAction}`);
105
+ }
106
+ const adr = advisories?.adrPresence;
107
+ if (adr?.missing && adr.ask) {
108
+ console.log('');
109
+ io.line(io.warn, adr.ask);
110
+ if (adr.nextAction) io.line(' ', `Next: ${adr.nextAction}`);
111
+ }
112
+ const catalog = advisories?.statusTransitionCatalog;
113
+ if (catalog?.ask) {
114
+ console.log('');
115
+ io.line(io.warn, catalog.ask);
116
+ if (catalog.nextAction) io.line(' ', `Next: ${catalog.nextAction}`);
117
+ } else {
118
+ const states = advisories?.statesTransitions;
119
+ if (states?.ask) {
120
+ console.log('');
121
+ io.line(io.warn, states.ask);
122
+ if (states.nextAction) io.line(' ', `Next: ${states.nextAction}`);
123
+ }
124
+ }
125
+ const noDomain = advisories?.noDomainFrontend;
126
+ if (noDomain?.ask) {
127
+ console.log('');
128
+ io.line(io.warn, noDomain.ask);
129
+ if (noDomain.nextAction) io.line(' ', `Next: ${noDomain.nextAction}`);
130
+ }
131
+ const prototypeShortcuts = advisories?.prototypeShortcuts;
132
+ if (prototypeShortcuts?.ask) {
133
+ console.log('');
134
+ io.line(io.warn, prototypeShortcuts.ask);
135
+ if (prototypeShortcuts.nextAction) io.line(' ', `Next: ${prototypeShortcuts.nextAction}`);
136
+ }
137
+ const testsPath = advisories?.invariantTestsPath;
138
+ if (testsPath?.missing && testsPath.ask) {
139
+ console.log('');
140
+ io.line(io.warn, testsPath.ask);
141
+ if (testsPath.nextAction) io.line(' ', `Next: ${testsPath.nextAction}`);
142
+ }
143
+ const coverageRoots = advisories?.invariantCoverageRoots;
144
+ if (coverageRoots?.missing && coverageRoots.ask) {
145
+ console.log('');
146
+ io.line(io.warn, coverageRoots.ask);
147
+ if (coverageRoots.nextAction) io.line(' ', `Next: ${coverageRoots.nextAction}`);
148
+ }
149
+ const rulesUnderContract = advisories?.rulesUnderContract;
150
+ const arkRulesLines = formatArkRulesDoctorLines(rulesUnderContract);
151
+ if (arkRulesLines.length > 0) {
152
+ console.log('');
153
+ const mark = arkRulesDoctorMark(rulesUnderContract, io.warn);
154
+ for (const text of arkRulesLines) io.line(mark, text);
155
+ }
84
156
  const arkRun = advisories?.arkRun;
85
157
  if (arkRun?.active === true && arkRun.notAScore === true) {
86
158
  console.log('');
87
159
  const residual = Number(arkRun.residual?.count) || 0;
88
- io.line(residual > 0 ? io.warn : ' ', `ArkRun: ${arkRun.mode || 'on'} · residual=${residual} · not a score`);
160
+ const mark = residual > 0 ? io.warn : ' ';
161
+ io.line(mark, ARKRUN_ONE_BREATH);
162
+ io.line(mark, `ArkRun: ${arkRun.mode || 'on'} · residual=${residual} · not a score`);
163
+ if (residual > 0) io.line(mark, ARKRUN_FIRST_CONTACT_NEXT);
89
164
  }
90
165
  const arkOrder = advisories?.arkOrder;
91
166
  if (arkOrder && arkOrder.notAScore === true) {
@@ -127,16 +202,36 @@ export function computeDoctorAdvisories(root, config, cov, rules, files, ts, par
127
202
  root,
128
203
  decisionMemory
129
204
  );
130
- // Prefer architecture facts paths when available; coverage I/O still walks test roots.
205
+ // Prefer architecture facts paths when available; still union the doctor walk
206
+ // so an empty-catalog residual can see Domain files the facts subset missed.
207
+ const normalizeDoctorFile = (entry) => {
208
+ const raw =
209
+ typeof entry === 'string'
210
+ ? entry
211
+ : typeof entry?.path === 'string'
212
+ ? entry.path
213
+ : '';
214
+ const path = raw.replace(/\\/g, '/').replace(/^\.\//, '');
215
+ return path ? { path } : null;
216
+ };
217
+ const walkFiles = Array.isArray(files) ? files.map(normalizeDoctorFile).filter(Boolean) : [];
218
+ const factFiles = Array.isArray(facts?.files)
219
+ ? facts.files.map(normalizeDoctorFile).filter(Boolean)
220
+ : [];
221
+ const seen = new Set();
222
+ const mergedFiles = [];
223
+ for (const entry of [...factFiles, ...walkFiles]) {
224
+ if (seen.has(entry.path)) continue;
225
+ seen.add(entry.path);
226
+ mergedFiles.push(entry);
227
+ }
131
228
  const factPaths =
132
- facts ??
133
- (Array.isArray(files)
229
+ facts || walkFiles.length > 0
134
230
  ? {
135
- files: files.map((f) => ({
136
- path: typeof f === 'string' ? f.replace(/\\/g, '/').replace(/^\.\//, '') : f?.path,
137
- })).filter((f) => f.path),
231
+ ...(facts && typeof facts === 'object' ? facts : {}),
232
+ files: mergedFiles,
138
233
  }
139
- : undefined);
234
+ : undefined;
140
235
  const classification = classificationFromCoverage(cov);
141
236
  const rulesUnderContract = summarizeRulesUnderContract(root, config, factPaths, classification);
142
237
  const { arkRun, arkOrder } = attachExtraDoctorSections(
@@ -145,7 +240,14 @@ export function computeDoctorAdvisories(root, config, cov, rules, files, ts, par
145
240
  classification,
146
241
  activeViolations
147
242
  );
243
+ const prototypeShortcuts = collectPrototypeShortcutsResidual({
244
+ root,
245
+ config,
246
+ coverage: cov,
247
+ files,
248
+ });
148
249
  return {
250
+ ...(prototypeShortcuts ? { prototypeShortcuts } : {}),
149
251
  contractHealth: computeContractHealth(root, config, cov, rules),
150
252
  ambientState: computeAmbientState(ts, root, config, files),
151
253
  physicalCohesion,
@@ -179,6 +281,14 @@ export function printDoctorAdvisories(advisories, io) {
179
281
  io.line(io.warn, nudge.ask);
180
282
  if (nudge.nextAction) io.line(' ', io.color.dim(`Next: ${nudge.nextAction}`));
181
283
  }
284
+ const rulesUnderContract = advisories.rulesUnderContract;
285
+ const arkRulesLines = formatArkRulesDoctorLines(rulesUnderContract);
286
+ if (arkRulesLines.length > 0) {
287
+ console.log('');
288
+ console.log(io.color.bold('ArkRules (not a score)'));
289
+ const mark = arkRulesDoctorMark(rulesUnderContract, io.warn);
290
+ for (const text of arkRulesLines) io.line(mark, text);
291
+ }
182
292
  const arkRun = advisories.arkRun;
183
293
  if (arkRun && arkRun.notAScore === true) {
184
294
  console.log('');