@able-autonomy/able 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Able Autonomy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/able.ts ADDED
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env bun
2
+ // able: Able's command line on the operator's machine.
3
+ // `able gh <args>` runs `gh <args>` as Able's GitHub App, so what it writes comes from `<app-slug>[bot]`.
4
+ // `able sync` keeps a host's follow-up issues and week records up to date (sync.ts).
5
+ // `able config --json` prints the host's resolved `able.config.ts` (config.ts).
6
+
7
+ import { createSign } from 'node:crypto'
8
+ import { mkdirSync } from 'node:fs'
9
+ import { homedir } from 'node:os'
10
+ import { join } from 'node:path'
11
+
12
+ // 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 api = 'https://api.github.com'
15
+
16
+ function fail(message: string): never {
17
+ console.error(`able: ${message}`)
18
+ process.exit(1)
19
+ }
20
+
21
+ // App ID and private key are Able's secrets, kept on the operator's machine, never in a client's repo.
22
+ async function readApp() {
23
+ const config = Bun.file(join(configDir, 'app.json'))
24
+ const key = Bun.file(join(configDir, 'private-key.pem'))
25
+ if (!(await config.exists()) || !(await key.exists())) {
26
+ fail(`missing ${join(configDir, 'app.json')} ({ "appId": <id> }) or ${join(configDir, 'private-key.pem')}`)
27
+ }
28
+ const { appId } = await config.json()
29
+ return { appId: String(appId), key: await key.text() }
30
+ }
31
+
32
+ function signJwt(appId: string, key: string) {
33
+ const now = Math.floor(Date.now() / 1000)
34
+ const encode = (value: object) => Buffer.from(JSON.stringify(value)).toString('base64url')
35
+ const unsigned = `${encode({ alg: 'RS256', typ: 'JWT' })}.${encode({ iat: now - 60, exp: now + 540, iss: appId })}`
36
+ return `${unsigned}.${createSign('RSA-SHA256').update(unsigned).sign(key, 'base64url')}`
37
+ }
38
+
39
+ async function github(path: string, jwt: string, method = 'GET') {
40
+ return fetch(`${api}${path}`, {
41
+ method,
42
+ headers: {
43
+ Accept: 'application/vnd.github+json',
44
+ Authorization: `Bearer ${jwt}`,
45
+ 'User-Agent': 'able-cli',
46
+ 'X-GitHub-Api-Version': '2022-11-28',
47
+ },
48
+ })
49
+ }
50
+
51
+ // The repo comes from --repo/-R, then GH_REPO, then the checkout's origin remote, as gh resolves it.
52
+ function resolveRepo(args: string[]) {
53
+ for (let i = 0; i < args.length; i++) {
54
+ if (args[i] === '--repo' || args[i] === '-R') return args[i + 1]
55
+ if (args[i].startsWith('--repo=')) return args[i].slice('--repo='.length)
56
+ }
57
+ if (process.env.GH_REPO) return process.env.GH_REPO
58
+ 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]
62
+ }
63
+
64
+ // Installation tokens last an hour; reuse one until five minutes before it expires.
65
+ async function installationToken(repo: string) {
66
+ const cacheDir = join(configDir, 'tokens')
67
+ const cache = Bun.file(join(cacheDir, `${repo.replace('/', '__')}.json`))
68
+ if (await cache.exists()) {
69
+ const { token, expiresAt } = await cache.json()
70
+ if (Date.parse(expiresAt) - Date.now() > 5 * 60_000) return token as string
71
+ }
72
+
73
+ const { appId, key } = await readApp()
74
+ const jwt = signJwt(appId, key)
75
+ const installation = await github(`/repos/${repo}/installation`, jwt)
76
+ if (installation.status === 404) {
77
+ // GitHub also answers 404 to a bad JWT, so check the app's own credentials before blaming the install.
78
+ const app = await github('/app', jwt)
79
+ if (!app.ok) fail(`GitHub rejected the app credentials in ${configDir}: ${app.status} ${await app.text()}`)
80
+ const { slug } = await app.json()
81
+ fail(`Able is not installed on ${repo}. Install it: https://github.com/apps/${slug}/installations/new`)
82
+ }
83
+ if (!installation.ok) fail(`GET /repos/${repo}/installation: ${installation.status} ${await installation.text()}`)
84
+ const { id } = await installation.json()
85
+
86
+ const created = await github(`/app/installations/${id}/access_tokens`, jwt, 'POST')
87
+ if (!created.ok) fail(`POST /app/installations/${id}/access_tokens: ${created.status} ${await created.text()}`)
88
+ const { token, expires_at } = await created.json()
89
+ mkdirSync(cacheDir, { recursive: true, mode: 0o700 })
90
+ await Bun.write(cache, JSON.stringify({ token, expiresAt: expires_at }))
91
+ return token as string
92
+ }
93
+
94
+ const [command, ...args] = process.argv.slice(2)
95
+ if (command === 'sync') {
96
+ await import('./sync.ts')
97
+ process.exit(0)
98
+ }
99
+ if (command === 'config') {
100
+ const { hostRoot, loadConfig } = await import('./config.ts')
101
+ console.log(JSON.stringify(await loadConfig(hostRoot()), null, args.includes('--json') ? undefined : 2))
102
+ process.exit(0)
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
+ }
109
+ if (command !== 'gh') {
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
+ )
113
+ process.exit(command ? 1 : 0)
114
+ }
115
+
116
+ const token = await installationToken(resolveRepo(args))
117
+ const gh = Bun.spawnSync(['gh', ...args], {
118
+ stdio: ['inherit', 'inherit', 'inherit'],
119
+ env: { ...process.env, GH_TOKEN: token },
120
+ })
121
+ process.exit(gh.exitCode ?? 1)
package/config.ts ADDED
@@ -0,0 +1,67 @@
1
+ // A host's `able.config.ts`, at the root of its main checkout. Required: Able has no defaults of its
2
+ // own, so one host's choices never become another's.
3
+
4
+ import { existsSync } from 'node:fs'
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
+ }
34
+
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
40
+ /** The branch workspaces are cut from and land on. */
41
+ trunk: string
42
+ /** The journal's folder from the root: `workspaces/<slug>.md` briefs and `weeks/<yyyy>-w<ww>.md` records. */
43
+ journal: string
44
+ /** The knowledge folder from the root: the docs the dashboard shows. Optional: without it, no docs view. */
45
+ knowledge?: string
46
+ }
47
+
48
+ /** Types and editor help for `able.config.ts`; returns the config unchanged. */
49
+ export const defineConfig = (config: AbleConfig): AbleConfig => config
50
+
51
+ /** The root of the checkout the command runs in. */
52
+ export function hostRoot() {
53
+ const r = Bun.spawnSync(['git', 'rev-parse', '--show-toplevel'], { stdout: 'pipe', stderr: 'pipe' })
54
+ if (r.exitCode !== 0) fail('not inside a git checkout')
55
+ return r.stdout.toString().trim()
56
+ }
57
+
58
+ export async function loadConfig(root: string): Promise<AbleConfig> {
59
+ const path = join(root, 'able.config.ts')
60
+ if (!existsSync(path)) fail(`no able.config.ts at ${root}. Run Able's onboarding to set this project up.`)
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`)
63
+ const missing = (['trunk', 'journal'] as const).filter((key) => typeof config?.[key] !== 'string' || !config[key])
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`)
66
+ return config as AbleConfig
67
+ }
package/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { defineConfig, type AbleConfig, type Command, type Service, type WorkspacesConfig } from './config.ts'
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@able-autonomy/able",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.3",
4
+ "description": "Able's command line and the config types a host's able.config.ts uses",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": "github:able-autonomy/able",
8
+ "exports": {
9
+ ".": "./index.ts"
10
+ },
11
+ "bin": {
12
+ "able": "able.ts"
13
+ },
14
+ "files": [
15
+ "able.ts",
16
+ "config.ts",
17
+ "index.ts",
18
+ "sync.ts",
19
+ "src"
20
+ ],
21
+ "publishConfig": {
22
+ "access": "public"
23
+ }
24
+ }
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 ADDED
@@ -0,0 +1,290 @@
1
+ // able sync: keeps a host's journal and follow-up issues up to date from git and the briefs, with no
2
+ // input from the operator. Safe to run any number of times: a second run finds nothing left to do.
3
+ //
4
+ // able sync [--dry-run]
5
+ //
6
+ // From the host's main checkout, on the trunk (`trunk` in its able.config.ts). For every workspace landed on
7
+ // the trunk (a `Land feat/<slug>` merge) it reads the workspace's brief and:
8
+ // files each "Raised for later" bullet as an issue (labels `follow-up`, `ws:<slug>`), found again
9
+ // by the marker `<!-- able:<slug>:<title> -->` in its body, so none is filed twice
10
+ // closes the issues listed under "Closed follow-ups" (`- #12 …`), as completed
11
+ // Then it writes the record of every calendar week that has ended and has none yet,
12
+ // `<journal>/weeks/<yyyy>-w<ww>.md`, and commits and pushes only those files. A record is
13
+ // never written before its Sunday is over. With no records yet, only the last ended week is written.
14
+
15
+ import { existsSync } from 'node:fs'
16
+ import { dirname, join, relative, resolve } from 'node:path'
17
+ import { hostRoot, loadConfig } from './config.ts'
18
+
19
+ const args = process.argv.slice(3)
20
+ const dry = args.includes('--dry-run')
21
+
22
+ function fail(message: string): never {
23
+ console.error(`able sync: ${message}`)
24
+ process.exit(1)
25
+ }
26
+
27
+ function run(cmd: string[], cwd: string) {
28
+ const r = Bun.spawnSync(cmd, { cwd, stdout: 'pipe', stderr: 'pipe' })
29
+ if (r.exitCode !== 0) throw new Error(`${cmd.join(' ')}: ${r.stderr.toString().trim()}`)
30
+ return r.stdout.toString().trim()
31
+ }
32
+
33
+ const root = hostRoot()
34
+ const { trunk, journal } = await loadConfig(root)
35
+ const git = (...a: string[]) => run(['git', ...a], root)
36
+ const gh = (...a: string[]) => run([process.execPath, join(import.meta.dir, 'able.ts'), 'gh', ...a], root)
37
+
38
+ // A workspace is a linked worktree: its records reach the trunk only when it lands.
39
+ if (resolve(root, git('rev-parse', '--git-dir')) !== resolve(root, git('rev-parse', '--git-common-dir'))) {
40
+ console.log('able sync: inside a workspace; it runs in the main checkout. Nothing done.')
41
+ process.exit(0)
42
+ }
43
+
44
+ Bun.spawnSync(['git', 'fetch', '--quiet', 'origin', trunk], { cwd: root, stdout: 'ignore', stderr: 'ignore' })
45
+ const behind = Number(git('rev-list', '--count', `HEAD..origin/${trunk}`) || '0')
46
+ if (behind) fail(`this checkout is ${behind} commit(s) behind origin/${trunk}; pull first, or the records that landed since are missed. Nothing done.`)
47
+
48
+ // ── Markdown: `## ` sections and their `### ` subsections ─────────────────────────────────────
49
+
50
+ const section = (text: string, name: string) =>
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)
62
+
63
+ type Item = { slug: string; title: string; text: string; key: string }
64
+ const bullets = (slug: string, block: string): Item[] =>
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
+ })
75
+
76
+ // ── Landed workspaces and their briefs ────────────────────────────────────────────────────────
77
+
78
+ type Land = { slug: string; hash: string; at: number; brief?: string }
79
+ const lands = new Map<string, Land>()
80
+ for (const line of git('log', `origin/${trunk}`, '--merges', '--format=%H%x09%ct%x09%s').split('\n').filter(Boolean)) {
81
+ const [hash = '', at = '0', subject = ''] = line.split('\t')
82
+ const slug = subject.match(/^Land feat\/(\S+)$/)?.[1]
83
+ if (slug && !lands.has(slug)) lands.set(slug, { slug, hash, at: Number(at) * 1000 })
84
+ }
85
+
86
+ // A brief is `<journal>/workspaces/<slug>.md`; one written before that layout stays where it is, beside the journal.
87
+ const briefs = new Map<string, string>()
88
+ for (const path of new Bun.Glob(`${dirname(journal)}/**/*.md`).scanSync(root)) {
89
+ const name = path.split('/').at(-1)!.slice(0, -3)
90
+ if (path === `${journal}/workspaces/${name}.md` || !briefs.has(name)) {
91
+ if (lands.has(name) && (await Bun.file(join(root, path)).text()).includes('\n## Ledger\n')) briefs.set(name, path)
92
+ }
93
+ }
94
+ for (const land of lands.values()) land.brief = briefs.get(land.slug)
95
+
96
+ // ── Follow-ups ────────────────────────────────────────────────────────────────────────────────
97
+
98
+ type Issue = { number: number; title: string; state: string; url: string; body: string; createdAt: string; closedAt: string | null }
99
+ const repo = (JSON.parse(gh('repo', 'view', '--json', 'nameWithOwner')) as { nameWithOwner: string }).nameWithOwner
100
+ const labels = new Set((JSON.parse(gh('label', 'list', '--limit', '1000', '--json', 'name')) as { name: string }[]).map((l) => l.name))
101
+ const issues: Issue[] = labels.has('follow-up')
102
+ ? JSON.parse(gh('issue', 'list', '--label', 'follow-up', '--state', 'all', '--limit', '2000', '--json', 'number,title,state,url,body,createdAt,closedAt'))
103
+ : []
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
+ )
110
+
111
+ const ensureLabel = (name: string, color: string, description: string) => {
112
+ if (labels.has(name) || dry) return
113
+ gh('label', 'create', name, '--color', color, '--description', description)
114
+ labels.add(name)
115
+ }
116
+
117
+ const texts = new Map<string, string>()
118
+ for (const land of lands.values()) if (land.brief) texts.set(land.slug, await Bun.file(join(root, land.brief)).text())
119
+
120
+ const filed: Item[] = []
121
+ const closed: { slug: string; number: number }[] = []
122
+ for (const land of lands.values()) {
123
+ const ledger = section(texts.get(land.slug) ?? '', 'Ledger')
124
+ for (const item of bullets(land.slug, sub(ledger, 'Raised for later'))) {
125
+ if (byKey.has(item.key)) continue
126
+ filed.push(item)
127
+ if (dry) continue
128
+ ensureLabel('follow-up', '5319e7', 'Raised for later by an Able workspace')
129
+ ensureLabel(`ws:${item.slug}`, 'bfd4f2', 'The workspace that raised it')
130
+ const link = `https://github.com/${repo}/blob/${trunk}/${land.brief}`
131
+ const body = `${item.text}\n\nRaised for later in \`${item.slug}\`: ${link}\n\n<!-- able:${item.key} -->\n`
132
+ const url = gh('issue', 'create', '--title', item.title, '--body', body, '--label', 'follow-up', '--label', `ws:${item.slug}`)
133
+ const now = new Date().toISOString()
134
+ const issue = { number: Number(url.split('/').at(-1)), title: item.title, state: 'OPEN', url, body, createdAt: now, closedAt: null }
135
+ issues.push(issue)
136
+ byKey.set(item.key, issue)
137
+ }
138
+ for (const n of [...sub(ledger, 'Closed follow-ups').matchAll(/^- .*?#(\d+)/gm)].map((m) => Number(m[1]))) {
139
+ const issue = issues.find((i) => i.number === n)
140
+ if (issue?.state !== 'OPEN') continue
141
+ closed.push({ slug: land.slug, number: n })
142
+ if (dry) continue
143
+ gh('issue', 'close', String(n), '--reason', 'completed', '--comment', `Closed by \`${land.slug}\`, which took it on.`)
144
+ issue.state = 'CLOSED'
145
+ issue.closedAt = new Date().toISOString()
146
+ }
147
+ }
148
+
149
+ // ── Week records: calendar weeks, Monday 00:00 to Monday 00:00 local time ─────────────────────
150
+
151
+ const DAY = 86_400_000
152
+ const monday = (t: number) => {
153
+ const d = new Date(t)
154
+ d.setHours(0, 0, 0, 0)
155
+ d.setDate(d.getDate() - ((d.getDay() + 6) % 7))
156
+ return d.getTime()
157
+ }
158
+ const addDays = (t: number, n: number) => {
159
+ const d = new Date(t)
160
+ d.setDate(d.getDate() + n)
161
+ return d.getTime()
162
+ }
163
+ // ISO 8601: a week belongs to the year that holds its Thursday.
164
+ const weekName = (start: number) => {
165
+ const thursday = new Date(addDays(start, 3))
166
+ const firstThursday = new Date(thursday.getFullYear(), 0, 4)
167
+ const week = 1 + Math.round((monday(thursday.getTime()) - monday(firstThursday.getTime())) / (7 * DAY))
168
+ return `${thursday.getFullYear()}-w${String(week).padStart(2, '0')}`
169
+ }
170
+ const date = (t: number) => {
171
+ const d = new Date(t)
172
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
173
+ }
174
+
175
+ const weeksDir = join(root, journal, 'weeks')
176
+ const existing = new Set(existsSync(weeksDir) ? [...new Bun.Glob('*.md').scanSync(weeksDir)].filter((f) => /^\d{4}-w\d{2}\.md$/.test(f)).map((f) => f.slice(0, -3)) : [])
177
+ const lastEnded = addDays(monday(Date.now()), -7)
178
+ const due: number[] = []
179
+ if (!existing.size) due.push(lastEnded)
180
+ else {
181
+ let start = lastEnded
182
+ while (!existing.has(weekName(start)) && due.length < 520) {
183
+ due.unshift(start)
184
+ start = addDays(start, -7)
185
+ }
186
+ }
187
+
188
+ // The package a path belongs to: its nearest folder with a justfile or package.json, else its top folder.
189
+ const packageOf = (path: string) => {
190
+ for (let dir = dirname(path); dir !== '.'; dir = dirname(dir)) {
191
+ if (existsSync(join(root, dir, 'justfile')) || existsSync(join(root, dir, 'package.json'))) return dir
192
+ }
193
+ return path.includes('/') ? path.split('/')[0]! : path
194
+ }
195
+
196
+ // Workspaces are worktrees on `feat/<slug>`; open ones are not yet in the trunk.
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
+ })
205
+
206
+ const record = (start: number) => {
207
+ const end = addDays(start, 7)
208
+ const name = weekName(start)
209
+ const inWeek = (t: number) => t >= start && t < end
210
+ const landed = [...lands.values()].filter((l) => inWeek(l.at)).sort((a, b) => a.at - b.at)
211
+ const rows = landed.map((l) => {
212
+ const changed = git('diff', '--name-only', `${l.hash}^1`, l.hash).split('\n').filter(Boolean)
213
+ const commits = git('rev-list', '--count', `${l.hash}^1..${l.hash}^2`)
214
+ const packages = [...new Set(changed.map(packageOf))].sort().join(', ')
215
+ const ws = l.brief ? `[\`${l.slug}\`](${relative(weeksDir, join(root, l.brief))})` : `\`${l.slug}\``
216
+ return `| ${ws} | ${date(l.at)} | ${commits} | ${packages} |`
217
+ })
218
+ const raised = issues.filter((i) => inWeek(Date.parse(i.createdAt))).sort((a, b) => a.number - b.number)
219
+ const done = issues.filter((i) => i.closedAt && inWeek(Date.parse(i.closedAt))).sort((a, b) => a.number - b.number)
220
+ const trunkCommits = git('rev-list', '--count', '--first-parent', '--no-merges', `--since=${start / 1000}`, `--until=${end / 1000}`, `origin/${trunk}`)
221
+ const list = (items: Issue[]) => (items.length ? items.map((i) => `- [#${i.number}](${i.url}) ${i.title}`).join('\n') : 'None.')
222
+
223
+ return `---
224
+ status: stable
225
+ ---
226
+
227
+ # Week ${name.slice(6)}, ${name.slice(0, 4)}
228
+
229
+ Monday ${date(start)} to Sunday ${date(addDays(start, 6))}. Written by \`able sync\` from git, the briefs and the follow-up issues.
230
+
231
+ ## Landed
232
+
233
+ ${rows.length ? `| Workspace | Landed | Commits | Packages |\n|---|---|---|---|\n${rows.join('\n')}` : 'Nothing landed.'}
234
+
235
+ ## Follow-ups raised
236
+
237
+ ${list(raised)}
238
+
239
+ ## Follow-ups closed
240
+
241
+ ${list(done)}
242
+
243
+ ## Still open
244
+
245
+ ${openNow.length ? `Workspaces open when this record was written: ${openNow.map((s) => `\`${s}\``).join(', ')}.` : 'No workspace was open when this record was written.'}
246
+
247
+ ## On the trunk
248
+
249
+ ${trunkCommits} commit(s) made on the trunk outside workspaces.
250
+ `
251
+ }
252
+
253
+ const written: string[] = []
254
+ for (const start of due) {
255
+ const path = `${journal}/weeks/${weekName(start)}.md`
256
+ written.push(path)
257
+ if (!dry) await Bun.write(join(root, path), record(start))
258
+ }
259
+
260
+ // ── Report, then publish only the records ─────────────────────────────────────────────────────
261
+
262
+ const verb = (now: string, later: string) => (dry ? later : now)
263
+ if (dry) console.log('able sync: dry run, nothing written, filed or closed')
264
+ console.log(`able 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')}`)
265
+ for (const i of filed) console.log(` ${verb('filed', 'file')} ${i.slug}: ${i.title}`)
266
+ for (const c of closed) console.log(` ${verb('closed', 'close')} #${c.number} (${c.slug})`)
267
+ for (const w of written) console.log(` ${verb('wrote', 'write')} ${w}`)
268
+
269
+ if (!written.length || dry) process.exit(0)
270
+
271
+ // Able commits its own records and nothing else; anything already waiting to be pushed is the operator's.
272
+ const reasons = [
273
+ git('branch', '--show-current') !== trunk && `not on ${trunk}`,
274
+ existsSync(join(root, '.git/MERGE_HEAD')) && 'a merge is in progress',
275
+ git('log', '--oneline', `origin/${trunk}..HEAD`) && `commits on ${trunk} are not pushed yet`,
276
+ ].filter(Boolean)
277
+ if (reasons.length) {
278
+ console.log(`able sync: left the record(s) uncommitted: ${reasons.join(', ')}`)
279
+ process.exit(0)
280
+ }
281
+ const names = due.map(weekName).join(', ')
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
+ ]) {
287
+ const r = Bun.spawnSync(cmd, { cwd: root, stdio: ['inherit', 'inherit', 'inherit'] })
288
+ if (r.exitCode !== 0) fail(`able ${cmd[2]} failed; the record(s) are written but not published`)
289
+ }
290
+ console.log(`able sync: committed and pushed ${names}`)
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.