agjan 0.0.11 → 0.0.13

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.
Files changed (114) hide show
  1. package/README.md +2 -2
  2. package/bin/agjan.mjs +9 -2
  3. package/dist/adapters/claude-code.js +136 -0
  4. package/dist/adapters/copilot.js +110 -0
  5. package/dist/auto.js +24 -0
  6. package/dist/baseline.js +66 -0
  7. package/dist/browser.js +46 -0
  8. package/dist/cli.js +170 -0
  9. package/dist/commands/branch.js +71 -0
  10. package/dist/commands/check.js +424 -0
  11. package/dist/commands/fix.js +122 -0
  12. package/dist/commands/gates.js +475 -0
  13. package/dist/commands/lint.js +76 -0
  14. package/dist/commands/log.js +74 -0
  15. package/dist/commands/map.js +47 -0
  16. package/dist/commands/models.js +90 -0
  17. package/dist/commands/new.js +65 -0
  18. package/dist/commands/pr-summary.js +176 -0
  19. package/dist/commands/progress.js +42 -0
  20. package/dist/commands/report.js +105 -0
  21. package/dist/commands/review.js +149 -0
  22. package/dist/commands/setup.js +393 -0
  23. package/dist/commands/status.js +323 -0
  24. package/dist/commands/ui-test.js +39 -0
  25. package/dist/config.js +114 -0
  26. package/dist/context.js +56 -0
  27. package/dist/copilot-mcp.js +56 -0
  28. package/dist/documents.js +207 -0
  29. package/dist/errors.js +15 -0
  30. package/dist/feature.js +221 -0
  31. package/dist/fix.js +117 -0
  32. package/dist/git.js +88 -0
  33. package/{src/hash.mjs → dist/hash.js} +11 -14
  34. package/dist/hook.js +47 -0
  35. package/dist/json-file.js +26 -0
  36. package/dist/log.js +50 -0
  37. package/dist/managed.js +182 -0
  38. package/dist/mcp-config.js +76 -0
  39. package/dist/mcp.js +187 -0
  40. package/dist/plan.js +40 -0
  41. package/dist/progress-view.js +494 -0
  42. package/dist/progress.js +106 -0
  43. package/dist/qa.js +77 -0
  44. package/dist/review-policy.js +84 -0
  45. package/dist/review.js +534 -0
  46. package/dist/scope.js +34 -0
  47. package/dist/terminal.js +127 -0
  48. package/dist/test-results.js +101 -0
  49. package/dist/tests-map.js +29 -0
  50. package/dist/types.js +5 -0
  51. package/dist/ui.js +136 -0
  52. package/dist/usage.js +116 -0
  53. package/dist/validate.js +46 -0
  54. package/docs/guide.md +80 -40
  55. package/kit/hooks/guard.mjs +48 -119
  56. package/kit/skills/agjan-build/SKILL.md +6 -2
  57. package/kit/skills/agjan-design/SKILL.md +9 -2
  58. package/kit/skills/agjan-fix/SKILL.md +8 -16
  59. package/kit/skills/agjan-map/SKILL.md +8 -16
  60. package/kit/skills/agjan-spec/SKILL.md +24 -17
  61. package/kit/skills/agjan-verify/SKILL.md +50 -16
  62. package/kit/skills/qa-tester/SKILL.md +74 -0
  63. package/kit/templates/agents-block.md +3 -3
  64. package/package.json +11 -3
  65. package/schemas/approvals.schema.json +23 -2
  66. package/schemas/config.schema.json +3 -7
  67. package/schemas/log.schema.json +1 -1
  68. package/schemas/reviews.schema.json +3 -1
  69. package/src/adapters/claude-code.mjs +0 -121
  70. package/src/adapters/copilot.mjs +0 -89
  71. package/src/baseline.mjs +0 -66
  72. package/src/browser.mjs +0 -49
  73. package/src/cli.mjs +0 -165
  74. package/src/commands/branch.mjs +0 -95
  75. package/src/commands/check.mjs +0 -376
  76. package/src/commands/fix.mjs +0 -116
  77. package/src/commands/gates.mjs +0 -267
  78. package/src/commands/lint.mjs +0 -74
  79. package/src/commands/log.mjs +0 -60
  80. package/src/commands/map.mjs +0 -47
  81. package/src/commands/new.mjs +0 -53
  82. package/src/commands/pr-summary.mjs +0 -137
  83. package/src/commands/progress.mjs +0 -40
  84. package/src/commands/report.mjs +0 -115
  85. package/src/commands/review.mjs +0 -141
  86. package/src/commands/setup.mjs +0 -393
  87. package/src/commands/status.mjs +0 -250
  88. package/src/commands/ui-test.mjs +0 -38
  89. package/src/config.mjs +0 -122
  90. package/src/context.mjs +0 -67
  91. package/src/copilot-mcp.mjs +0 -56
  92. package/src/documents.mjs +0 -188
  93. package/src/errors.mjs +0 -16
  94. package/src/feature.mjs +0 -225
  95. package/src/fix.mjs +0 -108
  96. package/src/git.mjs +0 -83
  97. package/src/hook.mjs +0 -48
  98. package/src/json-file.mjs +0 -24
  99. package/src/log.mjs +0 -51
  100. package/src/managed.mjs +0 -178
  101. package/src/mcp-config.mjs +0 -83
  102. package/src/mcp.mjs +0 -147
  103. package/src/plan.mjs +0 -45
  104. package/src/progress-view.mjs +0 -466
  105. package/src/progress.mjs +0 -85
  106. package/src/review-policy.mjs +0 -91
  107. package/src/review.mjs +0 -416
  108. package/src/scope.mjs +0 -30
  109. package/src/terminal.mjs +0 -118
  110. package/src/test-results.mjs +0 -111
  111. package/src/tests-map.mjs +0 -29
  112. package/src/ui.mjs +0 -136
  113. package/src/usage.mjs +0 -118
  114. package/src/validate.mjs +0 -41
@@ -0,0 +1,475 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { join, relative } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { writeJson } from '../json-file.js';
5
+ import { appendLog, readLog } from '../log.js';
6
+ import { APPROVALS_FILE, FEATURES_DIR, gateReview, loadFeature, selectFeature } from '../feature.js';
7
+ import { documentProblems, designProblems } from '../validate.js';
8
+ import { AgjanError, UsageError } from '../errors.js';
9
+ import { blink, mark, tone } from '../ui.js';
10
+ import { git } from '../git.js';
11
+ import { acceptanceState, verifyState } from '../progress.js';
12
+ import { NOT_ACCEPTED, runChecks } from './check.js';
13
+ import { qaProblem } from '../qa.js';
14
+ import { AUTO_DEFAULT_FILE, readAutoDefault, removeAutoDefault, writeAutoDefault } from '../auto.js';
15
+ function short(hash) {
16
+ return hash ? hash.slice('sha256:'.length, 'sha256:'.length + 12) : '-';
17
+ }
18
+ function refuse(what, problems) {
19
+ throw new AgjanError(`cannot ${what}:\n${problems.map((p) => ` - ${p}`).join('\n')}`);
20
+ }
21
+ /** The gate's review once nothing stands in its way; a ready gate always has one. */
22
+ function ready(what, { problems, record }) {
23
+ if (problems.length || !record)
24
+ refuse(what, problems.length ? problems : ['no review recorded']);
25
+ return record;
26
+ }
27
+ function save(ctx, feature, event, fields) {
28
+ writeJson(join(feature.dir, APPROVALS_FILE), feature.approvals);
29
+ appendLog(feature.dir, ctx.now(), event, fields);
30
+ }
31
+ /**
32
+ * One line of a confirmation: `label text`, the label in gray like the rows of
33
+ * `status`; a line that continues the one before (leading spaces) stays as it is.
34
+ */
35
+ function labeled(ctx, line) {
36
+ const match = /^(\S+)(\s+)(.*)$/.exec(line);
37
+ return match ? ` ${ctx.style.gray(match[1])}${match[2]}${match[3]}` : ` ${line}`;
38
+ }
39
+ /** Shows what is being approved and asks the human to type the feature key (design 9.4). */
40
+ async function confirmGate(ctx, feature, title, lines) {
41
+ const logo = mark(ctx.style, ctx.kit, 'a human decision, recorded with your name');
42
+ for (const line of logo)
43
+ ctx.out(line);
44
+ await blink(ctx, logo);
45
+ const summary = [
46
+ ...(logo.length ? [] : ['']),
47
+ ctx.style.bold(`agjan: ${title}`),
48
+ labeled(ctx, `feature ${ctx.style.bold(feature.slug)} (${ctx.style.cyan(feature.key)})`),
49
+ ...lines.map((l) => labeled(ctx, l)),
50
+ labeled(ctx, `approver ${ctx.style.bold(ctx.email())}`),
51
+ '',
52
+ ].join('\n');
53
+ if (!ctx.confirm(summary, feature.key)) {
54
+ ctx.out(ctx.style.yellow('cancelled, nothing recorded'));
55
+ return false;
56
+ }
57
+ return true;
58
+ }
59
+ /** One line, no control characters, at most 200 characters. */
60
+ export function cleanMessage(text) {
61
+ return String(text ?? '').replace(/[\x00-\x1f\x7f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 200);
62
+ }
63
+ /** The commit message the agent proposed when it handed `gate` over (`log --gate-requested --message`). */
64
+ function proposedMessage(feature, gate) {
65
+ const request = readLog(feature.dir).findLast((e) => e.event === 'gate-requested' && e.gate === gate);
66
+ return cleanMessage(request?.message);
67
+ }
68
+ /**
69
+ * After a recorded decision: commits the feature folder (the approved documents and the
70
+ * record) with a message the human confirms or edits. Only that folder goes into the
71
+ * commit, whatever else is staged; the pre-commit hook still runs. A failed or skipped
72
+ * commit leaves the decision recorded and says how to commit it.
73
+ */
74
+ async function commitRecord(ctx, feature, values, proposal) {
75
+ const s = ctx.style;
76
+ const folder = relative(ctx.root, feature.dir).split('\\').join('/');
77
+ const manual = s.yellow(`not committed; commit ${folder}/ yourself`);
78
+ if (values['no-commit'])
79
+ return ctx.out(manual);
80
+ if (!git(ctx.root, ['status', '--porcelain', '--', folder]).trim())
81
+ return undefined;
82
+ const message = cleanMessage(await ctx.edit(`${s.bold('Commit message')} (Enter to commit, empty to skip): `, proposal));
83
+ if (!message)
84
+ return ctx.out(manual);
85
+ git(ctx.root, ['add', '-A', '--', folder]);
86
+ const result = spawnSync('git', ['commit', '-q', '-m', message, '--', folder], { cwd: ctx.root, encoding: 'utf8' });
87
+ if (result.status !== 0) {
88
+ ctx.out(`${result.stdout ?? ''}${result.stderr ?? ''}`.trimEnd(), s.red(`the commit failed; the decision is recorded but ${folder}/ is not committed`));
89
+ return undefined;
90
+ }
91
+ const sha = git(ctx.root, ['rev-parse', '--short', 'HEAD']).trim();
92
+ return ctx.out(`${s.green('committed')} ${s.gray(sha)} ${message}`);
93
+ }
94
+ function reviewLine(ctx, review) {
95
+ const notes = review.findings?.length ? `, ${review.findings.length} finding(s)` : '';
96
+ return `review ${review.id} ${review.step} round ${review.round}: ${tone(ctx.style, review.verdict)}${notes}`;
97
+ }
98
+ function specGateProblems(feature) {
99
+ const problems = [];
100
+ if (!feature.spec)
101
+ problems.push('spec.md does not exist');
102
+ else
103
+ problems.push(...feature.spec.parsed.problems.map((p) => `spec.md: ${p}`));
104
+ return problems;
105
+ }
106
+ function designGateProblems(ctx, feature) {
107
+ const problems = [];
108
+ if (!feature.design)
109
+ problems.push('design.md does not exist');
110
+ if (!feature.tasks)
111
+ problems.push('tasks.md does not exist');
112
+ problems.push(...documentProblems(feature).filter((p) => !p.startsWith('spec.md')));
113
+ problems.push(...designProblems(feature, ctx.config));
114
+ return problems;
115
+ }
116
+ /** The gate a feature waits for: 'spec', 'spec design' (light mode) or 'design'; null in Build. */
117
+ export function pendingGate(feature) {
118
+ if (feature.stage === 'spec')
119
+ return feature.design?.parsed.mode === 'light' ? 'spec design' : 'spec';
120
+ if (feature.stage === 'design')
121
+ return 'design';
122
+ return null;
123
+ }
124
+ /**
125
+ * Gate 3 (decision 77): the human accepts the verified feature. Ready when the final
126
+ * verify review is current and `check --ci` has no error but the missing acceptance.
127
+ */
128
+ function verifyReadiness(ctx, feature) {
129
+ const problems = [];
130
+ if (feature.stage !== 'build')
131
+ return { problems: [`the feature is in ${feature.stage}; it is accepted after /agjan-verify`], record: null };
132
+ const qa = qaProblem(ctx.root, ctx.config, feature);
133
+ if (qa)
134
+ problems.push(qa);
135
+ const verify = verifyState(ctx.root, ctx.config, feature);
136
+ if (verify.state === 'none')
137
+ problems.push('no final verify review recorded: /agjan-verify');
138
+ else if (verify.state === 'blocked')
139
+ problems.push(`the final verify review ${verify.record.id} is blocked`);
140
+ else if (verify.state === 'stale')
141
+ problems.push(`files changed after the final verify review ${verify.record.id}: /agjan-verify again`);
142
+ else if (acceptanceState(ctx.root, ctx.config, feature, verify).state === 'accepted')
143
+ problems.push(`already accepted (verify review ${verify.record.id}, unchanged since)`);
144
+ if (verify.state === 'current') {
145
+ const { report } = runChecks(ctx, 'ci', feature.slug);
146
+ for (const item of report.items) {
147
+ if (item.level === 'error' && !item.message.startsWith(NOT_ACCEPTED))
148
+ problems.push(`check --ci: ${item.message}`);
149
+ }
150
+ }
151
+ return { problems, record: verify.record };
152
+ }
153
+ /**
154
+ * Everything that stands between a feature and the approval of `gate`, shared by
155
+ * `approve`, `status` and `log --gate-requested`. No problems means the gate is ready.
156
+ */
157
+ export function gateReadiness(ctx, feature, gate) {
158
+ if (gate === 'verify')
159
+ return verifyReadiness(ctx, feature);
160
+ const problems = [];
161
+ let review;
162
+ if (gate === 'spec') {
163
+ if (feature.state.spec === 'approved')
164
+ problems.push('spec.md is already approved and unchanged');
165
+ problems.push(...specGateProblems(feature));
166
+ review = gateReview(feature, 'spec');
167
+ if (feature.design?.parsed.mode === 'light')
168
+ problems.push("design.md is in light mode: approve both together with 'agjan approve spec design'");
169
+ }
170
+ else if (gate === 'design') {
171
+ if (feature.state.spec !== 'approved')
172
+ problems.push(`the spec must be approved first (it is ${feature.state.spec})`);
173
+ if (feature.state.design === 'approved')
174
+ problems.push('design.md and tasks.md are already approved and unchanged');
175
+ problems.push(...designGateProblems(ctx, feature));
176
+ if (feature.design?.parsed.mode === 'light')
177
+ problems.push("light-mode designs are approved together with the spec ('agjan approve spec design')");
178
+ review = gateReview(feature, 'design');
179
+ }
180
+ else {
181
+ if (feature.state.spec === 'approved' && feature.state.design === 'approved')
182
+ problems.push('spec and design are already approved and unchanged');
183
+ problems.push(...specGateProblems(feature), ...designGateProblems(ctx, feature));
184
+ if (feature.design && feature.design.parsed.mode !== 'light')
185
+ problems.push("design.md is in full mode: approve the spec first, then 'agjan approve design'");
186
+ review = gateReview(feature, 'design');
187
+ if (review.record && review.record.step !== 'design:light')
188
+ problems.push(`the latest review is ${review.record.step}; a combined approval needs a design:light review`);
189
+ }
190
+ problems.push(...review.problems);
191
+ return { problems, record: review.record };
192
+ }
193
+ /**
194
+ * Stamps the documents of a spec or design gate as approved by `by` (a person's email, or
195
+ * 'auto' with `enabledBy` in auto mode). A new spec stamp invalidates the design: its
196
+ * spec_hash no longer matches.
197
+ */
198
+ function stampGate(feature, gate, at, by, enabledBy) {
199
+ const who = enabledBy ? { by, enabled_by: enabledBy } : { by };
200
+ const spec = feature.spec;
201
+ if (gate === 'spec' || gate === 'spec design')
202
+ feature.approvals.approvals.spec = { hash: spec.hash, at_utc: at, ...who };
203
+ if (gate === 'design' || gate === 'spec design') {
204
+ feature.approvals.approvals.design = { hash: feature.designHash, spec_hash: spec.hash, at_utc: at, ...who };
205
+ }
206
+ }
207
+ /** The gates auto mode approves (decision 79): every gate but the acceptance. */
208
+ export const AUTO_GATES = ['spec', 'design', 'spec design'];
209
+ /**
210
+ * Auto mode (decision 79): when the feature's auto mode is on, the gate the agent
211
+ * requests is approved at once, marked `by: auto` with the person who switched it on.
212
+ * Only for a ready gate; never for `verify`. Returns false when auto mode does not apply.
213
+ */
214
+ export function approveAutomatically(ctx, feature, gate) {
215
+ const auto = feature.approvals.auto;
216
+ if (!auto || !AUTO_GATES.includes(gate))
217
+ return false;
218
+ ready(`approve ${gate} automatically`, gateReadiness(ctx, feature, gate));
219
+ stampGate(feature, gate, ctx.now(), 'auto', auto.by);
220
+ save(ctx, feature, 'approved', { gate, auto: true });
221
+ return true;
222
+ }
223
+ async function approveSpec(ctx, feature, values) {
224
+ const record = ready('approve the spec', gateReadiness(ctx, feature, 'spec'));
225
+ const spec = feature.spec;
226
+ const previous = feature.state.spec === 'stale' ? ' (re-approval: changed since the last approval)' : '';
227
+ if (!(await confirmGate(ctx, feature, `approve spec${previous}`, [`spec.md ${short(spec.hash)}`, reviewLine(ctx, record)])))
228
+ return 1;
229
+ stampGate(feature, 'spec', ctx.now(), ctx.email());
230
+ save(ctx, feature, 'approved', { gate: 'spec' });
231
+ ctx.out(ctx.style.green(`approved spec of ${feature.slug}`));
232
+ await commitRecord(ctx, feature, values, proposedMessage(feature, 'spec') || `${feature.key}: approve spec`);
233
+ return 0;
234
+ }
235
+ async function approveDesign(ctx, feature, values) {
236
+ const record = ready('approve the design', gateReadiness(ctx, feature, 'design'));
237
+ const designHash = feature.designHash;
238
+ const lines = [`design ${short(designHash)} (design.md + tasks.md, mode ${feature.design.parsed.mode})`, reviewLine(ctx, record)];
239
+ if (!(await confirmGate(ctx, feature, 'approve design', lines)))
240
+ return 1;
241
+ stampGate(feature, 'design', ctx.now(), ctx.email());
242
+ save(ctx, feature, 'approved', { gate: 'design' });
243
+ ctx.out(ctx.style.green(`approved design of ${feature.slug}`));
244
+ await commitRecord(ctx, feature, values, proposedMessage(feature, 'design') || `${feature.key}: approve design`);
245
+ return 0;
246
+ }
247
+ async function approveCombined(ctx, feature, values) {
248
+ const record = ready('approve spec and design', gateReadiness(ctx, feature, 'spec design'));
249
+ const spec = feature.spec;
250
+ const designHash = feature.designHash;
251
+ const lines = [
252
+ `spec.md ${short(spec.hash)}`,
253
+ `design ${short(designHash)} (design.md + tasks.md, mode light)`,
254
+ reviewLine(ctx, record),
255
+ ];
256
+ if (!(await confirmGate(ctx, feature, 'approve spec and design (light mode)', lines)))
257
+ return 1;
258
+ stampGate(feature, 'spec design', ctx.now(), ctx.email());
259
+ save(ctx, feature, 'approved', { gate: 'spec design' });
260
+ ctx.out(ctx.style.green(`approved spec and design of ${feature.slug}`));
261
+ await commitRecord(ctx, feature, values, proposedMessage(feature, 'spec design') || `${feature.key}: approve spec and design`);
262
+ return 0;
263
+ }
264
+ async function approveVerify(ctx, feature, values) {
265
+ const record = ready('accept the feature', gateReadiness(ctx, feature, 'verify'));
266
+ const manual = feature.spec.parsed.acs.filter((ac) => ac.verification === 'manual').map((ac) => ac.id);
267
+ const previous = acceptanceState(ctx.root, ctx.config, feature).state === 'stale' ? ' (again: changed since the last acceptance)' : '';
268
+ const lines = [
269
+ `change ${short(record.tree_hash)} (the files the verify review saw)`,
270
+ reviewLine(ctx, record),
271
+ manual.length ? `manual ${manual.join(', ')}: confirm that you tried them` : 'manual none (every AC has an automated test)',
272
+ ];
273
+ if (!(await confirmGate(ctx, feature, `accept the feature${previous}: implemented and verified`, lines)))
274
+ return 1;
275
+ feature.approvals.approvals.verify = { review: record.id, tree_hash: record.tree_hash, manual, at_utc: ctx.now(), by: ctx.email() };
276
+ save(ctx, feature, 'approved', { gate: 'verify' });
277
+ ctx.out(ctx.style.green(`accepted ${feature.slug}: implemented and verified`));
278
+ await commitRecord(ctx, feature, values, proposedMessage(feature, 'verify') || `${feature.key}: accept the feature`);
279
+ return 0;
280
+ }
281
+ async function approveAmendment(ctx, feature, id, values) {
282
+ const design = feature.approvals.approvals.design;
283
+ if (feature.state.design !== 'approved' || !design)
284
+ throw new AgjanError(`amendments need an approved design (it is ${feature.state.design})`);
285
+ const amendment = feature.approvals.amendments.find((a) => a.id === id);
286
+ if (!amendment)
287
+ throw new AgjanError(`no amendment ${id} in ${feature.slug}`);
288
+ if (amendment.approved_at_utc && amendment.design_hash === design.hash) {
289
+ throw new AgjanError(`${id} is already approved`);
290
+ }
291
+ const lines = [`amendment ${id} for ${amendment.task}`, `paths ${amendment.paths.join(', ')}`, `reason ${amendment.reason}`];
292
+ if (!(await confirmGate(ctx, feature, 'approve scope amendment', lines)))
293
+ return 1;
294
+ Object.assign(amendment, { approved_at_utc: ctx.now(), by: ctx.email(), design_hash: design.hash });
295
+ save(ctx, feature, 'approved', { gate: 'amendment', amendment: id });
296
+ ctx.out(ctx.style.green(`approved ${id}`));
297
+ await commitRecord(ctx, feature, values, `${feature.key}: approve amendment ${id}`);
298
+ return 0;
299
+ }
300
+ const FEATURE_OPTION = { feature: { type: 'string' }, 'no-commit': { type: 'boolean' } };
301
+ /** agjan approve spec | design | spec design | verify | amendment <id> [--feature <slug>] [--no-commit] */
302
+ export function approve(ctx, argv) {
303
+ const { values, positionals } = parseArgs({ args: argv, options: FEATURE_OPTION, allowPositionals: true });
304
+ const what = positionals.join(' ');
305
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
306
+ if (what === 'spec')
307
+ return approveSpec(ctx, feature, values);
308
+ if (what === 'design')
309
+ return approveDesign(ctx, feature, values);
310
+ if (what === 'spec design' || what === 'design spec')
311
+ return approveCombined(ctx, feature, values);
312
+ if (what === 'verify')
313
+ return approveVerify(ctx, feature, values);
314
+ if (positionals[0] === 'amendment' && positionals.length === 2)
315
+ return approveAmendment(ctx, feature, positionals[1], values);
316
+ throw new UsageError('usage: agjan approve spec | design | spec design | verify | amendment <id> [--feature <slug>] [--no-commit]');
317
+ }
318
+ /**
319
+ * agjan auto on|off --default: the person's default for this checkout (decision 79). Every
320
+ * feature created here afterwards starts with auto mode on; existing features keep theirs.
321
+ * Local (git-ignored), so teammates are not affected. Confirmed by typing `auto`.
322
+ */
323
+ async function autoDefault(ctx, on) {
324
+ const s = ctx.style;
325
+ const current = readAutoDefault(ctx.root);
326
+ if (on && current)
327
+ throw new AgjanError(`your auto mode default is already on (since ${current.at_utc}); new features start in auto mode`);
328
+ if (!on && !current)
329
+ throw new AgjanError('your auto mode default is off');
330
+ const logo = mark(s, ctx.kit, 'a human decision, recorded with your name');
331
+ for (const line of logo)
332
+ ctx.out(line);
333
+ await blink(ctx, logo);
334
+ const summary = [
335
+ ...(logo.length ? [] : ['']),
336
+ s.bold(on ? 'agjan: auto mode for every new feature in this checkout' : 'agjan: auto mode default off'),
337
+ ...(on
338
+ ? [
339
+ `new features created here from now on start with ${s.yellow('auto mode on')}: spec and design`,
340
+ ' pass automatically after their reviews; existing features keep their mode',
341
+ `yours ${s.bold('approve verify')} (the acceptance), accepting findings, amendments, the merge`,
342
+ `local ${s.cyan(AUTO_DEFAULT_FILE)} ${s.gray('(git-ignored)')}: your checkout only, not your teammates'`,
343
+ `off ${s.cyan('npx agjan auto off --default')}; one feature: ${s.cyan('npx agjan auto off')}`,
344
+ ]
345
+ : ['new features created here wait at their gates again; existing ones keep their mode']).map((l) => labeled(ctx, l)),
346
+ labeled(ctx, `by ${s.bold(ctx.email())}`),
347
+ '',
348
+ ].join('\n');
349
+ if (!ctx.confirm(summary, 'auto')) {
350
+ ctx.out(s.yellow('cancelled, nothing changed'));
351
+ return 1;
352
+ }
353
+ if (on) {
354
+ writeAutoDefault(ctx.root, { by: ctx.email(), at_utc: ctx.now() });
355
+ ctx.out(s.green('auto mode on for every new feature in this checkout'));
356
+ }
357
+ else {
358
+ removeAutoDefault(ctx.root);
359
+ ctx.out('auto mode default off: new features wait at their gates again');
360
+ }
361
+ return 0;
362
+ }
363
+ /**
364
+ * agjan auto on|off [--feature <slug>] [--no-commit] (decision 79): a human switches auto
365
+ * mode of one feature on or off, in a terminal. While it is on, the spec and design gates
366
+ * are approved automatically once their reviews pass, and the agent goes on to the next
367
+ * step; the acceptance (`approve verify`), findings, amendments and the merge stay human.
368
+ * With --default: the person's default for new features in this checkout.
369
+ */
370
+ export async function auto(ctx, argv) {
371
+ const { values, positionals } = parseArgs({ args: argv, options: { ...FEATURE_OPTION, default: { type: 'boolean' } }, allowPositionals: true });
372
+ const [what] = positionals;
373
+ const usage = 'usage: agjan auto on|off [--feature <slug>] [--no-commit] | agjan auto on|off --default';
374
+ if (!['on', 'off'].includes(what) || positionals.length !== 1)
375
+ throw new UsageError(usage);
376
+ if (values.default) {
377
+ if (values.feature)
378
+ throw new UsageError(usage);
379
+ return autoDefault(ctx, what === 'on');
380
+ }
381
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
382
+ if (feature.kind !== 'feature')
383
+ throw new AgjanError(`auto mode is for features; ${feature.slug} is a ${feature.kind}`);
384
+ const current = feature.approvals.auto;
385
+ if (what === 'on') {
386
+ if (current)
387
+ throw new AgjanError(`auto mode of ${feature.slug} is already on (since ${current.at_utc}, by ${current.by})`);
388
+ const s = ctx.style;
389
+ const lines = [
390
+ `auto spec and design are ${s.yellow('approved automatically')} once their reviews pass;`,
391
+ ' the agent goes on to the next step without waiting for you',
392
+ `yours ${s.bold('approve verify')} (the acceptance), accepting findings, amendments, the merge`,
393
+ `off ${s.cyan('npx agjan auto off')}, at any time`,
394
+ ];
395
+ if (!(await confirmGate(ctx, feature, 'switch auto mode on for this feature', lines)))
396
+ return 1;
397
+ feature.approvals.auto = { by: ctx.email(), at_utc: ctx.now() };
398
+ save(ctx, feature, 'auto-on', {});
399
+ ctx.out(ctx.style.green(`auto mode on for ${feature.slug}`));
400
+ await commitRecord(ctx, feature, values, `${feature.key}: auto mode on`);
401
+ return 0;
402
+ }
403
+ if (!current)
404
+ throw new AgjanError(`auto mode of ${feature.slug} is off`);
405
+ if (!(await confirmGate(ctx, feature, 'switch auto mode off', ['gates wait for your approval again'])))
406
+ return 1;
407
+ delete feature.approvals.auto;
408
+ save(ctx, feature, 'auto-off', {});
409
+ ctx.out(`auto mode off for ${feature.slug}; the gates wait for you again`);
410
+ await commitRecord(ctx, feature, values, `${feature.key}: auto mode off`);
411
+ return 0;
412
+ }
413
+ /** agjan accept <finding-id> --reason "…" [--feature <slug>] [--no-commit] */
414
+ export async function accept(ctx, argv) {
415
+ const { values, positionals } = parseArgs({ args: argv, options: { ...FEATURE_OPTION, reason: { type: 'string' } }, allowPositionals: true });
416
+ const [id] = positionals;
417
+ if (!id || positionals.length !== 1 || !values.reason?.trim())
418
+ throw new UsageError('usage: agjan accept <finding-id> --reason "<why>" [--feature <slug>] [--no-commit]');
419
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
420
+ const finding = feature.findings.find((f) => f.id === id);
421
+ if (!finding)
422
+ throw new AgjanError(`no finding ${id} in ${feature.slug}`);
423
+ if (finding.status !== 'open')
424
+ throw new AgjanError(`${id} is already ${finding.status}`);
425
+ const lines = [`finding ${id} [${finding.severity}] ${finding.file ?? ''}`.trimEnd(), `issue ${finding.issue}`, `reason ${values.reason}`];
426
+ if (!(await confirmGate(ctx, feature, 'accept finding', lines)))
427
+ return 1;
428
+ feature.approvals.accepted.push({ finding: id, reason: values.reason, at_utc: ctx.now(), by: ctx.email() });
429
+ save(ctx, feature, 'accepted', { finding: id, severity: finding.severity });
430
+ ctx.out(ctx.style.green(`accepted ${id}`));
431
+ await commitRecord(ctx, feature, values, `${feature.key}: accept ${id}`);
432
+ return 0;
433
+ }
434
+ /** agjan reject spec|design --reason "…" [--feature <slug>] [--no-commit]: sends a gate back (for quality signals). */
435
+ export async function reject(ctx, argv) {
436
+ const { values, positionals } = parseArgs({ args: argv, options: { ...FEATURE_OPTION, reason: { type: 'string' } }, allowPositionals: true });
437
+ const [gate] = positionals;
438
+ if (!['spec', 'design'].includes(gate) || positionals.length !== 1 || !values.reason?.trim()) {
439
+ throw new UsageError('usage: agjan reject spec|design --reason "<why>" [--feature <slug>] [--no-commit]');
440
+ }
441
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
442
+ if (!(await confirmGate(ctx, feature, `reject ${gate}`, [`reason ${values.reason}`])))
443
+ return 1;
444
+ feature.approvals.rejections.push({ gate, reason: values.reason, at_utc: ctx.now(), by: ctx.email() });
445
+ save(ctx, feature, 'rejected', { gate });
446
+ ctx.out(`recorded rejection of ${gate} for ${feature.slug}; the document stays draft`);
447
+ await commitRecord(ctx, feature, values, `${feature.key}: reject ${gate}`);
448
+ return 0;
449
+ }
450
+ /** agjan amend --task <id> --paths <p1,p2> --reason "…": proposes a scope amendment (agent-run). */
451
+ export function amend(ctx, argv) {
452
+ const { values } = parseArgs({
453
+ args: argv,
454
+ options: { ...FEATURE_OPTION, task: { type: 'string' }, paths: { type: 'string' }, reason: { type: 'string' } },
455
+ });
456
+ const paths = (values.paths ?? '').split(',').map((p) => p.trim()).filter(Boolean);
457
+ if (!values.task || paths.length === 0 || !values.reason?.trim()) {
458
+ throw new UsageError('usage: agjan amend --task <id> --paths <path,...> --reason "<why>" [--feature <slug>]');
459
+ }
460
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
461
+ if (feature.state.design !== 'approved')
462
+ throw new AgjanError(`amendments need an approved design (it is ${feature.state.design})`);
463
+ if (!feature.tasks?.parsed.tasks.some((t) => t.id === values.task))
464
+ throw new AgjanError(`no task ${values.task} in tasks.md`);
465
+ for (const p of paths) {
466
+ if (p.includes('\\') || p.startsWith('/') || p.split('/').includes('..'))
467
+ throw new UsageError(`path '${p}' must be relative, POSIX, without '..'`);
468
+ }
469
+ const id = `${feature.key}-A${feature.approvals.amendments.length + 1}`;
470
+ feature.approvals.amendments.push({ id, task: values.task, paths, reason: values.reason, proposed_at_utc: ctx.now() });
471
+ save(ctx, feature, 'amendment-proposed', { amendment: id, task: values.task });
472
+ ctx.out(`proposed ${id} in ${FEATURES_DIR}/${feature.slug}/${APPROVALS_FILE}`);
473
+ ctx.out(`a human must approve it in a terminal: agjan approve amendment ${id}`);
474
+ return 0;
475
+ }
@@ -0,0 +1,76 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { parseArgs } from 'node:util';
5
+ import { changedFiles, git, resolveBase } from '../git.js';
6
+ import { matcher } from '../scope.js';
7
+ import { UsageError } from '../errors.js';
8
+ import { overrideBase } from './check.js';
9
+ /** Quotes a path for the shell (sh and cmd both accept double quotes). */
10
+ const quote = (path) => (/^[\w./@-]+$/.test(path) ? path : `"${path.replace(/"/g, '\\"')}"`);
11
+ /**
12
+ * The folders an area's linter runs in, with the files to lint in each (paths relative to
13
+ * the folder). `lint.in` names the folders (for example `app/*`), `lint.files` the files
14
+ * inside them (for example `webapp/**`).
15
+ */
16
+ export function lintTargets(files, lint) {
17
+ const depth = lint.in.split('/').length;
18
+ const isTarget = matcher([`${lint.in}/${lint.files}`]);
19
+ const folders = new Map();
20
+ for (const file of files.filter((f) => isTarget(f))) {
21
+ const parts = file.split('/');
22
+ const folder = parts.slice(0, depth).join('/');
23
+ if (!folders.has(folder))
24
+ folders.set(folder, []);
25
+ folders.get(folder).push(parts.slice(depth).join('/'));
26
+ }
27
+ return folders;
28
+ }
29
+ /**
30
+ * agjan lint [--all] [--base <ref>]: runs each area's linter from the command line
31
+ * (`lint` in the domain or agjan.config.json; the fiori area runs the UI5 linter, which
32
+ * also checks manifest.json), in every folder with changed files and on those files.
33
+ * --all lints the whole folders. It needs no MCP server, so it runs on every host.
34
+ * Exit code 1 when a linter reports problems or cannot run.
35
+ */
36
+ export function run(ctx, argv) {
37
+ const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: { all: { type: 'boolean' }, base: { type: 'string' } } });
38
+ if (positionals.length)
39
+ throw new UsageError('usage: agjan lint [--all] [--base <ref>]');
40
+ overrideBase(ctx, values.base);
41
+ const s = ctx.style;
42
+ const linters = Object.entries(ctx.config.lint ?? {}).filter((entry) => Boolean(entry[1]?.command && entry[1].in && entry[1].files));
43
+ if (!linters.length) {
44
+ ctx.out(s.gray('no linter configured (lint in agjan.config.json)'));
45
+ return 0;
46
+ }
47
+ const root = ctx.root;
48
+ const files = values.all
49
+ ? (git(root, ['ls-files', '--cached', '--others', '--exclude-standard']) ?? '').split('\n').filter(Boolean)
50
+ : changedFiles(root, resolveBase(root, ctx.config.git?.base));
51
+ const present = files.filter((f) => existsSync(join(root, f)));
52
+ let failed = 0;
53
+ let ran = 0;
54
+ for (const [area, lint] of linters) {
55
+ for (const [folder, inside] of lintTargets(present, lint)) {
56
+ ran += 1;
57
+ const command = values.all ? lint.command : `${lint.command} ${inside.map(quote).join(' ')}`;
58
+ ctx.out(`${s.bold(`lint ${area}`)} ${folder}: ${s.gray(values.all ? lint.command : `${lint.command} (${inside.length} file(s))`)}`);
59
+ const result = spawnSync(command, { cwd: join(root, folder), shell: true, encoding: 'utf8', timeout: 600_000, maxBuffer: 64 * 1024 * 1024 });
60
+ const output = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim();
61
+ if (output)
62
+ ctx.out(output);
63
+ if (result.status === 0) {
64
+ ctx.out(` ${s.green('ok')}`);
65
+ }
66
+ else {
67
+ failed += 1;
68
+ const why = result.error ? `could not run: ${result.error.message}` : result.status === null ? 'could not run (stopped)' : `problems found (exit code ${result.status})`;
69
+ ctx.out(` ${s.red(why)}`);
70
+ }
71
+ }
72
+ }
73
+ if (!ran)
74
+ ctx.out(s.gray(values.all ? 'no files to lint' : 'no changed files to lint (--all lints everything)'));
75
+ return failed ? 1 : 0;
76
+ }
@@ -0,0 +1,74 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { appendLog } from '../log.js';
3
+ import { loadFeature, selectFeature } from '../feature.js';
4
+ import { AgjanError, UsageError } from '../errors.js';
5
+ import { approveAutomatically, cleanMessage, gateReadiness } from './gates.js';
6
+ const STAGES = ['map', 'spec', 'design', 'build', 'verify', 'fix'];
7
+ const GATES = ['spec', 'design', 'spec design', 'verify'];
8
+ /**
9
+ * agjan log --stage <stage> [--role r] [--task T1] [--skill s] [--host h] [--model m]
10
+ * agjan log --gate-requested <gate> [--message "<commit message>"]
11
+ * agjan log --waiting "<what the agent needs from the user>"
12
+ * Called once at the start of each step (design 12.1); the end of a step is inferred
13
+ * from the next event. `--message` proposes the commit message `approve` offers the human.
14
+ * In auto mode (decision 79) a requested spec or design gate is approved at once.
15
+ * `--waiting`: the agent stopped and waits for the user; its next step event ends the wait.
16
+ */
17
+ export function run(ctx, argv) {
18
+ const { values } = parseArgs({
19
+ args: argv,
20
+ options: {
21
+ feature: { type: 'string' },
22
+ stage: { type: 'string' },
23
+ role: { type: 'string' },
24
+ task: { type: 'string' },
25
+ skill: { type: 'string' },
26
+ host: { type: 'string' },
27
+ model: { type: 'string' },
28
+ 'gate-requested': { type: 'string' },
29
+ message: { type: 'string' },
30
+ waiting: { type: 'string' },
31
+ },
32
+ });
33
+ const gate = values['gate-requested'];
34
+ const usage = 'usage: agjan log --stage <stage> [--role r] [--task T1] [--skill s] | --gate-requested <gate> [--message "<text>"] | --waiting "<reason>"';
35
+ if ([gate, values.stage, values.waiting].filter((v) => v !== undefined).length !== 1)
36
+ throw new UsageError(usage);
37
+ if (values.waiting !== undefined && !values.waiting.trim())
38
+ throw new UsageError('--waiting needs a reason: what the user has to do or decide');
39
+ if (gate && !GATES.includes(gate))
40
+ throw new UsageError(`--gate-requested must be one of: ${GATES.join(', ')}`);
41
+ if (values.stage && !STAGES.includes(values.stage))
42
+ throw new UsageError(`--stage must be one of: ${STAGES.join(', ')}`);
43
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
44
+ if (values.waiting !== undefined) {
45
+ appendLog(feature.dir, ctx.now(), 'waiting', { reason: values.waiting.trim().replace(/\s+/g, ' ') });
46
+ }
47
+ else if (gate) {
48
+ // A gate is handed to the human only when approving it can succeed.
49
+ const { problems } = gateReadiness(ctx, feature, gate);
50
+ if (problems.length) {
51
+ throw new AgjanError(`the ${gate} gate is not ready; nothing logged:\n${problems.map((p) => ` - ${p}`).join('\n')}`);
52
+ }
53
+ const message = cleanMessage(values.message);
54
+ appendLog(feature.dir, ctx.now(), 'gate-requested', message ? { gate, message } : { gate });
55
+ if (approveAutomatically(ctx, feature, gate)) {
56
+ const next = gate === 'spec' ? 'agjan-design' : 'agjan-build';
57
+ ctx.out(`${ctx.style.green(`approved ${gate} automatically`)} (auto mode, switched on by ${feature.approvals.auto.by})`);
58
+ ctx.out(`commit the feature's documents (${message || `${feature.key}: approve ${gate} (auto mode)`}), then continue without stopping:`);
59
+ ctx.out(`your next action is the shell command: cat .claude/skills/${next}/SKILL.md (then follow it).`);
60
+ ctx.out('A reply without a tool call ends your run: put any note for the user into the same reply as that command.');
61
+ }
62
+ }
63
+ else {
64
+ const fields = { stage: values.stage };
65
+ for (const key of ['role', 'task', 'skill', 'host'])
66
+ if (values[key])
67
+ fields[key] = values[key];
68
+ // The configured model only; the actual model comes from host transcripts (design 12.2).
69
+ if (values.model)
70
+ fields.configured_model = values.model;
71
+ appendLog(feature.dir, ctx.now(), 'step', fields);
72
+ }
73
+ return 0;
74
+ }