agjan 0.0.10 → 0.0.12

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 (119) hide show
  1. package/README.md +2 -2
  2. package/bin/agjan.mjs +9 -2
  3. package/dist/adapters/claude-code.js +105 -0
  4. package/dist/adapters/copilot.js +80 -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 +164 -0
  9. package/dist/commands/branch.js +71 -0
  10. package/dist/commands/check.js +420 -0
  11. package/dist/commands/fix.js +122 -0
  12. package/dist/commands/gates.js +462 -0
  13. package/dist/commands/lint.js +76 -0
  14. package/dist/commands/log.js +72 -0
  15. package/dist/commands/map.js +47 -0
  16. package/dist/commands/new.js +65 -0
  17. package/dist/commands/pr-summary.js +168 -0
  18. package/dist/commands/progress.js +42 -0
  19. package/dist/commands/report.js +105 -0
  20. package/dist/commands/review.js +146 -0
  21. package/dist/commands/setup.js +393 -0
  22. package/dist/commands/status.js +303 -0
  23. package/dist/commands/ui-test.js +39 -0
  24. package/dist/config.js +110 -0
  25. package/dist/context.js +56 -0
  26. package/dist/copilot-mcp.js +56 -0
  27. package/dist/documents.js +207 -0
  28. package/dist/errors.js +15 -0
  29. package/dist/feature.js +221 -0
  30. package/dist/fix.js +117 -0
  31. package/dist/git.js +88 -0
  32. package/{src/hash.mjs → dist/hash.js} +11 -14
  33. package/dist/hook.js +47 -0
  34. package/dist/json-file.js +26 -0
  35. package/dist/log.js +50 -0
  36. package/dist/managed.js +182 -0
  37. package/dist/mcp-config.js +76 -0
  38. package/dist/mcp.js +142 -0
  39. package/dist/plan.js +40 -0
  40. package/dist/progress-view.js +494 -0
  41. package/dist/progress.js +106 -0
  42. package/{src/review-policy.mjs → dist/review-policy.js} +39 -47
  43. package/dist/review.js +435 -0
  44. package/dist/scope.js +30 -0
  45. package/dist/terminal.js +127 -0
  46. package/dist/test-results.js +101 -0
  47. package/dist/tests-map.js +29 -0
  48. package/dist/types.js +5 -0
  49. package/dist/ui.js +136 -0
  50. package/dist/usage.js +116 -0
  51. package/dist/validate.js +46 -0
  52. package/docs/guide.md +98 -37
  53. package/kit/domains/btp/domain.json +4 -4
  54. package/kit/hooks/guard.mjs +48 -119
  55. package/kit/skills/agjan-build/SKILL.md +14 -8
  56. package/kit/skills/agjan-design/SKILL.md +42 -6
  57. package/kit/skills/agjan-fix/SKILL.md +9 -10
  58. package/kit/skills/agjan-map/SKILL.md +9 -10
  59. package/kit/skills/agjan-spec/SKILL.md +22 -11
  60. package/kit/skills/agjan-verify/SKILL.md +46 -19
  61. package/kit/skills/cap-developer/SKILL.md +10 -2
  62. package/kit/skills/cap-developer/references/handlers.md +11 -9
  63. package/kit/skills/cap-developer/references/project-setup.md +21 -8
  64. package/kit/skills/cap-developer/references/testing.md +38 -14
  65. package/kit/skills/cap-developer/references/typescript.md +143 -0
  66. package/kit/skills/cap-developer/references/validation-security.md +26 -8
  67. package/kit/skills/fiori-developer/SKILL.md +20 -5
  68. package/kit/skills/fiori-developer/references/app-setup.md +91 -16
  69. package/kit/skills/fiori-developer/references/elements.md +19 -5
  70. package/kit/skills/fiori-developer/references/freestyle-ts.md +5 -1
  71. package/kit/skills/fiori-developer/references/testing.md +109 -15
  72. package/kit/templates/agents-block.md +7 -3
  73. package/package.json +11 -3
  74. package/schemas/approvals.schema.json +23 -2
  75. package/schemas/config.schema.json +0 -5
  76. package/schemas/log.schema.json +1 -1
  77. package/src/adapters/claude-code.mjs +0 -121
  78. package/src/adapters/copilot.mjs +0 -89
  79. package/src/baseline.mjs +0 -66
  80. package/src/cli.mjs +0 -155
  81. package/src/commands/branch.mjs +0 -60
  82. package/src/commands/check.mjs +0 -365
  83. package/src/commands/fix.mjs +0 -116
  84. package/src/commands/gates.mjs +0 -264
  85. package/src/commands/lint.mjs +0 -74
  86. package/src/commands/log.mjs +0 -60
  87. package/src/commands/map.mjs +0 -47
  88. package/src/commands/new.mjs +0 -53
  89. package/src/commands/pr-summary.mjs +0 -137
  90. package/src/commands/progress.mjs +0 -40
  91. package/src/commands/report.mjs +0 -115
  92. package/src/commands/review.mjs +0 -76
  93. package/src/commands/setup.mjs +0 -383
  94. package/src/commands/status.mjs +0 -248
  95. package/src/config.mjs +0 -122
  96. package/src/context.mjs +0 -67
  97. package/src/copilot-mcp.mjs +0 -56
  98. package/src/documents.mjs +0 -188
  99. package/src/errors.mjs +0 -16
  100. package/src/feature.mjs +0 -225
  101. package/src/fix.mjs +0 -108
  102. package/src/git.mjs +0 -83
  103. package/src/hook.mjs +0 -48
  104. package/src/json-file.mjs +0 -24
  105. package/src/log.mjs +0 -51
  106. package/src/managed.mjs +0 -178
  107. package/src/mcp-config.mjs +0 -83
  108. package/src/mcp.mjs +0 -147
  109. package/src/plan.mjs +0 -45
  110. package/src/progress-view.mjs +0 -466
  111. package/src/progress.mjs +0 -85
  112. package/src/review.mjs +0 -413
  113. package/src/scope.mjs +0 -30
  114. package/src/terminal.mjs +0 -118
  115. package/src/test-results.mjs +0 -111
  116. package/src/tests-map.mjs +0 -29
  117. package/src/ui.mjs +0 -136
  118. package/src/usage.mjs +0 -118
  119. package/src/validate.mjs +0 -41
@@ -1,365 +0,0 @@
1
- import { readFileSync, statSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import { parseArgs } from 'node:util';
4
- import { git, changedFiles, mergeBase, resolveBase } from '../git.mjs';
5
- import { CONFIG_FILE, resolveArea } from '../config.mjs';
6
- import { FEATURES_DIR, changedFeatures, listFeatures, loadFeature } from '../feature.mjs';
7
- import { documentProblems, designProblems } from '../validate.mjs';
8
- import { allowedPatterns, matcher } from '../scope.mjs';
9
- import { acTestFiles } from '../tests-map.mjs';
10
- import { acResults, loadResults } from '../test-results.mjs';
11
- import { buildProgress, verifyState } from '../progress.mjs';
12
- import { FIX_FILE, fixRules, freshReview } from '../fix.mjs';
13
- import { BASELINE_FILE, baselineDrift, projectProblems } from '../baseline.mjs';
14
- import { UsageError } from '../errors.mjs';
15
- import { readJson } from '../json-file.mjs';
16
- import { markLine, verdictColor } from '../ui.mjs';
17
- import { planStatus } from '../managed.mjs';
18
- import { buildPlan } from '../plan.mjs';
19
-
20
- /** Files whose change in a PR alters the rules that check it (design 9.3). */
21
- const POLICY_PATTERNS = [
22
- CONFIG_FILE,
23
- 'agjan.lock.json',
24
- 'AGENTS.md',
25
- 'CLAUDE.md',
26
- 'package.json',
27
- 'package-lock.json',
28
- '.claude/**',
29
- '.github/agents/**',
30
- '.github/hooks/**',
31
- '.github/workflows/**',
32
- '.github/CODEOWNERS',
33
- '.mcp.json',
34
- '.vscode/mcp.json',
35
- ];
36
-
37
- class Report {
38
- constructor() {
39
- this.items = [];
40
- }
41
- error(scope, message) {
42
- this.items.push({ level: 'error', scope, message });
43
- }
44
- warn(scope, message) {
45
- this.items.push({ level: 'warn', scope, message });
46
- }
47
- get errors() {
48
- return this.items.filter((i) => i.level === 'error').length;
49
- }
50
- get warnings() {
51
- return this.items.filter((i) => i.level === 'warn').length;
52
- }
53
- }
54
-
55
- /**
56
- * Soft size limits (design 9.2, `limits`): large documents cost tokens in every stage that
57
- * reads them. Warnings only; `design_kb` covers design.md and tasks.md together.
58
- */
59
- function checkSizes(report, feature, config) {
60
- const kb = (text) => Buffer.byteLength(text ?? '') / 1024;
61
- const { spec_kb: specKb, design_kb: designKb } = config.limits ?? {};
62
- if (specKb && feature.spec && kb(feature.spec.text) > specKb) {
63
- report.warn(feature.slug, `spec.md is ${kb(feature.spec.text).toFixed(1)} KB (soft limit ${specKb} KB); keep it to what the feature needs`);
64
- }
65
- const design = kb(feature.design?.text) + kb(feature.tasks?.text);
66
- if (designKb && feature.design && design > designKb) {
67
- report.warn(feature.slug, `design.md and tasks.md are ${design.toFixed(1)} KB (soft limit ${designKb} KB)`);
68
- }
69
- }
70
-
71
- /** A fix (design 6.7): the fast-path rules, no open blocker, and in CI a fresh review and the record. */
72
- function checkFix(report, root, config, fix, level) {
73
- const scope = fix.slug;
74
- for (const p of fixRules(root, config).problems) report.error(scope, `${p} (not a fix: use /agjan-spec)`);
75
- if (level === 'staged') return fix;
76
- for (const f of fix.findings.filter((x) => x.status === 'open' && x.severity === 'blocker')) {
77
- report.error(scope, `open blocker ${f.id}: ${f.issue}`);
78
- }
79
- if (level === 'ci') {
80
- const review = freshReview(root, config, fix, 'fix');
81
- if (review.problem) report.error(scope, review.problem);
82
- const record = readJson(join(fix.dir, FIX_FILE));
83
- if (!record?.recorded_at_utc || record.review?.tree_hash !== review.record?.tree_hash) {
84
- report.error(scope, 'the fix is not recorded for its latest review; run: npx agjan fix record');
85
- }
86
- }
87
- return fix;
88
- }
89
-
90
- /** A map run (design 6.2): a complete project.md, and in CI a fresh review and a current baseline. */
91
- function checkMap(report, root, config, run, level) {
92
- const scope = run.slug;
93
- if (level === 'staged') return run;
94
- for (const p of projectProblems(root, config)) report.error(scope, p);
95
- if (level === 'ci') {
96
- const review = freshReview(root, config, run, 'map');
97
- if (review.problem) report.error(scope, review.problem);
98
- const drift = baselineDrift(root, config);
99
- if (drift === null) report.error(scope, `${BASELINE_FILE} is missing; run: npx agjan baseline refresh`);
100
- else if (drift.length) report.error(scope, `${BASELINE_FILE} is not current (${drift.join(', ')}); run: npx agjan baseline refresh`);
101
- }
102
- return run;
103
- }
104
-
105
- function checkFeature(report, root, config, slug, level) {
106
- const feature = loadFeature(root, slug);
107
- if (feature.kind === 'fix') return checkFix(report, root, config, feature, level);
108
- if (feature.kind === 'map') return checkMap(report, root, config, feature, level);
109
- const scope = slug;
110
- const ci = level === 'ci';
111
-
112
- // Approved documents must not change silently (design 9.5), at every level.
113
- if (feature.state.spec === 'stale') report.error(scope, 'spec.md changed after its approval; re-approve it or revert the change');
114
- if (feature.state.design === 'stale') {
115
- report.error(scope, 'the design is stale (design.md, tasks.md or the spec changed after approval); re-approve it or revert');
116
- }
117
- if (level === 'staged') return feature;
118
-
119
- for (const p of documentProblems(feature)) report.error(scope, p);
120
- for (const p of designProblems(feature, config)) report.error(scope, p);
121
- checkSizes(report, feature, config);
122
-
123
- if (ci) {
124
- if (feature.state.spec !== 'approved') report.error(scope, `spec is ${feature.state.spec}, not approved`);
125
- if (feature.state.design !== 'approved') report.error(scope, `design is ${feature.state.design}, not approved`);
126
- }
127
-
128
- for (const f of feature.findings.filter((x) => x.status === 'open')) {
129
- const text = `open ${f.severity} ${f.id} (${f.step}): ${f.issue}`;
130
- if (f.severity === 'blocker') report.error(scope, text);
131
- else if (ci) report.warn(scope, text);
132
- }
133
- for (const a of feature.amendments.filter((x) => x.status === 'pending')) {
134
- report.warn(scope, `amendment ${a.id} is waiting for approval: agjan approve amendment ${a.id}`);
135
- }
136
-
137
- if (feature.stage === 'build' && feature.spec && feature.tasks) {
138
- const areaNames = [...new Set(feature.tasks.parsed.tasks.map((t) => resolveArea(config, t.area)?.name).filter(Boolean))];
139
- const inTests = acTestFiles(root, config, areaNames, feature.key);
140
- for (const ac of feature.spec.parsed.acs) {
141
- if (ac.verification === 'manual') continue;
142
- if (inTests.has(ac.id)) continue;
143
- // During Build tests may still be missing; a finished feature must have them.
144
- if (ci) report.error(scope, `${ac.id} has no test whose name contains the AC id`);
145
- else report.warn(scope, `${ac.id} has no test yet`);
146
- }
147
- checkResults(report, root, config, feature, areaNames, ci);
148
- if (ci) {
149
- const progress = buildProgress(root, config, feature);
150
- for (const t of progress.tasks.filter((x) => !x.commit)) {
151
- report.error(scope, `task ${t.id} has no commit '${feature.key}-${t.id}: …'`);
152
- }
153
- for (const d of progress.due) report.error(scope, `review ${d.step} is due (${d.reason})`);
154
- const { state, record } = verifyState(root, config, feature);
155
- if (state === 'none') report.error(scope, 'no final verify review recorded');
156
- else if (state === 'blocked') report.error(scope, `the final verify review ${record.id} is blocked`);
157
- else if (state === 'stale') report.error(scope, `the final verify review ${record.id} is stale: files changed after it; run the verify review again`);
158
- }
159
- }
160
- return feature;
161
- }
162
-
163
- /**
164
- * With results configured (design 6.6): every automated AC needs a passing test case
165
- * and none failing. Without results files the coverage is by test names only, which is
166
- * reported, not failed: CI usually has no results of the change.
167
- */
168
- function checkResults(report, root, config, feature, areaNames, ci) {
169
- const loaded = loadResults(root, config, areaNames);
170
- if (!loaded.configured) return;
171
- const scope = feature.slug;
172
- for (const file of loaded.missing) report.warn(scope, `test results ${file} not found; AC coverage is by test names only (run the tests)`);
173
- for (const file of loaded.unreadable) report.warn(scope, `test results ${file} are in an unknown format (JUnit XML, Jest or Mocha JSON)`);
174
- if (loaded.files.length === 0) return;
175
-
176
- const counts = acResults(loaded, feature.key);
177
- for (const ac of feature.spec.parsed.acs.filter((a) => a.verification !== 'manual')) {
178
- const c = counts.get(ac.id);
179
- if (c?.failed) {
180
- report.error(scope, `${ac.id} has ${c.failed} failing test(s) in the results`);
181
- } else if (!c?.passed) {
182
- const message = `${ac.id} has no passing test in the results`;
183
- if (ci) report.error(scope, message);
184
- else report.warn(scope, message);
185
- }
186
- }
187
- // Results older than the newest change do not describe it.
188
- const oldest = Math.min(...loaded.files.map((f) => f.mtimeMs));
189
- const changed = changedFiles(root, resolveBase(root, config.git?.base)).filter((f) => !f.startsWith(`${FEATURES_DIR}/`) && !f.startsWith('.agjan/'));
190
- const newest = Math.max(0, ...changed.map((f) => {
191
- try {
192
- return statSync(join(root, f)).mtimeMs;
193
- } catch {
194
- return 0; // deleted
195
- }
196
- }));
197
- if (newest > oldest) report.warn(scope, 'test results are older than the latest change; run the tests again');
198
- }
199
-
200
- /** Changed files outside every Build feature's approved scope (design 6.5). */
201
- function checkScope(report, features, config, files, level) {
202
- const docs = `${FEATURES_DIR}/`;
203
- // .agjan/ is local scratch (git-ignored by init); never part of a change.
204
- const outside = files.filter((f) => !f.startsWith(docs) && !f.startsWith('.agjan/'));
205
- // A branch carries features, or exactly one fix, or a map run (decision 57).
206
- const fixes = features.filter((f) => f.kind === 'fix');
207
- const maps = features.filter((f) => f.kind === 'map');
208
- if (fixes.length > 1 || (fixes.length && fixes.length !== features.length) || (maps.length && maps.length !== features.length)) {
209
- report.error('scope', `a branch carries either features, or one fix, or a map run; this one has ${features.map((f) => f.slug).join(', ')}`);
210
- return;
211
- }
212
- if (fixes.length === 1) return; // the fast-path rules replace the task paths
213
- if (maps.length) {
214
- for (const file of outside) report.error('scope', `${file} changed, but a map run only writes ${FEATURES_DIR}/project.md and ${BASELINE_FILE}`);
215
- return;
216
- }
217
- if (features.length === 0) {
218
- // A change without any feature (setup, tooling, or work done without agjan). Only
219
- // CI decides whether that is allowed; fixes get their own record in milestone 0.3.
220
- if (level === 'ci' && outside.length > 0) {
221
- const message = `${outside.length} changed file(s) are not covered by any feature`;
222
- if (config.ci.untracked_changes === 'warn') report.warn('scope', message);
223
- else report.error('scope', message);
224
- }
225
- return;
226
- }
227
- const building = features.filter((f) => f.stage === 'build');
228
- const allowed = matcher(building.flatMap((f) => allowedPatterns(f, config)));
229
- for (const file of outside) {
230
- if (allowed(file)) continue;
231
- if (building.length === 0) report.error('scope', `${file} changed, but no feature on this branch has an approved design`);
232
- else report.error('scope', `${file} is outside the approved task paths; revert it or propose an amendment (agjan amend)`);
233
- }
234
- }
235
-
236
- /**
237
- * What agjan a manifest pins: the version range in package.json, or the resolved
238
- * version, source and integrity in package-lock.json. Unparsable text pins "unknown".
239
- */
240
- function agjanPin(file, text) {
241
- try {
242
- const data = JSON.parse(text);
243
- if (file === 'package-lock.json') {
244
- const entry = data.packages?.['node_modules/agjan'] ?? data.dependencies?.agjan ?? null;
245
- return JSON.stringify(entry && { version: entry.version, resolved: entry.resolved, integrity: entry.integrity });
246
- }
247
- return JSON.stringify(data.devDependencies?.agjan ?? data.dependencies?.agjan ?? null);
248
- } catch {
249
- return 'unknown';
250
- }
251
- }
252
-
253
- /**
254
- * Policy changes relative to the merge-base: reported, and failing only when configured.
255
- * Returns the messages so the PR summary can list them.
256
- */
257
- function checkPolicy(report, root, config, files, base) {
258
- const isPolicy = matcher(POLICY_PATTERNS);
259
- const from = mergeBase(root, base);
260
- const messages = [];
261
- for (const file of files.filter(isPolicy)) {
262
- // Manifests count only when what they pin for agjan changed.
263
- if ((file === 'package.json' || file === 'package-lock.json') && from) {
264
- const before = git(root, ['show', `${from}:${file}`], { allowFail: true });
265
- let after = null;
266
- try {
267
- after = readFileSync(join(root, file), 'utf8');
268
- } catch {
269
- // deleted
270
- }
271
- if (before !== null && after !== null && agjanPin(file, before) === agjanPin(file, after)) continue;
272
- }
273
- const message = `policy change: ${file}`;
274
- messages.push(message);
275
- if (config.ci.policy_changes === 'fail') report.error('policy', message);
276
- else report.warn('policy', message);
277
- }
278
- // Editing a feature that already exists on the base branch (an archived feature).
279
- if (from) {
280
- for (const slug of new Set(files.filter((f) => f.startsWith(`${FEATURES_DIR}/`)).map((f) => f.split('/')[2]))) {
281
- if (git(root, ['cat-file', '-e', `${from}:${FEATURES_DIR}/${slug}/approvals.json`], { allowFail: true }) !== null) {
282
- const message = `feature '${slug}' already exists on the base branch; follow-up work should start a new feature`;
283
- messages.push(message);
284
- report.warn('policy', message);
285
- }
286
- }
287
- }
288
- return messages;
289
- }
290
-
291
- function print(ctx, report, level, slugs) {
292
- const s = ctx.style;
293
- // Not in the pre-commit hook (--staged): it runs on every commit.
294
- if (level !== 'staged') for (const line of markLine(s, ctx.kit, level === 'ci' ? 'check --ci' : 'check')) ctx.out(line);
295
- for (const item of report.items) {
296
- const label = item.level === 'error' ? s.bold(s.red('error')) : s.bold(s.yellow('warn '));
297
- ctx.out(`${label} ${s.cyan(item.scope)}: ${item.message}`);
298
- }
299
- const what = slugs.length ? `feature(s) ${slugs.map((slug) => s.bold(slug)).join(', ')}` : 'no changed feature';
300
- const color = verdictColor(s, report.errors, report.warnings);
301
- const counts = color(`${report.errors} error(s), ${report.warnings} warning(s)`);
302
- ctx.out(`${s.bold(`agjan check${level === 'default' ? '' : ` --${level}`}`)}: ${what}; ${counts}`);
303
- }
304
-
305
- /** Managed files and the recorded kit version (design 16.3); warnings only. */
306
- function checkManaged(report, ctx) {
307
- const raw = readJson(join(ctx.root, CONFIG_FILE));
308
- if (!raw) return; // not initialized: nothing is managed yet
309
- if (raw.kit !== ctx.kit) report.warn('kit', `${CONFIG_FILE} records kit ${raw.kit}, this agjan is ${ctx.kit}; run: npx agjan sync`);
310
- for (const item of planStatus(ctx.root, buildPlan(ctx.config))) {
311
- if (item.state !== 'ok') report.warn('managed', `${item.path} is ${item.state}; run: npx agjan sync`);
312
- }
313
- }
314
-
315
- /**
316
- * Runs the checks and returns the report without printing it, for `check` and for
317
- * `pr-summary`. `level` is 'staged', 'default' or 'ci'.
318
- */
319
- export function runChecks(ctx, level, explicitFeature) {
320
- const root = ctx.root;
321
- const config = ctx.config;
322
- const base = resolveBase(root, config.git?.base);
323
- const report = new Report();
324
-
325
- if (level === 'ci' && !mergeBase(root, base)) {
326
- report.error('git', `no merge-base with '${base ?? '(no base branch found)'}'; set git.base in ${CONFIG_FILE} or fetch the base branch`);
327
- }
328
- if (explicitFeature && !listFeatures(root).includes(explicitFeature)) throw new UsageError(`no feature '${explicitFeature}'`);
329
- // Every feature changed on the branch, also with --staged: scope is judged against
330
- // the whole branch's approved tasks, while only staged files are checked.
331
- const slugs = explicitFeature ? [explicitFeature] : changedFeatures(root, config);
332
-
333
- const features = slugs.map((slug) => checkFeature(report, root, config, slug, level));
334
- const files = changedFiles(root, base, { staged: level === 'staged' });
335
- checkScope(report, features, config, files, level);
336
- const policy = level === 'ci' ? checkPolicy(report, root, config, files, base) : [];
337
- if (level !== 'staged') {
338
- checkManaged(report, ctx);
339
- // The baseline describes the application; changes to watched files make it stale.
340
- const drift = features.some((f) => f.kind === 'map') ? null : baselineDrift(root, config);
341
- if (drift?.length) {
342
- report.warn('baseline', `watched files changed since the baseline (${drift.join(', ')}); update ${FEATURES_DIR}/project.md and run: npx agjan baseline refresh`);
343
- }
344
- }
345
- return { report, slugs, features, files, policy };
346
- }
347
-
348
- /** `--base <ref>` overrides git.base for this run, for CI where the base ref is known. */
349
- export function overrideBase(ctx, base) {
350
- if (base) ctx.config.git = { ...ctx.config.git, base };
351
- }
352
-
353
- /** agjan check [--staged | --ci] [--feature <slug>] [--base <ref>] */
354
- export function run(ctx, argv) {
355
- const { values } = parseArgs({
356
- args: argv,
357
- options: { staged: { type: 'boolean' }, ci: { type: 'boolean' }, feature: { type: 'string' }, base: { type: 'string' } },
358
- });
359
- if (values.staged && values.ci) throw new UsageError('use either --staged or --ci');
360
- overrideBase(ctx, values.base);
361
- const level = values.staged ? 'staged' : values.ci ? 'ci' : 'default';
362
- const { report, slugs } = runChecks(ctx, level, values.feature);
363
- print(ctx, report, level, slugs);
364
- return report.errors > 0 ? 1 : 0;
365
- }
@@ -1,116 +0,0 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import { parseArgs } from 'node:util';
4
- import { writeJson, readJson } from '../json-file.mjs';
5
- import { APPROVALS_FILE, FEATURES_DIR, KEY, SLUG, changedFeatures, emptyApprovals, featureDir, listFeatures, loadFeature, selectFeature } from '../feature.mjs';
6
- import { FIX_FILE, FIX_MD, fixRules, freshReview } from '../fix.mjs';
7
- import { appendLog } from '../log.mjs';
8
- import { AgjanError, UsageError } from '../errors.mjs';
9
-
10
- /** The fix a command acts on: --fix <id>, or the single fix changed on the branch. */
11
- function selectFix(ctx, explicit) {
12
- const id = explicit ? (explicit.startsWith('fixes/') ? explicit : `fixes/${explicit}`) : null;
13
- const unit = selectFeature(ctx.root, ctx.config, id);
14
- const fix = loadFeature(ctx.root, unit);
15
- if (fix.kind !== 'fix') throw new UsageError(`'${unit}' is not a fix; pass --fix <id>`);
16
- return fix;
17
- }
18
-
19
-
20
- function renderFixMd(fix, data) {
21
- const lines = [
22
- `# Fix ${fix.slug.replace(/^fixes\//, '')} (${fix.key})`,
23
- '',
24
- '<!-- Generated by agjan fix record from fix.json. Do not edit. -->',
25
- '',
26
- `what: ${data.what}`,
27
- `files: ${data.files.map((f) => `${f.path} (+${f.added}/-${f.deleted})${f.isNew ? ' new' : ''}`).join(', ')}`,
28
- `size: ${data.total} lines (limit ${data.limits.max_total}, per file ${data.limits.max_per_file})`,
29
- `verify: ${data.verify ?? 'not stated'}`,
30
- `review: ${data.review ? `${data.review.id} ${data.review.verdict} (reviewer: ${data.review.host}, isolation: ${data.review.isolation})` : 'none'}`,
31
- ];
32
- return `${lines.join('\n')}\n`;
33
- }
34
-
35
- /** agjan fix start <slug> --key <KEY> --what "<text>" */
36
- function start(ctx, argv) {
37
- const { values, positionals } = parseArgs({ args: argv, options: { key: { type: 'string' }, what: { type: 'string' } }, allowPositionals: true });
38
- const [slug] = positionals;
39
- if (!slug || positionals.length !== 1 || !values.key || !values.what?.trim()) {
40
- throw new UsageError('usage: agjan fix start <slug> --key <KEY> --what "<what the fix changes>"');
41
- }
42
- if (!SLUG.test(slug)) throw new UsageError(`slug '${slug}' must be lowercase letters, digits and '-'`);
43
- if (!KEY.test(values.key)) throw new UsageError(`key '${values.key}' must be 2 to 6 uppercase letters or digits, starting with a letter`);
44
- const root = ctx.root;
45
- // A branch carries either features or one fix (decision 57).
46
- const changed = changedFeatures(root, ctx.config);
47
- if (changed.length) throw new AgjanError(`this branch already carries ${changed.join(', ')}; start the fix on its own branch`);
48
- for (const other of listFeatures(root)) {
49
- if (loadFeature(root, other).key === values.key) throw new AgjanError(`key ${values.key} is already used by '${other}'`);
50
- }
51
- const id = `${ctx.now().slice(0, 10)}-${slug}`;
52
- const dir = featureDir(root, `fixes/${id}`);
53
- if (existsSync(dir)) throw new AgjanError(`${FEATURES_DIR}/fixes/${id} already exists`);
54
- mkdirSync(dir, { recursive: true });
55
- writeJson(join(dir, APPROVALS_FILE), emptyApprovals(id, values.key, ctx.kit, ctx.now(), 'fix'));
56
- writeJson(join(dir, FIX_FILE), { schema: 1, what: values.what.trim(), started_at_utc: ctx.now() });
57
- appendLog(dir, ctx.now(), 'step', { stage: 'fix', skill: 'agjan-fix' });
58
- ctx.out(`created ${FEATURES_DIR}/fixes/${id}/ (key ${values.key})`);
59
- return 0;
60
- }
61
-
62
- /** agjan fix check [--fix <id>]: the fast-path rules on the current change. */
63
- function check(ctx, argv) {
64
- const { values } = parseArgs({ args: argv, options: { fix: { type: 'string' } } });
65
- if (values.fix) selectFix(ctx, values.fix);
66
- const rules = fixRules(ctx.root, ctx.config);
67
- const ignored = new Set(rules.ignored);
68
- for (const f of rules.files) {
69
- const st = ctx.style;
70
- ctx.out(` ${f.path} ${st.green(`+${f.added}`)}/${st.red(`-${f.deleted}`)}${f.isNew ? ' (new)' : ''}${ignored.has(f.path) ? st.gray(' (ignored)') : ''}`);
71
- }
72
- const st = ctx.style;
73
- for (const p of rules.problems) ctx.out(`${st.bold(st.red('error'))} ${p}`);
74
- const verdict = rules.problems.length ? st.red('not a fix: use /agjan-spec') : st.green('within the fast-path rules');
75
- ctx.out(`${st.bold('agjan fix check')}: ${rules.total} changed lines (limit ${rules.limits.max_total}); ${verdict}`);
76
- return rules.problems.length ? 1 : 0;
77
- }
78
-
79
- /** agjan fix record [--verify "<command and result>"] [--fix <id>]: writes fix.json and fix.md. */
80
- function record(ctx, argv) {
81
- const { values } = parseArgs({ args: argv, options: { fix: { type: 'string' }, verify: { type: 'string' } } });
82
- const fix = selectFix(ctx, values.fix);
83
- const rules = fixRules(ctx.root, ctx.config);
84
- if (rules.problems.length) throw new AgjanError(`the change is not a fix:\n${rules.problems.map((p) => ` - ${p}`).join('\n')}`);
85
- const review = freshReview(ctx.root, ctx.config, fix, 'fix');
86
- if (review.problem) throw new AgjanError(`${review.problem}; ask the agjan reviewer for step fix first`);
87
- const previous = readJson(join(fix.dir, FIX_FILE)) ?? {};
88
- const data = {
89
- ...previous,
90
- schema: 1,
91
- files: rules.files,
92
- total: rules.total,
93
- limits: rules.limits,
94
- verify: values.verify ?? previous.verify ?? null,
95
- review: { id: review.record.id, verdict: review.record.verdict, host: review.record.reviewer?.host, isolation: review.record.reviewer?.isolation, tree_hash: review.record.tree_hash },
96
- recorded_at_utc: ctx.now(),
97
- };
98
- writeJson(join(fix.dir, FIX_FILE), data);
99
- writeFileSync(join(fix.dir, FIX_MD), renderFixMd(fix, data));
100
- ctx.out(`recorded ${FEATURES_DIR}/${fix.slug}/${FIX_MD}`);
101
- return 0;
102
- }
103
-
104
- export function run(ctx, argv) {
105
- const [sub, ...rest] = argv;
106
- if (sub === 'start') return start(ctx, rest);
107
- if (sub === 'check') return check(ctx, rest);
108
- if (sub === 'record') return record(ctx, rest);
109
- throw new UsageError('usage: agjan fix start <slug> --key <KEY> --what "…" | fix check | fix record [--verify "…"]');
110
- }
111
-
112
- /** For status and pr-summary: what the fix record says, if it exists. */
113
- export function readFix(fix) {
114
- const file = join(fix.dir, FIX_FILE);
115
- return existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : null;
116
- }