@veda-hq/niyam 0.6.16 → 0.6.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +261 -48
- package/dist/agent.js +4 -0
- package/dist/as-agent.js +26 -18
- package/dist/board.js +3 -3
- package/dist/brief.js +370 -0
- package/dist/cloud.js +28 -11
- package/dist/cubic-dismiss.js +284 -0
- package/dist/doctor.js +3 -6
- package/dist/handoff.js +527 -0
- package/dist/issue-types.js +2 -2
- package/dist/keep-going.js +384 -0
- package/dist/onboard.js +45 -16
- package/dist/pr-autocreate.js +984 -0
- package/dist/release-tag.js +40 -0
- package/dist/run.js +55 -5
- package/dist/session-start.js +2 -2
- package/dist/sys.js +44 -1
- package/dist/upgrade.js +7 -0
- package/dist/work.js +4 -0
- package/package.json +1 -1
package/dist/handoff.js
ADDED
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
import { SETTINGS_PATH, repoAt } from './agent.js';
|
|
2
|
+
import { relative, resolve } from 'node:path';
|
|
3
|
+
import { addToProject, deletedSince, judgeBrief, lintDraft, loadYaml, openBrief, readBrief, repoPath } from './brief.js';
|
|
4
|
+
import { sessionToken } from './work.js';
|
|
5
|
+
/** Repository-relative path of the declarations, JSON lines, appended to. */
|
|
6
|
+
export const RUN_LOG = '.tmp/push/handoff-log.jsonl';
|
|
7
|
+
export const MIN_FAILURES = 3;
|
|
8
|
+
export const MIN_TREES = 2;
|
|
9
|
+
const where = `${SETTINGS_PATH}: "handoff"`;
|
|
10
|
+
/** The `"handoff"` settings, or undefined when the repository names none. Throws on a malformed entry. */
|
|
11
|
+
export function handoffSettings(raw) {
|
|
12
|
+
const value = typeof raw === 'object' && raw !== null ? raw.handoff : undefined;
|
|
13
|
+
if (value === undefined)
|
|
14
|
+
return undefined;
|
|
15
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
16
|
+
throw new Error(`${where} must be an object`);
|
|
17
|
+
const { plumbing, history, ignoreStages = [], template, base = 'origin/main', ...rest } = value;
|
|
18
|
+
const extra = Object.keys(rest)[0];
|
|
19
|
+
if (extra !== undefined)
|
|
20
|
+
throw new Error(`${where} has an unknown key "${extra}"; it takes "plumbing", "history", "ignoreStages", "template" and "base"`);
|
|
21
|
+
const paths = (v) => Array.isArray(v) && v.every((p) => typeof p === 'string' && repoPath(p) !== null);
|
|
22
|
+
if (!paths(plumbing) || plumbing.length === 0)
|
|
23
|
+
throw new Error(`${where}.plumbing must be a non-empty list of paths in the repository, a folder ending in "/"`);
|
|
24
|
+
for (const [key, one] of [['history', history], ['template', template]]) {
|
|
25
|
+
if (one !== undefined && (typeof one !== 'string' || repoPath(one) === null))
|
|
26
|
+
throw new Error(`${where}.${key} must be a path in the repository`);
|
|
27
|
+
}
|
|
28
|
+
if (!Array.isArray(ignoreStages) || !ignoreStages.every((stage) => typeof stage === 'string'))
|
|
29
|
+
throw new Error(`${where}.ignoreStages must be a list of stage names`);
|
|
30
|
+
if (typeof base !== 'string' || !base || base.startsWith('-'))
|
|
31
|
+
throw new Error(`${where}.base must be a ref, such as "origin/main"`);
|
|
32
|
+
return {
|
|
33
|
+
plumbing,
|
|
34
|
+
ignoreStages: ignoreStages,
|
|
35
|
+
base,
|
|
36
|
+
...(typeof history === 'string' ? { history } : {}),
|
|
37
|
+
...(typeof template === 'string' ? { template } : {}),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** Whether `file` is shared plumbing: under a folder entry, on a segment boundary, or one file entry by its whole path. */
|
|
41
|
+
export function isPlumbing(file, plumbing) {
|
|
42
|
+
const path = file.replace(/^\.\//, '');
|
|
43
|
+
return plumbing.some((entry) => (entry.endsWith('/') ? path.startsWith(entry) : path === entry));
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The runs of the push history: every field its writer always writes, with the right type, or the line is not a
|
|
47
|
+
* run. A corrupt line is counted, never evidence, and never stops a push.
|
|
48
|
+
*/
|
|
49
|
+
export function parseHistory(text) {
|
|
50
|
+
const runs = [];
|
|
51
|
+
let malformed = 0;
|
|
52
|
+
const nullableText = (v) => v === undefined || v === null || typeof v === 'string';
|
|
53
|
+
for (const raw of text.split('\n')) {
|
|
54
|
+
const line = raw.trim();
|
|
55
|
+
if (!line)
|
|
56
|
+
continue;
|
|
57
|
+
let run = null;
|
|
58
|
+
try {
|
|
59
|
+
run = JSON.parse(line);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// Counted below.
|
|
63
|
+
}
|
|
64
|
+
const stage = (s) => {
|
|
65
|
+
const one = s;
|
|
66
|
+
return typeof one?.name === 'string' && typeof one.startMs === 'number' && typeof one.durationMs === 'number' && typeof one.status === 'string';
|
|
67
|
+
};
|
|
68
|
+
const ok = typeof run === 'object' &&
|
|
69
|
+
run !== null &&
|
|
70
|
+
typeof run.schema === 'number' &&
|
|
71
|
+
typeof run.id === 'string' &&
|
|
72
|
+
typeof run.invocation === 'string' &&
|
|
73
|
+
typeof run.startedAt === 'string' &&
|
|
74
|
+
typeof run.durationMs === 'number' &&
|
|
75
|
+
typeof run.kind === 'string' &&
|
|
76
|
+
typeof run.exitCode === 'number' &&
|
|
77
|
+
Array.isArray(run.stages) &&
|
|
78
|
+
run.stages.every(stage) &&
|
|
79
|
+
nullableText(run.branch) &&
|
|
80
|
+
nullableText(run.fingerprint);
|
|
81
|
+
if (ok)
|
|
82
|
+
runs.push(run);
|
|
83
|
+
else
|
|
84
|
+
malformed++;
|
|
85
|
+
}
|
|
86
|
+
return { runs, malformed };
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Fires when one stage was the one a push died at (failed, or timed out) three times on this branch, across two
|
|
90
|
+
* working trees or more: the code kept changing and the same thing kept failing. Runs of other branches, and of
|
|
91
|
+
* no branch, are not this push's. A run with no fingerprint counts as a failure but not as another tree.
|
|
92
|
+
*/
|
|
93
|
+
export function repeatedFailure(runs, branch, ignore) {
|
|
94
|
+
const counts = new Map();
|
|
95
|
+
const trees = new Map();
|
|
96
|
+
for (const run of runs) {
|
|
97
|
+
if (run.kind !== 'pre-push' || run.exitCode === 0 || run.branch !== branch)
|
|
98
|
+
continue;
|
|
99
|
+
const stage = run.stages.find((one) => one.status === 'failed' || one.status === 'timed_out')?.name;
|
|
100
|
+
if (stage === undefined || ignore.includes(stage))
|
|
101
|
+
continue;
|
|
102
|
+
counts.set(stage, (counts.get(stage) ?? 0) + 1);
|
|
103
|
+
const seen = trees.get(stage) ?? new Set();
|
|
104
|
+
if (run.fingerprint)
|
|
105
|
+
seen.add(run.fingerprint);
|
|
106
|
+
trees.set(stage, seen);
|
|
107
|
+
}
|
|
108
|
+
let worst = { fired: false, stage: null, failures: 0, trees: 0 };
|
|
109
|
+
for (const [stage, failures] of counts) {
|
|
110
|
+
const distinct = trees.get(stage)?.size ?? 0;
|
|
111
|
+
if (failures >= MIN_FAILURES && distinct >= MIN_TREES && failures > worst.failures)
|
|
112
|
+
worst = { fired: true, stage, failures, trees: distinct };
|
|
113
|
+
}
|
|
114
|
+
return worst;
|
|
115
|
+
}
|
|
116
|
+
export const CALL_SITES = ['push-skill', 'pre-push-hook', 'hook-verify'];
|
|
117
|
+
export const DISPOSITIONS = ['own-work', 'handed-off', 'carrying', 'dismissed', 'gate-pass', 'gate-refused', 'gate-skipped'];
|
|
118
|
+
/** The dispositions a session declares; the rest are the gate's own record. */
|
|
119
|
+
export const DECLARED = ['own-work', 'handed-off', 'carrying', 'dismissed'];
|
|
120
|
+
export const SPAWNED = ['chip', 'manual', 'unavailable', 'n/a'];
|
|
121
|
+
const oneOf = (list, v) => typeof v === 'string' && list.includes(v);
|
|
122
|
+
const texts = (v) => Array.isArray(v) && v.every((x) => typeof x === 'string');
|
|
123
|
+
/** The declarations, each line whole or not counted. */
|
|
124
|
+
export function parseRunLog(text) {
|
|
125
|
+
const entries = [];
|
|
126
|
+
let malformed = 0;
|
|
127
|
+
for (const raw of text.split('\n')) {
|
|
128
|
+
const line = raw.trim();
|
|
129
|
+
if (!line)
|
|
130
|
+
continue;
|
|
131
|
+
let e = null;
|
|
132
|
+
try {
|
|
133
|
+
e = JSON.parse(line);
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
// Counted below.
|
|
137
|
+
}
|
|
138
|
+
const ok = typeof e === 'object' &&
|
|
139
|
+
e !== null &&
|
|
140
|
+
typeof e.ts === 'string' &&
|
|
141
|
+
oneOf(CALL_SITES, e.callSite) &&
|
|
142
|
+
typeof e.branch === 'string' &&
|
|
143
|
+
typeof e.baseRef === 'string' &&
|
|
144
|
+
typeof e.baseSha === 'string' &&
|
|
145
|
+
typeof e.headSha === 'string' &&
|
|
146
|
+
texts(e.triggers) &&
|
|
147
|
+
oneOf(DISPOSITIONS, e.disposition) &&
|
|
148
|
+
typeof e.reason === 'string' &&
|
|
149
|
+
texts(e.briefs) &&
|
|
150
|
+
oneOf(SPAWNED, e.spawned);
|
|
151
|
+
if (ok)
|
|
152
|
+
entries.push(e);
|
|
153
|
+
else
|
|
154
|
+
malformed++;
|
|
155
|
+
}
|
|
156
|
+
return { entries, malformed };
|
|
157
|
+
}
|
|
158
|
+
/** Whether a dismissal's reason cites where the owner decided: an issue (#N or a URL), an id such as ABC-12, an ADR, or a commit. */
|
|
159
|
+
export function citesAuthority(reason) {
|
|
160
|
+
return /(?:^|[^\w])#\d+/.test(reason) || /\bhttps?:\/\/\S+/.test(reason) || /\b[A-Z]{2,}-\d+\b/.test(reason) || /\b[0-9a-f]{7,40}\b/.test(reason);
|
|
161
|
+
}
|
|
162
|
+
export function fired(triggers) {
|
|
163
|
+
return [...(triggers.plumbing.fired ? ['plumbing-edit'] : []), ...(triggers.repeated.fired ? ['repeated-stage-failure'] : [])];
|
|
164
|
+
}
|
|
165
|
+
function describe(triggers) {
|
|
166
|
+
const { paths } = triggers.plumbing;
|
|
167
|
+
return [
|
|
168
|
+
...(triggers.plumbing.fired ? [`this branch changes ${paths.length} shared-plumbing file(s) (${paths.slice(0, 5).join(', ')}${paths.length > 5 ? ', …' : ''})`] : []),
|
|
169
|
+
...(triggers.repeated.fired ? [`the push has failed ${triggers.repeated.failures} times at stage "${triggers.repeated.stage}" across ${triggers.repeated.trees} working trees`] : []),
|
|
170
|
+
].join(' and ');
|
|
171
|
+
}
|
|
172
|
+
const short = (sha) => sha.slice(0, 7) || '(none)';
|
|
173
|
+
/**
|
|
174
|
+
* Whether the push may go: no trigger fired, or the newest declaration the session made (never one the gate or a
|
|
175
|
+
* check wrote) covers this head, this base and every trigger that fired, and holds what its disposition owes.
|
|
176
|
+
*/
|
|
177
|
+
export async function assertDeclared(input) {
|
|
178
|
+
const names = fired(input.triggers);
|
|
179
|
+
const no = (reason, detail) => ({ ok: false, reason, detail, matched: null });
|
|
180
|
+
if (names.length === 0)
|
|
181
|
+
return { ok: true, reason: 'no-trigger', detail: 'this push changes no shared plumbing and shows no stage failing again and again', matched: null };
|
|
182
|
+
const why = describe(input.triggers);
|
|
183
|
+
if (input.entries.length === 0)
|
|
184
|
+
return no('empty-run-log', `${why}, and ${RUN_LOG} holds no declaration of whether this was your own work or something you tripped over`);
|
|
185
|
+
const fromSession = input.entries.filter((e) => e.callSite === 'push-skill');
|
|
186
|
+
if (fromSession.length === 0) {
|
|
187
|
+
return no('no-push-skill-entry', `${why}, and no declaration there was made by the session (callSite "push-skill"; there: ${[...new Set(input.entries.map((e) => e.callSite))].sort().join(', ')}); a gate or check run cannot declare for it`);
|
|
188
|
+
}
|
|
189
|
+
const atHead = fromSession.filter((e) => e.headSha === input.headSha);
|
|
190
|
+
if (atHead.length === 0)
|
|
191
|
+
return no('stale-head-sha', `the newest declaration covered head ${short(fromSession.at(-1).headSha)}, but this push carries ${short(input.headSha)}; declare again over the commits being pushed`);
|
|
192
|
+
const exact = atHead.filter((e) => e.baseSha === input.baseSha);
|
|
193
|
+
if (exact.length === 0)
|
|
194
|
+
return no('stale-base-sha', `the declaration at head ${short(input.headSha)} was made against base ${short(atHead.at(-1).baseSha)}, but this push compares with ${short(input.baseSha)}; declare again`);
|
|
195
|
+
// The repeated-failure trigger can start firing at a head already declared: a retried push adds failures without moving it.
|
|
196
|
+
const covering = exact.filter((e) => names.every((name) => e.triggers.includes(name)));
|
|
197
|
+
if (covering.length === 0) {
|
|
198
|
+
const newest = exact.at(-1);
|
|
199
|
+
return no('trigger-not-declared', `${why}, but the newest declaration at this head covered only [${newest.triggers.join(', ') || 'none'}]; ${names.filter((n) => !newest.triggers.includes(n)).join(', ')} fired after it, so declare again`);
|
|
200
|
+
}
|
|
201
|
+
const newest = covering.at(-1);
|
|
202
|
+
if (!oneOf(DECLARED, newest.disposition))
|
|
203
|
+
return no('declaration-not-concluded', `the newest declaration at ${short(input.headSha)} is "${newest.disposition}", the gate's own record, not a declaration`);
|
|
204
|
+
if (newest.disposition === 'own-work' || newest.disposition === 'dismissed') {
|
|
205
|
+
if (!newest.reason.trim())
|
|
206
|
+
return no('missing-reason', `"${newest.disposition}" was declared with no --reason; say in one sentence why, so a reviewer sees the scope decision`);
|
|
207
|
+
if (newest.disposition === 'dismissed' && !citesAuthority(newest.reason)) {
|
|
208
|
+
return no('uncited-dismissal', `"dismissed" says the owner overrode this, so its --reason cites where: an issue or pull request (#123 or a link), an id such as ABC-123, or a commit. Got: "${newest.reason}"`);
|
|
209
|
+
}
|
|
210
|
+
return { ok: true, reason: 'declared', detail: `${why}; declared "${newest.disposition}": ${newest.reason}`, matched: newest };
|
|
211
|
+
}
|
|
212
|
+
if (newest.briefs.length === 0)
|
|
213
|
+
return no('missing-brief', `"${newest.disposition}" was declared with no --brief; write one${input.template ? ` from ${input.template}` : ''} and open it with --open-brief <draft.md>`);
|
|
214
|
+
for (const brief of newest.briefs) {
|
|
215
|
+
const number = /^#([1-9]\d*)$/.exec(brief)?.[1];
|
|
216
|
+
if (number === undefined)
|
|
217
|
+
return no('brief-not-an-issue', `declared brief "${brief}" is not a Brief issue; open one with --open-brief <draft.md>, or declare one as #N`);
|
|
218
|
+
const verdict = judgeBrief(brief, await input.readIssue(Number(number)), {
|
|
219
|
+
branch: input.branch,
|
|
220
|
+
disposition: newest.disposition === 'carrying' ? 'carrying' : 'handed-off',
|
|
221
|
+
lint: { yaml: (input.yaml ??= await loadYaml()), pathExists: input.pathExists, pathDeletedSince: input.pathDeletedSince, changedFiles: input.changedFiles, ...(input.template ? { template: input.template } : {}) },
|
|
222
|
+
isAncestorOfHead: input.isAncestorOfHead,
|
|
223
|
+
});
|
|
224
|
+
if (!verdict.ok)
|
|
225
|
+
return no(verdict.reason, verdict.detail);
|
|
226
|
+
}
|
|
227
|
+
return { ok: true, reason: 'declared', detail: `${why}; declared "${newest.disposition}" with ${newest.briefs.join(', ')}`, matched: newest };
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* The repository's settings, and the `"handoff"` that decides, or undefined when none is named. The base's copy
|
|
231
|
+
* decides when it names one, read from the ref asked for or the remote's default branch, never a ref the branch's
|
|
232
|
+
* own settings name: a branch cannot turn the gate off, or shorten its list, in the push the gate judges.
|
|
233
|
+
*/
|
|
234
|
+
function settingsHere(sys, base) {
|
|
235
|
+
const { root, slug } = repoAt(sys);
|
|
236
|
+
const path = `${root}/${SETTINGS_PATH}`;
|
|
237
|
+
const raw = sys.exists(path) ? JSON.parse(sys.read(path)) : {};
|
|
238
|
+
const tree = handoffSettings(raw);
|
|
239
|
+
const remoteHead = sys.exec('git', ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], { cwd: root });
|
|
240
|
+
const at = base ?? (remoteHead.code === 0 && remoteHead.stdout.trim() ? remoteHead.stdout.trim() : 'origin/main');
|
|
241
|
+
const shown = sys.exec('git', ['show', `${at}:${SETTINGS_PATH}`], { cwd: root });
|
|
242
|
+
let atBase;
|
|
243
|
+
try {
|
|
244
|
+
atBase = shown.code === 0 ? handoffSettings(JSON.parse(shown.stdout)) : undefined;
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
// A base whose settings do not read decides nothing; the branch's own then do.
|
|
248
|
+
}
|
|
249
|
+
return { root, slug, raw, settings: atBase ?? tree };
|
|
250
|
+
}
|
|
251
|
+
function here(sys, asked) {
|
|
252
|
+
const { root, slug, raw, settings } = settingsHere(sys, asked);
|
|
253
|
+
if (!settings)
|
|
254
|
+
throw new Error(`${SETTINGS_PATH} names no "handoff": the gate is off in this repository`);
|
|
255
|
+
const git = (args) => {
|
|
256
|
+
const run = sys.exec('git', args, { cwd: root });
|
|
257
|
+
return { ok: run.code === 0, out: run.stdout.trim() };
|
|
258
|
+
};
|
|
259
|
+
const base = asked ?? settings.base;
|
|
260
|
+
// A ref the branch can point at itself, such as HEAD, would compare the push with itself and see nothing.
|
|
261
|
+
const full = git(['rev-parse', '--symbolic-full-name', base]);
|
|
262
|
+
if (!full.ok || !full.out.startsWith('refs/remotes/'))
|
|
263
|
+
throw new Error(`the base "${base}" is not a remote-tracking branch, such as origin/main: the gate compares a push with what the remote has`);
|
|
264
|
+
return { root, slug, raw, settings, base, git };
|
|
265
|
+
}
|
|
266
|
+
function must(h, args, what) {
|
|
267
|
+
const run = h.git(args);
|
|
268
|
+
if (!run.ok)
|
|
269
|
+
throw new Error(`git cannot tell ${what}`);
|
|
270
|
+
return run.out;
|
|
271
|
+
}
|
|
272
|
+
/** The branch, its changed files, the triggers, and the base and head commits, against `base`. */
|
|
273
|
+
export function collect(sys, h, base) {
|
|
274
|
+
const branch = must(h, ['rev-parse', '--abbrev-ref', 'HEAD'], 'the branch');
|
|
275
|
+
const changedFiles = must(h, ['diff', '--name-only', `${base}...HEAD`], `what this branch changes against ${base}`).split('\n').filter(Boolean);
|
|
276
|
+
// The settings file is plumbing itself: it says what plumbing is.
|
|
277
|
+
const paths = changedFiles.filter((file) => file === SETTINGS_PATH || isPlumbing(file, h.settings.plumbing));
|
|
278
|
+
const history = h.settings.history && sys.exists(`${h.root}/${h.settings.history}`) ? parseHistory(sys.read(`${h.root}/${h.settings.history}`)).runs : [];
|
|
279
|
+
return {
|
|
280
|
+
branch,
|
|
281
|
+
changedFiles,
|
|
282
|
+
triggers: { plumbing: { fired: paths.length > 0, paths }, repeated: repeatedFailure(history, branch, h.settings.ignoreStages) },
|
|
283
|
+
baseSha: must(h, ['merge-base', base, 'HEAD'], `where this branch left ${base}`),
|
|
284
|
+
headSha: must(h, ['rev-parse', 'HEAD'], 'the head commit'),
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
function lintContext(h, changedFiles) {
|
|
288
|
+
const existsAt = (rev, path) => h.git(['cat-file', '-e', `${rev}:${path}`]).ok;
|
|
289
|
+
const isAncestorOfHead = (sha) => h.git(['merge-base', '--is-ancestor', sha, 'HEAD']).ok;
|
|
290
|
+
return {
|
|
291
|
+
changedFiles,
|
|
292
|
+
pathExists: (path) => existsAt('HEAD', path),
|
|
293
|
+
pathDeletedSince: (sha, path) => deletedSince({ existsAt, isAncestor: isAncestorOfHead }, sha, path),
|
|
294
|
+
isAncestorOfHead,
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
const append = (sys, root, entry) => {
|
|
298
|
+
sys.mkdir(`${root}/.tmp/push`);
|
|
299
|
+
sys.append(`${root}/${RUN_LOG}`, `${JSON.stringify(entry)}\n`);
|
|
300
|
+
};
|
|
301
|
+
/** The gate at a push: refuses unless a declaration covers it, and records its own verdict. */
|
|
302
|
+
export async function gate(sys, io, base, callSite = 'pre-push-hook') {
|
|
303
|
+
// A repository that names no shared plumbing has turned the gate off.
|
|
304
|
+
if (!settingsHere(sys, base).settings)
|
|
305
|
+
return 0;
|
|
306
|
+
const h = here(sys, base);
|
|
307
|
+
const ref = h.base;
|
|
308
|
+
const { branch, changedFiles, triggers, baseSha, headSha } = collect(sys, h, ref);
|
|
309
|
+
const log = sys.exists(`${h.root}/${RUN_LOG}`) ? parseRunLog(sys.read(`${h.root}/${RUN_LOG}`)).entries : [];
|
|
310
|
+
const context = lintContext(h, changedFiles);
|
|
311
|
+
const token = sessionToken(sys);
|
|
312
|
+
const verdict = await assertDeclared({
|
|
313
|
+
triggers,
|
|
314
|
+
baseSha,
|
|
315
|
+
headSha,
|
|
316
|
+
branch,
|
|
317
|
+
entries: log,
|
|
318
|
+
...context,
|
|
319
|
+
readIssue: async (n) => (token ? readBrief(sys, token, h.slug, n) : null),
|
|
320
|
+
...(h.settings.template ? { template: h.settings.template } : {}),
|
|
321
|
+
});
|
|
322
|
+
append(sys, h.root, {
|
|
323
|
+
ts: sys.now().toISOString(),
|
|
324
|
+
callSite,
|
|
325
|
+
branch,
|
|
326
|
+
baseRef: ref,
|
|
327
|
+
baseSha,
|
|
328
|
+
headSha,
|
|
329
|
+
triggers: fired(triggers),
|
|
330
|
+
disposition: verdict.ok ? (verdict.reason === 'no-trigger' ? 'gate-skipped' : 'gate-pass') : 'gate-refused',
|
|
331
|
+
reason: verdict.detail,
|
|
332
|
+
briefs: verdict.matched?.briefs ?? [],
|
|
333
|
+
spawned: 'n/a',
|
|
334
|
+
});
|
|
335
|
+
if (verdict.ok) {
|
|
336
|
+
if (verdict.reason !== 'no-trigger')
|
|
337
|
+
io.out(`✓ handoff: ${verdict.detail}`);
|
|
338
|
+
return 0;
|
|
339
|
+
}
|
|
340
|
+
io.err(`✗ handoff: ${verdict.detail}`);
|
|
341
|
+
io.err(` what fired: niyam handoff --detect --base ${ref}`);
|
|
342
|
+
io.err(` then declare: niyam handoff --record --base ${ref} --disposition <own-work|handed-off|carrying|dismissed> --reason "..."`);
|
|
343
|
+
return 1;
|
|
344
|
+
}
|
|
345
|
+
/** The options `handoff` and `brief` take, each once, with a value that is not the next option. */
|
|
346
|
+
function options(args, known, flags) {
|
|
347
|
+
const found = new Map();
|
|
348
|
+
for (let i = 0; i < args.length; i++) {
|
|
349
|
+
const token = args[i];
|
|
350
|
+
const eq = token.startsWith('--') ? token.indexOf('=') : -1;
|
|
351
|
+
const name = eq > 0 ? token.slice(0, eq) : token;
|
|
352
|
+
if (found.has(name))
|
|
353
|
+
throw new Error(`${name} is given twice`);
|
|
354
|
+
if (flags.includes(name) && eq < 0) {
|
|
355
|
+
found.set(name, true);
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
if (!known.includes(name))
|
|
359
|
+
throw new Error(`unexpected argument "${token}"`);
|
|
360
|
+
const value = eq > 0 ? token.slice(eq + 1) : args[++i];
|
|
361
|
+
if (value === undefined || !value.trim() || value.startsWith('--'))
|
|
362
|
+
throw new Error(`${name} needs a value`);
|
|
363
|
+
found.set(name, value);
|
|
364
|
+
}
|
|
365
|
+
return found;
|
|
366
|
+
}
|
|
367
|
+
const MODES = ['--detect', '--record', '--assert-fresh'];
|
|
368
|
+
const VALUES = ['--base', '--disposition', '--reason', '--brief', '--open-brief', '--call-site', '--spawned'];
|
|
369
|
+
/** `handoff`'s arguments: one mode, and the options it takes; anything else is refused. */
|
|
370
|
+
export function handoffArgs(args) {
|
|
371
|
+
const found = options(args, VALUES, MODES);
|
|
372
|
+
const modes = MODES.filter((mode) => found.has(mode));
|
|
373
|
+
if (modes.length !== 1)
|
|
374
|
+
throw new Error('handoff takes one of --detect, --record or --assert-fresh');
|
|
375
|
+
const mode = modes[0].slice(2);
|
|
376
|
+
const value = (name) => found.get(name);
|
|
377
|
+
const only = (allowed) => {
|
|
378
|
+
const stray = VALUES.find((name) => found.has(name) && !allowed.includes(name));
|
|
379
|
+
if (stray)
|
|
380
|
+
throw new Error(`--${mode} does not take ${stray}`);
|
|
381
|
+
};
|
|
382
|
+
const disposition = value('--disposition');
|
|
383
|
+
const callSite = value('--call-site');
|
|
384
|
+
const spawned = value('--spawned') ?? 'n/a';
|
|
385
|
+
if (mode === 'detect')
|
|
386
|
+
only(['--base']);
|
|
387
|
+
if (mode === 'assert-fresh')
|
|
388
|
+
only(['--base', '--call-site']);
|
|
389
|
+
if (mode === 'record') {
|
|
390
|
+
if (!oneOf(DECLARED, disposition))
|
|
391
|
+
throw new Error(`--record needs --disposition ${DECLARED.join('|')}${disposition ? `, not "${disposition}"` : ''}`);
|
|
392
|
+
if (value('--open-brief') !== undefined && !value('--reason'))
|
|
393
|
+
throw new Error('--open-brief needs --reason: the gate refuses a declaration without one, so no issue is opened');
|
|
394
|
+
}
|
|
395
|
+
if (callSite !== undefined && !oneOf(CALL_SITES, callSite))
|
|
396
|
+
throw new Error(`--call-site takes ${CALL_SITES.join('|')}, not "${callSite}"`);
|
|
397
|
+
if (mode === 'assert-fresh' && callSite === 'push-skill')
|
|
398
|
+
throw new Error('--assert-fresh cannot run as "push-skill": the gate cannot write its own evidence');
|
|
399
|
+
if (!oneOf(SPAWNED, spawned))
|
|
400
|
+
throw new Error(`--spawned takes ${SPAWNED.join('|')}, not "${spawned}"`);
|
|
401
|
+
const base = value('--base');
|
|
402
|
+
const reason = value('--reason');
|
|
403
|
+
const openBrief = value('--open-brief');
|
|
404
|
+
return {
|
|
405
|
+
mode,
|
|
406
|
+
...(base === undefined ? {} : { base }),
|
|
407
|
+
...(disposition === undefined ? {} : { disposition: disposition }),
|
|
408
|
+
reason: reason ?? '',
|
|
409
|
+
briefs: (value('--brief') ?? '').split(',').map((b) => b.trim()).filter(Boolean),
|
|
410
|
+
...(openBrief === undefined ? {} : { openBrief }),
|
|
411
|
+
...(callSite === undefined ? {} : { callSite: callSite }),
|
|
412
|
+
spawned: spawned,
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
/** A draft path inside the repository, or null: its text goes to GitHub, so nothing from elsewhere may be read. */
|
|
416
|
+
function draftAt(h, sys, draft) {
|
|
417
|
+
const rel = relative(h.root, resolve(sys.cwd, draft));
|
|
418
|
+
return repoPath(rel);
|
|
419
|
+
}
|
|
420
|
+
/** Lints a draft for this branch and opens it as a Brief issue on the repository's Project; the issue's ref, or a problem. */
|
|
421
|
+
async function openDraft(sys, io, h, draft, disposition, branch, changedFiles) {
|
|
422
|
+
const rel = draftAt(h, sys, draft);
|
|
423
|
+
if (rel === null) {
|
|
424
|
+
io.err(`✗ the brief draft must be a file in the repository: ${draft}; no issue was opened`);
|
|
425
|
+
return undefined;
|
|
426
|
+
}
|
|
427
|
+
if (!sys.exists(`${h.root}/${rel}`)) {
|
|
428
|
+
io.err(`✗ no brief draft at ${draft}; no issue was opened`);
|
|
429
|
+
return undefined;
|
|
430
|
+
}
|
|
431
|
+
const lint = lintDraft(sys.read(`${h.root}/${rel}`), branch, { ...lintContext(h, changedFiles), yaml: await loadYaml(), disposition, ...(h.settings.template ? { template: h.settings.template } : {}) });
|
|
432
|
+
if (!lint.ok) {
|
|
433
|
+
io.err(`✗ ${draft}: ${lint.problems.join('; ')}`);
|
|
434
|
+
io.err('no issue was opened');
|
|
435
|
+
return undefined;
|
|
436
|
+
}
|
|
437
|
+
const token = sessionToken(sys);
|
|
438
|
+
if (!token) {
|
|
439
|
+
io.err('✗ this session has no token; run niyam doctor. No issue was opened');
|
|
440
|
+
return undefined;
|
|
441
|
+
}
|
|
442
|
+
const opened = await openBrief(sys, token, h.slug, lint.draft);
|
|
443
|
+
const project = typeof h.raw.project === 'string' ? h.raw.project : undefined;
|
|
444
|
+
// The issue is the brief once it exists, so it is recorded even when the board add fails: a rerun would open another.
|
|
445
|
+
try {
|
|
446
|
+
if (project)
|
|
447
|
+
await addToProject(sys, token, h.slug, opened.id, project);
|
|
448
|
+
io.out(`✓ opened #${opened.number}${project ? ` on "${project}"` : ''}: ${opened.url}`);
|
|
449
|
+
}
|
|
450
|
+
catch (error) {
|
|
451
|
+
io.err(`⚠ opened ${opened.url} but could not add it to "${project}" (${error instanceof Error ? error.message : String(error)}); add it by hand`);
|
|
452
|
+
}
|
|
453
|
+
return `#${opened.number}`;
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* `niyam handoff`: --detect says which triggers fire; --record appends the session's declaration, opening its
|
|
457
|
+
* brief first with --open-brief; --assert-fresh is the gate, as the pre-push hook runs it.
|
|
458
|
+
*/
|
|
459
|
+
export async function handoff(sys, io, args) {
|
|
460
|
+
const parsed = handoffArgs(args);
|
|
461
|
+
if (parsed.mode === 'assert-fresh')
|
|
462
|
+
return gate(sys, io, parsed.base, parsed.callSite);
|
|
463
|
+
const h = here(sys, parsed.base);
|
|
464
|
+
const { base } = h;
|
|
465
|
+
const { branch, changedFiles, triggers, baseSha, headSha } = collect(sys, h, base);
|
|
466
|
+
if (parsed.mode === 'detect') {
|
|
467
|
+
io.out(JSON.stringify({ branch, baseRef: base, changedFiles: changedFiles.length, triggers, fired: fired(triggers), runLog: RUN_LOG }, null, 2));
|
|
468
|
+
return 0;
|
|
469
|
+
}
|
|
470
|
+
const disposition = parsed.disposition;
|
|
471
|
+
const briefs = [...parsed.briefs];
|
|
472
|
+
if (parsed.openBrief !== undefined) {
|
|
473
|
+
if (disposition !== 'handed-off' && disposition !== 'carrying') {
|
|
474
|
+
io.err(`✗ --open-brief goes with --disposition handed-off or carrying, not "${disposition}"`);
|
|
475
|
+
return 1;
|
|
476
|
+
}
|
|
477
|
+
const opened = await openDraft(sys, io, h, parsed.openBrief, disposition, branch, changedFiles);
|
|
478
|
+
if (opened === undefined)
|
|
479
|
+
return 1;
|
|
480
|
+
if (!briefs.includes(opened))
|
|
481
|
+
briefs.push(opened);
|
|
482
|
+
}
|
|
483
|
+
const entry = {
|
|
484
|
+
ts: sys.now().toISOString(),
|
|
485
|
+
callSite: parsed.callSite ?? 'push-skill',
|
|
486
|
+
branch,
|
|
487
|
+
baseRef: base,
|
|
488
|
+
baseSha,
|
|
489
|
+
headSha,
|
|
490
|
+
triggers: fired(triggers),
|
|
491
|
+
disposition,
|
|
492
|
+
reason: parsed.reason,
|
|
493
|
+
briefs,
|
|
494
|
+
spawned: parsed.spawned,
|
|
495
|
+
};
|
|
496
|
+
append(sys, h.root, entry);
|
|
497
|
+
io.out(JSON.stringify({ recorded: entry, runLog: RUN_LOG }, null, 2));
|
|
498
|
+
return 0;
|
|
499
|
+
}
|
|
500
|
+
/** `brief <draft.md>` opens the draft as a Brief issue; `brief --lint <draft.md>` only checks it. */
|
|
501
|
+
export function briefArgs(args) {
|
|
502
|
+
const lint = args[0] === '--lint';
|
|
503
|
+
const rest = lint ? args.slice(1) : args;
|
|
504
|
+
if (rest.length !== 1 || !rest[0] || rest[0].startsWith('--'))
|
|
505
|
+
throw new Error('brief takes one draft file: niyam brief [--lint] <draft.md>');
|
|
506
|
+
return { draft: rest[0], lint };
|
|
507
|
+
}
|
|
508
|
+
export async function brief(sys, io, args) {
|
|
509
|
+
const { draft, lint } = briefArgs(args);
|
|
510
|
+
const h = here(sys);
|
|
511
|
+
const { branch, changedFiles } = collect(sys, h, h.base);
|
|
512
|
+
if (!lint)
|
|
513
|
+
return (await openDraft(sys, io, h, draft, 'handed-off', branch, changedFiles)) === undefined ? 1 : 0;
|
|
514
|
+
const rel = draftAt(h, sys, draft);
|
|
515
|
+
if (rel === null || !sys.exists(`${h.root}/${rel}`)) {
|
|
516
|
+
io.err(`✗ no brief draft in the repository at ${draft}`);
|
|
517
|
+
return 1;
|
|
518
|
+
}
|
|
519
|
+
const result = lintDraft(sys.read(`${h.root}/${rel}`), branch, { ...lintContext(h, changedFiles), yaml: await loadYaml(), disposition: 'handed-off', ...(h.settings.template ? { template: h.settings.template } : {}) });
|
|
520
|
+
if (result.ok) {
|
|
521
|
+
io.out(`✓ ${draft} is a brief this branch can open`);
|
|
522
|
+
return 0;
|
|
523
|
+
}
|
|
524
|
+
for (const problem of result.problems)
|
|
525
|
+
io.err(`✗ ${problem}`);
|
|
526
|
+
return 1;
|
|
527
|
+
}
|
package/dist/issue-types.js
CHANGED
|
@@ -359,8 +359,8 @@ export async function applyTypes(sys, io, token, plan) {
|
|
|
359
359
|
io.out(`✓ issue types in ${org}: ${names(ISSUE_TYPES)}`);
|
|
360
360
|
const archived = [...new Set(plan.held.map((issue) => issue.repo))];
|
|
361
361
|
return [
|
|
362
|
-
...(archived.length > 0 ? [`
|
|
363
|
-
...(plan.late.length > 0 ? [`
|
|
362
|
+
...(archived.length > 0 ? [`Once: unarchive ${archived.join(', ')}, then run niyam onboard again, so it retypes ${plan.held.map((issue) => `${issue.repo}#${issue.number}`).join(', ')}.`] : []),
|
|
363
|
+
...(plan.late.length > 0 ? [`Once: run niyam onboard again, so it retypes ${plan.late.map((issue) => `${issue.repo}#${issue.number}`).join(', ')}, which it found after showing its plan.`] : []),
|
|
364
364
|
];
|
|
365
365
|
}
|
|
366
366
|
/** Sets a type enabled or disabled, sending its name, description and colour back, since GitHub's PUT takes them all. */
|