@kurvball/ashlar 0.0.0-stage → 1.3.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.
Files changed (132) hide show
  1. package/CHANGELOG.md +238 -0
  2. package/LICENSE +21 -0
  3. package/README.md +145 -2
  4. package/dist/affected.d.ts +19 -0
  5. package/dist/affected.js +78 -0
  6. package/dist/areas.d.ts +2 -0
  7. package/dist/areas.js +20 -0
  8. package/dist/baseline.d.ts +27 -0
  9. package/dist/baseline.js +109 -0
  10. package/dist/beside.d.ts +1 -0
  11. package/dist/beside.js +4 -0
  12. package/dist/check.d.ts +39 -0
  13. package/dist/check.js +109 -0
  14. package/dist/cli.d.ts +2 -0
  15. package/dist/cli.js +211 -0
  16. package/dist/config.d.ts +84 -0
  17. package/dist/config.js +98 -0
  18. package/dist/configCheck.d.ts +2 -0
  19. package/dist/configCheck.js +204 -0
  20. package/dist/css.d.ts +13 -0
  21. package/dist/css.js +66 -0
  22. package/dist/drive.d.ts +77 -0
  23. package/dist/drive.js +188 -0
  24. package/dist/features.d.ts +32 -0
  25. package/dist/features.js +156 -0
  26. package/dist/git.d.ts +18 -0
  27. package/dist/git.js +140 -0
  28. package/dist/glob.d.ts +5 -0
  29. package/dist/glob.js +49 -0
  30. package/dist/graph.d.ts +16 -0
  31. package/dist/graph.js +83 -0
  32. package/dist/identity.d.ts +1 -0
  33. package/dist/identity.js +1 -0
  34. package/dist/index.d.ts +21 -0
  35. package/dist/index.js +18 -0
  36. package/dist/jsonc.d.ts +1 -0
  37. package/dist/jsonc.js +66 -0
  38. package/dist/knowledge/areas.d.ts +25 -0
  39. package/dist/knowledge/areas.js +86 -0
  40. package/dist/knowledge/decisions.d.ts +14 -0
  41. package/dist/knowledge/decisions.js +53 -0
  42. package/dist/knowledge/guards.d.ts +4 -0
  43. package/dist/knowledge/guards.js +60 -0
  44. package/dist/knowledge/rules.d.ts +12 -0
  45. package/dist/knowledge/rules.js +100 -0
  46. package/dist/knowledge/secrets.d.ts +6 -0
  47. package/dist/knowledge/secrets.js +58 -0
  48. package/dist/layout.d.ts +61 -0
  49. package/dist/layout.js +120 -0
  50. package/dist/ledger.d.ts +28 -0
  51. package/dist/ledger.js +44 -0
  52. package/dist/lint.d.ts +11 -0
  53. package/dist/lint.js +109 -0
  54. package/dist/map.d.ts +25 -0
  55. package/dist/map.js +37 -0
  56. package/dist/move.d.ts +18 -0
  57. package/dist/move.js +94 -0
  58. package/dist/onboard/applies.d.ts +11 -0
  59. package/dist/onboard/applies.js +28 -0
  60. package/dist/onboard/brief.d.ts +40 -0
  61. package/dist/onboard/brief.js +126 -0
  62. package/dist/onboard/guide.d.ts +7 -0
  63. package/dist/onboard/guide.js +150 -0
  64. package/dist/onboard/model.d.ts +15 -0
  65. package/dist/onboard/model.js +57 -0
  66. package/dist/onboard/onboard.d.ts +28 -0
  67. package/dist/onboard/onboard.js +86 -0
  68. package/dist/onboard/questions.d.ts +15 -0
  69. package/dist/onboard/questions.js +90 -0
  70. package/dist/onboard/snapshot.d.ts +28 -0
  71. package/dist/onboard/snapshot.js +58 -0
  72. package/dist/order.d.ts +1 -0
  73. package/dist/order.js +1 -0
  74. package/dist/origins.d.ts +6 -0
  75. package/dist/origins.js +51 -0
  76. package/dist/plugin/boundaries.d.ts +5 -0
  77. package/dist/plugin/boundaries.js +174 -0
  78. package/dist/plugin/exports.d.ts +2 -0
  79. package/dist/plugin/exports.js +41 -0
  80. package/dist/plugin/features.d.ts +4 -0
  81. package/dist/plugin/features.js +34 -0
  82. package/dist/plugin/here.d.ts +13 -0
  83. package/dist/plugin/here.js +69 -0
  84. package/dist/plugin/imports.d.ts +12 -0
  85. package/dist/plugin/imports.js +103 -0
  86. package/dist/plugin/index.d.ts +14 -0
  87. package/dist/plugin/index.js +19 -0
  88. package/dist/plugin/messages.d.ts +20 -0
  89. package/dist/plugin/messages.js +36 -0
  90. package/dist/plugin/names.d.ts +3 -0
  91. package/dist/plugin/names.js +68 -0
  92. package/dist/plugin/references.d.ts +5 -0
  93. package/dist/plugin/references.js +52 -0
  94. package/dist/plugin/text.d.ts +7 -0
  95. package/dist/plugin/text.js +87 -0
  96. package/dist/plugin/types.d.ts +87 -0
  97. package/dist/plugin/types.js +1 -0
  98. package/dist/reach.d.ts +82 -0
  99. package/dist/reach.js +163 -0
  100. package/dist/reachDrive.d.ts +31 -0
  101. package/dist/reachDrive.js +200 -0
  102. package/dist/reachReader.d.ts +1 -0
  103. package/dist/reachReader.js +31 -0
  104. package/dist/rehearse/dependents.d.ts +9 -0
  105. package/dist/rehearse/dependents.js +38 -0
  106. package/dist/rehearse/fill.d.ts +28 -0
  107. package/dist/rehearse/fill.js +44 -0
  108. package/dist/report.d.ts +6 -0
  109. package/dist/report.js +91 -0
  110. package/dist/resolve.d.ts +3 -0
  111. package/dist/resolve.js +114 -0
  112. package/dist/runner.d.ts +6 -0
  113. package/dist/runner.js +29 -0
  114. package/dist/skill.d.ts +23 -0
  115. package/dist/skill.js +235 -0
  116. package/dist/usage.d.ts +1 -0
  117. package/dist/usage.js +53 -0
  118. package/dist/workspace.d.ts +16 -0
  119. package/dist/workspace.js +125 -0
  120. package/ledger.json +201 -0
  121. package/package.json +73 -3
  122. package/schema/affected.v1.json +58 -0
  123. package/schema/brief.v1.json +205 -0
  124. package/schema/check.v1.json +151 -0
  125. package/schema/dependents.v1.json +30 -0
  126. package/schema/drive.v1.json +55 -0
  127. package/schema/ledger.v1.json +61 -0
  128. package/schema/map.v1.json +62 -0
  129. package/schema/move.v1.json +61 -0
  130. package/schema/onboard.v1.json +186 -0
  131. package/schema/rehearse.v1.json +91 -0
  132. package/schema/snapshot.v1.json +101 -0
package/dist/lint.js ADDED
@@ -0,0 +1,109 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { tmpdir } from 'node:os';
5
+ import { dirname, join } from 'node:path';
6
+ import { besideModule } from './beside.js';
7
+ import { AshlarError } from './config.js';
8
+ import { readWorkspace } from './workspace.js';
9
+ const PLUGIN = besideModule('./plugin/index', import.meta.url);
10
+ const CATEGORIES = ['correctness', 'suspicious', 'pedantic', 'perf', 'style', 'restriction', 'nursery'];
11
+ function oxlintBin() {
12
+ return join(dirname(createRequire(import.meta.url).resolve('oxlint/package.json')), 'bin', 'oxlint');
13
+ }
14
+ function unreadable(stdout) {
15
+ let report;
16
+ try {
17
+ report = JSON.parse(stdout);
18
+ }
19
+ catch {
20
+ return;
21
+ }
22
+ const errors = report.diagnostics ?? [];
23
+ if (errors.length === 0)
24
+ return;
25
+ const lines = errors.slice(0, 10).map((error) => {
26
+ const span = error.labels?.[0]?.span;
27
+ return ` ${error.filename}${span ? `:${span.line}:${span.column}` : ''} ${error.message}`;
28
+ });
29
+ if (errors.length > 10)
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')}`);
32
+ }
33
+ export function workspaceOf(config) {
34
+ return readWorkspace(config.root, config.include, new Set(config.ignore));
35
+ }
36
+ export function lint(config, rules, workspace = workspaceOf(config)) {
37
+ const started = performance.now();
38
+ const scratch = mkdtempSync(join(tmpdir(), 'ashlar-'));
39
+ try {
40
+ const record = join(scratch, 'findings.json');
41
+ const settings = {
42
+ root: config.root,
43
+ apps: config.apps,
44
+ maxLines: config.maxLines,
45
+ tests: config.tests,
46
+ confined: config.confined,
47
+ messages: config.messages,
48
+ workspace,
49
+ record,
50
+ };
51
+ const oxlintrc = {
52
+ plugins: [],
53
+ jsPlugins: [PLUGIN],
54
+ categories: Object.fromEntries(CATEGORIES.map((category) => [category, 'off'])),
55
+ settings: { ashlar: settings },
56
+ rules: Object.fromEntries(rules.map((rule) => [`ashlar/${rule}`, 'warn'])),
57
+ };
58
+ const rc = join(scratch, 'oxlintrc.json');
59
+ writeFileSync(rc, JSON.stringify(oxlintrc));
60
+ const folders = config.include.filter((folder) => existsSync(join(config.root, folder)));
61
+ const ignores = config.ignore.map((name) => `--ignore-pattern=**/${name}/**`);
62
+ const run = spawnSync(process.execPath, [
63
+ oxlintBin(),
64
+ '-c',
65
+ rc,
66
+ '--format=json',
67
+ '--quiet',
68
+ '--disable-nested-config',
69
+ '--no-error-on-unmatched-pattern',
70
+ ...ignores,
71
+ ...folders,
72
+ ], { cwd: config.root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
73
+ if (!existsSync(record)) {
74
+ const said = `${run.stderr ?? ''}${run.stdout ?? ''}`.trim();
75
+ throw new AshlarError(`oxlint stopped before it finished${said ? `: ${said}` : '.'}`);
76
+ }
77
+ unreadable(run.stdout);
78
+ const findings = JSON.parse(readFileSync(record, 'utf8'));
79
+ return { files: findings.files, seconds: (performance.now() - started) / 1000 };
80
+ }
81
+ finally {
82
+ rmSync(scratch, { recursive: true, force: true });
83
+ }
84
+ }
85
+ function joined(known, edge) {
86
+ const uses = edge.type ? {} : edge;
87
+ const takes = known?.takes === null || uses.takes === null
88
+ ? null
89
+ : known?.takes === undefined && uses.takes === undefined
90
+ ? undefined
91
+ : [...(known?.takes ?? []), ...(uses.takes ?? [])];
92
+ const passes = [...(known?.passes ?? []), ...(uses.passes ?? [])];
93
+ return {
94
+ to: edge.to,
95
+ type: (known?.type ?? true) && edge.type,
96
+ ...(takes !== undefined && { takes }),
97
+ ...(passes.length > 0 && { passes }),
98
+ };
99
+ }
100
+ export function edgesOf(files) {
101
+ const edges = new Map();
102
+ for (const [file, findings] of Object.entries(files)) {
103
+ const unique = new Map();
104
+ for (const edge of findings.edges)
105
+ unique.set(edge.to, joined(unique.get(edge.to), edge));
106
+ edges.set(file, [...unique.values()]);
107
+ }
108
+ return edges;
109
+ }
package/dist/map.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { type ReachScript, type ReachStep } from './reach.ts';
2
+ export declare const MAP_VERSION = 1;
3
+ export interface MapStep {
4
+ says: string;
5
+ run: string[];
6
+ }
7
+ export interface MapProof {
8
+ file: string;
9
+ }
10
+ export interface MapFeature {
11
+ name: string;
12
+ folder: string;
13
+ reach: MapStep[];
14
+ proofs: MapProof[];
15
+ }
16
+ export interface FeatureMap {
17
+ version: typeof MAP_VERSION;
18
+ features: MapFeature[];
19
+ }
20
+ export declare function mapStep(step: ReachStep): MapStep;
21
+ export declare function nameOfFolder(folder: string): string;
22
+ export declare function mapFeature(folder: string, script: ReachScript | null, proofs: readonly string[]): MapFeature;
23
+ export declare function featureMap(features: readonly MapFeature[]): FeatureMap;
24
+ export declare const UNREAD_REACH = "its reach script doesn\u2019t read: see below";
25
+ export declare function mapText(map: FeatureMap, unreadable?: ReadonlySet<string>): string;
package/dist/map.js ADDED
@@ -0,0 +1,37 @@
1
+ import { driveArgv, stepCommand } from './drive.js';
2
+ import { REACH_SEPARATOR, stepSays } from './reach.js';
3
+ export const MAP_VERSION = 1;
4
+ export function mapStep(step) {
5
+ return { says: stepSays(step), run: driveArgv(stepCommand(step)) };
6
+ }
7
+ export function nameOfFolder(folder) {
8
+ const last = folder.split('/').filter(Boolean).at(-1) ?? folder;
9
+ const spaced = last.replace(/[-_]+/g, ' ').trim();
10
+ return spaced ? spaced[0].toUpperCase() + spaced.slice(1) : folder;
11
+ }
12
+ export function mapFeature(folder, script, proofs) {
13
+ return {
14
+ name: script?.name ?? nameOfFolder(folder),
15
+ folder,
16
+ reach: (script?.steps ?? []).map(mapStep),
17
+ proofs: [...proofs].sort().map((file) => ({ file })),
18
+ };
19
+ }
20
+ export function featureMap(features) {
21
+ return {
22
+ version: MAP_VERSION,
23
+ features: [...features].sort((a, b) => a.folder.localeCompare(b.folder)),
24
+ };
25
+ }
26
+ const plural = (n, one) => `${n} ${one}${n === 1 ? '' : 's'}`;
27
+ export const UNREAD_REACH = 'its reach script doesn’t read: see below';
28
+ export function mapText(map, unreadable = new Set()) {
29
+ if (map.features.length === 0)
30
+ return 'No feature folders in the layout.\n';
31
+ const lines = map.features.map((f) => {
32
+ const missing = unreadable.has(f.folder) ? UNREAD_REACH : 'no reach script yet';
33
+ const reach = f.reach.length ? f.reach.map((s) => s.says).join(REACH_SEPARATOR) : missing;
34
+ return `${f.name} ${f.folder}\n ${reach}\n ${plural(f.proofs.length, 'proof')}`;
35
+ });
36
+ return `${lines.join('\n')}\n`;
37
+ }
package/dist/move.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ import { type Loaded } from './config.ts';
2
+ export interface MoveRise {
3
+ rule: string;
4
+ file: string;
5
+ held: number;
6
+ count: number;
7
+ }
8
+ export interface Moved {
9
+ from: string;
10
+ to: string;
11
+ kind: 'file' | 'folder';
12
+ breaks: number;
13
+ rises: MoveRise[];
14
+ }
15
+ export interface MoveOptions {
16
+ acceptRise?: boolean;
17
+ }
18
+ export declare function move(config: Loaded, pairs: [string, string][], cwd?: string, options?: MoveOptions): Moved[];
package/dist/move.js ADDED
@@ -0,0 +1,94 @@
1
+ import { statSync } from 'node:fs';
2
+ import { join, relative, resolve } from 'node:path';
3
+ import { add, countsOf, readBaseline, writeBaseline } from './baseline.js';
4
+ import { AshlarError } from './config.js';
5
+ import { withReachBreaks } from './features.js';
6
+ import { tidy, within } from './layout.js';
7
+ import { lint } from './lint.js';
8
+ import { lintRulesOf } from './plugin/messages.js';
9
+ function statOf(path) {
10
+ return statSync(path, { throwIfNoEntry: false });
11
+ }
12
+ function takeUnder(counts, path) {
13
+ const taken = {};
14
+ for (const [rule, files] of Object.entries(counts)) {
15
+ for (const file of Object.keys(files)) {
16
+ if (!within(file, path))
17
+ continue;
18
+ add(taken, rule, file, files[file]);
19
+ delete files[file];
20
+ }
21
+ }
22
+ return taken;
23
+ }
24
+ function rebased(counts, from, to) {
25
+ const out = {};
26
+ for (const [rule, files] of Object.entries(counts)) {
27
+ for (const [file, count] of Object.entries(files)) {
28
+ if (within(file, from))
29
+ add(out, rule, `${to}${file.slice(from.length)}`, count);
30
+ }
31
+ }
32
+ return out;
33
+ }
34
+ function moveCounts(counts, plan, actual, accept) {
35
+ const held = rebased(takeUnder(counts, plan.from), plan.from, plan.to);
36
+ for (const [rule, files] of Object.entries(takeUnder(counts, plan.to))) {
37
+ for (const [file, count] of Object.entries(files))
38
+ add(held, rule, file, count);
39
+ }
40
+ const now = plan.side === null ? held : rebased(actual(), plan.side, plan.to);
41
+ let breaks = 0;
42
+ const rises = [];
43
+ for (const rule of [...new Set([...Object.keys(held), ...Object.keys(now)])].sort()) {
44
+ const files = new Set([...Object.keys(held[rule] ?? {}), ...Object.keys(now[rule] ?? {})]);
45
+ for (const file of [...files].sort()) {
46
+ const was = held[rule]?.[file] ?? 0;
47
+ const is = now[rule]?.[file] ?? 0;
48
+ const kept = accept ? is : Math.min(is, was);
49
+ add(counts, rule, file, kept);
50
+ breaks += kept;
51
+ if (is > was)
52
+ rises.push({ rule, file, held: was, count: is });
53
+ }
54
+ }
55
+ return { from: plan.from, to: plan.to, kind: plan.kind, breaks, rises };
56
+ }
57
+ function planOf(config, counts, from, to) {
58
+ const source = statOf(join(config.root, from));
59
+ const target = statOf(join(config.root, to));
60
+ const side = target && !source ? to : source && !target ? from : null;
61
+ const listed = Object.values(counts).some((files) => Object.keys(files).some((file) => file !== from && within(file, from)));
62
+ if (source?.isDirectory() || target?.isDirectory() || (!source && !target && listed)) {
63
+ return { kind: 'folder', from, to, side };
64
+ }
65
+ if (!side) {
66
+ throw new AshlarError(`Ashlar can't tell where ${from}'s counts go: exactly one of ${from} and ${to} must exist.`);
67
+ }
68
+ return { kind: 'file', from, to, side };
69
+ }
70
+ function riseLines(moves) {
71
+ return moves.flatMap((moved) => moved.rises.map((rise) => `${moved.from} → ${moved.to}: ${rise.rule} rose to ${rise.count}, up from ${rise.held}${moved.kind === 'folder' ? `, in ${rise.file}` : ''}`));
72
+ }
73
+ export function move(config, pairs, cwd = process.cwd(), options = {}) {
74
+ const baseline = readBaseline(config.baseline);
75
+ if (!baseline) {
76
+ throw new AshlarError('There is no baseline to move counts in yet: take it first with `ashlar check --shrink`.');
77
+ }
78
+ const accept = options.acceptRise === true;
79
+ const counts = structuredClone(baseline);
80
+ let actual = null;
81
+ const actualCounts = () => (actual ??= countsOf(withReachBreaks(config, lint(config, lintRulesOf(config)).files)));
82
+ const at = (path) => tidy(relative(config.root, resolve(cwd, path)));
83
+ const planned = pairs.map(([from, to]) => planOf(config, counts, at(from), at(to)));
84
+ const moves = planned.map((plan) => moveCounts(counts, plan, actualCounts, accept));
85
+ if (!accept && moves.some((moved) => moved.rises.length > 0)) {
86
+ throw new AshlarError([
87
+ 'Ashlar moved no counts: the move would take in new breaks.',
88
+ ...riseLines(moves).map((line) => ` ${line}`),
89
+ 'Fix the moved code, or give `--accept-rise` to take the rise into the baseline.',
90
+ ].join('\n'));
91
+ }
92
+ writeBaseline(config.baseline, counts);
93
+ return moves;
94
+ }
@@ -0,0 +1,11 @@
1
+ import type { Loaded } from '../config.ts';
2
+ import { type Place } from '../layout.ts';
3
+ type Applies = (place: Place, path: string, config: Loaded) => boolean;
4
+ export declare const APPLIES: Readonly<Record<string, Applies>>;
5
+ export interface AppliedRule {
6
+ id: string;
7
+ applies: string;
8
+ message: string;
9
+ }
10
+ export declare function rulesAt(config: Loaded, paths: readonly string[]): AppliedRule[];
11
+ export {};
@@ -0,0 +1,28 @@
1
+ import { overlaps } from '../knowledge/areas.js';
2
+ import { placeOf } from '../layout.js';
3
+ import { ledgerOf } from '../ledger.js';
4
+ const EVERY = () => true;
5
+ const inFeatures = (place) => place.role === 'features';
6
+ export const APPLIES = {
7
+ 'no-cross-process-import': (place) => (place.process === 'main' || place.process === 'renderer') &&
8
+ (place.app?.processes.main.length ?? 0) > 0 &&
9
+ (place.app?.processes.renderer.length ?? 0) > 0,
10
+ 'shared-is-pure': (place) => place.process === 'shared',
11
+ 'public-api-only': EVERY,
12
+ 'no-effect': inFeatures,
13
+ 'no-timer': inFeatures,
14
+ 'no-dom-query': inFeatures,
15
+ 'client-only': (place) => place.role === 'features' || place.role === 'primitives',
16
+ 'no-comment': EVERY,
17
+ 'no-disable': EVERY,
18
+ 'max-lines': EVERY,
19
+ 'named-only-in': (_place, path, config) => config.confined.some((entry) => entry.within.length === 0 || entry.within.some((folder) => overlaps(folder, path))),
20
+ 'feature-reach': inFeatures,
21
+ };
22
+ export function rulesAt(config, paths) {
23
+ const places = paths.map((path) => placeOf(path, config.apps));
24
+ return ledgerOf(config)
25
+ .filter((entry) => entry.rule && config.rules.includes(entry.id))
26
+ .filter((entry) => paths.some((path, i) => (APPLIES[entry.id] ?? EVERY)(places[i], path, config)))
27
+ .map((entry) => ({ id: entry.id, applies: entry.applies, message: entry.message }));
28
+ }
@@ -0,0 +1,40 @@
1
+ import { type Loaded } from '../config.ts';
2
+ import { type Decision } from '../knowledge/decisions.ts';
3
+ import { type Question } from './questions.ts';
4
+ export declare const BRIEF_VERSION = 1;
5
+ export interface BriefRule {
6
+ id: string;
7
+ message: string;
8
+ }
9
+ export interface BriefFeature {
10
+ name: string;
11
+ folder: string;
12
+ reach: string | null;
13
+ }
14
+ export interface Brief {
15
+ version: typeof BRIEF_VERSION;
16
+ paths: string[];
17
+ areas: {
18
+ path: string;
19
+ name: string;
20
+ owner: string | null;
21
+ }[];
22
+ owners: {
23
+ path: string;
24
+ owner: string | null;
25
+ }[];
26
+ dataRules: string[];
27
+ rules: BriefRule[];
28
+ folderRules: {
29
+ file: string;
30
+ title: string;
31
+ gotcha: string | null;
32
+ guard: string | null;
33
+ text: string;
34
+ }[];
35
+ decisions: Omit<Decision, 'line'>[];
36
+ features: BriefFeature[];
37
+ questions: Question[];
38
+ }
39
+ export declare function brief(config: Loaded, said: readonly string[], cwd?: string): Brief;
40
+ export declare function briefText(b: Brief): string;
@@ -0,0 +1,126 @@
1
+ import { existsSync, statSync } from 'node:fs';
2
+ import { isAbsolute, join, relative, resolve } from 'node:path';
3
+ import { AshlarError } from '../config.js';
4
+ import { matcherOf } from '../glob.js';
5
+ import { decisionCovers, overlaps, ownerOf, staticPart } from '../knowledge/areas.js';
6
+ import { EVERYWHERE } from '../knowledge/decisions.js';
7
+ import { tidy, within } from '../layout.js';
8
+ import { byText } from '../order.js';
9
+ import { reachLine } from '../reach.js';
10
+ import { rulesAt } from './applies.js';
11
+ import { knowledgeOf } from './model.js';
12
+ import { questionsOf } from './questions.js';
13
+ export const BRIEF_VERSION = 1;
14
+ function isFolder(root, path) {
15
+ return statSync(join(root, path), { throwIfNoEntry: false })?.isDirectory() ?? false;
16
+ }
17
+ function ruleTouches(rule, path, folder) {
18
+ if (rule.paths === null)
19
+ return true;
20
+ return rule.paths.some((pattern) => {
21
+ if (matcherOf(pattern)(path))
22
+ return true;
23
+ const fixed = staticPart(pattern);
24
+ return folder && fixed !== '' && overlaps(fixed, path);
25
+ });
26
+ }
27
+ function areasTouched(areas, paths) {
28
+ return areas.filter((area) => paths.some((path) => within(path, area.path) || within(area.path, path)));
29
+ }
30
+ function pathsOf(config, said, cwd) {
31
+ const paths = [...new Set(said.map((path) => tidy(relative(config.root, resolve(cwd, path)))))].sort(byText);
32
+ const outside = paths.filter((path) => path === '..' || path.startsWith('../') || isAbsolute(path));
33
+ if (outside.length > 0) {
34
+ throw new AshlarError(`A brief covers files in this project only: ${outside.join(', ')} lies outside it.`);
35
+ }
36
+ const missing = paths.filter((path) => !existsSync(join(config.root, path)));
37
+ if (missing.length === paths.length) {
38
+ throw new AshlarError(`None of these is in the project: ${missing.join(', ')}.`);
39
+ }
40
+ return paths;
41
+ }
42
+ export function brief(config, said, cwd = process.cwd()) {
43
+ const paths = pathsOf(config, said, cwd);
44
+ const knowledge = knowledgeOf(config);
45
+ const folders = new Set(paths.filter((path) => path === '' || isFolder(config.root, path)));
46
+ const rules = rulesAt(config, paths).map(({ id, message }) => ({ id, message }));
47
+ const folderRules = knowledge.rules
48
+ .filter((rule) => paths.some((path) => ruleTouches(rule, path, folders.has(path))))
49
+ .map((rule) => ({
50
+ file: rule.file,
51
+ title: rule.title,
52
+ gotcha: rule.gotcha,
53
+ guard: rule.guard,
54
+ text: rule.text,
55
+ }));
56
+ const decisions = knowledge.decisions
57
+ .filter((decision) => decision.kind !== 'access' && decision.kind !== 'owner')
58
+ .filter((decision) => decision.areas.includes(EVERYWHERE) || paths.some((path) => decisionCovers(decision, path)))
59
+ .map(({ line: _line, ...decision }) => decision);
60
+ const touched = areasTouched(knowledge.areas, paths);
61
+ const features = knowledge.features
62
+ .filter((feature) => touched.some((area) => area.path === feature.folder))
63
+ .map((feature) => ({
64
+ name: feature.name,
65
+ folder: feature.folder,
66
+ reach: feature.reach?.ok ? reachLine(feature.reach.script.steps) : null,
67
+ }));
68
+ const questions = config.onboard.owner
69
+ ? questionsOf(config, knowledge).filter((q) => touched.some((area) => area.path === q.area) ||
70
+ (q.area !== EVERYWHERE && paths.some((path) => within(q.area, path) || within(path, q.area))))
71
+ : [];
72
+ const owners = new Map();
73
+ for (const path of [...touched.map((area) => area.path), ...paths]) {
74
+ if (!owners.has(path))
75
+ owners.set(path, ownerOf(config, knowledge.decisions, path)?.handle ?? null);
76
+ }
77
+ return {
78
+ version: BRIEF_VERSION,
79
+ paths,
80
+ areas: touched.map((area) => ({
81
+ path: area.path,
82
+ name: area.name,
83
+ owner: owners.get(area.path) ?? null,
84
+ })),
85
+ owners: paths.map((path) => ({ path, owner: owners.get(path) ?? null })),
86
+ dataRules: config.onboard.dataRules,
87
+ rules,
88
+ folderRules,
89
+ decisions,
90
+ features,
91
+ questions,
92
+ };
93
+ }
94
+ export function briefText(b) {
95
+ const lines = [`# Brief for ${b.paths.map((p) => `\`${p}\``).join(', ')}`, ''];
96
+ if (b.areas.length > 0) {
97
+ lines.push('## Areas', '', ...b.areas.map((a) => `- ${a.name} (\`${a.path}\`), owned by ${a.owner ?? 'nobody yet'}`), '');
98
+ }
99
+ const unowned = b.owners.filter((o) => !b.areas.some((a) => within(o.path, a.path)));
100
+ if (unowned.length > 0) {
101
+ lines.push('## Owners', '', ...unowned.map((o) => `- \`${o.path}\`: ${o.owner ?? 'nobody yet'}`), '');
102
+ }
103
+ lines.push('## Data rules', '', ...b.dataRules.map((rule) => `- ${rule}`), '');
104
+ lines.push('## Ashlar’s rules here', '', ...b.rules.map((rule) => `- **${rule.id}**: ${rule.message}`), '');
105
+ if (b.folderRules.length > 0) {
106
+ lines.push('## Folder rules', '');
107
+ for (const rule of b.folderRules) {
108
+ const guarded = rule.guard && rule.guard !== rule.file ? ['', `Guarded by \`${rule.guard}\`.`] : [];
109
+ lines.push(`### ${rule.title}${rule.gotcha ? ` (gotcha: ${rule.gotcha})` : ''}`, '', rule.text, ...guarded, '');
110
+ }
111
+ }
112
+ if (b.decisions.length > 0) {
113
+ lines.push('## Decisions', '');
114
+ for (const d of b.decisions) {
115
+ lines.push(`- ${d.date} ${d.owner} [${d.areas.join(', ')}] ${d.kind === 'decision' ? '' : `${d.kind}: `}${d.text}`);
116
+ }
117
+ lines.push('');
118
+ }
119
+ if (b.features.length > 0) {
120
+ lines.push('## Features', '', ...b.features.map((f) => `- ${f.name}: ${f.reach ?? 'no reach script yet'}`), '');
121
+ }
122
+ if (b.questions.length > 0) {
123
+ lines.push('## Open questions here', '', ...b.questions.map((q) => `- ${q.asks} Ask ${q.owner}.`), '');
124
+ }
125
+ return lines.join('\n');
126
+ }
@@ -0,0 +1,7 @@
1
+ import type { Loaded } from '../config.ts';
2
+ import { type Area } from '../knowledge/areas.ts';
3
+ import type { Knowledge } from './model.ts';
4
+ import type { Question } from './questions.ts';
5
+ export declare const GENERATED = "> Generated by `ashlar onboard` from the code, its decisions and its rules. Don\u2019t edit it: change those, then run `ashlar onboard` again.";
6
+ export declare const areaPage: (area: Pick<Area, 'path'>) => string;
7
+ export declare function guideOf(config: Loaded, knowledge: Knowledge, questions: readonly Question[]): Map<string, string>;
@@ -0,0 +1,150 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { decisionCovers, isCrossCutting, ownerOf, ruleCoversArea } from '../knowledge/areas.js';
4
+ import { EVERYWHERE } from '../knowledge/decisions.js';
5
+ import { reachLine } from '../reach.js';
6
+ import { proofsOf } from '../features.js';
7
+ import { readWorkspace } from '../workspace.js';
8
+ import { byText } from '../order.js';
9
+ import { rulesAt } from './applies.js';
10
+ export const GENERATED = '> Generated by `ashlar onboard` from the code, its decisions and its rules. Don’t edit it: change those, then run `ashlar onboard` again.';
11
+ const SHOWN_SCRIPTS = ['dev', 'start', 'build', 'test', 'typecheck', 'lint', 'check', 'format'];
12
+ export const areaPage = (area) => `areas/${area.path.replaceAll('/', '--')}.md`;
13
+ const cell = (text) => text.replaceAll('|', '\\|').replaceAll('\n', ' ');
14
+ function decisionLine(decision) {
15
+ const kind = decision.kind === 'decision' ? '' : `${decision.kind}: `;
16
+ return `- ${decision.date} ${decision.owner}: ${kind}${decision.text}`;
17
+ }
18
+ function scriptsOf(config) {
19
+ const file = join(config.root, 'package.json');
20
+ if (!existsSync(file))
21
+ return [];
22
+ try {
23
+ const scripts = JSON.parse(readFileSync(file, 'utf8')).scripts ?? {};
24
+ return SHOWN_SCRIPTS.flatMap((name) => typeof scripts[name] === 'string' ? [[name, scripts[name]]] : []);
25
+ }
26
+ catch {
27
+ return [];
28
+ }
29
+ }
30
+ function questionLines(questions) {
31
+ return questions.map((q) => `- [ ] TODO(${q.owner}) ${q.asks} Answered by ${q.answer}. \`${q.id}\``);
32
+ }
33
+ function readme(config, knowledge, questions) {
34
+ const lines = [`# Onboarding: ${knowledge.project}`, '', GENERATED, '', '## What the system is', ''];
35
+ if (config.apps.length > 0) {
36
+ lines.push('| App | Stack | Main | Renderer | Shared |', '| --- | --- | --- | --- | --- |');
37
+ for (const app of config.apps) {
38
+ const list = (paths) => (paths.length ? paths.map((p) => `\`${p}\``).join(', ') : 'none');
39
+ lines.push(`| \`${app.root || '.'}\` | ${app.stack} | ${list(app.processes.main)} | ${list(app.processes.renderer)} | ${list(app.processes.shared)} |`);
40
+ }
41
+ }
42
+ else
43
+ lines.push('No apps are laid out in `ashlar.config.ts`: the areas below are its folders.');
44
+ const packages = readWorkspace(config.root, config.include, new Set(config.ignore)).packages.sort((a, b) => byText(a.dir, b.dir));
45
+ if (packages.length > 0) {
46
+ lines.push('', '### Packages', '', ...packages.map((pkg) => `- \`${pkg.name}\` in \`${pkg.dir}\``));
47
+ }
48
+ const scripts = scriptsOf(config);
49
+ lines.push('', '## How to run and check it', '');
50
+ if (scripts.length > 0)
51
+ lines.push(...scripts.map(([name, command]) => `- \`${name}\`: \`${cell(command)}\``), '');
52
+ lines.push('- `ashlar check`: the rules and the import graph, against the baseline that only shrinks.', '- `ashlar affected <files>`: the tests a change reaches.', '- `ashlar brief <files>`: what an agent needs before it changes those files.', '- `ashlar snapshot`: where things stand today. It is printed, never kept here.');
53
+ const setups = knowledge.decisions.filter((d) => d.kind === 'setup');
54
+ if (setups.length > 0)
55
+ lines.push('', ...setups.map(decisionLine));
56
+ lines.push('', '## Areas', '', '| Area | Kind | Owner | Open questions |', '| --- | --- | --- | --- |');
57
+ for (const area of knowledge.areas) {
58
+ const owner = ownerOf(config, knowledge.decisions, area.path)?.handle ?? '?';
59
+ const open = questions.filter((q) => q.area === area.path).length;
60
+ lines.push(`| [${cell(area.name)}](${areaPage(area)}) \`${area.path}\` | ${area.kind} | ${owner} | ${open} |`);
61
+ }
62
+ lines.push('', '## The rules that apply where', '');
63
+ const places = [
64
+ ...knowledge.areas.map((area) => area.path),
65
+ ...config.apps.flatMap((app) => [
66
+ ...Object.values(app.processes).flat(),
67
+ ...Object.values(app.roles).flat(),
68
+ ]),
69
+ ].map((path) => (path.endsWith('/*') ? path.slice(0, -2) : path));
70
+ const everywhereElse = places.length > 0 ? places : config.include;
71
+ for (const entry of rulesAt(config, everywhereElse)) {
72
+ lines.push(`- **${entry.id}**, in ${entry.applies}: ${entry.message}`);
73
+ }
74
+ const everywhere = knowledge.rules.filter(isCrossCutting);
75
+ if (everywhere.length > 0) {
76
+ lines.push('', 'Rules for every folder:', '', ...everywhere.map((rule) => `- ${rule.title} (\`${rule.file}\`)${rule.paths ? `, for ${rule.paths.map((p) => `\`${p}\``).join(', ')}` : ''}`));
77
+ }
78
+ lines.push('', '## Data rules', '', ...config.onboard.dataRules.map((rule) => `- ${rule}`));
79
+ const global = knowledge.decisions.filter((d) => d.areas.includes(EVERYWHERE) && d.kind !== 'setup' && d.kind !== 'owner');
80
+ if (global.length > 0)
81
+ lines.push('', '## Decisions for the whole project', '', ...global.map(decisionLine));
82
+ const placed = (d) => d.areas.includes(EVERYWHERE) || knowledge.areas.some((area) => decisionCovers(d, area.path));
83
+ const other = knowledge.decisions.filter((d) => !placed(d) && d.kind !== 'owner');
84
+ if (other.length > 0) {
85
+ lines.push('', '## Other decisions', '', ...other.map((d) => `${decisionLine(d)} (\`${d.areas.join(', ')}\`)`));
86
+ }
87
+ lines.push('', '## Open questions', '', questions.length === 0
88
+ ? 'None: every area has an owner, a way in and what to know.'
89
+ : `${questions.length} questions wait on their owners: see [questions.md](questions.md).`, '');
90
+ return lines.join('\n');
91
+ }
92
+ function page(config, knowledge, area, questions) {
93
+ const owner = ownerOf(config, knowledge.decisions, area.path)?.handle ?? '?';
94
+ const lines = [
95
+ `# ${area.name}`,
96
+ '',
97
+ GENERATED,
98
+ '',
99
+ `- Folder: \`${area.path}\``,
100
+ `- Kind: ${area.kind}`,
101
+ `- Owner: ${owner}`,
102
+ ];
103
+ const feature = knowledge.features.find((candidate) => candidate.folder === area.path);
104
+ if (feature) {
105
+ const reach = feature.reach?.ok ? reachLine(feature.reach.script.steps) : 'no reach script yet';
106
+ lines.push(`- Reach: ${reach}`);
107
+ const proofs = proofsOf(config, area.path);
108
+ lines.push('', '## Proofs', '', ...(proofs.length ? proofs.map((p) => `- \`${p}\``) : ['None yet.']));
109
+ }
110
+ const rules = knowledge.rules.filter((rule) => ruleCoversArea(rule, area.path));
111
+ const gotchas = rules.filter((rule) => rule.gotcha);
112
+ const plain = rules.filter((rule) => !rule.gotcha);
113
+ if (plain.length > 0) {
114
+ lines.push('', '## Rules', '');
115
+ for (const rule of plain)
116
+ lines.push(`### ${rule.title}`, '', `From \`${rule.file}\`.`, '', rule.text, '');
117
+ }
118
+ if (gotchas.length > 0) {
119
+ lines.push('', '## Gotchas', '');
120
+ for (const rule of gotchas)
121
+ lines.push(`### ${rule.title} (${rule.gotcha})`, '', `From \`${rule.file}\`.${rule.guard && rule.guard !== rule.file ? ` Guarded by \`${rule.guard}\`.` : ''}`, '', rule.text, '');
122
+ }
123
+ const decisions = knowledge.decisions.filter((d) => !d.areas.includes(EVERYWHERE) && d.kind !== 'owner' && decisionCovers(d, area.path));
124
+ if (decisions.length > 0)
125
+ lines.push('', '## Decisions', '', ...decisions.map(decisionLine));
126
+ const open = questions.filter((q) => q.area === area.path);
127
+ if (open.length > 0)
128
+ lines.push('', '## Open questions', '', ...questionLines(open));
129
+ lines.push('');
130
+ return lines.join('\n').replace(/\n{3,}/g, '\n\n');
131
+ }
132
+ function questionsPage(questions) {
133
+ const lines = ['# Open questions', '', GENERATED, ''];
134
+ if (questions.length === 0)
135
+ lines.push('None.', '');
136
+ const owners = [...new Set(questions.map((q) => q.owner))];
137
+ for (const owner of owners) {
138
+ const theirs = questions.filter((q) => q.owner === owner);
139
+ lines.push(`## ${owner}`, '', ...questionLines(theirs), '');
140
+ }
141
+ return lines.join('\n');
142
+ }
143
+ export function guideOf(config, knowledge, questions) {
144
+ const files = new Map();
145
+ files.set('README.md', readme(config, knowledge, questions));
146
+ files.set('questions.md', questionsPage(questions));
147
+ for (const area of knowledge.areas)
148
+ files.set(areaPage(area), page(config, knowledge, area, questions));
149
+ return files;
150
+ }