@able-autonomy/able 0.0.14 → 0.0.17

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/able.ts CHANGED
@@ -3,14 +3,15 @@
3
3
  // `able gh <args>` runs `gh <args>` as Able's GitHub App, so what it writes comes from `<app-slug>[bot]`.
4
4
  // `able sync` keeps a host's follow-up issues and week records up to date (sync.ts).
5
5
  // `able config --json` prints the host's resolved `able.config.ts` (config.ts).
6
+ // `able init` brings a project to Able on this machine (src/init.ts); a work in progress.
6
7
 
7
8
  import { createSign } from 'node:crypto'
8
9
  import { mkdirSync } from 'node:fs'
9
- import { homedir } from 'node:os'
10
10
  import { join } from 'node:path'
11
+ import { ableDir, repoOf } from './src/machine.ts'
11
12
 
12
13
  // Machine-only config lives in `~/.config/able/<service>/`, the same whether the CLI is linked or installed.
13
- const configDir = join(process.env.ABLE_CONFIG_DIR ?? join(homedir(), '.config', 'able'), 'github')
14
+ const configDir = join(ableDir(), 'github')
14
15
  const api = 'https://api.github.com'
15
16
 
16
17
  function fail(message: string): never {
@@ -56,9 +57,7 @@ function resolveRepo(args: string[]) {
56
57
  }
57
58
  if (process.env.GH_REPO) return process.env.GH_REPO
58
59
  const origin = Bun.spawnSync(['git', 'remote', 'get-url', 'origin']).stdout.toString().trim()
59
- const match = origin.match(/github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/)
60
- if (!match) fail('no GitHub repo: pass --repo <owner>/<repo> or run inside a checkout with a GitHub origin')
61
- return match[1]
60
+ return repoOf(origin) ?? fail('no GitHub repo: pass --repo <owner>/<repo> or run inside a checkout with a GitHub origin')
62
61
  }
63
62
 
64
63
  // Installation tokens last an hour; reuse one until five minutes before it expires.
@@ -124,7 +123,7 @@ if (command === 'upgrade') {
124
123
  console.log(`Upgraded able v${current} → v${latest}`)
125
124
  process.exit(0)
126
125
  }
127
- const modules: Record<string, string> = { commit: './src/commit.ts', push: './src/push.ts', ws: './src/workspaces/index.ts' }
126
+ const modules: Record<string, string> = { agents: './src/agents/index.ts', commit: './src/commit.ts', init: './src/init.ts', push: './src/push.ts', ws: './src/workspaces/index.ts' }
128
127
  if (command && modules[command]) {
129
128
  await import(modules[command])
130
129
  process.exit(0)
@@ -143,7 +142,7 @@ if (delegate) {
143
142
  }
144
143
  if (command !== 'gh') {
145
144
  console.error(
146
- "usage: able gh <gh arguments> run gh as Able's GitHub App\n able sync [--dry-run] file follow-ups and write ended weeks' records\n able config [--json] print the host's able.config.ts\n able commit \"<message>\" [<path>…] a pathspec commit after the touched folders' checks\n able push pushes this branch with its tags\n able upgrade makes bunx run the latest published able\n able ws <new|ls|current|refresh|merge|rm|start|stop|status|take|build|attach> workspaces",
145
+ "usage: able gh <gh arguments> run gh as Able's GitHub App\n able sync [--dry-run] file follow-ups and write ended weeks' records\n able config [--json] print the host's able.config.ts\n able init [--list|--remove] sets this project up on this machine (WIP)\n able commit \"<message>\" [<path>…] a pathspec commit after the touched folders' checks\n able push pushes this branch with its tags\n able upgrade makes bunx run the latest published able\n able ws <new|ls|current|refresh|merge|rm|start|stop|status|take|build|attach> workspaces\n able agents <run|scan|load|blocks|checks|classify|propose|report|show|pick> where each agent-file rule belongs",
147
146
  )
148
147
  process.exit(command ? 1 : 0)
149
148
  }
package/config.ts CHANGED
@@ -93,7 +93,7 @@ export function hostRoot() {
93
93
 
94
94
  export async function loadConfig(root: string): Promise<AbleConfig> {
95
95
  const path = join(root, 'able.config.ts')
96
- if (!existsSync(path)) fail(`no able.config.ts at ${root}. Run Able's onboarding to set this project up.`)
96
+ if (!existsSync(path)) fail(`no able.config.ts at ${root}. Set the project up with \`bunx @able-autonomy/able init\`.`)
97
97
  const config = (await import(path)).default as Partial<AbleConfig> | undefined
98
98
  const unknown = unknownKeys(config, shape)
99
99
  if (unknown.length) fail(`${path}: unknown key(s) ${unknown.join(', ')}`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@able-autonomy/able",
3
- "version": "0.0.14",
3
+ "version": "0.0.17",
4
4
  "description": "Able's command line and the config types a host's able.config.ts uses",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,188 @@
1
+ // Step 3, blocks: cuts each instruction file into blocks, each kept with its heading path, its exact span in the file,
2
+ // and an id that survives unrelated edits (the file plus a short hash of the block's normalised text). One bullet (with
3
+ // its sub-bullets), one paragraph or one table is one block; a code block joins the block before it; a short line
4
+ // ending in a colon is context for the list under it. A block is not yet a rule: step 5 (classify) marks the rules
5
+ // inside each block as spans, and the rest is context. Downloaded skills are listed but not cut: they change upstream.
6
+
7
+ import { readFileSync } from 'node:fs'
8
+ import { join } from 'node:path'
9
+ import { splitFrontmatter } from './load.ts'
10
+ import { clip, countWords, n, type Entry } from './scan.ts'
11
+
12
+ export interface Block {
13
+ id: string
14
+ path: string
15
+ /** The headings above it, outermost first, and any lead-in line. */
16
+ heading: string[]
17
+ /** First and last line, 1-based, inclusive. */
18
+ lines: [number, number]
19
+ /** Character offsets into the file, [from, to), so a view can highlight exactly these words. */
20
+ span: [number, number]
21
+ words: number
22
+ text: string
23
+ }
24
+
25
+ export interface Blocks {
26
+ blocks: Block[]
27
+ /** Agent files listed but not cut, with why. */
28
+ skipped: { path: string; reason: string }[]
29
+ }
30
+
31
+ const cuttable = (e: Entry) => ['instructions', 'rule', 'skill', 'command'].includes(e.kind) && e.origin !== 'downloaded'
32
+
33
+ const normalise = (text: string) =>
34
+ text
35
+ .toLowerCase()
36
+ .replace(/[*_`#>|]/g, '')
37
+ .replace(/\s+/g, ' ')
38
+ .trim()
39
+
40
+ /** A short hash of text, normalised so whitespace and markup don't change it: the stable part of block and rule ids. */
41
+ export const hash = (text: string, length = 6) => new Bun.CryptoHasher('sha1').update(normalise(text)).digest('hex').slice(0, length)
42
+
43
+ /** A block while it is being read: its lines as indexes into the file's lines. */
44
+ type Draft = { heading: string[]; first: number; last: number; bullet?: boolean }
45
+
46
+ /** The blocks of a file's lines from `start`: bullets, paragraphs, tables, with code blocks joined to the block before them. */
47
+ function cut(lines: string[], start: number): Draft[] {
48
+ const out: Draft[] = []
49
+ const heading: string[] = []
50
+ const text = (d: Draft) => lines.slice(d.first, d.last + 1).join('\n')
51
+ let current: Draft | undefined
52
+ // A short line ending in a colon waits to see what follows: before a list it is context for the bullets (kept in
53
+ // their heading path); before anything else (code, a table, a paragraph) it is an ordinary block.
54
+ let lead: string | undefined
55
+ let waiting: Draft | undefined
56
+ const under = () => (lead ? [...heading, lead] : [...heading])
57
+ const flush = () => {
58
+ if (waiting) out.push(waiting)
59
+ waiting = undefined
60
+ lead = undefined
61
+ }
62
+ const close = () => {
63
+ if (!current) return
64
+ const t = text(current).trim()
65
+ if (!current.bullet && current.first === current.last && t.endsWith(':') && countWords(t) <= 20) {
66
+ flush()
67
+ waiting = current
68
+ lead = t.slice(0, -1)
69
+ } else if (t) out.push(current)
70
+ current = undefined
71
+ }
72
+ for (let i = start; i < lines.length; i++) {
73
+ const line = lines[i]
74
+ const h = line.match(/^(#{1,6})\s+(.*)$/)
75
+ if (h) {
76
+ close()
77
+ flush()
78
+ heading.splice(h[1].length - 1, heading.length, h[2].trim())
79
+ continue
80
+ }
81
+ if (/^\s*(```|~~~)/.test(line)) {
82
+ const first = i
83
+ while (++i < lines.length && !/^\s*(```|~~~)/.test(lines[i]));
84
+ const last = Math.min(i, lines.length - 1)
85
+ // The block before it: open, a lead-in waiting for it, or just closed under the same heading.
86
+ const before = current ?? waiting ?? (out.at(-1)?.heading.join('/') === heading.join('/') ? out.pop() : undefined)
87
+ if (waiting) waiting = lead = undefined
88
+ current = before ? { ...before, last } : { heading: [...heading], first, last }
89
+ continue
90
+ }
91
+ // A blank line ends a block; a thematic break (---) is layout.
92
+ if (!line.trim() || /^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) {
93
+ close()
94
+ continue
95
+ }
96
+ // A table is one block: reference data reads as a whole, not row by row.
97
+ if (/^\|/.test(line.trim())) {
98
+ close()
99
+ flush()
100
+ const first = i
101
+ while (i + 1 < lines.length && /^\|/.test(lines[i + 1].trim())) i++
102
+ out.push({ heading: [...heading], first, last: i })
103
+ continue
104
+ }
105
+ const bullet = /^([-*+]|\d+[.)])\s+/.test(line)
106
+ if (bullet) {
107
+ close()
108
+ waiting = undefined
109
+ current = { heading: under(), first: i, last: i, bullet: true }
110
+ continue
111
+ }
112
+ // An indented line continues the bullet it sits under; any other line starts or continues a paragraph.
113
+ if (current) current.last = i
114
+ else {
115
+ flush()
116
+ current = { heading: [...heading], first: i, last: i }
117
+ }
118
+ }
119
+ close()
120
+ flush()
121
+ return out
122
+ }
123
+
124
+ function blocksOf(root: string, path: string): Block[] {
125
+ const file = readFileSync(join(root, path), 'utf8')
126
+ const lines = file.split('\n')
127
+ const offsets = lines.reduce<number[]>((o, l, i) => (o.push(i ? o[i - 1] + lines[i - 1].length + 1 : 0), o), [])
128
+ const { meta, body } = splitFrontmatter(file)
129
+ const bodyStart = lines.length - body.split('\n').length
130
+ const drafts: Draft[] = []
131
+ const description = lines.findIndex((l, i) => i < bodyStart && /^description:/.test(l))
132
+ if (typeof meta.description === 'string' && description >= 0) drafts.push({ heading: ['description'], first: description, last: description })
133
+ drafts.push(...cut(lines, bodyStart))
134
+ const seen = new Map<string, number>()
135
+ return drafts.map((d) => {
136
+ const text = lines.slice(d.first, d.last + 1).join('\n')
137
+ const h = hash(text)
138
+ const count = (seen.get(h) ?? 0) + 1
139
+ seen.set(h, count)
140
+ return {
141
+ id: `${path}#${h}${count > 1 ? `-${count}` : ''}`,
142
+ path,
143
+ heading: d.heading,
144
+ lines: [d.first + 1, d.last + 1],
145
+ span: [offsets[d.first], offsets[d.last] + lines[d.last].length],
146
+ words: countWords(text),
147
+ text,
148
+ }
149
+ })
150
+ }
151
+
152
+ export function blocks(root: string, entries: Entry[]): Blocks {
153
+ return {
154
+ blocks: entries.filter(cuttable).flatMap((e) => blocksOf(root, e.path)),
155
+ skipped: entries.filter((e) => e.origin === 'downloaded').map((e) => ({ path: e.path, reason: 'downloaded: changed upstream' })),
156
+ }
157
+ }
158
+
159
+ /** One line for `able agents run`. */
160
+ export function summary(b: Blocks) {
161
+ const files = new Set(b.blocks.map((x) => x.path)).size
162
+ return `${b.blocks.length} blocks in ${files} file${files === 1 ? '' : 's'}${b.skipped.length ? `, ${b.skipped.length} skipped` : ''}`
163
+ }
164
+
165
+ /** The human view of `able agents blocks`: per file, each block's short id, lines, heading and opening words. */
166
+ export function render(b: Blocks) {
167
+ const out: string[] = []
168
+ for (const [path, list] of Map.groupBy(b.blocks, (x) => x.path)) {
169
+ out.push(` ${path} ${list.length} blocks, ${n(list.reduce((sum, x) => sum + x.words, 0))} words`)
170
+ for (const x of list) {
171
+ const where = clip(x.heading.at(-1) ?? '(top)', 18).padEnd(18)
172
+ const lines = x.lines[0] === x.lines[1] ? `L${x.lines[0]}` : `L${x.lines[0]}-${x.lines[1]}`
173
+ const gist = x.text.trim().startsWith('|')
174
+ ? `table, ${x.text.trim().split('\n').length - 2} rows`
175
+ : x.text
176
+ .replace(/\s+/g, ' ')
177
+ .trim()
178
+ .replace(/^description:\s*/, '')
179
+ .replace(/^[-*+]\s+|^\d+[.)]\s+/, '')
180
+ .replace(/\*\*/g, '')
181
+ out.push(` ${x.id.slice(x.id.lastIndexOf('#'))} ${lines.padEnd(8)} ${where} ${clip(gist, 40).padEnd(40)} ${String(x.words).padStart(4)}w`)
182
+ }
183
+ out.push('')
184
+ }
185
+ if (b.skipped.length) out.push(` not cut: ${b.skipped.length} downloaded skill${b.skipped.length === 1 ? '' : 's'}, changed upstream`, '')
186
+ out.push(` ${summary(b)}`)
187
+ return out.join('\n')
188
+ }
@@ -0,0 +1,256 @@
1
+ // Step 4, checks: what the host already enforces, so classify can tell "already a check" from "only a sentence".
2
+ // The commit and merge checks from the config, linter configs with their rules, permissions and hooks from the
3
+ // settings files, and the host's recipes and scripts by name. Reads only: a JavaScript config is read as text and its
4
+ // local imports followed, never loaded, so the rules found there are an approximation (marked `text`).
5
+
6
+ import { existsSync, readFileSync } from 'node:fs'
7
+ import { dirname, join, normalize } from 'node:path'
8
+ import { loadConfig, type AbleConfig } from '../../config.ts'
9
+ import { clip, n, type Entry } from './scan.ts'
10
+
11
+ export type Level = 'off' | 'warn' | 'error' | 'on'
12
+
13
+ export interface LintRule {
14
+ name: string
15
+ level: Level
16
+ /** The file the rule was found in: the config itself or one it imports or extends. */
17
+ from: string
18
+ }
19
+
20
+ export interface Linter {
21
+ tool: string
22
+ path: string
23
+ /** parsed: JSON or YAML, read exactly. text: JavaScript, read as text without running it. */
24
+ read: 'parsed' | 'text'
25
+ rules: LintRule[]
26
+ /** Files it imports or extends that were read too. */
27
+ via: string[]
28
+ /** Rule sets a JavaScript config switches on by name (`js.configs.recommended`): known on, their rules unlisted. */
29
+ presets?: string[]
30
+ }
31
+
32
+ export interface Checks {
33
+ commit: Record<string, string[]>
34
+ merge: string[]
35
+ linters: Linter[]
36
+ settings: { path: string; allow: string[]; deny: string[]; ask: string[]; hooks: Record<string, string[]> }[]
37
+ recipes: { path: string; names: string[] }[]
38
+ scripts: { path: string; names: string[] }[]
39
+ }
40
+
41
+ const tools: [RegExp, string][] = [
42
+ [/(^|\/)(eslint\.config\.[cm]?[jt]s|\.eslintrc(\.(json|ya?ml|c?js))?)$/, 'eslint'],
43
+ [/(^|\/)(\.prettierrc(\.(json|ya?ml))?|prettier\.config\.[cm]?[jt]s)$/, 'prettier'],
44
+ [/(^|\/)biome\.jsonc?$/, 'biome'],
45
+ [/(^|\/)(\.stylelintrc(\.(json|ya?ml))?|stylelint\.config\.[cm]?[jt]s)$/, 'stylelint'],
46
+ [/(^|\/)(\.htmlvalidate\.json|html-validate\.json)$/, 'html-validate'],
47
+ [/(^|\/)detekt[^/]*\.ya?ml$/, 'detekt'],
48
+ [/(^|\/)\.?swiftlint[^/]*\.ya?ml$/, 'swiftlint'],
49
+ ]
50
+
51
+ const isScript = (path: string) => /\.[cm]?[jt]s$/.test(path)
52
+ const commandText = (c: string | { run: string }) => (typeof c === 'string' ? c : c.run)
53
+
54
+ /** Parses JSON (with comments) or YAML; undefined when it can't. */
55
+ function parse(text: string, path: string): unknown {
56
+ try {
57
+ return /\.ya?ml$/.test(path) ? Bun.YAML.parse(text) : JSON.parse(text.replace(/^\s*\/\/.*$/gm, ''))
58
+ } catch {
59
+ try {
60
+ return Bun.YAML.parse(text)
61
+ } catch {
62
+ return undefined
63
+ }
64
+ }
65
+ }
66
+
67
+ const levelOf = (v: unknown): Level | undefined => {
68
+ const raw = Array.isArray(v) ? v[0] : v
69
+ if (raw === 0 || raw === 'off' || raw === false) return 'off'
70
+ if (raw === 1 || raw === 'warn' || raw === 'warning') return 'warn'
71
+ if (raw === 2 || raw === 'error') return 'error'
72
+ if (raw === true || raw === 'on') return 'on'
73
+ if (raw && typeof raw === 'object' && 'level' in raw) return levelOf((raw as { level: unknown }).level)
74
+ if (raw && typeof raw === 'object' && 'severity' in raw) return levelOf((raw as { severity: unknown }).severity)
75
+ }
76
+
77
+ /** The rules in a parsed config, per tool's own layout. */
78
+ function parsedRules(tool: string, data: unknown, from: string): LintRule[] {
79
+ if (!data || typeof data !== 'object') return []
80
+ const d = data as Record<string, unknown>
81
+ const entries = (o: unknown) => (o && typeof o === 'object' ? Object.entries(o as Record<string, unknown>) : [])
82
+ const rule = (name: string, v: unknown): LintRule[] => {
83
+ const level = levelOf(v)
84
+ return level ? [{ name, level, from }] : []
85
+ }
86
+ if (tool === 'prettier') return entries(d).map(([name, v]) => ({ name: `${name}=${JSON.stringify(v)}`, level: 'on', from }))
87
+ if (tool === 'biome') return entries((d.linter as Record<string, unknown>)?.rules).flatMap(([group, rules]) => entries(rules).flatMap(([n, v]) => rule(`${group}/${n}`, v)))
88
+ if (tool === 'detekt')
89
+ return entries(d).flatMap(([group, rules]) => entries(rules).flatMap(([n, v]) => (v && typeof v === 'object' && 'active' in v ? rule(`${group}/${n}`, (v as { active: unknown }).active) : [])))
90
+ if (tool === 'swiftlint') {
91
+ const list = (key: string, level: Level) => (Array.isArray(d[key]) ? (d[key] as string[]).map((name) => ({ name, level, from })) : [])
92
+ const severities = entries(d).flatMap(([n, v]) => (v && typeof v === 'object' && 'severity' in v ? rule(n, v) : []))
93
+ return [...list('opt_in_rules', 'on'), ...list('only_rules', 'on'), ...list('disabled_rules', 'off'), ...severities]
94
+ }
95
+ return entries(d.rules).flatMap(([n, v]) => rule(n, v))
96
+ }
97
+
98
+ /** What reading a host's configs needs: its files, its workspace packages parsed once, and configs already read. */
99
+ interface Host {
100
+ root: string
101
+ files: Set<string>
102
+ /** Workspace packages by name, so `@scope/pkg/sub` imports resolve to a folder in the host. */
103
+ packages: Map<string, { folder: string; data: { exports?: Record<string, unknown> } }>
104
+ /** Each JavaScript config's reading, by path, so a shared one imported by several configs is read once. */
105
+ read: Map<string, Found>
106
+ }
107
+
108
+ type Found = { rules: LintRule[]; via: string[]; presets: string[] }
109
+
110
+ /** A later setting of the same rule wins, as in a config read top to bottom. */
111
+ const lastWins = (rules: LintRule[]) => [...new Map(rules.map((r) => [r.name, r])).values()]
112
+
113
+ /** The file an import names, inside the host, or undefined for one from outside it (a dependency, build output). */
114
+ function resolveImport(host: Host, from: string, spec: string) {
115
+ // Only the host's own files: dependencies and build output are gitignored, so they are not in `files`.
116
+ const tryFile = (base: string) => [base, `${base}.js`, `${base}.mjs`, `${base}.ts`, `${base}/index.js`, `${base}/index.ts`].find((p) => host.files.has(p) && /\.[cm]?[jt]s(on)?$/.test(p))
117
+ if (spec.startsWith('.')) return tryFile(normalize(join(dirname(from), spec)))
118
+ const name = [...host.packages.keys()].filter((n) => spec === n || spec.startsWith(`${n}/`)).sort((a, b) => b.length - a.length)[0]
119
+ if (!name) return
120
+ const { folder, data } = host.packages.get(name)!
121
+ const sub = spec.slice(name.length).replace(/^\//, '')
122
+ const target = data.exports?.[sub ? `./${sub}` : '.']
123
+ const path = typeof target === 'string' ? target : target && typeof target === 'object' ? ((target as Record<string, string>).import ?? (target as Record<string, string>).default) : undefined
124
+ return path ? tryFile(normalize(join(folder, path)).replace(/\.[cm]?[jt]s$/, '')) : tryFile(join(folder, sub || 'index'))
125
+ }
126
+
127
+ /** Rules named in a JavaScript config and the host files it imports, read as text. What it imports from outside the
128
+ * host (a plugin, a framework's config) is a preset: switched on, its rules unlisted. */
129
+ function textRules(host: Host, path: string, seen = new Set<string>()): Found {
130
+ const cached = host.read.get(path)
131
+ if (cached) return cached
132
+ seen.add(path)
133
+ const text = readFileSync(join(host.root, path), 'utf8').replace(/^\s*\/\/.*$/gm, '')
134
+ const rules: LintRule[] = []
135
+ const via: string[] = []
136
+ const presets: string[] = []
137
+ for (const [, owner, keyed, dotted] of text.matchAll(/([\w$]+)\.configs(?:\[['"]([^'"]+)['"]\]|\.([\w-]+))/g)) presets.push(`${owner}:${keyed ?? dotted}`)
138
+ for (const [, spec] of text.matchAll(/(?:import\s[^'"]*?from\s*|import\s*\(\s*|require\s*\(\s*)['"]([^'"]+)['"]/g)) {
139
+ const target = resolveImport(host, path, spec)
140
+ if (!target) {
141
+ presets.push(spec)
142
+ continue
143
+ }
144
+ if (seen.has(target)) continue
145
+ const inner = textRules(host, target, seen)
146
+ via.push(target, ...inner.via)
147
+ rules.push(...inner.rules)
148
+ presets.push(...inner.presets)
149
+ }
150
+ for (const [, quoted, bare, level] of text.matchAll(/(?:['"]([@\w/-]+)['"]|\b([a-z][\w-]*))\s*:\s*\[?\s*['"](off|warn|error)['"]/g))
151
+ rules.push({ name: quoted ?? bare, level: level as Level, from: path })
152
+ const found = { rules: lastWins(rules), via: [...new Set(via)], presets: [...new Set(presets)] }
153
+ host.read.set(path, found)
154
+ return found
155
+ }
156
+
157
+ /** Parsed configs that extend local ones (html-validate, eslintrc, biome): the extended rules first, its own after. */
158
+ function parsedWithExtends(root: string, tool: string, path: string, seen = new Set<string>()): { rules: LintRule[]; via: string[] } {
159
+ seen.add(path)
160
+ const data = parse(readFileSync(join(root, path), 'utf8'), path) as Record<string, unknown> | undefined
161
+ const rules: LintRule[] = []
162
+ const via: string[] = []
163
+ for (const ext of [data?.extends].flat().filter((e): e is string => typeof e === 'string' && e.startsWith('.'))) {
164
+ const target = normalize(join(dirname(path), ext))
165
+ if (seen.has(target) || !existsSync(join(root, target))) continue
166
+ const inner = parsedWithExtends(root, tool, target, seen)
167
+ via.push(target, ...inner.via)
168
+ rules.push(...inner.rules)
169
+ }
170
+ rules.push(...parsedRules(tool, data, path))
171
+ return { rules: lastWins(rules), via }
172
+ }
173
+
174
+ function justRecipes(text: string) {
175
+ const names: string[] = []
176
+ for (const line of text.split('\n')) {
177
+ const mod = line.match(/^mod\s+([\w-]+)/)
178
+ if (mod) names.push(`${mod[1]}::`)
179
+ const recipe = line.match(/^@?([A-Za-z_][\w-]*)\b[^:=]*:(?!=)/)
180
+ if (recipe && !/^(set|export|alias|import|mod)\b/.test(line)) names.push(recipe[1])
181
+ }
182
+ return names
183
+ }
184
+
185
+ export async function checks(root: string, entries: Entry[], files: string[]): Promise<Checks> {
186
+ const config: AbleConfig = await loadConfig(root)
187
+ const present = files.filter((f) => existsSync(join(root, f)))
188
+ const packageFiles = present
189
+ .filter((f) => /(^|\/)package\.json$/.test(f))
190
+ .map((path) => ({ path, data: (parse(readFileSync(join(root, path), 'utf8'), path) ?? {}) as { name?: string; scripts?: object; exports?: Record<string, unknown> } }))
191
+ const host: Host = {
192
+ root,
193
+ files: new Set(files),
194
+ packages: new Map(packageFiles.flatMap((p) => (p.data.name ? [[p.data.name, { folder: dirname(p.path), data: p.data }] as const] : []))),
195
+ read: new Map(),
196
+ }
197
+ const linters = present.flatMap((path): Linter[] => {
198
+ const tool = tools.find(([re]) => re.test(path))?.[1]
199
+ if (!tool) return []
200
+ if (isScript(path)) return [{ tool, path, read: 'text', ...textRules(host, path) }]
201
+ return [{ tool, path, read: 'parsed', ...parsedWithExtends(root, tool, path) }]
202
+ })
203
+ const settings = entries
204
+ .filter((e) => e.kind === 'settings')
205
+ .map((e) => {
206
+ const d = (parse(readFileSync(join(root, e.path), 'utf8'), e.path) ?? {}) as { permissions?: Record<string, string[]>; hooks?: Record<string, { hooks?: { command?: string }[] }[]> }
207
+ const hooks = Object.fromEntries(Object.entries(d.hooks ?? {}).map(([event, list]) => [event, list.flatMap((m) => (m.hooks ?? []).map((h) => h.command ?? '?'))]))
208
+ return { path: e.path, allow: d.permissions?.allow ?? [], deny: d.permissions?.deny ?? [], ask: d.permissions?.ask ?? [], hooks }
209
+ })
210
+ const recipes = present.filter((f) => /(^|\/)([Jj]ustfile|[^/]+\.just)$/.test(f)).map((path) => ({ path, names: justRecipes(readFileSync(join(root, path), 'utf8')) }))
211
+ const scripts = packageFiles.map((p) => ({ path: p.path, names: Object.keys(p.data.scripts ?? {}) })).filter((s) => s.names.length)
212
+ const commit = Object.fromEntries(Object.entries(config.checks?.commit ?? {}).map(([folder, cs]) => [folder, cs.map(commandText)]))
213
+ return { commit, merge: (config.checks?.merge ?? []).map(commandText), linters, settings, recipes, scripts }
214
+ }
215
+
216
+ /** One line for `able agents run`. */
217
+ export function summary(c: Checks) {
218
+ const rules = c.linters.reduce((s, l) => s + l.rules.length, 0)
219
+ const deny = c.settings.reduce((s, x) => s + x.deny.length, 0)
220
+ const hooks = c.settings.reduce((s, x) => s + Object.values(x.hooks).flat().length, 0)
221
+ return `${c.linters.length} linters, ${n(rules)} rules, ${deny} deny, ${hooks} hook${hooks === 1 ? '' : 's'}`
222
+ }
223
+
224
+ const list = (names: string[], max = 64) => clip(names.join(', '), max)
225
+
226
+ /** The human view of `able agents checks`. */
227
+ export function render(c: Checks) {
228
+ const out: string[] = []
229
+ out.push(' COMMIT CHECKS (able.config.ts, per folder)')
230
+ const folders = Object.entries(c.commit)
231
+ if (!folders.length) out.push(' none')
232
+ for (const [folder, cs] of folders) out.push(` ${folder.padEnd(16)} ${list(cs)}`)
233
+ if (c.merge.length) out.push(` ${'at merge'.padEnd(16)} ${list(c.merge)}`)
234
+
235
+ out.push('', ' LINTERS (rules on / off; text = a JavaScript config read without running it)')
236
+ if (!c.linters.length) out.push(' none')
237
+ for (const l of c.linters) {
238
+ const off = l.rules.filter((r) => r.level === 'off')
239
+ out.push(` ${l.tool.padEnd(13)} ${l.path.padEnd(34)} ${l.read.padEnd(6)} ${String(l.rules.length - off.length).padStart(3)} on ${String(off.length).padStart(3)} off`)
240
+ if (l.via.length) out.push(` ${''.padEnd(13)} via ${list(l.via, 60)}`)
241
+ if (l.presets?.length) out.push(` ${''.padEnd(13)} presets ${list(l.presets, 56)}`)
242
+ }
243
+
244
+ out.push('', ' SETTINGS (permissions and hooks)')
245
+ if (!c.settings.length) out.push(' none')
246
+ for (const s of c.settings) {
247
+ out.push(` ${s.path.padEnd(30)} allow ${s.allow.length} deny ${s.deny.length} ask ${s.ask.length}`)
248
+ for (const [event, cmds] of Object.entries(s.hooks)) out.push(` ${''.padEnd(30)} hook ${event}: ${list(cmds, 40)}`)
249
+ }
250
+
251
+ out.push('', ' RECIPES AND SCRIPTS (by name)')
252
+ for (const r of c.recipes) out.push(` ${r.path.padEnd(24)} ${list(r.names)}`)
253
+ for (const s of c.scripts) out.push(` ${s.path.padEnd(24)} ${list(s.names)}`)
254
+ out.push('', ` ${summary(c)}`)
255
+ return out.join('\n')
256
+ }
@@ -0,0 +1,124 @@
1
+ // What the agent writes at step 5 (classify): for each block, the rules in it as exact quotes, each with one kind.
2
+ // The text of a block that no rule quotes is context (why, examples, intros). The CLI, not the agent, works out each
3
+ // rule's span and id, so the agent never counts characters. `report` (step 7) reuses this check.
4
+
5
+ import { existsSync, readFileSync } from 'node:fs'
6
+ import { hash, type Block } from './blocks.ts'
7
+ import { isKind, kinds, related, type Kind } from './kinds.ts'
8
+
9
+ export const format = 'able.agents.findings@1'
10
+
11
+ /** Where the skill keeps its findings between steps: Able's per-checkout state, gitignored. */
12
+ export const findingsPath = '.able/agents/findings.json'
13
+
14
+ export interface RuleFinding {
15
+ /** The rule's words, quoted exactly from the block (whitespace may differ). */
16
+ text: string
17
+ kind: Kind
18
+ confidence: 'high' | 'low'
19
+ /** One line: why this kind. */
20
+ reason: string
21
+ /** For a duplicate or a conflict: the ids of the blocks holding the other rule. */
22
+ with?: string[]
23
+ /** Step 6, for every rule not kept: the file the change goes in and the change itself, concrete enough to apply. */
24
+ proposal?: Proposal
25
+ /** Step 6: the agent's recommendation for the operator's pick. The picker starts from it. */
26
+ recommend?: 'yes' | 'no'
27
+ }
28
+
29
+ export interface Proposal {
30
+ /** The file the change goes in: a linter config, a settings file, a new rules file, the rule's own file. */
31
+ target: string
32
+ /** The change: the lint rule entry, the deny entry, the pointer line, the paths rule, "delete", or the question. */
33
+ change: string
34
+ }
35
+
36
+ export interface Findings {
37
+ format: typeof format
38
+ findings: { block: string; rules: RuleFinding[] }[]
39
+ }
40
+
41
+ export interface Rule extends RuleFinding {
42
+ /** The block's id plus a short hash of the rule's words: survives edits elsewhere in the block. */
43
+ id: string
44
+ block: string
45
+ path: string
46
+ /** Character offsets into the file, [from, to). */
47
+ span: [number, number]
48
+ }
49
+
50
+ export interface Checked {
51
+ rules: Rule[]
52
+ /** Blocks the findings don't mention: not yet classified. */
53
+ missing: string[]
54
+ errors: string[]
55
+ }
56
+
57
+ /** Where a quote sits in a block's text, matching any run of whitespace loosely. */
58
+ function locate(quote: string, text: string): [number, number] | undefined {
59
+ const exact = text.indexOf(quote)
60
+ if (exact >= 0) return [exact, exact + quote.length]
61
+ const words = quote
62
+ .trim()
63
+ .split(/\s+/)
64
+ .map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
65
+ const m = new RegExp(words.join('\\s+')).exec(text)
66
+ return m ? [m.index, m.index + m[0].length] : undefined
67
+ }
68
+
69
+ /** Checks the agent's findings against the blocks: every block known, every quote found in its block, every kind known. */
70
+ export function check(findings: Findings, blocks: Block[]): Checked {
71
+ const byId = new Map(blocks.map((b) => [b.id, b]))
72
+ const errors: string[] = []
73
+ const rules: Rule[] = []
74
+ const counts = new Map<string, number>()
75
+ if (findings.format !== format) errors.push(`format is ${JSON.stringify(findings.format)}, expected ${format}`)
76
+ for (const { block: id, rules: found = [] } of findings.findings ?? []) {
77
+ const block = byId.get(id)
78
+ if (!block) {
79
+ errors.push(`${id}: no such block (cut again with able agents blocks)`)
80
+ continue
81
+ }
82
+ for (const r of found) {
83
+ const at = locate(r.text ?? '', block.text)
84
+ if (!at) errors.push(`${id}: quote not found in the block: "${(r.text ?? '').slice(0, 50)}"`)
85
+ else if (!isKind(r.kind)) errors.push(`${id}: unknown kind ${JSON.stringify(r.kind)} (one of ${Object.keys(kinds).join(', ')})`)
86
+ else if (r.confidence !== 'high' && r.confidence !== 'low') errors.push(`${id}: confidence must be high or low`)
87
+ else if (related.includes(r.kind) && !r.with?.length) errors.push(`${id}: a ${r.kind} names the other rule's block in "with"`)
88
+ else if (r.with?.some((w) => !byId.has(w))) errors.push(`${id}: "with" names an unknown block`)
89
+ else if (r.proposal && (typeof r.proposal.target !== 'string' || typeof r.proposal.change !== 'string')) errors.push(`${id}: a proposal has a target and a change`)
90
+ else if (r.recommend !== undefined && r.recommend !== 'yes' && r.recommend !== 'no') errors.push(`${id}: recommend is yes or no`)
91
+ else {
92
+ const base = `${id}.${hash(r.text, 4)}`
93
+ const seen = (counts.get(base) ?? 0) + 1
94
+ counts.set(base, seen)
95
+ rules.push({ ...r, id: seen > 1 ? `${base}-${seen}` : base, block: id, path: block.path, span: [block.span[0] + at[0], block.span[0] + at[1]] })
96
+ }
97
+ }
98
+ }
99
+ const mentioned = new Set((findings.findings ?? []).map((f) => f.block))
100
+ return { rules, missing: blocks.filter((b) => !mentioned.has(b.id)).map((b) => b.id), errors }
101
+ }
102
+
103
+ /** The findings file, or undefined when there is none. */
104
+ export function readFindings(path: string): Findings | undefined {
105
+ return existsSync(path) ? (JSON.parse(readFileSync(path, 'utf8')) as Findings) : undefined
106
+ }
107
+
108
+ /** Rules step 6 still owes a proposal: every rule not kept. */
109
+ export const unproposed = (c: Checked) => c.rules.filter((r) => r.kind !== 'keep' && !r.proposal)
110
+
111
+ /** One line for `able agents run` at step 6. */
112
+ export const proposeSummary = (c: Checked) => {
113
+ const owed = c.rules.filter((r) => r.kind !== 'keep').length
114
+ return `${owed - unproposed(c).length} of ${owed} proposed`
115
+ }
116
+
117
+ /** One line for `able agents run`. */
118
+ export function summary(c: Checked) {
119
+ const byKind = Object.keys(kinds)
120
+ .map((k) => [k, c.rules.filter((r) => r.kind === k).length] as const)
121
+ .filter(([, count]) => count)
122
+ .map(([k, count]) => `${kinds[k as Kind].letter}${count}`)
123
+ return `${c.rules.length} rules ${byKind.join(' ')}${c.missing.length ? `, ${c.missing.length} blocks left` : ''}${c.errors.length ? `, ${c.errors.length} errors` : ''}`
124
+ }