@veda-hq/niyam 0.6.22 → 0.6.24

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/onboard.js CHANGED
@@ -7,9 +7,11 @@ import { appendToArray, removeElements, replaceValues, setMember } from './jsone
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
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
- import { cloudRepoScript, cloudScriptVersion, releaseSha256 } from './cloud.js';
10
+ import { SIGNING_KEY_VAR, cloudRepoScript, cloudScriptVersion, releaseSha256 } from './cloud.js';
11
+ import { CLOUD_KEY_TITLE, cloudKeyRefusal, listedKeys, makeCloudKey, pasteLines } from './cloud-key.js';
12
+ import { detail } from './doc-numbers.js';
11
13
  import { tagOnMain } from './release-tag.js';
12
- import { setSecret } from './secrets.js';
14
+ import { secretNames, setSecret } from './secrets.js';
13
15
  import { UPGRADE } from './upgrade.js';
14
16
  import { isNewer, packageVersion } from './version.js';
15
17
  import { GITHUB_WEB } from './host.js';
@@ -442,12 +444,46 @@ function workflowHead(branch, version, comments, schedule = DEFAULT_SCHEDULE, ty
442
444
  const FIGMA_SECRETS = [' secrets:', ' FIGMA_TOKEN: ${{ secrets.FIGMA_TOKEN }}', ' FIGMA_LIBRARY: ${{ secrets.FIGMA_LIBRARY }}'];
443
445
  /** The secrets every job passed before P-23, whether figma was on or not. */
444
446
  const OLDER_SECRETS = [' secrets:', ' FIGMA_TOKEN: ${{ secrets.FIGMA_TOKEN }}'];
447
+ /** 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
+ 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' };
445
452
  /**
446
- * A job's `niyam-ref` line and the block of Figma secrets after it, as
447
- * either list writes it, or the line alone when no secrets follow: a block
448
- * with secrets of the client's own is left as it is.
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.
449
457
  */
450
- const SECRETS_AFTER_REF = /^( {6}niyam-ref:[^\n]*\n)(?: {4}secrets:\n(?: {6}FIGMA_(?:TOKEN|LIBRARY): \$\{\{ secrets\.FIGMA_(?:TOKEN|LIBRARY) \}\}\n)+(?! {6})|(?! {4}secrets:))/gm;
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
+ }
466
+ /**
467
+ * The secrets block job `id` passes the shared checks: the Figma secrets on
468
+ * every job, and the board app's on the pull request job alone, since only
469
+ * its Slice started job uses them.
470
+ */
471
+ function secretsOf(id, { figma, board }) {
472
+ const lines = [...(figma ? FIGMA_SECRETS.slice(1) : []), ...(board && id === CLI ? BOARD_SECRET_LINES : [])];
473
+ return lines.length > 0 ? [' secrets:', ...lines] : [];
474
+ }
475
+ /** A secret onboard writes, by name, as a line of a job's block. */
476
+ const OWN_SECRET = String.raw `(?:FIGMA_(?:TOKEN|LIBRARY)|NIYAM_BOARD_APP_(?:ID|KEY))`;
477
+ /**
478
+ * A job's `niyam-ref` line and the block of onboard's secrets after it, as
479
+ * any release writes it, or the line alone when no secrets follow: a block
480
+ * with secrets of the client's own, or `secrets: inherit`, is left as it is.
481
+ */
482
+ const SECRETS_AFTER_REF = new RegExp(String.raw `^( {6}niyam-ref:[^\n]*\n)(?: {4}secrets:\n(?: {6}${OWN_SECRET}: \$\{\{ secrets\.${OWN_SECRET} \}\}\n)+(?! {6})|(?! {4}secrets:))`, 'gm');
483
+ /** The id of the job whose lines run through `offset` in workflow `text`: the last two-space key before it. */
484
+ function jobAt(text, offset) {
485
+ return [...text.slice(0, offset).matchAll(/^ {2}([\w-]+):[ \t]*$/gm)].at(-1)?.[1];
486
+ }
451
487
  /**
452
488
  * The jobs of a workflow that call the shared checks without passing them
453
489
  * FIGMA_LIBRARY, by name: each job's own block is read, so one job missing it
@@ -471,10 +507,11 @@ function callChecks(version, secrets) {
471
507
  * to the default branch and weekly, at the niyam release `version`.
472
508
  * Pull request and push runs are read-only; the weekly job alone writes to
473
509
  * issues. Upgrading is changing that version, which each job names twice.
474
- * The Figma secrets are passed only when the figma feature is on; the
510
+ * The Figma secrets are passed only when the figma feature is on, and the
511
+ * board app's, by the pull request job alone, only when `board` is; the
475
512
  * weekly job runs on the settings' `schedule`.
476
513
  */
477
- export function workflow(branch, version, figma, schedule = DEFAULT_SCHEDULE, settings = SETTINGS_PATH) {
514
+ export function workflow(branch, version, figma, schedule = DEFAULT_SCHEDULE, settings = SETTINGS_PATH, board = false) {
478
515
  const secrets = figma ? FIGMA_SECRETS : [];
479
516
  return [
480
517
  ...workflowHead(branch, version, [
@@ -485,7 +522,7 @@ export function workflow(branch, version, figma, schedule = DEFAULT_SCHEDULE, se
485
522
  ` ${CLI}:`,
486
523
  jobName(CLI),
487
524
  READ_ONLY_IF,
488
- ...callChecks(version, secrets),
525
+ ...callChecks(version, secretsOf(CLI, { figma, board })),
489
526
  '',
490
527
  ' # The weekly run alone writes to issues: it comments and opens undo issues.',
491
528
  ` ${CLI}-weekly:`,
@@ -537,17 +574,23 @@ function flowScalar(value, quote) {
537
574
  * already split into a read-only `niyam` job and a `niyam-weekly` job, move
538
575
  * the version pins, the one branch pushes run on when the default branch has
539
576
  * changed, the one cron the weekly job runs on when the settings' schedule
540
- * has changed, and each job's Figma secrets to what the figma feature needs,
577
+ * has changed, and each job's Figma secrets to what the figma feature needs
578
+ * and the pull request job's board app secrets to what `board` needs,
541
579
  * leaving the rest as the client has it; any other workflow is replaced.
542
580
  */
543
- export function workflowUpdate(before, branch, version, figma, schedule = DEFAULT_SCHEDULE, settings = SETTINGS_PATH) {
581
+ export function workflowUpdate(before, branch, version, figma, schedule = DEFAULT_SCHEDULE, settings = SETTINGS_PATH, board = false) {
544
582
  if (before === undefined)
545
- return { kind: 'write', text: workflow(branch, version, figma, schedule, settings) };
546
- return repinned(before, branch, version, figma, schedule, settings);
583
+ return { kind: 'write', text: workflow(branch, version, figma, schedule, settings, board) };
584
+ return repinned(before, branch, version, figma, schedule, settings, board);
585
+ }
586
+ /** The secrets of onboard's own a block of a job names, by what they are for. */
587
+ function ownSecrets(block) {
588
+ const names = [...block.matchAll(/^ {6}([\w-]+):/gm)].map((match) => match[1]);
589
+ return { figma: names.filter((name) => name.startsWith('FIGMA_')).join(','), board: names.filter((name) => name.startsWith('NIYAM_BOARD_')).join(',') };
547
590
  }
548
591
  /** workflowUpdate on a workflow that is there. */
549
- function repinned(before, branch, version, figma, schedule, settings) {
550
- const wanted = workflow(branch, version, figma, schedule, settings);
592
+ function repinned(before, branch, version, figma, schedule, settings, board) {
593
+ const wanted = workflow(branch, version, figma, schedule, settings, board);
551
594
  if (before === wanted)
552
595
  return { kind: 'same' };
553
596
  const pins = workflowPins(before);
@@ -558,13 +601,13 @@ function repinned(before, branch, version, figma, schedule, settings) {
558
601
  const merged = job(`${CLI}-merged`);
559
602
  const added = split && !merged && pins.length === 4 && from !== undefined ? addMergedJob(before, from, figma) : undefined;
560
603
  if (added !== undefined) {
561
- const update = repinned(added, branch, version, figma, schedule, settings);
604
+ const update = repinned(added, branch, version, figma, schedule, settings, board);
562
605
  return { ...(update.kind === 'repin' ? update : { text: added }), kind: 'repin', merged: true };
563
606
  }
564
607
  const asks = job(`${CLI}-asks`);
565
608
  const withAsks = split && merged && !asks && pins.length === 6 && from !== undefined ? addAsksJob(before, from, figma) : undefined;
566
609
  if (withAsks !== undefined) {
567
- const update = repinned(withAsks, branch, version, figma, schedule, settings);
610
+ const update = repinned(withAsks, branch, version, figma, schedule, settings, board);
568
611
  // The asks job it adds also types each new issue, so the plan says so.
569
612
  return { ...(update.kind === 'repin' ? update : { text: withAsks }), kind: 'repin', asks: true, types: true };
570
613
  }
@@ -590,12 +633,31 @@ function repinned(before, branch, version, figma, schedule, settings) {
590
633
  .replace(HEADER_PIN, (_, _head, _old, dot) => `# Written by ${CLI} onboard: the shared ${CLI} checks at v${version}${dot}`)
591
634
  .replace(PUSH_BRANCH, (line, head, quote, _old, tail) => moved ? `${head}${flowScalar(branch, quote)}${tail}` : line)
592
635
  .replace(SCHEDULE, (line, comment, head, quote, _old, tail) => rescheduled ? `${comment === undefined ? '' : `${scheduleComment(schedule, settings)}\n`}${head}${quote || "'"}${schedule}${quote || "'"}${tail}` : line);
593
- const secrets = figma ? `${FIGMA_SECRETS.join('\n')}\n` : '';
594
- const text = pinned.replace(SECRETS_AFTER_REF, (_, ref) => `${ref}${secrets}`);
636
+ // Each job's block as that job passes it; which part changed, Figma's or the board app's, is said apart.
637
+ const changed = { figma: false, board: false };
638
+ const text = pinned.replace(SECRETS_AFTER_REF, (block, ref, offset, whole) => {
639
+ const lines = secretsOf(jobAt(whole, offset) ?? '', { figma, board });
640
+ const now = `${ref}${lines.map((line) => `${line}\n`).join('')}`;
641
+ const had = ownSecrets(block);
642
+ const has = ownSecrets(now);
643
+ changed.figma ||= had.figma !== has.figma;
644
+ changed.board ||= had.board !== has.board;
645
+ return now;
646
+ });
595
647
  if (text === before)
596
648
  return { kind: 'same' };
597
649
  const stale = pins.find((pin) => pin !== version);
598
- return { kind: 'repin', text, ...(stale ? { from: stale } : {}), ...(moved ? { branch } : {}), ...(rescheduled ? { schedule } : {}), ...(text !== pinned ? { secrets: true } : {}), ...(authors ? { authors: true } : {}), ...(types ? { types: true } : {}) };
650
+ return {
651
+ kind: 'repin',
652
+ text,
653
+ ...(stale ? { from: stale } : {}),
654
+ ...(moved ? { branch } : {}),
655
+ ...(rescheduled ? { schedule } : {}),
656
+ ...(changed.figma ? { secrets: true } : {}),
657
+ ...(changed.board ? { board: true } : {}),
658
+ ...(authors ? { authors: true } : {}),
659
+ ...(types ? { types: true } : {}),
660
+ };
599
661
  }
600
662
  return { kind: 'replace', text: wanted };
601
663
  }
@@ -992,7 +1054,7 @@ export function onboardArgs(args) {
992
1054
  return { named, ...(features ? { features } : {}), ...(add ? { add } : {}), ...(yes ? { yes: true } : {}), ...(dryRun ? { dryRun: true } : {}) };
993
1055
  }
994
1056
  /** What a workflow update changes, in a few words for the plan. */
995
- function workflowDetail(update, version, figma) {
1057
+ function workflowDetail(update, version, { figma, board }) {
996
1058
  if (update.kind !== 'repin')
997
1059
  return { write: 'new', replace: 'replaced' }[update.kind];
998
1060
  return ([
@@ -1000,6 +1062,7 @@ function workflowDetail(update, version, figma) {
1000
1062
  ...(update.branch ? [`branch → ${update.branch}`] : []),
1001
1063
  ...(update.schedule ? [`schedule → ${update.schedule}`] : []),
1002
1064
  ...(update.secrets ? [figma ? 'Figma secrets' : 'no Figma secrets'] : []),
1065
+ ...(update.board ? [board ? 'board app secrets' : 'no board app secrets'] : []),
1003
1066
  ...(update.merged ? ['merged job'] : []),
1004
1067
  ...(update.asks ? ['needs-owner job'] : []),
1005
1068
  ...(update.authors ? ['needs-owner job only for owners, members and collaborators'] : []),
@@ -1007,7 +1070,7 @@ function workflowDetail(update, version, figma) {
1007
1070
  ].join(', ') || `header → v${version}`);
1008
1071
  }
1009
1072
  /** What a workflow update changes, in full for the pull request's description. */
1010
- function workflowWhat(update, version, figma, schedulePath, file = WORKFLOW_PATH) {
1073
+ function workflowWhat(update, version, { figma, board }, schedulePath, file = WORKFLOW_PATH) {
1011
1074
  if (update.kind !== 'repin') {
1012
1075
  return {
1013
1076
  write: `write ${WORKFLOW_PATH}, which runs the shared niyam checks`,
@@ -1019,6 +1082,9 @@ function workflowWhat(update, version, figma, schedulePath, file = WORKFLOW_PATH
1019
1082
  ...(update.branch ? [`run pushes on the default branch, ${update.branch}`] : []),
1020
1083
  ...(update.schedule ? [`run the weekly decisions job on the schedule ${schedulePath} sets, cron ${update.schedule} UTC`] : []),
1021
1084
  ...(update.secrets ? [figma ? 'pass the FIGMA_TOKEN and FIGMA_LIBRARY secrets' : 'stop passing Figma secrets, with figma off'] : []),
1085
+ ...(update.board
1086
+ ? [board ? `pass the pull request job's checks the board app's ${BOARD_SECRETS.join(' and ')} secrets, which move a slice to In Progress when its pull request opens` : 'stop passing the board app secrets, with board off']
1087
+ : []),
1022
1088
  ...(update.merged ? ['add a job that closes the slice a merged pull request names, the one pull request run that writes to issues'] : []),
1023
1089
  ...(update.asks ? ["add a job that labels an issue needs-owner where the agent asks the owner, and takes it off at the owner's approved label, Decision: comment or (hourly) 👍"] : []),
1024
1090
  ...(update.authors ? ['start the needs-owner job only on a comment by the owner, a member or a collaborator'] : []),
@@ -1046,7 +1112,9 @@ function planHead(paint, head) {
1046
1112
  * agent. It prints that as one plan and asks once (`--yes` skips the
1047
1113
  * question, `--dry-run` stops at the plan); a no changes nothing. After the
1048
1114
  * yes, one browser sign-in as the owner serves every step that acts as the
1049
- * owner, and each step shows as one line.
1115
+ * owner, and each step shows as one line. Last, once the pull request is
1116
+ * open, it makes the agent's cloud signing key when the agent has none
1117
+ * (#417), a failure there only warning.
1050
1118
  */
1051
1119
  export async function onboard(sys, io, args = []) {
1052
1120
  const { named, features: chosen, add, yes, dryRun } = onboardArgs(args);
@@ -1369,14 +1437,26 @@ export async function onboard(sys, io, args = []) {
1369
1437
  }
1370
1438
  // The shared checks run only for features that need them.
1371
1439
  const workflowFrom = workflowPins(fileAt(WORKFLOW_PATH) ?? '')[0];
1440
+ const passed = { figma: on('figma'), board: on('board') };
1372
1441
  const workflowFor = (branch) => {
1373
- const update = workflowUpdate(fileAt(WORKFLOW_PATH), branch, version, on('figma'), schedule);
1442
+ const update = workflowUpdate(fileAt(WORKFLOW_PATH), branch, version, passed.figma, schedule, SETTINGS_PATH, passed.board);
1374
1443
  if (update.kind !== 'same')
1375
- change(WORKFLOW_PATH, update.text, workflowWhat(update, version, on('figma'), SETTINGS_PATH));
1444
+ change(WORKFLOW_PATH, update.text, workflowWhat(update, version, passed, SETTINGS_PATH));
1376
1445
  };
1446
+ // The Slice started job's board token comes from the board app's secrets, which only the owner can make (P-70).
1447
+ // A personal repository's checks skip the work rules, so it needs none.
1448
+ if (workflowNeeded && passed.board && (await byOrganisation())) {
1449
+ const names = await secretNames(sys, slug, token);
1450
+ const missing = BOARD_SECRETS.filter((name) => !names?.includes(name));
1451
+ if (missing.length > 0) {
1452
+ const steps = boardAppSteps(slug, missing, names === undefined);
1453
+ byHand.push(steps);
1454
+ later.push(steps);
1455
+ }
1456
+ }
1377
1457
  if (workflowNeeded) {
1378
- const update = planned === undefined ? undefined : workflowUpdate(fileAt(WORKFLOW_PATH), planned, version, on('figma'), schedule);
1379
- const detail = update === undefined ? (fileAt(WORKFLOW_PATH) === undefined ? 'new' : 'write or update') : update.kind === 'same' ? undefined : workflowDetail(update, version, on('figma'));
1458
+ const update = planned === undefined ? undefined : workflowUpdate(fileAt(WORKFLOW_PATH), planned, version, passed.figma, schedule, SETTINGS_PATH, passed.board);
1459
+ const detail = update === undefined ? (fileAt(WORKFLOW_PATH) === undefined ? 'new' : 'write or update') : update.kind === 'same' ? undefined : workflowDetail(update, version, passed);
1380
1460
  if (detail !== undefined)
1381
1461
  pull.push({ label: 'workflow', detail });
1382
1462
  }
@@ -1481,6 +1561,26 @@ export async function onboard(sys, io, args = []) {
1481
1561
  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}`);
1482
1562
  }
1483
1563
  }
1564
+ // The agent's cloud signing key (#417) is the agent's, not the repository's: one line serves every cloud
1565
+ // environment it works in, so onboard makes one only when the agent's own list holds none, and the second repo
1566
+ // onboarded leaves it alone. Where cloud-key would refuse, the owner runs it instead.
1567
+ const keyByHand = `Once for ${agent}: in your own terminal on your Mac, run niyam cloud-key ${agent}, and paste the line it puts on the clipboard into each Claude cloud environment's variables.`;
1568
+ const cloudKeys = await listedKeys(sys, agent, token).catch((error) => {
1569
+ // fail-open: a list GitHub does not give is warned about below and makes no key.
1570
+ return { problem: detail(error) };
1571
+ });
1572
+ let makeKey = false;
1573
+ // A list GitHub does not give makes no key, which could be a second one: the warning says how to check.
1574
+ if ('problem' in cloudKeys)
1575
+ warnings.push(`cloud signing key not checked (${cloudKeys.problem}); niyam cloud-key ${agent} makes one`);
1576
+ else if (!cloudKeys.keys.some((one) => one.title === CLOUD_KEY_TITLE)) {
1577
+ if (dryRun || cloudKeyRefusal(sys) !== undefined)
1578
+ byHand.push(keyByHand);
1579
+ else {
1580
+ cloud.push({ label: 'signing key', detail: `for ${agent}, on the clipboard` });
1581
+ makeKey = true;
1582
+ }
1583
+ }
1484
1584
  let pullUrl;
1485
1585
  // Whether the pull request merges itself once its checks pass.
1486
1586
  let merging = false;
@@ -1576,12 +1676,36 @@ export async function onboard(sys, io, args = []) {
1576
1676
  if (log.length > 0)
1577
1677
  notes.push(`- ${step.label}:`, ...log.map((line) => ` - ${line.trim().replace(/^[✓-] /, '')}`));
1578
1678
  }
1679
+ // Last, once the pull request is open: a key that fails only warns, and nothing before it is undone.
1680
+ // A Ctrl-C that stops the key ends the run as one does.
1681
+ let exitCode = 0;
1682
+ if (makeKey) {
1683
+ let made = false;
1684
+ try {
1685
+ ({ ok: made } = await runStep(sys, io, paint, `cloud signing key for ${agent}`, async (out) => {
1686
+ const code = await makeCloudKey(sys, out, agent, token);
1687
+ if (code === 130)
1688
+ exitCode = 130;
1689
+ return code === 0;
1690
+ }));
1691
+ }
1692
+ catch (error) {
1693
+ // fail-open: the pull request is open and every step before stands; the key's failure is said and left by hand below.
1694
+ io.err(`onboard: ${detail(error)}`);
1695
+ }
1696
+ if (made)
1697
+ byHand.unshift(`Now: ${SIGNING_KEY_VAR}=… is on the clipboard. ${pasteLines(agent, "each Claude cloud environment's").join(' ')}`);
1698
+ else {
1699
+ io.err(`onboard: ${agent} has no cloud signing key yet; everything before it is done`);
1700
+ byHand.push(keyByHand);
1701
+ }
1702
+ }
1579
1703
  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}`}`));
1580
1704
  io.out('');
1581
1705
  io.out('By hand:');
1582
1706
  for (const line of byHand)
1583
1707
  io.out(` ${line}`);
1584
- return 0;
1708
+ return exitCode;
1585
1709
  }
1586
1710
  /** How many times onboard asks GitHub about the test commit, waiting a little longer each time. */
1587
1711
  export const COMMIT_ATTEMPTS = 5;
@@ -12,6 +12,7 @@ const DEFAULTS = {
12
12
  skip: ['mergify/', 'gh-readonly-queue/'],
13
13
  optOut: [],
14
14
  describe: '`gh pr edit --body-file`',
15
+ autofixList: false,
15
16
  };
16
17
  const where = `${SETTINGS_PATH} "prAutocreate"`;
17
18
  const BRANCH = /^(?!\/)(?!.*\/\/)(?!.*\.\.)[\w.\/+-]+$/;
@@ -35,17 +36,20 @@ export function autocreateSettings(raw) {
35
36
  return { ...DEFAULTS };
36
37
  if (typeof value !== 'object' || value === null || Array.isArray(value))
37
38
  throw new Error(`${where} must be an object`);
38
- const { base = DEFAULTS.base, draft = DEFAULTS.draft, protected: guarded = DEFAULTS.protected, skip = DEFAULTS.skip, optOut = DEFAULTS.optOut, describe, retired, retire, footer, ...rest } = value;
39
+ const { base = DEFAULTS.base, draft = DEFAULTS.draft, protected: guarded = DEFAULTS.protected, skip = DEFAULTS.skip, optOut = DEFAULTS.optOut, describe, retired, retire, footer, autofixList = DEFAULTS.autofixList, ...rest } = value;
39
40
  const extra = Object.keys(rest)[0];
40
41
  if (extra !== undefined)
41
- throw new Error(`${where} has an unknown key "${extra}"; it takes "base", "draft", "protected", "skip", "optOut", "describe", "retired", "retire" and "footer"`);
42
+ throw new Error(`${where} has an unknown key "${extra}"; it takes "base", "draft", "protected", "skip", "optOut", "describe", "retired", "retire", "footer" and "autofixList"`);
42
43
  if (typeof base !== 'string' || !BRANCH.test(base))
43
44
  throw new Error(`${where}.base must be a branch name`);
44
45
  if (typeof draft !== 'boolean')
45
46
  throw new Error(`${where}.draft must be true or false`);
47
+ if (typeof autofixList !== 'boolean')
48
+ throw new Error(`${where}.autofixList must be true or false`);
46
49
  const settings = {
47
50
  base,
48
51
  draft,
52
+ autofixList,
49
53
  protected: strings(guarded, 'protected', (item) => BRANCH.test(item)),
50
54
  skip: strings(skip, 'skip', (item) => item.length > 0 && BRANCH.test(item)),
51
55
  optOut: strings(optOut, 'optOut', (item) => ENV_NAME.test(item)),
@@ -499,29 +503,97 @@ export function pushTarget(command, cwd, home) {
499
503
  }
500
504
  return undefined;
501
505
  }
502
- /** The instruction a session in the desktop app gets: switch Autofix on for the pull request. */
503
- export function reminder(pr, opened, created, cloud) {
506
+ /**
507
+ * The instruction a session in the desktop app gets: switch Autofix on for the pull request. `listed`: the pull
508
+ * request is on the session's sarathi Auto-fix list and the repository says sarathi warns from it, so the
509
+ * `set_monitor` step is sarathi's and left out here. The tag and `bind_pr` stay: without them the app refuses
510
+ * `set_monitor` for a pull request a hook opened, and sarathi goes quiet once it records the refusal.
511
+ */
512
+ export function reminder(pr, opened, created, cloud, listed = false) {
504
513
  if (cloud) {
505
514
  return `PR #${pr.number} (${pr.url}) ${opened}\nThis cloud session has no Autofix: CI, conflicts and review comments reach no one until a session reads them (gh api; GraphQL is refused here).`;
506
515
  }
507
516
  // The tag claims the session opened the pull request, so one merely found
508
517
  // on the branch gets it only when the session knows it ran that create.
509
518
  const claim = created ? 'Write' : 'Only if this session itself ran the `gh pr create` that opened this PR (in a background command, say), write';
510
- return (`PR #${pr.number} (${pr.url}) ${opened}\n` +
511
- 'Standing instruction from the user: Autofix must be ON for every PR a session pushes. Do this now, before anything else:\n' +
512
- '1. If mcp__ccd_pr__get_status is not yet a callable tool, it may only be deferred: run ToolSearch with query "select:mcp__ccd_pr__get_status,mcp__ccd_pr__bind_pr,mcp__ccd_pr__set_monitor" to load its schema before concluding it is unavailable.\n' +
519
+ const steps = '1. If mcp__ccd_pr__get_status is not yet a callable tool, it may only be deferred: run ToolSearch with query "select:mcp__ccd_pr__get_status,mcp__ccd_pr__bind_pr,mcp__ccd_pr__set_monitor" to load its schema before concluding it is unavailable.\n' +
513
520
  `2. ${claim} this line in your reply text, exactly: <pr-created>${pr.url}</pr-created>\n` +
514
521
  'The app lets a session turn Autofix on only for a PR it is sure the session opened, and it learns that only from a FOREGROUND `gh pr create` result or this tag; a PR opened by this hook or inside a background command has neither. Never write the tag for a PR this session did not open.\n' +
515
- `3. Call mcp__ccd_pr__get_status. If it reports no bound PR, call mcp__ccd_pr__bind_pr with url ${pr.url}.\n` +
522
+ `3. Call mcp__ccd_pr__get_status. If it reports no bound PR, call mcp__ccd_pr__bind_pr with url ${pr.url}.\n`;
523
+ const why = "tell the user in one line that Autofix could not be enabled and why, quoting the app's reason (the tag counts only within 15 minutes of the PR's creation, from the PR's own branch, and when the app's gh login authored it) — never fail silently and leave it off unreported.";
524
+ if (listed) {
525
+ return (`PR #${pr.number} (${pr.url}) ${opened}\n` +
526
+ "Standing instruction from the user: Autofix must be ON for every PR a session pushes. This PR is on this session's sarathi Auto-fix list, and sarathi's warning gives the mcp__ccd_pr__set_monitor call that switches it on. Do this now, before anything else, so that call is not refused:\n" +
527
+ steps +
528
+ `If ToolSearch cannot find mcp__ccd_pr__* at all (truly not the desktop app), or get_status/bind_pr still fails, ${why}`);
529
+ }
530
+ return (`PR #${pr.number} (${pr.url}) ${opened}\n` +
531
+ 'Standing instruction from the user: Autofix must be ON for every PR a session pushes. Do this now, before anything else:\n' +
532
+ steps +
516
533
  `4. If auto_fix is not true, call mcp__ccd_pr__set_monitor with {"auto_fix": true, "address_comments": true, "url": "${pr.url}"}. If it says the app is not sure this session opened the PR, or has not read it yet, call get_status once more and retry set_monitor once.\n` +
517
- "If ToolSearch cannot find mcp__ccd_pr__* at all (truly not the desktop app), or get_status/bind_pr/set_monitor still fails, tell the user in one line that Autofix could not be enabled and why, quoting the app's reason (the tag counts only within 15 minutes of the PR's creation, from the PR's own branch, and when the app's gh login authored it) — never fail silently and leave it off unreported.");
534
+ `If ToolSearch cannot find mcp__ccd_pr__* at all (truly not the desktop app), or get_status/bind_pr/set_monitor still fails, ${why}`);
535
+ }
536
+ /** A Claude session id sarathi lets name a list file (its `SESSION`). */
537
+ const SARATHI_SESSION = /^[\w.-]{1,128}$/;
538
+ const NAME = /^[\w.-]+$/;
539
+ export const AUTOFIX_SOURCE = 'niyam pr-autocreate';
540
+ /** owner/repo#N and the bare URL of https://<host>/<owner>/<repo>/pull/<N>, as sarathi's `fromUrl` reads one. */
541
+ function pullOf(url) {
542
+ let parsed;
543
+ try {
544
+ parsed = new URL(url);
545
+ }
546
+ catch {
547
+ // fail-open: what is not a URL names no pull request, and the whole instruction goes out
548
+ return undefined;
549
+ }
550
+ const [, owner = '', repo = '', kind, number = ''] = parsed.pathname.split('/');
551
+ if (parsed.protocol !== 'https:' || kind !== 'pull' || !NAME.test(owner) || !NAME.test(repo) || !/^\d+$/.test(number))
552
+ return undefined;
553
+ return { pr: `${owner}/${repo}#${number}`, url: `https://${parsed.host}/${owner}/${repo}/pull/${number}` };
554
+ }
555
+ /** sarathi's Auto-fix list folder: SARATHI_AUTOFIX_DIR, else $XDG_STATE_HOME/sarathi/autofix, else ~/.local/state/sarathi/autofix. */
556
+ export function autofixDir(sys) {
557
+ const override = sys.env.SARATHI_AUTOFIX_DIR;
558
+ if (override)
559
+ return override;
560
+ const state = sys.env.XDG_STATE_HOME;
561
+ return resolve(state || resolve(sys.home, '.local', 'state'), 'sarathi', 'autofix');
562
+ }
563
+ /**
564
+ * Puts the pull request on the session's sarathi Auto-fix list (sarathi
565
+ * 0.6.15's `<dir>/<session id>.jsonl`, one JSON row per fact), as `sarathi
566
+ * autofix add` does: an `opened` row, unless the list names it already, so a
567
+ * Stop after every turn adds no more. True once it is on the list; false when
568
+ * the session id cannot name a list or the row could not be written.
569
+ */
570
+ export function listForAutofix(sys, session, url) {
571
+ const pull = pullOf(url);
572
+ if (!session || !SARATHI_SESSION.test(session) || !pull)
573
+ return false;
574
+ const file = resolve(autofixDir(sys), `${session}.jsonl`);
575
+ // sarathi writes its rows with JSON.stringify, so a row for the pull request holds this text; sarathi folds two
576
+ // spellings of one together by lower case. A row this misses only adds an `opened` row sarathi ignores.
577
+ const named = JSON.stringify({ pr: pull.pr }).slice(1, -1).toLowerCase();
578
+ try {
579
+ if (sys.exists(file) && sys.read(file).toLowerCase().includes(named))
580
+ return true;
581
+ sys.mkdir(dirname(file));
582
+ // The leading newline ends a partial row a short append left, as sarathi's appendRows does.
583
+ sys.append(file, `\n${JSON.stringify({ at: sys.now().toISOString(), ...pull, event: 'opened', source: AUTOFIX_SOURCE })}\n`);
584
+ return true;
585
+ }
586
+ catch {
587
+ // fail-open: a list that cannot be read or written leaves the pull request off it, and the whole instruction goes out
588
+ return false;
589
+ }
518
590
  }
519
591
  /** How the session replaces the placeholder body. */
520
592
  function editHint(settings, pulls, number) {
521
593
  return pulls.cloud ? `gh api -X PATCH repos/${pulls.slug}/pulls/${number} -F body=@FILE` : settings.describe;
522
594
  }
523
595
  /** The instruction for the record's open pull request, once per session and pull request; empty when there is nothing to say. */
524
- async function autofixMessage(sys, root, settings, state, session, pulls) {
596
+ async function autofixMessage(sys, root, settings, state, session, pulls, listed) {
525
597
  const pr = state.pr;
526
598
  if (!pr || pr.state !== 'OPEN' || !pr.url)
527
599
  return '';
@@ -547,7 +619,7 @@ async function autofixMessage(sys, root, settings, state, session, pulls) {
547
619
  else if (body.includes(MARKER))
548
620
  opened += ` Its body is still the automatic placeholder: ${replace}`;
549
621
  }
550
- return reminder(pr, opened, state.created, pulls.cloud);
622
+ return reminder(pr, opened, state.created, pulls.cloud, listed && settings.autofixList);
551
623
  }
552
624
  /**
553
625
  * The transport with the token GitHub is asked with: a session's hook acts
@@ -672,7 +744,10 @@ export async function claudeHook(sys, io, stdin, pullsOf = pullsFor) {
672
744
  }
673
745
  if ('problem' in state)
674
746
  return bail(state.problem);
675
- let message = await autofixMessage(sys, root, settings, state, session, pulls);
747
+ // On the session's sarathi Auto-fix list, every time and before the once-only instruction, so a pull request
748
+ // told about before this release joins it too. A cloud session has no set_monitor, and sarathi is quiet there.
749
+ const listed = !pulls.cloud && state.pr?.state === 'OPEN' && Boolean(state.pr.url) && listForAutofix(sys, session, state.pr.url);
750
+ let message = await autofixMessage(sys, root, settings, state, session, pulls, listed);
676
751
  if (typeof message !== 'string')
677
752
  return bail(message.problem);
678
753
  if (!message && state.notes.length > 0 && event === 'PostToolUse') {
package/dist/run.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { homedir } from 'node:os';
2
2
  import { LOCKED, asAgent, asAgentArgs } from './as-agent.js';
3
+ import { auditArgs, boardAudit } from './board-audit.js';
3
4
  import { cloudSetup } from './cloud.js';
5
+ import { cloudKey, cloudKeyArgs } from './cloud-key.js';
4
6
  import { needsOwner } from './asks.js';
5
7
  import { decisionsWeekly } from './decisions.js';
6
8
  import { prDesign } from './design.js';
@@ -24,7 +26,7 @@ import { onboard, onboardArgs } from './onboard.js';
24
26
  import { ownerStep, ownerStepArgs } from './owner-step.js';
25
27
  import { sessionStart } from './session-start.js';
26
28
  import { upgrade } from './upgrade.js';
27
- import { prMerged, prePush, prWorkRules, propose } from './work.js';
29
+ import { prMerged, prStarted, prePush, prWorkRules, propose } from './work.js';
28
30
  import { CLI } from './names.js';
29
31
  import { packageVersion } from './version.js';
30
32
  export { packageVersion, versionOf } from './version.js';
@@ -43,6 +45,9 @@ Commands:
43
45
  label <owner/repo> <number> <add|remove> <approved|do-not-merge>;
44
46
  required-checks <owner/repo> <ruleset id or name> [--check <name>]…
45
47
  cloud-setup Print an optional Setup snippet that makes Claude cloud sessions start faster
48
+ cloud-key [agent] [--yes]
49
+ In your own terminal: a new signing key for the agent's Claude cloud sessions, registered
50
+ as the agent, and NIYAM_SIGNING_KEY=… on the clipboard for the cloud environment's variables
46
51
  env [-- <command> [args...]]
47
52
  For agents run from any tool: the GitHub lock, then the agent identity where this Mac
48
53
  has it, as shell lines for eval "$(niyam env)", or with -- the command run under them
@@ -53,6 +58,7 @@ Commands:
53
58
  pr-identity Run by the shared workflow: agent commits Verified and pushed by the agent
54
59
  pr-work-rules Run by the shared workflow: an agent pull request builds one slice it may build
55
60
  pr-merged Run by the shared workflow: a merged pull request closes the slice and States it names
61
+ pr-started Run by the shared workflow: an opened pull request moves its slice to In Progress on the board
56
62
  pr-design Run by the shared workflow: each state of the slice links a frame from the design library
57
63
  decisions-weekly Run by the shared workflow weekly: decision checks, undo issues, expiring labels
58
64
  needs-owner Run by the shared workflow: an ask labels its issue needs-owner; the owner's answer takes it off
@@ -100,6 +106,10 @@ Commands:
100
106
  work-item-number [--issue <N>] [--apply]
101
107
  Run by a client's workflow on issue events: a Work item whose number something else
102
108
  holds is renumbered, with a comment; --apply writes
109
+ board-audit [owner/repo] [--project <title>]
110
+ Read only: the open issues not on the work board, items whose Status disagrees with
111
+ their issue, and whether the auto-add workflows are on; exit 3 when something is to fix.
112
+ Needs GH_TOKEN; cannot run in a Claude cloud session, whose proxy refuses Projects
103
113
  help Show this text
104
114
  version Print the installed version
105
115
 
@@ -141,17 +151,17 @@ export function proposeArgs(args) {
141
151
  /** Runs one command and returns its exit code: 0 done, 1 failed, 2 bad usage. */
142
152
  export async function run(args, io, sys) {
143
153
  const [command, ...rest] = args;
144
- 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' || command === 'doc-number' || command === 'renumber-doc' || command === 'work-item-number' ? Infinity : command === 'pre-push' || command === 'pr-signals' ? 2 : command === 'doctor' ? 1 : 0;
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;
145
155
  const extra = rest[allowed];
146
156
  if (extra !== undefined) {
147
157
  io.err(`niyam: unexpected argument "${extra}"`);
148
158
  io.err(USAGE);
149
159
  return 2;
150
160
  }
151
- 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' || command === 'doc-number' || command === 'renumber-doc' || command === 'work-item-number') {
161
+ if (command === 'onboard' || command === 'machine' || command === 'cloud-key' || command === 'review-thread' || command === 'as-agent' || command === 'env' || command === 'propose' || command === 'owner-step' || command === 'pr-signals' || command === 'handoff' || command === 'brief' || command === 'cubic-dismiss' || command === 'doc-number' || command === 'renumber-doc' || command === 'work-item-number' || command === 'board-audit') {
152
162
  // Their options are checked here, so a bad one is bad usage (exit 2).
153
163
  try {
154
- (command === 'doc-number' ? docNumberArgs : command === 'renumber-doc' ? renumberArgs : command === 'work-item-number' ? workItemArgs : 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);
164
+ (command === 'board-audit' ? auditArgs : command === 'cloud-key' ? cloudKeyArgs : command === 'doc-number' ? docNumberArgs : command === 'renumber-doc' ? renumberArgs : command === 'work-item-number' ? workItemArgs : 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);
155
165
  }
156
166
  catch (error) {
157
167
  io.err(`niyam: ${error instanceof Error ? error.message : String(error)}`);
@@ -227,11 +237,13 @@ export async function run(args, io, sys) {
227
237
  }
228
238
  }
229
239
  case 'machine':
240
+ case 'cloud-key':
230
241
  case 'doctor':
231
242
  case 'onboard':
232
243
  case 'pr-identity':
233
244
  case 'pr-work-rules':
234
245
  case 'pr-merged':
246
+ case 'pr-started':
235
247
  case 'pr-design':
236
248
  case 'decisions-weekly':
237
249
  case 'needs-owner':
@@ -249,7 +261,10 @@ export async function run(args, io, sys) {
249
261
  case 'doc-number':
250
262
  case 'renumber-doc':
251
263
  case 'work-item-number':
264
+ case 'board-audit':
252
265
  try {
266
+ if (command === 'board-audit')
267
+ return await boardAudit(await sys(), io, rest);
253
268
  if (command === 'doc-number')
254
269
  return docNumber(await sys(), io, rest);
255
270
  if (command === 'renumber-doc')
@@ -290,6 +305,8 @@ export async function run(args, io, sys) {
290
305
  return await prWorkRules(await sys(), io);
291
306
  if (command === 'pr-merged')
292
307
  return await prMerged(await sys(), io);
308
+ if (command === 'pr-started')
309
+ return await prStarted(await sys(), io);
293
310
  if (command === 'pre-push') {
294
311
  const real = await sys();
295
312
  return await prePush(real, io, real.readStdin(), rest[1] ?? '');
@@ -298,6 +315,8 @@ export async function run(args, io, sys) {
298
315
  return await onboard(await sys(), io, rest);
299
316
  if (command === 'machine')
300
317
  return await machine(await sys(), io, rest);
318
+ if (command === 'cloud-key')
319
+ return await cloudKey(await sys(), io, rest);
301
320
  return await doctor(await sys(), io, rest[0]);
302
321
  }
303
322
  catch (error) {
package/dist/secrets.js CHANGED
@@ -1,4 +1,25 @@
1
1
  import { API } from './agent.js';
2
+ /**
3
+ * The names of the Actions secrets `slug`'s workflows can read, its own and
4
+ * its organization's shared with it, as the account `token` sees them; never
5
+ * a value, which GitHub does not list. Undefined when GitHub will not list
6
+ * either, so a caller can tell "not set" from "cannot tell".
7
+ */
8
+ export async function secretNames(sys, slug, token) {
9
+ const names = [];
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
+ }
20
+ }
21
+ return names;
22
+ }
2
23
  /**
3
24
  * Sets the Actions secret `name` of `slug` to `value`, as the account `token`
4
25
  * is: GitHub takes a secret only sealed with the repository's Actions public