arkgate 2.5.0 → 2.6.1

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.
@@ -0,0 +1,1983 @@
1
+ /**
2
+ * Agent gate install, migrate, Codex, skills, adoption (roadmap #11).
3
+ */
4
+ import { createRequire } from 'node:module';
5
+ import { spawnSync } from 'node:child_process';
6
+ import crypto from 'node:crypto';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import {
12
+ arkCommand,
13
+ detectPackageManager,
14
+ execCommandParts,
15
+ execRunner,
16
+ presentLockfiles,
17
+ usableTypescript,
18
+ typescriptUsabilityHint,
19
+ DEFAULT_INTENT_PREFIXES,
20
+ DEFAULT_LAYER_DIRECTORIES,
21
+ DEFAULT_DOMAIN_FORBIDDEN_GLOBALS,
22
+ DEFAULT_RULES,
23
+ createElevenLayerConfig,
24
+ applyFrameworkLayoutOverlays
25
+ } from '../ark-shared.mjs';
26
+
27
+ /** Package root (parent of bin/). All modules live under bin/lib/. */
28
+ const __packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
29
+ const __arkCheckCli = path.join(__packageRoot, 'bin', 'ark-check.mjs');
30
+
31
+ export function readJson(file) {
32
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
33
+ }
34
+
35
+ export function readPackageJson(root) {
36
+ const file = path.join(root, 'package.json');
37
+ if (!fs.existsSync(file)) return null;
38
+ return readJson(file);
39
+ }
40
+
41
+ export function hasCheckArchitectureScript(root) {
42
+ const pkg = readPackageJson(root);
43
+ return Boolean(pkg?.scripts?.['check:architecture']);
44
+ }
45
+
46
+ export const REQUIRED_GATE_FILES = [
47
+ 'AGENTS.md',
48
+ '.mcp.json',
49
+ ];
50
+ const REQUIRED_GATE_WORKFLOW = '.github/workflows/*.yml running ark-check';
51
+
52
+ export function hasArkWorkflow(root) {
53
+ const workflowsDir = path.join(root, '.github', 'workflows');
54
+ if (!fs.existsSync(workflowsDir)) return false;
55
+ return fs
56
+ .readdirSync(workflowsDir)
57
+ .filter((file) => /\.ya?ml$/i.test(file))
58
+ .some((file) => {
59
+ try {
60
+ const content = fs.readFileSync(path.join(workflowsDir, file), 'utf8');
61
+ return /\bark-check\b/.test(content) || /\bcheck:architecture\b/.test(content);
62
+ } catch {
63
+ return false;
64
+ }
65
+ });
66
+ }
67
+
68
+ export function missingGates(root) {
69
+ const missing = REQUIRED_GATE_FILES.filter(
70
+ (relativePath) => !fs.existsSync(path.join(root, relativePath))
71
+ );
72
+ if (!hasArkWorkflow(root)) missing.push(REQUIRED_GATE_WORKFLOW);
73
+ return missing;
74
+ }
75
+
76
+ export function checkArchitectureScriptSnippet(root) {
77
+ // The package manager's runner resolves the installed binary; `node bin/ark-check.mjs`
78
+ // only works inside Ark's own repo. Package-manager aware so a pnpm/yarn repo isn't
79
+ // handed an `npx` alias that violates its "never npx" policy.
80
+ return `"check:architecture": "${arkCheckCommand(root)}"`;
81
+ }
82
+ export function ensureDirForFile(file) {
83
+ fs.mkdirSync(path.dirname(file), { recursive: true });
84
+ }
85
+
86
+ /**
87
+ * True when AGENTS.md is wholly Ark-owned (header is Ark Enforcement).
88
+ * Project guides that merely append an Ark section must remain non-Ark so --force
89
+ * never wipes them.
90
+ */
91
+ export function isArkAgentsContent(text) {
92
+ if (typeof text !== 'string' || !text.trim()) return false;
93
+ const head = text.trimStart().slice(0, 120);
94
+ return /^#\s*Ark(Gate)?\s+Enforcement\b/.test(head);
95
+ }
96
+
97
+ export function writeTemplate(root, relativePath, content, force) {
98
+ const fullPath = path.join(root, relativePath);
99
+ if (relativePath === 'AGENTS.md' && fs.existsSync(fullPath)) {
100
+ let existing = '';
101
+ try {
102
+ existing = fs.readFileSync(fullPath, 'utf8');
103
+ } catch {
104
+ existing = '';
105
+ }
106
+ if (existing && !isArkAgentsContent(existing)) {
107
+ // Never clobber a project-owned AGENTS.md — even with --force.
108
+ // If Ark section not present yet, merge once; subsequent runs leave it alone.
109
+ const hasArkSection =
110
+ /#\s*Ark(Gate)?\s+Enforcement\b/.test(existing) ||
111
+ /ark\.config\.json is authoritative/i.test(existing);
112
+ if (force && isArkAgentsContent(content) && !hasArkSection) {
113
+ try {
114
+ const merged = `${existing.replace(/\s*$/, '')}\n\n---\n\n${content}`;
115
+ ensureDirForFile(fullPath);
116
+ fs.writeFileSync(fullPath, merged);
117
+ return { relativePath, status: 'merged' };
118
+ } catch {
119
+ return { relativePath, status: 'failed' };
120
+ }
121
+ }
122
+ return { relativePath, status: 'skipped-non-ark' };
123
+ }
124
+ if (!force && isArkAgentsContent(existing)) {
125
+ return { relativePath, status: 'skipped' };
126
+ }
127
+ } else if (fs.existsSync(fullPath) && !force) {
128
+ return { relativePath, status: 'skipped' };
129
+ }
130
+ try {
131
+ ensureDirForFile(fullPath);
132
+ fs.writeFileSync(fullPath, content);
133
+ return { relativePath, status: 'written' };
134
+ } catch {
135
+ return { relativePath, status: 'failed' };
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Load a TypeScript module with a working JS API host (`sys` + AST + resolve).
141
+ * Prefer the project's install when API-compatible (TS 5/6 + any TS 7 that still
142
+ * exposes the classic JS host). TypeScript 7.0.x main entry is version-only
143
+ * (`{ version, versionMajorMinor }`); programmatic APIs live under
144
+ * `typescript/unstable/*` and are not yet the gate's host — we fall through to
145
+ * ArkGate's own `typescript` dependency (JS-API 5.x) or a bare import.
146
+ * Returns `{ ts, source, version, fallbackReason? }` or null.
147
+ */
148
+ export async function loadTypeScript(root) {
149
+ const { createRequire } = await import('node:module');
150
+ const loaders = [];
151
+ try {
152
+ const req = createRequire(path.join(root, 'package.json'));
153
+ loaders.push({
154
+ label: 'project',
155
+ load: () => req('typescript'),
156
+ resolvePath: () => {
157
+ try {
158
+ return req.resolve('typescript');
159
+ } catch {
160
+ return null;
161
+ }
162
+ },
163
+ });
164
+ } catch {
165
+ /* project has no package.json resolvable tree */
166
+ }
167
+ // Nested under arkgate (production dependency) — must work when project has only TS7.
168
+ try {
169
+ const req = createRequire(__arkCheckCli);
170
+ loaders.push({
171
+ label: 'arkgate',
172
+ load: () => req('typescript'),
173
+ resolvePath: () => {
174
+ try {
175
+ return req.resolve('typescript');
176
+ } catch {
177
+ return null;
178
+ }
179
+ },
180
+ });
181
+ } catch {
182
+ /* ark install tree unavailable */
183
+ }
184
+ loaders.push({
185
+ label: 'import',
186
+ load: async () => {
187
+ const m = await import('typescript');
188
+ return m;
189
+ },
190
+ resolvePath: () => null,
191
+ });
192
+
193
+ let projectRejected = null;
194
+ const triedPaths = new Set();
195
+ for (const { label, load, resolvePath } of loaders) {
196
+ try {
197
+ const resolved = typeof resolvePath === 'function' ? resolvePath() : null;
198
+ if (resolved && triedPaths.has(resolved)) {
199
+ // Same physical package already rejected (e.g. project === hoisted arkgate path).
200
+ continue;
201
+ }
202
+ if (resolved) triedPaths.add(resolved);
203
+
204
+ const mod = await load();
205
+ const ts = usableTypescript(mod);
206
+ if (ts) {
207
+ const version =
208
+ typeof ts.version === 'string'
209
+ ? ts.version
210
+ : typeof mod?.version === 'string'
211
+ ? mod.version
212
+ : undefined;
213
+ return {
214
+ ts,
215
+ source: label,
216
+ version,
217
+ ...(projectRejected ? { fallbackReason: projectRejected } : {}),
218
+ };
219
+ }
220
+ if (label === 'project' && mod) {
221
+ projectRejected = `project typescript is not API-compatible (${typescriptUsabilityHint(mod)}); using ArkGate's JS-API TypeScript fallback (TypeScript 7.0 main export is version-only). See docs/typescript-support.md.`;
222
+ }
223
+ } catch {
224
+ /* try next loader */
225
+ }
226
+ }
227
+ return null;
228
+ }
229
+
230
+ /**
231
+ * Args for every emitted `ark-check` (AGENTS.md, package.json, Cursor rule, CI).
232
+ * If `.ark-baseline.json` exists, include `--baseline` so agent/local/CI paths
233
+ * match the ratchet — otherwise agents re-fail on frozen debt (field-test bug).
234
+ */
235
+ export function checkArgsForRoot(root, { requireGates = false } = {}) {
236
+ const baselineFlag = fs.existsSync(path.join(root, '.ark-baseline.json'))
237
+ ? ' --baseline .ark-baseline.json'
238
+ : '';
239
+ const gatesFlag = requireGates ? ' --require-gates' : '';
240
+ return `--root . --config ark.config.json --strict-config${baselineFlag}${gatesFlag}`;
241
+ }
242
+
243
+ export function packageManager(root) {
244
+ // CI always require-gates; baseline follows checkArgsForRoot.
245
+ const checkArgs = checkArgsForRoot(root, { requireGates: true });
246
+ // Same detection as every emitted command (execRunner): honors the packageManager field and
247
+ // won't let a stray pnpm-lock.yaml hijack an npm project (package-lock.json wins the tie).
248
+ const pm = detectPackageManager(root);
249
+ if (pm === 'pnpm') {
250
+ return {
251
+ cache: 'pnpm',
252
+ setup: ['corepack enable'],
253
+ install: 'pnpm install --frozen-lockfile',
254
+ // Same runner as execRunner(): skip pnpm's verify-deps gate (ERR_PNPM_IGNORED_BUILDS).
255
+ run: `pnpm --config.verify-deps-before-run=false exec ark-check ${checkArgs}`,
256
+ };
257
+ }
258
+ if (pm === 'yarn') {
259
+ return {
260
+ cache: 'yarn',
261
+ setup: ['corepack enable'],
262
+ install: 'yarn install --frozen-lockfile',
263
+ run: `yarn ark-check ${checkArgs}`,
264
+ };
265
+ }
266
+ // Monorepo hosts (e.g. Next app under frontend/) often have a root package.json only for
267
+ // arkgate while real app deps live in frontend/package.json. Install both so CI can resolve
268
+ // the tree; ark-check itself only needs the root arkgate install.
269
+ const frontendPkg = fs.existsSync(path.join(root, 'frontend', 'package.json'));
270
+ const rootInstall = fs.existsSync(path.join(root, 'package-lock.json')) ? 'npm ci' : 'npm install';
271
+ const install = frontendPkg
272
+ ? `${rootInstall} && (cd frontend && ${fs.existsSync(path.join(root, 'frontend', 'package-lock.json')) ? 'npm ci' : 'npm install'})`
273
+ : rootInstall;
274
+ return {
275
+ cache: 'npm',
276
+ setup: [],
277
+ install,
278
+ run: `npx ark-check ${checkArgs}`,
279
+ };
280
+ }
281
+
282
+ // The runner prefix (npx / pnpm exec / yarn) is added per project by arkCheckCommand
283
+ // so a pnpm-only repo never gets an `npx` instruction — see execRunner() in ark-shared.mjs.
284
+ export function arkCheckCommand(root) {
285
+ return arkCommand(root, 'ark-check', checkArgsForRoot(root));
286
+ }
287
+
288
+ // Canonical agent contract. AGENTS.md and the Cursor rule both derive from this single
289
+ // source so the steps can never drift out of sync between the two files. `steps(checkCommand)`
290
+ // is a builder because the check command's runner prefix varies with the package manager.
291
+ const AGENT_CONTRACT = {
292
+ manifestResource: 'ark://manifest',
293
+ steps: (checkCommand) => [
294
+ `Read the Ark contract from \`ark://manifest\` when the MCP server is available.`,
295
+ `Keep source files inside the layer boundaries declared in \`ark.config.json\`.`,
296
+ `Do not bypass Ark publishers, event contracts, or source metadata for runtime mutations.`,
297
+ `After edits, run \`${checkCommand}\`.`,
298
+ `If Ark reports violations, fix the architecture instead of weakening the gate.`,
299
+ ],
300
+ // Cursor-only guidance: the write-time validate_code tool is available in
301
+ // Cursor's runtime but has no equivalent in a plain AGENTS.md read.
302
+ cursorValidateStep: `Validate the full post-edit file content with the \`validate_code\` tool before writing whenever your runtime supports it.`,
303
+ };
304
+
305
+ export function layerPlacementTable() {
306
+ const rows = DEFAULT_INTENT_PREFIXES.map((entry) => {
307
+ const dirs = (DEFAULT_LAYER_DIRECTORIES[entry.layer] ?? [])
308
+ .map((directory) => `\`${directory}/\``)
309
+ .join(', ');
310
+ return `| ${entry.layer} | ${dirs} | ${entry.prefixes.map((p) => `\`${p}\``).join(', ')} |`;
311
+ }).join('\n');
312
+ return `| Layer | Conventional directories (under the source root) | Intent prefixes |
313
+ |-------|---------------------------------------------------|-----------------|
314
+ ${rows}`;
315
+ }
316
+
317
+ export function agentInstructions(root) {
318
+ const checkCmd = arkCheckCommand(root);
319
+ const startCmd = arkCommand(root, 'ark', 'start');
320
+ const doctorCmd = arkCommand(root, 'ark-check', '--doctor');
321
+ const steps = AGENT_CONTRACT.steps(checkCmd)
322
+ .map((step, index) => `${index + 1}. ${step}`)
323
+ .join('\n');
324
+ return `# Ark Enforcement
325
+
326
+ ## Default agent flow (if unsure, do only this)
327
+
328
+ 1. If \`ark.config.json\` is missing: run \`${startCmd}\` once.
329
+ 2. For adoption / cleanup / “make architecture sound”: run the **\`/ark-autopilot\`** skill
330
+ (origin report → adopt → plan → safe fixes → gates). Do **not** invent a parallel workflow
331
+ from the long skill list.
332
+ 3. Status anytime: \`${doctorCmd}\` (status light + next action — not a mode picker).
333
+ 4. After ordinary feature edits: run \`${checkCmd}\`. On violations → **\`/ark-fix\`** (or
334
+ \`/ark-place\` for new files, \`/ark-contract\` only if the contract itself is wrong).
335
+
336
+ Other \`/ark-*\` skills are optional escapes (adopt, coverage, runtime, …), not required steps.
337
+
338
+ ## Before editing TypeScript or JavaScript source files
339
+
340
+ ${steps}
341
+
342
+ ## Where new code belongs
343
+
344
+ \`ark.config.json\` is authoritative for this project. When creating a NEW kind of code
345
+ that no existing layer covers (a saga, a background job, a read model, ...), use the
346
+ default 11-layer placement below and add the layer to \`ark.config.json\` — do not invent
347
+ an ungoverned location:
348
+
349
+ ${layerPlacementTable()}
350
+
351
+ The project is only considered Ark-enforced when the write gate and CI gate pass
352
+ (runtime path only if this project opted into the kernel).
353
+ `;
354
+ }
355
+
356
+ export function mcpJson(root) {
357
+ return `${JSON.stringify({
358
+ mcpServers: {
359
+ ark: {
360
+ type: 'stdio',
361
+ // Prefer arkgate-mcp; ark-mcp alias still works for one major.
362
+ ...execCommandParts(root, PREFERRED_MCP_BIN, ['--root', '.', '--config', 'ark.config.json']),
363
+ },
364
+ },
365
+ }, null, 2)}\n`;
366
+ }
367
+
368
+ // Sample for docs/ — `ark-check --install-agent-gates --tools codex` auto-merges the real
369
+ // block (with absolute paths) into ~/.codex/config.toml. This copy is a reference only, so
370
+ // it flags the two gotchas of hand-editing the global config: absolute paths (config.toml is
371
+ // loaded without the project as cwd) and the required restart.
372
+ export function codexTomlSnippet(root) {
373
+ const { command, args } = execCommandParts(root, PREFERRED_MCP_BIN, [
374
+ '--root',
375
+ '/absolute/path/to/project',
376
+ '--config',
377
+ '/absolute/path/to/project/ark.config.json',
378
+ ]);
379
+ const argsToml = args.map((value) => `"${value}"`).join(', ');
380
+ return `# Add to ~/.codex/config.toml (or $CODEX_HOME/config.toml), then RESTART Codex —
381
+ # it does not hot-load MCP servers. Use ABSOLUTE paths: config.toml is global, so
382
+ # "." would resolve against Codex's launch dir, not this project. Prefer:
383
+ # ark-check --install-agent-gates --tools codex (auto-merges the absolute paths)
384
+ [mcp_servers.ark]
385
+ command = "${command}"
386
+ args = [${argsToml}]
387
+ `;
388
+ }
389
+
390
+ /**
391
+ * Compact always-on rule for instruction-tier hosts (Windsurf, Cline, GitHub Copilot,
392
+ * Kiro, ...): agents that read a project rule file but have no MCP tools or hooks.
393
+ * Derived from the same AGENT_CONTRACT as AGENTS.md and the Cursor rule so the steps
394
+ * can never drift; points at AGENTS.md for the full placement table.
395
+ */
396
+ export function instructionRule(root) {
397
+ const steps = AGENT_CONTRACT.steps(arkCheckCommand(root))
398
+ .map((step, index) => `${index + 1}. ${step}`)
399
+ .join('\n');
400
+ return `# Ark architecture contract
401
+
402
+ This project's architecture is governed by Ark (\`ark.config.json\` is authoritative).
403
+ Before writing or editing TypeScript or JavaScript source files:
404
+
405
+ ${steps}
406
+
407
+ See \`AGENTS.md\` for the full contract and the layer placement table.
408
+ `;
409
+ }
410
+
411
+ export function cursorRule(root) {
412
+ return `---
413
+ description: Ark architecture contract
414
+ alwaysApply: true
415
+ ---
416
+
417
+ Before writing or editing TypeScript or JavaScript source files, read the
418
+ \`${AGENT_CONTRACT.manifestResource}\` resource from the \`ark\` MCP server when available.
419
+
420
+ ${AGENT_CONTRACT.cursorValidateStep} After edits, run:
421
+
422
+ \`\`\`bash
423
+ ${arkCheckCommand(root)}
424
+ \`\`\`
425
+
426
+ If Ark reports violations, fix the architecture instead of bypassing the gate.
427
+ `;
428
+ }
429
+
430
+ // Default CI Node when the project declares nothing. A current LTS, NOT the
431
+ // oldest supported: the npm-ci-lockfile-mismatch failure only happens when CI's
432
+ // npm is OLDER than the npm that wrote the lockfile, so defaulting high is safer.
433
+ const DEFAULT_CI_NODE_VERSION = '22';
434
+
435
+ // Decide the Node the generated CI should use, preferring the project's own
436
+ // declaration so CI's npm matches the dev's (a mismatch makes `npm ci` fail with
437
+ // "missing from lock file" — a red gate unrelated to architecture). In order:
438
+ // 1. .nvmrc / .node-version → setup-node's node-version-file (exact, best)
439
+ // 2. package.json engines.node → its concrete major
440
+ // 3. a current-LTS default
441
+ export function detectCiNode(root) {
442
+ for (const file of ['.nvmrc', '.node-version']) {
443
+ if (fs.existsSync(path.join(root, file))) return { kind: 'file', value: file };
444
+ }
445
+ const enginesNode = readPackageJson(root)?.engines?.node;
446
+ if (typeof enginesNode === 'string') {
447
+ const major = enginesNode.match(/\d+/)?.[0];
448
+ if (major) return { kind: 'version', value: major };
449
+ }
450
+ return { kind: 'default', value: DEFAULT_CI_NODE_VERSION };
451
+ }
452
+
453
+ export function githubWorkflow(pm, ciNode) {
454
+ // pnpm/yarn setup (corepack enable) MUST run before actions/setup-node so the package
455
+ // manager is on PATH when setup-node's `cache: pnpm|yarn` tries to resolve the store —
456
+ // otherwise the cache step fails on a fresh runner ("Unable to locate executable file: pnpm").
457
+ const setupSteps = pm.setup.map((command) => ` - run: ${command}`).join('\n');
458
+ // node-version-file keeps CI locked to the dev's exact toolchain; an explicit
459
+ // version comes from engines.node; the default carries a hint for the mismatch
460
+ // symptom since we can't know which npm wrote the lockfile.
461
+ const nodeSetup =
462
+ ciNode.kind === 'file'
463
+ ? ` node-version-file: ${ciNode.value}`
464
+ : ciNode.kind === 'version'
465
+ ? ` node-version: '${ciNode.value}'`
466
+ : ` # If the install step fails with "missing from lock file" / lockfile out
467
+ # of sync, your local package manager is newer than this Node's — add a
468
+ # .nvmrc with your Node version so CI matches the dev environment.
469
+ node-version: '${ciNode.value}'`;
470
+ return `name: Ark architecture gate
471
+
472
+ on:
473
+ pull_request:
474
+ push:
475
+ branches: [main, master]
476
+
477
+ jobs:
478
+ ark-check:
479
+ runs-on: ubuntu-latest
480
+ steps:
481
+ - name: Checkout
482
+ uses: actions/checkout@v4
483
+ ${setupSteps ? `${setupSteps}\n` : ''} - name: Setup Node
484
+ uses: actions/setup-node@v4
485
+ with:
486
+ ${nodeSetup}
487
+ cache: ${pm.cache}
488
+ - name: Install dependencies
489
+ run: ${pm.install}
490
+ - name: Ark architecture check
491
+ run: ${pm.run}
492
+ `;
493
+ }
494
+
495
+ export function claudeSettings(root) {
496
+ const runner = execRunner(root);
497
+ return `${JSON.stringify({
498
+ hooks: {
499
+ // Inject the contract at session start so the agent knows the architecture from
500
+ // the first token. Project-scoped by design; --session-context is also a silent
501
+ // no-op when no ark.config.json exists, so it can never leak into other projects.
502
+ SessionStart: [
503
+ {
504
+ hooks: [
505
+ {
506
+ type: 'command',
507
+ command: `${runner} ${PREFERRED_MCP_BIN} --session-context --root "$CLAUDE_PROJECT_DIR" --config ark.config.json`,
508
+ },
509
+ ],
510
+ },
511
+ ],
512
+ PreToolUse: [
513
+ {
514
+ matcher: 'Write|Edit|MultiEdit',
515
+ hooks: [
516
+ {
517
+ type: 'command',
518
+ command: `${runner} ${PREFERRED_MCP_BIN} --hook --root "$CLAUDE_PROJECT_DIR" --config ark.config.json`,
519
+ },
520
+ ],
521
+ },
522
+ ],
523
+ },
524
+ }, null, 2)}\n`;
525
+ }
526
+
527
+ // Grok Build project config: MCP registration (commit-friendly relative paths — unlike
528
+ // Codex's global config.toml, Grok loads .grok/config.toml from the project).
529
+ export function grokProjectConfig(root) {
530
+ const { command, args } = execCommandParts(root, PREFERRED_MCP_BIN, [
531
+ '--root',
532
+ '.',
533
+ '--config',
534
+ 'ark.config.json',
535
+ ]);
536
+ const argsToml = args.map((value) => `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`).join(', ');
537
+ return `# Generated by ark-check --install-agent-gates (Grok Build project scope).
538
+ # Restart Grok (or /mcps → refresh) after changes. Also loads repo-root .mcp.json.
539
+ [mcp_servers.ark]
540
+ command = "${command.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"
541
+ args = [${argsToml}]
542
+ `;
543
+ }
544
+
545
+ // Grok Build hooks: same arkgate-mcp contracts as Claude. Grok sets both
546
+ // GROK_WORKSPACE_ROOT and CLAUDE_PROJECT_DIR (Claude-compatible alias). Prefer
547
+ // GROK_* with fallback so hooks still work if only one is present.
548
+ // Matcher keeps Claude names (Write|Edit|MultiEdit) and Grok natives
549
+ // (write|search_replace) — Grok aliases both directions.
550
+ export function grokHooks(root) {
551
+ const runner = execRunner(root);
552
+ // Nested defaults: Grok native → Claude alias → project cwd (hook cwd is the workspace).
553
+ const grokRoot = '${GROK_WORKSPACE_ROOT:-${CLAUDE_PROJECT_DIR:-.}}';
554
+ return `${JSON.stringify({
555
+ hooks: {
556
+ SessionStart: [
557
+ {
558
+ hooks: [
559
+ {
560
+ type: 'command',
561
+ timeout: 30,
562
+ command: `${runner} ${PREFERRED_MCP_BIN} --session-context --root "${grokRoot}" --config ark.config.json`,
563
+ },
564
+ ],
565
+ },
566
+ ],
567
+ PreToolUse: [
568
+ {
569
+ matcher: 'Write|Edit|MultiEdit|write|search_replace',
570
+ hooks: [
571
+ {
572
+ type: 'command',
573
+ timeout: 30,
574
+ command: `${runner} ${PREFERRED_MCP_BIN} --hook --root "${grokRoot}" --config ark.config.json`,
575
+ },
576
+ ],
577
+ },
578
+ ],
579
+ },
580
+ }, null, 2)}\n`;
581
+ }
582
+
583
+ /** Normalize --tools from array or comma-separated string (never character-split a string). */
584
+ export function normalizeToolsList(tools) {
585
+ if (tools == null) return [];
586
+ if (Array.isArray(tools)) {
587
+ return tools
588
+ .flatMap((t) => String(t).split(','))
589
+ .map((t) => t.trim().toLowerCase())
590
+ .filter(Boolean);
591
+ }
592
+ if (typeof tools === 'string') {
593
+ return tools
594
+ .split(',')
595
+ .map((t) => t.trim().toLowerCase())
596
+ .filter(Boolean);
597
+ }
598
+ return [];
599
+ }
600
+
601
+ export function resolveTools(args) {
602
+ const explicit = normalizeToolsList(args.tools);
603
+ if (explicit.length > 0) {
604
+ return { tools: new Set(explicit), source: 'explicit' };
605
+ }
606
+ const root = args.root;
607
+ const detected = new Set();
608
+ if (fs.existsSync(path.join(root, '.claude'))) detected.add('claude');
609
+ if (fs.existsSync(path.join(root, '.cursor'))) detected.add('cursor');
610
+ if (fs.existsSync(path.join(root, '.codex'))) detected.add('codex');
611
+ if (fs.existsSync(path.join(root, '.grok'))) detected.add('grok');
612
+ if (fs.existsSync(path.join(root, '.windsurf'))) detected.add('windsurf');
613
+ // .clinerules can also be a single FILE (older Cline convention); only a directory
614
+ // can receive .clinerules/ark.md, so a file must not trigger detection.
615
+ if (fs.statSync(path.join(root, '.clinerules'), { throwIfNoEntry: false })?.isDirectory()) {
616
+ detected.add('cline');
617
+ }
618
+ if (fs.existsSync(path.join(root, '.kiro'))) detected.add('kiro');
619
+ if (fs.existsSync(path.join(root, '.roo'))) detected.add('roo');
620
+ if (fs.existsSync(path.join(root, '.continue'))) detected.add('continue');
621
+ if (fs.existsSync(path.join(root, '.gemini'))) detected.add('gemini');
622
+ // copilot has no reliable directory signal (.github exists in most repos),
623
+ // so it is explicit-only via --tools.
624
+ // No signal at all: fall back to writing the primary tools' templates so a fresh
625
+ // project still gets a complete, reviewable starter set.
626
+ if (detected.size === 0) {
627
+ return { tools: new Set(['claude', 'cursor', 'codex']), source: 'default' };
628
+ }
629
+ return { tools: detected, source: 'detected' };
630
+ }
631
+
632
+ const KNOWN_TOOLS = [
633
+ 'claude',
634
+ 'cursor',
635
+ 'codex',
636
+ 'grok',
637
+ 'windsurf',
638
+ 'cline',
639
+ 'copilot',
640
+ 'kiro',
641
+ 'roo',
642
+ 'continue',
643
+ 'gemini',
644
+ ];
645
+
646
+ // One canonical markdown per skill (templates/skills/*.md, shipped in the npm
647
+ // package); installed into each tool's slash-command location. The YAML
648
+ // frontmatter (name/description) is understood or harmlessly ignored by every
649
+ // host. Kiro has no command mechanism — its steering rule file is the only gate.
650
+ const SKILL_TOOL_TARGETS = {
651
+ claude: (name) => `.claude/skills/${name}/SKILL.md`,
652
+ cursor: (name) => `.cursor/commands/${name}.md`,
653
+ codex: (name) => `.codex/prompts/${name}.md`,
654
+ // Grok Build: project skills at .grok/skills/<name>/SKILL.md (slash-invocable).
655
+ grok: (name) => `.grok/skills/${name}/SKILL.md`,
656
+ windsurf: (name) => `.windsurf/workflows/${name}.md`,
657
+ cline: (name) => `.clinerules/workflows/${name}.md`,
658
+ copilot: (name) => `.github/prompts/${name}.prompt.md`,
659
+ };
660
+
661
+ // The version of the arkgate package these bins ship with. Used to
662
+ // stamp installed skills so a normal ark-check can tell "outdated skill from an
663
+ // older Ark" apart from "user-customized skill" — the stamp moves with the
664
+ // package, editing the body doesn't.
665
+ export function arkPackageVersion() {
666
+ try {
667
+ const pkg = readJson(path.join(__packageRoot, 'package.json'));
668
+ return typeof pkg.version === 'string' ? pkg.version : null;
669
+ } catch {
670
+ return null;
671
+ }
672
+ }
673
+
674
+ // Insert `arkVersion: <v>` into a skill's YAML frontmatter (before its closing
675
+ // `---`). No frontmatter → returned unchanged. Idempotent for a given version.
676
+ export function stampSkill(content, version) {
677
+ if (!version) return content;
678
+ const lines = content.split('\n');
679
+ if (lines[0] !== '---') return content;
680
+ const closeIdx = lines.indexOf('---', 1);
681
+ if (closeIdx === -1) return content;
682
+ const existing = lines.findIndex(
683
+ (line, i) => i > 0 && i < closeIdx && /^arkVersion:/.test(line)
684
+ );
685
+ if (existing !== -1) {
686
+ lines[existing] = `arkVersion: ${version}`;
687
+ } else {
688
+ lines.splice(closeIdx, 0, `arkVersion: ${version}`);
689
+ }
690
+ return lines.join('\n');
691
+ }
692
+
693
+ // Read the `arkVersion:` stamp from an installed skill file. Returns null when
694
+ // the file is absent or has no stamp (installed by a pre-stamp Ark, or hand-authored).
695
+ export function installedSkillVersion(filePath) {
696
+ let content;
697
+ try {
698
+ content = fs.readFileSync(filePath, 'utf8');
699
+ } catch {
700
+ return null;
701
+ }
702
+ const match = content.match(/^arkVersion:\s*(.+)$/m);
703
+ return match ? match[1].trim() : null;
704
+ }
705
+
706
+ // Numeric-tuple compare of dotted versions; true when `a` is strictly older than
707
+ // `b`. Non-numeric/absent segments compare as 0, so "1.7" < "1.7.5".
708
+ export function isVersionOlder(a, b) {
709
+ const parse = (v) => String(v).split('.').map((n) => Number.parseInt(n, 10) || 0);
710
+ const av = parse(a);
711
+ const bv = parse(b);
712
+ const len = Math.max(av.length, bv.length);
713
+ for (let i = 0; i < len; i += 1) {
714
+ const x = av[i] ?? 0;
715
+ const y = bv[i] ?? 0;
716
+ if (x !== y) return x < y;
717
+ }
718
+ return false;
719
+ }
720
+
721
+ export function skillTemplates() {
722
+ const dir = path.join(__packageRoot, 'templates', 'skills');
723
+ // A missing/mispackaged templates dir would otherwise install zero skills with
724
+ // exit 0 — warn so a packaging regression (e.g. "templates" dropped from the
725
+ // package.json files array) is visible instead of a silent no-op.
726
+ let entries;
727
+ try {
728
+ entries = fs.readdirSync(dir, { withFileTypes: true });
729
+ } catch {
730
+ console.error(
731
+ `Warning: skill templates directory not found (${dir}); no /ark-* skills installed.`
732
+ );
733
+ return [];
734
+ }
735
+ return entries
736
+ .filter((entry) => entry.isFile() && /^[a-z0-9-]+\.md$/.test(entry.name))
737
+ .map((entry) => entry.name)
738
+ .sort()
739
+ .map((name) => [path.basename(name, '.md'), fs.readFileSync(path.join(dir, name), 'utf8')]);
740
+ }
741
+
742
+ // Skill names only, silent on a missing templates dir — for the freshness
743
+ // advisory below, which must not print packaging warnings on every check run.
744
+ export function skillTemplateNames() {
745
+ const dir = path.join(__packageRoot, 'templates', 'skills');
746
+ let entries;
747
+ try {
748
+ entries = fs.readdirSync(dir, { withFileTypes: true });
749
+ } catch {
750
+ return [];
751
+ }
752
+ return entries
753
+ .filter((entry) => entry.isFile() && /^[a-z0-9-]+\.md$/.test(entry.name))
754
+ .map((entry) => path.basename(entry.name, '.md'));
755
+ }
756
+
757
+ // A normal ark-check run is the reliable discovery point for new /ark-* skills.
758
+ // Ark ships no install lifecycle script (a postinstall banner would be blocked by
759
+ // modern package managers' script-approval policy anyway, so careful users never
760
+ // saw it — and it broke hardened installs). When a project has adopted Ark agent
761
+ // gates (AGENTS.md present) but a detected tool is missing
762
+ // skills this version ships, surface it here so agents and CI actually notice.
763
+ // Advisory only — never affects the exit code. Copilot has no reliable directory
764
+ // signal, so it is not auto-detected (explicit --tools only), matching resolveTools.
765
+ // Where Codex loads slash-command prompts from. Codex reads $CODEX_HOME/prompts
766
+ // (defaulting to ~/.codex/prompts), NOT the repo — so home copies of the /ark-*
767
+ // skills drift out of date when a repo refresh only touches in-repo tool dirs.
768
+ export function codexPromptsDir() {
769
+ const base = process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
770
+ return path.join(base, 'prompts');
771
+ }
772
+
773
+ // Where Codex reads its MCP server registrations. Unlike Claude (.claude/settings.json)
774
+ // and Cursor (.cursor/mcp.json), Codex loads MCP servers only from $CODEX_HOME/config.toml
775
+ // (~/.codex/config.toml) — never from .mcp.json — so wiring Codex means editing the user's
776
+ // home config, not a repo file.
777
+ export function codexConfigPath() {
778
+ const base = process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
779
+ return path.join(base, 'config.toml');
780
+ }
781
+
782
+ // Merge the [mcp_servers.ark] table into Codex's config.toml so `ark://manifest` and the
783
+ // AI write gate are live from the first edit — the piece that was previously only shipped as
784
+ // a copy-me sample in docs/ark-codex-config.toml. Idempotent: an existing ark table is left
785
+ // untouched unless `force` replaces it; other content in the file is preserved. Returns a
786
+ // status for the install summary. The table match runs from the [mcp_servers.ark] header to
787
+ // the line before the next top-level table header (a line starting with `[`) or EOF.
788
+ //
789
+ // Unlike .mcp.json / .cursor/mcp.json (loaded relative to the project), config.toml is a
790
+ // GLOBAL file — Codex launches it without the project as cwd — so `--root .` would resolve
791
+ // against the wrong directory. The paths must be absolute, and TOML string values need the
792
+ // backslashes/quotes escaped (matters on Windows and for repo paths containing quotes).
793
+ export function wireCodexMcp(root, force) {
794
+ const file = codexConfigPath();
795
+ const esc = (s) => s.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
796
+ const absRoot = path.resolve(root);
797
+ const absConfig = path.join(absRoot, 'ark.config.json');
798
+ // Preferred product bin; absolute --root so Codex (cwd ≠ project) resolves correctly.
799
+ const preferredBin = 'arkgate-mcp';
800
+ const { command, args } = execCommandParts(root, preferredBin, [
801
+ '--root',
802
+ esc(absRoot),
803
+ '--config',
804
+ esc(absConfig),
805
+ ]);
806
+ const argsToml = args.map((value) => `"${value}"`).join(', ');
807
+ const makeBlock = (table) =>
808
+ `[mcp_servers.${table}]
809
+ command = "${command}"
810
+ args = [${argsToml}]`;
811
+ let existing = '';
812
+ try {
813
+ if (fs.existsSync(file)) existing = fs.readFileSync(file, 'utf8');
814
+ } catch (error) {
815
+ return { status: 'failed', file, message: error.message };
816
+ }
817
+ const tableRe = /(^|\n)\[mcp_servers\.ark\][^\n]*\n(?:(?!\[)[^\n]*\n?)*/;
818
+ const hasTable = tableRe.test(existing);
819
+ const existingRoot = hasTable ? extractCodexArkRootFromToml(existing) : null;
820
+ let differentProject = false;
821
+ try {
822
+ differentProject = Boolean(
823
+ existingRoot && path.resolve(existingRoot) !== absRoot
824
+ );
825
+ } catch {
826
+ differentProject = Boolean(existingRoot);
827
+ }
828
+ // Fail-closed: rewrite temp/upgrade roots and dual/wrong bins even without --force.
829
+ const mustRewrite = hasTable && codexArkBlockNeedsRewrite(existing, absRoot);
830
+
831
+ // Multi-project: another project's [mcp_servers.ark] is present. Without --force,
832
+ // add a project-scoped table so we do not steal the primary binding.
833
+ if (hasTable && differentProject && !force && !mustRewrite) {
834
+ const slug =
835
+ path
836
+ .basename(absRoot)
837
+ .replace(/[^a-zA-Z0-9_-]/g, '_')
838
+ .slice(0, 48) || 'project';
839
+ const table = `ark_${slug}`;
840
+ const multiRe = new RegExp(
841
+ `(^|\\n)\\[mcp_servers\\.${table.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\][^\\n]*\\n(?:(?!\\[)[^\\n]*\\n?)*`
842
+ );
843
+ const block = makeBlock(table);
844
+ let next;
845
+ if (multiRe.test(existing)) {
846
+ next = existing.replace(multiRe, (match) => `${match.startsWith('\n') ? '\n' : ''}${block}\n`);
847
+ } else {
848
+ const sep =
849
+ existing.length === 0
850
+ ? ''
851
+ : existing.endsWith('\n\n')
852
+ ? ''
853
+ : existing.endsWith('\n')
854
+ ? '\n'
855
+ : '\n\n';
856
+ next = `${existing}${sep}${block}\n`;
857
+ }
858
+ try {
859
+ fs.mkdirSync(path.dirname(file), { recursive: true });
860
+ fs.writeFileSync(file, next);
861
+ } catch (error) {
862
+ return { status: 'failed', file, message: error.message };
863
+ }
864
+ return { status: 'written-multi', file, table, primaryUnchanged: true };
865
+ }
866
+
867
+ if (hasTable && !force && !mustRewrite) {
868
+ return { status: 'skipped', file };
869
+ }
870
+ const block = makeBlock('ark');
871
+ let next;
872
+ if (hasTable) {
873
+ next = existing.replace(tableRe, (match) => `${match.startsWith('\n') ? '\n' : ''}${block}\n`);
874
+ } else {
875
+ const sep = existing.length === 0 ? '' : existing.endsWith('\n\n') ? '' : existing.endsWith('\n') ? '\n' : '\n\n';
876
+ next = `${existing}${sep}${block}\n`;
877
+ }
878
+ try {
879
+ fs.mkdirSync(path.dirname(file), { recursive: true });
880
+ fs.writeFileSync(file, next);
881
+ } catch (error) {
882
+ return { status: 'failed', file, message: error.message };
883
+ }
884
+ return {
885
+ status: hasTable ? 'updated' : 'written',
886
+ file,
887
+ ...(mustRewrite && !force ? { reason: 'temp-or-stale-root' } : {}),
888
+ };
889
+ }
890
+
891
+ // Detects stale/missing /ark-* skills in the Codex home prompts dir. Only nags
892
+ // when at least one ark-* prompt already lives there (evidence Codex was set up
893
+ // for this user) — never introduces Codex to someone who doesn't use it. Same
894
+ // guards as detectSkillGaps (adopted repo, not the Ark source tree).
895
+ export function detectCodexHomeGap(root) {
896
+ if (!fs.existsSync(path.join(root, 'AGENTS.md'))) return null;
897
+ if (fs.existsSync(path.join(root, 'templates', 'skills'))) return null;
898
+ const skillNames = skillTemplateNames();
899
+ if (skillNames.length === 0) return null;
900
+ const dir = codexPromptsDir();
901
+ if (!fs.existsSync(dir)) return null;
902
+ const present = skillNames.filter((name) => fs.existsSync(path.join(dir, `${name}.md`)));
903
+ if (present.length === 0) return null; // Codex home never set up for Ark — don't nag.
904
+ const version = arkPackageVersion();
905
+ const missing = skillNames.length - present.length;
906
+ let stale = 0;
907
+ if (version) {
908
+ for (const name of present) {
909
+ const installed = installedSkillVersion(path.join(dir, `${name}.md`));
910
+ if (installed === null || isVersionOlder(installed, version)) stale += 1;
911
+ }
912
+ }
913
+ return missing > 0 || stale > 0 ? { missing, stale } : null;
914
+ }
915
+
916
+ export function detectSkillGaps(root) {
917
+ if (!fs.existsSync(path.join(root, 'AGENTS.md'))) return [];
918
+ // The Ark source tree keeps the skill templates at templates/skills/ — it's the
919
+ // producer, not a consumer, so it must not nag itself to "install" its own skills.
920
+ if (fs.existsSync(path.join(root, 'templates', 'skills'))) return [];
921
+ const skillNames = skillTemplateNames();
922
+ if (skillNames.length === 0) return [];
923
+ const detected = [];
924
+ if (fs.existsSync(path.join(root, '.claude'))) detected.push('claude');
925
+ if (fs.existsSync(path.join(root, '.cursor'))) detected.push('cursor');
926
+ if (fs.existsSync(path.join(root, '.codex'))) detected.push('codex');
927
+ if (fs.existsSync(path.join(root, '.grok'))) detected.push('grok');
928
+ if (fs.existsSync(path.join(root, '.windsurf'))) detected.push('windsurf');
929
+ if (fs.statSync(path.join(root, '.clinerules'), { throwIfNoEntry: false })?.isDirectory()) {
930
+ detected.push('cline');
931
+ }
932
+ const version = arkPackageVersion();
933
+ const gaps = [];
934
+ for (const tool of detected) {
935
+ const target = SKILL_TOOL_TARGETS[tool];
936
+ if (!target) continue;
937
+ let missing = 0;
938
+ let stale = 0;
939
+ for (const name of skillNames) {
940
+ const file = path.join(root, target(name));
941
+ if (!fs.existsSync(file)) {
942
+ missing += 1;
943
+ } else if (version) {
944
+ // An installed skill with no stamp predates stamping (older Ark), or one
945
+ // stamped behind the current version is left over from an older install.
946
+ // Either way the shipped skill has moved on — offer a --force refresh.
947
+ const installed = installedSkillVersion(file);
948
+ if (installed === null || isVersionOlder(installed, version)) stale += 1;
949
+ }
950
+ }
951
+ if (missing > 0 || stale > 0) gaps.push({ tool, missing, stale });
952
+ }
953
+ return gaps;
954
+ }
955
+
956
+ // Files carrying an emitted Ark command whose runner (npx / pnpm exec / yarn) should match
957
+ // the project's package manager. .mcp.json / .cursor/mcp.json hold it structurally
958
+ // (command/args); the rest hold it as text ("npx ark-check …", incl. .claude/settings.json
959
+ // hook strings and the package.json check:architecture script).
960
+ const COMMAND_GATE_TEXT_FILES = [
961
+ '.claude/settings.json', 'AGENTS.md', '.cursor/rules/ark.mdc', '.windsurf/rules/ark.md',
962
+ '.clinerules/ark.md', '.github/copilot-instructions.md', '.kiro/steering/ark.md',
963
+ '.roo/rules/ark.md', '.continue/rules/ark.md', 'GEMINI.md', 'package.json',
964
+ '.grok/hooks/ark-write-gate.json', '.grok/config.toml',
965
+ ];
966
+ const COMMAND_GATE_JSON_FILES = ['.mcp.json', '.cursor/mcp.json'];
967
+ // Primary CLI names (product) + one-major aliases. migrate-commands must strip ALL of these
968
+ // before re-emitting a single preferred bin — otherwise a partial rename leaves
969
+ // args: ["ark-mcp", "arkgate-mcp", ...] which breaks stdio MCP hosts.
970
+ const ARK_MCP_BINS = new Set(['arkgate-mcp', 'ark-mcp']);
971
+ const ARK_CHECK_BINS = new Set(['arkgate-check', 'ark-check']);
972
+ const ARK_CLI_BINS = new Set(['arkgate', 'ark']);
973
+ const PREFERRED_MCP_BIN = 'arkgate-mcp';
974
+ const PREFERRED_CHECK_BIN = 'arkgate-check';
975
+ const PREFERRED_CLI_BIN = 'arkgate';
976
+ // Runner argv noise that is not a bin argument (pnpm exec form).
977
+ const MCP_RUNNER_ARGV = new Set(['exec', '--config.verify-deps-before-run=false']);
978
+ // The runner token immediately before an ark command in a text command string.
979
+ // Matches npm/yarn runners and both pnpm forms (legacy `pnpm exec` + verify-deps-safe form).
980
+ // Longer bin names first so `arkgate-check` is not partially matched as `ark`.
981
+ const RUNNER_BEFORE_ARK =
982
+ /\b(?:npx|pnpm --config\.verify-deps-before-run=false exec|pnpm exec|yarn)(?= (?:arkgate-check|arkgate-mcp|arkgate|ark-check|ark-mcp|ark)\b)/g;
983
+
984
+ /** Keep only MCP server flags from existing args (drop runner tokens + any ark* bin names). */
985
+ export function stripMcpServerArgs(args) {
986
+ if (!Array.isArray(args) || args.length === 0) {
987
+ return ['--root', '.', '--config', 'ark.config.json'];
988
+ }
989
+ const kept = args.filter(
990
+ (entry) =>
991
+ typeof entry === 'string' &&
992
+ !MCP_RUNNER_ARGV.has(entry) &&
993
+ !ARK_MCP_BINS.has(entry) &&
994
+ !ARK_CHECK_BINS.has(entry) &&
995
+ !ARK_CLI_BINS.has(entry)
996
+ );
997
+ return kept.length > 0 ? kept : ['--root', '.', '--config', 'ark.config.json'];
998
+ }
999
+
1000
+ /** True when mcpServers.ark.args list more than one Ark MCP bin (broken dual rename). */
1001
+ export function mcpArgsHaveDuplicateBins(args) {
1002
+ if (!Array.isArray(args)) return false;
1003
+ const hits = args.filter((entry) => ARK_MCP_BINS.has(entry));
1004
+ return hits.length > 1 || (hits.length === 1 && args.indexOf(hits[0]) !== args.lastIndexOf(hits[0]));
1005
+ }
1006
+
1007
+ export function brokenMcpGateFiles(root) {
1008
+ const bad = [];
1009
+ for (const rel of COMMAND_GATE_JSON_FILES) {
1010
+ let json;
1011
+ try {
1012
+ json = JSON.parse(fs.readFileSync(path.join(root, rel), 'utf8'));
1013
+ } catch {
1014
+ continue;
1015
+ }
1016
+ const ark = json?.mcpServers?.ark;
1017
+ if (ark && mcpArgsHaveDuplicateBins(ark.args)) bad.push(rel);
1018
+ }
1019
+ return bad;
1020
+ }
1021
+
1022
+ /** Core layers whose optionality matters once they match files (presets share these names). */
1023
+ const CORE_LAYER_NAMES = new Set([
1024
+ 'DomainModel',
1025
+ 'ApplicationOrchestration',
1026
+ 'PresentationAdapters',
1027
+ 'PersistenceAdapters',
1028
+ ]);
1029
+
1030
+ /** Temp / upgrade sandbox roots must never remain as Codex MCP --root. */
1031
+ export function isTempOrUpgradeRoot(p) {
1032
+ if (!p || typeof p !== 'string') return false;
1033
+ const n = p.replace(/\\/g, '/');
1034
+ return (
1035
+ /\/var\/folders\//i.test(n) ||
1036
+ /\/tmp\//i.test(n) ||
1037
+ /\/Temp\//i.test(n) ||
1038
+ /ark-upgrade/i.test(n) ||
1039
+ /\/T\/(?:ark-|grok-)/i.test(n) ||
1040
+ /[\\/]AppData[\\/]Local[\\/]Temp[\\/]/i.test(n)
1041
+ );
1042
+ }
1043
+
1044
+ /** Extract --root value from Codex [mcp_servers.ark] args array text. */
1045
+ export function extractCodexArkRootFromToml(tomlText) {
1046
+ if (!tomlText || typeof tomlText !== 'string') return null;
1047
+ const start = tomlText.search(/(^|\n)\[mcp_servers\.ark\]/);
1048
+ if (start < 0) return null;
1049
+ const rest = tomlText.slice(start);
1050
+ const endMatch = rest.slice(1).search(/\n\[/);
1051
+ const block = endMatch >= 0 ? rest.slice(0, endMatch + 1) : rest;
1052
+ // args = ["arkgate-mcp", "--root", "/abs/path", ...]
1053
+ const rootIdx = block.search(/"--root"\s*,\s*"/);
1054
+ if (rootIdx < 0) {
1055
+ // alternate: --root as adjacent string after any bin
1056
+ const m = block.match(/"--root"\s*,\s*"([^"]+)"/);
1057
+ return m ? m[1] : null;
1058
+ }
1059
+ const m = block.slice(rootIdx).match(/"--root"\s*,\s*"([^"]+)"/);
1060
+ return m ? m[1] : null;
1061
+ }
1062
+
1063
+ export function codexArkBlockHasPreferredBin(tomlText) {
1064
+ if (!tomlText) return false;
1065
+ const start = tomlText.search(/(^|\n)\[mcp_servers\.ark\]/);
1066
+ if (start < 0) return false;
1067
+ const rest = tomlText.slice(start);
1068
+ const endMatch = rest.slice(1).search(/\n\[/);
1069
+ const block = endMatch >= 0 ? rest.slice(0, endMatch + 1) : rest;
1070
+ const bins = [...block.matchAll(/"(arkgate-mcp|ark-mcp)"/g)].map((m) => m[1]);
1071
+ if (bins.length > 1) return false;
1072
+ return bins.length === 1 && bins[0] === PREFERRED_MCP_BIN;
1073
+ }
1074
+
1075
+ /**
1076
+ * True when the primary [mcp_servers.ark] block is broken (temp root / dual bin)
1077
+ * and should be rewritten fail-closed. Different permanent project roots are NOT
1078
+ * "broken" — multi-project wiring uses a secondary table instead.
1079
+ */
1080
+ export function codexArkBlockNeedsRewrite(tomlText, absRoot) {
1081
+ if (!tomlText || !tomlText.includes('[mcp_servers.ark]')) return true;
1082
+ const rootArg = extractCodexArkRootFromToml(tomlText);
1083
+ if (!rootArg || isTempOrUpgradeRoot(rootArg)) return true;
1084
+ // Permanent different project: multi-project path handles this (do not steal primary).
1085
+ try {
1086
+ if (path.resolve(rootArg) !== path.resolve(absRoot)) {
1087
+ if (!isTempOrUpgradeRoot(rootArg)) return false;
1088
+ return true;
1089
+ }
1090
+ } catch {
1091
+ return true;
1092
+ }
1093
+ if (!codexArkBlockHasPreferredBin(tomlText)) return true;
1094
+ return false;
1095
+ }
1096
+
1097
+ /**
1098
+ * Production deploy path quality (universal — any consumer repo).
1099
+ * Detects when the production build host runs ESLint / typecheck as part of
1100
+ * `build` (e.g. Next.js "Linting and checking validity of types") so failures
1101
+ * surface first on Vercel/Netlify/etc. unless CI/pre-merge runs the same checks.
1102
+ * Framework signals only (deps + scripts + config) — never project-specific.
1103
+ *
1104
+ * @returns {{
1105
+ * embedsLintInBuild: boolean,
1106
+ * embedsTypecheckInBuild: boolean,
1107
+ * engines: string[],
1108
+ * hasLintScript: boolean,
1109
+ * hasTypecheckScript: boolean,
1110
+ * ciRunsLint: boolean,
1111
+ * ciRunsTypecheck: boolean,
1112
+ * eslintIgnoreDuringBuilds: boolean,
1113
+ * }}
1114
+ */
1115
+ export function detectDeployPathQuality(root) {
1116
+ const pkg = readPackageJson(root) || {};
1117
+ const deps = {
1118
+ ...(pkg.dependencies && typeof pkg.dependencies === 'object' ? pkg.dependencies : {}),
1119
+ ...(pkg.devDependencies && typeof pkg.devDependencies === 'object' ? pkg.devDependencies : {}),
1120
+ ...(pkg.peerDependencies && typeof pkg.peerDependencies === 'object' ? pkg.peerDependencies : {}),
1121
+ };
1122
+ const scripts =
1123
+ pkg.scripts && typeof pkg.scripts === 'object' ? pkg.scripts : {};
1124
+ const buildScript = typeof scripts.build === 'string' ? scripts.build : '';
1125
+
1126
+ const engines = [];
1127
+ // Next.js production build runs ESLint + typecheck by default (unless opted out).
1128
+ if (deps.next || /\bnext\s+build\b/.test(buildScript)) engines.push('next');
1129
+ // Nuxt 3+ can lint via modules; only flag when build clearly invokes nuxt build + eslint tooling present.
1130
+ if ((deps.nuxt || deps['nuxt3'] || /\bnuxt\s+build\b/.test(buildScript)) && (deps.eslint || hasEslintConfig(root))) {
1131
+ engines.push('nuxt');
1132
+ }
1133
+ // Create React App historically failed build on ESLint errors.
1134
+ if (deps['react-scripts'] || /\breact-scripts\s+build\b/.test(buildScript)) engines.push('cra');
1135
+
1136
+ const eslintIgnoreDuringBuilds = engines.includes('next') && nextIgnoresEslintDuringBuilds(root);
1137
+ const embedsLintInBuild = engines.length > 0 && !eslintIgnoreDuringBuilds;
1138
+ // Next still typechecks during build even when eslint.ignoreDuringBuilds is true.
1139
+ const embedsTypecheckInBuild = engines.includes('next') || engines.includes('nuxt');
1140
+
1141
+ const scriptHasLint = (s) =>
1142
+ Boolean(
1143
+ s &&
1144
+ ((typeof s.lint === 'string' && s.lint.trim()) ||
1145
+ (typeof s.eslint === 'string' && s.eslint.trim()) ||
1146
+ (typeof s['lint:ci'] === 'string' && s['lint:ci'].trim()) ||
1147
+ (typeof s['check:lint'] === 'string' && s['check:lint'].trim()))
1148
+ );
1149
+ const scriptHasTypecheck = (s) =>
1150
+ Boolean(
1151
+ s &&
1152
+ ((typeof s.typecheck === 'string' && s.typecheck.trim()) ||
1153
+ (typeof s['type-check'] === 'string' && s['type-check'].trim()) ||
1154
+ (typeof s['check:types'] === 'string' && s['check:types'].trim()) ||
1155
+ (typeof s.tsc === 'string' && /\btsc\b/.test(s.tsc)))
1156
+ );
1157
+
1158
+ let hasLintScript = scriptHasLint(scripts);
1159
+ let hasTypecheckScript = scriptHasTypecheck(scripts);
1160
+ const packageLintScripts = [];
1161
+ // Monorepo: package-level scripts count (apps/web, packages/ui, …).
1162
+ try {
1163
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
1164
+ if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === 'node_modules') continue;
1165
+ const candidates = [path.join(root, entry.name)];
1166
+ // one more level: packages/foo
1167
+ try {
1168
+ for (const child of fs.readdirSync(path.join(root, entry.name), { withFileTypes: true })) {
1169
+ if (child.isDirectory() && !child.name.startsWith('.')) {
1170
+ candidates.push(path.join(root, entry.name, child.name));
1171
+ }
1172
+ }
1173
+ } catch {
1174
+ /* ignore */
1175
+ }
1176
+ for (const dir of candidates) {
1177
+ const pj = path.join(dir, 'package.json');
1178
+ if (!fs.existsSync(pj)) continue;
1179
+ try {
1180
+ const nested = JSON.parse(fs.readFileSync(pj, 'utf8'));
1181
+ const ns = nested.scripts && typeof nested.scripts === 'object' ? nested.scripts : {};
1182
+ if (scriptHasLint(ns)) {
1183
+ hasLintScript = true;
1184
+ packageLintScripts.push(path.relative(root, dir).split(path.sep).join('/'));
1185
+ }
1186
+ if (scriptHasTypecheck(ns)) hasTypecheckScript = true;
1187
+ const nd = {
1188
+ ...(nested.dependencies || {}),
1189
+ ...(nested.devDependencies || {}),
1190
+ };
1191
+ if (nd.next && !engines.includes('next')) engines.push('next');
1192
+ } catch {
1193
+ /* ignore */
1194
+ }
1195
+ }
1196
+ }
1197
+ } catch {
1198
+ /* ignore */
1199
+ }
1200
+
1201
+ const ciTexts = collectCiWorkflowTexts(root);
1202
+ const ciJoined = ciTexts.join('\n');
1203
+ const ciRunsLint =
1204
+ ciTexts.length > 0 &&
1205
+ (/\bnpm\s+run\s+lint\b/i.test(ciJoined) ||
1206
+ /\bpnpm\s+(?:run\s+)?lint\b/i.test(ciJoined) ||
1207
+ /\byarn\s+(?:run\s+)?lint\b/i.test(ciJoined) ||
1208
+ /\bbun\s+run\s+lint\b/i.test(ciJoined) ||
1209
+ /\beslint\b/i.test(ciJoined) ||
1210
+ /\blint:ci\b/i.test(ciJoined) ||
1211
+ /\bcheck:lint\b/i.test(ciJoined) ||
1212
+ // package-level: working-directory + lint, or path/filter lint
1213
+ (packageLintScripts.length > 0 &&
1214
+ packageLintScripts.some((p) => ciJoined.includes(p) && /lint/i.test(ciJoined))));
1215
+ const ciRunsTypecheck =
1216
+ ciTexts.length > 0 &&
1217
+ (/\btypecheck\b/i.test(ciJoined) ||
1218
+ /\btype-check\b/i.test(ciJoined) ||
1219
+ /\bcheck:types\b/i.test(ciJoined) ||
1220
+ /\btsc\s+--noEmit\b/i.test(ciJoined));
1221
+
1222
+ return {
1223
+ embedsLintInBuild,
1224
+ embedsTypecheckInBuild,
1225
+ engines,
1226
+ hasLintScript,
1227
+ hasTypecheckScript,
1228
+ ciRunsLint,
1229
+ ciRunsTypecheck,
1230
+ eslintIgnoreDuringBuilds,
1231
+ hasCiWorkflows: ciTexts.length > 0,
1232
+ packageLintScripts,
1233
+ };
1234
+ }
1235
+
1236
+ function hasEslintConfig(root) {
1237
+ return [
1238
+ 'eslint.config.mjs',
1239
+ 'eslint.config.js',
1240
+ 'eslint.config.cjs',
1241
+ 'eslint.config.ts',
1242
+ '.eslintrc.json',
1243
+ '.eslintrc.cjs',
1244
+ '.eslintrc.js',
1245
+ '.eslintrc.yml',
1246
+ '.eslintrc.yaml',
1247
+ ].some((f) => fs.existsSync(path.join(root, f)));
1248
+ }
1249
+
1250
+ /** next.config.* eslint.ignoreDuringBuilds: true → production build will not fail on ESLint. */
1251
+ function nextIgnoresEslintDuringBuilds(root) {
1252
+ const names = [
1253
+ 'next.config.ts',
1254
+ 'next.config.mts',
1255
+ 'next.config.js',
1256
+ 'next.config.mjs',
1257
+ 'next.config.cjs',
1258
+ ];
1259
+ for (const name of names) {
1260
+ const file = path.join(root, name);
1261
+ if (!fs.existsSync(file)) continue;
1262
+ try {
1263
+ const text = fs.readFileSync(file, 'utf8');
1264
+ // Common patterns: ignoreDuringBuilds: true | ignoreDuringBuilds: true,
1265
+ if (/ignoreDuringBuilds\s*:\s*true/.test(text)) return true;
1266
+ } catch {
1267
+ /* ignore */
1268
+ }
1269
+ }
1270
+ return false;
1271
+ }
1272
+
1273
+ function collectCiWorkflowTexts(root) {
1274
+ const texts = [];
1275
+ const pushFile = (rel) => {
1276
+ try {
1277
+ const full = path.join(root, rel);
1278
+ if (fs.existsSync(full) && fs.statSync(full).isFile()) {
1279
+ texts.push(fs.readFileSync(full, 'utf8'));
1280
+ }
1281
+ } catch {
1282
+ /* ignore */
1283
+ }
1284
+ };
1285
+ pushFile('.gitlab-ci.yml');
1286
+ pushFile('bitbucket-pipelines.yml');
1287
+ pushFile('azure-pipelines.yml');
1288
+ pushFile('.circleci/config.yml');
1289
+ const wfDir = path.join(root, '.github', 'workflows');
1290
+ try {
1291
+ if (fs.existsSync(wfDir)) {
1292
+ for (const f of fs.readdirSync(wfDir)) {
1293
+ if (!/\.ya?ml$/i.test(f)) continue;
1294
+ pushFile(path.join('.github', 'workflows', f));
1295
+ }
1296
+ }
1297
+ } catch {
1298
+ /* ignore */
1299
+ }
1300
+ return texts;
1301
+ }
1302
+
1303
+ /**
1304
+ * Adoption completeness (separate from 0–100 fitness). Pure-ish: filesystem + config.
1305
+ * @returns {{ gaps: object[], hosts: object[], mcp: object, codexHome: object|null, coreOptional: object[], originReport: object, baseline: object, layerBalance: object|null, deployPath: object|null }}
1306
+ */
1307
+ export function collectAdoptionGaps(root, config, coverage) {
1308
+ const gaps = [];
1309
+ const adopted = fs.existsSync(path.join(root, 'AGENTS.md'));
1310
+ const isProducer = fs.existsSync(path.join(root, 'templates', 'skills'));
1311
+
1312
+ // --- Repo MCP dual-bin ---
1313
+ const dualMcp = brokenMcpGateFiles(root);
1314
+ const mcp = {
1315
+ dualBinFiles: dualMcp,
1316
+ ok: dualMcp.length === 0,
1317
+ };
1318
+ if (dualMcp.length > 0) {
1319
+ gaps.push({
1320
+ id: 'mcp-dual-bin',
1321
+ severity: 'warn',
1322
+ message: `Broken MCP argv in ${dualMcp.join(', ')}: more than one of ark-mcp/arkgate-mcp`,
1323
+ fix: arkCommand(root, 'ark-check', '--install-agent-gates --migrate-commands'),
1324
+ });
1325
+ }
1326
+
1327
+ // --- Host completeness (only when project already adopted gates) ---
1328
+ const hosts = [];
1329
+ if (adopted && !isProducer) {
1330
+ const skillNames = skillTemplateNames();
1331
+ const hostChecks = [
1332
+ {
1333
+ host: 'grok',
1334
+ dir: '.grok',
1335
+ skill: (n) => path.join(root, '.grok', 'skills', n, 'SKILL.md'),
1336
+ extras: [
1337
+ ['.grok/hooks/ark-write-gate.json', 'write-gate hook'],
1338
+ ['.grok/config.toml', 'project MCP config'],
1339
+ ],
1340
+ toolsFlag: 'grok',
1341
+ },
1342
+ {
1343
+ host: 'claude',
1344
+ dir: '.claude',
1345
+ skill: (n) => path.join(root, '.claude', 'skills', n, 'SKILL.md'),
1346
+ extras: [['.claude/settings.json', 'settings/hooks']],
1347
+ toolsFlag: 'claude',
1348
+ },
1349
+ {
1350
+ host: 'cursor',
1351
+ dir: '.cursor',
1352
+ skill: (n) => path.join(root, '.cursor', 'commands', `${n}.md`),
1353
+ extras: [['.cursor/mcp.json', 'MCP config']],
1354
+ toolsFlag: 'cursor',
1355
+ },
1356
+ ];
1357
+ for (const h of hostChecks) {
1358
+ if (!fs.existsSync(path.join(root, h.dir))) continue;
1359
+ const missingSkills = skillNames.filter((n) => !fs.existsSync(h.skill(n)));
1360
+ const missingExtras = h.extras.filter(([rel]) => !fs.existsSync(path.join(root, rel)));
1361
+ const complete = missingSkills.length === 0 && missingExtras.length === 0;
1362
+ hosts.push({
1363
+ host: h.host,
1364
+ present: true,
1365
+ complete,
1366
+ missingSkills: missingSkills.length,
1367
+ missingExtras: missingExtras.map(([, label]) => label),
1368
+ });
1369
+ if (!complete) {
1370
+ gaps.push({
1371
+ id: `host-${h.host}-incomplete`,
1372
+ severity: 'warn',
1373
+ message: `${h.host} dir present but incomplete (${missingSkills.length} skill(s) missing${
1374
+ missingExtras.length ? `; missing ${missingExtras.map(([, l]) => l).join(', ')}` : ''
1375
+ })`,
1376
+ fix: arkCommand(
1377
+ root,
1378
+ 'ark-check',
1379
+ `--install-agent-gates --tools ${h.toolsFlag} --force`
1380
+ ),
1381
+ });
1382
+ }
1383
+ }
1384
+ }
1385
+
1386
+ // --- Codex home MCP (temp path / wrong root / dual bin) ---
1387
+ let codexHome = null;
1388
+ if (adopted && !isProducer) {
1389
+ const codexFile = codexConfigPath();
1390
+ let toml = '';
1391
+ try {
1392
+ if (fs.existsSync(codexFile)) toml = fs.readFileSync(codexFile, 'utf8');
1393
+ } catch {
1394
+ toml = '';
1395
+ }
1396
+ if (toml.includes('[mcp_servers.ark]')) {
1397
+ const rootArg = extractCodexArkRootFromToml(toml);
1398
+ const absRoot = path.resolve(root);
1399
+ const temp = isTempOrUpgradeRoot(rootArg);
1400
+ let wrongRoot = false;
1401
+ try {
1402
+ wrongRoot = rootArg ? path.resolve(rootArg) !== absRoot : true;
1403
+ } catch {
1404
+ wrongRoot = true;
1405
+ }
1406
+ const preferredBin = codexArkBlockHasPreferredBin(toml);
1407
+ const needsRewrite = codexArkBlockNeedsRewrite(toml, absRoot);
1408
+ codexHome = {
1409
+ file: codexFile,
1410
+ root: rootArg,
1411
+ tempPath: temp,
1412
+ wrongRoot,
1413
+ preferredBin,
1414
+ needsRewrite,
1415
+ };
1416
+ if (needsRewrite) {
1417
+ gaps.push({
1418
+ id: 'codex-home-mcp',
1419
+ severity: temp || wrongRoot ? 'warn' : 'info',
1420
+ message: temp
1421
+ ? `Codex home MCP --root points at a temp/upgrade path (${rootArg})`
1422
+ : wrongRoot
1423
+ ? `Codex home MCP --root is not this project (${rootArg || 'missing'} ≠ ${absRoot})`
1424
+ : `Codex home MCP should use a single ${PREFERRED_MCP_BIN} bin with absolute project paths`,
1425
+ fix: arkCommand(
1426
+ root,
1427
+ 'ark-check',
1428
+ '--install-agent-gates --codex-home --force'
1429
+ ),
1430
+ });
1431
+ }
1432
+ }
1433
+ }
1434
+
1435
+ // --- Core layers optional but populated ---
1436
+ const coreOptional = [];
1437
+ const layerRows = coverage?.layers ?? [];
1438
+ const countByName = new Map(layerRows.map((r) => [r.name, r.files]));
1439
+ for (const layer of config?.layers ?? []) {
1440
+ if (!CORE_LAYER_NAMES.has(layer.name)) continue;
1441
+ if (layer.optional !== true) continue;
1442
+ const files = countByName.get(layer.name) ?? 0;
1443
+ if (files > 0) {
1444
+ coreOptional.push({ layer: layer.name, files });
1445
+ gaps.push({
1446
+ id: `core-optional-${layer.name}`,
1447
+ severity: 'info',
1448
+ message: `Core layer ${layer.name} has ${files} file(s) but is still optional: true — contract is weaker than the tree`,
1449
+ fix: `Edit ark.config.json: remove optional on ${layer.name} (or set false), then ${arkCommand(root, 'ark-check', '--strict-config')}`,
1450
+ });
1451
+ }
1452
+ }
1453
+
1454
+ // --- Origin report ---
1455
+ const originJson = path.join(root, '.ark', 'reports', 'origin.json');
1456
+ const originReport = {
1457
+ present: fs.existsSync(originJson),
1458
+ path: '.ark/reports/origin.json',
1459
+ };
1460
+ if (adopted && !originReport.present && (coverage?.governed?.percent ?? 0) >= 50) {
1461
+ gaps.push({
1462
+ id: 'origin-report-missing',
1463
+ severity: 'info',
1464
+ message: 'No origin architecture snapshot under .ark/reports/ yet',
1465
+ fix: arkCommand(root, 'ark-check', '--report ark-report.html'),
1466
+ });
1467
+ }
1468
+
1469
+ // --- Baseline policy ---
1470
+ const baselinePath = path.join(root, '.ark-baseline.json');
1471
+ const baselineExists = fs.existsSync(baselinePath);
1472
+ let frozenKeys = 0;
1473
+ if (baselineExists) {
1474
+ try {
1475
+ const raw = JSON.parse(fs.readFileSync(baselinePath, 'utf8'));
1476
+ frozenKeys = Array.isArray(raw.violations) ? raw.violations.length : 0;
1477
+ } catch {
1478
+ frozenKeys = 0;
1479
+ }
1480
+ }
1481
+ let primaryPathUsesBaseline = false;
1482
+ try {
1483
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
1484
+ const scripts = pkg.scripts && typeof pkg.scripts === 'object' ? pkg.scripts : {};
1485
+ primaryPathUsesBaseline = Object.values(scripts).some(
1486
+ (s) => typeof s === 'string' && s.includes('--baseline')
1487
+ );
1488
+ } catch {
1489
+ /* no package.json */
1490
+ }
1491
+ if (!primaryPathUsesBaseline) {
1492
+ try {
1493
+ const wfDir = path.join(root, '.github', 'workflows');
1494
+ if (fs.existsSync(wfDir)) {
1495
+ for (const f of fs.readdirSync(wfDir)) {
1496
+ if (!/\.ya?ml$/i.test(f)) continue;
1497
+ const text = fs.readFileSync(path.join(wfDir, f), 'utf8');
1498
+ if (text.includes('--baseline') && (text.includes('ark-check') || text.includes('arkgate-check'))) {
1499
+ primaryPathUsesBaseline = true;
1500
+ break;
1501
+ }
1502
+ }
1503
+ }
1504
+ } catch {
1505
+ /* ignore */
1506
+ }
1507
+ }
1508
+ const baseline = {
1509
+ exists: baselineExists,
1510
+ frozenKeys,
1511
+ primaryPathUsesBaseline,
1512
+ signal: baselineExists
1513
+ ? frozenKeys === 0
1514
+ ? 'keep-empty'
1515
+ : 'active-ratchet'
1516
+ : 'absent',
1517
+ };
1518
+ if (adopted && baselineExists && frozenKeys === 0 && !primaryPathUsesBaseline) {
1519
+ gaps.push({
1520
+ id: 'baseline-unused',
1521
+ severity: 'info',
1522
+ message:
1523
+ 'Empty .ark-baseline.json exists but primary scripts/CI do not pass --baseline (policy unclear)',
1524
+ fix: 'Either add --baseline .ark-baseline.json to check:architecture / CI, or remove the unused baseline file',
1525
+ });
1526
+ }
1527
+
1528
+ // --- Educational layer balance (not a violation) ---
1529
+ let layerBalance = null;
1530
+ const total = layerRows.reduce((s, r) => s + (r.files || 0), 0);
1531
+ if (total >= 20) {
1532
+ const presentation = layerRows.find((r) => r.name === 'PresentationAdapters');
1533
+ const domain = layerRows.find((r) => r.name === 'DomainModel');
1534
+ if (presentation && domain) {
1535
+ const pShare = presentation.files / total;
1536
+ const dShare = domain.files / total;
1537
+ if (pShare >= 0.5 && dShare < 0.1) {
1538
+ layerBalance = {
1539
+ kind: 'presentation-heavy-thin-domain',
1540
+ presentationFiles: presentation.files,
1541
+ domainFiles: domain.files,
1542
+ totalFiles: total,
1543
+ educational:
1544
+ 'Presentation holds most of the tree while DomainModel is thin — common for UI apps; consider extracting domain types/use-cases as the product grows. Educational only (not a gate failure).',
1545
+ };
1546
+ }
1547
+ }
1548
+ }
1549
+
1550
+ // --- Empty scope: contract matches no TS/JS ---
1551
+ if (!isProducer && (coverage?.governed?.totalFiles ?? coverage?.totalFiles) === 0) {
1552
+ gaps.push({
1553
+ id: 'empty-scope',
1554
+ severity: 'warn',
1555
+ message:
1556
+ 'Empty scope: include paths match 0 TypeScript/JS files — checks are not governing this tree',
1557
+ fix: `${arkCommand(root, 'ark-check', '--suggest-include')} then ${arkCommand(root, 'ark-check', '--adopt-contract --write')}`,
1558
+ });
1559
+ }
1560
+
1561
+ // --- Deploy-path quality (ESLint/types that production build hosts run) ---
1562
+ // Universal: any Next/CRA/Nuxt (etc.) consumer. Not architecture — still adoption.
1563
+ // Skip pure library producer (this monorepo) to avoid self-noise.
1564
+ let deployPath = null;
1565
+ if (!isProducer) {
1566
+ deployPath = detectDeployPathQuality(root);
1567
+ const eng =
1568
+ deployPath.engines.length > 0 ? deployPath.engines.join('/') : 'production';
1569
+ if (deployPath.embedsLintInBuild && !deployPath.hasLintScript) {
1570
+ gaps.push({
1571
+ id: 'deploy-path-lint-script-missing',
1572
+ severity: 'warn',
1573
+ message: `${eng} production build runs ESLint — no package.json lint script, so failures often surface first on the deploy host`,
1574
+ fix: 'Add a package.json "lint" script (e.g. eslint .) matching production ESLint config; run it in CI and before merge',
1575
+ });
1576
+ } else if (
1577
+ deployPath.embedsLintInBuild &&
1578
+ deployPath.hasLintScript &&
1579
+ deployPath.hasCiWorkflows &&
1580
+ !deployPath.ciRunsLint
1581
+ ) {
1582
+ gaps.push({
1583
+ id: 'deploy-path-lint-not-in-ci',
1584
+ severity: 'warn',
1585
+ message: `${eng} production build runs ESLint — CI workflows exist but do not run lint, so deploy hosts may be the first fail`,
1586
+ fix: 'Add a CI step that runs your package.json lint script (npm run lint / pnpm lint / yarn lint) and require it before deploy',
1587
+ });
1588
+ } else if (
1589
+ deployPath.embedsLintInBuild &&
1590
+ deployPath.hasLintScript &&
1591
+ !deployPath.hasCiWorkflows
1592
+ ) {
1593
+ gaps.push({
1594
+ id: 'deploy-path-lint-no-ci',
1595
+ severity: 'info',
1596
+ message: `${eng} production build runs ESLint — no CI workflows detected; push-to-host builds may be the first lint fail`,
1597
+ fix: 'Add CI (or a pre-push hook) that runs lint before the deploy host builds; keep branch protection required when using GitHub',
1598
+ });
1599
+ }
1600
+
1601
+ if (deployPath.embedsTypecheckInBuild && !deployPath.hasTypecheckScript) {
1602
+ gaps.push({
1603
+ id: 'deploy-path-typecheck-script-missing',
1604
+ severity: 'info',
1605
+ message: `${eng} production build typechecks — no package.json typecheck script for local/CI parity`,
1606
+ fix: 'Add "typecheck": "tsc --noEmit" (or framework equivalent) and run it in CI alongside lint',
1607
+ });
1608
+ } else if (
1609
+ deployPath.embedsTypecheckInBuild &&
1610
+ deployPath.hasTypecheckScript &&
1611
+ deployPath.hasCiWorkflows &&
1612
+ !deployPath.ciRunsTypecheck
1613
+ ) {
1614
+ gaps.push({
1615
+ id: 'deploy-path-typecheck-not-in-ci',
1616
+ severity: 'info',
1617
+ message: `${eng} production build typechecks — CI does not run typecheck; type errors may appear first on the deploy host`,
1618
+ fix: 'Add a CI step for npm run typecheck (or your typecheck script) and require it before deploy',
1619
+ });
1620
+ }
1621
+ }
1622
+
1623
+ return {
1624
+ gaps,
1625
+ hosts,
1626
+ mcp,
1627
+ codexHome,
1628
+ coreOptional,
1629
+ originReport,
1630
+ baseline,
1631
+ layerBalance,
1632
+ deployPath,
1633
+ };
1634
+ }
1635
+
1636
+ // Gate files whose Ark command runner doesn't match this project's package manager — the
1637
+ // advisory (and --migrate-commands) target. Returns [] for npm/unknown projects (npx is right)
1638
+ // so the check is silent unless there's a real mismatch.
1639
+ export function staleRunnerGateFiles(root) {
1640
+ const want = execRunner(root);
1641
+ if (want === 'npx') return [];
1642
+ const stale = [];
1643
+ for (const rel of COMMAND_GATE_TEXT_FILES) {
1644
+ let text;
1645
+ try {
1646
+ text = fs.readFileSync(path.join(root, rel), 'utf8');
1647
+ } catch {
1648
+ continue;
1649
+ }
1650
+ RUNNER_BEFORE_ARK.lastIndex = 0;
1651
+ let match;
1652
+ while ((match = RUNNER_BEFORE_ARK.exec(text))) {
1653
+ if (match[0] !== want) {
1654
+ stale.push(rel);
1655
+ break;
1656
+ }
1657
+ }
1658
+ }
1659
+ for (const rel of COMMAND_GATE_JSON_FILES) {
1660
+ let json;
1661
+ try {
1662
+ json = JSON.parse(fs.readFileSync(path.join(root, rel), 'utf8'));
1663
+ } catch {
1664
+ continue;
1665
+ }
1666
+ const ark = json?.mcpServers?.ark;
1667
+ if (ark && ark.command && ark.command !== want.split(' ')[0]) stale.push(rel);
1668
+ }
1669
+ return stale;
1670
+ }
1671
+
1672
+ // When more than one lockfile is present the project is ambiguous. detectPackageManager()
1673
+ // resolves it (package-lock.json wins so a stray pnpm-lock.yaml can't hijack an npm project),
1674
+ // but the user should know it happened and how to make it explicit — otherwise a leftover
1675
+ // lockfile silently steers which runner every emitted command uses.
1676
+ export function warnLockfileConflict(root) {
1677
+ const locks = presentLockfiles(root);
1678
+ if (locks.length <= 1) return;
1679
+ const chosen = detectPackageManager(root);
1680
+ const files = { pnpm: 'pnpm-lock.yaml', yarn: 'yarn.lock', npm: 'package-lock.json' };
1681
+ console.log('');
1682
+ console.log(
1683
+ `Note: multiple lockfiles present (${locks.map((pm) => files[pm]).join(', ')}). Treating this`
1684
+ );
1685
+ console.log(
1686
+ `as a ${chosen} project — Ark commands use "${execRunner(root)}". If that's wrong, set`
1687
+ );
1688
+ console.log(
1689
+ '"packageManager" in package.json (e.g. "pnpm@9") to declare it, or remove the stray lockfile.'
1690
+ );
1691
+ }
1692
+
1693
+ // --migrate-commands: rewrite ONLY the Ark command runner in existing gate files to the
1694
+ // project's package manager (no --force clobber). Closes the upgrade gap where a repo that
1695
+ // adopted before the package-manager-aware templates keeps a stale `npx`.
1696
+ // Also normalizes MCP JSON to a single preferred bin (arkgate-mcp), stripping any dual
1697
+ // ark-mcp + arkgate-mcp residue left by partial renames during package identity cutover.
1698
+ export function runMigrateCommands(root) {
1699
+ const runner = execRunner(root);
1700
+ const changed = [];
1701
+ for (const rel of COMMAND_GATE_TEXT_FILES) {
1702
+ const full = path.join(root, rel);
1703
+ let text;
1704
+ try {
1705
+ text = fs.readFileSync(full, 'utf8');
1706
+ } catch {
1707
+ continue;
1708
+ }
1709
+ let next = text.replace(RUNNER_BEFORE_ARK, runner);
1710
+ // Prefer primary product bins in command strings (aliases still work if left alone).
1711
+ next = next
1712
+ .replace(/\bark-mcp\b/g, PREFERRED_MCP_BIN)
1713
+ .replace(/\bark-check\b/g, PREFERRED_CHECK_BIN);
1714
+ // Do not blanket-replace bare `ark` — it appears in prose ("Ark check", product name).
1715
+ if (next !== text) {
1716
+ fs.writeFileSync(full, next);
1717
+ changed.push(rel);
1718
+ }
1719
+ }
1720
+ for (const rel of COMMAND_GATE_JSON_FILES) {
1721
+ const full = path.join(root, rel);
1722
+ let json;
1723
+ try {
1724
+ json = JSON.parse(fs.readFileSync(full, 'utf8'));
1725
+ } catch {
1726
+ continue;
1727
+ }
1728
+ const ark = json?.mcpServers?.ark;
1729
+ if (!ark) continue;
1730
+ const binArgs = stripMcpServerArgs(ark.args);
1731
+ const parts = execCommandParts(root, PREFERRED_MCP_BIN, binArgs);
1732
+ if (ark.command !== parts.command || JSON.stringify(ark.args) !== JSON.stringify(parts.args)) {
1733
+ json.mcpServers.ark = { ...ark, ...parts };
1734
+ fs.writeFileSync(full, `${JSON.stringify(json, null, 2)}\n`);
1735
+ changed.push(rel);
1736
+ }
1737
+ }
1738
+ const pm = runner === 'pnpm exec' || runner.startsWith('pnpm ') ? 'pnpm' : runner;
1739
+ console.log(`Migrated ArkGate command runners to "${pm}" and normalized MCP bins in gate files.`);
1740
+ if (changed.length === 0) {
1741
+ console.log(' Nothing to change — runners and MCP bins already look correct.');
1742
+ } else {
1743
+ for (const rel of changed) console.log(` updated ${rel}`);
1744
+ console.log(
1745
+ ` (runner + single MCP bin \`${PREFERRED_MCP_BIN}\`; customized non-command content is untouched.)`
1746
+ );
1747
+ }
1748
+ warnLockfileConflict(root);
1749
+ }
1750
+
1751
+ export function runInstallAgentGates(args) {
1752
+ const root = args.root;
1753
+ if (args.migrateCommands) {
1754
+ runMigrateCommands(root);
1755
+ return;
1756
+ }
1757
+ if (args.tools != null) {
1758
+ const list = normalizeToolsList(args.tools);
1759
+ args.tools = list;
1760
+ const unknown = list.filter((tool) => !KNOWN_TOOLS.includes(tool));
1761
+ if (list.length === 0 || unknown.length > 0) {
1762
+ console.error(
1763
+ `--tools expects a comma-separated subset of: ${KNOWN_TOOLS.join(', ')}` +
1764
+ (unknown.length > 0 ? ` (unknown: ${unknown.join(', ')})` : '')
1765
+ );
1766
+ process.exitCode = 2;
1767
+ return;
1768
+ }
1769
+ }
1770
+ const pm = packageManager(root);
1771
+ const hasCheckScript = hasCheckArchitectureScript(root);
1772
+ const { tools, source } = resolveTools(args);
1773
+ const toolSource =
1774
+ source === 'explicit'
1775
+ ? 'from --tools'
1776
+ : source === 'detected'
1777
+ ? 'auto-detected from config dirs'
1778
+ : 'default set — no agent config dirs found';
1779
+ console.log(`Agent gates for: ${[...tools].sort().join(', ')} (${toolSource})`);
1780
+ const templates = [];
1781
+ // --skills-only refreshes just the canonical /ark-* skills, which are safe to
1782
+ // overwrite (they track the package). The gate/instruction files (AGENTS.md,
1783
+ // settings.json, CI workflow, rules) are the ones users customize, so a plain
1784
+ // `--force` clobbers them — this is the safe way to pick up new skill versions.
1785
+ if (!args.skillsOnly) {
1786
+ // Base gates: tool-agnostic contract + CI backstop, always written.
1787
+ templates.push(['AGENTS.md', agentInstructions(root)]);
1788
+ templates.push(['.mcp.json', mcpJson(root)]);
1789
+ templates.push([
1790
+ '.github/workflows/ark-check.yml',
1791
+ githubWorkflow(pm, detectCiNode(root)),
1792
+ ]);
1793
+ if (tools.has('cursor')) {
1794
+ templates.push(['.cursor/mcp.json', mcpJson(root)]);
1795
+ templates.push(['.cursor/rules/ark.mdc', cursorRule(root)]);
1796
+ }
1797
+ if (tools.has('claude')) {
1798
+ templates.push(['.claude/settings.json', claudeSettings(root)]);
1799
+ }
1800
+ if (tools.has('codex')) {
1801
+ templates.push(['docs/ark-codex-config.toml', codexTomlSnippet(root)]);
1802
+ }
1803
+ if (tools.has('grok')) {
1804
+ templates.push(['.grok/config.toml', grokProjectConfig(root)]);
1805
+ templates.push(['.grok/hooks/ark-write-gate.json', grokHooks(root)]);
1806
+ }
1807
+ // Instruction-tier hosts: one shared rule text, host-specific path.
1808
+ if (tools.has('windsurf')) {
1809
+ templates.push(['.windsurf/rules/ark.md', instructionRule(root)]);
1810
+ }
1811
+ if (tools.has('cline')) {
1812
+ templates.push(['.clinerules/ark.md', instructionRule(root)]);
1813
+ }
1814
+ if (tools.has('copilot')) {
1815
+ templates.push(['.github/copilot-instructions.md', instructionRule(root)]);
1816
+ }
1817
+ if (tools.has('kiro')) {
1818
+ templates.push(['.kiro/steering/ark.md', instructionRule(root)]);
1819
+ }
1820
+ if (tools.has('roo')) {
1821
+ templates.push(['.roo/rules/ark.md', instructionRule(root)]);
1822
+ }
1823
+ if (tools.has('continue')) {
1824
+ templates.push(['.continue/rules/ark.md', instructionRule(root)]);
1825
+ }
1826
+ // Gemini CLI reads GEMINI.md as its primary project context (it also reads
1827
+ // AGENTS.md, but GEMINI.md wins when both are present), so the rule lives there.
1828
+ if (tools.has('gemini')) {
1829
+ templates.push(['GEMINI.md', instructionRule(root)]);
1830
+ }
1831
+ }
1832
+ // /ark-* skills for every detected tool that supports project-level commands.
1833
+ // Stamp each with the shipping version so a later ark-check can flag skills
1834
+ // left behind by an older Ark (see detectSkillGaps) without nagging about
1835
+ // user edits to the body.
1836
+ const version = arkPackageVersion();
1837
+ const skills = skillTemplates().map(([name, content]) => [name, stampSkill(content, version)]);
1838
+ const skillPaths = new Set();
1839
+ for (const tool of tools) {
1840
+ const target = SKILL_TOOL_TARGETS[tool];
1841
+ if (!target) continue;
1842
+ for (const [name, content] of skills) {
1843
+ const relativePath = target(name);
1844
+ skillPaths.add(relativePath);
1845
+ templates.push([relativePath, content]);
1846
+ }
1847
+ }
1848
+
1849
+ const results = templates.map(([relativePath, content]) =>
1850
+ writeTemplate(root, relativePath, content, args.force)
1851
+ );
1852
+
1853
+ console.log('Ark agent gate templates:');
1854
+ let staleSkipped = 0;
1855
+ for (const result of results) {
1856
+ const marker =
1857
+ result.status === 'written'
1858
+ ? 'wrote'
1859
+ : result.status === 'merged'
1860
+ ? 'merged'
1861
+ : result.status === 'skipped-non-ark'
1862
+ ? 'kept'
1863
+ : result.status === 'failed'
1864
+ ? 'FAILED'
1865
+ : 'skipped';
1866
+ // A skipped skill reads as "you're fine" — but it may be a version behind.
1867
+ // Say which, so the user isn't left guessing (and knows the safe refresh cmd).
1868
+ let note = '';
1869
+ if (result.status === 'skipped' && skillPaths.has(result.relativePath) && version) {
1870
+ const installed = installedSkillVersion(path.join(root, result.relativePath));
1871
+ if (installed === null || isVersionOlder(installed, version)) {
1872
+ staleSkipped += 1;
1873
+ note = ` (stale: ${installed ?? 'no stamp'} < ${version})`;
1874
+ } else {
1875
+ note = ' (up to date)';
1876
+ }
1877
+ }
1878
+ console.log(` ${marker.padEnd(7)} ${result.relativePath}${note}`);
1879
+ }
1880
+ if (staleSkipped > 0 && !args.skillsOnly) {
1881
+ console.log('');
1882
+ console.log(
1883
+ ` ${staleSkipped} skill(s) are outdated but were left untouched. Refresh them with:`
1884
+ );
1885
+ console.log(` ${arkCommand(root, 'ark-check', '--install-agent-gates --skills-only --force')}`);
1886
+ }
1887
+
1888
+ // --codex-home writes the canonical skills straight to $CODEX_HOME/prompts.
1889
+ // Codex reads prompts from there (not the repo), so this is the only way to
1890
+ // refresh them for a repo that isn't itself configured for Codex. It writes to
1891
+ // the user's home dir, hence explicit opt-in rather than part of a normal run.
1892
+ const homeResults = [];
1893
+ if (args.codexHome) {
1894
+ const dir = codexPromptsDir();
1895
+ console.log('');
1896
+ console.log(`Codex home skills (${dir}):`);
1897
+ try {
1898
+ fs.mkdirSync(dir, { recursive: true });
1899
+ } catch (error) {
1900
+ console.error(` FAILED to create ${dir} (${error.message})`);
1901
+ homeResults.push({ status: 'failed' });
1902
+ }
1903
+ if (homeResults.length === 0) {
1904
+ for (const [name, content] of skills) {
1905
+ const file = path.join(dir, `${name}.md`);
1906
+ if (fs.existsSync(file) && !args.force) {
1907
+ const installed = installedSkillVersion(file);
1908
+ const behind = installed === null || (version && isVersionOlder(installed, version));
1909
+ const note = behind
1910
+ ? ` (stale: ${installed ?? 'no stamp'} < ${version}; use --force)`
1911
+ : ' (up to date)';
1912
+ console.log(` ${'skipped'.padEnd(7)} ${name}.md${note}`);
1913
+ homeResults.push({ status: 'skipped' });
1914
+ continue;
1915
+ }
1916
+ try {
1917
+ fs.writeFileSync(file, content);
1918
+ console.log(` ${'wrote'.padEnd(7)} ${name}.md`);
1919
+ homeResults.push({ status: 'written' });
1920
+ } catch (error) {
1921
+ console.log(` ${'FAILED'.padEnd(7)} ${name}.md (${error.message})`);
1922
+ homeResults.push({ status: 'failed' });
1923
+ }
1924
+ }
1925
+ }
1926
+ }
1927
+
1928
+ // Auto-wire the ark MCP server into Codex's home config.toml. Claude and Cursor get
1929
+ // machine-readable registrations (.claude/settings.json, .cursor/mcp.json) written as repo
1930
+ // templates above; Codex reads MCP servers only from ~/.codex/config.toml, so it needs a
1931
+ // home-dir merge instead. Fires whenever Codex is in play so `ark://manifest` is live
1932
+ // without a manual copy step.
1933
+ let codexMcp = null;
1934
+ if (tools.has('codex') || args.codexHome) {
1935
+ codexMcp = wireCodexMcp(root, args.force);
1936
+ console.log('');
1937
+ console.log(`Codex MCP registration (${codexMcp.file}):`);
1938
+ if (codexMcp.status === 'written-multi') {
1939
+ console.log(
1940
+ ` ${'wrote'.padEnd(7)} [mcp_servers.${codexMcp.table}] (multi-project — primary [mcp_servers.ark] left unchanged; --force rebinds primary)`
1941
+ );
1942
+ } else if (codexMcp.status === 'skipped') {
1943
+ console.log(` ${'skipped'.padEnd(7)} [mcp_servers.ark] already present (use --force to overwrite)`);
1944
+ } else if (codexMcp.status === 'failed') {
1945
+ console.log(` ${'FAILED'.padEnd(7)} [mcp_servers.ark] (${codexMcp.message})`);
1946
+ } else {
1947
+ const verb = codexMcp.status === 'updated' ? 'updated' : 'wrote';
1948
+ console.log(` ${verb.padEnd(7)} [mcp_servers.ark] with absolute paths`);
1949
+ console.log(' RESTART Codex — it does not hot-load MCP servers.');
1950
+ console.log(' Then expect: resource ark://manifest + tools validate_code, ark_check, ark_coverage, ark_place.');
1951
+ }
1952
+ }
1953
+
1954
+ const failed = [...results, ...homeResults, ...(codexMcp ? [codexMcp] : [])].filter((result) => result.status === 'failed');
1955
+ if (failed.length > 0) {
1956
+ console.error(`\nFailed to write ${failed.length} template(s).`);
1957
+ process.exitCode = 1;
1958
+ return;
1959
+ }
1960
+ console.log('');
1961
+ console.log('Next steps:');
1962
+ console.log(' 1. Review the generated files and commit the ones that match your tools.');
1963
+ console.log(` 2. Run: ${arkCheckCommand(root)}`);
1964
+ if (!hasCheckScript) {
1965
+ console.log(' 3. Add the package.json alias if you want `run check:architecture`:');
1966
+ console.log(` ${checkArchitectureScriptSnippet(root)}`);
1967
+ }
1968
+ if ((tools.has('codex') || args.codexHome)) {
1969
+ console.log('');
1970
+ if (codexMcp && codexMcp.status !== 'failed') {
1971
+ console.log(` Codex: ark MCP registered in ${codexMcp.file} — restart Codex so \`ark://manifest\` loads.`);
1972
+ }
1973
+ if (args.codexHome) {
1974
+ console.log(` Codex: refreshed the /ark-* skills in ${codexPromptsDir()} — Codex loads them from there.`);
1975
+ } else if (skills.length > 0) {
1976
+ console.log(' Codex loads slash-command prompts from $CODEX_HOME/prompts (~/.codex/prompts),');
1977
+ console.log(' not the repo. Install the /ark-* skills there with:');
1978
+ console.log(` ${arkCommand(root, 'ark-check', '--install-agent-gates --codex-home')}`);
1979
+ console.log(' (writes to your home dir; agents driving this setup should offer to run it).');
1980
+ }
1981
+ }
1982
+ warnLockfileConflict(root);
1983
+ }