@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.
@@ -0,0 +1,168 @@
1
+ // The cell views, the terminal form of the visual a browser page will show later: every file a box, every block a cell.
2
+ // Cells are sized by words for now; `show` marks them by kind once classify has run.
3
+
4
+ import { dirname } from 'node:path'
5
+ import { folderOf } from '../checks.ts'
6
+ import { dim, paint256, tty } from '../ui.ts'
7
+ import type { Blocks } from './blocks.ts'
8
+ import type { Checks } from './checks.ts'
9
+ import type { Checked } from './findings.ts'
10
+ import { kinds, type Kind } from './kinds.ts'
11
+ import { clip, n, type Entry } from './scan.ts'
12
+
13
+ const box = 11
14
+ const perRow = 5
15
+
16
+ /** A file's two lines in its box: a short name, and what it is. */
17
+ function label(e: Entry): [string, string] {
18
+ const parts = e.path.split('/')
19
+ const name = parts.at(-1) ?? ''
20
+ if (e.kind === 'instructions') return [parts.length === 1 ? 'root' : parts.at(-2)!, name]
21
+ if (e.kind === 'skill') return [parts.at(-2)!, `skill ${{ house: 'house', downloaded: 'down', source: 'src' }[e.origin!]}`]
22
+ if (e.kind === 'command') return [`/${name.replace('.md', '')}`, 'command']
23
+ if (e.kind === 'settings') return [name.includes('local') ? 'local' : 'shared', 'settings']
24
+ return [name.replace(/\.md$/, ''), e.kind]
25
+ }
26
+
27
+ /** Boxes grouped by kind, like the rows of a periodic table. */
28
+ const order = ['instructions', 'rule', 'skill', 'command', 'settings', 'hook', 'mcp', 'memory', 'cursor']
29
+
30
+ const centre = (s: string) => {
31
+ const t = clip(s, box, '~')
32
+ const left = Math.floor((box - t.length) / 2)
33
+ return `${' '.repeat(left)}${t}${' '.repeat(box - t.length - left)}`
34
+ }
35
+
36
+ /** `able agents scan --grid`: the files as a periodic table, one box each. */
37
+ export function files(entries: Entry[]) {
38
+ const out: string[] = []
39
+ const sorted = [...entries].sort((a, b) => order.indexOf(a.kind) - order.indexOf(b.kind))
40
+ for (let i = 0; i < sorted.length; i += perRow) {
41
+ const row = sorted.slice(i, i + perRow)
42
+ const line = (cell: (e: Entry) => string) => ` ${row.map((e) => `|${cell(e)}|`).join(' ')}`
43
+ const edge = ` ${row.map(() => `+${'-'.repeat(box)}+`).join(' ')}`
44
+ out.push(
45
+ edge,
46
+ line((e) => centre(label(e)[0])),
47
+ line((e) => centre(label(e)[1])),
48
+ line((e) => centre(`${n(e.words)} w`)),
49
+ edge,
50
+ )
51
+ }
52
+ return out.join('\n')
53
+ }
54
+
55
+ // A contribution grid per file, as GitHub draws commits: equal squares with gaps, empty ones faint, four shades by words.
56
+ // Green squares on a terminal; without colour (a pipe, a chat) the shades are characters, so it still reads.
57
+ const levels = [20, 40, 80]
58
+ const level = (words: number) => levels.filter((l) => words >= l).length + 1
59
+ const greens = [237, 22, 28, 34, 40]
60
+ const plain = ['·', '░', '▒', '▓', '█']
61
+ const square = (level: number) => (tty ? paint256(greens[level])('■') : plain[level])
62
+
63
+ /** `able agents blocks --grid`: per file, a card with a row per section and one square per block. */
64
+ export function blocks(b: Blocks) {
65
+ const out: string[] = []
66
+ for (const [path, list] of Map.groupBy(b.blocks, (x) => x.path)) {
67
+ const sections = [...Map.groupBy(list, (x) => x.heading[1] ?? x.heading[0] ?? '(top)')]
68
+ const label = Math.min(22, Math.max(...sections.map(([h]) => h.length)))
69
+ const columns = Math.max(...sections.map(([, cells]) => cells.length))
70
+ const words = list.reduce((n, x) => n + x.words, 0)
71
+ const rows = sections.map(([heading, cells]) => {
72
+ const name = clip(heading, label, '~').padEnd(label)
73
+ const squares = Array.from({ length: columns }, (_, i) => square(cells[i] ? level(cells[i].words) : 0))
74
+ return `${name} ${squares.join(' ')}`
75
+ })
76
+ const inner = label + 2 + columns * 2 - 1
77
+ const legend = `Less ${[0, 1, 2, 3, 4].map(square).join(' ')} More`
78
+ const width = Math.max(inner, 5 + 9 + 5)
79
+ const pad = (line: string, visible: number) => `${line}${' '.repeat(width - visible)}`
80
+ out.push(` ${list.length} blocks, ${n(words)} words in ${path}`)
81
+ out.push(` ┌${'─'.repeat(width + 2)}┐`)
82
+ for (const r of rows) out.push(` │ ${pad(r, inner)} │`)
83
+ out.push(` │ ${' '.repeat(width)} │`)
84
+ out.push(` │ ${' '.repeat(width - 19)}${legend} │`)
85
+ out.push(` └${'─'.repeat(width + 2)}┘`, '')
86
+ }
87
+ out.push(` One square per block, shaded by words: under ${levels[0]}, ${levels[0]}-${levels[1] - 1}, ${levels[1]}-${levels[2] - 1}, ${levels[2]} or more.`)
88
+ return out.join('\n')
89
+ }
90
+
91
+ /** A count as a shade: none, then 1, 2-9, 10-49, 50 or more. */
92
+ const shade = (count: number, present = count > 0) => (!present ? 0 : count < 2 ? 1 : count < 10 ? 2 : count < 50 ? 3 : 4)
93
+ const sum = (ns: number[]) => ns.reduce((a, b) => a + b, 0)
94
+
95
+ /** `able agents checks --grid`: per folder, which tools enforce anything there, shaded by how much. */
96
+ export function enforcement(c: Checks, entries: Entry[]) {
97
+ const folders = [...new Set(['.', ...Object.keys(c.commit), ...entries.filter((e) => e.kind === 'instructions').map((e) => dirname(e.path))])].sort()
98
+ // A config belongs to the nearest folder row at or above it (outs/android/outstanding/detekt.yml is outs/android's)
99
+ // and covers that folder and the ones under it, never the ones above.
100
+ const owner = (dir: string) => folderOf(dir, folders) ?? '.'
101
+ const covers = (dir: string, folder: string) => {
102
+ const o = owner(dir)
103
+ return o === '.' || folder === o || folder.startsWith(`${o}/`)
104
+ }
105
+ const settingsAt = (folder: string) => c.settings.filter((s) => covers(dirname(dirname(s.path)), folder))
106
+ const tools = [...new Set(c.linters.map((l) => l.tool))]
107
+ const columns: { name: string; at: (folder: string) => number }[] = [
108
+ ...tools.map((tool) => ({
109
+ name: tool === 'html-validate' ? 'html' : tool,
110
+ at: (folder: string) => {
111
+ const configs = c.linters.filter((l) => l.tool === tool && covers(dirname(l.path), folder))
112
+ return shade(Math.max(0, ...configs.map((l) => l.rules.filter((r) => r.level !== 'off').length)), configs.length > 0)
113
+ },
114
+ })),
115
+ { name: 'checks', at: (folder) => shade((c.commit[folder] ?? []).length + (folder === '.' ? c.merge.length : 0)) },
116
+ { name: 'deny', at: (folder) => shade(sum(settingsAt(folder).map((s) => s.deny.length))) },
117
+ { name: 'hooks', at: (folder) => shade(sum(settingsAt(folder).map((s) => Object.values(s.hooks).flat().length))) },
118
+ ]
119
+ const label = Math.min(24, Math.max(...folders.map((f) => (f === '.' ? 6 : f.length))))
120
+ const head = columns.map((col) => col.name).join(' ')
121
+ const inner = label + 2 + head.length
122
+ // The legend is 19 characters on screen; with colour its string is longer.
123
+ const width = Math.max(inner, 19)
124
+ const legend = `None ${[0, 1, 2, 3, 4].map(square).join(' ')} More`
125
+ const cell = (name: string, value: number) => `${' '.repeat(Math.floor((name.length - 1) / 2))}${square(value)}${' '.repeat(Math.ceil((name.length - 1) / 2))}`
126
+ const out = [' What already enforces rules, per folder', ` ┌${'─'.repeat(width + 2)}┐`, ` │ ${''.padEnd(label)} ${head}${' '.repeat(width - inner)} │`]
127
+ for (const f of folders) {
128
+ const name = f === '.' ? '(root)' : clip(f, label, '~')
129
+ out.push(` │ ${name.padEnd(label)} ${columns.map((col) => cell(col.name, col.at(f))).join(' ')}${' '.repeat(width - inner)} │`)
130
+ }
131
+ out.push(` │ ${' '.repeat(width)} │`, ` │ ${' '.repeat(width - 19)}${legend} │`, ` └${'─'.repeat(width + 2)}┘`, '')
132
+ out.push(' Linters: rules on (a preset alone is the lightest shade). checks: commands in able.config.ts. deny, hooks: from settings.')
133
+ return out.join('\n')
134
+ }
135
+
136
+ // By kind: what stays green, what moves into a tool blue, what goes grey, scoped yellow, a conflict red.
137
+ const kindColour: Record<Kind, number> = { keep: 34, scoped: 178, lint: 39, check: 39, enforced: 39, guard: 39, discoverable: 244, expiring: 244, duplicate: 244, conflict: 196 }
138
+ const mark = (kind?: Kind) => (kind ? paint256(kindColour[kind])(kinds[kind].letter) : '·')
139
+
140
+ /** `able agents classify`: per file, a row per section and one mark per rule, by kind; `·` a block that is all context. */
141
+ export function byKind(b: Blocks, c: Checked) {
142
+ const out: string[] = []
143
+ const rulesOf = Map.groupBy(c.rules, (r) => r.block)
144
+ const missing = new Set(c.missing)
145
+ for (const [path, list] of Map.groupBy(b.blocks, (x) => x.path)) {
146
+ const sections = [...Map.groupBy(list, (x) => x.heading[1] ?? x.heading[0] ?? '(top)')]
147
+ const label = Math.min(22, Math.max(...sections.map(([h]) => h.length)))
148
+ const cells = sections.map(
149
+ ([h, blocks]) =>
150
+ [
151
+ h,
152
+ blocks.flatMap((x) => {
153
+ const rs = rulesOf.get(x.id)
154
+ return missing.has(x.id) ? [dim('?')] : rs?.length ? rs.map((r) => mark(r.kind)) : [mark()]
155
+ }),
156
+ ] as const,
157
+ )
158
+ const columns = Math.max(...cells.map(([, cs]) => cs.length))
159
+ const inner = label + 2 + columns * 2 - 1
160
+ const rules = c.rules.filter((r) => r.path === path)
161
+ out.push(` ${rules.length} rules in ${list.length} blocks, ${path}`, ` ┌${'─'.repeat(inner + 2)}┐`)
162
+ for (const [h, cs] of cells) out.push(` │ ${clip(h, label, '~').padEnd(label)} ${cs.join(' ')}${' '.repeat((columns - cs.length) * 2)} │`)
163
+ out.push(` └${'─'.repeat(inner + 2)}┘`, '')
164
+ }
165
+ const legend = (Object.keys(kinds) as Kind[]).map((k) => `${mark(k)} ${k}`)
166
+ out.push(` ${legend.slice(0, 5).join(' ')}`, ` ${legend.slice(5).join(' ')}`, ` ${mark()} context only ${dim('?')} not classified yet`)
167
+ return out.join('\n')
168
+ }
@@ -0,0 +1,185 @@
1
+ // able agents: what a host's agent files load, the rules in them, and where each rule belongs (knowledge/product/modules/agents.md).
2
+ //
3
+ // able agents run every step in order, one line each
4
+ // able agents scan [--json|--grid] step 1: every agent file, its kind and size (--grid: one box per file)
5
+ // able agents load [--json] step 2: when each file loads, and the words at start per folder
6
+ // able agents blocks [--json|--grid] step 3: the files cut into blocks, with spans and stable ids (--grid: one square per block)
7
+ // able agents checks [--json|--grid] step 4: what the host already enforces (--grid: per folder, per tool)
8
+ // able agents classify [--json] step 5's result: the agent's findings checked against the blocks, drawn by kind
9
+ // able agents propose [--json] step 6's result: each rule not kept with its proposal, or what is still owed
10
+ // able agents report step 7: checks the findings and writes the run to <journal>/agents/<date>-<hhmm>.json
11
+ // able agents show [<run>] [--step <n>] step 8: a run read back from its file (the latest by default)
12
+ // able agents pick [<yes|no> <n>…] step 9: the operator's picks in the latest run (no arguments on a terminal: checkboxes)
13
+ //
14
+ // Read-only on the host's agent files: the only files written are the findings (by the skill) and the run file.
15
+
16
+ import { join, relative } from 'node:path'
17
+ import { hostRoot, loadConfig } from '../../config.ts'
18
+ import { confirm, dim, fail, green, tty } from '../ui.ts'
19
+ import * as blocks from './blocks.ts'
20
+ import * as checks from './checks.ts'
21
+ import * as findings from './findings.ts'
22
+ import * as grid from './grid.ts'
23
+ import * as load from './load.ts'
24
+ import { pickInteractive } from './picker.ts'
25
+ import * as report from './report.ts'
26
+ import * as scan from './scan.ts'
27
+ import * as show from './show.ts'
28
+ import { steps, who } from './steps.ts'
29
+
30
+ const [sub = '', ...args] = process.argv.slice(3)
31
+ const names = args.filter((a, i) => !a.startsWith('--') && args[i - 1] !== '--step')
32
+ const stepArg = args.includes('--step') ? args[args.indexOf('--step') + 1] : undefined
33
+ const json = args.includes('--json')
34
+ const asGrid = args.includes('--grid')
35
+ const root = hostRoot()
36
+
37
+ /** Each step's result, worked out once and shared by the steps after it. */
38
+ const once = <T>(f: () => T) => {
39
+ let value: { v: T } | undefined
40
+ return () => (value ??= { v: f() }).v
41
+ }
42
+ const files = once(() => scan.listFiles(root))
43
+ const entries = once(() => scan.scan(root, files()))
44
+
45
+ const scope = dim([` root ${root}`, ' scanned the root downwards, gitignored files skipped', ' outside folders above the root and ~/.claude/: counted in the load map (step 2)'].join('\n'))
46
+
47
+ /** A built step: its result, the line `run` prints, and its views. */
48
+ interface Built<T> {
49
+ result: () => T | Promise<T>
50
+ summary: (r: T) => string
51
+ render: (r: T) => string
52
+ grid?: (r: T) => string
53
+ }
54
+ const built = <T>(b: Built<T>) => b as Built<unknown>
55
+
56
+ const cut = once(() => blocks.blocks(root, entries()))
57
+ const classified = once(() => {
58
+ const f = findings.readFindings(join(root, findings.findingsPath))
59
+ return f && findings.check(f, cut().blocks)
60
+ })
61
+
62
+ const journal = once(async () => (await loadConfig(root)).journal)
63
+ /** The latest run, or the one named on the command line for `show`. */
64
+ const latest = once(async () => {
65
+ const path = report.findRun(root, await journal(), sub === 'show' ? names[0] : undefined)
66
+ return path ? { path, run: report.readRun(path) } : undefined
67
+ })
68
+ type Latest = Awaited<ReturnType<typeof latest>>
69
+ const requireLatest = async () => (await latest()) ?? fail('no run yet: able agents report writes one')
70
+ /** Steps 7 to 9 all show the latest run; only their line in `run` differs. */
71
+ const latestView = (summary: (l: NonNullable<Latest>) => string, none: string) =>
72
+ built<Latest>({ result: latest, summary: (l) => (l ? summary(l) : none), render: (l) => (l ? show.render(l.run, l.path, root) : ' No run yet.') })
73
+
74
+ const views: Record<string, Built<unknown>> = {
75
+ scan: built({ result: entries, summary: scan.summary, render: (e) => `${scope}\n\n${scan.render(e)}`, grid: (e) => `${scope}\n\n${grid.files(e)}` }),
76
+ load: built({ result: once(() => load.load(root, entries())), summary: load.summary, render: load.render }),
77
+ blocks: built({ result: cut, summary: blocks.summary, render: blocks.render, grid: grid.blocks }),
78
+ checks: built({ result: once(() => checks.checks(root, entries(), files())), summary: checks.summary, render: checks.render, grid: (c) => grid.enforcement(c, entries()) }),
79
+ classify: built({
80
+ result: classified,
81
+ summary: (c) => (c ? findings.summary(c) : `not run: the skill writes ${findings.findingsPath}`),
82
+ render: (c) =>
83
+ c
84
+ ? [grid.byKind(cut(), c), ...(c.errors.length ? ['', ' ERRORS', ...c.errors.map((e) => ` ${e}`)] : [])].join('\n')
85
+ : ` No findings yet: the skill (able-clean-agent-bloat) writes ${findings.findingsPath} at step 5.`,
86
+ }),
87
+ propose: built({
88
+ result: classified,
89
+ summary: (c) => (c ? findings.proposeSummary(c) : 'waits for classify'),
90
+ render: (c) =>
91
+ c
92
+ ? c.rules
93
+ .filter((r) => r.kind !== 'keep')
94
+ .map(
95
+ (r) => ` ${r.kind.padEnd(12)} ${r.id}
96
+ ${r.proposal ? `→ ${r.proposal.target}: ${r.proposal.change}` : dim('no proposal yet')}`,
97
+ )
98
+ .join('\n')
99
+ : ' No findings yet.',
100
+ }),
101
+ report: latestView((l) => `latest: ${relative(root, l.path)}`, 'not run yet'),
102
+ show: latestView(() => 'able agents show', 'no run yet'),
103
+ pick: latestView((l) => report.tally(l.run).line, 'no run yet'),
104
+ }
105
+
106
+ /** Step 7: refuses while the findings owe anything, then writes the run and shows it. */
107
+ async function writeReport() {
108
+ const c = classified()
109
+ if (!c) fail(`no findings: the skill writes ${findings.findingsPath} at steps 5 and 6`)
110
+ const owed = report.problems(c)
111
+ if (owed.length) fail(`the findings are not ready:\n${owed.map((p) => ` ${p}`).join('\n')}`)
112
+ const summaries: Record<string, string> = {}
113
+ for (const id of ['scan', 'load', 'blocks', 'checks', 'classify', 'propose']) summaries[id] = views[id].summary(await views[id].result())
114
+ const at = new Date()
115
+ const path = report.runPath(root, await journal(), at)
116
+ const run = report.build({
117
+ scan: entries(),
118
+ load: (await views.load.result()) as load.LoadMap,
119
+ blocks: cut(),
120
+ checks: (await views.checks.result()) as checks.Checks,
121
+ checked: c,
122
+ summaries,
123
+ root,
124
+ path,
125
+ at,
126
+ })
127
+ await report.saveRun(path, run)
128
+ console.log(`\n ${green('wrote')} ${relative(root, path)}\n\n${show.render(run, path, root)}\n`)
129
+ }
130
+
131
+ /** Step 9: on a terminal with no arguments, the checkbox picker; otherwise `pick yes 1 3 5`, `pick no 2`. */
132
+ async function writePicks() {
133
+ const l = await requireLatest()
134
+ const [answer, ...numbers] = names
135
+ let answers: Map<number, 'yes' | 'no'> | undefined
136
+ if (!answer && tty && process.stdin.isTTY) {
137
+ answers = await pickInteractive(l.run, l.path, root)
138
+ if (!answers) return console.log('\n Nothing recorded.\n')
139
+ } else if (answer === 'yes' || answer === 'no') answers = new Map(numbers.map((x) => [Number(x), answer]))
140
+ else fail('usage: able agents pick [<yes|no> <n>…] (no arguments on a terminal opens the checkboxes)')
141
+ const unknown = await report.pick(l.path, l.run, answers)
142
+ if (unknown.length) fail(`no finding numbered ${unknown.join(', ')} in ${relative(root, l.path)}`)
143
+ const { yes, no, open } = report.tally(l.run)
144
+ console.log(`\n ${green('recorded')} ${yes} yes, ${no} no, ${open} not picked, in ${relative(root, l.path)}\n`)
145
+ }
146
+
147
+ async function run() {
148
+ console.log()
149
+ for (const step of steps.filter((s) => s.v1)) {
150
+ const label = ` ${String(step.n).padStart(2)} ${who[step.kind]} ${step.id.padEnd(10)}`
151
+ const view = views[step.id]
152
+ if (!view) {
153
+ console.log(`${label} ${dim('not built yet')}`)
154
+ continue
155
+ }
156
+ const started = performance.now()
157
+ const result = await view.result()
158
+ const summary = view.summary(result)
159
+ const done = result !== undefined ? `${green('ok')} ${dim(`${Math.round(performance.now() - started)}ms`)}` : ''
160
+ console.log(`${label} ${result !== undefined ? summary.padEnd(44) : dim(summary)} ${done}`.trimEnd())
161
+ }
162
+ console.log(dim('\n M mechanical (the CLI) · A agent · O operator (you)\n'))
163
+ // On a terminal, step 9 follows on: the latest run's unpicked findings, as checkboxes.
164
+ const l = await latest()
165
+ if (l && tty && process.stdin.isTTY && report.tally(l.run).open && confirm('Pick now?')) await writePicks()
166
+ }
167
+
168
+ if (sub === 'run') await run()
169
+ else if (sub === 'report') await writeReport()
170
+ else if (sub === 'pick') await writePicks()
171
+ else if (sub === 'show' && stepArg) {
172
+ const l = await requireLatest()
173
+ const id = l.run.steps.find((s) => String(s.n) === stepArg || s.id === stepArg)?.id
174
+ if (!id) fail(`no step ${stepArg}: 1 to ${l.run.steps.length}, or a name`)
175
+ console.log(`\n${show.step(l.run, id)}\n`)
176
+ } else if (views[sub]) {
177
+ const view = views[sub]
178
+ const r = await view.result()
179
+ console.log(json ? JSON.stringify(r) : `\n${asGrid && view.grid ? view.grid(r) : view.render(r)}\n`)
180
+ } else {
181
+ console.error(`usage: able agents run | ${Object.keys(views).join(' | ')} [--json] [--grid]`)
182
+ process.exit(sub ? 1 : 0)
183
+ }
184
+
185
+ export {}
@@ -0,0 +1,25 @@
1
+ // The ten kinds a rule can be: where it really belongs. Step 5 (classify) gives each rule exactly one; the grid, the
2
+ // skill and `show` all read them from here.
3
+
4
+ export const kinds = {
5
+ keep: { letter: '#', means: "knowledge the agent can't find itself: architecture, boundaries, why", becomes: 'stays' },
6
+ scoped: { letter: 's', means: 'real knowledge, needed only for some files or tasks', becomes: 'a `paths:` rule, a skill or a linked doc' },
7
+ lint: { letter: 'L', means: 'a code rule a linter can enforce', becomes: 'a rule in a named linter config' },
8
+ check: { letter: 'C', means: 'enforceable, but by a custom script or recipe, not a linter', becomes: 'a check in a named recipe' },
9
+ enforced: { letter: 'E', means: 'already enforced by something `checks` found', becomes: 'deleted, or one pointer line' },
10
+ guard: { letter: 'G', means: 'a prohibition on an action (commit, stash, deploy, run suites)', becomes: 'a `deny` permission or a hook' },
11
+ discoverable: { letter: 'd', means: 'the agent finds it by looking: the tree, the code, the package manager', becomes: 'deleted' },
12
+ expiring: { letter: 'x', means: 'true for now: a pivot, a migration in progress, history', becomes: 'dated, or deleted' },
13
+ duplicate: { letter: '=', means: 'says what another rule already says', becomes: 'merged into the other' },
14
+ conflict: { letter: '!', means: 'contradicts another rule', becomes: 'the operator picks which holds' },
15
+ } as const
16
+
17
+ export type Kind = keyof typeof kinds
18
+
19
+ export const isKind = (k: unknown): k is Kind => typeof k === 'string' && k in kinds
20
+
21
+ /** The order findings are numbered and shown in: a conflict first, since only the operator can settle it. */
22
+ export const pickOrder: Kind[] = ['conflict', ...(Object.keys(kinds) as Kind[]).filter((k) => k !== 'conflict')]
23
+
24
+ /** Kinds that name the rule they relate to (`with`). */
25
+ export const related: Kind[] = ['duplicate', 'conflict']
@@ -0,0 +1,213 @@
1
+ // Step 2, load: when each agent file loads, and the words an agent starting in each folder loads before doing anything.
2
+ // Also counts what loads from outside the host (folders above the root, ~/.claude/): read only, paths and counts kept,
3
+ // never split or classified. Those numbers belong to the machine that ran it.
4
+
5
+ import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from 'node:fs'
6
+ import { homedir } from 'node:os'
7
+ import { dirname, join, relative, resolve } from 'node:path'
8
+ import { countWords, fit, instructionNames, n, type Entry } from './scan.ts'
9
+
10
+ /** always: at launch. folder: when the agent works in that folder. paths: a rule whose `paths:` match a file it touches.
11
+ * skill: its name and description at launch, the body on use. config: settings, hooks and MCP, not text the agent reads.
12
+ * never: not loaded by Claude here. */
13
+ export type LoadKind = 'always' | 'folder' | 'paths' | 'skill' | 'config' | 'never'
14
+
15
+ export interface LoadedFile {
16
+ path: string
17
+ load: LoadKind
18
+ /** The folder it belongs to, from the root ('.' for the root): where an instruction file sits, or the folder that holds its `.claude/`. */
19
+ folder: string
20
+ /** Words loaded at launch by an agent in `folder` (with any `@` imports), and words loaded only on use. */
21
+ atStart: number
22
+ onUse: number
23
+ imports?: string[]
24
+ note?: string
25
+ }
26
+
27
+ export interface FolderLoad {
28
+ folder: string
29
+ host: number
30
+ outside: number
31
+ }
32
+
33
+ export interface OutsideFile {
34
+ path: string
35
+ /** `broken`: a symlink whose target is gone, so Claude loads nothing from it. */
36
+ load: LoadKind | 'broken'
37
+ atStart: number
38
+ onUse: number
39
+ }
40
+
41
+ export interface LoadMap {
42
+ files: LoadedFile[]
43
+ folders: FolderLoad[]
44
+ outside: OutsideFile[]
45
+ }
46
+
47
+ const home = homedir()
48
+ const tilde = (p: string) => (p.startsWith(home) ? `~${p.slice(home.length)}` : p)
49
+
50
+ /** The frontmatter and the body of a Markdown file. */
51
+ export function splitFrontmatter(text: string): { meta: Record<string, unknown>; body: string } {
52
+ const m = text.match(/^---\n([\s\S]*?)\n---\n?/)
53
+ if (!m) return { meta: {}, body: text }
54
+ let meta: Record<string, unknown> = {}
55
+ try {
56
+ meta = (Bun.YAML.parse(m[1]) as Record<string, unknown>) ?? {}
57
+ } catch {}
58
+ return { meta, body: text.slice(m[0].length) }
59
+ }
60
+
61
+ /** What a skill or command shows at launch (name and description) and the rest, loaded on use. */
62
+ function skillWords(text: string) {
63
+ const { meta, body } = splitFrontmatter(text)
64
+ // Without a description, Claude lists a command by its first line.
65
+ const description = typeof meta.description === 'string' ? meta.description : (body.split('\n').find((l) => l.trim()) ?? '')
66
+ const listed = countWords([typeof meta.name === 'string' ? meta.name : '', description].join(' '))
67
+ return { atStart: listed, onUse: countWords(body) }
68
+ }
69
+
70
+ /** Files an instruction file pulls in with `@path`, outside code, resolved from its folder; only ones that exist. */
71
+ function importsOf(file: string, seen = new Set<string>()): string[] {
72
+ seen.add(file)
73
+ const text = readFileSync(file, 'utf8')
74
+ .replace(/```[\s\S]*?```/g, '')
75
+ .replace(/`[^`\n]*`/g, '')
76
+ const found: string[] = []
77
+ for (const [, ref] of text.matchAll(/(?:^|\s)@((?:~\/|\.{1,2}\/|\/)?[\w.\-/]+\.\w+)/g)) {
78
+ const target = ref.startsWith('~/') ? join(home, ref.slice(2)) : resolve(dirname(file), ref)
79
+ if (seen.has(target) || !existsSync(target) || !statSync(target).isFile()) continue
80
+ found.push(target, ...importsOf(target, seen))
81
+ }
82
+ return found
83
+ }
84
+
85
+ /** The folder an agent file belongs to: an instruction file's own folder, else the folder holding its `.claude/` or `.agents/`. */
86
+ function folderOf(path: string) {
87
+ const m = path.match(/^(.*?)(?:^|\/)\.(?:claude|agents)\//)
88
+ const dir = m ? m[1] : dirname(path)
89
+ return dir === '' ? '.' : dir
90
+ }
91
+
92
+ function loadOf(root: string, e: Entry): LoadedFile {
93
+ const folder = folderOf(e.path)
94
+ const file = join(root, e.path)
95
+ const text = readFileSync(file, 'utf8')
96
+ const base = { path: e.path, folder, atStart: 0, onUse: 0 }
97
+ switch (e.kind) {
98
+ case 'instructions': {
99
+ const imports = importsOf(file)
100
+ const words = e.words + imports.reduce((n, f) => n + countWords(readFileSync(f, 'utf8')), 0)
101
+ const load = folder === '.' ? 'always' : 'folder'
102
+ return { ...base, load, atStart: words, ...(imports.length ? { imports: imports.map((f) => relative(root, f)) } : {}) }
103
+ }
104
+ case 'rule': {
105
+ const { meta, body } = splitFrontmatter(text)
106
+ return meta.paths ? { ...base, load: 'paths', onUse: countWords(body), note: `paths: ${[meta.paths].flat().join(', ')}` } : { ...base, load: 'always', atStart: countWords(body) }
107
+ }
108
+ case 'skill':
109
+ case 'command':
110
+ if (e.origin === 'source') return { ...base, load: 'never', note: 'source: not loaded here' }
111
+ return { ...base, load: 'skill', ...skillWords(text) }
112
+ case 'memory':
113
+ return { ...base, load: 'never', note: 'memory is read from ~/.claude/projects, not the repo' }
114
+ case 'cursor':
115
+ return { ...base, load: 'never', note: 'Cursor only' }
116
+ default:
117
+ return { ...base, load: 'config', note: e.kind === 'hook' ? 'its output is not counted: Able never runs it' : undefined }
118
+ }
119
+ }
120
+
121
+ const isLink = (p: string) => {
122
+ try {
123
+ return lstatSync(p).isSymbolicLink()
124
+ } catch {
125
+ return false
126
+ }
127
+ }
128
+
129
+ /** Agent files Claude loads from outside the host: instruction files above the root, and the user's ~/.claude/. */
130
+ function outsideFiles(root: string): OutsideFile[] {
131
+ const found: OutsideFile[] = []
132
+ const add = (path: string, load: OutsideFile['load'], words: { atStart: number; onUse: number }) => found.push({ path: tilde(path), load, ...words })
133
+ const read = (path: string) => readFileSync(path, 'utf8')
134
+ for (let dir = dirname(root); ; dir = dirname(dir)) {
135
+ for (const name of instructionNames) {
136
+ const p = join(dir, name)
137
+ if (existsSync(p)) add(p, 'always', { atStart: countWords(read(p)), onUse: 0 })
138
+ }
139
+ if (dir === dirname(dir)) break
140
+ }
141
+ const user = join(home, '.claude')
142
+ const userClaude = join(user, 'CLAUDE.md')
143
+ if (existsSync(userClaude)) add(userClaude, 'always', { atStart: countWords(read(userClaude)), onUse: 0 })
144
+ const list = (dir: string) => (existsSync(dir) ? readdirSync(dir).sort() : [])
145
+ for (const name of list(join(user, 'rules')).filter((n) => n.endsWith('.md'))) {
146
+ const p = join(user, 'rules', name)
147
+ const { meta, body } = splitFrontmatter(read(p))
148
+ add(p, meta.paths ? 'paths' : 'always', meta.paths ? { atStart: 0, onUse: countWords(body) } : { atStart: countWords(body), onUse: 0 })
149
+ }
150
+ for (const name of list(join(user, 'skills'))) {
151
+ const p = join(user, 'skills', name, 'SKILL.md')
152
+ if (existsSync(p)) add(p, 'skill', skillWords(read(p)))
153
+ else if (isLink(p)) add(p, 'broken', { atStart: 0, onUse: 0 })
154
+ }
155
+ for (const name of list(join(user, 'commands')).filter((n) => n.endsWith('.md'))) add(join(user, 'commands', name), 'skill', skillWords(read(join(user, 'commands', name))))
156
+ return found
157
+ }
158
+
159
+ /** The folders from the root down to `folder`: '.', 'outs', 'outs/web'. */
160
+ export const chain = (folder: string) => (folder === '.' ? ['.'] : ['.', ...folder.split('/').map((_, i, parts) => parts.slice(0, i + 1).join('/'))])
161
+
162
+ export function load(root: string, entries: Entry[]): LoadMap {
163
+ const files = entries.map((e) => loadOf(root, e))
164
+ const outside = outsideFiles(root)
165
+ const outsideStart = outside.reduce((n, f) => n + f.atStart, 0)
166
+ const starts = [...new Set(['.', ...files.filter((f) => f.load === 'folder').map((f) => f.folder)])].sort()
167
+ const folders = starts.map((folder) => {
168
+ const on = new Set(chain(folder))
169
+ const host = files.filter((f) => on.has(f.folder) && f.load !== 'never').reduce((n, f) => n + f.atStart, 0)
170
+ return { folder, host, outside: outsideStart }
171
+ })
172
+ return { files, folders, outside }
173
+ }
174
+
175
+ /** One line for `able agents run`. */
176
+ export function summary(map: LoadMap) {
177
+ const words = map.folders.map((f) => f.host)
178
+ const range = words.length > 1 ? `${n(Math.min(...words))}-${n(Math.max(...words))}` : n(words[0] ?? 0)
179
+ return `${map.folders.length} folder${map.folders.length === 1 ? '' : 's'}, ${range} at start, +${n(map.folders[0]?.outside ?? 0)} outside`
180
+ }
181
+
182
+ /** The human view of `able agents load`. */
183
+ export function render(map: LoadMap) {
184
+ const out: string[] = []
185
+ const width = Math.min(40, Math.max(4, ...map.files.map((f) => f.path.length)))
186
+ out.push(` ${'FILE'.padEnd(width)} ${'LOADS'.padEnd(6)} ${'AT START'.padStart(8)} ${'ON USE'.padStart(6)}`)
187
+ for (const f of map.files) {
188
+ const nums = f.load === 'never' || f.load === 'config' ? `${'-'.padStart(8)} ${'-'.padStart(6)}` : `${n(f.atStart).padStart(8)} ${(f.onUse ? n(f.onUse) : '-').padStart(6)}`
189
+ out.push(` ${fit(f.path, width).padEnd(width)} ${f.load.padEnd(6)} ${nums}${f.note ? ` ${f.note}` : ''}`)
190
+ for (const i of f.imports ?? []) out.push(` + @${i}`)
191
+ }
192
+
193
+ out.push('', ` ${'WORDS AT START, BY FOLDER'.padEnd(width)} ${'HOST'.padStart(6)} ${'OUTSIDE'.padStart(8)} ${'TOTAL'.padStart(6)}`)
194
+ for (const f of map.folders) out.push(` ${fit(f.folder, width).padEnd(width)} ${n(f.host).padStart(6)} ${n(f.outside).padStart(8)} ${n(f.host + f.outside).padStart(6)}`)
195
+
196
+ const groups = new Map<string, OutsideFile[]>()
197
+ for (const f of map.outside) {
198
+ const key =
199
+ f.load === 'broken' ? '~/.claude/skills (broken links)' : f.path.includes('/.claude/skills/') ? '~/.claude/skills' : f.path.includes('/.claude/commands/') ? '~/.claude/commands' : f.path
200
+ groups.set(key, [...(groups.get(key) ?? []), f])
201
+ }
202
+ out.push('', ' OUTSIDE THE HOST (this machine)')
203
+ if (!groups.size) out.push(' none')
204
+ for (const [key, fs] of groups) {
205
+ const start = fs.reduce((s, f) => s + f.atStart, 0)
206
+ const use = fs.reduce((s, f) => s + f.onUse, 0)
207
+ const what = fs.length > 1 || key.includes('skills') ? `${fs.length} skills` : fs[0].load
208
+ const words = fs[0].load === 'broken' ? 'target gone, nothing loads' : `${n(start).padStart(6)} at start${use ? `, ${n(use)} on use` : ''}`
209
+ out.push(` ${fit(key, width).padEnd(width)} ${what.padEnd(10)} ${words}`)
210
+ }
211
+ out.push('', ' Words, not tokens: tokens are about 1.3 x words.')
212
+ return out.join('\n')
213
+ }