@veda-hq/niyam 0.6.16 → 0.6.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +200 -39
- package/dist/agent.js +4 -0
- package/dist/as-agent.js +26 -18
- package/dist/board.js +3 -3
- package/dist/brief.js +370 -0
- package/dist/cloud.js +28 -11
- package/dist/cubic-dismiss.js +284 -0
- package/dist/doctor.js +3 -6
- package/dist/handoff.js +527 -0
- package/dist/issue-types.js +2 -2
- package/dist/keep-going.js +384 -0
- package/dist/onboard.js +38 -16
- package/dist/pr-autocreate.js +866 -0
- package/dist/run.js +55 -5
- package/dist/session-start.js +2 -2
- package/dist/sys.js +44 -1
- package/dist/work.js +4 -0
- package/package.json +1 -1
|
@@ -0,0 +1,866 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { dirname, resolve } from 'node:path';
|
|
3
|
+
import { githubSlug, isNoToken, SETTINGS_PATH } from './agent.js';
|
|
4
|
+
import { agentEnv } from './as-agent.js';
|
|
5
|
+
import { GITHUB_API, GITHUB_HOST } from './host.js';
|
|
6
|
+
import { commands } from './shell.js';
|
|
7
|
+
import { sessionToken } from './work.js';
|
|
8
|
+
const DEFAULTS = {
|
|
9
|
+
base: 'main',
|
|
10
|
+
draft: false,
|
|
11
|
+
protected: ['main', 'master', 'develop', 'prod', 'production'],
|
|
12
|
+
skip: ['mergify/', 'gh-readonly-queue/'],
|
|
13
|
+
optOut: [],
|
|
14
|
+
describe: '`gh pr edit --body-file`',
|
|
15
|
+
};
|
|
16
|
+
const where = `${SETTINGS_PATH} "prAutocreate"`;
|
|
17
|
+
const BRANCH = /^(?!\/)(?!.*\/\/)(?!.*\.\.)[\w.\/+-]+$/;
|
|
18
|
+
const ENV_NAME = /^[A-Z_][A-Z0-9_]*$/;
|
|
19
|
+
function strings(value, name, test) {
|
|
20
|
+
if (!Array.isArray(value) || !value.every((item) => typeof item === 'string' && test(item)))
|
|
21
|
+
throw new Error(`${where}.${name} must be a list of ${name === 'optOut' ? 'variable names' : 'branch names'}`);
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
function line(value, name) {
|
|
25
|
+
if (value === undefined)
|
|
26
|
+
return undefined;
|
|
27
|
+
if (typeof value !== 'string' || !value.trim() || /[\r\n]/.test(value))
|
|
28
|
+
throw new Error(`${where}.${name} must be one line`);
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
/** The settings, from the parsed settings file; throws naming the first bad key. */
|
|
32
|
+
export function autocreateSettings(raw) {
|
|
33
|
+
const value = typeof raw === 'object' && raw !== null ? raw.prAutocreate : undefined;
|
|
34
|
+
if (value === undefined)
|
|
35
|
+
return { ...DEFAULTS };
|
|
36
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
37
|
+
throw new Error(`${where} must be an object`);
|
|
38
|
+
const { base = DEFAULTS.base, draft = DEFAULTS.draft, protected: guarded = DEFAULTS.protected, skip = DEFAULTS.skip, optOut = DEFAULTS.optOut, describe, retired, footer, ...rest } = value;
|
|
39
|
+
const extra = Object.keys(rest)[0];
|
|
40
|
+
if (extra !== undefined)
|
|
41
|
+
throw new Error(`${where} has an unknown key "${extra}"; it takes "base", "draft", "protected", "skip", "optOut", "describe", "retired" and "footer"`);
|
|
42
|
+
if (typeof base !== 'string' || !BRANCH.test(base))
|
|
43
|
+
throw new Error(`${where}.base must be a branch name`);
|
|
44
|
+
if (typeof draft !== 'boolean')
|
|
45
|
+
throw new Error(`${where}.draft must be true or false`);
|
|
46
|
+
const settings = {
|
|
47
|
+
base,
|
|
48
|
+
draft,
|
|
49
|
+
protected: strings(guarded, 'protected', (item) => BRANCH.test(item)),
|
|
50
|
+
skip: strings(skip, 'skip', (item) => item.length > 0 && BRANCH.test(item)),
|
|
51
|
+
optOut: strings(optOut, 'optOut', (item) => ENV_NAME.test(item)),
|
|
52
|
+
describe: line(describe, 'describe') ?? DEFAULTS.describe,
|
|
53
|
+
};
|
|
54
|
+
const page = line(retired, 'retired');
|
|
55
|
+
if (page !== undefined && !/^https:\/\/\S+$/.test(page))
|
|
56
|
+
throw new Error(`${where}.retired must be an https link`);
|
|
57
|
+
const last = line(footer, 'footer');
|
|
58
|
+
return { ...settings, ...(page === undefined ? {} : { retired: page }), ...(last === undefined ? {} : { footer: last }) };
|
|
59
|
+
}
|
|
60
|
+
/** The settings in the repository at `root`; the defaults where it has no settings file. */
|
|
61
|
+
export function settingsAt(sys, root) {
|
|
62
|
+
const path = `${root}/${SETTINGS_PATH}`;
|
|
63
|
+
if (!sys.exists(path))
|
|
64
|
+
return { ...DEFAULTS };
|
|
65
|
+
let raw;
|
|
66
|
+
try {
|
|
67
|
+
raw = JSON.parse(sys.read(path));
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
throw new Error(`${SETTINGS_PATH} cannot be read: ${error instanceof Error ? error.message : String(error)}`);
|
|
71
|
+
}
|
|
72
|
+
return autocreateSettings(raw);
|
|
73
|
+
}
|
|
74
|
+
/** The variable that turns automatic pull requests off for one push, whatever the client. */
|
|
75
|
+
export const OPT_OUT_VAR = 'NIYAM_PR_AUTOCREATE';
|
|
76
|
+
export const REMOTE = 'origin';
|
|
77
|
+
export const STATE_DIR = '.tmp/pr-autocreate';
|
|
78
|
+
export const MARKER = '<!-- pr-autocreate: placeholder body -->';
|
|
79
|
+
/** How many pushes a branch's opt-out record keeps. */
|
|
80
|
+
export const OPTOUT_KEPT = 50;
|
|
81
|
+
const OPTOUT_LINE = /^([0-9a-f]{40}|[0-9a-f]{64}) ([01])$/;
|
|
82
|
+
const ZERO_SHA = /^0+$/;
|
|
83
|
+
const LOCK_WAIT_MS = 90_000;
|
|
84
|
+
const LOCK_STALE_MS = 180_000;
|
|
85
|
+
/** Whether a push of `name` can get a pull request. */
|
|
86
|
+
export function eligible(settings, name) {
|
|
87
|
+
return !!name && name !== settings.base && !settings.protected.includes(name) && !settings.skip.some((prefix) => name.startsWith(prefix));
|
|
88
|
+
}
|
|
89
|
+
/** Whether this push said no automatic pull request. */
|
|
90
|
+
export function optedOutNow(sys, settings) {
|
|
91
|
+
return [OPT_OUT_VAR, ...settings.optOut].some((name) => sys.env[name] === '0');
|
|
92
|
+
}
|
|
93
|
+
export function stateDir(root) {
|
|
94
|
+
return `${root}/${STATE_DIR}`;
|
|
95
|
+
}
|
|
96
|
+
/** A branch's record: a readable prefix for people, a digest that keeps `a/b` and `a_b` apart. */
|
|
97
|
+
export function statePath(root, branch) {
|
|
98
|
+
const readable = branch.replace(/[^A-Za-z0-9._-]/g, '_');
|
|
99
|
+
const digest = createHash('sha256').update(branch, 'utf8').digest('hex').slice(0, 12);
|
|
100
|
+
return `${stateDir(root)}/${readable}-${digest}.json`;
|
|
101
|
+
}
|
|
102
|
+
export function optoutPath(root, branch) {
|
|
103
|
+
return statePath(root, branch).replace(/\.json$/, '.optout');
|
|
104
|
+
}
|
|
105
|
+
function loadState(sys, root, branch) {
|
|
106
|
+
try {
|
|
107
|
+
const value = JSON.parse(sys.read(statePath(root, branch)));
|
|
108
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {};
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return {};
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function saveState(sys, root, state) {
|
|
115
|
+
sys.mkdir(stateDir(root));
|
|
116
|
+
sys.write(statePath(root, state.branch), JSON.stringify(state));
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The opt-out record's (sha, flag) pairs, oldest first: none without a
|
|
120
|
+
* record, undefined when it cannot be read or is not what recordOptout
|
|
121
|
+
* writes (at least one line, each ending in a newline).
|
|
122
|
+
*/
|
|
123
|
+
export function optoutLines(sys, root, branch) {
|
|
124
|
+
const path = optoutPath(root, branch);
|
|
125
|
+
if (!sys.exists(path))
|
|
126
|
+
return [];
|
|
127
|
+
let text;
|
|
128
|
+
try {
|
|
129
|
+
text = sys.read(path);
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
if (!text.endsWith('\n'))
|
|
135
|
+
return undefined;
|
|
136
|
+
const pairs = [];
|
|
137
|
+
for (const each of text.slice(0, -1).split('\n')) {
|
|
138
|
+
const match = OPTOUT_LINE.exec(each);
|
|
139
|
+
if (!match)
|
|
140
|
+
return undefined;
|
|
141
|
+
pairs.push([match[1], match[2]]);
|
|
142
|
+
}
|
|
143
|
+
return pairs;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Did the push that sent `sha` opt out? Its own line decides, not the
|
|
147
|
+
* branch's last push: pre-push writes before git sends the refs, so a push
|
|
148
|
+
* that then fails must not change what a landed commit means. A record that
|
|
149
|
+
* cannot be read fails closed, and so does a full one without `sha`, whose
|
|
150
|
+
* line the trim may have dropped.
|
|
151
|
+
*/
|
|
152
|
+
export function optedOut(sys, root, branch, sha) {
|
|
153
|
+
const pairs = optoutLines(sys, root, branch);
|
|
154
|
+
if (pairs === undefined)
|
|
155
|
+
return true;
|
|
156
|
+
const flags = pairs.filter(([lineSha]) => lineSha === sha).map(([, flag]) => flag);
|
|
157
|
+
if (flags.length === 0)
|
|
158
|
+
return pairs.length >= OPTOUT_KEPT;
|
|
159
|
+
return flags[flags.length - 1] === '1';
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* How long an opted-out branch's "no PR" stands before GitHub is asked again,
|
|
163
|
+
* so a turn end does not list pull requests every time.
|
|
164
|
+
*/
|
|
165
|
+
function recheckSeconds(sys) {
|
|
166
|
+
const seconds = Number(sys.env.NIYAM_PR_OPTOUT_RECHECK ?? '60');
|
|
167
|
+
return Number.isFinite(seconds) && seconds >= 0 && sys.env.NIYAM_PR_OPTOUT_RECHECK?.trim() !== '' ? seconds : 60;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* One pull-request decision at a time per branch: the watcher and a session's
|
|
171
|
+
* hook can reach the same push. A lock older than three minutes is abandoned.
|
|
172
|
+
*/
|
|
173
|
+
export async function withLock(sys, root, branch, body) {
|
|
174
|
+
sys.mkdir(stateDir(root));
|
|
175
|
+
const path = `${statePath(root, branch)}.lock`;
|
|
176
|
+
const deadline = sys.now().getTime() + LOCK_WAIT_MS;
|
|
177
|
+
while (!sys.claim(path)) {
|
|
178
|
+
const changed = sys.modified(path);
|
|
179
|
+
if (changed === undefined)
|
|
180
|
+
continue;
|
|
181
|
+
if (sys.now().getTime() - changed.getTime() > LOCK_STALE_MS) {
|
|
182
|
+
sys.remove(path);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
if (sys.now().getTime() > deadline)
|
|
186
|
+
throw new Error(`lock ${path} held too long`);
|
|
187
|
+
await sys.sleep(500);
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
return await body();
|
|
191
|
+
}
|
|
192
|
+
finally {
|
|
193
|
+
sys.remove(path);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Records whether the push sending `sha` opted out, one "<sha> 1|0" line per
|
|
198
|
+
* push, the last OPTOUT_KEPT kept. The trim never drops the last line for
|
|
199
|
+
* `remoteSha`, the commit the remote branch holds before this push: later
|
|
200
|
+
* pushes, failed ones included, cannot evict the choice that landed. Under the
|
|
201
|
+
* branch lock, and replaced whole. An unreadable record is started afresh.
|
|
202
|
+
*/
|
|
203
|
+
export async function recordOptout(sys, root, branch, sha, opted, remoteSha) {
|
|
204
|
+
await withLock(sys, root, branch, () => {
|
|
205
|
+
const pairs = [...(optoutLines(sys, root, branch) ?? []), [sha, opted ? '1' : '0']];
|
|
206
|
+
let kept = pairs.slice(-OPTOUT_KEPT);
|
|
207
|
+
const landed = pairs.filter(([lineSha]) => lineSha === remoteSha);
|
|
208
|
+
const last = landed[landed.length - 1];
|
|
209
|
+
if (last && !kept.includes(last))
|
|
210
|
+
kept = [last, ...pairs.slice(-(OPTOUT_KEPT - 1))];
|
|
211
|
+
sys.replace(optoutPath(root, branch), kept.map(([lineSha, flag]) => `${lineSha} ${flag}\n`).join(''));
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
function git(sys, root, args) {
|
|
215
|
+
const result = sys.exec('git', args, { cwd: root, timeoutMs: 30_000 });
|
|
216
|
+
return result.code === 0 ? result.stdout.trim() : undefined;
|
|
217
|
+
}
|
|
218
|
+
/** Whether the commit has nothing the base lacks; false when the base cannot be read. */
|
|
219
|
+
function nothingAhead(sys, root, base, sha) {
|
|
220
|
+
const ref = `refs/remotes/${REMOTE}/${base}`;
|
|
221
|
+
return git(sys, root, ['rev-parse', '--verify', '--quiet', ref]) !== undefined && git(sys, root, ['rev-list', '--count', `${ref}..${sha}`]) === '0';
|
|
222
|
+
}
|
|
223
|
+
/** How pull requests are listed, opened and read: GitHub's REST API, with the token it is given. */
|
|
224
|
+
export class Pulls {
|
|
225
|
+
sys;
|
|
226
|
+
slug;
|
|
227
|
+
/** The token, or how to find it at the first request: a record that answers needs none. */
|
|
228
|
+
token;
|
|
229
|
+
/** In a Claude cloud session: no Autofix to switch on, so a Stop is never held. */
|
|
230
|
+
cloud;
|
|
231
|
+
constructor(sys, slug, token, cloud) {
|
|
232
|
+
this.sys = sys;
|
|
233
|
+
this.slug = slug;
|
|
234
|
+
this.token = token;
|
|
235
|
+
this.cloud = cloud;
|
|
236
|
+
}
|
|
237
|
+
async call(method, route, body) {
|
|
238
|
+
if (typeof this.token === 'function') {
|
|
239
|
+
const found = this.token();
|
|
240
|
+
if (typeof found !== 'string')
|
|
241
|
+
return found.problem;
|
|
242
|
+
this.token = found;
|
|
243
|
+
}
|
|
244
|
+
try {
|
|
245
|
+
return await this.sys.http(`${GITHUB_API}/repos/${this.slug}/${route}`, { method, token: this.token, timeoutMs: method === 'POST' ? 60_000 : 30_000, ...(body === undefined ? {} : { body }) });
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
return error instanceof Error ? error.message : String(error);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/** A REST pull as a decision reads it, or undefined when a field it decides by is missing. */
|
|
252
|
+
static read(value) {
|
|
253
|
+
if (typeof value !== 'object' || value === null)
|
|
254
|
+
return undefined;
|
|
255
|
+
const pull = value;
|
|
256
|
+
if (!Number.isInteger(pull.number) || typeof pull.html_url !== 'string' || !pull.html_url || (pull.state !== 'open' && pull.state !== 'closed'))
|
|
257
|
+
return undefined;
|
|
258
|
+
return { number: pull.number, url: pull.html_url, state: pull.merged_at ? 'MERGED' : pull.state === 'open' ? 'OPEN' : 'CLOSED' };
|
|
259
|
+
}
|
|
260
|
+
/** The branch's pull requests, newest first; a string says why they could not be listed. */
|
|
261
|
+
async list(branch) {
|
|
262
|
+
const owner = this.slug.split('/')[0];
|
|
263
|
+
const got = await this.call('GET', `pulls?head=${encodeURIComponent(`${owner}:${branch}`)}&state=all&per_page=20`);
|
|
264
|
+
if (typeof got === 'string')
|
|
265
|
+
return got;
|
|
266
|
+
if (got.status !== 200)
|
|
267
|
+
return `GitHub answered ${got.status} listing pull requests`;
|
|
268
|
+
// Any unreadable part makes the whole list unreadable: a pull request
|
|
269
|
+
// missed here would be opened again, and a misread one kept as closed.
|
|
270
|
+
if (!Array.isArray(got.json))
|
|
271
|
+
return 'GitHub listed pull requests unreadably';
|
|
272
|
+
const pulls = [];
|
|
273
|
+
for (const item of got.json) {
|
|
274
|
+
const pull = Pulls.read(item);
|
|
275
|
+
if (!pull)
|
|
276
|
+
return 'GitHub listed pull requests unreadably';
|
|
277
|
+
const head = item.head?.ref;
|
|
278
|
+
if (head === branch)
|
|
279
|
+
pulls.push(pull);
|
|
280
|
+
}
|
|
281
|
+
return pulls;
|
|
282
|
+
}
|
|
283
|
+
/** Opens a pull request: it, or "none ahead" when the branch adds nothing, or why it could not. */
|
|
284
|
+
async create(branch, base, title, body, draft) {
|
|
285
|
+
const got = await this.call('POST', 'pulls', { head: branch, base, title, body, draft });
|
|
286
|
+
if (typeof got === 'string')
|
|
287
|
+
return got;
|
|
288
|
+
const pull = got.status === 201 ? Pulls.read(got.json) : undefined;
|
|
289
|
+
if (pull)
|
|
290
|
+
return pull;
|
|
291
|
+
const text = JSON.stringify(got.json ?? '');
|
|
292
|
+
if (got.status === 422 && /no commits between/i.test(text))
|
|
293
|
+
return { noneAhead: true };
|
|
294
|
+
return `GitHub answered ${got.status} opening a pull request`;
|
|
295
|
+
}
|
|
296
|
+
/** The pull request's body now; undefined when GitHub cannot say. */
|
|
297
|
+
async body(number) {
|
|
298
|
+
const got = await this.call('GET', `pulls/${number}`);
|
|
299
|
+
if (typeof got === 'string' || got.status !== 200)
|
|
300
|
+
return undefined;
|
|
301
|
+
const body = got.json?.body;
|
|
302
|
+
return typeof body === 'string' ? body : body === null ? '' : undefined;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/** The placeholder body: what the push sent, and how the session replaces it. */
|
|
306
|
+
export function placeholder(sys, root, settings, branch, sha) {
|
|
307
|
+
const ref = `refs/remotes/${REMOTE}/${settings.base}`;
|
|
308
|
+
const hasBase = git(sys, root, ['rev-parse', '--verify', '--quiet', ref]) !== undefined;
|
|
309
|
+
const log = git(sys, root, ['log', '--no-merges', '--reverse', '--format=%h %s', hasBase ? `${ref}..${sha}` : sha]) ?? '';
|
|
310
|
+
const commits = log.split('\n').filter((each) => each.includes(' ')).map((each) => {
|
|
311
|
+
const at = each.indexOf(' ');
|
|
312
|
+
return { short: each.slice(0, at), subject: each.slice(at + 1) };
|
|
313
|
+
});
|
|
314
|
+
const listed = commits.slice(0, 50).map(({ short, subject }) => `- ${subject} (\`${short}\`)`);
|
|
315
|
+
if (commits.length > 50)
|
|
316
|
+
listed.push(`- …and ${commits.length - 50} more`);
|
|
317
|
+
const body = [
|
|
318
|
+
MARKER,
|
|
319
|
+
`Opened automatically when \`${branch}\` was pushed. The pushing session replaces this body with the full description (${settings.describe}).`,
|
|
320
|
+
'',
|
|
321
|
+
'## Commits',
|
|
322
|
+
'',
|
|
323
|
+
...listed,
|
|
324
|
+
...(settings.footer ? ['', settings.footer] : []),
|
|
325
|
+
'',
|
|
326
|
+
].join('\n');
|
|
327
|
+
return { title: commits[0]?.subject ?? branch, body };
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* The branch's decision for the pushed `sha`: its record, or why GitHub could
|
|
331
|
+
* not be asked (to retry). GitHub is asked once per pushed commit; the record
|
|
332
|
+
* keeps the answer, which is also how a session learns of a pull request a
|
|
333
|
+
* terminal push opened. When the push that sent `sha` opted out, a branch
|
|
334
|
+
* with no pull request gets none, and that answer stands for
|
|
335
|
+
* NIYAM_PR_OPTOUT_RECHECK seconds only, so the session's own is found later.
|
|
336
|
+
*/
|
|
337
|
+
export async function ensurePr(sys, root, settings, branch, sha, pulls) {
|
|
338
|
+
return withLock(sys, root, branch, async () => {
|
|
339
|
+
const known = loadState(sys, root, branch);
|
|
340
|
+
if (known.remoteSha === sha) {
|
|
341
|
+
const checked = known.optedOutAt;
|
|
342
|
+
if (typeof checked !== 'number')
|
|
343
|
+
return known;
|
|
344
|
+
if (optedOut(sys, root, branch, sha) && sys.now().getTime() / 1000 - checked < recheckSeconds(sys))
|
|
345
|
+
return known;
|
|
346
|
+
}
|
|
347
|
+
const listed = await pulls.list(branch);
|
|
348
|
+
if (typeof listed === 'string')
|
|
349
|
+
return { problem: `could not list PRs for ${branch} (${listed}); will retry` };
|
|
350
|
+
const open = listed.find((pull) => pull.state === 'OPEN');
|
|
351
|
+
const merged = listed.find((pull) => pull.state === 'MERGED');
|
|
352
|
+
let pr = null;
|
|
353
|
+
let created = false;
|
|
354
|
+
const notes = [];
|
|
355
|
+
if (open)
|
|
356
|
+
pr = open;
|
|
357
|
+
else if (merged) {
|
|
358
|
+
notes.push(`Branch ${branch} already has MERGED PR #${merged.number}, so no new PR was opened: a merged PR retires its branch${settings.retired ? ` (${settings.retired})` : ''}.`);
|
|
359
|
+
}
|
|
360
|
+
else if (listed[0]) {
|
|
361
|
+
notes.push(`Branch ${branch}'s PR #${listed[0].number} was closed without merging, so no new PR was opened; reopening it is the user's call.`);
|
|
362
|
+
}
|
|
363
|
+
else if (optedOut(sys, root, branch, sha)) {
|
|
364
|
+
const state = { remoteSha: sha, branch, pr: null, created: false, notes: [], optedOutAt: sys.now().getTime() / 1000 };
|
|
365
|
+
saveState(sys, root, state);
|
|
366
|
+
return state;
|
|
367
|
+
}
|
|
368
|
+
else if (nothingAhead(sys, root, settings.base, sha)) {
|
|
369
|
+
notes.push(`Branch ${branch} has no commits ahead of ${settings.base}, so no PR was opened.`);
|
|
370
|
+
}
|
|
371
|
+
else {
|
|
372
|
+
const { title, body } = placeholder(sys, root, settings, branch, sha);
|
|
373
|
+
const made = await pulls.create(branch, settings.base, title, body, settings.draft);
|
|
374
|
+
if (typeof made === 'object' && 'noneAhead' in made) {
|
|
375
|
+
notes.push(`Branch ${branch} has no commits ahead of ${settings.base}, so no PR was opened.`);
|
|
376
|
+
}
|
|
377
|
+
else if (typeof made === 'string') {
|
|
378
|
+
// A creator running at the same time makes this one fail on the pull request it opened.
|
|
379
|
+
const again = await pulls.list(branch);
|
|
380
|
+
const found = typeof again === 'string' ? undefined : again.find((pull) => pull.state === 'OPEN');
|
|
381
|
+
if (!found)
|
|
382
|
+
return { problem: `could not create a PR for ${branch} (${made}); will retry` };
|
|
383
|
+
pr = found;
|
|
384
|
+
}
|
|
385
|
+
else {
|
|
386
|
+
pr = made;
|
|
387
|
+
created = true;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
const state = { remoteSha: sha, branch, pr, created, notes };
|
|
391
|
+
saveState(sys, root, state);
|
|
392
|
+
return state;
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
const VALUE_OPTS = new Set(['-o', '--push-option', '--receive-pack', '--exec']);
|
|
396
|
+
const UNRESOLVABLE_OPTS = new Set(['--all', '--mirror', '--tags', '--repo', '--prune', '--delete', '-d']);
|
|
397
|
+
/**
|
|
398
|
+
* The first `git push` of a Bash command, read as a shell reads it. Anything
|
|
399
|
+
* this cannot name exactly (several refspecs, another remote, --all,
|
|
400
|
+
* --git-dir, a word only the shell can expand) is unresolvable.
|
|
401
|
+
*/
|
|
402
|
+
export function pushTarget(command, cwd, home) {
|
|
403
|
+
let simples;
|
|
404
|
+
try {
|
|
405
|
+
simples = commands(command, () => undefined);
|
|
406
|
+
}
|
|
407
|
+
catch {
|
|
408
|
+
return { dir: cwd, resolvable: false };
|
|
409
|
+
}
|
|
410
|
+
for (const { words } of simples) {
|
|
411
|
+
const start = words.findIndex((word) => word.text === 'git');
|
|
412
|
+
if (start < 0)
|
|
413
|
+
continue;
|
|
414
|
+
let dir = cwd;
|
|
415
|
+
let at = start + 1;
|
|
416
|
+
let unresolvable = false;
|
|
417
|
+
while (at < words.length && (words[at]?.text ?? '').startsWith('-')) {
|
|
418
|
+
const option = words[at].text;
|
|
419
|
+
const next = words[at + 1];
|
|
420
|
+
if (option === '-C' && next) {
|
|
421
|
+
if (!next.known)
|
|
422
|
+
unresolvable = true;
|
|
423
|
+
dir = resolve(dir, next.text.replace(/^~(?=$|\/)/, home));
|
|
424
|
+
at += 2;
|
|
425
|
+
}
|
|
426
|
+
else if (option === '-c' && next)
|
|
427
|
+
at += 2;
|
|
428
|
+
else if (option.startsWith('--git-dir') || option.startsWith('--work-tree')) {
|
|
429
|
+
unresolvable = true;
|
|
430
|
+
at++;
|
|
431
|
+
}
|
|
432
|
+
else
|
|
433
|
+
at++;
|
|
434
|
+
}
|
|
435
|
+
if (words[at]?.text !== 'push')
|
|
436
|
+
continue;
|
|
437
|
+
if (unresolvable)
|
|
438
|
+
return { dir: cwd, resolvable: false };
|
|
439
|
+
const positionals = [];
|
|
440
|
+
for (let each = at + 1; each < words.length; each++) {
|
|
441
|
+
const word = words[each];
|
|
442
|
+
if (VALUE_OPTS.has(word.text)) {
|
|
443
|
+
each++;
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
if (UNRESOLVABLE_OPTS.has(word.text.split('=')[0]))
|
|
447
|
+
return { dir, resolvable: false };
|
|
448
|
+
if (!word.text.startsWith('-')) {
|
|
449
|
+
if (!word.known)
|
|
450
|
+
return { dir, resolvable: false };
|
|
451
|
+
positionals.push(word.text);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
if (positionals[0] !== undefined && positionals[0] !== REMOTE)
|
|
455
|
+
return { dir, resolvable: false };
|
|
456
|
+
const refspecs = positionals.slice(1);
|
|
457
|
+
if (refspecs.length === 0)
|
|
458
|
+
return { dir, resolvable: true };
|
|
459
|
+
if (refspecs.length > 1)
|
|
460
|
+
return { dir, resolvable: false };
|
|
461
|
+
const spec = refspecs[0].replace(/^\+/, '');
|
|
462
|
+
let destination = spec.includes(':') ? spec.slice(spec.indexOf(':') + 1) : spec;
|
|
463
|
+
if (destination === '' || destination === 'HEAD')
|
|
464
|
+
return { dir, resolvable: true };
|
|
465
|
+
if (destination.startsWith('refs/heads/'))
|
|
466
|
+
destination = destination.slice('refs/heads/'.length);
|
|
467
|
+
else if (destination.startsWith('refs/'))
|
|
468
|
+
return { dir, resolvable: false };
|
|
469
|
+
return { dir, branch: destination, resolvable: true };
|
|
470
|
+
}
|
|
471
|
+
return undefined;
|
|
472
|
+
}
|
|
473
|
+
/** The instruction a session in the desktop app gets: switch Autofix on for the pull request. */
|
|
474
|
+
export function reminder(pr, opened, created, cloud) {
|
|
475
|
+
if (cloud) {
|
|
476
|
+
return `PR #${pr.number} (${pr.url}) ${opened}\nThis cloud session has no Autofix: CI, conflicts and review comments reach no one until a session reads them (gh api; GraphQL is refused here).`;
|
|
477
|
+
}
|
|
478
|
+
// The tag claims the session opened the pull request, so one merely found
|
|
479
|
+
// on the branch gets it only when the session knows it ran that create.
|
|
480
|
+
const claim = created ? 'Write' : 'Only if this session itself ran the `gh pr create` that opened this PR (in a background command, say), write';
|
|
481
|
+
return (`PR #${pr.number} (${pr.url}) ${opened}\n` +
|
|
482
|
+
'Standing instruction from the user: Autofix must be ON for every PR a session pushes. Do this now, before anything else:\n' +
|
|
483
|
+
'1. If mcp__ccd_pr__get_status is not yet a callable tool, it may only be deferred: run ToolSearch with query "select:mcp__ccd_pr__get_status,mcp__ccd_pr__bind_pr,mcp__ccd_pr__set_monitor" to load its schema before concluding it is unavailable.\n' +
|
|
484
|
+
`2. ${claim} this line in your reply text, exactly: <pr-created>${pr.url}</pr-created>\n` +
|
|
485
|
+
'The app lets a session turn Autofix on only for a PR it is sure the session opened, and it learns that only from a FOREGROUND `gh pr create` result or this tag; a PR opened by this hook or inside a background command has neither. Never write the tag for a PR this session did not open.\n' +
|
|
486
|
+
`3. Call mcp__ccd_pr__get_status. If it reports no bound PR, call mcp__ccd_pr__bind_pr with url ${pr.url}.\n` +
|
|
487
|
+
`4. If auto_fix is not true, call mcp__ccd_pr__set_monitor with {"auto_fix": true, "address_comments": true, "url": "${pr.url}"}. If it says the app is not sure this session opened the PR, or has not read it yet, call get_status once more and retry set_monitor once.\n` +
|
|
488
|
+
"If ToolSearch cannot find mcp__ccd_pr__* at all (truly not the desktop app), or get_status/bind_pr/set_monitor still fails, tell the user in one line that Autofix could not be enabled and why, quoting the app's reason (the tag counts only within 15 minutes of the PR's creation, from the PR's own branch, and when the app's gh login authored it) — never fail silently and leave it off unreported.");
|
|
489
|
+
}
|
|
490
|
+
/** How the session replaces the placeholder body. */
|
|
491
|
+
function editHint(settings, pulls, number) {
|
|
492
|
+
return pulls.cloud ? `gh api -X PATCH repos/${pulls.slug}/pulls/${number} -F body=@FILE` : settings.describe;
|
|
493
|
+
}
|
|
494
|
+
/** The instruction for the record's open pull request, once per session and pull request; empty when there is nothing to say. */
|
|
495
|
+
async function autofixMessage(sys, root, settings, state, session, pulls) {
|
|
496
|
+
const pr = state.pr;
|
|
497
|
+
if (!pr || pr.state !== 'OPEN' || !pr.url)
|
|
498
|
+
return '';
|
|
499
|
+
const who = String(session ?? 'nosession').replace(/[^A-Za-z0-9._-]/g, '_');
|
|
500
|
+
const ack = `${stateDir(root)}/acks/${who}-${pr.number}`;
|
|
501
|
+
if (sys.exists(ack))
|
|
502
|
+
return '';
|
|
503
|
+
try {
|
|
504
|
+
sys.mkdir(dirname(ack));
|
|
505
|
+
sys.write(ack, '');
|
|
506
|
+
}
|
|
507
|
+
catch (error) {
|
|
508
|
+
return { problem: `could not record the Autofix ack (${error instanceof Error ? error.message : String(error)}); not instructing, to avoid a loop` };
|
|
509
|
+
}
|
|
510
|
+
let opened = `is open for branch ${state.branch}.`;
|
|
511
|
+
if (state.created) {
|
|
512
|
+
opened = `was opened automatically for branch ${state.branch} after the push landed.`;
|
|
513
|
+
const replace = `replace it with the real description (${editHint(settings, pulls, pr.number)}) before asking anyone to review it.`;
|
|
514
|
+
const body = await pulls.body(pr.number);
|
|
515
|
+
if (body === undefined)
|
|
516
|
+
opened += ` If its body is still the automatic placeholder, ${replace}`;
|
|
517
|
+
else if (body.includes(MARKER))
|
|
518
|
+
opened += ` Its body is still the automatic placeholder: ${replace}`;
|
|
519
|
+
}
|
|
520
|
+
return reminder(pr, opened, state.created, pulls.cloud);
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* The transport with the token GitHub is asked with: a session's hook acts
|
|
524
|
+
* as the session's agent, with every check `as-agent` makes, and never as
|
|
525
|
+
* anyone else; the watcher, which no session runs, as the push's own
|
|
526
|
+
* GH_TOKEN, or gh's signed-in account.
|
|
527
|
+
*/
|
|
528
|
+
export function pullsFor(sys, root, session) {
|
|
529
|
+
const slug = githubSlug(git(sys, root, ['config', '--get', `remote.${REMOTE}.url`]) ?? '');
|
|
530
|
+
if (!slug)
|
|
531
|
+
return { problem: `${REMOTE} is not a ${GITHUB_HOST} repository` };
|
|
532
|
+
const cloud = sys.env.CLAUDE_CODE_REMOTE === 'true';
|
|
533
|
+
return new Pulls(sys, slug, () => tokenFor(sys, root, session), cloud);
|
|
534
|
+
}
|
|
535
|
+
function tokenFor(sys, root, session) {
|
|
536
|
+
if (session !== undefined) {
|
|
537
|
+
const env = agentEnv(sys, session, root);
|
|
538
|
+
if ('problem' in env)
|
|
539
|
+
return { problem: `niyam could not act as the agent (${env.problem}); run \`niyam doctor\`` };
|
|
540
|
+
// agentEnv always sets it; a lock's placeholder is no token.
|
|
541
|
+
const token = env.env.GH_TOKEN;
|
|
542
|
+
return token && !isNoToken(token) ? token : { problem: 'niyam gave the agent no token; run `niyam doctor`' };
|
|
543
|
+
}
|
|
544
|
+
const token = sessionToken(sys);
|
|
545
|
+
if (token)
|
|
546
|
+
return token;
|
|
547
|
+
const read = sys.exec('gh', ['auth', 'token', '-h', GITHUB_HOST], { cwd: root, timeoutMs: 30_000 });
|
|
548
|
+
const found = read.code === 0 ? read.stdout.trim() : '';
|
|
549
|
+
return found && !isNoToken(found) ? found : { problem: 'no GitHub token: GH_TOKEN is unset and gh is signed in to no account' };
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Claude Code's PostToolUse(Bash) and Stop hook, its input on stdin. A
|
|
553
|
+
* foreground push that landed, or at Stop the branch's push, gets its pull
|
|
554
|
+
* request; the session is told once to switch Autofix on. Exit 2 only at
|
|
555
|
+
* Stop, for that instruction; everything else exits 0.
|
|
556
|
+
*/
|
|
557
|
+
export async function claudeHook(sys, io, stdin, pullsOf = pullsFor) {
|
|
558
|
+
const bail = (message) => {
|
|
559
|
+
io.err(`pr-autocreate: ${message}`);
|
|
560
|
+
return 0;
|
|
561
|
+
};
|
|
562
|
+
let data;
|
|
563
|
+
try {
|
|
564
|
+
data = JSON.parse(stdin || 'null');
|
|
565
|
+
}
|
|
566
|
+
catch {
|
|
567
|
+
return bail('hook input is not valid JSON; nothing done');
|
|
568
|
+
}
|
|
569
|
+
if (typeof data !== 'object' || data === null || Array.isArray(data))
|
|
570
|
+
return bail('hook input is not a JSON object; nothing done');
|
|
571
|
+
const input = data;
|
|
572
|
+
// The main session's Stop catches a subagent's push.
|
|
573
|
+
if (input.agent_id)
|
|
574
|
+
return 0;
|
|
575
|
+
const event = input.hook_event_name;
|
|
576
|
+
const cwd = typeof input.cwd === 'string' && input.cwd ? input.cwd : (sys.env.CLAUDE_PROJECT_DIR ?? '');
|
|
577
|
+
// A folder that is not there, or not in a repository, has nothing pushed: rev-parse below fails.
|
|
578
|
+
if (!cwd)
|
|
579
|
+
return 0;
|
|
580
|
+
let dir = cwd;
|
|
581
|
+
let named;
|
|
582
|
+
if (event === 'PostToolUse') {
|
|
583
|
+
if (input.tool_name !== 'Bash')
|
|
584
|
+
return 0;
|
|
585
|
+
const tool = typeof input.tool_input === 'object' && input.tool_input !== null ? input.tool_input : {};
|
|
586
|
+
const command = typeof tool.command === 'string' ? tool.command : '';
|
|
587
|
+
// A background push is still running; the Stop half catches it.
|
|
588
|
+
if (tool.run_in_background)
|
|
589
|
+
return 0;
|
|
590
|
+
const target = pushTarget(command, cwd, sys.home);
|
|
591
|
+
if (!target?.resolvable)
|
|
592
|
+
return 0;
|
|
593
|
+
dir = target.dir;
|
|
594
|
+
named = target.branch;
|
|
595
|
+
}
|
|
596
|
+
else if (event === 'Stop') {
|
|
597
|
+
if (input.stop_hook_active)
|
|
598
|
+
return 0;
|
|
599
|
+
}
|
|
600
|
+
else
|
|
601
|
+
return 0;
|
|
602
|
+
const root = git(sys, dir, ['rev-parse', '--show-toplevel']);
|
|
603
|
+
if (!root)
|
|
604
|
+
return 0;
|
|
605
|
+
let settings;
|
|
606
|
+
try {
|
|
607
|
+
settings = settingsAt(sys, root);
|
|
608
|
+
}
|
|
609
|
+
catch (error) {
|
|
610
|
+
return bail(`${error instanceof Error ? error.message : String(error)}; nothing done`);
|
|
611
|
+
}
|
|
612
|
+
let branch = named;
|
|
613
|
+
if (branch === undefined) {
|
|
614
|
+
const current = git(sys, root, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
615
|
+
if (!current)
|
|
616
|
+
return 0;
|
|
617
|
+
const upstream = git(sys, root, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
|
|
618
|
+
if (upstream && !upstream.startsWith(`${REMOTE}/`))
|
|
619
|
+
return 0;
|
|
620
|
+
branch = upstream ? upstream.slice(REMOTE.length + 1) : current;
|
|
621
|
+
}
|
|
622
|
+
if (!eligible(settings, branch))
|
|
623
|
+
return 0;
|
|
624
|
+
// The proof it landed: git moves the tracking ref only on a push that did.
|
|
625
|
+
const remoteSha = git(sys, root, ['rev-parse', '--verify', '--quiet', `refs/remotes/${REMOTE}/${branch}`]);
|
|
626
|
+
if (!remoteSha)
|
|
627
|
+
return 0;
|
|
628
|
+
if (sys.exec('git', ['merge-base', '--is-ancestor', remoteSha, 'HEAD'], { cwd: root }).code !== 0)
|
|
629
|
+
return 0;
|
|
630
|
+
if (nothingAhead(sys, root, settings.base, remoteSha))
|
|
631
|
+
return 0;
|
|
632
|
+
const session = typeof input.session_id === 'string' && input.session_id ? input.session_id : undefined;
|
|
633
|
+
const pulls = pullsOf(sys, root, session);
|
|
634
|
+
if ('problem' in pulls)
|
|
635
|
+
return bail(pulls.problem);
|
|
636
|
+
let state;
|
|
637
|
+
try {
|
|
638
|
+
state = await ensurePr(sys, root, settings, branch, remoteSha, pulls);
|
|
639
|
+
}
|
|
640
|
+
catch (error) {
|
|
641
|
+
return bail(`PR check failed for ${branch} (${error instanceof Error ? error.message : String(error)})`);
|
|
642
|
+
}
|
|
643
|
+
if ('problem' in state)
|
|
644
|
+
return bail(state.problem);
|
|
645
|
+
let message = await autofixMessage(sys, root, settings, state, session, pulls);
|
|
646
|
+
if (typeof message !== 'string')
|
|
647
|
+
return bail(message.problem);
|
|
648
|
+
if (!message && state.notes.length > 0 && event === 'PostToolUse') {
|
|
649
|
+
message = state.notes.join('\n');
|
|
650
|
+
try {
|
|
651
|
+
saveState(sys, root, { ...state, notes: [] });
|
|
652
|
+
}
|
|
653
|
+
catch {
|
|
654
|
+
// The note is said again next time; nothing worse.
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
if (!message)
|
|
658
|
+
return 0;
|
|
659
|
+
if (event === 'Stop' && pulls.cloud) {
|
|
660
|
+
io.out(JSON.stringify({ systemMessage: message }));
|
|
661
|
+
return 0;
|
|
662
|
+
}
|
|
663
|
+
if (event === 'Stop') {
|
|
664
|
+
io.err(message);
|
|
665
|
+
return 2;
|
|
666
|
+
}
|
|
667
|
+
io.out(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: message } }));
|
|
668
|
+
return 0;
|
|
669
|
+
}
|
|
670
|
+
// ------------------------------------------------------ spawn-watchers / watch
|
|
671
|
+
/** `--name value` pairs; throws on anything else. */
|
|
672
|
+
function flags(args, names) {
|
|
673
|
+
const found = new Map();
|
|
674
|
+
for (let at = 0; at < args.length; at++) {
|
|
675
|
+
const arg = args[at];
|
|
676
|
+
const eq = arg.startsWith('--') ? arg.indexOf('=') : -1;
|
|
677
|
+
const name = eq > 0 ? arg.slice(0, eq) : arg;
|
|
678
|
+
if (!names.includes(name))
|
|
679
|
+
throw new Error(`unexpected argument "${arg}"`);
|
|
680
|
+
const value = eq > 0 ? arg.slice(eq + 1) : args[++at];
|
|
681
|
+
if (value === undefined || (eq < 0 && value.startsWith('--')))
|
|
682
|
+
throw new Error(`${name} needs a value`);
|
|
683
|
+
if (found.has(name))
|
|
684
|
+
throw new Error(`${name} is given twice`);
|
|
685
|
+
found.set(name, value);
|
|
686
|
+
}
|
|
687
|
+
return found;
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* The pre-push hook's half, git's ref lines on stdin: records each pushed
|
|
691
|
+
* branch's opt-out before the refs are sent, then starts one detached watcher
|
|
692
|
+
* per branch. Exit 3 only when an opt-out cannot be recorded, so the push is
|
|
693
|
+
* refused rather than given a pull request at turn end; otherwise 0.
|
|
694
|
+
*/
|
|
695
|
+
export async function spawnWatchers(sys, io, args, stdin) {
|
|
696
|
+
let root;
|
|
697
|
+
let remote;
|
|
698
|
+
try {
|
|
699
|
+
const given = flags(args, ['--root', '--remote']);
|
|
700
|
+
const named = given.get('--root');
|
|
701
|
+
if (!named)
|
|
702
|
+
throw new Error('spawn-watchers needs --root <repository>');
|
|
703
|
+
root = named;
|
|
704
|
+
remote = given.get('--remote') ?? '';
|
|
705
|
+
}
|
|
706
|
+
catch (error) {
|
|
707
|
+
io.err(`pr-autocreate: ${error instanceof Error ? error.message : String(error)}; no PR watcher started`);
|
|
708
|
+
return 0;
|
|
709
|
+
}
|
|
710
|
+
if (sys.env.CI || remote !== REMOTE)
|
|
711
|
+
return 0;
|
|
712
|
+
let settings;
|
|
713
|
+
try {
|
|
714
|
+
settings = settingsAt(sys, root);
|
|
715
|
+
}
|
|
716
|
+
catch (error) {
|
|
717
|
+
io.err(`pr-autocreate: ${error instanceof Error ? error.message : String(error)}; no PR watcher started`);
|
|
718
|
+
return 0;
|
|
719
|
+
}
|
|
720
|
+
const opted = optedOutNow(sys, settings);
|
|
721
|
+
const names = [OPT_OUT_VAR, ...settings.optOut].join(' or ');
|
|
722
|
+
const started = [];
|
|
723
|
+
for (const each of stdin.split('\n')) {
|
|
724
|
+
const parts = each.trim().split(/\s+/);
|
|
725
|
+
if (parts.length !== 4)
|
|
726
|
+
continue;
|
|
727
|
+
const [, localSha, remoteRef, remoteSha] = parts;
|
|
728
|
+
if (ZERO_SHA.test(localSha) || !remoteRef.startsWith('refs/heads/'))
|
|
729
|
+
continue;
|
|
730
|
+
const branch = remoteRef.slice('refs/heads/'.length);
|
|
731
|
+
if (!eligible(settings, branch))
|
|
732
|
+
continue;
|
|
733
|
+
// Written before the refs are sent, so no turn-end hook sees the push land without it.
|
|
734
|
+
try {
|
|
735
|
+
await recordOptout(sys, root, branch, localSha, opted, remoteSha);
|
|
736
|
+
}
|
|
737
|
+
catch (error) {
|
|
738
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
739
|
+
if (opted) {
|
|
740
|
+
io.out(`❌ Could not record ${names}=0 for ${branch} (${why}), so a PR could open for it at turn end; push refused. Fix the cause, or push without the variable.`);
|
|
741
|
+
return 3;
|
|
742
|
+
}
|
|
743
|
+
io.out(`⚠️ Could not record ${branch}'s push for the PR opt-out (${why}); if an earlier push of this commit said ${names}=0, no PR opens for it automatically: open one yourself.`);
|
|
744
|
+
}
|
|
745
|
+
if (opted)
|
|
746
|
+
continue;
|
|
747
|
+
try {
|
|
748
|
+
sys.mkdir(stateDir(root));
|
|
749
|
+
// Its own session and no inherited descriptors: git, the hook's
|
|
750
|
+
// supervisor and a closing terminal neither wait on it nor end it.
|
|
751
|
+
sys.detach(sys.runtime.node, [sys.runtime.cli, 'pr-autocreate', 'watch', '--root', root, '--branch', branch, '--sha', localSha], { cwd: root, log: `${stateDir(root)}/watch.log` });
|
|
752
|
+
started.push(branch);
|
|
753
|
+
}
|
|
754
|
+
catch (error) {
|
|
755
|
+
io.out(`⚠️ Could not start the PR watcher for ${branch} (${error instanceof Error ? error.message : String(error)}); open its PR yourself.`);
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
if (started.length > 0)
|
|
759
|
+
io.out(`→ PR watcher started for ${started.join(', ')}: a ${settings.draft ? 'draft' : 'ready'} PR opens once the push lands.`);
|
|
760
|
+
return 0;
|
|
761
|
+
}
|
|
762
|
+
function seconds(value, fallback, name) {
|
|
763
|
+
if (value === undefined || value.trim() === '')
|
|
764
|
+
return fallback;
|
|
765
|
+
const number = Number(value);
|
|
766
|
+
if (!Number.isFinite(number) || number < 0)
|
|
767
|
+
throw new Error(`${name} must be a number of seconds`);
|
|
768
|
+
return number;
|
|
769
|
+
}
|
|
770
|
+
/** The watcher's arguments, its timings from flags or NIYAM_PR_WATCH_* variables, in seconds. */
|
|
771
|
+
export function watchArgs(sys, args) {
|
|
772
|
+
const given = flags(args, ['--root', '--branch', '--sha', '--timeout', '--interval', '--retry-window', '--retry-interval']);
|
|
773
|
+
const need = (name) => {
|
|
774
|
+
const value = given.get(name);
|
|
775
|
+
if (!value)
|
|
776
|
+
throw new Error(`watch needs ${name}`);
|
|
777
|
+
return value;
|
|
778
|
+
};
|
|
779
|
+
return {
|
|
780
|
+
root: need('--root'),
|
|
781
|
+
branch: need('--branch'),
|
|
782
|
+
sha: need('--sha'),
|
|
783
|
+
timeout: seconds(given.get('--timeout') ?? sys.env.NIYAM_PR_WATCH_TIMEOUT, 900, '--timeout'),
|
|
784
|
+
interval: seconds(given.get('--interval') ?? sys.env.NIYAM_PR_WATCH_INTERVAL, 5, '--interval'),
|
|
785
|
+
retryWindow: seconds(given.get('--retry-window') ?? sys.env.NIYAM_PR_RETRY_WINDOW, 600, '--retry-window'),
|
|
786
|
+
retryInterval: seconds(given.get('--retry-interval') ?? sys.env.NIYAM_PR_RETRY_INTERVAL, 30, '--retry-interval'),
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
/**
|
|
790
|
+
* Waits for the remote branch to hold the pushed commit, then makes sure the
|
|
791
|
+
* branch has its pull request, retrying GitHub for a bounded window. Every
|
|
792
|
+
* line goes to the watch log; a give-up says "<branch>: gave up", which a
|
|
793
|
+
* client's push instructions may tell a session to look for.
|
|
794
|
+
*/
|
|
795
|
+
export async function watch(sys, io, args, pullsOf = pullsFor) {
|
|
796
|
+
const log = (message) => io.out(`${sys.now().toISOString().slice(0, 19)} ${message}`);
|
|
797
|
+
let parsed;
|
|
798
|
+
try {
|
|
799
|
+
parsed = watchArgs(sys, args);
|
|
800
|
+
}
|
|
801
|
+
catch (error) {
|
|
802
|
+
log(`watch: ${error instanceof Error ? error.message : String(error)}; no PR opened`);
|
|
803
|
+
return 0;
|
|
804
|
+
}
|
|
805
|
+
const { root, branch, sha } = parsed;
|
|
806
|
+
const ref = `refs/heads/${branch}`;
|
|
807
|
+
const deadline = sys.now().getTime() + parsed.timeout * 1000;
|
|
808
|
+
for (;;) {
|
|
809
|
+
const heads = sys.exec('git', ['ls-remote', REMOTE, ref], { cwd: root, timeoutMs: 30_000 });
|
|
810
|
+
if (heads.code === 0 && heads.stdout.trim().split(/\s+/)[0] === sha)
|
|
811
|
+
break;
|
|
812
|
+
if (sys.now().getTime() >= deadline) {
|
|
813
|
+
log(`${branch}: gave up: ${sha.slice(0, 8)} never reached ${ref} within ${parsed.timeout}s; no PR opened`);
|
|
814
|
+
return 0;
|
|
815
|
+
}
|
|
816
|
+
await sys.sleep(parsed.interval * 1000);
|
|
817
|
+
}
|
|
818
|
+
let settings;
|
|
819
|
+
try {
|
|
820
|
+
settings = settingsAt(sys, root);
|
|
821
|
+
}
|
|
822
|
+
catch (error) {
|
|
823
|
+
log(`${branch}: gave up: ${error instanceof Error ? error.message : String(error)}; no PR opened`);
|
|
824
|
+
return 0;
|
|
825
|
+
}
|
|
826
|
+
const retryDeadline = sys.now().getTime() + parsed.retryWindow * 1000;
|
|
827
|
+
for (;;) {
|
|
828
|
+
const pulls = pullsOf(sys, root, undefined);
|
|
829
|
+
let state;
|
|
830
|
+
try {
|
|
831
|
+
state = 'problem' in pulls ? pulls : await ensurePr(sys, root, settings, branch, sha, pulls);
|
|
832
|
+
}
|
|
833
|
+
catch (error) {
|
|
834
|
+
state = { problem: error instanceof Error ? error.message : String(error) };
|
|
835
|
+
}
|
|
836
|
+
if (!('problem' in state)) {
|
|
837
|
+
const pr = state.pr;
|
|
838
|
+
log(`${branch}: ${pr ? `PR #${pr.number} ${state.created ? 'created' : 'exists'} (${pr.url})` : state.notes.join(' ') || 'no PR'}`);
|
|
839
|
+
return 0;
|
|
840
|
+
}
|
|
841
|
+
if (sys.now().getTime() >= retryDeadline) {
|
|
842
|
+
log(`${branch}: gave up: ${state.problem}, after ${parsed.retryWindow}s of retries`);
|
|
843
|
+
return 0;
|
|
844
|
+
}
|
|
845
|
+
log(`${branch}: ${state.problem}; retrying`);
|
|
846
|
+
await sys.sleep(parsed.retryInterval * 1000);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
/** `niyam pr-autocreate <claude-hook | spawn-watchers | watch> ...`: never a usage exit, which would hold a hook. */
|
|
850
|
+
export async function prAutocreate(sys, io, args) {
|
|
851
|
+
const [mode, ...rest] = args;
|
|
852
|
+
try {
|
|
853
|
+
if (mode === 'claude-hook')
|
|
854
|
+
return await claudeHook(sys, io, sys.readStdin());
|
|
855
|
+
if (mode === 'spawn-watchers')
|
|
856
|
+
return await spawnWatchers(sys, io, rest, sys.readStdin());
|
|
857
|
+
if (mode === 'watch')
|
|
858
|
+
return await watch(sys, io, rest);
|
|
859
|
+
io.err(`pr-autocreate: unknown mode "${mode ?? ''}"; it takes claude-hook, spawn-watchers or watch; nothing done`);
|
|
860
|
+
return 0;
|
|
861
|
+
}
|
|
862
|
+
catch (error) {
|
|
863
|
+
io.err(`pr-autocreate: unexpected error (${error instanceof Error ? error.message : String(error)}); nothing done`);
|
|
864
|
+
return 0;
|
|
865
|
+
}
|
|
866
|
+
}
|