@dialecte/cli 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lookups.js CHANGED
@@ -63,6 +63,22 @@ var STOP_WORDS = /* @__PURE__ */ new Set([
63
63
  ]);
64
64
  var CORE_PACKAGE_NAME = "@dialecte/core";
65
65
 
66
+ // src/lib/api/source-functions.constants.ts
67
+ var SOURCE_INDEX_FILE = "dialecte-source-index.json";
68
+ var SOURCE_INDEX_SCHEMA = 1;
69
+ var SOURCE_FOLDER = "src";
70
+ var SOURCE_FILE_PATTERN = /(?<!\.d)\.ts$/;
71
+ var SOURCE_PATH_MARK = "#";
72
+ var INTENT_TAG = "intent";
73
+ var NO_SOURCE_FOLDER_NOTE = "no src/ folder in {root}";
74
+ var NOT_PARSED_NOTE = "{file}: not parsed ({why})";
75
+ var NO_SUMMARY_TEXT = "(no summary)";
76
+ var NOTE_LINE_PREFIX = "note: ";
77
+ var SOURCE_SUGGESTION_LIMIT = 5;
78
+ var UNKNOWN_SOURCE_CLOSEST_TEXT = 'no source function "{path}" in {root} - closest: {closest}';
79
+ var UNKNOWN_SOURCE_TEXT = 'no source function "{path}" in {root}: `npx @dialecte/cli api find --source "<what you need>"` lists them';
80
+ var NO_PACKAGE_TEXT = "{command}: no package at {cwd}: run it inside a package (a folder holding a package.json, or below one)";
81
+
66
82
  // src/lib/api/find-methods.ts
67
83
  function findMethods(params) {
68
84
  const needWords = new Set(wordsOf(params.need));
@@ -91,8 +107,9 @@ function isDefined(value) {
91
107
  function scoreMethod(params) {
92
108
  const { method, needWords } = params;
93
109
  const intentMatches = method.intents.map((intent) => sharedCount({ text: intent, needWords }));
110
+ const intentText = method.root === "source" && method.intents.length === 0 ? `${method.summary ?? ""} ${routeName(method)}` : method.intents.join(" ");
94
111
  const hits = {
95
- intent: sharedCount({ text: method.intents.join(" "), needWords }),
112
+ intent: sharedCount({ text: intentText, needWords }),
96
113
  summary: sharedCount({ text: method.summary ?? "", needWords }),
97
114
  name: sharedCount({ text: routeName(method), needWords })
98
115
  };
@@ -108,12 +125,14 @@ function sharedCount(params) {
108
125
  return new Set(wordsOf(params.text).filter((word) => params.needWords.has(word))).size;
109
126
  }
110
127
  function routeName(method) {
128
+ if (method.root === "source")
129
+ return method.path.slice(method.path.indexOf(SOURCE_PATH_MARK) + SOURCE_PATH_MARK.length);
111
130
  if (method.entry !== void 0 && method.path.startsWith(`${method.entry}.`))
112
131
  return method.path.slice(method.entry.length + 1);
113
132
  return method.path.replace(/^(doc\.query|tx|doc|project)\./, "");
114
133
  }
115
134
  function compareFound(left, right) {
116
- return right.hits.intent - left.hits.intent || right.hits.summary - left.hits.summary || right.hits.name - left.hits.name || Number(left.packageName === CORE_PACKAGE_NAME) - Number(right.packageName === CORE_PACKAGE_NAME) || TEXT_COLLATOR.compare(left.method.path, right.method.path);
135
+ return right.hits.intent - left.hits.intent || right.hits.summary - left.hits.summary || right.hits.name - left.hits.name || Number(left.method.root === "source") - Number(right.method.root === "source") || Number(left.packageName === CORE_PACKAGE_NAME) - Number(right.packageName === CORE_PACKAGE_NAME) || TEXT_COLLATOR.compare(left.method.path, right.method.path);
117
136
  }
118
137
 
119
138
  // src/lib/api/read-api-indexes.ts
@@ -140,11 +159,18 @@ import {
140
159
  unlinkSync,
141
160
  writeFileSync
142
161
  } from "fs";
143
- import { dirname as dirname2, join as join2, parse, relative, resolve } from "path";
162
+ import { dirname as dirname2, join as join2, parse, relative as relative2, resolve } from "path";
144
163
 
145
164
  // src/lib/file-system.ts
146
165
  import { lstatSync, realpathSync, statSync } from "fs";
147
- import { basename, dirname, join } from "path";
166
+ import { basename, dirname, isAbsolute, join, relative, sep } from "path";
167
+ function isFolder(path) {
168
+ try {
169
+ return statSync(path).isDirectory();
170
+ } catch {
171
+ return false;
172
+ }
173
+ }
148
174
 
149
175
  // src/lib/skills/skill-file.ts
150
176
  function readFrontmatter(markdown) {
@@ -337,40 +363,105 @@ function isApiJson(value) {
337
363
  return typeof value === "object" && value !== null && "package" in value && typeof value.package === "string" && "methods" in value && Array.isArray(value.methods);
338
364
  }
339
365
 
366
+ // src/lib/print/print.ts
367
+ import { writeSync } from "fs";
368
+
369
+ // src/lib/print/print.constants.ts
370
+ var DISPLAY_ESCAPED_RANGES = [
371
+ [0, 31],
372
+ [127, 159],
373
+ [1564, 1564],
374
+ [8206, 8207],
375
+ [8232, 8233],
376
+ [8234, 8238],
377
+ [8294, 8297]
378
+ ];
379
+ var ESCAPE_RADIX = 16;
380
+ var LINE_FEED = "\n";
381
+
382
+ // src/lib/print/print.ts
383
+ function escapeControlCharacters(params) {
384
+ return Array.from(params.text, function escapeOf(character) {
385
+ const code = character.codePointAt(0) ?? 0;
386
+ const escaped = DISPLAY_ESCAPED_RANGES.some(([first, last]) => code >= first && code <= last);
387
+ return escaped ? `\\u{${code.toString(ESCAPE_RADIX)}}` : character;
388
+ }).join("");
389
+ }
390
+ function textOf(lines) {
391
+ return lines.map((line) => escapeControlCharacters({ text: line })).join(LINE_FEED);
392
+ }
393
+ function jsonOf(value, indent) {
394
+ return JSON.stringify(value, null, indent);
395
+ }
396
+ function endedOf(text) {
397
+ return `${text}${LINE_FEED}`;
398
+ }
399
+
340
400
  // src/lib/api/short-summary.ts
341
401
  function shortSummary(summary) {
342
- const sentence = summary.match(/^.*?[.!?](?=\s|$)/)?.[0] ?? summary;
402
+ const sentence = firstSentence(summary);
343
403
  return sentence.length > SHORT_SUMMARY_MAX_LENGTH ? `${sentence.slice(0, SHORT_SUMMARY_MAX_LENGTH - 1)}\u2026` : sentence;
344
404
  }
405
+ function firstSentence(text) {
406
+ return text.match(/^.*?[.!?](?=\s|$)/)?.[0] ?? text;
407
+ }
345
408
 
346
409
  // src/lib/api/render-api.ts
347
410
  function renderFound(params) {
348
411
  if (params.json)
349
- return toJson({
350
- need: params.need,
351
- methods: params.found.map((found) => ({
352
- path: found.method.path,
353
- root: found.method.root,
354
- package: found.packageName,
355
- hits: found.hits,
356
- intent: found.matchingIntent,
357
- summary: found.method.summary
358
- }))
359
- });
360
- return params.found.map(
361
- (found) => `${found.method.path} ${found.method.root} ${found.matchingIntent ?? shortSummary(found.method.summary ?? "-")} ${found.packageName}
362
- `
363
- ).join("");
412
+ return endedOf(
413
+ jsonOf(
414
+ {
415
+ need: params.need,
416
+ methods: params.found.map(foundJsonOf),
417
+ ...params.notes === void 0 ? {} : { notes: params.notes }
418
+ },
419
+ " "
420
+ )
421
+ );
422
+ return endedTextOf([...params.found.map(foundRowOf), ...noteLinesOf(params.notes)]);
423
+ }
424
+ function foundJsonOf(found) {
425
+ const row = {
426
+ path: found.method.path,
427
+ root: found.method.root,
428
+ package: found.packageName,
429
+ hits: found.hits,
430
+ intent: found.matchingIntent,
431
+ summary: found.method.summary
432
+ };
433
+ return found.method.root === "source" ? { ...row, declaredAt: found.method.declaredAt } : row;
434
+ }
435
+ function foundRowOf(found) {
436
+ const { method } = found;
437
+ if (method.root === "source")
438
+ return `${method.path} source ${method.declaredAt} ${found.matchingIntent ?? (method.summary === void 0 ? NO_SUMMARY_TEXT : shortSummary(method.summary))} ${found.packageName}`;
439
+ return `${method.path} ${method.root} ${found.matchingIntent ?? shortSummary(method.summary ?? "-")} ${found.packageName}`;
440
+ }
441
+ function noteLinesOf(notes) {
442
+ return (notes ?? []).map((note) => `${NOTE_LINE_PREFIX}${note}`);
364
443
  }
365
444
  function renderShown(params) {
366
445
  if (params.json)
367
- return toJson({
368
- methods: params.methods.map(({ method, packageName: packageName2 }) => ({
369
- package: packageName2,
370
- ...method
371
- }))
372
- });
373
- return params.methods.map(renderMethod).join("\n");
446
+ return endedOf(
447
+ jsonOf(
448
+ {
449
+ methods: params.methods.map(({ method, packageName: packageName2 }) => ({
450
+ package: packageName2,
451
+ ...method
452
+ })),
453
+ ...params.notes === void 0 ? {} : { notes: params.notes }
454
+ },
455
+ " "
456
+ )
457
+ );
458
+ return endedTextOf([
459
+ ...params.methods.flatMap((packaged, index) => [
460
+ ...index === 0 ? [] : [""],
461
+ ...renderMethod(packaged)
462
+ ]),
463
+ ...noteLinesOf(params.notes)
464
+ ]);
374
465
  }
375
466
  function renderMethod({ method, packageName: packageName2 }) {
376
467
  const lines = [`${method.path} (${packageName2})`, method.signature];
@@ -379,1285 +470,2024 @@ function renderMethod({ method, packageName: packageName2 }) {
379
470
  if (method.otherRoutes.length) lines.push(`also: ${method.otherRoutes.join(", ")}`);
380
471
  if (method.declaredAt) lines.push(`source (repository): ${method.declaredAt}`);
381
472
  if (method.example) lines.push(`example: ${method.example}`);
382
- return `${lines.join("\n")}
383
- `;
473
+ return lines;
384
474
  }
385
- function toJson(value) {
386
- return `${JSON.stringify(value, null, " ")}
387
- `;
475
+ function endedTextOf(lines) {
476
+ return textOf(lines.length === 0 ? [] : [...lines, ""]);
388
477
  }
389
478
 
390
- // src/lib/config.ts
391
- import { readFileSync as readFileSync3, existsSync as existsSync3, readdirSync as readdirSync3, statSync as statSync3 } from "fs";
392
- import { join as join4 } from "path";
393
- var getArg = (argv, name) => {
394
- const i = argv.indexOf(`--${name}`);
395
- return i >= 0 ? argv[i + 1] : void 0;
396
- };
397
- var hasFlag = (argv, name) => argv.includes(`--${name}`);
398
- function positionalArguments(params) {
399
- const words = [];
400
- for (let index = 0; index < params.argv.length; index++) {
401
- const argument = params.argv[index];
402
- if (!argument.startsWith("--")) words.push(argument);
403
- else if (params.valueOptions.includes(argument.slice(2))) index++;
479
+ // src/lib/closest-names.ts
480
+ function closestNames(params) {
481
+ const name = params.name.toLowerCase();
482
+ const threshold = Math.max(2, Math.floor(name.length / 3));
483
+ return params.candidates.map((candidate) => ({
484
+ candidate,
485
+ distance: candidate.toLowerCase().includes(name) ? 0 : editDistance({ from: name, to: candidate.toLowerCase() })
486
+ })).filter(({ distance }) => distance <= threshold).sort(
487
+ (left, right) => left.distance - right.distance || TEXT_COLLATOR.compare(left.candidate, right.candidate)
488
+ ).slice(0, params.limit).map(({ candidate }) => candidate);
489
+ }
490
+ function editDistance(params) {
491
+ const { from, to } = params;
492
+ let previous = Array.from({ length: to.length + 1 }, (_, index) => index);
493
+ for (let row = 1; row <= from.length; row++) {
494
+ const current = [row];
495
+ for (let column = 1; column <= to.length; column++)
496
+ current[column] = Math.min(
497
+ previous[column] + 1,
498
+ current[column - 1] + 1,
499
+ previous[column - 1] + (from[row - 1] === to[column - 1] ? 0 : 1)
500
+ );
501
+ previous = current;
404
502
  }
405
- return words;
503
+ return previous[to.length];
406
504
  }
407
- var tsconfigOf = (argv, cwd = process.cwd()) => getArg(argv, "tsconfig") ?? pkgConfig(cwd).tsconfig ?? "tsconfig.build.json";
408
- var readPkg = (cwd) => {
409
- const p = join4(cwd, "package.json");
410
- return existsSync3(p) ? JSON.parse(readFileSync3(p, "utf8")) : {};
411
- };
412
- var pkgConfig = (cwd) => readPkg(cwd).dialecte ?? {};
413
- var capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
414
- function discoverNamespace(cwd) {
415
- return capitalize(
416
- String(readPkg(cwd).name ?? "dialecte").split("/").pop() ?? "dialecte"
417
- );
505
+
506
+ // src/lib/mutation/run-store.ts
507
+ import { randomBytes } from "crypto";
508
+ import {
509
+ existsSync as existsSync10,
510
+ mkdirSync as mkdirSync4,
511
+ readdirSync as readdirSync8,
512
+ readFileSync as readFileSync8,
513
+ renameSync as renameSync3,
514
+ writeFileSync as writeFileSync3
515
+ } from "fs";
516
+ import { basename as basename5, join as join13 } from "path";
517
+
518
+ // src/lib/git.ts
519
+ import { spawnSync } from "child_process";
520
+ import { realpathSync as realpathSync2 } from "fs";
521
+ import { basename as basename2, dirname as dirname3, isAbsolute as isAbsolute2, join as join4, resolve as resolve2 } from "path";
522
+
523
+ // src/lib/git.constants.ts
524
+ var GIT_READ_ENVIRONMENT = { GIT_OPTIONAL_LOCKS: "0" };
525
+
526
+ // src/lib/git.ts
527
+ function readGit(params) {
528
+ const result = spawnSync("git", ["-c", "core.quotePath=false", ...params.args], {
529
+ cwd: params.root,
530
+ encoding: "utf8",
531
+ input: params.input,
532
+ maxBuffer: 1e8,
533
+ // a status or diff never refreshes the index behind a commit running at the same time
534
+ env: { ...process.env, ...GIT_READ_ENVIRONMENT, ...params.environment }
535
+ });
536
+ if (result.status !== 0)
537
+ throw new Error(`git ${params.args.join(" ")}: ${(result.stderr || result.stdout).trim()}`);
538
+ return result.stdout;
418
539
  }
419
- function discoverVersions(cwd) {
420
- const src = join4(cwd, "src");
421
- if (!existsSync3(src)) return [];
422
- return readdirSync3(src).filter((v) => statSync3(join4(src, v)).isDirectory()).filter(
423
- (v) => existsSync3(join4(src, v, "definition", "constants.generated.ts")) && existsSync3(join4(src, v, "definition", "definition.generated.ts"))
424
- ).sort();
540
+ function tryReadGit(params) {
541
+ try {
542
+ return readGit(params);
543
+ } catch {
544
+ return void 0;
545
+ }
425
546
  }
426
- var CORE_PACKAGE = "@dialecte/core";
427
- var CORE_TEST_DIALECT = {
428
- version: "core",
429
- binding: {
430
- kind: "core",
431
- coreAlias: "Core",
432
- coreImport: "@/index",
433
- configType: "TestDialecteConfig",
434
- configImport: "@/test/config"
435
- },
436
- constantsDir: "./src/test/generated",
437
- outDir: "./benchmarks/types/generated"
438
- };
439
- function resolveTargets(argv, cwd = process.cwd()) {
440
- if (readPkg(cwd).name === CORE_PACKAGE)
441
- return [
442
- {
443
- ...CORE_TEST_DIALECT,
444
- version: getArg(argv, "version") ?? CORE_TEST_DIALECT.version,
445
- constantsDir: getArg(argv, "constants-dir") ?? CORE_TEST_DIALECT.constantsDir,
446
- outDir: getArg(argv, "out") ?? CORE_TEST_DIALECT.outDir
447
- }
448
- ];
449
- const cfg = pkgConfig(cwd);
450
- const namespace = getArg(argv, "namespace") ?? cfg.namespace ?? discoverNamespace(cwd);
451
- const only = getArg(argv, "version");
452
- let versions = discoverVersions(cwd);
453
- if (only) versions = versions.filter((v) => v === only);
454
- if (!versions.length && (getArg(argv, "constants-dir") || getArg(argv, "entry")))
455
- versions = [only ?? "default"];
456
- return versions.map((version) => {
457
- const entry = getArg(argv, "entry") ?? cfg.entry ?? `@/${version}`;
458
- return {
459
- version,
460
- binding: { kind: "namespace", name: namespace, import: entry },
461
- constantsDir: getArg(argv, "constants-dir") ?? cfg.constantsDir ?? `./src/${version}/definition`,
462
- outDir: getArg(argv, "out") ?? cfg.out ?? `./benchmarks/types/${version}/generated`
463
- };
464
- });
547
+ function listRepositoryFiles(params) {
548
+ return readGit({
549
+ root: params.root,
550
+ args: ["ls-files", "--cached", "--others", "--exclude-standard", "--", params.folder]
551
+ }).split("\n").filter(Boolean).sort();
552
+ }
553
+ function gitFolderOf(root) {
554
+ const folder = readGit({ root, args: ["rev-parse", "--git-dir"] }).trim();
555
+ return isAbsolute2(folder) ? folder : join4(root, folder);
556
+ }
557
+ function isInWorkTree(root) {
558
+ return tryReadGit({ root, args: ["rev-parse", "--is-inside-work-tree"] })?.trim() === "true";
465
559
  }
466
560
 
467
- // src/lib/missing-package.ts
468
- import { existsSync as existsSync4 } from "fs";
561
+ // src/lib/package-json.ts
562
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
469
563
  import { join as join5 } from "path";
470
- function missingPackage(params) {
471
- return existsSync4(join5(params.cwd, "package.json")) ? void 0 : {
472
- output: `no package.json in ${params.cwd}: run dialecte in your package's folder
473
- `,
474
- exitCode: 2
475
- };
564
+ function readPackageJson(root) {
565
+ const path = join5(root, "package.json");
566
+ return existsSync3(path) ? JSON.parse(readFileSync3(path, "utf8")) : {};
476
567
  }
477
568
 
478
- // src/commands/api.constants.ts
479
- var API_SUBCOMMANDS = ["find", "show"];
480
- var API_VALUE_OPTIONS = ["package", "limit"];
481
- var DEFAULT_FIND_LIMIT = 5;
482
- var API_USAGE = 'usage: dialecte api find "<need>" [--package <name>] [--limit 5] [--json] | dialecte api show <path> [--json]';
483
-
484
- // src/commands/api.ts
485
- function runApi(params) {
486
- const missing = missingPackage({ cwd: params.cwd });
487
- if (missing) return missing;
488
- const [subcommand, ...rest] = params.argv;
489
- const words = positionalArguments({ argv: rest, valueOptions: API_VALUE_OPTIONS });
490
- const limit = Number(getArg([...rest], "limit") ?? DEFAULT_FIND_LIMIT);
491
- if (!isSubcommand(subcommand) || words.length === 0 || !Number.isInteger(limit) || limit < 1)
492
- return { output: `${API_USAGE}
493
- `, exitCode: 2 };
494
- const packageName2 = getArg([...rest], "package");
495
- const indexes = readApiIndexes({ cwd: params.cwd }).filter(
496
- (index) => packageName2 === void 0 || index.package === packageName2
497
- );
498
- const json = hasFlag([...rest], "json");
499
- return subcommand === "find" ? find({ indexes, need: words.join(" "), limit, json }) : show({ indexes, path: words[0], json });
500
- }
501
- function isSubcommand(value) {
502
- return API_SUBCOMMANDS.some((subcommand) => subcommand === value);
569
+ // src/lib/process-alive.ts
570
+ function isProcessAlive(pid) {
571
+ try {
572
+ process.kill(pid, 0);
573
+ return true;
574
+ } catch (error) {
575
+ return error.code === "EPERM";
576
+ }
503
577
  }
504
- function find(params) {
505
- const found = findMethods(params);
506
- if (found.length === 0 && !params.json)
507
- return {
508
- output: `no method found for "${params.need}" in ${packagesText(params.indexes)}: try other words, or \`npx @dialecte/cli members <expression>\` for the live types
509
- `,
510
- exitCode: 1
511
- };
512
- return {
513
- output: renderFound({ need: params.need, found, json: params.json }),
514
- exitCode: found.length ? 0 : 1
515
- };
578
+
579
+ // src/lib/process-start-time.ts
580
+ import { spawnSync as spawnSync2 } from "child_process";
581
+
582
+ // src/lib/review-rounds/worktree-state.ts
583
+ import { spawnSync as spawnSync3 } from "child_process";
584
+ import { existsSync as existsSync9, lstatSync as lstatSync4, readdirSync as readdirSync7, statSync as statSync4 } from "fs";
585
+ import { dirname as dirname7, join as join12 } from "path";
586
+
587
+ // src/lib/store/lot-folder.ts
588
+ import { existsSync as existsSync8, realpathSync as realpathSync3 } from "fs";
589
+ import { basename as basename4, dirname as dirname6, join as join11, resolve as resolve4 } from "path";
590
+
591
+ // src/lib/store/store-folder.ts
592
+ import {
593
+ existsSync as existsSync7,
594
+ mkdirSync as mkdirSync3,
595
+ readdirSync as readdirSync6,
596
+ readFileSync as readFileSync7,
597
+ renameSync as renameSync2,
598
+ rmSync as rmSync3,
599
+ statSync as statSync3
600
+ } from "fs";
601
+ import { dirname as dirname5, join as join10, resolve as resolve3 } from "path";
602
+
603
+ // src/lib/handover/handover-store-read.ts
604
+ import { existsSync as existsSync4, readdirSync as readdirSync3, readFileSync as readFileSync4 } from "fs";
605
+ import { join as join6, sep as sep2 } from "path";
606
+
607
+ // src/lib/store/identity.ts
608
+ import { readFileSync as readFileSync5 } from "fs";
609
+ import { join as join7 } from "path";
610
+
611
+ // src/lib/store/store.constants.ts
612
+ var TEMPORARY_INFIX = ".tmp-";
613
+ var TEMPORARY_FILE_SUFFIX_PATTERN = /^\.tmp-(\d+)-\d+$/;
614
+ var WRITABLE_MODE = 420;
615
+ var PERMISSION_BITS = 511;
616
+ var REPLACED_LINK_REFUSAL = "refused to replace a symbolic link";
617
+
618
+ // src/lib/store/publish.ts
619
+ import {
620
+ chmodSync,
621
+ closeSync,
622
+ existsSync as existsSync5,
623
+ fsyncSync,
624
+ linkSync,
625
+ lstatSync as lstatSync3,
626
+ openSync,
627
+ readdirSync as readdirSync4,
628
+ renameSync,
629
+ rmSync as rmSync2,
630
+ writeFileSync as writeFileSync2
631
+ } from "fs";
632
+ import { basename as basename3, dirname as dirname4, join as join8 } from "path";
633
+ var temporaryCounter = 0;
634
+ function replaceWhole(params) {
635
+ const existing = lstatSync3(params.path, { throwIfNoEntry: false });
636
+ if (existing?.isSymbolicLink()) throw new Error(`${REPLACED_LINK_REFUSAL}: ${params.path}`);
637
+ const mode = existing ? existing.mode & PERMISSION_BITS : WRITABLE_MODE;
638
+ const temporary = writeTemporary({ path: params.path, text: params.text, mode });
639
+ params.afterTemporaryWritten?.(temporary);
640
+ try {
641
+ renameSync(temporary, params.path);
642
+ } catch (error) {
643
+ throw vanishedOr({ error, temporary });
644
+ }
516
645
  }
517
- function show(params) {
518
- const methods = findByPath(params);
519
- if (methods.length === 0 && !params.json)
520
- return {
521
- output: `no method "${params.path}" in ${packagesText(params.indexes)}: \`npx @dialecte/cli api find "<what you need>"\` lists the routes
522
- `,
523
- exitCode: 1
524
- };
525
- return { output: renderShown({ methods, json: params.json }), exitCode: methods.length ? 0 : 1 };
646
+ function removeDeadLeftovers(params) {
647
+ if (!existsSync5(params.folder)) return;
648
+ const folders = params.kind === "folders";
649
+ for (const entry of readdirSync4(params.folder, { withFileTypes: true })) {
650
+ const pid = params.pidOf(entry.name);
651
+ if (pid === void 0 || isProcessAlive(Number(pid))) continue;
652
+ if (entry.isDirectory() !== folders) continue;
653
+ rmSync2(join8(params.folder, entry.name), { recursive: folders, force: true });
654
+ }
526
655
  }
527
- function packagesText(indexes) {
528
- return indexes.length ? indexes.map((index) => index.package).join(", ") : "no installed package (none ships skills/<name>/references/api.json)";
656
+ function temporaryPidOf(params) {
657
+ if (!params.name.startsWith(params.finalName)) return void 0;
658
+ return TEMPORARY_FILE_SUFFIX_PATTERN.exec(params.name.slice(params.finalName.length))?.[1];
529
659
  }
530
-
531
- // src/lib/doctor/answer-doctor.ts
532
- function answerDoctor(params) {
533
- const exitCode = params.lines.some((line) => line.status !== "ok") ? 1 : 0;
534
- if (params.json)
535
- return { output: `${JSON.stringify({ lines: params.lines }, null, " ")}
536
- `, exitCode };
537
- return { output: params.lines.map(renderLine).join(""), exitCode };
660
+ function writeTemporary(params) {
661
+ const finalName = basename3(params.path);
662
+ removeDeadLeftovers({
663
+ folder: dirname4(params.path),
664
+ pidOf: (name) => temporaryPidOf({ name, finalName }),
665
+ kind: "files"
666
+ });
667
+ temporaryCounter += 1;
668
+ const temporary = `${params.path}${TEMPORARY_INFIX}${process.pid}-${temporaryCounter}`;
669
+ const descriptor = openSync(temporary, "w");
670
+ try {
671
+ writeFileSync2(descriptor, params.text);
672
+ fsyncSync(descriptor);
673
+ } finally {
674
+ closeSync(descriptor);
675
+ }
676
+ chmodSync(temporary, params.mode);
677
+ return temporary;
538
678
  }
539
- function answerDoctorBrief(lines) {
540
- return {
541
- output: lines.filter((line) => line.status !== "ok").map(renderLine).join(""),
542
- exitCode: 0
543
- };
679
+ function vanishedOr(params) {
680
+ if (isErrorCode({ error: params.error, code: "ENOENT" }) && !existsSync5(params.temporary))
681
+ return new Error(`the temporary file ${params.temporary} vanished before it was published`);
682
+ rmSync2(params.temporary, { force: true });
683
+ return params.error;
544
684
  }
545
- function renderLine(line) {
546
- if (line.status === "ok") return `\u2705 ${line.subject} ${line.detail}
547
- `;
548
- const fix = line.fix ? ` - fix: ${line.fix}` : "";
549
- return line.status === "error" ? `\u274C ${line.subject} ${line.detail}${fix}
550
- ` : `\u26A0\uFE0F ${line.subject} ${line.detail}${fix}
551
- `;
685
+ function isErrorCode(params) {
686
+ return params.error?.code === params.code;
552
687
  }
553
688
 
554
- // src/lib/doctor/diagnose.ts
555
- import { existsSync as existsSync9, lstatSync as lstatSync3, readdirSync as readdirSync4, readFileSync as readFileSync6 } from "fs";
556
- import { dirname as dirname3, join as join10, resolve as resolve2 } from "path";
689
+ // src/lib/store/transitions.ts
690
+ import { existsSync as existsSync6, mkdirSync as mkdirSync2, readdirSync as readdirSync5, readFileSync as readFileSync6 } from "fs";
691
+ import { join as join9 } from "path";
557
692
 
558
- // src/lib/package-json.ts
559
- import { existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
560
- import { join as join6 } from "path";
561
- function readPackageJson(root) {
562
- const path = join6(root, "package.json");
563
- return existsSync5(path) ? JSON.parse(readFileSync4(path, "utf8")) : {};
693
+ // src/lib/review-rounds/review-rounds.constants.ts
694
+ var DECISION_STATES = [
695
+ "open",
696
+ "fix-to-verify",
697
+ "fixed <round> [note]",
698
+ "accepted <reason>",
699
+ "logged <where>"
700
+ ];
701
+ var CHOICE_OPTIONS = ["by"];
702
+ var DECIDE_USAGE = `lot decide: expected <id|folder> <finding> <state...>; states: ${DECISION_STATES.join(", ")}`;
703
+ var SNAPSHOT_OPTIONS = ["round", "by", "reason"];
704
+ var VERIFY_OPTIONS = ["by", "note"];
705
+ var FINDING_OPTIONS = ["round", "severity", "at"];
706
+ var ROUND_OPTIONS = ["round"];
707
+ var REVIEW_ROUND_VALUE_OPTIONS = [
708
+ .../* @__PURE__ */ new Set([
709
+ ...FINDING_OPTIONS,
710
+ ...CHOICE_OPTIONS,
711
+ ...ROUND_OPTIONS,
712
+ ...SNAPSHOT_OPTIONS,
713
+ ...VERIFY_OPTIONS
714
+ ])
715
+ ];
716
+
717
+ // src/lib/review-rounds/worktree-state.ts
718
+ function listTreeFiles(folder) {
719
+ const found = [];
720
+ walkFolder({ folder, relative: "", found });
721
+ return found.sort();
722
+ }
723
+ function walkFolder(params) {
724
+ for (const name of readdirSync7(join12(params.folder, params.relative))) {
725
+ const path = params.relative ? `${params.relative}/${name}` : name;
726
+ if (lstatSync4(join12(params.folder, path)).isDirectory())
727
+ walkFolder({ folder: params.folder, relative: path, found: params.found });
728
+ else params.found.push(path);
729
+ }
564
730
  }
565
731
 
566
- // src/lib/profile/profile.constants.ts
567
- var PROFILES = ["contributor", "consumer"];
568
- var DEFAULT_PROFILE = "consumer";
569
- var INVALID_PROFILE = "dialecte.profile: {value} is not a profile; profiles: contributor, consumer";
732
+ // src/lib/mutation/mutation.constants.ts
733
+ var MUTANTS_USAGE_LINES = [
734
+ "usage: dialecte mutants run [--mode changed|audit] [--base <ref>]",
735
+ " dialecte mutants status [--json]",
736
+ " dialecte mutants schedule <follow-up> <survivor key>... | schedule <follow-up> --all-new [--json]",
737
+ " dialecte mutants abandon <run id> [--json]",
738
+ " dialecte mutants migrate [--json]",
739
+ " dialecte mutants judge [--file <file>] [--json]",
740
+ " dialecte mutants record (--key <survivor key>... | --file <file>) --family <family> --reason <text> [--removable] [--json]",
741
+ " dialecte mutants drop <run id> [--json]"
742
+ ];
743
+ var MUTANTS_USAGE = MUTANTS_USAGE_LINES.join("\n");
570
744
 
571
- // src/lib/profile/profile.ts
572
- function readProfile(root) {
573
- const declared = readPackageJson(root).dialecte?.profile;
574
- if (declared === void 0) return DEFAULT_PROFILE;
575
- const profile = PROFILES.find((known) => known === declared);
576
- if (!profile) throw new Error(INVALID_PROFILE.replace("{value}", JSON.stringify(declared)));
577
- return profile;
745
+ // src/lib/mutation/run-store.ts
746
+ function packageNameOf(root) {
747
+ return readPackageJson(root).name ?? basename5(root);
578
748
  }
579
749
 
580
- // src/lib/doctor/doctor.constants.ts
581
- var DIALECTE_SCOPE = "@dialecte/";
582
- var CORE_PACKAGE2 = "@dialecte/core";
583
- var SYNC_COMMAND = "npx @dialecte/cli skills sync";
584
- var INSTALL_COMMAND = "npm install";
585
- var ALIGN_CORE_FIX = "align @dialecte/core with the version the dialecte pins (or upgrade the dialecte), then npm install";
586
- var CORE_API_GENERATIONS = [
587
- {
588
- from: [0, 7],
589
- name: "0.7",
590
- says: "import inside the store (project.importFile answers { documentId, diagnostics }), per-file IO hook session, createTestHelpers"
591
- },
592
- {
593
- from: [0, 0],
594
- name: "0.6",
595
- says: "import and IO hooks before the store owned them: read the skills of this version, not the latest docs"
750
+ // src/lib/package-root.ts
751
+ import { existsSync as existsSync11 } from "fs";
752
+ import { dirname as dirname8, join as join14 } from "path";
753
+ function packageRootOf(cwd) {
754
+ for (let folder = cwd; ; folder = dirname8(folder)) {
755
+ if (existsSync11(join14(folder, "package.json"))) return folder;
756
+ if (dirname8(folder) === folder) return void 0;
596
757
  }
597
- ];
598
- var CHECKOUT_LIST_LIMIT = 8;
599
- var STATION_AGENTS_SUBJECT = "station agents";
600
- var PROFILE_SUBJECT = "profile";
601
- var CONSUMER_ALLOWS_REFERENCES = "allowReferences is the consumer default: remove it";
602
- var CONTRIBUTOR_GATE_STEPS = "dialecte.gate.full holds {steps}: dialecte contrib runs them, move them to dialecte.contrib.steps (or drop them for the defaults)";
603
- var CONTRIBUTOR_SKILLS_NOT_SYNCED = "{folder} lacks the contributor skills: dialecte skills sync installs them in a contributor";
758
+ }
604
759
 
605
- // src/lib/doctor/profile-lines.ts
606
- import { existsSync as existsSync6 } from "fs";
607
- import { join as join7 } from "path";
760
+ // src/lib/api/source-functions.ts
761
+ import { existsSync as existsSync13 } from "fs";
762
+ import { join as join18 } from "path";
608
763
 
609
- // src/lib/contrib/contrib.constants.ts
610
- var DEFAULT_CONTRIB_STEPS = [
611
- { name: "docs", run: "npm run doc:build", restoresGeneratedDocs: true },
612
- { name: "type-bench", run: "npm run type-bench:check" }
613
- ];
764
+ // src/lib/tdd/tdd.constants.ts
765
+ var TEST_FILE_PATTERN = /\.(test|spec)\.[cm]?[jt]sx?$/;
614
766
 
615
- // src/lib/doctor/profile-lines.ts
616
- function profileLines(cwd) {
617
- let profile;
618
- try {
619
- profile = readProfile(cwd);
620
- } catch (error) {
621
- const detail = error instanceof Error ? error.message : String(error);
622
- return [{ status: "error", subject: PROFILE_SUBJECT, detail }];
623
- }
624
- const dialecte = readPackageJson(cwd).dialecte;
625
- if (profile === "consumer") {
626
- const declared = dialecte?.profile === void 0 ? "consumer (default)" : "consumer";
627
- return [
628
- { status: "ok", subject: PROFILE_SUBJECT, detail: declared },
629
- ...dialecte?.allowReferences === void 0 ? [] : [
630
- {
631
- status: "warning",
632
- subject: PROFILE_SUBJECT,
633
- detail: CONSUMER_ALLOWS_REFERENCES
634
- }
635
- ]
636
- ];
637
- }
638
- const full = Array.isArray(dialecte?.gate?.full) ? dialecte.gate.full : [];
639
- const contributorSteps = DEFAULT_CONTRIB_STEPS.map((step) => step.name);
640
- const moved = full.map((step) => step.name).filter((name) => contributorSteps.includes(name));
641
- const unsynced = Object.values(AGENT_SKILL_FOLDERS).filter(
642
- (folder) => existsSync6(join7(cwd, folder, MANIFEST_FILE)) && readSyncManifest(join7(cwd, folder)).contributing !== true
643
- );
644
- return [
645
- { status: "ok", subject: PROFILE_SUBJECT, detail: "contributor" },
646
- ...moved.length ? [
647
- {
648
- status: "warning",
649
- subject: PROFILE_SUBJECT,
650
- detail: CONTRIBUTOR_GATE_STEPS.replace("{steps}", moved.join(", "))
651
- }
652
- ] : [],
653
- ...unsynced.map((folder) => ({
654
- status: "warning",
655
- subject: PROFILE_SUBJECT,
656
- detail: CONTRIBUTOR_SKILLS_NOT_SYNCED.replace("{folder}", folder)
657
- }))
658
- ];
659
- }
767
+ // src/lib/discover.constants.ts
768
+ import ts from "typescript";
769
+ var ENTRY_FOLDER = "node_modules/.cache/dialecte";
770
+ var ROOTS = ["q", "tx", "doc", "project"];
771
+ var PRIMITIVE_LIKE = ts.TypeFlags.StringLike | ts.TypeFlags.NumberLike | ts.TypeFlags.BooleanLike | ts.TypeFlags.ESSymbolLike | ts.TypeFlags.VoidLike | ts.TypeFlags.Null | ts.TypeFlags.BigIntLike;
772
+ var SIGNATURE_FORMAT = ts.TypeFormatFlags.WriteArrowStyleSignature | ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope;
773
+ var FENCED_CODE_PATTERN = /^[ \t]*```[a-z]*[ \t]*\n([\s\S]*?)^[ \t]*```/m;
774
+ var SIGNATURE_PRINTER = ts.createPrinter({ removeComments: true });
660
775
 
661
- // src/lib/doctor/station-agent-lines.ts
662
- import { existsSync as existsSync8, readFileSync as readFileSync5 } from "fs";
663
- import { join as join9 } from "path";
776
+ // src/lib/discover.ts
777
+ import { mkdirSync as mkdirSync5, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "fs";
778
+ import { dirname as dirname9, join as join15, relative as relative3 } from "path";
664
779
 
665
- // src/lib/models/remembered-vendor.ts
666
- import { existsSync as existsSync7, statSync as statSync4 } from "fs";
667
- import { join as join8 } from "path";
780
+ // src/lib/render-jsdoc-text.ts
781
+ function renderJsDocText(parts) {
782
+ let text = "";
783
+ let link;
784
+ for (const part of parts ?? []) {
785
+ if (part.kind === "link" && part.text.startsWith("{@link"))
786
+ link = { name: void 0, label: "" };
787
+ else if (link && part.kind === "linkName") link.name = part.text;
788
+ else if (link && part.kind === "linkText") link.label += part.text;
789
+ else if (link && part.kind === "link") {
790
+ text += renderLink(link);
791
+ link = void 0;
792
+ } else text += part.text;
793
+ }
794
+ return text;
795
+ }
796
+ function renderLink(link) {
797
+ if (link.name !== void 0) return link.label.trim() || `\`${link.name}\``;
798
+ const [target = "", ...label] = link.label.trim().split(/\s+/);
799
+ return label.join(" ") || `\`${target}\``;
800
+ }
668
801
 
669
- // src/lib/models/model-tiers.constants.ts
670
- var VENDOR_IDS = ["anthropic", "openai", "google"];
671
- var TIER_NAMES = ["fast", "standard", "strong", "frontier"];
672
- var TIER_DEFINITIONS = {
673
- fast: 'search and locate, graders with a schema, log and diff summaries, format and shape checks, "does file X say Y"',
674
- standard: "implementer on a mechanical or well-specified lot, fix mode on wording and rename findings, skill-eval runs, independent readers of a standard",
675
- strong: "the orchestrator, an implementer on a design-heavy lot, the review (one agent, both passes), adjudicating a disagreement, the retro",
676
- frontier: "rare: a plan challenge, a cross-repo architecture decision, a stuck lot after the 3-round cap"
677
- };
678
- var MODEL_TIERS = {
679
- checkedAt: "2026-10-28",
680
- vendors: {
681
- anthropic: {
682
- tiers: {
683
- fast: { model: "Haiku 5.5" },
684
- standard: { model: "Sonnet 5.5" },
685
- strong: { model: "Opus 5.5" },
686
- frontier: { model: "Fable 5.1" }
687
- }
688
- },
689
- openai: {
690
- tiers: {
691
- fast: { model: "Luna" },
692
- standard: { model: "Sol" },
693
- strong: { model: "Sol", effort: "high" },
694
- frontier: { model: "Astra" }
695
- }
696
- },
697
- google: {
698
- note: "frontier: check Google's own model page for the current flagship (4 Argon, if generally available)",
699
- tiers: {
700
- fast: { model: "Flash-Lite" },
701
- standard: { model: "Flash" },
702
- strong: { model: "Pro" },
703
- frontier: { model: "the current flagship" }
704
- }
802
+ // src/lib/discover.ts
803
+ import ts2 from "typescript";
804
+ function discoverMethods(params) {
805
+ const { entrySource, tsconfig, root, maxDepth = 1 } = params;
806
+ const entryPath = join15(root, ENTRY_FOLDER, `discover-entry-${process.pid}.ts`);
807
+ mkdirSync5(dirname9(entryPath), { recursive: true });
808
+ writeFileSync4(entryPath, entrySource);
809
+ try {
810
+ const parsed = ts2.parseJsonConfigFileContent(
811
+ ts2.readConfigFile(join15(root, tsconfig), ts2.sys.readFile).config,
812
+ ts2.sys,
813
+ root
814
+ );
815
+ const program = ts2.createProgram([entryPath], {
816
+ ...parsed.options,
817
+ noEmit: true,
818
+ rootDir: root
819
+ });
820
+ const checker = program.getTypeChecker();
821
+ const sourceFile = program.getSourceFile(entryPath);
822
+ if (!sourceFile) return [];
823
+ const exportsByName = new Map(
824
+ checker.getExportsOfModule(checker.getSymbolAtLocation(sourceFile)).map((symbol) => [symbol.getName(), symbol])
825
+ );
826
+ const entries = [];
827
+ for (const rootName of ROOTS) {
828
+ const symbol = exportsByName.get(rootName);
829
+ if (symbol)
830
+ walkMembers({
831
+ checker,
832
+ sourceFile,
833
+ type: checker.getTypeOfSymbolAtLocation(symbol, sourceFile),
834
+ path: rootName,
835
+ depth: 0,
836
+ maxDepth,
837
+ root,
838
+ entries
839
+ });
705
840
  }
841
+ return entries;
842
+ } finally {
843
+ rmSync4(entryPath, { force: true });
706
844
  }
707
- };
708
-
709
- // src/lib/models/vendor-id.ts
710
- function isVendorId(value) {
711
- return VENDOR_IDS.includes(value);
712
845
  }
713
-
714
- // src/lib/models/remembered-vendor.ts
715
- function listManifestFolders(cwd) {
716
- return Object.values(AGENT_SKILL_FOLDERS).filter(
717
- (folder) => existsSync7(join8(cwd, folder, MANIFEST_FILE))
846
+ function walkMembers(params) {
847
+ const { checker, sourceFile, type, path, depth, maxDepth } = params;
848
+ for (const property of type.getProperties()) {
849
+ if (!isPublic(property)) continue;
850
+ const propertyType = checker.getTypeOfSymbolAtLocation(
851
+ property,
852
+ declarationOf(property) ?? sourceFile
853
+ );
854
+ const propertyPath = `${path}.${property.getName()}`;
855
+ if (propertyType.getCallSignatures().length > 0) {
856
+ const { documentation, declaringSymbol } = documentationOf({
857
+ checker,
858
+ symbol: property,
859
+ root: params.root
860
+ });
861
+ params.entries.push({
862
+ path: propertyPath,
863
+ signature: signatureOf({ checker, boundType: propertyType, declaringSymbol }),
864
+ ...documentation
865
+ });
866
+ } else if (depth < maxDepth && !(propertyType.flags & PRIMITIVE_LIKE) && propertyType.getProperties().some(
867
+ (member) => isPublic(member) && !isTypeScriptLibrary(member) && checker.getTypeOfSymbolAtLocation(member, declarationOf(member) ?? sourceFile).getCallSignatures().length > 0
868
+ ))
869
+ walkMembers({ ...params, type: propertyType, path: propertyPath, depth: depth + 1 });
870
+ }
871
+ }
872
+ function signatureOf(params) {
873
+ const { checker } = params;
874
+ const boundSignatures = params.boundType.getCallSignatures();
875
+ const declarations = callableDeclarations(params.declaringSymbol);
876
+ if (declarations.length === 0)
877
+ return boundSignatures.map(
878
+ (signature) => checker.signatureToString(signature, void 0, SIGNATURE_FORMAT, ts2.SignatureKind.Call)
879
+ ).join("\n");
880
+ const boundParameterCount = Math.max(
881
+ ...boundSignatures.map((signature) => parameterCount({ checker, signature }))
718
882
  );
883
+ return declarations.map((declaration) => declaredSignatureText({ checker, declaration, boundParameterCount })).join("\n");
719
884
  }
720
- function readRememberedVendor(cwd) {
721
- const warnings = [];
722
- const entries = [];
723
- for (const folder of listManifestFolders(cwd)) {
724
- const { vendor } = readSyncManifest(join8(cwd, folder));
725
- if (vendor === void 0) continue;
726
- if (!isVendorId(vendor)) {
727
- warnings.push(`${folder}/${MANIFEST_FILE}: unknown vendor "${vendor}" ignored`);
885
+ function parameterCount(params) {
886
+ const { checker } = params;
887
+ const parameters = params.signature.getParameters();
888
+ const last = parameters.at(-1);
889
+ if (!last) return 0;
890
+ const lastType = checker.getTypeOfSymbol(last);
891
+ return checker.isTupleType(lastType) ? parameters.length - 1 + checker.getTypeArguments(lastType).length : parameters.length;
892
+ }
893
+ function callableDeclarations(symbol) {
894
+ const declarations = (symbol?.declarations ?? []).flatMap(
895
+ (declaration) => {
896
+ if (ts2.isFunctionDeclaration(declaration) || ts2.isMethodDeclaration(declaration))
897
+ return [declaration];
898
+ if (ts2.isVariableDeclaration(declaration) && declaration.initializer && (ts2.isArrowFunction(declaration.initializer) || ts2.isFunctionExpression(declaration.initializer)))
899
+ return [declaration.initializer];
900
+ return [];
901
+ }
902
+ );
903
+ const overloads = declarations.filter((declaration) => !hasBody(declaration));
904
+ return overloads.length > 0 ? overloads : declarations;
905
+ }
906
+ function hasBody(declaration) {
907
+ return "body" in declaration && declaration.body !== void 0;
908
+ }
909
+ function declaredSignatureText(params) {
910
+ const { checker, declaration } = params;
911
+ const sourceFile = declaration.getSourceFile();
912
+ const signature = checker.getSignatureFromDeclaration(declaration);
913
+ const parameters = declaration.parameters;
914
+ const skipped = Math.max(0, parameters.length - params.boundParameterCount);
915
+ const typeParameters = declaration.typeParameters?.length ? `<${declaration.typeParameters.map((typeParameter) => printed({ node: typeParameter, sourceFile })).join(", ")}>` : "";
916
+ const parameterTexts = parameters.slice(skipped).map(function parameterText(parameter) {
917
+ const optional = parameter.questionToken || parameter.initializer ? "?" : "";
918
+ const rest = parameter.dotDotDotToken ? "..." : "";
919
+ const type = parameter.type ? printed({ node: parameter.type, sourceFile }) : checker.typeToString(checker.getTypeAtLocation(parameter), declaration, SIGNATURE_FORMAT);
920
+ return `${rest}${printed({ node: parameter.name, sourceFile })}${optional}: ${type}`;
921
+ });
922
+ const returnType = declaration.type ? printed({ node: declaration.type, sourceFile }) : signature ? checker.typeToString(signature.getReturnType(), declaration, SIGNATURE_FORMAT) : "unknown";
923
+ return `${typeParameters}(${parameterTexts.join(", ")}) => ${returnType}`;
924
+ }
925
+ function printed(params) {
926
+ return SIGNATURE_PRINTER.printNode(
927
+ ts2.EmitHint.Unspecified,
928
+ params.node,
929
+ params.sourceFile
930
+ ).replace(/\s*\n\s*/g, " ");
931
+ }
932
+ function documentationOf(params) {
933
+ const { checker } = params;
934
+ const visited = /* @__PURE__ */ new Set();
935
+ const queue = [params.symbol];
936
+ let declaringSymbol;
937
+ while (queue.length) {
938
+ const symbol = queue.shift();
939
+ if (!symbol || visited.has(symbol)) continue;
940
+ visited.add(symbol);
941
+ if (symbol.flags & ts2.SymbolFlags.Alias) {
942
+ queue.push(checker.getAliasedSymbol(symbol));
728
943
  continue;
729
944
  }
730
- entries.push({
731
- folder,
732
- vendor,
733
- writtenAt: statSync4(join8(cwd, folder, MANIFEST_FILE)).mtimeMs
734
- });
945
+ declaringSymbol ??= symbol;
946
+ const comment = renderJsDocText(symbol.getDocumentationComment(checker));
947
+ if (comment) {
948
+ const tags2 = symbol.getJsDocTags(checker);
949
+ return {
950
+ documentation: {
951
+ summary: firstParagraph(comment),
952
+ intents: intentsOf(tags2),
953
+ example: exampleOf(tags2),
954
+ definedInPackage: isDeclaredInPackage({ symbol, root: params.root }),
955
+ internal: tags2.some((tag) => tag.name === "internal"),
956
+ declaredAt: declarationKey({ symbol, root: params.root })
957
+ },
958
+ declaringSymbol: symbol
959
+ };
960
+ }
961
+ for (const declaration of symbol.declarations ?? []) {
962
+ if (ts2.isShorthandPropertyAssignment(declaration))
963
+ queue.push(checker.getShorthandAssignmentValueSymbol(declaration));
964
+ else if (ts2.isPropertyAssignment(declaration))
965
+ queue.push(assignedSymbol({ checker, initializer: declaration.initializer }));
966
+ else if (ts2.isExportSpecifier(declaration))
967
+ queue.push(checker.getExportSpecifierLocalTargetSymbol(declaration));
968
+ }
735
969
  }
736
- entries.sort((first, second) => second.writtenAt - first.writtenAt);
737
- if (new Set(entries.map((entry) => entry.vendor)).size > 1)
738
- warnings.push(
739
- `manifests disagree on the vendor (${entries.map((entry) => `${entry.folder}: ${entry.vendor}`).join(", ")}): using the most recent, ${entries[0].vendor}`
740
- );
741
- return { vendor: entries[0]?.vendor, warnings };
970
+ const declaringFunction = lastDeclared(visited) ?? declaringSymbol;
971
+ const tags = declaringFunction?.getJsDocTags(checker) ?? [];
972
+ return {
973
+ documentation: {
974
+ summary: void 0,
975
+ intents: intentsOf(tags),
976
+ example: exampleOf(tags),
977
+ internal: tags.some((tag) => tag.name === "internal"),
978
+ definedInPackage: isDeclaredInPackage({ symbol: declaringFunction, root: params.root }),
979
+ declaredAt: declarationKey({ symbol: declaringFunction, root: params.root })
980
+ },
981
+ declaringSymbol: declaringFunction
982
+ };
983
+ }
984
+ function firstParagraph(comment) {
985
+ return comment.split(/\n\s*\n/)[0].replace(/\s+/g, " ").trim();
986
+ }
987
+ function intentsOf(tags) {
988
+ return tags.filter((tag) => tag.name === "intent").flatMap((tag) => parseIntentText(renderJsDocText(tag.text)));
989
+ }
990
+ function exampleOf(tags) {
991
+ const tag = tags.find((candidate) => candidate.name === "example");
992
+ if (!tag) return void 0;
993
+ const text = renderJsDocText(tag.text);
994
+ const fenced = text.match(FENCED_CODE_PATTERN);
995
+ const code = (fenced ? fenced[1] : text).trim();
996
+ return code || void 0;
997
+ }
998
+ function parseIntentText(text) {
999
+ const intents = [];
1000
+ let depth = 0;
1001
+ let current = "";
1002
+ for (const character of text.split(/\n\s*\n/)[0]) {
1003
+ if (character === "(") depth++;
1004
+ else if (character === ")") depth = Math.max(0, depth - 1);
1005
+ if (character === "," && depth === 0) {
1006
+ intents.push(current);
1007
+ current = "";
1008
+ } else current += character;
1009
+ }
1010
+ intents.push(current);
1011
+ return intents.map((intent) => intent.replace(/\s+/g, " ").trim()).filter(Boolean);
1012
+ }
1013
+ function assignedSymbol(params) {
1014
+ const { checker, initializer } = params;
1015
+ if (ts2.isIdentifier(initializer)) return checker.getSymbolAtLocation(initializer);
1016
+ if (ts2.isPropertyAccessExpression(initializer))
1017
+ return checker.getSymbolAtLocation(initializer.name);
1018
+ return void 0;
1019
+ }
1020
+ function lastDeclared(symbols) {
1021
+ return [...symbols].reverse().find((symbol) => (symbol.declarations ?? []).some(declaresFunction));
1022
+ }
1023
+ function declaresFunction(declaration) {
1024
+ if (ts2.isFunctionDeclaration(declaration) || ts2.isMethodDeclaration(declaration)) return true;
1025
+ if (!ts2.isVariableDeclaration(declaration) || !declaration.initializer) return false;
1026
+ return ts2.isArrowFunction(declaration.initializer) || ts2.isFunctionExpression(declaration.initializer);
1027
+ }
1028
+ function declarationKey(params) {
1029
+ const declaration = params.symbol?.declarations?.[0];
1030
+ if (!declaration) return void 0;
1031
+ return `${relative3(params.root, declaration.getSourceFile().fileName)}:${declaration.getStart()}`;
1032
+ }
1033
+ function isDeclaredInPackage(params) {
1034
+ const fileName = params.symbol?.declarations?.[0]?.getSourceFile().fileName;
1035
+ if (!fileName) return false;
1036
+ const path = relative3(params.root, fileName);
1037
+ return !path.startsWith("..") && !path.split(/[\\/]/).includes("node_modules");
1038
+ }
1039
+ function declarationOf(symbol) {
1040
+ return symbol.valueDeclaration ?? symbol.declarations?.[0];
1041
+ }
1042
+ function isPublic(symbol) {
1043
+ const declaration = declarationOf(symbol);
1044
+ return !declaration || !(ts2.getCombinedModifierFlags(declaration) & (ts2.ModifierFlags.Private | ts2.ModifierFlags.Protected));
1045
+ }
1046
+ function isTypeScriptLibrary(symbol) {
1047
+ return (declarationOf(symbol)?.getSourceFile()?.fileName ?? "").includes(
1048
+ "/node_modules/typescript/"
1049
+ );
742
1050
  }
743
1051
 
744
- // src/lib/stations/station-agents.constants.ts
745
- var STATION_AGENT_PREFIX = "dialecte-";
746
- var CLAUDE_AGENTS_FOLDER = ".claude/agents";
747
- var CLAUDE_MODEL_ALIASES = ["haiku", "sonnet", "opus", "fable"];
748
- var READ_TOOLS = ["Read", "Glob", "Grep", "Skill"];
749
- var REVIEW_TOOLS = ["Read", "Glob", "Grep", "Bash", "Skill"];
750
- var EDIT_TOOLS = ["Read", "Write", "Edit", "Glob", "Grep", "Bash", "Skill"];
751
- var CLAUDE_TOOLS_BY_ACCESS = {
752
- read: READ_TOOLS,
753
- review: REVIEW_TOOLS,
754
- edit: EDIT_TOOLS
1052
+ // src/lib/first-syntax-error.constants.ts
1053
+ import ts3 from "typescript";
1054
+ var SYNTAX_CHECK_OPTIONS = {
1055
+ noLib: true,
1056
+ noResolve: true,
1057
+ isolatedModules: true,
1058
+ allowNonTsExtensions: true,
1059
+ target: ts3.ScriptTarget.Latest
755
1060
  };
756
- var LOAD_SKILLS_LINE = "Read that section first: it says which skills you load (`dialecte-lot`, `dialecte-contributing`, `dialecte`). The skills are the source of truth; this file only sets your envelope.";
757
- var NEVER_LINE = "Never: commit, stage (`git add`), push, merge, `git stash`, `git reset`, `git restore`, `git checkout --`, `rm`; nothing outside the worktree your brief names. Your brief is your whole context.";
758
- var GENERATED_NOTE = "Generated by `npx @dialecte/cli skills sync` from `dialecte models`; the next sync overwrites it.";
759
- var STATIONS = [
760
- {
761
- name: "test-writer",
762
- tier: "standard",
763
- access: "edit",
764
- description: "Dialecte lot, test station of one brief step: writes the tests (and stubs) from the brief and the existing code, then proves them red with `dialecte tdd red`. Give it the brief step."
765
- },
766
- {
767
- name: "test-reviewer",
768
- tier: "strong",
769
- access: "review",
770
- description: "Dialecte lot, test review before any code: reads only the tests against the brief (does each pin a behaviour, would a plausible wrong implementation fail it). Read-only."
771
- },
772
- {
773
- name: "implementer",
774
- tier: "standard",
775
- access: "edit",
776
- description: "Dialecte lot, Station 1 (implement) on a mechanical or fully specified lot: production code only until `dialecte tdd green`, then the fast gate. Give it the brief."
777
- },
778
- {
779
- name: "implementer-strong",
780
- tier: "strong",
781
- access: "edit",
782
- description: "Dialecte lot, Station 1 (implement) on a design-heavy lot: production code only until `dialecte tdd green`, then the fast gate. Give it the brief."
783
- },
784
- {
785
- name: "reviewer",
786
- tier: "strong",
787
- access: "review",
788
- description: "Dialecte lot, Station 3 (independent review): pass 1 correctness, pass 2 fit, read-only. Give it the brief and the diff, not the implementer conclusions."
789
- },
790
- {
791
- name: "fixer",
792
- tier: "standard",
793
- access: "edit",
794
- description: "Dialecte lot, Station 4 (fix mode) on wording and naming findings: fixed, disagreed or escalated per finding. Give it the findings."
795
- },
796
- {
797
- name: "eval-runner",
798
- tier: "standard",
799
- access: "edit",
800
- description: "Runs one skill-eval case of a Dialecte skill, with or without the skill, and leaves the outputs the graders read."
801
- },
802
- {
803
- name: "grader",
804
- tier: "strong",
805
- access: "read",
806
- description: "Grades the output of a skill-eval run against one grader file, pass or fail with the evidence. Read-only."
807
- },
808
- {
809
- name: "standard-reader",
810
- tier: "standard",
811
- access: "read",
812
- description: "Independent reader of the IEC standard markdown for one question, with line references. Read-only."
813
- },
814
- {
815
- name: "searcher",
816
- tier: "fast",
817
- access: "read",
818
- description: "Finds where something lives in a Dialecte repository (files, symbols, API paths) and answers with paths and line numbers. Read-only."
819
- }
820
- ];
821
- var LOT_SKILL = "dialecte-lot";
822
- var STATIONS_PAGE_PATH = `${AGENT_SKILL_FOLDERS.claude}/${LOT_SKILL}/references/stations.md`;
823
- var BRIEF_DEFINED_STATIONS = ["eval-runner", "grader"];
824
1061
 
825
- // src/lib/stations/render-station-agent.ts
826
- function claudeModelAlias(modelName) {
827
- const alias = modelName.split(" ")[0].toLowerCase();
828
- return CLAUDE_MODEL_ALIASES.includes(alias) ? alias : void 0;
829
- }
830
- function stationLines(params) {
831
- const { station } = params;
832
- const play = `You play the \`${station.name}\` station of \`${LOT_SKILL}\`:`;
833
- if (BRIEF_DEFINED_STATIONS.includes(station.name))
834
- return [
835
- `${play} your brief carries your definition and names the only skill text you read; read no other.`,
836
- ""
837
- ];
838
- return [
839
- `${play} its definition is ${STATIONS_PAGE_PATH}, section \`${station.name}\`.`,
840
- "",
841
- LOAD_SKILLS_LINE,
842
- ""
843
- ];
1062
+ // src/lib/first-syntax-error.ts
1063
+ import ts4 from "typescript";
1064
+ function firstSyntaxErrorOf(params) {
1065
+ const { source } = params;
1066
+ const program = ts4.createProgram({
1067
+ rootNames: [source.fileName],
1068
+ options: SYNTAX_CHECK_OPTIONS,
1069
+ host: singleFileHost(source)
1070
+ });
1071
+ const [first] = program.getSyntacticDiagnostics(source);
1072
+ if (first === void 0) return void 0;
1073
+ const position = source.getLineAndCharacterOfPosition(first.start ?? 0);
1074
+ return {
1075
+ line: position.line + 1,
1076
+ column: position.character + 1,
1077
+ message: ts4.flattenDiagnosticMessageText(first.messageText, " ")
1078
+ };
844
1079
  }
845
- function renderStationAgent(params) {
846
- const { station, model } = params;
847
- return [
848
- "---",
849
- `name: ${STATION_AGENT_PREFIX}${station.name}`,
850
- `description: ${JSON.stringify(station.description)}`,
851
- `tools: ${CLAUDE_TOOLS_BY_ACCESS[station.access].join(", ")}`,
852
- `model: ${model}`,
853
- "---",
854
- `<!-- ${GENERATED_NOTE} -->`,
855
- "",
856
- ...stationLines({ station }),
857
- NEVER_LINE,
858
- ""
859
- ].join("\n");
1080
+ function singleFileHost(source) {
1081
+ return {
1082
+ getSourceFile: function sourceNamed(name) {
1083
+ return name === source.fileName ? source : void 0;
1084
+ },
1085
+ fileExists: function isTheFile(name) {
1086
+ return name === source.fileName;
1087
+ },
1088
+ readFile: function readNothing() {
1089
+ return void 0;
1090
+ },
1091
+ writeFile: function writeNothing() {
1092
+ },
1093
+ getDefaultLibFileName: function noLibrary() {
1094
+ return "";
1095
+ },
1096
+ getCurrentDirectory: function noDirectory() {
1097
+ return "";
1098
+ },
1099
+ getCanonicalFileName: function sameName(name) {
1100
+ return name;
1101
+ },
1102
+ useCaseSensitiveFileNames: function caseSensitive() {
1103
+ return true;
1104
+ },
1105
+ getNewLine: function newLine() {
1106
+ return "\n";
1107
+ }
1108
+ };
860
1109
  }
861
- function planStationAgents(params) {
862
- const { vendor } = params;
863
- if (vendor === void 0)
864
- return {
865
- kind: "skipped",
866
- reason: "no model vendor known for this project, so no Claude Code station agents: run `skills sync --vendor anthropic`"
867
- };
868
- if (vendor !== "anthropic")
1110
+
1111
+ // src/lib/api/source-file-functions.ts
1112
+ import ts5 from "typescript";
1113
+ function parseSourceFile(params) {
1114
+ const { file, text } = params;
1115
+ const source = ts5.createSourceFile(file, text, ts5.ScriptTarget.Latest, true);
1116
+ const syntaxError = firstSyntaxErrorOf({ source });
1117
+ if (syntaxError !== void 0)
869
1118
  return {
870
- kind: "skipped",
871
- reason: `no Claude Code station agents: the project's vendor is ${vendor}, whose tiers are named by \`dialecte models\``
1119
+ entries: [],
1120
+ note: NOT_PARSED_NOTE.replace("{file}", file).replace("{why}", syntaxError.message)
872
1121
  };
873
- const tiers = MODEL_TIERS.vendors[vendor].tiers;
874
- const files = [];
875
- for (const station of STATIONS) {
876
- const modelName = tiers[station.tier].model;
877
- const model = claudeModelAlias(modelName);
878
- if (model === void 0)
1122
+ return {
1123
+ entries: exportedFunctionsOf(source).map(function entryOfFunction(found) {
1124
+ return sourceEntry({ file, source, found });
1125
+ })
1126
+ };
1127
+ }
1128
+ function exportedFunctionsOf(source) {
1129
+ const listed = locallyExportedNames(source);
1130
+ return topLevelFunctionsOf(source).flatMap(function exportsOfFunction(found) {
1131
+ const names = [...found.exported ? [found.name] : [], ...listed.get(found.name) ?? []];
1132
+ return [...new Set(names)].map(function exportedAs(name) {
879
1133
  return {
880
- kind: "skipped",
881
- reason: `no Claude Code station agents: "${modelName}" (${station.tier}) is not a model name Claude Code accepts`
1134
+ name,
1135
+ node: found.node,
1136
+ declaration: found.declaration,
1137
+ documented: found.documented
882
1138
  };
883
- files.push({
884
- name: `${STATION_AGENT_PREFIX}${station.name}.md`,
885
- content: renderStationAgent({ station, model })
886
1139
  });
887
- }
888
- return { kind: "files", files };
1140
+ });
889
1141
  }
890
-
891
- // src/lib/doctor/station-agent-lines.ts
892
- function stationAgentLines(cwd) {
893
- const manifestFolder = join9(cwd, AGENT_SKILL_FOLDERS.claude);
894
- if (!existsSync8(join9(manifestFolder, MANIFEST_FILE))) return [];
895
- const listed = readSyncManifest(manifestFolder).stationAgents ?? [];
896
- if (listed.length === 0) return [];
897
- const plan = planStationAgents({ vendor: readRememberedVendor(cwd).vendor });
898
- if (plan.kind !== "files") return [];
899
- const missing = [];
900
- const stale = [];
901
- for (const file of plan.files) {
902
- const path = join9(cwd, CLAUDE_AGENTS_FOLDER, file.name);
903
- if (!existsSync8(path)) missing.push(file.name);
904
- else if (listed.includes(file.name) && readFileSync5(path, "utf8") !== file.content)
905
- stale.push(file.name);
1142
+ function locallyExportedNames(source) {
1143
+ const names = /* @__PURE__ */ new Map();
1144
+ for (const statement of source.statements) {
1145
+ if (!ts5.isExportDeclaration(statement) || statement.moduleSpecifier !== void 0) continue;
1146
+ if (statement.isTypeOnly || statement.exportClause === void 0) continue;
1147
+ if (!ts5.isNamedExports(statement.exportClause)) continue;
1148
+ for (const element of statement.exportClause.elements) {
1149
+ if (element.isTypeOnly) continue;
1150
+ const local = (element.propertyName ?? element.name).text;
1151
+ names.set(local, [...names.get(local) ?? [], element.name.text]);
1152
+ }
906
1153
  }
907
- if (missing.length === 0 && stale.length === 0)
908
- return [{ status: "ok", subject: STATION_AGENTS_SUBJECT, detail: `${CLAUDE_AGENTS_FOLDER} in sync` }];
909
- const parts = [
910
- ...stale.length ? [`holds stale ${stale.join(", ")}`] : [],
911
- ...missing.length ? [`lacks ${missing.join(", ")}`] : []
912
- ];
913
- return [
914
- {
915
- status: "warning",
916
- subject: STATION_AGENTS_SUBJECT,
917
- detail: `${CLAUDE_AGENTS_FOLDER} ${parts.join("; ")}`,
918
- fix: SYNC_COMMAND
1154
+ return names;
1155
+ }
1156
+ function topLevelFunctionsOf(source) {
1157
+ const found = [];
1158
+ const overloads = /* @__PURE__ */ new Map();
1159
+ for (const statement of source.statements) {
1160
+ if (ts5.isFunctionDeclaration(statement) && statement.name !== void 0) {
1161
+ const name = statement.name.text;
1162
+ const set = [...overloads.get(name) ?? [], statement];
1163
+ if (statement.body === void 0) {
1164
+ overloads.set(name, set);
1165
+ continue;
1166
+ }
1167
+ overloads.delete(name);
1168
+ found.push({
1169
+ name,
1170
+ node: statement,
1171
+ declaration: set[0],
1172
+ documented: set.find(hasJsDoc) ?? statement,
1173
+ exported: set.some(isExported)
1174
+ });
1175
+ } else if (ts5.isVariableStatement(statement) && statement.declarationList.flags & ts5.NodeFlags.Const)
1176
+ found.push(...constFunctionsOf(statement));
1177
+ }
1178
+ return found;
1179
+ }
1180
+ function constFunctionsOf(statement) {
1181
+ const exported = isExported(statement);
1182
+ return statement.declarationList.declarations.flatMap(
1183
+ function functionOfDeclaration(declaration) {
1184
+ const { initializer, name } = declaration;
1185
+ if (!ts5.isIdentifier(name) || initializer === void 0) return [];
1186
+ if (!ts5.isArrowFunction(initializer) && !ts5.isFunctionExpression(initializer)) return [];
1187
+ return [{ name: name.text, node: initializer, declaration, documented: statement, exported }];
919
1188
  }
920
- ];
1189
+ );
921
1190
  }
922
-
923
- // src/lib/doctor/diagnose.ts
924
- function diagnose(context) {
925
- return [
926
- { status: "ok", subject: "dialecte", detail: `cli ${context.cliVersion} running` },
927
- ...installedPackages(context.cwd),
928
- ...profileLines(context.cwd),
929
- ...coreGenerations(context.cwd),
930
- ...skills(context.cwd),
931
- ...stationAgentLines(context.cwd),
932
- ...context.brief ? [] : localCheckouts(context)
933
- ];
1191
+ function hasJsDoc(node) {
1192
+ return ts5.getJSDocCommentsAndTags(node).some(ts5.isJSDoc);
934
1193
  }
935
- function installedPackages(cwd) {
936
- const declared = declaredVersions(cwd);
937
- return Object.keys(declared).filter((name) => name.startsWith(DIALECTE_SCOPE)).sort(TEXT_COLLATOR.compare).map(function packageLine(name) {
938
- const version = installedVersion({ cwd, name });
939
- if (version === void 0)
940
- return { status: "warning", subject: name, detail: "not installed", fix: INSTALL_COMMAND };
941
- const pinned = declared[name];
942
- if (/^\d/.test(pinned) && pinned !== version)
943
- return {
944
- status: "warning",
945
- subject: name,
946
- detail: `${version} installed, ${pinned} declared`,
947
- fix: INSTALL_COMMAND
948
- };
949
- return { status: "ok", subject: name, detail: version };
1194
+ function isExported(statement) {
1195
+ return ts5.canHaveModifiers(statement) && (ts5.getModifiers(statement) ?? []).some(function isExportKeyword(modifier) {
1196
+ return modifier.kind === ts5.SyntaxKind.ExportKeyword;
950
1197
  });
951
1198
  }
952
- function coreGenerations(cwd) {
953
- const dialectes = dependencyNames(cwd).sort(TEXT_COLLATOR.compare).flatMap(function dialecteOnCore(name) {
954
- const folder = findInstalledPackage({ cwd, name });
955
- return folder && dependsOnCore(folder) ? [{ name, folder }] : [];
956
- });
957
- const appCore = installedVersion({ cwd, name: CORE_PACKAGE2 });
958
- const owners = dialectes.length ? dialectes : [{ name: void 0, folder: cwd }];
959
- return owners.flatMap(function generationLine({ name, folder }) {
960
- const version = installedVersion({ cwd: folder, name: CORE_PACKAGE2 });
961
- if (version === void 0) return [];
962
- const [major = 0, minor = 0] = version.split(".").map(Number);
963
- const generation = CORE_API_GENERATIONS.find(
964
- ({ from }) => major > from[0] || major === from[0] && minor >= from[1]
965
- );
966
- if (!generation) return [];
967
- const says = `${generation.name}: ${generation.says}`;
968
- if (name && appCore !== void 0 && appCore !== version)
969
- return [
970
- {
971
- status: "warning",
972
- subject: "core API",
973
- detail: `${name} on core ${version}, your app on core ${appCore}: two cores side by side (${says})`,
974
- fix: ALIGN_CORE_FIX
975
- }
976
- ];
977
- const owner = name ? `${name} on core ${version}` : `core ${version}`;
978
- return [{ status: "ok", subject: "core API", detail: `${owner} - ${says}` }];
1199
+ function sourceEntry(params) {
1200
+ const { file, source, found } = params;
1201
+ const jsDoc = ts5.getJSDocCommentsAndTags(found.documented).filter(ts5.isJSDoc).at(-1);
1202
+ const line = source.getLineAndCharacterOfPosition(found.declaration.getStart(source)).line + 1;
1203
+ return {
1204
+ path: `${file}#${found.name}`,
1205
+ root: "source",
1206
+ entry: void 0,
1207
+ otherRoutes: [],
1208
+ signature: signatureOf2({ source, node: found.node }),
1209
+ summary: summaryOf(jsDoc),
1210
+ intents: intentsOf2(jsDoc),
1211
+ declaredAt: `${file}:${line}`,
1212
+ example: void 0
1213
+ };
1214
+ }
1215
+ function summaryOf(jsDoc) {
1216
+ const text = (ts5.getTextOfJSDocComment(jsDoc?.comment) ?? "").replace(/\s+/g, " ").trim();
1217
+ return text === "" ? void 0 : firstSentence(text);
1218
+ }
1219
+ function intentsOf2(jsDoc) {
1220
+ return (jsDoc?.tags ?? []).filter(function isIntentTag(tag) {
1221
+ return tag.tagName.text === INTENT_TAG;
1222
+ }).flatMap(function intentsOfTag(tag) {
1223
+ return parseIntentText(ts5.getTextOfJSDocComment(tag.comment) ?? "");
979
1224
  });
980
1225
  }
981
- function skills(cwd) {
982
- const { sources } = discoverSkillSources({ cwd });
983
- if (sources.length === 0)
984
- return [{ status: "ok", subject: "skills", detail: "no dependency ships skills" }];
985
- const synced = Object.values(AGENT_SKILL_FOLDERS).filter(
986
- (folder) => existsSync9(join10(cwd, folder, MANIFEST_FILE))
1226
+ function signatureOf2(params) {
1227
+ const { source, node } = params;
1228
+ function print(part) {
1229
+ return oneLine(SIGNATURE_PRINTER.printNode(ts5.EmitHint.Unspecified, part, source));
1230
+ }
1231
+ const typeParameters = node.typeParameters ? `<${node.typeParameters.map(print).join(", ")}>` : "";
1232
+ const returnType = node.type ? `: ${print(node.type)}` : "";
1233
+ return `${typeParameters}(${node.parameters.map(print).join(", ")})${returnType}`;
1234
+ }
1235
+ function oneLine(printed2) {
1236
+ const scanner = ts5.createScanner(
1237
+ ts5.ScriptTarget.Latest,
1238
+ false,
1239
+ ts5.LanguageVariant.Standard,
1240
+ printed2
987
1241
  );
988
- if (synced.length === 0)
989
- return [
990
- {
991
- status: "warning",
992
- subject: "skills",
993
- detail: `not installed for your agents (${sources.map((source) => source.name).join(", ")} shipped)`,
994
- fix: SYNC_COMMAND
995
- }
996
- ];
997
- const contributor = isContributor(cwd);
998
- return synced.map(function syncLine(folder) {
999
- const manifest = readSyncManifest(join10(cwd, folder));
1000
- const expected = selectAudience({
1001
- sources,
1002
- contributing: contributor || manifest.contributing === true
1003
- }).selected;
1004
- const missing = expected.map((source) => source.name).filter((name) => !manifest.installed.includes(name));
1005
- if (missing.length)
1006
- return {
1007
- status: "warning",
1008
- subject: "skills",
1009
- detail: `${folder} lacks ${missing.join(", ")}`,
1010
- fix: SYNC_COMMAND
1011
- };
1012
- const stale = expected.flatMap(function staleCopy(source) {
1013
- const recorded = manifest.versions[source.name];
1014
- if (isLink(join10(cwd, folder, source.name)) || source.version === void 0) return [];
1015
- if (recorded?.version === source.version) return [];
1016
- return [
1017
- `${source.name} of ${source.origin} ${recorded?.version ?? "an unknown version"}, ${source.version} installed`
1018
- ];
1242
+ const tokens = [];
1243
+ const open = [];
1244
+ let spaced = false;
1245
+ for (let kind = scanner.scan(); kind !== ts5.SyntaxKind.EndOfFileToken; kind = scanner.scan()) {
1246
+ if (kind === ts5.SyntaxKind.WhitespaceTrivia || kind === ts5.SyntaxKind.NewLineTrivia) {
1247
+ spaced = tokens.length > 0;
1248
+ continue;
1249
+ }
1250
+ if (kind === ts5.SyntaxKind.CloseBraceToken && open.at(-1) === ts5.SyntaxKind.TemplateHead) {
1251
+ kind = scanner.reScanTemplateToken(false);
1252
+ if (kind === ts5.SyntaxKind.TemplateTail) open.pop();
1253
+ } else if (kind === ts5.SyntaxKind.OpenBraceToken || kind === ts5.SyntaxKind.TemplateHead)
1254
+ open.push(kind);
1255
+ else if (kind === ts5.SyntaxKind.CloseBraceToken) open.pop();
1256
+ tokens.push({ kind, text: scanner.getTokenText(), spaced });
1257
+ spaced = false;
1258
+ }
1259
+ return tokens.filter(function keptToken(token, index) {
1260
+ return !(token.kind === ts5.SyntaxKind.SemicolonToken && tokens[index + 1]?.kind === ts5.SyntaxKind.CloseBraceToken);
1261
+ }).map(function textOfToken(token) {
1262
+ return token.spaced ? ` ${token.text}` : token.text;
1263
+ }).join("");
1264
+ }
1265
+
1266
+ // src/lib/api/source-index.ts
1267
+ import { createHash } from "crypto";
1268
+ import { readFileSync as readFileSync10 } from "fs";
1269
+ import { join as join17 } from "path";
1270
+
1271
+ // src/lib/read-cli-version.ts
1272
+ import { existsSync as existsSync12, readFileSync as readFileSync9 } from "fs";
1273
+ import { dirname as dirname10, join as join16 } from "path";
1274
+ import { fileURLToPath } from "url";
1275
+ function readCliVersion(params = {}) {
1276
+ const startFolder = params.startFolder ?? dirname10(fileURLToPath(import.meta.url));
1277
+ let folder = startFolder;
1278
+ while (!existsSync12(join16(folder, "package.json"))) {
1279
+ const parent = dirname10(folder);
1280
+ if (parent === folder)
1281
+ throw new Error(`no package.json above ${startFolder}: cannot read the cli version`);
1282
+ folder = parent;
1283
+ }
1284
+ const { version } = JSON.parse(readFileSync9(join16(folder, "package.json"), "utf8"));
1285
+ return version;
1286
+ }
1287
+
1288
+ // src/lib/api/source-index.ts
1289
+ function indexSourceFiles(params) {
1290
+ const { root, files, parse: parse2 } = params;
1291
+ if (!isInWorkTree(root))
1292
+ return files.map(function parseFile(file) {
1293
+ return parse2({ file, text: readFileSync10(join17(root, file), "utf8") });
1019
1294
  });
1020
- if (stale.length)
1021
- return {
1022
- status: "warning",
1023
- subject: "skills",
1024
- detail: `${folder} holds ${stale.join("; ")}`,
1025
- fix: SYNC_COMMAND
1026
- };
1027
- return { status: "ok", subject: "skills", detail: `${folder} in sync with node_modules` };
1295
+ const cacheFile = join17(gitFolderOf(root), SOURCE_INDEX_FILE);
1296
+ const reader = readCliVersion();
1297
+ const prefix = readGit({ root, args: ["rev-parse", "--show-prefix"] }).trim();
1298
+ const cached = readCache({ cacheFile, reader });
1299
+ let changed = cached === void 0;
1300
+ const next = {
1301
+ schema: SOURCE_INDEX_SCHEMA,
1302
+ reader,
1303
+ files: othersFiles({ cached, prefix, files })
1304
+ };
1305
+ const answer = files.map(function parseChangedFile(file) {
1306
+ const key = `${prefix}${file}`;
1307
+ const bytes = readFileSync10(join17(root, file));
1308
+ const hash = createHash("sha256").update(bytes).digest("hex");
1309
+ const known = cached?.files[key];
1310
+ if (known !== void 0 && known.hash === hash) {
1311
+ next.files[key] = known;
1312
+ return parsedOf(known);
1313
+ }
1314
+ changed = true;
1315
+ const parsed = parse2({ file, text: bytes.toString("utf8") });
1316
+ next.files[key] = { hash, ...parsed };
1317
+ return parsed;
1028
1318
  });
1319
+ if (cached !== void 0 && Object.keys(cached.files).length !== Object.keys(next.files).length)
1320
+ changed = true;
1321
+ if (changed) writeCache({ cacheFile, cache: next });
1322
+ return answer;
1323
+ }
1324
+ function othersFiles(params) {
1325
+ const { prefix } = params;
1326
+ const folders = new Set(params.files.map(topFolderOf));
1327
+ return Object.fromEntries(
1328
+ Object.entries(params.cached?.files ?? {}).filter(function isOthers([key]) {
1329
+ return !(key.startsWith(prefix) && folders.has(topFolderOf(key.slice(prefix.length))));
1330
+ })
1331
+ );
1029
1332
  }
1030
- function isContributor(cwd) {
1333
+ function topFolderOf(path) {
1334
+ return path.split("/", 1)[0];
1335
+ }
1336
+ function readCache(params) {
1337
+ let value;
1031
1338
  try {
1032
- return readProfile(cwd) === "contributor";
1339
+ value = JSON.parse(readFileSync10(params.cacheFile, "utf8"));
1033
1340
  } catch {
1034
- return false;
1341
+ return void 0;
1035
1342
  }
1343
+ return isCache(value) && value.reader === params.reader ? value : void 0;
1344
+ }
1345
+ function isCache(value) {
1346
+ if (typeof value !== "object" || value === null) return false;
1347
+ const { schema, files } = value;
1348
+ if (schema !== SOURCE_INDEX_SCHEMA || typeof files !== "object" || files === null) return false;
1349
+ return Object.values(files).every(function isCachedFile(file) {
1350
+ if (typeof file !== "object" || file === null) return false;
1351
+ const { hash, entries, note } = file;
1352
+ return typeof hash === "string" && Array.isArray(entries) && entries.every(isCachedEntry) && (note === void 0 || typeof note === "string");
1353
+ });
1036
1354
  }
1037
- function isLink(path) {
1355
+ function isCachedEntry(value) {
1356
+ if (typeof value !== "object" || value === null) return false;
1357
+ const entry = value;
1358
+ return typeof entry.path === "string" && entry.root === "source" && typeof entry.signature === "string" && typeof entry.declaredAt === "string" && isStringList(entry.otherRoutes) && isStringList(entry.intents) && (entry.summary === void 0 || typeof entry.summary === "string");
1359
+ }
1360
+ function isStringList(value) {
1361
+ return Array.isArray(value) && value.every(function isString(item) {
1362
+ return typeof item === "string";
1363
+ });
1364
+ }
1365
+ function parsedOf(known) {
1366
+ return known.note === void 0 ? { entries: known.entries } : { entries: known.entries, note: known.note };
1367
+ }
1368
+ function writeCache(params) {
1038
1369
  try {
1039
- return lstatSync3(path).isSymbolicLink();
1370
+ replaceWhole({ path: params.cacheFile, text: JSON.stringify(params.cache) });
1040
1371
  } catch {
1041
- return false;
1042
1372
  }
1043
1373
  }
1044
- function dependsOnCore(folder) {
1045
- const manifest = JSON.parse(readFileSync6(join10(folder, "package.json"), "utf8"));
1046
- return manifest.name !== CORE_PACKAGE2 && (manifest.dependencies?.[CORE_PACKAGE2] !== void 0 || manifest.peerDependencies?.[CORE_PACKAGE2] !== void 0);
1374
+
1375
+ // src/lib/api/source-functions.ts
1376
+ function readSourceFunctions(params) {
1377
+ const { root } = params;
1378
+ const folder = join18(root, SOURCE_FOLDER);
1379
+ if (!isFolder(folder))
1380
+ return { entries: [], notes: [NO_SOURCE_FOLDER_NOTE.replace("{root}", root)] };
1381
+ const parsedFiles = indexSourceFiles({
1382
+ root,
1383
+ files: listSourceFiles(root),
1384
+ parse: params.parse ?? parseSourceFile
1385
+ });
1386
+ return {
1387
+ entries: parsedFiles.flatMap(function entriesOfFile(parsed) {
1388
+ return parsed.entries;
1389
+ }),
1390
+ notes: parsedFiles.flatMap(function noteOfFile(parsed) {
1391
+ return parsed.note === void 0 ? [] : [parsed.note];
1392
+ })
1393
+ };
1047
1394
  }
1048
- function localCheckouts(context) {
1049
- const roots = [
1050
- ...new Set([context.dialecteRoot, dirname3(resolve2(context.cwd))].filter(isDefined2))
1051
- ];
1052
- return roots.map(function checkoutLine(root) {
1053
- const names = existsSync9(root) ? readdirSync4(root, { withFileTypes: true }).filter((entry) => entry.isDirectory() && join10(root, entry.name) !== resolve2(context.cwd)).filter((entry) => packageName(join10(root, entry.name))?.startsWith(DIALECTE_SCOPE)).map((entry) => entry.name).sort(TEXT_COLLATOR.compare) : [];
1395
+ function listSourceFiles(root) {
1396
+ const files = isInWorkTree(root) ? listRepositoryFiles({ root, folder: SOURCE_FOLDER }).filter(function isOnDisk(file) {
1397
+ return existsSync13(join18(root, file));
1398
+ }) : listTreeFiles(join18(root, SOURCE_FOLDER)).map(function pathFromRoot(file) {
1399
+ return `${SOURCE_FOLDER}/${file}`;
1400
+ });
1401
+ return files.filter(function isSourceFile(file) {
1402
+ return SOURCE_FILE_PATTERN.test(file) && !TEST_FILE_PATTERN.test(file);
1403
+ }).sort(TEXT_COLLATOR.compare);
1404
+ }
1405
+
1406
+ // src/lib/api/source-lookup.ts
1407
+ function isSourcePath(path) {
1408
+ return path.includes(SOURCE_PATH_MARK);
1409
+ }
1410
+ function sourceRootOf(params) {
1411
+ const root = packageRootOf(params.cwd);
1412
+ if (root !== void 0) return { root };
1413
+ return {
1414
+ refusal: {
1415
+ output: textOf([
1416
+ NO_PACKAGE_TEXT.replace("{command}", params.command).replace("{cwd}", params.cwd),
1417
+ ""
1418
+ ]),
1419
+ exitCode: 2
1420
+ }
1421
+ };
1422
+ }
1423
+ function searchedIndexesOf(params) {
1424
+ const { indexes } = params;
1425
+ const source = readSourceIndex(params);
1426
+ if (source === void 0) return { indexes, notes: [] };
1427
+ return {
1428
+ indexes: [...indexes, withoutIndexed({ source: source.index, indexes })],
1429
+ notes: source.notes
1430
+ };
1431
+ }
1432
+ function showSource(params) {
1433
+ const source = readSourceIndex(params);
1434
+ const notes = source?.notes ?? [];
1435
+ const methods = findByPath({ indexes: source ? [source.index] : [], path: params.path });
1436
+ if (methods.length === 0 && !params.json)
1054
1437
  return {
1055
- status: "ok",
1056
- subject: "checkouts",
1057
- detail: names.length ? `${root}: ${names.slice(0, CHECKOUT_LIST_LIMIT).join(", ")}${names.length > CHECKOUT_LIST_LIMIT ? ` and ${names.length - CHECKOUT_LIST_LIMIT} more` : ""}` : `none in ${root} (the installed packages are the source)`
1438
+ output: textOf([
1439
+ unknownSourceText({
1440
+ path: params.path,
1441
+ root: params.root,
1442
+ methods: source?.index.methods ?? []
1443
+ }),
1444
+ ...noteLinesOf(notes),
1445
+ ""
1446
+ ]),
1447
+ exitCode: 1
1058
1448
  };
1059
- });
1449
+ return {
1450
+ output: renderShown({ methods, json: params.json, notes }),
1451
+ exitCode: methods.length ? 0 : 1
1452
+ };
1060
1453
  }
1061
- function declaredVersions(cwd) {
1062
- const manifest = JSON.parse(readFileSync6(join10(cwd, "package.json"), "utf8"));
1063
- const names = dependencyNames(cwd);
1064
- return Object.fromEntries(
1065
- names.map((name) => [
1066
- name,
1067
- String(
1068
- manifest.dependencies?.[name] ?? manifest.devDependencies?.[name] ?? manifest.peerDependencies?.[name]
1069
- )
1070
- ])
1454
+ function readSourceIndex(params) {
1455
+ const ownName = packageNameOf(params.root);
1456
+ if (params.packageName !== void 0 && params.packageName !== ownName) return void 0;
1457
+ const { entries, notes } = readSourceFunctions({ root: params.root });
1458
+ return { index: { package: ownName, methods: entries }, notes };
1459
+ }
1460
+ function withoutIndexed(params) {
1461
+ const { source } = params;
1462
+ const indexedAt = new Set(
1463
+ params.indexes.filter(function isSamePackage(index) {
1464
+ return index.package === source.package;
1465
+ }).flatMap(function declaredAtOfIndex(index) {
1466
+ return index.methods.flatMap(function declaredAtOfMethod(method) {
1467
+ return method.declaredAt === void 0 ? [] : [method.declaredAt];
1468
+ });
1469
+ })
1071
1470
  );
1471
+ return {
1472
+ package: source.package,
1473
+ methods: source.methods.filter(function isNotIndexed(method) {
1474
+ return method.declaredAt === void 0 || !indexedAt.has(method.declaredAt);
1475
+ })
1476
+ };
1477
+ }
1478
+ function unknownSourceText(params) {
1479
+ const closest = closestSourcePaths(params);
1480
+ const text = closest.length ? UNKNOWN_SOURCE_CLOSEST_TEXT : UNKNOWN_SOURCE_TEXT;
1481
+ return text.replace("{path}", params.path).replace("{root}", params.root).replace("{closest}", closest.join(", "));
1482
+ }
1483
+ function closestSourcePaths(params) {
1484
+ const paths = params.methods.map(function pathOfMethod(method) {
1485
+ return method.path;
1486
+ });
1487
+ const mark = params.path.lastIndexOf(SOURCE_PATH_MARK);
1488
+ const filePrefix = params.path.slice(0, mark + SOURCE_PATH_MARK.length);
1489
+ const names = paths.filter(function isOfTheFile(path) {
1490
+ return path.startsWith(filePrefix);
1491
+ }).map(function nameOfPath(path) {
1492
+ return path.slice(filePrefix.length);
1493
+ });
1494
+ if (names.length === 0)
1495
+ return closestNames({ name: params.path, candidates: paths, limit: SOURCE_SUGGESTION_LIMIT });
1496
+ const close = closestNames({
1497
+ name: params.path.slice(filePrefix.length),
1498
+ candidates: names,
1499
+ limit: SOURCE_SUGGESTION_LIMIT
1500
+ });
1501
+ const others = names.filter(function isNotClose(name) {
1502
+ return !close.includes(name);
1503
+ });
1504
+ return [...close, ...others].slice(0, SOURCE_SUGGESTION_LIMIT).map(function pathOfName(name) {
1505
+ return `${filePrefix}${name}`;
1506
+ });
1507
+ }
1508
+
1509
+ // src/lib/config.ts
1510
+ import { readFileSync as readFileSync11, existsSync as existsSync14, readdirSync as readdirSync9, statSync as statSync5 } from "fs";
1511
+ import { join as join19 } from "path";
1512
+
1513
+ // src/lib/config.constants.ts
1514
+ var CORE_PACKAGE = "@dialecte/core";
1515
+ var CORE_TEST_DIALECT = {
1516
+ version: "core",
1517
+ binding: {
1518
+ kind: "core",
1519
+ coreAlias: "Core",
1520
+ coreImport: "@/index",
1521
+ configType: "TestDialecteConfig",
1522
+ configImport: "@/test/config"
1523
+ },
1524
+ constantsDir: "./src/test/generated",
1525
+ outDir: "./benchmarks/types/generated"
1526
+ };
1527
+
1528
+ // src/lib/config.ts
1529
+ function getArg(argv, name) {
1530
+ const index = argv.indexOf(`--${name}`);
1531
+ return index >= 0 ? argv[index + 1] : void 0;
1072
1532
  }
1073
- function installedVersion(params) {
1074
- const folder = findInstalledPackage(params);
1075
- if (!folder || !existsSync9(join10(folder, "package.json"))) return void 0;
1076
- const version = JSON.parse(readFileSync6(join10(folder, "package.json"), "utf8")).version;
1077
- return typeof version === "string" ? version : void 0;
1533
+ function hasFlag(argv, name) {
1534
+ return argv.includes(`--${name}`);
1078
1535
  }
1079
- function packageName(folder) {
1080
- const path = join10(folder, "package.json");
1081
- if (!existsSync9(path)) return void 0;
1082
- const name = JSON.parse(readFileSync6(path, "utf8")).name;
1083
- return typeof name === "string" ? name : void 0;
1536
+ function positionalArguments(params) {
1537
+ const words = [];
1538
+ for (let index = 0; index < params.argv.length; index++) {
1539
+ const argument = params.argv[index];
1540
+ if (!argument.startsWith("--")) words.push(argument);
1541
+ else if (params.valueOptions.includes(argument.slice(2))) index++;
1542
+ }
1543
+ return words;
1084
1544
  }
1085
- function isDefined2(value) {
1086
- return value !== void 0;
1545
+ function tsconfigOf(argv, cwd = process.cwd()) {
1546
+ return getArg(argv, "tsconfig") ?? pkgConfig(cwd).tsconfig ?? "tsconfig.build.json";
1087
1547
  }
1088
-
1089
- // src/lib/read-cli-version.ts
1090
- import { existsSync as existsSync10, readFileSync as readFileSync7 } from "fs";
1091
- import { dirname as dirname4, join as join11 } from "path";
1092
- import { fileURLToPath } from "url";
1093
- function readCliVersion(params = {}) {
1094
- const startFolder = params.startFolder ?? dirname4(fileURLToPath(import.meta.url));
1095
- let folder = startFolder;
1096
- while (!existsSync10(join11(folder, "package.json"))) {
1097
- const parent = dirname4(folder);
1098
- if (parent === folder)
1099
- throw new Error(`no package.json above ${startFolder}: cannot read the cli version`);
1100
- folder = parent;
1101
- }
1102
- const { version } = JSON.parse(readFileSync7(join11(folder, "package.json"), "utf8"));
1103
- return version;
1548
+ function readPkg(cwd) {
1549
+ const packageJson = join19(cwd, "package.json");
1550
+ return existsSync14(packageJson) ? JSON.parse(readFileSync11(packageJson, "utf8")) : {};
1104
1551
  }
1105
-
1106
- // src/commands/doctor.ts
1107
- function runDoctor(params) {
1108
- const { argv, cliVersion, ...rest } = params;
1109
- if (hasFlag([...argv], "brief")) return runBrief({ ...rest, cliVersion });
1110
- const missing = missingPackage({ cwd: params.cwd });
1111
- if (missing) return missing;
1112
- return answerDoctor({
1113
- lines: diagnose({ ...rest, cliVersion: resolveVersion(cliVersion) }),
1114
- json: hasFlag([...argv], "json")
1115
- });
1552
+ function pkgConfig(cwd) {
1553
+ return readPkg(cwd).dialecte ?? {};
1116
1554
  }
1117
- function runBrief(context) {
1118
- try {
1119
- return answerDoctorBrief(
1120
- diagnose({ ...context, cliVersion: resolveVersion(context.cliVersion), brief: true })
1121
- );
1122
- } catch {
1123
- return { output: "", exitCode: 0 };
1124
- }
1555
+ function capitalize(word) {
1556
+ return word.charAt(0).toUpperCase() + word.slice(1);
1125
1557
  }
1126
- function resolveVersion(cliVersion) {
1127
- return typeof cliVersion === "string" ? cliVersion : cliVersion();
1558
+ function discoverNamespace(cwd) {
1559
+ return capitalize(
1560
+ String(readPkg(cwd).name ?? "dialecte").split("/").pop() ?? "dialecte"
1561
+ );
1128
1562
  }
1129
-
1130
- // src/lib/closest-names.ts
1131
- function closestNames(params) {
1132
- const name = params.name.toLowerCase();
1133
- const threshold = Math.max(2, Math.floor(name.length / 3));
1134
- return params.candidates.map((candidate) => ({
1135
- candidate,
1136
- distance: candidate.toLowerCase().includes(name) ? 0 : editDistance({ from: name, to: candidate.toLowerCase() })
1137
- })).filter(({ distance }) => distance <= threshold).sort(
1138
- (left, right) => left.distance - right.distance || TEXT_COLLATOR.compare(left.candidate, right.candidate)
1139
- ).slice(0, params.limit).map(({ candidate }) => candidate);
1563
+ function discoverVersions(cwd) {
1564
+ const src = join19(cwd, "src");
1565
+ if (!existsSync14(src)) return [];
1566
+ return readdirSync9(src).filter((v) => statSync5(join19(src, v)).isDirectory()).filter(
1567
+ (v) => existsSync14(join19(src, v, "definition", "constants.generated.ts")) && existsSync14(join19(src, v, "definition", "definition.generated.ts"))
1568
+ ).sort();
1140
1569
  }
1141
- function editDistance(params) {
1142
- const { from, to } = params;
1143
- let previous = Array.from({ length: to.length + 1 }, (_, index) => index);
1144
- for (let row = 1; row <= from.length; row++) {
1145
- const current = [row];
1146
- for (let column = 1; column <= to.length; column++)
1147
- current[column] = Math.min(
1148
- previous[column] + 1,
1149
- current[column - 1] + 1,
1150
- previous[column - 1] + (from[row - 1] === to[column - 1] ? 0 : 1)
1151
- );
1152
- previous = current;
1153
- }
1154
- return previous[to.length];
1570
+ function resolveTargets(argv, cwd = process.cwd()) {
1571
+ if (readPkg(cwd).name === CORE_PACKAGE)
1572
+ return [
1573
+ {
1574
+ ...CORE_TEST_DIALECT,
1575
+ version: getArg(argv, "version") ?? CORE_TEST_DIALECT.version,
1576
+ constantsDir: getArg(argv, "constants-dir") ?? CORE_TEST_DIALECT.constantsDir,
1577
+ outDir: getArg(argv, "out") ?? CORE_TEST_DIALECT.outDir
1578
+ }
1579
+ ];
1580
+ const cfg = pkgConfig(cwd);
1581
+ const namespace = getArg(argv, "namespace") ?? cfg.namespace ?? discoverNamespace(cwd);
1582
+ const only = getArg(argv, "version");
1583
+ let versions = discoverVersions(cwd);
1584
+ if (only) versions = versions.filter((v) => v === only);
1585
+ if (!versions.length && (getArg(argv, "constants-dir") || getArg(argv, "entry")))
1586
+ versions = [only ?? "default"];
1587
+ return versions.map((version) => {
1588
+ const entry = getArg(argv, "entry") ?? cfg.entry ?? `@/${version}`;
1589
+ return {
1590
+ version,
1591
+ binding: { kind: "namespace", name: namespace, import: entry },
1592
+ constantsDir: getArg(argv, "constants-dir") ?? cfg.constantsDir ?? `./src/${version}/definition`,
1593
+ outDir: getArg(argv, "out") ?? cfg.out ?? `./benchmarks/types/${version}/generated`
1594
+ };
1595
+ });
1155
1596
  }
1156
1597
 
1157
- // src/lib/api/list-members.ts
1158
- function listMembers(params) {
1159
- const path = discoveryPath(params.expression);
1160
- const exact = params.entries.find((entry) => entry.path === path);
1161
- if (exact) return [methodMember({ entry: exact, name: lastSegment(path) })];
1162
- const methods = [];
1163
- const methodCountByGroup = /* @__PURE__ */ new Map();
1164
- for (const entry of params.entries) {
1165
- if (!entry.path.startsWith(`${path}.`)) continue;
1166
- const [name, ...below] = entry.path.slice(path.length + 1).split(".");
1167
- if (below.length === 0) methods.push(methodMember({ entry, name }));
1168
- else methodCountByGroup.set(name, (methodCountByGroup.get(name) ?? 0) + 1);
1598
+ // src/lib/missing-package.ts
1599
+ import { existsSync as existsSync15 } from "fs";
1600
+ import { join as join20 } from "path";
1601
+ function missingPackage(params) {
1602
+ return existsSync15(join20(params.cwd, "package.json")) ? void 0 : {
1603
+ output: textOf([
1604
+ `no package.json in ${params.cwd}: run dialecte in your package's folder`,
1605
+ ""
1606
+ ]),
1607
+ exitCode: 2
1608
+ };
1609
+ }
1610
+
1611
+ // src/commands/api.constants.ts
1612
+ var API_SUBCOMMANDS = ["find", "show"];
1613
+ var API_VALUE_OPTIONS = ["package", "limit"];
1614
+ var DEFAULT_FIND_LIMIT = 5;
1615
+ var SOURCE_FLAG = "source";
1616
+ var API_USAGE = 'usage: dialecte api find "<need>" [--source] [--package <name>] [--limit 5] [--json] | dialecte api show <path> [--json] | dialecte api show <file>#<name> [--json]';
1617
+
1618
+ // src/commands/api.ts
1619
+ function runApi(params) {
1620
+ const [subcommand, ...rest] = params.argv;
1621
+ const words = positionalArguments({ argv: rest, valueOptions: API_VALUE_OPTIONS });
1622
+ const sourceFlag = hasFlag([...rest], SOURCE_FLAG);
1623
+ const reachesSource = sourceFlag || subcommand === "show" && isSourcePath(words[0] ?? "");
1624
+ if (!reachesSource) {
1625
+ const missing = missingPackage({ cwd: params.cwd });
1626
+ if (missing) return missing;
1169
1627
  }
1170
- const groups = [...methodCountByGroup].map(([name, methodCount]) => ({
1171
- kind: "group",
1172
- name,
1173
- methodCount
1174
- }));
1175
- return [...methods.sort(byName), ...groups.sort(byName)];
1628
+ const limit = Number(getArg([...rest], "limit") ?? DEFAULT_FIND_LIMIT);
1629
+ if (!isSubcommand(subcommand) || words.length === 0 || !Number.isInteger(limit) || limit < 1)
1630
+ return { output: textOf([API_USAGE, ""]), exitCode: 2 };
1631
+ const packageName2 = getArg([...rest], "package");
1632
+ const json = hasFlag([...rest], "json");
1633
+ const sourceRoot = reachesSource ? sourceRootOf({
1634
+ cwd: params.cwd,
1635
+ command: ["api", subcommand, ...sourceFlag ? [`--${SOURCE_FLAG}`] : []].join(" ")
1636
+ }) : { root: params.cwd };
1637
+ if ("refusal" in sourceRoot) return sourceRoot.refusal;
1638
+ const { root } = sourceRoot;
1639
+ if (reachesSource && subcommand === "show" && isSourcePath(words[0]))
1640
+ return showSource({ root, packageName: packageName2, path: words[0], json });
1641
+ const installed = readApiIndexes({ cwd: root }).filter(
1642
+ (index) => packageName2 === void 0 || index.package === packageName2
1643
+ );
1644
+ const { indexes, notes } = reachesSource ? searchedIndexesOf({ root, packageName: packageName2, indexes: installed }) : { indexes: installed, notes: void 0 };
1645
+ return subcommand === "find" ? find({ indexes, need: words.join(" "), limit, json, notes }) : show({ indexes, path: words[0], json, notes });
1176
1646
  }
1177
- function discoveryPath(expression) {
1178
- return expression.replace(/^(doc\.query|query)(?=\.|$)/, "q");
1647
+ function isSubcommand(value) {
1648
+ return API_SUBCOMMANDS.some((subcommand) => subcommand === value);
1179
1649
  }
1180
- function methodMember(params) {
1650
+ function find(params) {
1651
+ const found = findMethods(params);
1652
+ if (found.length === 0 && !params.json)
1653
+ return {
1654
+ output: textOf([
1655
+ `no method found for "${params.need}" in ${packagesText(params.indexes)}: try other words, or \`npx @dialecte/cli members <expression>\` for the live types`,
1656
+ ...noteLinesOf(params.notes),
1657
+ ""
1658
+ ]),
1659
+ exitCode: 1
1660
+ };
1181
1661
  return {
1182
- kind: "method",
1183
- name: params.name,
1184
- summary: params.entry.summary,
1185
- intents: params.entry.intents
1662
+ output: renderFound({ need: params.need, found, json: params.json, notes: params.notes }),
1663
+ exitCode: found.length ? 0 : 1
1186
1664
  };
1187
1665
  }
1188
- function lastSegment(path) {
1189
- return path.slice(path.lastIndexOf(".") + 1);
1666
+ function show(params) {
1667
+ const methods = findByPath(params);
1668
+ if (methods.length === 0 && !params.json)
1669
+ return {
1670
+ output: textOf([
1671
+ `no method "${params.path}" in ${packagesText(params.indexes)}: \`npx @dialecte/cli api find "<what you need>"\` lists the routes`,
1672
+ ...noteLinesOf(params.notes),
1673
+ ""
1674
+ ]),
1675
+ exitCode: 1
1676
+ };
1677
+ return {
1678
+ output: renderShown({ methods, json: params.json, notes: params.notes }),
1679
+ exitCode: methods.length ? 0 : 1
1680
+ };
1190
1681
  }
1191
- function byName(left, right) {
1192
- return TEXT_COLLATOR.compare(left.name, right.name);
1682
+ function packagesText(indexes) {
1683
+ return indexes.length ? [...new Set(indexes.map((index) => index.package))].join(", ") : "no installed package (none ships skills/<name>/references/api.json)";
1193
1684
  }
1194
1685
 
1195
- // src/lib/api/answer-members.ts
1196
- function answerMembers(params) {
1197
- const { expression } = params;
1198
- const members = listMembers(params);
1199
- if (params.json)
1200
- return {
1201
- output: `${JSON.stringify({ expression, members }, null, " ")}
1202
- `,
1203
- exitCode: members.length ? 0 : 1
1204
- };
1205
- if (members.length)
1206
- return { output: `${[expression, ...members.map(memberLine)].join("\n")}
1207
- `, exitCode: 0 };
1208
- const parent = expression.slice(0, Math.max(0, expression.lastIndexOf(".")));
1209
- const neighbours = parent ? listMembers({ entries: params.entries, expression: parent }).map((member) => member.name) : [];
1210
- const closest = closestNames({
1211
- name: expression.slice(expression.lastIndexOf(".") + 1),
1212
- candidates: neighbours,
1213
- limit: MEMBER_SUGGESTION_LIMIT
1214
- });
1215
- const hint = parent ? ` - under ${parent}: ${(closest.length ? closest : neighbours).join(", ") || "nothing"}` : "";
1216
- return { output: `nothing at ${expression}${hint}
1217
- `, exitCode: 1 };
1686
+ // src/lib/doctor/answer-doctor.ts
1687
+ function answerDoctor(params) {
1688
+ const exitCode = params.lines.some((line) => line.status !== "ok") ? 1 : 0;
1689
+ if (params.json) return { output: endedOf(jsonOf({ lines: params.lines }, " ")), exitCode };
1690
+ return { output: endedTextOf2(params.lines.map(renderLine)), exitCode };
1218
1691
  }
1219
- function memberLine(member) {
1220
- if (member.kind === "group")
1221
- return ` ${member.name}. ${member.methodCount} method${member.methodCount === 1 ? "" : "s"}`;
1222
- return member.summary ? ` ${member.name}() ${shortSummary(member.summary)}` : ` ${member.name}()`;
1692
+ function answerDoctorBrief(lines) {
1693
+ return {
1694
+ output: endedTextOf2(lines.filter((line) => line.status !== "ok").map(renderLine)),
1695
+ exitCode: 0
1696
+ };
1697
+ }
1698
+ function endedTextOf2(lines) {
1699
+ return textOf(lines.length === 0 ? [] : [...lines, ""]);
1700
+ }
1701
+ function renderLine(line) {
1702
+ if (line.status === "ok") return `\u2705 ${line.subject} ${line.detail}`;
1703
+ const fix = line.fix ? ` - fix: ${line.fix}` : "";
1704
+ return line.status === "error" ? `\u274C ${line.subject} ${line.detail}${fix}` : `\u26A0\uFE0F ${line.subject} ${line.detail}${fix}`;
1223
1705
  }
1224
1706
 
1225
- // src/lib/namespace-of.ts
1226
- function namespaceOf(packageName2) {
1227
- const name = packageName2.split("/").pop() || "dialecte";
1228
- return name.charAt(0).toUpperCase() + name.slice(1);
1707
+ // src/lib/doctor/diagnose.ts
1708
+ import { existsSync as existsSync19, lstatSync as lstatSync5, readdirSync as readdirSync10, readFileSync as readFileSync13 } from "fs";
1709
+ import { dirname as dirname11, join as join24, resolve as resolve5 } from "path";
1710
+
1711
+ // src/lib/profile/profile.constants.ts
1712
+ var PROFILES = ["contributor", "consumer"];
1713
+ var DEFAULT_PROFILE = "consumer";
1714
+ var INVALID_PROFILE = "dialecte.profile: {value} is not a profile; profiles: contributor, consumer";
1715
+
1716
+ // src/lib/profile/profile.ts
1717
+ function readProfile(root) {
1718
+ const declared = readPackageJson(root).dialecte?.profile;
1719
+ if (declared === void 0) return DEFAULT_PROFILE;
1720
+ const profile = PROFILES.find((known) => known === declared);
1721
+ if (!profile) throw new Error(INVALID_PROFILE.replace("{value}", JSON.stringify(declared)));
1722
+ return profile;
1229
1723
  }
1230
1724
 
1231
- // src/lib/schema/load-dialectes.ts
1232
- import { existsSync as existsSync11, readFileSync as readFileSync8 } from "fs";
1233
- import { createRequire } from "module";
1234
- import { join as join12 } from "path";
1235
- import { pathToFileURL } from "url";
1725
+ // src/lib/doctor/doctor.constants.ts
1726
+ var DIALECTE_SCOPE = "@dialecte/";
1727
+ var CORE_PACKAGE2 = "@dialecte/core";
1728
+ var SYNC_COMMAND = "npx @dialecte/cli skills sync";
1729
+ var INSTALL_COMMAND = "npm install";
1730
+ var ALIGN_CORE_FIX = "align @dialecte/core with the version the dialecte pins (or upgrade the dialecte), then npm install";
1731
+ var CORE_API_GENERATIONS = [
1732
+ {
1733
+ from: [0, 7],
1734
+ name: "0.7",
1735
+ says: "import inside the store (project.importFile answers { documentId, diagnostics }), per-file IO hook session, createTestHelpers"
1736
+ },
1737
+ {
1738
+ from: [0, 0],
1739
+ name: "0.6",
1740
+ says: "import and IO hooks before the store owned them: read the skills of this version, not the latest docs"
1741
+ }
1742
+ ];
1743
+ var CHECKOUT_LIST_LIMIT = 8;
1744
+ var STATION_AGENTS_SUBJECT = "station agents";
1745
+ var PROFILE_SUBJECT = "profile";
1746
+ var CONSUMER_ALLOWS_REFERENCES = "allowReferences is the consumer default: remove it";
1747
+ var CONTRIBUTOR_GATE_STEPS = "dialecte.gate.full holds {steps}: dialecte contrib runs them, move them to dialecte.contrib.steps (or drop them for the defaults)";
1748
+ var CONTRIBUTOR_SKILLS_NOT_SYNCED = "{folder} lacks the contributor skills: dialecte skills sync installs them in a contributor";
1749
+
1750
+ // src/lib/doctor/profile-lines.ts
1751
+ import { existsSync as existsSync16 } from "fs";
1752
+ import { join as join21 } from "path";
1236
1753
 
1237
- // src/lib/schema/schema.constants.ts
1238
- var CORE_PACKAGE3 = "@dialecte/core";
1239
- var CORE_READERS_ENTRY = "@dialecte/core/utils";
1240
- var CORE_READER_NAMES = [
1241
- "resolveDefinition",
1242
- "getAttributeRules",
1243
- "enumeratedValues",
1244
- "valuePatterns",
1245
- "admittedXsiTypes",
1246
- "childOccurrences",
1247
- "orderByConfigSequence"
1754
+ // src/lib/contrib/contrib.constants.ts
1755
+ var DEFAULT_CONTRIB_STEPS = [
1756
+ { name: "docs", run: "npm run doc:build", restoresGeneratedDocs: true },
1757
+ { name: "type-bench", run: "npm run type-bench:check" }
1248
1758
  ];
1249
- var SUGGESTION_LIMIT = 5;
1250
1759
 
1251
- // src/lib/schema/load-dialectes.ts
1252
- async function loadDialectes(params) {
1253
- const folders = [
1254
- params.cwd,
1255
- ...dependencyNames(params.cwd).flatMap(
1256
- (name) => findInstalledPackage({ cwd: params.cwd, name }) ?? []
1257
- )
1760
+ // src/lib/doctor/profile-lines.ts
1761
+ function profileLines(cwd) {
1762
+ let profile;
1763
+ try {
1764
+ profile = readProfile(cwd);
1765
+ } catch (error) {
1766
+ const detail = error instanceof Error ? error.message : String(error);
1767
+ return [{ status: "error", subject: PROFILE_SUBJECT, detail }];
1768
+ }
1769
+ const dialecte = readPackageJson(cwd).dialecte;
1770
+ if (profile === "consumer") {
1771
+ const declared = dialecte?.profile === void 0 ? "consumer (default)" : "consumer";
1772
+ return [
1773
+ { status: "ok", subject: PROFILE_SUBJECT, detail: declared },
1774
+ ...dialecte?.allowReferences === void 0 ? [] : [
1775
+ {
1776
+ status: "warning",
1777
+ subject: PROFILE_SUBJECT,
1778
+ detail: CONSUMER_ALLOWS_REFERENCES
1779
+ }
1780
+ ]
1781
+ ];
1782
+ }
1783
+ const full = Array.isArray(dialecte?.gate?.full) ? dialecte.gate.full : [];
1784
+ const contributorSteps = DEFAULT_CONTRIB_STEPS.map((step) => step.name);
1785
+ const moved = full.map((step) => step.name).filter((name) => contributorSteps.includes(name));
1786
+ const unsynced = Object.values(AGENT_SKILL_FOLDERS).filter(
1787
+ (folder) => existsSync16(join21(cwd, folder, MANIFEST_FILE)) && readSyncManifest(join21(cwd, folder)).contributing !== true
1788
+ );
1789
+ return [
1790
+ { status: "ok", subject: PROFILE_SUBJECT, detail: "contributor" },
1791
+ ...moved.length ? [
1792
+ {
1793
+ status: "warning",
1794
+ subject: PROFILE_SUBJECT,
1795
+ detail: CONTRIBUTOR_GATE_STEPS.replace("{steps}", moved.join(", "))
1796
+ }
1797
+ ] : [],
1798
+ ...unsynced.map((folder) => ({
1799
+ status: "warning",
1800
+ subject: PROFILE_SUBJECT,
1801
+ detail: CONTRIBUTOR_SKILLS_NOT_SYNCED.replace("{folder}", folder)
1802
+ }))
1258
1803
  ];
1259
- const result = { dialectes: [], skipped: [] };
1260
- for (const folder of folders) {
1261
- const manifest = readManifest(folder);
1262
- if (!manifest?.name || !isBuiltOnCore(manifest)) continue;
1263
- try {
1264
- const loaded = await loadDialecte({ folder, manifest, packageName: manifest.name });
1265
- if (loaded) result.dialectes.push(loaded);
1266
- } catch (error) {
1267
- result.skipped.push({
1268
- packageName: manifest.name,
1269
- reason: error instanceof Error ? error.message : String(error)
1270
- });
1804
+ }
1805
+
1806
+ // src/lib/doctor/station-agent-lines.ts
1807
+ import { existsSync as existsSync18, readFileSync as readFileSync12 } from "fs";
1808
+ import { join as join23 } from "path";
1809
+
1810
+ // src/lib/models/remembered-vendor.ts
1811
+ import { existsSync as existsSync17, statSync as statSync6 } from "fs";
1812
+ import { join as join22 } from "path";
1813
+
1814
+ // src/lib/models/model-tiers.constants.ts
1815
+ var VENDOR_IDS = ["anthropic", "openai", "google"];
1816
+ var TIER_NAMES = ["fast", "standard", "strong", "frontier"];
1817
+ var TIER_DEFINITIONS = {
1818
+ fast: 'search and locate, graders with a schema, log and diff summaries, format and shape checks, "does file X say Y"',
1819
+ standard: "implementer on a mechanical or well-specified lot, fix mode on wording and rename findings, skill-eval runs, independent readers of a standard",
1820
+ strong: "the orchestrator, an implementer on a design-heavy lot, the review (one agent, both passes), adjudicating a disagreement, the retro",
1821
+ frontier: "rare: a plan challenge, a cross-repo architecture decision, a stuck lot after the 3-round cap"
1822
+ };
1823
+ var MODEL_TIERS = {
1824
+ checkedAt: "2026-10-28",
1825
+ vendors: {
1826
+ anthropic: {
1827
+ tiers: {
1828
+ fast: { model: "Haiku 5.5" },
1829
+ standard: { model: "Sonnet 5.5" },
1830
+ strong: { model: "Opus 5.5" },
1831
+ frontier: { model: "Fable 5.1" }
1832
+ }
1833
+ },
1834
+ openai: {
1835
+ tiers: {
1836
+ fast: { model: "Luna" },
1837
+ standard: { model: "Sol" },
1838
+ strong: { model: "Sol", effort: "high" },
1839
+ frontier: { model: "Astra" }
1840
+ }
1841
+ },
1842
+ google: {
1843
+ note: "frontier: check Google's own model page for the current flagship (4 Argon, if generally available)",
1844
+ tiers: {
1845
+ fast: { model: "Flash-Lite" },
1846
+ standard: { model: "Flash" },
1847
+ strong: { model: "Pro" },
1848
+ frontier: { model: "the current flagship" }
1849
+ }
1271
1850
  }
1272
1851
  }
1273
- result.dialectes.sort((left, right) => TEXT_COLLATOR.compare(left.packageName, right.packageName));
1274
- return result;
1852
+ };
1853
+
1854
+ // src/lib/models/vendor-id.ts
1855
+ function isVendorId(value) {
1856
+ return VENDOR_IDS.includes(value);
1275
1857
  }
1276
- async function loadDialecte(params) {
1277
- let config;
1278
- for (const file of entryFiles(params)) {
1279
- const exported = await import(pathToFileURL(file).href);
1280
- config = Object.values(exported).find(isDialecteConfig);
1281
- if (config) break;
1858
+
1859
+ // src/lib/models/remembered-vendor.ts
1860
+ function listManifestFolders(cwd) {
1861
+ return Object.values(AGENT_SKILL_FOLDERS).filter(
1862
+ (folder) => existsSync17(join22(cwd, folder, MANIFEST_FILE))
1863
+ );
1864
+ }
1865
+ function readRememberedVendor(cwd) {
1866
+ const warnings = [];
1867
+ const entries = [];
1868
+ for (const folder of listManifestFolders(cwd)) {
1869
+ const { vendor } = readSyncManifest(join22(cwd, folder));
1870
+ if (vendor === void 0) continue;
1871
+ if (!isVendorId(vendor)) {
1872
+ warnings.push(`${folder}/${MANIFEST_FILE}: unknown vendor "${vendor}" ignored`);
1873
+ continue;
1874
+ }
1875
+ entries.push({
1876
+ folder,
1877
+ vendor,
1878
+ writtenAt: statSync6(join22(cwd, folder, MANIFEST_FILE)).mtimeMs
1879
+ });
1282
1880
  }
1283
- if (!config) return void 0;
1284
- const readersFile = createRequire(join12(params.folder, "package.json")).resolve(CORE_READERS_ENTRY);
1285
- const readers = await import(pathToFileURL(readersFile).href);
1286
- if (!isCoreReaders(readers))
1287
- throw new Error(
1288
- `its core (${readersFile}) lacks ${CORE_READER_NAMES.filter((name) => typeof readers[name] !== "function").join(", ")}: update @dialecte/core`
1881
+ entries.sort((first, second) => second.writtenAt - first.writtenAt);
1882
+ if (new Set(entries.map((entry) => entry.vendor)).size > 1)
1883
+ warnings.push(
1884
+ `manifests disagree on the vendor (${entries.map((entry) => `${entry.folder}: ${entry.vendor}`).join(", ")}): using the most recent, ${entries[0].vendor}`
1289
1885
  );
1290
- return { packageName: params.packageName, config, readers };
1291
- }
1292
- function readManifest(folder) {
1293
- const path = join12(folder, "package.json");
1294
- return existsSync11(path) ? JSON.parse(readFileSync8(path, "utf8")) : void 0;
1295
- }
1296
- function isBuiltOnCore(manifest) {
1297
- return manifest.name !== CORE_PACKAGE3 && (manifest.dependencies?.[CORE_PACKAGE3] !== void 0 || manifest.peerDependencies?.[CORE_PACKAGE3] !== void 0);
1298
- }
1299
- function entryFiles(params) {
1300
- const { exports, main } = params.manifest;
1301
- const targets = exports === void 0 ? main ? [[".", main]] : [] : typeof exports === "string" ? [[".", exports]] : Object.entries(exports);
1302
- return targets.filter(([subpath]) => !subpath.split("/").includes("test") && !subpath.includes("*")).flatMap(([, target]) => {
1303
- const file = fileOf(target);
1304
- return file && file.endsWith("js") ? [join12(params.folder, file)] : [];
1305
- }).map(function existingFile(file) {
1306
- if (!existsSync11(file))
1307
- throw new Error(`entry file not found: ${file} (is the package built?)`);
1308
- return file;
1309
- });
1310
- }
1311
- function fileOf(target) {
1312
- if (typeof target === "string") return target;
1313
- const file = target.import ?? target.node ?? target.default;
1314
- return typeof file === "string" ? file : void 0;
1315
- }
1316
- function isDialecteConfig(value) {
1317
- return typeof value === "object" && value !== null && "rootElementName" in value && typeof value.rootElementName === "string" && "definition" in value && typeof value.definition === "object";
1318
- }
1319
- function isCoreReaders(module) {
1320
- return CORE_READER_NAMES.every((name) => typeof module[name] === "function");
1886
+ return { vendor: entries[0]?.vendor, warnings };
1321
1887
  }
1322
1888
 
1323
- // src/lib/api/installed-bindings.constants.ts
1324
- var VERSION_SUBPATH_PATTERN = /^\.\/[^/*]+$/;
1325
- var TEST_ENTRY = "test";
1326
- var NO_DIALECTE_INSTALLED = "no dialecte installed here (a dependency built on @dialecte/core exporting ./<version> with ./<version>/test): pass --namespace <Name> --entry <module>\n";
1889
+ // src/lib/stations/station-agents.constants.ts
1890
+ var STATION_AGENT_PREFIX = "dialecte-";
1891
+ var CLAUDE_AGENTS_FOLDER = ".claude/agents";
1892
+ var CLAUDE_MODEL_ALIASES = ["haiku", "sonnet", "opus", "fable"];
1893
+ var READ_TOOLS = ["Read", "Glob", "Grep", "Skill"];
1894
+ var REVIEW_TOOLS = ["Read", "Glob", "Grep", "Bash", "Skill"];
1895
+ var EDIT_TOOLS = ["Read", "Write", "Edit", "Glob", "Grep", "Bash", "Skill"];
1896
+ var CLAUDE_TOOLS_BY_ACCESS = {
1897
+ read: READ_TOOLS,
1898
+ review: REVIEW_TOOLS,
1899
+ edit: EDIT_TOOLS
1900
+ };
1901
+ var LOAD_SKILLS_LINE = "Read that section first: it says which skills you load (`dialecte-lot`, `dialecte-contributing`, `dialecte`). The skills are the source of truth; this file only sets your envelope.";
1902
+ var NEVER_LINE = "Never: commit, stage (`git add`), push, merge, `git stash`, `git reset`, `git restore`, `git checkout --`, `rm`; nothing outside the worktree your brief names. Your brief is your whole context.";
1903
+ var GENERATED_NOTE = "Generated by `npx @dialecte/cli skills sync` from `dialecte models`; the next sync overwrites it.";
1904
+ var STATIONS = [
1905
+ {
1906
+ name: "test-writer",
1907
+ tier: "standard",
1908
+ access: "edit",
1909
+ description: "Dialecte lot, test station of one brief step: writes the tests (and stubs) from the brief and the existing code, then proves them red with `dialecte tdd red`. Give it the brief step."
1910
+ },
1911
+ {
1912
+ name: "test-reviewer",
1913
+ tier: "strong",
1914
+ access: "review",
1915
+ description: "Dialecte lot, test review before any code: reads only the tests against the brief (does each pin a behaviour, would a plausible wrong implementation fail it). Read-only."
1916
+ },
1917
+ {
1918
+ name: "implementer",
1919
+ tier: "standard",
1920
+ access: "edit",
1921
+ description: "Dialecte lot, Station 1 (implement) on a mechanical or fully specified lot: production code only until `dialecte tdd green`, then the fast gate. Give it the brief."
1922
+ },
1923
+ {
1924
+ name: "implementer-strong",
1925
+ tier: "strong",
1926
+ access: "edit",
1927
+ description: "Dialecte lot, Station 1 (implement) on a design-heavy lot: production code only until `dialecte tdd green`, then the fast gate. Give it the brief."
1928
+ },
1929
+ {
1930
+ name: "reviewer",
1931
+ tier: "strong",
1932
+ access: "review",
1933
+ description: "Dialecte lot, Station 3 (independent review): pass 1 correctness, pass 2 fit, read-only. Give it the brief and the diff, not the implementer conclusions."
1934
+ },
1935
+ {
1936
+ name: "fixer",
1937
+ tier: "standard",
1938
+ access: "edit",
1939
+ description: "Dialecte lot, Station 4 (fix mode) on wording and naming findings: fixed, disagreed or escalated per finding. Give it the findings."
1940
+ },
1941
+ {
1942
+ name: "eval-runner",
1943
+ tier: "standard",
1944
+ access: "edit",
1945
+ description: "Runs one skill-eval case of a Dialecte skill, with or without the skill, and leaves the outputs the graders read."
1946
+ },
1947
+ {
1948
+ name: "grader",
1949
+ tier: "strong",
1950
+ access: "read",
1951
+ description: "Grades the output of a skill-eval run against one grader file, pass or fail with the evidence. Read-only."
1952
+ },
1953
+ {
1954
+ name: "standard-reader",
1955
+ tier: "standard",
1956
+ access: "read",
1957
+ description: "Independent reader of the IEC standard markdown for one question, with line references. Read-only."
1958
+ },
1959
+ {
1960
+ name: "searcher",
1961
+ tier: "fast",
1962
+ access: "read",
1963
+ description: "Finds where something lives in a Dialecte repository (files, symbols, API paths) and answers with paths and line numbers. Read-only."
1964
+ }
1965
+ ];
1966
+ var LOT_SKILL = "dialecte-lot";
1967
+ var STATIONS_PAGE_PATH = `${AGENT_SKILL_FOLDERS.claude}/${LOT_SKILL}/references/stations.md`;
1968
+ var BRIEF_DEFINED_STATIONS = ["eval-runner", "grader"];
1327
1969
 
1328
- // src/lib/api/installed-bindings.ts
1329
- function findInstalledBindings(params) {
1330
- return dependencyNames(params.cwd).flatMap(function bindingsOf(name) {
1331
- const folder = findInstalledPackage({ cwd: params.cwd, name });
1332
- const manifest = folder ? readManifest(folder) : void 0;
1333
- if (!manifest?.name || !isBuiltOnCore(manifest)) return [];
1334
- const packageName2 = manifest.name;
1335
- return versionsOf(manifest).map((version) => ({
1336
- packageName: packageName2,
1337
- version,
1338
- binding: {
1339
- kind: "namespace",
1340
- name: namespaceOf(packageName2),
1341
- import: `${packageName2}/${version}`
1342
- }
1343
- }));
1344
- });
1970
+ // src/lib/stations/render-station-agent.ts
1971
+ function claudeModelAlias(modelName) {
1972
+ const alias = modelName.split(" ")[0].toLowerCase();
1973
+ return CLAUDE_MODEL_ALIASES.includes(alias) ? alias : void 0;
1345
1974
  }
1346
- function versionsOf(manifest) {
1347
- const subpaths = typeof manifest.exports === "object" ? Object.keys(manifest.exports) : [];
1348
- return subpaths.filter((subpath) => VERSION_SUBPATH_PATTERN.test(subpath)).filter((subpath) => subpaths.includes(`${subpath}/${TEST_ENTRY}`)).map((subpath) => subpath.slice(2));
1975
+ function stationLines(params) {
1976
+ const { station } = params;
1977
+ const play = `You play the \`${station.name}\` station of \`${LOT_SKILL}\`:`;
1978
+ if (BRIEF_DEFINED_STATIONS.includes(station.name))
1979
+ return [
1980
+ `${play} your brief carries your definition and names the only skill text you read; read no other.`,
1981
+ ""
1982
+ ];
1983
+ return [
1984
+ `${play} its definition is ${STATIONS_PAGE_PATH}, section \`${station.name}\`.`,
1985
+ "",
1986
+ LOAD_SKILLS_LINE,
1987
+ ""
1988
+ ];
1349
1989
  }
1350
- function chooseInstalledBinding(params) {
1351
- if (params.bindings.length === 0) return { kind: "output", message: NO_DIALECTE_INSTALLED };
1352
- const matching = params.bindings.filter(
1353
- (binding) => (params.packageName === void 0 || binding.packageName === params.packageName) && (params.version === void 0 || binding.version === params.version)
1354
- );
1355
- if (matching.length === 1) return { kind: "binding", binding: matching[0] };
1356
- if (matching.length === 0) {
1357
- const named = [
1358
- ...params.packageName === void 0 ? [] : [`--package ${params.packageName}`],
1359
- ...params.version === void 0 ? [] : [`--version ${params.version}`]
1360
- ].join(" ");
1990
+ function renderStationAgent(params) {
1991
+ const { station, model } = params;
1992
+ return [
1993
+ "---",
1994
+ `name: ${STATION_AGENT_PREFIX}${station.name}`,
1995
+ `description: ${JSON.stringify(station.description)}`,
1996
+ `tools: ${CLAUDE_TOOLS_BY_ACCESS[station.access].join(", ")}`,
1997
+ `model: ${model}`,
1998
+ "---",
1999
+ `<!-- ${GENERATED_NOTE} -->`,
2000
+ "",
2001
+ ...stationLines({ station }),
2002
+ NEVER_LINE,
2003
+ ""
2004
+ ].join("\n");
2005
+ }
2006
+ function planStationAgents(params) {
2007
+ const { vendor } = params;
2008
+ if (vendor === void 0)
1361
2009
  return {
1362
- kind: "output",
1363
- message: `no installed dialecte matches ${named}; installed:
1364
- ${listLines(params.bindings)}`
2010
+ kind: "skipped",
2011
+ reason: "no model vendor known for this project, so no Claude Code station agents: run `skills sync --vendor anthropic`"
2012
+ };
2013
+ if (vendor !== "anthropic")
2014
+ return {
2015
+ kind: "skipped",
2016
+ reason: `no Claude Code station agents: the project's vendor is ${vendor}, whose tiers are named by \`dialecte models\``
1365
2017
  };
2018
+ const tiers = MODEL_TIERS.vendors[vendor].tiers;
2019
+ const files = [];
2020
+ for (const station of STATIONS) {
2021
+ const modelName = tiers[station.tier].model;
2022
+ const model = claudeModelAlias(modelName);
2023
+ if (model === void 0)
2024
+ return {
2025
+ kind: "skipped",
2026
+ reason: `no Claude Code station agents: "${modelName}" (${station.tier}) is not a model name Claude Code accepts`
2027
+ };
2028
+ files.push({
2029
+ name: `${STATION_AGENT_PREFIX}${station.name}.md`,
2030
+ content: renderStationAgent({ station, model })
2031
+ });
1366
2032
  }
1367
- return {
1368
- kind: "output",
1369
- message: `several dialectes are installed: pass --package <name> [--version <v>]
1370
- ${listLines(matching)}`
1371
- };
1372
- }
1373
- function listLines(bindings) {
1374
- return bindings.map((binding) => ` ${binding.packageName} --version ${binding.version}
1375
- `).join("");
2033
+ return { kind: "files", files };
1376
2034
  }
1377
2035
 
1378
- // src/lib/discover.ts
1379
- import { mkdirSync as mkdirSync2, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
1380
- import { dirname as dirname5, join as join13, relative as relative2 } from "path";
1381
-
1382
- // src/lib/discover.constants.ts
1383
- import ts from "typescript";
1384
- var ENTRY_FOLDER = "node_modules/.cache/dialecte";
1385
- var ROOTS = ["q", "tx", "doc", "project"];
1386
- var PRIMITIVE_LIKE = ts.TypeFlags.StringLike | ts.TypeFlags.NumberLike | ts.TypeFlags.BooleanLike | ts.TypeFlags.ESSymbolLike | ts.TypeFlags.VoidLike | ts.TypeFlags.Null | ts.TypeFlags.BigIntLike;
1387
- var SIGNATURE_FORMAT = ts.TypeFormatFlags.WriteArrowStyleSignature | ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope;
1388
- var FENCED_CODE_PATTERN = /^[ \t]*```[a-z]*[ \t]*\n([\s\S]*?)^[ \t]*```/m;
1389
- var SIGNATURE_PRINTER = ts.createPrinter({ removeComments: true });
1390
-
1391
- // src/lib/render-jsdoc-text.ts
1392
- function renderJsDocText(parts) {
1393
- let text = "";
1394
- let link;
1395
- for (const part of parts ?? []) {
1396
- if (part.kind === "link" && part.text.startsWith("{@link"))
1397
- link = { name: void 0, label: "" };
1398
- else if (link && part.kind === "linkName") link.name = part.text;
1399
- else if (link && part.kind === "linkText") link.label += part.text;
1400
- else if (link && part.kind === "link") {
1401
- text += renderLink(link);
1402
- link = void 0;
1403
- } else text += part.text;
2036
+ // src/lib/doctor/station-agent-lines.ts
2037
+ function stationAgentLines(cwd) {
2038
+ const manifestFolder = join23(cwd, AGENT_SKILL_FOLDERS.claude);
2039
+ if (!existsSync18(join23(manifestFolder, MANIFEST_FILE))) return [];
2040
+ const listed = readSyncManifest(manifestFolder).stationAgents ?? [];
2041
+ if (listed.length === 0) return [];
2042
+ const plan = planStationAgents({ vendor: readRememberedVendor(cwd).vendor });
2043
+ if (plan.kind !== "files") return [];
2044
+ const missing = [];
2045
+ const stale = [];
2046
+ for (const file of plan.files) {
2047
+ const path = join23(cwd, CLAUDE_AGENTS_FOLDER, file.name);
2048
+ if (!existsSync18(path)) missing.push(file.name);
2049
+ else if (listed.includes(file.name) && readFileSync12(path, "utf8") !== file.content)
2050
+ stale.push(file.name);
1404
2051
  }
1405
- return text;
2052
+ if (missing.length === 0 && stale.length === 0)
2053
+ return [{ status: "ok", subject: STATION_AGENTS_SUBJECT, detail: `${CLAUDE_AGENTS_FOLDER} in sync` }];
2054
+ const parts = [
2055
+ ...stale.length ? [`holds stale ${stale.join(", ")}`] : [],
2056
+ ...missing.length ? [`lacks ${missing.join(", ")}`] : []
2057
+ ];
2058
+ return [
2059
+ {
2060
+ status: "warning",
2061
+ subject: STATION_AGENTS_SUBJECT,
2062
+ detail: `${CLAUDE_AGENTS_FOLDER} ${parts.join("; ")}`,
2063
+ fix: SYNC_COMMAND
2064
+ }
2065
+ ];
1406
2066
  }
1407
- function renderLink(link) {
1408
- if (link.name !== void 0) return link.label.trim() || `\`${link.name}\``;
1409
- const [target = "", ...label] = link.label.trim().split(/\s+/);
1410
- return label.join(" ") || `\`${target}\``;
2067
+
2068
+ // src/lib/doctor/diagnose.ts
2069
+ function diagnose(context) {
2070
+ return [
2071
+ { status: "ok", subject: "dialecte", detail: `cli ${context.cliVersion} running` },
2072
+ ...installedPackages(context.cwd),
2073
+ ...profileLines(context.cwd),
2074
+ ...coreGenerations(context.cwd),
2075
+ ...skills(context.cwd),
2076
+ ...stationAgentLines(context.cwd),
2077
+ ...context.brief ? [] : localCheckouts(context)
2078
+ ];
2079
+ }
2080
+ function installedPackages(cwd) {
2081
+ const declared = declaredVersions(cwd);
2082
+ return Object.keys(declared).filter((name) => name.startsWith(DIALECTE_SCOPE)).sort(TEXT_COLLATOR.compare).map(function packageLine(name) {
2083
+ const version = installedVersion({ cwd, name });
2084
+ if (version === void 0)
2085
+ return { status: "warning", subject: name, detail: "not installed", fix: INSTALL_COMMAND };
2086
+ const pinned = declared[name];
2087
+ if (/^\d/.test(pinned) && pinned !== version)
2088
+ return {
2089
+ status: "warning",
2090
+ subject: name,
2091
+ detail: `${version} installed, ${pinned} declared`,
2092
+ fix: INSTALL_COMMAND
2093
+ };
2094
+ return { status: "ok", subject: name, detail: version };
2095
+ });
2096
+ }
2097
+ function coreGenerations(cwd) {
2098
+ const dialectes = dependencyNames(cwd).sort(TEXT_COLLATOR.compare).flatMap(function dialecteOnCore(name) {
2099
+ const folder = findInstalledPackage({ cwd, name });
2100
+ return folder && dependsOnCore(folder) ? [{ name, folder }] : [];
2101
+ });
2102
+ const appCore = installedVersion({ cwd, name: CORE_PACKAGE2 });
2103
+ const owners = dialectes.length ? dialectes : [{ name: void 0, folder: cwd }];
2104
+ return owners.flatMap(function generationLine({ name, folder }) {
2105
+ const version = installedVersion({ cwd: folder, name: CORE_PACKAGE2 });
2106
+ if (version === void 0) return [];
2107
+ const [major = 0, minor = 0] = version.split(".").map(Number);
2108
+ const generation = CORE_API_GENERATIONS.find(
2109
+ ({ from }) => major > from[0] || major === from[0] && minor >= from[1]
2110
+ );
2111
+ if (!generation) return [];
2112
+ const says = `${generation.name}: ${generation.says}`;
2113
+ if (name && appCore !== void 0 && appCore !== version)
2114
+ return [
2115
+ {
2116
+ status: "warning",
2117
+ subject: "core API",
2118
+ detail: `${name} on core ${version}, your app on core ${appCore}: two cores side by side (${says})`,
2119
+ fix: ALIGN_CORE_FIX
2120
+ }
2121
+ ];
2122
+ const owner = name ? `${name} on core ${version}` : `core ${version}`;
2123
+ return [{ status: "ok", subject: "core API", detail: `${owner} - ${says}` }];
2124
+ });
2125
+ }
2126
+ function skills(cwd) {
2127
+ const { sources } = discoverSkillSources({ cwd });
2128
+ if (sources.length === 0)
2129
+ return [{ status: "ok", subject: "skills", detail: "no dependency ships skills" }];
2130
+ const synced = Object.values(AGENT_SKILL_FOLDERS).filter(
2131
+ (folder) => existsSync19(join24(cwd, folder, MANIFEST_FILE))
2132
+ );
2133
+ if (synced.length === 0)
2134
+ return [
2135
+ {
2136
+ status: "warning",
2137
+ subject: "skills",
2138
+ detail: `not installed for your agents (${sources.map((source) => source.name).join(", ")} shipped)`,
2139
+ fix: SYNC_COMMAND
2140
+ }
2141
+ ];
2142
+ const contributor = isContributor(cwd);
2143
+ return synced.map(function syncLine(folder) {
2144
+ const manifest = readSyncManifest(join24(cwd, folder));
2145
+ const expected = selectAudience({
2146
+ sources,
2147
+ contributing: contributor || manifest.contributing === true
2148
+ }).selected;
2149
+ const missing = expected.map((source) => source.name).filter((name) => !manifest.installed.includes(name));
2150
+ if (missing.length)
2151
+ return {
2152
+ status: "warning",
2153
+ subject: "skills",
2154
+ detail: `${folder} lacks ${missing.join(", ")}`,
2155
+ fix: SYNC_COMMAND
2156
+ };
2157
+ const stale = expected.flatMap(function staleCopy(source) {
2158
+ const recorded = manifest.versions[source.name];
2159
+ if (isLink(join24(cwd, folder, source.name)) || source.version === void 0) return [];
2160
+ if (recorded?.version === source.version) return [];
2161
+ return [
2162
+ `${source.name} of ${source.origin} ${recorded?.version ?? "an unknown version"}, ${source.version} installed`
2163
+ ];
2164
+ });
2165
+ if (stale.length)
2166
+ return {
2167
+ status: "warning",
2168
+ subject: "skills",
2169
+ detail: `${folder} holds ${stale.join("; ")}`,
2170
+ fix: SYNC_COMMAND
2171
+ };
2172
+ return { status: "ok", subject: "skills", detail: `${folder} in sync with node_modules` };
2173
+ });
1411
2174
  }
1412
-
1413
- // src/lib/discover.ts
1414
- import ts2 from "typescript";
1415
- function discoverMethods(params) {
1416
- const { entrySource, tsconfig, root, maxDepth = 1 } = params;
1417
- const entryPath = join13(root, ENTRY_FOLDER, `discover-entry-${process.pid}.ts`);
1418
- mkdirSync2(dirname5(entryPath), { recursive: true });
1419
- writeFileSync2(entryPath, entrySource);
2175
+ function isContributor(cwd) {
1420
2176
  try {
1421
- const parsed = ts2.parseJsonConfigFileContent(
1422
- ts2.readConfigFile(join13(root, tsconfig), ts2.sys.readFile).config,
1423
- ts2.sys,
1424
- root
1425
- );
1426
- const program = ts2.createProgram([entryPath], {
1427
- ...parsed.options,
1428
- noEmit: true,
1429
- rootDir: root
1430
- });
1431
- const checker = program.getTypeChecker();
1432
- const sourceFile = program.getSourceFile(entryPath);
1433
- if (!sourceFile) return [];
1434
- const exportsByName = new Map(
1435
- checker.getExportsOfModule(checker.getSymbolAtLocation(sourceFile)).map((symbol) => [symbol.getName(), symbol])
1436
- );
1437
- const entries = [];
1438
- for (const rootName of ROOTS) {
1439
- const symbol = exportsByName.get(rootName);
1440
- if (symbol)
1441
- walkMembers({
1442
- checker,
1443
- sourceFile,
1444
- type: checker.getTypeOfSymbolAtLocation(symbol, sourceFile),
1445
- path: rootName,
1446
- depth: 0,
1447
- maxDepth,
1448
- root,
1449
- entries
1450
- });
1451
- }
1452
- return entries;
1453
- } finally {
1454
- rmSync2(entryPath, { force: true });
2177
+ return readProfile(cwd) === "contributor";
2178
+ } catch {
2179
+ return false;
1455
2180
  }
1456
2181
  }
1457
- function walkMembers(params) {
1458
- const { checker, sourceFile, type, path, depth, maxDepth } = params;
1459
- for (const property of type.getProperties()) {
1460
- if (!isPublic(property)) continue;
1461
- const propertyType = checker.getTypeOfSymbolAtLocation(
1462
- property,
1463
- declarationOf(property) ?? sourceFile
1464
- );
1465
- const propertyPath = `${path}.${property.getName()}`;
1466
- if (propertyType.getCallSignatures().length > 0) {
1467
- const { documentation, declaringSymbol } = documentationOf({
1468
- checker,
1469
- symbol: property,
1470
- root: params.root
1471
- });
1472
- params.entries.push({
1473
- path: propertyPath,
1474
- signature: signatureOf({ checker, boundType: propertyType, declaringSymbol }),
1475
- ...documentation
1476
- });
1477
- } else if (depth < maxDepth && !(propertyType.flags & PRIMITIVE_LIKE) && propertyType.getProperties().some(
1478
- (member) => isPublic(member) && !isTypeScriptLibrary(member) && checker.getTypeOfSymbolAtLocation(member, declarationOf(member) ?? sourceFile).getCallSignatures().length > 0
1479
- ))
1480
- walkMembers({ ...params, type: propertyType, path: propertyPath, depth: depth + 1 });
2182
+ function isLink(path) {
2183
+ try {
2184
+ return lstatSync5(path).isSymbolicLink();
2185
+ } catch {
2186
+ return false;
1481
2187
  }
1482
2188
  }
1483
- function signatureOf(params) {
1484
- const { checker } = params;
1485
- const boundSignatures = params.boundType.getCallSignatures();
1486
- const declarations = callableDeclarations(params.declaringSymbol);
1487
- if (declarations.length === 0)
1488
- return boundSignatures.map(
1489
- (signature) => checker.signatureToString(signature, void 0, SIGNATURE_FORMAT, ts2.SignatureKind.Call)
1490
- ).join("\n");
1491
- const boundParameterCount = Math.max(
1492
- ...boundSignatures.map((signature) => parameterCount({ checker, signature }))
1493
- );
1494
- return declarations.map((declaration) => declaredSignatureText({ checker, declaration, boundParameterCount })).join("\n");
2189
+ function dependsOnCore(folder) {
2190
+ const manifest = JSON.parse(readFileSync13(join24(folder, "package.json"), "utf8"));
2191
+ return manifest.name !== CORE_PACKAGE2 && (manifest.dependencies?.[CORE_PACKAGE2] !== void 0 || manifest.peerDependencies?.[CORE_PACKAGE2] !== void 0);
1495
2192
  }
1496
- function parameterCount(params) {
1497
- const { checker } = params;
1498
- const parameters = params.signature.getParameters();
1499
- const last = parameters.at(-1);
1500
- if (!last) return 0;
1501
- const lastType = checker.getTypeOfSymbol(last);
1502
- return checker.isTupleType(lastType) ? parameters.length - 1 + checker.getTypeArguments(lastType).length : parameters.length;
2193
+ function localCheckouts(context) {
2194
+ const roots = [
2195
+ ...new Set([context.dialecteRoot, dirname11(resolve5(context.cwd))].filter(isDefined2))
2196
+ ];
2197
+ return roots.map(function checkoutLine(root) {
2198
+ const names = existsSync19(root) ? readdirSync10(root, { withFileTypes: true }).filter((entry) => entry.isDirectory() && join24(root, entry.name) !== resolve5(context.cwd)).filter((entry) => packageName(join24(root, entry.name))?.startsWith(DIALECTE_SCOPE)).map((entry) => entry.name).sort(TEXT_COLLATOR.compare) : [];
2199
+ return {
2200
+ status: "ok",
2201
+ subject: "checkouts",
2202
+ detail: names.length ? `${root}: ${names.slice(0, CHECKOUT_LIST_LIMIT).join(", ")}${names.length > CHECKOUT_LIST_LIMIT ? ` and ${names.length - CHECKOUT_LIST_LIMIT} more` : ""}` : `none in ${root} (the installed packages are the source)`
2203
+ };
2204
+ });
1503
2205
  }
1504
- function callableDeclarations(symbol) {
1505
- const declarations = (symbol?.declarations ?? []).flatMap(
1506
- (declaration) => {
1507
- if (ts2.isFunctionDeclaration(declaration) || ts2.isMethodDeclaration(declaration))
1508
- return [declaration];
1509
- if (ts2.isVariableDeclaration(declaration) && declaration.initializer && (ts2.isArrowFunction(declaration.initializer) || ts2.isFunctionExpression(declaration.initializer)))
1510
- return [declaration.initializer];
1511
- return [];
1512
- }
2206
+ function declaredVersions(cwd) {
2207
+ const manifest = JSON.parse(readFileSync13(join24(cwd, "package.json"), "utf8"));
2208
+ const names = dependencyNames(cwd);
2209
+ return Object.fromEntries(
2210
+ names.map((name) => [
2211
+ name,
2212
+ String(
2213
+ manifest.dependencies?.[name] ?? manifest.devDependencies?.[name] ?? manifest.peerDependencies?.[name]
2214
+ )
2215
+ ])
1513
2216
  );
1514
- const overloads = declarations.filter((declaration) => !hasBody(declaration));
1515
- return overloads.length > 0 ? overloads : declarations;
1516
2217
  }
1517
- function hasBody(declaration) {
1518
- return "body" in declaration && declaration.body !== void 0;
2218
+ function installedVersion(params) {
2219
+ const folder = findInstalledPackage(params);
2220
+ if (!folder || !existsSync19(join24(folder, "package.json"))) return void 0;
2221
+ const version = JSON.parse(readFileSync13(join24(folder, "package.json"), "utf8")).version;
2222
+ return typeof version === "string" ? version : void 0;
1519
2223
  }
1520
- function declaredSignatureText(params) {
1521
- const { checker, declaration } = params;
1522
- const sourceFile = declaration.getSourceFile();
1523
- const signature = checker.getSignatureFromDeclaration(declaration);
1524
- const parameters = declaration.parameters;
1525
- const skipped = Math.max(0, parameters.length - params.boundParameterCount);
1526
- const typeParameters = declaration.typeParameters?.length ? `<${declaration.typeParameters.map((typeParameter) => printed({ node: typeParameter, sourceFile })).join(", ")}>` : "";
1527
- const parameterTexts = parameters.slice(skipped).map(function parameterText(parameter) {
1528
- const optional = parameter.questionToken || parameter.initializer ? "?" : "";
1529
- const rest = parameter.dotDotDotToken ? "..." : "";
1530
- const type = parameter.type ? printed({ node: parameter.type, sourceFile }) : checker.typeToString(checker.getTypeAtLocation(parameter), declaration, SIGNATURE_FORMAT);
1531
- return `${rest}${printed({ node: parameter.name, sourceFile })}${optional}: ${type}`;
2224
+ function packageName(folder) {
2225
+ const path = join24(folder, "package.json");
2226
+ if (!existsSync19(path)) return void 0;
2227
+ const name = JSON.parse(readFileSync13(path, "utf8")).name;
2228
+ return typeof name === "string" ? name : void 0;
2229
+ }
2230
+ function isDefined2(value) {
2231
+ return value !== void 0;
2232
+ }
2233
+
2234
+ // src/commands/doctor.ts
2235
+ function runDoctor(params) {
2236
+ const { argv, cliVersion, ...rest } = params;
2237
+ if (hasFlag([...argv], "brief")) return runBrief({ ...rest, cliVersion });
2238
+ const missing = missingPackage({ cwd: params.cwd });
2239
+ if (missing) return missing;
2240
+ return answerDoctor({
2241
+ lines: diagnose({ ...rest, cliVersion: resolveVersion(cliVersion) }),
2242
+ json: hasFlag([...argv], "json")
1532
2243
  });
1533
- const returnType = declaration.type ? printed({ node: declaration.type, sourceFile }) : signature ? checker.typeToString(signature.getReturnType(), declaration, SIGNATURE_FORMAT) : "unknown";
1534
- return `${typeParameters}(${parameterTexts.join(", ")}) => ${returnType}`;
1535
2244
  }
1536
- function printed(params) {
1537
- return SIGNATURE_PRINTER.printNode(
1538
- ts2.EmitHint.Unspecified,
1539
- params.node,
1540
- params.sourceFile
1541
- ).replace(/\s*\n\s*/g, " ");
2245
+ function runBrief(context) {
2246
+ try {
2247
+ return answerDoctorBrief(
2248
+ diagnose({ ...context, cliVersion: resolveVersion(context.cliVersion), brief: true })
2249
+ );
2250
+ } catch {
2251
+ return { output: textOf([]), exitCode: 0 };
2252
+ }
1542
2253
  }
1543
- function documentationOf(params) {
1544
- const { checker } = params;
1545
- const visited = /* @__PURE__ */ new Set();
1546
- const queue = [params.symbol];
1547
- let declaringSymbol;
1548
- while (queue.length) {
1549
- const symbol = queue.shift();
1550
- if (!symbol || visited.has(symbol)) continue;
1551
- visited.add(symbol);
1552
- if (symbol.flags & ts2.SymbolFlags.Alias) {
1553
- queue.push(checker.getAliasedSymbol(symbol));
1554
- continue;
1555
- }
1556
- declaringSymbol ??= symbol;
1557
- const comment = renderJsDocText(symbol.getDocumentationComment(checker));
1558
- if (comment) {
1559
- const tags2 = symbol.getJsDocTags(checker);
1560
- return {
1561
- documentation: {
1562
- summary: firstParagraph(comment),
1563
- intents: intentsOf(tags2),
1564
- example: exampleOf(tags2),
1565
- definedInPackage: isDeclaredInPackage({ symbol, root: params.root }),
1566
- internal: tags2.some((tag) => tag.name === "internal"),
1567
- declaredAt: declarationKey({ symbol, root: params.root })
1568
- },
1569
- declaringSymbol: symbol
1570
- };
1571
- }
1572
- for (const declaration of symbol.declarations ?? []) {
1573
- if (ts2.isShorthandPropertyAssignment(declaration))
1574
- queue.push(checker.getShorthandAssignmentValueSymbol(declaration));
1575
- else if (ts2.isPropertyAssignment(declaration))
1576
- queue.push(assignedSymbol({ checker, initializer: declaration.initializer }));
1577
- else if (ts2.isExportSpecifier(declaration))
1578
- queue.push(checker.getExportSpecifierLocalTargetSymbol(declaration));
1579
- }
2254
+ function resolveVersion(cliVersion) {
2255
+ return typeof cliVersion === "string" ? cliVersion : cliVersion();
2256
+ }
2257
+
2258
+ // src/lib/api/list-members.ts
2259
+ function listMembers(params) {
2260
+ const path = discoveryPath(params.expression);
2261
+ const exact = params.entries.find((entry) => entry.path === path);
2262
+ if (exact) return [methodMember({ entry: exact, name: lastSegment(path) })];
2263
+ const methods = [];
2264
+ const methodCountByGroup = /* @__PURE__ */ new Map();
2265
+ for (const entry of params.entries) {
2266
+ if (!entry.path.startsWith(`${path}.`)) continue;
2267
+ const [name, ...below] = entry.path.slice(path.length + 1).split(".");
2268
+ if (below.length === 0) methods.push(methodMember({ entry, name }));
2269
+ else methodCountByGroup.set(name, (methodCountByGroup.get(name) ?? 0) + 1);
1580
2270
  }
1581
- const declaringFunction = lastDeclared(visited) ?? declaringSymbol;
1582
- const tags = declaringFunction?.getJsDocTags(checker) ?? [];
2271
+ const groups = [...methodCountByGroup].map(([name, methodCount]) => ({
2272
+ kind: "group",
2273
+ name,
2274
+ methodCount
2275
+ }));
2276
+ return [...methods.sort(byName), ...groups.sort(byName)];
2277
+ }
2278
+ function discoveryPath(expression) {
2279
+ return expression.replace(/^(doc\.query|query)(?=\.|$)/, "q");
2280
+ }
2281
+ function methodMember(params) {
1583
2282
  return {
1584
- documentation: {
1585
- summary: void 0,
1586
- intents: intentsOf(tags),
1587
- example: exampleOf(tags),
1588
- internal: tags.some((tag) => tag.name === "internal"),
1589
- definedInPackage: isDeclaredInPackage({ symbol: declaringFunction, root: params.root }),
1590
- declaredAt: declarationKey({ symbol: declaringFunction, root: params.root })
1591
- },
1592
- declaringSymbol: declaringFunction
2283
+ kind: "method",
2284
+ name: params.name,
2285
+ summary: params.entry.summary,
2286
+ intents: params.entry.intents
1593
2287
  };
1594
2288
  }
1595
- function firstParagraph(comment) {
1596
- return comment.split(/\n\s*\n/)[0].replace(/\s+/g, " ").trim();
2289
+ function lastSegment(path) {
2290
+ return path.slice(path.lastIndexOf(".") + 1);
1597
2291
  }
1598
- function intentsOf(tags) {
1599
- return tags.filter((tag) => tag.name === "intent").flatMap((tag) => parseIntentText(renderJsDocText(tag.text)));
2292
+ function byName(left, right) {
2293
+ return TEXT_COLLATOR.compare(left.name, right.name);
1600
2294
  }
1601
- function exampleOf(tags) {
1602
- const tag = tags.find((candidate) => candidate.name === "example");
1603
- if (!tag) return void 0;
1604
- const text = renderJsDocText(tag.text);
1605
- const fenced = text.match(FENCED_CODE_PATTERN);
1606
- const code = (fenced ? fenced[1] : text).trim();
1607
- return code || void 0;
2295
+
2296
+ // src/lib/api/answer-members.ts
2297
+ function answerMembers(params) {
2298
+ const { expression } = params;
2299
+ const members = listMembers(params);
2300
+ if (params.json)
2301
+ return {
2302
+ output: endedOf(jsonOf({ expression, members }, " ")),
2303
+ exitCode: members.length ? 0 : 1
2304
+ };
2305
+ if (members.length)
2306
+ return { output: textOf([expression, ...members.map(memberLine), ""]), exitCode: 0 };
2307
+ const parent = expression.slice(0, Math.max(0, expression.lastIndexOf(".")));
2308
+ const neighbours = parent ? listMembers({ entries: params.entries, expression: parent }).map((member) => member.name) : [];
2309
+ const closest = closestNames({
2310
+ name: expression.slice(expression.lastIndexOf(".") + 1),
2311
+ candidates: neighbours,
2312
+ limit: MEMBER_SUGGESTION_LIMIT
2313
+ });
2314
+ const hint = parent ? ` - under ${parent}: ${(closest.length ? closest : neighbours).join(", ") || "nothing"}` : "";
2315
+ return { output: textOf([`nothing at ${expression}${hint}`, ""]), exitCode: 1 };
1608
2316
  }
1609
- function parseIntentText(text) {
1610
- const intents = [];
1611
- let depth = 0;
1612
- let current = "";
1613
- for (const character of text.split(/\n\s*\n/)[0]) {
1614
- if (character === "(") depth++;
1615
- else if (character === ")") depth = Math.max(0, depth - 1);
1616
- if (character === "," && depth === 0) {
1617
- intents.push(current);
1618
- current = "";
1619
- } else current += character;
2317
+ function memberLine(member) {
2318
+ if (member.kind === "group")
2319
+ return ` ${member.name}. ${member.methodCount} method${member.methodCount === 1 ? "" : "s"}`;
2320
+ return member.summary ? ` ${member.name}() ${shortSummary(member.summary)}` : ` ${member.name}()`;
2321
+ }
2322
+
2323
+ // src/lib/namespace-of.ts
2324
+ function namespaceOf(packageName2) {
2325
+ const name = packageName2.split("/").pop() || "dialecte";
2326
+ return name.charAt(0).toUpperCase() + name.slice(1);
2327
+ }
2328
+
2329
+ // src/lib/schema/load-dialectes.ts
2330
+ import { existsSync as existsSync20, readFileSync as readFileSync14 } from "fs";
2331
+ import { createRequire } from "module";
2332
+ import { join as join25 } from "path";
2333
+ import { pathToFileURL } from "url";
2334
+
2335
+ // src/lib/schema/schema.constants.ts
2336
+ var CORE_PACKAGE3 = "@dialecte/core";
2337
+ var CORE_READERS_ENTRY = "@dialecte/core/utils";
2338
+ var CORE_READER_NAMES = [
2339
+ "resolveDefinition",
2340
+ "getAttributeRules",
2341
+ "enumeratedValues",
2342
+ "valuePatterns",
2343
+ "admittedXsiTypes",
2344
+ "childOccurrences",
2345
+ "orderByConfigSequence"
2346
+ ];
2347
+ var SUGGESTION_LIMIT = 5;
2348
+
2349
+ // src/lib/schema/load-dialectes.ts
2350
+ async function loadDialectes(params) {
2351
+ const folders = [
2352
+ params.cwd,
2353
+ ...dependencyNames(params.cwd).flatMap(
2354
+ (name) => findInstalledPackage({ cwd: params.cwd, name }) ?? []
2355
+ )
2356
+ ];
2357
+ const result = { dialectes: [], skipped: [] };
2358
+ for (const folder of folders) {
2359
+ const manifest = readManifest(folder);
2360
+ if (!manifest?.name || !isBuiltOnCore(manifest)) continue;
2361
+ try {
2362
+ const loaded = await loadDialecte({ folder, manifest, packageName: manifest.name });
2363
+ if (loaded) result.dialectes.push(loaded);
2364
+ } catch (error) {
2365
+ result.skipped.push({
2366
+ packageName: manifest.name,
2367
+ reason: error instanceof Error ? error.message : String(error)
2368
+ });
2369
+ }
1620
2370
  }
1621
- intents.push(current);
1622
- return intents.map((intent) => intent.replace(/\s+/g, " ").trim()).filter(Boolean);
2371
+ result.dialectes.sort((left, right) => TEXT_COLLATOR.compare(left.packageName, right.packageName));
2372
+ return result;
1623
2373
  }
1624
- function assignedSymbol(params) {
1625
- const { checker, initializer } = params;
1626
- if (ts2.isIdentifier(initializer)) return checker.getSymbolAtLocation(initializer);
1627
- if (ts2.isPropertyAccessExpression(initializer))
1628
- return checker.getSymbolAtLocation(initializer.name);
1629
- return void 0;
2374
+ async function loadDialecte(params) {
2375
+ const standard = readStandard(params.manifest);
2376
+ let config;
2377
+ for (const file of entryFiles(params)) {
2378
+ const exported = await import(pathToFileURL(file).href);
2379
+ config = Object.values(exported).find(isDialecteConfig);
2380
+ if (config) break;
2381
+ }
2382
+ if (!config) return void 0;
2383
+ const readersFile = createRequire(join25(params.folder, "package.json")).resolve(CORE_READERS_ENTRY);
2384
+ const readers = await import(pathToFileURL(readersFile).href);
2385
+ if (!isCoreReaders(readers))
2386
+ throw new Error(
2387
+ `its core (${readersFile}) lacks ${CORE_READER_NAMES.filter((name) => typeof readers[name] !== "function").join(", ")}: update @dialecte/core`
2388
+ );
2389
+ return { packageName: params.packageName, config, readers, standard };
1630
2390
  }
1631
- function lastDeclared(symbols) {
1632
- return [...symbols].reverse().find((symbol) => (symbol.declarations ?? []).some(declaresFunction));
2391
+ function readStandard(manifest) {
2392
+ const field = manifest.dialecte;
2393
+ if (typeof field !== "object" || field === null || !("standard" in field)) return void 0;
2394
+ const { standard } = field;
2395
+ if (typeof standard !== "string" || standard.trim() === "")
2396
+ throw new Error(
2397
+ `dialecte.standard must be a non-empty string, found ${JSON.stringify(standard) ?? String(standard)}`
2398
+ );
2399
+ return standard;
1633
2400
  }
1634
- function declaresFunction(declaration) {
1635
- if (ts2.isFunctionDeclaration(declaration) || ts2.isMethodDeclaration(declaration)) return true;
1636
- if (!ts2.isVariableDeclaration(declaration) || !declaration.initializer) return false;
1637
- return ts2.isArrowFunction(declaration.initializer) || ts2.isFunctionExpression(declaration.initializer);
2401
+ function readManifest(folder) {
2402
+ const path = join25(folder, "package.json");
2403
+ return existsSync20(path) ? JSON.parse(readFileSync14(path, "utf8")) : void 0;
1638
2404
  }
1639
- function declarationKey(params) {
1640
- const declaration = params.symbol?.declarations?.[0];
1641
- if (!declaration) return void 0;
1642
- return `${relative2(params.root, declaration.getSourceFile().fileName)}:${declaration.getStart()}`;
2405
+ function isBuiltOnCore(manifest) {
2406
+ return manifest.name !== CORE_PACKAGE3 && (manifest.dependencies?.[CORE_PACKAGE3] !== void 0 || manifest.peerDependencies?.[CORE_PACKAGE3] !== void 0);
1643
2407
  }
1644
- function isDeclaredInPackage(params) {
1645
- const fileName = params.symbol?.declarations?.[0]?.getSourceFile().fileName;
1646
- if (!fileName) return false;
1647
- const path = relative2(params.root, fileName);
1648
- return !path.startsWith("..") && !path.split(/[\\/]/).includes("node_modules");
2408
+ function entryFiles(params) {
2409
+ const { exports, main } = params.manifest;
2410
+ const targets = exports === void 0 ? main ? [[".", main]] : [] : typeof exports === "string" ? [[".", exports]] : Object.entries(exports);
2411
+ return targets.filter(([subpath]) => !subpath.split("/").includes("test") && !subpath.includes("*")).flatMap(([, target]) => {
2412
+ const file = fileOf(target);
2413
+ return file && file.endsWith("js") ? [join25(params.folder, file)] : [];
2414
+ }).map(function existingFile(file) {
2415
+ if (!existsSync20(file))
2416
+ throw new Error(`entry file not found: ${file} (is the package built?)`);
2417
+ return file;
2418
+ });
1649
2419
  }
1650
- function declarationOf(symbol) {
1651
- return symbol.valueDeclaration ?? symbol.declarations?.[0];
2420
+ function fileOf(target) {
2421
+ if (typeof target === "string") return target;
2422
+ const file = target.import ?? target.node ?? target.default;
2423
+ return typeof file === "string" ? file : void 0;
1652
2424
  }
1653
- function isPublic(symbol) {
1654
- const declaration = declarationOf(symbol);
1655
- return !declaration || !(ts2.getCombinedModifierFlags(declaration) & (ts2.ModifierFlags.Private | ts2.ModifierFlags.Protected));
2425
+ function isDialecteConfig(value) {
2426
+ return typeof value === "object" && value !== null && "rootElementName" in value && typeof value.rootElementName === "string" && "definition" in value && typeof value.definition === "object";
1656
2427
  }
1657
- function isTypeScriptLibrary(symbol) {
1658
- return (declarationOf(symbol)?.getSourceFile()?.fileName ?? "").includes(
1659
- "/node_modules/typescript/"
2428
+ function isCoreReaders(module) {
2429
+ return CORE_READER_NAMES.every((name) => typeof module[name] === "function");
2430
+ }
2431
+
2432
+ // src/lib/api/installed-bindings.constants.ts
2433
+ var VERSION_SUBPATH_PATTERN = /^\.\/[^/*]+$/;
2434
+ var TEST_ENTRY = "test";
2435
+ var NO_DIALECTE_INSTALLED = "no dialecte installed here (a dependency built on @dialecte/core exporting ./<version> with ./<version>/test): pass --namespace <Name> --entry <module>";
2436
+
2437
+ // src/lib/api/installed-bindings.ts
2438
+ function findInstalledBindings(params) {
2439
+ return dependencyNames(params.cwd).flatMap(function bindingsOf(name) {
2440
+ const folder = findInstalledPackage({ cwd: params.cwd, name });
2441
+ const manifest = folder ? readManifest(folder) : void 0;
2442
+ if (!manifest?.name || !isBuiltOnCore(manifest)) return [];
2443
+ const packageName2 = manifest.name;
2444
+ return versionsOf(manifest).map((version) => ({
2445
+ packageName: packageName2,
2446
+ version,
2447
+ binding: {
2448
+ kind: "namespace",
2449
+ name: namespaceOf(packageName2),
2450
+ import: `${packageName2}/${version}`
2451
+ }
2452
+ }));
2453
+ });
2454
+ }
2455
+ function versionsOf(manifest) {
2456
+ const subpaths = typeof manifest.exports === "object" ? Object.keys(manifest.exports) : [];
2457
+ return subpaths.filter((subpath) => VERSION_SUBPATH_PATTERN.test(subpath)).filter((subpath) => subpaths.includes(`${subpath}/${TEST_ENTRY}`)).map((subpath) => subpath.slice(2));
2458
+ }
2459
+ function chooseInstalledBinding(params) {
2460
+ if (params.bindings.length === 0)
2461
+ return { kind: "output", message: textOf([NO_DIALECTE_INSTALLED, ""]) };
2462
+ const matching = params.bindings.filter(
2463
+ (binding) => (params.packageName === void 0 || binding.packageName === params.packageName) && (params.version === void 0 || binding.version === params.version)
1660
2464
  );
2465
+ if (matching.length === 1) return { kind: "binding", binding: matching[0] };
2466
+ if (matching.length === 0) {
2467
+ const named = [
2468
+ ...params.packageName === void 0 ? [] : [`--package ${params.packageName}`],
2469
+ ...params.version === void 0 ? [] : [`--version ${params.version}`]
2470
+ ].join(" ");
2471
+ return {
2472
+ kind: "output",
2473
+ message: textOf([
2474
+ `no installed dialecte matches ${named}; installed:`,
2475
+ ...listLines(params.bindings),
2476
+ ""
2477
+ ])
2478
+ };
2479
+ }
2480
+ return {
2481
+ kind: "output",
2482
+ message: textOf([
2483
+ "several dialectes are installed: pass --package <name> [--version <v>]",
2484
+ ...listLines(matching),
2485
+ ""
2486
+ ])
2487
+ };
2488
+ }
2489
+ function listLines(bindings) {
2490
+ return bindings.map((binding) => ` ${binding.packageName} --version ${binding.version}`);
1661
2491
  }
1662
2492
 
1663
2493
  // src/lib/binding-refs.ts
@@ -1722,8 +2552,7 @@ function readMemberEntries(params) {
1722
2552
  const [expression] = positionalArguments({ argv, valueOptions: MEMBERS_VALUE_OPTIONS });
1723
2553
  const usage = {
1724
2554
  kind: "output",
1725
- output: { output: `${MEMBERS_USAGE}
1726
- `, exitCode: 2 }
2555
+ output: { output: textOf([MEMBERS_USAGE, ""]), exitCode: 2 }
1727
2556
  };
1728
2557
  if (!expression) return usage;
1729
2558
  const binding = readBinding({ argv, cwd });
@@ -1754,31 +2583,35 @@ function answerModels(params) {
1754
2583
  const knownIds = VENDOR_IDS;
1755
2584
  if (params.vendor === void 0)
1756
2585
  return {
1757
- output: `dialecte models: no vendor known for this project. Run \`dialecte skills sync --vendor <${knownIds.join("|")}>\`, or pass \`--vendor <id>\`.
1758
- `,
2586
+ output: textOf([
2587
+ `dialecte models: no vendor known for this project. Run \`dialecte skills sync --vendor <${knownIds.join("|")}>\`, or pass \`--vendor <id>\`.`,
2588
+ ""
2589
+ ]),
1759
2590
  exitCode: 2
1760
2591
  };
1761
2592
  if (!isVendorId(params.vendor))
1762
2593
  return {
1763
- output: `dialecte models: unknown vendor "${params.vendor}" (known: ${knownIds.join(", ")})
1764
- `,
2594
+ output: textOf([
2595
+ `dialecte models: unknown vendor "${params.vendor}" (known: ${knownIds.join(", ")})`,
2596
+ ""
2597
+ ]),
1765
2598
  exitCode: 1
1766
2599
  };
1767
2600
  const models = MODEL_TIERS.vendors[params.vendor];
1768
2601
  if (params.json)
1769
2602
  return {
1770
- output: `${JSON.stringify(
1771
- {
1772
- vendor: params.vendor,
1773
- checkedAt: MODEL_TIERS.checkedAt,
1774
- tiers: models.tiers,
1775
- ...models.note === void 0 ? {} : { note: models.note },
1776
- definitions: TIER_DEFINITIONS
1777
- },
1778
- null,
1779
- " "
1780
- )}
1781
- `,
2603
+ output: endedOf(
2604
+ jsonOf(
2605
+ {
2606
+ vendor: params.vendor,
2607
+ checkedAt: MODEL_TIERS.checkedAt,
2608
+ tiers: models.tiers,
2609
+ ...models.note === void 0 ? {} : { note: models.note },
2610
+ definitions: TIER_DEFINITIONS
2611
+ },
2612
+ " "
2613
+ )
2614
+ ),
1782
2615
  exitCode: 0
1783
2616
  };
1784
2617
  const width = Math.max(...TIER_NAMES.map((tier) => tier.length)) + 2;
@@ -1789,8 +2622,7 @@ function answerModels(params) {
1789
2622
  "",
1790
2623
  ...TIER_NAMES.map((tier) => `${tier.padEnd(width)}${TIER_DEFINITIONS[tier]}`)
1791
2624
  ];
1792
- return { output: `${lines.join("\n")}
1793
- `, exitCode: 0 };
2625
+ return { output: textOf([...lines, ""]), exitCode: 0 };
1794
2626
  }
1795
2627
  function renderModel(tierModel) {
1796
2628
  return tierModel.effort === void 0 ? tierModel.model : `${tierModel.model} (${tierModel.effort})`;
@@ -1799,22 +2631,102 @@ function renderModel(tierModel) {
1799
2631
  // src/commands/models.ts
1800
2632
  function runModels(params) {
1801
2633
  const missing = missingPackage({ cwd: params.cwd });
1802
- if (missing) return { ...missing, warnings: "" };
2634
+ if (missing) return { ...missing, warnings: textOf([]) };
1803
2635
  const argv = [...params.argv];
1804
2636
  const remembered = readRememberedVendor(params.cwd);
1805
2637
  const answer = answerModels({
1806
2638
  vendor: getArg(argv, "vendor") ?? remembered.vendor,
1807
2639
  json: hasFlag(argv, "json")
1808
2640
  });
1809
- return { ...answer, warnings: remembered.warnings.map((warning) => `\u26A0\uFE0F ${warning}
1810
- `).join("") };
2641
+ const warnings = remembered.warnings.map((warning) => `\u26A0\uFE0F ${warning}`);
2642
+ return { ...answer, warnings: textOf(warnings.length === 0 ? [] : [...warnings, ""]) };
2643
+ }
2644
+
2645
+ // src/lib/schema/resolve-declaration.ts
2646
+ function resolveDeclaration(params) {
2647
+ const tagLevel = params.definition[params.tagName];
2648
+ if (tagLevel === void 0) return void 0;
2649
+ const declarations = tagLevel.declarations;
2650
+ if (declarations === void 0) return { declarations: 1, resolved: true, id: void 0 };
2651
+ const id = singleHeldId({
2652
+ definition: params.definition,
2653
+ tagName: params.tagName,
2654
+ parent: params.parent
2655
+ });
2656
+ const known = id !== void 0 && declarations[id] !== void 0;
2657
+ return {
2658
+ declarations: Object.keys(declarations).length,
2659
+ resolved: known,
2660
+ id: known ? id : void 0
2661
+ };
2662
+ }
2663
+ function heldDeclarationIds(params) {
2664
+ const held = heldByNamespace(params);
2665
+ return held === void 0 ? [] : [...new Set(Object.values(held).flat())];
2666
+ }
2667
+ function declarationParents(params) {
2668
+ const { definition, tagName, id } = params;
2669
+ return (definition[tagName]?.parents ?? []).filter(function holdsDeclaration(parent) {
2670
+ return heldDeclarationIds({ definition, tagName, parent }).includes(id);
2671
+ });
2672
+ }
2673
+ function singleHeldId(params) {
2674
+ const held = heldByNamespace(params);
2675
+ if (held === void 0) return void 0;
2676
+ const namespaces = Object.keys(held);
2677
+ if (namespaces.length !== 1) return void 0;
2678
+ const ids = held[namespaces[0]];
2679
+ return ids?.length === 1 ? ids[0] : void 0;
2680
+ }
2681
+ function heldByNamespace(params) {
2682
+ if (params.parent === void 0) return void 0;
2683
+ return params.definition[params.parent]?.children.details[params.tagName]?.declarations;
1811
2684
  }
1812
2685
 
1813
2686
  // src/lib/schema/describe-element.ts
1814
2687
  function describeElement(params) {
2688
+ const { dialecte, tagName, parent } = params;
2689
+ const { definition, elements } = dialecte.config;
2690
+ const tagLevel = definition[tagName];
2691
+ if (!elements.includes(tagName) || tagLevel === void 0) return void 0;
2692
+ if (parent !== void 0 && !tagLevel.parents.includes(parent)) return void 0;
2693
+ const resolution = resolveDeclaration({ definition, tagName, parent });
2694
+ if (resolution === void 0) return void 0;
2695
+ if (resolution.id !== void 0)
2696
+ return describeDeclaration({ dialecte, tagName, id: resolution.id });
2697
+ return describeDefinition({
2698
+ dialecte,
2699
+ tagName,
2700
+ declaration: void 0,
2701
+ declarations: resolution.declarations,
2702
+ resolved: resolution.resolved
2703
+ });
2704
+ }
2705
+ function describeDeclaration(params) {
2706
+ const { dialecte, tagName, id } = params;
2707
+ const declarations = dialecte.config.definition[tagName]?.declarations;
2708
+ if (declarations?.[id] === void 0) return void 0;
2709
+ return describeDefinition({
2710
+ dialecte: { ...dialecte, config: declarationView({ config: dialecte.config, tagName, id }) },
2711
+ tagName,
2712
+ declaration: id,
2713
+ declarations: Object.keys(declarations).length,
2714
+ resolved: true
2715
+ });
2716
+ }
2717
+ function declarationView(params) {
2718
+ const { config, tagName, id } = params;
2719
+ const tagLevel = config.definition[tagName];
2720
+ const declaration = tagLevel.declarations?.[id];
2721
+ if (declaration === void 0) return config;
2722
+ const parents = declarationParents({ definition: config.definition, tagName, id });
2723
+ const element = { ...declaration, tag: tagLevel.tag, parents };
2724
+ return { ...config, definition: { ...config.definition, [tagName]: element } };
2725
+ }
2726
+ function describeDefinition(params) {
1815
2727
  const { config, readers, packageName: packageName2 } = params.dialecte;
1816
2728
  const record = { tagName: params.tagName, parent: null, attributes: [] };
1817
- const definition = config.elements.includes(params.tagName) ? readers.resolveDefinition({ dialecteConfig: config, record }) : void 0;
2729
+ const definition = readers.resolveDefinition({ dialecteConfig: config, record });
1818
2730
  if (definition === void 0) return void 0;
1819
2731
  const occurrences = readers.childOccurrences({ definition });
1820
2732
  const children = readers.orderByConfigSequence({
@@ -1845,7 +2757,12 @@ function describeElement(params) {
1845
2757
  };
1846
2758
  }),
1847
2759
  text: definition.textContent ? typeName(definition.textContent.type) ?? "string" : void 0,
1848
- xsiTypes: readers.admittedXsiTypes({ dialecteConfig: config, record })
2760
+ xsiTypes: readers.admittedXsiTypes({ dialecteConfig: config, record }),
2761
+ type: definition.type,
2762
+ documentation: definition.documentation,
2763
+ declaration: params.declaration,
2764
+ declarations: params.declarations,
2765
+ resolved: params.resolved
1849
2766
  };
1850
2767
  }
1851
2768
  function typeName(datatype) {
@@ -1854,24 +2771,104 @@ function typeName(datatype) {
1854
2771
  return "list" in datatype ? "list" : "union";
1855
2772
  }
1856
2773
 
2774
+ // src/lib/schema/describe-declarations.ts
2775
+ function describeDeclarations(params) {
2776
+ const { dialecte, tagName, ids } = params;
2777
+ const { definition, elements } = dialecte.config;
2778
+ const declarations = elements.includes(tagName) ? definition[tagName]?.declarations : void 0;
2779
+ const kept = Object.entries(declarations ?? {}).filter(
2780
+ ([id]) => ids === void 0 || ids.includes(id)
2781
+ );
2782
+ return kept.flatMap(function describeWay([id, declaration]) {
2783
+ const element = describeDeclaration({ dialecte, tagName, id });
2784
+ if (element === void 0) return [];
2785
+ return [
2786
+ {
2787
+ id,
2788
+ parents: declarationParents({ definition, tagName, id }),
2789
+ global: declaration.global === true,
2790
+ element
2791
+ }
2792
+ ];
2793
+ });
2794
+ }
2795
+
1857
2796
  // src/lib/schema/answer-schema.ts
1858
2797
  function answerSchema(params) {
1859
- const { loaded, tagName } = params;
1860
- const elements = loaded.dialectes.flatMap(
1861
- (dialecte) => describeElement({ dialecte, tagName }) ?? []
2798
+ const { loaded, tagName, under } = params;
2799
+ const answers = loaded.dialectes.flatMap(
2800
+ (dialecte) => answerOf({ dialecte, tagName, under }) ?? []
1862
2801
  );
1863
2802
  if (params.json)
1864
2803
  return {
1865
- output: `${JSON.stringify({ elements, skipped: loaded.skipped }, null, " ")}
1866
- `,
1867
- exitCode: elements.length ? 0 : 1
2804
+ output: endedOf(
2805
+ jsonOf({ elements: answers.map(jsonElementOf), skipped: loaded.skipped }, " ")
2806
+ ),
2807
+ exitCode: answers.length ? 0 : 1
2808
+ };
2809
+ if (answers.length)
2810
+ return {
2811
+ output: textOf([
2812
+ ...answers.flatMap((answer, index) => [
2813
+ ...index === 0 ? [] : [""],
2814
+ ...renderAnswer(answer)
2815
+ ]),
2816
+ ""
2817
+ ]),
2818
+ exitCode: 0
1868
2819
  };
1869
- if (elements.length) return { output: elements.map(renderElement).join("\n"), exitCode: 0 };
2820
+ return { output: textOf([...missingLines({ loaded, tagName, under }), ""]), exitCode: 1 };
2821
+ }
2822
+ function answerOf(params) {
2823
+ const { dialecte, tagName, under } = params;
2824
+ const element = describeElement({ dialecte, tagName, parent: under });
2825
+ if (element === void 0) return void 0;
2826
+ const ways = element.resolved ? [] : describeDeclarations({ dialecte, tagName, ids: openIds({ dialecte, tagName, under }) });
2827
+ return { element, ways, under };
2828
+ }
2829
+ function openIds(params) {
2830
+ const { dialecte, tagName, under } = params;
2831
+ if (under === void 0) return void 0;
2832
+ const held = heldDeclarationIds({
2833
+ definition: dialecte.config.definition,
2834
+ tagName,
2835
+ parent: under
2836
+ });
2837
+ return held.length ? held : void 0;
2838
+ }
2839
+ function jsonElementOf(answer) {
2840
+ return answer.element.resolved ? answer.element : { ...answer.element, ways: answer.ways };
2841
+ }
2842
+ function renderAnswer(answer) {
2843
+ const { element, under } = answer;
2844
+ if (element.resolved && (element.declaration === void 0 || under === void 0))
2845
+ return renderElement(element);
2846
+ if (element.resolved)
2847
+ return [
2848
+ `${element.tag} under ${under}: declaration ${element.declaration}, one of ${element.declarations} ways`,
2849
+ ...renderElement(element)
2850
+ ];
2851
+ const heading = under === void 0 ? `${element.tag} is declared ${element.declarations} ways - pick one with --under <Parent>` : `${element.tag} under ${under}: declarations ${listOf(answer.ways.map((way) => way.id))} of ${element.declarations}, the parent does not decide`;
2852
+ return [
2853
+ heading,
2854
+ ...answer.ways.flatMap((way, index) => [...index === 0 ? [] : [""], ...renderWay(way)])
2855
+ ];
2856
+ }
2857
+ function renderWay(way) {
2858
+ return [`declaration ${way.id}${way.global ? " global" : ""}`, ...renderElement(way.element)];
2859
+ }
2860
+ function listOf(words) {
2861
+ if (words.length < 2) return words.join("");
2862
+ return `${words.slice(0, -1).join(", ")} and ${words[words.length - 1]}`;
2863
+ }
2864
+ function missingLines(params) {
2865
+ const { loaded, tagName, under } = params;
1870
2866
  const skipped = loaded.skipped.length ? ` (skipped ${loaded.skipped.map((entry) => `${entry.packageName}: ${entry.reason}`).join("; ")})` : "";
1871
- if (loaded.dialectes.length === 0)
1872
- return { output: `no installed dialecte holds "${tagName}"${skipped}
1873
- `, exitCode: 1 };
1874
- const suggestions = loaded.dialectes.map((dialecte) => {
2867
+ if (loaded.dialectes.length === 0) return [`no installed dialecte holds "${tagName}"${skipped}`];
2868
+ const lines = loaded.dialectes.map(function missingLine(dialecte) {
2869
+ const tagLevel = dialecte.config.elements.includes(tagName) ? dialecte.config.definition[tagName] : void 0;
2870
+ if (tagLevel !== void 0 && under !== void 0)
2871
+ return `no ${tagName} under ${under} - its parents: ${tagLevel.parents.join(", ") || "none (the root)"}`;
1875
2872
  const closest = closestNames({
1876
2873
  name: tagName,
1877
2874
  candidates: dialecte.config.elements,
@@ -1879,14 +2876,14 @@ function answerSchema(params) {
1879
2876
  });
1880
2877
  return `no element "${tagName}" in ${dialecte.packageName}${closest.length ? ` - closest: ${closest.join(", ")}` : ""}`;
1881
2878
  });
1882
- return { output: `${suggestions.join("\n")}${skipped}
1883
- `, exitCode: 1 };
2879
+ const lastIndex = lines.length - 1;
2880
+ return lines.map((line, index) => index === lastIndex ? `${line}${skipped}` : line);
1884
2881
  }
1885
2882
  function renderElement(element) {
1886
- const lines = [
1887
- `${element.tag} ${element.packageName} {${element.namespace}}`,
1888
- `parents: ${element.parents.join(", ") || "none (the root)"}`
1889
- ];
2883
+ const lines = [`${element.tag} ${element.packageName} {${element.namespace}}`];
2884
+ if (element.documentation !== void 0) lines.push(`documentation: ${element.documentation}`);
2885
+ if (element.type !== void 0) lines.push(`type: ${element.type}`);
2886
+ lines.push(`parents: ${element.parents.join(", ") || "none (the root)"}`);
1890
2887
  if (element.children.length || element.anyChild) lines.push("children, in order:");
1891
2888
  else lines.push("children: none");
1892
2889
  for (const child of element.children)
@@ -1896,8 +2893,7 @@ function renderElement(element) {
1896
2893
  for (const attribute of element.attributes) lines.push(` ${renderAttribute(attribute)}`);
1897
2894
  lines.push(`text: ${element.text ?? "none"}`);
1898
2895
  if (element.xsiTypes.length) lines.push(`xsi:type: ${element.xsiTypes.join(", ")}`);
1899
- return `${lines.join("\n")}
1900
- `;
2896
+ return lines;
1901
2897
  }
1902
2898
  function renderAttribute(attribute) {
1903
2899
  const parts = [
@@ -1915,21 +2911,24 @@ function renderAttribute(attribute) {
1915
2911
  }
1916
2912
 
1917
2913
  // src/commands/schema.constants.ts
1918
- var SCHEMA_VALUE_OPTIONS = ["package"];
1919
- var SCHEMA_USAGE = "usage: dialecte schema <Tag> [--package <name>] [--json]";
2914
+ var SCHEMA_VALUE_OPTIONS = ["package", "under"];
2915
+ var SCHEMA_USAGE = "usage: dialecte schema <Tag> [--under <Parent>] [--package <name>] [--json]";
1920
2916
 
1921
2917
  // src/commands/schema.ts
1922
2918
  async function readSchemaDialectes(params) {
1923
2919
  const missing = missingPackage({ cwd: params.cwd });
1924
2920
  if (missing) return { kind: "output", output: missing };
1925
2921
  const [tagName] = positionalArguments({ argv: params.argv, valueOptions: SCHEMA_VALUE_OPTIONS });
1926
- if (!tagName) return { kind: "output", output: { output: `${SCHEMA_USAGE}
1927
- `, exitCode: 2 } };
2922
+ const under = getArg(params.argv, "under");
2923
+ const underWithoutValue = hasFlag(params.argv, "under") && (under === void 0 || under === "" || under.startsWith("--"));
2924
+ if (!tagName || underWithoutValue)
2925
+ return { kind: "output", output: { output: textOf([SCHEMA_USAGE, ""]), exitCode: 2 } };
1928
2926
  const packageName2 = getArg(params.argv, "package");
1929
2927
  const loaded = await loadDialectes({ cwd: params.cwd });
1930
2928
  return {
1931
2929
  kind: "dialectes",
1932
2930
  tagName,
2931
+ under,
1933
2932
  packageName: packageName2,
1934
2933
  installed: loaded.dialectes.map((dialecte) => dialecte.packageName),
1935
2934
  loaded: {
@@ -1943,6 +2942,7 @@ async function readSchemaDialectes(params) {
1943
2942
  export {
1944
2943
  answerMembers,
1945
2944
  answerSchema,
2945
+ describeElement,
1946
2946
  packagesText,
1947
2947
  readApiIndexes,
1948
2948
  readCliVersion,