@veda-hq/niyam 0.7.3 → 0.7.4

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,9 @@ 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 one with
294
+ `work-rules` on, the shared Guard's caller (`✗` when it is missing or not as
295
+ `onboard` writes it at `niyam.yml`'s release; see The shared Guard). It shows them grouped as
294
296
  This Mac, GitHub and This repo, one line each: `✓` fine, `▲` worth fixing,
295
297
  `✗` broken. Each problem line ends with its fix:
296
298
 
@@ -378,6 +380,7 @@ on any platform without a token store, `niyam env` prints the lock alone.
378
380
  │
379
381
  ◇ Pull request
380
382
  │ workflow pins → v0.5.20
383
+ │ guard caller new, the shared Guard at v0.5.20
381
384
  │ cloud-setup.sh new, installs v0.5.20
382
385
  │ auto-merge when checks pass
383
386
  │
@@ -449,7 +452,21 @@ on any platform without a token store, `niyam env` prints the lock alone.
449
452
  on pull requests and pushes, read-only, and `niyam-weekly` on the
450
453
  weekly run, the only one that writes to issues. Each job carries a
451
454
  `name:` (`niyam`, `niyam-weekly`, …), so its checks read
452
- `niyam / Work rules`. With identity alone `onboard` writes no workflow. It writes
455
+ `niyam / Work rules`. With identity alone `onboard` writes no workflow.
456
+ With `work-rules` on it also writes `.github/workflows/niyam-guard.yml`,
457
+ the shared Guard's caller (see The shared Guard below): run by
458
+ `pull_request_target` on pull requests to the default branch, read-only,
459
+ its one job `niyam-guard` only calling
460
+ `veda-hq/niyam/.github/workflows/shared-guard.yml` at the release
461
+ `niyam.yml` pins, so its check is `niyam-guard / judge`. A run again moves
462
+ its pin with the rest, and its branch when the default branch changes.
463
+ `onboard` rewrites a caller it wrote, even one edited by hand, so long as
464
+ its header is still `onboard`'s. Where the repo has a `niyam-guard.yml`
465
+ that `onboard` did not write, it refuses, naming the file, and changes
466
+ nothing. In a
467
+ public repository "By hand:" adds one step, once: allow
468
+ `pull_request_target` for the caller under Settings → Actions → Policies,
469
+ since from 2026-12-02 GitHub blocks it there without such a policy. It writes
453
470
  `.github/niyam/cloud-setup.sh`, which installs the CLI in Claude
454
471
  cloud sessions at the version the workflow pins, and writes it again on
455
472
  every run (see Claude cloud sessions below); a cloud session with no
@@ -1300,8 +1317,18 @@ come from the owner's sign-in for the run.
1300
1317
  **New issues get a type as they open.** With `board` on, `onboard` writes
1301
1318
  the client workflow (for `board` alone too), whose `niyam-asks` job
1302
1319
  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.
1320
+ issue-type`, which gives an issue with no type one by the same rule.
1321
+ `gh issue create` sets no type, so an opener types an issue in a second
1322
+ call, as it adds a parent or sub-issues after: the job, finding the issue
1323
+ with no type, waits 30 seconds, then reads it again from GitHub and decides
1324
+ from that read. A type set by then stands, and a parent or sub-issues added
1325
+ by then count. Every write, the hourly one's too, reads the issue once more
1326
+ just before it and writes only when it is still open with no type, so an
1327
+ issue typed or closed since the job read it is left as it is. The hourly
1328
+ run leaves an issue GitHub shows changed under 30 seconds before (opened,
1329
+ reopened, or changed in any other way, such as by a comment or a label), so
1330
+ its opener has the time: the issue's own run types
1331
+ it, or, where no run started, the next hour's.
1305
1332
  GitHub starts no run for an issue a workflow's own `GITHUB_TOKEN` opens, such
1306
1333
  as a monthly reminder a client's workflow files, so the job also runs on the
1307
1334
  asks job's hourly cron and types every open issue in the repository with
@@ -1626,6 +1653,27 @@ niyam owner-step required-checks <owner/repo> <ruleset id or name> [--check <nam
1626
1653
  workflow runs only for some paths can pass there and then never report
1627
1654
  on a pull request that skips them, holding it: name only checks that run
1628
1655
  on every pull request.
1656
+ - `required-checks` also requires the shared Guard's check,
1657
+ `niyam-guard / judge`, when the default branch's
1658
+ `.github/workflows/niyam-guard.yml` is the caller `onboard` writes, on the
1659
+ default branch, at the release `niyam.yml` pins. It adds the check only
1660
+ once it reported `success` on the head commit of the last pull request
1661
+ merged into the default branch from GitHub Actions alone, and requires it
1662
+ from GitHub Actions: another app reporting that name is the spoof the
1663
+ shared Guard stops. `--check niyam-guard / judge` gets this proof, never
1664
+ the one-app proof of any other `--check`. A ruleset that requires the
1665
+ check already from another app, or from any, gets it bound to GitHub
1666
+ Actions on the same proof. Until then it is a `✗` saying why. Guard runs
1667
+ from the default branch's copy of its caller, so it first reports on the
1668
+ pull request after the one that adds the caller; in a public repository,
1669
+ from 2026-12-02, it runs only once a policy allows `pull_request_target`,
1670
+ and the `✗` names where. A repository with no caller hears nothing of the
1671
+ check unless it is named with `--check` or required already from another
1672
+ app. In
1673
+ niyam's own ruleset, once the check has passed, it takes the place of
1674
+ niyam's `Guard`, as a `process-rules / …` check gives way to its
1675
+ `niyam / …` one; in any other repository a check named `Guard` is its
1676
+ own, and stays.
1629
1677
 
1630
1678
  It refuses in an agent session (`NIYAM_AGENT` set, or `CLAUDECODE=1`)
1631
1679
  and without a terminal. It makes a new folder in the user's temporary folder
@@ -1678,7 +1726,7 @@ tag and the commit. Install the attached package on each machine with pnpm,
1678
1726
  once; nothing is built on install:
1679
1727
 
1680
1728
  ```bash
1681
- pnpm add -g https://github.com/veda-hq/niyam/releases/download/v0.7.3/veda-hq-niyam-0.7.3.tgz
1729
+ pnpm add -g https://github.com/veda-hq/niyam/releases/download/v0.7.4/veda-hq-niyam-0.7.4.tgz
1682
1730
  ```
1683
1731
 
1684
1732
  The package puts one command on `PATH`, `niyam`. Since P-57 a release
@@ -1778,26 +1826,53 @@ item (for a slice added later, when the owner's `Decision:` settled it):
1778
1826
  ```
1779
1827
 
1780
1828
  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
1829
+ within one folder and `**` across them. The guard files are a floor every
1830
+ repository has, everything under `.github/`, `.githooks/` and `.husky/`,
1831
+ `lefthook.yml`, `.dvara.json`, `.dvara/records-baseline.json`,
1832
+ `.gitleaks.toml`, `.trufflehog-exclude` and the `scripts` of `package.json`,
1833
+ and the repository's own paths, named the same way as `"guard"` in the
1834
+ default branch's `.github/niyam.json` (niyam's: `scripts/*.mjs`). That list
1835
+ only adds to the floor, and the settings are under `.github/`, so changing it
1836
+ is a guard change too. A test file needs naming too when a pull request
1785
1837
  deletes it, leaves it fewer `test(`/`it(` calls than the merge base, or adds
1786
1838
  `.skip`, `.only` or `todo`.
1787
1839
 
1788
1840
  Two changes pass unnamed: an onboard pull request
1789
1841
  (`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
1842
+ niyam version, and a sha256 with it, to that release, tagged on
1843
+ `veda-hq/niyam`'s `main`; and a Dependabot pull request whose every changed
1844
+ line only moves a `uses:` to another full commit sha with its version
1845
+ comment. Whatever the slice says, Guard refuses a pull request that adds a
1846
+ job reporting a check the default branch's ruleset requires, or `Guard`, and any job
1847
+ that could report the shared Guard's check, `niyam-guard / judge`, other than
1848
+ its caller as `onboard` writes it. It fails closed: a truncated file list,
1849
+ settings it cannot read, any read GitHub does not answer, or an event other
1850
+ than `pull_request_target`, refuses. Each refusal names the file and how to
1796
1851
  pass. A slice edit does not run Guard again: edit or push the pull request.
1797
1852
 
1853
+ **The shared Guard.** The same script runs for any repository from
1854
+ `.github/workflows/shared-guard.yml`, a reusable workflow whose job, `judge`,
1855
+ checks out niyam at its own commit (`job.workflow_sha`, refusing when GitHub
1856
+ gives none), never the calling repository or the pull request, and judges
1857
+ the caller's pull request with the caller's token. A repository calls it
1858
+ from a workflow run by `pull_request_target` alone, whose one job,
1859
+ `niyam-guard` (id and name), only calls
1860
+ `veda-hq/niyam/.github/workflows/shared-guard.yml@vX.Y.Z` (a release tag or
1861
+ a full commit sha, never a branch), read-only, with no inputs or secrets; its
1862
+ check is `niyam-guard / judge`. The default branch is the repository's own,
1863
+ whatever its name. `niyam onboard` writes that caller,
1864
+ `.github/workflows/niyam-guard.yml`, in a repository with `work-rules` on,
1865
+ on pull requests to its default branch and at the release `niyam.yml` pins,
1866
+ and moves its pin with the rest on every run; `niyam doctor` marks it under
1867
+ "This repo", ✗ when it is missing or differs from what `onboard` writes in
1868
+ its trigger, branch, permissions, job, inputs, secrets, steps or release. From 2026-12-02
1869
+ GitHub blocks `pull_request_target` in a public repository unless Settings,
1870
+ Actions, Policies allows it for that workflow, so `onboard` names that step
1871
+ there.
1872
+
1798
1873
  Guard cannot judge a change to its own rules, so `.github/CODEOWNERS` names
1799
1874
  `@AlokBansal8` for the guard's files alone: `.github/workflows/guard.yml`,
1800
- `scripts/guard.mjs`, `scripts/guard.test.mjs` and `.github/CODEOWNERS`
1875
+ `.github/workflows/shared-guard.yml`, `scripts/guard.mjs`, `scripts/guard.test.mjs` and `.github/CODEOWNERS`
1801
1876
  itself. With "Require review from Code Owners" on in the `main` ruleset, a
1802
1877
  pull request that changes one of them waits for his approval. Every other
1803
1878
  pull request, including one under `.github/` that Guard passed, does not.
package/dist/doctor.js CHANGED
@@ -2,11 +2,12 @@ import { EXPIRY_WARNING_DAYS, SETTINGS_PATH, account, agentFrom, agentIn, anyLog
2
2
  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
- import { featuresIn } from './features.js';
5
+ import { featuresIn, isOn } from './features.js';
6
+ import { callerAt, callerIsOnboards, callerWanted, 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,63 @@ 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 an onboarded repo whose settings have onboard write it
228
+ * (`callerWanted`) and whose niyam.yml is there. Offline, so the caller's
229
+ * branch is checked against the one niyam.yml's pushes run on, which onboard
230
+ * keeps at the default branch; its release against the one niyam.yml pins.
231
+ */
232
+ async function callerFindings(sys) {
233
+ let root;
234
+ let wanted;
235
+ try {
236
+ root = repoRoot(sys);
237
+ if (!hasSettings(sys, root) || !sys.exists(`${root}/${WORKFLOW_PATH}`))
238
+ return [];
239
+ const here = root;
240
+ wanted = callerWanted((feature) => isOn(sys, here, feature));
241
+ }
242
+ catch {
243
+ // fail-open: outside a clone, or settings doctor cannot read, there is no caller to check; onboard says what is wrong with them.
244
+ return [];
245
+ }
246
+ if (!wanted)
247
+ return [];
248
+ const file = `${root}/${GUARD_CALLER_PATH}`;
249
+ if (!sys.exists(file))
250
+ return [{ mark: '✗', text: `${GUARD_CALLER_PATH} missing, so the shared Guard does not run here`, fix: ONBOARD }];
251
+ const { pinned } = repoReleases(sys, root);
252
+ if (pinned === undefined) {
253
+ return [{ mark: '▲', text: `${WORKFLOW_PATH} pins no one version, so ${GUARD_CALLER_PATH} is not checked against it`, fix: ONBOARD }];
254
+ }
255
+ let workflow;
256
+ let text;
257
+ try {
258
+ workflow = sys.read(`${root}/${WORKFLOW_PATH}`);
259
+ text = sys.read(file);
260
+ }
261
+ catch (error) {
262
+ // fail-open: a file doctor cannot read is marked ✗, naming why, and the rest of the report still runs.
263
+ return [{ mark: '✗', text: `${GUARD_CALLER_PATH} not checked: ${message(error)}`, fix: 'make the workflow and its caller readable' }];
264
+ }
265
+ const branch = await pushBranch(workflow);
266
+ const at = await callerAt(text);
267
+ if (at === undefined) {
268
+ // onboard writes its own file again, but leaves one it did not write to the repository.
269
+ const fix = (await callerIsOnboards(text)) ? ONBOARD : `rename or delete it, then ${ONBOARD}`;
270
+ return [{ mark: '✗', text: `${GUARD_CALLER_PATH} is not the caller onboard writes: another trigger, branch, permission, job, with:, secrets: or steps`, fix }];
271
+ }
272
+ if (at.version !== pinned)
273
+ return [{ mark: '✗', text: `${GUARD_CALLER_PATH} calls the shared Guard at v${at.version}, but ${WORKFLOW_PATH} pins v${pinned}`, fix: ONBOARD }];
274
+ // A push trigger of several branches, which onboard leaves as the client has it, says no one branch: the rest is still checked.
275
+ if (branch !== undefined && at.branch !== branch)
276
+ return [{ mark: '✗', text: `${GUARD_CALLER_PATH} runs on pull requests to ${at.branch}, but ${WORKFLOW_PATH} runs pushes on ${branch}`, fix: ONBOARD }];
277
+ return [{ mark: '✓', text: `${GUARD_CALLER_PATH} calls the shared Guard at v${pinned}, as ${WORKFLOW_PATH} pins` }];
278
+ }
222
279
  /** niyam's own hook commands, this release's and older ones, by what they do. */
223
280
  const NIYAM_HOOKS = [
224
281
  ["niyam's SessionStart hook", [HOOK_COMMAND, ...OLDER_HOOK_COMMANDS]],
@@ -402,7 +459,7 @@ async function cloudDoctor(sys, io, named) {
402
459
  return report(sys, io, about, [
403
460
  ['This cloud session', session],
404
461
  [`GitHub — as ${about}`, github],
405
- ['This repo', repoFindings(sys)],
462
+ ['This repo', await repoFindings(sys)],
406
463
  ]);
407
464
  }
408
465
  /**
@@ -0,0 +1,171 @@
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
+ /**
17
+ * Whether onboard writes the caller, and doctor checks it, for a repository
18
+ * whose settings turn on what `on` says: with work rules alone, since the
19
+ * Guard refuses a change to a guard file, this one included, that no
20
+ * approved Work item's slice names, and only a repository with work rules
21
+ * has those. The one place that decides it (docs/decisions.md, 2026-11-19).
22
+ */
23
+ export function callerWanted(on) {
24
+ return on('work-rules');
25
+ }
26
+ /** How the caller's header starts: a file that starts so is onboard's, which onboard writes again whatever it holds. */
27
+ const CALLER_MARK = `# Written by ${CLI} onboard: the shared Guard's caller.`;
28
+ /**
29
+ * Whether `text` is onboard's caller, at a release and branch or edited by
30
+ * hand since: onboard writes such a file again, and refuses to overwrite any
31
+ * other, the repository's own.
32
+ */
33
+ export async function callerIsOnboards(text) {
34
+ return text.startsWith(CALLER_MARK) || (await callerAt(text)) !== undefined;
35
+ }
36
+ /** What the caller and its job may read, and nothing more: the shared Guard reads the pull request through the API. */
37
+ const READ_ONLY = ['contents: read', 'pull-requests: read', 'issues: read'];
38
+ /**
39
+ * The shared Guard's caller, as onboard writes it: run by
40
+ * pull_request_target on pull requests to `branch`, the default branch, so
41
+ * GitHub runs the default branch's copy of it, never a pull request's; read
42
+ * only, at the top and on its one job; and that job only calls the shared
43
+ * Guard at `version`, the release niyam.yml pins, with no `with:`, no
44
+ * `secrets:` and no steps, as the Guard's `isCaller` asks. Its header names
45
+ * no version, so a run that moves the pin changes the `uses:` line alone.
46
+ */
47
+ export function guardCaller(branch, version) {
48
+ return [
49
+ `${CALLER_MARK} onboard writes it again on every run, its pin`,
50
+ `# moving with ${WORKFLOW_PATH}'s; change it by running onboard, not by hand. It holds nothing a pull`,
51
+ "# request could weaken: pull_request_target runs the default branch's copy of it, and the Guard it",
52
+ `# calls runs from the ${CLI} release it pins. Its check is ${CALLER_CHECK}.`,
53
+ 'on:',
54
+ ' pull_request_target:',
55
+ ' types: [opened, edited, synchronize, reopened]',
56
+ ` branches: [${JSON.stringify(branch)}]`,
57
+ '',
58
+ 'permissions:',
59
+ ...READ_ONLY.map((line) => ` ${line}`),
60
+ '',
61
+ 'jobs:',
62
+ ` ${CALLER_JOB}:`,
63
+ ` name: ${CALLER_JOB}`,
64
+ ' permissions:',
65
+ ...READ_ONLY.map((line) => ` ${line}`),
66
+ ` uses: ${SHARED_GUARD}@v${version}`,
67
+ '',
68
+ ].join('\n');
69
+ }
70
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
71
+ /** The caller's `uses:`, at the release tag onboard pins. */
72
+ const CALLER_PIN = new RegExp(`^${escape(SHARED_GUARD)}@v(\\d+\\.\\d+\\.\\d+)$`);
73
+ /** A `uses:` line calling the shared Guard at a release, whatever else the file holds. */
74
+ const PIN_LINE = new RegExp(`^\\s*uses:\\s*["']?${escape(SHARED_GUARD)}@v(\\d+\\.\\d+\\.\\d+)["']?\\s*(?:#.*)?$`, 'gm');
75
+ /**
76
+ * The releases of the shared Guard that `text` calls, read line by line so a
77
+ * caller edited by hand still counts: onboard's downgrade guard reads them
78
+ * beside niyam.yml's, so an older CLI never moves the caller's pin back.
79
+ */
80
+ export function callerPins(text) {
81
+ return [...text.matchAll(PIN_LINE)].map((match) => match[1]);
82
+ }
83
+ /**
84
+ * The release and branch of `text` when it is the caller as onboard writes
85
+ * it at some release and branch, read as YAML, so its comments and layout do
86
+ * not count; undefined for any other file: another trigger, types, branch
87
+ * list, permission, job, `with:`, `secrets:` or steps, or a pin that is not
88
+ * a release of the shared Guard. doctor marks such a file; onboard writes
89
+ * it again when it is still onboard's (`callerIsOnboards`), and otherwise
90
+ * refuses to overwrite it.
91
+ */
92
+ export async function callerAt(text) {
93
+ const { parse } = await import('yaml');
94
+ let doc;
95
+ try {
96
+ doc = parse(text);
97
+ }
98
+ catch {
99
+ // fail-open: a file that is not YAML is no caller onboard wrote, which onboard refuses to overwrite and doctor marks.
100
+ return undefined;
101
+ }
102
+ const workflow = doc;
103
+ const uses = workflow?.jobs?.[CALLER_JOB]?.uses;
104
+ const version = typeof uses === 'string' ? CALLER_PIN.exec(uses)?.[1] : undefined;
105
+ const branches = workflow?.on?.pull_request_target?.branches;
106
+ const branch = Array.isArray(branches) && branches.length === 1 && typeof branches[0] === 'string' ? branches[0] : undefined;
107
+ if (version === undefined || branch === undefined)
108
+ return undefined;
109
+ return isDeepStrictEqual(doc, parse(guardCaller(branch, version))) ? { version, branch } : undefined;
110
+ }
111
+ /** The one branch niyam.yml's pushes run on, read as YAML; undefined when it names none or several, or does not parse. */
112
+ export async function pushBranch(text) {
113
+ const { parse } = await import('yaml');
114
+ try {
115
+ const branches = parse(text)?.on?.push?.branches;
116
+ return Array.isArray(branches) && branches.length === 1 && typeof branches[0] === 'string' ? branches[0] : undefined;
117
+ }
118
+ catch {
119
+ // fail-open: a workflow that is not YAML names no branch, which doctor says leaves the caller unchecked.
120
+ return undefined;
121
+ }
122
+ }
123
+ /**
124
+ * What onboard does with the caller, given the checkout's `before` and,
125
+ * when it is onboard's, the release and branch it is at (`at`): write it
126
+ * where there is none, move its pin to `version` and its branch to `branch`,
127
+ * or write it again where only its comments or layout differ.
128
+ */
129
+ export function callerUpdate(before, at, branch, version) {
130
+ const text = guardCaller(branch, version);
131
+ if (before === undefined)
132
+ return { kind: 'write', text };
133
+ if (before === text)
134
+ return { kind: 'same' };
135
+ const from = at !== undefined && at.version !== version ? at.version : undefined;
136
+ const moved = at !== undefined && at.branch !== branch ? branch : undefined;
137
+ if (from === undefined && moved === undefined)
138
+ return { kind: 'rewrite', text };
139
+ return { kind: 'repin', text, ...(from === undefined ? {} : { from }), ...(moved === undefined ? {} : { branch: moved }) };
140
+ }
141
+ /** What a caller update changes, in a few words for the plan. */
142
+ export function callerDetail(update, version) {
143
+ if (update.kind === 'write')
144
+ return `new, the shared Guard at v${version}`;
145
+ if (update.kind === 'rewrite')
146
+ return 'written again';
147
+ return [...(update.from ? [`pin → v${version}`] : []), ...(update.branch ? [`branch → ${update.branch}`] : [])].join(', ');
148
+ }
149
+ /** What a caller update changes, in full for the pull request's description. */
150
+ export function callerWhat(update, version, branch) {
151
+ 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`;
152
+ if (update.kind === 'write')
153
+ return `write ${GUARD_CALLER_PATH}, the shared Guard's caller: ${holds}`;
154
+ if (update.kind === 'rewrite')
155
+ return `write ${GUARD_CALLER_PATH}, the shared Guard's caller, again as onboard writes it: ${holds}`;
156
+ 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}`] : [])];
157
+ return `in ${GUARD_CALLER_PATH}, the shared Guard's caller, ${parts.join(' and ')}`;
158
+ }
159
+ /**
160
+ * The step a public repository's owner takes once, for onboard's "By hand"
161
+ * and the pull request's "Left to do by hand": from 2026-12-02 GitHub blocks
162
+ * pull_request_target in public repositories without a policy that allows
163
+ * it for the workflow, and the caller runs on nothing else.
164
+ */
165
+ export function policySteps(slug) {
166
+ const at = `${GITHUB_WEB}/${slug}/settings/actions`;
167
+ return {
168
+ 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.`,
169
+ 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.`,
170
+ };
171
+ }
@@ -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, callerWanted, 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). onboard's own, edited by hand or not, is written again; a file of that name
1429
+ // onboard did not write is the repository's own: refused before any plan, so nothing changes.
1430
+ const callerNeeded = callerWanted(on);
1431
+ const callerBefore = callerNeeded ? fileAt(GUARD_CALLER_PATH) : undefined;
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,19 @@ 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
+ if (callerNeeded) {
1573
+ const update = planned === undefined ? undefined : callerUpdate(callerBefore, callerHad, planned, version);
1574
+ const detail = update === undefined ? (callerBefore === undefined ? `new, the shared Guard at v${version}` : 'write or update') : update.kind === 'same' ? undefined : callerDetail(update, version);
1575
+ if (detail !== undefined)
1576
+ pull.push({ label: 'guard caller', detail });
1577
+ }
1546
1578
  if (on('board')) {
1547
1579
  github.push({ label: 'board', detail: 'set up or check' });
1548
1580
  let approved;
@@ -1715,6 +1747,15 @@ export async function onboard(sys, io, args = []) {
1715
1747
  return false;
1716
1748
  if (workflowNeeded)
1717
1749
  workflowFor(reach.branch);
1750
+ if (callerNeeded) {
1751
+ callerFor(reach.branch);
1752
+ // From 2026-12-02 GitHub runs pull_request_target in a public repository only where a policy allows it.
1753
+ if (reach.public) {
1754
+ const policy = policySteps(slug);
1755
+ byHand.push(policy.byHand);
1756
+ later.push(policy.later);
1757
+ }
1758
+ }
1718
1759
  // From the workflow the pull request leaves, worked out only now that GitHub has said the branch.
1719
1760
  const text = fileAt(WORKFLOW_PATH);
1720
1761
  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.4",
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": {