@veda-hq/niyam 0.7.3 → 0.7.5

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
@@ -290,7 +290,10 @@ niyam (`~/.config/process-rules/`, or a keychain entry under the service
290
290
  `process-rules`: `▲`, which `niyam machine` removes), and
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
- the board on, the organisation's issue types (see Issue types). It shows them grouped as
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
295
+ as `onboard` writes it at `niyam.yml`'s release, or, with identity alone and so
296
+ no `niyam.yml`, at any release; see The shared Guard). It shows them grouped as
294
297
  This Mac, GitHub and This repo, one line each: `✓` fine, `▲` worth fixing,
295
298
  `✗` broken. Each problem line ends with its fix:
296
299
 
@@ -378,6 +381,7 @@ on any platform without a token store, `niyam env` prints the lock alone.
378
381
  │
379
382
  ◇ Pull request
380
383
  │ workflow pins → v0.5.20
384
+ │ guard caller new, the shared Guard at v0.5.20
381
385
  │ cloud-setup.sh new, installs v0.5.20
382
386
  │ auto-merge when checks pass
383
387
  │
@@ -449,7 +453,21 @@ on any platform without a token store, `niyam env` prints the lock alone.
449
453
  on pull requests and pushes, read-only, and `niyam-weekly` on the
450
454
  weekly run, the only one that writes to issues. Each job carries a
451
455
  `name:` (`niyam`, `niyam-weekly`, …), so its checks read
452
- `niyam / Work rules`. With identity alone `onboard` writes no workflow. It writes
456
+ `niyam / Work rules`. With identity alone `onboard` writes no `niyam.yml`.
457
+ Whatever the features, it also writes `.github/workflows/niyam-guard.yml`,
458
+ the shared Guard's caller (see The shared Guard below): run by
459
+ `pull_request_target` on pull requests to the default branch, read-only,
460
+ its one job `niyam-guard` only calling
461
+ `veda-hq/niyam/.github/workflows/shared-guard.yml` at the release
462
+ `niyam.yml` pins, so its check is `niyam-guard / judge`. A run again moves
463
+ its pin with the rest, and its branch when the default branch changes.
464
+ `onboard` rewrites a caller it wrote, even one edited by hand, so long as
465
+ its header is still `onboard`'s. Where the repo has a `niyam-guard.yml`
466
+ that `onboard` did not write, it refuses, naming the file, and changes
467
+ nothing. In a
468
+ public repository "By hand:" adds one step, once: allow
469
+ `pull_request_target` for the caller under Settings → Actions → Policies,
470
+ since from 2026-12-02 GitHub blocks it there without such a policy. It writes
453
471
  `.github/niyam/cloud-setup.sh`, which installs the CLI in Claude
454
472
  cloud sessions at the version the workflow pins, and writes it again on
455
473
  every run (see Claude cloud sessions below); a cloud session with no
@@ -1197,7 +1215,7 @@ client's own and stays as it is); any other workflow is offered a replacement. M
1197
1215
  features a client has turned on required on its default branch, such as
1198
1216
  `niyam / PR identity` with `pr-identity` and `niyam / Work rules` with
1199
1217
  `work-rules`; a check of a feature that is off still runs and passes, but with
1200
- identity alone there is no workflow at all, so require none.
1218
+ identity alone there is no `niyam.yml`, so require none of its checks.
1201
1219
 
1202
1220
  ### One feature at a time
1203
1221
 
@@ -1300,8 +1318,18 @@ come from the owner's sign-in for the run.
1300
1318
  **New issues get a type as they open.** With `board` on, `onboard` writes
1301
1319
  the client workflow (for `board` alone too), whose `niyam-asks` job
1302
1320
  also starts when an issue is opened or reopened, and runs `niyam
1303
- issue-type`, which gives an issue with no type one by the same rule, read
1304
- from GitHub when the job runs, so a parent set as the issue was made counts.
1321
+ issue-type`, which gives an issue with no type one by the same rule.
1322
+ `gh issue create` sets no type, so an opener types an issue in a second
1323
+ call, as it adds a parent or sub-issues after: the job, finding the issue
1324
+ with no type, waits 30 seconds, then reads it again from GitHub and decides
1325
+ from that read. A type set by then stands, and a parent or sub-issues added
1326
+ by then count. Every write, the hourly one's too, reads the issue once more
1327
+ just before it and writes only when it is still open with no type, so an
1328
+ issue typed or closed since the job read it is left as it is. The hourly
1329
+ run leaves an issue GitHub shows changed under 30 seconds before (opened,
1330
+ reopened, or changed in any other way, such as by a comment or a label), so
1331
+ its opener has the time: the issue's own run types
1332
+ it, or, where no run started, the next hour's.
1305
1333
  GitHub starts no run for an issue a workflow's own `GITHUB_TOKEN` opens, such
1306
1334
  as a monthly reminder a client's workflow files, so the job also runs on the
1307
1335
  asks job's hourly cron and types every open issue in the repository with
@@ -1626,6 +1654,27 @@ niyam owner-step required-checks <owner/repo> <ruleset id or name> [--check <nam
1626
1654
  workflow runs only for some paths can pass there and then never report
1627
1655
  on a pull request that skips them, holding it: name only checks that run
1628
1656
  on every pull request.
1657
+ - `required-checks` also requires the shared Guard's check,
1658
+ `niyam-guard / judge`, when the default branch's
1659
+ `.github/workflows/niyam-guard.yml` is the caller `onboard` writes, on the
1660
+ default branch, at the release `niyam.yml` pins. It adds the check only
1661
+ once it reported `success` on the head commit of the last pull request
1662
+ merged into the default branch from GitHub Actions alone, and requires it
1663
+ from GitHub Actions: another app reporting that name is the spoof the
1664
+ shared Guard stops. `--check niyam-guard / judge` gets this proof, never
1665
+ the one-app proof of any other `--check`. A ruleset that requires the
1666
+ check already from another app, or from any, gets it bound to GitHub
1667
+ Actions on the same proof. Until then it is a `✗` saying why. Guard runs
1668
+ from the default branch's copy of its caller, so it first reports on the
1669
+ pull request after the one that adds the caller; in a public repository,
1670
+ from 2026-12-02, it runs only once a policy allows `pull_request_target`,
1671
+ and the `✗` names where. A repository with no caller hears nothing of the
1672
+ check unless it is named with `--check` or required already from another
1673
+ app. In
1674
+ niyam's own ruleset, once the check has passed, it takes the place of
1675
+ niyam's `Guard`, as a `process-rules / …` check gives way to its
1676
+ `niyam / …` one; in any other repository a check named `Guard` is its
1677
+ own, and stays.
1629
1678
 
1630
1679
  It refuses in an agent session (`NIYAM_AGENT` set, or `CLAUDECODE=1`)
1631
1680
  and without a terminal. It makes a new folder in the user's temporary folder
@@ -1678,7 +1727,7 @@ tag and the commit. Install the attached package on each machine with pnpm,
1678
1727
  once; nothing is built on install:
1679
1728
 
1680
1729
  ```bash
1681
- pnpm add -g https://github.com/veda-hq/niyam/releases/download/v0.7.3/veda-hq-niyam-0.7.3.tgz
1730
+ pnpm add -g https://github.com/veda-hq/niyam/releases/download/v0.7.5/veda-hq-niyam-0.7.5.tgz
1682
1731
  ```
1683
1732
 
1684
1733
  The package puts one command on `PATH`, `niyam`. Since P-57 a release
@@ -1778,26 +1827,62 @@ item (for a slice added later, when the owner's `Decision:` settled it):
1778
1827
  ```
1779
1828
 
1780
1829
  A name is a path, a folder ending in `/`, or a pattern where `*` matches
1781
- within one folder and `**` across them. The guard files are everything under
1782
- `.github/`, `.githooks/`, `.dvara.json`, `.dvara/records-baseline.json`,
1783
- `.gitleaks.toml`, `.trufflehog-exclude`, the `scripts` of `package.json`,
1784
- and `scripts/*.mjs`. A test file needs naming too when a pull request
1830
+ within one folder and `**` across them. The guard files are a floor every
1831
+ repository has, everything under `.github/`, `.githooks/` and `.husky/`,
1832
+ `lefthook.yml`, `.dvara.json`, `.dvara/records-baseline.json`,
1833
+ `.gitleaks.toml`, `.trufflehog-exclude` and the `scripts` of `package.json`,
1834
+ and the repository's own paths, named the same way as `"guard"` in the
1835
+ default branch's `.github/niyam.json` (niyam's: `scripts/*.mjs`). That list
1836
+ only adds to the floor, and the settings are under `.github/`, so changing it
1837
+ is a guard change too. A test file needs naming too when a pull request
1785
1838
  deletes it, leaves it fewer `test(`/`it(` calls than the merge base, or adds
1786
1839
  `.skip`, `.only` or `todo`.
1787
1840
 
1841
+ A repository whose `.github/niyam.json` turns `work-rules` off has no Work
1842
+ items, so no slice to name a change: the shared Guard judges no slice there,
1843
+ and its log lists each change it would have asked one to name. It still
1844
+ refuses what no slice passes: a job added under the name of a check the
1845
+ ruleset requires, a job that could report `niyam-guard / judge` but is not
1846
+ the caller `onboard` writes, and a pull request with more files than GitHub
1847
+ lists. With `work-rules` on, or no `features` listed, it judges every change;
1848
+ a `features` it cannot read refuses.
1849
+
1788
1850
  Two changes pass unnamed: an onboard pull request
1789
1851
  (`chore(niyam): onboard at vX.Y.Z`) whose every changed line only moves the
1790
- niyam version, and a sha256 with it, to that release, tagged on `main`; and a
1791
- Dependabot pull request whose every changed line only moves a `uses:` to
1792
- another full commit sha with its version comment. Whatever the slice says,
1793
- Guard refuses a pull request that adds a job reporting a check the `main`
1794
- ruleset requires, or `Guard`. It fails closed: a truncated file list, or any
1795
- read GitHub does not answer, refuses. Each refusal names the file and how to
1852
+ niyam version, and a sha256 with it, to that release, tagged on
1853
+ `veda-hq/niyam`'s `main`; and a Dependabot pull request whose every changed
1854
+ line only moves a `uses:` to another full commit sha with its version
1855
+ comment. Whatever the slice says, Guard refuses a pull request that adds a
1856
+ job reporting a check the default branch's ruleset requires, or `Guard`, and any job
1857
+ that could report the shared Guard's check, `niyam-guard / judge`, other than
1858
+ its caller as `onboard` writes it. It fails closed: a truncated file list,
1859
+ settings it cannot read, any read GitHub does not answer, or an event other
1860
+ than `pull_request_target`, refuses. Each refusal names the file and how to
1796
1861
  pass. A slice edit does not run Guard again: edit or push the pull request.
1797
1862
 
1863
+ **The shared Guard.** The same script runs for any repository from
1864
+ `.github/workflows/shared-guard.yml`, a reusable workflow whose job, `judge`,
1865
+ checks out niyam at its own commit (`job.workflow_sha`, refusing when GitHub
1866
+ gives none), never the calling repository or the pull request, and judges
1867
+ the caller's pull request with the caller's token. A repository calls it
1868
+ from a workflow run by `pull_request_target` alone, whose one job,
1869
+ `niyam-guard` (id and name), only calls
1870
+ `veda-hq/niyam/.github/workflows/shared-guard.yml@vX.Y.Z` (a release tag or
1871
+ a full commit sha, never a branch), read-only, with no inputs or secrets; its
1872
+ check is `niyam-guard / judge`. The default branch is the repository's own,
1873
+ whatever its name. `niyam onboard` writes that caller,
1874
+ `.github/workflows/niyam-guard.yml`, in every repository it onboards,
1875
+ on pull requests to its default branch and at the release `niyam.yml` pins,
1876
+ and moves its pin with the rest on every run; `niyam doctor` marks it under
1877
+ "This repo", ✗ when it is missing or differs from what `onboard` writes in
1878
+ its trigger, branch, permissions, job, inputs, secrets, steps or release. From 2026-12-02
1879
+ GitHub blocks `pull_request_target` in a public repository unless Settings,
1880
+ Actions, Policies allows it for that workflow, so `onboard` names that step
1881
+ there.
1882
+
1798
1883
  Guard cannot judge a change to its own rules, so `.github/CODEOWNERS` names
1799
1884
  `@AlokBansal8` for the guard's files alone: `.github/workflows/guard.yml`,
1800
- `scripts/guard.mjs`, `scripts/guard.test.mjs` and `.github/CODEOWNERS`
1885
+ `.github/workflows/shared-guard.yml`, `scripts/guard.mjs`, `scripts/guard.test.mjs` and `.github/CODEOWNERS`
1801
1886
  itself. With "Require review from Code Owners" on in the `main` ruleset, a
1802
1887
  pull request that changes one of them waits for his approval. Every other
1803
1888
  pull request, including one under `.github/` that Guard passed, does not.
package/dist/doctor.js CHANGED
@@ -3,10 +3,11 @@ import { LOCKED, clientHooks, hooksHittingLock } from './as-agent.js';
3
3
  import { FROM_SETUP, SIGNING_KEY_VAR, cloudLogin, fileFromSetup, ranFromSetup, repoReleases } from './cloud.js';
4
4
  import { GITHUB_NOREPLY } from './host.js';
5
5
  import { featuresIn } from './features.js';
6
+ import { callerAt, callerIsOnboards, pushBranch } from './guard-caller.js';
6
7
  import { typesDrift } from './issue-types.js';
7
8
  import { closing, findingLines, heading, painter, tilde } from './layout.js';
8
9
  import { exposure, exposureFindings, movedFindings, readDeclined, setAside } from './lockout.js';
9
- import { CLOUD_SETUP_PATH, HOOKS_PATH, SARATHI_PATH } from './onboard-pull.js';
10
+ import { CLOUD_SETUP_PATH, GUARD_CALLER_PATH, HOOKS_PATH, SARATHI_PATH, WORKFLOW_PATH } from './onboard-pull.js';
10
11
  import { leftoverDir, leftoverToken } from './machine.js';
11
12
  import { BOARD_SECRETS, GUARD_COMMAND, HOOK_COMMAND, OLDER_GUARD_COMMANDS, OLDER_HOOK_COMMANDS, ARTIFACT_RULES, AUTO_FIX_RULES, artifactRuleNeeds, autoFixRuleNeeds, sarathiRunner } from './onboard.js';
12
13
  import { secretNames } from './secrets.js';
@@ -95,7 +96,7 @@ export async function doctor(sys, io, named) {
95
96
  return report(sys, io, agent, [
96
97
  ['This Mac', mac],
97
98
  [`GitHub — as ${agent}`, github],
98
- ['This repo', repoFindings(sys)],
99
+ ['This repo', await repoFindings(sys)],
99
100
  ]);
100
101
  }
101
102
  /**
@@ -206,9 +207,10 @@ async function boardAppFindings(sys, token) {
206
207
  /**
207
208
  * Client hooks that reach GitHub outside `as-agent` where doctor runs, a Mac
208
209
  * or a cloud session, and the Auto-fix and artifact rules an onboarded repo's
209
- * Claude Code settings lack.
210
+ * Claude Code settings lack, and whether its shared Guard caller is pinned
211
+ * with the rest.
210
212
  */
211
- function repoFindings(sys) {
213
+ async function repoFindings(sys) {
212
214
  return [
213
215
  ...hooksHittingLock(sys).map((hook) => ({
214
216
  mark: '▲',
@@ -217,8 +219,62 @@ function repoFindings(sys) {
217
219
  })),
218
220
  ...allowFindings(sys),
219
221
  ...twiceFindings(sys),
222
+ ...(await callerFindings(sys)),
220
223
  ];
221
224
  }
225
+ /**
226
+ * Whether the shared Guard's caller is as onboard writes it, pinned with the
227
+ * rest: checked in every onboarded repo, since onboard writes it in every one
228
+ * (#485). Offline, so the caller's branch is checked against the one
229
+ * niyam.yml's pushes run on, which onboard keeps at the default branch; its
230
+ * release against the one niyam.yml pins. A repo with no niyam.yml has
231
+ * neither to check against, so only the caller's shape is checked there.
232
+ */
233
+ async function callerFindings(sys) {
234
+ let root;
235
+ try {
236
+ root = repoRoot(sys);
237
+ if (!hasSettings(sys, root))
238
+ return [];
239
+ }
240
+ catch {
241
+ // fail-open: outside a clone, or settings doctor cannot read, there is no caller to check; onboard says what is wrong with them.
242
+ return [];
243
+ }
244
+ const file = `${root}/${GUARD_CALLER_PATH}`;
245
+ if (!sys.exists(file))
246
+ return [{ mark: '✗', text: `${GUARD_CALLER_PATH} missing, so the shared Guard does not run here`, fix: ONBOARD }];
247
+ const workflowFile = `${root}/${WORKFLOW_PATH}`;
248
+ let workflow;
249
+ let text;
250
+ try {
251
+ workflow = sys.exists(workflowFile) ? sys.read(workflowFile) : undefined;
252
+ text = sys.read(file);
253
+ }
254
+ catch (error) {
255
+ // fail-open: a file doctor cannot read is marked ✗, naming why, and the rest of the report still runs.
256
+ return [{ mark: '✗', text: `${GUARD_CALLER_PATH} not checked: ${message(error)}`, fix: 'make the workflow and its caller readable' }];
257
+ }
258
+ const at = await callerAt(text);
259
+ if (at === undefined) {
260
+ // onboard writes its own file again, but leaves one it did not write to the repository.
261
+ const fix = (await callerIsOnboards(text)) ? ONBOARD : `rename or delete it, then ${ONBOARD}`;
262
+ return [{ mark: '✗', text: `${GUARD_CALLER_PATH} is not the caller onboard writes: another trigger, branch, permission, job, with:, secrets: or steps`, fix }];
263
+ }
264
+ if (workflow === undefined)
265
+ return [{ mark: '✓', text: `${GUARD_CALLER_PATH} calls the shared Guard at v${at.version}, as onboard writes it` }];
266
+ const { pinned } = repoReleases(sys, root);
267
+ if (pinned === undefined) {
268
+ return [{ mark: '▲', text: `${WORKFLOW_PATH} pins no one version, so ${GUARD_CALLER_PATH} is not checked against it`, fix: ONBOARD }];
269
+ }
270
+ const branch = await pushBranch(workflow);
271
+ if (at.version !== pinned)
272
+ return [{ mark: '✗', text: `${GUARD_CALLER_PATH} calls the shared Guard at v${at.version}, but ${WORKFLOW_PATH} pins v${pinned}`, fix: ONBOARD }];
273
+ // A push trigger of several branches, which onboard leaves as the client has it, says no one branch: the rest is still checked.
274
+ if (branch !== undefined && at.branch !== branch)
275
+ return [{ mark: '✗', text: `${GUARD_CALLER_PATH} runs on pull requests to ${at.branch}, but ${WORKFLOW_PATH} runs pushes on ${branch}`, fix: ONBOARD }];
276
+ return [{ mark: '✓', text: `${GUARD_CALLER_PATH} calls the shared Guard at v${pinned}, as ${WORKFLOW_PATH} pins` }];
277
+ }
222
278
  /** niyam's own hook commands, this release's and older ones, by what they do. */
223
279
  const NIYAM_HOOKS = [
224
280
  ["niyam's SessionStart hook", [HOOK_COMMAND, ...OLDER_HOOK_COMMANDS]],
@@ -402,7 +458,7 @@ async function cloudDoctor(sys, io, named) {
402
458
  return report(sys, io, about, [
403
459
  ['This cloud session', session],
404
460
  [`GitHub — as ${about}`, github],
405
- ['This repo', repoFindings(sys)],
461
+ ['This repo', await repoFindings(sys)],
406
462
  ]);
407
463
  }
408
464
  /**
@@ -0,0 +1,161 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { GITHUB_WEB } from './host.js';
3
+ import { CLI, PRODUCT } from './names.js';
4
+ import { GUARD_CALLER_PATH, WORKFLOW_PATH } from './onboard-pull.js';
5
+ export { GUARD_CALLER_PATH } from './onboard-pull.js';
6
+ /** niyam's shared Guard, which the caller runs at a release (#469). */
7
+ export const SHARED_GUARD = `${PRODUCT}/.github/workflows/shared-guard.yml`;
8
+ /**
9
+ * The caller's one job, by id and name: not `Guard`, which today's Guard
10
+ * refuses as an added job of its own check's name, and not `niyam`, which
11
+ * niyam.yml's job already is.
12
+ */
13
+ export const CALLER_JOB = `${CLI}-guard`;
14
+ /** The check the caller reports, the same in every client and in niyam. */
15
+ export const CALLER_CHECK = `${CALLER_JOB} / judge`;
16
+ /** How the caller's header starts: a file that starts so is onboard's, which onboard writes again whatever it holds. */
17
+ const CALLER_MARK = `# Written by ${CLI} onboard: the shared Guard's caller.`;
18
+ /**
19
+ * Whether `text` is onboard's caller, at a release and branch or edited by
20
+ * hand since: onboard writes such a file again, and refuses to overwrite any
21
+ * other, the repository's own.
22
+ */
23
+ export async function callerIsOnboards(text) {
24
+ return text.startsWith(CALLER_MARK) || (await callerAt(text)) !== undefined;
25
+ }
26
+ /** What the caller and its job may read, and nothing more: the shared Guard reads the pull request through the API. */
27
+ const READ_ONLY = ['contents: read', 'pull-requests: read', 'issues: read'];
28
+ /**
29
+ * The shared Guard's caller, as onboard writes it: run by
30
+ * pull_request_target on pull requests to `branch`, the default branch, so
31
+ * GitHub runs the default branch's copy of it, never a pull request's; read
32
+ * only, at the top and on its one job; and that job only calls the shared
33
+ * Guard at `version`, the release niyam.yml pins, with no `with:`, no
34
+ * `secrets:` and no steps, as the Guard's `isCaller` asks. Its header names
35
+ * no version, so a run that moves the pin changes the `uses:` line alone.
36
+ */
37
+ export function guardCaller(branch, version) {
38
+ return [
39
+ `${CALLER_MARK} onboard writes it again on every run, its pin`,
40
+ `# moving with ${WORKFLOW_PATH}'s; change it by running onboard, not by hand. It holds nothing a pull`,
41
+ "# request could weaken: pull_request_target runs the default branch's copy of it, and the Guard it",
42
+ `# calls runs from the ${CLI} release it pins. Its check is ${CALLER_CHECK}.`,
43
+ 'on:',
44
+ ' pull_request_target:',
45
+ ' types: [opened, edited, synchronize, reopened]',
46
+ ` branches: [${JSON.stringify(branch)}]`,
47
+ '',
48
+ 'permissions:',
49
+ ...READ_ONLY.map((line) => ` ${line}`),
50
+ '',
51
+ 'jobs:',
52
+ ` ${CALLER_JOB}:`,
53
+ ` name: ${CALLER_JOB}`,
54
+ ' permissions:',
55
+ ...READ_ONLY.map((line) => ` ${line}`),
56
+ ` uses: ${SHARED_GUARD}@v${version}`,
57
+ '',
58
+ ].join('\n');
59
+ }
60
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
61
+ /** The caller's `uses:`, at the release tag onboard pins. */
62
+ const CALLER_PIN = new RegExp(`^${escape(SHARED_GUARD)}@v(\\d+\\.\\d+\\.\\d+)$`);
63
+ /** A `uses:` line calling the shared Guard at a release, whatever else the file holds. */
64
+ const PIN_LINE = new RegExp(`^\\s*uses:\\s*["']?${escape(SHARED_GUARD)}@v(\\d+\\.\\d+\\.\\d+)["']?\\s*(?:#.*)?$`, 'gm');
65
+ /**
66
+ * The releases of the shared Guard that `text` calls, read line by line so a
67
+ * caller edited by hand still counts: onboard's downgrade guard reads them
68
+ * beside niyam.yml's, so an older CLI never moves the caller's pin back.
69
+ */
70
+ export function callerPins(text) {
71
+ return [...text.matchAll(PIN_LINE)].map((match) => match[1]);
72
+ }
73
+ /**
74
+ * The release and branch of `text` when it is the caller as onboard writes
75
+ * it at some release and branch, read as YAML, so its comments and layout do
76
+ * not count; undefined for any other file: another trigger, types, branch
77
+ * list, permission, job, `with:`, `secrets:` or steps, or a pin that is not
78
+ * a release of the shared Guard. doctor marks such a file; onboard writes
79
+ * it again when it is still onboard's (`callerIsOnboards`), and otherwise
80
+ * refuses to overwrite it.
81
+ */
82
+ export async function callerAt(text) {
83
+ const { parse } = await import('yaml');
84
+ let doc;
85
+ try {
86
+ doc = parse(text);
87
+ }
88
+ catch {
89
+ // fail-open: a file that is not YAML is no caller onboard wrote, which onboard refuses to overwrite and doctor marks.
90
+ return undefined;
91
+ }
92
+ const workflow = doc;
93
+ const uses = workflow?.jobs?.[CALLER_JOB]?.uses;
94
+ const version = typeof uses === 'string' ? CALLER_PIN.exec(uses)?.[1] : undefined;
95
+ const branches = workflow?.on?.pull_request_target?.branches;
96
+ const branch = Array.isArray(branches) && branches.length === 1 && typeof branches[0] === 'string' ? branches[0] : undefined;
97
+ if (version === undefined || branch === undefined)
98
+ return undefined;
99
+ return isDeepStrictEqual(doc, parse(guardCaller(branch, version))) ? { version, branch } : undefined;
100
+ }
101
+ /** The one branch niyam.yml's pushes run on, read as YAML; undefined when it names none or several, or does not parse. */
102
+ export async function pushBranch(text) {
103
+ const { parse } = await import('yaml');
104
+ try {
105
+ const branches = parse(text)?.on?.push?.branches;
106
+ return Array.isArray(branches) && branches.length === 1 && typeof branches[0] === 'string' ? branches[0] : undefined;
107
+ }
108
+ catch {
109
+ // fail-open: a workflow that is not YAML names no branch, which doctor says leaves the caller unchecked.
110
+ return undefined;
111
+ }
112
+ }
113
+ /**
114
+ * What onboard does with the caller, given the checkout's `before` and,
115
+ * when it is onboard's, the release and branch it is at (`at`): write it
116
+ * where there is none, move its pin to `version` and its branch to `branch`,
117
+ * or write it again where only its comments or layout differ.
118
+ */
119
+ export function callerUpdate(before, at, branch, version) {
120
+ const text = guardCaller(branch, version);
121
+ if (before === undefined)
122
+ return { kind: 'write', text };
123
+ if (before === text)
124
+ return { kind: 'same' };
125
+ const from = at !== undefined && at.version !== version ? at.version : undefined;
126
+ const moved = at !== undefined && at.branch !== branch ? branch : undefined;
127
+ if (from === undefined && moved === undefined)
128
+ return { kind: 'rewrite', text };
129
+ return { kind: 'repin', text, ...(from === undefined ? {} : { from }), ...(moved === undefined ? {} : { branch: moved }) };
130
+ }
131
+ /** What a caller update changes, in a few words for the plan. */
132
+ export function callerDetail(update, version) {
133
+ if (update.kind === 'write')
134
+ return `new, the shared Guard at v${version}`;
135
+ if (update.kind === 'rewrite')
136
+ return 'written again';
137
+ return [...(update.from ? [`pin → v${version}`] : []), ...(update.branch ? [`branch → ${update.branch}`] : [])].join(', ');
138
+ }
139
+ /** What a caller update changes, in full for the pull request's description. */
140
+ export function callerWhat(update, version, branch) {
141
+ const holds = `on each pull request to ${branch} it runs ${PRODUCT}'s Guard at v${version}, the release ${WORKFLOW_PATH} pins, as the check ${CALLER_CHECK}, and does nothing else`;
142
+ if (update.kind === 'write')
143
+ return `write ${GUARD_CALLER_PATH}, the shared Guard's caller: ${holds}`;
144
+ if (update.kind === 'rewrite')
145
+ return `write ${GUARD_CALLER_PATH}, the shared Guard's caller, again as onboard writes it: ${holds}`;
146
+ const parts = [...(update.from ? [`move its pin from v${update.from} to v${version}`] : []), ...(update.branch ? [`run it on pull requests to the default branch, ${update.branch}`] : [])];
147
+ return `in ${GUARD_CALLER_PATH}, the shared Guard's caller, ${parts.join(' and ')}`;
148
+ }
149
+ /**
150
+ * The step a public repository's owner takes once, for onboard's "By hand"
151
+ * and the pull request's "Left to do by hand": from 2026-12-02 GitHub blocks
152
+ * pull_request_target in public repositories without a policy that allows
153
+ * it for the workflow, and the caller runs on nothing else.
154
+ */
155
+ export function policySteps(slug) {
156
+ const at = `${GITHUB_WEB}/${slug}/settings/actions`;
157
+ return {
158
+ byHand: `Once for ${slug}: allow pull_request_target for ${GUARD_CALLER_PATH} in a new policy under Settings → Actions → Policies, at ${at}, since from 2026-12-02 GitHub blocks it in public repositories without one; skip it if done.`,
159
+ later: `Allow pull_request_target for \`${GUARD_CALLER_PATH}\` in a new policy under ${slug} → Settings → Actions → Policies (${at}): from 2026-12-02 GitHub blocks the event in public repositories without one, and the shared Guard's caller runs on it alone.`,
160
+ };
161
+ }
@@ -69,6 +69,7 @@ function asHolder(repo, row, from) {
69
69
  from,
70
70
  parent: typeof issue.parent_issue_url === 'string' ? issue.parent_issue_url : null,
71
71
  subIssues: typeof issue.sub_issues_summary?.total === 'number' ? issue.sub_issues_summary.total : 0,
72
+ ...(typeof issue.updated_at === 'string' ? { changed: issue.updated_at } : {}),
72
73
  };
73
74
  }
74
75
  /** Whether a 422's body is GitHub's refusal of the `type` filter, not another validation failure such as spam. */
@@ -398,6 +399,26 @@ export async function typesDrift(sys, token, org, slug, approvals) {
398
399
  ];
399
400
  return { mark: '▲', text: parts.join('; '), fix: RERUN };
400
401
  }
402
+ /**
403
+ * How long the job waits, on an issue opened with no type, before it reads
404
+ * the issue again and types it: time for its opener to set a type in a
405
+ * second call, and to add its parent or sub-issues.
406
+ */
407
+ export const OPENER_WAIT_MS = 30_000;
408
+ /**
409
+ * The instant a GitHub timestamp names, in milliseconds; undefined unless
410
+ * it is UTC to the second (`2026-11-17T09:15:16Z`), as GitHub writes it, and
411
+ * a real date, so a repaired one (30 February) is not read as another.
412
+ */
413
+ function instant(text) {
414
+ const parts = text === undefined ? null : /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)Z$/.exec(text);
415
+ if (!parts || text === undefined)
416
+ return undefined;
417
+ const [year, month, day, hour, minute, second] = parts.slice(1).map(Number);
418
+ const at = Date.UTC(year, month - 1, day, hour, minute, second);
419
+ // Date.UTC carries an impossible field into the next one: a round trip that differs names no real instant.
420
+ return new Date(at).toISOString() === `${text.slice(0, 19)}.000Z` ? at : undefined;
421
+ }
401
422
  /** The type of the issue at `url`, as GitHub shows it now; undefined for none. */
402
423
  async function typeOf(sys, token, url, number) {
403
424
  const above = await sys.http(url, { token });
@@ -406,15 +427,31 @@ async function typeOf(sys, token, url, number) {
406
427
  const type = above.json?.type?.name;
407
428
  return typeof type === 'string' ? type : undefined;
408
429
  }
409
- /** Sets an issue's type, checking GitHub's answer; returns the line saying so. */
430
+ async function readIssue(sys, token, url, number) {
431
+ const read = await sys.http(url, { token });
432
+ if (read.status !== 200)
433
+ throw new Error(`cannot read #${number} (HTTP ${read.status})`);
434
+ return read.json;
435
+ }
436
+ /**
437
+ * Sets an issue's type, checking GitHub's answer; returns the line saying so.
438
+ * It reads the issue again first and writes only when it is still open with
439
+ * no type, so a type its opener set since the job read it stands.
440
+ */
410
441
  async function setType(sys, token, url, number, { to, why }) {
442
+ const fresh = await readIssue(sys, token, url, number);
443
+ const had = fresh?.type?.name;
444
+ if (typeof had === 'string')
445
+ return { line: `issue-type: #${number} is a ${had} now, typed since the job read it; left as it is`, typed: false };
446
+ if (fresh?.state !== 'open')
447
+ return { line: `issue-type: #${number} is closed now, since the job read it; left as it is`, typed: false };
411
448
  const { status, json } = await sys.http(url, { method: 'PATCH', token, body: { type: to } });
412
449
  const now = json?.type?.name;
413
450
  if (status !== 200 || typeof now !== 'string' || !same(now, to)) {
414
451
  // GitHub refuses a type the organisation lacks or has disabled, and drops one silently where the token may not set it.
415
452
  throw new Error(`GitHub did not make #${number} a ${to} (HTTP ${status}); the owner runs niyam onboard, which adds and enables the work model's issue types`);
416
453
  }
417
- return `issue-type: #${number} had no type; now a ${to}: ${why}`;
454
+ return { line: `issue-type: #${number} had no type; now a ${to}: ${why}`, typed: true };
418
455
  }
419
456
  /**
420
457
  * The type each of `issues` gets, decided before any is set: a parent among
@@ -441,11 +478,13 @@ async function decideAll(sys, token, issues) {
441
478
  /**
442
479
  * The issue-type job, run by the shared workflow. When an issue is opened or
443
480
  * reopened, an issue with no type gets the work model's by the rule onboard
444
- * applies (see typeFor), read from GitHub when the job runs, so a parent set
445
- * as the issue was made counts. GitHub starts no run for an issue a
481
+ * applies (see typeFor), read from GitHub half a minute after the job finds
482
+ * it with no type, so a type its opener sets in a second call stands, and a
483
+ * parent or sub-issues added in that time count. GitHub starts no run for an issue a
446
484
  * workflow's own token opens, such as a monthly reminder, so the hourly
447
485
  * sweep types every open issue here with none. An issue with a type, and the
448
- * Approvals issue the settings name, are left as they are.
486
+ * Approvals issue the settings name, are left as they are; each write reads
487
+ * the type again first, so an issue typed since the job read it keeps that type.
449
488
  */
450
489
  export async function issueType(sys, io) {
451
490
  const { GITHUB_EVENT_NAME: name, GITHUB_EVENT_PATH: eventPath, GITHUB_REPOSITORY: slug, GH_TOKEN: token } = sys.env;
@@ -468,11 +507,24 @@ export async function issueType(sys, io) {
468
507
  io.out('issue-type: GitHub has issue types for organisations only; nothing to do');
469
508
  return 0;
470
509
  }
471
- const bare = (await untyped(sys, token, slug)).filter((issue) => issue.number !== approvals);
510
+ // An issue opened or reopened within the wait is its own run's to type, once its opener has had the time. GitHub
511
+ // moves `updated_at` on a reopen, and on any other change: such an issue, and one a workflow token opened, which
512
+ // no run sees, is typed by the next hour's run.
513
+ const since = sys.now().getTime() - OPENER_WAIT_MS;
514
+ const listed = (await untyped(sys, token, slug)).filter((issue) => issue.number !== approvals);
515
+ const young = listed.filter((issue) => (instant(issue.changed) ?? 0) > since);
516
+ for (const issue of young)
517
+ io.out(`issue-type: #${issue.number} changed under ${OPENER_WAIT_MS / 1000} seconds ago; left for its opener, and the next run`);
518
+ const bare = listed.filter((issue) => !young.includes(issue));
472
519
  const types = await decideAll(sys, token, bare);
473
- for (const issue of bare)
474
- io.out(await setType(sys, token, issue.url, issue.number, types.get(issue.url)));
475
- io.out(`issue-type: ${plural(bare.length, 'open issue')} with no type typed`);
520
+ let typed = 0;
521
+ for (const issue of bare) {
522
+ const set = await setType(sys, token, issue.url, issue.number, types.get(issue.url));
523
+ io.out(set.line);
524
+ if (set.typed)
525
+ typed++;
526
+ }
527
+ io.out(`issue-type: ${plural(typed, 'open issue')} with no type typed`);
476
528
  return 0;
477
529
  }
478
530
  const number = event.issue?.number;
@@ -489,26 +541,33 @@ export async function issueType(sys, io) {
489
541
  return 0;
490
542
  }
491
543
  const url = `${API}/repos/${slug}/issues/${number}`;
492
- const read = await sys.http(url, { token });
493
- if (read.status !== 200)
494
- throw new Error(`cannot read #${number} (HTTP ${read.status})`);
495
- const issue = read.json;
496
- if (issue?.pull_request) {
497
- io.out(`issue-type: #${number} is a pull request, which has no type`);
498
- return 0;
499
- }
500
- // Closed since the event, as a queued run may find it: a closed issue with no type is left as it is.
501
- if (issue?.state !== 'open') {
502
- io.out(`issue-type: #${number} is not open; left as it is`);
503
- return 0;
544
+ /** The line saying why the issue is left as it is; undefined when it is open with no type. */
545
+ const leave = (issue) => {
546
+ if (issue?.pull_request)
547
+ return `issue-type: #${number} is a pull request, which has no type`;
548
+ // Closed since the event, as a queued run may find it: a closed issue with no type is left as it is.
549
+ if (issue?.state !== 'open')
550
+ return `issue-type: #${number} is not open; left as it is`;
551
+ if (typeof issue?.type?.name === 'string')
552
+ return `issue-type: #${number} is a ${issue.type.name} already; nothing to do`;
553
+ return undefined;
554
+ };
555
+ let issue = await readIssue(sys, token, url, number);
556
+ let left = leave(issue);
557
+ if (left === undefined) {
558
+ // `gh issue create` sets no type, so its opener sets one in a second call, and adds sub-issues or a parent
559
+ // after: the job waits for them, then decides from the issue as it is.
560
+ await sys.sleep(OPENER_WAIT_MS);
561
+ issue = await readIssue(sys, token, url, number);
562
+ left = leave(issue);
504
563
  }
505
- if (typeof issue?.type?.name === 'string') {
506
- io.out(`issue-type: #${number} is a ${issue.type.name} already; nothing to do`);
564
+ if (left !== undefined) {
565
+ io.out(left);
507
566
  return 0;
508
567
  }
509
568
  const parentUrl = typeof issue?.parent_issue_url === 'string' ? issue.parent_issue_url : undefined;
510
569
  const parent = parentUrl ? { number: parentUrl.split('/').at(-1), type: await typeOf(sys, token, parentUrl, number) } : undefined;
511
570
  const subIssues = issue?.sub_issues_summary?.total;
512
- io.out(await setType(sys, token, url, number, typeFor(parent, typeof subIssues === 'number' ? subIssues : 0)));
571
+ io.out((await setType(sys, token, url, number, typeFor(parent, typeof subIssues === 'number' ? subIssues : 0))).line);
513
572
  return 0;
514
573
  }
@@ -7,6 +7,8 @@ export const HOOKS_PATH = '.claude/settings.json';
7
7
  export const SARATHI_PATH = '.claude/sarathi.json';
8
8
  /** The client's workflow. */
9
9
  export const WORKFLOW_PATH = '.github/workflows/niyam.yml';
10
+ /** The client's caller of the shared Guard (#470), which runs niyam's Guard from the release the rest pins. */
11
+ export const GUARD_CALLER_PATH = '.github/workflows/niyam-guard.yml';
10
12
  /** The repo's cloud setup file, which installs the pinned CLI in Claude cloud sessions. */
11
13
  export const CLOUD_SETUP_PATH = '.github/niyam/cloud-setup.sh';
12
14
  /**
@@ -15,7 +17,7 @@ export const CLOUD_SETUP_PATH = '.github/niyam/cloud-setup.sh';
15
17
  */
16
18
  export const LEFTOVER_CLOUD_SETUP_PATH = '.github/process-rules/cloud-setup.sh';
17
19
  /** Every file onboard's pull request may change. */
18
- export const ONBOARD_FILES = [SETTINGS_PATH, HOOKS_PATH, SARATHI_PATH, WORKFLOW_PATH, CLOUD_SETUP_PATH, LEFTOVER_CLOUD_SETUP_PATH];
20
+ export const ONBOARD_FILES = [SETTINGS_PATH, HOOKS_PATH, SARATHI_PATH, WORKFLOW_PATH, GUARD_CALLER_PATH, CLOUD_SETUP_PATH, LEFTOVER_CLOUD_SETUP_PATH];
19
21
  /** The files onboard's pull request may delete, each moved to its new name, which the pull request must write or its base hold (P-56, P-57). */
20
22
  export const MOVED_FILES = { [LEFTOVER_CLOUD_SETUP_PATH]: CLOUD_SETUP_PATH };
21
23
  /** A subject's leading emoji, or gitmoji shortcode, and the rest of it. */
package/dist/onboard.js CHANGED
@@ -11,6 +11,7 @@ import { routineTrace } from './reviews.js';
11
11
  import { DEFAULT_SCHEDULE, FEATURES, FIGMA_FILE_KEY, NEEDS_ISSUE_TYPES, featuresIn, parseFeatures, renamedLines, scheduleIn } from './features.js';
12
12
  import { CLOUD_SETUP_PATH, HOOKS_PATH, LEFTOVER_CLOUD_SETUP_PATH, ONBOARD_BRANCH, SARATHI_PATH, WORKFLOW_PATH, autoMerge, mergeQueue, openPull, remoteFile, } from './onboard-pull.js';
13
13
  import { SIGNING_KEY_VAR, cloudRepoScript, cloudScriptVersion, releaseSha256 } from './cloud.js';
14
+ import { GUARD_CALLER_PATH, callerAt, callerIsOnboards, callerPins, callerDetail, callerUpdate, callerWhat, policySteps } from './guard-caller.js';
14
15
  import { CLOUD_KEY_TITLE, cloudKeyRefusal, listedKeys, makeCloudKey, pasteLines } from './cloud-key.js';
15
16
  import { newKey, publicLine } from './sshsig.js';
16
17
  import { detail } from './doc-numbers.js';
@@ -716,12 +717,14 @@ function newest(pins, version) {
716
717
  }
717
718
  /**
718
719
  * A release newer than `version` that the checkout pins already, in its
719
- * workflow or its cloud setup file. An older CLI onboarding over it would
720
- * move the pins back and drop what the newer release added.
720
+ * workflow, the shared Guard's caller or its cloud setup file. An older CLI
721
+ * onboarding over it would move the pins back and drop what the newer
722
+ * release added.
721
723
  */
722
724
  function newerPinHere(fileAt, version) {
723
725
  return newest([
724
726
  ...workflowPins(fileAt(WORKFLOW_PATH) ?? '').map((pin) => ({ version: pin, where: `${WORKFLOW_PATH} in this checkout` })),
727
+ ...callerPins(fileAt(GUARD_CALLER_PATH) ?? '').map((pin) => ({ version: pin, where: `${GUARD_CALLER_PATH} in this checkout` })),
725
728
  ...[cloudScriptVersion(fileAt(CLOUD_SETUP_PATH) ?? '')].filter((pin) => pin !== undefined).map((pin) => ({ version: pin, where: `${CLOUD_SETUP_PATH} in this checkout` })),
726
729
  ], version);
727
730
  }
@@ -745,6 +748,10 @@ async function newerPinOnGitHub(sys, slug, token, branch, version) {
745
748
  if ('problem' in read)
746
749
  return read;
747
750
  pins.push(...workflowPins(read.text ?? '').map((pin) => ({ version: pin, where: `${WORKFLOW_PATH} on ${ref}` })));
751
+ const caller = await remoteFile(sys, slug, GUARD_CALLER_PATH, ref, token);
752
+ if ('problem' in caller)
753
+ return caller;
754
+ pins.push(...callerPins(caller.text ?? '').map((pin) => ({ version: pin, where: `${GUARD_CALLER_PATH} on ${ref}` })));
748
755
  }
749
756
  return newest(pins, version);
750
757
  }
@@ -758,8 +765,10 @@ async function access(sys, slug, token) {
758
765
  const { status, json, headers = {} } = await sys.http(`${API}/repos/${slug}`, { token });
759
766
  const repo = json;
760
767
  if (status === 200) {
768
+ // Public only when GitHub says so: a repository it does not say of asks for no policy.
769
+ const open = repo?.private === false || repo?.visibility === 'public';
761
770
  return repo?.permissions?.push === true && typeof repo.default_branch === 'string'
762
- ? { kind: 'push', branch: repo.default_branch }
771
+ ? { kind: 'push', branch: repo.default_branch, ...(open ? { public: true } : {}) }
763
772
  : { kind: 'read', ...(typeof repo?.default_branch === 'string' ? { branch: repo.default_branch } : {}) };
764
773
  }
765
774
  if (status === 404)
@@ -1169,7 +1178,8 @@ function planHead(paint, head) {
1169
1178
  * Sets up the client repository the working directory is in, run by its
1170
1179
  * owner on a Mac `machine` has set up for the agent. It first works out
1171
1180
  * everything it would change, changing nothing: the settings file, the
1172
- * Claude Code settings, the workflow and the cloud setup file, opened as the agent's pull request
1181
+ * Claude Code settings, the workflow, the shared Guard's caller (with work
1182
+ * rules on) and the cloud setup file, opened as the agent's pull request
1173
1183
  * so the owner's checkout is never modified; the agent's push access; the
1174
1184
  * work board (issue types, labels, Project, fields and views); the pre-push
1175
1185
  * hook; and one signed test commit GitHub must show as Verified by the
@@ -1415,6 +1425,15 @@ export async function onboard(sys, io, args = []) {
1415
1425
  }
1416
1426
  const on = (feature) => features.includes(feature);
1417
1427
  const workflowNeeded = on('pr-identity') || on('board') || on('work-rules') || on('figma') || on('decisions') || on('review');
1428
+ // The shared Guard's caller (#470), in every repository whatever its features (#485). onboard's own, edited by
1429
+ // hand or not, is written again; a file of that name onboard did not write is the repository's own: refused
1430
+ // before any plan, so nothing changes.
1431
+ const callerBefore = fileAt(GUARD_CALLER_PATH);
1432
+ const callerHad = callerBefore === undefined ? undefined : await callerAt(callerBefore);
1433
+ if (callerBefore !== undefined && !(await callerIsOnboards(callerBefore))) {
1434
+ io.err(`onboard: ${GUARD_CALLER_PATH} is not the shared Guard's caller as onboard writes it, and onboard does not overwrite a workflow of the repository's own; nothing changed. Rename or delete it, then run onboard again.`);
1435
+ return 1;
1436
+ }
1418
1437
  const existing = fileAt(HOOKS_PATH);
1419
1438
  // Worked out before the plan, so a file onboard cannot edit is refused before any question.
1420
1439
  const claude = claudeSettings(existing, fileAt(SARATHI_PATH));
@@ -1543,6 +1562,17 @@ export async function onboard(sys, io, args = []) {
1543
1562
  if (detail !== undefined)
1544
1563
  pull.push({ label: 'workflow', detail });
1545
1564
  }
1565
+ // The caller runs on pull requests to the default branch, which only GitHub can say: as the workflow, worked out
1566
+ // again in the pull request's step.
1567
+ const callerFor = (branch) => {
1568
+ const update = callerUpdate(callerBefore, callerHad, branch, version);
1569
+ if (update.kind !== 'same')
1570
+ change(GUARD_CALLER_PATH, update.text, callerWhat(update, version, branch));
1571
+ };
1572
+ const callerUpdated = planned === undefined ? undefined : callerUpdate(callerBefore, callerHad, planned, version);
1573
+ const callerPlan = callerUpdated === undefined ? (callerBefore === undefined ? `new, the shared Guard at v${version}` : 'write or update') : callerUpdated.kind === 'same' ? undefined : callerDetail(callerUpdated, version);
1574
+ if (callerPlan !== undefined)
1575
+ pull.push({ label: 'guard caller', detail: callerPlan });
1546
1576
  if (on('board')) {
1547
1577
  github.push({ label: 'board', detail: 'set up or check' });
1548
1578
  let approved;
@@ -1715,6 +1745,13 @@ export async function onboard(sys, io, args = []) {
1715
1745
  return false;
1716
1746
  if (workflowNeeded)
1717
1747
  workflowFor(reach.branch);
1748
+ callerFor(reach.branch);
1749
+ // From 2026-12-02 GitHub runs pull_request_target in a public repository only where a policy allows it.
1750
+ if (reach.public) {
1751
+ const policy = policySteps(slug);
1752
+ byHand.push(policy.byHand);
1753
+ later.push(policy.later);
1754
+ }
1718
1755
  // From the workflow the pull request leaves, worked out only now that GitHub has said the branch.
1719
1756
  const text = fileAt(WORKFLOW_PATH);
1720
1757
  const unpassed = workflowNeeded && on('figma') && text !== undefined ? jobsWithoutLibrary(text) : [];
@@ -1,8 +1,10 @@
1
1
  import { SETTINGS_PATH, sameLogin } from './agent.js';
2
2
  import { featuresIn } from './features.js';
3
+ import { CALLER_CHECK, GUARD_CALLER_PATH, callerAt, policySteps } from './guard-caller.js';
3
4
  import { GITHUB_HOST, GITHUB_WEB } from './host.js';
4
5
  import { ISSUE_TYPES } from './issue-types.js';
5
- import { CLI } from './names.js';
6
+ import { CLI, PRODUCT } from './names.js';
7
+ import { workflowPins } from './onboard.js';
6
8
  import { WORKFLOW_PATH } from './onboard-pull.js';
7
9
  import { signInLines } from './owner-login.js';
8
10
  import { agentSession } from './push-identity.js';
@@ -28,6 +30,12 @@ export const FEATURE_CHECKS = {
28
30
  };
29
31
  /** GitHub Actions' app, which reports the workflow's checks. */
30
32
  const ACTIONS_APP = 15368;
33
+ /**
34
+ * niyam's own Guard check, which the shared Guard's takes the place of in
35
+ * niyam's ruleset alone (#472): in any other repository a check of that
36
+ * name is its own, and stays.
37
+ */
38
+ const OWN_GUARD = 'Guard';
31
39
  /** How long one gh call gets. */
32
40
  const GH_MS = 60_000;
33
41
  /** How long the event loop gets between gh calls, for a Ctrl-C's handler. */
@@ -385,12 +393,52 @@ function passedOnPull(gh, repo, names) {
385
393
  }
386
394
  return found;
387
395
  }
396
+ /**
397
+ * Whether the ruleset may require the shared Guard's check: only when the
398
+ * default branch's caller is as onboard writes it, at the release
399
+ * niyam.yml pins, on the default branch, and the check reported `success`
400
+ * from GitHub Actions on the head of the last pull request merged there.
401
+ * Another app reporting that name proves nothing: it is the spoof the
402
+ * shared Guard is there to stop. `asked`: the owner named the check, so a
403
+ * repository with no caller is a ✗, not silence. `what`: how a ✗ starts.
404
+ */
405
+ async function sharedGuard(gh, repo, asked, what) {
406
+ const not = (why, fix) => ({ skipped: { mark: '✗', text: `${what}: ${why}`, fix } });
407
+ const onboard = `${CLI} onboard there, merge its pull request, then run this again`;
408
+ const text = fileIn(gh, repo, GUARD_CALLER_PATH);
409
+ if (text === undefined)
410
+ return asked ? not(`${repo} has no ${GUARD_CALLER_PATH} on its default branch, so nothing runs it`, onboard) : undefined;
411
+ const at = await callerAt(text.replaceAll('\r\n', '\n'));
412
+ if (at === undefined) {
413
+ return not(`${GUARD_CALLER_PATH} on the default branch is not the shared Guard's caller as onboard writes it`, `rename or delete a ${GUARD_CALLER_PATH} onboard did not write, then ${onboard}`);
414
+ }
415
+ const pins = [...new Set(workflowPins(workflowIn(gh, repo).text ?? ''))];
416
+ if (pins.length !== 1)
417
+ return not(`${WORKFLOW_PATH} on the default branch pins ${pins.length === 0 ? 'no' : 'more than one'} release, so the caller's is not known to be the one`, onboard);
418
+ if (at.version !== pins[0])
419
+ return not(`${GUARD_CALLER_PATH} calls the shared Guard at v${at.version}, but ${WORKFLOW_PATH} pins v${String(pins[0])}`, onboard);
420
+ const about = must(gh.api(`repos/${repo}`), `reading ${repo}`);
421
+ const branch = about?.default_branch;
422
+ if (typeof branch !== 'string' || !branch)
423
+ return not(`GitHub did not say ${repo}'s default branch`, 'run this again');
424
+ if (at.branch !== branch)
425
+ return not(`${GUARD_CALLER_PATH} runs on pull requests into ${at.branch}, not the default branch ${branch}`, onboard);
426
+ const passed = passedOnPull(gh, repo, [CALLER_CHECK]).get(CALLER_CHECK);
427
+ if ('app' in passed && passed.app === ACTIONS_APP) {
428
+ return { note: `${CALLER_CHECK} passed on ${repo}#${passed.pull}, reported by ${passed.appName}; ${GUARD_CALLER_PATH} runs it on pull requests into ${branch} alone, so a ruleset that also targets other branches would hold theirs` };
429
+ }
430
+ const why = 'app' in passed ? `${CALLER_CHECK} on ${repo}#${passed.pull} was reported by ${passed.appName}, not GitHub Actions` : passed.problem;
431
+ const visible = about?.private === false || about?.visibility === 'public';
432
+ const runs = `Guard runs from the default branch's copy of its caller, so it first reports on the pull request after the one that adds it${visible ? ', and from 2026-12-02 GitHub runs it in a public repository only once a policy allows pull_request_target' : ''}`;
433
+ const merge = 'merge a pull request it passes on, then run this again';
434
+ return not(`${why}; ${runs}`, visible ? `${policySteps(repo).byHand} Then ${merge}` : merge);
435
+ }
388
436
  /**
389
437
  * The ruleset's required checks, with the checks of the features the
390
438
  * repository's settings turn on added; every other check and rule stays as
391
439
  * it is, and none is taken away.
392
440
  */
393
- function requiredChecks(gh, { repo, ruleset, checks: named = [] }) {
441
+ async function requiredChecks(gh, { repo, ruleset, checks: named = [] }) {
394
442
  const listed = must(gh.api(`repos/${repo}/rulesets?includes_parents=false&per_page=100`), `listing ${repo}'s rulesets`);
395
443
  const matches = (listed ?? []).filter((one) => String(one.id) === ruleset || (typeof one.name === 'string' && same(one.name, ruleset)));
396
444
  if (matches.length !== 1) {
@@ -417,10 +465,25 @@ function requiredChecks(gh, { repo, ruleset, checks: named = [] }) {
417
465
  const jobs = turnedOn.some((check) => !had.includes(check)) || required.some(stale) ? workflowJobs(gh, repo) : new Set();
418
466
  const runs = (check) => had.includes(check) || (jobs instanceof Set && jobs.has(check.slice(CHECK_PREFIX.length)));
419
467
  const swaps = [...new Set(required.filter(stale))].map((from) => ({ from, to: runs(renamed(from)) ? renamed(from) : undefined }));
420
- const target = (check) => (stale(check) ? swaps.find((swap) => swap.from === check)?.to : check);
421
468
  const checks = turnedOn.filter(runs);
469
+ // The shared Guard's check, on its own proof (sharedGuard), never --check's, which any one app passes.
470
+ const own = same(repo, PRODUCT);
471
+ // Required already from another app, or from any, it is the spoof itself: it is bound to GitHub Actions, on the same proof.
472
+ const bound = (rules) => rules.find((rule) => rule.type === 'required_status_checks')?.parameters?.required_status_checks ?? [];
473
+ const loose = (rules) => bound(rules).find((check) => check.context === CALLER_CHECK && check.integration_id !== ACTIONS_APP);
474
+ const looseBefore = loose(before.rules);
475
+ const from = looseBefore?.integration_id === undefined ? 'any app' : `app ${looseBefore.integration_id}`;
476
+ const sound = had.includes(CALLER_CHECK) && looseBefore === undefined;
477
+ const what = looseBefore ? `leaving ${CALLER_CHECK} required from ${from}, not bound to GitHub Actions` : sound ? `keeping ${OWN_GUARD}, not ${CALLER_CHECK} in its place` : `not requiring ${CALLER_CHECK}`;
478
+ const guard = !sound || (own && required.includes(OWN_GUARD)) ? await sharedGuard(gh, repo, named.includes(CALLER_CHECK) || looseBefore !== undefined, what) : undefined;
479
+ const guardRuns = guard !== undefined && 'note' in guard;
480
+ const guardRebind = guardRuns && looseBefore !== undefined;
481
+ // In niyam's ruleset its own Guard check goes, the shared one in its place, once that has passed (#472).
482
+ const swapsGuard = (check) => own && guardRuns && check === OWN_GUARD;
483
+ const guardAdded = guardRuns && !had.includes(CALLER_CHECK) ? [CALLER_CHECK] : [];
484
+ const target = (check) => (stale(check) ? swaps.find((swap) => swap.from === check)?.to : swapsGuard(check) ? CALLER_CHECK : check);
422
485
  // Each check the owner named, unless required already or a feature's: added only with proof that pull requests run it.
423
- const toProve = named.filter((check) => !had.includes(check) && !turnedOn.includes(check));
486
+ const toProve = named.filter((check) => check !== CALLER_CHECK && !had.includes(check) && !turnedOn.includes(check));
424
487
  const proof = passedOnPull(gh, repo, toProve);
425
488
  const proven = toProve.flatMap((context) => {
426
489
  const passed = proof.get(context);
@@ -434,6 +497,8 @@ function requiredChecks(gh, { repo, ruleset, checks: named = [] }) {
434
497
  text: `not adding ${check}: ${why(check)}, so it would never report and would hold every pull request`,
435
498
  fix: `${CLI} onboard there, then run this again`,
436
499
  }));
500
+ if (guard !== undefined && 'skipped' in guard)
501
+ skipped.push(guard.skipped);
437
502
  for (const check of toProve) {
438
503
  const passed = proof.get(check);
439
504
  if (passed && 'problem' in passed) {
@@ -442,7 +507,7 @@ function requiredChecks(gh, { repo, ruleset, checks: named = [] }) {
442
507
  }
443
508
  const unique = (names) => [...new Set(names)];
444
509
  const afterSwaps = unique(required.flatMap((check) => target(check) ?? []));
445
- const missing = [...checks, ...proven.map((check) => check.context)].filter((check) => !afterSwaps.includes(check));
510
+ const missing = [...checks, ...proven.map((check) => check.context), ...guardAdded].filter((check) => !afterSwaps.includes(check));
446
511
  const after = [...afterSwaps, ...missing];
447
512
  const list = (names) => (names.length === 0 ? 'none' : names.join(', '));
448
513
  const notes = [`${file} turns on the checks ${list(turnedOn)}`];
@@ -450,22 +515,28 @@ function requiredChecks(gh, { repo, ruleset, checks: named = [] }) {
450
515
  const passed = proof.get(check.context);
451
516
  notes.push(`${check.context} passed on ${repo}#${passed.pull}, reported by ${passed.appName}; a check that runs only for some paths would hold a pull request it skips`);
452
517
  }
518
+ if (guard !== undefined && 'note' in guard)
519
+ notes.push(guard.note);
453
520
  notes.push(`before: ${list(required)}`, `after: ${list(after)}`);
454
521
  const namedHad = named.filter((check) => had.includes(check) && !turnedOn.includes(check));
455
- if (missing.length === 0 && swaps.length === 0) {
522
+ const guardSwap = required.some(swapsGuard);
523
+ if (missing.length === 0 && swaps.length === 0 && !guardSwap && !guardRebind) {
456
524
  return { changes: [], notes, skipped, already: `the ruleset ${before.name} requires every check ${file} turns on${namedHad.length > 0 ? `, and ${list(namedHad)}` : ''}` };
457
525
  }
458
526
  // Built on the ruleset as it is just before the write, so an edit made while the owner read the plan is kept.
459
527
  const withChecks = (current) => {
460
- // Each check before P-53 in its place under its niyam name, its app kept, or gone; a second copy of a name goes.
528
+ // Each check before P-53 in its place under its niyam name, its app kept, or gone; niyam's Guard as the shared
529
+ // Guard's, from GitHub Actions; a second copy of a name goes.
461
530
  const moved = (list) => list
462
531
  .flatMap((check) => {
532
+ if (swapsGuard(check.context) || (guardRuns && check.context === CALLER_CHECK))
533
+ return [{ context: CALLER_CHECK, integration_id: ACTIONS_APP }];
463
534
  const to = stale(check.context) ? (runs(renamed(check.context)) ? renamed(check.context) : undefined) : check.context;
464
535
  return to === undefined ? [] : [{ ...check, context: to }];
465
536
  })
466
537
  .filter((check, at, all) => all.findIndex((one) => one.context === check.context) === at);
467
538
  const kept = moved(current.find((rule) => rule.type === 'required_status_checks')?.parameters?.required_status_checks ?? []).map((check) => check.context);
468
- const added = [...checks.map((context) => ({ context, integration_id: ACTIONS_APP })), ...proven].filter((check) => !kept.includes(check.context));
539
+ const added = [...[...checks, ...guardAdded].map((context) => ({ context, integration_id: ACTIONS_APP })), ...proven].filter((check) => !kept.includes(check.context));
469
540
  return current.some((rule) => rule.type === 'required_status_checks')
470
541
  ? current.map((rule) => rule.type === 'required_status_checks'
471
542
  ? { ...rule, parameters: { ...rule.parameters, required_status_checks: [...moved(rule.parameters?.required_status_checks ?? []), ...added] } }
@@ -477,6 +548,8 @@ function requiredChecks(gh, { repo, ruleset, checks: named = [] }) {
477
548
  {
478
549
  plan: [
479
550
  ...swaps.map(({ from, to }) => (to ? `require ${to} in place of ${from}` : `drop ${from}, which no workflow reports since P-53`)),
551
+ ...(guardSwap ? [`require ${CALLER_CHECK} in place of ${OWN_GUARD}`] : []),
552
+ ...(guardRebind ? [`require ${CALLER_CHECK} from GitHub Actions, not ${from}`] : []),
480
553
  ...(missing.length > 0 ? [`also require ${missing.join(', ')}`] : []),
481
554
  ].reduce((plan, part, at) => `${plan}${at === 0 ? ' ' : ', and '}${part}`, `make the ruleset ${before.name} of ${repo}`),
482
555
  apply: async (checkpoint) => {
@@ -484,12 +557,14 @@ function requiredChecks(gh, { repo, ruleset, checks: named = [] }) {
484
557
  await checkpoint();
485
558
  must(gh.api(`repos/${repo}/rulesets/${id}`, { method: 'PUT', body: { rules: withChecks(current.rules) } }), `updating the ruleset ${before.name}`);
486
559
  const now = read();
487
- const lacking = unique([...checks, ...proven.map((check) => check.context), ...swaps.flatMap(({ to }) => to ?? [])]).filter((check) => !contexts(now.rules).includes(check));
560
+ const lacking = unique([...checks, ...proven.map((check) => check.context), ...guardAdded, ...swaps.flatMap(({ to }) => to ?? []), ...(guardSwap ? [CALLER_CHECK] : [])]).filter((check) => !contexts(now.rules).includes(check));
488
561
  if (lacking.length > 0)
489
562
  throw new Error(`GitHub shows the ruleset without ${lacking.join(', ')} afterwards`);
490
- const left = contexts(now.rules).filter(stale);
563
+ const left = contexts(now.rules).filter((check) => stale(check) || swapsGuard(check));
491
564
  if (left.length > 0)
492
565
  throw new Error(`GitHub shows the ruleset still requiring ${left.join(', ')} afterwards`);
566
+ if (guardRuns && loose(now.rules))
567
+ throw new Error(`GitHub shows the ruleset requiring ${CALLER_CHECK} from another app than GitHub Actions afterwards`);
493
568
  if (others(now.rules) !== others(current.rules))
494
569
  throw new Error(`GitHub shows the ruleset's other rules changed afterwards; check it at ${GITHUB_WEB}/${repo}/rules/${id}`);
495
570
  return `the ruleset ${now.name} requires ${list(contexts(now.rules))}`;
@@ -608,7 +683,7 @@ async function signedIn(sys, io, step, scopes, dir, env, results, interrupted) {
608
683
  const notOwner = step.step === 'issue-types' ? (ownsOrg(gh, step.org) ? undefined : `${login} is not an owner of the organisation ${step.org}`) : notRepoOwner(gh, login, step.repo);
609
684
  if (notOwner)
610
685
  throw new Error(`${notOwner}; sign in to ${GITHUB_HOST} in the browser as the owner and run it again. Nothing changed`);
611
- const found = step.step === 'issue-types' ? issueTypes(gh, step.org) : step.step === 'label' ? label(gh, step) : requiredChecks(gh, step);
686
+ const found = step.step === 'issue-types' ? issueTypes(gh, step.org) : step.step === 'label' ? label(gh, step) : await requiredChecks(gh, step);
612
687
  for (const note of found.notes)
613
688
  io.out(` ${note}`);
614
689
  results.push(...found.skipped);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veda-hq/niyam",
3
- "version": "0.7.3",
3
+ "version": "0.7.5",
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": {