@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,85 @@
1
+ // Step 9 on a terminal: the findings as checkboxes, ten to a page. Checked is yes, unchecked is no; the boxes start
2
+ // at earlier picks, else at the agent's recommendation. Enter asks for a final confirmation before anything is written.
3
+ // Plain keys and ANSI codes on Bun's raw stdin, no dependency; outside a terminal, `pick yes|no <n>…` does the same.
4
+
5
+ import { relative } from 'node:path'
6
+ import { bold, dim, paint256 } from '../ui.ts'
7
+ import { kinds } from './kinds.ts'
8
+ import type { Run } from './report.ts'
9
+ import { clip, fit } from './scan.ts'
10
+
11
+ const perPage = 10
12
+ const keys = { up: '\x1b[A', down: '\x1b[B', right: '\x1b[C', left: '\x1b[D', ctrlC: '\x03' }
13
+
14
+ /** Reads one keypress from raw stdin. */
15
+ const key = () =>
16
+ new Promise<string>((resolve) => {
17
+ process.stdin.once('data', (d) => resolve(d.toString()))
18
+ })
19
+
20
+ /** Lets the operator check findings on a terminal. Returns the answers to record, or undefined when they quit. */
21
+ export async function pickInteractive(run: Run, path: string, root: string): Promise<Map<number, 'yes' | 'no'> | undefined> {
22
+ const items = run.rules.filter((r) => r.n)
23
+ if (!items.length) return new Map()
24
+ const checked = new Set(items.filter((r) => (r.pick ?? r.recommend) === 'yes').map((r) => r.n!))
25
+ const pages = Math.ceil(items.length / perPage)
26
+ let at = 0
27
+ const width = Math.max(60, Math.min(process.stdout.columns || 100, 110))
28
+
29
+ const draw = (footer = '') => {
30
+ const page = Math.floor(at / perPage)
31
+ const out = [
32
+ `\x1b[H\x1b[2J ${bold('PICK')} ${relative(root, path)} page ${page + 1} of ${pages} · ${items.length} findings · ${checked.size} checked`,
33
+ dim(' ↑↓ move space check ←→ page a all on page enter done q quit'),
34
+ '',
35
+ ]
36
+ for (let i = page * perPage; i < Math.min(items.length, (page + 1) * perPage); i++) {
37
+ const r = items[i]
38
+ const k = kinds[r.kind]
39
+ const box = checked.has(r.n!) ? paint256(34)('[x]') : '[ ]'
40
+ const cursor = i === at ? bold('❯') : ' '
41
+ const rec = r.recommend ? dim(` rec ${r.recommend}`) : ''
42
+ out.push(` ${cursor} ${box} ${String(r.n).padStart(2)} ${k.letter} ${r.kind.padEnd(12)} ${fit(`${r.path}:${r.line}`, 44)}${rec}`)
43
+ out.push(` ${dim(`"${clip(r.text.replace(/\s+/g, ' '), width - 20)}"`)}`)
44
+ if (r.proposal) out.push(` → ${clip(`${r.proposal.target}: ${r.proposal.change}`, width - 18)}`)
45
+ }
46
+ if (footer) out.push('', footer)
47
+ process.stdout.write(out.join('\n'))
48
+ }
49
+
50
+ process.stdout.write('\x1b[?1049h\x1b[?25l')
51
+ process.stdin.setRawMode(true)
52
+ process.stdin.resume()
53
+ const leave = () => {
54
+ process.stdin.setRawMode(false)
55
+ process.stdin.pause()
56
+ process.stdout.write('\x1b[?25h\x1b[?1049l')
57
+ }
58
+ try {
59
+ for (;;) {
60
+ draw()
61
+ const k = await key()
62
+ const page = Math.floor(at / perPage)
63
+ if (k === 'q' || k === keys.ctrlC) return undefined
64
+ if (k === keys.up) at = Math.max(0, at - 1)
65
+ else if (k === keys.down) at = Math.min(items.length - 1, at + 1)
66
+ else if (k === keys.right) at = Math.min(items.length - 1, (page + 1) * perPage)
67
+ else if (k === keys.left) at = Math.max(0, (page - 1) * perPage)
68
+ else if (k === ' ') {
69
+ const n = items[at].n!
70
+ if (checked.has(n)) checked.delete(n)
71
+ else checked.add(n)
72
+ } else if (k === 'a') {
73
+ const onPage = items.slice(page * perPage, (page + 1) * perPage).map((r) => r.n!)
74
+ const all = onPage.every((n) => checked.has(n))
75
+ for (const n of onPage) all ? checked.delete(n) : checked.add(n)
76
+ } else if (k === '\r') {
77
+ const no = items.length - checked.size
78
+ draw(` ${bold(`Record ${checked.size} yes and ${no} no in ${relative(root, path)}?`)} Nothing is applied: version 1 only records picks. [y/N] `)
79
+ if ((await key()).toLowerCase() === 'y') return new Map(items.map((r) => [r.n!, checked.has(r.n!) ? 'yes' : 'no']))
80
+ }
81
+ }
82
+ } finally {
83
+ leave()
84
+ }
85
+ }
@@ -0,0 +1,191 @@
1
+ // Step 7, report: checks the agent's findings (every block classified, every rule not kept proposed), merges them with
2
+ // steps 1 to 4, works out the impact, and writes the run to `<journal>/agents/<yyyy-mm-dd>-<hhmm>.json`. Every run is
3
+ // kept. Step 9's picks are written into the same file by `able agents pick`. The run is the one source `show` and,
4
+ // later, the dashboard read; it holds each rule's span, so a view can highlight its words.
5
+
6
+ import { existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs'
7
+ import { dirname, join, relative } from 'node:path'
8
+ import type { Blocks } from './blocks.ts'
9
+ import type { Checks } from './checks.ts'
10
+ import type { Checked, Rule } from './findings.ts'
11
+ import { unproposed } from './findings.ts'
12
+ import { pickOrder, type Kind } from './kinds.ts'
13
+ import { chain, type LoadMap } from './load.ts'
14
+ import { countWords, type Entry } from './scan.ts'
15
+ import { runsDir, steps } from './steps.ts'
16
+
17
+ export const format = 'able.agents@1'
18
+
19
+ export interface Finding extends Rule {
20
+ /** The number the operator picks it by, in the order `show` lists them; kept rules have none. */
21
+ n?: number
22
+ /** 1-based line of the rule's first word in its file. */
23
+ line: number
24
+ words: number
25
+ pick?: 'yes' | 'no'
26
+ }
27
+
28
+ export interface Run {
29
+ format: typeof format
30
+ at: string
31
+ steps: { n: number; id: string; kind: string; summary: string }[]
32
+ scan: Entry[]
33
+ load: LoadMap
34
+ blocks: Blocks
35
+ checks: Checks
36
+ /** Every rule found, kept ones included; the ones not kept carry a number to pick by. */
37
+ rules: Finding[]
38
+ impact: {
39
+ /** Host words an agent starting in each folder loads, now and with every proposal applied. */
40
+ folders: { folder: string; before: number; after: number }[]
41
+ /** Rules and words per kind. */
42
+ byKind: Partial<Record<Kind, { rules: number; words: number }>>
43
+ }
44
+ /** Each CLAUDE.md as a vendor-neutral AGENTS.md: what would convert, and what stands in the way (version 2 converts). */
45
+ agentsMd: { path: string; blockers: string[] }[]
46
+ }
47
+
48
+ /** Kinds whose words leave the start-up set once applied: everything but keep, and a conflict until it is picked. */
49
+ const leaves = (k: Kind) => k !== 'keep' && k !== 'conflict'
50
+
51
+ export function runsFolder(root: string, journal: string) {
52
+ return join(root, journal, runsDir)
53
+ }
54
+
55
+ /** The run files, oldest first. */
56
+ export function runs(root: string, journal: string) {
57
+ const dir = runsFolder(root, journal)
58
+ return existsSync(dir)
59
+ ? readdirSync(dir)
60
+ .filter((f) => /^\d{4}-\d{2}-\d{2}-\d{4}\.json$/.test(f))
61
+ .sort()
62
+ .map((f) => join(dir, f))
63
+ : []
64
+ }
65
+
66
+ export const readRun = (path: string) => JSON.parse(readFileSync(path, 'utf8')) as Run
67
+
68
+ /** A run file by name or date prefix (`2026-11-16`, `2026-11-16-2240`), or the latest. */
69
+ export function findRun(root: string, journal: string, name?: string) {
70
+ const all = runs(root, journal)
71
+ return name
72
+ ? all
73
+ .filter((p) =>
74
+ p
75
+ .split('/')
76
+ .at(-1)!
77
+ .startsWith(name.replace(/\.json$/, '')),
78
+ )
79
+ .at(-1)
80
+ : all.at(-1)
81
+ }
82
+
83
+ /** What blocks the report: findings errors, blocks not classified, rules not proposed. */
84
+ export function problems(c: Checked) {
85
+ return [...c.errors, ...c.missing.map((id) => `${id}: not classified`), ...unproposed(c).map((r) => `${r.id}: ${r.kind}, no proposal yet`)]
86
+ }
87
+
88
+ /** Step 9's tally: findings to pick, and the answers so far. */
89
+ export function tally(run: Run) {
90
+ const numbered = run.rules.filter((r) => r.n)
91
+ const yes = numbered.filter((r) => r.pick === 'yes').length
92
+ const no = numbered.filter((r) => r.pick === 'no').length
93
+ return { numbered: numbered.length, yes, no, open: numbered.length - yes - no, line: `${yes + no} of ${numbered.length} picked` }
94
+ }
95
+
96
+ /** Builds the run. `path` is where it will be written; `summaries` are steps 1 to 6's lines, the rest are worked out here. */
97
+ export function build(input: { scan: Entry[]; load: LoadMap; blocks: Blocks; checks: Checks; checked: Checked; summaries: Record<string, string>; root: string; path: string; at: Date }): Run {
98
+ const { scan, load, blocks, checks, checked } = input
99
+ const blockOf = new Map(blocks.blocks.map((b) => [b.id, b]))
100
+ let n = 0
101
+ const rules = checked.rules
102
+ .map((r) => {
103
+ const b = blockOf.get(r.block)!
104
+ const line = b.lines[0] + b.text.slice(0, r.span[0] - b.span[0]).split('\n').length - 1
105
+ return { ...r, line, words: countWords(r.text) }
106
+ })
107
+ .sort((a, b) => pickOrder.indexOf(a.kind) - pickOrder.indexOf(b.kind) || a.path.localeCompare(b.path) || a.span[0] - b.span[0])
108
+ .map((r) => (r.kind === 'keep' ? r : { ...r, n: ++n }))
109
+
110
+ // A rule counts at start for a folder when its file loads at start there: an instruction file or always-on rule in the
111
+ // folder's chain, or a skill's description.
112
+ const fileLoad = new Map(load.files.map((f) => [f.path, f]))
113
+ const atStart = (r: (typeof rules)[number], folder: string) => {
114
+ const f = fileLoad.get(r.path)
115
+ if (!f) return false
116
+ if (f.load === 'skill') return blockOf.get(r.block)?.heading[0] === 'description'
117
+ return (f.load === 'always' || f.load === 'folder') && chain(folder).includes(f.folder)
118
+ }
119
+ const folders = load.folders.map((f) => ({
120
+ folder: f.folder,
121
+ before: f.host,
122
+ after: f.host - rules.filter((r) => leaves(r.kind) && atStart(r, f.folder)).reduce((s, r) => s + r.words, 0),
123
+ }))
124
+ const byKind: Run['impact']['byKind'] = {}
125
+ for (const r of rules) {
126
+ const k = (byKind[r.kind] ??= { rules: 0, words: 0 })
127
+ k.rules++
128
+ k.words += r.words
129
+ }
130
+
131
+ const pathRules = scan.some((e) => e.kind === 'rule')
132
+ const agentsMd = scan
133
+ .filter((e) => e.kind === 'instructions' && e.path.endsWith('CLAUDE.md') && !e.path.endsWith('CLAUDE.local.md'))
134
+ .map((e) => {
135
+ const dir = dirname(e.path)
136
+ const at = (name: string) => (dir === '.' ? name : `${dir}/${name}`)
137
+ const blockers = [
138
+ ...(existsSync(join(input.root, at('CLAUDE.local.md'))) ? ['a CLAUDE.local.md beside it stops Claude reading AGENTS.md'] : []),
139
+ ...(scan.some((x) => x.path === at('AGENTS.md')) ? ['an AGENTS.md already exists beside it: merge, do not overwrite'] : []),
140
+ ...(pathRules && dir === '.' ? ['.claude/rules with paths: are Claude-only and stay where they are'] : []),
141
+ ]
142
+ return { path: e.path, blockers }
143
+ })
144
+
145
+ const root = folders.find((f) => f.folder === '.')
146
+ const summaries: Record<string, string> = {
147
+ ...input.summaries,
148
+ report: relative(input.root, input.path),
149
+ show: `${root ? root.before - root.after : 0} words leave the root's start`,
150
+ pick: `0 of ${rules.filter((r) => r.n).length} picked`,
151
+ }
152
+ return {
153
+ format,
154
+ at: input.at.toISOString(),
155
+ steps: steps.filter((s) => s.v1).map((s) => ({ n: s.n, id: s.id, kind: s.kind, summary: summaries[s.id] ?? '' })),
156
+ scan,
157
+ load,
158
+ blocks,
159
+ checks,
160
+ rules,
161
+ impact: { folders, byKind },
162
+ agentsMd,
163
+ }
164
+ }
165
+
166
+ /** The run's file name: local date and time, so two runs a minute apart are both kept. */
167
+ export function runName(at = new Date()) {
168
+ const p = (v: number) => String(v).padStart(2, '0')
169
+ return `${at.getFullYear()}-${p(at.getMonth() + 1)}-${p(at.getDate())}-${p(at.getHours())}${p(at.getMinutes())}.json`
170
+ }
171
+
172
+ /** Where a run taken at `at` is written. */
173
+ export const runPath = (root: string, journal: string, at: Date) => join(runsFolder(root, journal), runName(at))
174
+
175
+ /** Writes a run file; the one place its format on disk is set. */
176
+ export async function saveRun(path: string, run: Run) {
177
+ mkdirSync(dirname(path), { recursive: true })
178
+ await Bun.write(path, `${JSON.stringify(run, null, 1)}\n`)
179
+ }
180
+
181
+ /** Step 9: records the operator's yes or no on numbered findings in the run, and saves it. */
182
+ export async function pick(path: string, run: Run, answers: Map<number, 'yes' | 'no'>) {
183
+ const known = new Set(run.rules.flatMap((r) => (r.n ? [r.n] : [])))
184
+ const unknown = [...answers.keys()].filter((x) => !known.has(x))
185
+ if (unknown.length) return unknown
186
+ for (const r of run.rules) if (r.n && answers.has(r.n)) r.pick = answers.get(r.n)
187
+ const step = run.steps.find((s) => s.id === 'pick')
188
+ if (step) step.summary = tally(run).line
189
+ await saveRun(path, run)
190
+ return unknown
191
+ }
@@ -0,0 +1,96 @@
1
+ // Step 1, scan: every agent file in the host, what kind it is, and its size. Reads only.
2
+ // Files come from git (tracked plus untracked, gitignored ones skipped), so `node_modules` and build output never show.
3
+
4
+ import { existsSync, readFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import { lines as gitLines } from '../git.ts'
7
+
8
+ export type FileKind = 'instructions' | 'rule' | 'settings' | 'skill' | 'command' | 'hook' | 'memory' | 'mcp' | 'cursor'
9
+
10
+ /** house: the host's own skill. downloaded: listed in skills-lock.json, changed upstream. source: a root `skills/` the
11
+ * host publishes (Able's own), which Claude does not load in this repo. */
12
+ export type SkillOrigin = 'house' | 'downloaded' | 'source'
13
+
14
+ export interface Entry {
15
+ path: string
16
+ kind: FileKind
17
+ words: number
18
+ lines: number
19
+ origin?: SkillOrigin
20
+ }
21
+
22
+ export const countWords = (text: string) => text.split(/\s+/).filter(Boolean).length
23
+
24
+ /** A number as the views print it: 1,234. */
25
+ export const n = (v: number) => v.toLocaleString('en')
26
+
27
+ /** Text cut at the end with a mark, since text is read by how it opens. */
28
+ export const clip = (text: string, max: number, mark = '...') => (text.length <= max ? text : `${text.slice(0, max - mark.length)}${mark}`)
29
+
30
+ /** The instruction files Claude loads by name, in the host and in the folders above it. */
31
+ export const instructionNames = ['CLAUDE.md', 'CLAUDE.local.md', 'AGENTS.md']
32
+
33
+ /** The kind of an agent file from its path, or undefined for any other file. */
34
+ function kindOf(path: string): FileKind | undefined {
35
+ const name = path.split('/').at(-1) ?? ''
36
+ if (instructionNames.includes(name)) return 'instructions'
37
+ if (/(^|\/)\.claude\/rules\/.+\.md$/.test(path)) return 'rule'
38
+ if (/(^|\/)\.claude\/settings(\.local)?\.json$/.test(path)) return 'settings'
39
+ if (/(^|\/)(\.claude\/skills|\.agents\/skills)\/[^/]+\/SKILL\.md$/.test(path) || /^skills\/[^/]+\/SKILL\.md$/.test(path)) return 'skill'
40
+ if (/(^|\/)\.claude\/commands\/.+\.md$/.test(path)) return 'command'
41
+ if (/(^|\/)\.claude\/hooks\/[^/]+$/.test(path)) return 'hook'
42
+ if (/(^|\/)\.claude\/projects\/.+\/memory\/.+\.md$/.test(path)) return 'memory'
43
+ if (name === '.mcp.json') return 'mcp'
44
+ if (/(^|\/)\.cursor\/rules\/.+/.test(path)) return 'cursor'
45
+ }
46
+
47
+ // Local files are usually gitignored but still load, so the root's are looked for by name.
48
+ const localFiles = ['CLAUDE.local.md', '.claude/settings.local.json']
49
+
50
+ /** The host's files: tracked and untracked, gitignored ones skipped, plus the root's local agent files. */
51
+ export function listFiles(root: string) {
52
+ return [...new Set([...gitLines(root, 'ls-files', '--cached', '--others', '--exclude-standard'), ...localFiles.filter((f) => existsSync(join(root, f)))])]
53
+ }
54
+
55
+ /** The skill names in the host's skills-lock.json, the skills it downloaded. */
56
+ function downloadedSkills(root: string) {
57
+ const lock = join(root, 'skills-lock.json')
58
+ if (!existsSync(lock)) return new Set<string>()
59
+ return new Set(Object.keys(JSON.parse(readFileSync(lock, 'utf8')).skills ?? {}))
60
+ }
61
+
62
+ export function scan(root: string, files: string[]): Entry[] {
63
+ const downloaded = downloadedSkills(root)
64
+ return files
65
+ .flatMap((path) => {
66
+ const kind = kindOf(path)
67
+ // A deleted file git still tracks is skipped.
68
+ if (!kind || !existsSync(join(root, path))) return []
69
+ const text = readFileSync(join(root, path), 'utf8')
70
+ const entry: Entry = { path, kind, words: countWords(text), lines: text.split('\n').length }
71
+ if (kind === 'skill') {
72
+ const name = path.split('/').at(-2) ?? ''
73
+ entry.origin = path.startsWith('skills/') ? 'source' : downloaded.has(name) ? 'downloaded' : 'house'
74
+ }
75
+ return [entry]
76
+ })
77
+ .sort((a, b) => a.path.localeCompare(b.path))
78
+ }
79
+
80
+ /** One line for `able agents run`. */
81
+ export const summary = (entries: Entry[]) => `${entries.length} files, ${n(entries.reduce((sum, e) => sum + e.words, 0))} words`
82
+
83
+ /** A path cut in the middle to fit, so the view stays narrow enough for a terminal and a chat. */
84
+ export const fit = (path: string, max: number) => (path.length <= max ? path : `${path.slice(0, 12)}...${path.slice(-(max - 15))}`)
85
+
86
+ /** The human view of `able agents scan`. */
87
+ export function render(entries: Entry[]) {
88
+ const width = Math.min(48, Math.max(4, ...entries.map((e) => e.path.length)))
89
+ const lines = [` ${'PATH'.padEnd(width)} ${'KIND'.padEnd(16)} ${'WORDS'.padStart(6)} ${'LINES'.padStart(5)}`]
90
+ for (const e of entries) {
91
+ const kind = e.origin ? `${e.kind}:${e.origin}` : e.kind
92
+ lines.push(` ${fit(e.path, width).padEnd(width)} ${kind.padEnd(16)} ${String(e.words).padStart(6)} ${String(e.lines).padStart(5)}`)
93
+ }
94
+ lines.push('', ` ${summary(entries)}`)
95
+ return lines.join('\n')
96
+ }
@@ -0,0 +1,73 @@
1
+ // Step 8, show: a run read back from its file and printed as plain text, narrow enough for a terminal and a chat.
2
+ // `--step <n>` prints one step's full view from the same file, so any step can be looked at again later.
3
+
4
+ import { relative } from 'node:path'
5
+ import { dim } from '../ui.ts'
6
+ import * as blocks from './blocks.ts'
7
+ import * as checks from './checks.ts'
8
+ import * as grid from './grid.ts'
9
+ import { kinds, pickOrder } from './kinds.ts'
10
+ import * as load from './load.ts'
11
+ import { runName, tally, type Run } from './report.ts'
12
+ import { who } from './steps.ts'
13
+ import { clip, fit, n, render as renderScan } from './scan.ts'
14
+
15
+ /** One step's full view, from the run file. */
16
+ export function step(run: Run, id: string) {
17
+ // In reading order, as the file has them; the run stores them in pick order.
18
+ const checked = { rules: [...run.rules].sort((a, b) => a.span[0] - b.span[0]), missing: [], errors: [] }
19
+ const views: Record<string, () => string> = {
20
+ scan: () => renderScan(run.scan),
21
+ load: () => load.render(run.load),
22
+ blocks: () => blocks.render(run.blocks),
23
+ checks: () => checks.render(run.checks),
24
+ classify: () => grid.byKind(run.blocks, checked),
25
+ }
26
+ return views[id]?.() ?? ` Step ${id} has no view of its own: its result is in the findings below.\n\n${findings(run)}`
27
+ }
28
+
29
+ function findings(run: Run) {
30
+ const out: string[] = []
31
+ const numbered = run.rules.filter((r) => r.n)
32
+ for (const kind of pickOrder) {
33
+ const list = numbered.filter((r) => r.kind === kind)
34
+ if (!list.length) continue
35
+ out.push(` ${kinds[kind].letter} ${kind.toUpperCase()} ${list.length} ${dim(`→ ${kinds[kind].becomes}`)}`)
36
+ for (const r of list) {
37
+ const pick = r.pick === 'yes' ? '[y]' : r.pick === 'no' ? '[n]' : '[ ]'
38
+ const rec = r.recommend ? dim(` rec ${r.recommend}`) : ''
39
+ out.push(` ${pick} ${String(r.n).padStart(2)} ${r.confidence.padEnd(4)} ${fit(`${r.path}:${r.line}`, 34).padEnd(34)} "${clip(r.text.replace(/\s+/g, ' '), 46)}"${rec}`)
40
+ out.push(` ${dim(clip(r.reason, 92))}`)
41
+ if (r.proposal) out.push(` → ${clip(r.proposal.target, 40)}: ${clip(r.proposal.change, 64)}`)
42
+ }
43
+ out.push('')
44
+ }
45
+ return out.join('\n')
46
+ }
47
+
48
+ export function render(run: Run, path: string, root: string) {
49
+ const out: string[] = []
50
+ const { numbered } = tally(run)
51
+ out.push(
52
+ ` RUN ${runName(new Date(run.at))
53
+ .replace(/\.json$/, '')
54
+ .replace(/-(\d\d)(\d\d)$/, ' $1:$2')} ${relative(root, path)} ${run.format}`,
55
+ '',
56
+ )
57
+ out.push(' STEPS')
58
+ for (const s of run.steps) out.push(` ${String(s.n).padStart(2)} ${who[s.kind as keyof typeof who]} ${s.id.padEnd(10)} ${s.summary}`)
59
+
60
+ out.push('', ` WORDS AT START, BY FOLDER (host files; tokens are about 1.3 x words)`)
61
+ out.push(` ${'folder'.padEnd(24)} ${'now'.padStart(6)} ${'after'.padStart(6)} ${'saved'.padStart(6)}`)
62
+ for (const f of run.impact.folders)
63
+ out.push(` ${clip(f.folder === '.' ? '(root)' : f.folder, 24).padEnd(24)} ${n(f.before).padStart(6)} ${n(f.after).padStart(6)} ${`-${n(f.before - f.after)}`.padStart(6)}`)
64
+
65
+ const kept = run.impact.byKind.keep
66
+ out.push('', ` FINDINGS ${numbered} to pick${kept ? `, ${kept.rules} rules kept` : ''} [y] yes [n] no [ ] not picked yet`, '')
67
+ out.push(findings(run))
68
+
69
+ out.push(' AGENTS.md (vendor-neutral; converting is version 2)')
70
+ for (const a of run.agentsMd) out.push(` ${a.path.padEnd(24)} ${a.blockers.length ? a.blockers.join('; ') : 'would convert: AGENTS.md, plus a CLAUDE.md of one line, @AGENTS.md'}`)
71
+ if (!run.agentsMd.length) out.push(' no CLAUDE.md files')
72
+ return out.join('\n')
73
+ }
@@ -0,0 +1,32 @@
1
+ // The steps of a run, as data: `able agents run` walks them, the skill follows them, a dashboard page will show them.
2
+
3
+ export type StepKind = 'mechanical' | 'agent' | 'operator'
4
+
5
+ export interface Step {
6
+ n: number
7
+ /** The step's one name, also its command: `able agents <id>`. */
8
+ id: string
9
+ kind: StepKind
10
+ /** False for the steps that come after version 1. */
11
+ v1: boolean
12
+ }
13
+
14
+ /** The letter each kind of step shows as in `run` and `show`. */
15
+ export const who: Record<StepKind, string> = { mechanical: 'M', agent: 'A', operator: 'O' }
16
+
17
+ export const steps: Step[] = [
18
+ { n: 1, id: 'scan', kind: 'mechanical', v1: true },
19
+ { n: 2, id: 'load', kind: 'mechanical', v1: true },
20
+ { n: 3, id: 'blocks', kind: 'mechanical', v1: true },
21
+ { n: 4, id: 'checks', kind: 'mechanical', v1: true },
22
+ { n: 5, id: 'classify', kind: 'agent', v1: true },
23
+ { n: 6, id: 'propose', kind: 'agent', v1: true },
24
+ { n: 7, id: 'report', kind: 'mechanical', v1: true },
25
+ { n: 8, id: 'show', kind: 'mechanical', v1: true },
26
+ { n: 9, id: 'pick', kind: 'operator', v1: true },
27
+ { n: 10, id: 'apply', kind: 'agent', v1: false },
28
+ { n: 11, id: 'compare', kind: 'mechanical', v1: false },
29
+ ]
30
+
31
+ /** The folder runs are written to, under the host's journal. One name, so renaming the skill is one line. */
32
+ export const runsDir = 'agents'
package/src/commit.ts CHANGED
@@ -12,7 +12,8 @@ import { join, relative, resolve } from 'node:path'
12
12
  import { loadConfig, trailerArgs } from '../config.ts'
13
13
  import { runChecks } from './checks.ts'
14
14
  import { failOnMerge, git, gitLoud } from './git.ts'
15
- import { bold, confirm, dim, fail, green } from './ui.ts'
15
+ import { status, working } from './status.ts'
16
+ import { bold, cancel, confirm, dim, fail, green } from './ui.ts'
16
17
  import { current } from './workspaces/state.ts'
17
18
 
18
19
  const argv = process.argv.slice(3)
@@ -38,19 +39,28 @@ const changed = () => {
38
39
  return paths
39
40
  }
40
41
 
42
+ const step = working('commit')
43
+ step('reading what changed')
41
44
  const before = changed()
42
45
  if (!before.length) fail('nothing to commit')
43
46
  console.log(`\n ${bold(`${before.length} file(s)`)} ${dim(scope.join(' '))}`)
44
47
  for (const f of before) console.log(dim(` ${f}`))
45
- if (argv.includes('--dry')) process.exit(0)
46
- if (!argv.includes('--yes') && !confirm(`Run the checks and commit as "${msg}"?`)) fail('aborted; nothing committed')
48
+ if (argv.includes('--dry')) {
49
+ status({ state: 'done', msg: `commit: ${before.length} file(s) would go in` })
50
+ process.exit(0)
51
+ }
52
+ if (!argv.includes('--yes') && !confirm(`Run the checks and commit as "${msg}"?`)) cancel('aborted; nothing committed')
47
53
 
48
54
  const config = await loadConfig(root)
55
+ step(`checks for ${before.length} file(s)`)
49
56
  if (!runChecks(config, before, at)) fail('a check failed; nothing committed')
50
57
 
51
58
  // The checks may have formatted files, so the list is read again.
52
59
  const paths = changed()
60
+ step('committing')
53
61
  // A path that is gone (a deletion, a rename's old name) has nothing to add, but still goes into the commit.
54
62
  const present = paths.filter((p) => existsSync(join(root, p)))
55
63
  if ((present.length && !gitLoud(root, 'add', '--', ...present)) || !gitLoud(root, 'commit', '--quiet', '-m', msg, ...trailerArgs(config), '--', ...paths)) fail('git commit failed')
56
- console.log(`\n ${green('✓')} ${git(root, 'log', '--oneline', '-1')}\n`)
64
+ const made = git(root, 'log', '--oneline', '-1')
65
+ console.log(`\n ${green('✓')} ${made}\n`)
66
+ status({ state: 'done', msg: `commit: ${made}` })
package/src/init.ts ADDED
@@ -0,0 +1,75 @@
1
+ // able init: brings a project to Able on this machine, from any of its checkouts. It walks a short list of steps and
2
+ // does the ones still missing, so it is safe to run again: on a project already set up (a teammate's clone, a second
3
+ // laptop) only the machine's steps are left.
4
+ //
5
+ // able init sets this project up here
6
+ // able init --list the projects set up on this machine
7
+ // able init --remove forgets this project on this machine (its repo is left as it is)
8
+ //
9
+ // The steps:
10
+ // 1. config the project's able.config.ts. WIP: init does not write one yet. It is meant to ask the operator a few
11
+ // questions and write it (the onboarding `loadConfig`'s message points to); today it must exist already.
12
+ // 2. machine records the project's main checkout in `~/.config/able/checkouts.json` (`owner/name` to its path), so
13
+ // the dashboard running on this machine reads the journal and docs off disk. Nothing leaves the machine.
14
+ // Next to come, each its own step here: installing Able's skills, the GitHub App, the project on the dashboard.
15
+
16
+ import { existsSync, mkdirSync } from 'node:fs'
17
+ import { join } from 'node:path'
18
+ import { hostRoot, loadConfig } from '../config.ts'
19
+ import { git, mainRoot } from './git.ts'
20
+ import { ableDir, checkoutsFile, repoOf } from './machine.ts'
21
+ import { status, working } from './status.ts'
22
+ import { bold, dim, fail, green, yellow } from './ui.ts'
23
+
24
+ const args = process.argv.slice(3)
25
+ const file = checkoutsFile()
26
+
27
+ const read = async (): Promise<Record<string, string>> => (existsSync(file) ? await Bun.file(file).json() : {})
28
+ const write = async (map: Record<string, string>) => {
29
+ mkdirSync(ableDir(), { recursive: true, mode: 0o700 })
30
+ await Bun.write(file, `${JSON.stringify(map, null, 2)}\n`)
31
+ }
32
+ const row = (mark: string, step: string, text: string) => console.log(` ${mark} ${step.padEnd(9)} ${text}`)
33
+ const wip = (text: string) => console.log(dim(`\n WIP: ${text}\n`))
34
+
35
+ if (args.includes('--list')) {
36
+ const entries = Object.entries(await read())
37
+ if (!entries.length) console.log(dim(`\n no projects set up on this machine (${file})\n`))
38
+ else console.log(`\n${entries.map(([repo, path]) => ` ${bold(repo)} ${dim(path)}`).join('\n')}\n`)
39
+ process.exit(0)
40
+ }
41
+
42
+ const root = hostRoot()
43
+ const repo = repoOf(git(root, 'remote', 'get-url', 'origin'))
44
+ if (!repo) fail('no GitHub repo: this checkout has no GitHub origin')
45
+
46
+ if (args.includes('--remove')) {
47
+ const map = await read()
48
+ if (!(repo in map)) fail(`${repo} is not set up on this machine`)
49
+ delete map[repo]
50
+ await write(map)
51
+ console.log(`\n ${green('✓')} ${bold(repo)} forgotten on this machine; nothing in its repo changed\n`)
52
+ process.exit(0)
53
+ }
54
+
55
+ const main = mainRoot(root)
56
+ const step = working(`init ${repo}`)
57
+ console.log(`\n ${bold('able init')} ${repo}\n`)
58
+
59
+ // 1. config
60
+ if (!existsSync(join(main, 'able.config.ts'))) {
61
+ row(yellow('◌'), 'config', `no able.config.ts in ${main}`)
62
+ fail("WIP: init can't write able.config.ts yet. Write it by hand (README.md in Able, the host contract), then run init again.")
63
+ }
64
+ step('reading the config')
65
+ const config = await loadConfig(main)
66
+ row(green('✓'), 'config', `able.config.ts ${dim(`journal ${config.journal}, knowledge ${config.knowledge ?? 'none'}`)}`)
67
+
68
+ // 2. machine
69
+ const map = await read()
70
+ const before = map[repo]
71
+ if (before !== main) await write({ ...map, [repo]: main })
72
+ row(green('✓'), 'machine', `${main} ${dim(before === main ? 'already recorded' : before ? `was ${before}` : 'recorded')}`)
73
+
74
+ wip(`init only checks the config and records this checkout so far. Add ${repo} on the dashboard's Projects page to see its journal.`)
75
+ status({ state: 'done', msg: `init: ${repo} set up on this machine` })
package/src/machine.ts ADDED
@@ -0,0 +1,15 @@
1
+ // What a command knows about this machine and a checkout's GitHub repo, with no imports of Able's own, so any
2
+ // command can use it. api/docs.ts keeps its own copy of `repoOf` and the checkouts file's path, because api/'s image
3
+ // carries no cli/: change them together.
4
+
5
+ import { homedir } from 'node:os'
6
+ import { join } from 'node:path'
7
+
8
+ /** Able's machine-only folder: `~/.config/able/`, or `ABLE_CONFIG_DIR`. */
9
+ export const ableDir = () => process.env.ABLE_CONFIG_DIR ?? join(homedir(), '.config', 'able')
10
+
11
+ /** The projects set up on this machine (`able init`): `owner/name` to the main checkout's path. */
12
+ export const checkoutsFile = () => join(ableDir(), 'checkouts.json')
13
+
14
+ /** A GitHub remote's `owner/name`, or undefined for any other URL. */
15
+ export const repoOf = (origin: string) => /github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(origin)?.[1]
@@ -0,0 +1,43 @@
1
+ import { expect, test } from 'bun:test'
2
+ import { oneLine, report } from './status.ts'
3
+
4
+ const b64 = (s: string) => Buffer.from(s).toString('base64')
5
+ // The message a report carries, decoded.
6
+ const msgOf = (bytes: string) => Buffer.from(/msg=([A-Za-z0-9+/=]*)/.exec(bytes)![1]!, 'base64').toString()
7
+
8
+ test('the exact bytes of each state', () => {
9
+ expect(report({ state: 'idle' })).toBe('\x1b]7501;state=idle:app=able\x1b\\')
10
+ expect(report({ state: 'clear' })).toBe('\x1b]7501;state=clear:app=able\x1b\\')
11
+ expect(report({ state: 'working', msg: 'Installing updates' })).toBe('\x1b]7501;state=working:app=able:msg=SW5zdGFsbGluZyB1cGRhdGVz\x1b\\')
12
+ expect(report({ state: 'working', msg: 'api: checks', progress: 40 })).toBe(`\x1b]7501;state=working:app=able:progress=40:msg=${b64('api: checks')}\x1b\\`)
13
+ expect(report({ state: 'blocked', kind: 'question', msg: 'Merge?' })).toBe(`\x1b]7501;state=blocked:app=able:kind=question:msg=${b64('Merge?')}\x1b\\`)
14
+ expect(report({ state: 'done', msg: 'Upgraded 12 packages' })).toBe('\x1b]7501;state=done:app=able:msg=VXBncmFkZWQgMTIgcGFja2FnZXM=\x1b\\')
15
+ expect(report({ state: 'error', msg: 'a check failed' })).toBe(`\x1b]7501;state=error:app=able:msg=${b64('a check failed')}\x1b\\`)
16
+ })
17
+
18
+ test('kind and progress go only with the states that take them', () => {
19
+ expect(report({ state: 'done', kind: 'auth', progress: 50 })).toBe('\x1b]7501;state=done:app=able\x1b\\')
20
+ expect(report({ state: 'working', kind: 'auth' })).toBe('\x1b]7501;state=working:app=able\x1b\\')
21
+ expect(report({ state: 'working', progress: 140.4 })).toContain('progress=100')
22
+ expect(report({ state: 'blocked', progress: -3 })).toContain('progress=0')
23
+ expect(report({ state: 'working', progress: Number.NaN })).not.toContain('progress')
24
+ })
25
+
26
+ test('control characters and colour codes never reach a report', () => {
27
+ expect(oneLine('\n \x1b[31mconflict\x1b[0m merging:\n\tapi/docs.ts\r\n\x07 done\x7f\u0085')).toBe('conflict merging: api/docs.ts done')
28
+ expect(msgOf(report({ state: 'error', msg: 'one\ntwo\tthree' }))).toBe('one two three')
29
+ // An empty message is left out rather than sent empty.
30
+ expect(report({ state: 'working', msg: '\n\t' })).toBe('\x1b]7501;state=working:app=able\x1b\\')
31
+ })
32
+
33
+ test('a long message is cut to 2048 bytes on a character boundary', () => {
34
+ expect(oneLine('a'.repeat(3000))).toBe('a'.repeat(2048))
35
+ // 'é' is two bytes: 1024 of them fit exactly, and one byte more must not split the next.
36
+ expect(oneLine('é'.repeat(2000))).toBe('é'.repeat(1024))
37
+ expect(oneLine(`a${'é'.repeat(2000)}`)).toBe(`a${'é'.repeat(1023)}`)
38
+ // '🙂' is four bytes.
39
+ const cut = oneLine(`ab${'🙂'.repeat(600)}`)
40
+ expect(cut).toBe(`ab${'🙂'.repeat(511)}`)
41
+ expect(new TextEncoder().encode(cut).length).toBeLessThanOrEqual(2048)
42
+ expect(msgOf(report({ state: 'working', msg: 'é'.repeat(2000) }))).toBe('é'.repeat(1024))
43
+ })