@veda-hq/niyam 0.6.17 → 0.6.19

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
@@ -614,7 +614,14 @@ opening with `Needs you:` or `Proposal:`, on an issue, a pull request or a revie
614
614
  owner's `approved` label or `Decision:` comment takes the label off at once;
615
615
  on a pull request, where a label approves nothing (approvals are given on
616
616
  issues only), the owner answers with a `Decision:` comment, which takes it
617
- off at once, or a 👍 on the ask, which the hourly sweep counts. The sweep
617
+ off at once, or a 👍 on the ask, which the hourly sweep counts. The owner
618
+ may answer an ask on an issue while its own run is still going, before the
619
+ label is on: that run reads the owner's `approved` label, a `Decision:` that
620
+ no one but owners edited, a 👍 on the ask, or a batch answer on the
621
+ Approvals issue whose first line names the ask's issue (for a `Proposal:`,
622
+ the issue its first line names) that no one but owners edited, each newer
623
+ than the ask, before it labels the issue and again after, and leaves the
624
+ label off when one is there. The sweep
618
625
  reads an issue's or pull request's own comments, not review threads, so an
619
626
  ask in a review thread is answered with a `Decision:` reply there. Hourly
620
627
  (cron `41 * * * *`), on a run by hand, and at once when the owner posts a
@@ -797,7 +804,16 @@ be recorded is refused (exit 3). Every answer is kept in
797
804
  log), so GitHub is asked once per pushed commit. A session's hook reaches
798
805
  GitHub as the session's agent, with every check `as-agent` makes, and the
799
806
  watcher with the push's own token. Its own errors never fail a push or hold
800
- a session. The settings:
807
+ a session.
808
+
809
+ `refuse-retired --root <repo> --remote <name>`, which the pre-push hook runs
810
+ before its expensive checks with the same ref lines, refuses (exit 3) a push to
811
+ a branch whose pull request merged while none is open. Such a push recreates a
812
+ branch the merge retired, and the commits after the merge land in no pull
813
+ request. The refusal names the way out. A branch GitHub cannot answer for, or
814
+ one with a full page of pull requests (which may hide the open one), only
815
+ warns. Exit 4 means it could not check at all; a hook reports that as not
816
+ checked. The settings:
801
817
 
802
818
  ```json
803
819
  { "prAutocreate": { "base": "main", "draft": false, "protected": ["main", "master", "develop", "prod", "production"], "skip": ["mergify/", "gh-readonly-queue/"], "optOut": [], "describe": "`gh pr edit --body-file`" } }
@@ -806,7 +822,8 @@ a session. The settings:
806
822
  `optOut` names older opt-out variables read beside `NIYAM_PR_AUTOCREATE`;
807
823
  `describe` says how the pushing session writes the real description;
808
824
  `retired`, a link, explains why a merged pull request retires its branch;
809
- `footer` ends the placeholder body.
825
+ `retire`, a command with `{number}` for the merged pull request, is the way out
826
+ `refuse-retired` names; `footer` ends the placeholder body.
810
827
 
811
828
  **Started work runs to merge.** `niyam keep-going`, Claude Code's Stop hook,
812
829
  sends a session back while its branch has commits the base lacks and its
@@ -1281,7 +1298,10 @@ niyam owner-step required-checks <owner/repo> <ruleset id or name> [--check <nam
1281
1298
  when it reported `success` on the head commit of the last pull request
1282
1299
  merged into the default branch, from one app alone, and requires it from
1283
1300
  that app. That shows pull requests run it and it passes. One that never
1284
- ran there, did not pass, or that two apps reported is a `✗`. A check a
1301
+ ran there, did not pass, or that two apps reported is a `✗`. A
1302
+ `cancelled` run counts for nothing when a run from the same app started
1303
+ after it and passed, as a workflow with `cancel-in-progress` leaves
1304
+ one when a pull request is edited or pushed again. A check a
1285
1305
  workflow runs only for some paths can pass there and then never report
1286
1306
  on a pull request that skips them, holding it: name only checks that run
1287
1307
  on every pull request.
@@ -1319,15 +1339,25 @@ is a slice the owner approves.
1319
1339
 
1320
1340
  ### Releases and upgrading
1321
1341
 
1322
- Each release is a tag `vX.Y.Z` on `main`, matching `package.json`; the
1323
- Release workflow checks both, runs `pnpm check` and publishes the GitHub
1324
- release, attaching the CLI package it built and tested. From 0.6.16 the same
1342
+ A release is the merge of its version bump: a push to `main` whose
1343
+ `package.json` version has no tag `vX.Y.Z` yet (P-61). The Release workflow
1344
+ then runs `pnpm check`, makes that annotated tag (`niyam X.Y.Z`) on the
1345
+ merged commit itself, and publishes the GitHub release, attaching the CLI
1346
+ package it built and tested. Agents push no release tags. The tag is made as
1347
+ niyam's own GitHub App, the one bypass of the `v*` tag ruleset's rule against
1348
+ creating a tag, so no one else, and no other workflow, can make one (P-64);
1349
+ the app's client id and private key are the `npm` environment's
1350
+ `RELEASE_APP_CLIENT_ID` and `RELEASE_APP_PRIVATE_KEY`. From 0.6.16 the same
1325
1351
  package is on npm as `@veda-hq/niyam`, with provenance, for a repository that
1326
- pins it as an exact version. Install the attached package on each machine with
1327
- pnpm, once; nothing is built on install:
1352
+ pins it as an exact version; it publishes from the `npm` environment, which
1353
+ only `main` may deploy to. A tag on any other commit is not a release:
1354
+ `niyam upgrade` and `niyam onboard` ask GitHub's compare API, with no token,
1355
+ whether the tag's commit is on `main`, and refuse one that is not, naming the
1356
+ tag and the commit. Install the attached package on each machine with pnpm,
1357
+ once; nothing is built on install:
1328
1358
 
1329
1359
  ```bash
1330
- pnpm add -g https://github.com/veda-hq/niyam/releases/download/v0.6.17/veda-hq-niyam-0.6.17.tgz
1360
+ pnpm add -g https://github.com/veda-hq/niyam/releases/download/v0.6.19/veda-hq-niyam-0.6.19.tgz
1331
1361
  ```
1332
1362
 
1333
1363
  The package puts one command on `PATH`, `niyam`. Since P-57 a release
@@ -1343,11 +1373,11 @@ niyam upgrade
1343
1373
  ```
1344
1374
 
1345
1375
  `upgrade` asks GitHub's public releases API for the newest release, with no
1346
- token and no sign-in, and when it is newer than the CLI running, installs it
1347
- with the same `pnpm add -g`, printing old → new and the version the shell then
1376
+ token and no sign-in, and when it is newer than the CLI running and its tag's
1377
+ commit is on `main`, installs it with the same `pnpm add -g`, printing old → new and the version the shell then
1348
1378
  runs. On the newest release it says so and installs nothing; it never moves
1349
1379
  back to an older one. When GitHub cannot be reached, or a newer release has no
1350
- package attached yet, or pnpm fails, it says which and exits 1, checking
1380
+ package attached yet, or its tag is not on `main`, or pnpm fails, it says which and exits 1, checking
1351
1381
  nothing more. After an install, or when there was nothing to install, it walks
1352
1382
  `PATH`, as `type -a niyam` does, reading an empty or relative entry
1353
1383
  against the current folder as the shell does. It exits 0 when exactly one
@@ -1362,7 +1392,10 @@ newest release with the line above. `onboard`, when the repo pins a newer releas
1362
1392
  CLI running, refuses and says to run `niyam upgrade` first.
1363
1393
 
1364
1394
  `onboard` pins the client's workflow to one version, the release of the CLI
1365
- that ran it. Each job writes the pin twice, `checks.yml@vX.Y.Z` and, two lines
1395
+ that ran it, and writes `.github/niyam/cloud-setup.sh` at the same one. First
1396
+ it asks GitHub's compare API, with no token, whether that release's tag is on
1397
+ `main`; when it is not, or GitHub cannot say, it refuses and changes nothing.
1398
+ Each job writes the pin twice, `checks.yml@vX.Y.Z` and, two lines
1366
1399
  below it under `with:`, `niyam-ref: vX.Y.Z`, the one input `checks.yml`
1367
1400
  declares; GitHub refuses a caller that passes an input the called workflow
1368
1401
  does not declare, `process-rules-ref` too since P-57. Every job of
@@ -1398,6 +1431,46 @@ functions, 90% branches), builds `dist/` and runs it. `pnpm scan:secrets` runs
1398
1431
  Gitleaks and TruffleHog over the working tree; CI runs both over the whole
1399
1432
  history.
1400
1433
 
1434
+ ### Guard
1435
+
1436
+ The `guard` workflow (`.github/workflows/guard.yml`) runs on
1437
+ `pull_request_target`, so GitHub runs it from `main`'s copy, never the pull
1438
+ request's. Its job, `Guard`, checks out `main` alone, reads the pull
1439
+ request's changed files from GitHub's API as data, and runs
1440
+ `scripts/guard.mjs` (tested in `scripts/guard.test.mjs`). A change to a guard
1441
+ file passes only when the pull request's slice names it in a `**Guards:**`
1442
+ section, one already in the slice when the owner put `approved` on its Work
1443
+ item (for a slice added later, when the owner's `Decision:` settled it):
1444
+
1445
+ ```markdown
1446
+ **Guards:** `.github/workflows/ci.yml`, `scripts/*.mjs`, `.githooks/`
1447
+ ```
1448
+
1449
+ A name is a path, a folder ending in `/`, or a pattern where `*` matches
1450
+ within one folder and `**` across them. The guard files are everything under
1451
+ `.github/`, `.githooks/`, `.dvara.json`, `.dvara/records-baseline.json`,
1452
+ `.gitleaks.toml`, `.trufflehog-exclude`, the `scripts` of `package.json`,
1453
+ and `scripts/*.mjs`. A test file needs naming too when a pull request
1454
+ deletes it, leaves it fewer `test(`/`it(` calls than the merge base, or adds
1455
+ `.skip`, `.only` or `todo`.
1456
+
1457
+ Two changes pass unnamed: an onboard pull request
1458
+ (`chore(niyam): onboard at vX.Y.Z`) whose every changed line only moves the
1459
+ niyam version, and a sha256 with it, to that release, tagged on `main`; and a
1460
+ Dependabot pull request whose every changed line only moves a `uses:` to
1461
+ another full commit sha with its version comment. Whatever the slice says,
1462
+ Guard refuses a pull request that adds a job reporting a check the `main`
1463
+ ruleset requires, or `Guard`. It fails closed: a truncated file list, or any
1464
+ read GitHub does not answer, refuses. Each refusal names the file and how to
1465
+ pass. A slice edit does not run Guard again: edit or push the pull request.
1466
+
1467
+ Guard cannot judge a change to its own rules, so `.github/CODEOWNERS` names
1468
+ `@AlokBansal8` for the guard's files alone: `.github/workflows/guard.yml`,
1469
+ `scripts/guard.mjs`, `scripts/guard.test.mjs` and `.github/CODEOWNERS`
1470
+ itself. With "Require review from Code Owners" on in the `main` ruleset, a
1471
+ pull request that changes one of them waits for his approval. Every other
1472
+ pull request, including one under `.github/` that Guard passed, does not.
1473
+
1401
1474
  ## License
1402
1475
 
1403
1476
  MIT
package/dist/asks.js CHANGED
@@ -354,6 +354,35 @@ async function answered(sys, token, slug, number, { owners, agents, approvals },
354
354
  const waiting = owed.filter((one) => !how.has(one));
355
355
  return waiting.length > 0 ? { waiting } : { answer: [...new Set(how.values())].join(' and ') };
356
356
  }
357
+ /**
358
+ * How the owner has answered issue `number` since the ask `ask`, the ask's
359
+ * own run reading it, or undefined: their `approved` label, a `Decision:`
360
+ * comment no one but owners edited, a 👍 on the ask, or a batch answer on
361
+ * the Approvals issue whose first line names `ask.names` (the issue a
362
+ * proposal's first line names, as the sweep reads it) that no one but owners
363
+ * edited, each newer than the ask. The owner's approval and batch answer run
364
+ * their own jobs, which take off only a label already on, so an ask whose run
365
+ * labels the issue after that answer reads it here (#355, #357).
366
+ */
367
+ async function answeredSince(sys, token, slug, number, ask, { owners, approvals }) {
368
+ const owner = (login) => anyLogin(owners, login);
369
+ const events = await every(sys, token, `${API}/repos/${slug}/issues/${number}/events`);
370
+ const approved = events.some((one) => one.event === 'labeled' && one.label?.name === 'approved' && owner(one.actor?.login ?? undefined) && (one.created_at ?? '') > ask.created_at);
371
+ if (approved)
372
+ return 'their approved label';
373
+ const comments = await every(sys, token, `${API}/repos/${slug}/issues/${number}/comments?since=${encodeURIComponent(ask.created_at)}`);
374
+ const decisions = comments.filter((comment) => comment.created_at > ask.created_at && owner(comment.user?.login ?? undefined) && opensDecision(comment.body ?? ''));
375
+ if (decisions.length > 0 && (await ownersAlone(sys, token, decisions, owners)).kept.length > 0)
376
+ return 'a Decision: comment';
377
+ const reactions = await every(sys, token, `${API}/repos/${slug}/issues/comments/${ask.id}/reactions?content=%2B1`);
378
+ if (reactions.some((reaction) => owner(reaction.user?.login ?? undefined) && reaction.created_at > ask.created_at))
379
+ return 'a 👍 on the ask';
380
+ // The Approvals issue is read last, only when the issue itself has no answer, and none where GitHub cannot find it.
381
+ if (approvals === undefined)
382
+ return undefined;
383
+ 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
+ return answers.length > 0 && (await ownersAlone(sys, token, answers, owners)).kept.length > 0 ? `a "Decision: approve" on #${approvals}, the Approvals issue` : undefined;
385
+ }
357
386
  /** The asks still waiting, as the sweep names them. */
358
387
  function waitingOn(waiting) {
359
388
  return waiting.map(({ kind, number }) => (kind === 'Proposal' ? `the proposal for #${number}` : 'the Needs you: ask')).join(', ');
@@ -431,10 +460,27 @@ export async function needsOwner(sys, io) {
431
460
  if ((name === 'issue_comment' || name === 'pull_request_review_comment') && issue !== undefined) {
432
461
  const author = event.comment?.user?.login ?? undefined;
433
462
  const body = event.comment?.body ?? '';
434
- if (event.action === 'created' && anyLogin(settings.agents, author) && opensAsk(body)) {
463
+ const kind = opensAsk(body);
464
+ if (event.action === 'created' && anyLogin(settings.agents, author) && kind) {
465
+ // The owner may answer while this run is still going: read their answer before labelling, and again after,
466
+ // since their approval's run takes off only a label its event shows. An issue's comment alone is read, by its id and time.
467
+ const { id, created_at } = event.comment ?? {};
468
+ const names = kind === 'Proposal' ? (firstIssue(body.split(/\r?\n/, 1)[0]) ?? issue) : issue;
469
+ const ask = !labelled && name === 'issue_comment' && id !== undefined && created_at ? { id, created_at, names } : undefined;
470
+ const before = ask ? await answeredSince(sys, token, slug, issue, ask, settings) : undefined;
471
+ if (before) {
472
+ io.out(`needs-owner: #${issue} asks the owner (${kind}:), and the owner already answered with ${before}; not labelled ${NEEDS_OWNER}`);
473
+ return 0;
474
+ }
435
475
  if (!labelled)
436
476
  await addLabel(sys, token, slug, issue);
437
- io.out(`needs-owner: #${issue} asks the owner (${opensAsk(body)}:); labelled ${NEEDS_OWNER}`);
477
+ const after = ask ? await answeredSince(sys, token, slug, issue, ask, settings) : undefined;
478
+ if (after) {
479
+ await removeLabel(sys, token, slug, issue);
480
+ io.out(`needs-owner: #${issue} asks the owner (${kind}:), and the owner answered with ${after} as it was labelled; ${NEEDS_OWNER} taken off`);
481
+ return 0;
482
+ }
483
+ io.out(`needs-owner: #${issue} asks the owner (${kind}:); labelled ${NEEDS_OWNER}`);
438
484
  return 0;
439
485
  }
440
486
  // The owner's batch answer on the Approvals issue names a proposal's own issue, such as a dropped State, not
package/dist/onboard.js CHANGED
@@ -8,6 +8,7 @@ import { HOURLY } from './asks.js';
8
8
  import { DEFAULT_SCHEDULE, FEATURES, FIGMA_FILE_KEY, NEEDS_ISSUE_TYPES, featuresIn, parseFeatures, renamedLines, scheduleIn } from './features.js';
9
9
  import { CLOUD_SETUP_PATH, HOOKS_PATH, LEFTOVER_CLOUD_SETUP_PATH, ONBOARD_BRANCH, WORKFLOW_PATH, autoMerge, mergeQueue, openPull, remoteFile, } from './onboard-pull.js';
10
10
  import { cloudRepoScript, cloudScriptVersion, releaseSha256 } from './cloud.js';
11
+ import { tagOnMain } from './release-tag.js';
11
12
  import { setSecret } from './secrets.js';
12
13
  import { UPGRADE } from './upgrade.js';
13
14
  import { isNewer, packageVersion } from './version.js';
@@ -935,6 +936,12 @@ export async function onboard(sys, io, args = []) {
935
936
  const aheadHere = newerPinHere(fileAt, version);
936
937
  if (aheadHere !== undefined)
937
938
  return refuseOlder(io, slug, aheadHere, version);
939
+ // The workflow and cloud-setup.sh pin this release: a tag off main is not one (P-61).
940
+ const onMain = await tagOnMain(sys, version);
941
+ if ('problem' in onMain) {
942
+ io.err(`onboard: ${onMain.problem}; nothing changed`);
943
+ return 1;
944
+ }
938
945
  // The plan, by group, and the steps that carry it out after the yes.
939
946
  const pull = [];
940
947
  const github = [];
@@ -322,12 +322,24 @@ function workflowJobs(gh, repo) {
322
322
  }
323
323
  /** How many recently updated pull requests are searched for the last one merged. */
324
324
  const RECENT_PULLS = 30;
325
+ /**
326
+ * `runs` without the cancelled ones a later run replaced: a `cancelled`
327
+ * run is left out when a run from the same app started after it and
328
+ * concluded `success`. A workflow with `cancel-in-progress` cancels the
329
+ * run an edit or a push replaced, in another check suite, so both are
330
+ * latest runs of the name (#358). A cancelled run nothing replaced stays.
331
+ */
332
+ function superseded(runs) {
333
+ const at = (one) => (typeof one.started_at === 'string' ? one.started_at : '');
334
+ return runs.filter((one) => one.conclusion !== 'cancelled' || !runs.some((other) => other.conclusion === 'success' && other.app?.id === one.app?.id && at(other) > at(one) && at(one) !== ''));
335
+ }
325
336
  /**
326
337
  * Whether each named check reported `success` on the head commit of the
327
338
  * last pull request merged into the default branch, and from which app.
328
339
  * A check that does is one pull requests run, so a ruleset requiring it
329
340
  * holds none; one that does not might never report on a pull request. Two
330
341
  * apps reporting the same name is refused: the ruleset requires one app's.
342
+ * A cancelled run a later success replaced does not count (`superseded`).
331
343
  */
332
344
  function passedOnPull(gh, repo, names) {
333
345
  const found = new Map();
@@ -352,7 +364,7 @@ function passedOnPull(gh, repo, names) {
352
364
  continue;
353
365
  }
354
366
  const runs = (answer.json?.check_runs ?? []);
355
- const named = runs.filter((one) => one.name === name);
367
+ const named = superseded(runs.filter((one) => one.name === name));
356
368
  // Every latest run of that name passed, all from one app.
357
369
  const apps = [...new Set(named.map((one) => one.app?.id))];
358
370
  const app = apps[0];
@@ -35,10 +35,10 @@ export function autocreateSettings(raw) {
35
35
  return { ...DEFAULTS };
36
36
  if (typeof value !== 'object' || value === null || Array.isArray(value))
37
37
  throw new Error(`${where} must be an object`);
38
- const { base = DEFAULTS.base, draft = DEFAULTS.draft, protected: guarded = DEFAULTS.protected, skip = DEFAULTS.skip, optOut = DEFAULTS.optOut, describe, retired, footer, ...rest } = value;
38
+ const { base = DEFAULTS.base, draft = DEFAULTS.draft, protected: guarded = DEFAULTS.protected, skip = DEFAULTS.skip, optOut = DEFAULTS.optOut, describe, retired, retire, footer, ...rest } = value;
39
39
  const extra = Object.keys(rest)[0];
40
40
  if (extra !== undefined)
41
- throw new Error(`${where} has an unknown key "${extra}"; it takes "base", "draft", "protected", "skip", "optOut", "describe", "retired" and "footer"`);
41
+ throw new Error(`${where} has an unknown key "${extra}"; it takes "base", "draft", "protected", "skip", "optOut", "describe", "retired", "retire" and "footer"`);
42
42
  if (typeof base !== 'string' || !BRANCH.test(base))
43
43
  throw new Error(`${where}.base must be a branch name`);
44
44
  if (typeof draft !== 'boolean')
@@ -54,8 +54,11 @@ export function autocreateSettings(raw) {
54
54
  const page = line(retired, 'retired');
55
55
  if (page !== undefined && !/^https:\/\/\S+$/.test(page))
56
56
  throw new Error(`${where}.retired must be an https link`);
57
+ const way = line(retire, 'retire');
58
+ if (way !== undefined && !way.includes('{number}'))
59
+ throw new Error(`${where}.retire must name the merged pull request as {number}`);
57
60
  const last = line(footer, 'footer');
58
- return { ...settings, ...(page === undefined ? {} : { retired: page }), ...(last === undefined ? {} : { footer: last }) };
61
+ return { ...settings, ...(page === undefined ? {} : { retired: page }), ...(way === undefined ? {} : { retire: way }), ...(last === undefined ? {} : { footer: last }) };
59
62
  }
60
63
  /** The settings in the repository at `root`; the defaults where it has no settings file. */
61
64
  export function settingsAt(sys, root) {
@@ -102,6 +105,19 @@ export function statePath(root, branch) {
102
105
  export function optoutPath(root, branch) {
103
106
  return statePath(root, branch).replace(/\.json$/, '.optout');
104
107
  }
108
+ /** How many pull requests one listing of a branch asks for. */
109
+ export const PR_LIST_LIMIT = 20;
110
+ /**
111
+ * The merged pull request that retired a branch, given its pull requests, or
112
+ * undefined. A branch with an open one is live whatever merged before it; one
113
+ * whose pull requests only closed unmerged was never retired. ensurePr opens
114
+ * none for a retired branch, and refuse-retired refuses a push to one.
115
+ */
116
+ export function retiredBy(pulls) {
117
+ if (pulls.some((pull) => pull.state === 'OPEN'))
118
+ return undefined;
119
+ return pulls.find((pull) => pull.state === 'MERGED');
120
+ }
105
121
  function loadState(sys, root, branch) {
106
122
  try {
107
123
  const value = JSON.parse(sys.read(statePath(root, branch)));
@@ -259,8 +275,17 @@ export class Pulls {
259
275
  }
260
276
  /** The branch's pull requests, newest first; a string says why they could not be listed. */
261
277
  async list(branch) {
278
+ const listed = await this.listing(branch);
279
+ return typeof listed === 'string' ? listed : listed.pulls;
280
+ }
281
+ /**
282
+ * The branch's pull requests, newest first, and whether GitHub's page was
283
+ * full (`PR_LIST_LIMIT` entries before any was dropped), so it may hold
284
+ * back more; a string says why they could not be listed.
285
+ */
286
+ async listing(branch) {
262
287
  const owner = this.slug.split('/')[0];
263
- const got = await this.call('GET', `pulls?head=${encodeURIComponent(`${owner}:${branch}`)}&state=all&per_page=20`);
288
+ const got = await this.call('GET', `pulls?head=${encodeURIComponent(`${owner}:${branch}`)}&state=all&per_page=${PR_LIST_LIMIT}`);
264
289
  if (typeof got === 'string')
265
290
  return got;
266
291
  if (got.status !== 200)
@@ -278,7 +303,7 @@ export class Pulls {
278
303
  if (head === branch)
279
304
  pulls.push(pull);
280
305
  }
281
- return pulls;
306
+ return { pulls, full: got.json.length >= PR_LIST_LIMIT };
282
307
  }
283
308
  /** Opens a pull request: it, or "none ahead" when the branch adds nothing, or why it could not. */
284
309
  async create(branch, base, title, body, draft) {
@@ -348,7 +373,7 @@ export async function ensurePr(sys, root, settings, branch, sha, pulls) {
348
373
  if (typeof listed === 'string')
349
374
  return { problem: `could not list PRs for ${branch} (${listed}); will retry` };
350
375
  const open = listed.find((pull) => pull.state === 'OPEN');
351
- const merged = listed.find((pull) => pull.state === 'MERGED');
376
+ const merged = retiredBy(listed);
352
377
  let pr = null;
353
378
  let created = false;
354
379
  const notes = [];
@@ -686,6 +711,98 @@ function flags(args, names) {
686
711
  }
687
712
  return found;
688
713
  }
714
+ /**
715
+ * The branches git's pre-push ref lines update on the remote, in order: each
716
+ * refs/heads/* destination with a real local commit. A deletion (an all-zero
717
+ * local sha), a tag and a line that is not a ref line name none. The branch
718
+ * is the remote ref, the pull request's head: `git push origin HEAD:x` pushes x.
719
+ */
720
+ export function pushedRefs(stdin) {
721
+ const refs = [];
722
+ for (const each of stdin.split('\n')) {
723
+ const parts = each.trim().split(/\s+/);
724
+ if (parts.length !== 4)
725
+ continue;
726
+ const [, localSha, remoteRef, remoteSha] = parts;
727
+ if (ZERO_SHA.test(localSha) || !remoteRef.startsWith('refs/heads/'))
728
+ continue;
729
+ refs.push({ localSha, branch: remoteRef.slice('refs/heads/'.length), remoteSha });
730
+ }
731
+ return refs;
732
+ }
733
+ /** refuse-retired's exits: a push to a retired branch, and a check that crashed. */
734
+ export const RETIRED_REFUSAL = 3;
735
+ export const RETIRED_UNCHECKED = 4;
736
+ /**
737
+ * The pre-push hook's check before its expensive ones, git's ref lines on
738
+ * stdin. A push to a branch whose pull request already merged, with none
739
+ * open, recreates a branch the merge retired, and its commits then sit in no
740
+ * pull request: RETIRED_REFUSAL names each such branch and the way out. A
741
+ * branch GitHub cannot answer for warns in one line and refuses nothing, as
742
+ * every other path here fails open; so does a listing as long as one page,
743
+ * which may hold back the open pull request that keeps the branch live.
744
+ */
745
+ export async function refuseRetired(sys, io, args, stdin, pullsOf = pullsFor) {
746
+ const unchecked = (why) => {
747
+ io.out(`⚠️ Could not check whether a pushed branch's PR already merged (${why}); not checked.`);
748
+ return RETIRED_UNCHECKED;
749
+ };
750
+ let root;
751
+ let remote;
752
+ try {
753
+ const given = flags(args, ['--root', '--remote']);
754
+ const named = given.get('--root');
755
+ if (!named)
756
+ throw new Error('refuse-retired needs --root <repository>');
757
+ root = named;
758
+ remote = given.get('--remote') ?? '';
759
+ }
760
+ catch (error) {
761
+ return unchecked(error instanceof Error ? error.message : String(error));
762
+ }
763
+ // A workflow's push is not a session reviving a branch, and its token answers for no worktree.
764
+ if (sys.env.CI || remote !== REMOTE)
765
+ return 0;
766
+ let settings;
767
+ try {
768
+ settings = settingsAt(sys, root);
769
+ }
770
+ catch (error) {
771
+ return unchecked(error instanceof Error ? error.message : String(error));
772
+ }
773
+ const branches = [...new Set(pushedRefs(stdin).map((ref) => ref.branch).filter((branch) => eligible(settings, branch)))];
774
+ if (branches.length === 0)
775
+ return 0;
776
+ const pulls = pullsOf(sys, root, undefined);
777
+ const retired = [];
778
+ const skip = (branch, why) => io.out(`⚠️ Could not ask GitHub whether ${branch}'s PR already merged (${why}); not checked.`);
779
+ for (const branch of branches) {
780
+ const listed = 'problem' in pulls ? pulls.problem : await pulls.listing(branch);
781
+ if (typeof listed === 'string') {
782
+ skip(branch, listed);
783
+ continue;
784
+ }
785
+ if (listed.full) {
786
+ skip(branch, `GitHub listed ${PR_LIST_LIMIT} or more PRs, more than one page shows`);
787
+ continue;
788
+ }
789
+ const pull = retiredBy(listed.pulls);
790
+ if (pull)
791
+ retired.push([branch, pull.number]);
792
+ }
793
+ for (const [branch, number] of retired) {
794
+ io.out(`❌ Error: ${branch} already has MERGED PR #${number} and no open PR. Pushing it`);
795
+ io.out(' recreates a branch the merge retired, and the commits after the merge land in no PR.');
796
+ if (settings.retire) {
797
+ io.out(' Retire it: move the commits missing from the PR head to a fresh branch, then push that:');
798
+ io.out(` ${settings.retire.replaceAll('{number}', String(number))}`);
799
+ }
800
+ else {
801
+ io.out(` Move the commits missing from the PR head to a fresh branch, then push that${settings.retired ? ` (${settings.retired})` : ''}.`);
802
+ }
803
+ }
804
+ return retired.length > 0 ? RETIRED_REFUSAL : 0;
805
+ }
689
806
  /**
690
807
  * The pre-push hook's half, git's ref lines on stdin: records each pushed
691
808
  * branch's opt-out before the refs are sent, then starts one detached watcher
@@ -720,14 +837,7 @@ export async function spawnWatchers(sys, io, args, stdin) {
720
837
  const opted = optedOutNow(sys, settings);
721
838
  const names = [OPT_OUT_VAR, ...settings.optOut].join(' or ');
722
839
  const started = [];
723
- for (const each of stdin.split('\n')) {
724
- const parts = each.trim().split(/\s+/);
725
- if (parts.length !== 4)
726
- continue;
727
- const [, localSha, remoteRef, remoteSha] = parts;
728
- if (ZERO_SHA.test(localSha) || !remoteRef.startsWith('refs/heads/'))
729
- continue;
730
- const branch = remoteRef.slice('refs/heads/'.length);
840
+ for (const { localSha, branch, remoteSha } of pushedRefs(stdin)) {
731
841
  if (!eligible(settings, branch))
732
842
  continue;
733
843
  // Written before the refs are sent, so no turn-end hook sees the push land without it.
@@ -846,7 +956,7 @@ export async function watch(sys, io, args, pullsOf = pullsFor) {
846
956
  await sys.sleep(parsed.retryInterval * 1000);
847
957
  }
848
958
  }
849
- /** `niyam pr-autocreate <claude-hook | spawn-watchers | watch> ...`: never a usage exit, which would hold a hook. */
959
+ /** `niyam pr-autocreate <claude-hook | spawn-watchers | refuse-retired | watch> ...`: never a usage exit, which would hold a hook. */
850
960
  export async function prAutocreate(sys, io, args) {
851
961
  const [mode, ...rest] = args;
852
962
  try {
@@ -854,13 +964,21 @@ export async function prAutocreate(sys, io, args) {
854
964
  return await claudeHook(sys, io, sys.readStdin());
855
965
  if (mode === 'spawn-watchers')
856
966
  return await spawnWatchers(sys, io, rest, sys.readStdin());
967
+ if (mode === 'refuse-retired')
968
+ return await refuseRetired(sys, io, rest, sys.readStdin());
857
969
  if (mode === 'watch')
858
970
  return await watch(sys, io, rest);
859
- io.err(`pr-autocreate: unknown mode "${mode ?? ''}"; it takes claude-hook, spawn-watchers or watch; nothing done`);
971
+ io.err(`pr-autocreate: unknown mode "${mode ?? ''}"; it takes claude-hook, spawn-watchers, refuse-retired or watch; nothing done`);
860
972
  return 0;
861
973
  }
862
974
  catch (error) {
863
- io.err(`pr-autocreate: unexpected error (${error instanceof Error ? error.message : String(error)}); nothing done`);
975
+ const why = error instanceof Error ? error.message : String(error);
976
+ // A crash is not "not retired": the hook reports RETIRED_UNCHECKED as not checked, never the 0 of a live branch.
977
+ if (mode === 'refuse-retired') {
978
+ io.out(`⚠️ Could not check whether a pushed branch's PR already merged (pr-autocreate crashed: ${why}); not checked.`);
979
+ return RETIRED_UNCHECKED;
980
+ }
981
+ io.err(`pr-autocreate: unexpected error (${why}); nothing done`);
864
982
  return 0;
865
983
  }
866
984
  }
@@ -0,0 +1,40 @@
1
+ import { API } from './agent.js';
2
+ import { PRODUCT } from './names.js';
3
+ /** How long GitHub gets to compare a release tag with main. */
4
+ const COMPARE_MS = 15_000;
5
+ /** The branch every release is cut from (P-61). */
6
+ export const RELEASE_BRANCH = 'main';
7
+ /**
8
+ * Whether release `version`'s tag names a commit on main, asked of GitHub's
9
+ * compare API with no token, as `upgrade` asks for the newest release: the
10
+ * repository is public. Since P-61 only main's Release workflow makes a
11
+ * `v*` tag, but GitHub lets anyone with write access push one, on any
12
+ * commit, so `upgrade` and `onboard` ask before they install or pin a
13
+ * release. Comparing the tag with main gives the tag's commit as the base,
14
+ * and says main is `ahead` of it, or `identical`, exactly when that commit
15
+ * is on main. Both refs are written in full, so a branch named like the
16
+ * tag, or a tag named main, is never the one compared. Anything else is a
17
+ * refusal: a tag off main, no such tag, or no answer, each with its own
18
+ * words, so nothing is installed for want of one.
19
+ */
20
+ export async function tagOnMain(sys, version) {
21
+ const tag = `v${version}`;
22
+ let answer;
23
+ try {
24
+ answer = await sys.http(`${API}/repos/${PRODUCT}/compare/refs/tags/${tag}...refs/heads/${RELEASE_BRANCH}?per_page=1`, { timeoutMs: COMPARE_MS });
25
+ }
26
+ catch (error) {
27
+ return { problem: `GitHub could not be asked whether the ${tag} tag is on ${RELEASE_BRANCH} (${error instanceof Error ? error.message : String(error)})` };
28
+ }
29
+ if (answer.status === 404)
30
+ return { problem: `${PRODUCT} has no ${tag} tag that GitHub can compare with ${RELEASE_BRANCH}` };
31
+ if (answer.status !== 200)
32
+ return { problem: `GitHub answered HTTP ${answer.status} when asked whether the ${tag} tag is on ${RELEASE_BRANCH}` };
33
+ const json = answer.json;
34
+ const sha = typeof json?.base_commit?.sha === 'string' && /^[0-9a-f]{40}$/.test(json.base_commit.sha) ? json.base_commit.sha : undefined;
35
+ if (sha === undefined)
36
+ return { problem: `GitHub's comparison of the ${tag} tag with ${RELEASE_BRANCH} names no commit for the tag` };
37
+ if (json?.status === 'ahead' || json?.status === 'identical')
38
+ return { sha };
39
+ return { problem: `the ${tag} tag is on commit ${sha.slice(0, 12)}, which is not on ${PRODUCT}'s ${RELEASE_BRANCH} (GitHub's comparison: ${JSON.stringify(json?.status ?? null)}); a release comes only from ${RELEASE_BRANCH}, so this tag is not one` };
40
+ }
package/dist/upgrade.js CHANGED
@@ -3,6 +3,7 @@ import { tilde } from './layout.js';
3
3
  import { CLI, PRODUCT, tarballName } from './names.js';
4
4
  import { CLOUD_SETUP_PATH } from './onboard-pull.js';
5
5
  import { GITHUB_WEB } from './host.js';
6
+ import { tagOnMain } from './release-tag.js';
6
7
  import { isNewer, packageVersion } from './version.js';
7
8
  /** The command that updates this machine's CLI, as messages name it. */
8
9
  export const UPGRADE = `${CLI} upgrade`;
@@ -119,6 +120,12 @@ export async function upgrade(sys, io, running = packageVersion()) {
119
120
  io.err(`upgrade: the v${version} release has no ${tarballName(version)} yet; run ${UPGRADE} again once the Release workflow attaches it`);
120
121
  return 1;
121
122
  }
123
+ // A tag off main is not a release, whatever GitHub's releases list says (P-61).
124
+ const onMain = await tagOnMain(sys, version);
125
+ if ('problem' in onMain) {
126
+ io.err(`upgrade: ${onMain.problem}; nothing installed`);
127
+ return 1;
128
+ }
122
129
  io.out(`upgrade: ${CLI} ${running} → ${version}`);
123
130
  io.out(` pnpm add -g ${url}`);
124
131
  const installing = sys.spin(`Installing ${CLI} ${version}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veda-hq/niyam",
3
- "version": "0.6.17",
3
+ "version": "0.6.19",
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": {
@@ -31,7 +31,7 @@
31
31
  "typescript": "7.0.2"
32
32
  },
33
33
  "dependencies": {
34
- "@clack/prompts": "1.8.1",
34
+ "@clack/prompts": "1.9.0",
35
35
  "libsodium-wrappers": "0.8.4",
36
36
  "yaml": "2.9.1"
37
37
  },