@able-autonomy/able 0.0.21 → 0.2.1
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 +10 -2
- package/config.ts +11 -0
- package/package.json +1 -1
- package/src/audit/bloat/apply.test.ts +81 -0
- package/src/audit/bloat/apply.ts +49 -0
- package/src/{agents → audit/bloat}/blocks.ts +2 -2
- package/src/{agents → audit/bloat}/checks.ts +3 -3
- package/src/audit/bloat/compare.ts +63 -0
- package/src/{agents → audit/bloat}/findings.ts +11 -7
- package/src/{agents → audit/bloat}/grid.ts +6 -6
- package/src/audit/bloat/index.ts +258 -0
- package/src/{agents → audit/bloat}/load.ts +2 -2
- package/src/{agents → audit/bloat}/picker.ts +4 -4
- package/src/audit/bloat/report.ts +286 -0
- package/src/{agents → audit/bloat}/scan.ts +3 -3
- package/src/audit/bloat/show.ts +79 -0
- package/src/audit/bloat/steps.ts +32 -0
- package/src/{agents → audit/bloat}/types.ts +48 -3
- package/src/audit/index.ts +19 -0
- package/src/commit.ts +2 -1
- package/src/git.ts +43 -2
- package/src/push.ts +2 -1
- package/src/ui.ts +3 -0
- package/src/workspaces/fixture.ts +49 -0
- package/src/workspaces/index.ts +3 -1
- package/src/workspaces/ls.ts +56 -11
- package/src/workspaces/merge.ts +31 -15
- package/src/workspaces/new.ts +17 -15
- package/src/workspaces/overlap.test.ts +53 -0
- package/src/workspaces/overlap.ts +86 -0
- package/src/workspaces/preview.test.ts +81 -0
- package/src/workspaces/preview.ts +162 -0
- package/src/workspaces/refresh.ts +26 -24
- package/src/workspaces/rm.ts +6 -1
- package/src/workspaces/services.ts +2 -2
- package/src/workspaces/state.ts +56 -9
- package/src/workspaces/trunk.test.ts +88 -0
- package/sync.ts +5 -2
- package/src/agents/index.ts +0 -198
- package/src/agents/report.ts +0 -211
- package/src/agents/show.ts +0 -73
- package/src/agents/steps.ts +0 -32
- /package/src/{agents → audit/bloat}/kinds.ts +0 -0
package/src/workspaces/state.ts
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
// Which workspaces exist comes from git (decision 92): every worktree on `feat/<slug>`. What git can't know, a
|
|
2
2
|
// workspace's port offset and creation date and who holds each shared resource, is in `.able/workspaces.json` in the
|
|
3
3
|
// main checkout.
|
|
4
|
+
//
|
|
5
|
+
// One more checkout is registered there: the combined preview, slug `all` (preview.ts), a detached worktree with
|
|
6
|
+
// `kind: 'preview'`, its own offset and its last build. It is a checkout of its own, never the main one, and never a
|
|
7
|
+
// workspace anything is merged from.
|
|
4
8
|
|
|
5
|
-
import { existsSync } from 'node:fs'
|
|
9
|
+
import { copyFileSync, existsSync, mkdirSync } from 'node:fs'
|
|
6
10
|
import { dirname, join, resolve } from 'node:path'
|
|
7
11
|
import { loadConfig, type AbleConfig } from '../../config.ts'
|
|
8
12
|
import { failOnMerge, git } from '../git.ts'
|
|
@@ -10,6 +14,9 @@ import type { Place } from '../run.ts'
|
|
|
10
14
|
import { fail } from '../ui.ts'
|
|
11
15
|
|
|
12
16
|
export const branchOf = (slug: string) => `feat/${slug}`
|
|
17
|
+
|
|
18
|
+
/** The combined preview's slug, reserved: no workspace can take it. */
|
|
19
|
+
export const PREVIEW = 'all'
|
|
13
20
|
const slugOf = (ref: string) => ref.match(/^refs\/heads\/feat\/(.+)$/)?.[1]
|
|
14
21
|
|
|
15
22
|
export interface Workspace {
|
|
@@ -18,10 +25,17 @@ export interface Workspace {
|
|
|
18
25
|
path: string
|
|
19
26
|
portOffset: number
|
|
20
27
|
createdAt?: string
|
|
28
|
+
/** Set only on the combined preview. */
|
|
29
|
+
kind?: 'preview'
|
|
21
30
|
}
|
|
22
31
|
|
|
32
|
+
/** The preview's last build: what went in, and what was left out with whom it conflicts. */
|
|
33
|
+
export type Build = { at: string; commit: string; base: string; included: { slug: string; tip: string }[]; left: { slug: string; tip: string; with: string[] }[] }
|
|
34
|
+
|
|
35
|
+
type Entry = { portOffset: number; createdAt: string; kind?: 'preview'; path?: string; build?: Build }
|
|
36
|
+
|
|
23
37
|
/** What git can't know: each workspace's offset and creation date, and each shared resource's holders, the current one last (89, 95). */
|
|
24
|
-
export type State = { workspaces: Record<string,
|
|
38
|
+
export type State = { workspaces: Record<string, Entry>; holders?: Record<string, string[]> }
|
|
25
39
|
|
|
26
40
|
const statePath = (main: string) => join(main, '.able', 'workspaces.json')
|
|
27
41
|
|
|
@@ -41,28 +55,56 @@ export async function running(checkout: string): Promise<Record<string, { pid: n
|
|
|
41
55
|
return Object.fromEntries(Object.entries(saved as Record<string, { pid: number; startedAt: string }>).filter(([, s]) => alive(s.pid)))
|
|
42
56
|
}
|
|
43
57
|
|
|
44
|
-
/**
|
|
58
|
+
/** Copies the host's `copy` files, gitignored ones a worktree can't inherit, from the main checkout into a new one. */
|
|
59
|
+
export function copyFiles(main: string, path: string, rels: string[] = []) {
|
|
60
|
+
for (const rel of rels) {
|
|
61
|
+
if (!existsSync(join(main, rel))) continue
|
|
62
|
+
mkdirSync(dirname(join(path, rel)), { recursive: true })
|
|
63
|
+
copyFileSync(join(main, rel), join(path, rel))
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The first port offset no checkout holds; 0 for every checkout when the host gives no `ports`. */
|
|
68
|
+
export function freeOffset(state: State, ports?: { step: number; max: number }) {
|
|
69
|
+
if (!ports) return 0
|
|
70
|
+
const taken = new Set(Object.values(state.workspaces).map((w) => w.portOffset))
|
|
71
|
+
return Array.from({ length: ports.max }, (_, i) => (i + 1) * ports.step).find((o) => !taken.has(o)) ?? fail('no free port offset; remove a workspace first')
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Every workspace git knows, with what the state file adds, and the preview: from its entry, even when its folder
|
|
75
|
+
* is gone (it still holds its offset, and `ws rm all` clears it). */
|
|
45
76
|
export async function workspaces(main: string, state?: State): Promise<Workspace[]> {
|
|
46
77
|
const saved = (state ?? (await readState(main))).workspaces
|
|
78
|
+
const preview = saved[PREVIEW]?.kind === 'preview' ? saved[PREVIEW] : undefined
|
|
79
|
+
const previewAt = preview?.path ? resolve(preview.path) : undefined
|
|
47
80
|
// `-z`: fields end in NUL, records in an empty field, so paths with spaces or newlines survive.
|
|
48
|
-
|
|
81
|
+
const listed = git(main, 'worktree', 'list', '--porcelain', '-z')
|
|
49
82
|
.split('\0\0')
|
|
50
|
-
.flatMap((record) => {
|
|
83
|
+
.flatMap((record): Workspace[] => {
|
|
51
84
|
const fields = record.split('\0')
|
|
52
85
|
const path = fields.find((f) => f.startsWith('worktree '))?.slice('worktree '.length)
|
|
53
86
|
const slug = slugOf(fields.find((f) => f.startsWith('branch '))?.slice('branch '.length) ?? '')
|
|
54
|
-
if (!path || !slug) return []
|
|
87
|
+
if (!path || !slug || resolve(path) === previewAt) return []
|
|
55
88
|
return [{ slug, branch: branchOf(slug), path, portOffset: saved[slug]?.portOffset ?? 0, createdAt: saved[slug]?.createdAt }]
|
|
56
89
|
})
|
|
90
|
+
return preview && previewAt ? [...listed, { slug: PREVIEW, branch: '', path: previewAt, portOffset: preview.portOffset, createdAt: preview.createdAt, kind: 'preview' }] : listed
|
|
57
91
|
}
|
|
58
92
|
|
|
93
|
+
/** Oldest first, the preview last: the order checkouts are listed and merged in. */
|
|
94
|
+
export const byAge = (a: Workspace, b: Workspace) => Number(Boolean(a.kind)) - Number(Boolean(b.kind)) || (a.createdAt ?? '').localeCompare(b.createdAt ?? '')
|
|
95
|
+
|
|
96
|
+
/** The open workspaces of a list, oldest first, without the preview: the ones work is merged from. */
|
|
97
|
+
export const openOf = (list: Workspace[]) => list.filter((w) => !w.kind && existsSync(w.path)).sort(byAge)
|
|
98
|
+
|
|
99
|
+
export const openWorkspaces = async (main: string, state?: State) => openOf(await workspaces(main, state))
|
|
100
|
+
|
|
59
101
|
/** The main checkout, at offset 0, and every workspace. */
|
|
60
102
|
export const checkouts = async (main: string, state?: State): Promise<Place[]> => [
|
|
61
103
|
{ slug: 'main', path: main, portOffset: 0, main },
|
|
62
104
|
...(await workspaces(main, state)).map((w) => ({ slug: w.slug, path: w.path, portOffset: w.portOffset, main })),
|
|
63
105
|
]
|
|
64
106
|
|
|
65
|
-
/** The checkout the command runs in. The main checkout is `main`, at offset 0, and not a workspace
|
|
107
|
+
/** The checkout the command runs in. The main checkout is `main`, at offset 0, and not a workspace; the preview answers as `all`. */
|
|
66
108
|
export async function current(cwd = process.cwd()) {
|
|
67
109
|
const [common = '.git', root = cwd, branch = ''] = git(cwd, 'rev-parse', '--git-common-dir', '--show-toplevel', '--abbrev-ref', 'HEAD').split('\n')
|
|
68
110
|
const main = dirname(resolve(cwd, common))
|
|
@@ -70,9 +112,14 @@ export async function current(cwd = process.cwd()) {
|
|
|
70
112
|
return ws ? { ...ws, main, isWorkspace: true } : { slug: 'main', branch, path: root, portOffset: 0, main, isWorkspace: false }
|
|
71
113
|
}
|
|
72
114
|
|
|
73
|
-
/**
|
|
74
|
-
export
|
|
115
|
+
/** Fails in the preview: it is rebuilt by `able ws preview`, never committed to, pushed or merged from. */
|
|
116
|
+
export const refuseInPreview = (at: { kind?: string }, what: string) =>
|
|
117
|
+
at.kind === 'preview' && fail(`${what} doesn't run in the preview: it is read-only, rebuilt by able ws preview; make the change in its workspace`)
|
|
118
|
+
|
|
119
|
+
/** The workspace a command runs in, with its config; fails in the main checkout, the preview, or during a merge. */
|
|
120
|
+
export async function inWorkspace(what: string): Promise<{ ws: Awaited<ReturnType<typeof current>>; config: AbleConfig }> {
|
|
75
121
|
const ws = await current()
|
|
122
|
+
refuseInPreview(ws, what)
|
|
76
123
|
if (!ws.isWorkspace) fail('not inside a workspace')
|
|
77
124
|
failOnMerge(ws.path)
|
|
78
125
|
return { ws, config: await loadConfig(ws.path) }
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// The trunk rule: every command means `origin/<trunk>`, and commits only on `local <trunk>` never leave inside a merge.
|
|
2
|
+
|
|
3
|
+
import { expect, test } from 'bun:test'
|
|
4
|
+
import { commit, git, host, run } from './fixture.ts'
|
|
5
|
+
|
|
6
|
+
test('ws new warns about unpushed commits on local main, and cuts from origin/main', () => {
|
|
7
|
+
const h = host()
|
|
8
|
+
commit(h.main, 'local.txt', 'mine\n', 'local only')
|
|
9
|
+
const r = run(h.main, 'ws', 'new', 'one', '--no-brief')
|
|
10
|
+
expect(r.code).toBe(0)
|
|
11
|
+
expect(r.out).toContain('1 commit(s) on local main not in the new workspace')
|
|
12
|
+
expect(r.out).toContain('local only')
|
|
13
|
+
expect(git(h.ws('one'), 'log', '--format=%s')).not.toContain('local only')
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
test('ws refresh merges origin/main only, and names what it left out', () => {
|
|
17
|
+
const h = host()
|
|
18
|
+
run(h.main, 'ws', 'new', 'one', '--no-brief')
|
|
19
|
+
commit(h.main, 'pushed.txt', 'p\n', 'pushed')
|
|
20
|
+
git(h.main, 'push', '--quiet', 'origin', 'main')
|
|
21
|
+
commit(h.main, 'local.txt', 'mine\n', 'local only')
|
|
22
|
+
const r = run(h.ws('one'), 'ws', 'refresh')
|
|
23
|
+
expect(r.code).toBe(0)
|
|
24
|
+
expect(r.out).toContain('1 commit(s) on local main not included')
|
|
25
|
+
const log = git(h.ws('one'), 'log', '--format=%s')
|
|
26
|
+
expect(log).toContain('pushed')
|
|
27
|
+
expect(log).not.toContain('local only')
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
test('ws merge never carries a commit that is only on local main', () => {
|
|
31
|
+
const h = host()
|
|
32
|
+
run(h.main, 'ws', 'new', 'one', '--no-brief')
|
|
33
|
+
commit(h.ws('one'), 'work.txt', 'w\n', 'work')
|
|
34
|
+
commit(h.main, 'local.txt', 'mine\n', 'local only')
|
|
35
|
+
|
|
36
|
+
// A plain merge: origin/main gets the work, never the local commit.
|
|
37
|
+
expect(run(h.ws('one'), 'ws', 'merge', '--yes', '--keep-open').code).toBe(0)
|
|
38
|
+
const onOrigin = git(h.main, 'log', '--format=%s', 'origin/main')
|
|
39
|
+
expect(onOrigin).toContain('work')
|
|
40
|
+
expect(onOrigin).not.toContain('local only')
|
|
41
|
+
|
|
42
|
+
// A branch that took local main in (as the old refresh did) is refused, naming the commit.
|
|
43
|
+
git(h.ws('one'), 'merge', '--quiet', '--no-edit', 'main')
|
|
44
|
+
commit(h.ws('one'), 'more.txt', 'm\n', 'more')
|
|
45
|
+
const r = run(h.ws('one'), 'ws', 'merge', '--yes', '--keep-open')
|
|
46
|
+
expect(r.code).not.toBe(0)
|
|
47
|
+
expect(r.out).toContain('holds 1 commit(s) from local main')
|
|
48
|
+
expect(r.out).toContain('local only')
|
|
49
|
+
expect(git(h.main, 'log', '--format=%s', 'origin/main')).not.toContain('more')
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
test('an unreachable origin is reported: a read carries on, a push fails', () => {
|
|
53
|
+
const h = host()
|
|
54
|
+
run(h.main, 'ws', 'new', 'one', '--no-brief')
|
|
55
|
+
commit(h.ws('one'), 'work.txt', 'w\n', 'work')
|
|
56
|
+
git(h.main, 'remote', 'set-url', 'origin', `${h.dir}/gone.git`)
|
|
57
|
+
|
|
58
|
+
const refresh = run(h.ws('one'), 'ws', 'refresh')
|
|
59
|
+
expect(refresh.code).toBe(0)
|
|
60
|
+
expect(refresh.out).toMatch(/couldn't reach origin; using origin\/main as of \S/)
|
|
61
|
+
|
|
62
|
+
const merge = run(h.ws('one'), 'ws', 'merge', '--yes', '--keep-open')
|
|
63
|
+
expect(merge.code).not.toBe(0)
|
|
64
|
+
expect(merge.out).toContain("couldn't reach origin")
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
test("ws merge doesn't blame local main for the branch's own commits, even when local main was moved onto them", () => {
|
|
68
|
+
const h = host()
|
|
69
|
+
run(h.main, 'ws', 'new', 'one', '--no-brief')
|
|
70
|
+
commit(h.ws('one'), 'work.txt', 'w\n', 'work')
|
|
71
|
+
git(h.main, 'merge', '--quiet', '--ff-only', 'feat/one')
|
|
72
|
+
const r = run(h.ws('one'), 'ws', 'merge', '--yes', '--keep-open')
|
|
73
|
+
expect(r.out).not.toContain('from local main')
|
|
74
|
+
expect(r.code).toBe(0)
|
|
75
|
+
expect(git(h.main, 'log', '--format=%s', 'origin/main')).toContain('work')
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
test('ws refresh names local main commits the branch already holds apart from those it left out', () => {
|
|
79
|
+
const h = host()
|
|
80
|
+
run(h.main, 'ws', 'new', 'one', '--no-brief')
|
|
81
|
+
commit(h.ws('one'), 'work.txt', 'w\n', 'work')
|
|
82
|
+
commit(h.main, 'local.txt', 'mine\n', 'local only')
|
|
83
|
+
git(h.ws('one'), 'merge', '--quiet', '--no-edit', 'main')
|
|
84
|
+
const r = run(h.ws('one'), 'ws', 'refresh')
|
|
85
|
+
expect(r.code).toBe(0)
|
|
86
|
+
expect(r.out).not.toContain('not included')
|
|
87
|
+
expect(r.out).toContain('1 commit(s) from local main already in feat/one')
|
|
88
|
+
})
|
package/sync.ts
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
import { existsSync } from 'node:fs'
|
|
16
16
|
import { dirname, join, relative, resolve } from 'node:path'
|
|
17
17
|
import { hostRoot, loadConfig } from './config.ts'
|
|
18
|
+
import { fetchTrunk, needOrigin } from './src/git.ts'
|
|
18
19
|
import { status, working } from './src/status.ts'
|
|
19
20
|
import { fail as failWith } from './src/ui.ts'
|
|
20
21
|
|
|
@@ -41,8 +42,9 @@ if (resolve(root, git('rev-parse', '--git-dir')) !== resolve(root, git('rev-pars
|
|
|
41
42
|
}
|
|
42
43
|
|
|
43
44
|
const step = working('sync')
|
|
44
|
-
step(`fetching
|
|
45
|
-
|
|
45
|
+
step(`fetching origin/${trunk}`)
|
|
46
|
+
// Offline it still reads and reports; it fails only once it has records to push.
|
|
47
|
+
const fetched = fetchTrunk(root, trunk)
|
|
46
48
|
const behind = Number(git('rev-list', '--count', `HEAD..origin/${trunk}`) || '0')
|
|
47
49
|
if (behind) fail(`this checkout is ${behind} commit(s) behind origin/${trunk}; pull first, or the records merged since are missed. Nothing done.`)
|
|
48
50
|
|
|
@@ -287,6 +289,7 @@ if (reasons.length) {
|
|
|
287
289
|
status({ state: 'done', msg: `${summary}, left uncommitted` })
|
|
288
290
|
process.exit(0)
|
|
289
291
|
}
|
|
292
|
+
needOrigin(fetched, trunk)
|
|
290
293
|
const names = due.map(weekName).join(', ')
|
|
291
294
|
const able = [process.execPath, join(import.meta.dir, 'able.ts')]
|
|
292
295
|
step('publishing the week records')
|
package/src/agents/index.ts
DELETED
|
@@ -1,198 +0,0 @@
|
|
|
1
|
-
// able agents: what a host's agent files load, the rules in them, and where each rule belongs (knowledge/product/modules/agents.md).
|
|
2
|
-
//
|
|
3
|
-
// able agents run every step in order, one line each
|
|
4
|
-
// able agents scan [--json|--grid] step 1: every agent file, its kind and size (--grid: one box per file)
|
|
5
|
-
// able agents load [--json] step 2: when each file loads, and the words at start per folder
|
|
6
|
-
// able agents blocks [--json|--grid] step 3: the files cut into blocks, with spans and stable ids (--grid: one square per block)
|
|
7
|
-
// able agents checks [--json|--grid] step 4: what the host already enforces (--grid: per folder, per tool)
|
|
8
|
-
// able agents classify [--json] step 5's result: the agent's findings checked against the blocks, drawn by kind
|
|
9
|
-
// able agents propose [--json] step 6's result: each rule not kept with its proposal, or what is still owed
|
|
10
|
-
// able agents report step 7: checks the findings and writes the run to <journal>/agents/<date>-<hhmm>.json
|
|
11
|
-
// able agents show [<run>] [--step <n>|--json] step 8: a run read back from its file (the latest by default)
|
|
12
|
-
// able agents pick [<yes|no> <n>…]… [--run <run>] step 9: the operator's picks in the latest run, or the one named
|
|
13
|
-
// (no arguments on a terminal: checkboxes)
|
|
14
|
-
//
|
|
15
|
-
// Read-only on the host's agent files: the only files written are the findings (by the skill) and the run file.
|
|
16
|
-
|
|
17
|
-
import { join, relative } from 'node:path'
|
|
18
|
-
import { hostRoot, loadConfig } from '../../config.ts'
|
|
19
|
-
import { confirm, dim, fail, green, tty } from '../ui.ts'
|
|
20
|
-
import * as blocks from './blocks.ts'
|
|
21
|
-
import * as checks from './checks.ts'
|
|
22
|
-
import * as findings from './findings.ts'
|
|
23
|
-
import * as grid from './grid.ts'
|
|
24
|
-
import * as load from './load.ts'
|
|
25
|
-
import { pickInteractive } from './picker.ts'
|
|
26
|
-
import * as report from './report.ts'
|
|
27
|
-
import * as scan from './scan.ts'
|
|
28
|
-
import * as show from './show.ts'
|
|
29
|
-
import { steps, who } from './steps.ts'
|
|
30
|
-
|
|
31
|
-
const [sub = '', ...args] = process.argv.slice(3)
|
|
32
|
-
const valued = ['--step', '--run']
|
|
33
|
-
const names = args.filter((a, i) => !a.startsWith('--') && !valued.includes(args[i - 1] ?? ''))
|
|
34
|
-
const option = (name: string) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined)
|
|
35
|
-
const stepArg = option('--step')
|
|
36
|
-
const json = args.includes('--json')
|
|
37
|
-
const asGrid = args.includes('--grid')
|
|
38
|
-
const root = hostRoot()
|
|
39
|
-
|
|
40
|
-
/** Each step's result, worked out once and shared by the steps after it. */
|
|
41
|
-
const once = <T>(f: () => T) => {
|
|
42
|
-
let value: { v: T } | undefined
|
|
43
|
-
return () => (value ??= { v: f() }).v
|
|
44
|
-
}
|
|
45
|
-
const files = once(() => scan.listFiles(root))
|
|
46
|
-
const entries = once(() => scan.scan(root, files()))
|
|
47
|
-
|
|
48
|
-
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'))
|
|
49
|
-
|
|
50
|
-
/** A built step: its result, the line `run` prints, and its views. */
|
|
51
|
-
interface Built<T> {
|
|
52
|
-
result: () => T | Promise<T>
|
|
53
|
-
summary: (r: T) => string
|
|
54
|
-
render: (r: T) => string
|
|
55
|
-
grid?: (r: T) => string
|
|
56
|
-
}
|
|
57
|
-
const built = <T>(b: Built<T>) => b as Built<unknown>
|
|
58
|
-
|
|
59
|
-
const cut = once(() => blocks.blocks(root, entries()))
|
|
60
|
-
const classified = once(() => {
|
|
61
|
-
const f = findings.readFindings(join(root, findings.findingsPath))
|
|
62
|
-
return f && findings.check(f, cut().blocks)
|
|
63
|
-
})
|
|
64
|
-
|
|
65
|
-
const journal = once(async () => (await loadConfig(root)).journal)
|
|
66
|
-
/** The latest run, or the one named on the command line: `show <run>`, `pick --run <run>`. */
|
|
67
|
-
const latest = once(async () => {
|
|
68
|
-
const path = report.findRun(root, await journal(), sub === 'show' ? names[0] : option('--run'))
|
|
69
|
-
return path ? { path, run: report.readRun(path) } : undefined
|
|
70
|
-
})
|
|
71
|
-
type Latest = Awaited<ReturnType<typeof latest>>
|
|
72
|
-
const requireLatest = async () => (await latest()) ?? fail(option('--run') || (sub === 'show' && names[0]) ? 'no such run' : 'no run yet: able agents report writes one')
|
|
73
|
-
/** Steps 7 to 9 all show the latest run; only their line in `run` differs. */
|
|
74
|
-
const latestView = (summary: (l: NonNullable<Latest>) => string, none: string) =>
|
|
75
|
-
built<Latest>({ result: latest, summary: (l) => (l ? summary(l) : none), render: (l) => (l ? show.render(l.run, l.path, root) : ' No run yet.') })
|
|
76
|
-
|
|
77
|
-
const views: Record<string, Built<unknown>> = {
|
|
78
|
-
scan: built({ result: entries, summary: scan.summary, render: (e) => `${scope}\n\n${scan.render(e)}`, grid: (e) => `${scope}\n\n${grid.files(e)}` }),
|
|
79
|
-
load: built({ result: once(() => load.load(root, entries())), summary: load.summary, render: load.render }),
|
|
80
|
-
blocks: built({ result: cut, summary: blocks.summary, render: blocks.render, grid: grid.blocks }),
|
|
81
|
-
checks: built({ result: once(() => checks.checks(root, entries(), files())), summary: checks.summary, render: checks.render, grid: (c) => grid.enforcement(c, entries()) }),
|
|
82
|
-
classify: built({
|
|
83
|
-
result: classified,
|
|
84
|
-
summary: (c) => (c ? findings.summary(c) : `not run: the skill writes ${findings.findingsPath}`),
|
|
85
|
-
render: (c) =>
|
|
86
|
-
c
|
|
87
|
-
? [grid.byKind(cut(), c), ...(c.errors.length ? ['', ' ERRORS', ...c.errors.map((e) => ` ${e}`)] : [])].join('\n')
|
|
88
|
-
: ` No findings yet: the skill (able-clean-agent-bloat) writes ${findings.findingsPath} at step 5.`,
|
|
89
|
-
}),
|
|
90
|
-
propose: built({
|
|
91
|
-
result: classified,
|
|
92
|
-
summary: (c) => (c ? findings.proposeSummary(c) : 'waits for classify'),
|
|
93
|
-
render: (c) =>
|
|
94
|
-
c
|
|
95
|
-
? c.rules
|
|
96
|
-
.filter((r) => r.kind !== 'keep')
|
|
97
|
-
.map(
|
|
98
|
-
(r) => ` ${r.kind.padEnd(12)} ${r.id}
|
|
99
|
-
${r.proposal ? `→ ${r.proposal.target}: ${r.proposal.change}` : dim('no proposal yet')}`,
|
|
100
|
-
)
|
|
101
|
-
.join('\n')
|
|
102
|
-
: ' No findings yet.',
|
|
103
|
-
}),
|
|
104
|
-
report: latestView((l) => `latest: ${relative(root, l.path)}`, 'not run yet'),
|
|
105
|
-
show: latestView(() => 'able agents show', 'no run yet'),
|
|
106
|
-
pick: latestView((l) => report.tally(l.run).line, 'no run yet'),
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/** Step 7: refuses while the findings owe anything, then writes the run and shows it. */
|
|
110
|
-
async function writeReport() {
|
|
111
|
-
const c = classified()
|
|
112
|
-
if (!c) fail(`no findings: the skill writes ${findings.findingsPath} at steps 5 and 6`)
|
|
113
|
-
const owed = report.problems(c)
|
|
114
|
-
if (owed.length) fail(`the findings are not ready:\n${owed.map((p) => ` ${p}`).join('\n')}`)
|
|
115
|
-
const summaries: Record<string, string> = {}
|
|
116
|
-
for (const id of ['scan', 'load', 'blocks', 'checks', 'classify', 'propose']) summaries[id] = views[id].summary(await views[id].result())
|
|
117
|
-
const at = new Date()
|
|
118
|
-
const path = report.runPath(root, await journal(), at)
|
|
119
|
-
const before = report.findRun(root, await journal())
|
|
120
|
-
const run = report.build({
|
|
121
|
-
scan: entries(),
|
|
122
|
-
load: (await views.load.result()) as load.LoadMap,
|
|
123
|
-
blocks: cut(),
|
|
124
|
-
checks: (await views.checks.result()) as checks.Checks,
|
|
125
|
-
checked: c,
|
|
126
|
-
summaries,
|
|
127
|
-
root,
|
|
128
|
-
path,
|
|
129
|
-
at,
|
|
130
|
-
previous: before ? report.readRun(before) : undefined,
|
|
131
|
-
})
|
|
132
|
-
await report.saveRun(path, run)
|
|
133
|
-
console.log(`\n ${green('wrote')} ${relative(root, path)}\n\n${show.render(run, path, root)}\n`)
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/** Step 9: on a terminal with no arguments, the checkbox picker; otherwise `pick yes 1 3 5`, `pick no 2`, or both at
|
|
137
|
-
* once, `pick yes 1 3 no 2` (the dashboard's page records its checkboxes this way). */
|
|
138
|
-
async function writePicks() {
|
|
139
|
-
const l = await requireLatest()
|
|
140
|
-
let answers: Map<number, 'yes' | 'no'> | undefined
|
|
141
|
-
if (!names.length && tty && process.stdin.isTTY) {
|
|
142
|
-
answers = await pickInteractive(l.run, l.path, root)
|
|
143
|
-
if (!answers) return console.log('\n Nothing recorded.\n')
|
|
144
|
-
} else if (names[0] === 'yes' || names[0] === 'no') {
|
|
145
|
-
answers = new Map()
|
|
146
|
-
let answer: 'yes' | 'no' = names[0]
|
|
147
|
-
for (const x of names.slice(1))
|
|
148
|
-
if (x === 'yes' || x === 'no') answer = x
|
|
149
|
-
else if (/^\d+$/.test(x)) answers.set(Number(x), answer)
|
|
150
|
-
else fail(`not a finding number: ${x}`)
|
|
151
|
-
} else fail('usage: able agents pick [<yes|no> <n>…]… [--run <run>] (no arguments on a terminal opens the checkboxes)')
|
|
152
|
-
const unknown = await report.pick(l.path, l.run, answers)
|
|
153
|
-
if (unknown.length) fail(`no finding numbered ${unknown.join(', ')} in ${relative(root, l.path)}`)
|
|
154
|
-
const { yes, no, open } = report.tally(l.run)
|
|
155
|
-
if (json) return console.log(JSON.stringify({ run: relative(root, l.path), yes, no, open }))
|
|
156
|
-
console.log(`\n ${green('recorded')} ${yes} yes, ${no} no, ${open} not picked, in ${relative(root, l.path)}\n`)
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
async function run() {
|
|
160
|
-
console.log()
|
|
161
|
-
for (const step of steps.filter((s) => s.v1)) {
|
|
162
|
-
const label = ` ${String(step.n).padStart(2)} ${who[step.kind]} ${step.id.padEnd(10)}`
|
|
163
|
-
const view = views[step.id]
|
|
164
|
-
if (!view) {
|
|
165
|
-
console.log(`${label} ${dim('not built yet')}`)
|
|
166
|
-
continue
|
|
167
|
-
}
|
|
168
|
-
const started = performance.now()
|
|
169
|
-
const result = await view.result()
|
|
170
|
-
const summary = view.summary(result)
|
|
171
|
-
const done = result !== undefined ? `${green('ok')} ${dim(`${Math.round(performance.now() - started)}ms`)}` : ''
|
|
172
|
-
console.log(`${label} ${result !== undefined ? summary.padEnd(44) : dim(summary)} ${done}`.trimEnd())
|
|
173
|
-
}
|
|
174
|
-
console.log(dim('\n M mechanical (the CLI) · A agent · O operator (you)\n'))
|
|
175
|
-
// On a terminal, step 9 follows on: the latest run's unpicked findings, as checkboxes.
|
|
176
|
-
const l = await latest()
|
|
177
|
-
if (l && tty && process.stdin.isTTY && report.tally(l.run).open && confirm('Pick now?')) await writePicks()
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
if (sub === 'run') await run()
|
|
181
|
-
else if (sub === 'report') await writeReport()
|
|
182
|
-
else if (sub === 'pick') await writePicks()
|
|
183
|
-
else if (sub === 'show' && stepArg) {
|
|
184
|
-
const l = await requireLatest()
|
|
185
|
-
const id = l.run.steps.find((s) => String(s.n) === stepArg || s.id === stepArg)?.id
|
|
186
|
-
if (!id) fail(`no step ${stepArg}: 1 to ${l.run.steps.length}, or a name`)
|
|
187
|
-
console.log(`\n${show.step(l.run, id)}\n`)
|
|
188
|
-
} else if (sub === 'show' && json) console.log(JSON.stringify((await requireLatest()).run))
|
|
189
|
-
else if (views[sub]) {
|
|
190
|
-
const view = views[sub]
|
|
191
|
-
const r = await view.result()
|
|
192
|
-
console.log(json ? JSON.stringify(r) : `\n${asGrid && view.grid ? view.grid(r) : view.render(r)}\n`)
|
|
193
|
-
} else {
|
|
194
|
-
console.error(`usage: able agents run | ${Object.keys(views).join(' | ')} [--json] [--grid]`)
|
|
195
|
-
process.exit(sub ? 1 : 0)
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
export {}
|
package/src/agents/report.ts
DELETED
|
@@ -1,211 +0,0 @@
|
|
|
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 the
|
|
4
|
-
// dashboard read; it holds each rule's span, so a view can highlight its words.
|
|
5
|
-
//
|
|
6
|
-
// On disk (`able.agents@2`) a rule keeps no copy of its words or its path: both come from its block (the block's text
|
|
7
|
-
// at the rule's span), filled in again by `readRun`. `@1` runs, which stored both, still read.
|
|
8
|
-
|
|
9
|
-
import { existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs'
|
|
10
|
-
import { dirname, join, relative } from 'node:path'
|
|
11
|
-
import type { Blocks } from './blocks.ts'
|
|
12
|
-
import type { Checks } from './checks.ts'
|
|
13
|
-
import type { Checked, Rule } from './findings.ts'
|
|
14
|
-
import { unproposed } from './findings.ts'
|
|
15
|
-
import { pickOrder, type Kind } from './kinds.ts'
|
|
16
|
-
import { chain, type LoadMap } from './load.ts'
|
|
17
|
-
import { countWords, type Entry } from './scan.ts'
|
|
18
|
-
import { runsDir, steps } from './steps.ts'
|
|
19
|
-
import type { Finding, Run } from './types.ts'
|
|
20
|
-
|
|
21
|
-
export type { Finding, Run }
|
|
22
|
-
|
|
23
|
-
export const format = 'able.agents@2'
|
|
24
|
-
|
|
25
|
-
/** The formats `readRun` reads: every one written so far. */
|
|
26
|
-
export const formats = ['able.agents@1', format] as const satisfies Run['format'][]
|
|
27
|
-
|
|
28
|
-
/** Kinds whose words leave the start-up set once applied: everything but keep, and a conflict until it is picked. */
|
|
29
|
-
const leaves = (k: Kind) => k !== 'keep' && k !== 'conflict'
|
|
30
|
-
|
|
31
|
-
export function runsFolder(root: string, journal: string) {
|
|
32
|
-
return join(root, journal, runsDir)
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** The run files, oldest first. */
|
|
36
|
-
export function runs(root: string, journal: string) {
|
|
37
|
-
const dir = runsFolder(root, journal)
|
|
38
|
-
return existsSync(dir)
|
|
39
|
-
? readdirSync(dir)
|
|
40
|
-
.filter((f) => /^\d{4}-\d{2}-\d{2}-\d{4}\.json$/.test(f))
|
|
41
|
-
.sort()
|
|
42
|
-
.map((f) => join(dir, f))
|
|
43
|
-
: []
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** A run from its text, whichever format it was written in, with each rule's words and path filled in from its block. */
|
|
47
|
-
export function parseRun(text: string): Run {
|
|
48
|
-
const run = JSON.parse(text) as Run
|
|
49
|
-
if (!formats.includes(run.format)) throw new Error(`a run in format ${JSON.stringify(run.format)}: this able reads ${formats.join(' and ')}`)
|
|
50
|
-
const blockOf = new Map(run.blocks.blocks.map((b) => [b.id, b]))
|
|
51
|
-
for (const r of run.rules) {
|
|
52
|
-
const b = blockOf.get(r.block)
|
|
53
|
-
if (!b) continue
|
|
54
|
-
r.path ??= b.path
|
|
55
|
-
r.text ??= b.text.slice(r.span[0] - b.span[0], r.span[1] - b.span[0])
|
|
56
|
-
}
|
|
57
|
-
return run
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export const readRun = (path: string) => parseRun(readFileSync(path, 'utf8'))
|
|
61
|
-
|
|
62
|
-
/** A run file by name or date prefix (`2026-11-16`, `2026-11-16-2240`), or the latest. */
|
|
63
|
-
export function findRun(root: string, journal: string, name?: string) {
|
|
64
|
-
const all = runs(root, journal)
|
|
65
|
-
return name
|
|
66
|
-
? all
|
|
67
|
-
.filter((p) =>
|
|
68
|
-
p
|
|
69
|
-
.split('/')
|
|
70
|
-
.at(-1)!
|
|
71
|
-
.startsWith(name.replace(/\.json$/, '')),
|
|
72
|
-
)
|
|
73
|
-
.at(-1)
|
|
74
|
-
: all.at(-1)
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/** What blocks the report: findings errors, blocks not classified, rules not proposed. */
|
|
78
|
-
export function problems(c: Checked) {
|
|
79
|
-
return [...c.errors, ...c.missing.map((id) => `${id}: not classified`), ...unproposed(c).map((r) => `${r.id}: ${r.kind}, no proposal yet`)]
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/** Step 9's tally: findings to pick, and the answers so far. */
|
|
83
|
-
export function tally(run: Run) {
|
|
84
|
-
const numbered = run.rules.filter((r) => r.n)
|
|
85
|
-
const yes = numbered.filter((r) => r.pick === 'yes').length
|
|
86
|
-
const no = numbered.filter((r) => r.pick === 'no').length
|
|
87
|
-
return { numbered: numbered.length, yes, no, open: numbered.length - yes - no, line: `${yes + no} of ${numbered.length} picked` }
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/** Builds the run. `path` is where it will be written; `summaries` are steps 1 to 6's lines, the rest are worked out here. */
|
|
91
|
-
export function build(input: {
|
|
92
|
-
scan: Entry[]
|
|
93
|
-
load: LoadMap
|
|
94
|
-
blocks: Blocks
|
|
95
|
-
checks: Checks
|
|
96
|
-
checked: Checked
|
|
97
|
-
summaries: Record<string, string>
|
|
98
|
-
root: string
|
|
99
|
-
path: string
|
|
100
|
-
at: Date
|
|
101
|
-
/** The run before this one: its picks carry forward by rule id, so what was answered isn't asked again. */
|
|
102
|
-
previous?: Run
|
|
103
|
-
}): Run {
|
|
104
|
-
const { scan, load, blocks, checks, checked } = input
|
|
105
|
-
const earlier = new Map(input.previous?.rules.flatMap((r) => (r.pick ? [[r.id, r.pick] as const] : [])))
|
|
106
|
-
const blockOf = new Map(blocks.blocks.map((b) => [b.id, b]))
|
|
107
|
-
let n = 0
|
|
108
|
-
const rules = checked.rules
|
|
109
|
-
.map((r) => {
|
|
110
|
-
const b = blockOf.get(r.block)!
|
|
111
|
-
const line = b.lines[0] + b.text.slice(0, r.span[0] - b.span[0]).split('\n').length - 1
|
|
112
|
-
return { ...r, line, words: countWords(r.text) }
|
|
113
|
-
})
|
|
114
|
-
.sort((a, b) => pickOrder.indexOf(a.kind) - pickOrder.indexOf(b.kind) || a.path.localeCompare(b.path) || a.span[0] - b.span[0])
|
|
115
|
-
.map((r) => (r.kind === 'keep' ? r : { ...r, n: ++n, ...(earlier.has(r.id) && { pick: earlier.get(r.id) }) }))
|
|
116
|
-
|
|
117
|
-
// A rule counts at start for a folder when its file loads at start there: an instruction file or always-on rule in the
|
|
118
|
-
// folder's chain, or a skill's description.
|
|
119
|
-
const fileLoad = new Map(load.files.map((f) => [f.path, f]))
|
|
120
|
-
const atStart = (r: (typeof rules)[number], folder: string) => {
|
|
121
|
-
const f = fileLoad.get(r.path)
|
|
122
|
-
if (!f) return false
|
|
123
|
-
if (f.load === 'skill') return blockOf.get(r.block)?.heading[0] === 'description'
|
|
124
|
-
return (f.load === 'always' || f.load === 'folder') && chain(folder).includes(f.folder)
|
|
125
|
-
}
|
|
126
|
-
const folders = load.folders.map((f) => ({
|
|
127
|
-
folder: f.folder,
|
|
128
|
-
before: f.host,
|
|
129
|
-
after: f.host - rules.filter((r) => leaves(r.kind) && atStart(r, f.folder)).reduce((s, r) => s + r.words, 0),
|
|
130
|
-
}))
|
|
131
|
-
const byKind: Run['impact']['byKind'] = {}
|
|
132
|
-
for (const r of rules) {
|
|
133
|
-
const k = (byKind[r.kind] ??= { rules: 0, words: 0 })
|
|
134
|
-
k.rules++
|
|
135
|
-
k.words += r.words
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
const pathRules = scan.some((e) => e.kind === 'rule')
|
|
139
|
-
const agentsMd = scan
|
|
140
|
-
.filter((e) => e.kind === 'instructions' && e.path.endsWith('CLAUDE.md') && !e.path.endsWith('CLAUDE.local.md'))
|
|
141
|
-
.map((e) => {
|
|
142
|
-
const dir = dirname(e.path)
|
|
143
|
-
const at = (name: string) => (dir === '.' ? name : `${dir}/${name}`)
|
|
144
|
-
const blockers = [
|
|
145
|
-
...(existsSync(join(input.root, at('CLAUDE.local.md'))) ? ['a CLAUDE.local.md beside it stops Claude reading AGENTS.md'] : []),
|
|
146
|
-
...(scan.some((x) => x.path === at('AGENTS.md')) ? ['an AGENTS.md already exists beside it: merge, do not overwrite'] : []),
|
|
147
|
-
...(pathRules && dir === '.' ? ['.claude/rules with paths: are Claude-only and stay where they are'] : []),
|
|
148
|
-
]
|
|
149
|
-
return { path: e.path, blockers }
|
|
150
|
-
})
|
|
151
|
-
|
|
152
|
-
const root = folders.find((f) => f.folder === '.')
|
|
153
|
-
const summaries: Record<string, string> = {
|
|
154
|
-
...input.summaries,
|
|
155
|
-
report: relative(input.root, input.path),
|
|
156
|
-
show: `${root ? root.before - root.after : 0} words leave the root's start`,
|
|
157
|
-
}
|
|
158
|
-
const run: Run = {
|
|
159
|
-
format,
|
|
160
|
-
at: input.at.toISOString(),
|
|
161
|
-
steps: steps.filter((s) => s.v1).map((s) => ({ n: s.n, id: s.id, kind: s.kind, summary: summaries[s.id] ?? '' })),
|
|
162
|
-
scan,
|
|
163
|
-
load,
|
|
164
|
-
blocks,
|
|
165
|
-
checks,
|
|
166
|
-
rules,
|
|
167
|
-
impact: { folders, byKind },
|
|
168
|
-
agentsMd,
|
|
169
|
-
}
|
|
170
|
-
run.steps.find((s) => s.id === 'pick')!.summary = tally(run).line
|
|
171
|
-
return run
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
/** The run's file name: local date and time, so two runs a minute apart are both kept. */
|
|
175
|
-
export function runName(at = new Date()) {
|
|
176
|
-
const p = (v: number) => String(v).padStart(2, '0')
|
|
177
|
-
return `${at.getFullYear()}-${p(at.getMonth() + 1)}-${p(at.getDate())}-${p(at.getHours())}${p(at.getMinutes())}.json`
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/** Where a run taken at `at` is written. */
|
|
181
|
-
export const runPath = (root: string, journal: string, at: Date) => join(runsFolder(root, journal), runName(at))
|
|
182
|
-
|
|
183
|
-
/** JSON broken into lines down to the lists (rules, blocks, files), each of their items on one line: small, and still a
|
|
184
|
-
* readable diff. */
|
|
185
|
-
export function lines(value: unknown, depth = 0): string {
|
|
186
|
-
const flat = JSON.stringify(value)
|
|
187
|
-
if (value === null || typeof value !== 'object' || flat.length <= 100 || depth > 2 || (depth === 2 && !Array.isArray(value))) return flat
|
|
188
|
-
const pad = ' '.repeat(depth + 1)
|
|
189
|
-
const items = Array.isArray(value) ? value.map((v) => lines(v, depth + 1)) : Object.entries(value).map(([k, v]) => `${JSON.stringify(k)}: ${lines(v, depth + 1)}`)
|
|
190
|
-
const [open, close] = Array.isArray(value) ? ['[', ']'] : ['{', '}']
|
|
191
|
-
return `${open}\n${items.map((i) => pad + i).join(',\n')}\n${' '.repeat(depth)}${close}`
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
/** Writes a run file, always in the current format; the one place its form on disk is set. */
|
|
195
|
-
export async function saveRun(path: string, run: Run) {
|
|
196
|
-
mkdirSync(dirname(path), { recursive: true })
|
|
197
|
-
const rules = run.rules.map(({ text: _text, path: _path, ...r }) => r)
|
|
198
|
-
await Bun.write(path, `${lines({ ...run, format, rules })}\n`)
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
/** Step 9: records the operator's yes or no on numbered findings in the run, and saves it. */
|
|
202
|
-
export async function pick(path: string, run: Run, answers: Map<number, 'yes' | 'no'>) {
|
|
203
|
-
const known = new Set(run.rules.flatMap((r) => (r.n ? [r.n] : [])))
|
|
204
|
-
const unknown = [...answers.keys()].filter((x) => !known.has(x))
|
|
205
|
-
if (unknown.length) return unknown
|
|
206
|
-
for (const r of run.rules) if (r.n && answers.has(r.n)) r.pick = answers.get(r.n)
|
|
207
|
-
const step = run.steps.find((s) => s.id === 'pick')
|
|
208
|
-
if (step) step.summary = tally(run).line
|
|
209
|
-
await saveRun(path, run)
|
|
210
|
-
return unknown
|
|
211
|
-
}
|