@veda-hq/niyam 0.6.24 → 0.6.26

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/dist/cloud.js CHANGED
@@ -1,4 +1,6 @@
1
- import { API, BASE_ENV, authorVars, configVars, isNoToken, keyBody, noreplyEmail, pathsFor, signingConfig } from './agent.js';
1
+ import { API, BASE_ENV, authorVars, configVars, isNoToken, keyBody, pathsFor, signingConfig } from './agent.js';
2
+ import { SSH_SIGN, signerScript } from './ssh-sign.js';
3
+ import { commitSignature, publicLine, readPrivateKey, signatureProblem } from './sshsig.js';
2
4
  import { CLAUDE_CODE_WEB, SETUP_FIRST, workflowPins } from './onboard.js';
3
5
  import { PRODUCT, tarballName } from './names.js';
4
6
  import { CLOUD_SETUP_PATH, WORKFLOW_PATH } from './onboard-pull.js';
@@ -44,8 +46,10 @@ const PROBE_MESSAGE = 'niyam: a probe of the agent\'s signing, never on a branch
44
46
  * What makes a cloud session's commits the agent's: its author and committer
45
47
  * variables, with the address of the id GitHub gave with the login, and SSH
46
48
  * signing with the key in SIGNING_KEY_VAR, over the platform's own signing
47
- * (Claude's, through a program of its own: `gpg.ssh.program` goes back to
48
- * ssh-keygen). All of them or none, since a commit that claims the agent
49
+ * (Claude's, through a program of its own: `gpg.ssh.program` becomes niyam's
50
+ * own signer, `niyam ssh-sign`, in Node, since the hosted image has no
51
+ * ssh-keygen, #425, and installing one costs every session time and needs the
52
+ * network). All of them or none, since a commit that claims the agent
49
53
  * must be Verified as the agent (PR identity) and a signing setup that fails
50
54
  * breaks every commit: each is given only when the key is one GitHub lists
51
55
  * for the agent and a probe commit signed with exactly these settings, in
@@ -63,38 +67,31 @@ export async function cloudSigning(sys, root, login, id) {
63
67
  if (!text.startsWith(`${PEM_BEGIN}\n`) || !text.endsWith(`\n${PEM_END}`)) {
64
68
  return { problem: `${SIGNING_KEY_VAR} is not an OpenSSH private key, base64 on one line or as is` };
65
69
  }
66
- const { dir, key } = pathsFor(sys.home, login);
67
- const pub = `${key}.pub`;
68
- const signers = `${dir}/allowed-signers`;
69
- const email = noreplyEmail(id, login);
70
- try {
71
- sys.mkdir(dir);
72
- sys.mkdir(key.slice(0, key.lastIndexOf('/')));
73
- sys.write(key, `${text}\n`, 0o600);
74
- }
75
- catch (error) {
76
- // fail-open: the session keeps the image's identity, which PR identity passes, and says why.
77
- return { problem: `writing ${SIGNING_KEY_VAR} to ${key} failed (${messageOf(error)})` };
78
- }
79
- const derived = sys.exec('ssh-keygen', ['-y', '-f', key], { input: '' });
80
- if (derived.code !== 0)
81
- return { problem: `ssh-keygen cannot read ${SIGNING_KEY_VAR} (${lastLine(derived.stderr) || `exit ${derived.code}`})` };
82
- const body = keyBody(derived.stdout);
70
+ const parsed = readPrivateKey(text);
71
+ if ('problem' in parsed)
72
+ return { problem: `${SIGNING_KEY_VAR} cannot be used: ${parsed.problem}` };
73
+ const body = publicLine(parsed);
83
74
  const listed = await listedSigningKeys(sys, login);
84
75
  if ('problem' in listed)
85
76
  return listed;
86
77
  if (!listed.keys.includes(body))
87
78
  return { problem: `GitHub does not list ${SIGNING_KEY_VAR}'s public half as one of ${login}'s signing keys` };
79
+ const { dir, key } = pathsFor(sys.home, login);
80
+ const pub = `${key}.pub`;
81
+ const signer = `${dir}/${SSH_SIGN}`;
88
82
  try {
83
+ sys.mkdir(dir);
84
+ sys.mkdir(key.slice(0, key.lastIndexOf('/')));
85
+ sys.write(key, `${text}\n`, 0o600);
89
86
  sys.write(pub, `${body} ${login} cloud signing\n`, 0o644);
90
- sys.write(signers, `${email} namespaces="git" ${body}\n`, 0o644);
87
+ sys.write(signer, signerScript(sys.runtime.node, sys.runtime.cli), 0o755);
91
88
  }
92
89
  catch (error) {
93
90
  // fail-open: the session keeps the image's identity, which PR identity passes, and says why.
94
- return { problem: `writing ${pub} failed (${messageOf(error)})` };
91
+ return { problem: `writing ${SIGNING_KEY_VAR} to ${key} failed (${messageOf(error)})` };
95
92
  }
96
- const vars = [...authorVars(login, id), ...configVars([['gpg.ssh.program', 'ssh-keygen'], ...signingConfig(pub)])];
97
- const probe = probeSignature(sys, root, vars, signers);
93
+ const vars = [...authorVars(login, id), ...configVars([['gpg.ssh.program', signer], ...signingConfig(pub)])];
94
+ const probe = probeSignature(sys, root, vars, body);
98
95
  return probe ? { problem: `a probe commit signed with ${SIGNING_KEY_VAR} did not verify as that key (${probe})` } : { vars };
99
96
  }
100
97
  const PEM_BEGIN = '-----BEGIN OPENSSH PRIVATE KEY-----';
@@ -120,10 +117,10 @@ async function listedSigningKeys(sys, login) {
120
117
  }
121
118
  /**
122
119
  * Makes a commit object on no branch with the environment `vars` give, and
123
- * verifies its signature against `signers`, the agent's key alone: undefined
124
- * when it verifies, else what failed.
120
+ * checks its signature is the agent key's, `publicKey`, in git's namespace,
121
+ * in Node, as there is no ssh-keygen: undefined when it is, else what failed.
125
122
  */
126
- function probeSignature(sys, root, vars, signers) {
123
+ function probeSignature(sys, root, vars, publicKey) {
127
124
  // The session's commands get the env file's lines, which unset the lock first: the probe does the same.
128
125
  const base = Object.fromEntries(Object.entries(sys.env).filter(([name]) => !(name in BASE_ENV) && name !== SIGNING_KEY_VAR));
129
126
  const env = { ...base, ...Object.fromEntries(vars) };
@@ -134,8 +131,14 @@ function probeSignature(sys, root, vars, signers) {
134
131
  const commit = sys.exec('git', ['commit-tree', '-S', tree.stdout.trim(), '-m', PROBE_MESSAGE], { cwd: root, env, input: '' });
135
132
  if (commit.code !== 0)
136
133
  return `git commit-tree: ${lastLine(commit.stderr) || `exit ${commit.code}`}`;
137
- const verified = sys.exec('git', ['-c', `gpg.ssh.allowedSignersFile=${signers}`, 'verify-commit', commit.stdout.trim()], { cwd: root, env, input: '' });
138
- return verified.code === 0 ? undefined : `git verify-commit: ${lastLine(verified.stderr) || 'no signature by that key'}`;
134
+ const raw = sys.exec('git', ['cat-file', 'commit', commit.stdout.trim()], { cwd: root, env, input: '' });
135
+ if (raw.code !== 0)
136
+ return `git cat-file: ${lastLine(raw.stderr) || `exit ${raw.code}`}`;
137
+ const signed = commitSignature(raw.stdout);
138
+ if (!signed)
139
+ return 'the probe commit has no signature';
140
+ const problem = signatureProblem(signed.signature, signed.payload, 'git', publicKey);
141
+ return problem ? `its signature: ${problem}` : undefined;
139
142
  }
140
143
  function lastLine(text) {
141
144
  return text.trim().split('\n').at(-1) ?? '';
package/dist/doctor.js CHANGED
@@ -8,7 +8,7 @@ import { closing, findingLines, heading, painter, tilde } from './layout.js';
8
8
  import { exposure, exposureFindings, movedFindings, readDeclined, setAside } from './lockout.js';
9
9
  import { CLOUD_SETUP_PATH, HOOKS_PATH, SARATHI_PATH } from './onboard-pull.js';
10
10
  import { leftoverDir, leftoverToken } from './machine.js';
11
- import { BOARD_SECRETS, GUARD_COMMAND, HOOK_COMMAND, OLDER_GUARD_COMMANDS, OLDER_HOOK_COMMANDS, missingAutoFixRules, sarathiRunner } from './onboard.js';
11
+ import { BOARD_SECRETS, GUARD_COMMAND, HOOK_COMMAND, OLDER_GUARD_COMMANDS, OLDER_HOOK_COMMANDS, missingArtifactRules, missingAutoFixRules, sarathiRunner } from './onboard.js';
12
12
  import { secretNames } from './secrets.js';
13
13
  import { isOrganisation } from './owner-login.js';
14
14
  import { leftBehind } from './owner-step.js';
@@ -196,7 +196,7 @@ async function boardAppFindings(sys, token) {
196
196
  const missing = BOARD_SECRETS.filter((name) => !names.includes(name));
197
197
  return missing.length === 0
198
198
  ? [{ mark: '✓', text: 'board app secrets' }]
199
- : [{ mark: '▲', text: `no ${missing.join(' or ')} secret, so a slice moves to In Progress only from a desktop push`, fix: `${ONBOARD}, which says how to set up the board app` }];
199
+ : [{ mark: '▲', text: `no ${missing.join(' or ')} secret, so a slice moves to In Progress only from a desktop push`, fix: `${ONBOARD} at your own terminal, which sets up the board app` }];
200
200
  }
201
201
  catch (error) {
202
202
  // fail-open: a read that failed is the one ▲ here, as a missing secret breaks nothing.
@@ -205,8 +205,8 @@ async function boardAppFindings(sys, token) {
205
205
  }
206
206
  /**
207
207
  * Client hooks that reach GitHub outside `as-agent` where doctor runs, a Mac
208
- * or a cloud session, and the Auto-fix rules an onboarded repo's Claude Code
209
- * settings lack.
208
+ * or a cloud session, and the Auto-fix and artifact rules an onboarded repo's
209
+ * Claude Code settings lack.
210
210
  */
211
211
  function repoFindings(sys) {
212
212
  return [
@@ -215,7 +215,7 @@ function repoFindings(sys) {
215
215
  text: `${hook} reaches GitHub outside as-agent, so gets 401`,
216
216
  fix: `run its gh or git via niyam as-agent --session <session_id> -- (exit ${LOCKED} when not the agent)`,
217
217
  })),
218
- ...autoFixFindings(sys),
218
+ ...allowFindings(sys),
219
219
  ...twiceFindings(sys),
220
220
  ];
221
221
  }
@@ -261,11 +261,12 @@ function twiceFindings(sys) {
261
261
  return found;
262
262
  }
263
263
  /**
264
- * Which of onboard's Auto-fix rules the repo's `.claude/settings.json`
265
- * lacks, so the auto-mode classifier refuses an agent session turning
266
- * Auto-fix on: checked in an onboarded repo whose file doctor can read.
264
+ * Which of onboard's Auto-fix and artifact rules the repo's
265
+ * `.claude/settings.json` lacks, so the auto-mode classifier refuses an agent
266
+ * session turning Auto-fix on, or publishing the page an ask to the owner
267
+ * links: checked in an onboarded repo whose file doctor can read.
267
268
  */
268
- function autoFixFindings(sys) {
269
+ function allowFindings(sys) {
269
270
  let settings;
270
271
  try {
271
272
  // Where session-start looks, so a cloud session's CLI run from outside the clone still finds it.
@@ -279,9 +280,11 @@ function autoFixFindings(sys) {
279
280
  return [];
280
281
  }
281
282
  const missing = missingAutoFixRules(settings);
282
- return missing.length === 0
283
- ? []
284
- : [{ mark: '▲', text: `${HOOKS_PATH} does not allow ${missing.join(', ')}, so agent sessions cannot turn Auto-fix on`, fix: ONBOARD }];
283
+ const unpublished = missingArtifactRules(settings);
284
+ return [
285
+ ...(missing.length === 0 ? [] : [{ mark: '▲', text: `${HOOKS_PATH} does not allow ${missing.join(', ')}, so agent sessions cannot turn Auto-fix on`, fix: ONBOARD }]),
286
+ ...(unpublished.length === 0 ? [] : [{ mark: '▲', text: `${HOOKS_PATH} does not allow ${unpublished.join(', ')}, so agent sessions cannot publish the page an ask to the owner links`, fix: ONBOARD }]),
287
+ ];
285
288
  }
286
289
  /** Prints the findings, grouped, and closes; exit 1 when any is broken. */
287
290
  function report(sys, io, about, groups) {
@@ -0,0 +1,12 @@
1
+ /** What a caught value says, never throwing itself: its message, else its text, else a stand-in. */
2
+ export function errorDetail(value) {
3
+ try {
4
+ if (value instanceof Error && typeof value.message === 'string')
5
+ return value.message;
6
+ return String(value);
7
+ }
8
+ catch {
9
+ // fail-open: a value with a hostile toString is described, not rethrown from the handler.
10
+ return 'an error that cannot be described';
11
+ }
12
+ }
package/dist/layout.js CHANGED
@@ -35,6 +35,49 @@ export function findingLines(paint, title, findings) {
35
35
  return [];
36
36
  return [paint.dim('│'), `${paint.done('◇')} ${title}`, ...findings.map((finding) => findingLine(paint, finding))];
37
37
  }
38
+ /** How wide a by-hand step's lines are, bar and number included: the narrowest terminal people keep. */
39
+ export const BY_HAND_WIDTH = 80;
40
+ /**
41
+ * `text` in lines of at most `width` characters, broken at spaces; a word
42
+ * longer than that, such as a link, has a line of its own. `width` is a
43
+ * count of UTF-16 code units, not of a terminal's columns, so a line with
44
+ * wide characters (in a path or a name) can run past it.
45
+ */
46
+ export function wrap(text, width) {
47
+ const lines = [];
48
+ let line = '';
49
+ for (const word of text.split(/\s+/).filter(Boolean)) {
50
+ if (line && line.length + 1 + word.length > width) {
51
+ lines.push(line);
52
+ line = word;
53
+ }
54
+ else
55
+ line = line ? `${line} ${word}` : word;
56
+ }
57
+ if (line)
58
+ lines.push(line);
59
+ return lines;
60
+ }
61
+ /**
62
+ * The ◇ By hand group, after a bar: each step numbered, wrapped behind the
63
+ * bar to BY_HAND_WIDTH, a bar between steps; nothing when there are none.
64
+ */
65
+ export function byHandLines(paint, steps) {
66
+ if (steps.length === 0)
67
+ return [];
68
+ const bar = paint.dim('│');
69
+ const lines = [bar, `${paint.warn('◇')} By hand`];
70
+ steps.forEach((step, index) => {
71
+ const number = `${index + 1}.`;
72
+ const indent = ' '.length + number.length + 1;
73
+ const [first = '', ...rest] = wrap(step, BY_HAND_WIDTH - 1 - indent);
74
+ if (index > 0)
75
+ lines.push(bar);
76
+ lines.push(`${bar} ${paint.accent(number)} ${first}`, ...rest.map((line) => `${bar}${' '.repeat(indent)}${line}`));
77
+ });
78
+ lines.push(bar);
79
+ return lines;
80
+ }
38
81
  /** The run's last line. */
39
82
  export function closing(paint, text) {
40
83
  return `${paint.dim('└')} ${text}`;
package/dist/onboard.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { AGENT_VAR, CLI, CONFIG_DIR, PRODUCT } from './names.js';
2
2
  import { API, BASE_ENV, SETTINGS_PATH, account, agentHere, agentIn, agentsSetUp, anyLogin, checkToken, either, isLogin, keyPairProblem, loadSettings, pathsFor, readToken, repoAt, sameLogin, sessionEnv, tokenInfo, } from './agent.js';
3
3
  import { setUpBoard } from './board.js';
4
+ import { BOARD_SECRETS, boardAppSteps, setUpBoardApp } from './board-app.js';
5
+ import { agentSession } from './push-identity.js';
4
6
  import { typesDetail, typesLines, typesPlan } from './issue-types.js';
5
7
  import { asOwner, isOrganisation, ownerScopes, signInOnce } from './owner-login.js';
6
8
  import { appendToArray, removeElements, replaceValues, setMember } from './jsonedit.js';
@@ -15,7 +17,7 @@ import { secretNames, setSecret } from './secrets.js';
15
17
  import { UPGRADE } from './upgrade.js';
16
18
  import { isNewer, packageVersion } from './version.js';
17
19
  import { GITHUB_WEB } from './host.js';
18
- import { closing, heading, painter, planLines, runStep } from './layout.js';
20
+ import { byHandLines, closing, heading, painter, planLines, runStep } from './layout.js';
19
21
  /** Where claude.ai connects the GitHub account its cloud sessions and routines work as. */
20
22
  export const CLAUDE_CODE_WEB = 'https://claude.ai/code';
21
23
  /** Where claude.ai changes that connection. */
@@ -208,14 +210,36 @@ export const AUTO_FIX_RULES = ['mcp__ccd_pr__bind_pr', 'mcp__ccd_pr__get_status'
208
210
  /** The rules that allow every tool of the app's pull request server, AUTO_FIX_RULES among them. */
209
211
  const PR_SERVER_RULES = ['mcp__ccd_pr', 'mcp__ccd_pr__*'];
210
212
  /**
211
- * Which of AUTO_FIX_RULES a settings file's `permissions.allow` lacks, in
212
- * their order: none when it allows the whole server.
213
+ * The permission rules that let agent sessions publish the claude.ai page
214
+ * every ask to the owner links (`Needs you:`, `Proposal:`, `niyam propose
215
+ * --page`): a new page, one from files, and a change to one. Without them
216
+ * the auto-mode classifier refuses the calls as communication. A new page
217
+ * is private to its owner, but a republish (`publish_version` or
218
+ * `edit_version` with a slug) to a page already shared with an organisation
219
+ * or the public changes what its readers see, with no prompt: a cost the
220
+ * owner accepted on veda-hq/niyam#432. Claude Code skips an `mcp__` allow
221
+ * rule with arguments, so no rule here can limit them to private pages.
213
222
  */
214
- export function missingAutoFixRules(settings) {
223
+ export const ARTIFACT_RULES = ['mcp__claude-artifacts__publish_version', 'mcp__claude-artifacts__publish_files', 'mcp__claude-artifacts__edit_version'];
224
+ /** The rules that allow every tool of the artifacts server, ARTIFACT_RULES among them. */
225
+ const ARTIFACT_SERVER_RULES = ['mcp__claude-artifacts', 'mcp__claude-artifacts__*'];
226
+ /**
227
+ * Which of `rules` a settings file's `permissions.allow` lacks, in their
228
+ * order: none when it allows the whole server, by one of `server`.
229
+ */
230
+ function missingRules(settings, rules, server) {
215
231
  const allow = settings?.permissions?.allow;
216
- if (Array.isArray(allow) && allow.some((rule) => PR_SERVER_RULES.includes(rule)))
232
+ if (Array.isArray(allow) && allow.some((rule) => server.includes(rule)))
217
233
  return [];
218
- return AUTO_FIX_RULES.filter((rule) => !Array.isArray(allow) || !allow.includes(rule));
234
+ return rules.filter((rule) => !Array.isArray(allow) || !allow.includes(rule));
235
+ }
236
+ /** Which of AUTO_FIX_RULES a settings file's `permissions.allow` lacks. */
237
+ export function missingAutoFixRules(settings) {
238
+ return missingRules(settings, AUTO_FIX_RULES, PR_SERVER_RULES);
239
+ }
240
+ /** Which of ARTIFACT_RULES a settings file's `permissions.allow` lacks. */
241
+ export function missingArtifactRules(settings) {
242
+ return missingRules(settings, ARTIFACT_RULES, ARTIFACT_SERVER_RULES);
219
243
  }
220
244
  /** The hook commands older releases wrote, which onboard replaces with this release's. */
221
245
  export const OLDER_HOOK_COMMANDS = [
@@ -445,24 +469,8 @@ const FIGMA_SECRETS = [' secrets:', ' FIGMA_TOKEN: ${{ secrets.FIGMA_TOK
445
469
  /** The secrets every job passed before P-23, whether figma was on or not. */
446
470
  const OLDER_SECRETS = [' secrets:', ' FIGMA_TOKEN: ${{ secrets.FIGMA_TOKEN }}'];
447
471
  /** The board GitHub App's secrets, which the Slice started job makes its board token from (P-70). */
448
- export const BOARD_SECRETS = ['NIYAM_BOARD_APP_ID', 'NIYAM_BOARD_APP_KEY'];
449
472
  const BOARD_SECRET_LINES = BOARD_SECRETS.map((name) => ` ${name}: \${{ secrets.${name} }}`);
450
- /** What each board app secret holds. */
451
- const BOARD_SECRET_HOLDS = { NIYAM_BOARD_APP_ID: 'client id', NIYAM_BOARD_APP_KEY: 'private key' };
452
- /**
453
- * The owner's steps, once per organization, to give `slug`'s Slice started
454
- * job the board app's token: make the app, install it, and set the secrets
455
- * `missing`. `unknown` when GitHub would not list the secrets, so they may be
456
- * set already.
457
- */
458
- export function boardAppSteps(slug, missing, unknown = false) {
459
- const org = slug.split('/')[0];
460
- const set = missing.map((name) => `its ${BOARD_SECRET_HOLDS[name]} as ${name}`).join(' and ');
461
- return (`${unknown ? `Unless ${slug} has the Actions secrets ${BOARD_SECRETS.join(' and ')} already, once` : 'Once'} for ${org}: ` +
462
- `make a GitHub App with organization Projects read and write and repository Issues read at ${GITHUB_WEB}/organizations/${org}/settings/apps/new, ` +
463
- `install it on ${slug}, and set ${set}, Actions secrets of the organization or of ${GITHUB_WEB}/${slug}/settings/secrets/actions. ` +
464
- 'Until then a slice moves to In Progress on the board only from a desktop push.');
465
- }
473
+ export { BOARD_SECRETS, boardAppSteps };
466
474
  /**
467
475
  * The secrets block job `id` passes the shared checks: the Figma secrets on
468
476
  * every job, and the board app's on the pull request job alone, since only
@@ -822,7 +830,7 @@ function handlersOf(sarathi, event) {
822
830
  /**
823
831
  * The client's Claude Code settings with this release's hooks and lock: each
824
832
  * entry an older release wrote swapped where it stands, a missing one added,
825
- * the lock's variables set in `env`, and REVIEW_THREAD_RULE and AUTO_FIX_RULES allowed. Every edit is made in the text, so
833
+ * the lock's variables set in `env`, and REVIEW_THREAD_RULE, AUTO_FIX_RULES and ARTIFACT_RULES allowed. Every edit is made in the text, so
826
834
  * the rest of the file keeps its layout. Says what changed, for the question.
827
835
  *
828
836
  * Where the project keeps `.claude/sarathi.json` (`sarathiBefore`) and the
@@ -982,9 +990,16 @@ export function claudeSettings(before, sarathiBefore) {
982
990
  if (lacking.length > 0) {
983
991
  changes.push(`allow ${lacking.join(', ')} without a prompt, so agent sessions turn Auto-fix on for their own pull requests`);
984
992
  }
985
- // One word for both, so the plan's line stays short.
986
- if (review || renamed.replaced > 0 || lacking.length > 0)
987
- labels.push(!(review || renamed.replaced > 0) ? 'Auto-fix rules' : lacking.length === 0 ? 'review rule' : 'allow rules');
993
+ const unpublished = missingArtifactRules(parsed());
994
+ for (const rule of unpublished)
995
+ text = appendToArray(text, ['permissions'], 'allow', rule);
996
+ if (unpublished.length > 0) {
997
+ changes.push(`allow ${unpublished.join(', ')} without a prompt, so agent sessions publish the page an ask to the owner links`);
998
+ }
999
+ // One group's own word, or one word for several, so the plan's line stays short.
1000
+ const groups = [review || renamed.replaced > 0 ? 'review rule' : '', lacking.length > 0 ? 'Auto-fix rules' : '', unpublished.length > 0 ? 'artifact rules' : ''].filter(Boolean);
1001
+ if (groups.length > 0)
1002
+ labels.push(groups.length === 1 ? groups[0] : 'allow rules');
988
1003
  }
989
1004
  catch (error) {
990
1005
  throw new Error(`${HOOKS_PATH}: ${error.message}`);
@@ -1448,7 +1463,25 @@ export async function onboard(sys, io, args = []) {
1448
1463
  if (workflowNeeded && passed.board && (await byOrganisation())) {
1449
1464
  const names = await secretNames(sys, slug, token);
1450
1465
  const missing = BOARD_SECRETS.filter((name) => !names?.includes(name));
1451
- if (missing.length > 0) {
1466
+ // The app is made from a manifest in the owner's browser (P-72): a run with no one at the terminal, or an agent's
1467
+ // or a cloud session, leaves it by hand.
1468
+ const browser = sys.tty && !agentSession(sys) && sys.env.CLAUDE_CODE_REMOTE !== 'true';
1469
+ if (missing.length > 0 && browser) {
1470
+ // An organisation's app already made is shared with the repository with no click.
1471
+ github.push({ label: 'board app', detail: 'two clicks in the browser, if it is new' });
1472
+ steps.push({
1473
+ label: 'board app',
1474
+ owner: true,
1475
+ async run(out, mine) {
1476
+ const left = await setUpBoardApp(sys, out, slug, mine);
1477
+ byHand.push(...left);
1478
+ later.push(...left);
1479
+ // fail-open: what GitHub refused, or a click that did not come, is left by hand; the run goes on.
1480
+ return true;
1481
+ },
1482
+ });
1483
+ }
1484
+ else if (missing.length > 0) {
1452
1485
  const steps = boardAppSteps(slug, missing, names === undefined);
1453
1486
  byHand.push(steps);
1454
1487
  later.push(steps);
@@ -1700,11 +1733,9 @@ export async function onboard(sys, io, args = []) {
1700
1733
  byHand.push(keyByHand);
1701
1734
  }
1702
1735
  }
1736
+ for (const line of byHandLines(paint, byHand))
1737
+ io.out(line);
1703
1738
  io.out(closing(paint, `${!pullUrl ? 'Done; no file changes, so no pull request.' : merging ? `${pullUrl} ${queue !== undefined ? 'the merge queue merges it' : 'merges itself'} when checks pass` : `Merge ${pullUrl}`}`));
1704
- io.out('');
1705
- io.out('By hand:');
1706
- for (const line of byHand)
1707
- io.out(` ${line}`);
1708
1739
  return exitCode;
1709
1740
  }
1710
1741
  /** How many times onboard asks GitHub about the test commit, waiting a little longer each time. */
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';
2
2
  import { dirname, resolve } from 'node:path';
3
3
  import { githubSlug, isNoToken, SETTINGS_PATH } from './agent.js';
4
4
  import { agentEnv } from './as-agent.js';
5
+ import { schema } from './doc-numbers.js';
5
6
  import { GITHUB_API, GITHUB_HOST } from './host.js';
6
7
  import { commands } from './shell.js';
7
8
  import { sessionToken } from './work.js';
@@ -588,6 +589,50 @@ export function listForAutofix(sys, session, url) {
588
589
  return false;
589
590
  }
590
591
  }
592
+ /**
593
+ * The pull request's latest state on the session's sarathi Auto-fix list, folded as sarathi's `readRows` and
594
+ * `fold` do: rows whose `pr` and `event` are strings, the pull request matched in lower case, `warned` skipped,
595
+ * `opened` only adding it, any other event setting its state. Undefined when the list does not name it, or
596
+ * cannot be read.
597
+ */
598
+ export function autofixState(sys, session, url) {
599
+ const pull = pullOf(url);
600
+ if (!session || !SARATHI_SESSION.test(session) || !pull)
601
+ return undefined;
602
+ const file = resolve(autofixDir(sys), `${session}.jsonl`);
603
+ let text;
604
+ try {
605
+ text = sys.read(file);
606
+ }
607
+ catch {
608
+ // fail-open: a list that cannot be read shows no state, and the whole instruction goes out
609
+ return undefined;
610
+ }
611
+ const key = pull.pr.toLowerCase();
612
+ let state;
613
+ for (const line of text.split('\n')) {
614
+ let row;
615
+ try {
616
+ row = ListRowSchema.parse(JSON.parse(line));
617
+ }
618
+ catch {
619
+ // fail-open: a blank or partial line, or one that is no row, as sarathi skips it
620
+ continue;
621
+ }
622
+ if (row.pr.toLowerCase() !== key || row.event === 'warned')
623
+ continue;
624
+ if (row.event !== 'opened' || state === undefined)
625
+ state = row.event;
626
+ }
627
+ return state;
628
+ }
629
+ /** A row of sarathi's Auto-fix list, as its `readRows` keeps one: `pr` and `event` strings. */
630
+ const ListRowSchema = schema((value) => {
631
+ const { pr, event } = (typeof value === 'object' && value !== null ? value : {});
632
+ if (typeof pr !== 'string' || typeof event !== 'string')
633
+ throw new Error('not a list row');
634
+ return { pr, event };
635
+ });
591
636
  /** How the session replaces the placeholder body. */
592
637
  function editHint(settings, pulls, number) {
593
638
  return pulls.cloud ? `gh api -X PATCH repos/${pulls.slug}/pulls/${number} -F body=@FILE` : settings.describe;
@@ -601,6 +646,9 @@ async function autofixMessage(sys, root, settings, state, session, pulls, listed
601
646
  const ack = `${stateDir(root)}/acks/${who}-${pr.number}`;
602
647
  if (sys.exists(ack))
603
648
  return '';
649
+ // sarathi's list shows Auto-fix on already: nothing to say, and no ack, so an `off` later is told at a later Stop.
650
+ if (listed && settings.autofixList && autofixState(sys, typeof session === 'string' ? session : undefined, pr.url) === 'on')
651
+ return '';
604
652
  try {
605
653
  sys.confine(root, ack);
606
654
  sys.mkdir(dirname(ack));
package/dist/run.js CHANGED
@@ -25,6 +25,7 @@ import { reviewThread, threadArgs } from './review-thread.js';
25
25
  import { onboard, onboardArgs } from './onboard.js';
26
26
  import { ownerStep, ownerStepArgs } from './owner-step.js';
27
27
  import { sessionStart } from './session-start.js';
28
+ import { SSH_SIGN, sshSign } from './ssh-sign.js';
28
29
  import { upgrade } from './upgrade.js';
29
30
  import { prMerged, prStarted, prePush, prWorkRules, propose } from './work.js';
30
31
  import { CLI } from './names.js';
@@ -52,6 +53,8 @@ Commands:
52
53
  For agents run from any tool: the GitHub lock, then the agent identity where this Mac
53
54
  has it, as shell lines for eval "$(niyam env)", or with -- the command run under them
54
55
  session-start Run by a client's SessionStart hook: the agent identity, or GitHub locked out
56
+ ssh-sign -Y sign -n <namespace> -f <key> <file>...
57
+ Run by git in a Claude cloud session, as gpg.ssh.program: signs as ssh-keygen does
55
58
  guard Run by a client's PreToolUse hook: gh and git's remote commands only as the agent
56
59
  as-agent --session <session_id> -- <command> [args...]
57
60
  For a client's hook: run one command as the session's agent, or nothing (exit ${LOCKED})
@@ -151,7 +154,7 @@ export function proposeArgs(args) {
151
154
  /** Runs one command and returns its exit code: 0 done, 1 failed, 2 bad usage. */
152
155
  export async function run(args, io, sys) {
153
156
  const [command, ...rest] = args;
154
- const allowed = command === 'onboard' || command === 'machine' || command === 'cloud-key' || 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' || command === 'doc-number' || command === 'renumber-doc' || command === 'work-item-number' || command === 'board-audit' ? Infinity : command === 'pre-push' || command === 'pr-signals' ? 2 : command === 'doctor' ? 1 : 0;
157
+ const allowed = command === 'onboard' || command === 'machine' || command === 'cloud-key' || 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' || command === 'doc-number' || command === 'renumber-doc' || command === 'work-item-number' || command === 'board-audit' || command === SSH_SIGN ? Infinity : command === 'pre-push' || command === 'pr-signals' ? 2 : command === 'doctor' ? 1 : 0;
155
158
  const extra = rest[allowed];
156
159
  if (extra !== undefined) {
157
160
  io.err(`niyam: unexpected argument "${extra}"`);
@@ -183,6 +186,8 @@ export async function run(args, io, sys) {
183
186
  return 0;
184
187
  case 'cloud-setup':
185
188
  return cloudSetup(io);
189
+ case SSH_SIGN:
190
+ return sshSign(io, rest);
186
191
  case 'session-start':
187
192
  return sessionStart(await sys(), io);
188
193
  case 'guard':
package/dist/secrets.js CHANGED
@@ -8,48 +8,96 @@ import { API } from './agent.js';
8
8
  export async function secretNames(sys, slug, token) {
9
9
  const names = [];
10
10
  for (const kind of ['secrets', 'organization-secrets']) {
11
- for (let page = 1;; page++) {
12
- const listed = await sys.http(`${API}/repos/${slug}/actions/${kind}?per_page=100&page=${page}`, { token });
13
- const secrets = listed.json?.secrets;
14
- if (listed.status !== 200 || !Array.isArray(secrets))
15
- return undefined;
16
- names.push(...secrets.flatMap((secret) => (typeof secret?.name === 'string' ? [secret.name] : [])));
17
- if (secrets.length < 100)
18
- break;
19
- }
11
+ const listed = await listNames(sys, `${API}/repos/${slug}/actions/${kind}`, token);
12
+ if (listed === undefined)
13
+ return undefined;
14
+ names.push(...listed);
20
15
  }
21
16
  return names;
22
17
  }
18
+ /** The names of `slug`'s own Actions secrets, not its organization's, as `token` sees them; undefined when GitHub will not list them. */
19
+ export function repoSecretNames(sys, slug, token) {
20
+ return listNames(sys, `${API}/repos/${slug}/actions/secrets`, token);
21
+ }
22
+ /** The names of the organization `org`'s own Actions secrets, as `token` sees them; undefined when GitHub will not list them. */
23
+ export function orgSecretNames(sys, org, token) {
24
+ return listNames(sys, `${API}/orgs/${org}/actions/secrets`, token);
25
+ }
26
+ /** The names of the secrets GitHub lists at `url`, page by page; undefined when it will not list them. */
27
+ async function listNames(sys, url, token) {
28
+ const names = [];
29
+ for (let page = 1;; page++) {
30
+ const listed = await sys.http(`${url}?per_page=100&page=${page}`, { token });
31
+ const secrets = listed.json?.secrets;
32
+ if (listed.status !== 200 || !Array.isArray(secrets))
33
+ return undefined;
34
+ names.push(...secrets.flatMap((secret) => (typeof secret?.name === 'string' ? [secret.name] : [])));
35
+ if (secrets.length < 100)
36
+ return names;
37
+ }
38
+ }
23
39
  /**
24
- * Sets the Actions secret `name` of `slug` to `value`, as the account `token`
25
- * is: GitHub takes a secret only sealed with the repository's Actions public
26
- * key, as a libsodium sealed box, so the value never reaches GitHub, or any
27
- * output, in the clear. Returns why it failed, never naming the value.
40
+ * `value` sealed with the Actions public key GitHub gives at `keyUrl`, as a
41
+ * libsodium sealed box, so the value never reaches GitHub, or any output, in
42
+ * the clear; or why not, naming `where` and never the value.
28
43
  */
29
- export async function setSecret(sys, slug, token, name, value) {
30
- const asked = await sys.http(`${API}/repos/${slug}/actions/secrets/public-key`, { token });
44
+ async function seal(sys, keyUrl, token, where, name, value) {
45
+ const asked = await sys.http(keyUrl, { token });
31
46
  const { key_id: id, key } = (asked.json ?? {});
32
47
  if (asked.status !== 200 || typeof id !== 'string' || typeof key !== 'string') {
33
- return `GitHub did not give ${slug}'s Actions public key (HTTP ${asked.status}), so the ${name} secret is not set`;
48
+ return { problem: `GitHub did not give ${where}'s Actions public key (HTTP ${asked.status}), so the ${name} secret is not set` };
34
49
  }
35
50
  // Loaded here alone: the shared checks run the CLI from its source with no packages installed.
36
51
  const { default: sodium } = await import('libsodium-wrappers');
37
52
  await sodium.ready;
38
- let sealed;
39
53
  try {
40
- sealed = sodium.crypto_box_seal(new TextEncoder().encode(value), Buffer.from(key, 'base64'));
54
+ return { encrypted_value: Buffer.from(sodium.crypto_box_seal(new TextEncoder().encode(value), Buffer.from(key, 'base64'))).toString('base64'), key_id: id };
41
55
  }
42
56
  catch {
43
- return `${slug}'s Actions public key is not one a secret can be sealed with, so the ${name} secret is not set`;
57
+ return { problem: `${where}'s Actions public key is not one a secret can be sealed with, so the ${name} secret is not set` };
44
58
  }
45
- const put = await sys.http(`${API}/repos/${slug}/actions/secrets/${name}`, {
46
- method: 'PUT',
47
- token,
48
- body: { encrypted_value: Buffer.from(sealed).toString('base64'), key_id: id },
49
- });
50
- // 201: made; 204: replaced.
59
+ }
60
+ /** Why a PUT of the secret `name` failed; nothing when GitHub made (201) or replaced (204) it. */
61
+ function putProblem(name, put) {
51
62
  if (put.status === 201 || put.status === 204)
52
63
  return undefined;
53
64
  const why = put.json?.message;
54
65
  return `GitHub did not set the ${name} secret (HTTP ${put.status}${typeof why === 'string' ? `: ${why}` : ''})`;
55
66
  }
67
+ /**
68
+ * Sets the Actions secret `name` of `slug` to `value`, as the account `token`
69
+ * is, sealed with the repository's Actions public key. Returns why it failed,
70
+ * never naming the value.
71
+ */
72
+ export async function setSecret(sys, slug, token, name, value) {
73
+ const sealed = await seal(sys, `${API}/repos/${slug}/actions/secrets/public-key`, token, slug, name, value);
74
+ if ('problem' in sealed)
75
+ return sealed.problem;
76
+ return putProblem(name, await sys.http(`${API}/repos/${slug}/actions/secrets/${name}`, { method: 'PUT', token, body: sealed }));
77
+ }
78
+ /**
79
+ * Sets the organization `org`'s Actions secret `name` to `value`, shared
80
+ * with the repositories `repositoryIds` alone, as the account `token` is,
81
+ * sealed with the organization's Actions public key. Returns why it failed,
82
+ * never naming the value.
83
+ */
84
+ export async function setOrgSecret(sys, org, token, name, value, repositoryIds) {
85
+ const sealed = await seal(sys, `${API}/orgs/${org}/actions/secrets/public-key`, token, org, name, value);
86
+ if ('problem' in sealed)
87
+ return sealed.problem;
88
+ const body = { ...sealed, visibility: 'selected', selected_repository_ids: repositoryIds };
89
+ return putProblem(name, await sys.http(`${API}/orgs/${org}/actions/secrets/${name}`, { method: 'PUT', token, body }));
90
+ }
91
+ /**
92
+ * Shares the organization `org`'s Actions secret `name`, one with selected
93
+ * repositories, with the repository `repositoryId` too. Returns why not.
94
+ */
95
+ export async function shareOrgSecret(sys, org, token, name, repositoryId) {
96
+ const put = await sys.http(`${API}/orgs/${org}/actions/secrets/${name}/repositories/${repositoryId}`, { method: 'PUT', token });
97
+ if (put.status === 204)
98
+ return undefined;
99
+ // 409: the secret's visibility is all or private repositories, so GitHub decides by that which repositories see it.
100
+ return put.status === 409
101
+ ? `${org}'s ${name} secret is visible by type of repository, not to selected ones, so GitHub will not add one to it`
102
+ : `GitHub did not share ${org}'s ${name} secret with the repository (HTTP ${put.status})`;
103
+ }