@able-autonomy/able 0.0.2 → 0.0.3

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
@@ -101,8 +101,15 @@ if (command === 'config') {
101
101
  console.log(JSON.stringify(await loadConfig(hostRoot()), null, args.includes('--json') ? undefined : 2))
102
102
  process.exit(0)
103
103
  }
104
+ const modules: Record<string, string> = { commit: './src/commit.ts', push: './src/push.ts', ws: './src/workspaces/index.ts' }
105
+ if (command && modules[command]) {
106
+ await import(modules[command])
107
+ process.exit(0)
108
+ }
104
109
  if (command !== 'gh') {
105
- console.error('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')
110
+ console.error(
111
+ "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 ws <new|ls|current|refresh|merge|rm|start|stop|status|take> workspaces",
112
+ )
106
113
  process.exit(command ? 1 : 0)
107
114
  }
108
115
 
package/config.ts CHANGED
@@ -3,22 +3,51 @@
3
3
 
4
4
  import { existsSync } from 'node:fs'
5
5
  import { join } from 'node:path'
6
+ import { fail } from './src/ui.ts'
7
+
8
+ /** A host command: a shell line, run in its folder (the checkout's root, or `cwd` from it). */
9
+ export type Command = string | { run: string; cwd?: string }
10
+
11
+ /** A long-running process of a workspace. A `ready` port is the main checkout's; Able adds the workspace's offset. */
12
+ export interface Service {
13
+ start: string
14
+ stop?: string
15
+ ready?: { cmd: string } | { port: number }
16
+ needs?: string[]
17
+ cwd?: string
18
+ }
19
+
20
+ export interface WorkspacesConfig {
21
+ /** Where workspaces live, from the main checkout's root. */
22
+ dir: string
23
+ /** Offsets Able hands out, `step` apart, up to `max` workspaces. Without it, one workspace at a time, at offset 0. */
24
+ ports?: { step: number; max: number }
25
+ /** Gitignored files a worktree needs, copied from the main checkout. */
26
+ copy?: string[]
27
+ onCreate?: Command[]
28
+ onRemove?: Command[]
29
+ services?: Record<string, Service>
30
+ /** Shared resources with one holder at a time on a machine (the tunnel, the devices): `able ws take` runs `take` and
31
+ * records the holder. An `auto` one is taken by `able ws start` and goes back to its earlier holder at `able ws stop`. */
32
+ resources?: Record<string, { take: Command; auto?: boolean }>
33
+ }
6
34
 
7
35
  export interface AbleConfig {
36
+ /** `commit`: per folder from the root (`.` for the root itself), run in order for the folders a commit or a landing
37
+ * touches; any failure stops it. Kept fast: release checks (builds, tests) come with the Release module (97). */
38
+ checks?: { commit?: Record<string, Command[]> }
39
+ workspaces?: WorkspacesConfig
8
40
  /** The branch workspaces are cut from and land on. */
9
41
  trunk: string
10
42
  /** The journal's folder from the root: `workspaces/<slug>.md` briefs and `weeks/<yyyy>-w<ww>.md` records. */
11
43
  journal: string
44
+ /** The knowledge folder from the root: the docs the dashboard shows. Optional: without it, no docs view. */
45
+ knowledge?: string
12
46
  }
13
47
 
14
48
  /** Types and editor help for `able.config.ts`; returns the config unchanged. */
15
49
  export const defineConfig = (config: AbleConfig): AbleConfig => config
16
50
 
17
- function fail(message: string): never {
18
- console.error(`able: ${message}`)
19
- process.exit(1)
20
- }
21
-
22
51
  /** The root of the checkout the command runs in. */
23
52
  export function hostRoot() {
24
53
  const r = Bun.spawnSync(['git', 'rev-parse', '--show-toplevel'], { stdout: 'pipe', stderr: 'pipe' })
@@ -30,7 +59,9 @@ export async function loadConfig(root: string): Promise<AbleConfig> {
30
59
  const path = join(root, 'able.config.ts')
31
60
  if (!existsSync(path)) fail(`no able.config.ts at ${root}. Run Able's onboarding to set this project up.`)
32
61
  const config = (await import(path)).default as Partial<AbleConfig> | undefined
62
+ if (config?.workspaces && typeof config.workspaces.dir !== 'string') fail(`${path}: workspaces needs a dir`)
33
63
  const missing = (['trunk', 'journal'] as const).filter((key) => typeof config?.[key] !== 'string' || !config[key])
34
64
  if (missing.length) fail(`${path} is missing ${missing.join(', ')}`)
65
+ if (config?.knowledge !== undefined && (typeof config.knowledge !== 'string' || !config.knowledge)) fail(`${path}: knowledge must be a folder name`)
35
66
  return config as AbleConfig
36
67
  }
package/index.ts CHANGED
@@ -1 +1 @@
1
- export { defineConfig, type AbleConfig } from './config.ts'
1
+ export { defineConfig, type AbleConfig, type Command, type Service, type WorkspacesConfig } from './config.ts'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@able-autonomy/able",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
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",
@@ -15,7 +15,8 @@
15
15
  "able.ts",
16
16
  "config.ts",
17
17
  "index.ts",
18
- "sync.ts"
18
+ "sync.ts",
19
+ "src"
19
20
  ],
20
21
  "publishConfig": {
21
22
  "access": "public"
package/src/checks.ts ADDED
@@ -0,0 +1,20 @@
1
+ // A host's commit checks, per folder (decisions 73, 93, 97): only the folders a change touches run theirs, in their own folder.
2
+
3
+ import type { AbleConfig } from '../config.ts'
4
+ import { runCommand, type Place } from './run.ts'
5
+ import { bold } from './ui.ts'
6
+
7
+ /** The folder a path belongs to: the longest `checks.commit` key it sits in, else `.` when the root has checks. */
8
+ export const folderOf = (path: string, folders: string[]) =>
9
+ folders.filter((f) => f !== '.' && (path === f || path.startsWith(`${f}/`))).sort((a, b) => b.length - a.length)[0] ?? (folders.includes('.') ? '.' : undefined)
10
+
11
+ /** Runs the checks of every folder the paths touch; false at the first failure. */
12
+ export function runChecks(config: AbleConfig, paths: string[], at: Place): boolean {
13
+ const checks = config.checks?.commit ?? {}
14
+ const folders = [...new Set(paths.map((p) => folderOf(p, Object.keys(checks))).filter((f): f is string => Boolean(f)))].sort()
15
+ for (const folder of folders) {
16
+ console.log(`\n ${bold(folder)}`)
17
+ for (const c of checks[folder] ?? []) if (!runCommand(c, at, { base: `${at.path}/${folder}` })) return false
18
+ }
19
+ return true
20
+ }
package/src/commit.ts ADDED
@@ -0,0 +1,55 @@
1
+ // able commit: a pathspec commit after the checks of every folder it touches (decisions 72, 73).
2
+ //
3
+ // able commit "message" everything uncommitted under the current folder
4
+ // able commit "message" <path>… only those paths, whatever else is uncommitted
5
+ // able commit "message" --dry list what would go in and run nothing
6
+ // able commit "message" --yes no confirmation
7
+ //
8
+ // It runs in the main checkout and in a workspace alike. It never versions, tags or pushes.
9
+
10
+ import { existsSync } from 'node:fs'
11
+ import { join, relative, resolve } from 'node:path'
12
+ import { loadConfig } from '../config.ts'
13
+ import { runChecks } from './checks.ts'
14
+ import { failOnMerge, git, gitLoud } from './git.ts'
15
+ import { bold, confirm, dim, fail, green } from './ui.ts'
16
+ import { current } from './workspaces/state.ts'
17
+
18
+ const argv = process.argv.slice(3)
19
+ const [msg, ...named] = argv.filter((a) => !a.startsWith('--'))
20
+ if (!msg) fail('usage: able commit "<message>" [<path>…] [--dry] [--yes]')
21
+
22
+ const at = await current()
23
+ const root = at.path
24
+ failOnMerge(root)
25
+
26
+ const scope = named.length ? named.map((p) => relative(root, resolve(p))) : [relative(root, process.cwd()) || '.']
27
+ // `-z`: one NUL-ended entry per path, unquoted; a rename or copy is followed by its old path, which goes in too.
28
+ const changed = () => {
29
+ const entries = git(root, 'status', '--porcelain', '-z', '--untracked-files=all', '--', ...scope)
30
+ .split('\0')
31
+ .filter(Boolean)
32
+ const paths: string[] = []
33
+ for (let i = 0; i < entries.length; i++) {
34
+ const entry = entries[i] ?? ''
35
+ paths.push(entry.slice(3))
36
+ if (/[RC]/.test(entry.slice(0, 2))) paths.push(entries[++i] ?? '')
37
+ }
38
+ return paths
39
+ }
40
+
41
+ const before = changed()
42
+ if (!before.length) fail('nothing to commit')
43
+ console.log(`\n ${bold(`${before.length} file(s)`)} ${dim(scope.join(' '))}`)
44
+ 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')
47
+
48
+ if (!runChecks(await loadConfig(root), before, at)) fail('a check failed; nothing committed')
49
+
50
+ // The checks may have formatted files, so the list is read again.
51
+ const paths = changed()
52
+ // A path that is gone (a deletion, a rename's old name) has nothing to add, but still goes into the commit.
53
+ const present = paths.filter((p) => existsSync(join(root, p)))
54
+ if ((present.length && !gitLoud(root, 'add', '--', ...present)) || !gitLoud(root, 'commit', '--quiet', '-m', msg, '--', ...paths)) fail('git commit failed')
55
+ console.log(`\n ${green('✓')} ${git(root, 'log', '--oneline', '-1')}\n`)
package/src/git.ts ADDED
@@ -0,0 +1,47 @@
1
+ // The git calls every command shares: capture output, stream it, or stay quiet; and the questions commands keep
2
+ // asking (dirty, unpushed, behind, merge in progress) answered once.
3
+
4
+ import { dirname, resolve } from 'node:path'
5
+ import { dim, fail, red } from './ui.ts'
6
+
7
+ const spawn = (cwd: string, args: string[], stdio: 'inherit' | 'ignore') => Bun.spawnSync(['git', '-C', cwd, ...args], { stdout: stdio, stderr: stdio })
8
+
9
+ /** Stdout, or '' when git fails: for questions where no answer means no. */
10
+ export const git = (cwd: string, ...args: string[]) => {
11
+ const r = Bun.spawnSync(['git', '-C', cwd, ...args], { stdout: 'pipe', stderr: 'pipe' })
12
+ // trimEnd: porcelain output starts with a status column that may be a space.
13
+ return r.exitCode === 0 ? r.stdout.toString().trimEnd() : ''
14
+ }
15
+
16
+ /** Runs git with its output on the terminal; true when it succeeds. */
17
+ export const gitLoud = (cwd: string, ...args: string[]) => spawn(cwd, args, 'inherit').exitCode === 0
18
+
19
+ /** Runs git silently; true when it succeeds. */
20
+ export const gitQuiet = (cwd: string, ...args: string[]) => spawn(cwd, args, 'ignore').exitCode === 0
21
+
22
+ export const lines = (cwd: string, ...args: string[]) =>
23
+ git(cwd, ...args)
24
+ .split('\n')
25
+ .filter(Boolean)
26
+
27
+ /** The number of commits in a range, e.g. `HEAD..origin/main`. */
28
+ export const count = (cwd: string, ...range: string[]) => Number(git(cwd, 'rev-list', '--count', ...range) || '0')
29
+
30
+ export const dirtyCount = (cwd: string) => lines(cwd, 'status', '--porcelain').length
31
+
32
+ /** Commits reachable from HEAD and from no remote ref: what exists only here. */
33
+ export const unpushedCount = (cwd: string) => count(cwd, 'HEAD', '--not', '--remotes')
34
+
35
+ export const fetchTrunk = (cwd: string, trunk: string) => gitQuiet(cwd, 'fetch', '--quiet', 'origin', trunk)
36
+
37
+ export const failOnMerge = (cwd: string) => git(cwd, 'rev-parse', '-q', '--verify', 'MERGE_HEAD') && fail('a merge is in progress; finish it (commit) or abort it first')
38
+
39
+ /** Merges `source` in, or fails naming the conflicting files. */
40
+ export function mergeOrFail(cwd: string, source: string, branch: string, hint: string) {
41
+ if (gitQuiet(cwd, 'merge', '--no-edit', source)) return
42
+ const files = lines(cwd, 'diff', '--name-only', '--diff-filter=U')
43
+ fail(`${red('conflict')} merging ${source} into ${branch}:\n${files.map((f) => ` ${f}`).join('\n')}\n ${dim(hint)}`)
44
+ }
45
+
46
+ /** The main checkout's root, from inside it or any of its worktrees. */
47
+ export const mainRoot = (cwd = process.cwd()) => dirname(resolve(cwd, git(cwd, 'rev-parse', '--git-common-dir')))
package/src/push.ts ADDED
@@ -0,0 +1,11 @@
1
+ // able push: pushes the branch the checkout is on, with its tags. A workspace lands with `able ws merge` instead.
2
+
3
+ import { gitLoud } from './git.ts'
4
+ import { fail, green } from './ui.ts'
5
+ import { current } from './workspaces/state.ts'
6
+
7
+ const at = await current()
8
+ if (at.isWorkspace) fail('a workspace lands with: able ws merge')
9
+ if (!at.branch || at.branch === 'HEAD') fail('not on a branch')
10
+ if (!gitLoud(at.path, 'push', '--follow-tags', 'origin', at.branch)) fail(`push of ${at.branch} failed`)
11
+ console.log(`\n ${green('✓')} pushed ${at.branch}\n`)
package/src/run.ts ADDED
@@ -0,0 +1,44 @@
1
+ // Runs a host's commands (checks, hooks, services) in their folder, with the workspace's facts in `ABLE_WS_*`
2
+ // (decision 84). Every process Able starts for a host goes through `shellFor`.
3
+
4
+ import { resolve } from 'node:path'
5
+ import type { Command } from '../config.ts'
6
+ import { dim, red } from './ui.ts'
7
+
8
+ export interface Place {
9
+ slug: string
10
+ path: string
11
+ portOffset: number
12
+ main: string
13
+ }
14
+
15
+ /** The shell line, folder and environment for a host command: `cwd` is from `base`, the checkout's root by default. */
16
+ export function shellFor(at: Place, run: string, cwd = '.', base = at.path) {
17
+ return {
18
+ argv: ['sh', '-c', run],
19
+ cwd: resolve(base, cwd),
20
+ env: { ...process.env, ABLE_WS_SLUG: at.slug, ABLE_WS_PATH: at.path, ABLE_WS_PORT_OFFSET: String(at.portOffset), ABLE_WS_MAIN: at.main },
21
+ }
22
+ }
23
+
24
+ /** Runs one command; reported, its output is shown only when it fails. */
25
+ export function runCommand(c: Command, at: Place, { base = at.path, quiet = false } = {}): boolean {
26
+ const { run, cwd } = typeof c === 'string' ? { run: c } : c
27
+ const sh = shellFor(at, run, cwd, base)
28
+ const r = Bun.spawnSync(sh.argv, { cwd: sh.cwd, env: sh.env, stdout: 'pipe', stderr: 'pipe' })
29
+ if (quiet) return r.exitCode === 0
30
+ const where = sh.cwd === at.path ? '' : dim(` (${sh.cwd.slice(at.path.length + 1) || '.'})`)
31
+ console.log(` ${r.exitCode === 0 ? '✓' : red('✗')} ${run}${where}`)
32
+ if (r.exitCode !== 0)
33
+ console.log(
34
+ dim(
35
+ `${r.stdout}${r.stderr}`
36
+ .trim()
37
+ .split('\n')
38
+ .slice(-30)
39
+ .map((l) => ` │ ${l}`)
40
+ .join('\n'),
41
+ ),
42
+ )
43
+ return r.exitCode === 0
44
+ }
package/src/ui.ts ADDED
@@ -0,0 +1,18 @@
1
+ // Terminal output shared by the commands: colour only on a terminal.
2
+
3
+ const tty = Boolean(process.stdout.isTTY)
4
+ const paint = (code: number) => (s: string) => (tty ? `\x1b[${code}m${s}\x1b[0m` : s)
5
+
6
+ export const dim = paint(2)
7
+ export const bold = paint(1)
8
+ export const red = paint(31)
9
+ export const green = paint(32)
10
+ export const yellow = paint(33)
11
+
12
+ export function fail(message: string): never {
13
+ console.error(`\n ${red('able:')} ${message}\n`)
14
+ process.exit(1)
15
+ }
16
+
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]`) ?? '')
@@ -0,0 +1,36 @@
1
+ // able ws: the Workspaces module (knowledge/modules/workspaces.md).
2
+ //
3
+ // able ws new <slug> [--no-fetch] a worktree on feat/<slug> from the trunk, with the host's copy and onCreate
4
+ // able ws ls every checkout: offset, services, tree, resources held
5
+ // able ws current [--json] the checkout this runs in: slug, branch, path, port offset, main checkout
6
+ // able ws refresh merges the trunk into this workspace
7
+ // able ws merge ["message"] [--yes] lands this workspace on the trunk as `Land feat/<slug>`
8
+ // able ws rm <slug> [--force] stops and removes a workspace, deleting its branch once merged
9
+ // able ws start | stop [<service>…] the workspace's services, in dependency order
10
+ // able ws status the services running in this checkout
11
+ // able ws take <resource> moves a shared resource to this checkout
12
+
13
+ const [sub = '', ...args] = process.argv.slice(3)
14
+ const names = args.filter((a) => !a.startsWith('-'))
15
+
16
+ const commands: Record<string, () => Promise<unknown>> = {
17
+ new: () => import('./new.ts'),
18
+ ls: () => import('./ls.ts'),
19
+ rm: () => import('./rm.ts'),
20
+ refresh: () => import('./refresh.ts'),
21
+ merge: () => import('./merge.ts'),
22
+ take: () => import('./take.ts'),
23
+ current: async () => console.log(JSON.stringify(await (await import('./state.ts')).current(), null, args.includes('--json') ? undefined : 2)),
24
+ start: async () => (await import('./services.ts')).start(names),
25
+ stop: async () => (await import('./services.ts')).stop(names),
26
+ status: async () => (await import('./services.ts')).status(),
27
+ }
28
+
29
+ const command = commands[sub]
30
+ if (command) await command()
31
+ else {
32
+ console.error(`usage: able ws ${Object.keys(commands).join(' | ')}`)
33
+ process.exit(sub ? 1 : 0)
34
+ }
35
+
36
+ export {}
@@ -0,0 +1,26 @@
1
+ // able ws ls: the main checkout and every workspace, read live: offset, services, tree, shared resources held.
2
+
3
+ import { existsSync } from 'node:fs'
4
+ import { dirtyCount, mainRoot, unpushedCount } from '../git.ts'
5
+ import { bold, dim, yellow } from '../ui.ts'
6
+ import { checkouts, holderOf, readState, running } from './state.ts'
7
+
8
+ const main = mainRoot()
9
+ const state = await readState(main)
10
+ const rows = await checkouts(main, state)
11
+
12
+ console.log(`\n${bold(' CHECKOUT OFFSET SERVICES TREE')}`)
13
+ for (const w of rows) {
14
+ const up = Object.keys(await running(w.path)).length
15
+ let tree = yellow('directory missing')
16
+ if (existsSync(w.path)) {
17
+ const dirty = dirtyCount(w.path)
18
+ const ahead = unpushedCount(w.path)
19
+ tree = [dirty ? yellow(`${dirty} dirty`) : dim('clean'), ahead ? yellow(`${ahead} unpushed`) : dim('0 unpushed')].join(dim(' · '))
20
+ }
21
+ const holds = Object.keys(state.holders ?? {}).filter((name) => holderOf(state, name) === w.slug)
22
+ const services = up ? `${up} running`.padEnd(10) : dim('stopped'.padEnd(10))
23
+ console.log(` ${w.slug.padEnd(16)} ${String(w.portOffset).padEnd(7)} ${services} ${tree}${holds.length ? bold(` holds ${holds.join(' + ')}`) : ''}`)
24
+ }
25
+ if (rows.length === 1) console.log(dim('\n no workspaces: able ws new <slug>'))
26
+ console.log()
@@ -0,0 +1,63 @@
1
+ // able ws merge ["message"] [--yes]: lands this workspace on the trunk, from inside it.
2
+ //
3
+ // Merges origin's trunk into `feat/<slug>`, runs the checks of every folder the branch changed (decision 73), then
4
+ // pushes `feat/<slug>` and lands it on origin's trunk as one merge commit, `Land feat/<slug>`, which is how `able sync`
5
+ // finds it. A message commits what is still dirty first. The main checkout takes no part; afterwards it is
6
+ // fast-forwarded when it is on the trunk and nothing of its own is in the way.
7
+ //
8
+ // A conflict stops it with the files named: resolve them here, commit, and run it again. A push refused because the
9
+ // trunk moved meanwhile is the same: run it again, and it merges the newer trunk in.
10
+
11
+ import { runChecks } from '../checks.ts'
12
+ import { count, dirtyCount, fetchTrunk, git, gitLoud, gitQuiet, lines, mergeOrFail } from '../git.ts'
13
+ import { bold, confirm, dim, fail, green, yellow } from '../ui.ts'
14
+ import { inWorkspace } from './state.ts'
15
+
16
+ const args = process.argv.slice(4)
17
+ const msg = args.find((a) => !a.startsWith('-') && a !== '')
18
+
19
+ const { ws, config } = await inWorkspace()
20
+ const { trunk } = config
21
+ const dirty = dirtyCount(ws.path)
22
+ if (dirty && !msg) fail(`${dirty} uncommitted file(s); commit them (able commit), or pass a message to commit them all at once`)
23
+
24
+ fetchTrunk(ws.path, trunk)
25
+ const ahead = count(ws.path, `origin/${trunk}..HEAD`)
26
+ const behind = count(ws.path, `HEAD..origin/${trunk}`)
27
+
28
+ console.log(`\n ${bold(`Land ${ws.branch} on ${trunk}`)}`)
29
+ console.log(` ${ahead} commit(s) to land${dirty ? `, +${dirty} uncommitted → "${msg}"` : ''}; ${trunk} is ${behind} commit(s) ahead${behind ? ', merged in first' : ''}`)
30
+ if (!ahead && !dirty) {
31
+ console.log(dim(' nothing to land\n'))
32
+ process.exit(0)
33
+ }
34
+ if (!args.includes('--yes') && !confirm(`Merge ${trunk} in, run the checks, and push to ${trunk}?`)) fail('aborted; nothing pushed')
35
+
36
+ const commitAll = (message: string) => gitLoud(ws.path, 'add', '-A') && gitLoud(ws.path, 'commit', '--quiet', '-m', message)
37
+ if (dirty && msg && !commitAll(msg)) fail('commit failed')
38
+ if (behind) mergeOrFail(ws.path, `origin/${trunk}`, ws.branch, 'resolve them here, commit the merge, then run able ws merge again')
39
+
40
+ if (!runChecks(config, lines(ws.path, 'diff', '--name-only', `origin/${trunk}...HEAD`), ws)) fail('a check failed; fix it here, commit, and run it again; nothing was pushed')
41
+ // A check that formats files leaves them changed: they go in before landing.
42
+ if (dirtyCount(ws.path) && !commitAll('Format before landing')) fail('could not commit what the checks changed')
43
+
44
+ if (!gitLoud(ws.path, 'push', '--quiet', '-u', 'origin', ws.branch)) fail(`push of ${ws.branch} failed`)
45
+
46
+ // The branch already holds the trunk, so the landing merge cannot conflict.
47
+ if (!gitLoud(ws.path, 'checkout', '--quiet', '--detach', `origin/${trunk}`) || !gitLoud(ws.path, 'merge', '--quiet', '--no-ff', '-m', `Land ${ws.branch}`, ws.branch))
48
+ fail('could not build the landing commit')
49
+ const landed = git(ws.path, 'rev-parse', 'HEAD')
50
+ const pushed = gitLoud(ws.path, 'push', '--quiet', 'origin', `HEAD:${trunk}`)
51
+ gitLoud(ws.path, 'checkout', '--quiet', ws.branch)
52
+ if (!pushed) fail(`${trunk} moved meanwhile; run it again to merge it in`)
53
+ console.log(`\n ${green('✓')} ${bold(ws.branch)} is on ${trunk}`)
54
+
55
+ // `--ff-only` either moves the main checkout to the landing or refuses without touching it.
56
+ const onTrunk = git(ws.main, 'rev-parse', '--abbrev-ref', 'HEAD') === trunk
57
+ const synced = onTrunk && gitQuiet(ws.main, 'merge', '--quiet', '--ff-only', landed)
58
+ console.log(
59
+ synced
60
+ ? ` ${green('✓')} main checkout fast-forwarded`
61
+ : 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`),
62
+ )
63
+ console.log(`\n ${dim('next, from the main checkout:')} able ws rm ${ws.slug}\n`)
@@ -0,0 +1,60 @@
1
+ // able ws new <slug> [--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.
4
+
5
+ import { copyFileSync, existsSync, mkdirSync } from 'node:fs'
6
+ import { dirname, join, relative, resolve } from 'node:path'
7
+ import { loadConfig } from '../../config.ts'
8
+ import { fetchTrunk, git, mainRoot } from '../git.ts'
9
+ import { runCommand } from '../run.ts'
10
+ import { bold, dim, fail, green, yellow } from '../ui.ts'
11
+ import { branchOf, readState, workspaces, writeState } from './state.ts'
12
+
13
+ const args = process.argv.slice(4)
14
+ const slug = args.find((a) => !a.startsWith('-'))
15
+ if (!slug) fail('usage: able ws new <slug> [--no-fetch]')
16
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) fail(`invalid name '${slug}': lowercase letters, digits and dashes only`)
17
+
18
+ const main = mainRoot()
19
+ const config = await loadConfig(main)
20
+ const ws = config.workspaces ?? fail('able.config.ts has no workspaces')
21
+ const branch = branchOf(slug)
22
+ const path = resolve(main, ws.dir, slug)
23
+
24
+ const state = await readState(main)
25
+ if ((await workspaces(main, state)).some((w) => w.slug === slug)) fail(`workspace '${slug}' already exists; see able ws ls`)
26
+ if (existsSync(path)) fail(`${path} already exists; remove it first`)
27
+ if (git(main, 'rev-parse', '--verify', '--quiet', branch)) fail(`branch '${branch}' already exists`)
28
+
29
+ // Without `ports` every workspace sits at offset 0 and only one runs services at a time (88, 94).
30
+ const taken = new Set(Object.values(state.workspaces).map((w) => w.portOffset))
31
+ const { ports } = ws
32
+ 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
33
+
34
+ if (!args.includes('--no-fetch')) fetchTrunk(main, config.trunk)
35
+ // Cut from origin's trunk: the main checkout's own branch may lag, and is the operator's to move.
36
+ const start = git(main, 'rev-parse', '--verify', '--quiet', `origin/${config.trunk}`) ? `origin/${config.trunk}` : config.trunk
37
+
38
+ const started = Date.now()
39
+ mkdirSync(dirname(path), { recursive: true })
40
+ const added = Bun.spawnSync(['git', '-C', main, 'worktree', 'add', '--no-track', '-b', branch, path, start], { stdout: 'pipe', stderr: 'pipe' })
41
+ if (added.exitCode !== 0) fail(`worktree add failed: ${added.stderr.toString().trim()}`)
42
+
43
+ state.workspaces[slug] = { portOffset, createdAt: new Date().toISOString() }
44
+ await writeState(main, state)
45
+
46
+ for (const rel of ws.copy ?? []) {
47
+ if (!existsSync(join(main, rel))) continue
48
+ mkdirSync(dirname(join(path, rel)), { recursive: true })
49
+ copyFileSync(join(main, rel), join(path, rel))
50
+ }
51
+
52
+ const failed = (ws.onCreate ?? []).filter((c) => !runCommand(c, { slug, path, portOffset, main }))
53
+
54
+ const brief = git(path, 'ls-files', `${config.journal}/workspaces/${slug}.md`)
55
+ console.log(`\n${green('✓')} ${bold(slug)} ${dim(path)} ${dim(`in ${((Date.now() - started) / 1000).toFixed(1)}s`)}\n`)
56
+ console.log(` ${'branch'.padEnd(12)} ${branch} ${dim(`from ${start}`)}`)
57
+ console.log(` ${'port offset'.padEnd(12)} ${portOffset}`)
58
+ console.log(` ${'brief'.padEnd(12)} ${brief || yellow(`none: ${config.trunk} has no ${config.journal}/workspaces/${slug}.md`)}`)
59
+ if (failed.length) console.log(yellow(`\n ${failed.length} onCreate command(s) failed; run them inside the workspace`))
60
+ console.log(`\n ${dim(`cd ${relative(process.cwd(), path)}`)}\n`)
@@ -0,0 +1,32 @@
1
+ // able ws refresh: catches this workspace up with the trunk, from inside it (decision 81).
2
+ //
3
+ // A worktree shares the main checkout's repository, so it sees the main checkout's own trunk as well as origin's. It
4
+ // merges whichever holds the other (both, origin's first, when they have diverged), so work committed on the trunk
5
+ // reaches a workspace without being pushed first. Refuses on uncommitted files.
6
+
7
+ import { count, dirtyCount, fetchTrunk, git, gitQuiet, mergeOrFail } from '../git.ts'
8
+ import { bold, dim, fail, green, yellow } from '../ui.ts'
9
+ import { inWorkspace } from './state.ts'
10
+
11
+ const { ws, config } = await inWorkspace()
12
+ const { trunk } = config
13
+ const dirty = dirtyCount(ws.path)
14
+ if (dirty) fail(`${dirty} uncommitted file(s); commit them first, so the merge stays separable from your work`)
15
+
16
+ fetchTrunk(ws.path, trunk)
17
+ const contains = (outer: string, inner: string) => gitQuiet(ws.path, 'merge-base', '--is-ancestor', inner, outer)
18
+ const local = git(ws.path, 'rev-parse', '--verify', '--quiet', trunk) ? trunk : ''
19
+ const remote = git(ws.path, 'rev-parse', '--verify', '--quiet', `origin/${trunk}`) ? `origin/${trunk}` : ''
20
+ const sources = !local ? [remote] : !remote || contains(local, remote) ? [local] : contains(remote, local) ? [remote] : [remote, local]
21
+
22
+ for (const source of sources.filter(Boolean)) {
23
+ const behind = count(ws.path, `HEAD..${source}`)
24
+ if (!behind) {
25
+ console.log(dim(` ${source}: already merged`))
26
+ continue
27
+ }
28
+ const unpushed = source === trunk && remote ? count(ws.path, `${remote}..${trunk}`) : 0
29
+ console.log(` ${bold(source)}: ${behind} commit(s)${unpushed ? yellow(`; ${unpushed} not on origin yet, they reach it when this workspace lands`) : ''}`)
30
+ mergeOrFail(ws.path, source, ws.branch, 'resolve them here and commit the merge, or abort it with git merge --abort')
31
+ }
32
+ console.log(`\n${green('✓')} ${bold(ws.branch)} holds ${trunk}\n`)
@@ -0,0 +1,59 @@
1
+ // Shared resources (decisions 89, 95): one holder at a time on a machine. Each resource's holders are a stack in
2
+ // `.able/workspaces.json`, the current one last. An `auto` resource follows the services: `able ws start` takes it, and
3
+ // once a checkout runs nothing it goes back to the latest earlier holder still running services.
4
+
5
+ import type { WorkspacesConfig } from '../../config.ts'
6
+ import { runCommand, type Place } from '../run.ts'
7
+ import { dim, fail, green } from '../ui.ts'
8
+ import { checkouts, holderOf, readState, running, writeState } from './state.ts'
9
+
10
+ type Resources = NonNullable<WorkspacesConfig['resources']>
11
+
12
+ /** Runs a resource's `take` here and makes this checkout its holder; returns the one it took it from. */
13
+ export async function take(name: string, resource: Resources[string], at: Place) {
14
+ if (!runCommand(resource.take, at)) fail(`taking ${name} failed`)
15
+ const state = await readState(at.main)
16
+ const before = (state.holders?.[name] ?? []).filter((s) => s !== at.slug)
17
+ state.holders = { ...state.holders, [name]: [...before, at.slug] }
18
+ await writeState(at.main, state)
19
+ return before.at(-1)
20
+ }
21
+
22
+ /** Takes every `auto` resource this checkout doesn't hold yet. */
23
+ export async function takeAuto(resources: Resources, at: Place) {
24
+ const state = await readState(at.main)
25
+ for (const [name, r] of Object.entries(resources)) {
26
+ if (!r.auto || holderOf(state, name) === at.slug) continue
27
+ const from = await take(name, r, at)
28
+ console.log(` ${green('✓')} holds ${name}${from ? dim(`, taken from ${from}`) : ''}`)
29
+ }
30
+ }
31
+
32
+ /** This checkout leaves every resource's holders; an `auto` one it held goes back to the latest earlier holder still running services. */
33
+ export async function leave(resources: Resources, at: Place) {
34
+ const state = await readState(at.main)
35
+ const held = Object.entries(state.holders ?? {}).filter(([, holders]) => holders.includes(at.slug))
36
+ if (!held.length) return
37
+ const places = await checkouts(at.main, state)
38
+ const runsServices = async (slug = '') => {
39
+ const p = places.find((p) => p.slug === slug)
40
+ return p && Object.keys(await running(p.path)).length ? p : undefined
41
+ }
42
+ const next = { ...state.holders }
43
+ for (const [name, holders] of held) {
44
+ const rest = holders.filter((s) => s !== at.slug)
45
+ const resource = resources[name]
46
+ if (resource?.auto && holders.at(-1) === at.slug)
47
+ while (rest.length) {
48
+ const back = await runsServices(rest.at(-1))
49
+ if (back) {
50
+ if (runCommand(resource.take, back)) console.log(` ${green('✓')} ${name} back to ${back.slug}`)
51
+ break
52
+ }
53
+ rest.pop()
54
+ }
55
+ next[name] = rest
56
+ }
57
+ state.holders = Object.fromEntries(Object.entries(next).filter(([, holders]) => holders.length))
58
+ await writeState(at.main, state)
59
+ }
@@ -0,0 +1,55 @@
1
+ // able ws rm <slug> [--force]: stops its services, runs the host's `onRemove`, removes the worktree and its state,
2
+ // and deletes its branch, local and remote, once it is merged into origin's trunk.
3
+ //
4
+ // Refuses while the worktree is dirty or holds commits no remote has, the two ways to lose work that exists nowhere
5
+ // else; --force skips that check. An unmerged branch survives and is named.
6
+
7
+ import { existsSync, rmSync } from 'node:fs'
8
+ import { loadConfig } from '../../config.ts'
9
+ import { dirtyCount, fetchTrunk, git, gitQuiet, mainRoot, unpushedCount } from '../git.ts'
10
+ import { runCommand } from '../run.ts'
11
+ import { bold, dim, fail, green, red, yellow } from '../ui.ts'
12
+ import { leave } from './resources.ts'
13
+ import { stop } from './services.ts'
14
+ import { readState, workspaces, writeState } from './state.ts'
15
+
16
+ const args = process.argv.slice(4)
17
+ const slug = args.find((a) => !a.startsWith('-'))
18
+ if (!slug) fail('usage: able ws rm <slug> [--force]')
19
+
20
+ const main = mainRoot()
21
+ const config = await loadConfig(main)
22
+ const ws = (await workspaces(main)).find((w) => w.slug === slug) ?? fail(`no workspace '${slug}'; see able ws ls`)
23
+
24
+ if (!args.includes('--force') && existsSync(ws.path)) {
25
+ const dirty = dirtyCount(ws.path)
26
+ const ahead = unpushedCount(ws.path)
27
+ const blockers = [dirty && `${dirty} uncommitted file(s)`, ahead && `${ahead} unpushed commit(s)`].filter(Boolean)
28
+ if (blockers.length) fail(`${red('refusing to remove')} ${bold(slug)}: this work exists nowhere else: ${blockers.join(', ')}\n ${dim('push it, or --force to discard')}`)
29
+ }
30
+
31
+ const at = { slug, path: ws.path, portOffset: ws.portOffset, main }
32
+ if (existsSync(ws.path)) {
33
+ await stop([], at)
34
+ for (const c of config.workspaces?.onRemove ?? []) runCommand(c, at)
35
+ const r = Bun.spawnSync(['git', '-C', main, 'worktree', 'remove', '--force', ws.path], { stdout: 'pipe', stderr: 'pipe' })
36
+ if (r.exitCode !== 0) console.error(yellow(` worktree remove failed: ${r.stderr.toString().trim()}`))
37
+ if (existsSync(ws.path)) rmSync(ws.path, { recursive: true, force: true })
38
+ }
39
+ gitQuiet(main, 'worktree', 'prune')
40
+
41
+ await leave(config.workspaces?.resources ?? {}, at)
42
+ const state = await readState(main)
43
+ delete state.workspaces[slug]
44
+ await writeState(main, state)
45
+ console.log(`\n${green('✓')} removed ${bold(slug)}`)
46
+
47
+ fetchTrunk(main, config.trunk)
48
+ if (git(main, 'branch', '--merged', `origin/${config.trunk}`, '--list', ws.branch)) {
49
+ gitQuiet(main, 'branch', '-D', ws.branch)
50
+ gitQuiet(main, 'push', '--quiet', 'origin', '--delete', ws.branch)
51
+ console.log(dim(` ${ws.branch} deleted, local and remote`))
52
+ } else if (git(main, 'rev-parse', '--verify', '--quiet', ws.branch)) {
53
+ console.log(yellow(` ${ws.branch} kept: not merged into ${config.trunk}; delete it yourself once it is not needed`))
54
+ }
55
+ console.log()
@@ -0,0 +1,103 @@
1
+ // A workspace's services (decision 90): started in dependency order, each waited on until ready, stopped in reverse.
2
+ // A service runs detached, in its own process group, logging to `.able/logs/<name>.log` in its checkout; what runs is
3
+ // recorded in that checkout's `.able/services.json`, so any later command can stop it (96).
4
+ //
5
+ // able ws start [<service>…] the named services and what they need, or all of them
6
+ // able ws stop [<service>…] the named services, or all of them, in reverse order
7
+ // able ws status what runs in this checkout
8
+ //
9
+ // `auto` resources follow the services (95, `resources.ts`).
10
+
11
+ import { spawn } from 'node:child_process'
12
+ import { mkdirSync, openSync } from 'node:fs'
13
+ import { connect } from 'node:net'
14
+ import { join, resolve } from 'node:path'
15
+ import { loadConfig, type Service } from '../../config.ts'
16
+ import { runCommand, shellFor, type Place } from '../run.ts'
17
+ import { bold, dim, fail, green, red, yellow } from '../ui.ts'
18
+ import { leave, takeAuto } from './resources.ts'
19
+ import { checkouts, current, running, runningPath } from './state.ts'
20
+
21
+ const save = (checkout: string, r: Awaited<ReturnType<typeof running>>) => {
22
+ mkdirSync(join(checkout, '.able'), { recursive: true })
23
+ return Bun.write(runningPath(checkout), `${JSON.stringify(r, null, 2)}\n`)
24
+ }
25
+
26
+ /** The named services in dependency order, each after what it needs. */
27
+ export function ordered(services: Record<string, Service>, names: string[]): [string, Service][] {
28
+ const out: [string, Service][] = []
29
+ const visit = (name: string, trail: string[]) => {
30
+ if (out.some(([n]) => n === name)) return
31
+ if (trail.includes(name)) fail(`services need each other in a circle: ${[...trail, name].join(' → ')}`)
32
+ const s = services[name] ?? fail(`no service '${name}' in able.config.ts`)
33
+ for (const need of s.needs ?? []) visit(need, [...trail, name])
34
+ out.push([name, s])
35
+ }
36
+ for (const name of names) visit(name, [])
37
+ return out
38
+ }
39
+
40
+ const portOpen = (port: number) =>
41
+ new Promise<boolean>((done) => {
42
+ const socket = connect({ port, host: '127.0.0.1' }, () => (socket.destroy(), done(true)))
43
+ socket.on('error', () => done(false))
44
+ })
45
+
46
+ async function ready(s: Service, at: Place, timeoutMs = 120_000): Promise<boolean> {
47
+ const check = s.ready
48
+ if (!check) return true
49
+ for (const until = Date.now() + timeoutMs; Date.now() < until; await Bun.sleep(250)) {
50
+ if ('port' in check ? await portOpen(check.port + at.portOffset) : runCommand({ run: check.cmd, cwd: s.cwd }, at, { quiet: true })) return true
51
+ }
52
+ return false
53
+ }
54
+
55
+ export async function start(names: string[]) {
56
+ const at = await current()
57
+ const config = await loadConfig(at.path)
58
+ const services = config.workspaces?.services ?? fail('able.config.ts has no workspaces.services')
59
+ // Without `ports`, every checkout uses the same ports: only one runs services at a time (88, 94).
60
+ if (!config.workspaces?.ports) {
61
+ const others = (await checkouts(at.main)).filter((c) => resolve(c.path) !== resolve(at.path))
62
+ for (const other of others) if (Object.keys(await running(other.path)).length) fail(`services already run in ${other.slug}, on the same ports; stop them there first (able ws stop)`)
63
+ }
64
+ const now = await running(at.path)
65
+ mkdirSync(join(at.path, '.able', 'logs'), { recursive: true })
66
+ for (const [name, s] of ordered(services, names.length ? names : Object.keys(services))) {
67
+ if (now[name]) {
68
+ console.log(dim(` · ${name} runs already`))
69
+ continue
70
+ }
71
+ const log = openSync(join(at.path, '.able', 'logs', `${name}.log`), 'a')
72
+ const sh = shellFor(at, s.start, s.cwd)
73
+ const child = spawn(sh.argv[0] ?? 'sh', sh.argv.slice(1), { cwd: sh.cwd, env: sh.env, detached: true, stdio: ['ignore', log, log] })
74
+ child.unref()
75
+ if (!child.pid) fail(`${name} did not start`)
76
+ now[name] = { pid: child.pid, startedAt: new Date().toISOString() }
77
+ await save(at.path, now)
78
+ const ok = await ready(s, at)
79
+ console.log(` ${ok ? green('✓') : red('✗')} ${name}${ok ? '' : dim(` not ready; see .able/logs/${name}.log`)}`)
80
+ if (!ok) fail(`${name} is not ready`)
81
+ }
82
+ await takeAuto(config.workspaces?.resources ?? {}, at)
83
+ }
84
+
85
+ export async function stop(names: string[], at?: Place) {
86
+ const place = at ?? (await current())
87
+ const { services = {}, resources = {} } = (await loadConfig(place.path)).workspaces ?? {}
88
+ const now = await running(place.path)
89
+ const chosen = ordered(services, Object.keys(services)).filter(([n]) => now[n] && (!names.length || names.includes(n)))
90
+ for (const [name, s] of chosen.reverse()) {
91
+ if (s.stop) runCommand({ run: s.stop, cwd: s.cwd }, place)
92
+ Bun.spawnSync(['kill', '-TERM', `-${now[name]?.pid}`], { stdout: 'ignore', stderr: 'ignore' })
93
+ delete now[name]
94
+ console.log(` ${green('✓')} ${name} stopped`)
95
+ }
96
+ await save(place.path, now)
97
+ if (!Object.keys(now).length) await leave(resources, place)
98
+ }
99
+
100
+ export async function status() {
101
+ const entries = Object.entries(await running((await current()).path))
102
+ console.log(entries.length ? entries.map(([n, s]) => ` ${bold(n)} ${dim(`pid ${s.pid}, since ${s.startedAt}`)}`).join('\n') : yellow(' no services running in this checkout'))
103
+ }
@@ -0,0 +1,79 @@
1
+ // Which workspaces exist comes from git (decision 92): every worktree on `feat/<slug>`. What git can't know, a
2
+ // workspace's port offset and creation date and who holds each shared resource, is in `.able/workspaces.json` in the
3
+ // main checkout.
4
+
5
+ import { existsSync } from 'node:fs'
6
+ import { dirname, join, resolve } from 'node:path'
7
+ import { loadConfig, type AbleConfig } from '../../config.ts'
8
+ import { failOnMerge, git } from '../git.ts'
9
+ import type { Place } from '../run.ts'
10
+ import { fail } from '../ui.ts'
11
+
12
+ export const branchOf = (slug: string) => `feat/${slug}`
13
+ const slugOf = (ref: string) => ref.match(/^refs\/heads\/feat\/(.+)$/)?.[1]
14
+
15
+ export interface Workspace {
16
+ slug: string
17
+ branch: string
18
+ path: string
19
+ portOffset: number
20
+ createdAt?: string
21
+ }
22
+
23
+ /** 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, { portOffset: number; createdAt: string }>; holders?: Record<string, string[]> }
25
+
26
+ const statePath = (main: string) => join(main, '.able', 'workspaces.json')
27
+
28
+ export const readState = async (main: string): Promise<State> => (existsSync(statePath(main)) ? Bun.file(statePath(main)).json() : { workspaces: {} })
29
+
30
+ export const writeState = (main: string, state: State) => Bun.write(statePath(main), `${JSON.stringify(state, null, 2)}\n`)
31
+
32
+ /** Which checkout holds a resource now. */
33
+ export const holderOf = (state: State, name: string) => state.holders?.[name]?.at(-1)
34
+
35
+ export const runningPath = (checkout: string) => join(checkout, '.able', 'services.json')
36
+ const alive = (pid: number) => Bun.spawnSync(['kill', '-0', String(pid)], { stdout: 'ignore', stderr: 'ignore' }).exitCode === 0
37
+
38
+ /** The services running in a checkout (96); entries whose process has gone are dropped. */
39
+ export async function running(checkout: string): Promise<Record<string, { pid: number; startedAt: string }>> {
40
+ const saved = existsSync(runningPath(checkout)) ? await Bun.file(runningPath(checkout)).json() : {}
41
+ return Object.fromEntries(Object.entries(saved as Record<string, { pid: number; startedAt: string }>).filter(([, s]) => alive(s.pid)))
42
+ }
43
+
44
+ /** Every workspace git knows, with what the state file adds. */
45
+ export async function workspaces(main: string, state?: State): Promise<Workspace[]> {
46
+ const saved = (state ?? (await readState(main))).workspaces
47
+ // `-z`: fields end in NUL, records in an empty field, so paths with spaces or newlines survive.
48
+ return git(main, 'worktree', 'list', '--porcelain', '-z')
49
+ .split('\0\0')
50
+ .flatMap((record) => {
51
+ const fields = record.split('\0')
52
+ const path = fields.find((f) => f.startsWith('worktree '))?.slice('worktree '.length)
53
+ const slug = slugOf(fields.find((f) => f.startsWith('branch '))?.slice('branch '.length) ?? '')
54
+ if (!path || !slug) return []
55
+ return [{ slug, branch: branchOf(slug), path, portOffset: saved[slug]?.portOffset ?? 0, createdAt: saved[slug]?.createdAt }]
56
+ })
57
+ }
58
+
59
+ /** The main checkout, at offset 0, and every workspace. */
60
+ export const checkouts = async (main: string, state?: State): Promise<Place[]> => [
61
+ { slug: 'main', path: main, portOffset: 0, main },
62
+ ...(await workspaces(main, state)).map((w) => ({ slug: w.slug, path: w.path, portOffset: w.portOffset, main })),
63
+ ]
64
+
65
+ /** The checkout the command runs in. The main checkout is `main`, at offset 0, and not a workspace. */
66
+ export async function current(cwd = process.cwd()) {
67
+ const [common = '.git', root = cwd, branch = ''] = git(cwd, 'rev-parse', '--git-common-dir', '--show-toplevel', '--abbrev-ref', 'HEAD').split('\n')
68
+ const main = dirname(resolve(cwd, common))
69
+ const ws = (await workspaces(main)).find((w) => resolve(w.path) === resolve(root))
70
+ return ws ? { ...ws, main, isWorkspace: true } : { slug: 'main', branch, path: root, portOffset: 0, main, isWorkspace: false }
71
+ }
72
+
73
+ /** The workspace a command runs in, with its config; fails in the main checkout or during a merge. */
74
+ export async function inWorkspace(): Promise<{ ws: Awaited<ReturnType<typeof current>>; config: AbleConfig }> {
75
+ const ws = await current()
76
+ if (!ws.isWorkspace) fail('not inside a workspace')
77
+ failOnMerge(ws.path)
78
+ return { ws, config: await loadConfig(ws.path) }
79
+ }
@@ -0,0 +1,14 @@
1
+ // able ws take <resource>: moves a shared resource to this checkout by hand (decisions 89, 95). An `auto` resource
2
+ // needs no take: `able ws start` takes it and `able ws stop` gives it back.
3
+
4
+ import { loadConfig } from '../../config.ts'
5
+ import { bold, fail, green } from '../ui.ts'
6
+ import { take } from './resources.ts'
7
+ import { current } from './state.ts'
8
+
9
+ const name = process.argv[4] ?? ''
10
+ const at = await current()
11
+ const resources = (await loadConfig(at.path)).workspaces?.resources ?? {}
12
+ const resource = resources[name] ?? fail(`usage: able ws take <${Object.keys(resources).join('|') || 'resource'}>`)
13
+ const from = await take(name, resource, at)
14
+ console.log(`\n ${green('✓')} ${bold(at.slug)} holds ${name}${from ? `, taken from ${from}` : ''}\n`)
package/sync.ts CHANGED
@@ -48,18 +48,30 @@ if (behind) fail(`this checkout is ${behind} commit(s) behind origin/${trunk}; p
48
48
  // ── Markdown: `## ` sections and their `### ` subsections ─────────────────────────────────────
49
49
 
50
50
  const section = (text: string, name: string) =>
51
- text.split(/^(?=## )/m).find((p) => p.startsWith(`## ${name}\n`))?.slice(name.length + 4) ?? ''
52
- const sub = (body: string, name: string) =>
53
- body.match(new RegExp(`^### ${name}\\s*\\n([\\s\\S]*?)(?=^### |(?![\\s\\S]))`, 'm'))?.[1] ?? ''
54
- const slugify = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 60)
51
+ text
52
+ .split(/^(?=## )/m)
53
+ .find((p) => p.startsWith(`## ${name}\n`))
54
+ ?.slice(name.length + 4) ?? ''
55
+ const sub = (body: string, name: string) => body.match(new RegExp(`^### ${name}\\s*\\n([\\s\\S]*?)(?=^### |(?![\\s\\S]))`, 'm'))?.[1] ?? ''
56
+ const slugify = (s: string) =>
57
+ s
58
+ .toLowerCase()
59
+ .replace(/[^a-z0-9]+/g, '-')
60
+ .replace(/^-|-$/g, '')
61
+ .slice(0, 60)
55
62
 
56
63
  type Item = { slug: string; title: string; text: string; key: string }
57
64
  const bullets = (slug: string, block: string): Item[] =>
58
- block.split(/^- /m).slice(1).map((b) => b.trim()).filter(Boolean).map((b) => {
59
- const text = b.replace(/\n\s*/g, ' ')
60
- const title = (text.match(/^\*\*(.+?)\*\*/)?.[1] ?? text.split(/(?<=\.)\s/)[0] ?? text).replace(/[.:]$/, '').slice(0, 120)
61
- return { slug, title, text, key: `${slug}:${slugify(title)}` }
62
- })
65
+ block
66
+ .split(/^- /m)
67
+ .slice(1)
68
+ .map((b) => b.trim())
69
+ .filter(Boolean)
70
+ .map((b) => {
71
+ const text = b.replace(/\n\s*/g, ' ')
72
+ const title = (text.match(/^\*\*(.+?)\*\*/)?.[1] ?? text.split(/(?<=\.)\s/)[0] ?? text).replace(/[.:]$/, '').slice(0, 120)
73
+ return { slug, title, text, key: `${slug}:${slugify(title)}` }
74
+ })
63
75
 
64
76
  // ── Landed workspaces and their briefs ────────────────────────────────────────────────────────
65
77
 
@@ -89,10 +101,12 @@ const labels = new Set((JSON.parse(gh('label', 'list', '--limit', '1000', '--jso
89
101
  const issues: Issue[] = labels.has('follow-up')
90
102
  ? JSON.parse(gh('issue', 'list', '--label', 'follow-up', '--state', 'all', '--limit', '2000', '--json', 'number,title,state,url,body,createdAt,closedAt'))
91
103
  : []
92
- const byKey = new Map(issues.flatMap((i) => {
93
- const key = i.body.match(/<!-- able:(\S+) -->/)?.[1]
94
- return key ? [[key, i] as const] : []
95
- }))
104
+ const byKey = new Map(
105
+ issues.flatMap((i) => {
106
+ const key = i.body.match(/<!-- able:(\S+) -->/)?.[1]
107
+ return key ? [[key, i] as const] : []
108
+ }),
109
+ )
96
110
 
97
111
  const ensureLabel = (name: string, color: string, description: string) => {
98
112
  if (labels.has(name) || dry) return
@@ -180,12 +194,14 @@ const packageOf = (path: string) => {
180
194
  }
181
195
 
182
196
  // Workspaces are worktrees on `feat/<slug>`; open ones are not yet in the trunk.
183
- const openNow = git('worktree', 'list', '--porcelain').split('\n').flatMap((l) => {
184
- const slug = l.match(/^branch refs\/heads\/feat\/(\S+)$/)?.[1]
185
- if (!slug) return []
186
- const merged = Bun.spawnSync(['git', 'merge-base', '--is-ancestor', `feat/${slug}`, `origin/${trunk}`], { cwd: root }).exitCode === 0
187
- return merged ? [] : [slug]
188
- })
197
+ const openNow = git('worktree', 'list', '--porcelain')
198
+ .split('\n')
199
+ .flatMap((l) => {
200
+ const slug = l.match(/^branch refs\/heads\/feat\/(\S+)$/)?.[1]
201
+ if (!slug) return []
202
+ const merged = Bun.spawnSync(['git', 'merge-base', '--is-ancestor', `feat/${slug}`, `origin/${trunk}`], { cwd: root }).exitCode === 0
203
+ return merged ? [] : [slug]
204
+ })
189
205
 
190
206
  const record = (start: number) => {
191
207
  const end = addDays(start, 7)
@@ -263,8 +279,12 @@ if (reasons.length) {
263
279
  process.exit(0)
264
280
  }
265
281
  const names = due.map(weekName).join(', ')
266
- for (const cmd of [['just', 'commit', `journal: week record ${names}`, ...written, '--yes'], ['just', 'push']]) {
282
+ const able = [process.execPath, join(import.meta.dir, 'able.ts')]
283
+ for (const cmd of [
284
+ [...able, 'commit', `journal: week record ${names}`, ...written, '--yes'],
285
+ [...able, 'push'],
286
+ ]) {
267
287
  const r = Bun.spawnSync(cmd, { cwd: root, stdio: ['inherit', 'inherit', 'inherit'] })
268
- if (r.exitCode !== 0) fail(`${cmd.slice(0, 2).join(' ')} failed; the record(s) are written but not published`)
288
+ if (r.exitCode !== 0) fail(`able ${cmd[2]} failed; the record(s) are written but not published`)
269
289
  }
270
290
  console.log(`able sync: committed and pushed ${names}`)