@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.
@@ -0,0 +1,284 @@
1
+ import { isAbsolute, relative, resolve } from 'node:path';
2
+ import { SETTINGS_PATH } from './agent.js';
3
+ const DEFAULTS = { file: '.cubic-dismiss', subject: 'chore(review): dismiss {count} Cubic finding{s}', ownerBasis: 'owner' };
4
+ const WIDTH = 78;
5
+ const where = `${SETTINGS_PATH}: "cubicDismiss"`;
6
+ /** The settings, its defaults filled in; throws on a malformed entry. */
7
+ export function dismissSettings(raw) {
8
+ const value = typeof raw === 'object' && raw !== null ? raw.cubicDismiss : undefined;
9
+ if (value === undefined)
10
+ return { ...DEFAULTS };
11
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
12
+ throw new Error(`${where} must be an object`);
13
+ const { file = DEFAULTS.file, subject = DEFAULTS.subject, ownerBasis = DEFAULTS.ownerBasis, ...rest } = value;
14
+ const extra = Object.keys(rest)[0];
15
+ if (extra !== undefined)
16
+ throw new Error(`${where} has an unknown key "${extra}"; it takes "file", "subject" and "ownerBasis"`);
17
+ if (typeof file !== 'string' || !/^(?!\/)(?!.*(?:^|\/)\.\.?(?:\/|$))[\w@+=,.\/-]+$/.test(file))
18
+ throw new Error(`${where}.file must be a path in the repository`);
19
+ if (typeof subject !== 'string' || !subject.trim() || /[\r\n]/.test(subject))
20
+ throw new Error(`${where}.subject must be one line`);
21
+ if (typeof ownerBasis !== 'string' || !/^[a-z][\w-]*$/.test(ownerBasis) || ownerBasis === 'evidence')
22
+ throw new Error(`${where}.ownerBasis must be one lower-case word other than "evidence"`);
23
+ return { file, subject, ownerBasis };
24
+ }
25
+ const USAGE = 'cubic-dismiss (--evidence <what proves it wrong> | --decision <where the owner chose>) ((--title <exact title> --reason <why>)... | --from <file.json>) [--context <work id>]';
26
+ /** The arguments: one basis, and titles paired in order with their reasons, from argv or a file. */
27
+ export function dismissArgs(args) {
28
+ const titles = [];
29
+ const reasons = [];
30
+ const once = new Map();
31
+ for (let i = 0; i < args.length; i++) {
32
+ const token = args[i];
33
+ const eq = token.startsWith('--') ? token.indexOf('=') : -1;
34
+ const name = eq > 0 ? token.slice(0, eq) : token;
35
+ if (!['--evidence', '--decision', '--title', '--reason', '--from', '--context'].includes(name))
36
+ throw new Error(`unexpected argument "${token}"`);
37
+ const value = eq > 0 ? token.slice(eq + 1) : args[++i];
38
+ if (value === undefined || value.startsWith('--'))
39
+ throw new Error(`${name} needs a value`);
40
+ if (name === '--title')
41
+ titles.push(value);
42
+ else if (name === '--reason')
43
+ reasons.push(value);
44
+ else if (once.has(name))
45
+ throw new Error(`${name} is given twice`);
46
+ else
47
+ once.set(name, value);
48
+ }
49
+ if (titles.length !== reasons.length)
50
+ throw new Error('each --title needs its own --reason');
51
+ const evidence = once.get('--evidence');
52
+ const decision = once.get('--decision');
53
+ if ((evidence === undefined) === (decision === undefined))
54
+ throw new Error(`give exactly one of --evidence or --decision: ${USAGE}`);
55
+ const flag = evidence === undefined ? '--decision' : '--evidence';
56
+ const cite = (evidence ?? decision);
57
+ if (!cite.trim())
58
+ throw new Error(`${flag} is blank`);
59
+ const context = once.get('--context');
60
+ // Both land in a comment line; a line break would start an active title.
61
+ for (const [name, value] of [[flag, cite], ['--context', context]]) {
62
+ if (value !== undefined && /[\r\n]/.test(value))
63
+ throw new Error(`${name} spans lines`);
64
+ }
65
+ const from = once.get('--from');
66
+ if (titles.length === 0 && from === undefined)
67
+ throw new Error(`nothing to dismiss: ${USAGE}`);
68
+ return {
69
+ titles: titles.map((title, index) => ({ title, reason: reasons[index] })),
70
+ basis: evidence === undefined ? 'decision' : 'evidence',
71
+ cite,
72
+ ...(context === undefined ? {} : { context }),
73
+ ...(from === undefined ? {} : { from }),
74
+ };
75
+ }
76
+ const FROM_SHAPE = '--from must hold a JSON array of { "title", "reason" } strings';
77
+ /** `--from`'s findings: a JSON array of `{ title, reason }`. */
78
+ export function parseFrom(text) {
79
+ let json;
80
+ try {
81
+ json = JSON.parse(text);
82
+ }
83
+ catch {
84
+ throw new Error(`${FROM_SHAPE}; it is not JSON`);
85
+ }
86
+ if (!Array.isArray(json) || !json.every((one) => typeof one?.title === 'string' && typeof one.reason === 'string'))
87
+ throw new Error(FROM_SHAPE);
88
+ return json.map(({ title, reason }) => ({ title, reason }));
89
+ }
90
+ /** The titles a dismiss file holds: every line that is neither blank nor a comment. */
91
+ export function parseDismissals(text) {
92
+ return new Set(text
93
+ .split('\n')
94
+ .map((line) => line.replace(/\r$/, ''))
95
+ .filter((line) => line !== '' && !line.startsWith('#')));
96
+ }
97
+ /** Words that mark a true finding left unfixed: the owner's call, never the agent's on evidence. */
98
+ const DEFERRED = /pre-?existing|predates|out of scope|\blater\b|follow-?up/i;
99
+ /** Why a finding cannot be dismissed, or null when it can; the deferral words are looked for in what the agent wrote, not in the title. */
100
+ export function refusal(dismissal, dismissed, options) {
101
+ const { title, reason } = dismissal;
102
+ if (title.trim() === '')
103
+ return 'a title is empty';
104
+ if (/[\r\n]/.test(title))
105
+ return `"${title}" spans lines; a dismissal is one line`;
106
+ if (title.startsWith('#'))
107
+ return `"${title}" starts with #, which the dismiss file reads as a comment`;
108
+ if (reason.trim() === '')
109
+ return `"${title}" has no reason`;
110
+ if (dismissed.has(title))
111
+ return `"${title}" is already dismissed`;
112
+ const deferred = options.basis === 'evidence' ? DEFERRED.exec([reason, options.cite, options.context ?? ''].join('\n')) : null;
113
+ if (deferred)
114
+ return `"${title}": the reason, evidence or context says "${deferred[0]}": a true finding left unfixed is the owner's call; use --decision`;
115
+ return null;
116
+ }
117
+ /**
118
+ * Whether evidence names something there: a title already dismissed, a commit HEAD contains named by its full
119
+ * 40-hex id, or a path at HEAD (a trailing `#section` or `:line` dropped). Seven to 39 hex digits read as an
120
+ * abbreviated commit and resolve as nothing, so one is never taken for a path. git failing throws, never reading
121
+ * as evidence that does not resolve.
122
+ */
123
+ export function resolves(cite, dismissed, git) {
124
+ if (dismissed.has(cite))
125
+ return true;
126
+ if (/^[0-9a-f]{40}$/i.test(cite)) {
127
+ if (git(['rev-list', '--no-walk', '--ignore-missing', cite]).trim() === '')
128
+ return false;
129
+ return git(['rev-list', '-n', '1', cite, '^HEAD']).trim() === '';
130
+ }
131
+ if (/^[0-9a-f]{7,39}$/i.test(cite))
132
+ return false;
133
+ const path = cite.replace(/#.*$/, '').replace(/:\d+(?:-\d+)?$/, '');
134
+ // Only plain repository-relative segments: no root, `.`, `..`, empty segment, leading `-` or revision syntax.
135
+ if (!path.split('/').every((segment) => /^(?!\.+$)(?!-)[\w@+=,.-]+$/.test(segment)))
136
+ return false;
137
+ return git(['ls-tree', '--full-tree', '--name-only', 'HEAD', '--', path]).trim() !== '';
138
+ }
139
+ /** One dismissal as dismiss-file lines: the dated reason, wrapped, then the title. */
140
+ export function formatEntry(dismissal, date, options) {
141
+ const basis = options.basis === 'evidence' ? `evidence: ${options.cite}` : options.cite;
142
+ const cited = [options.context, basis].filter(Boolean).join('; ');
143
+ const lines = [];
144
+ let line = `# ${date} (${cited}):`;
145
+ for (const word of dismissal.reason.split(/\s+/).filter(Boolean)) {
146
+ if (line.length + 1 + word.length > WIDTH) {
147
+ lines.push(line);
148
+ line = '#';
149
+ }
150
+ line += ` ${word}`;
151
+ }
152
+ return [...lines, line, dismissal.title];
153
+ }
154
+ const clip = (text) => (text.length > 96 ? `${text.slice(0, 93)}...` : text);
155
+ /** The subject, a body citing the basis and listing up to 12 titles, and the trailer. */
156
+ export function commitMessage(options, settings) {
157
+ const count = options.dismissals.length;
158
+ const subject = settings.subject.replaceAll('{count}', String(count)).replaceAll('{s}', count === 1 ? '' : 's');
159
+ const titles = options.dismissals.slice(0, 12).map(({ title }) => `- ${clip(title)}`);
160
+ const label = options.basis === 'evidence' ? 'Evidence' : 'Decision';
161
+ return {
162
+ subject,
163
+ body: [clip(`${label}: ${options.cite}`), ...titles].join('\n'),
164
+ trailer: `Dismissal-Basis: ${options.basis === 'evidence' ? 'evidence' : settings.ownerBasis}`,
165
+ };
166
+ }
167
+ function localDate(now) {
168
+ const pad = (value) => String(value).padStart(2, '0');
169
+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
170
+ }
171
+ /** `niyam cubic-dismiss`: appends, stages the dismiss file alone and commits it; 0 committed, 1 refused or failed. */
172
+ export function cubicDismiss(sys, io, args) {
173
+ const parsed = dismissArgs(args);
174
+ const git = (gitArgs, cwd = sys.cwd) => {
175
+ const run = sys.exec('git', gitArgs, { cwd });
176
+ if (run.code !== 0)
177
+ throw new Error(`git ${gitArgs[0]} failed: ${run.stderr.trim() || `exit ${run.code}`}`);
178
+ return run.stdout;
179
+ };
180
+ const root = git(['rev-parse', '--show-toplevel']).trim();
181
+ const run = (gitArgs) => git(gitArgs, root);
182
+ const settingsFile = `${root}/${SETTINGS_PATH}`;
183
+ const settings = dismissSettings(sys.exists(settingsFile) ? JSON.parse(sys.read(settingsFile)) : {});
184
+ let fromFile = [];
185
+ if (parsed.from !== undefined) {
186
+ // Its titles are committed and pushed, and the allow rule runs this without a prompt: only a file in the repository.
187
+ const at = resolve(sys.cwd, parsed.from);
188
+ const inside = relative(root, at);
189
+ if (!inside || inside.startsWith('..') || isAbsolute(inside)) {
190
+ io.err(`✗ --from must be a file in the repository: ${parsed.from}`);
191
+ return 1;
192
+ }
193
+ fromFile = parseFrom(sys.read(at));
194
+ }
195
+ const { titles, from: _from, ...rest } = parsed;
196
+ const options = { ...rest, dismissals: [...titles, ...fromFile] };
197
+ if (options.dismissals.length === 0) {
198
+ io.err(`✗ ${parsed.from} holds nothing to dismiss`);
199
+ return 1;
200
+ }
201
+ const file = settings.file;
202
+ const path = `${root}/${file}`;
203
+ const changed = run(['status', '--porcelain', '--', file]).trim();
204
+ if (changed) {
205
+ io.err(`✗ ${file} already differs from HEAD (${changed}); commit or restore it first`);
206
+ return 1;
207
+ }
208
+ // The first dismissal starts the file; undone, it is removed, since an empty file left behind is untracked.
209
+ const existed = sys.exists(path);
210
+ const before = existed ? sys.read(path) : '';
211
+ const dismissed = parseDismissals(before);
212
+ if (options.basis === 'evidence' && !resolves(options.cite, dismissed, run)) {
213
+ io.err(`✗ refused: --evidence "${options.cite}" is no path at HEAD, commit HEAD contains (by its full 40-hex id), or dismissed title; nothing was written`);
214
+ return 1;
215
+ }
216
+ for (const dismissal of options.dismissals) {
217
+ const why = refusal(dismissal, dismissed, options);
218
+ if (why !== null) {
219
+ io.err(`✗ refused: ${why}; nothing was written`);
220
+ return 1;
221
+ }
222
+ dismissed.add(dismissal.title);
223
+ }
224
+ const added = options.dismissals.flatMap((dismissal) => formatEntry(dismissal, localDate(sys.now()), options));
225
+ const written = `${before}${before === '' || before.endsWith('\n') ? '' : '\n'}${added.join('\n')}\n`;
226
+ const head = run(['rev-parse', 'HEAD']).trim();
227
+ sys.write(path, written);
228
+ // A commit that landed is kept even when git reports a failure; only one that did not is undone, and a cleanup
229
+ // that cannot finish is named, so a leftover line is never taken as recorded: a rerun refuses a changed file.
230
+ const undo = () => {
231
+ let now;
232
+ try {
233
+ now = run(['rev-parse', 'HEAD']).trim();
234
+ if (now === head) {
235
+ if (existed)
236
+ sys.write(path, before);
237
+ else
238
+ sys.remove(path);
239
+ run(['reset', '-q', 'HEAD', '--', file]);
240
+ const left = run(['status', '--porcelain', '--', file]).trim();
241
+ io.err(left ? `✗ the commit failed and ${file} still differs from HEAD (${left}); check git status and git log` : `✗ the commit failed; ${file} is restored`);
242
+ return;
243
+ }
244
+ }
245
+ catch (error) {
246
+ io.err(`✗ the commit failed and restoring ${file} failed too (${error instanceof Error ? error.message : String(error)}); it may still hold the new lines: check git status`);
247
+ return;
248
+ }
249
+ io.err(`✗ git reported a failure, but the commit landed (${now}); ${file} is left as committed: check git log`);
250
+ };
251
+ const { subject, body, trailer } = commitMessage(options, settings);
252
+ let committed;
253
+ try {
254
+ run(['add', '--', file]);
255
+ committed = sys.exec('git', ['commit', '--only', '-m', subject, '-m', body, '-m', trailer, '--', file], { cwd: root });
256
+ }
257
+ catch (error) {
258
+ undo();
259
+ throw error;
260
+ }
261
+ const output = `${committed.stdout}${committed.stderr}`.trimEnd();
262
+ if (output)
263
+ io.out(output);
264
+ if (committed.code !== 0) {
265
+ undo();
266
+ return 1;
267
+ }
268
+ // Nothing locks the file, so a process writing it meanwhile would have its text committed: never report success
269
+ // for text this did not write. A read-back that cannot run leaves the landed commit standing, named.
270
+ let recorded;
271
+ try {
272
+ recorded = run(['show', `HEAD:${file}`]);
273
+ }
274
+ catch {
275
+ io.err(`! committed, but ${file} could not be read back from HEAD to check it: check git show HEAD`);
276
+ return 0;
277
+ }
278
+ if (recorded !== written) {
279
+ io.err(`✗ the commit holds a ${file} this did not write; something changed it meanwhile: check git show HEAD`);
280
+ return 1;
281
+ }
282
+ io.out(`✓ committed ${options.dismissals.length} dismissal(s) alone`);
283
+ return 0;
284
+ }
package/dist/doctor.js CHANGED
@@ -246,7 +246,7 @@ async function cloudDoctor(sys, io, named) {
246
246
  const { pinned, scripted, workflow, script } = repoReleases(sys, root);
247
247
  setupFile = script;
248
248
  if (scripted === undefined) {
249
- session.push({ mark: '✗', text: `${script} missing, or not the file onboard writes, so the Setup script installs no niyam`, fix: ONBOARD });
249
+ session.push({ mark: '✗', text: `${script} missing, or not the file onboard writes, so a session without niyam cannot install it`, fix: ONBOARD });
250
250
  }
251
251
  else if (pinned === undefined) {
252
252
  session.push({ mark: '▲', text: `${workflow} is missing or pins no one version, so ${script} is not checked against it`, fix: ONBOARD });
@@ -271,11 +271,8 @@ async function cloudDoctor(sys, io, named) {
271
271
  }
272
272
  session.push(ranFromSetup(sys)
273
273
  ? { mark: '✓', text: `the Setup script runs ${fileFromSetup(sys) ?? "the repo's cloud setup file"}` }
274
- : {
275
- mark: '▲',
276
- text: `${FROM_SETUP} missing, so the cloud environment's Setup script does not run ${setupFile}`,
277
- fix: "paste what niyam cloud-setup prints into the cloud environment's Setup script, once",
278
- });
274
+ : // The SessionStart hook installs niyam where the Setup script does not (P-60): the paste only makes sessions start faster.
275
+ { mark: '✓', text: `the SessionStart hook installs niyam from ${setupFile} when a session has none; the Setup script does not run it, which only makes sessions start slower` });
279
276
  let agents = named === undefined ? undefined : [named];
280
277
  if (agents === undefined && root !== undefined) {
281
278
  try {