@veda-hq/niyam 0.6.21 → 0.6.23

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/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';
@@ -12,6 +14,9 @@ import { prIdentity } from './identity.js';
12
14
  import { machine, machineArgs } from './machine.js';
13
15
  import { brief, briefArgs, handoff, handoffArgs } from './handoff.js';
14
16
  import { cubicDismiss, dismissArgs } from './cubic-dismiss.js';
17
+ import { docNumber, docNumberArgs } from './doc-numbers.js';
18
+ import { renumberArgs, renumberDoc } from './renumber-doc.js';
19
+ import { workItemArgs, workItemNumber } from './work-item-number.js';
15
20
  import { keepGoing } from './keep-going.js';
16
21
  import { prAutocreate } from './pr-autocreate.js';
17
22
  import { prSignals, signalArgs } from './pr-signals.js';
@@ -21,7 +26,7 @@ import { onboard, onboardArgs } from './onboard.js';
21
26
  import { ownerStep, ownerStepArgs } from './owner-step.js';
22
27
  import { sessionStart } from './session-start.js';
23
28
  import { upgrade } from './upgrade.js';
24
- import { prMerged, prePush, prWorkRules, propose } from './work.js';
29
+ import { prMerged, prStarted, prePush, prWorkRules, propose } from './work.js';
25
30
  import { CLI } from './names.js';
26
31
  import { packageVersion } from './version.js';
27
32
  export { packageVersion, versionOf } from './version.js';
@@ -40,6 +45,9 @@ Commands:
40
45
  label <owner/repo> <number> <add|remove> <approved|do-not-merge>;
41
46
  required-checks <owner/repo> <ruleset id or name> [--check <name>]…
42
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
43
51
  env [-- <command> [args...]]
44
52
  For agents run from any tool: the GitHub lock, then the agent identity where this Mac
45
53
  has it, as shell lines for eval "$(niyam env)", or with -- the command run under them
@@ -50,6 +58,7 @@ Commands:
50
58
  pr-identity Run by the shared workflow: agent commits Verified and pushed by the agent
51
59
  pr-work-rules Run by the shared workflow: an agent pull request builds one slice it may build
52
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
53
62
  pr-design Run by the shared workflow: each state of the slice links a frame from the design library
54
63
  decisions-weekly Run by the shared workflow weekly: decision checks, undo issues, expiring labels
55
64
  needs-owner Run by the shared workflow: an ask labels its issue needs-owner; the owner's answer takes it off
@@ -87,6 +96,20 @@ Commands:
87
96
  Claude Code's Stop hook: sends a session back while its branch has commits the base
88
97
  lacks and its pull request has not merged, saying what is left ("1 of 5"); --stop
89
98
  records why started work stops at this commit. The hook always exits 0
99
+ doc-number <kind> [--reserve] [--json] [--offline]
100
+ The next free number of a numbered document kind (adr), against main, this tree, every
101
+ ref, open pull requests and Work item titles; --reserve claims it for good, and refuses
102
+ when GitHub could not be read. The kinds are .github/niyam.json's "docNumbers"
103
+ renumber-doc <kind> <from> <to> [--apply]
104
+ Move a numbered document to a free number with every citation, path and relationship
105
+ that names it; a dry run unless --apply
106
+ work-item-number [--issue <N>] [--apply]
107
+ Run by a client's workflow on issue events: a Work item whose number something else
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
90
113
  help Show this text
91
114
  version Print the installed version
92
115
 
@@ -128,17 +151,17 @@ export function proposeArgs(args) {
128
151
  /** Runs one command and returns its exit code: 0 done, 1 failed, 2 bad usage. */
129
152
  export async function run(args, io, sys) {
130
153
  const [command, ...rest] = args;
131
- const allowed = command === 'onboard' || command === 'machine' || command === 'review-thread' || command === 'as-agent' || command === 'env' || command === 'propose' || command === 'owner-step' || command === 'handoff' || command === 'brief' || command === 'cubic-dismiss' || command === 'pr-autocreate' || command === 'keep-going' ? Infinity : command === 'pre-push' || command === 'pr-signals' ? 2 : command === 'doctor' ? 1 : 0;
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;
132
155
  const extra = rest[allowed];
133
156
  if (extra !== undefined) {
134
157
  io.err(`niyam: unexpected argument "${extra}"`);
135
158
  io.err(USAGE);
136
159
  return 2;
137
160
  }
138
- if (command === 'onboard' || command === 'machine' || command === 'review-thread' || command === 'as-agent' || command === 'env' || command === 'propose' || command === 'owner-step' || command === 'pr-signals' || command === 'handoff' || command === 'brief' || command === 'cubic-dismiss') {
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') {
139
162
  // Their options are checked here, so a bad one is bad usage (exit 2).
140
163
  try {
141
- (command === 'onboard' ? onboardArgs : command === 'machine' ? machineArgs : command === 'as-agent' ? asAgentArgs : command === 'env' ? envArgs : command === 'propose' ? proposeArgs : command === 'owner-step' ? ownerStepArgs : command === 'pr-signals' ? signalArgs : command === 'handoff' ? handoffArgs : command === 'brief' ? briefArgs : command === 'cubic-dismiss' ? dismissArgs : threadArgs)(rest);
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);
142
165
  }
143
166
  catch (error) {
144
167
  io.err(`niyam: ${error instanceof Error ? error.message : String(error)}`);
@@ -214,11 +237,13 @@ export async function run(args, io, sys) {
214
237
  }
215
238
  }
216
239
  case 'machine':
240
+ case 'cloud-key':
217
241
  case 'doctor':
218
242
  case 'onboard':
219
243
  case 'pr-identity':
220
244
  case 'pr-work-rules':
221
245
  case 'pr-merged':
246
+ case 'pr-started':
222
247
  case 'pr-design':
223
248
  case 'decisions-weekly':
224
249
  case 'needs-owner':
@@ -233,7 +258,19 @@ export async function run(args, io, sys) {
233
258
  case 'cubic-dismiss':
234
259
  case 'upgrade':
235
260
  case 'owner-step':
261
+ case 'doc-number':
262
+ case 'renumber-doc':
263
+ case 'work-item-number':
264
+ case 'board-audit':
236
265
  try {
266
+ if (command === 'board-audit')
267
+ return await boardAudit(await sys(), io, rest);
268
+ if (command === 'doc-number')
269
+ return docNumber(await sys(), io, rest);
270
+ if (command === 'renumber-doc')
271
+ return renumberDoc(await sys(), io, rest);
272
+ if (command === 'work-item-number')
273
+ return workItemNumber(await sys(), io, rest);
237
274
  if (command === 'upgrade')
238
275
  return await upgrade(await sys(), io);
239
276
  if (command === 'pr-signals')
@@ -268,6 +305,8 @@ export async function run(args, io, sys) {
268
305
  return await prWorkRules(await sys(), io);
269
306
  if (command === 'pr-merged')
270
307
  return await prMerged(await sys(), io);
308
+ if (command === 'pr-started')
309
+ return await prStarted(await sys(), io);
271
310
  if (command === 'pre-push') {
272
311
  const real = await sys();
273
312
  return await prePush(real, io, real.readStdin(), rest[1] ?? '');
@@ -276,6 +315,8 @@ export async function run(args, io, sys) {
276
315
  return await onboard(await sys(), io, rest);
277
316
  if (command === 'machine')
278
317
  return await machine(await sys(), io, rest);
318
+ if (command === 'cloud-key')
319
+ return await cloudKey(await sys(), io, rest);
279
320
  return await doctor(await sys(), io, rest[0]);
280
321
  }
281
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
@@ -1,6 +1,6 @@
1
- import { BASE_ENV, agentHere, anyLogin, either, loadSettings, lockScript, sameLogin, pathsFor, sessionNames, sessionRecord, sessionFileIs, } from './agent.js';
1
+ import { BASE_ENV, agentHere, exportLines, anyLogin, either, loadSettings, lockScript, sameLogin, pathsFor, sessionNames, sessionRecord, sessionFileIs, } from './agent.js';
2
2
  import { AGENT_VAR } from './names.js';
3
- import { cloudLogin, cloudToken, ranFromSetup, repoReleases } from './cloud.js';
3
+ import { SIGNING_KEY_VAR, cloudLogin, cloudSigning, cloudToken, ranFromSetup, repoReleases } from './cloud.js';
4
4
  import { CLOUD_SETUP_PATH } from './onboard-pull.js';
5
5
  import { PRE_PUSH_HOOK, prePushHook } from './onboard.js';
6
6
  import { packageVersion } from './version.js';
@@ -117,7 +117,9 @@ function recordFor(sys) {
117
117
  * identity is the account claude.ai's GitHub connection uses, which GitHub
118
118
  * names through the session's proxy. When that is the agent, the lock the
119
119
  * settings' `env` gave the session is lifted, so gh and git reach GitHub
120
- * through the proxy, and the session is marked as the agent's for the guard
120
+ * through the proxy, the agent becomes the author, committer and signer of
121
+ * its commits when the environment holds its cloud signing key
122
+ * (`cloudCommits`), and the session is marked as the agent's for the guard
121
123
  * and the pre-push hook, which it writes, since a cloud clone has none of
122
124
  * the owner's. Otherwise GitHub stays locked out and the session is told to
123
125
  * stop: it would act as someone else.
@@ -171,7 +173,32 @@ async function cloudStart(sys) {
171
173
  : hook.state === 'outside'
172
174
  ? ` Its pre-push hook ${hook.path} is outside the repository and was not checked, so only the pull request's checks may hold the work rules.`
173
175
  : '';
174
- return { line: `niyam: this cloud session works as ${asked.login} on GitHub.${unchecked}`, agent: asked.login };
176
+ const signed = await cloudCommits(sys, root, envFile, asked);
177
+ return { line: `niyam: this cloud session works as ${asked.login} on GitHub.${unchecked}${signed}`, agent: asked.login };
178
+ }
179
+ /**
180
+ * Makes the agent the author, committer and signer of a cloud session's
181
+ * commits, as a local session's file does, over the cloud image's own
182
+ * identity, Claude's: `cloudSigning`'s variables, appended to CLAUDE_ENV_FILE
183
+ * after the lock is lifted, which reaches every command Claude Code runs and
184
+ * leaves the clone's git config alone. The key's variable is unset there, so
185
+ * commands do not carry it in their environment. A warning only, said after
186
+ * the line: when any of it fails, the session works on as the agent and its
187
+ * commits keep the image's identity, which PR identity passes.
188
+ */
189
+ async function cloudCommits(sys, root, envFile, asked) {
190
+ const keeps = (why) => ` Its commits keep the cloud image's identity, Claude's: ${why}.`;
191
+ const signing = await cloudSigning(sys, root, asked.login, asked.id);
192
+ if ('problem' in signing)
193
+ return keeps(signing.problem);
194
+ try {
195
+ sys.append(envFile, `unset ${SIGNING_KEY_VAR}\n${exportLines(signing.vars).join('\n')}\n`);
196
+ }
197
+ catch (error) {
198
+ // fail-open: nothing of the signing reached the env file, so the session keeps the image's identity, and says why.
199
+ return keeps(`writing ${asked.login}'s signing to CLAUDE_ENV_FILE failed (${message(error)})`);
200
+ }
201
+ return ` Its commits are ${asked.login}'s, signed with ${SIGNING_KEY_VAR}.`;
175
202
  }
176
203
  function start(sys) {
177
204
  let local;
@@ -0,0 +1,262 @@
1
+ import { SETTINGS_PATH, repoAt } from './agent.js';
2
+ import { allocate, basenamesOnRef, detail, frozenEntries, ghIn, listWorkItems, loadDocSettings, numberFromFilename, numberFromName, numberFromWorkItemTitle, prClaimedNumbers, schema, wholeNumber, } from './doc-numbers.js';
3
+ const describe = (item) => `#${String(item.number)} (${item.title})`;
4
+ /** What outside the Work items holds `number` against `item`, or null. */
5
+ function externalHolder(settings, kind, item, number, s) {
6
+ const doc = s.mainNames.find((name) => numberFromFilename(name) === number);
7
+ if (doc !== undefined)
8
+ return `\`${kind.dir}/${doc}\` on main`;
9
+ if (s.prNumbers.has(number))
10
+ return `an open pull request's new ${kind.citation}-${number}`;
11
+ if (item.number <= (settings.workItems?.lastMovedIssue ?? 0))
12
+ return null;
13
+ const frozen = frozenEntries(settings, kind.kind).find((path) => numberFromName(path) === number);
14
+ return frozen === undefined ? null : `the frozen work folder \`${frozen}\``;
15
+ }
16
+ /** Which Work items must move, each with what holds its number. */
17
+ export function planMoves(settings, kind, sources, event) {
18
+ const moving = new Map();
19
+ const items = [...sources.items].sort((a, b) => a.number - b.number);
20
+ if (event !== null) {
21
+ const other = items.find((i) => i.workNumber === event.work && i.number !== event.item.number);
22
+ const holder = other === undefined ? externalHolder(settings, kind, event.item, event.work, sources) : describe(other);
23
+ if (holder !== null)
24
+ moving.set(event.item.number, { item: event.item, work: event.work, holder });
25
+ }
26
+ const keeper = new Map();
27
+ for (const item of items) {
28
+ const work = item.workNumber;
29
+ if (work === null || moving.has(item.number))
30
+ continue;
31
+ const first = keeper.get(work);
32
+ if (first === undefined)
33
+ keeper.set(work, item);
34
+ else
35
+ moving.set(item.number, { item, work, holder: describe(first) });
36
+ }
37
+ for (const [work, item] of keeper) {
38
+ const holder = externalHolder(settings, kind, item, work, sources);
39
+ if (holder !== null)
40
+ moving.set(item.number, { item, work, holder });
41
+ }
42
+ return moving;
43
+ }
44
+ /** The hidden line that tells a rerun this renumber is already explained. */
45
+ export function renumberMarker(from, to) {
46
+ return `<!-- work-item-number: renumbered from ${from} to ${to} -->`;
47
+ }
48
+ /** The comment a renumbered issue carries. */
49
+ export function renumberComment(work, from, to, holder) {
50
+ const reserve = work.reserveCommand ?? `niyam doc-number ${work.kind} --reserve`;
51
+ return [
52
+ `Renumbered from ${from} to ${to}: ${from} is already held by ${holder}. Numbers are identity and never reused.`,
53
+ '',
54
+ `A Work item takes its number from \`${reserve}\` before \`gh issue create\`. This one was filed without it, so the \`work-item-number\` check took the next free number from the same allocator.`,
55
+ renumberMarker(from, to),
56
+ ].join('\n');
57
+ }
58
+ /** One issue as `gh api …/issues/N --jq '{number, title, type: .type.name}'` gives it; `type` is null untyped. */
59
+ const IssueSchema = schema((value) => {
60
+ const { title, type } = (typeof value === 'object' && value !== null ? value : {});
61
+ if (typeof title !== 'string' || (type !== null && typeof type !== 'string'))
62
+ throw new Error('unexpected shape');
63
+ return { title, type };
64
+ });
65
+ /** The event's issue as a Work item, or why it needs nothing; throws when it cannot be read. */
66
+ function readEvent(work, gh, issue, previousTitle) {
67
+ const at = `#${String(issue)}`;
68
+ const raw = gh(['api', `repos/{owner}/{repo}/issues/${String(issue)}`, '--jq', '{number, title, type: .type.name}']);
69
+ let read;
70
+ try {
71
+ read = IssueSchema.parse(JSON.parse(raw));
72
+ }
73
+ catch (error) {
74
+ throw new Error(error instanceof SyntaxError ? `${at} came back as text that is not JSON` : `${at} came back in an unexpected shape`);
75
+ }
76
+ const { title, type } = read;
77
+ if (type !== work.issueType)
78
+ return `${at} is not a ${work.issueType}`;
79
+ const workNumber = numberFromWorkItemTitle(title);
80
+ if (workNumber === null)
81
+ return `${at}'s title carries no number`;
82
+ // A retitle that keeps the number took nothing new, so an earlier holder must not yield to it.
83
+ if (previousTitle !== undefined && numberFromWorkItemTitle(previousTitle) === workNumber)
84
+ return `${at} kept its number ${workNumber}`;
85
+ return { item: { number: issue, title, workNumber }, work: workNumber };
86
+ }
87
+ /**
88
+ * Comment, then retitle: a run that stops between them leaves the clash, so a rerun renumbers again and, finding the
89
+ * marker, does not comment twice. A title changed since the run listed it stops the renumber: that edit's own run
90
+ * checks it again.
91
+ */
92
+ function applyRenumber(work, gh, move, was) {
93
+ const issue = String(move.issue);
94
+ const unchanged = () => {
95
+ const now = gh(['api', `repos/{owner}/{repo}/issues/${issue}`, '--jq', '.title']).trimEnd();
96
+ if (now !== was)
97
+ throw new Error(`its title changed during the run, to "${now}"; that edit's own run checks it again`);
98
+ };
99
+ unchanged();
100
+ const comments = gh(['api', '--paginate', `repos/{owner}/{repo}/issues/${issue}/comments`, '--jq', '.[].body']);
101
+ if (!comments.includes(renumberMarker(move.from, move.to)))
102
+ gh(['issue', 'comment', issue, '--body', renumberComment(work, move.from, move.to, move.holder)]);
103
+ unchanged();
104
+ gh(['issue', 'edit', issue, '--title', move.title]);
105
+ }
106
+ /** Checks the event's issue and every Work item; with `apply`, renumbers each clash. An incomplete source is an error. */
107
+ export function checkWorkItemNumbers(sys, root, settings, gh, options = {}) {
108
+ const work = settings.workItems;
109
+ const kind = settings.kinds[work.kind];
110
+ const ref = options.ref ?? 'origin/main';
111
+ let event = null;
112
+ let note = null;
113
+ if (options.issue !== undefined) {
114
+ let read;
115
+ try {
116
+ read = readEvent(work, gh, options.issue, options.previousTitle);
117
+ }
118
+ catch (error) {
119
+ // fail-open: the failure is the return value, and the command exits 1 on it.
120
+ return { ok: false, error: `could not read #${String(options.issue)}: ${detail(error)}` };
121
+ }
122
+ if (typeof read === 'string')
123
+ note = read;
124
+ else
125
+ event = read;
126
+ }
127
+ const mainNames = basenamesOnRef(sys, kind, ref, root);
128
+ if (mainNames === null)
129
+ return { ok: false, error: `could not read \`${ref}\` — fetch it first` };
130
+ const listed = listWorkItems(work, gh);
131
+ const claims = prClaimedNumbers(kind, mainNames, gh);
132
+ const warnings = [...listed.warnings, ...claims.warnings];
133
+ if (warnings.length > 0)
134
+ return { ok: false, error: `sources incomplete: ${warnings.join('; ')}` };
135
+ const moving = planMoves(settings, kind, { items: listed.items, mainNames, prNumbers: claims.numbers }, event);
136
+ if (moving.size === 0)
137
+ return { ok: true, note, renumbers: [], applied: options.apply ?? false };
138
+ // A preview, not a reservation: a runner's reservation refs die with it. A number picked blind could clash again,
139
+ // so a warning is an error here. Every number above the allocator's answer is free, so the moves count up.
140
+ const next = options.allocate ? options.allocate() : allocate(sys, root, settings, kind, { ref, gh });
141
+ if (!next.ok)
142
+ return next;
143
+ if (next.warnings.length > 0)
144
+ return { ok: false, error: `allocator incomplete: ${next.warnings.join('; ')}` };
145
+ const first = /^\d{4}$/.test(next.next) ? wholeNumber(next.next) : Number.NaN;
146
+ if (!/^\d{4}$/.test(next.next) || first < 1 || first + moving.size > 10_000)
147
+ return { ok: false, error: `no room for ${String(moving.size)} number(s) from ${next.next}` };
148
+ const planned = [...moving.values()].map(({ item, work: from, holder }, index) => {
149
+ const to = String(first + index).padStart(4, '0');
150
+ return { move: { issue: item.number, from, to, holder, title: item.title.trimStart().replace(/^\d{4}/, to) }, was: item.title };
151
+ });
152
+ const renumbers = planned.map(({ move }) => move);
153
+ if (!options.apply)
154
+ return { ok: true, note, renumbers, applied: false };
155
+ for (const { move, was } of planned) {
156
+ try {
157
+ applyRenumber(work, gh, move, was);
158
+ }
159
+ catch (error) {
160
+ // fail-open: the failure is the return value, and the command exits 1 on it.
161
+ return { ok: false, error: `could not renumber #${String(move.issue)}: ${detail(error)}` };
162
+ }
163
+ }
164
+ return { ok: true, note, renumbers, applied: true };
165
+ }
166
+ /** Every Work item still without `label`, read before any write; a run that cannot read it changes nothing. */
167
+ export function unlabelledWorkItems(work, gh) {
168
+ const issues = [];
169
+ try {
170
+ const out = gh(['api', '--paginate', `repos/{owner}/{repo}/issues?state=all&type=${encodeURIComponent(work.issueType)}&per_page=100`, '--jq', `.[] | select(.type.name == ${JSON.stringify(work.issueType)}) | select(any(.labels[]; .name == ${JSON.stringify(work.label)}) | not) | .number`]);
171
+ for (const line of out.split('\n')) {
172
+ if (line === '')
173
+ continue;
174
+ if (!/^[1-9]\d{0,8}$/.test(line))
175
+ throw new Error(`unexpected issue number "${line}"`);
176
+ issues.push(wholeNumber(line));
177
+ }
178
+ }
179
+ catch (error) {
180
+ // fail-open: the failure is the return value, and the command exits 1 on it.
181
+ return { ok: false, error: `could not list unlabelled Work items: ${detail(error)}` };
182
+ }
183
+ return { ok: true, issues };
184
+ }
185
+ /** work-item-number's arguments: `--issue N` and `--apply`. */
186
+ export function workItemArgs(args) {
187
+ let issue;
188
+ let apply = false;
189
+ for (let i = 0; i < args.length; i++) {
190
+ const arg = args[i];
191
+ if (arg === '--apply')
192
+ apply = true;
193
+ else if (arg === '--issue' || arg.startsWith('--issue=')) {
194
+ const value = arg === '--issue' ? args[++i] : arg.slice('--issue='.length);
195
+ if (value === undefined || !/^[1-9]\d{0,7}$/.test(value))
196
+ throw new Error('work-item-number --issue needs an issue number');
197
+ if (issue !== undefined)
198
+ throw new Error('work-item-number takes one --issue');
199
+ issue = wholeNumber(value);
200
+ }
201
+ else
202
+ throw new Error(`work-item-number: unexpected argument "${arg}"`);
203
+ }
204
+ return { ...(issue === undefined ? {} : { issue }), apply };
205
+ }
206
+ /**
207
+ * `niyam work-item-number [--issue N] [--apply]`: a preview, or with --apply the renumbers and labels. A retitle's
208
+ * old title comes in WORK_ITEM_PREVIOUS_TITLE, never an argument: anyone filing an issue chooses it.
209
+ */
210
+ export function workItemNumber(sys, io, args) {
211
+ const parsed = workItemArgs(args);
212
+ const { root } = repoAt(sys);
213
+ const settings = loadDocSettings(sys, root);
214
+ const work = settings.workItems;
215
+ if (work === undefined) {
216
+ io.err(`niyam work-item-number: ${SETTINGS_PATH}'s "docNumbers" names no "workItems"`);
217
+ return 2;
218
+ }
219
+ const gh = ghIn(sys, root);
220
+ const label = work.label;
221
+ const unlabelled = label === undefined ? { ok: true, issues: [] } : unlabelledWorkItems({ ...work, label }, gh);
222
+ if (!unlabelled.ok) {
223
+ io.err(`❌ ${unlabelled.error}`);
224
+ return 1;
225
+ }
226
+ const previous = sys.env.WORK_ITEM_PREVIOUS_TITLE;
227
+ const result = checkWorkItemNumbers(sys, root, settings, gh, { apply: parsed.apply, ...(parsed.issue === undefined ? {} : { issue: parsed.issue }), ...(previous === undefined ? {} : { previousTitle: previous }) });
228
+ let code = 0;
229
+ if (result.ok) {
230
+ if (result.note !== null)
231
+ io.out(`✓ ${result.note}`);
232
+ if (result.renumbers.length === 0)
233
+ io.out('✓ no Work item shares a number');
234
+ const verb = result.applied ? '✓ renumbered' : '→ would renumber';
235
+ for (const move of result.renumbers)
236
+ io.out(`${verb} #${String(move.issue)} from ${move.from} to ${move.to} (${move.from} is held by ${move.holder})`);
237
+ }
238
+ else {
239
+ io.err(`❌ ${result.error}`);
240
+ code = 1;
241
+ }
242
+ if (label === undefined)
243
+ return code;
244
+ // Labelled whatever the number check found: the board needs every Work item.
245
+ if (parsed.apply) {
246
+ for (const issue of unlabelled.issues) {
247
+ try {
248
+ gh(['issue', 'edit', String(issue), '--add-label', label]);
249
+ }
250
+ catch (error) {
251
+ // fail-open: reported, and the command exits 1.
252
+ io.err(`❌ could not label #${String(issue)}: ${detail(error)}`);
253
+ return 1;
254
+ }
255
+ }
256
+ }
257
+ if (unlabelled.issues.length === 0)
258
+ io.out(`✓ every Work item carries ${label}`);
259
+ for (const issue of unlabelled.issues)
260
+ io.out(`${parsed.apply ? '✓ labelled' : '→ would label'} #${String(issue)} ${label}`);
261
+ return code;
262
+ }
package/dist/work.js CHANGED
@@ -527,11 +527,16 @@ export async function prePush(sys, io, refLines, url) {
527
527
  await moveBoard(sys, io, token, slug, slice);
528
528
  return report(io, 'pre-push', problems);
529
529
  }
530
+ /** How a Claude cloud session's GitHub proxy refuses a path outside `repos/{owner}/{repo}/…`, such as an org's Projects. */
531
+ const CLOUD_PROXY_REFUSAL = /sessions are bound to their configured repositories/i;
530
532
  /**
531
533
  * Moves the board on for slice `slice`, which a push is starting to build,
532
- * with the board feature on, through GitHub's REST API, which a Claude
533
- * cloud session's proxy lets through; a board it cannot read, or a move
534
- * GitHub refuses, is said and does not stop the push.
534
+ * with the board feature on, through GitHub's REST API; a board it cannot
535
+ * read, or a move GitHub refuses, is said and does not stop the push. A
536
+ * Claude cloud session's proxy lets through only `repos/{owner}/{repo}/…`,
537
+ * never an org's or a user's Projects, so there the push only says that the
538
+ * shared workflow's Slice started job moves the slice when its pull request
539
+ * opens.
535
540
  */
536
541
  async function moveBoard(sys, io, token, slug, slice) {
537
542
  try {
@@ -539,7 +544,10 @@ async function moveBoard(sys, io, token, slug, slice) {
539
544
  io.err(line);
540
545
  }
541
546
  catch (error) {
542
- io.err(`! board: could not read where #${slice} and its work item are on the board, so nothing moved (${error.message}); the push goes on`);
547
+ const message = error.message;
548
+ io.err(CLOUD_PROXY_REFUSAL.test(message)
549
+ ? `- board: this cloud session cannot reach the board; niyam's workflow moves #${slice} when its pull request opens`
550
+ : `! board: could not read where #${slice} and its work item are on the board, so nothing moved (${message}); the push goes on`);
543
551
  }
544
552
  }
545
553
  /** Throws for a write to an issue that GitHub refused, saying how to fix a workflow that grants no issues: write. */
@@ -651,6 +659,72 @@ export async function prMerged(sys, io) {
651
659
  }
652
660
  return 0;
653
661
  }
662
+ /**
663
+ * Moves the board on for the slice a pull request names as it opens or
664
+ * reopens, run by the shared workflow's Slice started job: the move a push
665
+ * makes from the desktop, which a Claude cloud session's push cannot, since
666
+ * its proxy never reaches an org's Projects. It moves nothing unless the
667
+ * pull request names one slice, the board and work-rules features are on,
668
+ * and the slice passes the work rules, which it reads with the workflow's
669
+ * GH_TOKEN. A workflow's GITHUB_TOKEN cannot write a Project, so the board
670
+ * moves with NIYAM_BOARD_TOKEN, minted from the board GitHub App. Without
671
+ * that token, or when GitHub refuses, it says so and passes: the board never
672
+ * fails a pull request.
673
+ */
674
+ export async function prStarted(sys, io) {
675
+ const { GITHUB_EVENT_PATH: eventPath, GITHUB_REPOSITORY: slug, GH_TOKEN: token, NIYAM_BOARD_TOKEN: board } = sys.env;
676
+ if (!eventPath || !slug || !token) {
677
+ throw new Error('pr-started runs in GitHub Actions: GITHUB_EVENT_PATH, GITHUB_REPOSITORY and GH_TOKEN must be set');
678
+ }
679
+ const event = JSON.parse(sys.read(eventPath));
680
+ const pull = event.pull_request;
681
+ if (!pull) {
682
+ io.out('pr-started: not a pull request; nothing to move');
683
+ return 0;
684
+ }
685
+ const notAdopted = notAdoptedLine(sys, sys.cwd, 'pr-started');
686
+ if (notAdopted) {
687
+ io.out(notAdopted);
688
+ return 0;
689
+ }
690
+ for (const feature of ['work-rules', 'board']) {
691
+ if (!isOn(sys, sys.cwd, feature)) {
692
+ io.out(offLine('pr-started', feature));
693
+ return 0;
694
+ }
695
+ }
696
+ if (await isPersonal(sys, slug, token)) {
697
+ io.out(offLine('pr-started', 'work-rules', PERSONAL_REPO));
698
+ return 0;
699
+ }
700
+ const slices = slicesNamed(pull.body ?? '');
701
+ if (slices.length !== 1) {
702
+ io.out(`pr-started: #${pull.number} names ${slices.length === 0 ? 'no slice' : `${slices.length} slices`}; nothing moves on the board`);
703
+ return 0;
704
+ }
705
+ const [slice] = slices;
706
+ if (!board) {
707
+ io.out(`pr-started: no board app token here (the NIYAM_BOARD_APP_ID and NIYAM_BOARD_APP_KEY secrets are not passed, or GitHub would not make the token), so #${slice} moves on the board only from a desktop push`);
708
+ return 0;
709
+ }
710
+ try {
711
+ const problems = await sliceProblems(sys, token, slug, slice, loadSettings(sys, sys.cwd), { pull: pull.number, states: statesNamed(pull.body ?? '') });
712
+ if (problems.length > 0) {
713
+ io.out(`pr-started: #${slice} may not be built yet (Work rules says why), so nothing moves on the board`);
714
+ return 0;
715
+ }
716
+ const moved = await boardStarted(sys, board, slug, slice);
717
+ for (const line of moved)
718
+ io.out(line);
719
+ if (moved.length === 0)
720
+ io.out(`pr-started: #${slice} and its work item are where they belong on the board already`);
721
+ }
722
+ catch (error) {
723
+ // fail-open: the board never fails a pull request; Work rules judges the slice, and the line says what GitHub refused.
724
+ io.out(`! board: nothing moved for #${slice} (${error.message}); the pull request's checks go on`);
725
+ }
726
+ return 0;
727
+ }
654
728
  /** The newest of `comments`, which is not empty: GitHub lists comments oldest first. */
655
729
  function newest(comments) {
656
730
  return comments[comments.length - 1];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veda-hq/niyam",
3
- "version": "0.6.21",
3
+ "version": "0.6.23",
4
4
  "description": "Work rules for repos that track work in GitHub Issues: setup, agent identity, push and PR checks.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -28,7 +28,7 @@
28
28
  "@types/node": "24.19.2",
29
29
  "@veda-hq/dvara": "0.5.16",
30
30
  "@veda-hq/pariksha": "0.5.20",
31
- "@veda-hq/sarathi": "0.6.10",
31
+ "@veda-hq/sarathi": "0.6.12",
32
32
  "typescript": "7.0.2"
33
33
  },
34
34
  "dependencies": {