@veda-hq/niyam 0.6.16 → 0.6.17

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.
@@ -0,0 +1,384 @@
1
+ import { basename, dirname } from 'node:path';
2
+ import { githubSlug, isNoToken, SETTINGS_PATH } from './agent.js';
3
+ import { agentEnv } from './as-agent.js';
4
+ import { GITHUB_API } from './host.js';
5
+ import { sessionToken } from './work.js';
6
+ /**
7
+ * Claude Code's Stop hook: a session whose branch has commits the default
8
+ * branch lacks keeps going until its pull request merges (docs/decisions.md,
9
+ * W-56.5). Started work stops only when merged, stuck on the owner, or proven
10
+ * unneeded; a session that ends a turn waiting on something that cannot wake
11
+ * it stalls for hours, so this sends it back with what is left.
12
+ *
13
+ * The session may stop when any of these holds:
14
+ * - it is a subagent;
15
+ * - its branch is the base or another trunk, detached, has no commit the
16
+ * base lacks (or git cannot say), or has its commits inside another remote
17
+ * branch while its own is not pushed (that branch carries them);
18
+ * - it wrote a stop note at this commit (`niyam keep-going --stop <why>`);
19
+ * the hook shows the owner the reason once;
20
+ * - its pull request merged at this commit, or GitHub cannot say (fail open);
21
+ * - a background task, or a `git commit` or `git push` in its worktree,
22
+ * still runs (its exit wakes the session), unless it runs in print mode,
23
+ * where the task dies with the turn;
24
+ * - it is a desktop session, clean, with every commit on a ready pull
25
+ * request: the app's Autofix wakes it;
26
+ * - it was sent back five times at one commit: the hook writes the stop note
27
+ * itself and sends it back once more to say so.
28
+ *
29
+ * Otherwise it is sent back with what is left and the count ("1 of 5"). A
30
+ * new commit resets the count and voids a stop note. A cloud session is held
31
+ * the same way, since nothing there wakes a stopped one; pull requests are
32
+ * read over REST, which its proxy allows.
33
+ */
34
+ export const CAP = 5;
35
+ /** How many pages of pull requests a branch name is read to: a reused name has a few. */
36
+ const PAGES = 10;
37
+ export const STORE = '.tmp/keep-going';
38
+ export const PRINT_MODE_VAR = 'NIYAM_PRINT_MODE';
39
+ export const STOP_COMMAND = 'niyam keep-going --stop "<why, in plain English>"';
40
+ const DEFAULTS = { base: '', trunks: [], printMode: [], owner: 'the owner', tag: 'niyam keep-going' };
41
+ const where = `${SETTINGS_PATH} "keepGoing"`;
42
+ const BRANCH = /^(?!\/)(?!.*\/\/)(?!.*\.\.)[\w.\/+-]+$/;
43
+ function oneLine(value, name) {
44
+ if (typeof value !== 'string' || !value.trim() || /[\r\n]/.test(value))
45
+ throw new Error(`${where}.${name} must be one line`);
46
+ return value;
47
+ }
48
+ /** The settings, from the parsed settings file; throws naming the first bad key. */
49
+ export function keepGoingSettings(raw) {
50
+ const value = typeof raw === 'object' && raw !== null ? raw.keepGoing : undefined;
51
+ if (value === undefined)
52
+ return { ...DEFAULTS };
53
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
54
+ throw new Error(`${where} must be an object`);
55
+ const { base = DEFAULTS.base, trunks = DEFAULTS.trunks, printMode = DEFAULTS.printMode, owner = DEFAULTS.owner, tag = DEFAULTS.tag, ...rest } = value;
56
+ const extra = Object.keys(rest)[0];
57
+ if (extra !== undefined)
58
+ throw new Error(`${where} has an unknown key "${extra}"; it takes "base", "trunks", "printMode", "owner" and "tag"`);
59
+ if (typeof base !== 'string' || (base !== '' && !BRANCH.test(base)))
60
+ throw new Error(`${where}.base must be a branch name`);
61
+ if (!Array.isArray(trunks) || !trunks.every((item) => typeof item === 'string' && BRANCH.test(item)))
62
+ throw new Error(`${where}.trunks must be a list of branch names`);
63
+ if (!Array.isArray(printMode) || !printMode.every((item) => typeof item === 'string' && /^[A-Z_][A-Z0-9_]*$/.test(item)))
64
+ throw new Error(`${where}.printMode must be a list of variable names`);
65
+ return { base, trunks: trunks, printMode: printMode, owner: oneLine(owner, 'owner'), tag: oneLine(tag, 'tag') };
66
+ }
67
+ /** The settings in the repository at `root`, the base resolved: origin's default branch when none is set, else main. */
68
+ export function settingsAt(sys, root) {
69
+ const path = `${root}/${SETTINGS_PATH}`;
70
+ const settings = sys.exists(path) ? keepGoingSettings(JSON.parse(sys.read(path))) : { ...DEFAULTS };
71
+ if (settings.base)
72
+ return settings;
73
+ const head = out(sys, root, 'git', ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD']);
74
+ return { ...settings, base: head?.startsWith('origin/') ? head.slice('origin/'.length) : 'main' };
75
+ }
76
+ const noteHolds = (facts) => facts.note !== null && facts.note.branch === facts.branch && facts.note.head === facts.head;
77
+ /** Work the rule does not hold: nothing to merge, or not the session's. */
78
+ function notStarted(facts, settings) {
79
+ return !(facts.ahead !== null && facts.ahead > 0) || facts.branch === '' || facts.branch === settings.base || settings.trunks.includes(facts.branch) || facts.carried;
80
+ }
81
+ export function decide(facts, previous, settings) {
82
+ const counter = previous?.head === facts.head ? previous : { head: facts.head, count: 0 };
83
+ const { pr } = facts;
84
+ if (facts.subagent || notStarted(facts, settings))
85
+ return { stop: true, counter };
86
+ if (noteHolds(facts))
87
+ return facts.note.shown ? { stop: true, counter } : { stop: true, counter, say: facts.note.reason };
88
+ if ((facts.pushing && !facts.print) || pr === 'unknown')
89
+ return { stop: true, counter };
90
+ // A merge releases the session only if it merged this commit: a reused
91
+ // branch name can still show an older merged pull request, and work left
92
+ // uncommitted on top is not merged either.
93
+ if (pr?.state === 'MERGED' && pr.headRefOid === facts.head && !facts.dirty)
94
+ return { stop: true, counter };
95
+ const pushed = facts.remote === facts.head;
96
+ // A draft still needs the session; only a ready pull request waits on
97
+ // events Autofix reports, and only once nothing is left uncommitted.
98
+ if (facts.desktop && pr?.state === 'OPEN' && !pr.isDraft && pushed && !facts.dirty)
99
+ return { stop: true, counter };
100
+ const count = counter.count + 1;
101
+ const next = { head: facts.head, count };
102
+ if (count > CAP) {
103
+ return {
104
+ stop: true,
105
+ counter: next,
106
+ record: `stop hook: the session tried to stop ${CAP + 1} times at ${facts.head.slice(0, 9)} with no new commit and gave no reason; cause unknown, ${settings.owner} to look (${settings.tag} cap)`,
107
+ };
108
+ }
109
+ const release = `If only ${settings.owner} can unblock it, or it is proven unneeded, run \`${STOP_COMMAND}\` and say so to ${settings.owner}; then you may stop. After ${CAP}, the hook writes that note itself.`;
110
+ // A running task in print mode (only then does one get here): gather read
111
+ // nothing past it, since the task may still be changing the branch.
112
+ const left = facts.pushing ? ['a commit, push or background task is running, and in print mode it dies with this turn: wait for it in the foreground'] : stillToDo(facts, pr, pushed);
113
+ const what = `Branch ${facts.branch} has ${facts.ahead} commit(s) origin/${settings.base} lacks, and started work runs to merge`;
114
+ return {
115
+ stop: false,
116
+ counter: next,
117
+ reason: `${what}. ${left.join('; ')}. Do not end a turn waiting on something that cannot wake you. ${release} (${settings.tag}, ${count} of ${CAP}.)`,
118
+ };
119
+ }
120
+ /** What is left before the merge. */
121
+ function stillToDo(facts, pr, pushed) {
122
+ const left = [];
123
+ if (!pushed) {
124
+ left.push(facts.remote === null ? 'the branch is not on the remote: push it' : 'local commits are not on the remote: push them');
125
+ left.push(facts.print ? 'in print mode nothing wakes you: run the push in the foreground with the longest Bash timeout' : 'run the push as a background task so you are told when it exits');
126
+ }
127
+ if (pr === null)
128
+ left.push('no pull request yet: open it');
129
+ else if (pr.state === 'MERGED')
130
+ left.push(`PR ${pr.number} merged an older commit; the work since is not merged: commit it and open a new PR`);
131
+ else if (pr.state !== 'OPEN')
132
+ left.push(`PR ${pr.number} was closed without merging: reopen it, or record why the work stops`);
133
+ else if (pushed && pr.isDraft)
134
+ left.push(`PR ${pr.number} is a draft: finish the work, push, mark it ready`);
135
+ else if (pushed)
136
+ left.push(`PR ${pr.number} is open: carry it to merge, polling checks and review threads with foreground waits`);
137
+ return left;
138
+ }
139
+ function out(sys, root, command, args) {
140
+ const result = sys.exec(command, args, { cwd: root, timeoutMs: 20_000 });
141
+ return result.code === 0 ? result.stdout.trim() : null;
142
+ }
143
+ /**
144
+ * Is this command line `git [global options] commit|push …`? Only global
145
+ * options may precede git's command, so `git log --grep push` is not one.
146
+ */
147
+ export function gitVerb(words) {
148
+ const start = words.findIndex((word) => basename(word) === 'git');
149
+ if (start < 0)
150
+ return false;
151
+ for (let at = start + 1; at < words.length; at++) {
152
+ const word = words[at];
153
+ if (word === '-C' || word === '-c')
154
+ at++;
155
+ else if (!word.startsWith('-'))
156
+ return word === 'push' || word === 'commit';
157
+ }
158
+ return false;
159
+ }
160
+ /** Is a `git commit` or `git push` running with its working directory in this worktree? */
161
+ export function pushInFlight(sys, root) {
162
+ const table = out(sys, root, 'ps', ['-Ao', 'pid=,command=']);
163
+ if (table === null)
164
+ return false;
165
+ return table
166
+ .split('\n')
167
+ .flatMap((line) => {
168
+ const [pid = '', ...words] = line.trim().split(/\s+/);
169
+ return /^\d+$/.test(pid) && gitVerb(words) ? [pid] : [];
170
+ })
171
+ .some((pid) => {
172
+ const path = out(sys, root, 'lsof', ['-a', '-p', pid, '-d', 'cwd', '-Fn'])
173
+ ?.split('\n')
174
+ .find((line) => line.startsWith('n'))
175
+ ?.slice(1);
176
+ return path !== undefined && (path === root || path.startsWith(`${root}/`));
177
+ });
178
+ }
179
+ /**
180
+ * Does the Claude process `claudePid` still run a background task? Its Bash
181
+ * tasks are direct children running a shell that sources a snapshot from
182
+ * `shell-snapshots/`; at Stop every foreground one has ended.
183
+ */
184
+ export function backgroundTask(sys, claudePid, root) {
185
+ if (!claudePid)
186
+ return false;
187
+ const table = out(sys, root, 'ps', ['-Ao', 'pid=,ppid=,command=']);
188
+ if (table === null)
189
+ return false;
190
+ return table.split('\n').some((line) => {
191
+ const match = /^\s*\d+\s+(\d+)\s+(.*)$/.exec(line);
192
+ return match !== null && match[1] === claudePid && /\/shell-snapshots\/snapshot-/.test(match[2]);
193
+ });
194
+ }
195
+ /** Does a remote branch other than this one and the base hold HEAD? Git silent reads as "carried" (fail open). */
196
+ export function carriedElsewhere(sys, root, branch, base) {
197
+ const refs = out(sys, root, 'git', ['for-each-ref', '--contains', 'HEAD', '--format=%(refname:short)', 'refs/remotes/origin']);
198
+ if (refs === null)
199
+ return true;
200
+ const own = new Set([`origin/${branch}`, `origin/${base}`, 'origin/HEAD', 'origin']);
201
+ return refs.split('\n').some((ref) => ref !== '' && !own.has(ref));
202
+ }
203
+ const notePath = (root) => `${root}/${STORE}/stop-note.json`;
204
+ /** The worktree's stop note, or null. A torn note throws: the hook fails open. */
205
+ export function readStopNote(sys, root) {
206
+ const path = notePath(root);
207
+ return sys.exists(path) ? JSON.parse(sys.read(path)) : null;
208
+ }
209
+ export function writeStopNote(sys, root, note) {
210
+ sys.mkdir(dirname(notePath(root)));
211
+ sys.write(notePath(root), `${JSON.stringify(note)}\n`);
212
+ }
213
+ /** The token to read the pull request with: the session's agent, or the shell's own outside a session; undefined when there is none. */
214
+ function tokenFor(sys, root, session, err) {
215
+ if (session === undefined)
216
+ return sessionToken(sys);
217
+ const env = agentEnv(sys, session, root);
218
+ if ('problem' in env) {
219
+ err?.(`niyam could not act as the agent (${env.problem}); run \`niyam doctor\``);
220
+ return undefined;
221
+ }
222
+ const token = env.env.GH_TOKEN;
223
+ return token && !isNoToken(token) ? token : undefined;
224
+ }
225
+ /**
226
+ * This branch's pull request, from REST: the one from this repository
227
+ * carrying this commit, else the newest from it; null with none; 'unknown'
228
+ * when origin is not on GitHub, there is no token, or GitHub cannot say.
229
+ */
230
+ export async function readPr(sys, root, branch, head, session, err) {
231
+ const slug = githubSlug(out(sys, root, 'git', ['config', '--get', 'remote.origin.url']) ?? '');
232
+ if (!slug)
233
+ return 'unknown';
234
+ const token = tokenFor(sys, root, session, err);
235
+ if (!token)
236
+ return 'unknown';
237
+ const pulls = [];
238
+ const route = `${GITHUB_API}/repos/${slug}/pulls?head=${encodeURIComponent(`${slug.split('/')[0]}:${branch}`)}&state=all&per_page=100`;
239
+ // Each page bounded, and the pages too, under the hook's own timeout.
240
+ for (let page = 1;; page++) {
241
+ if (page > PAGES)
242
+ return 'unknown';
243
+ let got;
244
+ try {
245
+ got = await sys.http(`${route}&page=${page}`, { token, timeoutMs: 15_000 });
246
+ }
247
+ catch {
248
+ return 'unknown';
249
+ }
250
+ if (got.status !== 200 || !Array.isArray(got.json))
251
+ return 'unknown';
252
+ pulls.push(...got.json);
253
+ if (got.json.length < 100)
254
+ break;
255
+ }
256
+ const own = [];
257
+ for (const item of pulls) {
258
+ const pull = item;
259
+ if (!Number.isInteger(pull.number) || typeof pull.state !== 'string' || typeof pull.draft !== 'boolean' || typeof pull.head?.sha !== 'string')
260
+ return 'unknown';
261
+ // A fork's branch can share the name.
262
+ const from = pull.head.repo?.full_name;
263
+ if (typeof from !== 'string' || from.toLowerCase() !== slug.toLowerCase())
264
+ continue;
265
+ own.push({ number: pull.number, state: pull.merged_at ? 'MERGED' : pull.state === 'open' ? 'OPEN' : 'CLOSED', isDraft: pull.draft, headRefOid: pull.head.sha });
266
+ }
267
+ // A reused branch name lists several: the one carrying this commit is the branch's, else the newest.
268
+ return own.find((pr) => pr.headRefOid === head) ?? own[0] ?? null;
269
+ }
270
+ export async function gather(sys, root, settings, subagent, session, err) {
271
+ const head = out(sys, root, 'git', ['rev-parse', 'HEAD']) ?? '';
272
+ const branch = out(sys, root, 'git', ['symbolic-ref', '--quiet', '--short', 'HEAD']) ?? '';
273
+ const facts = {
274
+ desktop: sys.env.CLAUDE_CODE_ENTRYPOINT === 'claude-desktop',
275
+ print: [PRINT_MODE_VAR, ...settings.printMode].some((name) => sys.env[name] === '1'),
276
+ subagent,
277
+ branch,
278
+ head,
279
+ ahead: null,
280
+ carried: false,
281
+ note: null,
282
+ remote: out(sys, root, 'git', ['rev-parse', '--verify', '--quiet', '@{u}']),
283
+ pr: null,
284
+ pushing: false,
285
+ dirty: false,
286
+ };
287
+ if (subagent)
288
+ return facts;
289
+ const ahead = Number(out(sys, root, 'git', ['rev-list', '--count', `origin/${settings.base}..HEAD`]) ?? NaN);
290
+ facts.ahead = Number.isInteger(ahead) ? ahead : null;
291
+ if (notStarted(facts, settings))
292
+ return facts;
293
+ facts.carried = facts.remote !== head && carriedElsewhere(sys, root, branch, settings.base);
294
+ facts.note = readStopNote(sys, root);
295
+ if (notStarted(facts, settings) || noteHolds(facts))
296
+ return facts;
297
+ facts.pushing = backgroundTask(sys, sys.env.CLAUDE_PID, root) || pushInFlight(sys, root);
298
+ if (facts.pushing)
299
+ return facts;
300
+ // Its own records, and pr-autocreate's, are no work left, where a client does not ignore .tmp/.
301
+ facts.dirty = Boolean(out(sys, root, 'git', ['status', '--porcelain', '--', '.', `:(exclude)${STORE}`, ':(exclude).tmp/pr-autocreate']));
302
+ facts.pr = await readPr(sys, root, branch, head, session, err);
303
+ return facts;
304
+ }
305
+ /** The hook: reads the Stop input, returns a block decision, a message, or nothing. Never throws. */
306
+ export async function stopHook(sys, input, err) {
307
+ try {
308
+ const data = JSON.parse(input || 'null');
309
+ const cwd = typeof data?.cwd === 'string' && data.cwd ? data.cwd : sys.env.CLAUDE_PROJECT_DIR;
310
+ if (!data || !cwd)
311
+ return '';
312
+ const root = out(sys, cwd, 'git', ['rev-parse', '--show-toplevel']);
313
+ if (!root)
314
+ return '';
315
+ const settings = settingsAt(sys, root);
316
+ const session = typeof data.session_id === 'string' && data.session_id ? data.session_id : undefined;
317
+ const file = `${root}/${STORE}/${(session ?? 'unknown').replace(/[^\w-]/g, '_')}.json`;
318
+ const previous = sys.exists(file) ? JSON.parse(sys.read(file)) : null;
319
+ const facts = await gather(sys, root, settings, Boolean(data.agent_id), session, err);
320
+ const decision = decide(facts, previous, settings);
321
+ sys.mkdir(`${root}/${STORE}`);
322
+ sys.write(file, JSON.stringify(decision.counter));
323
+ if (!decision.stop)
324
+ return JSON.stringify({ decision: 'block', reason: decision.reason });
325
+ if (decision.say !== undefined && facts.note) {
326
+ // Shown once: the session already said so; this makes sure the owner saw it.
327
+ writeStopNote(sys, root, { ...facts.note, shown: true });
328
+ return JSON.stringify({ systemMessage: `Stopped: ${decision.say}` });
329
+ }
330
+ if (decision.record) {
331
+ writeStopNote(sys, root, { branch: facts.branch, head: facts.head, reason: decision.record, at: sys.now().toISOString(), shown: true });
332
+ return JSON.stringify({
333
+ decision: 'block',
334
+ reason: `The stop hook wrote a stop note for ${facts.branch}: started work is held at ${facts.head.slice(0, 9)} with no reason given. Tell ${settings.owner} what happened, why, and the options; then stop.`,
335
+ systemMessage: `${facts.branch} stopped by the hook: ${decision.record}.`,
336
+ });
337
+ }
338
+ return '';
339
+ }
340
+ catch {
341
+ return '';
342
+ }
343
+ }
344
+ /** `--stop <why>`: records why started work stops at this commit (stuck on the owner, or proven unneeded). */
345
+ export function recordStop(sys, reason) {
346
+ const root = out(sys, sys.cwd, 'git', ['rev-parse', '--show-toplevel']);
347
+ const head = root && out(sys, root, 'git', ['rev-parse', 'HEAD']);
348
+ const branch = root && out(sys, root, 'git', ['symbolic-ref', '--quiet', '--short', 'HEAD']);
349
+ if (!root || !head || !branch)
350
+ return { ok: false, message: 'Not on a branch of a git checkout.' };
351
+ if (reason.trim() === '')
352
+ return { ok: false, message: `Say why in plain English: ${STOP_COMMAND}` };
353
+ let owner = DEFAULTS.owner;
354
+ try {
355
+ owner = settingsAt(sys, root).owner;
356
+ }
357
+ catch {
358
+ // The note matters more than the name it is told to.
359
+ }
360
+ writeStopNote(sys, root, { branch, head, reason: reason.trim(), at: sys.now().toISOString() });
361
+ 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
+ }
363
+ /**
364
+ * `niyam keep-going`, Claude Code's Stop hook (its input on stdin, exit 0
365
+ * always), or `niyam keep-going --stop <why>` (exit 1 when no note was written).
366
+ */
367
+ export async function keepGoing(sys, io, args) {
368
+ if (args[0] === '--stop') {
369
+ const { ok, message } = recordStop(sys, args.slice(1).join(' '));
370
+ io.out(message);
371
+ return ok ? 0 : 1;
372
+ }
373
+ let input = '';
374
+ try {
375
+ input = sys.readStdin();
376
+ }
377
+ catch {
378
+ return 0;
379
+ }
380
+ const said = await stopHook(sys, input, (line) => io.err(line));
381
+ if (said)
382
+ io.out(said);
383
+ return 0;
384
+ }
package/dist/onboard.js CHANGED
@@ -13,6 +13,10 @@ import { UPGRADE } from './upgrade.js';
13
13
  import { isNewer, packageVersion } from './version.js';
14
14
  import { GITHUB_WEB } from './host.js';
15
15
  import { closing, heading, painter, planLines, runStep } from './layout.js';
16
+ /** Where claude.ai connects the GitHub account its cloud sessions and routines work as. */
17
+ export const CLAUDE_CODE_WEB = 'https://claude.ai/code';
18
+ /** Where claude.ai changes that connection. */
19
+ export const CLAUDE_CONNECTORS = 'https://claude.ai/customize/connectors';
16
20
  /** Where `cloud-setup`'s script goes in a Setup field the repo's own setup shares. */
17
21
  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.";
18
22
  /** This product's repository: clients call its shared workflow. */
@@ -145,13 +149,28 @@ const OLD_FIND_CLI = 'cli="$HOME/.config/process-rules/bin/process-rules"; [ -x
145
149
  /** The SessionStart hook after it has found the CLI. */
146
150
  const HOOK_RUN = 'if said=$("$cli" session-start 2>&1); then printf \'%s\\n\' "$said"; ' +
147
151
  'else printf \'%s\\n\' "niyam: STOP. niyam session-start did not run here ($said), so this session cannot be given the agent identity and GitHub is locked out of it. Do not push, fetch, or run gh in this session; tell the owner."; fi';
152
+ /**
153
+ * In a Claude cloud session with no CLI, the SessionStart hook installs it
154
+ * from the clone's cloud setup file, which onboard keeps at the pin, so no
155
+ * Setup script needs pasting: Claude Code has no API for one. The install's
156
+ * own output is dropped; a failure says its last line and the user it ran
157
+ * as, since it writes under /opt and /usr/local, before the STOP that
158
+ * follows when session-start still cannot run. On a Mac, or with a CLI
159
+ * found, it does nothing.
160
+ */
161
+ const CLOUD_INSTALL = `if [ "\${CLAUDE_CODE_REMOTE:-}" = true ] && ! command -v "$cli" >/dev/null 2>&1; then ` +
162
+ `setup="\${CLAUDE_PROJECT_DIR:-.}/${CLOUD_SETUP_PATH}"; ` +
163
+ 'if [ ! -f "$setup" ]; then printf \'%s\\n\' "niyam: this cloud session has no niyam, and the clone has no ' + CLOUD_SETUP_PATH + ' to install it from; run niyam onboard, which writes it."; ' +
164
+ 'elif failed=$(bash "$setup" </dev/null 2>&1 >/dev/null); then printf \'%s\\n\' "niyam: this cloud session had no niyam, so the SessionStart hook installed it from ' + CLOUD_SETUP_PATH + '."; ' +
165
+ 'else printf \'%s\\n\' "niyam: this cloud session has no niyam, and installing it from ' + CLOUD_SETUP_PATH + ' as $(id -un) (uid $(id -u)) failed: $(printf \'%s\\n\' "$failed" | tail -n 1)"; fi; fi; ';
148
166
  /**
149
167
  * What the client's SessionStart hook runs, on a Mac and in a Claude cloud
150
168
  * session alike. When the CLI is missing or fails, what it printed reaches
151
169
  * the session inside a line telling it to stop; the settings' `env` has
152
- * already locked GitHub out.
170
+ * already locked GitHub out. A cloud session with no CLI installs it first
171
+ * (CLOUD_INSTALL).
153
172
  */
154
- export const HOOK_COMMAND = FIND_CLI + HOOK_RUN;
173
+ export const HOOK_COMMAND = FIND_CLI + CLOUD_INSTALL + HOOK_RUN;
155
174
  /** The PreToolUse hook before it finds the CLI: a command naming neither gh nor git goes ahead. */
156
175
  const GUARD_SKIP = 'input=$(cat); ' +
157
176
  // The command alone, not the rest of the input, such as its description and paths.
@@ -197,6 +216,8 @@ export function missingAutoFixRules(settings) {
197
216
  }
198
217
  /** The hook commands older releases wrote, which onboard replaces with this release's. */
199
218
  export const OLDER_HOOK_COMMANDS = [
219
+ // 0.6.11 to 0.6.16's, before P-60: a cloud session with no CLI stopped.
220
+ FIND_CLI + HOOK_RUN,
200
221
  // 0.6.10's, before P-57.
201
222
  P55_FIND_CLI + HOOK_RUN,
202
223
  // 0.6.8 and 0.6.9's, before P-55: the launcher in the old folder alone.
@@ -1030,7 +1051,7 @@ export async function onboard(sys, io, args = []) {
1030
1051
  });
1031
1052
  }
1032
1053
  else if (library !== undefined) {
1033
- byHand.push(`FIGMA_LIBRARY secret: the design library's file key → ${GITHUB_WEB}/${slug}/settings/secrets/actions`);
1054
+ byHand.push(`Once for ${slug}: add the Actions secret FIGMA_LIBRARY, the design library's Figma file key, at ${GITHUB_WEB}/${slug}/settings/secrets/actions.`);
1034
1055
  later.push(`The "figma.library" taken out was not a Figma file key; set the FIGMA_LIBRARY Actions secret to the design library's file key under ${slug} → Settings → Secrets and variables → Actions.`);
1035
1056
  }
1036
1057
  }
@@ -1214,7 +1235,7 @@ export async function onboard(sys, io, args = []) {
1214
1235
  // moves its items and closes it: that is left to the owner, with what the template would have set.
1215
1236
  const board = await setUpBoard(sys, out, (_, step) => Promise.resolve(step !== 'replace'), slug, owner, mine, typeof projectTitle === 'string' ? projectTitle : undefined, approved);
1216
1237
  byHand.unshift(...(board?.byHand ?? []));
1217
- later.unshift(...(board?.byHand ?? []).map((line) => `On the board: ${line}.`));
1238
+ later.unshift(...(board?.byHand ?? []));
1218
1239
  return board !== undefined;
1219
1240
  },
1220
1241
  });
@@ -1235,8 +1256,9 @@ export async function onboard(sys, io, args = []) {
1235
1256
  }
1236
1257
  else if (hook.state === 'outside' || hook.state === 'own') {
1237
1258
  // A hooks folder shared by other repositories (a global core.hooksPath), or the client's own hook, is the owner's to change.
1238
- byHand.push(`add ${hookLine} → ${hook.path}`);
1239
- later.push(`Add the line \`${hookLine}\` to the pre-push git hook ${hook.path}, which ${hook.state === 'own' ? 'is your own' : 'git runs from outside this repository'}.`);
1259
+ const addLine = `Add the line \`${hookLine}\` to the pre-push git hook ${hook.path}, which ${hook.state === 'own' ? 'is your own' : 'git runs from outside this repository'}.`;
1260
+ byHand.push(`Once on this Mac: ${addLine.charAt(0).toLowerCase()}${addLine.slice(1)}`);
1261
+ later.push(addLine);
1240
1262
  }
1241
1263
  steps.push({
1242
1264
  label: `test commit Verified as ${agent}`,
@@ -1248,11 +1270,11 @@ export async function onboard(sys, io, args = []) {
1248
1270
  // connection, so onboard cannot create one or check it.
1249
1271
  if (on('review')) {
1250
1272
  const routine = `${GITHUB_WEB}/${PRODUCT}/blob/v${version}/routines/review.md`;
1251
- byHand.push(`review routine → ${routine}`);
1273
+ byHand.push(`Once for ${slug}: in Claude Code, run /schedule and create a weekly routine on it, with claude.ai's GitHub connected as ${agent} and the prompt below the line in ${routine}.`);
1252
1274
  later.push(`The review routine: create a weekly Claude routine on ${slug} (claude.ai/code/routines, or /schedule in Claude Code), with claude.ai's GitHub connected as ${agent}, and give it the prompt below the line in ${routine}. Until it gives its verdicts, the weekly job labels needs-owner each decision over a week past its review date.`);
1253
1275
  }
1254
1276
  // Claude cloud sessions. Claude Code has no API for a cloud environment's Setup script, so the version lives in a
1255
- // file the repo owns, written at the pin on every run, and the Setup script runs it: one paste, the first time.
1277
+ // file the repo owns, written at the pin on every run, and the SessionStart hook runs it when a session has no CLI.
1256
1278
  const cloudBefore = fileAt(CLOUD_SETUP_PATH);
1257
1279
  const released = await releaseSha256(sys, version, token);
1258
1280
  if ('problem' in released)
@@ -1265,9 +1287,9 @@ export async function onboard(sys, io, args = []) {
1265
1287
  change(CLOUD_SETUP_PATH, text, `installs niyam ${version} in Claude cloud sessions, its download checked against its sha256`);
1266
1288
  }
1267
1289
  if (cloudBefore === undefined) {
1268
- cloud.push({ label: 'Setup script', detail: 'niyam cloud-setup, first' }, { label: "claude.ai's GitHub", detail: `as ${agent}` });
1269
- byHand.push(`cloud sessions, once: claude.ai's GitHub as ${agent}, Setup script from niyam cloud-setup, first`);
1270
- later.push(`Claude cloud sessions, once: connect claude.ai's GitHub as ${agent}, and paste what niyam cloud-setup prints into the cloud environment's Setup script, over any older niyam part. It runs ${CLOUD_SETUP_PATH}, which onboard keeps at the pin, so a new release needs no new paste. ${SETUP_FIRST}`);
1290
+ cloud.push({ label: "claude.ai's GitHub", detail: `as ${agent}` });
1291
+ byHand.push(`Once per claude.ai account: sign in at ${CLAUDE_CODE_WEB} and connect GitHub as ${agent} (or change it at ${CLAUDE_CONNECTORS}); skip it if done.`);
1292
+ later.push(`Claude cloud sessions, once per claude.ai account: connect claude.ai's GitHub as ${agent}. Each session with no niyam installs it from ${CLOUD_SETUP_PATH}, which onboard keeps at the pin, so there is nothing to paste; what niyam cloud-setup prints, put in the cloud environment's Setup script, makes sessions start faster, since Claude caches what a Setup script installs.`);
1271
1293
  }
1272
1294
  }
1273
1295
  // The file under its name before P-56, which no release writes or runs since P-57, goes where the new one is left.
@@ -1280,7 +1302,7 @@ export async function onboard(sys, io, args = []) {
1280
1302
  else
1281
1303
  pull.push({ label: 'cloud-setup.sh', detail: deleted });
1282
1304
  if (cloudBefore !== undefined) {
1283
- later.push(`Claude cloud sessions: a Setup script pasted before niyam 0.6.10 runs ${LEFTOVER_CLOUD_SETUP_PATH}, which this pull request deletes; if yours is one, paste what niyam cloud-setup prints over it, once. ${SETUP_FIRST}`);
1305
+ later.push(`Claude cloud sessions: a Setup script pasted before niyam 0.6.10 runs ${LEFTOVER_CLOUD_SETUP_PATH}, which this pull request deletes; if yours is one, delete niyam's part of it, since sessions now install niyam themselves, or paste what niyam cloud-setup prints over it. ${SETUP_FIRST}`);
1284
1306
  }
1285
1307
  }
1286
1308
  let pullUrl;
@@ -1300,7 +1322,7 @@ export async function onboard(sys, io, args = []) {
1300
1322
  const text = fileAt(WORKFLOW_PATH);
1301
1323
  const unpassed = workflowNeeded && on('figma') && text !== undefined ? jobsWithoutLibrary(text) : [];
1302
1324
  if (unpassed.length > 0) {
1303
- byHand.unshift(`pass FIGMA_LIBRARY in ${unpassed.join(', ')} → ${WORKFLOW_PATH}`);
1325
+ byHand.unshift(`Once for ${slug}: in ${WORKFLOW_PATH}, add FIGMA_LIBRARY: \${{ secrets.FIGMA_LIBRARY }} under the secrets of ${unpassed.join(', ')}, so the design check runs there.`);
1304
1326
  later.unshift(`In ${WORKFLOW_PATH}, ${unpassed.join(', ')} pass the shared checks no FIGMA_LIBRARY secret, so the design check stays off there; add \`FIGMA_LIBRARY: \${{ secrets.FIGMA_LIBRARY }}\` under their secrets.`);
1305
1327
  }
1306
1328
  // A change that puts a file back as it was is no change.
@@ -1329,9 +1351,9 @@ export async function onboard(sys, io, args = []) {
1329
1351
  }));
1330
1352
  merging = refused === undefined;
1331
1353
  if (refused?.notAllowed)
1332
- byHand.unshift(`auto-merge: turn on Allow auto-merge → ${GITHUB_WEB}/${slug}/settings, or merge it yourself`);
1354
+ byHand.unshift(`Now: turn on Allow auto-merge at ${GITHUB_WEB}/${slug}/settings, or merge ${opened.url} yourself once its checks pass.`);
1333
1355
  else if (refused)
1334
- byHand.unshift(`auto-merge: GitHub refused (${refused.problem}); merge it yourself`);
1356
+ byHand.unshift(`Now: merge ${opened.url} yourself once its checks pass, since GitHub refused auto-merge (${refused.problem}).`);
1335
1357
  return true;
1336
1358
  },
1337
1359
  });
@@ -1353,7 +1375,7 @@ export async function onboard(sys, io, args = []) {
1353
1375
  },
1354
1376
  { title: asOwnerItems ? (signedAs && 'login' in signedAs ? `GitHub — signed in as ${signedAs.login}` : `GitHub — one sign-in as ${owner}`) : 'GitHub', items: github },
1355
1377
  { title: 'This Mac', items: mac },
1356
- { title: 'Claude cloud — by hand, once', items: cloud },
1378
+ { title: 'Claude cloud — by hand, once per claude.ai account', items: cloud },
1357
1379
  { title: 'Check', items: [{ label: `one signed test commit by ${agent}, deleted after` }] },
1358
1380
  ];
1359
1381
  for (const line of planLines(paint, planHead(paint, { from: workflowNeeded ? workflowFrom : undefined, version, slug, owner, agent, warnings }), groups))