@able-autonomy/able 0.0.21 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/able.ts +9 -2
  2. package/config.ts +11 -0
  3. package/package.json +1 -1
  4. package/src/bloat/apply.test.ts +81 -0
  5. package/src/bloat/apply.ts +49 -0
  6. package/src/{agents → bloat}/blocks.ts +2 -2
  7. package/src/{agents → bloat}/checks.ts +2 -2
  8. package/src/bloat/compare.ts +63 -0
  9. package/src/{agents → bloat}/findings.ts +11 -7
  10. package/src/{agents → bloat}/grid.ts +4 -4
  11. package/src/bloat/index.ts +258 -0
  12. package/src/{agents → bloat}/load.ts +2 -2
  13. package/src/{agents → bloat}/picker.ts +3 -3
  14. package/src/bloat/report.ts +286 -0
  15. package/src/{agents → bloat}/scan.ts +2 -2
  16. package/src/bloat/show.ts +79 -0
  17. package/src/bloat/steps.ts +32 -0
  18. package/src/{agents → bloat}/types.ts +48 -3
  19. package/src/commit.ts +2 -1
  20. package/src/git.ts +43 -2
  21. package/src/push.ts +2 -1
  22. package/src/ui.ts +3 -0
  23. package/src/workspaces/fixture.ts +49 -0
  24. package/src/workspaces/index.ts +3 -1
  25. package/src/workspaces/ls.ts +56 -11
  26. package/src/workspaces/merge.ts +29 -13
  27. package/src/workspaces/new.ts +17 -15
  28. package/src/workspaces/overlap.test.ts +53 -0
  29. package/src/workspaces/overlap.ts +86 -0
  30. package/src/workspaces/preview.test.ts +81 -0
  31. package/src/workspaces/preview.ts +162 -0
  32. package/src/workspaces/refresh.ts +26 -24
  33. package/src/workspaces/rm.ts +6 -1
  34. package/src/workspaces/services.ts +2 -2
  35. package/src/workspaces/state.ts +56 -9
  36. package/src/workspaces/trunk.test.ts +88 -0
  37. package/sync.ts +5 -2
  38. package/src/agents/index.ts +0 -198
  39. package/src/agents/report.ts +0 -211
  40. package/src/agents/show.ts +0 -73
  41. package/src/agents/steps.ts +0 -32
  42. /package/src/{agents → bloat}/kinds.ts +0 -0
package/able.ts CHANGED
@@ -128,7 +128,14 @@ if (command === 'upgrade') {
128
128
  console.log(`Upgraded able v${current} → v${latest}`)
129
129
  process.exit(0)
130
130
  }
131
- const modules: Record<string, string> = { agents: './src/agents/index.ts', commit: './src/commit.ts', init: './src/init.ts', push: './src/push.ts', ws: './src/workspaces/index.ts' }
131
+ const modules: Record<string, string> = {
132
+ bloat: './src/bloat/index.ts',
133
+ agents: './src/bloat/index.ts',
134
+ commit: './src/commit.ts',
135
+ init: './src/init.ts',
136
+ push: './src/push.ts',
137
+ ws: './src/workspaces/index.ts',
138
+ }
132
139
  if (command && modules[command]) {
133
140
  await import(modules[command])
134
141
  process.exit(0)
@@ -147,7 +154,7 @@ if (delegate) {
147
154
  }
148
155
  if (command !== 'gh') {
149
156
  console.error(
150
- "usage: able gh <gh arguments> run gh as Able's GitHub App\n able sync [--dry-run] file follow-ups and write ended weeks' records\n able config [--json] print the host's able.config.ts\n able init [--list|--remove] sets this project up on this machine (WIP)\n able commit \"<message>\" [<path>…] a pathspec commit after the touched folders' checks\n able push pushes this branch with its tags\n able upgrade makes bunx run the latest published able\n able -v prints this able's version\n able ws <new|ls|current|refresh|merge|rm|start|stop|status|take|build|attach> workspaces\n able agents <run|scan|load|blocks|checks|classify|propose|report|show|pick> where each agent-file rule belongs",
157
+ "usage: able gh <gh arguments> run gh as Able's GitHub App\n able sync [--dry-run] file follow-ups and write ended weeks' records\n able config [--json] print the host's able.config.ts\n able init [--list|--remove] sets this project up on this machine (WIP)\n able commit \"<message>\" [<path>…] a pathspec commit after the touched folders' checks\n able push pushes this branch with its tags\n able upgrade makes bunx run the latest published able\n able -v prints this able's version\n able ws <new|ls|current|refresh|merge|preview|rm|start|stop|status|take|build|attach> workspaces\n able bloat <status|scan|load|blocks|checks|classify|propose|report|show|pick|history> the bloat diagnostic: where each agent-file rule belongs",
151
158
  )
152
159
  process.exit(command ? 1 : 0)
153
160
  }
package/config.ts CHANGED
@@ -26,6 +26,12 @@ export interface WorkspacesConfig {
26
26
  copy?: string[]
27
27
  onCreate?: Command[]
28
28
  onRemove?: Command[]
29
+ /** Run in the combined preview (`able ws preview`) after each rebuild, before its services start: what makes the
30
+ * rebuilt tree run, such as resetting its database (migrate and seed). */
31
+ onPreview?: Command[]
32
+ /** Where a checkout's app answers, printed by `able ws preview` and in `able ws ls --json`:
33
+ * `http://<slug>.localhost:<port + offset><path>`. */
34
+ url?: { port: number; path?: string }
29
35
  services?: Record<string, Service>
30
36
  /** Shared resources with one holder at a time on a machine (the tunnel, the devices): `able ws take` runs `take` and
31
37
  * records the holder. An `auto` one is taken by `able ws start` and goes back to its earlier holder at `able ws stop`.
@@ -51,6 +57,9 @@ export interface AbleConfig {
51
57
  knowledge?: string
52
58
  }
53
59
 
60
+ /** A checkout's URL from `workspaces.url`. */
61
+ export const urlOf = (url: NonNullable<WorkspacesConfig['url']>, slug: string, offset: number) => `http://${slug}.localhost:${url.port + offset}${url.path ?? ''}`
62
+
54
63
  /** The `git commit` flags for the host's trailers. */
55
64
  export const trailerArgs = (config: AbleConfig) => (config.commit?.trailers ?? []).flatMap((t) => ['--trailer', t])
56
65
 
@@ -66,6 +75,8 @@ const shape: Shape = {
66
75
  copy: true,
67
76
  onCreate: true,
68
77
  onRemove: true,
78
+ onPreview: true,
79
+ url: { port: true, path: true },
69
80
  services: { '*': { start: true, stop: true, ready: true, needs: true, cwd: true } },
70
81
  resources: { '*': { take: true, auto: true, holder: true } },
71
82
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@able-autonomy/able",
3
- "version": "0.0.21",
3
+ "version": "0.2.0",
4
4
  "description": "Able's command line and the config types a host's able.config.ts uses",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,81 @@
1
+ import { expect, test } from 'bun:test'
2
+ import { copyFile, mkdtemp } from 'node:fs/promises'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import * as apply from './apply.ts'
6
+ import { compare } from './compare.ts'
7
+ import { applyTally, lineage, pick, readReport, type Report } from './report.ts'
8
+
9
+ // Able's report of 18 Nov 14:49, copied so recording doesn't touch the journal, with picks of its own and nothing applied.
10
+ async function picked() {
11
+ const path = join(await mkdtemp(join(tmpdir(), 'able-apply-')), '2026-11-18-1449.json')
12
+ await copyFile(join(import.meta.dir, '../../../journal/bloat/2026-11-18-1449.json'), path)
13
+ const report = readReport(path)
14
+ for (const r of report.rules) {
15
+ if (r.n) r.pick = r.n <= 4 ? 'yes' : r.n === 5 ? 'no' : undefined
16
+ delete r.applied
17
+ }
18
+ return { path, report }
19
+ }
20
+
21
+ test('apply lists the yes picks not applied, by kind in the order they are applied', async () => {
22
+ const { report } = await picked()
23
+ const groups = apply.todo(report)
24
+ expect(groups.map((g) => g.kind)).toEqual(['scoped', 'conflict'])
25
+ expect(groups.flatMap((g) => g.findings.map((r) => r.n))).toEqual([2, 3, 4, 1])
26
+ expect(applyTally(report).line).toBe('0 applied, 4 to apply')
27
+ })
28
+
29
+ test('recording an apply saves where it went, and refuses what was not picked yes', async () => {
30
+ const { path, report } = await picked()
31
+ expect(await apply.record(path, report, 5)).toBe('finding 5 was not picked yes')
32
+ expect(await apply.record(path, report, 99)).toBe('no finding numbered 99')
33
+ expect(await apply.record(path, report, 2)).toMatchObject({ n: 2 })
34
+ const saved = readReport(path)
35
+ expect(saved.rules.find((r) => r.n === 2)!.applied!.target).toBe('.claude/rules/decisions.md')
36
+ expect(applyTally(saved).line).toBe('1 applied, 3 to apply')
37
+ expect(saved.steps.find((s) => s.id === 'apply')?.summary).toBe('1 applied, 3 to apply')
38
+ })
39
+
40
+ test('the next report follows an applied rule to its new file, and compare sets prediction against what happened', async () => {
41
+ const { path, report } = await picked()
42
+ await apply.record(path, report, 2)
43
+ const old = readReport(path)
44
+ const moved = old.rules.find((r) => r.n === 2)!
45
+ // The next report, as a rescan after the apply would see it: the rule gone from CLAUDE.md, its words in the rules file.
46
+ const next: Report = structuredClone(old)
47
+ next.rules = next.rules.filter((r) => r.id !== moved.id && r.n !== 6)
48
+ const there = { ...moved, id: 'decisions-1-abcd', block: 'decisions-1', path: '.claude/rules/decisions.md', kind: 'keep' as const, n: undefined, pick: undefined, applied: undefined }
49
+ expect(lineage(old)(there)).toBe(moved.id)
50
+ next.rules.push({ ...there, from: moved.id })
51
+ next.impact.folders = old.impact.folders.map((f) => ({ ...f, before: f.before - moved.words }))
52
+ const c = compare(old, next)
53
+ const root = c.folders.find((f) => f.folder === '.')!
54
+ expect(root.predicted).toBe(root.before - moved.words)
55
+ expect(root.actual).toBe(root.predicted)
56
+ expect(c.applied).toEqual([
57
+ {
58
+ n: 2,
59
+ id: moved.id,
60
+ kind: 'scoped',
61
+ path: 'CLAUDE.md',
62
+ target: '.claude/rules/decisions.md',
63
+ gone: true,
64
+ became: { id: there.id, kind: 'keep', path: there.path },
65
+ state: `now keep in ${there.path}`,
66
+ },
67
+ ])
68
+ expect(c.unpicked.map((u) => u.n)).toEqual([6])
69
+ expect(c.unrecorded).toEqual([])
70
+ })
71
+
72
+ test('a yes pick gone with nothing recorded is listed apart, and an applied finding keeps its yes', async () => {
73
+ const { path, report } = await picked()
74
+ await apply.record(path, report, 2)
75
+ const old = readReport(path)
76
+ const next: Report = structuredClone(old)
77
+ next.rules = next.rules.filter((r) => r.n !== 3)
78
+ expect(compare(old, next).unrecorded.map((u) => u.n)).toEqual([3])
79
+ await pick(path, old, new Map([[2, 'no']]))
80
+ expect(readReport(path).rules.find((r) => r.n === 2)!.pick).toBe('yes')
81
+ })
@@ -0,0 +1,49 @@
1
+ // Step 10, apply: the agent makes the operator's yes picks, one kind at a time (the skill's "Step 10" section). This is
2
+ // the CLI's half: what is left to apply, in the order the agent works, and recording where each went, in the report,
3
+ // so the next report can follow each rule to its new place (report.ts, lineage). Downloaded skills are never cut into
4
+ // blocks (blocks.ts), so no finding is ever in one.
5
+
6
+ import { dim } from '../ui.ts'
7
+ import { kinds } from './kinds.ts'
8
+ import { applyTally, saveReport, type Report } from './report.ts'
9
+ import { findingLine } from './show.ts'
10
+ import type { Kind } from './types.ts'
11
+
12
+ /** The order the agent applies kinds in, each followed by the host's commit checks: deletions first (nothing can
13
+ * break), then rules moved into other files, then new checks and permissions, then the conflicts as picked. */
14
+ export const applyOrder: Kind[] = ['duplicate', 'expiring', 'discoverable', 'enforced', 'scoped', 'lint', 'check', 'guard', 'conflict']
15
+
16
+ /** The yes picks not applied yet, by kind in `applyOrder`. */
17
+ export function todo(report: Report) {
18
+ const open = report.rules.filter((r) => r.n && r.pick === 'yes' && !r.applied)
19
+ return applyOrder.map((kind) => ({ kind, findings: open.filter((r) => r.kind === kind) })).filter((g) => g.findings.length)
20
+ }
21
+
22
+ /** Step 10's view, and its JSON: the groups still to apply, with the tally. */
23
+ export const left = (report: Report) => ({ groups: todo(report), ...applyTally(report) })
24
+ export type Left = ReturnType<typeof left>
25
+
26
+ export function render({ groups, applied }: Left) {
27
+ if (!groups.length) return ` Nothing to apply: ${applied ? `all ${applied} yes picks are applied` : 'no yes picks yet (able bloat pick)'}.`
28
+ const out: string[] = []
29
+ groups.forEach((g, i) => {
30
+ out.push(` ${i + 1}. ${kinds[g.kind].letter} ${g.kind.toUpperCase()} ${g.findings.length} ${dim(`→ ${kinds[g.kind].becomes}`)}`)
31
+ for (const r of g.findings) out.push(...findingLine(r))
32
+ out.push('')
33
+ })
34
+ out.push(dim(` One kind at a time, the host's commit checks after each. Then: able bloat apply --record <n> [<target>]`))
35
+ return out.join('\n')
36
+ }
37
+
38
+ /** Records that finding `n` was applied, to `target` (its proposal's by default), and saves the report. The finding,
39
+ * or why it can't be recorded. */
40
+ export async function record(path: string, report: Report, n: number, target?: string, at = new Date()) {
41
+ const r = report.rules.find((x) => x.n === n)
42
+ if (!r) return `no finding numbered ${n}`
43
+ if (r.pick !== 'yes') return `finding ${n} was not picked yes`
44
+ const where = target ?? r.proposal?.target
45
+ if (!where) return `finding ${n} has no proposal: name where it went`
46
+ r.applied = { at: at.toISOString(), target: where }
47
+ await saveReport(path, report)
48
+ return r
49
+ }
@@ -140,13 +140,13 @@ export function blocks(root: string, entries: Entry[]): Blocks {
140
140
  }
141
141
  }
142
142
 
143
- /** One line for `able agents run`. */
143
+ /** One line for `able bloat status`. */
144
144
  export function summary(b: Blocks) {
145
145
  const files = new Set(b.blocks.map((x) => x.path)).size
146
146
  return `${b.blocks.length} blocks in ${files} file${files === 1 ? '' : 's'}${b.skipped.length ? `, ${b.skipped.length} skipped` : ''}`
147
147
  }
148
148
 
149
- /** The human view of `able agents blocks`: per file, each block's short id, lines, heading and opening words. */
149
+ /** The human view of `able bloat blocks`: per file, each block's short id, lines, heading and opening words. */
150
150
  export function render(b: Blocks) {
151
151
  const out: string[] = []
152
152
  for (const [path, list] of Map.groupBy(b.blocks, (x) => x.path)) {
@@ -186,7 +186,7 @@ export async function checks(root: string, entries: Entry[], files: string[]): P
186
186
  return { commit, merge: (config.checks?.merge ?? []).map(commandText), linters, settings, recipes, scripts }
187
187
  }
188
188
 
189
- /** One line for `able agents run`. */
189
+ /** One line for `able bloat status`. */
190
190
  export function summary(c: Checks) {
191
191
  const rules = c.linters.reduce((s, l) => s + l.rules.length, 0)
192
192
  const deny = c.settings.reduce((s, x) => s + x.deny.length, 0)
@@ -196,7 +196,7 @@ export function summary(c: Checks) {
196
196
 
197
197
  const list = (names: string[], max = 64) => clip(names.join(', '), max)
198
198
 
199
- /** The human view of `able agents checks`. */
199
+ /** The human view of `able bloat checks`. */
200
200
  export function render(c: Checks) {
201
201
  const out: string[] = []
202
202
  out.push(' COMMIT CHECKS (able.config.ts, per folder)')
@@ -0,0 +1,63 @@
1
+ // Step 11, compare: a report against the one before it, once picks were applied in between. Read-only, from the two
2
+ // report files: the words at start per folder as predicted (the old report's, less what was applied) against the
3
+ // actual (the new report's), what happened to each applied finding, and any finding that went without being picked.
4
+
5
+ import { dim, green, red } from '../ui.ts'
6
+ import { atStart, reportCode, type Finding, type Report } from './report.ts'
7
+ import { clip, fit, n } from './scan.ts'
8
+ import type { Comparison } from './types.ts'
9
+
10
+ export function compare(old: Report, next: Report): Comparison {
11
+ const nextIds = new Set(next.rules.map((r) => r.id))
12
+ const became = new Map(next.rules.flatMap((r) => (r.from ? [[r.from, r] as const] : [])))
13
+ const applied = old.rules.filter((r): r is Finding & { n: number; applied: NonNullable<Finding['applied']> } => Boolean(r.n && r.applied))
14
+ const starts = atStart(old.load, old.blocks)
15
+ const actual = new Map(next.impact.folders.map((f) => [f.folder, f.before]))
16
+ const gone = (which: (r: Finding) => boolean) => old.rules.filter((r) => r.n && which(r) && !nextIds.has(r.id)).map((r) => ({ n: r.n!, id: r.id, kind: r.kind, path: r.path, text: r.text }))
17
+ return {
18
+ folders: old.impact.folders.map((f) => ({
19
+ folder: f.folder,
20
+ before: f.before,
21
+ predicted: f.before - applied.filter((r) => starts(r, f.folder)).reduce((s, r) => s + r.words, 0),
22
+ actual: actual.get(f.folder) ?? null,
23
+ })),
24
+ applied: applied.map((r) => {
25
+ const b = became.get(r.id)
26
+ const gone = !nextIds.has(r.id)
27
+ const state = !gone ? 'still there' : b ? `now ${b.kind} in ${b.path}` : `gone, to ${r.applied.target}`
28
+ return { n: r.n, id: r.id, kind: r.kind, path: r.path, target: r.applied.target, gone, ...(b && { became: { id: b.id, kind: b.kind, path: b.path } }), state }
29
+ }),
30
+ unpicked: gone((r) => r.pick !== 'yes'),
31
+ unrecorded: gone((r) => r.pick === 'yes' && !r.applied),
32
+ }
33
+ }
34
+
35
+ export function summary(c: Comparison) {
36
+ const root = c.folders.find((f) => f.folder === '.')
37
+ if (!c.applied.length) return 'nothing applied between the two latest'
38
+ if (!root || root.actual === null) return `${c.applied.length} applied`
39
+ return `root ${n(root.before)} → ${n(root.actual)} words (predicted ${n(root.predicted)}), ${c.applied.length} applied`
40
+ }
41
+
42
+ export function render(c: Comparison, names: { old: string; next: string }) {
43
+ const label = (name: string) => `${reportCode(name)} ${name}`
44
+ const out = [` ${label(names.old)} → ${label(names.next)}`, '', ' WORDS AT START, BY FOLDER (host files)']
45
+ out.push(` ${'folder'.padEnd(24)} ${'before'.padStart(7)} ${'predicted'.padStart(9)} ${'actual'.padStart(7)}`)
46
+ for (const f of c.folders) {
47
+ const off = f.actual === null ? '' : f.actual <= f.predicted ? green(' ✓') : red(` +${n(f.actual - f.predicted)}`)
48
+ out.push(` ${clip(f.folder === '.' ? '(root)' : f.folder, 24).padEnd(24)} ${n(f.before).padStart(7)} ${n(f.predicted).padStart(9)} ${(f.actual === null ? '–' : n(f.actual)).padStart(7)}${off}`)
49
+ }
50
+ out.push('', ` APPLIED ${c.applied.length}`)
51
+ for (const a of c.applied) {
52
+ out.push(` ${String(a.n).padStart(3)} ${a.kind.padEnd(12)} ${fit(a.path, 34).padEnd(34)} ${a.gone ? clip(a.state, 60) : red(a.state)}`)
53
+ }
54
+ if (!c.applied.length) out.push(dim(' none: nothing was recorded with able bloat apply --record'))
55
+ const gone = (title: string, why: string, list: Comparison['unpicked']) => {
56
+ if (!list.length) return
57
+ out.push('', ` ${title} ${list.length} ${dim(why)}`)
58
+ for (const u of list) out.push(` ${String(u.n).padStart(3)} ${u.kind.padEnd(12)} ${fit(u.path, 34).padEnd(34)} "${clip(u.text.replace(/\s+/g, ' '), 40)}"`)
59
+ }
60
+ gone('GONE, NOT RECORDED', 'picked yes and gone, but no able bloat apply --record says where', c.unrecorded)
61
+ gone('GONE WITHOUT A YES', 'a rule lost, or its words changed so its id did', c.unpicked)
62
+ return out.join('\n')
63
+ }
@@ -9,13 +9,17 @@ import type { RuleFinding, Proposal, Rule } from './types.ts'
9
9
 
10
10
  export type { RuleFinding, Proposal, Rule }
11
11
 
12
- export const format = 'able.agents.findings@1'
12
+ export const format = 'able.bloat.findings@1'
13
+ /** The same findings from before the rename (`able agents`), still read: an agent's work is not thrown away. */
14
+ const legacyFormat = 'able.agents.findings@1'
13
15
 
14
16
  /** Where the skill keeps its findings between steps: Able's per-checkout state, gitignored. */
15
- export const findingsPath = '.able/agents/findings.json'
17
+ export const findingsPath = '.able/bloat/findings.json'
18
+ /** Where they were kept before the rename, read when the new place has none. */
19
+ export const legacyFindingsPath = '.able/agents/findings.json'
16
20
 
17
21
  export interface Findings {
18
- format: typeof format
22
+ format: typeof format | typeof legacyFormat
19
23
  findings: { block: string; rules: RuleFinding[] }[]
20
24
  }
21
25
 
@@ -44,11 +48,11 @@ export function check(findings: Findings, blocks: Block[]): Checked {
44
48
  const errors: string[] = []
45
49
  const rules: Rule[] = []
46
50
  const counts = new Map<string, number>()
47
- if (findings.format !== format) errors.push(`format is ${JSON.stringify(findings.format)}, expected ${format}`)
51
+ if (findings.format !== format && findings.format !== legacyFormat) errors.push(`format is ${JSON.stringify(findings.format)}, expected ${format}`)
48
52
  for (const { block: id, rules: found = [] } of findings.findings ?? []) {
49
53
  const block = byId.get(id)
50
54
  if (!block) {
51
- errors.push(`${id}: no such block (cut again with able agents blocks)`)
55
+ errors.push(`${id}: no such block (cut again with able bloat blocks)`)
52
56
  continue
53
57
  }
54
58
  for (const r of found) {
@@ -81,13 +85,13 @@ export function readFindings(path: string): Findings | undefined {
81
85
  /** Rules step 6 still owes a proposal: every rule not kept. */
82
86
  export const unproposed = (c: Checked) => c.rules.filter((r) => r.kind !== 'keep' && !r.proposal)
83
87
 
84
- /** One line for `able agents run` at step 6. */
88
+ /** One line for `able bloat status` at step 6. */
85
89
  export const proposeSummary = (c: Checked) => {
86
90
  const owed = c.rules.filter((r) => r.kind !== 'keep').length
87
91
  return `${owed - unproposed(c).length} of ${owed} proposed`
88
92
  }
89
93
 
90
- /** One line for `able agents run`. */
94
+ /** One line for `able bloat status`. */
91
95
  export function summary(c: Checked) {
92
96
  const byKind = Object.keys(kinds)
93
97
  .map((k) => [k, c.rules.filter((r) => r.kind === k).length] as const)
@@ -33,7 +33,7 @@ const centre = (s: string) => {
33
33
  return `${' '.repeat(left)}${t}${' '.repeat(box - t.length - left)}`
34
34
  }
35
35
 
36
- /** `able agents scan --grid`: the files as a periodic table, one box each. */
36
+ /** `able bloat scan --grid`: the files as a periodic table, one box each. */
37
37
  export function files(entries: Entry[]) {
38
38
  const out: string[] = []
39
39
  const sorted = [...entries].sort((a, b) => order.indexOf(a.kind) - order.indexOf(b.kind))
@@ -60,7 +60,7 @@ const greens = [237, 22, 28, 34, 40]
60
60
  const plain = ['·', '░', '▒', '▓', '█']
61
61
  const square = (level: number) => (tty ? paint256(greens[level])('■') : plain[level])
62
62
 
63
- /** `able agents blocks --grid`: per file, a card with a row per section and one square per block. */
63
+ /** `able bloat blocks --grid`: per file, a card with a row per section and one square per block. */
64
64
  export function blocks(b: Blocks) {
65
65
  const out: string[] = []
66
66
  for (const [path, list] of Map.groupBy(b.blocks, (x) => x.path)) {
@@ -92,7 +92,7 @@ export function blocks(b: Blocks) {
92
92
  const shade = (count: number, present = count > 0) => (!present ? 0 : count < 2 ? 1 : count < 10 ? 2 : count < 50 ? 3 : 4)
93
93
  const sum = (ns: number[]) => ns.reduce((a, b) => a + b, 0)
94
94
 
95
- /** `able agents checks --grid`: per folder, which tools enforce anything there, shaded by how much. */
95
+ /** `able bloat checks --grid`: per folder, which tools enforce anything there, shaded by how much. */
96
96
  export function enforcement(c: Checks, entries: Entry[]) {
97
97
  const folders = [...new Set(['.', ...Object.keys(c.commit), ...entries.filter((e) => e.kind === 'instructions').map((e) => dirname(e.path))])].sort()
98
98
  // A config belongs to the nearest folder row at or above it (outs/android/outstanding/detekt.yml is outs/android's)
@@ -137,7 +137,7 @@ export function enforcement(c: Checks, entries: Entry[]) {
137
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
138
  const mark = (kind?: Kind) => (kind ? paint256(kindColour[kind])(kinds[kind].letter) : '·')
139
139
 
140
- /** `able agents classify`: per file, a row per section and one mark per rule, by kind; `·` a block that is all context. */
140
+ /** `able bloat classify`: per file, a row per section and one mark per rule, by kind; `·` a block that is all context. */
141
141
  export function byKind(b: Blocks, c: Checked) {
142
142
  const out: string[] = []
143
143
  const rulesOf = Map.groupBy(c.rules, (r) => r.block)
@@ -0,0 +1,258 @@
1
+ // able bloat: the bloat diagnostic. What a host's agent files load, the rules in them, and where each rule belongs, as
2
+ // a report (knowledge/product/modules/bloat.md). `able agents` is the same, its name before.
3
+ //
4
+ // able bloat status every step in order, one line each, for the latest report
5
+ // able bloat scan [--json|--grid] step 1: every agent file, its kind and size (--grid: one box per file)
6
+ // able bloat load [--json] step 2: when each file loads, and the words at start per folder
7
+ // able bloat blocks [--json|--grid] step 3: the files cut into blocks, with spans and stable ids (--grid: one square per block)
8
+ // able bloat checks [--json|--grid] step 4: what the host already enforces (--grid: per folder, per tool)
9
+ // able bloat classify [--json] step 5's result: the agent's findings checked against the blocks, drawn by kind
10
+ // able bloat propose [--json] step 6's result: each rule not kept with its proposal, or what is still owed
11
+ // able bloat report step 7: checks the findings and writes a report to <journal>/bloat/<date>-<hhmm>.json
12
+ // able bloat show [<report>] [--step <n>|--json] step 8: a report read back from its file (the latest by default)
13
+ // able bloat history [--json] every report, oldest first, one line each: the picker and the trend
14
+ // able bloat pick [<yes|no> <n>…]… [--report <report>] step 9: the operator's picks in the latest report, or the one named
15
+ // (no arguments on a terminal: checkboxes)
16
+ // able bloat apply [--json] step 10: the yes picks not applied yet, in the order the agent applies them
17
+ // able bloat apply --record <n> [<target>] step 10: finding n is applied, to target (its proposal's by default)
18
+ // able bloat compare [<report>] [<new>] [--json] step 11: a report against the one before it (the latest by default),
19
+ // or two reports named, old then new
20
+ //
21
+ // Read-only on the host's agent files: the only files written are the findings (by the skill) and the report. The
22
+ // agent changes them at step 10, as the skill says, only when the operator asks.
23
+
24
+ import { basename, join, relative } from 'node:path'
25
+ import { hostRoot, loadConfig } from '../../config.ts'
26
+ import { confirm, dim, fail, green, tty } from '../ui.ts'
27
+ import * as apply from './apply.ts'
28
+ import * as blocks from './blocks.ts'
29
+ import * as checks from './checks.ts'
30
+ import * as compare from './compare.ts'
31
+ import * as findings from './findings.ts'
32
+ import * as grid from './grid.ts'
33
+ import * as load from './load.ts'
34
+ import { pickInteractive } from './picker.ts'
35
+ import * as report from './report.ts'
36
+ import * as scan from './scan.ts'
37
+ import * as show from './show.ts'
38
+ import { steps, who } from './steps.ts'
39
+ import type { Compared } from './types.ts'
40
+
41
+ const [sub = '', ...args] = process.argv.slice(3)
42
+ const valued = ['--step', '--report', '--record']
43
+ const names = args.filter((a, i) => !a.startsWith('--') && !valued.includes(args[i - 1] ?? ''))
44
+ const option = (name: string) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined)
45
+ const stepArg = option('--step')
46
+ const json = args.includes('--json')
47
+ const asGrid = args.includes('--grid')
48
+ const root = hostRoot()
49
+
50
+ /** Each step's result, worked out once and shared by the steps after it. */
51
+ const once = <T>(f: () => T) => {
52
+ let value: { v: T } | undefined
53
+ return () => (value ??= { v: f() }).v
54
+ }
55
+ const files = once(() => scan.listFiles(root))
56
+ const entries = once(() => scan.scan(root, files()))
57
+
58
+ 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'))
59
+
60
+ /** A built step: its result, the line `status` prints, and its views. */
61
+ interface Built<T> {
62
+ result: () => T | Promise<T>
63
+ summary: (r: T) => string
64
+ render: (r: T) => string
65
+ grid?: (r: T) => string
66
+ }
67
+ const built = <T>(b: Built<T>) => b as Built<unknown>
68
+
69
+ const cut = once(() => blocks.blocks(root, entries()))
70
+ const classified = once(() => {
71
+ const f = findings.readFindings(join(root, findings.findingsPath)) ?? findings.readFindings(join(root, findings.legacyFindingsPath))
72
+ return f && findings.check(f, cut().blocks)
73
+ })
74
+
75
+ const journal = once(async () => (await loadConfig(root)).journal)
76
+ /** The latest report, or the one named on the command line: `show <report>`, `pick --report <report>`. */
77
+ const latest = once(async () => {
78
+ const path = report.findReport(root, await journal(), sub === 'show' ? names[0] : option('--report'))
79
+ return path ? { path, report: report.readReport(path) } : undefined
80
+ })
81
+ type Latest = Awaited<ReturnType<typeof latest>>
82
+ const requireLatest = async () => (await latest()) ?? fail(option('--report') || (sub === 'show' && names[0]) ? 'no such report' : 'no report yet: able bloat report writes one')
83
+ /** Steps 7 to 9 all show the latest report; only their line in `status` differs. */
84
+ const latestView = (summary: (l: NonNullable<Latest>) => string, none: string) =>
85
+ built<Latest>({ result: latest, summary: (l) => (l ? summary(l) : none), render: (l) => (l ? show.render(l.report, l.path, root) : ' No report yet.') })
86
+
87
+ const views: Record<string, Built<unknown>> = {
88
+ scan: built({ result: entries, summary: scan.summary, render: (e) => `${scope}\n\n${scan.render(e)}`, grid: (e) => `${scope}\n\n${grid.files(e)}` }),
89
+ load: built({ result: once(() => load.load(root, entries())), summary: load.summary, render: load.render }),
90
+ blocks: built({ result: cut, summary: blocks.summary, render: blocks.render, grid: grid.blocks }),
91
+ checks: built({ result: once(() => checks.checks(root, entries(), files())), summary: checks.summary, render: checks.render, grid: (c) => grid.enforcement(c, entries()) }),
92
+ classify: built({
93
+ result: classified,
94
+ summary: (c) => (c ? findings.summary(c) : `not run: the skill writes ${findings.findingsPath}`),
95
+ render: (c) =>
96
+ c
97
+ ? [grid.byKind(cut(), c), ...(c.errors.length ? ['', ' ERRORS', ...c.errors.map((e) => ` ${e}`)] : [])].join('\n')
98
+ : ` No findings yet: the skill (able-clean-agent-bloat) writes ${findings.findingsPath} at step 5.`,
99
+ }),
100
+ propose: built({
101
+ result: classified,
102
+ summary: (c) => (c ? findings.proposeSummary(c) : 'waits for classify'),
103
+ render: (c) =>
104
+ c
105
+ ? c.rules
106
+ .filter((r) => r.kind !== 'keep')
107
+ .map(
108
+ (r) => ` ${r.kind.padEnd(12)} ${r.id}
109
+ ${r.proposal ? `→ ${r.proposal.target}: ${r.proposal.change}` : dim('no proposal yet')}`,
110
+ )
111
+ .join('\n')
112
+ : ' No findings yet.',
113
+ }),
114
+ report: latestView((l) => `latest: ${relative(root, l.path)}`, 'not run yet'),
115
+ show: latestView(() => 'able bloat show', 'no report yet'),
116
+ pick: latestView((l) => report.tally(l.report).line, 'no report yet'),
117
+ apply: built<apply.Left | undefined>({
118
+ result: once(async () => {
119
+ const l = await latest()
120
+ return l && apply.left(l.report)
121
+ }),
122
+ summary: (t) => (t ? t.line : 'no report yet'),
123
+ render: (t) => (t ? apply.render(t) : ' No report yet.'),
124
+ }),
125
+ compare: built({
126
+ result: pair,
127
+ summary: (p) => (p ? compare.summary(p.c) : 'waits for a second report'),
128
+ render: (p) => (p ? compare.render(p.c, p.names) : ' Nothing to compare: one report so far.'),
129
+ }),
130
+ }
131
+
132
+ /** Step 11's two reports: `compare <old> <new>`, or one report (the latest by default) and the one before it. */
133
+ async function pair(): Promise<Compared | undefined> {
134
+ const dir = await journal()
135
+ const all = report.reports(root, dir)
136
+ const find = (name: string) => report.findReport(root, dir, name)
137
+ const next = names[1] ? find(names[1]) : names[0] ? find(names[0]) : all.at(-1)
138
+ const old = names[1] ? find(names[0]!) : next && all[all.indexOf(next) - 1]
139
+ if (!old || !next) return
140
+ const name = (p: string) => basename(p, '.json')
141
+ return { c: compare.compare(report.readReport(old), report.readReport(next)), names: { old: name(old), next: name(next) } }
142
+ }
143
+
144
+ /** Step 10's record: finding n was applied, to the target named or its proposal's. */
145
+ async function recordApplied() {
146
+ const l = await requireLatest()
147
+ const n = Number(option('--record'))
148
+ if (!Number.isInteger(n) || n < 1) fail('usage: able bloat apply --record <n> [<target>]')
149
+ const r = await apply.record(l.path, l.report, n, names[0])
150
+ if (typeof r === 'string') fail(r)
151
+ if (json) return console.log(JSON.stringify({ report: relative(root, l.path), n, applied: r.applied }))
152
+ console.log(`\n ${green('recorded')} ${n} applied, to ${r.applied!.target} ${dim(report.applyTally(l.report).line)}\n`)
153
+ }
154
+
155
+ /** Step 7: refuses while the findings owe anything, then writes the report and shows it. */
156
+ async function writeReport() {
157
+ const c = classified()
158
+ if (!c) fail(`no findings: the skill writes ${findings.findingsPath} at steps 5 and 6`)
159
+ const owed = report.problems(c)
160
+ if (owed.length) fail(`the findings are not ready:\n${owed.map((p) => ` ${p}`).join('\n')}`)
161
+ const summaries: Record<string, string> = {}
162
+ for (const id of ['scan', 'load', 'blocks', 'checks', 'classify', 'propose']) summaries[id] = views[id].summary(await views[id].result())
163
+ const at = new Date()
164
+ const path = report.reportPath(root, await journal(), at)
165
+ const before = report.findReport(root, await journal())
166
+ const written = report.build({
167
+ scan: entries(),
168
+ load: (await views.load.result()) as load.LoadMap,
169
+ blocks: cut(),
170
+ checks: (await views.checks.result()) as checks.Checks,
171
+ checked: c,
172
+ summaries,
173
+ root,
174
+ path,
175
+ at,
176
+ previous: before ? report.readReport(before) : undefined,
177
+ })
178
+ await report.saveReport(path, written)
179
+ console.log(`\n ${green('wrote')} ${relative(root, path)}\n\n${show.render(written, path, root)}\n`)
180
+ }
181
+
182
+ /** Step 9: on a terminal with no arguments, the checkbox picker; otherwise `pick yes 1 3 5`, `pick no 2`, or both at
183
+ * once, `pick yes 1 3 no 2` (the dashboard's page records its checkboxes this way). */
184
+ async function writePicks() {
185
+ const l = await requireLatest()
186
+ let answers: Map<number, 'yes' | 'no'> | undefined
187
+ if (!names.length && tty && process.stdin.isTTY) {
188
+ answers = await pickInteractive(l.report, l.path, root)
189
+ if (!answers) return console.log('\n Nothing recorded.\n')
190
+ } else if (names[0] === 'yes' || names[0] === 'no') {
191
+ answers = new Map()
192
+ let answer: 'yes' | 'no' = names[0]
193
+ for (const x of names.slice(1))
194
+ if (x === 'yes' || x === 'no') answer = x
195
+ else if (/^\d+$/.test(x)) answers.set(Number(x), answer)
196
+ else fail(`not a finding number: ${x}`)
197
+ } else fail('usage: able bloat pick [<yes|no> <n>…]… [--report <report>] (no arguments on a terminal opens the checkboxes)')
198
+ const unknown = await report.pick(l.path, l.report, answers)
199
+ if (unknown.length) fail(`no finding numbered ${unknown.join(', ')} in ${relative(root, l.path)}`)
200
+ const { yes, no, open } = report.tally(l.report)
201
+ if (json) return console.log(JSON.stringify({ report: relative(root, l.path), yes, no, open }))
202
+ console.log(`\n ${green('recorded')} ${yes} yes, ${no} no, ${open} not picked, in ${relative(root, l.path)}\n`)
203
+ }
204
+
205
+ async function status() {
206
+ console.log()
207
+ for (const step of steps) {
208
+ const label = ` ${String(step.n).padStart(2)} ${who[step.kind]} ${step.id.padEnd(10)}`
209
+ const view = views[step.id]
210
+ if (!view) {
211
+ console.log(`${label} ${dim('not built yet')}`)
212
+ continue
213
+ }
214
+ const started = performance.now()
215
+ const result = await view.result()
216
+ const summary = view.summary(result)
217
+ const done = result !== undefined ? `${green('ok')} ${dim(`${Math.round(performance.now() - started)}ms`)}` : ''
218
+ console.log(`${label} ${result !== undefined ? summary.padEnd(44) : dim(summary)} ${done}`.trimEnd())
219
+ }
220
+ console.log(dim('\n M mechanical (the CLI) · A agent · O operator (you)\n'))
221
+ // On a terminal, step 9 follows on: the latest report's unpicked findings, as checkboxes.
222
+ const l = await latest()
223
+ if (l && tty && process.stdin.isTTY && report.tally(l.report).open && confirm('Pick now?')) await writePicks()
224
+ }
225
+
226
+ // `run` was its name before the report vocabulary.
227
+ if (sub === 'status' || sub === 'run') await status()
228
+ else if (sub === 'report') await writeReport()
229
+ else if (sub === 'pick') await writePicks()
230
+ else if (sub === 'apply' && args.includes('--record')) await recordApplied()
231
+ else if (sub === 'history') {
232
+ const lines = report.history(root, await journal())
233
+ if (json) console.log(JSON.stringify(lines))
234
+ else {
235
+ console.log()
236
+ for (const h of lines)
237
+ console.log(
238
+ ` ${h.code} ${h.name} ${String(h.files).padStart(3)} files ${String(h.rules).padStart(4)} rules ${String(h.start.before).padStart(6)} → ${String(h.start.after).padStart(6)} words at start ${h.picks.yes + h.picks.no} of ${h.picks.numbered} picked`,
239
+ )
240
+ console.log(lines.length ? '' : ' No report yet.\n')
241
+ }
242
+ } else if (sub === 'show' && stepArg) {
243
+ const l = await requireLatest()
244
+ const id = l.report.steps.find((s) => String(s.n) === stepArg || s.id === stepArg)?.id
245
+ if (!id) fail(`no step ${stepArg}: 1 to ${l.report.steps.length}, or a name`)
246
+ console.log(`\n${show.step(l.report, id)}\n`)
247
+ } else if (sub === 'show' && json) console.log(JSON.stringify((await requireLatest()).report))
248
+ else if (views[sub]) {
249
+ const view = views[sub]
250
+ const r = await view.result()
251
+ // Nothing to show is `null` in JSON, so a reader always gets JSON.
252
+ console.log(json ? JSON.stringify(r ?? null) : `\n${asGrid && view.grid ? view.grid(r) : view.render(r)}\n`)
253
+ } else {
254
+ console.error(`usage: able bloat status | ${Object.keys(views).join(' | ')} [--json] [--grid]`)
255
+ process.exit(sub ? 1 : 0)
256
+ }
257
+
258
+ export {}