@kurvball/ashlar 1.5.0 → 1.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/CHANGELOG.md CHANGED
@@ -6,6 +6,14 @@ changesets merged since the release before it, under its version and release dat
6
6
  and patch changes; see [RELEASING.md](RELEASING.md). Versions up to 1.0.1 follow
7
7
  [Keep a Changelog 1.1.0](https://keepachangelog.com/en/1.1.0/).
8
8
 
9
+ ## 1.6.0
10
+
11
+ _Released 2026-12-04._
12
+
13
+ ### Minor Changes
14
+
15
+ - `ashlar init` finds a repository's apps, their features and their areas, writes `ashlar.config.ts` (`.mts` in a package that isn't a module) and takes the baseline, where there is no config yet. `--dry-run` prints the config it would write. `--json` answers in `schema/init.v1.json`, and `ashlar mcp` serves it as the `init` tool.
16
+
9
17
  ## 1.5.0
10
18
 
11
19
  _Released 2026-12-04._
package/README.md CHANGED
@@ -58,9 +58,13 @@ Install Ashlar from npm, as a dev dependency:
58
58
 
59
59
  ```sh
60
60
  pnpm add -D @kurvball/ashlar
61
+ pnpm exec ashlar init
61
62
  pnpm exec ashlar check
62
63
  ```
63
64
 
65
+ `ashlar init` finds the repository's apps, their features and their areas, writes `ashlar.config.ts`, and takes
66
+ the baseline.
67
+
64
68
  With npm, `npm install -D @kurvball/ashlar`, then `npx --no-install ashlar check`. Each version is published by
65
69
  Ashlar's release workflow with [provenance](https://docs.npmjs.com/generating-provenance-statements): its npm
66
70
  page names the commit and the workflow run that built it. To try an unreleased change, `pnpm pack` this
@@ -95,6 +99,7 @@ wrong type, gets one line saying which key and what is wrong.
95
99
 
96
100
  | Command | What it does |
97
101
  | ---------------------------- | --------------------------------------------------------------------------------------- |
102
+ | `ashlar init` | Finds the apps, writes `ashlar.config.ts` and takes the baseline. |
98
103
  | `ashlar check` | Fails when a file's count rises above the baseline. `--shrink` lowers it. |
99
104
  | `ashlar affected <files...>` | Lists the tests that reach the files. `--since <ref>` takes a branch's changes. |
100
105
  | `ashlar move <from> <to>` | Moves a file's or a folder's counts in the baseline to its new name. |
@@ -108,7 +113,7 @@ wrong type, gets one line saying which key and what is wrong.
108
113
  | `ashlar skill onboard` | Prints the skill an agent follows to read its brief and keep decisions. |
109
114
  | `ashlar dependents <files>` | Lists what reaches each file, for Rehearse's `rehearse list --affected`. |
110
115
  | `ashlar rehearse` | Prints the blocks of `rehearse.yaml` Ashlar fills: each reach script a flow. |
111
- | `ashlar mcp` | Serves `brief`, `check`, `affected`, `map` and `onboard` as MCP tools, for agents. |
116
+ | `ashlar mcp` | Serves `init`, `brief`, `check`, `affected`, `map` and `onboard` as MCP tools. |
112
117
 
113
118
  A feature's reach script, `reach.ts` in its folder, lists the steps a person takes to get to it in the running
114
119
  app. `affected` follows imports, stylesheets, setup files and builds. `skill verify --write` writes the skill
package/dist/cli.js CHANGED
@@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs';
3
3
  import { relative } from 'node:path';
4
4
  import { affectedAnswer, briefAnswer, checkAnswer, mapAnswer, onboardAnswer } from './answers.js';
5
5
  import { AshlarError, loadConfig } from './config.js';
6
+ import { init, initText } from './init.js';
6
7
  import { serve } from './mcp.js';
7
8
  import { featuresOf, unreadText } from './features.js';
8
9
  import { ledgerOf, ledgerText } from './ledger.js';
@@ -31,6 +32,7 @@ const FLAGS = {
31
32
  dependents: ['json'],
32
33
  rehearse: ['json'],
33
34
  mcp: [],
35
+ init: ['dry-run', 'json'],
34
36
  };
35
37
  const VALUED = new Map([
36
38
  ['since', 'a ref'],
@@ -91,6 +93,15 @@ async function main(args) {
91
93
  throw new AshlarError(`\`ashlar ${command}\` takes no ${unknown.map((f) => `--${f}`).join(', ')}: it takes ${named}.`);
92
94
  }
93
95
  }
96
+ if (command === 'init') {
97
+ if (positional.length > 0)
98
+ throw new AshlarError('`ashlar init` takes no paths: run it at the root of the repository.');
99
+ const { report, warnings } = init(process.cwd(), { dryRun: flags.has('dry-run') });
100
+ print(json, report, initText(report));
101
+ for (const warning of warnings)
102
+ process.stderr.write(`Warning: ${warning}\n`);
103
+ return 0;
104
+ }
94
105
  if (command === 'mcp') {
95
106
  if (positional.length > 0)
96
107
  throw new AshlarError('`ashlar mcp` takes no files.');
package/dist/init.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ import { type AshlarConfig } from './config.ts';
2
+ import type { AppConfig, Stack } from './layout.ts';
3
+ export interface InitApp {
4
+ root: string;
5
+ stack: Stack;
6
+ features: number;
7
+ why: string;
8
+ }
9
+ export interface InitReport {
10
+ version: 1;
11
+ config: string;
12
+ wrote: boolean;
13
+ include: string[];
14
+ apps: InitApp[];
15
+ owner: string | null;
16
+ baseline: {
17
+ file: string | null;
18
+ breaks: number;
19
+ } | null;
20
+ source: string;
21
+ seconds: number;
22
+ }
23
+ export interface Found {
24
+ include: string[];
25
+ apps: {
26
+ config: AppConfig;
27
+ found: InitApp;
28
+ }[];
29
+ owner: string | null;
30
+ }
31
+ export declare function detect(root: string): Found;
32
+ export declare function configOf(found: Found): AshlarConfig;
33
+ export declare function configSource(config: AshlarConfig): string;
34
+ export declare function init(root: string, options?: {
35
+ dryRun?: boolean;
36
+ }): {
37
+ report: InitReport;
38
+ warnings: string[];
39
+ };
40
+ export declare function initText(report: InitReport): string;
package/dist/init.js ADDED
@@ -0,0 +1,308 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { join, posix, relative } from 'node:path';
4
+ import { check } from './check.js';
5
+ import { AshlarError, CONFIG_FILE, findConfig, settle } from './config.js';
6
+ const SKIPPED = new Set([
7
+ 'node_modules',
8
+ 'dist',
9
+ 'out',
10
+ 'release',
11
+ 'build',
12
+ 'coverage',
13
+ '.git',
14
+ 'target',
15
+ 'vendor',
16
+ ]);
17
+ const BESIDE = new Set(['docs', 'doc', 'examples', 'example', 'fixtures', '__fixtures__']);
18
+ const NOT_APPS = new Set([...BESIDE, 'test', 'tests', '__tests__', 'e2e', 'scripts']);
19
+ const UI_PACKAGES = ['react', 'react-dom', 'vue', 'svelte', 'solid-js', 'preact', '@angular/core', 'lit'];
20
+ const SOURCE = /\.(?:ts|tsx|mts|cts)$/;
21
+ const DECLARATION = /\.d\.[mc]?ts$/;
22
+ const DEEPEST_FEATURES = 4;
23
+ function filesOf(root) {
24
+ const listed = spawnSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], {
25
+ cwd: root,
26
+ encoding: 'utf8',
27
+ maxBuffer: 256 * 1024 * 1024,
28
+ });
29
+ const files = listed.status === 0 ? listed.stdout.split('\n').filter((line) => line !== '') : walk(root, '');
30
+ return files.filter((file) => !file.split('/').some((part) => SKIPPED.has(part)));
31
+ }
32
+ function walk(root, folder) {
33
+ return readdirSync(join(root, folder), { withFileTypes: true }).flatMap((entry) => {
34
+ const path = folder ? `${folder}/${entry.name}` : entry.name;
35
+ if (SKIPPED.has(entry.name) || entry.name.startsWith('.'))
36
+ return [];
37
+ return entry.isDirectory() ? walk(root, path) : [path];
38
+ });
39
+ }
40
+ const isSource = (file) => SOURCE.test(file) && !DECLARATION.test(file);
41
+ function foldersOf(files) {
42
+ const folders = new Set();
43
+ for (const file of files) {
44
+ const parts = file.split('/');
45
+ for (let depth = 1; depth < parts.length; depth += 1)
46
+ folders.add(parts.slice(0, depth).join('/'));
47
+ }
48
+ return folders;
49
+ }
50
+ const joined = (...parts) => posix.join(...parts.filter((part) => part !== '')) || '';
51
+ const inside = (path, folder) => folder === '' || path.startsWith(`${folder}/`);
52
+ const childrenOf = (folders, folder) => [...folders].filter((path) => inside(path, folder) && !path.slice(folder ? folder.length + 1 : 0).includes('/'));
53
+ function dependenciesOf(root, folder) {
54
+ const file = join(root, folder, 'package.json');
55
+ if (!existsSync(file))
56
+ return new Set();
57
+ const manifest = JSON.parse(readFileSync(file, 'utf8'));
58
+ return new Set([
59
+ ...Object.keys(manifest.dependencies ?? {}),
60
+ ...Object.keys(manifest.devDependencies ?? {}),
61
+ ...Object.keys(manifest.peerDependencies ?? {}),
62
+ ]);
63
+ }
64
+ function includeOf(sources) {
65
+ const counts = new Map();
66
+ for (const file of sources) {
67
+ const [top, ...rest] = file.split('/');
68
+ if (rest.length === 0 || !top || BESIDE.has(top))
69
+ continue;
70
+ counts.set(top, (counts.get(top) ?? 0) + 1);
71
+ }
72
+ return [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([top]) => top);
73
+ }
74
+ function candidatesOf(files, sources) {
75
+ const packages = files
76
+ .filter((file) => file.endsWith('/package.json'))
77
+ .map((file) => posix.dirname(file))
78
+ .filter((folder) => !folder.split('/').some((part) => NOT_APPS.has(part)))
79
+ .filter((folder) => sources.some((file) => inside(file, folder)))
80
+ .sort();
81
+ if (packages.length === 0)
82
+ return [''];
83
+ const loose = sources.some((file) => file.startsWith('src/') && !packages.some((folder) => inside(file, folder)));
84
+ return loose ? ['', ...packages] : packages;
85
+ }
86
+ function featuresFolder(folders, source) {
87
+ const found = [...folders]
88
+ .filter((path) => inside(path, source) && posix.basename(path) === 'features')
89
+ .filter((path) => {
90
+ const rest = path.slice(source ? source.length + 1 : 0).split('/');
91
+ return rest.length <= DEEPEST_FEATURES && !rest.some((part) => NOT_APPS.has(part));
92
+ })
93
+ .filter((path) => childrenOf(folders, path).length > 0)
94
+ .sort((a, b) => a.split('/').length - b.split('/').length || a.localeCompare(b));
95
+ return found[0] ?? null;
96
+ }
97
+ const local = (path, root) => (root === '' ? path : path.slice(root.length + 1)) || '.';
98
+ function roles(folders, root, renderer) {
99
+ const at = (name) => joined(root, renderer === '.' ? '' : renderer, name);
100
+ const role = (name) => (folders.has(at(name)) ? [local(at(name), root)] : undefined);
101
+ return { client: role('client'), primitives: role('primitives') };
102
+ }
103
+ function counted(folders, pattern) {
104
+ return pattern.endsWith('/*') ? childrenOf(folders, pattern.slice(0, -2)).length : 0;
105
+ }
106
+ function app(given, why, folders) {
107
+ const config = Object.fromEntries(Object.entries({ ...given, root: given.root || '.' }).filter(([, value]) => value !== undefined));
108
+ const features = (config.features ?? [])
109
+ .map((pattern) => counted(folders, joined(config.root, pattern)))
110
+ .reduce((sum, count) => sum + count, 0);
111
+ return { config, found: { root: config.root, stack: config.stack, features, why } };
112
+ }
113
+ function classify(root, folder, folders, sources) {
114
+ const has = (path) => folders.has(path);
115
+ const src = joined(folder, 'src');
116
+ if (has(joined(folder, 'src-tauri'))) {
117
+ const features = has(joined(src, 'features')) ? { features: ['src/features/*'] } : {};
118
+ return app({ root: folder, stack: 'tauri', ...features }, 'a Tauri app: its host in src-tauri/, its screens in src/', folders);
119
+ }
120
+ for (const at of [folder, src]) {
121
+ if (has(joined(at, 'electron-main')) || has(joined(at, 'electron-renderer'))) {
122
+ const features = has(joined(at, 'electron-renderer/features'))
123
+ ? { features: ['electron-renderer/features/*'] }
124
+ : {};
125
+ return app({ root: at, stack: 'electron', ...features }, 'an Electron app: electron-main/ and electron-renderer/', folders);
126
+ }
127
+ }
128
+ for (const at of [folder, src]) {
129
+ if (has(joined(at, 'server')) && has(joined(at, 'client'))) {
130
+ const features = has(joined(at, 'client/features')) ? { features: ['client/features/*'] } : {};
131
+ return app({ root: at, stack: 'web', ...features }, 'a web app: its server in server/, its screens in client/', folders);
132
+ }
133
+ }
134
+ const dependencies = dependenciesOf(root, folder);
135
+ if (dependencies.has('electron') && has(joined(src, 'main')) && has(joined(src, 'renderer'))) {
136
+ const feature = featuresFolder(folders, joined(src, 'renderer'));
137
+ return app({
138
+ root: folder,
139
+ stack: 'electron',
140
+ main: ['src/main', ...(has(joined(src, 'preload')) ? ['src/preload'] : [])],
141
+ renderer: ['src/renderer'],
142
+ shared: has(joined(src, 'shared')) ? ['src/shared'] : [],
143
+ ...(feature ? { features: [`${local(feature, folder)}/*`] } : {}),
144
+ ...roles(folders, folder, feature ? local(posix.dirname(feature), folder) : 'src/renderer'),
145
+ }, 'an Electron app: its main process in src/main, its screens in src/renderer', folders);
146
+ }
147
+ const base = has(src) ? src : folder;
148
+ const feature = featuresFolder(folders, base);
149
+ const ui = UI_PACKAGES.some((name) => dependencies.has(name));
150
+ const shown = (path) => path || '.';
151
+ if (feature && posix.dirname(feature) !== base) {
152
+ const renderer = local(posix.dirname(feature), base);
153
+ const { client, primitives } = roles(folders, base, renderer);
154
+ return app({
155
+ root: base,
156
+ stack: 'web',
157
+ main: ['.'],
158
+ renderer: [renderer],
159
+ features: [`${renderer}/features/*`],
160
+ ...(client ? { client } : {}),
161
+ ...(primitives ? { primitives } : {}),
162
+ areas: ['*', ...(client ?? []), ...(primitives ?? [])],
163
+ ...(client ? { bridge: { global: 'fetch' } } : {}),
164
+ }, `a web app: its code in ${shown(base)}, its screens in ${joined(base, renderer)}`, folders);
165
+ }
166
+ if (feature || ui) {
167
+ const { client, primitives } = roles(folders, base, '.');
168
+ return app({
169
+ root: base,
170
+ stack: 'web',
171
+ main: [],
172
+ renderer: ['.'],
173
+ shared: [],
174
+ ...(feature ? { features: ['features/*'] } : {}),
175
+ ...(client ? { client } : {}),
176
+ ...(primitives ? { primitives } : {}),
177
+ ...(client ? { bridge: { global: 'fetch' } } : {}),
178
+ }, `a web front end in ${shown(base)}`, folders);
179
+ }
180
+ const subfolders = childrenOf(folders, base).filter((path) => sources.some((file) => inside(file, path)));
181
+ if (subfolders.length === 0)
182
+ return null;
183
+ return app({ root: base, stack: 'web', main: ['.'], renderer: [], shared: [], areas: ['*'] }, `no screens: each folder of ${shown(base)} is an area`, folders);
184
+ }
185
+ function ownerOf(root) {
186
+ for (const file of ['.github/CODEOWNERS', 'CODEOWNERS', 'docs/CODEOWNERS']) {
187
+ const path = join(root, file);
188
+ if (!existsSync(path))
189
+ continue;
190
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
191
+ const [pattern, owner] = line.trim().split(/\s+/);
192
+ if ((pattern === '*' || pattern === '/*') && owner?.startsWith('@'))
193
+ return owner;
194
+ }
195
+ }
196
+ return null;
197
+ }
198
+ export function detect(root) {
199
+ const files = filesOf(root);
200
+ const sources = files.filter(isSource);
201
+ if (sources.length === 0)
202
+ throw new AshlarError(`Ashlar found no TypeScript in ${root}: run it in a TypeScript repository.`);
203
+ const folders = foldersOf(files);
204
+ const apps = candidatesOf(files, sources)
205
+ .map((folder) => classify(root, folder, folders, sources))
206
+ .filter((found) => found !== null);
207
+ const include = includeOf(sources);
208
+ return { include: include.length > 0 ? include : ['.'], apps, owner: ownerOf(root) };
209
+ }
210
+ const quoted = (value) => `'${value.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'`;
211
+ function literal(value, indent) {
212
+ if (typeof value === 'string')
213
+ return quoted(value);
214
+ if (typeof value === 'boolean' || typeof value === 'number')
215
+ return String(value);
216
+ if (Array.isArray(value))
217
+ return `[${value.map((entry) => literal(entry, indent)).join(', ')}]`;
218
+ const entries = Object.entries(value).filter(([, entry]) => entry !== undefined);
219
+ const inner = `${indent} `;
220
+ const short = `{ ${entries.map(([key, entry]) => `${key}: ${literal(entry, inner)}`).join(', ')} }`;
221
+ if (short.length + indent.length <= 100)
222
+ return short;
223
+ return `{\n${entries.map(([key, entry]) => `${inner}${key}: ${literal(entry, inner)},`).join('\n')}\n${indent}}`;
224
+ }
225
+ export function configOf(found) {
226
+ return {
227
+ include: found.include,
228
+ ...(found.apps.length > 0 ? { apps: found.apps.map((entry) => entry.config) } : {}),
229
+ ...(found.owner ? { onboard: { owner: found.owner } } : {}),
230
+ };
231
+ }
232
+ export function configSource(config) {
233
+ const body = Object.entries(config)
234
+ .map(([key, value]) => {
235
+ if (key !== 'apps')
236
+ return ` ${key}: ${literal(value, ' ')},`;
237
+ const apps = value.map((entry) => ` ${literal(entry, ' ')},`).join('\n');
238
+ return ` apps: [\n${apps}\n ],`;
239
+ })
240
+ .join('\n');
241
+ return `import { defineConfig } from '@kurvball/ashlar';\n\nexport default defineConfig({\n${body}\n});\n`;
242
+ }
243
+ function configFileFor(root) {
244
+ const manifest = join(root, 'package.json');
245
+ if (!existsSync(manifest))
246
+ return 'ashlar.config.mts';
247
+ const type = JSON.parse(readFileSync(manifest, 'utf8')).type;
248
+ return type === 'module' ? CONFIG_FILE : 'ashlar.config.mts';
249
+ }
250
+ export function init(root, options = {}) {
251
+ const started = performance.now();
252
+ const existing = findConfig(root);
253
+ if (existing) {
254
+ throw new AshlarError(`Ashlar already reads ${relative(root, existing) || existing}: init writes a config only where there is none.`);
255
+ }
256
+ const found = detect(root);
257
+ const config = configOf(found);
258
+ const file = configFileFor(root);
259
+ const settled = settle(config, root, file);
260
+ const source = configSource(config);
261
+ let baseline = null;
262
+ let warnings = [];
263
+ if (!options.dryRun) {
264
+ writeFileSync(join(root, file), source);
265
+ const checked = check(settled, { shrink: true });
266
+ const breaks = checked.rules.reduce((total, rule) => total + rule.baseline, 0);
267
+ baseline = { file: breaks > 0 ? relative(root, settled.baseline) : null, breaks };
268
+ warnings = checked.warnings;
269
+ }
270
+ const report = {
271
+ version: 1,
272
+ config: file,
273
+ wrote: !options.dryRun,
274
+ include: found.include,
275
+ apps: found.apps.map((entry) => entry.found),
276
+ owner: found.owner,
277
+ baseline,
278
+ source,
279
+ seconds: (performance.now() - started) / 1000,
280
+ };
281
+ return { report, warnings };
282
+ }
283
+ const plural = (count, one, many) => `${count} ${count === 1 ? one : many}`;
284
+ function listed(names) {
285
+ return names.length < 2 ? (names[0] ?? '') : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`;
286
+ }
287
+ export function initText(report) {
288
+ const lines = report.apps.length === 0
289
+ ? ['Ashlar found no app, so only the rules that hold in every file apply.']
290
+ : [
291
+ `Ashlar found ${plural(report.apps.length, 'app', 'apps')} in ${report.seconds.toFixed(1)} s:`,
292
+ ...report.apps.map((app) => ` ${app.root}: ${app.why}${app.features > 0 ? `, ${plural(app.features, 'feature', 'features')}` : ''}.`),
293
+ ];
294
+ lines.push(`It checks ${listed(report.include)}.`);
295
+ if (report.baseline?.file) {
296
+ lines.push(`Wrote ${report.config}, and took the baseline: ${plural(report.baseline.breaks, 'break', 'breaks')} in ${report.baseline.file}.`, 'Commit both. From now on `ashlar check` fails when a file gets worse: run it on every pull request,', 'as https://ashlar.kurvball.ca/recipes/run-in-github-actions/ shows.');
297
+ }
298
+ else if (report.baseline) {
299
+ lines.push(`Wrote ${report.config}. Nothing breaks a rule, so there is no baseline: every count must stay at zero.`, 'Commit it, and run `ashlar check` on every pull request,', 'as https://ashlar.kurvball.ca/recipes/run-in-github-actions/ shows.');
300
+ }
301
+ else {
302
+ lines.push(`It would write ${report.config}, and take the baseline:`, '', report.source.trimEnd());
303
+ }
304
+ if (!report.owner) {
305
+ lines.push(`Before \`ashlar onboard\`, name who answers its questions: \`onboard: { owner: '@handle' }\`.`);
306
+ }
307
+ return `${lines.join('\n')}\n`;
308
+ }
package/dist/mcp.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { Readable, Writable } from 'node:stream';
2
2
  import { type Loaded } from './config.ts';
3
3
  export declare const PROTOCOL_VERSIONS: readonly ['2025-11-25', '2025-06-18', '2025-03-26'];
4
- export declare const INSTRUCTIONS = "Ashlar checks a TypeScript repository against rules that came from corrections, and holds each file to a baseline that only shrinks. Brief before you write, and check before you push: the skill at skill/ashlar/SKILL.md in the package teaches the loop.";
4
+ export declare const INSTRUCTIONS = "Ashlar checks a TypeScript repository against rules that came from corrections, and holds each file to a baseline that only shrinks. In a repository with no ashlar.config.ts, init writes one. Brief before you write, and check before you push: the skill at skill/ashlar/SKILL.md in the package teaches the loop.";
5
5
  type Kind = 'boolean' | 'string' | 'paths';
6
6
  interface Argument {
7
7
  kind: Kind;
@@ -17,7 +17,8 @@ interface Tool {
17
17
  args: Record<string, Argument>;
18
18
  required?: string[];
19
19
  readOnly: boolean;
20
- run: (config: Loaded, args: Record<string, unknown>) => Answer;
20
+ run?: (config: Loaded, args: Record<string, unknown>) => Answer;
21
+ start?: (args: Record<string, unknown>, cwd: string) => Answer;
21
22
  }
22
23
  export declare const TOOLS: readonly Tool[];
23
24
  export declare function outputSchemaOf(name: string): Record<string, unknown>;
package/dist/mcp.js CHANGED
@@ -2,12 +2,25 @@ import { readFileSync } from 'node:fs';
2
2
  import { createInterface } from 'node:readline';
3
3
  import { affectedAnswer, briefAnswer, checkAnswer, mapAnswer, onboardAnswer } from './answers.js';
4
4
  import { AshlarError, loadConfig } from './config.js';
5
+ import { init } from './init.js';
5
6
  export const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26'];
6
- export const INSTRUCTIONS = 'Ashlar checks a TypeScript repository against rules that came from corrections, and holds each file to a baseline that only shrinks. Brief before you write, and check before you push: the skill at skill/ashlar/SKILL.md in the package teaches the loop.';
7
+ export const INSTRUCTIONS = 'Ashlar checks a TypeScript repository against rules that came from corrections, and holds each file to a baseline that only shrinks. In a repository with no ashlar.config.ts, init writes one. Brief before you write, and check before you push: the skill at skill/ashlar/SKILL.md in the package teaches the loop.';
7
8
  const paths = (args, name) => args[name] ?? [];
8
9
  const flag = (args, name) => args[name] === true;
9
10
  const text = (args, name) => args[name];
10
11
  export const TOOLS = [
12
+ {
13
+ name: 'init',
14
+ description: 'Finds the repository’s apps, their features and areas, writes ashlar.config.ts and takes the baseline, where there is no config yet. With dryRun, answers with the config it would write, and writes nothing. Answers with init.v1.json.',
15
+ args: {
16
+ dryRun: { kind: 'boolean', description: 'Answer with the config it would write, and write nothing.' },
17
+ },
18
+ readOnly: false,
19
+ start: (args, cwd) => {
20
+ const { report, warnings } = init(cwd, { dryRun: flag(args, 'dryRun') });
21
+ return { json: report, warnings };
22
+ },
23
+ },
11
24
  {
12
25
  name: 'brief',
13
26
  description: 'What an agent needs before it changes some files: the data rules, the rules that apply there, the folder rules and gotchas, the decisions, the features and the open questions. Answers with brief.v1.json.',
@@ -137,8 +150,9 @@ export async function callTool(name, given, cwd = process.cwd(), log = process.s
137
150
  return null;
138
151
  try {
139
152
  const args = argumentsOf(tool, given);
140
- const config = await loadConfig(cwd);
141
- const { json, warnings = [] } = tool.run(config, args);
153
+ const { json, warnings = [] } = tool.start
154
+ ? tool.start(args, cwd)
155
+ : tool.run(await loadConfig(cwd), args);
142
156
  for (const warning of warnings)
143
157
  log.write(`Warning: ${warning}\n`);
144
158
  return {
package/dist/usage.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const USAGE = "Usage:\n ashlar check [--shrink] [--accept-rise] [--since <ref>] [--json]\n Runs the rules and the import graph, and fails when a file's count rises above what the\n baseline holds for that file. A file the baseline doesn't name holds none.\n --shrink writes the baseline: it takes it the first time, then only lowers each file's counts.\n A file that is gone drops out, and a file git saw renamed takes its counts to its new name.\n --accept-rise takes each count that rose into the baseline, and says what it took in.\n --since <ref> measures the lines a change touched, and the files it renamed, from where it\n left <ref> rather than main: on a pull request into a release line, give that line.\n ashlar affected [files...] [--since <ref>] [--json]\n Lists the tests that reach the files, or the files changed since <ref>, through imports,\n stylesheets, setup files and builds. A deleted file lists the tests that imported it,\n and --json lists the deleted files apart.\n ashlar move <from> <to> [<from> <to> ...] [--accept-rise] [--json]\n Moves a file's counts in the baseline to its new name, or those of every file in a folder.\n Each file keeps what it holds now, up to what the baseline held for it.\n It refuses a move that takes in new breaks, unless --accept-rise is given.\n ashlar ledger [--json]\n Lists Ashlar's ledger: each rule and each check from the import graph, what it corrected, the\n case it came from as a test, the prose it replaced and the message agents read.\n ashlar map [--json]\n Lists each feature folder in the layout: its name, its reach and its proofs, the tests in it.\n --json prints it as JSON, in the feature map's schema.\n ashlar drive <feature> [--scheme light|dark] [--json]\n ashlar drive --all [--scheme light|dark] [--json]\n Walks a feature's reach script, step by step, through the config's drive command, or through\n rehearse drive when the project has a rehearse.yaml and names none. It stops at the first step\n that fails, saying which and why. --all walks every feature's.\n ashlar onboard [--check] [--json]\n Writes the onboarding guide from the map, DECISIONS.md and .claude/rules/: what the system is, a\n page per area, and every unknown as a question routed to its owner. --check fails when the\n guide is stale or was edited by hand, and writes nothing.\n ashlar brief <paths...> [--json]\n Prints what an agent needs before it changes those files: the data rules, the rules that apply\n there, the folder rules and gotchas, the decisions, the features and the open questions. Never\n access lines, and never a secret-shaped value.\n ashlar mcp\n Serves brief, check, affected, map and onboard as MCP tools on stdio, for agents. Each tool\n takes its command's options and answers with the object its command prints with --json.\n ashlar snapshot [--json]\n Prints where things stand today: the ratchet, the map, the decisions and questions, and each\n area's recent commits. It writes nothing.\n ashlar dependents <files...> [--json]\n Lists every file that reaches each file through imports, directly or not, and the reach script\n of each feature whose folder they touch: what Rehearse reads for rehearse list --affected.\n --json prints it in Rehearse's dependents contract.\n ashlar rehearse [--json]\n Prints the blocks of rehearse.yaml Ashlar fills: each feature's reach script as a flow that\n covers its folder. --json adds each flow as Rehearse reads it.\n ashlar skill verify|onboard [--write] [--force]\n Prints a skill for agents. verify: how an agent checks its own work with the map and drive,\n and shows what it made, through the attach section the config names, if any. onboard: how an\n agent reads its brief before it changes files, and keeps what people decide.\n --write writes it into .claude/skills/<name>/SKILL.md, and --force replaces one that differs.\n\n ashlar --version\n Prints the version of Ashlar that runs.\n";
1
+ export declare const USAGE = "Usage:\n ashlar init [--dry-run] [--json]\n Finds the repository's apps, their features and areas, writes the config and takes the\n baseline, where there is no config yet. --dry-run prints the config it would write, and writes\n nothing.\n ashlar check [--shrink] [--accept-rise] [--since <ref>] [--json]\n Runs the rules and the import graph, and fails when a file's count rises above what the\n baseline holds for that file. A file the baseline doesn't name holds none.\n --shrink writes the baseline: it takes it the first time, then only lowers each file's counts.\n A file that is gone drops out, and a file git saw renamed takes its counts to its new name.\n --accept-rise takes each count that rose into the baseline, and says what it took in.\n --since <ref> measures the lines a change touched, and the files it renamed, from where it\n left <ref> rather than main: on a pull request into a release line, give that line.\n ashlar affected [files...] [--since <ref>] [--json]\n Lists the tests that reach the files, or the files changed since <ref>, through imports,\n stylesheets, setup files and builds. A deleted file lists the tests that imported it,\n and --json lists the deleted files apart.\n ashlar move <from> <to> [<from> <to> ...] [--accept-rise] [--json]\n Moves a file's counts in the baseline to its new name, or those of every file in a folder.\n Each file keeps what it holds now, up to what the baseline held for it.\n It refuses a move that takes in new breaks, unless --accept-rise is given.\n ashlar ledger [--json]\n Lists Ashlar's ledger: each rule and each check from the import graph, what it corrected, the\n case it came from as a test, the prose it replaced and the message agents read.\n ashlar map [--json]\n Lists each feature folder in the layout: its name, its reach and its proofs, the tests in it.\n --json prints it as JSON, in the feature map's schema.\n ashlar drive <feature> [--scheme light|dark] [--json]\n ashlar drive --all [--scheme light|dark] [--json]\n Walks a feature's reach script, step by step, through the config's drive command, or through\n rehearse drive when the project has a rehearse.yaml and names none. It stops at the first step\n that fails, saying which and why. --all walks every feature's.\n ashlar onboard [--check] [--json]\n Writes the onboarding guide from the map, DECISIONS.md and .claude/rules/: what the system is, a\n page per area, and every unknown as a question routed to its owner. --check fails when the\n guide is stale or was edited by hand, and writes nothing.\n ashlar brief <paths...> [--json]\n Prints what an agent needs before it changes those files: the data rules, the rules that apply\n there, the folder rules and gotchas, the decisions, the features and the open questions. Never\n access lines, and never a secret-shaped value.\n ashlar mcp\n Serves init, brief, check, affected, map and onboard as MCP tools on stdio, for agents. Each tool\n takes its command's options and answers with the object its command prints with --json.\n ashlar snapshot [--json]\n Prints where things stand today: the ratchet, the map, the decisions and questions, and each\n area's recent commits. It writes nothing.\n ashlar dependents <files...> [--json]\n Lists every file that reaches each file through imports, directly or not, and the reach script\n of each feature whose folder they touch: what Rehearse reads for rehearse list --affected.\n --json prints it in Rehearse's dependents contract.\n ashlar rehearse [--json]\n Prints the blocks of rehearse.yaml Ashlar fills: each feature's reach script as a flow that\n covers its folder. --json adds each flow as Rehearse reads it.\n ashlar skill verify|onboard [--write] [--force]\n Prints a skill for agents. verify: how an agent checks its own work with the map and drive,\n and shows what it made, through the attach section the config names, if any. onboard: how an\n agent reads its brief before it changes files, and keeps what people decide.\n --write writes it into .claude/skills/<name>/SKILL.md, and --force replaces one that differs.\n\n ashlar --version\n Prints the version of Ashlar that runs.\n";
package/dist/usage.js CHANGED
@@ -1,4 +1,8 @@
1
1
  export const USAGE = `Usage:
2
+ ashlar init [--dry-run] [--json]
3
+ Finds the repository's apps, their features and areas, writes the config and takes the
4
+ baseline, where there is no config yet. --dry-run prints the config it would write, and writes
5
+ nothing.
2
6
  ashlar check [--shrink] [--accept-rise] [--since <ref>] [--json]
3
7
  Runs the rules and the import graph, and fails when a file's count rises above what the
4
8
  baseline holds for that file. A file the baseline doesn't name holds none.
@@ -35,7 +39,7 @@ export const USAGE = `Usage:
35
39
  there, the folder rules and gotchas, the decisions, the features and the open questions. Never
36
40
  access lines, and never a secret-shaped value.
37
41
  ashlar mcp
38
- Serves brief, check, affected, map and onboard as MCP tools on stdio, for agents. Each tool
42
+ Serves init, brief, check, affected, map and onboard as MCP tools on stdio, for agents. Each tool
39
43
  takes its command's options and answers with the object its command prints with --json.
40
44
  ashlar snapshot [--json]
41
45
  Prints where things stand today: the ratchet, the map, the decisions and questions, and each
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kurvball/ashlar",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "The rules for building software with agents: lint rules, an import graph with a shrink-only ratchet, a feature map and onboarding for TypeScript projects.",
5
5
  "keywords": [
6
6
  "agents",
@@ -0,0 +1,63 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://github.com/kurvball/ashlar/blob/main/schema/init.v1.json",
4
+ "title": "ashlar init --json",
5
+ "description": "The apps Ashlar found, the folders it checks, the config it wrote, and the baseline it took.",
6
+ "type": "object",
7
+ "required": ["version", "config", "wrote", "include", "apps", "owner", "baseline", "source", "seconds"],
8
+ "additionalProperties": false,
9
+ "properties": {
10
+ "version": { "const": 1 },
11
+ "config": {
12
+ "type": "string",
13
+ "description": "The config file, ashlar.config.ts, or ashlar.config.mts in a package that isn't a module."
14
+ },
15
+ "wrote": {
16
+ "type": "boolean",
17
+ "description": "Whether it wrote the config and took the baseline: false with --dry-run."
18
+ },
19
+ "include": {
20
+ "type": "array",
21
+ "items": { "type": "string" },
22
+ "description": "The folders Ashlar checks."
23
+ },
24
+ "apps": {
25
+ "type": "array",
26
+ "description": "Each app it found, as the config names it.",
27
+ "items": {
28
+ "type": "object",
29
+ "required": ["root", "stack", "features", "why"],
30
+ "additionalProperties": false,
31
+ "properties": {
32
+ "root": { "type": "string" },
33
+ "stack": { "enum": ["electron", "tauri", "web"] },
34
+ "features": {
35
+ "type": "integer",
36
+ "minimum": 0,
37
+ "description": "How many feature folders it holds."
38
+ },
39
+ "why": { "type": "string", "description": "What Ashlar saw that made it this app, in a sentence." }
40
+ }
41
+ }
42
+ },
43
+ "owner": { "type": ["string", "null"], "description": "The default owner, from CODEOWNERS, or null." },
44
+ "baseline": {
45
+ "type": ["object", "null"],
46
+ "description": "The baseline it took, or null with --dry-run.",
47
+ "required": ["file", "breaks"],
48
+ "additionalProperties": false,
49
+ "properties": {
50
+ "file": {
51
+ "type": ["string", "null"],
52
+ "description": "The baseline file, or null when nothing breaks a rule."
53
+ },
54
+ "breaks": { "type": "integer", "minimum": 0 }
55
+ }
56
+ },
57
+ "source": {
58
+ "type": "string",
59
+ "description": "The config's text, written or, with --dry-run, as it would be written."
60
+ },
61
+ "seconds": { "type": "number" }
62
+ }
63
+ }
@@ -16,6 +16,10 @@ Every step below works two ways, and both answer with the same JSON object:
16
16
  - **The command,** when it doesn't: run it with `--json` through the package manager, `pnpm exec ashlar`,
17
17
  `yarn ashlar` or `npx --no-install ashlar`. Never a bare `npx ashlar`: that package is someone else's.
18
18
 
19
+ In a repository with no `ashlar.config.ts` yet, `init` writes one and takes the baseline: the tool `init`, or
20
+ `ashlar init --json`. With `{ "dryRun": true }` (`--dry-run`) it answers with the config it would write, and
21
+ writes nothing. Show a person the config before you commit it.
22
+
19
23
  ## The loop
20
24
 
21
25
  1. **Brief before you write.** Name the files or folders you will change.