@veda-hq/niyam 0.7.16 → 0.7.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 CHANGED
@@ -291,7 +291,9 @@ niyam (`~/.config/process-rules/`, or a keychain entry under the service
291
291
  what of the owner's an agent session could reach, any `owner-step` folder
292
292
  left behind (`▲`, saying whether it still holds a token; see Owner steps), and, in a repository with
293
293
  the board on, the organisation's issue types (see Issue types), and, in every
294
- onboarded repository, the shared Guard's caller (`✗` when it is missing or not
294
+ onboarded repository, that GitHub deletes a merged pull request's branch
295
+ (`delete_branch_on_merge`: `✗` when off, naming the repository's settings
296
+ page for the owner, since turning it on takes an admin; #557) and the shared Guard's caller (`✗` when it is missing or not
295
297
  as `onboard` writes it at `niyam.yml`'s release, or, with identity alone and so
296
298
  no `niyam.yml`, at any release; see The shared Guard). It shows them grouped as
297
299
  This Mac, GitHub and This repo, one line each: `✓` fine, `▲` worth fixing,
@@ -642,11 +644,22 @@ slice may be built:
642
644
  - each of its State sub-issues closed as not planned after the approval
643
645
  carries the owner's approval: a 👍 on the agent's proposal for it, or a
644
646
  `Decision:` comment;
645
- - no other open pull request names it;
647
+ - no other open pull request names it. The refusal gives that pull
648
+ request's full address and, for a branch in the repository, the command
649
+ that deletes its branch once it is closed as superseded,
650
+ `git push origin --delete <branch>`: the agent does that itself (#557);
646
651
  - each State it names with a line `State: #N` is a State sub-issue of the
647
652
  slice, and when the slice is closed already, so the pull request is a fix,
648
653
  it names at least one open State: the one the fix is filed as.
649
654
 
655
+ A refusal that sends the agent to the owner about an issue or a comment,
656
+ here, in Guard, in `propose` and in the needs-owner job, names its full
657
+ `https://github.com/…` address, once, where it first names it: the
658
+ proposal comment's own `#issuecomment-` link where there is one, else the
659
+ issue's, and the Approvals issue's. The agent passes that link on, never a
660
+ bare number (#557). Guard's refusal for a pull request that names no slice
661
+ has no issue to link yet: it says to add the `Slice:` line first.
662
+
650
663
  **One comment answers a batch.** Settings that name the repository's standing
651
664
  Approvals issue (`"approvals": N`) let the owner answer many asks at once:
652
665
  an owner's comment there whose first line opens `Decision: approve`, then
@@ -1059,7 +1072,24 @@ owner can unblock the work or it is proven unneeded, and whose reason it
1059
1072
  shows once. At the sixth stop at one commit it writes that note itself. A new
1060
1073
  commit resets the count and voids the note. The pull request is read over
1061
1074
  REST, as the session's agent; a cloud session is held the same way. Its
1062
- records are in `.tmp/keep-going/`. The settings:
1075
+ records are in `.tmp/keep-going/`.
1076
+
1077
+ An agent deletes its own closed pull requests' branches, never asking the
1078
+ owner (#557). So a merge, or a ready pull request on the desktop, does not
1079
+ let the session stop while one of the agents' pull requests for a slice its
1080
+ commits name was closed without merging and its branch is still on origin,
1081
+ building no open pull request. The hook reads the latest hundred closed
1082
+ pull requests and checks their branches newest first. A branch deleted
1083
+ already costs one read, so it hides none after it. Each stop names at
1084
+ most five branches still there; the rest show at a later stop, once those
1085
+ five are deleted. A stop spends at most 30 reads, and stops reading at
1086
+ the first one GitHub does not answer, or answers with anything but found
1087
+ or not found (404). The session is sent back with each
1088
+ pull request's address and
1089
+ `git push origin --delete <branch>`; anything GitHub or the settings cannot
1090
+ say holds nothing. A pull request of the session's own branch closed
1091
+ unmerged gets the same command, with reopening as the other way. The
1092
+ settings:
1063
1093
 
1064
1094
  ```json
1065
1095
  { "keepGoing": { "trunks": [], "printMode": [], "owner": "the owner", "tag": "niyam keep-going" } }
@@ -1761,7 +1791,7 @@ commit. `upgrade` asks with no token; `onboard` asks with the agent's. Install t
1761
1791
  once; nothing is built on install:
1762
1792
 
1763
1793
  ```bash
1764
- pnpm add -g https://github.com/veda-hq/niyam/releases/download/v0.7.16/veda-hq-niyam-0.7.16.tgz
1794
+ pnpm add -g https://github.com/veda-hq/niyam/releases/download/v0.7.17/veda-hq-niyam-0.7.17.tgz
1765
1795
  ```
1766
1796
 
1767
1797
  The package puts one command on `PATH`, `niyam`. Since P-57 a release
package/dist/asks.js CHANGED
@@ -3,6 +3,7 @@ import { ownersAlone } from './edits.js';
3
3
  import { approvedIn, batchAnswers, firstIssue } from './approvals.js';
4
4
  import { isOn, notAdoptedLine, offLine } from './features.js';
5
5
  import { UNKNOWN, commands } from './shell.js';
6
+ import { GITHUB_WEB } from './host.js';
6
7
  /** The label an ask puts on its issue, which the board's "Needs you" view lists. */
7
8
  export const NEEDS_OWNER = 'needs-owner';
8
9
  /** The longest comment that may ask the owner, in characters: the question, the page link and how to answer. */
@@ -383,9 +384,13 @@ async function answeredSince(sys, token, slug, number, ask, { owners, approvals
383
384
  const answers = batchAnswers(await every(sys, token, `${API}/repos/${slug}/issues/${approvals}/comments?since=${encodeURIComponent(ask.created_at)}`, true), owners, ask.names, ask.created_at);
384
385
  return answers.length > 0 && (await ownersAlone(sys, token, answers, owners)).kept.length > 0 ? `a "Decision: approve" on #${approvals}, the Approvals issue` : undefined;
385
386
  }
386
- /** The asks still waiting, as the sweep names them. */
387
- function waitingOn(waiting) {
388
- return waiting.map(({ kind, number }) => (kind === 'Proposal' ? `the proposal for #${number}` : 'the Needs you: ask')).join(', ');
387
+ /** Where the owner answers ask `ask` on issue `number`: the comment's own address, else the issue's. */
388
+ function askUrl(slug, number, ask) {
389
+ return ask?.html_url?.startsWith('https://') ? ask.html_url : `${GITHUB_WEB}/${slug}/issues/${number}`;
390
+ }
391
+ /** The asks still waiting on issue `issue`, as the sweep names them, each by the address the owner answers it at. */
392
+ function waitingOn(slug, issue, waiting) {
393
+ return waiting.map(({ kind, number, ask }) => `${kind === 'Proposal' ? `the proposal for #${number}` : 'the Needs you: ask'}, ${askUrl(slug, issue, ask)}`).join('; ');
389
394
  }
390
395
  /**
391
396
  * Judges each open issue labelled `needs-owner` by its asks, and takes the
@@ -410,7 +415,7 @@ async function sweep(sys, token, slug, settings, io, posted, named = []) {
410
415
  for (const { number } of waiting) {
411
416
  const standing = await answered(sys, token, slug, number, settings, batch);
412
417
  if ('waiting' in standing) {
413
- io.out(`#${number}: waits on the owner (${waitingOn(standing.waiting)})`);
418
+ io.out(`#${number}: waits on the owner (${waitingOn(slug, number, standing.waiting)})`);
414
419
  }
415
420
  else if ('answer' in standing) {
416
421
  await removeLabel(sys, token, slug, number);
@@ -480,7 +485,7 @@ export async function needsOwner(sys, io) {
480
485
  io.out(`needs-owner: #${issue} asks the owner (${kind}:), and the owner answered with ${after} as it was labelled; ${NEEDS_OWNER} taken off`);
481
486
  return 0;
482
487
  }
483
- io.out(`needs-owner: #${issue} asks the owner (${kind}:); labelled ${NEEDS_OWNER}`);
488
+ io.out(`needs-owner: #${issue} asks the owner (${kind}:) at ${askUrl(slug, issue, event.comment)}; labelled ${NEEDS_OWNER}`);
484
489
  return 0;
485
490
  }
486
491
  // The owner's batch answer on the Approvals issue names a proposal's own issue, such as a dropped State, not
package/dist/doctor.js CHANGED
@@ -1,8 +1,8 @@
1
- import { EXPIRY_WARNING_DAYS, SETTINGS_PATH, account, agentFrom, agentIn, anyLogin, either, hasSettings, loadSettings, repoAt, sameLogin, checkToken, keyBody, keyPairProblem, launcherPath, pathsFor, sessionFileIs, signingKeys, tokenInfo, } from './agent.js';
1
+ import { EXPIRY_WARNING_DAYS, SETTINGS_PATH, account, agentFrom, agentIn, anyLogin, githubSlug, either, hasSettings, loadSettings, repoAt, sameLogin, checkToken, keyBody, keyPairProblem, launcherPath, pathsFor, sessionFileIs, signingKeys, tokenInfo, } from './agent.js';
2
2
  import { LOCKED, clientHooks, hooksHittingLock } from './as-agent.js';
3
- import { FROM_SETUP, SIGNING_KEY_VAR, cloudLogin, fileFromSetup, ranFromSetup, repoReleases } from './cloud.js';
4
- import { GITHUB_NOREPLY } from './host.js';
5
- import { featuresIn } from './features.js';
3
+ import { FROM_SETUP, SIGNING_KEY_VAR, cloudLogin, cloudToken, fileFromSetup, ranFromSetup, repoReleases } from './cloud.js';
4
+ import { GITHUB_NOREPLY, GITHUB_WEB } from './host.js';
5
+ import { featuresIn, readRepo } from './features.js';
6
6
  import { callerAt, callerIsOnboards, pushBranch } from './guard-caller.js';
7
7
  import { typesDrift } from './issue-types.js';
8
8
  import { closing, findingLines, heading, painter, tilde } from './layout.js';
@@ -92,6 +92,7 @@ export async function doctor(sys, io, named) {
92
92
  }),
93
93
  ...(await typesFindings(sys, token)),
94
94
  ...(await boardAppFindings(sys, token)),
95
+ ...(await branchFindings(sys, token)),
95
96
  ];
96
97
  return report(sys, io, agent, [
97
98
  ['This Mac', mac],
@@ -204,6 +205,49 @@ async function boardAppFindings(sys, token) {
204
205
  return [{ mark: '▲', text: `board app secrets: cannot ask GitHub (${message(error)})`, fix: 'niyam doctor again' }];
205
206
  }
206
207
  }
208
+ /**
209
+ * Whether GitHub deletes a pull request's branch once it merges, the
210
+ * repository's "Automatically delete head branches" (`delete_branch_on_merge`,
211
+ * which a writer's token reads): required in an onboarded repository, so a
212
+ * merged branch never waits on anyone, as an agent deletes a closed one
213
+ * itself (#557). Turning it on takes an admin, so the fix names the owner
214
+ * and the settings page by its full address. GitHub not saying says nothing.
215
+ */
216
+ async function branchFindings(sys, token) {
217
+ let slug;
218
+ let owner;
219
+ try {
220
+ // The repository the session works in, as the caller check reads it, wherever doctor runs from.
221
+ const root = repoRoot(sys);
222
+ slug = githubSlug(sys.exec('git', ['remote', 'get-url', 'origin'], { cwd: root }).stdout.trim());
223
+ if (!token || !slug || !hasSettings(sys, root))
224
+ return [];
225
+ owner = either(loadSettings(sys, root).owners);
226
+ }
227
+ catch {
228
+ // fail-open: outside a client's clone, or settings doctor cannot read, there is no repository to check; onboard says what is wrong with them.
229
+ return [];
230
+ }
231
+ try {
232
+ const { status, json } = await readRepo(sys, slug, token);
233
+ const on = status === 200 ? json?.delete_branch_on_merge : undefined;
234
+ if (on === true)
235
+ return [{ mark: '✓', text: 'merged pull requests’ branches are deleted' }];
236
+ if (on !== false)
237
+ return [];
238
+ return [
239
+ {
240
+ mark: '✗',
241
+ text: `${slug} keeps a merged pull request’s branch: "Automatically delete head branches" is off`,
242
+ fix: `${owner} ticks it under General at ${GITHUB_WEB}/${slug}/settings`,
243
+ },
244
+ ];
245
+ }
246
+ catch (error) {
247
+ // fail-open: a read that failed is worth asking again, and breaks nothing yet.
248
+ return [{ mark: '▲', text: `merged branches: cannot ask GitHub (${message(error)})`, fix: 'niyam doctor again' }];
249
+ }
250
+ }
207
251
  /**
208
252
  * Client hooks that reach GitHub outside `as-agent` where doctor runs, a Mac
209
253
  * or a cloud session, and the Auto-fix and artifact rules an onboarded repo's
@@ -454,6 +498,8 @@ async function cloudDoctor(sys, io, named) {
454
498
  const agent = given ?? ('login' in asked ? asked.login : undefined);
455
499
  if (agent !== undefined)
456
500
  github.push(cloudCommits(sys, agent));
501
+ // The repository's own setting reads through the proxy as on a Mac (#557).
502
+ github.push(...(await branchFindings(sys, cloudToken(sys))));
457
503
  const about = 'login' in asked ? asked.login : agents !== undefined ? either(agents) : 'this cloud session';
458
504
  return report(sys, io, about, [
459
505
  ['This cloud session', session],
@@ -1,8 +1,8 @@
1
1
  import { basename, dirname } from 'node:path';
2
- import { githubSlug, isNoToken, SETTINGS_PATH } from './agent.js';
2
+ import { anyLogin, githubSlug, isNoToken, loadSettings, SETTINGS_PATH } from './agent.js';
3
3
  import { agentEnv } from './as-agent.js';
4
4
  import { GITHUB_API } from './host.js';
5
- import { sessionToken } from './work.js';
5
+ import { deleteBranchCommand, pullUrl, sessionToken, slicesNamed } from './work.js';
6
6
  /**
7
7
  * Claude Code's Stop hook: a session whose branch has commits the default
8
8
  * branch lacks keeps going until its pull request merges (docs/decisions.md,
@@ -17,12 +17,14 @@ import { sessionToken } from './work.js';
17
17
  * branch while its own is not pushed (that branch carries them);
18
18
  * - it wrote a stop note at this commit (`niyam keep-going --stop <why>`);
19
19
  * the hook shows the owner the reason once;
20
- * - its pull request merged at this commit, or GitHub cannot say (fail open);
20
+ * - its pull request merged at this commit, or GitHub cannot say (fail open),
21
+ * and no agent pull request for its slice was closed unmerged with its
22
+ * branch still on origin (#557): an agent deletes such a branch itself;
21
23
  * - a background task, or a `git commit` or `git push` in its worktree,
22
24
  * still runs (its exit wakes the session), unless it runs in print mode,
23
25
  * where the task dies with the turn;
24
26
  * - it is a desktop session, clean, with every commit on a ready pull
25
- * request: the app's Autofix wakes it;
27
+ * request, and no such closed branch left: the app's Autofix wakes it;
26
28
  * - it was sent back five times at one commit: the hook writes the stop note
27
29
  * itself and sends it back once more to say so.
28
30
  *
@@ -34,6 +36,10 @@ import { sessionToken } from './work.js';
34
36
  export const CAP = 5;
35
37
  /** How many pages of pull requests a branch name is read to: a reused name has a few. */
36
38
  const PAGES = 10;
39
+ /** How many closed pull requests' branches left on origin one stop names; the rest show once those are deleted. */
40
+ export const LEFT_MOST = 5;
41
+ /** How many reads one stop spends on closed pull requests' branches: one for a deleted branch, two for one still there. */
42
+ export const READS_MOST = 30;
37
43
  export const STORE = '.tmp/keep-going';
38
44
  export const PRINT_MODE_VAR = 'NIYAM_PRINT_MODE';
39
45
  export const STOP_COMMAND = 'niyam keep-going --stop "<why, in plain English>"';
@@ -87,15 +93,18 @@ export function decide(facts, previous, settings) {
87
93
  return facts.note.shown ? { stop: true, counter } : { stop: true, counter, say: facts.note.reason };
88
94
  if ((facts.pushing && !facts.print) || pr === 'unknown')
89
95
  return { stop: true, counter };
96
+ // A closed pull request's branch left on origin holds the session whatever else is done: the agent deletes it, never the owner (#557).
97
+ const leftOver = facts.left.map((one) => `PR ${one.number}, ${one.url}, for this slice was closed without merging and its branch ${one.ref} is still on origin: delete it yourself with \`${deleteBranchCommand(one.ref)}\`, never asking the owner`);
90
98
  // A merge releases the session only if it merged this commit: a reused
91
99
  // branch name can still show an older merged pull request, and work left
92
100
  // uncommitted on top is not merged either.
93
- if (pr?.state === 'MERGED' && pr.headRefOid === facts.head && !facts.dirty)
101
+ const merged = pr?.state === 'MERGED' && pr.headRefOid === facts.head && !facts.dirty;
102
+ if (merged && leftOver.length === 0)
94
103
  return { stop: true, counter };
95
104
  const pushed = facts.remote === facts.head;
96
105
  // A draft still needs the session; only a ready pull request waits on
97
106
  // events Autofix reports, and only once nothing is left uncommitted.
98
- if (facts.desktop && pr?.state === 'OPEN' && !pr.isDraft && pushed && !facts.dirty)
107
+ if (facts.desktop && pr?.state === 'OPEN' && !pr.isDraft && pushed && !facts.dirty && leftOver.length === 0)
99
108
  return { stop: true, counter };
100
109
  const count = counter.count + 1;
101
110
  const next = { head: facts.head, count };
@@ -109,8 +118,12 @@ export function decide(facts, previous, settings) {
109
118
  const release = `If only ${settings.owner} can unblock it, or it is proven unneeded, run \`${STOP_COMMAND}\` and say so to ${settings.owner}; then you may stop. After ${CAP}, the hook writes that note itself.`;
110
119
  // A running task in print mode (only then does one get here): gather read
111
120
  // nothing past it, since the task may still be changing the branch.
112
- const left = facts.pushing ? ['a commit, push or background task is running, and in print mode it dies with this turn: wait for it in the foreground'] : stillToDo(facts, pr, pushed);
113
- const what = `Branch ${facts.branch} has ${facts.ahead} commit(s) origin/${settings.base} lacks, and started work runs to merge`;
121
+ const left = facts.pushing
122
+ ? ['a commit, push or background task is running, and in print mode it dies with this turn: wait for it in the foreground']
123
+ : [...leftOver, ...(merged ? [] : stillToDo(facts, pr, pushed))];
124
+ const what = merged
125
+ ? `PR ${pr.number} merged branch ${facts.branch}, but closed pull requests for its slice left branches on origin, and started work ends only once they are gone`
126
+ : `Branch ${facts.branch} has ${facts.ahead} commit(s) origin/${settings.base} lacks, and started work runs to merge`;
114
127
  return {
115
128
  stop: false,
116
129
  counter: next,
@@ -128,8 +141,9 @@ function stillToDo(facts, pr, pushed) {
128
141
  left.push('no pull request yet: open it');
129
142
  else if (pr.state === 'MERGED')
130
143
  left.push(`PR ${pr.number} merged an older commit; the work since is not merged: commit it and open a new PR`);
131
- else if (pr.state !== 'OPEN')
132
- left.push(`PR ${pr.number} was closed without merging: reopen it, or record why the work stops`);
144
+ else if (pr.state !== 'OPEN') {
145
+ left.push(`PR ${pr.number}, ${pr.url}, was closed without merging: reopen it, or, if it is superseded, delete its branch yourself with \`${deleteBranchCommand(facts.branch)}\` and record why the work stops`);
146
+ }
133
147
  else if (pushed && pr.isDraft)
134
148
  left.push(`PR ${pr.number} is a draft: finish the work, push, mark it ready`);
135
149
  else if (pushed)
@@ -229,12 +243,18 @@ function tokenFor(sys, root, session, err) {
229
243
  * when origin is not on GitHub, there is no token, or GitHub cannot say.
230
244
  */
231
245
  export async function readPr(sys, root, branch, head, session, err) {
246
+ const github = reach(sys, root, session, err);
247
+ return github ? readPrAt(sys, github, branch, head) : 'unknown';
248
+ }
249
+ /** Where to ask GitHub: origin's repository and the token to read it with; undefined when origin is not on GitHub or there is no token. */
250
+ function reach(sys, root, session, err) {
232
251
  const slug = githubSlug(out(sys, root, 'git', ['config', '--get', 'remote.origin.url']) ?? '');
233
252
  if (!slug)
234
- return 'unknown';
253
+ return undefined;
235
254
  const token = tokenFor(sys, root, session, err);
236
- if (!token)
237
- return 'unknown';
255
+ return token ? { slug, token } : undefined;
256
+ }
257
+ async function readPrAt(sys, { slug, token }, branch, head) {
238
258
  const pulls = [];
239
259
  const route = `${GITHUB_API}/repos/${slug}/pulls?head=${encodeURIComponent(`${slug.split('/')[0]}:${branch}`)}&state=all&per_page=100`;
240
260
  // Each page bounded, and the pages too, under the hook's own timeout.
@@ -263,11 +283,81 @@ export async function readPr(sys, root, branch, head, session, err) {
263
283
  const from = pull.head.repo?.full_name;
264
284
  if (typeof from !== 'string' || from.toLowerCase() !== slug.toLowerCase())
265
285
  continue;
266
- own.push({ number: pull.number, state: pull.merged_at ? 'MERGED' : pull.state === 'open' ? 'OPEN' : 'CLOSED', isDraft: pull.draft, headRefOid: pull.head.sha });
286
+ const number = pull.number;
287
+ own.push({ number, state: pull.merged_at ? 'MERGED' : pull.state === 'open' ? 'OPEN' : 'CLOSED', isDraft: pull.draft, headRefOid: pull.head.sha, url: pullUrl(slug, number, pull.html_url) });
267
288
  }
268
289
  // A reused branch name lists several: the one carrying this commit is the branch's, else the newest.
269
290
  return own.find((pr) => pr.headRefOid === head) ?? own[0] ?? null;
270
291
  }
292
+ /**
293
+ * The agents' pull requests for the slices this branch's own commits name
294
+ * (`Slice: #N` trailers), closed without merging, from this repository,
295
+ * whose branch is still on origin and builds no open pull request: a
296
+ * superseded one, whose branch the agent deletes itself (#557). The most
297
+ * recently updated hundred closed pull requests are read, each page and
298
+ * branch with a timeout; whatever GitHub or the settings cannot say gives
299
+ * none, so the hook fails open.
300
+ */
301
+ export async function leftBranches(sys, root, settings, branch, { slug, token }) {
302
+ const slices = slicesNamed(out(sys, root, 'git', ['log', '--format=%B', `origin/${settings.base}..HEAD`]) ?? '');
303
+ if (slices.length === 0)
304
+ return [];
305
+ let agents;
306
+ try {
307
+ agents = loadSettings(sys, root).agents;
308
+ }
309
+ catch {
310
+ // fail-open: settings the hook cannot read name no agent, so no closed branch is the session's to delete.
311
+ return [];
312
+ }
313
+ const list = async (query) => {
314
+ const got = await sys.http(`${GITHUB_API}/repos/${slug}/pulls?${query}`, { token, timeoutMs: 15_000 }).catch(() => {
315
+ // fail-open: GitHub not answering says nothing about closed branches, and the hook lets the session stop.
316
+ return undefined;
317
+ });
318
+ return got?.status === 200 && Array.isArray(got.json) ? got.json : undefined;
319
+ };
320
+ const here = (pull) => typeof pull.head?.repo?.full_name === 'string' && pull.head.repo.full_name.toLowerCase() === slug.toLowerCase();
321
+ const closed = await list('state=closed&sort=updated&direction=desc&per_page=100');
322
+ const candidates = (closed ?? []).flatMap((pull) => {
323
+ const ref = pull.head?.ref;
324
+ if (!Number.isInteger(pull.number) || pull.merged_at || typeof ref !== 'string' || ref === branch || !here(pull))
325
+ return [];
326
+ if (!anyLogin(agents, typeof pull.user?.login === 'string' ? pull.user.login : undefined))
327
+ return [];
328
+ if (!slicesNamed(typeof pull.body === 'string' ? pull.body : '').some((slice) => slices.includes(slice)))
329
+ return [];
330
+ return [{ number: pull.number, url: pullUrl(slug, pull.number, pull.html_url), ref }];
331
+ });
332
+ // Each branch once, newest first, until LEFT_MOST are found (the rest show once those are gone) or READS_MOST reads
333
+ // are spent. A deleted branch costs one read, so the branches already cleaned up never hide a later one.
334
+ const branches = candidates.filter((one, at) => candidates.findIndex((other) => other.ref === one.ref) === at);
335
+ const left = [];
336
+ let reads = 0;
337
+ for (const one of branches) {
338
+ if (left.length >= LEFT_MOST || reads >= READS_MOST)
339
+ break;
340
+ reads++;
341
+ const ref = await sys.http(`${GITHUB_API}/repos/${slug}/git/ref/heads/${one.ref.split('/').map(encodeURIComponent).join('/')}`, { token, timeoutMs: 15_000 }).catch(() => {
342
+ // fail-open: a branch GitHub cannot be asked about is not held against the session.
343
+ return undefined;
344
+ });
345
+ // 404 alone says deleted already, so the scan goes on past it.
346
+ if (ref?.status === 404)
347
+ continue;
348
+ // GitHub not answering, or answering anything but 200, stops the reads: the next would fare no better, and the hook fails open.
349
+ if (ref?.status !== 200)
350
+ break;
351
+ reads++;
352
+ // A branch an open pull request still builds from is not left over: asked by its own head, so no page can hide one.
353
+ const open = await list(`state=open&head=${encodeURIComponent(`${slug.split('/')[0]}:${one.ref}`)}&per_page=100`);
354
+ if (!open)
355
+ break;
356
+ if (!open.some((pull) => here(pull) && pull.head?.ref === one.ref))
357
+ left.push(one);
358
+ }
359
+ return left;
360
+ }
271
361
  export async function gather(sys, root, settings, subagent, session, err) {
272
362
  const head = out(sys, root, 'git', ['rev-parse', 'HEAD']) ?? '';
273
363
  const branch = out(sys, root, 'git', ['symbolic-ref', '--quiet', '--short', 'HEAD']) ?? '';
@@ -282,6 +372,7 @@ export async function gather(sys, root, settings, subagent, session, err) {
282
372
  note: null,
283
373
  remote: out(sys, root, 'git', ['rev-parse', '--verify', '--quiet', '@{u}']),
284
374
  pr: null,
375
+ left: [],
285
376
  pushing: false,
286
377
  dirty: false,
287
378
  };
@@ -300,7 +391,10 @@ export async function gather(sys, root, settings, subagent, session, err) {
300
391
  return facts;
301
392
  // Its own records, and pr-autocreate's, are no work left, where a client does not ignore .tmp/.
302
393
  facts.dirty = Boolean(out(sys, root, 'git', ['status', '--porcelain', '--', '.', `:(exclude)${STORE}`, ':(exclude).tmp/pr-autocreate']));
303
- facts.pr = await readPr(sys, root, branch, head, session, err);
394
+ const github = reach(sys, root, session, err);
395
+ facts.pr = github ? await readPrAt(sys, github, branch, head) : 'unknown';
396
+ if (github && facts.pr !== 'unknown')
397
+ facts.left = await leftBranches(sys, root, settings, branch, github);
304
398
  return facts;
305
399
  }
306
400
  /** The hook: reads the Stop input, returns a block decision, a message, or nothing. Never throws. */
package/dist/work.js CHANGED
@@ -145,10 +145,10 @@ async function readSlice(sys, token, slug, slice, { owners, agents, approvals })
145
145
  .filter((event) => (event.event === 'labeled' || event.event === 'unlabeled') && event.label.name === 'approved')
146
146
  .at(-1);
147
147
  if (approval?.event !== 'labeled') {
148
- return { problems: [`work item #${parent.number} is not approved: ${either(owners)} adds the approved label before any slice starts`], owed: [] };
148
+ return { problems: [`work item #${parent.number}, ${issueUrl(slug, parent.number)}, is not approved: ${either(owners)} adds the approved label before any slice starts`], owed: [] };
149
149
  }
150
150
  if (!anyLogin(owners, approval.actor?.login)) {
151
- return { problems: [`work item #${parent.number} was labeled approved by ${approval.actor?.login ?? 'someone unknown'}, not ${either(owners)}`], owed: [] };
151
+ return { problems: [`work item #${parent.number}, ${issueUrl(slug, parent.number)}, was labeled approved by ${approval.actor?.login ?? 'someone unknown'}, not ${either(owners)}`], owed: [] };
152
152
  }
153
153
  const approvedAt = approval.created_at;
154
154
  const parentComments = events.filter((event) => event.event === 'commented');
@@ -249,16 +249,48 @@ function stateProblems(slice, closed, states, names) {
249
249
  return problems;
250
250
  }
251
251
  /** Why `owed` stops slice `slice`, and how the owner settles it. */
252
- function owedProblem(one, slice, parent, { owners, agents, approvals }) {
252
+ function owedProblem(slug, one, slice, parent, { owners, agents, approvals }) {
253
253
  const owner = either(owners);
254
254
  // The agent proposes as itself; with several, any of them.
255
255
  const agent = either(agents);
256
256
  const ask = `${one.note ? ` (${one.note})` : ''}${one.proposals.length > 0 ? '' : `; ${agent} proposes it with: ${proposeCommand(one.number)}`}`;
257
+ // Each place the owner acts, by its full address, so an agent passes on a link, never a bare number.
258
+ const issue = (number) => issueUrl(slug, number);
259
+ // The comment the owner reacts to, where there is one; else the slice, where the proposal is to be posted.
260
+ const on = one.proposals.length > 0
261
+ ? `${agent}'s proposal${one.kind === 'added' ? '' : ' for it'}, ${newest(one.proposals).html_url}`
262
+ : `${agent}'s proposal${one.kind === 'added' ? '' : ' for it'} on #${slice}, ${issue(slice)}`;
257
263
  // Where the settings name an Approvals issue, one comment there answers this among a batch.
258
- const batch = approvals === undefined ? '' : `, or ${owner} comments on #${approvals}, the Approvals issue, with a first line "Decision: approve #${one.number}"`;
264
+ const batch = approvals === undefined ? '' : `, or ${owner} comments on #${approvals}, the Approvals issue, ${issue(approvals)}, with a first line "Decision: approve #${one.number}"`;
259
265
  return one.kind === 'added'
260
- ? `#${slice} was added to work item #${parent} after its approval; ${owner} reacts 👍 on ${agent}'s proposal on #${slice}, or adds a "Decision:" comment naming #${slice}, or #${slice} links ${owner}'s request for it on #${parent}${batch}${ask}`
261
- : `state #${one.number} was closed as not planned after approval; ${owner} reacts 👍 on ${agent}'s proposal for it on #${slice}, or adds a "Decision:" comment to it${batch}${ask}`;
266
+ ? `#${slice} was added to work item #${parent}, ${issue(parent)}, after its approval; ${owner} reacts 👍 on ${on}, or adds a "Decision:" comment naming #${slice} on ${issue(slice)}, or #${slice} links ${owner}'s request for it on #${parent}${batch}${ask}`
267
+ : `state #${one.number}, ${issue(one.number)}, was closed as not planned after approval; ${owner} reacts 👍 on ${on}, or adds a "Decision:" comment to it${batch}${ask}`;
268
+ }
269
+ /** Issue `number`'s own address on GitHub, where the owner acts on it. */
270
+ export function issueUrl(slug, number) {
271
+ return `${GITHUB_WEB}/${slug}/issues/${number}`;
272
+ }
273
+ /** A pull request's own address on GitHub: GitHub's, else built from its number. */
274
+ export function pullUrl(slug, number, given) {
275
+ return typeof given === 'string' && given.startsWith('https://') ? given : `${GITHUB_WEB}/${slug}/pull/${number}`;
276
+ }
277
+ /**
278
+ * The command that deletes branch `ref` on origin, quoted where the shell
279
+ * would read it otherwise. A branch starting `-` or `+` is named in full,
280
+ * `refs/heads/…`, so git reads it neither as an option nor as a forced push.
281
+ */
282
+ export function deleteBranchCommand(ref) {
283
+ const target = /^[-+]/.test(ref) ? `refs/heads/${ref}` : ref;
284
+ return `git push origin --delete ${/^[\w./+-]+$/.test(target) ? target : `'${target.replaceAll("'", "'\\''")}'`}`;
285
+ }
286
+ /**
287
+ * Why `pull` stops another pull request for slice `slice`, with its address
288
+ * and, when it is superseded, what to do: close it and, for a branch in this
289
+ * repository (`here`), delete its branch, as an agent does itself.
290
+ */
291
+ function secondPull(slug, slice, pull, here) {
292
+ const remedy = here ? `close it and delete its branch: ${deleteBranchCommand(pull.head.ref)}` : 'close it';
293
+ return `#${slice} already has pull request #${pull.number}, ${pullUrl(slug, pull.number, pull.html_url)}; one slice, one pull request. If #${pull.number} is superseded, ${remedy}`;
262
294
  }
263
295
  /**
264
296
  * The work rules for building one slice, as problems; none means it may be
@@ -273,7 +305,7 @@ export async function sliceProblems(sys, token, slug, slice, accounts, mine) {
273
305
  const read = await readSlice(sys, token, slug, slice, accounts);
274
306
  if (read.problems.length > 0)
275
307
  return read.problems;
276
- const problems = read.owed.filter((one) => !one.settled).map((one) => owedProblem(one, slice, read.parent, accounts));
308
+ const problems = read.owed.filter((one) => !one.settled).map((one) => owedProblem(slug, one, slice, read.parent, accounts));
277
309
  if (mine.states)
278
310
  problems.push(...stateProblems(slice, read.closed ?? false, read.states ?? [], mine.states));
279
311
  // The pull request being checked: by number, or by its branch in this repository (not a fork's of the same name).
@@ -282,10 +314,11 @@ export async function sliceProblems(sys, token, slug, slice, accounts, mine) {
282
314
  if (pulls.status !== 200 || !Array.isArray(pulls.json))
283
315
  throw new Error(`cannot list open pull requests (HTTP ${pulls.status})`);
284
316
  for (const pull of pulls.json) {
285
- if (pull.number === mine.pull || (pull.head.ref === mine.branch && pull.head.repo?.full_name.toLowerCase() === slug.toLowerCase()))
317
+ const here = pull.head.repo?.full_name.toLowerCase() === slug.toLowerCase();
318
+ if (pull.number === mine.pull || (pull.head.ref === mine.branch && here))
286
319
  continue;
287
320
  if (slicesNamed(pull.body ?? '').includes(slice))
288
- problems.push(`#${slice} already has pull request #${pull.number}; one slice, one pull request`);
321
+ problems.push(secondPull(slug, slice, pull, here));
289
322
  }
290
323
  if (pulls.json.length < 100)
291
324
  break;
@@ -765,13 +798,13 @@ function proposeCommand(number) {
765
798
  * argues it, and how to answer. What changes, why and what it costs live on
766
799
  * the page, from the slice's sections.
767
800
  */
768
- function proposalBody(one, parent, page, { owners, approvals }) {
801
+ function proposalBody(slug, one, parent, page, { owners, approvals }) {
769
802
  // The issue it is for comes first: that is how the work rules match a 👍 to it.
770
803
  const what = one.kind === 'added'
771
804
  ? `Proposal: add #${one.number} (${one.title}) to work item #${parent}.`
772
805
  : `Proposal: drop state #${one.number} (${one.title}), closed as not planned after work item #${parent}'s approval.`;
773
806
  // Where the settings name an Approvals issue, the owner may answer this there, among a batch.
774
- const batch = approvals === undefined ? '' : `, or answer the batch on Approvals, #${approvals}`;
807
+ const batch = approvals === undefined ? '' : `, or answer the batch on Approvals, ${issueUrl(slug, approvals)}`;
775
808
  return `${what}\n\nPage: ${page}\n\n${either(owners.map((owner) => `@${owner}`))}: react 👍 to this comment to approve it, or comment "Decision:"${batch}.`;
776
809
  }
777
810
  /**
@@ -868,7 +901,7 @@ async function proposeOne(sys, io, token, slug, accounts, number, page) {
868
901
  };
869
902
  }
870
903
  // Each comment meets the guard's rule for asks (a page link, ASK_LIMIT characters) before any is posted.
871
- const bodies = new Map(page === undefined ? [] : fresh.map((one) => [one, proposalBody(one, read.parent, page, accounts)]));
904
+ const bodies = new Map(page === undefined ? [] : fresh.map((one) => [one, proposalBody(slug, one, read.parent, page, accounts)]));
872
905
  const unfit = [...bodies].flatMap(([one, body]) => {
873
906
  const problem = askProblem({ text: body, known: true, opensUnknown: false }, accounts.owners);
874
907
  return problem ? [`${named(one)}'s proposal is not posted: ${problem}; shorten ${named(one)}'s title`] : [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veda-hq/niyam",
3
- "version": "0.7.16",
3
+ "version": "0.7.17",
4
4
  "description": "Work rules for repos that track work in GitHub Issues: setup, agent identity, push and PR checks.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -29,7 +29,7 @@
29
29
  "@types/node": "24.19.2",
30
30
  "@veda-hq/dvara": "0.5.16",
31
31
  "@veda-hq/pariksha": "0.5.20",
32
- "@veda-hq/sarathi": "0.7.8",
32
+ "@veda-hq/sarathi": "0.7.19",
33
33
  "typescript": "7.0.2"
34
34
  },
35
35
  "dependencies": {