@able-autonomy/able 0.0.0-stage → 0.0.2
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 +21 -0
- package/able.ts +114 -0
- package/config.ts +36 -0
- package/index.ts +1 -0
- package/package.json +21 -4
- package/sync.ts +270 -0
- package/README.md +0 -3
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,114 @@
|
|
|
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
|
+
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')
|
|
106
|
+
process.exit(command ? 1 : 0)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const token = await installationToken(resolveRepo(args))
|
|
110
|
+
const gh = Bun.spawnSync(['gh', ...args], {
|
|
111
|
+
stdio: ['inherit', 'inherit', 'inherit'],
|
|
112
|
+
env: { ...process.env, GH_TOKEN: token },
|
|
113
|
+
})
|
|
114
|
+
process.exit(gh.exitCode ?? 1)
|
package/config.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
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
|
+
|
|
7
|
+
export interface AbleConfig {
|
|
8
|
+
/** The branch workspaces are cut from and land on. */
|
|
9
|
+
trunk: string
|
|
10
|
+
/** The journal's folder from the root: `workspaces/<slug>.md` briefs and `weeks/<yyyy>-w<ww>.md` records. */
|
|
11
|
+
journal: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Types and editor help for `able.config.ts`; returns the config unchanged. */
|
|
15
|
+
export const defineConfig = (config: AbleConfig): AbleConfig => config
|
|
16
|
+
|
|
17
|
+
function fail(message: string): never {
|
|
18
|
+
console.error(`able: ${message}`)
|
|
19
|
+
process.exit(1)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The root of the checkout the command runs in. */
|
|
23
|
+
export function hostRoot() {
|
|
24
|
+
const r = Bun.spawnSync(['git', 'rev-parse', '--show-toplevel'], { stdout: 'pipe', stderr: 'pipe' })
|
|
25
|
+
if (r.exitCode !== 0) fail('not inside a git checkout')
|
|
26
|
+
return r.stdout.toString().trim()
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function loadConfig(root: string): Promise<AbleConfig> {
|
|
30
|
+
const path = join(root, 'able.config.ts')
|
|
31
|
+
if (!existsSync(path)) fail(`no able.config.ts at ${root}. Run Able's onboarding to set this project up.`)
|
|
32
|
+
const config = (await import(path)).default as Partial<AbleConfig> | undefined
|
|
33
|
+
const missing = (['trunk', 'journal'] as const).filter((key) => typeof config?.[key] !== 'string' || !config[key])
|
|
34
|
+
if (missing.length) fail(`${path} is missing ${missing.join(', ')}`)
|
|
35
|
+
return config as AbleConfig
|
|
36
|
+
}
|
package/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { defineConfig, type AbleConfig } from './config.ts'
|
package/package.json
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@able-autonomy/able",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.2",
|
|
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
|
+
],
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public"
|
|
22
|
+
}
|
|
23
|
+
}
|
package/sync.ts
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
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.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)
|
|
55
|
+
|
|
56
|
+
type Item = { slug: string; title: string; text: string; key: string }
|
|
57
|
+
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
|
+
})
|
|
63
|
+
|
|
64
|
+
// ── Landed workspaces and their briefs ────────────────────────────────────────────────────────
|
|
65
|
+
|
|
66
|
+
type Land = { slug: string; hash: string; at: number; brief?: string }
|
|
67
|
+
const lands = new Map<string, Land>()
|
|
68
|
+
for (const line of git('log', `origin/${trunk}`, '--merges', '--format=%H%x09%ct%x09%s').split('\n').filter(Boolean)) {
|
|
69
|
+
const [hash = '', at = '0', subject = ''] = line.split('\t')
|
|
70
|
+
const slug = subject.match(/^Land feat\/(\S+)$/)?.[1]
|
|
71
|
+
if (slug && !lands.has(slug)) lands.set(slug, { slug, hash, at: Number(at) * 1000 })
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// A brief is `<journal>/workspaces/<slug>.md`; one written before that layout stays where it is, beside the journal.
|
|
75
|
+
const briefs = new Map<string, string>()
|
|
76
|
+
for (const path of new Bun.Glob(`${dirname(journal)}/**/*.md`).scanSync(root)) {
|
|
77
|
+
const name = path.split('/').at(-1)!.slice(0, -3)
|
|
78
|
+
if (path === `${journal}/workspaces/${name}.md` || !briefs.has(name)) {
|
|
79
|
+
if (lands.has(name) && (await Bun.file(join(root, path)).text()).includes('\n## Ledger\n')) briefs.set(name, path)
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
for (const land of lands.values()) land.brief = briefs.get(land.slug)
|
|
83
|
+
|
|
84
|
+
// ── Follow-ups ────────────────────────────────────────────────────────────────────────────────
|
|
85
|
+
|
|
86
|
+
type Issue = { number: number; title: string; state: string; url: string; body: string; createdAt: string; closedAt: string | null }
|
|
87
|
+
const repo = (JSON.parse(gh('repo', 'view', '--json', 'nameWithOwner')) as { nameWithOwner: string }).nameWithOwner
|
|
88
|
+
const labels = new Set((JSON.parse(gh('label', 'list', '--limit', '1000', '--json', 'name')) as { name: string }[]).map((l) => l.name))
|
|
89
|
+
const issues: Issue[] = labels.has('follow-up')
|
|
90
|
+
? JSON.parse(gh('issue', 'list', '--label', 'follow-up', '--state', 'all', '--limit', '2000', '--json', 'number,title,state,url,body,createdAt,closedAt'))
|
|
91
|
+
: []
|
|
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
|
+
}))
|
|
96
|
+
|
|
97
|
+
const ensureLabel = (name: string, color: string, description: string) => {
|
|
98
|
+
if (labels.has(name) || dry) return
|
|
99
|
+
gh('label', 'create', name, '--color', color, '--description', description)
|
|
100
|
+
labels.add(name)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const texts = new Map<string, string>()
|
|
104
|
+
for (const land of lands.values()) if (land.brief) texts.set(land.slug, await Bun.file(join(root, land.brief)).text())
|
|
105
|
+
|
|
106
|
+
const filed: Item[] = []
|
|
107
|
+
const closed: { slug: string; number: number }[] = []
|
|
108
|
+
for (const land of lands.values()) {
|
|
109
|
+
const ledger = section(texts.get(land.slug) ?? '', 'Ledger')
|
|
110
|
+
for (const item of bullets(land.slug, sub(ledger, 'Raised for later'))) {
|
|
111
|
+
if (byKey.has(item.key)) continue
|
|
112
|
+
filed.push(item)
|
|
113
|
+
if (dry) continue
|
|
114
|
+
ensureLabel('follow-up', '5319e7', 'Raised for later by an Able workspace')
|
|
115
|
+
ensureLabel(`ws:${item.slug}`, 'bfd4f2', 'The workspace that raised it')
|
|
116
|
+
const link = `https://github.com/${repo}/blob/${trunk}/${land.brief}`
|
|
117
|
+
const body = `${item.text}\n\nRaised for later in \`${item.slug}\`: ${link}\n\n<!-- able:${item.key} -->\n`
|
|
118
|
+
const url = gh('issue', 'create', '--title', item.title, '--body', body, '--label', 'follow-up', '--label', `ws:${item.slug}`)
|
|
119
|
+
const now = new Date().toISOString()
|
|
120
|
+
const issue = { number: Number(url.split('/').at(-1)), title: item.title, state: 'OPEN', url, body, createdAt: now, closedAt: null }
|
|
121
|
+
issues.push(issue)
|
|
122
|
+
byKey.set(item.key, issue)
|
|
123
|
+
}
|
|
124
|
+
for (const n of [...sub(ledger, 'Closed follow-ups').matchAll(/^- .*?#(\d+)/gm)].map((m) => Number(m[1]))) {
|
|
125
|
+
const issue = issues.find((i) => i.number === n)
|
|
126
|
+
if (issue?.state !== 'OPEN') continue
|
|
127
|
+
closed.push({ slug: land.slug, number: n })
|
|
128
|
+
if (dry) continue
|
|
129
|
+
gh('issue', 'close', String(n), '--reason', 'completed', '--comment', `Closed by \`${land.slug}\`, which took it on.`)
|
|
130
|
+
issue.state = 'CLOSED'
|
|
131
|
+
issue.closedAt = new Date().toISOString()
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// ── Week records: calendar weeks, Monday 00:00 to Monday 00:00 local time ─────────────────────
|
|
136
|
+
|
|
137
|
+
const DAY = 86_400_000
|
|
138
|
+
const monday = (t: number) => {
|
|
139
|
+
const d = new Date(t)
|
|
140
|
+
d.setHours(0, 0, 0, 0)
|
|
141
|
+
d.setDate(d.getDate() - ((d.getDay() + 6) % 7))
|
|
142
|
+
return d.getTime()
|
|
143
|
+
}
|
|
144
|
+
const addDays = (t: number, n: number) => {
|
|
145
|
+
const d = new Date(t)
|
|
146
|
+
d.setDate(d.getDate() + n)
|
|
147
|
+
return d.getTime()
|
|
148
|
+
}
|
|
149
|
+
// ISO 8601: a week belongs to the year that holds its Thursday.
|
|
150
|
+
const weekName = (start: number) => {
|
|
151
|
+
const thursday = new Date(addDays(start, 3))
|
|
152
|
+
const firstThursday = new Date(thursday.getFullYear(), 0, 4)
|
|
153
|
+
const week = 1 + Math.round((monday(thursday.getTime()) - monday(firstThursday.getTime())) / (7 * DAY))
|
|
154
|
+
return `${thursday.getFullYear()}-w${String(week).padStart(2, '0')}`
|
|
155
|
+
}
|
|
156
|
+
const date = (t: number) => {
|
|
157
|
+
const d = new Date(t)
|
|
158
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const weeksDir = join(root, journal, 'weeks')
|
|
162
|
+
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)) : [])
|
|
163
|
+
const lastEnded = addDays(monday(Date.now()), -7)
|
|
164
|
+
const due: number[] = []
|
|
165
|
+
if (!existing.size) due.push(lastEnded)
|
|
166
|
+
else {
|
|
167
|
+
let start = lastEnded
|
|
168
|
+
while (!existing.has(weekName(start)) && due.length < 520) {
|
|
169
|
+
due.unshift(start)
|
|
170
|
+
start = addDays(start, -7)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// The package a path belongs to: its nearest folder with a justfile or package.json, else its top folder.
|
|
175
|
+
const packageOf = (path: string) => {
|
|
176
|
+
for (let dir = dirname(path); dir !== '.'; dir = dirname(dir)) {
|
|
177
|
+
if (existsSync(join(root, dir, 'justfile')) || existsSync(join(root, dir, 'package.json'))) return dir
|
|
178
|
+
}
|
|
179
|
+
return path.includes('/') ? path.split('/')[0]! : path
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// 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
|
+
})
|
|
189
|
+
|
|
190
|
+
const record = (start: number) => {
|
|
191
|
+
const end = addDays(start, 7)
|
|
192
|
+
const name = weekName(start)
|
|
193
|
+
const inWeek = (t: number) => t >= start && t < end
|
|
194
|
+
const landed = [...lands.values()].filter((l) => inWeek(l.at)).sort((a, b) => a.at - b.at)
|
|
195
|
+
const rows = landed.map((l) => {
|
|
196
|
+
const changed = git('diff', '--name-only', `${l.hash}^1`, l.hash).split('\n').filter(Boolean)
|
|
197
|
+
const commits = git('rev-list', '--count', `${l.hash}^1..${l.hash}^2`)
|
|
198
|
+
const packages = [...new Set(changed.map(packageOf))].sort().join(', ')
|
|
199
|
+
const ws = l.brief ? `[\`${l.slug}\`](${relative(weeksDir, join(root, l.brief))})` : `\`${l.slug}\``
|
|
200
|
+
return `| ${ws} | ${date(l.at)} | ${commits} | ${packages} |`
|
|
201
|
+
})
|
|
202
|
+
const raised = issues.filter((i) => inWeek(Date.parse(i.createdAt))).sort((a, b) => a.number - b.number)
|
|
203
|
+
const done = issues.filter((i) => i.closedAt && inWeek(Date.parse(i.closedAt))).sort((a, b) => a.number - b.number)
|
|
204
|
+
const trunkCommits = git('rev-list', '--count', '--first-parent', '--no-merges', `--since=${start / 1000}`, `--until=${end / 1000}`, `origin/${trunk}`)
|
|
205
|
+
const list = (items: Issue[]) => (items.length ? items.map((i) => `- [#${i.number}](${i.url}) ${i.title}`).join('\n') : 'None.')
|
|
206
|
+
|
|
207
|
+
return `---
|
|
208
|
+
status: stable
|
|
209
|
+
---
|
|
210
|
+
|
|
211
|
+
# Week ${name.slice(6)}, ${name.slice(0, 4)}
|
|
212
|
+
|
|
213
|
+
Monday ${date(start)} to Sunday ${date(addDays(start, 6))}. Written by \`able sync\` from git, the briefs and the follow-up issues.
|
|
214
|
+
|
|
215
|
+
## Landed
|
|
216
|
+
|
|
217
|
+
${rows.length ? `| Workspace | Landed | Commits | Packages |\n|---|---|---|---|\n${rows.join('\n')}` : 'Nothing landed.'}
|
|
218
|
+
|
|
219
|
+
## Follow-ups raised
|
|
220
|
+
|
|
221
|
+
${list(raised)}
|
|
222
|
+
|
|
223
|
+
## Follow-ups closed
|
|
224
|
+
|
|
225
|
+
${list(done)}
|
|
226
|
+
|
|
227
|
+
## Still open
|
|
228
|
+
|
|
229
|
+
${openNow.length ? `Workspaces open when this record was written: ${openNow.map((s) => `\`${s}\``).join(', ')}.` : 'No workspace was open when this record was written.'}
|
|
230
|
+
|
|
231
|
+
## On the trunk
|
|
232
|
+
|
|
233
|
+
${trunkCommits} commit(s) made on the trunk outside workspaces.
|
|
234
|
+
`
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const written: string[] = []
|
|
238
|
+
for (const start of due) {
|
|
239
|
+
const path = `${journal}/weeks/${weekName(start)}.md`
|
|
240
|
+
written.push(path)
|
|
241
|
+
if (!dry) await Bun.write(join(root, path), record(start))
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// ── Report, then publish only the records ─────────────────────────────────────────────────────
|
|
245
|
+
|
|
246
|
+
const verb = (now: string, later: string) => (dry ? later : now)
|
|
247
|
+
if (dry) console.log('able sync: dry run, nothing written, filed or closed')
|
|
248
|
+
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')}`)
|
|
249
|
+
for (const i of filed) console.log(` ${verb('filed', 'file')} ${i.slug}: ${i.title}`)
|
|
250
|
+
for (const c of closed) console.log(` ${verb('closed', 'close')} #${c.number} (${c.slug})`)
|
|
251
|
+
for (const w of written) console.log(` ${verb('wrote', 'write')} ${w}`)
|
|
252
|
+
|
|
253
|
+
if (!written.length || dry) process.exit(0)
|
|
254
|
+
|
|
255
|
+
// Able commits its own records and nothing else; anything already waiting to be pushed is the operator's.
|
|
256
|
+
const reasons = [
|
|
257
|
+
git('branch', '--show-current') !== trunk && `not on ${trunk}`,
|
|
258
|
+
existsSync(join(root, '.git/MERGE_HEAD')) && 'a merge is in progress',
|
|
259
|
+
git('log', '--oneline', `origin/${trunk}..HEAD`) && `commits on ${trunk} are not pushed yet`,
|
|
260
|
+
].filter(Boolean)
|
|
261
|
+
if (reasons.length) {
|
|
262
|
+
console.log(`able sync: left the record(s) uncommitted: ${reasons.join(', ')}`)
|
|
263
|
+
process.exit(0)
|
|
264
|
+
}
|
|
265
|
+
const names = due.map(weekName).join(', ')
|
|
266
|
+
for (const cmd of [['just', 'commit', `journal: week record ${names}`, ...written, '--yes'], ['just', 'push']]) {
|
|
267
|
+
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`)
|
|
269
|
+
}
|
|
270
|
+
console.log(`able sync: committed and pushed ${names}`)
|
package/README.md
DELETED