@able-autonomy/able 0.0.15 → 0.0.18

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 CHANGED
@@ -3,14 +3,15 @@
3
3
  // `able gh <args>` runs `gh <args>` as Able's GitHub App, so what it writes comes from `<app-slug>[bot]`.
4
4
  // `able sync` keeps a host's follow-up issues and week records up to date (sync.ts).
5
5
  // `able config --json` prints the host's resolved `able.config.ts` (config.ts).
6
+ // `able init` brings a project to Able on this machine (src/init.ts); a work in progress.
6
7
 
7
8
  import { createSign } from 'node:crypto'
8
9
  import { mkdirSync } from 'node:fs'
9
- import { homedir } from 'node:os'
10
10
  import { join } from 'node:path'
11
+ import { ableDir, repoOf } from './src/machine.ts'
11
12
 
12
13
  // Machine-only config lives in `~/.config/able/<service>/`, the same whether the CLI is linked or installed.
13
- const configDir = join(process.env.ABLE_CONFIG_DIR ?? join(homedir(), '.config', 'able'), 'github')
14
+ const configDir = join(ableDir(), 'github')
14
15
  const api = 'https://api.github.com'
15
16
 
16
17
  function fail(message: string): never {
@@ -56,9 +57,7 @@ function resolveRepo(args: string[]) {
56
57
  }
57
58
  if (process.env.GH_REPO) return process.env.GH_REPO
58
59
  const origin = Bun.spawnSync(['git', 'remote', 'get-url', 'origin']).stdout.toString().trim()
59
- const match = origin.match(/github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/)
60
- if (!match) fail('no GitHub repo: pass --repo <owner>/<repo> or run inside a checkout with a GitHub origin')
61
- return match[1]
60
+ return repoOf(origin) ?? fail('no GitHub repo: pass --repo <owner>/<repo> or run inside a checkout with a GitHub origin')
62
61
  }
63
62
 
64
63
  // Installation tokens last an hour; reuse one until five minutes before it expires.
@@ -124,7 +123,7 @@ if (command === 'upgrade') {
124
123
  console.log(`Upgraded able v${current} → v${latest}`)
125
124
  process.exit(0)
126
125
  }
127
- const modules: Record<string, string> = { agents: './src/agents/index.ts', commit: './src/commit.ts', push: './src/push.ts', ws: './src/workspaces/index.ts' }
126
+ 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' }
128
127
  if (command && modules[command]) {
129
128
  await import(modules[command])
130
129
  process.exit(0)
@@ -143,7 +142,7 @@ if (delegate) {
143
142
  }
144
143
  if (command !== 'gh') {
145
144
  console.error(
146
- "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 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 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",
145
+ "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 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",
147
146
  )
148
147
  process.exit(command ? 1 : 0)
149
148
  }
package/config.ts CHANGED
@@ -93,7 +93,7 @@ export function hostRoot() {
93
93
 
94
94
  export async function loadConfig(root: string): Promise<AbleConfig> {
95
95
  const path = join(root, 'able.config.ts')
96
- if (!existsSync(path)) fail(`no able.config.ts at ${root}. Run Able's onboarding to set this project up.`)
96
+ if (!existsSync(path)) fail(`no able.config.ts at ${root}. Set the project up with \`bunx @able-autonomy/able init\`.`)
97
97
  const config = (await import(path)).default as Partial<AbleConfig> | undefined
98
98
  const unknown = unknownKeys(config, shape)
99
99
  if (unknown.length) fail(`${path}: unknown key(s) ${unknown.join(', ')}`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@able-autonomy/able",
3
- "version": "0.0.15",
3
+ "version": "0.0.18",
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",
@@ -1,4 +1,4 @@
1
- // able agents: what a host's agent files load, the rules in them, and where each rule belongs (knowledge/modules/agents.md).
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
2
  //
3
3
  // able agents run every step in order, one line each
4
4
  // able agents scan [--json|--grid] step 1: every agent file, its kind and size (--grid: one box per file)
package/src/commit.ts CHANGED
@@ -12,7 +12,8 @@ import { join, relative, resolve } from 'node:path'
12
12
  import { loadConfig, trailerArgs } from '../config.ts'
13
13
  import { runChecks } from './checks.ts'
14
14
  import { failOnMerge, git, gitLoud } from './git.ts'
15
- import { bold, confirm, dim, fail, green } from './ui.ts'
15
+ import { status, working } from './status.ts'
16
+ import { bold, cancel, confirm, dim, fail, green } from './ui.ts'
16
17
  import { current } from './workspaces/state.ts'
17
18
 
18
19
  const argv = process.argv.slice(3)
@@ -38,19 +39,28 @@ const changed = () => {
38
39
  return paths
39
40
  }
40
41
 
42
+ const step = working('commit')
43
+ step('reading what changed')
41
44
  const before = changed()
42
45
  if (!before.length) fail('nothing to commit')
43
46
  console.log(`\n ${bold(`${before.length} file(s)`)} ${dim(scope.join(' '))}`)
44
47
  for (const f of before) console.log(dim(` ${f}`))
45
- if (argv.includes('--dry')) process.exit(0)
46
- if (!argv.includes('--yes') && !confirm(`Run the checks and commit as "${msg}"?`)) fail('aborted; nothing committed')
48
+ if (argv.includes('--dry')) {
49
+ status({ state: 'done', msg: `commit: ${before.length} file(s) would go in` })
50
+ process.exit(0)
51
+ }
52
+ if (!argv.includes('--yes') && !confirm(`Run the checks and commit as "${msg}"?`)) cancel('aborted; nothing committed')
47
53
 
48
54
  const config = await loadConfig(root)
55
+ step(`checks for ${before.length} file(s)`)
49
56
  if (!runChecks(config, before, at)) fail('a check failed; nothing committed')
50
57
 
51
58
  // The checks may have formatted files, so the list is read again.
52
59
  const paths = changed()
60
+ step('committing')
53
61
  // A path that is gone (a deletion, a rename's old name) has nothing to add, but still goes into the commit.
54
62
  const present = paths.filter((p) => existsSync(join(root, p)))
55
63
  if ((present.length && !gitLoud(root, 'add', '--', ...present)) || !gitLoud(root, 'commit', '--quiet', '-m', msg, ...trailerArgs(config), '--', ...paths)) fail('git commit failed')
56
- console.log(`\n ${green('✓')} ${git(root, 'log', '--oneline', '-1')}\n`)
64
+ const made = git(root, 'log', '--oneline', '-1')
65
+ console.log(`\n ${green('✓')} ${made}\n`)
66
+ status({ state: 'done', msg: `commit: ${made}` })
package/src/init.ts ADDED
@@ -0,0 +1,75 @@
1
+ // able init: brings a project to Able on this machine, from any of its checkouts. It walks a short list of steps and
2
+ // does the ones still missing, so it is safe to run again: on a project already set up (a teammate's clone, a second
3
+ // laptop) only the machine's steps are left.
4
+ //
5
+ // able init sets this project up here
6
+ // able init --list the projects set up on this machine
7
+ // able init --remove forgets this project on this machine (its repo is left as it is)
8
+ //
9
+ // The steps:
10
+ // 1. config the project's able.config.ts. WIP: init does not write one yet. It is meant to ask the operator a few
11
+ // questions and write it (the onboarding `loadConfig`'s message points to); today it must exist already.
12
+ // 2. machine records the project's main checkout in `~/.config/able/checkouts.json` (`owner/name` to its path), so
13
+ // the dashboard running on this machine reads the journal and docs off disk. Nothing leaves the machine.
14
+ // Next to come, each its own step here: installing Able's skills, the GitHub App, the project on the dashboard.
15
+
16
+ import { existsSync, mkdirSync } from 'node:fs'
17
+ import { join } from 'node:path'
18
+ import { hostRoot, loadConfig } from '../config.ts'
19
+ import { git, mainRoot } from './git.ts'
20
+ import { ableDir, checkoutsFile, repoOf } from './machine.ts'
21
+ import { status, working } from './status.ts'
22
+ import { bold, dim, fail, green, yellow } from './ui.ts'
23
+
24
+ const args = process.argv.slice(3)
25
+ const file = checkoutsFile()
26
+
27
+ const read = async (): Promise<Record<string, string>> => (existsSync(file) ? await Bun.file(file).json() : {})
28
+ const write = async (map: Record<string, string>) => {
29
+ mkdirSync(ableDir(), { recursive: true, mode: 0o700 })
30
+ await Bun.write(file, `${JSON.stringify(map, null, 2)}\n`)
31
+ }
32
+ const row = (mark: string, step: string, text: string) => console.log(` ${mark} ${step.padEnd(9)} ${text}`)
33
+ const wip = (text: string) => console.log(dim(`\n WIP: ${text}\n`))
34
+
35
+ if (args.includes('--list')) {
36
+ const entries = Object.entries(await read())
37
+ if (!entries.length) console.log(dim(`\n no projects set up on this machine (${file})\n`))
38
+ else console.log(`\n${entries.map(([repo, path]) => ` ${bold(repo)} ${dim(path)}`).join('\n')}\n`)
39
+ process.exit(0)
40
+ }
41
+
42
+ const root = hostRoot()
43
+ const repo = repoOf(git(root, 'remote', 'get-url', 'origin'))
44
+ if (!repo) fail('no GitHub repo: this checkout has no GitHub origin')
45
+
46
+ if (args.includes('--remove')) {
47
+ const map = await read()
48
+ if (!(repo in map)) fail(`${repo} is not set up on this machine`)
49
+ delete map[repo]
50
+ await write(map)
51
+ console.log(`\n ${green('✓')} ${bold(repo)} forgotten on this machine; nothing in its repo changed\n`)
52
+ process.exit(0)
53
+ }
54
+
55
+ const main = mainRoot(root)
56
+ const step = working(`init ${repo}`)
57
+ console.log(`\n ${bold('able init')} ${repo}\n`)
58
+
59
+ // 1. config
60
+ if (!existsSync(join(main, 'able.config.ts'))) {
61
+ row(yellow('◌'), 'config', `no able.config.ts in ${main}`)
62
+ fail("WIP: init can't write able.config.ts yet. Write it by hand (README.md in Able, the host contract), then run init again.")
63
+ }
64
+ step('reading the config')
65
+ const config = await loadConfig(main)
66
+ row(green('✓'), 'config', `able.config.ts ${dim(`journal ${config.journal}, knowledge ${config.knowledge ?? 'none'}`)}`)
67
+
68
+ // 2. machine
69
+ const map = await read()
70
+ const before = map[repo]
71
+ if (before !== main) await write({ ...map, [repo]: main })
72
+ row(green('✓'), 'machine', `${main} ${dim(before === main ? 'already recorded' : before ? `was ${before}` : 'recorded')}`)
73
+
74
+ wip(`init only checks the config and records this checkout so far. Add ${repo} on the dashboard's Projects page to see its journal.`)
75
+ status({ state: 'done', msg: `init: ${repo} set up on this machine` })
package/src/machine.ts ADDED
@@ -0,0 +1,15 @@
1
+ // What a command knows about this machine and a checkout's GitHub repo, with no imports of Able's own, so any
2
+ // command can use it. api/docs.ts keeps its own copy of `repoOf` and the checkouts file's path, because api/'s image
3
+ // carries no cli/: change them together.
4
+
5
+ import { homedir } from 'node:os'
6
+ import { join } from 'node:path'
7
+
8
+ /** Able's machine-only folder: `~/.config/able/`, or `ABLE_CONFIG_DIR`. */
9
+ export const ableDir = () => process.env.ABLE_CONFIG_DIR ?? join(homedir(), '.config', 'able')
10
+
11
+ /** The projects set up on this machine (`able init`): `owner/name` to the main checkout's path. */
12
+ export const checkoutsFile = () => join(ableDir(), 'checkouts.json')
13
+
14
+ /** A GitHub remote's `owner/name`, or undefined for any other URL. */
15
+ export const repoOf = (origin: string) => /github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(origin)?.[1]
@@ -0,0 +1,43 @@
1
+ import { expect, test } from 'bun:test'
2
+ import { oneLine, report } from './status.ts'
3
+
4
+ const b64 = (s: string) => Buffer.from(s).toString('base64')
5
+ // The message a report carries, decoded.
6
+ const msgOf = (bytes: string) => Buffer.from(/msg=([A-Za-z0-9+/=]*)/.exec(bytes)![1]!, 'base64').toString()
7
+
8
+ test('the exact bytes of each state', () => {
9
+ expect(report({ state: 'idle' })).toBe('\x1b]7501;state=idle:app=able\x1b\\')
10
+ expect(report({ state: 'clear' })).toBe('\x1b]7501;state=clear:app=able\x1b\\')
11
+ expect(report({ state: 'working', msg: 'Installing updates' })).toBe('\x1b]7501;state=working:app=able:msg=SW5zdGFsbGluZyB1cGRhdGVz\x1b\\')
12
+ expect(report({ state: 'working', msg: 'api: checks', progress: 40 })).toBe(`\x1b]7501;state=working:app=able:progress=40:msg=${b64('api: checks')}\x1b\\`)
13
+ expect(report({ state: 'blocked', kind: 'question', msg: 'Merge?' })).toBe(`\x1b]7501;state=blocked:app=able:kind=question:msg=${b64('Merge?')}\x1b\\`)
14
+ expect(report({ state: 'done', msg: 'Upgraded 12 packages' })).toBe('\x1b]7501;state=done:app=able:msg=VXBncmFkZWQgMTIgcGFja2FnZXM=\x1b\\')
15
+ expect(report({ state: 'error', msg: 'a check failed' })).toBe(`\x1b]7501;state=error:app=able:msg=${b64('a check failed')}\x1b\\`)
16
+ })
17
+
18
+ test('kind and progress go only with the states that take them', () => {
19
+ expect(report({ state: 'done', kind: 'auth', progress: 50 })).toBe('\x1b]7501;state=done:app=able\x1b\\')
20
+ expect(report({ state: 'working', kind: 'auth' })).toBe('\x1b]7501;state=working:app=able\x1b\\')
21
+ expect(report({ state: 'working', progress: 140.4 })).toContain('progress=100')
22
+ expect(report({ state: 'blocked', progress: -3 })).toContain('progress=0')
23
+ expect(report({ state: 'working', progress: Number.NaN })).not.toContain('progress')
24
+ })
25
+
26
+ test('control characters and colour codes never reach a report', () => {
27
+ expect(oneLine('\n \x1b[31mconflict\x1b[0m merging:\n\tapi/docs.ts\r\n\x07 done\x7f\u0085')).toBe('conflict merging: api/docs.ts done')
28
+ expect(msgOf(report({ state: 'error', msg: 'one\ntwo\tthree' }))).toBe('one two three')
29
+ // An empty message is left out rather than sent empty.
30
+ expect(report({ state: 'working', msg: '\n\t' })).toBe('\x1b]7501;state=working:app=able\x1b\\')
31
+ })
32
+
33
+ test('a long message is cut to 2048 bytes on a character boundary', () => {
34
+ expect(oneLine('a'.repeat(3000))).toBe('a'.repeat(2048))
35
+ // 'é' is two bytes: 1024 of them fit exactly, and one byte more must not split the next.
36
+ expect(oneLine('é'.repeat(2000))).toBe('é'.repeat(1024))
37
+ expect(oneLine(`a${'é'.repeat(2000)}`)).toBe(`a${'é'.repeat(1023)}`)
38
+ // '🙂' is four bytes.
39
+ const cut = oneLine(`ab${'🙂'.repeat(600)}`)
40
+ expect(cut).toBe(`ab${'🙂'.repeat(511)}`)
41
+ expect(new TextEncoder().encode(cut).length).toBeLessThanOrEqual(2048)
42
+ expect(msgOf(report({ state: 'working', msg: 'é'.repeat(2000) }))).toBe('é'.repeat(1024))
43
+ })
package/src/status.ts ADDED
@@ -0,0 +1,63 @@
1
+ // Status reports for terminals that read the Program Status Protocol (OSC 7501, revision 0.4:
2
+ // https://www.superlogical.com/rex/docs/build/program-status), so a terminal can show that Able is working, waiting
3
+ // on the operator, done or failed. A terminal ignores an OSC it does not know, so nothing is asked first; and nothing
4
+ // is sent unless stdout is a terminal, so `--json` output and pipes stay clean.
5
+ //
6
+ // A report is `ESC ] 7501 ;`, `key=value` pairs joined by `:`, then `ESC \`. Each one replaces the record whole, so
7
+ // every report repeats `app`. Only the root record is used: no feature query, no ids, no child records.
8
+
9
+ export interface Report {
10
+ state: 'idle' | 'working' | 'done' | 'blocked' | 'error' | 'clear'
11
+ /** One line for the operator. */
12
+ msg?: string
13
+ /** What a `blocked` program waits for. */
14
+ kind?: 'permission' | 'question' | 'auth'
15
+ /** 0 to 100, with `working` or `blocked`. */
16
+ progress?: number
17
+ }
18
+
19
+ const maxBytes = 2048
20
+
21
+ /** A message as the protocol takes it: one line with no control characters (a terminal discards the whole report for
22
+ * one, newline and tab included), at most 2048 bytes of UTF-8, cut on a character boundary. Colour codes go first. */
23
+ export function oneLine(msg: string) {
24
+ const clean = msg
25
+ .replace(/\x1b\[[0-9;]*m/g, '')
26
+ .replace(/[\u0000-\u001f\u007f-\u009f]+/g, ' ')
27
+ .replace(/ {2,}/g, ' ')
28
+ .trim()
29
+ const bytes = new TextEncoder().encode(clean)
30
+ if (bytes.length <= maxBytes) return clean
31
+ // A UTF-8 continuation byte is 10xxxxxx: step back to the start of the character the limit falls in.
32
+ let end = maxBytes
33
+ while ((bytes[end]! & 0xc0) === 0x80) end--
34
+ return new TextDecoder().decode(bytes.subarray(0, end))
35
+ }
36
+
37
+ /** The bytes of one report. `kind` and `progress` go only with the states that take them. */
38
+ export function report({ state, msg, kind, progress }: Report) {
39
+ const pairs = [`state=${state}`, 'app=able']
40
+ if (kind && state === 'blocked') pairs.push(`kind=${kind}`)
41
+ if (progress !== undefined && Number.isFinite(progress) && (state === 'working' || state === 'blocked')) pairs.push(`progress=${Math.min(100, Math.max(0, Math.round(progress)))}`)
42
+ const text = msg ? oneLine(msg) : ''
43
+ if (text) pairs.push(`msg=${Buffer.from(text).toString('base64')}`)
44
+ return `\x1b]7501;${pairs.join(':')}\x1b\\`
45
+ }
46
+
47
+ /** A command's `working` reports, each a step under one prefix: `working('merge x')('checks')`. */
48
+ export const working = (prefix: string) => (step: string) => status({ state: 'working', msg: `${prefix}: ${step}` })
49
+
50
+ const onInterrupt = () => {
51
+ process.stdout.write(report({ state: 'idle' }))
52
+ process.exit(130)
53
+ }
54
+
55
+ /** Sends a report, on a terminal only. While `working`, an interrupt reports `idle` (best effort: a terminal drops
56
+ * `working` itself when the process exits). Not while `blocked`: a handler would keep Ctrl-C from ending a prompt,
57
+ * which reads the terminal without returning to the event loop. */
58
+ export function status(r: Report) {
59
+ if (!process.stdout.isTTY) return
60
+ process.stdout.write(report(r))
61
+ process.off('SIGINT', onInterrupt)
62
+ if (r.state === 'working') process.once('SIGINT', onInterrupt)
63
+ }
package/src/ui.ts CHANGED
@@ -1,4 +1,7 @@
1
- // Terminal output shared by the commands: colour only on a terminal.
1
+ // Terminal output shared by the commands: colour only on a terminal, and each command's state reported to terminals
2
+ // that show it (status.ts).
3
+
4
+ import { status } from './status.ts'
2
5
 
3
6
  export const tty = Boolean(process.stdout.isTTY)
4
7
  const paint = (code: number) => (s: string) => (tty ? `\x1b[${code}m${s}\x1b[0m` : s)
@@ -12,10 +15,24 @@ export const red = paint(31)
12
15
  export const green = paint(32)
13
16
  export const yellow = paint(33)
14
17
 
18
+ /** Prints the message, reports the error and exits 1. */
15
19
  export function fail(message: string): never {
20
+ status({ state: 'error', msg: message })
16
21
  console.error(`\n ${red('able:')} ${message}\n`)
17
22
  process.exit(1)
18
23
  }
19
24
 
20
- /** Asks on the terminal; anything but y or yes is a no. */
21
- export const confirm = (question: string) => /^y(es)?$/i.test(prompt(` ${question} [y/N]`) ?? '')
25
+ /** Stops because the operator said no: printed like a failure, but reported as idle, since nothing went wrong. */
26
+ export function cancel(message: string): never {
27
+ status({ state: 'idle' })
28
+ console.error(`\n ${yellow('able:')} ${message}\n`)
29
+ process.exit(1)
30
+ }
31
+
32
+ /** Asks on the terminal; anything but y or yes is a no. Reported as blocked on a question until answered. */
33
+ export function confirm(question: string) {
34
+ status({ state: 'blocked', kind: 'question', msg: question })
35
+ const yes = /^y(es)?$/i.test(prompt(` ${question} [y/N]`) ?? '')
36
+ status({ state: 'working' })
37
+ return yes
38
+ }
@@ -1,4 +1,4 @@
1
- // able ws: the Workspaces module (knowledge/modules/workspaces.md).
1
+ // able ws: the Workspaces module (knowledge/product/modules/workspaces.md).
2
2
  //
3
3
  // able ws new <slug> [--no-fetch] a worktree on feat/<slug> from the trunk, with the host's copy and onCreate
4
4
  // able ws ls [--json] every checkout: offset, services, tree, resources held
@@ -12,7 +12,8 @@ import { existsSync, readFileSync } from 'node:fs'
12
12
  import { join, relative } from 'node:path'
13
13
  import { runChecks, runMergeChecks } from '../checks.ts'
14
14
  import { count, dirtyCount, fetchTrunk, git, gitLoud, gitQuiet, lines, mergeOrFail } from '../git.ts'
15
- import { bold, confirm, dim, fail, green, yellow } from '../ui.ts'
15
+ import { status, working } from '../status.ts'
16
+ import { bold, cancel, confirm, dim, fail, green, yellow } from '../ui.ts'
16
17
  import { inWorkspace } from './state.ts'
17
18
 
18
19
  const args = process.argv.slice(4)
@@ -27,6 +28,8 @@ if (dirty && !msg) fail(`${dirty} uncommitted file(s); commit them (able commit)
27
28
  const brief = join(ws.path, config.journal, 'workspaces', `${ws.slug}.md`)
28
29
  if (existsSync(brief) && !readFileSync(brief, 'utf8').includes('\n## Ledger\n')) fail(`${relative(ws.path, brief)} has no ## Ledger; close the workspace first (the able-close-ws skill), then merge`)
29
30
 
31
+ const step = working(`merge ${ws.slug}`)
32
+ step(`fetching ${trunk}`)
30
33
  fetchTrunk(ws.path, trunk)
31
34
  const ahead = count(ws.path, `origin/${trunk}..HEAD`)
32
35
  const behind = count(ws.path, `HEAD..origin/${trunk}`)
@@ -35,22 +38,29 @@ console.log(`\n ${bold(`Merge ${ws.branch} into ${trunk}`)}`)
35
38
  console.log(` ${ahead} commit(s) to merge${dirty ? `, +${dirty} uncommitted → "${msg}"` : ''}; ${trunk} is ${behind} commit(s) ahead${behind ? ', merged in first' : ''}`)
36
39
  if (!ahead && !dirty) {
37
40
  console.log(dim(' nothing to merge\n'))
41
+ status({ state: 'done', msg: `merge ${ws.slug}: nothing to merge` })
38
42
  process.exit(0)
39
43
  }
40
- if (!args.includes('--yes') && !confirm(`Merge ${trunk} in, run the checks, and push to ${trunk}?`)) fail('aborted; nothing pushed')
44
+ if (!args.includes('--yes') && !confirm(`Merge ${trunk} in, run the checks, and push to ${trunk}?`)) cancel('aborted; nothing pushed')
41
45
 
42
46
  const commitAll = (message: string) => gitLoud(ws.path, 'add', '-A') && gitLoud(ws.path, 'commit', '--quiet', '-m', message)
43
47
  if (dirty && msg && !commitAll(msg)) fail('commit failed')
44
- if (behind) mergeOrFail(ws.path, `origin/${trunk}`, ws.branch, 'resolve them here, commit the merge, then run able ws merge again')
48
+ if (behind) {
49
+ step(`merging ${trunk} in`)
50
+ mergeOrFail(ws.path, `origin/${trunk}`, ws.branch, 'resolve them here, commit the merge, then run able ws merge again')
51
+ }
45
52
 
53
+ step('checks')
46
54
  const checked = runChecks(config, lines(ws.path, 'diff', '--name-only', `origin/${trunk}...HEAD`), ws) && runMergeChecks(config, ws)
47
55
  if (!checked) fail('a check failed; fix it here, commit, and run it again; nothing was pushed')
48
56
  // A check that formats files leaves them changed: they go in before the merge.
49
57
  if (dirtyCount(ws.path) && !commitAll('Format before merging')) fail('could not commit what the checks changed')
50
58
 
59
+ step(`pushing ${ws.branch}`)
51
60
  if (!gitLoud(ws.path, 'push', '--quiet', '-u', 'origin', ws.branch)) fail(`push of ${ws.branch} failed`)
52
61
 
53
62
  // The branch already holds the trunk, so this merge cannot conflict.
63
+ step(`pushing the merge to ${trunk}`)
54
64
  if (!gitLoud(ws.path, 'checkout', '--quiet', '--detach', `origin/${trunk}`) || !gitLoud(ws.path, 'merge', '--quiet', '--no-ff', '-m', `Merge ${ws.branch}`, ws.branch))
55
65
  fail('could not build the merge commit')
56
66
  const merged = git(ws.path, 'rev-parse', 'HEAD')
@@ -68,3 +78,4 @@ console.log(
68
78
  : yellow(` main checkout not updated${onTrunk ? ': its own changes are in the way' : `: it is not on ${trunk}`}; pull it there: git pull --ff-only`),
69
79
  )
70
80
  console.log(`\n ${dim('next, from the main checkout:')} able ws rm ${ws.slug}\n`)
81
+ status({ state: 'done', msg: `merge: ${ws.branch} is on ${trunk}` })
@@ -1,23 +1,26 @@
1
- // able ws new <slug> [--brief] [--no-fetch]: a worktree on `feat/<slug>` cut from origin's trunk, in `workspaces.dir`, then
2
- // what a worktree can't inherit: the host's `copy` files and its `onCreate` commands, with this workspace's facts in
3
- // `ABLE_WS_*`. Services are not started: `able ws start` does that. Every check runs before anything is created.
1
+ // able ws new <slug> [--no-brief] [--no-fetch]: a worktree on `feat/<slug>` cut from origin's trunk, in `workspaces.dir`,
2
+ // then what a worktree can't inherit: the host's `copy` files and its `onCreate` commands, with this workspace's facts
3
+ // in `ABLE_WS_*`. Services are not started: `able ws start` does that. Every check runs before anything is created.
4
4
  //
5
- // `--brief` first publishes the workspace's brief, `<journal>/workspaces/<slug>.md`, from the main checkout on the trunk:
6
- // it commits that file alone after its checks, when it has changes, and pushes the trunk, so the cut carries it. It
7
- // refuses while the trunk has other unpushed commits, which would leave with it.
5
+ // The workspace's brief, `<journal>/workspaces/<slug>.md`, is published first when origin's trunk doesn't carry it as
6
+ // the main checkout has it: the file alone is committed after its checks (when it has changes) and the trunk pushed, so
7
+ // the cut carries it. Already on origin as it is here: nothing to publish. Nowhere: refused, unless `--no-brief`.
8
+ // Running it again after a failure picks up where it stopped: a brief committed but not pushed is pushed, since the
9
+ // only unpushed changes it allows are the brief's own. `--brief`, the old way to ask for this, is still accepted.
8
10
 
9
11
  import { copyFileSync, existsSync, mkdirSync } from 'node:fs'
10
12
  import { dirname, join, relative, resolve } from 'node:path'
11
13
  import { loadConfig, trailerArgs } from '../../config.ts'
12
14
  import { runChecks } from '../checks.ts'
13
- import { count, failOnMerge, fetchTrunk, git, gitLoud, mainRoot } from '../git.ts'
15
+ import { count, failOnMerge, fetchTrunk, git, gitLoud, gitQuiet, lines, mainRoot } from '../git.ts'
14
16
  import { runCommand } from '../run.ts'
17
+ import { status, working } from '../status.ts'
15
18
  import { bold, dim, fail, green, yellow } from '../ui.ts'
16
19
  import { branchOf, readState, workspaces, writeState } from './state.ts'
17
20
 
18
21
  const args = process.argv.slice(4)
19
22
  const slug = args.find((a) => !a.startsWith('-'))
20
- if (!slug) fail('usage: able ws new <slug> [--brief] [--no-fetch]')
23
+ if (!slug) fail('usage: able ws new <slug> [--no-brief] [--no-fetch]')
21
24
  if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) fail(`invalid name '${slug}': lowercase letters, digits and dashes only`)
22
25
 
23
26
  const main = mainRoot()
@@ -36,16 +39,28 @@ const taken = new Set(Object.values(state.workspaces).map((w) => w.portOffset))
36
39
  const { ports } = ws
37
40
  const portOffset = ports ? (Array.from({ length: ports.max }, (_, i) => (i + 1) * ports.step).find((o) => !taken.has(o)) ?? fail('no free port offset; remove a workspace first')) : 0
38
41
 
39
- if (!args.includes('--no-fetch')) fetchTrunk(main, config.trunk)
42
+ const step = working(`new ${slug}`)
43
+ if (!args.includes('--no-fetch')) {
44
+ step(`fetching ${config.trunk}`)
45
+ fetchTrunk(main, config.trunk)
46
+ }
47
+
48
+ const { trunk, journal } = config
49
+ const file = `${journal}/workspaces/${slug}.md`
50
+ const local = existsSync(join(main, file))
51
+ const onOrigin = gitQuiet(main, 'cat-file', '-e', `origin/${trunk}:${file}`)
52
+ // Untracked, edited, or committed differently from origin's trunk: the cut wouldn't carry it as it is here.
53
+ const differs = local && (Boolean(git(main, 'status', '--porcelain', '--', file)) || !gitQuiet(main, 'diff', '--quiet', `origin/${trunk}`, '--', file))
54
+ if (!local && !onOrigin && !args.includes('--no-brief')) fail(`no brief at ${file}; write it first, or pass --no-brief for a workspace without one`)
40
55
 
41
- if (args.includes('--brief')) {
42
- const { trunk, journal } = config
43
- const file = `${journal}/workspaces/${slug}.md`
44
- if (!existsSync(join(main, file))) fail(`no brief at ${file}; write it first`)
56
+ if (differs) {
45
57
  if (git(main, 'rev-parse', '--abbrev-ref', 'HEAD') !== trunk) fail(`the main checkout is not on ${trunk}`)
46
58
  failOnMerge(main)
47
- const unpushed = git(main, 'log', '--oneline', `origin/${trunk}..${trunk}`)
48
- if (unpushed) fail(`${trunk} has unpushed commits that would leave with the brief:\n${unpushed}`)
59
+ step('publishing the brief')
60
+ // Unpushed work other than the brief would leave with it. The brief's own commit (a run that stopped before its
61
+ // push) is fine: this run pushes it.
62
+ const others = lines(main, 'diff', '--name-only', `origin/${trunk}...${trunk}`).filter((f) => f !== file)
63
+ if (others.length) fail(`${trunk} has unpushed changes that would leave with the brief:\n${git(main, 'log', '--oneline', `origin/${trunk}..${trunk}`)}`)
49
64
  if (git(main, 'status', '--porcelain', '--', file)) {
50
65
  const at = { slug: 'main', path: main, portOffset: 0, main }
51
66
  if (!runChecks(config, [file], at)) fail('a check failed; nothing committed')
@@ -58,6 +73,7 @@ if (args.includes('--brief')) {
58
73
  const start = git(main, 'rev-parse', '--verify', '--quiet', `origin/${config.trunk}`) ? `origin/${config.trunk}` : config.trunk
59
74
 
60
75
  const started = Date.now()
76
+ step('adding the worktree')
61
77
  mkdirSync(dirname(path), { recursive: true })
62
78
  const added = Bun.spawnSync(['git', '-C', main, 'worktree', 'add', '--no-track', '-b', branch, path, start], { stdout: 'pipe', stderr: 'pipe' })
63
79
  if (added.exitCode !== 0) fail(`worktree add failed: ${added.stderr.toString().trim()}`)
@@ -71,6 +87,7 @@ for (const rel of ws.copy ?? []) {
71
87
  copyFileSync(join(main, rel), join(path, rel))
72
88
  }
73
89
 
90
+ if (ws.onCreate?.length) step('onCreate commands')
74
91
  const failed = (ws.onCreate ?? []).filter((c) => !runCommand(c, { slug, path, portOffset, main }))
75
92
 
76
93
  const brief = git(path, 'ls-files', `${config.journal}/workspaces/${slug}.md`)
@@ -80,3 +97,4 @@ console.log(` ${'port offset'.padEnd(12)} ${portOffset}`)
80
97
  console.log(` ${'brief'.padEnd(12)} ${brief || yellow(`none: ${config.trunk} has no ${config.journal}/workspaces/${slug}.md`)}`)
81
98
  if (failed.length) console.log(yellow(`\n ${failed.length} onCreate command(s) failed; run them inside the workspace`))
82
99
  console.log(`\n ${dim(`cd ${relative(process.cwd(), path)}`)}\n`)
100
+ status({ state: 'done', msg: `new: ${slug} is ready${failed.length ? `, ${failed.length} onCreate command(s) failed` : ''}` })
@@ -5,6 +5,7 @@
5
5
  // reaches a workspace without being pushed first. Refuses on uncommitted files.
6
6
 
7
7
  import { count, dirtyCount, fetchTrunk, git, gitQuiet, mergeOrFail } from '../git.ts'
8
+ import { status, working } from '../status.ts'
8
9
  import { bold, dim, fail, green, yellow } from '../ui.ts'
9
10
  import { inWorkspace } from './state.ts'
10
11
 
@@ -13,6 +14,8 @@ const { trunk } = config
13
14
  const dirty = dirtyCount(ws.path)
14
15
  if (dirty) fail(`${dirty} uncommitted file(s); commit them first, so the merge stays separable from your work`)
15
16
 
17
+ const step = working(`refresh ${ws.slug}`)
18
+ step(`fetching ${trunk}`)
16
19
  fetchTrunk(ws.path, trunk)
17
20
  const contains = (outer: string, inner: string) => gitQuiet(ws.path, 'merge-base', '--is-ancestor', inner, outer)
18
21
  const local = git(ws.path, 'rev-parse', '--verify', '--quiet', trunk) ? trunk : ''
@@ -27,6 +30,8 @@ for (const source of sources.filter(Boolean)) {
27
30
  }
28
31
  const unpushed = source === trunk && remote ? count(ws.path, `${remote}..${trunk}`) : 0
29
32
  console.log(` ${bold(source)}: ${behind} commit(s)${unpushed ? yellow(`; ${unpushed} not on origin yet, they reach it when this workspace is merged`) : ''}`)
33
+ step(`merging ${source}`)
30
34
  mergeOrFail(ws.path, source, ws.branch, 'resolve them here and commit the merge, or abort it with git merge --abort')
31
35
  }
32
36
  console.log(`\n${green('✓')} ${bold(ws.branch)} holds ${trunk}\n`)
37
+ status({ state: 'done', msg: `refresh: ${ws.branch} holds ${trunk}` })
package/sync.ts CHANGED
@@ -15,14 +15,13 @@
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 { status, working } from './src/status.ts'
19
+ import { fail as failWith } from './src/ui.ts'
18
20
 
19
21
  const args = process.argv.slice(3)
20
22
  const dry = args.includes('--dry-run')
21
23
 
22
- function fail(message: string): never {
23
- console.error(`able sync: ${message}`)
24
- process.exit(1)
25
- }
24
+ const fail = (message: string) => failWith(`sync: ${message}`)
26
25
 
27
26
  function run(cmd: string[], cwd: string) {
28
27
  const r = Bun.spawnSync(cmd, { cwd, stdout: 'pipe', stderr: 'pipe' })
@@ -41,6 +40,8 @@ if (resolve(root, git('rev-parse', '--git-dir')) !== resolve(root, git('rev-pars
41
40
  process.exit(0)
42
41
  }
43
42
 
43
+ const step = working('sync')
44
+ step(`fetching ${trunk}`)
44
45
  Bun.spawnSync(['git', 'fetch', '--quiet', 'origin', trunk], { cwd: root, stdout: 'ignore', stderr: 'ignore' })
45
46
  const behind = Number(git('rev-list', '--count', `HEAD..origin/${trunk}`) || '0')
46
47
  if (behind) fail(`this checkout is ${behind} commit(s) behind origin/${trunk}; pull first, or the records merged since are missed. Nothing done.`)
@@ -76,6 +77,7 @@ const bullets = (slug: string, block: string): Item[] =>
76
77
  // ── Merged workspaces and their briefs ────────────────────────────────────────────────────────
77
78
 
78
79
  type Merged = { slug: string; hash: string; at: number; brief?: string }
80
+ step('reading merged workspaces')
79
81
  const merges = new Map<string, Merged>()
80
82
  for (const line of git('log', `origin/${trunk}`, '--merges', '--format=%H%x09%ct%x09%s').split('\n').filter(Boolean)) {
81
83
  const [hash = '', at = '0', subject = ''] = line.split('\t')
@@ -95,6 +97,7 @@ for (const m of merges.values()) m.brief = briefs.get(m.slug)
95
97
 
96
98
  // ── Follow-ups ────────────────────────────────────────────────────────────────────────────────
97
99
 
100
+ step('follow-ups')
98
101
  type Issue = { number: number; title: string; state: string; url: string; body: string; createdAt: string; closedAt: string | null }
99
102
  const repo = (JSON.parse(gh('repo', 'view', '--json', 'nameWithOwner')) as { nameWithOwner: string }).nameWithOwner
100
103
  const labels = new Set((JSON.parse(gh('label', 'list', '--limit', '1000', '--json', 'name')) as { name: string }[]).map((l) => l.name))
@@ -149,6 +152,7 @@ for (const m of merges.values()) {
149
152
  // ── Week records: calendar weeks, Monday 00:00 to Monday 00:00 local time ─────────────────────
150
153
 
151
154
  const DAY = 86_400_000
155
+ step('week records')
152
156
  const monday = (t: number) => {
153
157
  const d = new Date(t)
154
158
  d.setHours(0, 0, 0, 0)
@@ -266,7 +270,11 @@ for (const i of filed) console.log(` ${verb('filed', 'file')} ${i.slug}: ${i.
266
270
  for (const c of closed) console.log(` ${verb('closed', 'close')} #${c.number} (${c.slug})`)
267
271
  for (const w of written) console.log(` ${verb('wrote', 'write')} ${w}`)
268
272
 
269
- if (!written.length || dry) process.exit(0)
273
+ const summary = `sync: ${filed.length} follow-up(s) ${verb('filed', 'to file')}, ${closed.length} ${verb('closed', 'to close')}, ${written.length} week record(s) ${verb('written', 'to write')}`
274
+ if (!written.length || dry) {
275
+ status({ state: 'done', msg: summary })
276
+ process.exit(0)
277
+ }
270
278
 
271
279
  // Able commits its own records and nothing else; anything already waiting to be pushed is the operator's.
272
280
  const reasons = [
@@ -276,10 +284,12 @@ const reasons = [
276
284
  ].filter(Boolean)
277
285
  if (reasons.length) {
278
286
  console.log(`able sync: left the record(s) uncommitted: ${reasons.join(', ')}`)
287
+ status({ state: 'done', msg: `${summary}, left uncommitted` })
279
288
  process.exit(0)
280
289
  }
281
290
  const names = due.map(weekName).join(', ')
282
291
  const able = [process.execPath, join(import.meta.dir, 'able.ts')]
292
+ step('publishing the week records')
283
293
  for (const cmd of [
284
294
  [...able, 'commit', `journal: week record ${names}`, ...written, '--yes'],
285
295
  [...able, 'push'],
@@ -288,3 +298,4 @@ for (const cmd of [
288
298
  if (r.exitCode !== 0) fail(`able ${cmd[2]} failed; the record(s) are written but not published`)
289
299
  }
290
300
  console.log(`able sync: committed and pushed ${names}`)
301
+ status({ state: 'done', msg: `${summary}, committed and pushed` })