@veda-hq/niyam 0.6.19 → 0.6.21

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
@@ -26,12 +26,10 @@ Server and GitHub Enterprise Cloud with data residency (GHE.com) are not
26
26
  supported yet; every GitHub address in the CLI comes from one host constant,
27
27
  so a host setting can be added later.
28
28
 
29
- Claude Code is the only supported agent runner. The agent identity and the
30
- GitHub lock reach a session through Claude Code's SessionStart hook and
31
- `CLAUDE_ENV_FILE`, so an agent run from another tool (Codex, Cursor,
32
- Copilot's agent, Aider, a plain script) gets neither, and only the pull
33
- request's PR identity check catches its work, after the push. Other runners
34
- wait for adoption outside Athya (#50).
29
+ Claude Code is one agent runner among others. Its SessionStart hook gives a
30
+ session the agent identity and the GitHub lock; an agent run from any other
31
+ tool on a Mac (Codex, Cursor, Copilot's agent, Aider, a plain script) gets
32
+ the same through `niyam env` (see Agents outside Claude Code below).
35
33
 
36
34
  ## Agent identity on a Mac
37
35
 
@@ -299,6 +297,51 @@ It closes with `└ All good` or `└ N to fix`, and exits 1 when anything is
299
297
  terminal. In a Claude cloud session it runs the cloud checks instead (see
300
298
  Claude cloud sessions below).
301
299
 
300
+ ### Agents outside Claude Code
301
+
302
+ `niyam env` gives any shell the lines session-start gives a Claude Code
303
+ session: the GitHub lock, then, when this Mac has the session file `machine`
304
+ wrote for the repo's agent, exactly as `machine` writes it, that file, which
305
+ replaces the lock with the agent's identity. Run it in the repo, with the
306
+ agent's runner started from it:
307
+
308
+ ```sh
309
+ niyam env -- codex
310
+ niyam env -- aider --model sonnet
311
+ ```
312
+
313
+ `niyam env -- <command>` runs the command under those lines through
314
+ `/bin/sh`, so a runner started this way cannot start without niyam. To give
315
+ a shell itself the identity, as a runner's own startup script would:
316
+
317
+ ```sh
318
+ eval "$(niyam env)"
319
+ ```
320
+
321
+ Lead with the first form for runners: when niyam is missing from PATH,
322
+ `eval "$(niyam env)"` evaluates nothing and leaves the shell acting as the
323
+ owner. A script can guard it with `lines=$(niyam env) || exit` before
324
+ `eval "$lines"`, which also stops when GitHub stays locked out. A shell
325
+ tracing its commands (`set -x`) prints the token as `eval` exports it, so
326
+ turn tracing off around it, or use the wrapper, whose shell traces nothing.
327
+
328
+ One line on standard error says which account the shell works as, or why
329
+ GitHub stays locked out, with the fix; printing exits 0 as the agent and 77
330
+ when locked, and every failure still prints the lock, never the owner's
331
+ login. Run with a command, it runs the command locked when it cannot work as
332
+ the agent, and exits with the command's code. The token is never in its
333
+ output: the session file holds the keychain command that reads it, and the
334
+ shell runs that command itself.
335
+
336
+ The session file sets `NIYAM_AGENT`, so the pre-push hook checks every push
337
+ from such a shell, as it does in Claude Code. What other runners lack is
338
+ Claude Code's PreToolUse guard; the lock and the pre-push hook hold there,
339
+ as they hold for what a script runs inside Claude Code. A runner started
340
+ without `niyam env` acts as the owner, since nothing on the Mac tells its
341
+ shell from the owner's (P-18), and only PR identity catches its work, after
342
+ the push. Claude cloud sessions keep session-start's cloud path; there, and
343
+ on any platform without a token store, `niyam env` prints the lock alone.
344
+
302
345
  ## Adopting
303
346
 
304
347
  1. On each Mac that runs agent sessions: `niyam machine <agent>`.
@@ -361,7 +404,8 @@ Claude cloud sessions below).
361
404
  the lock in `env`, a SessionStart hook running `niyam session-start`, a
362
405
  PreToolUse hook running `niyam guard` (each through the launcher `machine`
363
406
  writes, else `niyam` on PATH; hooks an older release wrote are replaced
364
- in place, 0.6.10's too), and `permissions.allow` rules
407
+ in place, 0.6.10's too; where sarathi runs the hooks, both go to
408
+ `.claude/sarathi.json`, below), and `permissions.allow` rules
365
409
  for `niyam review-thread` (replacing the rule under the old command) and for
366
410
  the app's `mcp__ccd_pr__bind_pr`, `mcp__ccd_pr__get_status` and
367
411
  `mcp__ccd_pr__set_monitor`, which turn Auto-fix on (a rerun adds only
@@ -459,7 +503,26 @@ Claude cloud sessions below).
459
503
  requests that change the files it matches, and the repo's own rules
460
504
  decide whether that review is required. An existing `.claude/settings.json`
461
505
  keeps its layout: `onboard` adds only its entries, and replaces the hook
462
- entries an older release wrote where they stand. The repository needs at
506
+ entries an older release wrote where they stand.
507
+
508
+ **Under sarathi.** A project that runs its hooks through sarathi, as veda
509
+ does, keeps one settings entry per event, sarathi's, and lists the
510
+ handlers in `.claude/sarathi.json`. For each event where that file exists
511
+ and `.claude/settings.json` runs `sarathi hook <Event>` or
512
+ `.claude/hooks/sarathi.sh <Event>`, with a matcher that lets niyam's hook
513
+ fire, `onboard` writes the hook into `.claude/sarathi.json` instead:
514
+ `SessionStart` as `{ "command": …, "timeout": 600 }` (the time Claude Code
515
+ gives it in the settings, for session-start's installs), and `PreToolUse`
516
+ as `{ "matcher": "Bash", "command": …, "failClosed": true }`. It replaces
517
+ an older release's command there in place, takes niyam's hooks out of
518
+ `.claude/settings.json`, and raises sarathi's own entry's timeout to the
519
+ handler's when it is shorter, as `sarathi check --settings` asks. The lock
520
+ and the `permissions` rules stay in `.claude/settings.json`. The work
521
+ rules count `.claude/sarathi.json` as one of the files `onboard` writes.
522
+ `niyam doctor` warns under "This repo" (`▲`) about a hook in both files
523
+ for the same event, which then runs twice: `onboard` again moves
524
+ niyam's own; any other is the repo's to take out of
525
+ `.claude/settings.json`. The repository needs at
463
526
  least one commit. The pull request checks read the settings from the base
464
527
  branch, so a pull request cannot rename the agent it is checked against.
465
528
  The pull request that first commits them, `onboard`'s, passes PR identity, Work rules
@@ -1139,7 +1202,7 @@ or in a file, and it never falls back to the owner's `gh` logins, git
1139
1202
  password or SSH. Use the launcher line above, as the hooks `onboard` writes do:
1140
1203
  the app's hooks may have no node on their `PATH`. `niyam doctor`,
1141
1204
  run in the client repo, warns under "This repo" about each hook in `.claude/settings.json` or
1142
- `.claude/settings.local.json` whose command, or the repo script it runs,
1205
+ `.claude/settings.local.json`, and each handler in `.claude/sarathi.json`, whose command, or the repo script it runs,
1143
1206
  calls `gh` or git's remote commands outside `as-agent`. A script that
1144
1207
  imports a Python module tracked in the repo whose code runs `as-agent` (a
1145
1208
  helper wrapping each `gh` call) counts as routed through it; the hook's
@@ -1357,7 +1420,7 @@ tag and the commit. Install the attached package on each machine with pnpm,
1357
1420
  once; nothing is built on install:
1358
1421
 
1359
1422
  ```bash
1360
- pnpm add -g https://github.com/veda-hq/niyam/releases/download/v0.6.19/veda-hq-niyam-0.6.19.tgz
1423
+ pnpm add -g https://github.com/veda-hq/niyam/releases/download/v0.6.21/veda-hq-niyam-0.6.21.tgz
1361
1424
  ```
1362
1425
 
1363
1426
  The package puts one command on `PATH`, `niyam`. Since P-57 a release
@@ -1426,11 +1489,21 @@ pnpm install
1426
1489
  pnpm check
1427
1490
  ```
1428
1491
 
1429
- `pnpm check` typechecks, runs the tests with a coverage floor (95% lines and
1492
+ `pnpm check` typechecks, lints, runs the tests with a coverage floor (95% lines and
1430
1493
  functions, 90% branches), builds `dist/` and runs it. `pnpm scan:secrets` runs
1431
1494
  Gitleaks and TruffleHog over the working tree; CI runs both over the whole
1432
1495
  history.
1433
1496
 
1497
+ `pnpm lint` lints `src/` with veda's released ESLint rules,
1498
+ `@veda-hq/eslint-plugin-shuddhi`: its error-handling, input-parsing and
1499
+ test-lint families, the type-aware `strict-scalar-parse` among them. The lint
1500
+ tools live in the `lint/` workspace package, pinned exactly, with TypeScript
1501
+ 5.9 for the parser, since shuddhi needs TypeScript 5's compiler API; the root
1502
+ builds with TypeScript 7. Findings older than the lint are held in
1503
+ `lint/eslint-suppressions.json`, ESLint's bulk suppressions, so new code is
1504
+ checked from the start. A fix that clears one leaves a suppression unused,
1505
+ which fails the lint until `pnpm lint --prune-suppressions` drops it.
1506
+
1434
1507
  ### Guard
1435
1508
 
1436
1509
  The `guard` workflow (`.github/workflows/guard.yml`) runs on
package/dist/as-agent.js CHANGED
@@ -3,6 +3,7 @@ import { AGENT_VAR } from './names.js';
3
3
  import { cloudToken } from './cloud.js';
4
4
  import { recordedAgent, reachesGitHub, refusal } from './guard.js';
5
5
  import { GUARD_COMMAND, HOOK_COMMAND, OLDER_GUARD_COMMANDS, OLDER_HOOK_COMMANDS } from './onboard.js';
6
+ import { SARATHI_PATH } from './onboard-pull.js';
6
7
  import { tokenStore, unsupported } from './token-store.js';
7
8
  /**
8
9
  * What `as-agent` exits with when it runs nothing because the session does
@@ -122,8 +123,8 @@ function cloudEnv(sys, agent) {
122
123
  const SETTINGS_FILES = ['.claude/settings.json', '.claude/settings.local.json'];
123
124
  const OWN_COMMANDS = new Set([HOOK_COMMAND, GUARD_COMMAND, ...OLDER_HOOK_COMMANDS, ...OLDER_GUARD_COMMANDS]);
124
125
  /**
125
- * The client's hooks, in the repo around the working directory, that reach
126
- * GitHub outside `as-agent`, so get the lock's placeholder token: by the
126
+ * The client's hooks, in the repo around the working directory, sarathi's
127
+ * handlers among them (`clientHooks`), that reach GitHub outside `as-agent`, so get the lock's placeholder token: by the
127
128
  * hook's command, or by a script in the repo it names. Like the guard, it
128
129
  * reads text, so a script that runs another script is missed. Comments and
129
130
  * docstrings are left out, so prose that names gh or git push is not a call.
@@ -138,32 +139,56 @@ export function hooksHittingLock(sys) {
138
139
  const root = top.stdout.trim();
139
140
  const cloud = sys.env.CLAUDE_CODE_REMOTE === 'true';
140
141
  const found = [];
141
- for (const file of SETTINGS_FILES) {
142
- let settings;
142
+ for (const { file, event, command, kind } of clientHooks(sys, root)) {
143
+ if (OWN_COMMANDS.has(command))
144
+ continue;
145
+ const script = scriptOf(sys, root, command);
146
+ // A routed script's own text is not judged; the command that runs it still is, and then names the hook.
147
+ const judgedScript = script && !routedByHelper(sys, root, script.text) ? script : undefined;
148
+ const [line, code] = [withoutComments(command), withoutComments(judgedScript?.text ?? '')];
149
+ const judged = cloud ? `${line}\n${code}` : `${beforeCloudOnly(line)}\n${beforeCloudOnly(code)}`;
150
+ if (reachesGitHub(withoutAsAgent(judged)))
151
+ found.push(`${file} ${event} ${kind} ${judgedScript ? judgedScript.path : JSON.stringify(command)}`);
152
+ }
153
+ return found;
154
+ }
155
+ /**
156
+ * Every command the client's hooks run, in the repo at `root`: the
157
+ * settings files' hooks, then the handlers `.claude/sarathi.json` lists,
158
+ * which sarathi runs for the settings (P-66). A file that is missing or not
159
+ * JSON gives none.
160
+ */
161
+ export function clientHooks(sys, root) {
162
+ const found = [];
163
+ const read = (file) => {
143
164
  try {
144
- settings = JSON.parse(sys.read(`${root}/${file}`));
165
+ const parsed = JSON.parse(sys.read(`${root}/${file}`));
166
+ return typeof parsed === 'object' && parsed !== null ? parsed : undefined;
145
167
  }
146
168
  catch {
147
- continue;
169
+ return undefined;
148
170
  }
149
- for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
150
- for (const group of Array.isArray(groups) ? groups : []) {
171
+ };
172
+ const events = (hooks) => typeof hooks === 'object' && hooks !== null ? Object.entries(hooks).map(([event, list]) => [event, Array.isArray(list) ? list : []]) : [];
173
+ for (const file of SETTINGS_FILES) {
174
+ for (const [event, groups] of events(read(file)?.hooks)) {
175
+ for (const group of groups) {
151
176
  const hooks = group?.hooks;
152
177
  for (const hook of Array.isArray(hooks) ? hooks : []) {
153
178
  const command = hook?.command;
154
- if (typeof command !== 'string' || OWN_COMMANDS.has(command))
155
- continue;
156
- const script = scriptOf(sys, root, command);
157
- // A routed script's own text is not judged; the command that runs it still is, and then names the hook.
158
- const judgedScript = script && !routedByHelper(sys, root, script.text) ? script : undefined;
159
- const [line, code] = [withoutComments(command), withoutComments(judgedScript?.text ?? '')];
160
- const judged = cloud ? `${line}\n${code}` : `${beforeCloudOnly(line)}\n${beforeCloudOnly(code)}`;
161
- if (reachesGitHub(withoutAsAgent(judged)))
162
- found.push(`${file} ${event} hook ${judgedScript ? judgedScript.path : JSON.stringify(command)}`);
179
+ if (typeof command === 'string')
180
+ found.push({ file, event, command, kind: 'hook' });
163
181
  }
164
182
  }
165
183
  }
166
184
  }
185
+ for (const [event, entries] of events(read(SARATHI_PATH)?.hooks)) {
186
+ for (const entry of entries) {
187
+ const command = entry?.command;
188
+ if (typeof command === 'string')
189
+ found.push({ file: SARATHI_PATH, event, command, kind: 'handler' });
190
+ }
191
+ }
167
192
  return found;
168
193
  }
169
194
  /**
@@ -200,6 +200,14 @@ export function cubicDismiss(sys, io, args) {
200
200
  }
201
201
  const file = settings.file;
202
202
  const path = `${root}/${file}`;
203
+ // A link, at the file or a folder above it, would take the write out of the repository; git status does not show it.
204
+ try {
205
+ sys.confine(root, path);
206
+ }
207
+ catch (error) {
208
+ io.err(`✗ ${error instanceof Error ? error.message : String(error)}; nothing was written`);
209
+ return 1;
210
+ }
203
211
  const changed = run(['status', '--porcelain', '--', file]).trim();
204
212
  if (changed) {
205
213
  io.err(`✗ ${file} already differs from HEAD (${changed}); commit or restore it first`);
package/dist/doctor.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import { EXPIRY_WARNING_DAYS, SETTINGS_PATH, account, agentFrom, agentIn, anyLogin, either, hasSettings, loadSettings, repoAt, sameLogin, checkToken, keyBody, keyPairProblem, launcherPath, pathsFor, sessionFileIs, signingKeys, tokenInfo, } from './agent.js';
2
- import { LOCKED, hooksHittingLock } from './as-agent.js';
2
+ import { LOCKED, clientHooks, hooksHittingLock } from './as-agent.js';
3
3
  import { FROM_SETUP, cloudLogin, fileFromSetup, ranFromSetup, repoReleases } from './cloud.js';
4
4
  import { featuresIn } from './features.js';
5
5
  import { typesDrift } from './issue-types.js';
6
6
  import { closing, findingLines, heading, painter, tilde } from './layout.js';
7
7
  import { exposure, exposureFindings, movedFindings, readDeclined, setAside } from './lockout.js';
8
- import { CLOUD_SETUP_PATH, HOOKS_PATH } from './onboard-pull.js';
8
+ import { CLOUD_SETUP_PATH, HOOKS_PATH, SARATHI_PATH } from './onboard-pull.js';
9
9
  import { leftoverDir, leftoverToken } from './machine.js';
10
- import { missingAutoFixRules } from './onboard.js';
10
+ import { GUARD_COMMAND, HOOK_COMMAND, OLDER_GUARD_COMMANDS, OLDER_HOOK_COMMANDS, missingAutoFixRules, sarathiRunner } from './onboard.js';
11
11
  import { isOrganisation } from './owner-login.js';
12
12
  import { leftBehind } from './owner-step.js';
13
13
  import { repoRoot } from './session-start.js';
@@ -179,8 +179,50 @@ function repoFindings(sys) {
179
179
  fix: `run its gh or git via niyam as-agent --session <session_id> -- (exit ${LOCKED} when not the agent)`,
180
180
  })),
181
181
  ...autoFixFindings(sys),
182
+ ...twiceFindings(sys),
182
183
  ];
183
184
  }
185
+ /** niyam's own hook commands, this release's and older ones, by what they do. */
186
+ const NIYAM_HOOKS = [
187
+ ["niyam's SessionStart hook", [HOOK_COMMAND, ...OLDER_HOOK_COMMANDS]],
188
+ ["niyam's guard hook", [GUARD_COMMAND, ...OLDER_GUARD_COMMANDS]],
189
+ ];
190
+ /**
191
+ * Hooks that run twice: a command in both `.claude/settings.json` and the
192
+ * handlers `.claude/sarathi.json` lists for the same event, where the
193
+ * settings run sarathi for it (P-66). onboard moves niyam's own; any other
194
+ * is the repo's to take out of the settings.
195
+ */
196
+ function twiceFindings(sys) {
197
+ let hooks;
198
+ let settings;
199
+ try {
200
+ const root = repoRoot(sys);
201
+ hooks = clientHooks(sys, root);
202
+ settings = JSON.parse(sys.read(`${root}/${HOOKS_PATH}`));
203
+ }
204
+ catch {
205
+ // Outside a clone, or settings doctor cannot read: no hook in them runs twice that it can tell.
206
+ return [];
207
+ }
208
+ const handlers = new Set(hooks.filter((hook) => hook.file === SARATHI_PATH).map((hook) => `${hook.event}\n${hook.command}`));
209
+ const seen = new Set();
210
+ const found = [];
211
+ for (const { file, event, command } of hooks) {
212
+ const key = `${event}\n${command}`;
213
+ if (file !== HOOKS_PATH || !handlers.has(key) || seen.has(key) || !sarathiRunner(settings, event))
214
+ continue;
215
+ seen.add(key);
216
+ const own = NIYAM_HOOKS.find(([, commands]) => commands.includes(command))?.[0];
217
+ const named = own ?? `the ${event} hook ${JSON.stringify(command.length > 60 ? `${command.slice(0, 57)}...` : command)}`;
218
+ found.push({
219
+ mark: '▲',
220
+ text: `${named} is in both ${HOOKS_PATH} and ${SARATHI_PATH} for ${event}, so it runs twice`,
221
+ fix: own ? ONBOARD : `take it out of ${HOOKS_PATH}; sarathi runs it`,
222
+ });
223
+ }
224
+ return found;
225
+ }
184
226
  /**
185
227
  * Which of onboard's Auto-fix rules the repo's `.claude/settings.json`
186
228
  * lacks, so the auto-mode classifier refuses an agent session turning
package/dist/env.js ADDED
@@ -0,0 +1,79 @@
1
+ import { lockScript } from './agent.js';
2
+ import { LOCKED } from './as-agent.js';
3
+ import { localIdentity } from './session-start.js';
4
+ /** The arguments of `env`: none, or `-- <command> [args...]` to run under its lines. */
5
+ export function envArgs(args) {
6
+ if (args.length === 0)
7
+ return { args: [] };
8
+ const [dashes, command, ...rest] = args;
9
+ if (dashes !== '--')
10
+ throw new Error(`env takes no options; to run a command under it, put -- before the command, not "${dashes}"`);
11
+ if (!command)
12
+ throw new Error('env needs a command after --');
13
+ return { command, args: rest };
14
+ }
15
+ /**
16
+ * Runs the lines in $1, then the command after them, in their place.
17
+ * The lines only export and unset variables, and their token command runs
18
+ * here, in the shell, so the token never passes through niyam's output.
19
+ */
20
+ export const RUN_UNDER = 'eval "$1" && shift && exec "$@"';
21
+ /**
22
+ * For agents run from any tool on a Mac, not only Claude Code
23
+ * (docs/decisions.md, P-68). The shell lines session-start gives a Claude
24
+ * Code session: the GitHub lock, then, when this Mac has the session file
25
+ * `machine` wrote for the repo's agent exactly as it writes it, that file,
26
+ * which replaces the lock with the agent's identity (`localIdentity`). With
27
+ * no command it prints them, for `eval "$(niyam env)"`; with `-- <command>`
28
+ * it runs the command under them through /bin/sh, so a runner started that
29
+ * way never starts without niyam. Either way one line on standard error
30
+ * says which account the shell works as, or why GitHub stays locked out,
31
+ * and the owner's login is never a fallback. The token is never in the
32
+ * output: the session file holds the token store's read command, which the
33
+ * shell runs itself. Printing exits 0 as the agent and LOCKED otherwise;
34
+ * running exits with the command's code, locked or not.
35
+ */
36
+ export function env(sys, io, parsed) {
37
+ const local = localIdentity(sys);
38
+ const lines = local.script === undefined ? lockScript(sys.home) : `${lockScript(sys.home)}\n${local.script}`;
39
+ if ('reason' in local) {
40
+ io.err(`niyam: GitHub is locked out of this shell: ${local.reason}. Do not work around the lock; ${local.fix}.`);
41
+ }
42
+ else {
43
+ io.err(`niyam: this shell works as ${local.agent} on GitHub.`);
44
+ }
45
+ if (parsed.command === undefined) {
46
+ io.out(forEval(lines));
47
+ return 'reason' in local ? LOCKED : 0;
48
+ }
49
+ const result = sys.exec('/bin/sh', ['-c', RUN_UNDER, 'niyam env', lines, parsed.command, ...parsed.args], { interactive: true });
50
+ // With standard error passed through, what is left is why the shell could not start.
51
+ if (result.stderr)
52
+ io.err(`niyam env: ${parsed.command}: ${result.stderr.trim()}`);
53
+ return result.code;
54
+ }
55
+ /**
56
+ * The lines as `env` prints them: without comments or blank lines, each
57
+ * ended by `;`, so an unquoted `eval $(niyam env)`, whose newlines the shell
58
+ * turns into spaces, runs every one rather than one comment swallowing the
59
+ * rest. Unquoted, a value holding two spaces in a row or a glob character
60
+ * would still change, so the README quotes it; niyam's own values hold none.
61
+ */
62
+ export function forEval(lines) {
63
+ return lines
64
+ .split('\n')
65
+ .filter((line) => line.trim() !== '' && !line.startsWith('#'))
66
+ .map((line) => `${line};`)
67
+ .join('\n');
68
+ }
69
+ /** What `env` prints when its own check fails: the lock alone, so `eval` still locks the shell. */
70
+ export function envFailed(home, io, parsed, error) {
71
+ const why = error instanceof Error ? error.message : String(error);
72
+ if (parsed.command !== undefined) {
73
+ io.err(`niyam env: ran nothing, because the check failed: ${why}`);
74
+ return LOCKED;
75
+ }
76
+ io.err(`niyam: GitHub is locked out of this shell, because the check failed: ${why}`);
77
+ io.out(forEval(lockScript(home)));
78
+ return LOCKED;
79
+ }
package/dist/handoff.js CHANGED
@@ -295,6 +295,7 @@ function lintContext(h, changedFiles) {
295
295
  };
296
296
  }
297
297
  const append = (sys, root, entry) => {
298
+ sys.confine(root, `${root}/${RUN_LOG}`);
298
299
  sys.mkdir(`${root}/.tmp/push`);
299
300
  sys.append(`${root}/${RUN_LOG}`, `${JSON.stringify(entry)}\n`);
300
301
  };
@@ -304,6 +305,8 @@ export async function gate(sys, io, base, callSite = 'pre-push-hook') {
304
305
  if (!settingsHere(sys, base).settings)
305
306
  return 0;
306
307
  const h = here(sys, base);
308
+ // Refused before any work, so a push is not judged only to fail at its record.
309
+ sys.confine(h.root, `${h.root}/${RUN_LOG}`);
307
310
  const ref = h.base;
308
311
  const { branch, changedFiles, triggers, baseSha, headSha } = collect(sys, h, ref);
309
312
  const log = sys.exists(`${h.root}/${RUN_LOG}`) ? parseRunLog(sys.read(`${h.root}/${RUN_LOG}`)).entries : [];
@@ -467,6 +470,8 @@ export async function handoff(sys, io, args) {
467
470
  io.out(JSON.stringify({ branch, baseRef: base, changedFiles: changedFiles.length, triggers, fired: fired(triggers), runLog: RUN_LOG }, null, 2));
468
471
  return 0;
469
472
  }
473
+ // Refused before --open-brief opens an issue that no record would then name.
474
+ sys.confine(h.root, `${h.root}/${RUN_LOG}`);
470
475
  const disposition = parsed.disposition;
471
476
  const briefs = [...parsed.briefs];
472
477
  if (parsed.openBrief !== undefined) {
package/dist/jsonedit.js CHANGED
@@ -130,22 +130,39 @@ function addMember(text, objectStart, name, value, layout) {
130
130
  ? `${text.slice(0, at)},${eol}${member}${eol}${outer}}${text.slice(close + 1)}`
131
131
  : `${text.slice(0, objectStart)}{${eol}${member}${eol}${outer}}${text.slice(close + 1)}`;
132
132
  }
133
+ /** An array index in a path: digits alone. */
134
+ const INDEX = /^\d+$/;
135
+ /** The span of `name` in the value starting at `start`: a member of an object, or an element of an array by its index. */
136
+ function childSpan(text, start, name) {
137
+ if (text[start] === '{')
138
+ return memberSpan(text, start, name);
139
+ return text[start] === '[' && INDEX.test(name) ? elementSpans(text, start)[Number(name)] : undefined;
140
+ }
133
141
  /**
134
- * The text with each value at `path` that `replace` maps to something new
135
- * swapped for it where it stands, and how many were swapped. `*` in `path`
136
- * stands for every element of an array; a value of another shape on the way
137
- * is passed over.
142
+ * The spans of the values at `path`: `*` stands for every element of an
143
+ * array, digits for one element; a value of another shape on the way is
144
+ * passed over.
138
145
  */
139
- export function replaceValues(text, path, replace) {
146
+ function spansAt(text, path) {
140
147
  let spans = [{ start: skipSpace(text, 0), end: text.length }];
141
148
  for (const name of path) {
142
149
  spans = spans.flatMap(({ start }) => {
143
150
  if (name === '*')
144
151
  return text[start] === '[' ? elementSpans(text, start) : [];
145
- const span = text[start] === '{' ? memberSpan(text, start, name) : undefined;
152
+ const span = childSpan(text, start, name);
146
153
  return span ? [span] : [];
147
154
  });
148
155
  }
156
+ return spans;
157
+ }
158
+ /**
159
+ * The text with each value at `path` that `replace` maps to something new
160
+ * swapped for it where it stands, and how many were swapped. `*` in `path`
161
+ * stands for every element of an array, digits for one element; a value of
162
+ * another shape on the way is passed over.
163
+ */
164
+ export function replaceValues(text, path, replace) {
165
+ const spans = spansAt(text, path);
149
166
  let out = text;
150
167
  let replaced = 0;
151
168
  // Last first, so each swap leaves the spans before it where they were.
@@ -158,9 +175,38 @@ export function replaceValues(text, path, replace) {
158
175
  }
159
176
  return { text: out, replaced };
160
177
  }
178
+ /**
179
+ * The text without the elements of each array at `path` that `drop` takes,
180
+ * and how many went. The elements kept stay as written, with the array's
181
+ * own separators between them; an array left with none becomes `[]`. `path`
182
+ * reads as in replaceValues.
183
+ */
184
+ export function removeElements(text, path, drop) {
185
+ let out = text;
186
+ let removed = 0;
187
+ // Last first, so each edit leaves the spans before it where they were.
188
+ for (const array of spansAt(text, path).reverse()) {
189
+ if (text[array.start] !== '[')
190
+ continue;
191
+ const elements = elementSpans(text, array.start);
192
+ const kept = elements.filter((span) => !drop(JSON.parse(text.slice(span.start, span.end))));
193
+ if (kept.length === elements.length)
194
+ continue;
195
+ removed += elements.length - kept.length;
196
+ const first = elements[0];
197
+ const last = elements.at(-1);
198
+ const between = elements.length > 1 ? text.slice(first.end, elements[1].start) : '';
199
+ const inside = kept.length === 0
200
+ ? '[]'
201
+ : `${text.slice(array.start, first.start)}${kept.map((span) => text.slice(span.start, span.end)).join(between)}${text.slice(last.end, array.end)}`;
202
+ out = `${out.slice(0, array.start)}${inside}${out.slice(array.end)}`;
203
+ }
204
+ return { text: out, removed };
205
+ }
161
206
  /**
162
207
  * The text with `object.key` set to `value`: swapped where it stands when
163
208
  * the key is there, else added last, creating the objects on the way.
209
+ * Digits in `path` walk into an array's element, which must be there.
164
210
  * Refuses, changing nothing, when a value on the way is not an object.
165
211
  */
166
212
  export function setMember(text, path, key, value) {
@@ -169,10 +215,15 @@ export function setMember(text, path, key, value) {
169
215
  const layout = layoutOf(text);
170
216
  let objectStart = skipSpace(text, 0);
171
217
  for (const [i, name] of path.entries()) {
172
- const span = memberSpan(text, objectStart, name);
173
- if (!span)
218
+ const span = childSpan(text, objectStart, name);
219
+ if (!span) {
220
+ if (text[objectStart] !== '{')
221
+ throw new Error(`${path.slice(0, i + 1).join('.')} is not there`);
174
222
  return addMember(text, objectStart, name, nest([...path.slice(i + 1), key], value), layout);
175
- if (text[span.start] !== '{')
223
+ }
224
+ // An array is walked into only by an index.
225
+ const into = text[span.start] === '[' && INDEX.test(path[i + 1] ?? '');
226
+ if (text[span.start] !== '{' && !into)
176
227
  throw new Error(`${path.slice(0, i + 1).join('.')} is not an object`);
177
228
  objectStart = span.start;
178
229
  }
@@ -207,6 +207,7 @@ export function readStopNote(sys, root) {
207
207
  return sys.exists(path) ? JSON.parse(sys.read(path)) : null;
208
208
  }
209
209
  export function writeStopNote(sys, root, note) {
210
+ sys.confine(root, notePath(root));
210
211
  sys.mkdir(dirname(notePath(root)));
211
212
  sys.write(notePath(root), `${JSON.stringify(note)}\n`);
212
213
  }
@@ -315,6 +316,15 @@ export async function stopHook(sys, input, err) {
315
316
  const settings = settingsAt(sys, root);
316
317
  const session = typeof data.session_id === 'string' && data.session_id ? data.session_id : undefined;
317
318
  const file = `${root}/${STORE}/${(session ?? 'unknown').replace(/[^\w-]/g, '_')}.json`;
319
+ // Both records it may write, checked before any is read or written; the hook fails open, so it says why.
320
+ try {
321
+ sys.confine(root, file);
322
+ sys.confine(root, notePath(root));
323
+ }
324
+ catch (error) {
325
+ err?.(`niyam keep-going: ${error instanceof Error ? error.message : String(error)}`);
326
+ return '';
327
+ }
318
328
  const previous = sys.exists(file) ? JSON.parse(sys.read(file)) : null;
319
329
  const facts = await gather(sys, root, settings, Boolean(data.agent_id), session, err);
320
330
  const decision = decide(facts, previous, settings);
@@ -357,7 +367,12 @@ export function recordStop(sys, reason) {
357
367
  catch {
358
368
  // The note matters more than the name it is told to.
359
369
  }
360
- writeStopNote(sys, root, { branch, head, reason: reason.trim(), at: sys.now().toISOString() });
370
+ try {
371
+ writeStopNote(sys, root, { branch, head, reason: reason.trim(), at: sys.now().toISOString() });
372
+ }
373
+ catch (error) {
374
+ return { ok: false, message: `No stop note written: ${error instanceof Error ? error.message : String(error)}` };
375
+ }
361
376
  return { ok: true, message: `Stop note written for ${branch} at ${head.slice(0, 9)}; a new commit voids it. Tell ${owner} what happened, why, and the options; then stop.` };
362
377
  }
363
378
  /**
@@ -3,6 +3,8 @@ import { GITHUB_WEB } from './host.js';
3
3
  /** The branch onboard's pull request comes from: a run again updates the same one. */
4
4
  export const ONBOARD_BRANCH = 'niyam/onboard';
5
5
  export const HOOKS_PATH = '.claude/settings.json';
6
+ /** sarathi's hook list, where a project runs its hooks through sarathi: niyam's hooks go there as handlers (P-66). */
7
+ export const SARATHI_PATH = '.claude/sarathi.json';
6
8
  /** The client's workflow. */
7
9
  export const WORKFLOW_PATH = '.github/workflows/niyam.yml';
8
10
  /** The repo's cloud setup file, which installs the pinned CLI in Claude cloud sessions. */
@@ -13,7 +15,7 @@ export const CLOUD_SETUP_PATH = '.github/niyam/cloud-setup.sh';
13
15
  */
14
16
  export const LEFTOVER_CLOUD_SETUP_PATH = '.github/process-rules/cloud-setup.sh';
15
17
  /** Every file onboard's pull request may change. */
16
- export const ONBOARD_FILES = [SETTINGS_PATH, HOOKS_PATH, WORKFLOW_PATH, CLOUD_SETUP_PATH, LEFTOVER_CLOUD_SETUP_PATH];
18
+ export const ONBOARD_FILES = [SETTINGS_PATH, HOOKS_PATH, SARATHI_PATH, WORKFLOW_PATH, CLOUD_SETUP_PATH, LEFTOVER_CLOUD_SETUP_PATH];
17
19
  /** 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). */
18
20
  export const MOVED_FILES = { [LEFTOVER_CLOUD_SETUP_PATH]: CLOUD_SETUP_PATH };
19
21
  /** A subject's leading emoji, or gitmoji shortcode, and the rest of it. */
package/dist/onboard.js CHANGED
@@ -3,10 +3,10 @@ import { API, BASE_ENV, SETTINGS_PATH, account, agentHere, agentIn, agentsSetUp,
3
3
  import { setUpBoard } from './board.js';
4
4
  import { typesDetail, typesLines, typesPlan } from './issue-types.js';
5
5
  import { asOwner, isOrganisation, ownerScopes, signInOnce } from './owner-login.js';
6
- import { appendToArray, replaceValues, setMember } from './jsonedit.js';
6
+ import { appendToArray, removeElements, replaceValues, setMember } from './jsonedit.js';
7
7
  import { HOURLY } from './asks.js';
8
8
  import { DEFAULT_SCHEDULE, FEATURES, FIGMA_FILE_KEY, NEEDS_ISSUE_TYPES, featuresIn, parseFeatures, renamedLines, scheduleIn } from './features.js';
9
- import { CLOUD_SETUP_PATH, HOOKS_PATH, LEFTOVER_CLOUD_SETUP_PATH, ONBOARD_BRANCH, WORKFLOW_PATH, autoMerge, mergeQueue, openPull, remoteFile, } from './onboard-pull.js';
9
+ import { CLOUD_SETUP_PATH, HOOKS_PATH, LEFTOVER_CLOUD_SETUP_PATH, ONBOARD_BRANCH, SARATHI_PATH, WORKFLOW_PATH, autoMerge, mergeQueue, openPull, remoteFile, } from './onboard-pull.js';
10
10
  import { cloudRepoScript, cloudScriptVersion, releaseSha256 } from './cloud.js';
11
11
  import { tagOnMain } from './release-tag.js';
12
12
  import { setSecret } from './secrets.js';
@@ -22,7 +22,7 @@ export const CLAUDE_CONNECTORS = 'https://claude.ai/customize/connectors';
22
22
  export const SETUP_FIRST = "If the repo has its own Setup script, put this first, then the repo's own: a repo's script may end with exit, and nothing after that runs.";
23
23
  /** This product's repository: clients call its shared workflow. */
24
24
  export { PRODUCT } from './names.js';
25
- export { HOOKS_PATH, WORKFLOW_PATH } from './onboard-pull.js';
25
+ export { HOOKS_PATH, SARATHI_PATH, WORKFLOW_PATH } from './onboard-pull.js';
26
26
  /** The launcher `machine` writes, as a hook's shell spells it. */
27
27
  const HOOK_LAUNCHER = `$HOME/${CONFIG_DIR}/bin/${CLI}`;
28
28
  /**
@@ -692,28 +692,177 @@ function hooksOf(settings, event) {
692
692
  return Array.isArray(hooks) ? hooks.filter((hook) => typeof hook === 'object' && hook !== null) : [];
693
693
  });
694
694
  }
695
+ /** How long sarathi gives a handler with no `timeout` of its own, in seconds. */
696
+ const SARATHI_DEFAULT_TIMEOUT = 60;
697
+ /**
698
+ * niyam's hooks as sarathi handlers (P-66). session-start's installs, the
699
+ * drift install and a cloud session's, need the 600 s Claude Code gives a
700
+ * hook in the settings, not sarathi's 60 s. The guard only reads local state,
701
+ * so sarathi's default does; it fails closed, as its own exits already do.
702
+ */
703
+ export const SARATHI_HANDLERS = {
704
+ SessionStart: { command: HOOK_COMMAND, timeout: 600 },
705
+ PreToolUse: { matcher: 'Bash', command: GUARD_COMMAND, failClosed: true },
706
+ };
707
+ /** A matcher's plain form, as Claude Code and sarathi read it: names, or `A|B`. Anything else is a regular expression. */
708
+ const PLAIN_MATCHER = /^[\w|-]+$/;
709
+ /** Whether a hook with `matcher` fires for `target`, by Claude Code's rules: absent, empty and `*` match all. */
710
+ function matcherTakes(matcher, target) {
711
+ if (matcher === undefined || matcher === '' || matcher === '*')
712
+ return true;
713
+ if (PLAIN_MATCHER.test(matcher))
714
+ return matcher.split('|').includes(target);
715
+ try {
716
+ return new RegExp(matcher).test(target);
717
+ }
718
+ catch {
719
+ return false;
720
+ }
721
+ }
722
+ /** Whether a settings entry with `runner`'s matcher lets a handler with `handler`'s fire whenever it would. */
723
+ function matcherCovers(runner, handler) {
724
+ if (runner === undefined || runner === '' || runner === '*')
725
+ return true;
726
+ if (handler === undefined || handler === '' || handler === '*' || !PLAIN_MATCHER.test(handler))
727
+ return false;
728
+ return handler.split('|').every((name) => matcherTakes(runner, name));
729
+ }
730
+ /**
731
+ * Whether a settings command runs sarathi for `event`, as `sarathi check`
732
+ * reads it: it names sarathi, the program or a launcher named after it,
733
+ * and passes the event as a word of its own (`sarathi hook PreToolUse`,
734
+ * `"$CLAUDE_PROJECT_DIR"/.claude/hooks/sarathi.sh PreToolUse`).
735
+ */
736
+ export function runsSarathiFor(command, event) {
737
+ return /\bsarathi\b/.test(command) && new RegExp(`(?:^|[\\s"'])${event}(?:$|[\\s"'])`).test(command);
738
+ }
739
+ /** The first settings entry that runs sarathi for `event`, or undefined. */
740
+ export function sarathiRunner(settings, event) {
741
+ const groups = settings?.hooks?.[event];
742
+ if (!Array.isArray(groups))
743
+ return undefined;
744
+ for (const [group, entry] of groups.entries()) {
745
+ const { matcher, hooks } = (entry ?? {});
746
+ for (const [hook, item] of (Array.isArray(hooks) ? hooks : []).entries()) {
747
+ const { command, timeout } = (item ?? {});
748
+ if (typeof command !== 'string' || !runsSarathiFor(command, event))
749
+ continue;
750
+ return { group, hook, ...(typeof matcher === 'string' ? { matcher } : {}), ...(typeof timeout === 'number' ? { timeout } : {}) };
751
+ }
752
+ }
753
+ return undefined;
754
+ }
755
+ /** The handlers `.claude/sarathi.json` lists under `event`. */
756
+ function handlersOf(sarathi, event) {
757
+ const list = sarathi.hooks?.[event];
758
+ return Array.isArray(list) ? list.filter((entry) => typeof entry === 'object' && entry !== null) : [];
759
+ }
695
760
  /**
696
761
  * The client's Claude Code settings with this release's hooks and lock: each
697
762
  * entry an older release wrote swapped where it stands, a missing one added,
698
763
  * the lock's variables set in `env`, and REVIEW_THREAD_RULE and AUTO_FIX_RULES allowed. Every edit is made in the text, so
699
764
  * the rest of the file keeps its layout. Says what changed, for the question.
765
+ *
766
+ * Where the project keeps `.claude/sarathi.json` (`sarathiBefore`) and the
767
+ * settings run sarathi for an event, with a matcher that lets niyam's hook
768
+ * fire, that hook goes into sarathi.json as a handler instead (P-66): an
769
+ * older one swapped in place, a missing one added, and niyam's hooks taken
770
+ * out of the settings, so sarathi's is the event's one entry there. sarathi's
771
+ * own entry gets at least the handler's timeout, as `sarathi check` asks.
772
+ * `sarathi` is said only when that file changes.
700
773
  */
701
- export function claudeSettings(before) {
774
+ export function claudeSettings(before, sarathiBefore) {
702
775
  let text = before ?? '{}\n';
703
776
  const changes = [];
704
777
  // The same, in a word or two each, for the plan.
705
778
  let hooksChanged;
779
+ let moved = false;
780
+ let timed = false;
706
781
  const labels = [];
707
782
  const parsed = () => JSON.parse(text);
708
783
  const first = parsed();
709
784
  if (typeof first !== 'object' || first === null || Array.isArray(first))
710
785
  throw new Error(`${HOOKS_PATH} is not a JSON object`);
786
+ let sarathi;
787
+ if (sarathiBefore !== undefined) {
788
+ let list;
789
+ try {
790
+ list = JSON.parse(sarathiBefore);
791
+ }
792
+ catch (error) {
793
+ throw new Error(`${SARATHI_PATH} is not JSON (${error.message})`);
794
+ }
795
+ if (typeof list !== 'object' || list === null || Array.isArray(list))
796
+ throw new Error(`${SARATHI_PATH} is not a JSON object`);
797
+ sarathi = { text: sarathiBefore, changes: [], labels: [] };
798
+ }
799
+ let handlersChanged;
800
+ let handlersTimed = false;
711
801
  const hooks = [
712
802
  ['SessionStart', HOOK_COMMAND, OLDER_HOOK_COMMANDS, 'the SessionStart hook that runs niyam session-start', {}],
713
803
  ['PreToolUse', GUARD_COMMAND, OLDER_GUARD_COMMANDS, "the PreToolUse hook that refuses gh and git's remote commands outside the agent identity", { matcher: 'Bash' }],
714
804
  ];
715
- try {
716
- for (const [event, command, older, name, extra] of hooks) {
805
+ for (const [event, command, older, name, extra] of hooks) {
806
+ const handler = SARATHI_HANDLERS[event];
807
+ const runner = sarathi === undefined ? undefined : sarathiRunner(first, event);
808
+ if (sarathi !== undefined && runner !== undefined && matcherCovers(runner.matcher, handler.matcher)) {
809
+ const edit = sarathi;
810
+ try {
811
+ const swapped = replaceValues(edit.text, ['hooks', event, '*', 'command'], (value) => (typeof value === 'string' && older.includes(value) ? command : undefined));
812
+ if (swapped.replaced > 0) {
813
+ edit.text = swapped.text;
814
+ edit.changes.push(`replace the older ${name.replace(/^the /, '')} with this release's`);
815
+ handlersChanged = 'updated';
816
+ }
817
+ else if (!handlersOf(JSON.parse(edit.text), event).some((entry) => entry.command === command)) {
818
+ edit.text = appendToArray(edit.text, ['hooks'], event, handler);
819
+ edit.changes.push(`add ${name}, as a handler sarathi runs`);
820
+ handlersChanged ??= 'added';
821
+ }
822
+ // A handler moved there by hand may have sarathi's 60 s, too short for session-start's installs.
823
+ const wanted = handler.timeout;
824
+ for (const [at, entry] of handlersOf(JSON.parse(edit.text), event).entries()) {
825
+ if (wanted === undefined || entry.command !== command || (typeof entry.timeout === 'number' && entry.timeout >= wanted))
826
+ continue;
827
+ edit.text = setMember(edit.text, ['hooks', event, String(at)], 'timeout', wanted);
828
+ edit.changes.push(`give ${name} ${wanted} s, as long as Claude Code gives it in the settings`);
829
+ handlersTimed = true;
830
+ }
831
+ }
832
+ catch (error) {
833
+ throw new Error(`${SARATHI_PATH}: ${error.message}`);
834
+ }
835
+ try {
836
+ const own = (value) => {
837
+ const found = value?.command;
838
+ return typeof found === 'string' && (found === command || older.includes(found));
839
+ };
840
+ // A group of niyam's hooks alone goes whole; niyam's hook in a group beside others goes alone.
841
+ const groups = removeElements(text, ['hooks', event], (group) => {
842
+ const inner = group?.hooks;
843
+ return Array.isArray(inner) && inner.length > 0 && inner.every(own);
844
+ });
845
+ const single = removeElements(groups.text, ['hooks', event, '*', 'hooks'], own);
846
+ if (groups.removed + single.removed > 0) {
847
+ text = single.text;
848
+ changes.push(`take out ${name}, which ${SARATHI_PATH} now runs under sarathi`);
849
+ moved = true;
850
+ }
851
+ // Found again: taking niyam's groups out moves sarathi's.
852
+ const now = sarathiRunner(parsed(), event);
853
+ const needed = handler.timeout ?? SARATHI_DEFAULT_TIMEOUT;
854
+ if (now.timeout === undefined || now.timeout < needed) {
855
+ text = setMember(text, ['hooks', event, String(now.group), 'hooks', String(now.hook)], 'timeout', needed);
856
+ changes.push(`give sarathi's ${event} hook ${needed} s, so niyam's handler under it has its time`);
857
+ timed = true;
858
+ }
859
+ }
860
+ catch (error) {
861
+ throw new Error(`${HOOKS_PATH}: ${error.message}`);
862
+ }
863
+ continue;
864
+ }
865
+ try {
717
866
  const swapped = replaceValues(text, ['hooks', event, '*', 'hooks', '*', 'command'], (value) => typeof value === 'string' && older.includes(value) ? command : undefined);
718
867
  if (swapped.replaced > 0) {
719
868
  text = swapped.text;
@@ -726,6 +875,11 @@ export function claudeSettings(before) {
726
875
  hooksChanged ??= 'added';
727
876
  }
728
877
  }
878
+ catch (error) {
879
+ throw new Error(`${HOOKS_PATH}: ${error.message}`);
880
+ }
881
+ }
882
+ try {
729
883
  const env = parsed().env;
730
884
  const current = typeof env === 'object' && env !== null ? env : {};
731
885
  const missing = Object.entries(BASE_ENV).filter(([name, value]) => current[name] !== value);
@@ -737,6 +891,10 @@ export function claudeSettings(before) {
737
891
  const named = (names) => (names.length <= 3 ? names.join(', ') : `${names.slice(0, 2).join(', ')} and ${names.length - 2} more`);
738
892
  if (hooksChanged)
739
893
  labels.push(`hooks ${hooksChanged}`);
894
+ if (moved)
895
+ labels.push('hooks moved to sarathi.json');
896
+ if (timed)
897
+ labels.push('sarathi timeout');
740
898
  if (added.length > 0)
741
899
  changes.push(`set ${named(added)} in env, so GitHub is locked out until session-start gives the agent identity`);
742
900
  if (updated.length > 0)
@@ -769,6 +927,13 @@ export function claudeSettings(before) {
769
927
  catch (error) {
770
928
  throw new Error(`${HOOKS_PATH}: ${error.message}`);
771
929
  }
930
+ if (sarathi !== undefined && sarathi.changes.length > 0) {
931
+ if (handlersChanged)
932
+ sarathi.labels.push(`hooks ${handlersChanged}`);
933
+ if (handlersTimed)
934
+ sarathi.labels.push('timeout');
935
+ return { text, changes, labels, sarathi };
936
+ }
772
937
  return { text, changes, labels };
773
938
  }
774
939
  /** Who the run's sign-in is, the owner's likely login; undefined when it failed. */
@@ -1120,11 +1285,15 @@ export async function onboard(sys, io, args = []) {
1120
1285
  const workflowNeeded = on('pr-identity') || on('board') || on('work-rules') || on('figma') || on('decisions') || on('review');
1121
1286
  const existing = fileAt(HOOKS_PATH);
1122
1287
  // Worked out before the plan, so a file onboard cannot edit is refused before any question.
1123
- const claude = claudeSettings(existing);
1288
+ const claude = claudeSettings(existing, fileAt(SARATHI_PATH));
1124
1289
  if (claude.changes.length > 0) {
1125
1290
  pull.push({ label: 'settings.json', detail: existing === undefined ? 'new' : claude.labels.join(', ') });
1126
1291
  change(HOOKS_PATH, claude.text, claude.changes.join('; '));
1127
1292
  }
1293
+ if (claude.sarathi) {
1294
+ pull.push({ label: 'sarathi.json', detail: claude.sarathi.labels.join(', ') });
1295
+ change(SARATHI_PATH, claude.sarathi.text, claude.sarathi.changes.join('; '));
1296
+ }
1128
1297
  const paths = pathsFor(sys.home, agent);
1129
1298
  const token = readToken(sys, agent);
1130
1299
  const ready = token && checkToken(token, await tokenInfo(sys, token), agent, sys.now());
@@ -128,6 +128,7 @@ function loadState(sys, root, branch) {
128
128
  }
129
129
  }
130
130
  function saveState(sys, root, state) {
131
+ sys.confine(root, statePath(root, state.branch));
131
132
  sys.mkdir(stateDir(root));
132
133
  sys.write(statePath(root, state.branch), JSON.stringify(state));
133
134
  }
@@ -187,8 +188,11 @@ function recheckSeconds(sys) {
187
188
  * hook can reach the same push. A lock older than three minutes is abandoned.
188
189
  */
189
190
  export async function withLock(sys, root, branch, body) {
190
- sys.mkdir(stateDir(root));
191
191
  const path = `${statePath(root, branch)}.lock`;
192
+ // Every record the body may touch, checked before any is: a link out of the toplevel stops it before GitHub is asked.
193
+ for (const each of [path, statePath(root, branch), optoutPath(root, branch)])
194
+ sys.confine(root, each);
195
+ sys.mkdir(stateDir(root));
192
196
  const deadline = sys.now().getTime() + LOCK_WAIT_MS;
193
197
  while (!sys.claim(path)) {
194
198
  const changed = sys.modified(path);
@@ -526,6 +530,7 @@ async function autofixMessage(sys, root, settings, state, session, pulls) {
526
530
  if (sys.exists(ack))
527
531
  return '';
528
532
  try {
533
+ sys.confine(root, ack);
529
534
  sys.mkdir(dirname(ack));
530
535
  sys.write(ack, '');
531
536
  }
@@ -855,6 +860,7 @@ export async function spawnWatchers(sys, io, args, stdin) {
855
860
  if (opted)
856
861
  continue;
857
862
  try {
863
+ sys.confine(root, `${stateDir(root)}/watch.log`);
858
864
  sys.mkdir(stateDir(root));
859
865
  // Its own session and no inherited descriptors: git, the hook's
860
866
  // supervisor and a closing terminal neither wait on it nor end it.
package/dist/run.js CHANGED
@@ -1,9 +1,11 @@
1
+ import { homedir } from 'node:os';
1
2
  import { LOCKED, asAgent, asAgentArgs } from './as-agent.js';
2
3
  import { cloudSetup } from './cloud.js';
3
4
  import { needsOwner } from './asks.js';
4
5
  import { decisionsWeekly } from './decisions.js';
5
6
  import { prDesign } from './design.js';
6
7
  import { doctor } from './doctor.js';
8
+ import { env, envArgs, envFailed } from './env.js';
7
9
  import { guard } from './guard.js';
8
10
  import { issueType } from './issue-types.js';
9
11
  import { prIdentity } from './identity.js';
@@ -38,6 +40,9 @@ Commands:
38
40
  label <owner/repo> <number> <add|remove> <approved|do-not-merge>;
39
41
  required-checks <owner/repo> <ruleset id or name> [--check <name>]…
40
42
  cloud-setup Print an optional Setup snippet that makes Claude cloud sessions start faster
43
+ env [-- <command> [args...]]
44
+ For agents run from any tool: the GitHub lock, then the agent identity where this Mac
45
+ has it, as shell lines for eval "$(niyam env)", or with -- the command run under them
41
46
  session-start Run by a client's SessionStart hook: the agent identity, or GitHub locked out
42
47
  guard Run by a client's PreToolUse hook: gh and git's remote commands only as the agent
43
48
  as-agent --session <session_id> -- <command> [args...]
@@ -123,17 +128,17 @@ export function proposeArgs(args) {
123
128
  /** Runs one command and returns its exit code: 0 done, 1 failed, 2 bad usage. */
124
129
  export async function run(args, io, sys) {
125
130
  const [command, ...rest] = args;
126
- const allowed = command === 'onboard' || command === 'machine' || command === 'review-thread' || command === 'as-agent' || command === 'propose' || command === 'owner-step' || command === 'handoff' || command === 'brief' || command === 'cubic-dismiss' || command === 'pr-autocreate' || command === 'keep-going' ? Infinity : command === 'pre-push' || command === 'pr-signals' ? 2 : command === 'doctor' ? 1 : 0;
131
+ const allowed = command === 'onboard' || command === 'machine' || command === 'review-thread' || command === 'as-agent' || command === 'env' || command === 'propose' || command === 'owner-step' || command === 'handoff' || command === 'brief' || command === 'cubic-dismiss' || command === 'pr-autocreate' || command === 'keep-going' ? Infinity : command === 'pre-push' || command === 'pr-signals' ? 2 : command === 'doctor' ? 1 : 0;
127
132
  const extra = rest[allowed];
128
133
  if (extra !== undefined) {
129
134
  io.err(`niyam: unexpected argument "${extra}"`);
130
135
  io.err(USAGE);
131
136
  return 2;
132
137
  }
133
- if (command === 'onboard' || command === 'machine' || command === 'review-thread' || command === 'as-agent' || command === 'propose' || command === 'owner-step' || command === 'pr-signals' || command === 'handoff' || command === 'brief' || command === 'cubic-dismiss') {
138
+ if (command === 'onboard' || command === 'machine' || command === 'review-thread' || command === 'as-agent' || command === 'env' || command === 'propose' || command === 'owner-step' || command === 'pr-signals' || command === 'handoff' || command === 'brief' || command === 'cubic-dismiss') {
134
139
  // Their options are checked here, so a bad one is bad usage (exit 2).
135
140
  try {
136
- (command === 'onboard' ? onboardArgs : command === 'machine' ? machineArgs : command === 'as-agent' ? asAgentArgs : command === 'propose' ? proposeArgs : command === 'owner-step' ? ownerStepArgs : command === 'pr-signals' ? signalArgs : command === 'handoff' ? handoffArgs : command === 'brief' ? briefArgs : command === 'cubic-dismiss' ? dismissArgs : threadArgs)(rest);
141
+ (command === 'onboard' ? onboardArgs : command === 'machine' ? machineArgs : command === 'as-agent' ? asAgentArgs : command === 'env' ? envArgs : command === 'propose' ? proposeArgs : command === 'owner-step' ? ownerStepArgs : command === 'pr-signals' ? signalArgs : command === 'handoff' ? handoffArgs : command === 'brief' ? briefArgs : command === 'cubic-dismiss' ? dismissArgs : threadArgs)(rest);
137
142
  }
138
143
  catch (error) {
139
144
  io.err(`niyam: ${error instanceof Error ? error.message : String(error)}`);
@@ -194,6 +199,20 @@ export async function run(args, io, sys) {
194
199
  io.err(`niyam as-agent: ran nothing, because the check failed: ${error instanceof Error ? error.message : String(error)}`);
195
200
  return LOCKED;
196
201
  }
202
+ case 'env': {
203
+ // Any failure of its own check still locks: it prints the lock alone, or runs nothing.
204
+ const parsed = envArgs(rest);
205
+ let home = homedir();
206
+ try {
207
+ const real = await sys();
208
+ home = real.home;
209
+ return env(real, io, parsed);
210
+ }
211
+ catch (error) {
212
+ // fail-open: only in that env carries on, printing the lock alone or running nothing, so the shell stays locked.
213
+ return envFailed(home, io, parsed, error);
214
+ }
215
+ }
197
216
  case 'machine':
198
217
  case 'doctor':
199
218
  case 'onboard':
@@ -1,4 +1,4 @@
1
- import { BASE_ENV, SETTINGS_PATH, agentHere, anyLogin, either, loadSettings, lockScript, sameLogin, pathsFor, sessionNames, sessionRecord, sessionFileIs, } from './agent.js';
1
+ import { BASE_ENV, agentHere, anyLogin, either, loadSettings, lockScript, sameLogin, pathsFor, sessionNames, sessionRecord, sessionFileIs, } from './agent.js';
2
2
  import { AGENT_VAR } from './names.js';
3
3
  import { cloudLogin, cloudToken, ranFromSetup, repoReleases } from './cloud.js';
4
4
  import { CLOUD_SETUP_PATH } from './onboard-pull.js';
@@ -174,20 +174,15 @@ async function cloudStart(sys) {
174
174
  return { line: `niyam: this cloud session works as ${asked.login} on GitHub.${unchecked}`, agent: asked.login };
175
175
  }
176
176
  function start(sys) {
177
- let settings;
178
- let settingsProblem = '';
179
- let file;
177
+ let local;
180
178
  try {
181
- const root = repoRoot(sys);
182
- file = SETTINGS_PATH;
183
- settings = loadSettings(sys, root);
179
+ local = localIdentity(sys);
184
180
  }
185
181
  catch (error) {
186
- settingsProblem = message(error);
182
+ // fail-open: only in that session-start carries on to write the lock, and a check that failed gives no identity.
183
+ local = { owner: 'the owner', fix: 'tell the owner', reason: `the check failed (${message(error)})` };
187
184
  }
188
- // Any owner can run machine here: the first is the one to tell.
189
- const owner = settings?.owners[0] ?? 'the owner';
190
- const stop = `Do not push, fetch, or run gh in this session; tell ${owner}.`;
185
+ const stop = `Do not push, fetch, or run gh in this session; tell ${local.owner}.`;
191
186
  const envFile = sys.env.CLAUDE_ENV_FILE;
192
187
  if (!envFile) {
193
188
  return { line: `niyam: STOP. CLAUDE_ENV_FILE is unset, so this session cannot be given the agent identity and gh and git would act as the owner. ${stop} ${HOOK_ONLY}` };
@@ -201,40 +196,59 @@ function start(sys) {
201
196
  const locked = (reason, fix) => ({
202
197
  line: `niyam: GitHub is locked out of this session: ${reason}. Do not work around the lock; ${fix}.`,
203
198
  });
199
+ if (local.script !== undefined) {
200
+ try {
201
+ sys.append(envFile, `\n${local.script}`);
202
+ }
203
+ catch (error) {
204
+ return locked(`appending ${local.session} to CLAUDE_ENV_FILE failed (${message(error)})`, local.fix);
205
+ }
206
+ }
207
+ if ('reason' in local)
208
+ return locked(local.reason, local.fix);
209
+ return { line: `niyam: this session works as ${local.agent} on GitHub. ${AUTO_FIX}`, agent: local.agent };
210
+ }
211
+ export function localIdentity(sys) {
212
+ let settings;
213
+ let settingsProblem = '';
214
+ try {
215
+ settings = loadSettings(sys, repoRoot(sys));
216
+ }
217
+ catch (error) {
218
+ settingsProblem = message(error);
219
+ }
220
+ // Any owner can run machine here: the first is the one to tell.
221
+ const owner = settings?.owners[0] ?? 'the owner';
222
+ const tell = `tell ${owner}`;
204
223
  if (!settings)
205
- return locked(settingsProblem, `tell ${owner}`);
224
+ return { owner, fix: tell, reason: settingsProblem };
206
225
  const here = agentHere(sys, settings.agents);
207
226
  if ('problem' in here)
208
- return locked(here.problem, `ask ${owner} to run niyam machine <agent> for one of them`);
227
+ return { owner, fix: `ask ${owner} to run niyam machine <agent> for one of them`, reason: here.problem };
209
228
  const { agent } = here;
210
229
  const paths = pathsFor(sys.home, agent);
211
230
  const fix = `ask ${owner} to run niyam machine ${agent} (niyam doctor ${agent} names what is missing)`;
212
231
  const store = tokenStore(sys);
213
232
  if (!store)
214
- return locked(unsupported(sys), `tell ${owner}`);
215
- if (!sys.exists(paths.session))
216
- return locked(`${paths.session} is missing`, fix);
233
+ return { owner, fix: tell, reason: unsupported(sys) };
234
+ const session = paths.session;
235
+ if (!sys.exists(session))
236
+ return { owner, fix, reason: `${session} is missing` };
217
237
  let script;
218
238
  try {
219
- script = sys.read(paths.session);
239
+ script = sys.read(session);
220
240
  }
221
241
  catch (error) {
222
- return locked(`${paths.session} cannot be read (${message(error)})`, fix);
242
+ return { owner, fix, reason: `${session} cannot be read (${message(error)})` };
223
243
  }
224
244
  const names = sessionNames(script);
225
245
  if (!names || !sameLogin(names.agent, agent) || !sessionFileIs(script, names.agent, names.id, paths, store)) {
226
- return locked(`${paths.session} is out of date, or not the file niyam machine writes, for ${agent}`, fix);
227
- }
228
- try {
229
- sys.append(envFile, `\n${script}`);
230
- }
231
- catch (error) {
232
- return locked(`appending ${paths.session} to CLAUDE_ENV_FILE failed (${message(error)})`, fix);
246
+ return { owner, fix, reason: `${session} is out of date, or not the file niyam machine writes, for ${agent}` };
233
247
  }
234
248
  if (!store.read(sys, names.agent)) {
235
- return locked(`${store.where} has no ${names.agent} token, so GitHub refuses gh and git`, fix);
249
+ return { owner, fix, session, script, reason: `${store.where} has no ${names.agent} token, so GitHub refuses gh and git` };
236
250
  }
237
- return { line: `niyam: this session works as ${names.agent} on GitHub. ${AUTO_FIX}`, agent: names.agent };
251
+ return { owner, fix, session, script, agent: names.agent };
238
252
  }
239
253
  /**
240
254
  * The Claude desktop app turns Auto-fix on for a pull request a session opens
package/dist/sys.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { spawn, spawnSync } from 'node:child_process';
2
- import { appendFileSync, chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync, } from 'node:fs';
2
+ import { appendFileSync, chmodSync, closeSync, existsSync, lstatSync, fsyncSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync, } from 'node:fs';
3
3
  import * as http from 'node:http';
4
4
  import { constants, homedir, tmpdir } from 'node:os';
5
- import { join } from 'node:path';
5
+ import { dirname, join, resolve, sep } from 'node:path';
6
6
  import { createInterface as askFrom } from 'node:readline/promises';
7
7
  import { createInterface } from 'node:readline';
8
8
  import { isatty } from 'node:tty';
@@ -43,6 +43,7 @@ export function realSys() {
43
43
  },
44
44
  append: (path, data) => appendFileSync(path, data),
45
45
  mkdir: (path) => mkdirSync(path, { recursive: true, mode: 0o700 }),
46
+ confine: (root, path) => confine(root, path),
46
47
  list: (path) => (existsSync(path) ? readdirSync(path) : []),
47
48
  tempDir: (prefix) => mkdtempSync(prefix ?? join(tmpdir(), `${CLI}-`)),
48
49
  remove: (path) => rmSync(path, { recursive: true, force: true }),
@@ -232,6 +233,33 @@ function reason(error) {
232
233
  return `${code} (${message})`;
233
234
  return message || code || String(error);
234
235
  }
236
+ /** Sys.confine on the real machine. */
237
+ export function confine(root, path) {
238
+ const top = realpathSync(root);
239
+ // The nearest part that is there, by lstat: existsSync follows a link, so one that leads nowhere would read as absent.
240
+ let at = resolve(path);
241
+ while (!present(at) && dirname(at) !== at)
242
+ at = dirname(at);
243
+ let real;
244
+ try {
245
+ real = realpathSync(at);
246
+ }
247
+ catch (error) {
248
+ throw new Error(`refused to write ${path}: ${at} is a link that cannot be followed (${error.code ?? String(error)}), so it may lead outside ${top}`);
249
+ }
250
+ if (real !== top && !real.startsWith(top.endsWith(sep) ? top : `${top}${sep}`)) {
251
+ throw new Error(`refused to write ${path}: it leads to ${real}, outside the git toplevel ${top}`);
252
+ }
253
+ }
254
+ function present(path) {
255
+ try {
256
+ lstatSync(path);
257
+ return true;
258
+ }
259
+ catch {
260
+ return false;
261
+ }
262
+ }
235
263
  /** A path with its links resolved, or as given when it cannot be. */
236
264
  function realPath(path) {
237
265
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veda-hq/niyam",
3
- "version": "0.6.19",
3
+ "version": "0.6.21",
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": {
@@ -28,6 +28,7 @@
28
28
  "@types/node": "24.19.2",
29
29
  "@veda-hq/dvara": "0.5.16",
30
30
  "@veda-hq/pariksha": "0.5.20",
31
+ "@veda-hq/sarathi": "0.6.10",
31
32
  "typescript": "7.0.2"
32
33
  },
33
34
  "dependencies": {
@@ -38,13 +39,15 @@
38
39
  "scripts": {
39
40
  "build": "tsc -p tsconfig.build.json",
40
41
  "typecheck": "tsc -p tsconfig.json",
42
+ "lint": "lint/node_modules/.bin/eslint --config lint/eslint.config.js --suppressions-location lint/eslint-suppressions.json --max-warnings 0 src",
41
43
  "test": "node --test --experimental-test-coverage --test-coverage-lines=95 --test-coverage-functions=95 --test-coverage-branches=90 --test-coverage-exclude=src/**/*.test.ts src/**/*.test.ts",
42
44
  "test:scripts": "node --test --experimental-test-coverage --test-coverage-lines=95 --test-coverage-functions=95 --test-coverage-branches=90 '--test-coverage-include=scripts/*.mjs' '--test-coverage-exclude=scripts/*.test.mjs' scripts/*.test.mjs",
43
45
  "provenance": "node scripts/own-provenance.mjs",
44
46
  "smoke": "node dist/cli.js --version",
45
47
  "scan:secrets": "gitleaks dir --no-banner --redact --config=.gitleaks.toml . && trufflehog filesystem . --no-update --fail --results=verified,unknown --exclude-paths=.trufflehog-exclude",
46
- "check": "pnpm provenance && pnpm typecheck && pnpm test && pnpm test:scripts && pnpm pins && pnpm pariksha && pnpm build && pnpm smoke",
48
+ "check": "pnpm provenance && pnpm typecheck && pnpm lint && pnpm test && pnpm test:scripts && pnpm pins && pnpm pariksha && pnpm hooks:check && pnpm build && pnpm smoke",
47
49
  "pins": "node scripts/released-pins.mjs",
48
- "pariksha": "node_modules/.bin/pariksha absolute-paths && node_modules/.bin/pariksha aggregate-gate-needs && node_modules/.bin/pariksha masked-exit-codes && node_modules/.bin/pariksha pnpm-settings --config pariksha-pnpm-settings.json && node_modules/.bin/pariksha shell-gates --all"
50
+ "pariksha": "node_modules/.bin/pariksha absolute-paths && node_modules/.bin/pariksha aggregate-gate-needs && node_modules/.bin/pariksha masked-exit-codes && node_modules/.bin/pariksha pnpm-settings --config pariksha-pnpm-settings.json && node_modules/.bin/pariksha shell-gates --all",
51
+ "hooks:check": "node_modules/.bin/sarathi check --settings .claude/settings.json"
49
52
  }
50
53
  }