@able-autonomy/able 0.0.13 → 0.0.15
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 +2 -2
- package/config.ts +29 -0
- package/package.json +1 -1
- package/src/agents/blocks.ts +188 -0
- package/src/agents/checks.ts +256 -0
- package/src/agents/findings.ts +124 -0
- package/src/agents/grid.ts +168 -0
- package/src/agents/index.ts +185 -0
- package/src/agents/kinds.ts +25 -0
- package/src/agents/load.ts +213 -0
- package/src/agents/picker.ts +85 -0
- package/src/agents/report.ts +191 -0
- package/src/agents/scan.ts +96 -0
- package/src/agents/show.ts +73 -0
- package/src/agents/steps.ts +32 -0
- package/src/ui.ts +4 -1
- package/src/workspaces/agent.ts +119 -0
- package/src/workspaces/index.ts +4 -0
|
@@ -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/ui.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
// Terminal output shared by the commands: colour only on a terminal.
|
|
2
2
|
|
|
3
|
-
const tty = Boolean(process.stdout.isTTY)
|
|
3
|
+
export const tty = Boolean(process.stdout.isTTY)
|
|
4
4
|
const paint = (code: number) => (s: string) => (tty ? `\x1b[${code}m${s}\x1b[0m` : s)
|
|
5
5
|
|
|
6
|
+
/** One of the terminal's 256 colours, on a terminal only. */
|
|
7
|
+
export const paint256 = (code: number) => (s: string) => (tty ? `\x1b[38;5;${code}m${s}\x1b[0m` : s)
|
|
8
|
+
|
|
6
9
|
export const dim = paint(2)
|
|
7
10
|
export const bold = paint(1)
|
|
8
11
|
export const red = paint(31)
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// able ws build <slug> ["message"]: runs a headless builder (`claude -p`) in a workspace, in the background. With no
|
|
2
|
+
// message it starts a session on "build the brief <journal>/workspaces/<slug>.md"; with one it resumes the saved session.
|
|
3
|
+
// able ws attach [<slug>]: follows that session live while the builder runs, then opens it as a normal `claude` session.
|
|
4
|
+
//
|
|
5
|
+
// The session id and pid live in the workspace's `.able/builder.json`. The conversation itself is Claude's own
|
|
6
|
+
// transcript, `~/.claude/projects/<path>/<id>.jsonl`, so there is no second log. A builder started some other way is
|
|
7
|
+
// found as the workspace's newest headless session.
|
|
8
|
+
|
|
9
|
+
import { spawn } from 'node:child_process'
|
|
10
|
+
import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs'
|
|
11
|
+
import { homedir } from 'node:os'
|
|
12
|
+
import { join } from 'node:path'
|
|
13
|
+
import { loadConfig } from '../../config.ts'
|
|
14
|
+
import { bold, dim, fail, green } from '../ui.ts'
|
|
15
|
+
import { current, workspaces, type Workspace } from './state.ts'
|
|
16
|
+
|
|
17
|
+
type Builder = { sessionId: string; pid: number; startedAt: string }
|
|
18
|
+
|
|
19
|
+
const savedPath = (ws: Workspace) => join(ws.path, '.able', 'builder.json')
|
|
20
|
+
const alive = (pid: number) => Bun.spawnSync(['kill', '-0', String(pid)], { stdout: 'ignore', stderr: 'ignore' }).exitCode === 0
|
|
21
|
+
// A `claude` started from inside another Claude session counts itself that session's child; the builder is its own.
|
|
22
|
+
const cleanEnv = () => Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith('CLAUDE')))
|
|
23
|
+
const transcriptDir = (ws: Workspace) => join(homedir(), '.claude', 'projects', realpathSync(ws.path).replace(/[^a-zA-Z0-9]/g, '-'))
|
|
24
|
+
const transcript = (ws: Workspace, id: string) => join(transcriptDir(ws), `${id}.jsonl`)
|
|
25
|
+
|
|
26
|
+
async function target(slug?: string) {
|
|
27
|
+
const at = await current()
|
|
28
|
+
const name = slug ?? (at.isWorkspace ? at.slug : undefined)
|
|
29
|
+
if (!name) fail('usage: able ws build <slug> ["message"] | able ws attach [<slug>]')
|
|
30
|
+
const ws = (await workspaces(at.main)).find((w) => w.slug === name)
|
|
31
|
+
if (!ws) fail(`no workspace '${name}'`)
|
|
32
|
+
return ws
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const readSaved = (ws: Workspace): Builder | undefined => (existsSync(savedPath(ws)) ? JSON.parse(readFileSync(savedPath(ws), 'utf8')) : undefined)
|
|
36
|
+
|
|
37
|
+
/** The newest headless session in the workspace, for a builder Able didn't start. */
|
|
38
|
+
function newestHeadless(ws: Workspace) {
|
|
39
|
+
const dir = transcriptDir(ws)
|
|
40
|
+
if (!existsSync(dir)) return
|
|
41
|
+
return readdirSync(dir)
|
|
42
|
+
.filter((f) => f.endsWith('.jsonl'))
|
|
43
|
+
.map((f) => ({ id: f.slice(0, -'.jsonl'.length), at: statSync(join(dir, f)).mtimeMs, head: readFileSync(join(dir, f), 'utf8').slice(0, 20_000) }))
|
|
44
|
+
.filter((s) => s.head.includes('"entrypoint":"sdk-cli"'))
|
|
45
|
+
.sort((a, b) => b.at - a.at)[0]?.id
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function build(slug: string | undefined, message: string | undefined) {
|
|
49
|
+
const ws = await target(slug)
|
|
50
|
+
const saved = readSaved(ws)
|
|
51
|
+
if (saved && alive(saved.pid)) fail(`the builder is still running in ${ws.slug} (pid ${saved.pid}); able ws attach ${ws.slug}`)
|
|
52
|
+
const resumeId = message ? (saved?.sessionId ?? newestHeadless(ws)) : undefined
|
|
53
|
+
if (message && !resumeId) fail(`no builder session in ${ws.slug} to resume; start one with able ws build ${ws.slug}`)
|
|
54
|
+
const sessionId = resumeId ?? crypto.randomUUID()
|
|
55
|
+
const prompt = message ?? `build the brief ${(await loadConfig(ws.path)).journal}/workspaces/${ws.slug}.md`
|
|
56
|
+
|
|
57
|
+
mkdirSync(join(ws.path, '.able'), { recursive: true })
|
|
58
|
+
const out = openSync(join(ws.path, '.able', 'builder.log'), 'a')
|
|
59
|
+
const session = resumeId ? ['--resume', resumeId] : ['--session-id', sessionId]
|
|
60
|
+
const child = spawn('claude', ['-p', prompt, ...session, '--permission-mode', 'bypassPermissions'], {
|
|
61
|
+
cwd: ws.path,
|
|
62
|
+
env: cleanEnv(),
|
|
63
|
+
detached: true,
|
|
64
|
+
stdio: ['ignore', out, out],
|
|
65
|
+
})
|
|
66
|
+
child.unref()
|
|
67
|
+
closeSync(out)
|
|
68
|
+
if (!child.pid) fail('claude did not start; is it on PATH?')
|
|
69
|
+
await Bun.write(savedPath(ws), `${JSON.stringify({ sessionId, pid: child.pid, startedAt: new Date().toISOString() } satisfies Builder, null, 2)}\n`)
|
|
70
|
+
console.log(`\n ${green('✓')} builder ${resumeId ? 'resumed' : 'started'} in ${bold(ws.slug)} ${dim(`session ${sessionId}`)}\n ${dim(`follow it: able ws attach ${ws.slug}`)}\n`)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** One line per thing the builder said (💬) or ran (🔧). */
|
|
74
|
+
function lines(record: string) {
|
|
75
|
+
const entry = JSON.parse(record)
|
|
76
|
+
if (entry.type !== 'assistant' || !Array.isArray(entry.message?.content)) return []
|
|
77
|
+
return entry.message.content.flatMap((part: { type: string; text?: string; name?: string; input?: Record<string, unknown> }) => {
|
|
78
|
+
if (part.type === 'text' && part.text?.trim()) return [`💬 ${part.text.trim()}`]
|
|
79
|
+
if (part.type !== 'tool_use') return []
|
|
80
|
+
const detail = String(part.input?.description ?? part.input?.command ?? part.input?.file_path ?? '').split('\n')[0] ?? ''
|
|
81
|
+
return [dim(`🔧 ${part.name} ${detail.slice(0, 110)}`)]
|
|
82
|
+
})
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function follow(file: string, pid: number) {
|
|
86
|
+
let seen = 0
|
|
87
|
+
const show = (all: string[]) => all.flatMap(lines).forEach((l) => console.log(l))
|
|
88
|
+
const records = () => (existsSync(file) ? readFileSync(file, 'utf8').split('\n') : [])
|
|
89
|
+
const first = records()
|
|
90
|
+
// The whole line count minus the last, possibly partial, record.
|
|
91
|
+
seen = Math.max(0, first.length - 1)
|
|
92
|
+
show(first.slice(0, seen).slice(-40))
|
|
93
|
+
while (alive(pid)) {
|
|
94
|
+
await Bun.sleep(500)
|
|
95
|
+
const now = records()
|
|
96
|
+
const complete = Math.max(0, now.length - 1)
|
|
97
|
+
show(now.slice(seen, complete))
|
|
98
|
+
seen = complete
|
|
99
|
+
}
|
|
100
|
+
show(records().slice(seen))
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export async function attach(slug: string | undefined) {
|
|
104
|
+
const ws = await target(slug)
|
|
105
|
+
const saved = readSaved(ws)
|
|
106
|
+
const sessionId = saved?.sessionId ?? newestHeadless(ws)
|
|
107
|
+
if (!sessionId) fail(`no builder session in ${ws.slug}; start one with able ws build ${ws.slug}`)
|
|
108
|
+
if (saved && alive(saved.pid)) {
|
|
109
|
+
console.log(`\n ${bold(ws.slug)} builder running ${dim('ctrl-c leaves it running')}\n`)
|
|
110
|
+
process.on('SIGINT', () => {
|
|
111
|
+
console.log(`\n ${dim(`left; the builder runs on. able ws attach ${ws.slug} to come back`)}\n`)
|
|
112
|
+
process.exit(0)
|
|
113
|
+
})
|
|
114
|
+
await follow(transcript(ws, sessionId), saved.pid)
|
|
115
|
+
console.log(`\n ${green('✓')} builder finished; opening its session\n`)
|
|
116
|
+
}
|
|
117
|
+
const claude = Bun.spawnSync(['claude', '--resume', sessionId], { cwd: ws.path, env: cleanEnv(), stdio: ['inherit', 'inherit', 'inherit'] })
|
|
118
|
+
process.exit(claude.exitCode ?? 0)
|
|
119
|
+
}
|
package/src/workspaces/index.ts
CHANGED
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
// able ws start | stop [<service>…] the workspace's services, in dependency order
|
|
10
10
|
// able ws status the services running in this checkout
|
|
11
11
|
// able ws take <resource> moves a shared resource to this checkout
|
|
12
|
+
// able ws build <slug> ["message"] a headless builder on the brief, or the saved session resumed with a message
|
|
13
|
+
// able ws attach [<slug>] follows the builder live, then opens its session
|
|
12
14
|
|
|
13
15
|
const [sub = '', ...args] = process.argv.slice(3)
|
|
14
16
|
const names = args.filter((a) => !a.startsWith('-'))
|
|
@@ -24,6 +26,8 @@ const commands: Record<string, () => Promise<unknown>> = {
|
|
|
24
26
|
start: async () => (await import('./services.ts')).start(names),
|
|
25
27
|
stop: async () => (await import('./services.ts')).stop(names),
|
|
26
28
|
status: async () => (await import('./services.ts')).status(),
|
|
29
|
+
build: async () => (await import('./agent.ts')).build(names[0], names[1]),
|
|
30
|
+
attach: async () => (await import('./agent.ts')).attach(names[0]),
|
|
27
31
|
}
|
|
28
32
|
|
|
29
33
|
const command = commands[sub]
|