@able-autonomy/able 0.0.14 → 0.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,18 +1,38 @@
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).
2
3
 
3
- const tty = Boolean(process.stdout.isTTY)
4
+ import { status } from './status.ts'
5
+
6
+ export const tty = Boolean(process.stdout.isTTY)
4
7
  const paint = (code: number) => (s: string) => (tty ? `\x1b[${code}m${s}\x1b[0m` : s)
5
8
 
9
+ /** One of the terminal's 256 colours, on a terminal only. */
10
+ export const paint256 = (code: number) => (s: string) => (tty ? `\x1b[38;5;${code}m${s}\x1b[0m` : s)
11
+
6
12
  export const dim = paint(2)
7
13
  export const bold = paint(1)
8
14
  export const red = paint(31)
9
15
  export const green = paint(32)
10
16
  export const yellow = paint(33)
11
17
 
18
+ /** Prints the message, reports the error and exits 1. */
12
19
  export function fail(message: string): never {
20
+ status({ state: 'error', msg: message })
13
21
  console.error(`\n ${red('able:')} ${message}\n`)
14
22
  process.exit(1)
15
23
  }
16
24
 
17
- /** Asks on the terminal; anything but y or yes is a no. */
18
- 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}` })
@@ -12,6 +12,7 @@ import { loadConfig, trailerArgs } from '../../config.ts'
12
12
  import { runChecks } from '../checks.ts'
13
13
  import { count, failOnMerge, fetchTrunk, git, gitLoud, mainRoot } from '../git.ts'
14
14
  import { runCommand } from '../run.ts'
15
+ import { status, working } from '../status.ts'
15
16
  import { bold, dim, fail, green, yellow } from '../ui.ts'
16
17
  import { branchOf, readState, workspaces, writeState } from './state.ts'
17
18
 
@@ -36,7 +37,11 @@ const taken = new Set(Object.values(state.workspaces).map((w) => w.portOffset))
36
37
  const { ports } = ws
37
38
  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
39
 
39
- if (!args.includes('--no-fetch')) fetchTrunk(main, config.trunk)
40
+ const step = working(`new ${slug}`)
41
+ if (!args.includes('--no-fetch')) {
42
+ step(`fetching ${config.trunk}`)
43
+ fetchTrunk(main, config.trunk)
44
+ }
40
45
 
41
46
  if (args.includes('--brief')) {
42
47
  const { trunk, journal } = config
@@ -44,6 +49,7 @@ if (args.includes('--brief')) {
44
49
  if (!existsSync(join(main, file))) fail(`no brief at ${file}; write it first`)
45
50
  if (git(main, 'rev-parse', '--abbrev-ref', 'HEAD') !== trunk) fail(`the main checkout is not on ${trunk}`)
46
51
  failOnMerge(main)
52
+ step('publishing the brief')
47
53
  const unpushed = git(main, 'log', '--oneline', `origin/${trunk}..${trunk}`)
48
54
  if (unpushed) fail(`${trunk} has unpushed commits that would leave with the brief:\n${unpushed}`)
49
55
  if (git(main, 'status', '--porcelain', '--', file)) {
@@ -58,6 +64,7 @@ if (args.includes('--brief')) {
58
64
  const start = git(main, 'rev-parse', '--verify', '--quiet', `origin/${config.trunk}`) ? `origin/${config.trunk}` : config.trunk
59
65
 
60
66
  const started = Date.now()
67
+ step('adding the worktree')
61
68
  mkdirSync(dirname(path), { recursive: true })
62
69
  const added = Bun.spawnSync(['git', '-C', main, 'worktree', 'add', '--no-track', '-b', branch, path, start], { stdout: 'pipe', stderr: 'pipe' })
63
70
  if (added.exitCode !== 0) fail(`worktree add failed: ${added.stderr.toString().trim()}`)
@@ -71,6 +78,7 @@ for (const rel of ws.copy ?? []) {
71
78
  copyFileSync(join(main, rel), join(path, rel))
72
79
  }
73
80
 
81
+ if (ws.onCreate?.length) step('onCreate commands')
74
82
  const failed = (ws.onCreate ?? []).filter((c) => !runCommand(c, { slug, path, portOffset, main }))
75
83
 
76
84
  const brief = git(path, 'ls-files', `${config.journal}/workspaces/${slug}.md`)
@@ -80,3 +88,4 @@ console.log(` ${'port offset'.padEnd(12)} ${portOffset}`)
80
88
  console.log(` ${'brief'.padEnd(12)} ${brief || yellow(`none: ${config.trunk} has no ${config.journal}/workspaces/${slug}.md`)}`)
81
89
  if (failed.length) console.log(yellow(`\n ${failed.length} onCreate command(s) failed; run them inside the workspace`))
82
90
  console.log(`\n ${dim(`cd ${relative(process.cwd(), path)}`)}\n`)
91
+ 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` })