@veda-hq/niyam 0.7.16 → 0.7.18

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,33 @@ 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
+
663
+ **A slice in another repository.** A repository whose work is planned in
664
+ another one names that repository's slice as `Slice: owner/name#N` or by its
665
+ address, `Slice: https://github.com/owner/name/issues/N`, and its States as
666
+ `State: owner/name#N`; a bare `#N` is always this repository's. The slice is
667
+ read there by the same rules, judged by this repository's owners, with that
668
+ repository's own Approvals issue. It counts only where the token reads that
669
+ repository. A workflow's own token reads no private repository but its own,
670
+ so the pull request check refuses a slice in another private repository,
671
+ saying so. The pre-push hook, on the agent's token, can pass it. Slice done
672
+ leaves it to its own repository.
673
+
650
674
  **One comment answers a batch.** Settings that name the repository's standing
651
675
  Approvals issue (`"approvals": N`) let the owner answer many asks at once:
652
676
  an owner's comment there whose first line opens `Decision: approve`, then
@@ -1059,7 +1083,24 @@ owner can unblock the work or it is proven unneeded, and whose reason it
1059
1083
  shows once. At the sixth stop at one commit it writes that note itself. A new
1060
1084
  commit resets the count and voids the note. The pull request is read over
1061
1085
  REST, as the session's agent; a cloud session is held the same way. Its
1062
- records are in `.tmp/keep-going/`. The settings:
1086
+ records are in `.tmp/keep-going/`.
1087
+
1088
+ An agent deletes its own closed pull requests' branches, never asking the
1089
+ owner (#557). So a merge, or a ready pull request on the desktop, does not
1090
+ let the session stop while one of the agents' pull requests for a slice its
1091
+ commits name was closed without merging and its branch is still on origin,
1092
+ building no open pull request. The hook reads the latest hundred closed
1093
+ pull requests and checks their branches newest first. A branch deleted
1094
+ already costs one read, so it hides none after it. Each stop names at
1095
+ most five branches still there; the rest show at a later stop, once those
1096
+ five are deleted. A stop spends at most 30 reads, and stops reading at
1097
+ the first one GitHub does not answer, or answers with anything but found
1098
+ or not found (404). The session is sent back with each
1099
+ pull request's address and
1100
+ `git push origin --delete <branch>`; anything GitHub or the settings cannot
1101
+ say holds nothing. A pull request of the session's own branch closed
1102
+ unmerged gets the same command, with reopening as the other way. The
1103
+ settings:
1063
1104
 
1064
1105
  ```json
1065
1106
  { "keepGoing": { "trunks": [], "printMode": [], "owner": "the owner", "tag": "niyam keep-going" } }
@@ -1761,7 +1802,7 @@ commit. `upgrade` asks with no token; `onboard` asks with the agent's. Install t
1761
1802
  once; nothing is built on install:
1762
1803
 
1763
1804
  ```bash
1764
- pnpm add -g https://github.com/veda-hq/niyam/releases/download/v0.7.16/veda-hq-niyam-0.7.16.tgz
1805
+ pnpm add -g https://github.com/veda-hq/niyam/releases/download/v0.7.18/veda-hq-niyam-0.7.18.tgz
1765
1806
  ```
1766
1807
 
1767
1808
  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/design.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { API, SETTINGS_PATH, anyLogin, loadSettings } from './agent.js';
2
- import { slicesNamed } from './work.js';
2
+ import { refName, slicesNamed } from './work.js';
3
3
  import { FIGMA_FILE_KEY, PERSONAL_REPO, isOn, isPersonal, notAdoptedLine, offLine, renamedLines } from './features.js';
4
4
  const FIGMA = 'https://api.figma.com/v1';
5
5
  /** A Figma link to one node: the file's key and the node's id. */
@@ -148,13 +148,16 @@ export async function prDesign(sys, io) {
148
148
  const event = JSON.parse(sys.read(eventPath));
149
149
  const pull = event.pull_request;
150
150
  const { agents } = loadSettings(sys, sys.cwd);
151
- const [slice] = slicesNamed(pull?.body ?? '');
152
- if (!pull || !anyLogin(agents, pull.user.login) || slice === undefined) {
151
+ const [ref] = slicesNamed(pull?.body ?? '', slug);
152
+ if (!pull || !anyLogin(agents, pull.user.login) || ref === undefined) {
153
153
  io.out('pr-design: not an agent pull request naming a slice; nothing to check');
154
154
  return 0;
155
155
  }
156
+ // A slice in another repository is read there.
157
+ const { number: slice } = ref;
158
+ const label = refName(ref, slug);
156
159
  // Every state of the slice, 100 a page: GitHub's most.
157
- const [owner, name] = slug.split('/');
160
+ const [owner, name] = ref.repo.split('/');
158
161
  const states = [];
159
162
  for (let after = null;;) {
160
163
  const { status, json } = await sys.http(`${API}/graphql`, {
@@ -168,13 +171,13 @@ export async function prDesign(sys, io) {
168
171
  const issue = json?.data?.repository?.issue;
169
172
  const page = issue?.subIssues;
170
173
  if (status !== 200 || !page)
171
- throw new Error(`cannot read the states of #${slice} (HTTP ${status})`);
174
+ throw new Error(`cannot read the states of ${label} (HTTP ${status})`);
172
175
  // The work item's kind, read with the first page: only Experience work is designed in Figma.
173
176
  const parent = issue.parent;
174
177
  if (after === null && parent?.issueType?.name === 'Work item') {
175
178
  const kind = workItemKind(parent.body);
176
179
  if (kind && kind.toLowerCase() !== DESIGNED_KIND.toLowerCase()) {
177
- io.out(`✓ pr-design: #${slice} builds ${kind} work item #${parent.number}; frames are for ${DESIGNED_KIND} work`);
180
+ io.out(`✓ pr-design: ${label} builds ${kind} work item #${parent.number}; frames are for ${DESIGNED_KIND} work`);
178
181
  return 0;
179
182
  }
180
183
  }
@@ -202,6 +205,6 @@ export async function prDesign(sys, io) {
202
205
  io.err('pr-design: refused by the design check');
203
206
  return 1;
204
207
  }
205
- io.out(`✓ pr-design: ${checked} state${checked === 1 ? '' : 's'} of #${slice}, each a frame built from the design library`);
208
+ io.out(`✓ pr-design: ${checked} state${checked === 1 ? '' : 's'} of ${label}, each a frame built from the design library`);
206
209
  return 0;
207
210
  }
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],
@@ -118,7 +118,7 @@ async function untyped(sys, token, repo) {
118
118
  * standing record the owner answers batches on, never closed, which no work
119
119
  * model type fits.
120
120
  */
121
- async function approvalsOf(sys, token, repo) {
121
+ export async function approvalsOf(sys, token, repo) {
122
122
  const { status, json } = await sys.http(`${API}/repos/${repo}/contents/${SETTINGS_PATH}`, { token });
123
123
  if (status === 404)
124
124
  return undefined;
@@ -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, sameIssue, 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:` trailers, here or in another repository), 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`]) ?? '', slug);
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 : '', slug).some((slice) => slices.some((mine) => sameIssue(mine, 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
@@ -8,21 +8,50 @@ import { boardStarted } from './board.js';
8
8
  import { gate } from './handoff.js';
9
9
  import { ownersAlone, whyNotCounted } from './edits.js';
10
10
  import { batchAnswers } from './approvals.js';
11
+ import { approvalsOf } from './issue-types.js';
11
12
  import { PAGE_LINK, askProblem } from './asks.js';
13
+ /**
14
+ * How a line names an issue: `#N` in the repository it is in, or another
15
+ * repository's issue as `owner/name#N` or by its full address.
16
+ */
17
+ const REPO_NAMED = '[A-Za-z0-9-]+/[A-Za-z0-9._-]+';
18
+ const ISSUE_NAMED = `(?:#(\\d+)|(${REPO_NAMED})#(\\d+)|https://${GITHUB_HOST_RE}/(${REPO_NAMED})/issues/(\\d+))`;
12
19
  /** How a pull request or a commit names the slice it builds. */
13
- const SLICE_LINE = new RegExp(`^Slice:\\s*(?:#|https://${GITHUB_HOST_RE}/[^/\\s]+/[^/\\s]+/issues/)(\\d+)\\s*$`, 'gim');
20
+ const SLICE_LINE = new RegExp(`^Slice:\\s*${ISSUE_NAMED}\\s*$`, 'gim');
14
21
  /** How a pull request names a State of its slice that it delivers. */
15
- const STATE_LINE = new RegExp(`^State:\\s*(?:#|https://${GITHUB_HOST_RE}/[^/\\s]+/[^/\\s]+/issues/)(\\d+)\\s*$`, 'gim');
16
- /** The issues `line` names in `text`, in order, without repeats. */
17
- const named = (line, text) => [...new Set([...text.matchAll(line)].map((match) => Number(match[1])))];
18
- /** The slices `text` names, in order, without repeats. */
19
- export function slicesNamed(text) {
20
- return named(SLICE_LINE, text);
22
+ const STATE_LINE = new RegExp(`^State:\\s*${ISSUE_NAMED}\\s*$`, 'gim');
23
+ /** Whether `a` and `b` name one repository: GitHub reads owner and name in any case. */
24
+ const sameRepo = (a, b) => a.toLowerCase() === b.toLowerCase();
25
+ /** Whether `a` and `b` are one issue. */
26
+ export const sameIssue = (a, b) => a.number === b.number && sameRepo(a.repo, b.repo);
27
+ /** How a message names `ref` from repository `here`: `#N` there, `owner/name#N` anywhere else. */
28
+ export function refName(ref, here) {
29
+ return sameRepo(ref.repo, here) ? `#${ref.number}` : `${ref.repo}#${ref.number}`;
30
+ }
31
+ /**
32
+ * The issues `line` names in `text`, read from repository `here`, in order,
33
+ * without repeats: a line naming `here` by name is one of its own issues.
34
+ */
35
+ function named(line, text, here) {
36
+ const refs = [];
37
+ for (const match of text.matchAll(line)) {
38
+ const repo = match[2] ?? match[4];
39
+ const ref = { repo: repo === undefined || sameRepo(repo, here) ? here : repo, number: Number(match[1] ?? match[3] ?? match[5]) };
40
+ if (!refs.some((one) => sameIssue(one, ref)))
41
+ refs.push(ref);
42
+ }
43
+ return refs;
21
44
  }
22
- /** The States `text` names with a line `State: #N`, in order, without repeats. */
23
- export function statesNamed(text) {
24
- return named(STATE_LINE, text);
45
+ /** The slices `text` names, read from repository `here`, in order, without repeats. */
46
+ export function slicesNamed(text, here) {
47
+ return named(SLICE_LINE, text, here);
25
48
  }
49
+ /** The States `text` names with a line `State: #N`, read from repository `here`, in order, without repeats. */
50
+ export function statesNamed(text, here) {
51
+ return named(STATE_LINE, text, here);
52
+ }
53
+ /** How an error names `slice`. */
54
+ const tagOf = (slice) => (typeof slice === 'number' ? `#${slice}` : slice);
26
55
  /**
27
56
  * Reads `url` from GitHub's REST API for slice `slice`'s work rules: its
28
57
  * JSON, or undefined on 404 when `missing` allows it. The work rules read
@@ -35,9 +64,14 @@ async function rest(sys, token, slice, url, missing = false) {
35
64
  return undefined;
36
65
  if (status !== 200) {
37
66
  const why = json?.message ?? `HTTP ${status}`;
38
- // A client workflow from before the work rules grants no issues: read.
39
- const hint = /not accessible/i.test(why) ? '; the client workflow needs issues: read, so run niyam onboard to update it' : '';
40
- throw new Error(`cannot read #${slice}: ${why} (${url.replace(API, '')})${hint}`);
67
+ // A client workflow from before the work rules grants no issues: read. Another repository's slice is read with
68
+ // whatever the token reaches there, which onboard does not set.
69
+ const hint = /not accessible/i.test(why)
70
+ ? typeof slice === 'number'
71
+ ? '; the client workflow needs issues: read, so run niyam onboard to update it'
72
+ : `; this token cannot read ${slice.replace(/#\d+$/, '')}`
73
+ : '';
74
+ throw new Error(`cannot read ${tagOf(slice)}: ${why} (${url.replace(API, '')})${hint}`);
41
75
  }
42
76
  return json;
43
77
  }
@@ -49,7 +83,7 @@ async function every(sys, token, slice, url, missing = false) {
49
83
  if (json === undefined)
50
84
  return items;
51
85
  if (!Array.isArray(json))
52
- throw new Error(`cannot read #${slice}: GitHub did not answer a list (${url.replace(API, '')})`);
86
+ throw new Error(`cannot read ${tagOf(slice)}: GitHub did not answer a list (${url.replace(API, '')})`);
53
87
  items.push(...json);
54
88
  if (json.length < 100)
55
89
  return items;
@@ -114,7 +148,7 @@ async function readIssue(sys, token, slug, number) {
114
148
  * Read from the parent endpoint, not the issue's `parent_issue_url`: on a
115
149
  * private repository a workflow's GITHUB_TOKEN gets that field back as null.
116
150
  */
117
- async function parentOf(sys, token, issue) {
151
+ async function parentOf(sys, token, issue, nameOf = (number) => `#${number}`) {
118
152
  const { status, json } = await sys.http(`${issue.url}/parent`, { token });
119
153
  if (status === 200)
120
154
  return { parent: json };
@@ -122,40 +156,85 @@ async function parentOf(sys, token, issue) {
122
156
  // An issue with no parent reads as 404 "No parent issue found"; any other failure is a read that failed, not a missing parent.
123
157
  if (status === 404 && message && /no parent/i.test(message))
124
158
  return {};
125
- return { problem: `could not read #${issue.number}'s parent (HTTP ${status}${message ? `: ${message}` : ''})` };
159
+ return { problem: `could not read ${nameOf(issue.number)}'s parent (HTTP ${status}${message ? `: ${message}` : ''})` };
160
+ }
161
+ /**
162
+ * Issue `ref` from another repository than `here`, or the problem that
163
+ * refuses it: one the token cannot read there (GitHub answers 404 or 403
164
+ * for a private repository it does not reach) or a pull request.
165
+ */
166
+ async function foreignIssue(sys, token, here, ref) {
167
+ const name = refName(ref, here);
168
+ const url = `${API}/repos/${ref.repo}/issues/${ref.number}`;
169
+ const { status, json } = await sys.http(url, { token });
170
+ const message = json?.message;
171
+ if (status === 404 || status === 403 || status === 401) {
172
+ return {
173
+ problem: `${name} cannot be read with this token (HTTP ${status}${message ? `: ${message}` : ''}): a slice in another repository counts only where the token reads that repository, and a workflow's GITHUB_TOKEN reads no private repository but ${here}`,
174
+ };
175
+ }
176
+ if (status !== 200)
177
+ throw new Error(`cannot read ${name}: ${message ?? `HTTP ${status}`} (${url.replace(API, '')})`);
178
+ const issue = json;
179
+ return issue.pull_request ? { problem: `${name} is a pull request, not an issue` } : { issue };
126
180
  }
127
181
  /**
128
- * Reads slice `slice` against the work rules' approvals: the problems that
182
+ * Reads slice `ref` against the work rules' approvals: the problems that
129
183
  * stop it outright (not a Slice under a Work item an owner approved), else
130
- * the decisions it owes an owner and whether each was given.
184
+ * the decisions it owes an owner and whether each was given. The slice may
185
+ * be in another repository than `here`, the one being pushed or checked:
186
+ * it is then read there, by the owners and agents `here`'s settings name,
187
+ * and the Approvals issue is the one that repository's settings name.
131
188
  */
132
- async function readSlice(sys, token, slug, slice, { owners, agents, approvals }) {
133
- const issue = await readIssue(sys, token, slug, slice);
189
+ async function readSlice(sys, token, here, ref, settings) {
190
+ const { owners, agents } = settings;
191
+ const { repo: slug, number: slice } = ref;
192
+ const foreign = !sameRepo(slug, here);
193
+ const nameOf = (number) => refName({ repo: slug, number }, here);
194
+ // How errors name the slice: a number here, `owner/name#N` from another repository.
195
+ const tag = foreign ? nameOf(slice) : slice;
196
+ let issue;
197
+ if (foreign) {
198
+ const read = await foreignIssue(sys, token, here, ref);
199
+ if (read.problem)
200
+ return { problems: [read.problem], owed: [] };
201
+ issue = read.issue;
202
+ }
203
+ else {
204
+ issue = await readIssue(sys, token, slug, slice);
205
+ }
134
206
  if (!issue)
135
207
  return { problems: [`#${slice} is not an issue in ${slug}`], owed: [] };
136
208
  if (issue.type?.name !== 'Slice')
137
- return { problems: [`#${slice} is not a Slice (its type is ${issue.type?.name ?? 'none'})`], owed: [] };
138
- const { parent, problem } = await parentOf(sys, token, issue);
209
+ return { problems: [`${nameOf(slice)} is not a Slice (its type is ${issue.type?.name ?? 'none'})`], owed: [] };
210
+ const { parent, problem } = await parentOf(sys, token, issue, nameOf);
139
211
  if (problem)
140
212
  return { problems: [problem], owed: [] };
141
213
  if (parent?.type?.name !== 'Work item')
142
- return { problems: [`#${slice} is not a sub-issue of a Work item`], owed: [] };
143
- const events = await every(sys, token, slice, `${parent.url}/timeline`);
214
+ return { problems: [`${nameOf(slice)} is not a sub-issue of a Work item`], owed: [] };
215
+ // Another repository's batch answers are on its own Approvals issue.
216
+ const approvals = foreign
217
+ ? await approvalsOf(sys, token, slug).catch(() => {
218
+ // fail-open: settings there that cannot be read name no Approvals issue, which only takes a way to pass away.
219
+ return undefined;
220
+ })
221
+ : settings.approvals;
222
+ const events = await every(sys, token, tag, `${parent.url}/timeline`);
144
223
  const approval = events
145
224
  .filter((event) => (event.event === 'labeled' || event.event === 'unlabeled') && event.label.name === 'approved')
146
225
  .at(-1);
147
226
  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: [] };
227
+ return { problems: [`work item ${nameOf(parent.number)}, ${issueUrl(slug, parent.number)}, is not approved: ${either(owners)} adds the approved label before any slice starts`], owed: [] };
149
228
  }
150
229
  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: [] };
230
+ return { problems: [`work item ${nameOf(parent.number)}, ${issueUrl(slug, parent.number)}, was labeled approved by ${approval.actor?.login ?? 'someone unknown'}, not ${either(owners)}`], owed: [] };
152
231
  }
153
232
  const approvedAt = approval.created_at;
154
233
  const parentComments = events.filter((event) => event.event === 'commented');
155
234
  // Every comment on the slice, so a proposal or decision that later discussion pushed back still counts.
156
- const comments = await every(sys, token, slice, `${issue.url}/comments`);
235
+ const comments = await every(sys, token, tag, `${issue.url}/comments`);
157
236
  // Every state, however many: one past the first page can be a dropped one.
158
- const states = await every(sys, token, slice, `${issue.url}/sub_issues`);
237
+ const states = await every(sys, token, tag, `${issue.url}/sub_issues`);
159
238
  // The Approvals issue's comments, read once a check and only when a decision owed may need them; an
160
239
  // Approvals issue GitHub cannot find answers nothing. Only an owner's comment whose first line approves
161
240
  // `number`, made after `since`, counts there.
@@ -163,7 +242,7 @@ async function readSlice(sys, token, slug, slice, { owners, agents, approvals })
163
242
  const batchFor = async (number, since) => {
164
243
  if (approvals === undefined)
165
244
  return [];
166
- batch ??= await every(sys, token, slice, `${API}/repos/${slug}/issues/${approvals}/comments`, true);
245
+ batch ??= await every(sys, token, tag, `${API}/repos/${slug}/issues/${approvals}/comments`, true);
167
246
  return batchAnswers(batch, owners, number, since);
168
247
  };
169
248
  const owed = [];
@@ -173,7 +252,7 @@ async function readSlice(sys, token, slug, slice, { owners, agents, approvals })
173
252
  .filter((event) => event.event === 'parent_issue_added')
174
253
  .map((event) => event.created_at);
175
254
  const mine = [
176
- ...(await joined(slice, issue.url)),
255
+ ...(await joined(tag, issue.url)),
177
256
  ...events.flatMap((event) => (event.event === 'sub_issue_added' && event.sub_issue?.number === slice ? [event.created_at] : [])),
178
257
  ];
179
258
  // An addition after approval that names no issue may be this slice's. It is put down to another sub-issue of the
@@ -181,10 +260,10 @@ async function readSlice(sys, token, slug, slice, { owners, agents, approvals })
181
260
  // slice's, so it owes the owner's say rather than passing.
182
261
  let hidden = events.flatMap((event) => event.event === 'sub_issue_added' && !event.sub_issue && event.created_at > approvedAt && !mine.includes(event.created_at) ? [event.created_at] : []);
183
262
  if (hidden.length > 0) {
184
- for (const sibling of await every(sys, token, slice, `${parent.url}/sub_issues`)) {
263
+ for (const sibling of await every(sys, token, tag, `${parent.url}/sub_issues`)) {
185
264
  if (sibling.number === slice || hidden.length === 0)
186
265
  continue;
187
- const theirs = await joined(slice, sibling.url);
266
+ const theirs = await joined(tag, sibling.url);
188
267
  hidden = hidden.filter((at) => !theirs.includes(at));
189
268
  }
190
269
  }
@@ -213,7 +292,7 @@ async function readSlice(sys, token, slug, slice, { owners, agents, approvals })
213
292
  // unedited decision on the slice settles it.
214
293
  const decisions = onSlice.some((one) => !editedAt(one))
215
294
  ? onSlice
216
- : [...onSlice, ...decisionsIn(await every(sys, token, slice, `${state.url}/comments`), owners), ...(await batchFor(state.number, state.closed_at))];
295
+ : [...onSlice, ...decisionsIn(await every(sys, token, tag, `${state.url}/comments`), owners), ...(await batchFor(state.number, state.closed_at))];
217
296
  owed.push({
218
297
  kind: 'dropped',
219
298
  number: state.number,
@@ -226,11 +305,11 @@ async function readSlice(sys, token, slug, slice, { owners, agents, approvals })
226
305
  // Reactions are read only for the proposals that could still settle something; a deleted proposal has none.
227
306
  const reactions = new Map();
228
307
  for (const proposal of owed.filter((one) => !one.settled).flatMap((one) => one.proposals)) {
229
- reactions.set(proposal.id, await every(sys, token, slice, `${API}/repos/${slug}/issues/comments/${proposal.id}/reactions?content=%2B1`, true));
308
+ reactions.set(proposal.id, await every(sys, token, tag, `${API}/repos/${slug}/issues/comments/${proposal.id}/reactions?content=%2B1`, true));
230
309
  }
231
310
  for (const one of owed)
232
311
  one.settled ||= thumbsUp(one.proposals, reactions, owners, one.since);
233
- return { problems: [], parent: parent.number, owed, closed: issue.state === 'closed', states };
312
+ return { problems: [], parent: parent.number, owed, closed: issue.state === 'closed', states, ...(approvals === undefined ? {} : { approvals }) };
234
313
  }
235
314
  /**
236
315
  * What is wrong with the States a pull request for slice `slice` names with
@@ -238,27 +317,69 @@ async function readSlice(sys, token, slug, slice, { owners, agents, approvals })
238
317
  * under the slice, and a pull request for a slice closed already, a fix,
239
318
  * must name the open State it is filed as.
240
319
  */
241
- function stateProblems(slice, closed, states, names) {
242
- const problems = names.flatMap((number) => states.some((state) => state.number === number && state.type?.name === 'State')
320
+ function stateProblems(slice, here, closed, states, names) {
321
+ const name = refName(slice, here);
322
+ // A State is a sub-issue of the slice, so it is in the slice's repository.
323
+ const ours = (ref) => sameRepo(ref.repo, slice.repo);
324
+ const problems = names.flatMap((ref) => ours(ref) && states.some((state) => state.number === ref.number && state.type?.name === 'State')
243
325
  ? []
244
- : [`#${number} is not a State under slice #${slice}; a "State: #N" line names a State sub-issue of the slice the pull request builds`]);
245
- const open = states.some((state) => names.includes(state.number) && state.type?.name === 'State' && state.state !== 'closed');
326
+ : [`${refName(ref, here)} is not a State under slice ${name}; a "State: #N" line names a State sub-issue of the slice the pull request builds`]);
327
+ const open = states.some((state) => names.some((ref) => ours(ref) && ref.number === state.number) && state.type?.name === 'State' && state.state !== 'closed');
246
328
  if (closed && !open) {
247
- problems.push(`#${slice} is closed, so this pull request is a fix: file it as a State under #${slice} and name it with a line "State: #N"`);
329
+ problems.push(`${name} is closed, so this pull request is a fix: file it as a State under ${name} and name it with a line "State: ${sameRepo(slice.repo, here) ? '#N' : `${slice.repo}#N`}"`);
248
330
  }
249
331
  return problems;
250
332
  }
251
- /** Why `owed` stops slice `slice`, and how the owner settles it. */
252
- function owedProblem(one, slice, parent, { owners, agents, approvals }) {
333
+ /**
334
+ * Why `owed` stops slice `slice`, and how the owner settles it; a slice in
335
+ * another repository than `here` is settled there, on its Approvals issue
336
+ * `approvals`.
337
+ */
338
+ function owedProblem(one, slice, here, parent, approvals, { owners, agents }) {
253
339
  const owner = either(owners);
254
340
  // The agent proposes as itself; with several, any of them.
255
341
  const agent = either(agents);
256
- const ask = `${one.note ? ` (${one.note})` : ''}${one.proposals.length > 0 ? '' : `; ${agent} proposes it with: ${proposeCommand(one.number)}`}`;
342
+ const at = (number) => (number === undefined ? '#undefined' : refName({ repo: slice.repo, number }, here));
343
+ const s = at(slice.number);
344
+ const where = sameRepo(slice.repo, here) ? '' : ` in a clone of ${slice.repo}`;
345
+ const ask = `${one.note ? ` (${one.note})` : ''}${one.proposals.length > 0 ? '' : `; ${agent} proposes it${where} with: ${proposeCommand(one.number)}`}`;
346
+ // Each place the owner acts, by its full address, so an agent passes on a link, never a bare number.
347
+ const issue = (number) => issueUrl(slice.repo, number);
348
+ // The comment the owner reacts to, where there is one; else the slice, where the proposal is to be posted.
349
+ const on = one.proposals.length > 0
350
+ ? `${agent}'s proposal${one.kind === 'added' ? '' : ' for it'}, ${newest(one.proposals).html_url}`
351
+ : `${agent}'s proposal${one.kind === 'added' ? '' : ' for it'} on ${s}, ${issue(slice.number)}`;
257
352
  // 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}"`;
353
+ const batch = approvals === undefined ? '' : `, or ${owner} comments on ${at(approvals)}, the Approvals issue, ${issue(approvals)}, with a first line "Decision: approve #${one.number}"`;
259
354
  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}`;
355
+ ? `${s} was added to work item ${at(parent)}, ${issue(parent)}, after its approval; ${owner} reacts 👍 on ${on}, or adds a "Decision:" comment naming #${slice.number} on ${issue(slice.number)}, or ${s} links ${owner}'s request for it on ${at(parent)}${batch}${ask}`
356
+ : `state ${at(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}`;
357
+ }
358
+ /** Issue `number`'s own address on GitHub, where the owner acts on it. */
359
+ export function issueUrl(slug, number) {
360
+ return `${GITHUB_WEB}/${slug}/issues/${number}`;
361
+ }
362
+ /** A pull request's own address on GitHub: GitHub's, else built from its number. */
363
+ export function pullUrl(slug, number, given) {
364
+ return typeof given === 'string' && given.startsWith('https://') ? given : `${GITHUB_WEB}/${slug}/pull/${number}`;
365
+ }
366
+ /**
367
+ * The command that deletes branch `ref` on origin, quoted where the shell
368
+ * would read it otherwise. A branch starting `-` or `+` is named in full,
369
+ * `refs/heads/…`, so git reads it neither as an option nor as a forced push.
370
+ */
371
+ export function deleteBranchCommand(ref) {
372
+ const target = /^[-+]/.test(ref) ? `refs/heads/${ref}` : ref;
373
+ return `git push origin --delete ${/^[\w./+-]+$/.test(target) ? target : `'${target.replaceAll("'", "'\\''")}'`}`;
374
+ }
375
+ /**
376
+ * Why `pull` stops another pull request for slice `slice`, with its address
377
+ * and, when it is superseded, what to do: close it and, for a branch in this
378
+ * repository (`here`), delete its branch, as an agent does itself.
379
+ */
380
+ function secondPull(slug, slice, pull, here) {
381
+ const remedy = here ? `close it and delete its branch: ${deleteBranchCommand(pull.head.ref)}` : 'close it';
382
+ return `${refName(slice, slug)} 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
383
  }
263
384
  /**
264
385
  * The work rules for building one slice, as problems; none means it may be
@@ -269,23 +390,26 @@ function owedProblem(one, slice, parent, { owners, agents, approvals }) {
269
390
  * request, whose States are in `mine.states`, each is a State under the slice
270
391
  * and a closed slice's names an open one.
271
392
  */
272
- export async function sliceProblems(sys, token, slug, slice, accounts, mine) {
393
+ export async function sliceProblems(sys, token, slug, which, accounts, mine) {
394
+ // A slice in this repository may be given by its number alone.
395
+ const slice = typeof which === 'number' ? { repo: slug, number: which } : which;
273
396
  const read = await readSlice(sys, token, slug, slice, accounts);
274
397
  if (read.problems.length > 0)
275
398
  return read.problems;
276
- const problems = read.owed.filter((one) => !one.settled).map((one) => owedProblem(one, slice, read.parent, accounts));
399
+ const problems = read.owed.filter((one) => !one.settled).map((one) => owedProblem(one, slice, slug, read.parent, read.approvals, accounts));
277
400
  if (mine.states)
278
- problems.push(...stateProblems(slice, read.closed ?? false, read.states ?? [], mine.states));
401
+ problems.push(...stateProblems(slice, slug, read.closed ?? false, read.states ?? [], mine.states));
279
402
  // The pull request being checked: by number, or by its branch in this repository (not a fork's of the same name).
280
403
  for (let page = 1;; page++) {
281
404
  const pulls = await sys.http(`${API}/repos/${slug}/pulls?state=open&per_page=100&page=${page}`, { token });
282
405
  if (pulls.status !== 200 || !Array.isArray(pulls.json))
283
406
  throw new Error(`cannot list open pull requests (HTTP ${pulls.status})`);
284
407
  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()))
408
+ const here = pull.head.repo?.full_name.toLowerCase() === slug.toLowerCase();
409
+ if (pull.number === mine.pull || (pull.head.ref === mine.branch && here))
286
410
  continue;
287
- if (slicesNamed(pull.body ?? '').includes(slice))
288
- problems.push(`#${slice} already has pull request #${pull.number}; one slice, one pull request`);
411
+ if (slicesNamed(pull.body ?? '', slug).some((one) => sameIssue(one, slice)))
412
+ problems.push(secondPull(slug, slice, pull, here));
289
413
  }
290
414
  if (pulls.json.length < 100)
291
415
  break;
@@ -356,18 +480,18 @@ export async function prWorkRules(sys, io) {
356
480
  return 0;
357
481
  }
358
482
  }
359
- const slices = slicesNamed(pull.body ?? '');
483
+ const slices = slicesNamed(pull.body ?? '', slug);
360
484
  if (slices.length !== 1) {
361
485
  return report(io, 'pr-work-rules', [
362
486
  slices.length === 0
363
487
  ? `#${pull.number} names no slice; add a line "Slice: #N" to its description`
364
- : `#${pull.number} names ${slices.length} slices (${slices.map((n) => `#${n}`).join(', ')}); an agent pull request builds exactly one`,
488
+ : `#${pull.number} names ${slices.length} slices (${slices.map((one) => refName(one, slug)).join(', ')}); an agent pull request builds exactly one`,
365
489
  ]);
366
490
  }
367
491
  const [slice] = slices;
368
- const problems = await sliceProblems(sys, token, slug, slice, accounts, { pull: pull.number, states: statesNamed(pull.body ?? '') });
492
+ const problems = await sliceProblems(sys, token, slug, slice, accounts, { pull: pull.number, states: statesNamed(pull.body ?? '', slug) });
369
493
  if (problems.length === 0)
370
- io.out(`✓ pr-work-rules: #${pull.number} builds slice #${slice}, which may be built`);
494
+ io.out(`✓ pr-work-rules: #${pull.number} builds slice ${refName(slice, slug)}, which may be built`);
371
495
  return report(io, 'pr-work-rules', problems);
372
496
  }
373
497
  const ZERO = /^0+$/;
@@ -495,14 +619,14 @@ export async function prePush(sys, io, refLines, url) {
495
619
  if (!log.trim())
496
620
  continue;
497
621
  // Asked of GitHub only when the push would be refused: what its merges brought from the default branch.
498
- if (branch && slicesNamed(log).length !== 1) {
622
+ if (branch && slicesNamed(log, slug).length !== 1) {
499
623
  const merged = await mergedFromDefault(sys, root, slug, token, branch, rangeOf(base));
500
624
  if (merged.length > 0) {
501
625
  base = [...base, ...merged];
502
626
  log = gitLog(sys, root, ['--format=%B', ...rangeOf(base)]);
503
627
  }
504
628
  }
505
- if (slicesNamed(log).length === 0) {
629
+ if (slicesNamed(log, slug).length === 0) {
506
630
  log = (base.length > 0 ? gitLog(sys, root, ['--format=%B', local, '--not', ...base]) : branchBeyondMerges(sys, root, rangeOf(base))) ?? log;
507
631
  }
508
632
  messages += `${log}\n`;
@@ -510,13 +634,13 @@ export async function prePush(sys, io, refLines, url) {
510
634
  }
511
635
  if (branches.length === 0)
512
636
  return 0;
513
- const slices = slicesNamed(messages);
637
+ const slices = slicesNamed(messages, slug);
514
638
  const where = branches.join(', ');
515
639
  if (slices.length !== 1) {
516
640
  return report(io, 'pre-push', [
517
641
  slices.length === 0
518
642
  ? `the commits for ${where} name no slice; add a trailer "Slice: #N" to a commit message`
519
- : `the commits for ${where} name ${slices.length} slices (${slices.map((n) => `#${n}`).join(', ')}); one push builds one slice`,
643
+ : `the commits for ${where} name ${slices.length} slices (${slices.map((one) => refName(one, slug)).join(', ')}); one push builds one slice`,
520
644
  ]);
521
645
  }
522
646
  if (branches.length > 1)
@@ -538,16 +662,17 @@ const CLOUD_PROXY_REFUSAL = /sessions are bound to their configured repositories
538
662
  * shared workflow's Slice started job moves the slice when its pull request
539
663
  * opens.
540
664
  */
541
- async function moveBoard(sys, io, token, slug, slice) {
665
+ async function moveBoard(sys, io, token, here, ref) {
666
+ const slice = refName(ref, here);
542
667
  try {
543
- for (const line of await boardStarted(sys, token, slug, slice))
668
+ for (const line of await boardStarted(sys, token, ref.repo, ref.number))
544
669
  io.err(line);
545
670
  }
546
671
  catch (error) {
547
672
  const message = error.message;
548
673
  io.err(CLOUD_PROXY_REFUSAL.test(message)
549
- ? `- board: this cloud session cannot reach the board; niyam's workflow moves #${slice} when its pull request opens`
550
- : `! board: could not read where #${slice} and its work item are on the board, so nothing moved (${message}); the push goes on`);
674
+ ? `- board: this cloud session cannot reach the board; niyam's workflow moves ${slice} when its pull request opens`
675
+ : `! board: could not read where ${slice} and its work item are on the board, so nothing moved (${message}); the push goes on`);
551
676
  }
552
677
  }
553
678
  /** Throws for a write to an issue that GitHub refused, saying how to fix a workflow that grants no issues: write. */
@@ -623,12 +748,23 @@ export async function prMerged(sys, io) {
623
748
  io.out(`pr-merged: #${pull.number} merged into ${pull.base.ref}, not ${branch}; its slices stay open until their work reaches ${branch}`);
624
749
  return 0;
625
750
  }
626
- const slices = slicesNamed(pull.body ?? '');
751
+ const slices = slicesNamed(pull.body ?? '', slug);
627
752
  if (slices.length === 0)
628
753
  io.out(`pr-merged: #${pull.number} names no slice; nothing to close`);
754
+ // A slice or State in another repository is closed there, by whoever builds the rest of it: this workflow's
755
+ // GITHUB_TOKEN writes only here, and never touches this repository's issue of the same number.
756
+ const elsewhere = (ref) => {
757
+ if (sameRepo(ref.repo, slug))
758
+ return false;
759
+ io.out(`- ${refName(ref, slug)} is in another repository; left as it is`);
760
+ return true;
761
+ };
629
762
  // The slices named that are Slices: a State is closed only under one of them.
630
763
  const built = [];
631
- for (const slice of slices) {
764
+ for (const ref of slices) {
765
+ if (elsewhere(ref))
766
+ continue;
767
+ const slice = ref.number;
632
768
  const issue = await readIssue(sys, token, slug, slice);
633
769
  if (issue?.type?.name !== 'Slice') {
634
770
  io.out(`- #${slice} is not a Slice in ${slug}; left as it is`);
@@ -638,7 +774,10 @@ export async function prMerged(sys, io) {
638
774
  // GitHub closes a slice itself when the pull request also says "Closes #N"; the slice still gets its comment, once.
639
775
  await closeBuilt(sys, io, token, issue, pull);
640
776
  }
641
- for (const number of statesNamed(pull.body ?? '')) {
777
+ for (const ref of statesNamed(pull.body ?? '', slug)) {
778
+ if (elsewhere(ref))
779
+ continue;
780
+ const { number } = ref;
642
781
  const issue = await readIssue(sys, token, slug, number);
643
782
  if (issue?.type?.name !== 'State') {
644
783
  io.out(`- #${number} is not a State in ${slug}; left as it is`);
@@ -697,31 +836,32 @@ export async function prStarted(sys, io) {
697
836
  io.out(offLine('pr-started', 'work-rules', PERSONAL_REPO));
698
837
  return 0;
699
838
  }
700
- const slices = slicesNamed(pull.body ?? '');
839
+ const slices = slicesNamed(pull.body ?? '', slug);
701
840
  if (slices.length !== 1) {
702
841
  io.out(`pr-started: #${pull.number} names ${slices.length === 0 ? 'no slice' : `${slices.length} slices`}; nothing moves on the board`);
703
842
  return 0;
704
843
  }
705
- const [slice] = slices;
844
+ const [ref] = slices;
845
+ const slice = refName(ref, slug);
706
846
  if (!board) {
707
- io.out(`pr-started: no board app token here (the NIYAM_BOARD_APP_ID and NIYAM_BOARD_APP_KEY secrets are not passed, or GitHub would not make the token), so #${slice} moves on the board only from a desktop push`);
847
+ io.out(`pr-started: no board app token here (the NIYAM_BOARD_APP_ID and NIYAM_BOARD_APP_KEY secrets are not passed, or GitHub would not make the token), so ${slice} moves on the board only from a desktop push`);
708
848
  return 0;
709
849
  }
710
850
  try {
711
- const problems = await sliceProblems(sys, token, slug, slice, loadSettings(sys, sys.cwd), { pull: pull.number, states: statesNamed(pull.body ?? '') });
851
+ const problems = await sliceProblems(sys, token, slug, ref, loadSettings(sys, sys.cwd), { pull: pull.number, states: statesNamed(pull.body ?? '', slug) });
712
852
  if (problems.length > 0) {
713
- io.out(`pr-started: #${slice} may not be built yet (Work rules says why), so nothing moves on the board`);
853
+ io.out(`pr-started: ${slice} may not be built yet (Work rules says why), so nothing moves on the board`);
714
854
  return 0;
715
855
  }
716
- const moved = await boardStarted(sys, board, slug, slice);
856
+ const moved = await boardStarted(sys, board, ref.repo, ref.number);
717
857
  for (const line of moved)
718
858
  io.out(line);
719
859
  if (moved.length === 0)
720
- io.out(`pr-started: #${slice} and its work item are where they belong on the board already`);
860
+ io.out(`pr-started: ${slice} and its work item are where they belong on the board already`);
721
861
  }
722
862
  catch (error) {
723
863
  // fail-open: the board never fails a pull request; Work rules judges the slice, and the line says what GitHub refused.
724
- io.out(`! board: nothing moved for #${slice} (${error.message}); the pull request's checks go on`);
864
+ io.out(`! board: nothing moved for ${slice} (${error.message}); the pull request's checks go on`);
725
865
  }
726
866
  return 0;
727
867
  }
@@ -765,13 +905,13 @@ function proposeCommand(number) {
765
905
  * argues it, and how to answer. What changes, why and what it costs live on
766
906
  * the page, from the slice's sections.
767
907
  */
768
- function proposalBody(one, parent, page, { owners, approvals }) {
908
+ function proposalBody(slug, one, parent, page, { owners, approvals }) {
769
909
  // The issue it is for comes first: that is how the work rules match a 👍 to it.
770
910
  const what = one.kind === 'added'
771
911
  ? `Proposal: add #${one.number} (${one.title}) to work item #${parent}.`
772
912
  : `Proposal: drop state #${one.number} (${one.title}), closed as not planned after work item #${parent}'s approval.`;
773
913
  // 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}`;
914
+ const batch = approvals === undefined ? '' : `, or answer the batch on Approvals, ${issueUrl(slug, approvals)}`;
775
915
  return `${what}\n\nPage: ${page}\n\n${either(owners.map((owner) => `@${owner}`))}: react 👍 to this comment to approve it, or comment "Decision:"${batch}.`;
776
916
  }
777
917
  /**
@@ -842,7 +982,7 @@ async function proposeOne(sys, io, token, slug, accounts, number, page) {
842
982
  return { code: report(io, 'propose', [problem]), waiting: [] };
843
983
  const state = parent?.type?.name === 'Slice';
844
984
  const slice = state ? parent.number : number;
845
- const read = await readSlice(sys, token, slug, slice, accounts);
985
+ const read = await readSlice(sys, token, slug, { repo: slug, number: slice }, accounts);
846
986
  if (read.problems.length > 0)
847
987
  return { code: report(io, 'propose', read.problems), waiting: [] };
848
988
  const owner = either(accounts.owners);
@@ -868,7 +1008,7 @@ async function proposeOne(sys, io, token, slug, accounts, number, page) {
868
1008
  };
869
1009
  }
870
1010
  // 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)]));
1011
+ const bodies = new Map(page === undefined ? [] : fresh.map((one) => [one, proposalBody(slug, one, read.parent, page, accounts)]));
872
1012
  const unfit = [...bodies].flatMap(([one, body]) => {
873
1013
  const problem = askProblem({ text: body, known: true, opensUnknown: false }, accounts.owners);
874
1014
  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.18",
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": {