@kurvball/ashlar 1.5.0 → 1.7.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,22 @@ 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.7.0
10
+
11
+ _Released 2026-12-04._
12
+
13
+ ### Minor Changes
14
+
15
+ - With `--json`, a command that can't do what it was asked prints the error object on stdout, `{ v: 1, ok: false, error: { code, says, file?, line? } }`, in `schema/error.v1.json`: the same shape as Rehearse's and Marquee's refusals. Its exit code is unchanged, 2. An MCP tool's refusal carries the same object. Without `--json`, the sentence still goes to stderr.
16
+
17
+ ## 1.6.0
18
+
19
+ _Released 2026-12-04._
20
+
21
+ ### Minor Changes
22
+
23
+ - `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.
24
+
9
25
  ## 1.5.0
10
26
 
11
27
  _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/baseline.js CHANGED
@@ -31,10 +31,10 @@ export function readBaseline(file) {
31
31
  counts = JSON.parse(readFileSync(file, 'utf8'));
32
32
  }
33
33
  catch (error) {
34
- throw new AshlarError(BASELINE_WORDS.unreadable(file, error.message));
34
+ throw new AshlarError(BASELINE_WORDS.unreadable(file, error.message), 'baseline', { file });
35
35
  }
36
36
  if (isPerFolder(counts))
37
- throw new AshlarError(BASELINE_WORDS.perFolder(file));
37
+ throw new AshlarError(BASELINE_WORDS.perFolder(file), 'baseline', { file });
38
38
  return counts;
39
39
  }
40
40
  export function tidyCounts(counts) {
package/dist/cli.js CHANGED
@@ -3,6 +3,8 @@ 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';
7
+ import { errorJson } from './errors.js';
6
8
  import { serve } from './mcp.js';
7
9
  import { featuresOf, unreadText } from './features.js';
8
10
  import { ledgerOf, ledgerText } from './ledger.js';
@@ -31,6 +33,7 @@ const FLAGS = {
31
33
  dependents: ['json'],
32
34
  rehearse: ['json'],
33
35
  mcp: [],
36
+ init: ['dry-run', 'json'],
34
37
  };
35
38
  const VALUED = new Map([
36
39
  ['since', 'a ref'],
@@ -91,6 +94,15 @@ async function main(args) {
91
94
  throw new AshlarError(`\`ashlar ${command}\` takes no ${unknown.map((f) => `--${f}`).join(', ')}: it takes ${named}.`);
92
95
  }
93
96
  }
97
+ if (command === 'init') {
98
+ if (positional.length > 0)
99
+ throw new AshlarError('`ashlar init` takes no paths: run it at the root of the repository.');
100
+ const { report, warnings } = init(process.cwd(), { dryRun: flags.has('dry-run') });
101
+ print(json, report, initText(report));
102
+ for (const warning of warnings)
103
+ process.stderr.write(`Warning: ${warning}\n`);
104
+ return 0;
105
+ }
94
106
  if (command === 'mcp') {
95
107
  if (positional.length > 0)
96
108
  throw new AshlarError('`ashlar mcp` takes no files.');
@@ -205,8 +217,19 @@ try {
205
217
  process.exitCode = await main(process.argv.slice(2));
206
218
  }
207
219
  catch (error) {
208
- if (!(error instanceof AshlarError))
209
- throw error;
210
- process.stderr.write(`${error.message}\n`);
211
- process.exitCode = 2;
220
+ const json = process.argv.slice(2).includes('--json');
221
+ if (!(error instanceof AshlarError)) {
222
+ if (!json)
223
+ throw error;
224
+ process.stderr.write(`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
225
+ process.stdout.write(`${JSON.stringify(errorJson(error), null, 2)}\n`);
226
+ process.exitCode = 1;
227
+ }
228
+ else {
229
+ if (json)
230
+ process.stdout.write(`${JSON.stringify(errorJson(error), null, 2)}\n`);
231
+ else
232
+ process.stderr.write(`${error.message}\n`);
233
+ process.exitCode = 2;
234
+ }
212
235
  }
package/dist/config.d.ts CHANGED
@@ -76,7 +76,16 @@ export declare const CONFIG_FILE = "ashlar.config.ts";
76
76
  export declare const CONFIG_FILES: string[];
77
77
  export declare const DEFAULT_IGNORE: string[];
78
78
  export declare const DEFAULT_TESTS: string[];
79
+ export declare const ERROR_CODES: readonly ['usage', 'config', 'baseline', 'git', 'lint', 'rules', 'decisions', 'secret', 'drive', 'refused'];
80
+ export type ErrorCode = (typeof ERROR_CODES)[number];
79
81
  export declare class AshlarError extends Error {
82
+ readonly code: ErrorCode;
83
+ readonly file: string | undefined;
84
+ readonly line: number | undefined;
85
+ constructor(says: string, code?: ErrorCode, at?: {
86
+ file?: string;
87
+ line?: number;
88
+ });
80
89
  }
81
90
  export declare function defineConfig(config: AshlarConfig): AshlarConfig;
82
91
  export declare function findConfig(from: string): string | null;
package/dist/config.js CHANGED
@@ -21,7 +21,28 @@ export const CONFIG_FILE = 'ashlar.config.ts';
21
21
  export const CONFIG_FILES = [CONFIG_FILE, 'ashlar.config.mts', 'ashlar.config.js', 'ashlar.config.mjs'];
22
22
  export const DEFAULT_IGNORE = ['node_modules', 'out', 'dist', 'release'];
23
23
  export const DEFAULT_TESTS = ['.test.ts', '.test.tsx'];
24
+ export const ERROR_CODES = [
25
+ 'usage',
26
+ 'config',
27
+ 'baseline',
28
+ 'git',
29
+ 'lint',
30
+ 'rules',
31
+ 'decisions',
32
+ 'secret',
33
+ 'drive',
34
+ 'refused',
35
+ ];
24
36
  export class AshlarError extends Error {
37
+ code;
38
+ file;
39
+ line;
40
+ constructor(says, code = 'usage', at = {}) {
41
+ super(says);
42
+ this.code = code;
43
+ this.file = at.file;
44
+ this.line = at.line;
45
+ }
25
46
  }
26
47
  export function defineConfig(config) {
27
48
  return config;
@@ -41,7 +62,7 @@ export function findConfig(from) {
41
62
  export function settle(config, root, file = CONFIG_FILE) {
42
63
  const problems = checkConfig(config);
43
64
  if (problems.length > 0) {
44
- throw new AshlarError(`${file} doesn't read:\n${problems.map((line) => ` ${line}`).join('\n')}`);
65
+ throw new AshlarError(`${file} doesn't read:\n${problems.map((line) => ` ${line}`).join('\n')}`, 'config', { file });
45
66
  }
46
67
  return {
47
68
  root,
@@ -78,7 +99,7 @@ function onboardOf(onboard) {
78
99
  function confinedOf(entry) {
79
100
  const words = (entry.words ?? []).map((word) => word.trim()).filter(Boolean);
80
101
  if (words.length === 0 || !entry.message?.trim()) {
81
- throw new AshlarError(`Each of ${CONFIG_FILE}'s confined names needs its words and the message agents read.`);
102
+ throw new AshlarError(`Each of ${CONFIG_FILE}'s confined names needs its words and the message agents read.`, 'config');
82
103
  }
83
104
  return {
84
105
  words,
@@ -90,10 +111,10 @@ function confinedOf(entry) {
90
111
  export async function loadConfig(from = process.cwd()) {
91
112
  const file = findConfig(from);
92
113
  if (!file)
93
- throw new AshlarError(`There is no ${CONFIG_FILE} in ${resolve(from)} or above it.`);
114
+ throw new AshlarError(`There is no ${CONFIG_FILE} in ${resolve(from)} or above it.`, 'config');
94
115
  const fresh = `${pathToFileURL(file).href}?v=${statSync(file).mtimeMs}`;
95
116
  const loaded = (await import(__rewriteRelativeImportExtension(fresh)));
96
117
  if (!loaded.default)
97
- throw new AshlarError(`${file} has no default export: export its config.`);
118
+ throw new AshlarError(`${file} has no default export: export its config.`, 'config', { file });
98
119
  return settle(loaded.default, realpathSync(dirname(file)), basename(file));
99
120
  }
@@ -0,0 +1,12 @@
1
+ import { type ErrorCode } from './config.ts';
2
+ export interface ErrorJson {
3
+ v: 1;
4
+ ok: false;
5
+ error: {
6
+ code: ErrorCode | 'crashed';
7
+ says: string;
8
+ file?: string;
9
+ line?: number;
10
+ };
11
+ }
12
+ export declare function errorJson(error: unknown, cwd?: string): ErrorJson;
package/dist/errors.js ADDED
@@ -0,0 +1,19 @@
1
+ import { isAbsolute, relative } from 'node:path';
2
+ import { AshlarError } from './config.js';
3
+ export function errorJson(error, cwd = process.cwd()) {
4
+ if (!(error instanceof AshlarError)) {
5
+ const said = error instanceof Error ? error.message.split('\n')[0] || error.name : String(error);
6
+ return { v: 1, ok: false, error: { code: 'crashed', says: `Ashlar stopped: ${said}` } };
7
+ }
8
+ const file = error.file === undefined ? undefined : isAbsolute(error.file) ? relative(cwd, error.file) : error.file;
9
+ return {
10
+ v: 1,
11
+ ok: false,
12
+ error: {
13
+ code: error.code,
14
+ says: error.message,
15
+ ...(file !== undefined && { file }),
16
+ ...(error.line !== undefined && { line: error.line }),
17
+ },
18
+ };
19
+ }
package/dist/git.js CHANGED
@@ -101,7 +101,7 @@ export function hasHead(root) {
101
101
  }
102
102
  export function knownRef(root, ref) {
103
103
  if (git(root, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]) === null) {
104
- throw new AshlarError(`git knows no ${ref} here.`);
104
+ throw new AshlarError(`git knows no ${ref} here.`, 'git');
105
105
  }
106
106
  }
107
107
  function said(output) {
@@ -116,7 +116,7 @@ export function atRef(config, ref, read) {
116
116
  maxBuffer: 64 * 1024 * 1024,
117
117
  });
118
118
  if (listing.status !== 0) {
119
- throw new AshlarError(`git couldn't list the files at ${ref}: ${said(listing.stderr)}`);
119
+ throw new AshlarError(`git couldn't list the files at ${ref}: ${said(listing.stderr)}`, 'git');
120
120
  }
121
121
  const listed = lines(listing.stdout);
122
122
  if (listed.length === 0)
@@ -126,13 +126,13 @@ export function atRef(config, ref, read) {
126
126
  maxBuffer: 1024 * 1024 * 1024,
127
127
  });
128
128
  if (archive.status !== 0) {
129
- throw new AshlarError(`git couldn't read the files at ${ref}: ${said(archive.stderr)}`);
129
+ throw new AshlarError(`git couldn't read the files at ${ref}: ${said(archive.stderr)}`, 'git');
130
130
  }
131
131
  const root = realpathSync(mkdtempSync(join(tmpdir(), 'ashlar-at-')));
132
132
  try {
133
133
  const unpacked = spawnSync('tar', ['-x', '-f', '-', '-C', root], { input: archive.stdout });
134
134
  if (unpacked.status !== 0) {
135
- throw new AshlarError(`Ashlar couldn't unpack the files at ${ref}: ${said(unpacked.stderr)}`);
135
+ throw new AshlarError(`Ashlar couldn't unpack the files at ${ref}: ${said(unpacked.stderr)}`, 'git');
136
136
  }
137
137
  const holds = (path) => existsSync(join(root, path));
138
138
  return read({ config: { ...config, root }, holds });
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.`, 'refused');
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.`, 'refused');
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
+ }
@@ -44,7 +44,7 @@ export function parseDecisions(text, file) {
44
44
  });
45
45
  });
46
46
  if (problems.length > 0)
47
- throw new AshlarError(problems.join('\n'));
47
+ throw new AshlarError(problems.join('\n'), 'decisions');
48
48
  return decisions;
49
49
  }
50
50
  export function readDecisions(root, file) {
@@ -44,7 +44,7 @@ function frontOf(text, file) {
44
44
  return { values: new Map(), paths: null, body: text };
45
45
  const end = lines.findIndex((line, i) => i > 0 && line.trim() === FENCE);
46
46
  if (end === -1)
47
- throw new AshlarError(`${file}: its frontmatter opens with --- and never closes.`);
47
+ throw new AshlarError(`${file}: its frontmatter opens with --- and never closes.`, 'rules', { file });
48
48
  const values = new Map();
49
49
  let paths = null;
50
50
  let inPaths = false;
@@ -59,7 +59,7 @@ function frontOf(text, file) {
59
59
  }
60
60
  const pair = /^([A-Za-z]+):\s*(.*)$/.exec(line);
61
61
  if (!pair || !KEYS.has(pair[1])) {
62
- throw new AshlarError(`${file}:${i + 1}: Ashlar reads only these frontmatter keys: ${[...KEYS].join(', ')}.`);
62
+ throw new AshlarError(`${file}:${i + 1}: Ashlar reads only these frontmatter keys: ${[...KEYS].join(', ')}.`, 'rules', { file, line: i + 1 });
63
63
  }
64
64
  inPaths = pair[1] === 'paths';
65
65
  if (inPaths)
package/dist/lint.js CHANGED
@@ -28,7 +28,7 @@ function unreadable(stdout) {
28
28
  });
29
29
  if (errors.length > 10)
30
30
  lines.push(` and ${errors.length - 10} more`);
31
- throw new AshlarError(`oxlint couldn't read these files, so Ashlar can't count them:\n${lines.join('\n')}`);
31
+ throw new AshlarError(`oxlint couldn't read these files, so Ashlar can't count them:\n${lines.join('\n')}`, 'lint');
32
32
  }
33
33
  export function workspaceOf(config) {
34
34
  return readWorkspace(config.root, config.include, new Set(config.ignore));
@@ -72,7 +72,7 @@ export function lint(config, rules, workspace = workspaceOf(config)) {
72
72
  ], { cwd: config.root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
73
73
  if (!existsSync(record)) {
74
74
  const said = `${run.stderr ?? ''}${run.stdout ?? ''}`.trim();
75
- throw new AshlarError(`oxlint stopped before it finished${said ? `: ${said}` : '.'}`);
75
+ throw new AshlarError(`oxlint stopped before it finished${said ? `: ${said}` : '.'}`, 'lint');
76
76
  }
77
77
  unreadable(run.stdout);
78
78
  const findings = JSON.parse(readFileSync(record, 'utf8'));
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,26 @@ 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 { errorJson } from './errors.js';
6
+ import { init } from './init.js';
5
7
  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.';
8
+ 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
9
  const paths = (args, name) => args[name] ?? [];
8
10
  const flag = (args, name) => args[name] === true;
9
11
  const text = (args, name) => args[name];
10
12
  export const TOOLS = [
13
+ {
14
+ name: 'init',
15
+ 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.',
16
+ args: {
17
+ dryRun: { kind: 'boolean', description: 'Answer with the config it would write, and write nothing.' },
18
+ },
19
+ readOnly: false,
20
+ start: (args, cwd) => {
21
+ const { report, warnings } = init(cwd, { dryRun: flag(args, 'dryRun') });
22
+ return { json: report, warnings };
23
+ },
24
+ },
11
25
  {
12
26
  name: 'brief',
13
27
  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.',
@@ -130,15 +144,19 @@ function argumentsOf(tool, given) {
130
144
  }
131
145
  return args;
132
146
  }
133
- const said = (message) => ({ content: [{ type: 'text', text: message }], isError: true });
147
+ const refused = (error) => ({
148
+ content: [{ type: 'text', text: JSON.stringify(errorJson(error)) }],
149
+ isError: true,
150
+ });
134
151
  export async function callTool(name, given, cwd = process.cwd(), log = process.stderr) {
135
152
  const tool = TOOLS.find((entry) => entry.name === name);
136
153
  if (!tool)
137
154
  return null;
138
155
  try {
139
156
  const args = argumentsOf(tool, given);
140
- const config = await loadConfig(cwd);
141
- const { json, warnings = [] } = tool.run(config, args);
157
+ const { json, warnings = [] } = tool.start
158
+ ? tool.start(args, cwd)
159
+ : tool.run(await loadConfig(cwd), args);
142
160
  for (const warning of warnings)
143
161
  log.write(`Warning: ${warning}\n`);
144
162
  return {
@@ -148,10 +166,10 @@ export async function callTool(name, given, cwd = process.cwd(), log = process.s
148
166
  };
149
167
  }
150
168
  catch (error) {
151
- if (error instanceof AshlarError)
152
- return said(error.message);
153
- log.write(`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
154
- return said(`Ashlar failed: ${error instanceof Error ? error.message : String(error)}`);
169
+ if (!(error instanceof AshlarError)) {
170
+ log.write(`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
171
+ }
172
+ return refused(error);
155
173
  }
156
174
  }
157
175
  const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
package/dist/move.js CHANGED
@@ -63,7 +63,7 @@ function planOf(config, counts, from, to) {
63
63
  return { kind: 'folder', from, to, side };
64
64
  }
65
65
  if (!side) {
66
- throw new AshlarError(`Ashlar can't tell where ${from}'s counts go: exactly one of ${from} and ${to} must exist.`);
66
+ throw new AshlarError(`Ashlar can't tell where ${from}'s counts go: exactly one of ${from} and ${to} must exist.`, 'refused');
67
67
  }
68
68
  return { kind: 'file', from, to, side };
69
69
  }
@@ -73,7 +73,7 @@ function riseLines(moves) {
73
73
  export function move(config, pairs, cwd = process.cwd(), options = {}) {
74
74
  const baseline = readBaseline(config.baseline);
75
75
  if (!baseline) {
76
- throw new AshlarError('There is no baseline to move counts in yet: take it first with `ashlar check --shrink`.');
76
+ throw new AshlarError('There is no baseline to move counts in yet: take it first with `ashlar check --shrink`.', 'refused');
77
77
  }
78
78
  const accept = options.acceptRise === true;
79
79
  const counts = structuredClone(baseline);
@@ -87,7 +87,7 @@ export function move(config, pairs, cwd = process.cwd(), options = {}) {
87
87
  'Ashlar moved no counts: the move would take in new breaks.',
88
88
  ...riseLines(moves).map((line) => ` ${line}`),
89
89
  'Fix the moved code, or give `--accept-rise` to take the rise into the baseline.',
90
- ].join('\n'));
90
+ ].join('\n'), 'refused');
91
91
  }
92
92
  writeBaseline(config.baseline, counts);
93
93
  return moves;
@@ -25,7 +25,7 @@ export function refuseSecrets(config) {
25
25
  'Secrets never enter knowledge files, and these lines look like one:',
26
26
  ...found,
27
27
  'Take the value out. Say who grants access instead, as an `access` line, never the credential.',
28
- ].join('\n'));
28
+ ].join('\n'), 'secret');
29
29
  }
30
30
  }
31
31
  const UNNAMED = 'this project';
@@ -30,7 +30,7 @@ export function documentsOf(config) {
30
30
  export function defaultOwner(config) {
31
31
  if (config.onboard.owner)
32
32
  return config.onboard.owner;
33
- throw new AshlarError('Name the project’s default owner, who gets every question nobody else owns: `onboard: { owner: "@handle" }` in ashlar.config.ts.');
33
+ throw new AshlarError('Name the project’s default owner, who gets every question nobody else owns: `onboard: { owner: "@handle" }` in ashlar.config.ts.', 'config');
34
34
  }
35
35
  export function questionsOf(config, knowledge) {
36
36
  const fallback = defaultOwner(config);
@@ -14,7 +14,7 @@ export function driveOf(config) {
14
14
  const drive = driveCommandOf(config);
15
15
  if (drive)
16
16
  return drive;
17
- throw new AshlarError(`Nothing drives this project's app: add Rehearse (a rehearse.yaml), and Ashlar walks each reach through \`rehearse drive\`, or name a drive command in ${CONFIG_FILE}, such as \`drive: 'pnpm drive'\`.`);
17
+ throw new AshlarError(`Nothing drives this project's app: add Rehearse (a rehearse.yaml), and Ashlar walks each reach through \`rehearse drive\`, or name a drive command in ${CONFIG_FILE}, such as \`drive: 'pnpm drive'\`.`, 'drive');
18
18
  }
19
19
  const record = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : null;
20
20
  function printedResult(stdout) {
@@ -129,9 +129,9 @@ function startThroughRehearse(config, options) {
129
129
  if (!start.error && !start.signal && printedResult(start.stdout ?? '')?.ok === true)
130
130
  return;
131
131
  driveCommand(config, { command: 'stop' }, options);
132
- throw new AshlarError(`\`rehearse drive start\` couldn't start this project's app: ${saidBy(start, 'start')}`);
132
+ throw new AshlarError(`\`rehearse drive start\` couldn't start this project's app: ${saidBy(start, 'start')}`, 'drive');
133
133
  }
134
- const rehearseCantDrive = (said) => new AshlarError(`This project has a rehearse.yaml, so Ashlar walks each reach through \`rehearse drive\`, and it didn't answer: ${said} Rehearse drives from its 0.3.0; until then, name a drive command in ${CONFIG_FILE}, such as \`drive: 'pnpm drive'\`.`);
134
+ const rehearseCantDrive = (said) => new AshlarError(`This project has a rehearse.yaml, so Ashlar walks each reach through \`rehearse drive\`, and it didn't answer: ${said} Rehearse drives from its 0.3.0; until then, name a drive command in ${CONFIG_FILE}, such as \`drive: 'pnpm drive'\`.`, 'drive');
135
135
  export function driveFeature(config, feature, options) {
136
136
  const head = { feature: feature.name, folder: feature.folder, stoppedAt: null, step: null, ms: 0 };
137
137
  if (!feature.reach)
package/dist/skill.js CHANGED
@@ -134,7 +134,7 @@ function attachOf(config) {
134
134
  return null;
135
135
  const path = join(config.root, file);
136
136
  if (!existsSync(path)) {
137
- throw new AshlarError(`skills.verify.attach names ${file}, and there is no such file.`);
137
+ throw new AshlarError(`skills.verify.attach names ${file}, and there is no such file.`, 'config');
138
138
  }
139
139
  return readFileSync(path, 'utf8');
140
140
  }
@@ -216,14 +216,14 @@ export function writeSkill(config, name, options = {}) {
216
216
  const text = skillText(name, config);
217
217
  const root = realpathSync(config.root);
218
218
  if (!inside(root, realpathSync(nearest(dirname(file)))) || linkedOut(root, file)) {
219
- throw new AshlarError(`${shown} leads out of the project: Ashlar writes skills only into it.`);
219
+ throw new AshlarError(`${shown} leads out of the project: Ashlar writes skills only into it.`, 'refused');
220
220
  }
221
221
  mkdirSync(dirname(file), { recursive: true });
222
222
  const was = existsSync(file) ? readFileSync(file, 'utf8') : null;
223
223
  if (was === text)
224
224
  return 'same';
225
225
  if (was !== null && !options.force) {
226
- throw new AshlarError(`${shown} differs from Ashlar's ${name} skill: give \`--force\` to replace it with Ashlar's.`);
226
+ throw new AshlarError(`${shown} differs from Ashlar's ${name} skill: give \`--force\` to replace it with Ashlar's.`, 'refused');
227
227
  }
228
228
  writeFileSync(file, text);
229
229
  return was === null ? 'written' : 'replaced';
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.7.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,45 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://github.com/kurvball/ashlar/blob/main/schema/error.v1.json",
4
+ "title": "A refusal, from any command with --json",
5
+ "description": "What any command prints with --json when it can't do what it was asked, in the shape Rehearse's and Marquee's refusals share. It exits with 2, or with 1 when Ashlar crashed.",
6
+ "type": "object",
7
+ "required": ["v", "ok", "error"],
8
+ "additionalProperties": false,
9
+ "properties": {
10
+ "v": { "const": 1, "description": "The contract version." },
11
+ "ok": { "const": false },
12
+ "error": {
13
+ "type": "object",
14
+ "required": ["code", "says"],
15
+ "additionalProperties": false,
16
+ "properties": {
17
+ "code": {
18
+ "enum": [
19
+ "usage",
20
+ "config",
21
+ "baseline",
22
+ "git",
23
+ "lint",
24
+ "rules",
25
+ "decisions",
26
+ "secret",
27
+ "drive",
28
+ "refused",
29
+ "crashed"
30
+ ],
31
+ "description": "A stable word for the kind of refusal: usage (the command line), config (ashlar.config.ts), baseline (ashlar.baseline.json), git, lint (oxlint), rules (a file in .claude/rules/), decisions (DECISIONS.md), secret (a knowledge file holds what looks like one), drive (the drive command), refused (what was asked would lose or overwrite something), or crashed."
32
+ },
33
+ "says": {
34
+ "type": "string",
35
+ "description": "What went wrong and what to do, in plain words: the sentence the command prints on stderr without --json."
36
+ },
37
+ "file": {
38
+ "type": "string",
39
+ "description": "The file at fault, from the folder Ashlar runs in, when there is one."
40
+ },
41
+ "line": { "type": "integer", "minimum": 1, "description": "Its line, when Ashlar knows it." }
42
+ }
43
+ }
44
+ }
45
+ }
@@ -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.
@@ -61,5 +65,6 @@ Every step below works two ways, and both answer with the same JSON object:
61
65
  `ashlar.config.ts`, by a person.
62
66
  - When `onboard` with `{ "check": true }` answers `ok: false`, the guide is stale: run `onboard` and commit
63
67
  what it wrote.
64
- - A refusal comes back with `isError: true` and a sentence saying what was wrong, such as a ref git doesn't
65
- know. Fix the call; don't retry it unchanged.
68
+ - A refusal comes back with `isError: true` and the error object, `{ "v": 1, "ok": false, "error": { "code",
69
+ "says" } }`, also what a command prints with `--json` when it can't run. `says` tells you what was wrong, such
70
+ as a ref git doesn't know. Fix the call; don't retry it unchanged.