heyquilt 0.3.138 → 0.3.141
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/RELEASES.md +10 -0
- package/bin/quilt.js +7 -143
- package/package.json +1 -1
- package/src/account.js +0 -29
- package/src/api/memory-store.js +0 -29
- package/src/api/routes/teams.js +0 -23
- package/src/api/server.js +5 -19
- package/src/api/supabase-store.js +0 -52
- package/src/branch-view.js +6 -131
- package/src/control.js +2 -33
- package/src/duties.js +1 -1
- package/src/github-commit.js +3 -315
- package/src/mcp.js +8 -157
- package/src/relay-ask.js +3 -66
- package/src/relay-cluster.js +3 -5
- package/src/relay-mcp.js +6 -418
- package/src/relay-prune.js +6 -145
- package/src/relay-turn-sync.js +1 -1
- package/src/server.js +33 -1331
- package/src/session-follow.js +18 -5
- package/src/session.js +58 -3526
- package/src/status.js +2 -58
- package/src/turn-sync.js +15 -2
- package/src/ui/changes.js +5 -14
- package/src/ui/chat.js +0 -1
- package/src/ui/common.js +0 -2
- package/src/ui/git-rule.js +2 -30
- package/src/ui/home.js +3 -76
- package/src/ui/session.js +34 -528
- package/src/ui/tree.js +2 -8
- package/src/ui/workspaces.js +2 -122
- package/src/ui-server.js +1 -38
- package/src/api/routes/github.js +0 -380
- package/src/branches.js +0 -194
- package/src/clash.js +0 -128
- package/src/commit-request.js +0 -59
- package/src/commit.js +0 -213
- package/src/git-hook.js +0 -48
- package/src/gitignore.js +0 -49
- package/src/gitstate.js +0 -1069
- package/src/relay-ci.js +0 -111
- package/src/relay-clash.js +0 -214
- package/src/relay-commit.js +0 -923
- package/src/relay-filekey.js +0 -46
- package/src/relay-git.js +0 -274
- package/src/relay-githttp.js +0 -166
- package/src/relay-github.js +0 -109
- package/src/relay-outbound.js +0 -1295
- package/src/relay-repo-moves.js +0 -43
- package/src/relay-sync.js +0 -795
- package/src/relay-upstream.js +0 -889
- package/src/sync-words.js +0 -42
- package/src/upstream.js +0 -192
package/src/api/routes/github.js
DELETED
|
@@ -1,380 +0,0 @@
|
|
|
1
|
-
// Connecting GitHub (github-app.js): a person starts from the app or the website, GitHub asks them
|
|
2
|
-
// which repositories to install Quilt on and who they are, and comes back here. The relay then asks
|
|
3
|
-
// for a repository's credentials for a session's owner when an agent commits.
|
|
4
|
-
import crypto from 'node:crypto'
|
|
5
|
-
import { HttpError, Raw } from '../http.js'
|
|
6
|
-
import { githubApp, signState, readStateFull, WRITE_ROLES, READ_ROLES, GitHubAppError } from '../github-app.js'
|
|
7
|
-
import { orgAccess, orgGrantsFor } from '../org-access.js'
|
|
8
|
-
import { workspaceAccess } from '../workspace-access.js'
|
|
9
|
-
export { ensureWebhookSecret, redeliverFailed } from '../github-app.js'
|
|
10
|
-
|
|
11
|
-
const PART = /^[A-Za-z0-9_.-]{1,100}$/
|
|
12
|
-
/** A lease lapses this long after its last heartbeat: two missed heartbeats (plan §8). */
|
|
13
|
-
const ACCOUNT = /^person:([A-Za-z0-9_-]{1,64})$/
|
|
14
|
-
const ACTOR = /^(person|agent):([A-Za-z0-9_-]{1,64})$/
|
|
15
|
-
const ROOM = /^[A-Za-z0-9_-]{1,64}$/
|
|
16
|
-
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
17
|
-
const MAX_REPOS = 200
|
|
18
|
-
/** owner/name from what a person typed ("github.com/acme/widgets.git", "acme/widgets"), or null. */
|
|
19
|
-
const cleanRepo = (v) => { const m = /^(?:https?:\/\/)?(?:github\.com\/)?([A-Za-z0-9_.-]{1,100})\/([A-Za-z0-9_.-]{1,100}?)(?:\.git)?\/?$/.exec(String(v || '').trim()); return m ? `${m[1]}/${m[2]}` : null }
|
|
20
|
-
const digest = (s) => crypto.createHash('sha256').update(String(s)).digest()
|
|
21
|
-
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]))
|
|
22
|
-
|
|
23
|
-
/** The page GitHub sends people back to: plain, so it works from any browser. */
|
|
24
|
-
const page = (title, text) => new Raw(200, `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)}</title>
|
|
25
|
-
<style>body{font:16px/1.5 system-ui,sans-serif;background:#fdf6f0;color:#2b2420;display:grid;place-items:center;min-height:100vh;margin:0;padding:16px}main{max-width:420px;text-align:center}h1{font-size:22px}</style>
|
|
26
|
-
<main><h1>${esc(title)}</h1><p>${esc(text)}</p></main>`, 'text/html; charset=utf-8')
|
|
27
|
-
|
|
28
|
-
export function githubRoutes ({ store, person, bearer, relaySecret, github: cfg, githubFetch, relayHttp = '', relayFetch = globalThis.fetch, tellRelays = null, now, log, hookSecret = { value: cfg && cfg.webhookSecret }, workspaces = false }) {
|
|
29
|
-
const app = cfg ? githubApp(cfg, { fetch: githubFetch, now }) : null
|
|
30
|
-
const need = () => { if (!app) throw new HttpError(503, 'GitHub is not set up on this server') }
|
|
31
|
-
const fromRelay = (req) => {
|
|
32
|
-
if (!relaySecret) throw new HttpError(503, 'the relay is not set up on this server')
|
|
33
|
-
if (!crypto.timingSafeEqual(digest(bearer(req)), digest(relaySecret))) throw new HttpError(401, 'only the relay may ask for this')
|
|
34
|
-
}
|
|
35
|
-
// Credentials per account and repository, kept until a few minutes before they run out.
|
|
36
|
-
const cache = new Map()
|
|
37
|
-
// What agents may commit, for a whole workspace or org: '' (each session decides), 'off', 'branches' or 'any'.
|
|
38
|
-
const agentCommitsGiven = (v) => {
|
|
39
|
-
if (v === '' || v === null) return ''
|
|
40
|
-
if (['off', 'branches', 'any'].includes(v)) return v
|
|
41
|
-
throw new HttpError(400, 'agentCommits is "" (each session decides), off, branches or any.')
|
|
42
|
-
}
|
|
43
|
-
// A nudge for the relay: every relay machine gets it (src/api/relay-cluster.js), each for the sessions it holds.
|
|
44
|
-
const tell = tellRelays || (async (path, body) => {
|
|
45
|
-
await relayFetch(`${relayHttp}${path}`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${relaySecret}` }, body: JSON.stringify(body) })
|
|
46
|
-
})
|
|
47
|
-
const nudge = (path, body, what) => {
|
|
48
|
-
if (!relayHttp || !relaySecret) return Promise.resolve()
|
|
49
|
-
return Promise.resolve().then(() => tell(path, body)).catch((err) => log(`${what} to relay: ${err.message}`))
|
|
50
|
-
}
|
|
51
|
-
// The relay asks its sessions again now (relay /github/policy), so a change applies at once.
|
|
52
|
-
const policyChanged = () => { nudge('/github/policy', {}, 'agent policy') }
|
|
53
|
-
|
|
54
|
-
/** A workspace by id that `userId` may manage GitHub for (its admins), or an HttpError. */
|
|
55
|
-
const workspaceToManage = async (userId, id, { manage = true } = {}) => {
|
|
56
|
-
if (!workspaces) throw new HttpError(404, 'not found')
|
|
57
|
-
const ws = UUID.test(String(id || '')) ? await store.workspaceById(id) : null
|
|
58
|
-
const a = ws && await workspaceAccess(store, ws, `person:${userId}`, { orgGrants: ws.orgId ? await orgGrantsFor(store, ws.orgId, `person:${userId}`) : null })
|
|
59
|
-
if (!a) throw new HttpError(404, 'no such workspace')
|
|
60
|
-
if (manage && !a.admin) throw new HttpError(403, 'only the workspace\'s admins change its GitHub connection')
|
|
61
|
-
return { ws, admin: !!a.admin }
|
|
62
|
-
}
|
|
63
|
-
/** Where a connection attaches (plan §2): the caller ('person', the default), a workspace they manage, or an org whose settings they may change. */
|
|
64
|
-
const scopeFor = async (userId, b) => {
|
|
65
|
-
const scope = ['workspace', 'org'].includes(b.scope) ? b.scope : 'person'
|
|
66
|
-
if (scope === 'person') return { scope, scopeId: userId }
|
|
67
|
-
if (scope === 'workspace') { const { ws } = await workspaceToManage(userId, b.id); return { scope, scopeId: ws.id } }
|
|
68
|
-
const org = await orgAccess(store, userId, b.id)
|
|
69
|
-
org.need('org', 'u')
|
|
70
|
-
return { scope, scopeId: org.org.id }
|
|
71
|
-
}
|
|
72
|
-
/** Who connected GitHub for a scope, with their GitHub login. */
|
|
73
|
-
const connectionsOf = async (scope, scopeId) => {
|
|
74
|
-
const out = []
|
|
75
|
-
for (const c of await store.githubConnections({ scope, scopeId })) {
|
|
76
|
-
const link = await store.githubLink(c.connectedBy)
|
|
77
|
-
const p = await store.profile(c.connectedBy).catch(() => null)
|
|
78
|
-
out.push({ connectedBy: c.connectedBy, name: (p && p.name) || '', login: link ? link.login : '', at: c.createdAt })
|
|
79
|
-
}
|
|
80
|
-
return out
|
|
81
|
-
}
|
|
82
|
-
/** The person an account works for (Require GitHub): a person themselves; an agent, its owner, or (an org's agent) the session's owner. */
|
|
83
|
-
const personFor = async (actor, session) => {
|
|
84
|
-
const m = ACTOR.exec(actor || '')
|
|
85
|
-
if (!m) return null
|
|
86
|
-
if (m[1] === 'person') return m[2]
|
|
87
|
-
const agent = await store.agentById(m[2]).catch(() => null)
|
|
88
|
-
if (agent && agent.ownerUserId) return agent.ownerUserId
|
|
89
|
-
const owner = session && ACCOUNT.exec(session.ownerAccount || '')
|
|
90
|
-
return owner ? owner[1] : null
|
|
91
|
-
}
|
|
92
|
-
/**
|
|
93
|
-
* Whose GitHub connections may cover `owner/name` for a session (plan §2): its workspace's, then its
|
|
94
|
-
* org's, then its people's own, in that order; { ids } or { refused } when the workspace's access mode
|
|
95
|
-
* keeps the repository out. With the org's Require GitHub and an `actingFor`, only the person that
|
|
96
|
-
* account works for counts: an agent gets their live GitHub permissions, no more.
|
|
97
|
-
*/
|
|
98
|
-
const coverFor = async ({ room, accounts, actingFor, owner, name }) => {
|
|
99
|
-
const ids = []
|
|
100
|
-
let session = null
|
|
101
|
-
let ws = null
|
|
102
|
-
if (room) session = await store.sessionByRoom(room).catch(() => null)
|
|
103
|
-
if (session && session.workspaceId) ws = await store.workspaceById(session.workspaceId).catch(() => null)
|
|
104
|
-
let require = false
|
|
105
|
-
if (ws) {
|
|
106
|
-
const g = await store.workspaceGithub(ws.id)
|
|
107
|
-
if (g.access === 'repos' && !g.repos.some((r) => r.toLowerCase() === `${owner}/${name}`.toLowerCase())) return { refused: { state: 'not-allowed', why: `the workspace ${ws.name} works only with the repositories it lists, and ${owner}/${name} isn't one of them` } }
|
|
108
|
-
for (const c of await store.githubConnections({ scope: 'workspace', scopeId: ws.id })) ids.push(c.connectedBy)
|
|
109
|
-
if (ws.orgId) {
|
|
110
|
-
require = (await store.orgGithub(ws.orgId)).requireGithub
|
|
111
|
-
for (const c of await store.githubConnections({ scope: 'org', scopeId: ws.orgId })) ids.push(c.connectedBy)
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
if (require && actingFor) {
|
|
115
|
-
const who = await personFor(actingFor, session)
|
|
116
|
-
return { ids: who ? [who] : [], require: true, actingFor }
|
|
117
|
-
}
|
|
118
|
-
return { ids: [...new Set([...ids, ...accounts])], require }
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
return [
|
|
122
|
-
// Where to send a person to connect GitHub: installing the app, then back to the callback.
|
|
123
|
-
['POST', /^\/v1\/github\/connect$/, async (req, b) => {
|
|
124
|
-
need()
|
|
125
|
-
const { userId } = await person(req)
|
|
126
|
-
const where = await scopeFor(userId, b)
|
|
127
|
-
// For a repository: straight to its owner's (person's or organization's) install page, skipping the account picker.
|
|
128
|
-
const m = /^(?:github\.com\/)?([A-Za-z0-9_.-]{1,100})\/[A-Za-z0-9_.-]{1,100}$/.exec(String(b.repo || '').replace(/\.git$/, ''))
|
|
129
|
-
const target = m ? await app.accountId(m[1]).catch(() => null) : null
|
|
130
|
-
return { url: app.installUrl(signState(cfg, userId, now(), where.scope === 'person' ? {} : where), { targetId: target }) }
|
|
131
|
-
}],
|
|
132
|
-
['GET', /^\/v1\/me\/github$/, async (req) => {
|
|
133
|
-
const { userId } = await person(req)
|
|
134
|
-
const link = await store.githubLink(userId)
|
|
135
|
-
return { available: !!app, connected: !!link, ...(link ? { login: link.login } : {}) }
|
|
136
|
-
}],
|
|
137
|
-
['DELETE', /^\/v1\/me\/github$/, async (req) => {
|
|
138
|
-
const { userId } = await person(req)
|
|
139
|
-
await store.deleteGithubLink(userId)
|
|
140
|
-
cache.clear()
|
|
141
|
-
return { ok: true }
|
|
142
|
-
}],
|
|
143
|
-
// GitHub sends the person back here after the install, with who they are (code) and our state.
|
|
144
|
-
['GET', /^\/v1\/github\/(callback|setup)$/, async (req) => {
|
|
145
|
-
need()
|
|
146
|
-
const q = new URL(req.url, 'http://x').searchParams
|
|
147
|
-
const st = readStateFull(cfg, q.get('state'), now())
|
|
148
|
-
const userId = st ? st.userId : null
|
|
149
|
-
if (!userId) return page('Start from Quilt', 'Open Quilt and click Connect GitHub in the commit panel, so Quilt knows which account to connect. Quilt is installed on GitHub either way.')
|
|
150
|
-
if (!q.get('code')) return page('GitHub did not sign you in', 'Try Connect GitHub again from Quilt.')
|
|
151
|
-
let who
|
|
152
|
-
try { who = await app.whoAuthorized(q.get('code')) } catch (err) { log(`github connect: ${err.message}`); return page('GitHub did not sign you in', 'Try Connect GitHub again from Quilt.') }
|
|
153
|
-
await store.setGithubLink(userId, { githubId: who.id, login: who.login })
|
|
154
|
-
// Connected for a workspace or an org (plan §2): its sessions use this connection before their people's own.
|
|
155
|
-
if (st.scope) {
|
|
156
|
-
const inst = Number(q.get('installation_id'))
|
|
157
|
-
await store.addGithubConnection({ scope: st.scope, scopeId: st.scopeId, connectedBy: userId, installationId: Number.isSafeInteger(inst) && inst > 0 ? inst : null })
|
|
158
|
-
}
|
|
159
|
-
cache.clear()
|
|
160
|
-
// The relay checks every session this person is in again now, so the card in their app clears as they come back.
|
|
161
|
-
nudge('/github/connected', { account: `person:${userId}` }, 'github connected')
|
|
162
|
-
// An organization that has its admins approve apps: the install is asked for, not done yet.
|
|
163
|
-
if (q.get('setup_action') === 'request') return page(`Asked, as @${who.login}`, 'The organization\'s admins have to approve Quilt on GitHub. As soon as they do, agents in your sessions on its repositories commit and merge on their own; nothing more to do on your side. You can close this tab.')
|
|
164
|
-
if (st.scope) return page(`Connected as @${who.login}`, `Sessions in this ${st.scope} use this connection now, before their people's own. You can close this tab.`)
|
|
165
|
-
return page(`Connected as @${who.login}`, 'Agents in your sessions can now commit and merge on the repositories you installed Quilt on, as far as each session\'s owner allows, and pushes reach the session within seconds. You can close this tab.')
|
|
166
|
-
}],
|
|
167
|
-
// A workspace's GitHub: its connections and access mode ('open', or 'repos' with the repositories it allows).
|
|
168
|
-
['GET', /^\/v1\/workspaces\/([^/]+)\/github$/, async (req) => {
|
|
169
|
-
const { userId } = await person(req)
|
|
170
|
-
const { ws, admin } = await workspaceToManage(userId, req.url.split('/')[3], { manage: false })
|
|
171
|
-
let org = null
|
|
172
|
-
if (ws.orgId) {
|
|
173
|
-
const o = await store.orgById(ws.orgId)
|
|
174
|
-
const g = await orgGrantsFor(store, ws.orgId, `person:${userId}`)
|
|
175
|
-
const og = await store.orgGithub(ws.orgId)
|
|
176
|
-
org = { slug: o ? o.slug : '', name: o ? o.name : '', requireGithub: og.requireGithub, agentCommits: og.agentCommits, admin: !!(g && g.can('org', 'u')), connections: await connectionsOf('org', ws.orgId) }
|
|
177
|
-
}
|
|
178
|
-
return { ...(await store.workspaceGithub(ws.id)), connections: await connectionsOf('workspace', ws.id), admin, me: userId, ...(org ? { org } : {}) }
|
|
179
|
-
}],
|
|
180
|
-
['PUT', /^\/v1\/workspaces\/([^/]+)\/github$/, async (req, b) => {
|
|
181
|
-
const { userId } = await person(req)
|
|
182
|
-
const { ws } = await workspaceToManage(userId, req.url.split('/')[3])
|
|
183
|
-
const patch = {}
|
|
184
|
-
if ('access' in b) {
|
|
185
|
-
const access = b.access === 'repos' ? 'repos' : b.access === 'open' ? 'open' : null
|
|
186
|
-
if (!access) throw new HttpError(400, 'Access is open or repos.')
|
|
187
|
-
const given = Array.isArray(b.repos) ? b.repos : []
|
|
188
|
-
const repos = [...new Set(given.map(cleanRepo))]
|
|
189
|
-
if (repos.includes(null)) throw new HttpError(400, 'Give repositories as owner/name.')
|
|
190
|
-
if (repos.length > MAX_REPOS) throw new HttpError(400, `List at most ${MAX_REPOS} repositories.`)
|
|
191
|
-
if (access === 'repos' && !repos.length) throw new HttpError(400, 'List the repositories this workspace may use.')
|
|
192
|
-
Object.assign(patch, { access, repos })
|
|
193
|
-
}
|
|
194
|
-
if ('agentCommits' in b) patch.agentCommits = agentCommitsGiven(b.agentCommits)
|
|
195
|
-
if (!Object.keys(patch).length) throw new HttpError(400, 'Give access (and repos) or agentCommits.')
|
|
196
|
-
await store.setWorkspaceGithub(ws.id, patch)
|
|
197
|
-
cache.clear()
|
|
198
|
-
if ('agentCommits' in patch) policyChanged()
|
|
199
|
-
return store.workspaceGithub(ws.id)
|
|
200
|
-
}],
|
|
201
|
-
['DELETE', /^\/v1\/workspaces\/([^/]+)\/github\/connection$/, async (req, b) => {
|
|
202
|
-
const { userId } = await person(req)
|
|
203
|
-
const { ws, admin } = await workspaceToManage(userId, req.url.split('/')[3], { manage: false })
|
|
204
|
-
const whose = typeof b.connectedBy === 'string' && b.connectedBy ? b.connectedBy : userId
|
|
205
|
-
if (whose !== userId && !admin) throw new HttpError(403, 'only the workspace\'s admins remove others\' connections')
|
|
206
|
-
await store.removeGithubConnection({ scope: 'workspace', scopeId: ws.id, connectedBy: whose })
|
|
207
|
-
cache.clear()
|
|
208
|
-
return { ok: true }
|
|
209
|
-
}],
|
|
210
|
-
// An org's GitHub: its connections and the Require GitHub switch.
|
|
211
|
-
['GET', /^\/v1\/orgs\/([^/]+)\/github$/, async (req) => {
|
|
212
|
-
const { userId } = await person(req)
|
|
213
|
-
const org = await orgAccess(store, userId, decodeURIComponent(req.url.split('/')[3]))
|
|
214
|
-
return { ...(await store.orgGithub(org.org.id)), connections: await connectionsOf('org', org.org.id), admin: org.can('org', 'u') }
|
|
215
|
-
}],
|
|
216
|
-
['PUT', /^\/v1\/orgs\/([^/]+)\/github$/, async (req, b) => {
|
|
217
|
-
const { userId } = await person(req)
|
|
218
|
-
const org = await orgAccess(store, userId, decodeURIComponent(req.url.split('/')[3]))
|
|
219
|
-
org.need('org', 'u')
|
|
220
|
-
const patch = {}
|
|
221
|
-
if ('requireGithub' in b) {
|
|
222
|
-
if (typeof b.requireGithub !== 'boolean') throw new HttpError(400, 'Say requireGithub: true or false.')
|
|
223
|
-
patch.requireGithub = b.requireGithub
|
|
224
|
-
}
|
|
225
|
-
if ('agentCommits' in b) patch.agentCommits = agentCommitsGiven(b.agentCommits)
|
|
226
|
-
if (!Object.keys(patch).length) throw new HttpError(400, 'Give requireGithub or agentCommits.')
|
|
227
|
-
await store.setOrgGithub(org.org.id, patch)
|
|
228
|
-
cache.clear()
|
|
229
|
-
if ('agentCommits' in patch) policyChanged()
|
|
230
|
-
return store.orgGithub(org.org.id)
|
|
231
|
-
}],
|
|
232
|
-
['DELETE', /^\/v1\/orgs\/([^/]+)\/github\/connection$/, async (req, b) => {
|
|
233
|
-
const { userId } = await person(req)
|
|
234
|
-
const org = await orgAccess(store, userId, decodeURIComponent(req.url.split('/')[3]))
|
|
235
|
-
const whose = typeof b.connectedBy === 'string' && b.connectedBy ? b.connectedBy : userId
|
|
236
|
-
if (whose !== userId) org.need('org', 'u')
|
|
237
|
-
await store.removeGithubConnection({ scope: 'org', scopeId: org.org.id, connectedBy: whose })
|
|
238
|
-
cache.clear()
|
|
239
|
-
return { ok: true }
|
|
240
|
-
}],
|
|
241
|
-
// GitHub's events, signed with the app's webhook secret (set by the API itself, github-app.js
|
|
242
|
-
// ensureWebhookSecret). Each is passed to the relay as a hint with what it needs; the relay
|
|
243
|
-
// trusts only the ref name and reads the truth from git.
|
|
244
|
-
['POST', /^\/v1\/github\/webhook$/, async (req, raw) => {
|
|
245
|
-
const secret = hookSecret.value || ''
|
|
246
|
-
if (!cfg || !secret) throw new HttpError(503, 'GitHub webhooks are not set up on this server')
|
|
247
|
-
{
|
|
248
|
-
const sig = String(req.headers['x-hub-signature-256'] || '')
|
|
249
|
-
const want = 'sha256=' + crypto.createHmac('sha256', secret).update(raw).digest('hex')
|
|
250
|
-
if (sig.length !== want.length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(want))) throw new HttpError(401, 'bad signature')
|
|
251
|
-
}
|
|
252
|
-
const event = String(req.headers['x-github-event'] || '')
|
|
253
|
-
if (!['push', 'create', 'delete', 'pull_request', 'check_suite', 'repository'].includes(event)) return { ok: true }
|
|
254
|
-
let e
|
|
255
|
-
try { e = JSON.parse(raw.toString('utf8')) } catch { throw new HttpError(400, 'bad json') }
|
|
256
|
-
const repo = e && e.repository && typeof e.repository.full_name === 'string' ? e.repository.full_name : ''
|
|
257
|
-
if (!repo || !relayHttp || !relaySecret) return { ok: true }
|
|
258
|
-
const tellHook = (path, body) => nudge(path, { repo: `github.com/${repo}`, ...body }, 'github webhook')
|
|
259
|
-
const sha = (v) => typeof v === 'string' && /^[0-9a-f]{40}$/.test(v) ? v : ''
|
|
260
|
-
if (event === 'repository') {
|
|
261
|
-
// Renamed, or moved to another owner: every session following the old name follows the new one
|
|
262
|
-
// (relay /github/moved), and its members' folders point origin at it.
|
|
263
|
-
const r = e.repository || {}
|
|
264
|
-
const ch = e.changes || {}
|
|
265
|
-
const name = String(r.name || '')
|
|
266
|
-
const owner = String((r.owner && r.owner.login) || '')
|
|
267
|
-
const fromOwner = ch.owner && ch.owner.from ? String((ch.owner.from.user && ch.owner.from.user.login) || (ch.owner.from.organization && ch.owner.from.organization.login) || '') : ''
|
|
268
|
-
const fromName = ch.repository && ch.repository.name && typeof ch.repository.name.from === 'string' ? ch.repository.name.from : ''
|
|
269
|
-
const from = e.action === 'transferred' && fromOwner ? `${fromOwner}/${name}` : e.action === 'renamed' && fromName ? `${owner}/${fromName}` : ''
|
|
270
|
-
if (from && from.toLowerCase() !== repo.toLowerCase()) await nudge('/github/moved', { repo: `github.com/${from}`, to: `github.com/${repo}` }, 'github webhook')
|
|
271
|
-
return { ok: true }
|
|
272
|
-
}
|
|
273
|
-
if (event === 'pull_request') {
|
|
274
|
-
// A pull request changed (opened, closed, merged, synchronized): the relay looks at the one its tasks are in.
|
|
275
|
-
const pr = e.pull_request || {}
|
|
276
|
-
const number = Number.isInteger(pr.number) ? pr.number : (Number.isInteger(e.number) ? e.number : null)
|
|
277
|
-
const ref = (x) => x && typeof x.ref === 'string' ? x.ref : ''
|
|
278
|
-
if (number != null) await tellHook('/github/pull', { number, action: String(e.action || ''), ...(pr.merged === true ? { merged: true } : {}), ...(ref(pr.head) ? { head: ref(pr.head) } : {}), ...(ref(pr.base) ? { base: ref(pr.base) } : {}), ...(sha(pr.merge_commit_sha) ? { sha: pr.merge_commit_sha } : {}) })
|
|
279
|
-
return { ok: true }
|
|
280
|
-
}
|
|
281
|
-
if (event === 'check_suite') {
|
|
282
|
-
const cs = e.check_suite || {}
|
|
283
|
-
if (sha(cs.head_sha)) await tellHook('/github/checks', { sha: cs.head_sha, branch: typeof cs.head_branch === 'string' ? cs.head_branch : '', conclusion: String(cs.conclusion || '') })
|
|
284
|
-
return { ok: true }
|
|
285
|
-
}
|
|
286
|
-
if (event === 'create' || event === 'delete') {
|
|
287
|
-
if (e.ref_type !== 'branch' || typeof e.ref !== 'string' || !e.ref) return { ok: true }
|
|
288
|
-
await tellHook('/github/push', { ref: e.ref, ...(event === 'create' ? { created: true } : { deleted: true }) })
|
|
289
|
-
return { ok: true }
|
|
290
|
-
}
|
|
291
|
-
const ref = typeof e.ref === 'string' && e.ref.startsWith('refs/heads/') ? e.ref.slice('refs/heads/'.length) : ''
|
|
292
|
-
if (!ref) return { ok: true }
|
|
293
|
-
const after = e.deleted ? '' : sha(e.after)
|
|
294
|
-
await tellHook('/github/push', { ref, before: sha(e.before), after, sha: after, forced: !!e.forced, deleted: !!e.deleted })
|
|
295
|
-
return { ok: true }
|
|
296
|
-
}, { raw: true, maxBody: 25 * 1024 * 1024 }],
|
|
297
|
-
// The relay: whether git is on for everyone in a session, and what agents may push there, when a rule
|
|
298
|
-
// above the session says (docs/superpowers/specs/2026-10-17-git-for-everyone.md): its org's, the teams'
|
|
299
|
-
// its owner is on (in the org) and its workspace's. Each rule is a ceiling (off < branches < any), so the
|
|
300
|
-
// strictest is the one that holds; at equal strictness the broader is named, since that's the one to change.
|
|
301
|
-
// { agentCommits: '' } when none is set: the session's owner decides.
|
|
302
|
-
['POST', /^\/v1\/relay\/session-policy$/, async (req, b) => {
|
|
303
|
-
fromRelay(req)
|
|
304
|
-
const room = typeof b.room === 'string' && ROOM.test(b.room) ? b.room : ''
|
|
305
|
-
if (!room) throw new HttpError(400, 'give the room')
|
|
306
|
-
const session = await store.sessionByRoom(room).catch(() => null)
|
|
307
|
-
const ws = session && session.workspaceId ? await store.workspaceById(session.workspaceId).catch(() => null) : null
|
|
308
|
-
if (!ws) return { agentCommits: '' }
|
|
309
|
-
const rules = []
|
|
310
|
-
if (ws.orgId) {
|
|
311
|
-
const o = await store.orgGithub(ws.orgId)
|
|
312
|
-
if (o.agentCommits) { const org = await store.orgById(ws.orgId).catch(() => null); rules.push({ agentCommits: o.agentCommits, by: 'org', name: (org && org.name) || '' }) }
|
|
313
|
-
const owner = ACCOUNT.exec(session.ownerAccount || '')
|
|
314
|
-
const member = owner ? await store.memberOf(ws.orgId, owner[1]).catch(() => null) : null
|
|
315
|
-
if (member) for (const r of await store.teamGitRules(member.id)) rules.push({ agentCommits: r.agentCommits, by: 'team', name: r.name })
|
|
316
|
-
}
|
|
317
|
-
const w = await store.workspaceGithub(ws.id)
|
|
318
|
-
if (w.agentCommits) rules.push({ agentCommits: w.agentCommits, by: 'workspace', name: ws.name || '' })
|
|
319
|
-
if (!rules.length) return { agentCommits: '' }
|
|
320
|
-
const rank = { off: 0, branches: 1, any: 2 }
|
|
321
|
-
// Stable: the first of the strictest, and rules are in order broadest first.
|
|
322
|
-
return rules.reduce((best, r) => rank[r.agentCommits] < rank[best.agentCommits] ? r : best)
|
|
323
|
-
}],
|
|
324
|
-
// The relay: which GitHub accounts the session's people linked (login and id), for commit authorship
|
|
325
|
-
// (relay-outbound.js: a person's commits carry their GitHub noreply address). Never a token.
|
|
326
|
-
['POST', /^\/v1\/relay\/github-logins$/, async (req, b) => {
|
|
327
|
-
fromRelay(req)
|
|
328
|
-
const given = Array.isArray(b.accounts) ? b.accounts : []
|
|
329
|
-
const accounts = [...new Set(given.map((x) => { const m = ACCOUNT.exec(String(x || '')); return m ? m[1] : null }).filter(Boolean))].slice(0, 200)
|
|
330
|
-
const logins = {}
|
|
331
|
-
for (const id of accounts) { const l = await store.githubLink(id); if (l) logins[`person:${id}`] = { login: l.login, id: l.githubId } }
|
|
332
|
-
return { logins }
|
|
333
|
-
}],
|
|
334
|
-
// The relay: credentials for one repository, for the first of the session's people whose linked
|
|
335
|
-
// GitHub account may do what is asked there (write: commit, merge; read: fetch, clone).
|
|
336
|
-
['POST', /^\/v1\/relay\/github-token$/, async (req, b) => {
|
|
337
|
-
fromRelay(req)
|
|
338
|
-
need()
|
|
339
|
-
const access = b.access === 'read' ? 'read' : 'write'
|
|
340
|
-
const given = Array.isArray(b.accounts) ? b.accounts : b.account ? [b.account] : []
|
|
341
|
-
const members = [...new Set(given.map((x) => { const m = ACCOUNT.exec(String(x || '')); return m ? m[1] : null }).filter(Boolean))].slice(0, 50)
|
|
342
|
-
const [owner, name] = String(b.repo || '').split('/')
|
|
343
|
-
if (!members.length || !PART.test(owner || '') || !PART.test(name || '')) throw new HttpError(400, 'give the session\'s people (person:<id>) and the repository (owner/name)')
|
|
344
|
-
// `room`: the session asking, for its workspace's and org's connections and access mode; `actingFor`: who the token is for.
|
|
345
|
-
const room = typeof b.room === 'string' && ROOM.test(b.room) ? b.room : ''
|
|
346
|
-
const actingFor = typeof b.actingFor === 'string' && ACTOR.test(b.actingFor) ? b.actingFor : ''
|
|
347
|
-
const cover = await coverFor({ room, accounts: members, actingFor, owner, name })
|
|
348
|
-
if (cover.refused) return cover.refused
|
|
349
|
-
const accounts = cover.ids
|
|
350
|
-
const linked = []
|
|
351
|
-
for (const id of accounts) { const l = await store.githubLink(id); if (l) linked.push({ id, ...l }) }
|
|
352
|
-
if (!linked.length) return { state: 'not-connected', ...(cover.require ? { require: true, actingFor } : {}) }
|
|
353
|
-
// `fresh`: a token of its own for one agent (minted anew, not kept): it can be revoked on its own.
|
|
354
|
-
const fresh = b.fresh === true
|
|
355
|
-
const key = (id) => `${id}\0${owner}/${name}\0${access}`.toLowerCase()
|
|
356
|
-
if (!fresh) for (const l of linked) { const hit = cache.get(key(l.id)); if (hit && hit.expiresAt - now() > 5 * 60 * 1000) return { state: 'ok', ...hit } }
|
|
357
|
-
try {
|
|
358
|
-
const inst = await app.installation(owner, name)
|
|
359
|
-
if (!inst) return { state: 'not-installed', login: linked[0].login, installUrl: `https://github.com/apps/${cfg.slug}/installations/new` }
|
|
360
|
-
// One token for the role checks (read is enough to ask), then one with what was asked for.
|
|
361
|
-
const probe = await app.repoToken(inst, name, { access: 'read' })
|
|
362
|
-
let first = null
|
|
363
|
-
for (const l of linked) {
|
|
364
|
-
const role = await app.role(probe.token, owner, name, l.login)
|
|
365
|
-
const ok = access === 'read' ? READ_ROLES.includes(role) : WRITE_ROLES.includes(role)
|
|
366
|
-
if (!first) first = { login: l.login, role }
|
|
367
|
-
if (!ok) continue
|
|
368
|
-
const t = access === 'read' && !fresh ? probe : await app.repoToken(inst, name, { access })
|
|
369
|
-
const out = { token: t.token, expiresAt: t.expiresAt, login: l.login }
|
|
370
|
-
if (!fresh) cache.set(key(l.id), out)
|
|
371
|
-
return { state: 'ok', ...out }
|
|
372
|
-
}
|
|
373
|
-
return { state: 'no-access', login: first.login, role: first.role }
|
|
374
|
-
} catch (err) {
|
|
375
|
-
if (err instanceof GitHubAppError) { log(`github token for ${owner}/${name}: ${err.message}`); return { state: 'error', error: err.message } }
|
|
376
|
-
throw err
|
|
377
|
-
}
|
|
378
|
-
}]
|
|
379
|
-
]
|
|
380
|
-
}
|
package/src/branches.js
DELETED
|
@@ -1,194 +0,0 @@
|
|
|
1
|
-
// The session's branches: which branch each member's folder is on, how it
|
|
2
|
-
// stands against its upstream, and every branch and worktree of the
|
|
3
|
-
// repository with who last worked on it. Each folder tells the room about its
|
|
4
|
-
// own git (Session.gitSummary, in presence); this folds those into one list.
|
|
5
|
-
// Pure: Session.status() and the hosted relay both call it.
|
|
6
|
-
|
|
7
|
-
import { RELAY_NAME, isRelay } from './ui/chat.js'
|
|
8
|
-
|
|
9
|
-
// Who the relay is in chat, the activity log, the chronology and the branch list: what it posts
|
|
10
|
-
// itself, the commits it brings in for a branch no folder is online on (relay-upstream.js), and
|
|
11
|
-
// the questions it answers (relay-ask.js).
|
|
12
|
-
export const RELAY_BY = RELAY_NAME
|
|
13
|
-
|
|
14
|
-
export { isRelay }
|
|
15
|
-
|
|
16
|
-
const str = (v, n) => typeof v === 'string' ? v.slice(0, n) : null
|
|
17
|
-
const num = (v) => Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0
|
|
18
|
-
|
|
19
|
-
/** A member's git summary as it came over presence (anyone's to write), trimmed to its shape. */
|
|
20
|
-
export function cleanGit (g) {
|
|
21
|
-
if (!g || typeof g !== 'object') return null
|
|
22
|
-
const u = g.upstream && typeof g.upstream === 'object' ? g.upstream : null
|
|
23
|
-
const r = g.repo && typeof g.repo === 'object' ? g.repo : null
|
|
24
|
-
return {
|
|
25
|
-
branch: str(g.branch, 200),
|
|
26
|
-
key: str(g.key, 200),
|
|
27
|
-
on: str(g.on, 200),
|
|
28
|
-
held: str(g.held, 20),
|
|
29
|
-
upstream: u ? { name: str(u.name, 200), url: str(u.url, 500), behind: num(u.behind), ahead: num(u.ahead), diverged: !!u.diverged, conflicts: num(u.conflicts), waiting: str(u.waiting, 300), mergedBy: str(u.mergedBy, 120), clashTask: typeof u.clashTask === 'string' && /^[0-9a-f]{16}$/.test(u.clashTask) ? u.clashTask : null, ...(u.fetchOk === false ? { fetchOk: false, fetchError: str(u.fetchError, 200) || 'git fetch failed' } : {}) } : null,
|
|
30
|
-
repo: r ? {
|
|
31
|
-
worktrees: (Array.isArray(r.worktrees) ? r.worktrees : []).slice(0, 50).map((w) => ({ name: str(w && w.name, 200), branch: str(w && w.branch, 200) })),
|
|
32
|
-
branches: (Array.isArray(r.branches) ? r.branches : []).slice(0, 30).map((b) => ({
|
|
33
|
-
name: str(b && b.name, 200), upstream: str(b && b.upstream, 200), ahead: num(b && b.ahead), behind: num(b && b.behind),
|
|
34
|
-
author: str(b && b.author, 100), ts: num(b && b.ts), subject: str(b && b.subject, 200)
|
|
35
|
-
})).filter((b) => b.name)
|
|
36
|
-
} : null
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* One entry per branch: { name, folders: [{ name, held }] (members whose folder is on it),
|
|
42
|
-
* ais: [names] (AI sessions named after it), worktrees: [names], hosted: [names] (hosted agents
|
|
43
|
-
* working on it, from the room's branch list), upstream: { name, url,
|
|
44
|
-
* behind, ahead, diverged, conflicts, waiting } | null, last: { author, ts, subject } | null,
|
|
45
|
-
* session: true when the branch has a live document in this session (a copy, whether or not
|
|
46
|
-
* anyone is on it right now), default: true for the room's default branch, full: true when its
|
|
47
|
-
* document is over the session's size limit (it takes no new changes), relay: what the relay
|
|
48
|
-
* brought in itself while no folder was on it, and when it last looked (relayLine) | null }.
|
|
49
|
-
* Branches someone is on come first, then the rest by last commit. `members`: [{ name, git, persona? }].
|
|
50
|
-
* `sessionBranches`: the room's own branch list (Session.branchList / the relay's), [{ key, default, full }].
|
|
51
|
-
*/
|
|
52
|
-
export function branchBoard (members, sessionBranches = []) {
|
|
53
|
-
const byName = new Map()
|
|
54
|
-
const entry = (name) => {
|
|
55
|
-
if (!byName.has(name)) byName.set(name, { name, folders: [], ais: [], worktrees: [], hosted: [], upstream: null, last: null, session: false, default: false, full: false, relay: null, onGitHub: false, merged: null })
|
|
56
|
-
return byName.get(name)
|
|
57
|
-
}
|
|
58
|
-
for (const m of members) {
|
|
59
|
-
const g = m.git
|
|
60
|
-
if (!g) continue
|
|
61
|
-
if (g.branch || g.key) {
|
|
62
|
-
const e = entry(g.on || g.key || g.branch)
|
|
63
|
-
e.folders.push({ name: m.name, held: g.held === 'switching' ? null : g.held, upstream: g.upstream })
|
|
64
|
-
// The folder that sees the most: one whose fetch works over one whose doesn't, then the least behind.
|
|
65
|
-
const better = (a, b) => !b || ((a.fetchOk === false) !== (b.fetchOk === false) ? b.fetchOk === false : a.behind < b.behind)
|
|
66
|
-
if (g.upstream && better(g.upstream, e.upstream)) e.upstream = g.upstream
|
|
67
|
-
}
|
|
68
|
-
if (!g.repo) continue
|
|
69
|
-
for (const b of g.repo.branches) {
|
|
70
|
-
const e = entry(b.name)
|
|
71
|
-
if (!e.last || b.ts > e.last.ts) e.last = { author: b.author, ts: b.ts, subject: b.subject }
|
|
72
|
-
if (!e.upstream && b.upstream) e.upstream = { name: b.upstream, url: null, behind: b.behind, ahead: b.ahead, diverged: b.ahead > 0 && b.behind > 0, conflicts: 0, waiting: null }
|
|
73
|
-
}
|
|
74
|
-
for (const w of g.repo.worktrees) if (w.branch && w.name !== '.' && !entry(w.branch).worktrees.includes(w.name)) entry(w.branch).worktrees.push(w.name)
|
|
75
|
-
}
|
|
76
|
-
// An AI session is named after its work, its git branch when it has one (persona.js).
|
|
77
|
-
for (const m of members) {
|
|
78
|
-
if (!m.persona) continue
|
|
79
|
-
const label = m.name.includes(' · ') ? m.name.slice(m.name.indexOf(' · ') + 3) : null
|
|
80
|
-
if (label && byName.has(label)) byName.get(label).ais.push(m.name)
|
|
81
|
-
}
|
|
82
|
-
// Every branch with a live copy in the session, whether or not anyone is on it right now
|
|
83
|
-
// (it still appears here), and which one is the room's default.
|
|
84
|
-
for (const b of (Array.isArray(sessionBranches) ? sessionBranches : [])) {
|
|
85
|
-
if (!b || typeof b.key !== 'string') continue
|
|
86
|
-
const e = entry(b.key)
|
|
87
|
-
if (b.onGitHub) { e.onGitHub = true; continue }
|
|
88
|
-
e.session = true
|
|
89
|
-
if (b.merged) e.merged = b.merged
|
|
90
|
-
if (b.default) e.default = true
|
|
91
|
-
if (b.full) e.full = true
|
|
92
|
-
if (b.relay && typeof b.relay === 'object') e.relay = b.relay
|
|
93
|
-
for (const n of (Array.isArray(b.hosted) ? b.hosted : [])) if (!e.hosted.includes(n)) e.hosted.push(n)
|
|
94
|
-
}
|
|
95
|
-
const active = (e) => e.folders.length + e.ais.length + e.worktrees.length + e.hosted.length
|
|
96
|
-
return [...byName.values()].sort((a, b) => (active(b) > 0) - (active(a) > 0) || (b.last?.ts || 0) - (a.last?.ts || 0) || (a.name < b.name ? -1 : 1))
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
const ago = (ts, now) => {
|
|
100
|
-
const s = Math.max(0, Math.round((now - ts) / 1000))
|
|
101
|
-
if (s < 90) return 'just now'
|
|
102
|
-
if (s < 5400) return `${Math.round(s / 60)}m ago`
|
|
103
|
-
if (s < 129600) return `${Math.round(s / 3600)}h ago`
|
|
104
|
-
return `${Math.round(s / 86400)}d ago`
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/** One line on how a branch stands against its upstream, or ''. */
|
|
108
|
-
export function upstreamLine (u) {
|
|
109
|
-
if (!u || !u.name) return ''
|
|
110
|
-
// A fetch that failed: what git last knew is stale, so never "up to date".
|
|
111
|
-
if (u.fetchOk === false) return `can't fetch ${u.name}: ${u.fetchError || 'git fetch failed'}${u.behind ? ` (${u.behind} behind at the last fetch that worked)` : ''}`
|
|
112
|
-
// A clash is handed to one AI as a task (clash.js): who, when it is.
|
|
113
|
-
const by = u.mergedBy ? `; being merged by ${u.mergedBy}${u.clashTask ? ` (task ${u.clashTask})` : ''}` : ''
|
|
114
|
-
if (u.diverged) return `diverged from ${u.name} (${u.ahead} ahead, ${u.behind} behind)${by}`
|
|
115
|
-
const n = Array.isArray(u.conflicts) ? u.conflicts.length : u.conflicts
|
|
116
|
-
if (n) return `${u.behind} behind ${u.name}; ${n} file${n === 1 ? '' : 's'} clash with the session's work${by}`
|
|
117
|
-
if (u.waiting) return `${u.behind} behind ${u.name}; waiting: ${u.waiting}`
|
|
118
|
-
if (u.behind) return `${u.behind} behind ${u.name}`
|
|
119
|
-
if (u.ahead) return `${u.ahead} ahead of ${u.name}`
|
|
120
|
-
return `up to date with ${u.name}`
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
/**
|
|
124
|
-
* One line on what the relay does for a branch no folder is online on: brought in by the relay
|
|
125
|
-
* (when, how many commits), a clash it handed out, why it can't, and when it last looked; or ''.
|
|
126
|
-
*/
|
|
127
|
-
export function relayLine (r, now = Date.now()) {
|
|
128
|
-
if (!r || !(r.checkedAt || (r.brought && r.brought.at))) return ''
|
|
129
|
-
const up = r.upstream || 'its upstream'
|
|
130
|
-
const bits = []
|
|
131
|
-
if (r.brought && r.brought.at) bits.push(`brought in by the relay ${ago(r.brought.at, now)} (${r.brought.count} commit${r.brought.count === 1 ? '' : 's'} from ${up}, ${r.brought.files} file${r.brought.files === 1 ? '' : 's'})`)
|
|
132
|
-
if (r.clashTask) bits.push(`the relay handed a clash with ${up} to task ${r.clashTask}`)
|
|
133
|
-
if (r.problem) bits.push(r.problem)
|
|
134
|
-
if (r.checkedAt) bits.push(`the relay last checked ${up} ${ago(r.checkedAt, now)}`)
|
|
135
|
-
return bits.join('; ')
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
/** The board as markdown for an AI (quilt_status, quilt_branches). `mine`: the caller's own branch, marked "(yours)". */
|
|
139
|
-
export function branchesMarkdown (board, { now = Date.now(), limit = 12, mine = null } = {}) {
|
|
140
|
-
if (!board.length) return '_No git branches: the folders in this session are not git repositories._'
|
|
141
|
-
const out = []
|
|
142
|
-
for (const b of board.slice(0, limit)) {
|
|
143
|
-
const who = [
|
|
144
|
-
...b.folders.map((f) => `${f.name}'s folder${f.held ? ` (${f.held})` : ''}${f.upstream && (f.upstream.conflicts || f.upstream.diverged || f.upstream.fetchOk === false) ? ` (${upstreamLine(f.upstream)})` : ''}`),
|
|
145
|
-
...b.ais.map((n) => `AI session ${n}`),
|
|
146
|
-
...b.hosted.map((n) => `hosted agent ${n}`),
|
|
147
|
-
...b.worktrees.map((w) => `worktree \`${w}\``)
|
|
148
|
-
]
|
|
149
|
-
const line = upstreamLine(b.upstream)
|
|
150
|
-
const bits = [
|
|
151
|
-
b.default ? 'default' : '',
|
|
152
|
-
b.session ? 'in the session' : b.onGitHub ? 'on GitHub, not in the session yet (quilt_git_branch with create: true opens it)' : '',
|
|
153
|
-
b.merged ? `merged into ${b.merged.into}${b.merged.number ? ` (pull request #${b.merged.number})` : ''}` : '',
|
|
154
|
-
who.length ? `on it: ${who.join(', ')}` : '',
|
|
155
|
-
who.some((w) => w.includes(`(${line})`)) ? '' : line,
|
|
156
|
-
relayLine(b.relay, now),
|
|
157
|
-
b.last ? `last commit ${ago(b.last.ts, now)} by ${b.last.author}: ${b.last.subject}` : ''
|
|
158
|
-
].filter(Boolean)
|
|
159
|
-
out.push(`- \`${b.name}\`${b.name === mine ? ' (yours)' : ''}${bits.length ? ` · ${bits.join(' · ')}` : ''}`)
|
|
160
|
-
}
|
|
161
|
-
if (board.length > limit) out.push(`- …and ${board.length - limit} more`)
|
|
162
|
-
return out.join('\n')
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/** What the relay said when asked to look at GitHub now (Room.syncUpstreamNow), for an AI; '' when it wasn't asked. */
|
|
166
|
-
export function describeRelaySync (r, branch = '') {
|
|
167
|
-
if (!r) return ''
|
|
168
|
-
if (r.error) return `The relay couldn't be asked to look at GitHub for \`${branch}\` (${r.error}).`
|
|
169
|
-
return r.said || ''
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/** What quilt_sync_branch did, for the AI that asked. */
|
|
173
|
-
export function describeBranchSync (r) {
|
|
174
|
-
if (!r || !r.git) {
|
|
175
|
-
const relay = r && r.relay && !r.relay.error && r.relay.state !== 'unknown-repo' ? describeRelaySync(r.relay) : ''
|
|
176
|
-
return `This folder is not a git repository, so it can't bring commits in itself: clone the repository into this folder (\`git clone <url> .\`, with credentials that work without a prompt) and join again from there.${relay ? `\n\nMeanwhile the relay brings commits in for this branch from GitHub: ${relay}` : ' Until then, the relay brings commits in for this branch from GitHub once a member\'s folder on it has told it which repository the branch follows.'}`
|
|
177
|
-
}
|
|
178
|
-
if (!r.branch) return 'This folder is not on a branch (detached HEAD): check out a branch first.'
|
|
179
|
-
if (r.busy) return `Not now: ${r.busy === 'switching' ? 'this folder is moving to the branch you checked out' : r.busy === 'busy' || r.busy === 'settling' ? 'git is at work in this folder' : r.busy}. Quilt looks again by itself in a minute.`
|
|
180
|
-
const u = r.upstream
|
|
181
|
-
if (!u || !u.name) return `\`${r.branch}\` has no upstream (git branch --set-upstream-to sets one), so there is nothing to bring in.`
|
|
182
|
-
if (u.fetchOk === false) {
|
|
183
|
-
const relay = describeRelaySync(r.relay, r.branch)
|
|
184
|
-
return `Couldn't fetch ${u.name}: ${u.fetchError || 'git fetch failed'}. Nothing new could be looked for through this folder, so \`${r.branch}\` may be behind ${u.name}. Give git in this folder credentials that work without a prompt (a credential helper, an SSH key, or a token in the remote's URL) and call quilt_sync_branch again.${relay ? `\n\nThe relay brings commits in for \`${r.branch}\` from GitHub while no folder on it can: ${relay}` : ''}`
|
|
185
|
-
}
|
|
186
|
-
if (r.moved) {
|
|
187
|
-
const b = u.brought
|
|
188
|
-
return `Brought ${b && b.count ? `${b.count} commit${b.count === 1 ? '' : 's'}` : 'the new commits'} from ${u.name} into the session (${b ? b.files : 0} file${b && b.files === 1 ? '' : 's'}), merged with its uncommitted work. \`${r.branch}\` is up to date.`
|
|
189
|
-
}
|
|
190
|
-
if (u.conflicts && u.conflicts.length) {
|
|
191
|
-
return `Nothing brought in: ${u.behind} commit${u.behind === 1 ? '' : 's'} on ${u.name} clash with the session's uncommitted work in:\n${u.conflicts.map((c) => `- ${c.path}: ${c.why}`).join('\n')}\n${u.mergedBy && !u.clashMine ? `${u.mergedBy} is merging them (task ${u.clashTask}): leave those files to them.` : `Run git pull in this folder and resolve those; the session takes in the result.${u.clashTask ? ` This merge is yours: task ${u.clashTask} on the board.` : ''}`}`
|
|
192
|
-
}
|
|
193
|
-
return `\`${r.branch}\`: ${upstreamLine(u)}.${u.diverged ? ' Quilt never merges git history: pull or rebase it yourself, and the session takes in whatever that changes.' : ''}`
|
|
194
|
-
}
|